@khanacademy/graphql-flow 1.1.0 → 1.1.2
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.
- package/.flowconfig +2 -0
- package/CHANGELOG.md +12 -0
- package/dist/cli/config.js +4 -3
- package/dist/cli/config.js.flow +3 -4
- package/dist/cli/config.js.map +1 -1
- package/dist/cli/run.js +18 -1
- package/dist/cli/run.js.flow +14 -3
- package/dist/cli/run.js.map +1 -1
- package/dist/generateTypeFiles.js +3 -1
- package/dist/generateTypeFiles.js.flow +6 -1
- package/dist/generateTypeFiles.js.map +1 -1
- package/dist/parser/__test__/parse.test.js +3 -1
- package/dist/parser/parse.js +7 -4
- package/dist/parser/parse.js.flow +15 -6
- package/dist/parser/parse.js.map +1 -1
- package/package.json +1 -1
- package/src/cli/config.js +3 -4
- package/src/cli/run.js +14 -3
- package/src/generateTypeFiles.js +6 -1
- package/src/parser/__test__/parse.test.js +3 -1
- package/src/parser/parse.js +15 -6
package/.flowconfig
CHANGED
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# @khanacademy/graphql-flow
|
|
2
2
|
|
|
3
|
+
## 1.1.2
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 9867001: Fix empty variables object
|
|
8
|
+
|
|
9
|
+
## 1.1.1
|
|
10
|
+
|
|
11
|
+
### Patch Changes
|
|
12
|
+
|
|
13
|
+
- a581359: Fix processing of typescript imports that don't use an extension
|
|
14
|
+
|
|
3
15
|
## 1.1.0
|
|
4
16
|
|
|
5
17
|
### Minor Changes
|
package/dist/cli/config.js
CHANGED
|
@@ -33,11 +33,12 @@ const validateOrThrow = (value, jsonSchema) => {
|
|
|
33
33
|
exports.validateOrThrow = validateOrThrow;
|
|
34
34
|
|
|
35
35
|
const loadConfigFile = configFile => {
|
|
36
|
-
// $FlowIgnore
|
|
37
|
-
const data = require(configFile); // eslint-disable-
|
|
36
|
+
// $FlowIgnore
|
|
37
|
+
const data = require(configFile); // eslint-disable-line flowtype-errors/uncovered
|
|
38
38
|
|
|
39
39
|
|
|
40
|
-
validateOrThrow(data, _schema.default);
|
|
40
|
+
validateOrThrow(data, _schema.default); // eslint-disable-line flowtype-errors/uncovered
|
|
41
|
+
|
|
41
42
|
return data;
|
|
42
43
|
};
|
|
43
44
|
/**
|
package/dist/cli/config.js.flow
CHANGED
|
@@ -28,10 +28,9 @@ export const validateOrThrow = (value: mixed, jsonSchema: mixed) => {
|
|
|
28
28
|
};
|
|
29
29
|
|
|
30
30
|
export const loadConfigFile = (configFile: string): Config => {
|
|
31
|
-
// $FlowIgnore
|
|
32
|
-
const data: Config = require(configFile);
|
|
33
|
-
// eslint-disable-
|
|
34
|
-
validateOrThrow(data, configSchema);
|
|
31
|
+
// $FlowIgnore
|
|
32
|
+
const data: Config = require(configFile); // eslint-disable-line flowtype-errors/uncovered
|
|
33
|
+
validateOrThrow(data, configSchema); // eslint-disable-line flowtype-errors/uncovered
|
|
35
34
|
return data;
|
|
36
35
|
};
|
|
37
36
|
|
package/dist/cli/config.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/cli/config.js"],"names":["validateOrThrow","value","jsonSchema","result","valid","Error","errors","map","error","toString","join","loadConfigFile","configFile","data","require","configSchema","getSchemas","schemaFilePath","raw","fs","readFileSync","endsWith","schemaForValidation","queryResponse","descriptions","schemaForTypeGeneration","introspectionData","JSON","parse","findApplicableConfig","path","configs","Array","isArray","find","config","exclude","some","RegExp","test","match","matcher"],"mappings":";;;;;;;AAIA;;AACA;;AAEA;;AACA;;AAQA;;;;AAX0C;AAWL;AAE9B,MAAMA,eAAe,GAAG,CAACC,KAAD,EAAeC,UAAf,KAAqC;AAChE;AACA,QAAMC,MAAM,GAAG,0BAASF,KAAT,EAAgBC,UAAhB,CAAf;;AACA,MAAI,CAACC,MAAM,CAACC,KAAZ,EAAmB;AACf,UAAM,IAAIC,KAAJ,CACFF,MAAM,CAACG,MAAP,CAAcC,GAAd,CAAmBC,KAAD,IAAWA,KAAK,CAACC,QAAN,EAA7B,EAA+CC,IAA/C,CAAoD,IAApD,CADE,CAAN;AAGH;AACD;;AACH,CATM;;;;AAWA,MAAMC,cAAc,GAAIC,UAAD,IAAgC;AAC1D;AACA,QAAMC,IAAY,GAAGC,OAAO,CAACF,UAAD,CAA5B,CAF0D,
|
|
1
|
+
{"version":3,"sources":["../../src/cli/config.js"],"names":["validateOrThrow","value","jsonSchema","result","valid","Error","errors","map","error","toString","join","loadConfigFile","configFile","data","require","configSchema","getSchemas","schemaFilePath","raw","fs","readFileSync","endsWith","schemaForValidation","queryResponse","descriptions","schemaForTypeGeneration","introspectionData","JSON","parse","findApplicableConfig","path","configs","Array","isArray","find","config","exclude","some","RegExp","test","match","matcher"],"mappings":";;;;;;;AAIA;;AACA;;AAEA;;AACA;;AAQA;;;;AAX0C;AAWL;AAE9B,MAAMA,eAAe,GAAG,CAACC,KAAD,EAAeC,UAAf,KAAqC;AAChE;AACA,QAAMC,MAAM,GAAG,0BAASF,KAAT,EAAgBC,UAAhB,CAAf;;AACA,MAAI,CAACC,MAAM,CAACC,KAAZ,EAAmB;AACf,UAAM,IAAIC,KAAJ,CACFF,MAAM,CAACG,MAAP,CAAcC,GAAd,CAAmBC,KAAD,IAAWA,KAAK,CAACC,QAAN,EAA7B,EAA+CC,IAA/C,CAAoD,IAApD,CADE,CAAN;AAGH;AACD;;AACH,CATM;;;;AAWA,MAAMC,cAAc,GAAIC,UAAD,IAAgC;AAC1D;AACA,QAAMC,IAAY,GAAGC,OAAO,CAACF,UAAD,CAA5B,CAF0D,CAEhB;;;AAC1CZ,EAAAA,eAAe,CAACa,IAAD,EAAOE,eAAP,CAAf,CAH0D,CAGrB;;AACrC,SAAOF,IAAP;AACH,CALM;AAOP;AACA;AACA;;;;;AACO,MAAMG,UAAU,GAAIC,cAAD,IAAqD;AAC3E,QAAMC,GAAG,GAAGC,YAAGC,YA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G,OAAX,EAAoBF,IAApB,CAAyBT,IAAzB,CAA/B,CAAP;AACH,GARM,CAAP;AASH,CAhBM","sourcesContent":["// @flow\nimport type {Schema} from '../types';\nimport type {GraphQLSchema} from 'graphql/type/schema';\n\nimport {schemaFromIntrospectionData} from '../schemaFromIntrospectionData';\nimport configSchema from './schema.json'; // eslint-disable-line flowtype-errors/uncovered\n\nimport fs from 'fs';\nimport {\n buildClientSchema,\n buildSchema,\n getIntrospectionQuery,\n graphqlSync,\n type IntrospectionQuery,\n} from 'graphql';\nimport type {Config, GenerateConfig} from '../types';\nimport {validate} from 'jsonschema'; // eslint-disable-line flowtype-errors/uncovered\n\nexport const validateOrThrow = (value: mixed, jsonSchema: mixed) => {\n /* eslint-disable flowtype-errors/uncovered */\n const result = validate(value, jsonSchema);\n if (!result.valid) {\n throw new Error(\n result.errors.map((error) => error.toString()).join('\\n'),\n );\n }\n /* eslint-enable flowtype-errors/uncovered */\n};\n\nexport const loadConfigFile = (configFile: string): Config => {\n // $FlowIgnore\n const data: Config = require(configFile); // eslint-disable-line flowtype-errors/uncovered\n validateOrThrow(data, configSchema); // eslint-disable-line flowtype-errors/uncovered\n return data;\n};\n\n/**\n * Loads a .json 'introspection query response', or a .graphql schema definition.\n */\nexport const getSchemas = (schemaFilePath: string): [GraphQLSchema, Schema] => {\n const raw = fs.readFileSync(schemaFilePath, 'utf8');\n if (schemaFilePath.endsWith('.graphql')) {\n const schemaForValidation = buildSchema(raw);\n const queryResponse = graphqlSync(\n schemaForValidation,\n getIntrospectionQuery({descriptions: true}),\n );\n const schemaForTypeGeneration = schemaFromIntrospectionData(\n // eslint-disable-next-line flowtype-errors/uncovered\n ((queryResponse.data: any): IntrospectionQuery),\n );\n return [schemaForValidation, schemaForTypeGeneration];\n } else {\n // eslint-disable-next-line flowtype-errors/uncovered\n const introspectionData: IntrospectionQuery = JSON.parse(raw);\n const schemaForValidation = buildClientSchema(introspectionData);\n const schemaForTypeGeneration =\n schemaFromIntrospectionData(introspectionData);\n return [schemaForValidation, schemaForTypeGeneration];\n }\n};\n\n/**\n * Find the first item of the `config.generate` array where both:\n * - no item of `exclude` matches\n * - at least one item of `match` matches\n */\nexport const findApplicableConfig = (\n path: string,\n configs: Array<GenerateConfig> | GenerateConfig,\n): ?GenerateConfig => {\n if (!Array.isArray(configs)) {\n configs = [configs];\n }\n return configs.find((config) => {\n if (config.exclude?.some((exclude) => new RegExp(exclude).test(path))) {\n return false;\n }\n if (!config.match) {\n return true;\n }\n return config.match.some((matcher) => new RegExp(matcher).test(path));\n });\n};\n"],"file":"config.js"}
|
package/dist/cli/run.js
CHANGED
|
@@ -73,7 +73,24 @@ const files = (0, _parse.processFiles)(inputFiles, f => {
|
|
|
73
73
|
}
|
|
74
74
|
|
|
75
75
|
if ((0, _fs.existsSync)(f + '.js')) {
|
|
76
|
-
return
|
|
76
|
+
return {
|
|
77
|
+
text: (0, _fs.readFileSync)(f + '.js', 'utf8'),
|
|
78
|
+
resolvedPath: f + '.js'
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if ((0, _fs.existsSync)(f + '.ts')) {
|
|
83
|
+
return {
|
|
84
|
+
text: (0, _fs.readFileSync)(f + '.ts', 'utf8'),
|
|
85
|
+
resolvedPath: f + '.ts'
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
if ((0, _fs.existsSync)(f + '.tsx')) {
|
|
90
|
+
return {
|
|
91
|
+
text: (0, _fs.readFileSync)(f + '.tsx', 'utf8'),
|
|
92
|
+
resolvedPath: f + '.tsx'
|
|
93
|
+
};
|
|
77
94
|
}
|
|
78
95
|
|
|
79
96
|
throw new Error(`Unable to find ${f}`);
|
package/dist/cli/run.js.flow
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// @flow
|
|
3
3
|
/* eslint-disable no-console */
|
|
4
|
+
import type {Schema} from '../types';
|
|
5
|
+
import type {GraphQLSchema} from 'graphql/type/schema';
|
|
6
|
+
|
|
4
7
|
import {generateTypeFiles, processPragmas} from '../generateTypeFiles';
|
|
5
8
|
import {processFiles} from '../parser/parse';
|
|
6
9
|
import {resolveDocuments} from '../parser/resolve';
|
|
@@ -15,7 +18,6 @@ import {print} from 'graphql/language/printer';
|
|
|
15
18
|
import {validate} from 'graphql/validation';
|
|
16
19
|
import path from 'path';
|
|
17
20
|
import {dirname} from 'path';
|
|
18
|
-
import type {GenerateConfig} from '../types';
|
|
19
21
|
|
|
20
22
|
/**
|
|
21
23
|
* This CLI tool executes the following steps:
|
|
@@ -81,7 +83,16 @@ const files = processFiles(inputFiles, (f) => {
|
|
|
81
83
|
return readFileSync(f, 'utf8');
|
|
82
84
|
}
|
|
83
85
|
if (existsSync(f + '.js')) {
|
|
84
|
-
return readFileSync(f + '.js', 'utf8');
|
|
86
|
+
return {text: readFileSync(f + '.js', 'utf8'), resolvedPath: f + '.js'};
|
|
87
|
+
}
|
|
88
|
+
if (existsSync(f + '.ts')) {
|
|
89
|
+
return {text: readFileSync(f + '.ts', 'utf8'), resolvedPath: f + '.ts'};
|
|
90
|
+
}
|
|
91
|
+
if (existsSync(f + '.tsx')) {
|
|
92
|
+
return {
|
|
93
|
+
text: readFileSync(f + '.tsx', 'utf8'),
|
|
94
|
+
resolvedPath: f + '.tsx',
|
|
95
|
+
};
|
|
85
96
|
}
|
|
86
97
|
throw new Error(`Unable to find ${f}`);
|
|
87
98
|
});
|
|
@@ -118,7 +129,7 @@ console.log(Object.keys(resolved).length, 'resolved queries');
|
|
|
118
129
|
|
|
119
130
|
/** Step (4) */
|
|
120
131
|
|
|
121
|
-
const schemaCache = {};
|
|
132
|
+
const schemaCache: {[key: string]: [GraphQLSchema, Schema]} = {};
|
|
122
133
|
const getCachedSchemas = (schemaFilePath: string) => {
|
|
123
134
|
if (!schemaCache[schemaFilePath]) {
|
|
124
135
|
schemaCache[schemaFilePath] = getSchemas(
|
package/dist/cli/run.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/cli/run.js"],"names":["findGraphqlTagReferences","root","response","encoding","cwd","trim","split","map","relative","path","join","_","__","configFilePath","cliFiles","process","argv","console","log","exit","makeAbsPath","maybeRelativePath","basePath","isAbsolute","absConfigPath","config","inputFiles","length","crawl","dirname","files","f","Error","filesHadErrors","Object","keys","forEach","key","file","errors","error","message","resolved","loc","schemaCache","getCachedSchemas","schemaFilePath","validationFailures","printedOperations","filePathAndLine","document","raw","hasNonFragments","definitions","some","kind","rawSource","literals","generateConfig","generate","withTypeNames","printed","includes","push","pragmaResult","strict","strictNullability","schemaForValidation","schemaForTypeGeneration","err","dumpOperations","parent","recursive","JSON","stringify","sort"],"mappings":"AAAA;;AAEA;;;AACA;;AACA;;AACA;;AACA;;AAEA;;AAEA;;AACA;;AAEA;;AACA;;AACA;;;;;;AAPwD;;AAWxD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AAEA,MAAMA,wBAAwB,GAAIC,IAAD,IAAiC;AAC9D,QAAMC,QAAQ,GAAG,6BACb,sGADa,EAEb;AACIC,IAAAA,QAAQ,EAAE,MADd;AAEIC,IAAAA,GAAG,EAAEH;AAFT,GAFa,CAAjB;AAOA,SAAOC,QAAQ,CACVG,IADE,GAEFC,KAFE,CAEI,IAFJ,EAGFC,GAHE,CAGGC,QAAD,IAAcC,cAAKC,IAAL,CAAUT,IAAV,EAAgBO,QAAhB,CAHhB,CAAP;AAIH,CAZD;;AAcA,MAAM,CAACG,CAAD,EAAIC,EAAJ,EAAQC,cAAR,EAAwB,GAAGC,QAA3B,IAAuCC,OAAO,CAACC,IAArD;;AAEA,IACIH,cAAc,KAAK,IAAnB,IACAA,cAAc,KAAK,QADnB,IAEAA,cAAc,KAAK,MAFnB,IAGA,CAACA,cAJL,EAKE;AACEI,EAAAA,OAAO,CAACC,GAAR,CAAa;AACjB;AACA,wDAFI;AAGAH,EAAAA,OAAO,CAACI,IAAR,CAAa,CAAb,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/env node\n// @flow\n/* eslint-disable no-console */\nimport {generateTypeFiles, processPragmas} from '../generateTypeFiles';\nimport {processFiles} from '../parser/parse';\nimport {resolveDocuments} from '../parser/resolve';\nimport {findApplicableConfig, getSchemas, loadConfigFile} from './config';\n\nimport {addTypenameToDocument} from 'apollo-utilities'; // eslint-disable-line flowtype-errors/uncovered\n\nimport {execSync} from 'child_process';\nimport {existsSync, mkdirSync, readFileSync, writeFileSync} from 'fs';\nimport {type DocumentNode} from 'graphql';\nimport {print} from 'graphql/language/printer';\nimport {validate} from 'graphql/validation';\nimport path from 'path';\nimport {dirname} from 'path';\nimport type {GenerateConfig} from '../types';\n\n/**\n * This CLI tool executes the following steps:\n * 1) parse & validate config file\n * 2) crawl files to find all operations and fragments, with\n * tagged template literals and expressions.\n * 3) resolve the found operations, passing the literals and\n * fragments into the `graphql-tag` function to produce\n * the DocumentNodes.\n * 4) generate types for all resolved Queries & Mutations\n */\n\n/** Step (1) */\n\nconst findGraphqlTagReferences = (root: string): Array<string> => {\n const response = execSync(\n \"git grep -I --word-regexp --name-only --fixed-strings 'graphql-tag' -- '*.js' '*.jsx' '*.ts' '*.tsx'\",\n {\n encoding: 'utf8',\n cwd: root,\n },\n );\n return response\n .trim()\n .split('\\n')\n .map((relative) => path.join(root, relative));\n};\n\nconst [_, __, configFilePath, ...cliFiles] = process.argv;\n\nif (\n configFilePath === '-h' ||\n configFilePath === '--help' ||\n configFilePath === 'help' ||\n !configFilePath\n) {\n console.log(`graphql-flow\n\nUsage: graphql-flow [configFile.json] [filesToCrawl...]`);\n process.exit(1); // eslint-disable-line flowtype-errors/uncovered\n}\n\nconst makeAbsPath = (maybeRelativePath: string, basePath: string) => {\n return path.isAbsolute(maybeRelativePath)\n ? maybeRelativePath\n : path.join(basePath, maybeRelativePath);\n};\n\nconst absConfigPath = makeAbsPath(configFilePath, process.cwd());\n\nconst config = loadConfigFile(absConfigPath);\n\nconst inputFiles = cliFiles.length\n ? cliFiles\n : findGraphqlTagReferences(\n makeAbsPath(config.crawl.root, path.dirname(absConfigPath)),\n );\n\n/** Step (2) */\n\nconst files = processFiles(inputFiles, (f) => {\n if (existsSync(f)) {\n return readFileSync(f, 'utf8');\n }\n if (existsSync(f + '.js')) {\n return readFileSync(f + '.js', 'utf8');\n }\n throw new Error(`Unable to find ${f}`);\n});\n\nlet filesHadErrors = false;\nObject.keys(files).forEach((key) => {\n const file = files[key];\n if (file.errors.length) {\n filesHadErrors = true;\n console.error(`Errors in ${file.path}`);\n file.errors.forEach((error) => {\n console.error(` - ${error.message}`);\n });\n }\n});\n\nif (filesHadErrors) {\n console.error('Aborting');\n process.exit(1); // eslint-disable-line flowtype-errors/uncovered\n}\n\n/** Step (3) */\n\nconst {resolved, errors} = resolveDocuments(files);\nif (errors.length) {\n errors.forEach((error) => {\n console.error(`Resolution error ${error.message} in ${error.loc.path}`);\n });\n console.error('Aborting');\n process.exit(1); // eslint-disable-line flowtype-errors/uncovered\n}\n\nconsole.log(Object.keys(resolved).length, 'resolved queries');\n\n/** Step (4) */\n\nconst schemaCache = {};\nconst getCachedSchemas = (schemaFilePath: string) => {\n if (!schemaCache[schemaFilePath]) {\n schemaCache[schemaFilePath] = getSchemas(\n makeAbsPath(schemaFilePath, path.dirname(absConfigPath)),\n );\n }\n\n return schemaCache[schemaFilePath];\n};\n\nlet validationFailures: number = 0;\nconst printedOperations: Array<string> = [];\n\nObject.keys(resolved).forEach((filePathAndLine) => {\n const {document, raw} = resolved[filePathAndLine];\n\n const hasNonFragments = document.definitions.some(\n ({kind}) => kind !== 'FragmentDefinition',\n );\n const rawSource: string = raw.literals[0];\n\n const generateConfig = findApplicableConfig(\n // strip off the trailing line number, e.g. `:23`\n filePathAndLine.split(':')[0],\n config.generate,\n );\n if (!generateConfig) {\n return; // no generate config matches, bail\n }\n\n // eslint-disable-next-line flowtype-errors/uncovered\n const withTypeNames: DocumentNode = addTypenameToDocument(document);\n const printed = print(withTypeNames);\n if (hasNonFragments && !printedOperations.includes(printed)) {\n printedOperations.push(printed);\n }\n\n const pragmaResult = processPragmas(\n generateConfig,\n config.crawl,\n rawSource,\n );\n if (!pragmaResult.generate) {\n return;\n }\n if (pragmaResult.strict != null) {\n generateConfig.strictNullability = pragmaResult.strict;\n }\n\n const [schemaForValidation, schemaForTypeGeneration] = getCachedSchemas(\n generateConfig.schemaFilePath,\n );\n\n if (hasNonFragments) {\n /* eslint-disable flowtype-errors/uncovered */\n const errors = validate(schemaForValidation, withTypeNames);\n /* eslint-disable flowtype-errors/uncovered */\n if (errors.length) {\n errors.forEach((error) => {\n console.error(\n `Schema validation found errors for ${raw.loc.path}!`,\n );\n console.error(printed);\n console.error(error);\n validationFailures++;\n });\n }\n /* eslint-enable flowtype-errors/uncovered */\n }\n\n try {\n generateTypeFiles(\n raw.loc.path,\n schemaForTypeGeneration,\n withTypeNames,\n generateConfig,\n );\n // eslint-disable-next-line flowtype-errors/uncovered\n } catch (err) {\n console.error(`Error while generating operation from ${raw.loc.path}`);\n console.error(printed);\n // eslint-disable-next-line flowtype-errors/uncovered\n console.error(err);\n validationFailures++;\n }\n});\n\nif (validationFailures) {\n console.error(\n `Encountered ${validationFailures} validation failures while printing types.`,\n );\n // eslint-disable-next-line flowtype-errors/uncovered\n process.exit(1);\n}\n\nif (config.crawl.dumpOperations) {\n const dumpOperations = config.crawl.dumpOperations;\n const parent = dirname(dumpOperations);\n mkdirSync(parent, {recursive: true});\n writeFileSync(\n dumpOperations,\n JSON.stringify(printedOperations.sort(), null, 2),\n );\n}\n"],"file":"run.js"}
|
|
1
|
+
{"version":3,"sources":["../../src/cli/run.js"],"names":["findGraphqlTagReferences","root","response","encoding","cwd","trim","split","map","relative","path","join","_","__","configFilePath","cliFiles","process","argv","console","log","exit","makeAbsPath","maybeRelativePath","basePath","isAbsolute","absConfigPath","config","inputFiles","length","crawl","dirname","files","f","text","resolvedPath","Error","filesHadErrors","Object","keys","forEach","key","file","errors","error","message","resolved","loc","schemaCache","getCachedSchemas","schemaFilePath","validationFailures","printedOperations","filePathAndLine","document","raw","hasNonFragments","definitions","some","kind","rawSource","literals","generateConfig","generate","withTypeNames","printed","includes","push","pragmaResult","strict","strictNullability","schemaForValidation","schemaForTypeGeneration","err","dumpOperations","parent","recursive","JSON","stringify","sort"],"mappings":"AAAA;;AAEA;;;AAIA;;AACA;;AACA;;AACA;;AAEA;;AAEA;;AACA;;AAEA;;AACA;;AACA;;;;;;AAPwD;;AAUxD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AAEA,MAAMA,wBAAwB,GAAIC,IAAD,IAAiC;AAC9D,QAAMC,QAAQ,GAAG,6BACb,sGADa,EAEb;AACIC,IAAAA,QAAQ,EAAE,MADd;AAEIC,IAAAA,GAAG,EAAEH;AAFT,GAFa,CAAjB;AAOA,SAAOC,QAAQ,CACVG,IADE,GAEFC,KAFE,CAEI,IAFJ,EAGFC,GAHE,CAGGC,QAAD,IAAcC,cAAKC,IAAL,CAAUT,IAAV,EAAgBO,QAAhB,CAHhB,CAAP;AAIH,CAZD;;AAcA,MAAM,CAACG,CAAD,EAAIC,EAAJ,EAAQC,cAAR,EAAwB,GAAGC,QAA3B,IAAuCC,OAAO,CAACC,IAArD;;AAEA,IACIH,cAAc,KAAK,IAAnB,IACAA,cAAc,KAAK,QADnB,IAEAA,cAAc,KAAK,MAFnB,IAGA,CAACA,cAJL,EAKE;AACEI,EAAAA,OAAO,CAACC,GAAR,CAAa;AACjB;AACA,wDAFI;AAGAH,EAAAA,OAAO,CAACI,IAAR,CAAa,CAAb,EAJF,CAImB;AACpB;;AAED,MAAMC,WAAW,GAAG,CAACC,iBAAD,EAA4BC,QAA5B,KAAiD;AACjE,SAAOb,cAAKc,UAAL,CAAgBF,iBAAhB,IACDA,iBADC,GAEDZ,cAAKC,IAAL,CAAUY,QAAV,EAAoBD,iBAApB,CAFN;AAGH,CAJD;;AAMA,MAAMG,aAAa,GAAGJ,WAAW,CAACP,cAAD,EAAiBE,OAAO,CAACX,GAAR,EAAjB,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V,EAAkB;AAACC,IAAAA,SAAS,EAAE;AAAZ,GAAlB;AACA,yBACIF,cADJ,EAEIG,IAAI,CAACC,SAAL,CAAe1B,iBAAiB,CAAC2B,IAAlB,EAAf,EAAyC,IAAzC,EAA+C,CAA/C,CAFJ;AAIH","sourcesContent":["#!/usr/bin/env node\n// @flow\n/* eslint-disable no-console */\nimport type {Schema} from '../types';\nimport type {GraphQLSchema} from 'graphql/type/schema';\n\nimport {generateTypeFiles, processPragmas} from '../generateTypeFiles';\nimport {processFiles} from '../parser/parse';\nimport {resolveDocuments} from '../parser/resolve';\nimport {findApplicableConfig, getSchemas, loadConfigFile} from './config';\n\nimport {addTypenameToDocument} from 'apollo-utilities'; // eslint-disable-line flowtype-errors/uncovered\n\nimport {execSync} from 'child_process';\nimport {existsSync, mkdirSync, readFileSync, writeFileSync} from 'fs';\nimport {type DocumentNode} from 'graphql';\nimport {print} from 'graphql/language/printer';\nimport {validate} from 'graphql/validation';\nimport path from 'path';\nimport {dirname} from 'path';\n\n/**\n * This CLI tool executes the following steps:\n * 1) parse & validate config file\n * 2) crawl files to find all operations and fragments, with\n * tagged template literals and expressions.\n * 3) resolve the found operations, passing the literals and\n * fragments into the `graphql-tag` function to produce\n * the DocumentNodes.\n * 4) generate types for all resolved Queries & Mutations\n */\n\n/** Step (1) */\n\nconst findGraphqlTagReferences = (root: string): Array<string> => {\n const response = execSync(\n \"git grep -I --word-regexp --name-only --fixed-strings 'graphql-tag' -- '*.js' '*.jsx' '*.ts' '*.tsx'\",\n {\n encoding: 'utf8',\n cwd: root,\n },\n );\n return response\n .trim()\n .split('\\n')\n .map((relative) => path.join(root, relative));\n};\n\nconst [_, __, configFilePath, ...cliFiles] = process.argv;\n\nif (\n configFilePath === '-h' ||\n configFilePath === '--help' ||\n configFilePath === 'help' ||\n !configFilePath\n) {\n console.log(`graphql-flow\n\nUsage: graphql-flow [configFile.json] [filesToCrawl...]`);\n process.exit(1); // eslint-disable-line flowtype-errors/uncovered\n}\n\nconst makeAbsPath = (maybeRelativePath: string, basePath: string) => {\n return path.isAbsolute(maybeRelativePath)\n ? maybeRelativePath\n : path.join(basePath, maybeRelativePath);\n};\n\nconst absConfigPath = makeAbsPath(configFilePath, process.cwd());\n\nconst config = loadConfigFile(absConfigPath);\n\nconst inputFiles = cliFiles.length\n ? cliFiles\n : findGraphqlTagReferences(\n makeAbsPath(config.crawl.root, path.dirname(absConfigPath)),\n );\n\n/** Step (2) */\n\nconst files = processFiles(inputFiles, (f) => {\n if (existsSync(f)) {\n return readFileSync(f, 'utf8');\n }\n if (existsSync(f + '.js')) {\n return {text: readFileSync(f + '.js', 'utf8'), resolvedPath: f + '.js'};\n }\n if (existsSync(f + '.ts')) {\n return {text: readFileSync(f + '.ts', 'utf8'), resolvedPath: f + '.ts'};\n }\n if (existsSync(f + '.tsx')) {\n return {\n text: readFileSync(f + '.tsx', 'utf8'),\n resolvedPath: f + '.tsx',\n };\n }\n throw new Error(`Unable to find ${f}`);\n});\n\nlet filesHadErrors = false;\nObject.keys(files).forEach((key) => {\n const file = files[key];\n if (file.errors.length) {\n filesHadErrors = true;\n console.error(`Errors in ${file.path}`);\n file.errors.forEach((error) => {\n console.error(` - ${error.message}`);\n });\n }\n});\n\nif (filesHadErrors) {\n console.error('Aborting');\n process.exit(1); // eslint-disable-line flowtype-errors/uncovered\n}\n\n/** Step (3) */\n\nconst {resolved, errors} = resolveDocuments(files);\nif (errors.length) {\n errors.forEach((error) => {\n console.error(`Resolution error ${error.message} in ${error.loc.path}`);\n });\n console.error('Aborting');\n process.exit(1); // eslint-disable-line flowtype-errors/uncovered\n}\n\nconsole.log(Object.keys(resolved).length, 'resolved queries');\n\n/** Step (4) */\n\nconst schemaCache: {[key: string]: [GraphQLSchema, Schema]} = {};\nconst getCachedSchemas = (schemaFilePath: string) => {\n if (!schemaCache[schemaFilePath]) {\n schemaCache[schemaFilePath] = getSchemas(\n makeAbsPath(schemaFilePath, path.dirname(absConfigPath)),\n );\n }\n\n return schemaCache[schemaFilePath];\n};\n\nlet validationFailures: number = 0;\nconst printedOperations: Array<string> = [];\n\nObject.keys(resolved).forEach((filePathAndLine) => {\n const {document, raw} = resolved[filePathAndLine];\n\n const hasNonFragments = document.definitions.some(\n ({kind}) => kind !== 'FragmentDefinition',\n );\n const rawSource: string = raw.literals[0];\n\n const generateConfig = findApplicableConfig(\n // strip off the trailing line number, e.g. `:23`\n filePathAndLine.split(':')[0],\n config.generate,\n );\n if (!generateConfig) {\n return; // no generate config matches, bail\n }\n\n // eslint-disable-next-line flowtype-errors/uncovered\n const withTypeNames: DocumentNode = addTypenameToDocument(document);\n const printed = print(withTypeNames);\n if (hasNonFragments && !printedOperations.includes(printed)) {\n printedOperations.push(printed);\n }\n\n const pragmaResult = processPragmas(\n generateConfig,\n config.crawl,\n rawSource,\n );\n if (!pragmaResult.generate) {\n return;\n }\n if (pragmaResult.strict != null) {\n generateConfig.strictNullability = pragmaResult.strict;\n }\n\n const [schemaForValidation, schemaForTypeGeneration] = getCachedSchemas(\n generateConfig.schemaFilePath,\n );\n\n if (hasNonFragments) {\n /* eslint-disable flowtype-errors/uncovered */\n const errors = validate(schemaForValidation, withTypeNames);\n /* eslint-disable flowtype-errors/uncovered */\n if (errors.length) {\n errors.forEach((error) => {\n console.error(\n `Schema validation found errors for ${raw.loc.path}!`,\n );\n console.error(printed);\n console.error(error);\n validationFailures++;\n });\n }\n /* eslint-enable flowtype-errors/uncovered */\n }\n\n try {\n generateTypeFiles(\n raw.loc.path,\n schemaForTypeGeneration,\n withTypeNames,\n generateConfig,\n );\n // eslint-disable-next-line flowtype-errors/uncovered\n } catch (err) {\n console.error(`Error while generating operation from ${raw.loc.path}`);\n console.error(printed);\n // eslint-disable-next-line flowtype-errors/uncovered\n console.error(err);\n validationFailures++;\n }\n});\n\nif (validationFailures) {\n console.error(\n `Encountered ${validationFailures} validation failures while printing types.`,\n );\n // eslint-disable-next-line flowtype-errors/uncovered\n process.exit(1);\n}\n\nif (config.crawl.dumpOperations) {\n const dumpOperations = config.crawl.dumpOperations;\n const parent = dirname(dumpOperations);\n mkdirSync(parent, {recursive: true});\n writeFileSync(\n dumpOperations,\n JSON.stringify(printedOperations.sort(), null, 2),\n );\n}\n"],"file":"run.js"}
|
|
@@ -15,6 +15,7 @@ var _convert = require("@khanacademy/flow-to-ts/dist/convert.bundle");
|
|
|
15
15
|
|
|
16
16
|
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
17
17
|
|
|
18
|
+
// eslint-disable-next-line flowtype-errors/uncovered
|
|
18
19
|
const indexPrelude = regenerateCommand => `// @flow
|
|
19
20
|
//
|
|
20
21
|
// AUTOGENERATED
|
|
@@ -138,7 +139,8 @@ const generateTypeFiles = (fileName, schema, document, options) => {
|
|
|
138
139
|
let fname = key;
|
|
139
140
|
|
|
140
141
|
if (options.typeScript) {
|
|
141
|
-
|
|
142
|
+
// eslint-disable-next-line flowtype-errors/uncovered
|
|
143
|
+
files[key] = (0, _convert.convert)(files[key]).replace(`variables: {}`, `variables: Record<never, never>`);
|
|
142
144
|
fname = key.replace(/\.js$/, '.ts');
|
|
143
145
|
}
|
|
144
146
|
|
|
@@ -4,6 +4,7 @@ import type {GenerateConfig, CrawlConfig, Schema} from './types';
|
|
|
4
4
|
import fs from 'fs';
|
|
5
5
|
import path from 'path';
|
|
6
6
|
import {documentToFlowTypes} from '.';
|
|
7
|
+
// eslint-disable-next-line flowtype-errors/uncovered
|
|
7
8
|
import {convert} from '@khanacademy/flow-to-ts/dist/convert.bundle';
|
|
8
9
|
|
|
9
10
|
export const indexPrelude = (regenerateCommand?: string): string => `// @flow
|
|
@@ -150,7 +151,11 @@ export const generateTypeFiles = (
|
|
|
150
151
|
Object.keys(files).forEach((key) => {
|
|
151
152
|
let fname = key;
|
|
152
153
|
if (options.typeScript) {
|
|
153
|
-
|
|
154
|
+
// eslint-disable-next-line flowtype-errors/uncovered
|
|
155
|
+
files[key] = convert(files[key]).replace(
|
|
156
|
+
`variables: {}`,
|
|
157
|
+
`variables: Record<never, never>`,
|
|
158
|
+
);
|
|
154
159
|
fname = key.replace(/\.js$/, '.ts');
|
|
155
160
|
}
|
|
156
161
|
fs.writeFileSync(fname, files[key]);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/generateTypeFiles.js"],"names":["indexPrelude","regenerateCommand","generateTypeFileContents","fileName","schema","document","options","generatedDir","indexContents","files","addToIndex","filePath","typeName","typeScript","replace","newLine","path","basename","indexOf","lines","split","map","line","includes","join","generated","forEach","name","code","isFragment","extraTypes","experimentalEnums","targetFileName","typeFileName","targetPath","fileContents","splitTypes","Object","keys","enumNames","length","getGeneratedDir","generatedDirectory","isAbsolute","relative","process","cwd","dirname","generateTypeFiles","indexFile","fs","existsSync","mkdirSync","recursive","writeFileSync","readFileSync","key","fname","processPragmas","generateConfig","crawlConfig","rawSource","ignorePragma","generate","autogen","loosePragma","autogenStrict","pragma","noPragmas","strict","strictNullability"],"mappings":";;;;;;;AAGA;;AACA;;AACA;;AACA;;;;AAEO,MAAMA,YAAY,GAAIC,iBAAD,IAAyC;AACrE;AACA;AACA;AACA;AACA,IAAIA,iBAAiB,GAAG,8BAA8BA,iBAAjC,GAAqD,EAAG;AAC7E;AACA;AACA,CARO;;;;AAUA,MAAMC,wBAAwB,GAAG,CACpCC,QADoC,EAEpCC,MAFoC,EAGpCC,QAHoC,EAIpCC,OAJoC,EAKpCC,YALoC,EAMpCC,aANoC,KAOsB;AAC1D,QAAMC,KAAK,GAAG,EAAd,CAD0D,CAG1D;;AACA,QAAMC,UAAU,GAAG,CAACC,QAAD,EAAWC,QAAX,KAAwB;AACvC,QAAIN,OAAO,CAACO,UAAZ,EAAwB;AACpB;AACAF,MAAAA,QAAQ,GAAGA,QAAQ,CAACG,OAAT,CAAiB,OAAjB,EAA0B,EAA1B,CAAX;AACH;;AACD,UAAMC,OAAO,GAAI,gBAAeH,QAAS,aAAYI,cAAKC,QAAL,CACjDN,QADiD,CAEnD,IAFF;;AA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types';\nimport fs from 'fs';\nimport path from 'path';\nimport {documentToFlowTypes} from '.';\nimport {convert} from '@khanacademy/flow-to-ts/dist/convert.bundle';\n\nexport const indexPrelude = (regenerateCommand?: string): string => `// @flow\n//\n// AUTOGENERATED\n// NOTE: New response types are added to this file automatically.\n// Outdated response types can be removed manually as they are deprecated.\n//${regenerateCommand ? ' To regenerate, run ' + regenerateCommand : ''}\n//\n\n`;\n\nexport const generateTypeFileContents = (\n fileName: string,\n schema: Schema,\n document: DocumentNode,\n options: GenerateConfig,\n generatedDir: string,\n indexContents: string,\n): {indexContents: string, files: {[key: string]: string}} => {\n const files = {};\n\n /// Write export for __generated__/index.js if it doesn't exist\n const addToIndex = (filePath, typeName) => {\n if (options.typeScript) {\n // Typescript doesn't like file extensions\n filePath = filePath.replace(/\\.js$/, '');\n }\n const newLine = `export type {${typeName}} from './${path.basename(\n filePath,\n )}';`;\n if (indexContents.indexOf('./' + path.basename(filePath)) === -1) {\n indexContents += newLine + '\\n';\n } else {\n const lines = indexContents.split('\\n').map((line) => {\n if (line.includes('./' + path.basename(filePath))) {\n return newLine;\n }\n return line;\n });\n indexContents = lines.join('\\n');\n }\n };\n\n const generated = documentToFlowTypes(document, schema, options);\n generated.forEach(\n ({name, typeName, code, isFragment, extraTypes, experimentalEnums}) => {\n // We write all generated files to a `__generated__` subdir to keep\n // things tidy.\n const targetFileName = options.typeFileName\n ? options.typeFileName.replace('[operationName]', name)\n : `${name}.js`;\n const targetPath = path.join(generatedDir, targetFileName);\n\n let fileContents =\n '// @' +\n `flow\\n// AUTOGENERATED -- DO NOT EDIT\\n` +\n `// Generated for operation '${name}' in file '../${path.basename(\n fileName,\n )}'\\n` +\n (options.regenerateCommand\n ? `// To regenerate, run '${options.regenerateCommand}'.\\n`\n : '') +\n code;\n if (options.splitTypes && !isFragment) {\n fileContents +=\n `\\nexport type ${name} = ${typeName}['response'];\\n` +\n `export type ${name}Variables = ${typeName}['variables'];\\n`;\n }\n Object.keys(extraTypes).forEach(\n (name) =>\n (fileContents += `\\n\\nexport type ${name} = ${extraTypes[name]};`),\n );\n const enumNames = Object.keys(experimentalEnums);\n if (options.experimentalEnums && enumNames.length) {\n // TODO(somewhatabstract, FEI-4172): Update to fixed eslint-plugin-flowtype\n // and remove this disable.\n fileContents += `\\n\\n/* eslint-disable no-undef */`;\n enumNames.forEach(\n (name) =>\n (fileContents += `\\nexport ${experimentalEnums[name]};\\n`),\n );\n fileContents += `/* eslint-enable no-undef */`;\n }\n\n addToIndex(targetPath, typeName);\n files[targetPath] =\n fileContents\n // Remove whitespace from the ends of lines; babel's generate sometimes\n // leaves them hanging around.\n .replace(/\\s+$/gm, '') + '\\n';\n },\n );\n\n return {files, indexContents};\n};\n\nconst getGeneratedDir = (fileName: string, options: GenerateConfig) => {\n const generatedDirectory = options.generatedDirectory ?? '__generated__';\n if (path.isAbsolute(generatedDirectory)) {\n // fileName is absolute here, so we make it relative to cwd\n // for more reasonable filenames. We convert leading ..'s\n // to `__` so this doesn't escape the output directory.\n return path.join(\n generatedDirectory,\n path\n .relative(process.cwd(), path.dirname(fileName))\n .replace(/\\.\\.\\//g, '__/'),\n );\n } else {\n return path.join(path.dirname(fileName), generatedDirectory);\n }\n};\n\nexport const generateTypeFiles = (\n fileName: string,\n schema: Schema,\n document: DocumentNode,\n options: GenerateConfig,\n) => {\n const generatedDir = getGeneratedDir(fileName, options);\n const indexFile = path.join(\n generatedDir,\n 'index' + (options.typeScript ? '.ts' : '.js'),\n );\n\n if (!fs.existsSync(generatedDir)) {\n fs.mkdirSync(generatedDir, {recursive: true});\n }\n if (!fs.existsSync(indexFile)) {\n fs.writeFileSync(indexFile, indexPrelude(options.regenerateCommand));\n }\n\n const {indexContents, files} = generateTypeFileContents(\n fileName,\n schema,\n document,\n options,\n generatedDir,\n fs.readFileSync(indexFile, 'utf8'),\n );\n\n fs.writeFileSync(indexFile, indexContents);\n Object.keys(files).forEach((key) => {\n let fname = key;\n if (options.typeScript) {\n files[key] = convert(files[key]);\n fname = key.replace(/\\.js$/, '.ts');\n }\n fs.writeFileSync(fname, files[key]);\n });\n\n fs.writeFileSync(indexFile, indexContents);\n};\n\nexport const processPragmas = (\n generateConfig: GenerateConfig,\n crawlConfig: CrawlConfig,\n rawSource: string,\n): {generate: boolean, strict?: boolean} => {\n if (\n crawlConfig.ignorePragma &&\n rawSource.includes(crawlConfig.ignorePragma)\n ) {\n return {generate: false};\n }\n\n const autogen = crawlConfig.loosePragma\n ? rawSource.includes(crawlConfig.loosePragma)\n : false;\n const autogenStrict = crawlConfig.pragma\n ? rawSource.includes(crawlConfig.pragma)\n : false;\n const noPragmas = !crawlConfig.loosePragma && !crawlConfig.pragma;\n\n if (autogen || autogenStrict || noPragmas) {\n return {\n generate: true,\n strict: noPragmas\n ? generateConfig.strictNullability\n : autogenStrict || !autogen,\n };\n } else {\n return {generate: false};\n }\n};\n"],"file":"generateTypeFiles.js"}
|
|
1
|
+
{"version":3,"sources":["../src/generateTypeFiles.js"],"names":["indexPrelude","regenerateCommand","generateTypeFileContents","fileName","schema","document","options","generatedDir","indexContents","files","addToIndex","filePath","typeName","typeScript","replace","newLine","path","basename","indexOf","lines","split","map","line","includes","join","generated","forEach","name","code","isFragment","extraTypes","experimentalEnums","targetFileName","typeFileName","targetPath","fileContents","splitTypes","Object","keys","enumNames","length","getGeneratedDir","generatedDirectory","isAbsolute","relative","process","cwd","dirname","generateTypeFiles","indexFile","fs","existsSync","mkdirSync","recursive","writeFileSync","readFileSync","key","fname","processPragmas","generateConfig","crawlConfig","rawSource","ignorePragma","generate","autogen","loosePragma","autogenStrict","pragma","noPragmas","strict","strictNullability"],"mappings":";;;;;;;AAGA;;AACA;;AACA;;AAEA;;;;AADA;AAGO,MAAMA,YAAY,GAAIC,iBAAD,IAAyC;AACrE;AACA;AACA;AACA;AACA,IAAIA,iBAAiB,GAAG,8BAA8BA,iBAAjC,GAAqD,EAAG;AAC7E;AACA;AACA,CARO;;;;AAUA,MAAMC,wBAAwB,GAAG,CACpCC,Q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MAA/B,CADgB,GAEhB,KAFN;AAGA,QAAMC,SAAS,GAAG,CAACR,WAAW,CAACK,WAAb,IAA4B,CAACL,WAAW,CAACO,MAA3D;;AAEA,MAAIH,OAAO,IAAIE,aAAX,IAA4BE,SAAhC,EAA2C;AACvC,WAAO;AACHL,MAAAA,QAAQ,EAAE,IADP;AAEHM,MAAAA,MAAM,EAAED,SAAS,GACXT,cAAc,CAACW,iBADJ,GAEXJ,aAAa,IAAI,CAACF;AAJrB,KAAP;AAMH,GAPD,MAOO;AACH,WAAO;AAACD,MAAAA,QAAQ,EAAE;AAAX,KAAP;AACH;AACJ,CA9BM","sourcesContent":["// @flow\nimport type {DocumentNode} from 'graphql';\nimport type {GenerateConfig, CrawlConfig, Schema} from './types';\nimport fs from 'fs';\nimport path from 'path';\nimport {documentToFlowTypes} from '.';\n// eslint-disable-next-line flowtype-errors/uncovered\nimport {convert} from '@khanacademy/flow-to-ts/dist/convert.bundle';\n\nexport const indexPrelude = (regenerateCommand?: string): string => `// @flow\n//\n// AUTOGENERATED\n// NOTE: New response types are added to this file automatically.\n// Outdated response types can be removed manually as they are deprecated.\n//${regenerateCommand ? ' To regenerate, run ' + regenerateCommand : ''}\n//\n\n`;\n\nexport const generateTypeFileContents = (\n fileName: string,\n schema: Schema,\n document: DocumentNode,\n options: GenerateConfig,\n generatedDir: string,\n indexContents: string,\n): {indexContents: string, files: {[key: string]: string}} => {\n const files = {};\n\n /// Write export for __generated__/index.js if it doesn't exist\n const addToIndex = (filePath, typeName) => {\n if (options.typeScript) {\n // Typescript doesn't like file extensions\n filePath = filePath.replace(/\\.js$/, '');\n }\n const newLine = `export type {${typeName}} from './${path.basename(\n filePath,\n )}';`;\n if (indexContents.indexOf('./' + path.basename(filePath)) === -1) {\n indexContents += newLine + '\\n';\n } else {\n const lines = indexContents.split('\\n').map((line) => {\n if (line.includes('./' + path.basename(filePath))) {\n return newLine;\n }\n return line;\n });\n indexContents = lines.join('\\n');\n }\n };\n\n const generated = documentToFlowTypes(document, schema, options);\n generated.forEach(\n ({name, typeName, code, isFragment, extraTypes, experimentalEnums}) => {\n // We write all generated files to a `__generated__` subdir to keep\n // things tidy.\n const targetFileName = options.typeFileName\n ? options.typeFileName.replace('[operationName]', name)\n : `${name}.js`;\n const targetPath = path.join(generatedDir, targetFileName);\n\n let fileContents =\n '// @' +\n `flow\\n// AUTOGENERATED -- DO NOT EDIT\\n` +\n `// Generated for operation '${name}' in file '../${path.basename(\n fileName,\n )}'\\n` +\n (options.regenerateCommand\n ? `// To regenerate, run '${options.regenerateCommand}'.\\n`\n : '') +\n code;\n if (options.splitTypes && !isFragment) {\n fileContents +=\n `\\nexport type ${name} = ${typeName}['response'];\\n` +\n `export type ${name}Variables = ${typeName}['variables'];\\n`;\n }\n Object.keys(extraTypes).forEach(\n (name) =>\n (fileContents += `\\n\\nexport type ${name} = ${extraTypes[name]};`),\n );\n const enumNames = Object.keys(experimentalEnums);\n if (options.experimentalEnums && enumNames.length) {\n // TODO(somewhatabstract, FEI-4172): Update to fixed eslint-plugin-flowtype\n // and remove this disable.\n fileContents += `\\n\\n/* eslint-disable no-undef */`;\n enumNames.forEach(\n (name) =>\n (fileContents += `\\nexport ${experimentalEnums[name]};\\n`),\n );\n fileContents += `/* eslint-enable no-undef */`;\n }\n\n addToIndex(targetPath, typeName);\n files[targetPath] =\n fileContents\n // Remove whitespace from the ends of lines; babel's generate sometimes\n // leaves them hanging around.\n .replace(/\\s+$/gm, '') + '\\n';\n },\n );\n\n return {files, indexContents};\n};\n\nconst getGeneratedDir = (fileName: string, options: GenerateConfig) => {\n const generatedDirectory = options.generatedDirectory ?? '__generated__';\n if (path.isAbsolute(generatedDirectory)) {\n // fileName is absolute here, so we make it relative to cwd\n // for more reasonable filenames. We convert leading ..'s\n // to `__` so this doesn't escape the output directory.\n return path.join(\n generatedDirectory,\n path\n .relative(process.cwd(), path.dirname(fileName))\n .replace(/\\.\\.\\//g, '__/'),\n );\n } else {\n return path.join(path.dirname(fileName), generatedDirectory);\n }\n};\n\nexport const generateTypeFiles = (\n fileName: string,\n schema: Schema,\n document: DocumentNode,\n options: GenerateConfig,\n) => {\n const generatedDir = getGeneratedDir(fileName, options);\n const indexFile = path.join(\n generatedDir,\n 'index' + (options.typeScript ? '.ts' : '.js'),\n );\n\n if (!fs.existsSync(generatedDir)) {\n fs.mkdirSync(generatedDir, {recursive: true});\n }\n if (!fs.existsSync(indexFile)) {\n fs.writeFileSync(indexFile, indexPrelude(options.regenerateCommand));\n }\n\n const {indexContents, files} = generateTypeFileContents(\n fileName,\n schema,\n document,\n options,\n generatedDir,\n fs.readFileSync(indexFile, 'utf8'),\n );\n\n fs.writeFileSync(indexFile, indexContents);\n Object.keys(files).forEach((key) => {\n let fname = key;\n if (options.typeScript) {\n // eslint-disable-next-line flowtype-errors/uncovered\n files[key] = convert(files[key]).replace(\n `variables: {}`,\n `variables: Record<never, never>`,\n );\n fname = key.replace(/\\.js$/, '.ts');\n }\n fs.writeFileSync(fname, files[key]);\n });\n\n fs.writeFileSync(indexFile, indexContents);\n};\n\nexport const processPragmas = (\n generateConfig: GenerateConfig,\n crawlConfig: CrawlConfig,\n rawSource: string,\n): {generate: boolean, strict?: boolean} => {\n if (\n crawlConfig.ignorePragma &&\n rawSource.includes(crawlConfig.ignorePragma)\n ) {\n return {generate: false};\n }\n\n const autogen = crawlConfig.loosePragma\n ? rawSource.includes(crawlConfig.loosePragma)\n : false;\n const autogenStrict = crawlConfig.pragma\n ? rawSource.includes(crawlConfig.pragma)\n : false;\n const noPragmas = !crawlConfig.loosePragma && !crawlConfig.pragma;\n\n if (autogen || autogenStrict || noPragmas) {\n return {\n generate: true,\n strict: noPragmas\n ? generateConfig.strictNullability\n : autogenStrict || !autogen,\n };\n } else {\n return {generate: false};\n }\n};\n"],"file":"generateTypeFiles.js"}
|
|
@@ -5,7 +5,9 @@ import {resolveDocuments} from '../resolve';
|
|
|
5
5
|
|
|
6
6
|
import {print} from 'graphql/language/printer';
|
|
7
7
|
|
|
8
|
-
const fixtureFiles: {
|
|
8
|
+
const fixtureFiles: {
|
|
9
|
+
[key: string]: string | {text: string, resolvedPath: string},
|
|
10
|
+
} = {
|
|
9
11
|
'/firstFile.js': `
|
|
10
12
|
// Note that you can import graphql-tag as
|
|
11
13
|
// something other than gql.
|
package/dist/parser/parse.js
CHANGED
|
@@ -57,14 +57,17 @@ const processFile = (filePath, contents) => {
|
|
|
57
57
|
locals: {},
|
|
58
58
|
errors: []
|
|
59
59
|
};
|
|
60
|
+
const resolved = typeof contents === 'string' ? filePath : contents.resolvedPath;
|
|
61
|
+
const text = typeof contents === 'string' ? contents : contents.text;
|
|
62
|
+
const plugins = resolved.match(/\.tsx?$/) ? ['typescript', filePath.endsWith('x') ? 'jsx' : null].filter(Boolean) : [['flow', {
|
|
63
|
+
enums: true
|
|
64
|
+
}], 'jsx'];
|
|
60
65
|
/* eslint-disable flowtype-errors/uncovered */
|
|
61
66
|
|
|
62
|
-
const ast = (0, _parser.parse)(
|
|
67
|
+
const ast = (0, _parser.parse)(text, {
|
|
63
68
|
sourceType: 'module',
|
|
64
69
|
allowImportExportEverywhere: true,
|
|
65
|
-
plugins:
|
|
66
|
-
enums: true
|
|
67
|
-
}], 'jsx']
|
|
70
|
+
plugins: plugins
|
|
68
71
|
});
|
|
69
72
|
/* eslint-enable flowtype-errors/uncovered */
|
|
70
73
|
|
|
@@ -121,7 +121,10 @@ const listExternalReferences = (file: FileResult): Array<string> => {
|
|
|
121
121
|
return Object.keys(paths);
|
|
122
122
|
};
|
|
123
123
|
|
|
124
|
-
export const processFile = (
|
|
124
|
+
export const processFile = (
|
|
125
|
+
filePath: string,
|
|
126
|
+
contents: string | {text: string, resolvedPath: string},
|
|
127
|
+
): FileResult => {
|
|
125
128
|
const dir = path.dirname(filePath);
|
|
126
129
|
const result: FileResult = {
|
|
127
130
|
path: filePath,
|
|
@@ -130,13 +133,17 @@ export const processFile = (filePath: string, contents: string): FileResult => {
|
|
|
130
133
|
locals: {},
|
|
131
134
|
errors: [],
|
|
132
135
|
};
|
|
136
|
+
const resolved =
|
|
137
|
+
typeof contents === 'string' ? filePath : contents.resolvedPath;
|
|
138
|
+
const text = typeof contents === 'string' ? contents : contents.text;
|
|
139
|
+
const plugins = resolved.match(/\.tsx?$/)
|
|
140
|
+
? ['typescript', filePath.endsWith('x') ? 'jsx' : null].filter(Boolean)
|
|
141
|
+
: [['flow', {enums: true}], 'jsx'];
|
|
133
142
|
/* eslint-disable flowtype-errors/uncovered */
|
|
134
|
-
const ast: BabelNodeFile = parse(
|
|
143
|
+
const ast: BabelNodeFile = parse(text, {
|
|
135
144
|
sourceType: 'module',
|
|
136
145
|
allowImportExportEverywhere: true,
|
|
137
|
-
plugins:
|
|
138
|
-
? ['typescript', 'jsx']
|
|
139
|
-
: [['flow', {enums: true}], 'jsx'],
|
|
146
|
+
plugins: plugins,
|
|
140
147
|
});
|
|
141
148
|
/* eslint-enable flowtype-errors/uncovered */
|
|
142
149
|
const gqlTagNames = [];
|
|
@@ -384,7 +391,9 @@ const getLocals = (
|
|
|
384
391
|
|
|
385
392
|
export const processFiles = (
|
|
386
393
|
filePaths: Array<string>,
|
|
387
|
-
getFileSource: (
|
|
394
|
+
getFileSource: (
|
|
395
|
+
path: string,
|
|
396
|
+
) => string | {text: string, resolvedPath: string},
|
|
388
397
|
): Files => {
|
|
389
398
|
const files: Files = {};
|
|
390
399
|
const toProcess = filePaths.slice();
|
package/dist/parser/parse.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/parser/parse.js"],"names":["listExternalReferences","file","paths","add","v","followImports","type","path","source","expressions","forEach","expr","Object","keys","exports","k","locals","operations","op","processFile","filePath","contents","dir","dirname","result","errors","ast","sourceType","allowImportExportEverywhere","plugins","match","enums","gqlTagNames","seenTemplates","program","body","toplevel","newLocals","getLocals","local","startsWith","name","push","importPath","value","resolve","join","specifiers","spec","exported","loc","start","end","line","processDeclarator","decl","isExported","id","init","tag","includes","tpl","processTemplate","document","declarations","declaration","visitTpl","node","getBinding","TaggedTemplateExpression","binding","scope","getTemplate","literals","quasi","quasis","map","q","cooked","message","found","filter","Boolean","myPath","importKind","imported","processFiles","filePaths","getFileSource","files","toProcess","slice","length","next","shift"],"mappings":";;;;;;;AAQA;;AACA;;AAEA;;;;AAHqC;AACG;;AAoExC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMA,sBAAsB,GAAIC,IAAD,IAAqC;AAChE,QAAMC,KAAK,GAAG,EAAd;;AACA,QAAMC,GAAG,GAAG,CAACC,CAAD,EAAuBC,aAAvB,KAAkD;AAC1D,QAAID,CAAC,CAACE,IAAF,KAAW,QAAf,EAAyB;AACrB,UAAID,aAAJ,EAAmB;AACfH,QAAAA,KAAK,CAACE,CAAC,CAACG,IAAH,CAAL,GAAgB,IAAhB;AACH;AACJ,KAJD,MAIO;AACHH,MAAAA,CAAC,CAACI,MAAF,CAASC,WAAT,CAAqBC,OAArB,CAA8BC,IAAD,IAAUR,GAAG,CAACQ,IAAD,EAAO,IAAP,CAA1C;AACH;AACJ,GARD;;AASAC,EAAAA,MAAM,CAACC,IAAP,CAAYZ,IAAI,CAACa,OAAjB,EAA0BJ,OAA1B,CAAmCK,CAAD,IAC9BZ,GAAG,CACCF,IAAI,CAACa,OAAL,CAAaC,CAAb,CADD,EAEC;AACA,MAHD,CADP;AAOAH,EAAAA,MAAM,CAACC,IAAP,CAAYZ,IAAI,CAACe,MAAjB,EAAyBN,OAAzB,CAAkCK,CAAD,IAC7BZ,GAAG,CACCF,IAAI,CAACe,MAAL,CAAYD,CAAZ,CADD,EAEC;AACA;AACA,OAJD,CADP;AAQAd,EAAAA,IAAI,CAACgB,UAAL,CAAgBP,OAAhB,CAAyBQ,EAAD,IACpBA,EAAE,CAACV,MAAH,CAAUC,WAAV,CAAsBC,OAAtB,CAA+BC,IAAD,IAC1BR,GAAG,CACCQ,IADD,EAEC;AACA,MAHD,CADP,CADJ;AASA,SAAOC,MAAM,CAACC,IAAP,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AACA,QAAMC,SAAS,GAAGH,SAAS,CAACI,KAAV,EAAlB;;AACA,SAAOD,SAAS,CAACE,MAAjB,EAAyB;AACrB,UAAMC,IAAI,GAAGH,SAAS,CAACI,KAAV,EAAb;;AACA,QAAIL,KAAK,CAACI,IAAD,CAAT,EAAiB;AACb;AACH;;AACD,UAAMrE,MAAM,GAAGL,WAAW,CAAC0E,IAAD,EAAOL,aAAa,CAACK,IAAD,CAApB,CAA1B;AACAJ,IAAAA,KAAK,CAACI,IAAD,CAAL,GAAcrE,MAAd;AACAxB,IAAAA,sBAAsB,CAACwB,MAAD,CAAtB,CAA+Bd,OAA/B,CAAwCH,IAAD,IAAU;AAC7C,UAAI,CAACkF,KAAK,CAAClF,IAAD,CAAN,IAAgB,CAACmF,SAAS,CAAC9B,QAAV,CAAmBrD,IAAnB,CAArB,EAA+C;AAC3CmF,QAAAA,SAAS,CAAChD,IAAV,CAAenC,IAAf;AACH;AACJ,KAJD;AAKH;;AACD,SAAOkF,KAAP;AACH,CApBM","sourcesContent":["// @flow\nimport type {\n BabelNodeImportDeclaration,\n BabelNodeVariableDeclarator,\n BabelNodeTaggedTemplateExpression,\n BabelNodeFile,\n} from '@babel/types';\n\nimport {parse} from '@babel/parser'; // eslint-disable-line flowtype-errors/uncovered\nimport traverse from '@babel/traverse'; // eslint-disable-line flowtype-errors/uncovered\n\nimport path from 'path';\n\n/**\n * This file is responsible for finding all gql`-annotated\n * template strings in a set of provided files, and for resolving\n * all fragment references to their eventual sources.\n *\n * Things that are supported:\n * - importing fragments from other files\n * - re-exporting fragments that were imported\n * - using locally-defined fragments, even if they're\n * not at the top level (scope is honored correctly)\n * - importing the gql tag as some other name\n * \t (e.g. 'import blah from \"graphql-tag\"')\n * - renaming fragments at the top level\n *\n * Things that are *not* supported:\n * - doing anything other than 'const x = gql`my template`'\n * \t e.g. const x = someCond ? one fragment literal : another fragment literal\n * or const x = someFragmentPreprocessor(fragment literal)\n * - importing the graphql tag fn from anywhere other than \"graphql-tag\"\n * - anything else fancy with the graphql tag fn, e.g. 'const blah = gql; blah`xyz`'\n * - including a fragment in an operation by anything other than a bare identifier,\n * e.g. 'const myQuery = gql`query xyz {...} ${cond ? someFrag : otherFrag}`.\n * - getting fragments from e.g. function arguments, or renaming non-toplevel fragments\n *\n * Things that could be supported, but are not yet:\n * - tracking whether a given graphql operation has already been wrapped\n * in `gqlOp<Type>()` or not (to inform an auto-wrapper of the future)\n */\n\nexport type Template = {|\n literals: Array<string>,\n expressions: Array<Document | Import>,\n loc: Loc,\n|};\nexport type Loc = {start: number, end: number, path: string, line: number};\n\nexport type Document = {|\n type: 'document',\n source: Template,\n|};\nexport type Import = {|\n type: 'import',\n name: string,\n path: string,\n loc: Loc,\n|};\n\nexport type Operation = {|\n source: Template,\n // TODO: Determine if an operation is already wrapped\n // in `gqlOp` so we can automatically wrap if needed.\n // needsWrapping: boolean,\n|};\n\nexport type FileResult = {|\n path: string,\n operations: Array<Operation>,\n exports: {[key: string]: Document | Import},\n locals: {[key: string]: Document | Import},\n errors: Array<{loc: Loc, message: string}>,\n|};\n\nexport type Files = {[path: string]: FileResult};\n\n/**\n * Finds all referenced imports that might possibly be relevant\n * graphql fragments.\n *\n * Importantly, any values that are re-exported are treated as\n * potentially relevant, and of course any values referenced\n * from a graphql template are treated as relevant.\n */\nconst listExternalReferences = (file: FileResult): Array<string> => {\n const paths = {};\n const add = (v: Document | Import, followImports: boolean) => {\n if (v.type === 'import') {\n if (followImports) {\n paths[v.path] = true;\n }\n } else {\n v.source.expressions.forEach((expr) => add(expr, true));\n }\n };\n Object.keys(file.exports).forEach((k) =>\n add(\n file.exports[k],\n // If we're re-exporting something, we need to follow that import.\n true,\n ),\n );\n Object.keys(file.locals).forEach((k) =>\n add(\n file.locals[k],\n // If we've imported something but haven't used it or exported it,\n // we don't need to follow the import.\n false,\n ),\n );\n file.operations.forEach((op) =>\n op.source.expressions.forEach((expr) =>\n add(\n expr,\n // Imports that are used in graphql expressions definitely need to be followed.\n true,\n ),\n ),\n );\n return Object.keys(paths);\n};\n\nexport const processFile = (filePath: string, contents: string): FileResult => {\n const dir = path.dirname(filePath);\n const result: FileResult = {\n path: filePath,\n operations: [],\n exports: {},\n locals: {},\n errors: [],\n };\n /* eslint-disable flowtype-errors/uncovered */\n const ast: BabelNodeFile = parse(contents, {\n sourceType: 'module',\n allowImportExportEverywhere: true,\n plugins: filePath.match(/\\.tsx?$/)\n ? ['typescript', 'jsx']\n : [['flow', {enums: true}], 'jsx'],\n });\n /* eslint-enable flowtype-errors/uncovered */\n const gqlTagNames = [];\n const seenTemplates: {[key: number]: Document | false} = {};\n\n ast.program.body.forEach((toplevel) => {\n if (toplevel.type === 'ImportDeclaration') {\n const newLocals = getLocals(dir, toplevel, filePath);\n if (newLocals) {\n Object.keys(newLocals).forEach((k) => {\n const local = newLocals[k];\n if (local.path.startsWith('/')) {\n result.locals[k] = local;\n }\n if (\n local.path === 'graphql-tag' &&\n local.name === 'default'\n ) {\n gqlTagNames.push(k);\n }\n });\n }\n }\n if (toplevel.type === 'ExportNamedDeclaration') {\n if (toplevel.source) {\n const source = toplevel.source;\n const importPath = source.value.startsWith('.')\n ? path.resolve(path.join(dir, source.value))\n : source.value;\n toplevel.specifiers?.forEach((spec) => {\n if (\n spec.type === 'ExportSpecifier' &&\n spec.exported.type === 'Identifier'\n ) {\n result.exports[spec.exported.name] = {\n type: 'import',\n name: spec.local.name,\n path: importPath,\n loc: {\n start: spec.start ?? -1,\n end: spec.end ?? -1,\n line: spec.loc?.start.line ?? -1,\n path: filePath,\n },\n };\n }\n });\n } else {\n toplevel.specifiers?.forEach((spec) => {\n if (spec.type === 'ExportSpecifier') {\n const local = result.locals[spec.local.name];\n if (local && spec.exported.type === 'Identifier') {\n result.exports[spec.exported.name] = local;\n }\n }\n });\n }\n }\n\n const processDeclarator = (\n decl: BabelNodeVariableDeclarator,\n isExported: boolean,\n ) => {\n if (decl.id.type !== 'Identifier' || !decl.init) {\n return;\n }\n const {init} = decl;\n const id = decl.id.name;\n if (\n init.type === 'TaggedTemplateExpression' &&\n init.tag.type === 'Identifier'\n ) {\n if (gqlTagNames.includes(init.tag.name)) {\n const tpl = processTemplate(init, result);\n if (tpl) {\n const document = (result.locals[id] = {\n type: 'document',\n source: tpl,\n });\n seenTemplates[init.start ?? -1] = document;\n if (isExported) {\n result.exports[id] = document;\n }\n } else {\n seenTemplates[init.start ?? -1] = false;\n }\n }\n }\n if (init.type === 'Identifier' && result.locals[init.name]) {\n result.locals[id] = result.locals[init.name];\n if (isExported) {\n result.exports[id] = result.locals[init.name];\n }\n }\n };\n\n if (toplevel.type === 'VariableDeclaration') {\n toplevel.declarations.forEach((decl) => {\n processDeclarator(decl, false);\n });\n }\n\n if (\n toplevel.type === 'ExportNamedDeclaration' &&\n toplevel.declaration?.type === 'VariableDeclaration'\n ) {\n toplevel.declaration.declarations.forEach((decl) => {\n processDeclarator(decl, true);\n });\n }\n });\n\n const visitTpl = (\n node: BabelNodeTaggedTemplateExpression,\n getBinding: (name: string) => Document | null,\n ) => {\n if (seenTemplates[node.start ?? -1] != null) {\n return;\n }\n if (\n node.tag.type !== 'Identifier' ||\n !gqlTagNames.includes(node.tag.name)\n ) {\n return;\n }\n const tpl = processTemplate(node, result, getBinding);\n if (tpl) {\n seenTemplates[node.start ?? -1] = {type: 'document', source: tpl};\n result.operations.push({\n source: tpl,\n });\n } else {\n seenTemplates[node.start ?? -1] = false;\n }\n };\n\n /* eslint-disable flowtype-errors/uncovered */\n traverse(ast, {\n TaggedTemplateExpression(path) {\n visitTpl(path.node, (name) => {\n const binding = path.scope.getBinding(name);\n const start = binding.path.node.init\n ? binding.path.node.init.start\n : null;\n if (start && seenTemplates[start]) {\n return seenTemplates[start];\n }\n return null;\n });\n },\n });\n /* eslint-enable flowtype-errors/uncovered */\n\n return result;\n};\n\nconst processTemplate = (\n tpl: BabelNodeTaggedTemplateExpression,\n result: FileResult,\n getTemplate?: (name: string) => Document | null,\n // getBinding?: (name: string) => Binding,\n // seenTemplates,\n): ?Template => {\n // 'cooked' is the string as runtime javascript will see it.\n const literals = tpl.quasi.quasis.map((q) => q.value.cooked || '');\n const expressions = tpl.quasi.expressions.map(\n (expr): null | Document | Import => {\n const loc: Loc = {\n start: expr.start ?? -1,\n end: expr.end ?? -1,\n line: expr.loc?.start.line ?? -1,\n path: result.path,\n };\n if (expr.type !== 'Identifier') {\n result.errors.push({\n loc,\n message: `Template literal interpolation must be an identifier`,\n });\n return null;\n }\n if (!result.locals[expr.name]) {\n if (getTemplate) {\n const found = getTemplate(expr.name);\n return found;\n }\n result.errors.push({\n loc,\n message: `Unable to resolve ${expr.name}`,\n });\n return null;\n }\n return result.locals[expr.name];\n },\n );\n if (expressions.includes(null)) {\n // bail, stop processing.\n return;\n }\n return {\n literals,\n expressions: expressions.filter(Boolean),\n loc: {\n line: tpl.loc?.start.line ?? -1,\n start: tpl.start ?? -1,\n end: tpl.end ?? -1,\n path: result.path,\n },\n };\n};\n\nconst getLocals = (\n dir,\n toplevel: BabelNodeImportDeclaration,\n myPath: string,\n): ?{[key: string]: Import} => {\n if (toplevel.importKind === 'type') {\n return null;\n }\n const importPath = toplevel.source.value.startsWith('.')\n ? path.resolve(path.join(dir, toplevel.source.value))\n : toplevel.source.value;\n const locals = {};\n toplevel.specifiers.forEach((spec) => {\n if (spec.type === 'ImportDefaultSpecifier') {\n locals[spec.local.name] = {\n type: 'import',\n name: 'default',\n path: importPath,\n loc: {start: spec.start, end: spec.end, path: myPath},\n };\n } else if (spec.type === 'ImportSpecifier') {\n locals[spec.local.name] = {\n type: 'import',\n name:\n spec.imported.type === 'Identifier'\n ? spec.imported.name\n : spec.imported.value,\n path: importPath,\n loc: {start: spec.start, end: spec.end, path: myPath},\n };\n }\n });\n return locals;\n};\n\nexport const processFiles = (\n filePaths: Array<string>,\n getFileSource: (path: string) => string,\n): Files => {\n const files: Files = {};\n const toProcess = filePaths.slice();\n while (toProcess.length) {\n const next = toProcess.shift();\n if (files[next]) {\n continue;\n }\n const result = processFile(next, getFileSource(next));\n files[next] = result;\n listExternalReferences(result).forEach((path) => {\n if (!files[path] && !toProcess.includes(path)) {\n toProcess.push(path);\n }\n });\n }\n return files;\n};\n"],"file":"parse.js"}
|
|
1
|
+
{"version":3,"sources":["../../src/parser/parse.js"],"names":["listExternalReferences","file","paths","add","v","followImports","type","path","source","expressions","forEach","expr","Object","keys","exports","k","locals","operations","op","processFile","filePath","contents","dir","dirname","result","errors","resolved","resolvedPath","text","plugins","match","endsWith","filter","Boolean","enums","ast","sourceType","allowImportExportEverywhere","gqlTagNames","seenTemplates","program","body","toplevel","newLocals","getLocals","local","startsWith","name","push","importPath","value","resolve","join","specifiers","spec","exported","loc","start","end","line","processDeclarator","decl","isExported","id","init","tag","includes","tpl","processTemplate","document","declarations","declaration","visitTpl","node","getBinding","TaggedTemplateExpression","binding","scope","getTemplate","literals","quasi","quasis","map","q","cooked","message","found","myPath","importKind","imported","processFiles","filePaths","getFileSource","files","toProcess","slice","length","next","shift"],"mappings":";;;;;;;AAQA;;AACA;;AAEA;;;;AAHqC;AACG;;AAoExC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMA,sBAAsB,GAAIC,IAAD,IAAqC;AAChE,QAAMC,KAAK,GAAG,EAAd;;AACA,QAAMC,GAAG,GAAG,CAACC,CAAD,EAAuBC,aAAvB,KAAkD;AAC1D,QAAID,CAAC,CAACE,IAAF,KAAW,QAAf,EAAyB;AACrB,UAAID,aAAJ,EAAmB;AACfH,QAAAA,KAAK,CAACE,CAAC,CAACG,IAAH,CAAL,GAAgB,IAAhB;AACH;AACJ,KAJD,MAIO;AACHH,MAAAA,CAAC,CAACI,MAAF,CAASC,WAAT,CAAqBC,OAArB,CAA8BC,IAAD,IAAUR,GAAG,CAACQ,IAAD,EAAO,IAAP,CAA1C;AACH;AACJ,GARD;;AASAC,EAAAA,MAAM,CAACC,IAAP,CAAYZ,IAAI,CAACa,OAAjB,EAA0BJ,OAA1B,CAAmCK,CAAD,IAC9BZ,GA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AgB,CAACuF,SAAS,CAAC5B,QAAV,CAAmB3D,IAAnB,CAArB,EAA+C;AAC3CuF,QAAAA,SAAS,CAAC9C,IAAV,CAAezC,IAAf;AACH;AACJ,KAJD;AAKH;;AACD,SAAOsF,KAAP;AACH,CAtBM","sourcesContent":["// @flow\nimport type {\n BabelNodeImportDeclaration,\n BabelNodeVariableDeclarator,\n BabelNodeTaggedTemplateExpression,\n BabelNodeFile,\n} from '@babel/types';\n\nimport {parse} from '@babel/parser'; // eslint-disable-line flowtype-errors/uncovered\nimport traverse from '@babel/traverse'; // eslint-disable-line flowtype-errors/uncovered\n\nimport path from 'path';\n\n/**\n * This file is responsible for finding all gql`-annotated\n * template strings in a set of provided files, and for resolving\n * all fragment references to their eventual sources.\n *\n * Things that are supported:\n * - importing fragments from other files\n * - re-exporting fragments that were imported\n * - using locally-defined fragments, even if they're\n * not at the top level (scope is honored correctly)\n * - importing the gql tag as some other name\n * \t (e.g. 'import blah from \"graphql-tag\"')\n * - renaming fragments at the top level\n *\n * Things that are *not* supported:\n * - doing anything other than 'const x = gql`my template`'\n * \t e.g. const x = someCond ? one fragment literal : another fragment literal\n * or const x = someFragmentPreprocessor(fragment literal)\n * - importing the graphql tag fn from anywhere other than \"graphql-tag\"\n * - anything else fancy with the graphql tag fn, e.g. 'const blah = gql; blah`xyz`'\n * - including a fragment in an operation by anything other than a bare identifier,\n * e.g. 'const myQuery = gql`query xyz {...} ${cond ? someFrag : otherFrag}`.\n * - getting fragments from e.g. function arguments, or renaming non-toplevel fragments\n *\n * Things that could be supported, but are not yet:\n * - tracking whether a given graphql operation has already been wrapped\n * in `gqlOp<Type>()` or not (to inform an auto-wrapper of the future)\n */\n\nexport type Template = {|\n literals: Array<string>,\n expressions: Array<Document | Import>,\n loc: Loc,\n|};\nexport type Loc = {start: number, end: number, path: string, line: number};\n\nexport type Document = {|\n type: 'document',\n source: Template,\n|};\nexport type Import = {|\n type: 'import',\n name: string,\n path: string,\n loc: Loc,\n|};\n\nexport type Operation = {|\n source: Template,\n // TODO: Determine if an operation is already wrapped\n // in `gqlOp` so we can automatically wrap if needed.\n // needsWrapping: boolean,\n|};\n\nexport type FileResult = {|\n path: string,\n operations: Array<Operation>,\n exports: {[key: string]: Document | Import},\n locals: {[key: string]: Document | Import},\n errors: Array<{loc: Loc, message: string}>,\n|};\n\nexport type Files = {[path: string]: FileResult};\n\n/**\n * Finds all referenced imports that might possibly be relevant\n * graphql fragments.\n *\n * Importantly, any values that are re-exported are treated as\n * potentially relevant, and of course any values referenced\n * from a graphql template are treated as relevant.\n */\nconst listExternalReferences = (file: FileResult): Array<string> => {\n const paths = {};\n const add = (v: Document | Import, followImports: boolean) => {\n if (v.type === 'import') {\n if (followImports) {\n paths[v.path] = true;\n }\n } else {\n v.source.expressions.forEach((expr) => add(expr, true));\n }\n };\n Object.keys(file.exports).forEach((k) =>\n add(\n file.exports[k],\n // If we're re-exporting something, we need to follow that import.\n true,\n ),\n );\n Object.keys(file.locals).forEach((k) =>\n add(\n file.locals[k],\n // If we've imported something but haven't used it or exported it,\n // we don't need to follow the import.\n false,\n ),\n );\n file.operations.forEach((op) =>\n op.source.expressions.forEach((expr) =>\n add(\n expr,\n // Imports that are used in graphql expressions definitely need to be followed.\n true,\n ),\n ),\n );\n return Object.keys(paths);\n};\n\nexport const processFile = (\n filePath: string,\n contents: string | {text: string, resolvedPath: string},\n): FileResult => {\n const dir = path.dirname(filePath);\n const result: FileResult = {\n path: filePath,\n operations: [],\n exports: {},\n locals: {},\n errors: [],\n };\n const resolved =\n typeof contents === 'string' ? filePath : contents.resolvedPath;\n const text = typeof contents === 'string' ? contents : contents.text;\n const plugins = resolved.match(/\\.tsx?$/)\n ? ['typescript', filePath.endsWith('x') ? 'jsx' : null].filter(Boolean)\n : [['flow', {enums: true}], 'jsx'];\n /* eslint-disable flowtype-errors/uncovered */\n const ast: BabelNodeFile = parse(text, {\n sourceType: 'module',\n allowImportExportEverywhere: true,\n plugins: plugins,\n });\n /* eslint-enable flowtype-errors/uncovered */\n const gqlTagNames = [];\n const seenTemplates: {[key: number]: Document | false} = {};\n\n ast.program.body.forEach((toplevel) => {\n if (toplevel.type === 'ImportDeclaration') {\n const newLocals = getLocals(dir, toplevel, filePath);\n if (newLocals) {\n Object.keys(newLocals).forEach((k) => {\n const local = newLocals[k];\n if (local.path.startsWith('/')) {\n result.locals[k] = local;\n }\n if (\n local.path === 'graphql-tag' &&\n local.name === 'default'\n ) {\n gqlTagNames.push(k);\n }\n });\n }\n }\n if (toplevel.type === 'ExportNamedDeclaration') {\n if (toplevel.source) {\n const source = toplevel.source;\n const importPath = source.value.startsWith('.')\n ? path.resolve(path.join(dir, source.value))\n : source.value;\n toplevel.specifiers?.forEach((spec) => {\n if (\n spec.type === 'ExportSpecifier' &&\n spec.exported.type === 'Identifier'\n ) {\n result.exports[spec.exported.name] = {\n type: 'import',\n name: spec.local.name,\n path: importPath,\n loc: {\n start: spec.start ?? -1,\n end: spec.end ?? -1,\n line: spec.loc?.start.line ?? -1,\n path: filePath,\n },\n };\n }\n });\n } else {\n toplevel.specifiers?.forEach((spec) => {\n if (spec.type === 'ExportSpecifier') {\n const local = result.locals[spec.local.name];\n if (local && spec.exported.type === 'Identifier') {\n result.exports[spec.exported.name] = local;\n }\n }\n });\n }\n }\n\n const processDeclarator = (\n decl: BabelNodeVariableDeclarator,\n isExported: boolean,\n ) => {\n if (decl.id.type !== 'Identifier' || !decl.init) {\n return;\n }\n const {init} = decl;\n const id = decl.id.name;\n if (\n init.type === 'TaggedTemplateExpression' &&\n init.tag.type === 'Identifier'\n ) {\n if (gqlTagNames.includes(init.tag.name)) {\n const tpl = processTemplate(init, result);\n if (tpl) {\n const document = (result.locals[id] = {\n type: 'document',\n source: tpl,\n });\n seenTemplates[init.start ?? -1] = document;\n if (isExported) {\n result.exports[id] = document;\n }\n } else {\n seenTemplates[init.start ?? -1] = false;\n }\n }\n }\n if (init.type === 'Identifier' && result.locals[init.name]) {\n result.locals[id] = result.locals[init.name];\n if (isExported) {\n result.exports[id] = result.locals[init.name];\n }\n }\n };\n\n if (toplevel.type === 'VariableDeclaration') {\n toplevel.declarations.forEach((decl) => {\n processDeclarator(decl, false);\n });\n }\n\n if (\n toplevel.type === 'ExportNamedDeclaration' &&\n toplevel.declaration?.type === 'VariableDeclaration'\n ) {\n toplevel.declaration.declarations.forEach((decl) => {\n processDeclarator(decl, true);\n });\n }\n });\n\n const visitTpl = (\n node: BabelNodeTaggedTemplateExpression,\n getBinding: (name: string) => Document | null,\n ) => {\n if (seenTemplates[node.start ?? -1] != null) {\n return;\n }\n if (\n node.tag.type !== 'Identifier' ||\n !gqlTagNames.includes(node.tag.name)\n ) {\n return;\n }\n const tpl = processTemplate(node, result, getBinding);\n if (tpl) {\n seenTemplates[node.start ?? -1] = {type: 'document', source: tpl};\n result.operations.push({\n source: tpl,\n });\n } else {\n seenTemplates[node.start ?? -1] = false;\n }\n };\n\n /* eslint-disable flowtype-errors/uncovered */\n traverse(ast, {\n TaggedTemplateExpression(path) {\n visitTpl(path.node, (name) => {\n const binding = path.scope.getBinding(name);\n const start = binding.path.node.init\n ? binding.path.node.init.start\n : null;\n if (start && seenTemplates[start]) {\n return seenTemplates[start];\n }\n return null;\n });\n },\n });\n /* eslint-enable flowtype-errors/uncovered */\n\n return result;\n};\n\nconst processTemplate = (\n tpl: BabelNodeTaggedTemplateExpression,\n result: FileResult,\n getTemplate?: (name: string) => Document | null,\n // getBinding?: (name: string) => Binding,\n // seenTemplates,\n): ?Template => {\n // 'cooked' is the string as runtime javascript will see it.\n const literals = tpl.quasi.quasis.map((q) => q.value.cooked || '');\n const expressions = tpl.quasi.expressions.map(\n (expr): null | Document | Import => {\n const loc: Loc = {\n start: expr.start ?? -1,\n end: expr.end ?? -1,\n line: expr.loc?.start.line ?? -1,\n path: result.path,\n };\n if (expr.type !== 'Identifier') {\n result.errors.push({\n loc,\n message: `Template literal interpolation must be an identifier`,\n });\n return null;\n }\n if (!result.locals[expr.name]) {\n if (getTemplate) {\n const found = getTemplate(expr.name);\n return found;\n }\n result.errors.push({\n loc,\n message: `Unable to resolve ${expr.name}`,\n });\n return null;\n }\n return result.locals[expr.name];\n },\n );\n if (expressions.includes(null)) {\n // bail, stop processing.\n return;\n }\n return {\n literals,\n expressions: expressions.filter(Boolean),\n loc: {\n line: tpl.loc?.start.line ?? -1,\n start: tpl.start ?? -1,\n end: tpl.end ?? -1,\n path: result.path,\n },\n };\n};\n\nconst getLocals = (\n dir,\n toplevel: BabelNodeImportDeclaration,\n myPath: string,\n): ?{[key: string]: Import} => {\n if (toplevel.importKind === 'type') {\n return null;\n }\n const importPath = toplevel.source.value.startsWith('.')\n ? path.resolve(path.join(dir, toplevel.source.value))\n : toplevel.source.value;\n const locals = {};\n toplevel.specifiers.forEach((spec) => {\n if (spec.type === 'ImportDefaultSpecifier') {\n locals[spec.local.name] = {\n type: 'import',\n name: 'default',\n path: importPath,\n loc: {start: spec.start, end: spec.end, path: myPath},\n };\n } else if (spec.type === 'ImportSpecifier') {\n locals[spec.local.name] = {\n type: 'import',\n name:\n spec.imported.type === 'Identifier'\n ? spec.imported.name\n : spec.imported.value,\n path: importPath,\n loc: {start: spec.start, end: spec.end, path: myPath},\n };\n }\n });\n return locals;\n};\n\nexport const processFiles = (\n filePaths: Array<string>,\n getFileSource: (\n path: string,\n ) => string | {text: string, resolvedPath: string},\n): Files => {\n const files: Files = {};\n const toProcess = filePaths.slice();\n while (toProcess.length) {\n const next = toProcess.shift();\n if (files[next]) {\n continue;\n }\n const result = processFile(next, getFileSource(next));\n files[next] = result;\n listExternalReferences(result).forEach((path) => {\n if (!files[path] && !toProcess.includes(path)) {\n toProcess.push(path);\n }\n });\n }\n return files;\n};\n"],"file":"parse.js"}
|
package/package.json
CHANGED
package/src/cli/config.js
CHANGED
|
@@ -28,10 +28,9 @@ export const validateOrThrow = (value: mixed, jsonSchema: mixed) => {
|
|
|
28
28
|
};
|
|
29
29
|
|
|
30
30
|
export const loadConfigFile = (configFile: string): Config => {
|
|
31
|
-
// $FlowIgnore
|
|
32
|
-
const data: Config = require(configFile);
|
|
33
|
-
// eslint-disable-
|
|
34
|
-
validateOrThrow(data, configSchema);
|
|
31
|
+
// $FlowIgnore
|
|
32
|
+
const data: Config = require(configFile); // eslint-disable-line flowtype-errors/uncovered
|
|
33
|
+
validateOrThrow(data, configSchema); // eslint-disable-line flowtype-errors/uncovered
|
|
35
34
|
return data;
|
|
36
35
|
};
|
|
37
36
|
|
package/src/cli/run.js
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// @flow
|
|
3
3
|
/* eslint-disable no-console */
|
|
4
|
+
import type {Schema} from '../types';
|
|
5
|
+
import type {GraphQLSchema} from 'graphql/type/schema';
|
|
6
|
+
|
|
4
7
|
import {generateTypeFiles, processPragmas} from '../generateTypeFiles';
|
|
5
8
|
import {processFiles} from '../parser/parse';
|
|
6
9
|
import {resolveDocuments} from '../parser/resolve';
|
|
@@ -15,7 +18,6 @@ import {print} from 'graphql/language/printer';
|
|
|
15
18
|
import {validate} from 'graphql/validation';
|
|
16
19
|
import path from 'path';
|
|
17
20
|
import {dirname} from 'path';
|
|
18
|
-
import type {GenerateConfig} from '../types';
|
|
19
21
|
|
|
20
22
|
/**
|
|
21
23
|
* This CLI tool executes the following steps:
|
|
@@ -81,7 +83,16 @@ const files = processFiles(inputFiles, (f) => {
|
|
|
81
83
|
return readFileSync(f, 'utf8');
|
|
82
84
|
}
|
|
83
85
|
if (existsSync(f + '.js')) {
|
|
84
|
-
return readFileSync(f + '.js', 'utf8');
|
|
86
|
+
return {text: readFileSync(f + '.js', 'utf8'), resolvedPath: f + '.js'};
|
|
87
|
+
}
|
|
88
|
+
if (existsSync(f + '.ts')) {
|
|
89
|
+
return {text: readFileSync(f + '.ts', 'utf8'), resolvedPath: f + '.ts'};
|
|
90
|
+
}
|
|
91
|
+
if (existsSync(f + '.tsx')) {
|
|
92
|
+
return {
|
|
93
|
+
text: readFileSync(f + '.tsx', 'utf8'),
|
|
94
|
+
resolvedPath: f + '.tsx',
|
|
95
|
+
};
|
|
85
96
|
}
|
|
86
97
|
throw new Error(`Unable to find ${f}`);
|
|
87
98
|
});
|
|
@@ -118,7 +129,7 @@ console.log(Object.keys(resolved).length, 'resolved queries');
|
|
|
118
129
|
|
|
119
130
|
/** Step (4) */
|
|
120
131
|
|
|
121
|
-
const schemaCache = {};
|
|
132
|
+
const schemaCache: {[key: string]: [GraphQLSchema, Schema]} = {};
|
|
122
133
|
const getCachedSchemas = (schemaFilePath: string) => {
|
|
123
134
|
if (!schemaCache[schemaFilePath]) {
|
|
124
135
|
schemaCache[schemaFilePath] = getSchemas(
|
package/src/generateTypeFiles.js
CHANGED
|
@@ -4,6 +4,7 @@ import type {GenerateConfig, CrawlConfig, Schema} from './types';
|
|
|
4
4
|
import fs from 'fs';
|
|
5
5
|
import path from 'path';
|
|
6
6
|
import {documentToFlowTypes} from '.';
|
|
7
|
+
// eslint-disable-next-line flowtype-errors/uncovered
|
|
7
8
|
import {convert} from '@khanacademy/flow-to-ts/dist/convert.bundle';
|
|
8
9
|
|
|
9
10
|
export const indexPrelude = (regenerateCommand?: string): string => `// @flow
|
|
@@ -150,7 +151,11 @@ export const generateTypeFiles = (
|
|
|
150
151
|
Object.keys(files).forEach((key) => {
|
|
151
152
|
let fname = key;
|
|
152
153
|
if (options.typeScript) {
|
|
153
|
-
|
|
154
|
+
// eslint-disable-next-line flowtype-errors/uncovered
|
|
155
|
+
files[key] = convert(files[key]).replace(
|
|
156
|
+
`variables: {}`,
|
|
157
|
+
`variables: Record<never, never>`,
|
|
158
|
+
);
|
|
154
159
|
fname = key.replace(/\.js$/, '.ts');
|
|
155
160
|
}
|
|
156
161
|
fs.writeFileSync(fname, files[key]);
|
|
@@ -5,7 +5,9 @@ import {resolveDocuments} from '../resolve';
|
|
|
5
5
|
|
|
6
6
|
import {print} from 'graphql/language/printer';
|
|
7
7
|
|
|
8
|
-
const fixtureFiles: {
|
|
8
|
+
const fixtureFiles: {
|
|
9
|
+
[key: string]: string | {text: string, resolvedPath: string},
|
|
10
|
+
} = {
|
|
9
11
|
'/firstFile.js': `
|
|
10
12
|
// Note that you can import graphql-tag as
|
|
11
13
|
// something other than gql.
|
package/src/parser/parse.js
CHANGED
|
@@ -121,7 +121,10 @@ const listExternalReferences = (file: FileResult): Array<string> => {
|
|
|
121
121
|
return Object.keys(paths);
|
|
122
122
|
};
|
|
123
123
|
|
|
124
|
-
export const processFile = (
|
|
124
|
+
export const processFile = (
|
|
125
|
+
filePath: string,
|
|
126
|
+
contents: string | {text: string, resolvedPath: string},
|
|
127
|
+
): FileResult => {
|
|
125
128
|
const dir = path.dirname(filePath);
|
|
126
129
|
const result: FileResult = {
|
|
127
130
|
path: filePath,
|
|
@@ -130,13 +133,17 @@ export const processFile = (filePath: string, contents: string): FileResult => {
|
|
|
130
133
|
locals: {},
|
|
131
134
|
errors: [],
|
|
132
135
|
};
|
|
136
|
+
const resolved =
|
|
137
|
+
typeof contents === 'string' ? filePath : contents.resolvedPath;
|
|
138
|
+
const text = typeof contents === 'string' ? contents : contents.text;
|
|
139
|
+
const plugins = resolved.match(/\.tsx?$/)
|
|
140
|
+
? ['typescript', filePath.endsWith('x') ? 'jsx' : null].filter(Boolean)
|
|
141
|
+
: [['flow', {enums: true}], 'jsx'];
|
|
133
142
|
/* eslint-disable flowtype-errors/uncovered */
|
|
134
|
-
const ast: BabelNodeFile = parse(
|
|
143
|
+
const ast: BabelNodeFile = parse(text, {
|
|
135
144
|
sourceType: 'module',
|
|
136
145
|
allowImportExportEverywhere: true,
|
|
137
|
-
plugins:
|
|
138
|
-
? ['typescript', 'jsx']
|
|
139
|
-
: [['flow', {enums: true}], 'jsx'],
|
|
146
|
+
plugins: plugins,
|
|
140
147
|
});
|
|
141
148
|
/* eslint-enable flowtype-errors/uncovered */
|
|
142
149
|
const gqlTagNames = [];
|
|
@@ -384,7 +391,9 @@ const getLocals = (
|
|
|
384
391
|
|
|
385
392
|
export const processFiles = (
|
|
386
393
|
filePaths: Array<string>,
|
|
387
|
-
getFileSource: (
|
|
394
|
+
getFileSource: (
|
|
395
|
+
path: string,
|
|
396
|
+
) => string | {text: string, resolvedPath: string},
|
|
388
397
|
): Files => {
|
|
389
398
|
const files: Files = {};
|
|
390
399
|
const toProcess = filePaths.slice();
|