@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,176 @@
1
+ import * as debug from 'debug'
2
+ import * as fs from 'fs-extra'
3
+ import * as glob from 'glob'
4
+ import * as inquirer from 'inquirer'
5
+ import * as path from 'path'
6
+ import * as yaml from 'yaml'
7
+
8
+ /**
9
+ * Get effective StepZen endpoint configuration for a directory:
10
+ * Traverse the file system starting at `source` and
11
+ * - merge all `config.yaml` files (discarding unrecognized properties)
12
+ * - merge all `config` sections from `stepzen.config.json` files
13
+ *
14
+ * Possibly, interactive: if `silent` is `false` and there are non-empty
15
+ * `config` sections in `stepzen.config.json` files.
16
+ */
17
+ export default async (source: string, silent = false, answers: any = {}) => {
18
+ const config = {
19
+ configurationset: [] as any[],
20
+ ruleset: [] as any[],
21
+ access: undefined as any,
22
+ deployment: undefined as any,
23
+ }
24
+
25
+ debug('stepzen:transpiler:config')(`getting effective config for ${source}`)
26
+
27
+ // Now let's parse and add any config.yamls
28
+ let configYamlCount = 0
29
+ for (const y of glob.sync('**/config.yaml', {cwd: source})) {
30
+ const filePath = path.join(source, y)
31
+
32
+ const file = fs.readFileSync(filePath, 'utf8')
33
+ let asYAML
34
+ try {
35
+ asYAML = yaml.parse(file, {schema: 'failsafe'})
36
+ } catch (error) {
37
+ debug('stepzen:transpiler:config')(
38
+ `Ignoring an invalid config.yaml ${filePath}.` +
39
+ ` YAML parse error: ${error}`,
40
+ )
41
+ continue
42
+ }
43
+
44
+ if (!asYAML) {
45
+ debug('stepzen:transpiler:config')(
46
+ `ignoring an empty config.yaml ${filePath}`,
47
+ )
48
+ continue
49
+ }
50
+
51
+ configYamlCount += 1
52
+ debug('stepzen:transpiler:config')(
53
+ `adding config.yaml ${filePath}:\n${JSON.stringify(asYAML, null, 2)}`,
54
+ )
55
+
56
+ // strip away any non-recognized properties
57
+ Object.entries(asYAML).forEach(([keyAsAny, value]) => {
58
+ if (Object.prototype.hasOwnProperty.call(config, keyAsAny)) {
59
+ const key = keyAsAny as keyof typeof config
60
+ config[key] = Array.isArray(config[key])
61
+ ? config[key].concat(value)
62
+ : value
63
+ } else {
64
+ debug('stepzen:transpiler:config')(
65
+ `ignoring unrecognized config property ${keyAsAny}`,
66
+ )
67
+ }
68
+ })
69
+ }
70
+
71
+ debug('stepzen:transpiler:config')(
72
+ `done adding **/config.yaml files (processed: ${configYamlCount})`,
73
+ )
74
+
75
+ // Now let's build configs from questions
76
+ let configJsonCount = 0
77
+ for await (const j of glob.sync('**/stepzen.config.json', {
78
+ cwd: source,
79
+ })) {
80
+ const filePath = path.join(source, j)
81
+
82
+ const file = fs.readFileSync(filePath, 'utf8')
83
+ const asJSON = JSON.parse(file)
84
+
85
+ configJsonCount += 1
86
+ debug('stepzen:transpiler:config')(
87
+ `adding stepzen.config.json ${filePath}:` +
88
+ `\n${JSON.stringify(asJSON, null, 2)}`,
89
+ )
90
+
91
+ if (asJSON.config?.questions) {
92
+ for await (const question of asJSON.config?.questions) {
93
+ const [name, key] = question.name.split('.')
94
+
95
+ let answer: any = {}
96
+
97
+ if (silent) {
98
+ answer = {
99
+ [name]: {[key]: answers[name]?.[key] ? answers[name]?.[key] : ''},
100
+ }
101
+ } else {
102
+ answer = await inquirer.prompt({
103
+ type: 'password',
104
+ ...question,
105
+ })
106
+ }
107
+
108
+ const configset = {
109
+ configuration: {
110
+ name,
111
+ [key]: answer[name][key],
112
+ },
113
+ }
114
+
115
+ debug('stepzen:transpiler:config')(
116
+ `question: ${JSON.stringify(question, null, 2)}`,
117
+ )
118
+ debug('stepzen:transpiler:config')(
119
+ `answer: ${JSON.stringify(configset, null, 2)}`,
120
+ )
121
+
122
+ config.configurationset.push({...configset})
123
+ }
124
+ }
125
+ }
126
+
127
+ debug('stepzen:transpiler:config')(
128
+ `done adding **/stepzen.config.json files (processed: ${configJsonCount})`,
129
+ )
130
+
131
+ debug('stepzen:transpiler:config')(
132
+ `combined content of all config files:` +
133
+ `\n${JSON.stringify(config, null, 2)}`,
134
+ )
135
+
136
+ // OK now let's collate everything into shared configurations
137
+ const configurationset = []
138
+ {
139
+ const obj: any = {}
140
+ for (const c of config.configurationset) {
141
+ const name = c.configuration.name
142
+ if (!obj[name]) obj[name] = {}
143
+ for (const [key, value] of Object.entries(c.configuration)) {
144
+ if (key === name) continue
145
+ obj[name][key] = value
146
+ }
147
+ }
148
+
149
+ for (const configuration of Object.keys(obj)) {
150
+ configurationset.push({
151
+ configuration: {...obj[configuration]},
152
+ })
153
+ }
154
+ }
155
+
156
+ // Now convert back into StepZen format
157
+ const structured = Object.fromEntries(
158
+ Object.entries({...config, configurationset}).filter(([_key, value]) =>
159
+ Array.isArray(value) ? value.length > 0 : value !== undefined,
160
+ ),
161
+ )
162
+
163
+ // Return YAML, if appropriate
164
+ if (Object.keys(structured).length > 0) {
165
+ const configYamlStr = yaml.stringify(structured)
166
+ debug('stepzen:transpiler:config')(`effective config:\n${configYamlStr}`)
167
+ return configYamlStr
168
+ }
169
+
170
+ debug('stepzen:transpiler:config')(
171
+ `Could not find any of the supported properties in the config:` +
172
+ ` [ '${Object.keys(config).join(`', '`)}' ].` +
173
+ ` Retuning 'false' meaning 'effective config is empty'.`,
174
+ )
175
+ return false
176
+ }
@@ -0,0 +1,44 @@
1
+ import * as fs from 'fs-extra'
2
+ import * as os from 'os'
3
+ import * as path from 'path'
4
+ import * as shell from 'shelljs'
5
+
6
+ import stitch from '../actions/stitch'
7
+ import {getExtensions} from '../utils/merge-helpers'
8
+
9
+ export default async (
10
+ source: string,
11
+ options: {
12
+ extensions: string
13
+ } = {
14
+ extensions: '',
15
+ },
16
+ ) => {
17
+ if (!fs.existsSync(source)) {
18
+ throw new Error(`Cannot find source directory ${source}`)
19
+ }
20
+
21
+ let extensions = options.extensions
22
+
23
+ if (!extensions) {
24
+ extensions = await getExtensions()
25
+ }
26
+
27
+ const stitched = stitch(source)
28
+ const index = path.join(stitched, 'index.graphql')
29
+ const graphql = fs.readFileSync(index, 'utf8')
30
+
31
+ const tmp = path.join(os.tmpdir(), `stepzen-lint-${Date.now()}`)
32
+ fs.ensureDirSync(tmp)
33
+ const lintFile = path.join(tmp, 'index.graphql')
34
+ fs.writeFileSync(lintFile, `${extensions}${os.EOL}${os.EOL}${graphql}`)
35
+
36
+ shell.exec(
37
+ `npx graphql-schema-linter ${lintFile}`,
38
+ {silent: true},
39
+ (code, stdout, stderr) => {
40
+ console.log(stdout)
41
+ fs.removeSync(tmp)
42
+ },
43
+ )
44
+ }
@@ -0,0 +1,243 @@
1
+ import * as fs from 'fs-extra'
2
+ import * as glob from 'glob'
3
+ import {mergeTypeDefs} from '@graphql-tools/merge'
4
+ import {parse, visit} from 'graphql'
5
+ import * as os from 'os'
6
+ import * as path from 'path'
7
+
8
+ import {
9
+ dedupeTempFolder,
10
+ findQueryMutationInSchema,
11
+ findTypeInSchema,
12
+ getSchema,
13
+ mergeQueryMutationIntoSchema,
14
+ removeQueryMutationFromSchema,
15
+ mergeTypeIntoSchema,
16
+ removeTypeFromSchema,
17
+ getConfiguration,
18
+ findNextAvailableSubfolder,
19
+ getExtensions,
20
+ } from '../utils/merge-helpers'
21
+ import print from './print'
22
+ import setFilesInSDL from '../utils/set-files-in-sdl'
23
+ import stripEmptyQueriesAndMutations from '../utils/strip-empty-queries-and-mutations'
24
+ import copyWorkspaceContent from '../utils/copy-workspace-content'
25
+ import {ALL_GRAPHQL_FILES} from '../utils/constants'
26
+
27
+ // It's safe to use this special placeholder value here: in case of a failure
28
+ // in the merge / import process it will not reach the workspace folder.
29
+ // All intermediary steps are carried out in a temp folder, and only when all
30
+ // merge / import steps are completed, the result it copied over to the
31
+ // workspace folder.
32
+ const BLANK_INDEX_TEMPLATE = `
33
+ schema @sdl(files: ["${ALL_GRAPHQL_FILES}"]) {
34
+ query: Query
35
+ }
36
+ `.trim()
37
+
38
+ const BLANK_QUERY_TYPE = `
39
+ type Query {
40
+ __query: String
41
+ }
42
+ `.trim()
43
+
44
+ export default async (
45
+ original: string,
46
+ imported: {
47
+ name: string
48
+ source: string
49
+ },
50
+ options: {
51
+ answers: any
52
+ output: string | null
53
+ silent: boolean
54
+ /** when `false` merge only covers config files and updates @sdl directrive */
55
+ mergeTypes?: boolean
56
+ /** merge behaviour when a schema with the given name exists in the source */
57
+ onConflict?: 'overwrite' | 'append'
58
+ extensions?: string
59
+ } = {
60
+ answers: {},
61
+ output: null,
62
+ silent: false,
63
+ mergeTypes: true,
64
+ onConflict: 'append',
65
+ extensions: '',
66
+ },
67
+ ) => {
68
+ // Make sure there is an output directory
69
+ if (!options.answers) options.answers = {}
70
+ if (!options.output)
71
+ options.output = path.join(os.tmpdir(), `stepzen-tmp-${Date.now()}`)
72
+ if (!options.silent) options.silent = false
73
+ if (options.mergeTypes === undefined) options.mergeTypes = true
74
+ if (options.onConflict === undefined) options.onConflict = 'append'
75
+ if (!options.extensions) options.extensions = await getExtensions()
76
+
77
+ // To stop things like
78
+ // C:\Users\Darren\AppData\Local\Temp\stepzen-tmp-config-1638293497187\C:\Users\Darren\AppData\Local\Temp\stepzen-tmp-1638293496286
79
+ options.output = dedupeTempFolder(options.output)
80
+
81
+ // Ensure original, importing and output directories exist
82
+ if (!fs.existsSync(original))
83
+ throw new Error(`Cannot find original directory ${original}`)
84
+ if (!fs.existsSync(imported.source))
85
+ throw new Error(`Cannot find imported source directory ${imported.source}`)
86
+ fs.ensureDirSync(options.output)
87
+
88
+ // Copy the original into the output.
89
+ copyWorkspaceContent(original, options.output)
90
+
91
+ // Ensure an index.graphql exists
92
+ const outputIndex = path.join(options.output, 'index.graphql')
93
+ if (!fs.existsSync(outputIndex)) {
94
+ fs.writeFileSync(
95
+ outputIndex,
96
+ options.mergeTypes
97
+ ? // (2022-03-09, vluakshov) Not sure what'd break without the
98
+ // blank Query type, but that's why I do not want to remove it
99
+ // from the default code path.
100
+ BLANK_INDEX_TEMPLATE + BLANK_QUERY_TYPE
101
+ : // In the non-default code path that does NOT merge types
102
+ // the blank Query type causes explicit problems
103
+ // (https://github.com/steprz/stepzen-cli/issues/482).
104
+ BLANK_INDEX_TEMPLATE,
105
+ )
106
+ }
107
+
108
+ const targetSubfolder =
109
+ options.onConflict === 'overwrite'
110
+ ? imported.name
111
+ : findNextAvailableSubfolder(original, imported.name)
112
+
113
+ let importedGraphQLFiles: string[] = []
114
+ if (options.mergeTypes) {
115
+ const merged = mergeTypeDefs([
116
+ await getSchema(options.output, options.extensions),
117
+ await getSchema(imported.source, options.extensions),
118
+ ])
119
+
120
+ let queries: any[] = []
121
+ let mutations: any[] = []
122
+ let types: any[] = []
123
+
124
+ visit(merged, {
125
+ ObjectTypeDefinition(node) {
126
+ if (node.name.value === 'Query') queries = queries.concat(node.fields)
127
+ else if (node.name.value === 'Mutation')
128
+ mutations = mutations.concat(node.fields)
129
+ else types = types.concat(node)
130
+ },
131
+ })
132
+
133
+ const details = {
134
+ original: glob.sync('**/*.graphql', {cwd: options.output}).map(file => {
135
+ const content = fs.readFileSync(`${options.output}/${file}`, 'utf8')
136
+ return {ast: parse(content), file}
137
+ }),
138
+ imported: glob.sync('**/*.graphql', {cwd: imported.source}).map(file => {
139
+ const content = fs.readFileSync(`${imported.source}/${file}`, 'utf8')
140
+ return {ast: parse(content), file}
141
+ }),
142
+ }
143
+
144
+ // Merge Queries and Mutations
145
+ for (const type of [...queries, ...mutations]) {
146
+ const isInOriginal = findQueryMutationInSchema(
147
+ type.name.value,
148
+ details.original,
149
+ )
150
+ const isInImported = findQueryMutationInSchema(
151
+ type.name.value,
152
+ details.imported,
153
+ )
154
+
155
+ if (isInOriginal && isInImported) {
156
+ details.original = mergeQueryMutationIntoSchema(type, details.original)
157
+ details.imported = removeQueryMutationFromSchema(
158
+ type.name.value,
159
+ details.imported,
160
+ )
161
+ }
162
+ }
163
+
164
+ // Merge Types
165
+ for (const type of types) {
166
+ const isInOriginal = findTypeInSchema(type.name.value, details.original)
167
+ const isInImported = findTypeInSchema(type.name.value, details.imported)
168
+
169
+ if (isInOriginal && isInImported) {
170
+ details.original = mergeTypeIntoSchema(type, details.original)
171
+ details.imported = removeTypeFromSchema(
172
+ type.name.value,
173
+ details.imported,
174
+ )
175
+ }
176
+ }
177
+
178
+ // Clean up the files. Remove empty Query / Mutation types, filter out now-empty files
179
+ const cleaned = {
180
+ original: details.original
181
+ .map(item => ({
182
+ ...item,
183
+ ast: stripEmptyQueriesAndMutations(item.ast),
184
+ }))
185
+ .filter(item => item.ast.definitions.length > 0),
186
+ imported: details.imported
187
+ .map(item => ({
188
+ ...item,
189
+ ast: stripEmptyQueriesAndMutations(item.ast),
190
+ }))
191
+ .filter(item => item.ast.definitions.length > 0),
192
+ }
193
+
194
+ // Write the files to the output directory
195
+ cleaned.original.forEach((a: any) => {
196
+ // eslint-disable-next-line
197
+ const file = path.join(options.output as any, a.file)
198
+ const deduped = dedupeTempFolder(file)
199
+
200
+ fs.ensureFileSync(deduped)
201
+ fs.writeFileSync(deduped, print(a.ast))
202
+ })
203
+
204
+ cleaned.imported.forEach(a => {
205
+ // eslint-disable-next-line
206
+ const file = path.join(options.output as any, targetSubfolder, a.file)
207
+ const deduped = dedupeTempFolder(file)
208
+
209
+ fs.ensureFileSync(deduped)
210
+ fs.writeFileSync(deduped, print(a.ast))
211
+ importedGraphQLFiles.push(path.relative(options.output!, deduped))
212
+ })
213
+ } else {
214
+ glob.sync('**/*.graphql', {cwd: imported.source}).forEach(relativePath => {
215
+ const importedFullPath = path.join(imported.source, relativePath)
216
+ const targetFullPath = path.join(
217
+ options.output!,
218
+ targetSubfolder,
219
+ relativePath,
220
+ )
221
+ fs.ensureDirSync(path.dirname(targetFullPath))
222
+ fs.copyFileSync(importedFullPath, targetFullPath)
223
+ importedGraphQLFiles.push(path.relative(options.output!, targetFullPath))
224
+ })
225
+ }
226
+
227
+ // Make sure all files are referenced in @sdl
228
+ setFilesInSDL(options.output, importedGraphQLFiles)
229
+
230
+ // Generate configuration
231
+ const config = await getConfiguration(
232
+ [options.output, imported.source],
233
+ options.silent,
234
+ options.answers,
235
+ )
236
+ if (config) {
237
+ const configFile = path.join(options.output, 'config.yaml')
238
+ fs.writeFileSync(configFile, config as string)
239
+ }
240
+
241
+ // Return a merged schema!
242
+ return options.output
243
+ }
@@ -0,0 +1,8 @@
1
+ import {DocumentNode, print} from 'graphql'
2
+ import * as prettier from 'prettier'
3
+
4
+ export default (ast: DocumentNode): string => {
5
+ const printed = print(ast)
6
+ const formatted = prettier.format(printed, {parser: 'graphql'})
7
+ return formatted
8
+ }
@@ -0,0 +1,113 @@
1
+ import {clone, cloneDeep} from 'lodash'
2
+ import {parse, print, visit} from 'graphql'
3
+ import * as fs from 'fs-extra'
4
+ import * as glob from 'glob'
5
+ import * as os from 'os'
6
+ import * as path from 'path'
7
+ import * as prettier from 'prettier'
8
+
9
+ import dedupeQueryAndMutationTypes from '../utils/dedupe-query-and-mutation-types'
10
+ import {ALL_GRAPHQL_FILES} from '../utils/constants'
11
+ import {getAllGraphQLFiles} from '../utils/copy-workspace-content'
12
+
13
+ export default (
14
+ source: string,
15
+ output: string = path.join(os.tmpdir(), `stepzen-tmp-${Date.now()}`),
16
+ ) => {
17
+ // Ensure source and output directories exist
18
+ if (!fs.existsSync(source))
19
+ throw new Error(`Cannot find source directory ${source}`)
20
+ fs.ensureDirSync(output)
21
+
22
+ // Get a list of files.
23
+ let ast: any
24
+ let files: string[] = []
25
+
26
+ // If there's an index.graphQL - get files argument in @sdl directive
27
+ const sourceIndex = path.join(source, 'index.graphql')
28
+
29
+ if (fs.existsSync(sourceIndex)) {
30
+ const index = fs.readFileSync(sourceIndex, 'utf8')
31
+ ast = parse(index)
32
+ ast = visit(ast, {
33
+ Directive(node) {
34
+ if (node.name.value === 'sdl') {
35
+ const list = node.arguments?.find(
36
+ (arg: any) => arg.name.value === 'files',
37
+ )
38
+ // If we find a 'files' argument, we copy the list, and remove the argument
39
+ if (list) {
40
+ const copy: any = clone(list.value)
41
+ for (const file of copy.values) {
42
+ if (file.value === ALL_GRAPHQL_FILES) {
43
+ files = files.concat(getAllGraphQLFiles(source))
44
+ } else {
45
+ files = files.concat(file.value)
46
+ }
47
+ }
48
+ const mutated: any = cloneDeep(node)
49
+ mutated.arguments = mutated.arguments.filter(
50
+ (arg: any) => arg.name.value !== 'files',
51
+ )
52
+ return mutated
53
+ }
54
+ }
55
+ },
56
+ })
57
+ } else {
58
+ const content = glob
59
+ .sync('**/*.graphql', {cwd: source})
60
+ .map((file: string) => {
61
+ const graphql = fs.readFileSync(`${source}/${file}`, 'utf8')
62
+ return graphql
63
+ })
64
+ ast = parse(content.join(os.EOL))
65
+ }
66
+
67
+ // Strip @sdl directive
68
+ ast = visit(ast, {
69
+ Directive(node) {
70
+ if (node.name.value === 'sdl') return null
71
+ },
72
+ })
73
+
74
+ // Check all the files exist
75
+ for (const file of files) {
76
+ const find = path.join(source, file)
77
+ if (!fs.existsSync(find)) {
78
+ throw new Error(
79
+ `Cannot find file ${file} referenced in the @sdl directive in index.graphql`,
80
+ )
81
+ }
82
+ }
83
+
84
+ // Get all the files and stitch
85
+ const printed = print(ast)
86
+ let stitched = `${printed}${os.EOL}`
87
+ for (const file of files) {
88
+ const find = path.join(source, file)
89
+ const content = fs.readFileSync(find, 'utf8')
90
+ stitched += `${content}${os.EOL}`
91
+ }
92
+
93
+ // Dedupe Query and Mutation types
94
+ stitched = dedupeQueryAndMutationTypes(stitched)
95
+
96
+ // Format
97
+ stitched = prettier.format(stitched, {parser: 'graphql'})
98
+
99
+ // Write to output folder
100
+ const outputIndex = path.join(output, 'index.graphql')
101
+ fs.writeFileSync(outputIndex, stitched)
102
+
103
+ // Copy config if exists, too
104
+ const sourceConfig = path.join(source, 'config.yaml')
105
+ const outputConfig = path.join(output, 'config.yaml')
106
+
107
+ if (fs.existsSync(sourceConfig)) {
108
+ fs.copyFileSync(sourceConfig, outputConfig)
109
+ }
110
+
111
+ // Return output folder
112
+ return output
113
+ }
@@ -0,0 +1,74 @@
1
+ import {DocumentNode, parse} from 'graphql'
2
+ import * as dotenv from 'dotenv'
3
+ import * as debug from 'debug'
4
+ import * as fs from 'fs'
5
+ import * as glob from 'glob'
6
+ import * as path from 'path'
7
+
8
+ import print from '../actions/print'
9
+ import stitch from '../actions/stitch'
10
+ import configure from './configure'
11
+
12
+ import configMutations from '../mutations/config'
13
+
14
+ /**
15
+ * Read a StepZen workspace directory, apply StepZen-specific schema and config
16
+ * transformations, and return its effective GraphQL schema and configuration
17
+ * as in-memory strings.
18
+ *
19
+ * @param {*} source absolute path to a schema root folder
20
+ * @return {*} schema, configuration, and a "transpiled" flag indicating
21
+ * whether or not any StepZen-specific transformations have actually
22
+ * been applied.
23
+ */
24
+ export default async (source: string) => {
25
+ // Ensure source and output directories exist
26
+ if (!fs.existsSync(source)) {
27
+ throw new Error(`Cannot find source directory ${source}`)
28
+ }
29
+
30
+ // Load env vars, from working and source directories
31
+ debug('stepzen:dotenv')(
32
+ `loading .env from ${process.cwd()}, at transpiler/src/actions/transpile.ts:24`,
33
+ )
34
+ dotenv.config()
35
+ debug('stepzen:dotenv')(
36
+ `loading .env from ${path.resolve(source)}` +
37
+ `, at transpiler/src/actions/transpile.ts:29`,
38
+ )
39
+ dotenv.config({path: path.resolve(source, '.env')})
40
+
41
+ // State of whether we've transpiled or not
42
+ let transpiledConfig = false
43
+
44
+ // See whether to transpile config
45
+ let config = await configure(source, true)
46
+ const configCopy = config
47
+
48
+ if (config) {
49
+ for await (const mutation of configMutations) {
50
+ config = await mutation(config)
51
+ }
52
+ }
53
+
54
+ if (configCopy !== config) {
55
+ transpiledConfig = true
56
+ }
57
+
58
+ // See whether to transpile GraphQL
59
+ const graphqlFiles = glob.sync('**/*.graphql', {cwd: source})
60
+ let schema = ''
61
+
62
+ if (graphqlFiles.length > 0) {
63
+ const stitched = await stitch(source)
64
+ const index = path.join(stitched, 'index.graphql')
65
+ const graphql = fs.readFileSync(index, 'utf8')
66
+ schema = print(parse(graphql))
67
+ }
68
+
69
+ return {
70
+ config,
71
+ schema,
72
+ transpiled: transpiledConfig,
73
+ }
74
+ }