1
1
import * as querystring from 'querystring'
2
- import { bold } from './utils/text'
2
+ import { bold , red } from './utils/text'
3
3
import { arrows } from './utils/arrows'
4
4
import { load , manifestExists , MANIFEST_FILE_NAME } from './manifest'
5
5
import type { Manifest } from './manifest'
6
+ import { isFieldPluginOption } from '@storyblok/field-plugin'
6
7
7
8
export const SANDBOX_BASE_URL = `https://plugin-sandbox.storyblok.com/field-plugin`
8
9
@@ -11,16 +12,61 @@ export type SandboxQueryParams = {
11
12
manifest : Manifest | null
12
13
}
13
14
15
+ const areOptionsValid = ( options : unknown ) : boolean => {
16
+ if ( ! Array . isArray ( options ) || options . length === 0 ) {
17
+ displayManifestErrorLoading (
18
+ new Error ( 'ERROR: Manifest options must be an array of objects' ) ,
19
+ )
20
+ return false
21
+ }
22
+
23
+ const incorrectValues : string [ ] = [ ]
24
+
25
+ for ( const option of options ) {
26
+ if ( ! isFieldPluginOption ( option ) ) {
27
+ incorrectValues . push ( JSON . stringify ( option ) )
28
+ }
29
+ }
30
+
31
+ if ( incorrectValues . length > 0 ) {
32
+ displayManifestErrorLoading (
33
+ new Error (
34
+ 'ERROR: Each option must be an object with string properties "name" and "value". The following values need to be corrected: \n ' +
35
+ incorrectValues . join ( ',\n ' ) ,
36
+ ) ,
37
+ )
38
+ return false
39
+ }
40
+
41
+ return true
42
+ }
43
+
44
+ const isManifestValid = ( manifest : unknown ) : boolean => {
45
+ if ( typeof manifest !== 'object' || manifest === null ) {
46
+ return false
47
+ }
48
+
49
+ if ( 'options' in manifest && manifest . options !== null ) {
50
+ return areOptionsValid ( manifest . options )
51
+ }
52
+
53
+ return true
54
+ }
55
+
14
56
export const buildQueryString = ( params : SandboxQueryParams ) => {
15
57
const queryParams : querystring . ParsedUrlQueryInput = {
16
58
url : params . url ,
17
59
}
18
60
19
- if ( params . manifest !== null ) {
20
- queryParams . manifest = JSON . stringify ( params . manifest )
61
+ if ( params . manifest === null ) {
62
+ return querystring . stringify ( queryParams )
63
+ }
64
+
65
+ if ( ! isManifestValid ( params . manifest ) ) {
66
+ throw Error ( 'Invalid manifest' )
21
67
}
22
68
23
- return querystring . stringify ( queryParams )
69
+ queryParams . manifest = JSON . stringify ( params . manifest )
24
70
}
25
71
26
72
export const generateSandboxUrl = ( fieldPluginUrl : string ) => {
@@ -58,4 +104,4 @@ const displayManifestChecking = () => {
58
104
}
59
105
60
106
const displayManifestErrorLoading = ( err : Error ) =>
61
- console . log ( `${ arrows . red } ${ bold ( `${ err . message } ` ) } ` )
107
+ console . log ( `${ arrows . red } ${ red ( `${ err . message } ` ) } ` )
0 commit comments