@stepzen/transpiler 0.0.0-experimental-20221114-610843f6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -0
  3. package/lib/actions/configure.d.ts +12 -0
  4. package/lib/actions/configure.d.ts.map +1 -0
  5. package/lib/actions/configure.js +134 -0
  6. package/lib/actions/configure.js.map +1 -0
  7. package/lib/actions/lint.d.ts +5 -0
  8. package/lib/actions/lint.d.ts.map +1 -0
  9. package/lib/actions/lint.js +31 -0
  10. package/lib/actions/lint.js.map +1 -0
  11. package/lib/actions/merge.d.ts +15 -0
  12. package/lib/actions/merge.d.ts.map +1 -0
  13. package/lib/actions/merge.js +177 -0
  14. package/lib/actions/merge.js.map +1 -0
  15. package/lib/actions/print.d.ts +4 -0
  16. package/lib/actions/print.d.ts.map +1 -0
  17. package/lib/actions/print.js +10 -0
  18. package/lib/actions/print.js.map +1 -0
  19. package/lib/actions/stitch.d.ts +3 -0
  20. package/lib/actions/stitch.d.ts.map +1 -0
  21. package/lib/actions/stitch.js +96 -0
  22. package/lib/actions/stitch.js.map +1 -0
  23. package/lib/actions/transpile.d.ts +17 -0
  24. package/lib/actions/transpile.d.ts.map +1 -0
  25. package/lib/actions/transpile.js +62 -0
  26. package/lib/actions/transpile.js.map +1 -0
  27. package/lib/actions/validate.d.ts +5 -0
  28. package/lib/actions/validate.d.ts.map +1 -0
  29. package/lib/actions/validate.js +40 -0
  30. package/lib/actions/validate.js.map +1 -0
  31. package/lib/index.d.ts +8 -0
  32. package/lib/index.d.ts.map +1 -0
  33. package/lib/index.js +18 -0
  34. package/lib/index.js.map +1 -0
  35. package/lib/mutations/config/envvars.d.ts +3 -0
  36. package/lib/mutations/config/envvars.d.ts.map +1 -0
  37. package/lib/mutations/config/envvars.js +27 -0
  38. package/lib/mutations/config/envvars.js.map +1 -0
  39. package/lib/mutations/config/index.d.ts +3 -0
  40. package/lib/mutations/config/index.d.ts.map +1 -0
  41. package/lib/mutations/config/index.js +5 -0
  42. package/lib/mutations/config/index.js.map +1 -0
  43. package/lib/utils/constants.d.ts +4 -0
  44. package/lib/utils/constants.d.ts.map +1 -0
  45. package/lib/utils/constants.js +19 -0
  46. package/lib/utils/constants.js.map +1 -0
  47. package/lib/utils/copy-workspace-content.d.ts +15 -0
  48. package/lib/utils/copy-workspace-content.d.ts.map +1 -0
  49. package/lib/utils/copy-workspace-content.js +46 -0
  50. package/lib/utils/copy-workspace-content.js.map +1 -0
  51. package/lib/utils/dedupe-query-and-mutation-types.d.ts +3 -0
  52. package/lib/utils/dedupe-query-and-mutation-types.d.ts.map +1 -0
  53. package/lib/utils/dedupe-query-and-mutation-types.js +68 -0
  54. package/lib/utils/dedupe-query-and-mutation-types.js.map +1 -0
  55. package/lib/utils/ensure-query-and-mutation-types.d.ts +4 -0
  56. package/lib/utils/ensure-query-and-mutation-types.d.ts.map +1 -0
  57. package/lib/utils/ensure-query-and-mutation-types.js +49 -0
  58. package/lib/utils/ensure-query-and-mutation-types.js.map +1 -0
  59. package/lib/utils/graphql-helpers.d.ts +5 -0
  60. package/lib/utils/graphql-helpers.d.ts.map +1 -0
  61. package/lib/utils/graphql-helpers.js +6 -0
  62. package/lib/utils/graphql-helpers.js.map +1 -0
  63. package/lib/utils/merge-helpers.d.ts +13 -0
  64. package/lib/utils/merge-helpers.d.ts.map +1 -0
  65. package/lib/utils/merge-helpers.js +180 -0
  66. package/lib/utils/merge-helpers.js.map +1 -0
  67. package/lib/utils/set-files-in-sdl.d.ts +7 -0
  68. package/lib/utils/set-files-in-sdl.d.ts.map +1 -0
  69. package/lib/utils/set-files-in-sdl.js +122 -0
  70. package/lib/utils/set-files-in-sdl.js.map +1 -0
  71. package/lib/utils/strip-empty-queries-and-mutations.d.ts +4 -0
  72. package/lib/utils/strip-empty-queries-and-mutations.d.ts.map +1 -0
  73. package/lib/utils/strip-empty-queries-and-mutations.js +44 -0
  74. package/lib/utils/strip-empty-queries-and-mutations.js.map +1 -0
  75. package/lib/validators/config-exists/index.d.ts +4 -0
  76. package/lib/validators/config-exists/index.d.ts.map +1 -0
  77. package/lib/validators/config-exists/index.js +46 -0
  78. package/lib/validators/config-exists/index.js.map +1 -0
  79. package/lib/validators/index.d.ts +3 -0
  80. package/lib/validators/index.d.ts.map +1 -0
  81. package/lib/validators/index.js +5 -0
  82. package/lib/validators/index.js.map +1 -0
  83. package/package.json +57 -0
  84. package/src/actions/configure.ts +176 -0
  85. package/src/actions/lint.ts +44 -0
  86. package/src/actions/merge.ts +243 -0
  87. package/src/actions/print.ts +8 -0
  88. package/src/actions/stitch.ts +113 -0
  89. package/src/actions/transpile.ts +74 -0
  90. package/src/actions/validate.ts +54 -0
  91. package/src/index.ts +7 -0
  92. package/src/mutations/config/envvars.ts +33 -0
  93. package/src/mutations/config/index.ts +3 -0
  94. package/src/utils/constants.ts +22 -0
  95. package/src/utils/copy-workspace-content.ts +48 -0
  96. package/src/utils/dedupe-query-and-mutation-types.ts +74 -0
  97. package/src/utils/ensure-query-and-mutation-types.ts +52 -0
  98. package/src/utils/graphql-helpers.ts +3 -0
  99. package/src/utils/merge-helpers.ts +205 -0
  100. package/src/utils/set-files-in-sdl.ts +156 -0
  101. package/src/utils/strip-empty-queries-and-mutations.ts +43 -0
  102. package/src/validators/config-exists/index.ts +54 -0
  103. package/src/validators/index.ts +3 -0
@@ -0,0 +1,54 @@
1
+ import {buildASTSchema, DocumentNode, parse, print} from 'graphql'
2
+ import * as fs from 'fs-extra'
3
+ import * as os from 'os'
4
+ import * as path from 'path'
5
+
6
+ import ensureQueryAndMutationTypes from '../utils/ensure-query-and-mutation-types'
7
+ import {EXPERIMENTAL_EXTENSIONS} from '../utils/constants'
8
+ import validators from '../validators'
9
+
10
+ export default (
11
+ source: string,
12
+ options: {
13
+ extensions: string
14
+ } = {
15
+ extensions: '',
16
+ },
17
+ ) => {
18
+ // Ensure source and output directories exist
19
+ if (!fs.existsSync(source)) {
20
+ throw new Error(`Cannot find source directory ${source}`)
21
+ }
22
+
23
+ // Ensure index.graphql exists
24
+ if (!fs.existsSync(`${source}/index.graphql`)) {
25
+ throw new Error(`Cannot find index.graphql in ${source}`)
26
+ }
27
+
28
+ // Get the index.graphql file
29
+ const file = path.join(source, 'index.graphql')
30
+ const index = fs.readFileSync(file, 'utf8')
31
+
32
+ // Parse
33
+ let ast: DocumentNode = parse(
34
+ `${EXPERIMENTAL_EXTENSIONS}${os.EOL}${options.extensions}${os.EOL}${index}`,
35
+ {
36
+ noLocation: true,
37
+ },
38
+ )
39
+
40
+ // We make an exception for 'no type Query' or 'no type Mutation'
41
+ ast = ensureQueryAndMutationTypes(ast)
42
+
43
+ // Build and print, to validate
44
+ buildASTSchema(ast)
45
+ print(ast)
46
+
47
+ // Custom validators
48
+ for (const validator of validators) {
49
+ validator(ast, source)
50
+ }
51
+
52
+ // Return true
53
+ return true
54
+ }
package/src/index.ts ADDED
@@ -0,0 +1,7 @@
1
+ export {default as configure} from './actions/configure'
2
+ export {default as lint} from './actions/lint'
3
+ export {default as merge} from './actions/merge'
4
+ export {default as print} from './actions/print'
5
+ export {default as stitch} from './actions/stitch'
6
+ export {default as transpile} from './actions/transpile'
7
+ export {default as validate} from './actions/validate'
@@ -0,0 +1,33 @@
1
+ import * as debug from 'debug'
2
+
3
+ export default async (config: string): Promise<string> => {
4
+ const envvars = Object.keys(process.env)
5
+ .filter(key => {
6
+ return key.startsWith(`STEPZEN_`)
7
+ })
8
+ .reduce((obj: any, key) => {
9
+ obj[key] = process.env[key]
10
+ return obj
11
+ }, {})
12
+
13
+ let replacements = 0
14
+ debug('stepzen:transpiler:config')(
15
+ `STEPZEN_* env vars available for replacement:` +
16
+ ` ${JSON.stringify(envvars, undefined, 2)}`,
17
+ )
18
+
19
+ for (const [key, value] of Object.entries(envvars)) {
20
+ const regex = new RegExp(key, 'g')
21
+ config = config.replace(regex, (match, offset) => {
22
+ replacements += 1
23
+ debug('stepzen:transpiler:config')(
24
+ `replacing ${match} at offset ${offset}`,
25
+ )
26
+ return `${value}`
27
+ })
28
+ }
29
+
30
+ debug('stepzen:transpiler:config')(`total replacements made: ${replacements}`)
31
+
32
+ return config
33
+ }
@@ -0,0 +1,3 @@
1
+ import envvars from './envvars'
2
+
3
+ export default [envvars]
@@ -0,0 +1,22 @@
1
+ import * as dotenv from 'dotenv'
2
+ import * as debug from 'debug'
3
+
4
+ debug('stepzen:dotenv')(
5
+ `loading .env from ${process.cwd()}, at transpiler/src/utils/constants.ts`,
6
+ )
7
+ dotenv.config()
8
+
9
+ const {STEPZEN_DOMAIN: ENV_VAR_STEPZEN_DOMAIN} = process.env
10
+
11
+ export const EXPERIMENTAL_EXTENSIONS = `
12
+ directive @experimental(
13
+ debug: Boolean
14
+ function: String
15
+ mock: String
16
+ setter: String
17
+ ) on OBJECT | FIELD_DEFINITION
18
+ `
19
+
20
+ export const STEPZEN_DOMAIN = ENV_VAR_STEPZEN_DOMAIN || 'stepzen.io'
21
+
22
+ export const ALL_GRAPHQL_FILES = '**/*.graphql'
@@ -0,0 +1,48 @@
1
+ import * as fs from 'fs-extra'
2
+ import * as glob from 'glob'
3
+ import * as path from 'path'
4
+ import {flatMap} from 'lodash'
5
+ import {ALL_GRAPHQL_FILES} from './constants'
6
+
7
+ const WORKSPACE_FILE_PATTERNS = [
8
+ '**/*.graphql',
9
+ 'stepzen.config.json',
10
+ 'config.yaml',
11
+ ]
12
+
13
+ const IGNORED_PATTERNS = ['node_modules/**']
14
+
15
+ /**
16
+ * Copy StepZen workspace content from one directory to another.
17
+ *
18
+ * Include only the files relevant to StepZen:
19
+ * - **​/*.graphql
20
+ * - config.yaml
21
+ * - stepzen.config.json
22
+ *
23
+ * Exclude all other files.
24
+ * Exclude special folders, e.g. node_modules
25
+ */
26
+ export default (srcPath: string, dstPath: string) => {
27
+ if (!fs.existsSync(srcPath)) {
28
+ throw new Error(`Cannot find source directory ${srcPath}`)
29
+ }
30
+
31
+ flatMap(WORKSPACE_FILE_PATTERNS, pattern =>
32
+ glob.sync(pattern, {
33
+ cwd: srcPath,
34
+ ignore: IGNORED_PATTERNS,
35
+ }),
36
+ ).forEach(relativePath => {
37
+ const srcFileFullPath = path.join(srcPath, relativePath)
38
+ const dstFileFullPath = path.join(dstPath, relativePath)
39
+ fs.ensureDirSync(path.dirname(dstFileFullPath))
40
+ fs.copyFileSync(srcFileFullPath, dstFileFullPath)
41
+ })
42
+ }
43
+
44
+ export const getAllGraphQLFiles = (srcPath: string) => {
45
+ return glob
46
+ .sync(ALL_GRAPHQL_FILES, {cwd: srcPath})
47
+ .filter(file => file !== 'index.graphql')
48
+ }
@@ -0,0 +1,74 @@
1
+ import {DocumentNode, parse, print, visit} from 'graphql'
2
+
3
+ import {cloneDeep} from '../utils/graphql-helpers'
4
+
5
+ export default (schema: string): string => {
6
+ let ast: DocumentNode = parse(schema)
7
+
8
+ let queries: any = []
9
+ let mutations: any = []
10
+
11
+ // Loop through the AST and find Query and Mutation types.
12
+ // Store their fields.
13
+ // Return null to remove it from the tree
14
+ ast = visit(ast, {
15
+ ObjectTypeDefinition: {
16
+ enter(node) {
17
+ if (node.name.kind === 'Name' && node.name.value === 'Query') {
18
+ queries = queries.concat(node.fields)
19
+ return null
20
+ }
21
+ if (node.name.kind === 'Name' && node.name.value === 'Mutation') {
22
+ mutations = mutations.concat(node.fields)
23
+ return null
24
+ }
25
+ },
26
+ },
27
+ })
28
+
29
+ // This is the template for the new Query type
30
+ const queryTemplate = {
31
+ kind: 'ObjectTypeDefinition',
32
+ description: undefined,
33
+ name: {kind: 'Name', value: 'Query'},
34
+ interfaces: [],
35
+ directives: [],
36
+ fields: [],
37
+ }
38
+
39
+ // This is the template for the new Mutation type
40
+ const mutationTemplate = {
41
+ kind: 'ObjectTypeDefinition',
42
+ description: undefined,
43
+ name: {kind: 'Name', value: 'Mutation'},
44
+ interfaces: [],
45
+ directives: [],
46
+ fields: [],
47
+ }
48
+
49
+ // If there are queries, add a single Query type
50
+ // with all the concatenated queries
51
+ if (queries.length > 0) {
52
+ const mutated: any = cloneDeep(ast)
53
+ const query = {
54
+ ...queryTemplate,
55
+ fields: queries,
56
+ }
57
+ mutated.definitions.push(query)
58
+ ast = mutated
59
+ }
60
+
61
+ // If there are mutations, add a single Query type
62
+ // with all the concatenated mutations
63
+ if (mutations.length > 0) {
64
+ const mutated: any = cloneDeep(ast)
65
+ const query = {
66
+ ...mutationTemplate,
67
+ fields: mutations,
68
+ }
69
+ mutated.definitions.push(query)
70
+ ast = mutated
71
+ }
72
+
73
+ return print(ast)
74
+ }
@@ -0,0 +1,52 @@
1
+ import {DocumentNode, visit} from 'graphql'
2
+
3
+ import {cloneDeep} from '../utils/graphql-helpers'
4
+
5
+ export default (ast: DocumentNode): DocumentNode => {
6
+ let queries: any = []
7
+ let mutations: any = []
8
+
9
+ // Loop through the AST and find Query and Mutation types.
10
+ ast = visit(ast, {
11
+ ObjectTypeDefinition: {
12
+ enter(node) {
13
+ if (node.name.kind === 'Name' && node.name.value === 'Query') {
14
+ queries = queries.concat(node.fields)
15
+ }
16
+ if (node.name.kind === 'Name' && node.name.value === 'Mutation') {
17
+ mutations = mutations.concat(node.fields)
18
+ }
19
+ },
20
+ },
21
+ })
22
+
23
+ // If there are no queries, add a single empty Query type
24
+ if (queries.length === 0) {
25
+ const mutated: any = cloneDeep(ast)
26
+ mutated.definitions.push({
27
+ kind: 'ObjectTypeDefinition',
28
+ description: undefined,
29
+ name: {kind: 'Name', value: 'Query'},
30
+ interfaces: [],
31
+ directives: [],
32
+ fields: [],
33
+ })
34
+ ast = mutated
35
+ }
36
+
37
+ // If there are mutations, add a single empty Mutation type
38
+ if (mutations.length === 0) {
39
+ const mutated: any = cloneDeep(ast)
40
+ mutated.definitions.push({
41
+ kind: 'ObjectTypeDefinition',
42
+ description: undefined,
43
+ name: {kind: 'Name', value: 'Mutation'},
44
+ interfaces: [],
45
+ directives: [],
46
+ fields: [],
47
+ })
48
+ ast = mutated
49
+ }
50
+
51
+ return ast
52
+ }
@@ -0,0 +1,3 @@
1
+ export type DeepWriteable<T> = {-readonly [P in keyof T]: DeepWriteable<T[P]>}
2
+ export const cloneDeep = <T>(obj: T): DeepWriteable<T> =>
3
+ JSON.parse(JSON.stringify(obj))
@@ -0,0 +1,205 @@
1
+ import * as debug from 'debug'
2
+ import {BREAK, GraphQLSchema, visit} from 'graphql'
3
+ import {buildSchema} from 'graphql/utilities'
4
+ import fetch from '@stepzen/fetch'
5
+ import * as fs from 'fs-extra'
6
+ import * as glob from 'glob'
7
+ import * as os from 'os'
8
+ import * as path from 'path'
9
+ import {replace} from 'lodash'
10
+
11
+ import {cloneDeep} from '../utils/graphql-helpers'
12
+ import {STEPZEN_DOMAIN} from './constants'
13
+
14
+ import configure from '../actions/configure'
15
+ import transpile from '../actions/transpile'
16
+
17
+ export const dedupeTempFolder = (dirpath: string) => {
18
+ do {
19
+ dirpath = replace(dirpath, os.tmpdir(), '')
20
+ } while (dirpath.includes(os.tmpdir()))
21
+
22
+ dirpath = path.join(os.tmpdir(), dirpath)
23
+
24
+ return dirpath
25
+ }
26
+
27
+ export const findNextAvailableSubfolder = (folder: string, name: string) => {
28
+ let subfolder = name
29
+ let counter = 1
30
+ while (fs.existsSync(path.join(folder, subfolder))) {
31
+ const suffix = `${counter++}`.padStart(2, '0')
32
+ subfolder = `${name}-${suffix}`
33
+ }
34
+
35
+ return subfolder
36
+ }
37
+
38
+ export const findQueryMutationInSchema = (
39
+ name: string,
40
+ files: any,
41
+ ): Boolean => {
42
+ for (const file of files) {
43
+ let found = false
44
+ visit(file.ast, {
45
+ FieldDefinition(node) {
46
+ if (node.name.value === name) {
47
+ found = true
48
+ return BREAK
49
+ }
50
+ },
51
+ })
52
+ if (found) return true
53
+ }
54
+ return false
55
+ }
56
+
57
+ export const findTypeInSchema = (name: string, files: any): Boolean => {
58
+ for (const file of files) {
59
+ let found = false
60
+ visit(file.ast, {
61
+ ObjectTypeDefinition(node) {
62
+ if (node.name.value === name) {
63
+ found = true
64
+ return BREAK
65
+ }
66
+ },
67
+ })
68
+ if (found) return true
69
+ }
70
+ return false
71
+ }
72
+
73
+ export const getConfiguration = async (
74
+ directories: string[],
75
+ silent: boolean = false,
76
+ answers: any = {},
77
+ ): Promise<string | boolean> => {
78
+ const tmp = path.join(os.tmpdir(), `stepzen-tmp-config-${Date.now()}`)
79
+ fs.ensureDirSync(tmp)
80
+
81
+ for (const directory of directories) {
82
+ const configs = [
83
+ ...glob.sync('**/config.yaml', {cwd: directory}),
84
+ ...glob.sync('**/stepzen.config.json', {cwd: directory}),
85
+ ]
86
+
87
+ for (const config of configs) {
88
+ const configFolder = path.join(directory, config)
89
+
90
+ let writeFolder = path.join(tmp, directory, config)
91
+ writeFolder = dedupeTempFolder(writeFolder)
92
+
93
+ const content = fs.readFileSync(configFolder, 'utf8')
94
+
95
+ fs.ensureFileSync(writeFolder)
96
+ fs.writeFileSync(writeFolder, content)
97
+ }
98
+ }
99
+
100
+ const configuration = await configure(tmp, silent, answers)
101
+ fs.removeSync(tmp)
102
+ return configuration
103
+ }
104
+
105
+ export const getExtensions = async (): Promise<string> => {
106
+ const domain = STEPZEN_DOMAIN.replace('.io', '.net')
107
+ const url = `https://stepzen.${domain}/directives.graphql`
108
+
109
+ const startedAt = new Date().getTime()
110
+ debug('stepzen:extensions')(
111
+ `[transpiler] fetching StepZen extensions from ${url}`,
112
+ )
113
+
114
+ const response = await fetch(url)
115
+ const text = await response.text()
116
+
117
+ const doneAt = new Date().getTime()
118
+ debug('stepzen:extensions')(
119
+ `[transpiler] fetched extensions (${text.length} bytes, ${
120
+ doneAt - startedAt
121
+ } ms)`,
122
+ )
123
+
124
+ return text
125
+ }
126
+
127
+ export const getSchema = async (
128
+ directory: string,
129
+ extensions: string,
130
+ ): Promise<GraphQLSchema> => {
131
+ const transpiled = await transpile(directory)
132
+ return buildSchema(`${extensions}${os.EOL}${transpiled.schema}`)
133
+ }
134
+
135
+ export const mergeQueryMutationIntoSchema = (type: any, files: any) => {
136
+ files = files.map((file: any) => {
137
+ return {
138
+ ...file,
139
+ ast: visit(file.ast, {
140
+ FieldDefinition(node) {
141
+ if (node.name.value === type.name.value) {
142
+ const directives = cloneDeep(type.directives)
143
+ const mutated: any = cloneDeep(node)
144
+ mutated.directives = directives
145
+ return mutated
146
+ }
147
+ },
148
+ }),
149
+ }
150
+ })
151
+ return files
152
+ }
153
+
154
+ export const mergeTypeIntoSchema = (type: any, files: any) => {
155
+ files = files.map((file: any) => {
156
+ return {
157
+ ...file,
158
+ ast: visit(file.ast, {
159
+ ObjectTypeDefinition(node) {
160
+ if (node.name.value === type.name.value) {
161
+ const directives = cloneDeep(type.directives)
162
+ const fields = cloneDeep(type.fields)
163
+ const mutated: any = cloneDeep(node)
164
+ mutated.directives = directives
165
+ mutated.fields = fields
166
+ return mutated
167
+ }
168
+ },
169
+ }),
170
+ }
171
+ })
172
+ return files
173
+ }
174
+
175
+ export const removeQueryMutationFromSchema = (name: string, files: any) => {
176
+ files = files.map((file: any) => {
177
+ return {
178
+ ...file,
179
+ ast: visit(file.ast, {
180
+ FieldDefinition(node) {
181
+ if (node.name.value === name) {
182
+ return null
183
+ }
184
+ },
185
+ }),
186
+ }
187
+ })
188
+ return files
189
+ }
190
+
191
+ export const removeTypeFromSchema = (name: string, files: any) => {
192
+ files = files.map((file: any) => {
193
+ return {
194
+ ...file,
195
+ ast: visit(file.ast, {
196
+ ObjectTypeDefinition(node) {
197
+ if (node.name.value === name) {
198
+ return null
199
+ }
200
+ },
201
+ }),
202
+ }
203
+ })
204
+ return files
205
+ }
@@ -0,0 +1,156 @@
1
+ import * as fs from 'fs'
2
+ import * as glob from 'glob'
3
+ import {
4
+ DirectiveNode,
5
+ ListValueNode,
6
+ parse,
7
+ SchemaDefinitionNode,
8
+ StringValueNode,
9
+ visit,
10
+ } from 'graphql'
11
+ import * as path from 'path'
12
+
13
+ import {cloneDeep, DeepWriteable} from './graphql-helpers'
14
+ import print from '../actions/print'
15
+ import {ALL_GRAPHQL_FILES} from './constants'
16
+ import {getAllGraphQLFiles} from './copy-workspace-content'
17
+
18
+ const normalizePathSep = (pathlike: string) =>
19
+ pathlike.replace(path.sep, path.posix.sep)
20
+
21
+ export const createOrUpdateSdlDirective = (
22
+ importedGraphQLFiles: readonly string[],
23
+ allGraphQLFiles: readonly string[],
24
+ origSdlDirective?: DeepWriteable<DirectiveNode>,
25
+ ) => {
26
+ let sdlDirective: DeepWriteable<DirectiveNode>
27
+ if (origSdlDirective) {
28
+ sdlDirective = cloneDeep(origSdlDirective)
29
+ } else {
30
+ sdlDirective = {
31
+ kind: 'Directive',
32
+ name: {
33
+ kind: 'Name',
34
+ value: 'sdl',
35
+ },
36
+ arguments: [
37
+ {
38
+ kind: 'Argument',
39
+ name: {
40
+ kind: 'Name',
41
+ value: 'files',
42
+ },
43
+ value: {
44
+ kind: 'ListValue',
45
+ values: [
46
+ {
47
+ kind: 'StringValue',
48
+ value: ALL_GRAPHQL_FILES,
49
+ },
50
+ ],
51
+ },
52
+ },
53
+ ],
54
+ }
55
+ }
56
+
57
+ sdlDirective.arguments = sdlDirective.arguments?.map(arg => {
58
+ if (arg.name.value === 'files') {
59
+ const filesValueNodes = arg.value as DeepWriteable<ListValueNode>
60
+ const fileset = new Set<string>(
61
+ [
62
+ ...filesValueNodes.values.map(
63
+ value => (value as StringValueNode).value,
64
+ ),
65
+ ...importedGraphQLFiles,
66
+ // Make sure paths in the `@sdl()` directive use the `/` separator
67
+ // even on Windows.
68
+ ].map(normalizePathSep),
69
+ )
70
+ if (fileset.has(ALL_GRAPHQL_FILES)) {
71
+ fileset.delete(ALL_GRAPHQL_FILES)
72
+ allGraphQLFiles.forEach(file => fileset.add(normalizePathSep(file)))
73
+ }
74
+ filesValueNodes.values = [...fileset].map(file => ({
75
+ kind: 'StringValue',
76
+ value: file,
77
+ }))
78
+ }
79
+ return arg
80
+ })
81
+
82
+ return sdlDirective
83
+ }
84
+
85
+ export const createSchemaElement = (
86
+ importedGraphQLFiles: readonly string[],
87
+ allGraphQLFiles: readonly string[],
88
+ ) => {
89
+ const schemaElement: DeepWriteable<SchemaDefinitionNode> = {
90
+ kind: 'SchemaDefinition',
91
+ directives: [
92
+ createOrUpdateSdlDirective(importedGraphQLFiles, allGraphQLFiles),
93
+ ],
94
+ operationTypes: [
95
+ {
96
+ kind: 'OperationTypeDefinition',
97
+ operation: 'query',
98
+ type: {
99
+ kind: 'NamedType',
100
+ name: {
101
+ kind: 'Name',
102
+ value: 'Query',
103
+ },
104
+ },
105
+ },
106
+ ],
107
+ }
108
+
109
+ return schemaElement
110
+ }
111
+
112
+ export default (source: string, importedGraphQLFiles: readonly string[]) => {
113
+ const allGraphQLFiles = getAllGraphQLFiles(source)
114
+
115
+ const output = path.join(source, 'index.graphql')
116
+ const index = fs.readFileSync(output, 'utf8')
117
+
118
+ let hasSchemaElement
119
+ let ast = parse(index)
120
+ ast = visit(ast, {
121
+ SchemaDefinition(node) {
122
+ hasSchemaElement = true
123
+ const mutated = cloneDeep(node)
124
+ const idx = mutated.directives?.findIndex(
125
+ directive => directive.name.value === 'sdl',
126
+ )
127
+ if (mutated.directives && idx !== undefined && idx > -1) {
128
+ mutated.directives[idx] = createOrUpdateSdlDirective(
129
+ importedGraphQLFiles,
130
+ allGraphQLFiles,
131
+ mutated.directives[idx],
132
+ )
133
+ } else {
134
+ mutated.directives = mutated.directives || []
135
+ mutated.directives.push(
136
+ createOrUpdateSdlDirective(importedGraphQLFiles, allGraphQLFiles),
137
+ )
138
+ }
139
+ return mutated
140
+ },
141
+ })
142
+
143
+ if (!hasSchemaElement) {
144
+ ast = visit(ast, {
145
+ Document(node) {
146
+ const mutated = cloneDeep(node)
147
+ mutated.definitions.push(
148
+ createSchemaElement(importedGraphQLFiles, allGraphQLFiles),
149
+ )
150
+ return mutated
151
+ },
152
+ })
153
+ }
154
+
155
+ fs.writeFileSync(output, print(ast))
156
+ }