@khanacademy/graphql-flow 0.2.2 → 0.2.3
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/CHANGELOG.md +6 -0
- package/Readme.md +4 -0
- package/dist/cli/config.js +1 -1
- package/dist/cli/config.js.flow +1 -0
- package/dist/cli/config.js.map +1 -1
- package/dist/cli/run.js +11 -1
- package/dist/cli/run.js.flow +10 -2
- package/dist/cli/run.js.map +1 -1
- package/dist/generateTypeFiles.js +3 -2
- package/dist/generateTypeFiles.js.flow +5 -1
- package/dist/generateTypeFiles.js.map +1 -1
- package/dist/types.js.flow +1 -0
- package/package.json +1 -1
- package/src/__test__/generateTypeFileContents.test.js +42 -0
- package/src/cli/config.js +1 -0
- package/src/cli/run.js +10 -2
- package/src/generateTypeFiles.js +5 -1
- package/src/types.js +1 -0
package/CHANGELOG.md
CHANGED
package/Readme.md
CHANGED
|
@@ -70,6 +70,10 @@ type Options = {
|
|
|
70
70
|
// Names are generated by concatenating the attribute names
|
|
71
71
|
// of the path to the object type, separated by underscores.
|
|
72
72
|
exportAllObjectTypes?: boolean,
|
|
73
|
+
|
|
74
|
+
// A template for the name of generated files
|
|
75
|
+
// default: [operationName].js
|
|
76
|
+
typeFileName?: string,
|
|
73
77
|
}
|
|
74
78
|
```
|
|
75
79
|
|
package/dist/cli/config.js
CHANGED
|
@@ -28,7 +28,7 @@ const loadConfigFile = configFile => {
|
|
|
28
28
|
});
|
|
29
29
|
|
|
30
30
|
if (data.options) {
|
|
31
|
-
const externalOptionsKeys = ['pragma', 'loosePragma', 'ignorePragma', 'scalars', 'strictNullability', 'regenerateCommand', 'readOnlyArray', 'splitTypes', 'generatedDirectory', 'exportAllObjectTypes'];
|
|
31
|
+
const externalOptionsKeys = ['pragma', 'loosePragma', 'ignorePragma', 'scalars', 'strictNullability', 'regenerateCommand', 'readOnlyArray', 'splitTypes', 'generatedDirectory', 'exportAllObjectTypes', 'typeFileName'];
|
|
32
32
|
Object.keys(data.options).forEach(k => {
|
|
33
33
|
if (!externalOptionsKeys.includes(k)) {
|
|
34
34
|
throw new Error(`Invalid option in config file ${configFile}: ${k}. Allowed options: ${externalOptionsKeys.join(', ')}`);
|
package/dist/cli/config.js.flow
CHANGED
package/dist/cli/config.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/cli/config.js"],"names":["loadConfigFile","configFile","data","JSON","parse","fs","readFileSync","toplevelKeys","Object","keys","forEach","k","includes","Error","join","options","externalOptionsKeys","excludes","map","string","RegExp","schemaFilePath","path","dirname","getSchemas","raw","endsWith","schemaForValidation","queryResponse","descriptions","schemaForTypeGeneration","introspectionData"],"mappings":";;;;;;;AAKA;;AAEA;;AACA;;AAOA;;;;AAkBO,MAAMA,cAAc,GAAIC,UAAD,IAAmC;AAAA;;AAC7D;AACA,QAAMC,IAAgB,GAAGC,IAAI,CAACC,KAAL,CAAWC,YAAGC,YAAH,CAAgBL,UAAhB,EAA4B,MAA5B,CAAX,CAAzB;AACA,QAAMM,YAAY,GAAG,CAAC,UAAD,EAAa,gBAAb,EAA+B,SAA/B,CAArB;AACAC,EAAAA,MAAM,CAACC,IAAP,CAAYP,IAAZ,EAAkBQ,OAAlB,CAA2BC,CAAD,IAAO;AAC7B,QAAI,CAACJ,YAAY,CAACK,QAAb,CAAsBD,CAAtB,CAAL,EAA+B;AAC3B,YAAM,IAAIE,KAAJ,CACD,oCAAmCZ,UAAW,KAAIU,CAAE,yBAAwBJ,YAAY,CAACO,IAAb,CACzE,IADyE,CAE3E,EAHA,CAAN;AAKH;AACJ,GARD;;AASA,MAAIZ,IAAI,CAACa,OAAT,EAAkB;AACd,UAAMC,mBAAmB,GAAG,CACxB,QADwB,EAExB,aAFwB,EAGxB,cAHwB,EAIxB,SAJwB,EAKxB,mBALwB,EAMxB,mBANwB,EAOxB,eAPwB,EAQxB,YARwB,EASxB,oBATwB,EAUxB,sBAVwB,CAA5B;
|
|
1
|
+
{"version":3,"sources":["../../src/cli/config.js"],"names":["loadConfigFile","configFile","data","JSON","parse","fs","readFileSync","toplevelKeys","Object","keys","forEach","k","includes","Error","join","options","externalOptionsKeys","excludes","map","string","RegExp","schemaFilePath","path","dirname","getSchemas","raw","endsWith","schemaForValidation","queryResponse","descriptions","schemaForTypeGeneration","introspectionData"],"mappings":";;;;;;;AAKA;;AAEA;;AACA;;AAOA;;;;AAkBO,MAAMA,cAAc,GAAIC,UAAD,IAAmC;AAAA;;AAC7D;AACA,QAAMC,IAAgB,GAAGC,IAAI,CAACC,KAAL,CAAWC,YAAGC,YAAH,CAAgBL,UAAhB,EAA4B,MAA5B,CAAX,CAAzB;AACA,QAAMM,YAAY,GAAG,CAAC,UAAD,EAAa,gBAAb,EAA+B,SAA/B,CAArB;AACAC,EAAAA,MAAM,CAACC,IAAP,CAAYP,IAAZ,EAAkBQ,OAAlB,CAA2BC,CAAD,IAAO;AAC7B,QAAI,CAACJ,YAAY,CAACK,QAAb,CAAsBD,CAAtB,CAAL,EAA+B;AAC3B,YAAM,IAAIE,KAAJ,CACD,oCAAmCZ,UAAW,KAAIU,CAAE,yBAAwBJ,YAAY,CAACO,IAAb,CACzE,IADyE,CAE3E,EAHA,CAAN;AAKH;AACJ,GARD;;AASA,MAAIZ,IAAI,CAACa,OAAT,EAAkB;AACd,UAAMC,mBAAmB,GAAG,CACxB,QADwB,EAExB,aAFwB,EAGxB,cAHwB,EAIxB,SAJwB,EAKxB,mBALwB,EAMxB,mBANwB,EAOxB,eAPwB,EAQxB,YARwB,EASxB,oBATwB,EAUxB,sBAVwB,EAWxB,cAXwB,CAA5B;AAaAR,IAAAA,MAAM,CAACC,IAAP,CAAYP,IAAI,CAACa,OAAjB,EAA0BL,OAA1B,CAAmCC,CAAD,IAAO;AACrC,UAAI,CAACK,mBAAmB,CAACJ,QAApB,CAA6BD,CAA7B,CAAL,EAAsC;AAClC,cAAM,IAAIE,KAAJ,CACD,iCAAgCZ,UAAW,KAAIU,CAAE,sBAAqBK,mBAAmB,CAACF,IAApB,CACnE,IADmE,CAErE,EAHA,CAAN;AAKH;AACJ,KARD;AASH;;AACD,SAAO;AACHC,IAAAA,OAAO,mBAAEb,IAAI,CAACa,OAAP,yDAAkB,EADtB;AAEHE,IAAAA,QAAQ,0CAAEf,IAAI,CAACe,QAAP,mDAAE,eAAeC,GAAf,CAAoBC,MAAD,IAAY,IAAIC,MAAJ,CAAWD,MAAX,CAA/B,CAAF,mEAAwD,EAF7D;AAGHE,IAAAA,cAAc,EAAEC,cAAKR,IAAL,CACZQ,cAAKC,OAAL,CAAatB,UAAb,CADY,EAEZC,IAAI,CAACmB,cAFO;AAHb,GAAP;AAQH,CA7CM;AA+CP;AACA;AACA;;;;;AACO,MAAMG,UAAU,GAAIH,cAAD,IAAqD;AAC3E,QAAMI,GAAG,GAAGpB,YAAGC,YAAH,CAAgBe,cAAhB,EAAgC,MAAhC,CAAZ;;AACA,MAAIA,cAAc,CAACK,QAAf,CAAwB,UAAxB,CAAJ,EAAyC;AACrC,UAAMC,mBAAmB,GAAG,0BAAYF,GAAZ,CAA5B;AACA,UAAMG,aAAa,GAAG,0BAClBD,mBADkB,EAElB,oCAAsB;AAACE,MAAAA,YAAY,EAAE;AAAf,KAAtB,CAFkB,CAAtB;AAIA,UAAMC,uBAAuB,GAAG,+DAC5B;AACEF,IAAAA,aAAa,CAAC1B,IAFY,CAAhC;AAIA,WAAO,CAACyB,mBAAD,EAAsBG,uBAAtB,CAAP;AACH,GAXD,MAWO;AACH;AACA,UAAMC,iBAAqC,GAAG5B,IAAI,CAACC,KAAL,CAAWqB,GAAX,CAA9C;AACA,UAAME,mBAAmB,GAAG,gCAAkBI,iBAAlB,CAA5B;AACA,UAAMD,uBAAuB,GACzB,8DAA4BC,iBAA5B,CADJ;AAEA,WAAO,CAACJ,mBAAD,EAAsBG,uBAAtB,CAAP;AACH;AACJ,CArBM","sourcesContent":["// @flow\nimport type {ExternalOptions} from '../generateTypeFiles';\nimport type {Schema} from '../types';\nimport type {GraphQLSchema} from 'graphql/type/schema';\n\nimport {schemaFromIntrospectionData} from '../schemaFromIntrospectionData';\n\nimport fs from 'fs';\nimport {\n buildClientSchema,\n buildSchema,\n getIntrospectionQuery,\n graphqlSync,\n type IntrospectionQuery,\n} from 'graphql';\nimport path from 'path';\n\nexport type CliConfig = {\n excludes: Array<RegExp>,\n schemaFilePath: string,\n options: ExternalOptions,\n};\n\n/**\n * This is the json-compatible form of the config\n * object.\n */\ntype JSONConfig = {\n excludes?: Array<string>,\n schemaFilePath: string,\n options?: ExternalOptions,\n};\n\nexport const loadConfigFile = (configFile: string): CliConfig => {\n // eslint-disable-next-line flowtype-errors/uncovered\n const data: JSONConfig = JSON.parse(fs.readFileSync(configFile, 'utf8'));\n const toplevelKeys = ['excludes', 'schemaFilePath', 'options'];\n Object.keys(data).forEach((k) => {\n if (!toplevelKeys.includes(k)) {\n throw new Error(\n `Invalid attribute in config file ${configFile}: ${k}. Allowed attributes: ${toplevelKeys.join(\n ', ',\n )}`,\n );\n }\n });\n if (data.options) {\n const externalOptionsKeys = [\n 'pragma',\n 'loosePragma',\n 'ignorePragma',\n 'scalars',\n 'strictNullability',\n 'regenerateCommand',\n 'readOnlyArray',\n 'splitTypes',\n 'generatedDirectory',\n 'exportAllObjectTypes',\n 'typeFileName',\n ];\n Object.keys(data.options).forEach((k) => {\n if (!externalOptionsKeys.includes(k)) {\n throw new Error(\n `Invalid option in config file ${configFile}: ${k}. Allowed options: ${externalOptionsKeys.join(\n ', ',\n )}`,\n );\n }\n });\n }\n return {\n options: data.options ?? {},\n excludes: data.excludes?.map((string) => new RegExp(string)) ?? [],\n schemaFilePath: path.join(\n path.dirname(configFile),\n data.schemaFilePath,\n ),\n };\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"],"file":"config.js"}
|
package/dist/cli/run.js
CHANGED
|
@@ -61,7 +61,17 @@ const [schemaForValidation, schemaForTypeGeneration] = (0, _config.getSchemas)(c
|
|
|
61
61
|
const inputFiles = cliFiles.length ? cliFiles : findGraphqlTagReferences(process.cwd());
|
|
62
62
|
/** Step (2) */
|
|
63
63
|
|
|
64
|
-
const files = (0, _parse.processFiles)(inputFiles, f =>
|
|
64
|
+
const files = (0, _parse.processFiles)(inputFiles, f => {
|
|
65
|
+
if ((0, _fs.existsSync)(f)) {
|
|
66
|
+
return (0, _fs.readFileSync)(f, 'utf8');
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
if ((0, _fs.existsSync)(f + '.js')) {
|
|
70
|
+
return (0, _fs.readFileSync)(f + '.js', 'utf8');
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
throw new Error(`Unable to find ${f}`);
|
|
74
|
+
});
|
|
65
75
|
let filesHadErrors = false;
|
|
66
76
|
Object.keys(files).forEach(key => {
|
|
67
77
|
const file = files[key];
|
package/dist/cli/run.js.flow
CHANGED
|
@@ -9,7 +9,7 @@ import {getSchemas, loadConfigFile} from './config';
|
|
|
9
9
|
import {addTypenameToDocument} from 'apollo-utilities'; // eslint-disable-line flowtype-errors/uncovered
|
|
10
10
|
|
|
11
11
|
import {execSync} from 'child_process';
|
|
12
|
-
import {readFileSync} from 'fs';
|
|
12
|
+
import {existsSync, readFileSync} from 'fs';
|
|
13
13
|
import {type DocumentNode} from 'graphql';
|
|
14
14
|
import {print} from 'graphql/language/printer';
|
|
15
15
|
import {validate} from 'graphql/validation';
|
|
@@ -68,7 +68,15 @@ const inputFiles = cliFiles.length
|
|
|
68
68
|
|
|
69
69
|
/** Step (2) */
|
|
70
70
|
|
|
71
|
-
const files = processFiles(inputFiles, (f) =>
|
|
71
|
+
const files = processFiles(inputFiles, (f) => {
|
|
72
|
+
if (existsSync(f)) {
|
|
73
|
+
return readFileSync(f, 'utf8');
|
|
74
|
+
}
|
|
75
|
+
if (existsSync(f + '.js')) {
|
|
76
|
+
return readFileSync(f + '.js', 'utf8');
|
|
77
|
+
}
|
|
78
|
+
throw new Error(`Unable to find ${f}`);
|
|
79
|
+
});
|
|
72
80
|
|
|
73
81
|
let filesHadErrors = false;
|
|
74
82
|
Object.keys(files).forEach((key) => {
|
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","_","__","configFile","cliFiles","process","argv","console","log","exit","config","schemaForValidation","schemaForTypeGeneration","schemaFilePath","inputFiles","length","files","f","filesHadErrors","Object","keys","forEach","key","file","errors","error","message","resolved","loc","validationFailures","k","document","raw","excludes","some","rx","test","hasNonFragments","definitions","kind","rawSource","literals","processedOptions","options","withTypeNames","printed","err"],"mappings":"AAAA;;AAEA;;;AACA;;AACA;;AACA;;AACA;;AAEA;;AAEA;;AACA;;AAEA;;AACA;;AACA;;;;AAPwD;;AASxD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AAEA,MAAMA,wBAAwB,GAAIC,IAAD,IAAiC;AAC9D,QAAMC,QAAQ,GAAG,6BACb,uFADa,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,UAAR,EAAoB,GAAGC,QAAvB,IAAmCC,OAAO,CAACC,IAAjD;;AAEA,IACIH,UAAU,KAAK,IAAf,IACAA,UAAU,KAAK,QADf,IAEAA,UAAU,KAAK,MAFf,IAGA,CAACA,UAJL,EAKE;AACEI,EAAAA,OAAO,CAACC,GAAR,CAAa;AACjB;AACA,wDAFI;AAGAH,EAAAA,OAAO,CAACI,IAAR,CAAa,CAAb,EAJF,CAImB;AACpB;;AAED,MAAMC,MAAM,GAAG,4BAAeP,UAAf,CAAf;AAEA,MAAM,CAACQ,mBAAD,EAAsBC,uBAAtB,IAAiD,wBACnDF,MAAM,CAACG,cAD4C,CAAvD;AAIA,MAAMC,UAAU,GAAGV,QAAQ,CAACW,MAAT,GACbX,QADa,GAEbd,wBAAwB,CAACe,OAAO,CAACX,GAAR,EAAD,CAF9B;AAIA;;AAEA,MAAMsB,KAAK,GAAG,yBAAaF,UAAb,EAA0BG,CAAD,IAAO,sBAAaA,CAAb,EAAgB,MAAhB,
|
|
1
|
+
{"version":3,"sources":["../../src/cli/run.js"],"names":["findGraphqlTagReferences","root","response","encoding","cwd","trim","split","map","relative","path","join","_","__","configFile","cliFiles","process","argv","console","log","exit","config","schemaForValidation","schemaForTypeGeneration","schemaFilePath","inputFiles","length","files","f","Error","filesHadErrors","Object","keys","forEach","key","file","errors","error","message","resolved","loc","validationFailures","k","document","raw","excludes","some","rx","test","hasNonFragments","definitions","kind","rawSource","literals","processedOptions","options","withTypeNames","printed","err"],"mappings":"AAAA;;AAEA;;;AACA;;AACA;;AACA;;AACA;;AAEA;;AAEA;;AACA;;AAEA;;AACA;;AACA;;;;AAPwD;;AASxD;AACA;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G,GAAG,CAACJ,GAAJ,CAAQ9B,IADZ,EAEIa,uBAFJ,EAGIiC,aAHJ,EAIIF,gBAJJ,EADA,CAOA;AACH,GARD,CAQE,OAAOI,GAAP,EAAY;AACVxC,IAAAA,OAAO,CAACmB,KAAR,CAAe,yCAAwCO,GAAG,CAACJ,GAAJ,CAAQ9B,IAAK,EAApE;AACAQ,IAAAA,OAAO,CAACmB,KAAR,CAAcoB,OAAd,EAFU,CAGV;;AACAvC,IAAAA,OAAO,CAACmB,KAAR,CAAcqB,GAAd;AACAjB,IAAAA,kBAAkB;AACrB;AACJ,CAlDD;;AAoDA,IAAIA,kBAAJ,EAAwB;AACpBvB,EAAAA,OAAO,CAACmB,KAAR,CACK,eAAcI,kBAAmB,4CADtC,EADoB,CAIpB;;AACAzB,EAAAA,OAAO,CAACI,IAAR,CAAa,CAAb;AACH","sourcesContent":["#!/usr/bin/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 {getSchemas, loadConfigFile} from './config';\n\nimport {addTypenameToDocument} from 'apollo-utilities'; // eslint-disable-line flowtype-errors/uncovered\n\nimport {execSync} from 'child_process';\nimport {existsSync, readFileSync} from 'fs';\nimport {type DocumentNode} from 'graphql';\nimport {print} from 'graphql/language/printer';\nimport {validate} from 'graphql/validation';\nimport path from 'path';\n\n/**\n * This CLI tool executes the following steps:\n * 1) process options\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'\",\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 [_, __, configFile, ...cliFiles] = process.argv;\n\nif (\n configFile === '-h' ||\n configFile === '--help' ||\n configFile === 'help' ||\n !configFile\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 config = loadConfigFile(configFile);\n\nconst [schemaForValidation, schemaForTypeGeneration] = getSchemas(\n config.schemaFilePath,\n);\n\nconst inputFiles = cliFiles.length\n ? cliFiles\n : findGraphqlTagReferences(process.cwd());\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\nlet validationFailures: number = 0;\n\nObject.keys(resolved).forEach((k) => {\n const {document, raw} = resolved[k];\n if (config.excludes.some((rx) => rx.test(raw.loc.path))) {\n return; // skip\n }\n const hasNonFragments = document.definitions.some(\n ({kind}) => kind !== 'FragmentDefinition',\n );\n const rawSource: string = raw.literals[0];\n const processedOptions = processPragmas(config.options, rawSource);\n if (!processedOptions) {\n return;\n }\n\n // eslint-disable-next-line flowtype-errors/uncovered\n const withTypeNames: DocumentNode = addTypenameToDocument(document);\n const printed = print(withTypeNames);\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 processedOptions,\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"],"file":"run.js"}
|
|
@@ -56,7 +56,7 @@ const generateTypeFileContents = (fileName, schema, document, options, generated
|
|
|
56
56
|
}) => {
|
|
57
57
|
// We write all generated files to a `__generated__` subdir to keep
|
|
58
58
|
// things tidy.
|
|
59
|
-
const targetFileName = `${name}.js`;
|
|
59
|
+
const targetFileName = options.typeFileName ? options.typeFileName.replace('[operationName]', name) : `${name}.js`;
|
|
60
60
|
|
|
61
61
|
const targetPath = _path.default.join(generatedDir, targetFileName);
|
|
62
62
|
|
|
@@ -132,7 +132,8 @@ const processPragmas = (options, rawSource) => {
|
|
|
132
132
|
scalars: options.scalars,
|
|
133
133
|
splitTypes: options.splitTypes,
|
|
134
134
|
generatedDirectory: options.generatedDirectory,
|
|
135
|
-
exportAllObjectTypes: options.exportAllObjectTypes
|
|
135
|
+
exportAllObjectTypes: options.exportAllObjectTypes,
|
|
136
|
+
typeFileName: options.typeFileName
|
|
136
137
|
};
|
|
137
138
|
} else {
|
|
138
139
|
return null;
|
|
@@ -20,6 +20,7 @@ export type ExternalOptions = {
|
|
|
20
20
|
splitTypes?: boolean,
|
|
21
21
|
generatedDirectory?: string,
|
|
22
22
|
exportAllObjectTypes?: boolean,
|
|
23
|
+
typeFileName?: string,
|
|
23
24
|
};
|
|
24
25
|
|
|
25
26
|
export const indexPrelude = (regenerateCommand?: string): string => `// @flow
|
|
@@ -64,7 +65,9 @@ export const generateTypeFileContents = (
|
|
|
64
65
|
generated.forEach(({name, typeName, code, isFragment, extraTypes}) => {
|
|
65
66
|
// We write all generated files to a `__generated__` subdir to keep
|
|
66
67
|
// things tidy.
|
|
67
|
-
const targetFileName =
|
|
68
|
+
const targetFileName = options.typeFileName
|
|
69
|
+
? options.typeFileName.replace('[operationName]', name)
|
|
70
|
+
: `${name}.js`;
|
|
68
71
|
const targetPath = path.join(generatedDir, targetFileName);
|
|
69
72
|
|
|
70
73
|
let fileContents =
|
|
@@ -160,6 +163,7 @@ export const processPragmas = (
|
|
|
160
163
|
splitTypes: options.splitTypes,
|
|
161
164
|
generatedDirectory: options.generatedDirectory,
|
|
162
165
|
exportAllObjectTypes: options.exportAllObjectTypes,
|
|
166
|
+
typeFileName: options.typeFileName,
|
|
163
167
|
};
|
|
164
168
|
} else {
|
|
165
169
|
return null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/generateTypeFiles.js"],"names":["indexPrelude","regenerateCommand","generateTypeFileContents","fileName","schema","document","options","generatedDir","indexContents","files","addToIndex","filePath","typeName","newLine","path","basename","indexOf","lines","split","map","line","includes","join","generated","forEach","name","code","isFragment","extraTypes","targetFileName","targetPath","fileContents","splitTypes","Object","keys","replace","generateTypeFiles","dirname","generatedDirectory","indexFile","fs","existsSync","mkdirSync","recursive","writeFileSync","readFileSync","key","processPragmas","rawSource","ignorePragma","autogen","loosePragma","autogenStrict","pragma","noPragmas","strictNullability","readOnlyArray","scalars","exportAllObjectTypes"],"mappings":";;;;;;;AAIA;;AACA;;AACA;;;;AALA;A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,CAAC+C,MAA3B,CADgB,GAEhB,KAFN;AAGA,QAAMC,SAAS,GAAG,CAAChD,OAAO,CAAC6C,WAAT,IAAwB,CAAC7C,OAAO,CAAC+C,MAAnD;;AAEA,MAAIH,OAAO,IAAIE,aAAX,IAA4BE,SAAhC,EAA2C;AACvC,WAAO;AACHrD,MAAAA,iBAAiB,EAAEK,OAAO,CAACL,iBADxB;AAEHsD,MAAAA,iBAAiB,EAAED,SAAS,GACtBhD,OAAO,CAACiD,iBADc,GAEtBH,aAAa,IAAI,CAACF,OAJrB;AAKHM,MAAAA,aAAa,EAAElD,OAAO,CAACkD,aALpB;AAMHC,MAAAA,OAAO,EAAEnD,OAAO,CAACmD,OANd;AAOHzB,MAAAA,UAAU,EAAE1B,OAAO,CAAC0B,UAPjB;AAQHM,MAAAA,kBAAkB,EAAEhC,OAAO,CAACgC,kBARzB;AASHoB,MAAAA,oBAAoB,EAAEpD,OAAO,CAACoD;AAT3B,KAAP;AAWH,GAZD,MAYO;AACH,WAAO,IAAP;AACH;AACJ,CA/BM","sourcesContent":["// @flow\n// Import this in your jest setup, to mock out graphql-tag!\nimport type {DocumentNode} from 'graphql';\nimport type {Options, Schema, Scalars} from './types';\nimport fs from 'fs';\nimport path from 'path';\nimport {documentToFlowTypes} from '.';\n\nexport type ExternalOptions = {\n pragma?: string,\n loosePragma?: string,\n ignorePragma?: string,\n scalars?: Scalars,\n strictNullability?: boolean,\n /**\n * The command that users should run to regenerate the types files.\n */\n regenerateCommand?: string,\n readOnlyArray?: boolean,\n splitTypes?: boolean,\n generatedDirectory?: string,\n exportAllObjectTypes?: boolean,\n};\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: Options,\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 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(({name, typeName, code, isFragment, extraTypes}) => {\n // We write all generated files to a `__generated__` subdir to keep\n // things tidy.\n const targetFileName = `${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((name) => {\n fileContents += `\\n\\nexport type ${name} = ${extraTypes[name]};`;\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 return {files, indexContents};\n};\n\nexport const generateTypeFiles = (\n fileName: string,\n schema: Schema,\n document: DocumentNode,\n options: Options,\n) => {\n const generatedDir = path.join(\n path.dirname(fileName),\n options.generatedDirectory ?? '__generated__',\n );\n const indexFile = path.join(generatedDir, 'index.js');\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 fs.writeFileSync(key, files[key]);\n });\n\n fs.writeFileSync(indexFile, indexContents);\n};\n\nexport const processPragmas = (\n options: ExternalOptions,\n rawSource: string,\n): null | Options => {\n if (options.ignorePragma && rawSource.includes(options.ignorePragma)) {\n return null;\n }\n\n const autogen = options.loosePragma\n ? rawSource.includes(options.loosePragma)\n : false;\n const autogenStrict = options.pragma\n ? rawSource.includes(options.pragma)\n : false;\n const noPragmas = !options.loosePragma && !options.pragma;\n\n if (autogen || autogenStrict || noPragmas) {\n return {\n regenerateCommand: options.regenerateCommand,\n strictNullability: noPragmas\n ? options.strictNullability\n : autogenStrict || !autogen,\n readOnlyArray: options.readOnlyArray,\n scalars: options.scalars,\n splitTypes: options.splitTypes,\n generatedDirectory: options.generatedDirectory,\n exportAllObjectTypes: options.exportAllObjectTypes,\n };\n } else {\n return null;\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","newLine","path","basename","indexOf","lines","split","map","line","includes","join","generated","forEach","name","code","isFragment","extraTypes","targetFileName","typeFileName","replace","targetPath","fileContents","splitTypes","Object","keys","generateTypeFiles","dirname","generatedDirectory","indexFile","fs","existsSync","mkdirSync","recursive","writeFileSync","readFileSync","key","processPragmas","rawSource","ignorePragma","autogen","loosePragma","autogenStrict","pragma","noPragmas","strictNullability","readOnlyArray","scalars","exportAllObjectTypes"],"mappings":";;;;;;;AAIA;;AACA;;AACA;;;;AALA;AAwBO,MAAMA,YAAY,GAAIC,iBAAD,IAAyC;AACrE;AACA;AACA;AACA;AACA,IAAIA,iBA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,CAAC5B,QAAV,CAAmBf,OAAO,CAACgD,MAA3B,CADgB,GAEhB,KAFN;AAGA,QAAMC,SAAS,GAAG,CAACjD,OAAO,CAAC8C,WAAT,IAAwB,CAAC9C,OAAO,CAACgD,MAAnD;;AAEA,MAAIH,OAAO,IAAIE,aAAX,IAA4BE,SAAhC,EAA2C;AACvC,WAAO;AACHtD,MAAAA,iBAAiB,EAAEK,OAAO,CAACL,iBADxB;AAEHuD,MAAAA,iBAAiB,EAAED,SAAS,GACtBjD,OAAO,CAACkD,iBADc,GAEtBH,aAAa,IAAI,CAACF,OAJrB;AAKHM,MAAAA,aAAa,EAAEnD,OAAO,CAACmD,aALpB;AAMHC,MAAAA,OAAO,EAAEpD,OAAO,CAACoD,OANd;AAOHxB,MAAAA,UAAU,EAAE5B,OAAO,CAAC4B,UAPjB;AAQHK,MAAAA,kBAAkB,EAAEjC,OAAO,CAACiC,kBARzB;AASHoB,MAAAA,oBAAoB,EAAErD,OAAO,CAACqD,oBAT3B;AAUH7B,MAAAA,YAAY,EAAExB,OAAO,CAACwB;AAVnB,KAAP;AAYH,GAbD,MAaO;AACH,WAAO,IAAP;AACH;AACJ,CAhCM","sourcesContent":["// @flow\n// Import this in your jest setup, to mock out graphql-tag!\nimport type {DocumentNode} from 'graphql';\nimport type {Options, Schema, Scalars} from './types';\nimport fs from 'fs';\nimport path from 'path';\nimport {documentToFlowTypes} from '.';\n\nexport type ExternalOptions = {\n pragma?: string,\n loosePragma?: string,\n ignorePragma?: string,\n scalars?: Scalars,\n strictNullability?: boolean,\n /**\n * The command that users should run to regenerate the types files.\n */\n regenerateCommand?: string,\n readOnlyArray?: boolean,\n splitTypes?: boolean,\n generatedDirectory?: string,\n exportAllObjectTypes?: boolean,\n typeFileName?: string,\n};\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: Options,\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 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(({name, typeName, code, isFragment, extraTypes}) => {\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((name) => {\n fileContents += `\\n\\nexport type ${name} = ${extraTypes[name]};`;\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 return {files, indexContents};\n};\n\nexport const generateTypeFiles = (\n fileName: string,\n schema: Schema,\n document: DocumentNode,\n options: Options,\n) => {\n const generatedDir = path.join(\n path.dirname(fileName),\n options.generatedDirectory ?? '__generated__',\n );\n const indexFile = path.join(generatedDir, 'index.js');\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 fs.writeFileSync(key, files[key]);\n });\n\n fs.writeFileSync(indexFile, indexContents);\n};\n\nexport const processPragmas = (\n options: ExternalOptions,\n rawSource: string,\n): null | Options => {\n if (options.ignorePragma && rawSource.includes(options.ignorePragma)) {\n return null;\n }\n\n const autogen = options.loosePragma\n ? rawSource.includes(options.loosePragma)\n : false;\n const autogenStrict = options.pragma\n ? rawSource.includes(options.pragma)\n : false;\n const noPragmas = !options.loosePragma && !options.pragma;\n\n if (autogen || autogenStrict || noPragmas) {\n return {\n regenerateCommand: options.regenerateCommand,\n strictNullability: noPragmas\n ? options.strictNullability\n : autogenStrict || !autogen,\n readOnlyArray: options.readOnlyArray,\n scalars: options.scalars,\n splitTypes: options.splitTypes,\n generatedDirectory: options.generatedDirectory,\n exportAllObjectTypes: options.exportAllObjectTypes,\n typeFileName: options.typeFileName,\n };\n } else {\n return null;\n }\n};\n"],"file":"generateTypeFiles.js"}
|
package/dist/types.js.flow
CHANGED
package/package.json
CHANGED
|
@@ -58,4 +58,46 @@ describe('generateTypeFileContents', () => {
|
|
|
58
58
|
"
|
|
59
59
|
`);
|
|
60
60
|
});
|
|
61
|
+
|
|
62
|
+
it('should respect the typeFileName option', () => {
|
|
63
|
+
const {files} = generateTypeFileContents(
|
|
64
|
+
'hello.js',
|
|
65
|
+
exampleSchema,
|
|
66
|
+
gql`
|
|
67
|
+
query Hello {
|
|
68
|
+
human(id: "Han") {
|
|
69
|
+
id
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
`,
|
|
73
|
+
{
|
|
74
|
+
splitTypes: true,
|
|
75
|
+
typeFileName: 'prefix-[operationName]-suffix.js',
|
|
76
|
+
},
|
|
77
|
+
'__generated__',
|
|
78
|
+
indexPrelude('yarn queries'),
|
|
79
|
+
);
|
|
80
|
+
expect(
|
|
81
|
+
Object.keys(files)
|
|
82
|
+
.map((k) => `// ${k}\n${files[k]}`)
|
|
83
|
+
.join('\n\n'),
|
|
84
|
+
).toMatchInlineSnapshot(`
|
|
85
|
+
"// __generated__/prefix-Hello-suffix.js
|
|
86
|
+
// @flow
|
|
87
|
+
// AUTOGENERATED -- DO NOT EDIT
|
|
88
|
+
// Generated for operation 'Hello' in file '../hello.js'
|
|
89
|
+
export type HelloType = {|
|
|
90
|
+
variables: {||},
|
|
91
|
+
response: {|
|
|
92
|
+
/** A human character*/
|
|
93
|
+
human: ?{|
|
|
94
|
+
id: string
|
|
95
|
+
|}
|
|
96
|
+
|}
|
|
97
|
+
|};
|
|
98
|
+
export type Hello = HelloType['response'];
|
|
99
|
+
export type HelloVariables = HelloType['variables'];
|
|
100
|
+
"
|
|
101
|
+
`);
|
|
102
|
+
});
|
|
61
103
|
});
|
package/src/cli/config.js
CHANGED
package/src/cli/run.js
CHANGED
|
@@ -9,7 +9,7 @@ import {getSchemas, loadConfigFile} from './config';
|
|
|
9
9
|
import {addTypenameToDocument} from 'apollo-utilities'; // eslint-disable-line flowtype-errors/uncovered
|
|
10
10
|
|
|
11
11
|
import {execSync} from 'child_process';
|
|
12
|
-
import {readFileSync} from 'fs';
|
|
12
|
+
import {existsSync, readFileSync} from 'fs';
|
|
13
13
|
import {type DocumentNode} from 'graphql';
|
|
14
14
|
import {print} from 'graphql/language/printer';
|
|
15
15
|
import {validate} from 'graphql/validation';
|
|
@@ -68,7 +68,15 @@ const inputFiles = cliFiles.length
|
|
|
68
68
|
|
|
69
69
|
/** Step (2) */
|
|
70
70
|
|
|
71
|
-
const files = processFiles(inputFiles, (f) =>
|
|
71
|
+
const files = processFiles(inputFiles, (f) => {
|
|
72
|
+
if (existsSync(f)) {
|
|
73
|
+
return readFileSync(f, 'utf8');
|
|
74
|
+
}
|
|
75
|
+
if (existsSync(f + '.js')) {
|
|
76
|
+
return readFileSync(f + '.js', 'utf8');
|
|
77
|
+
}
|
|
78
|
+
throw new Error(`Unable to find ${f}`);
|
|
79
|
+
});
|
|
72
80
|
|
|
73
81
|
let filesHadErrors = false;
|
|
74
82
|
Object.keys(files).forEach((key) => {
|
package/src/generateTypeFiles.js
CHANGED
|
@@ -20,6 +20,7 @@ export type ExternalOptions = {
|
|
|
20
20
|
splitTypes?: boolean,
|
|
21
21
|
generatedDirectory?: string,
|
|
22
22
|
exportAllObjectTypes?: boolean,
|
|
23
|
+
typeFileName?: string,
|
|
23
24
|
};
|
|
24
25
|
|
|
25
26
|
export const indexPrelude = (regenerateCommand?: string): string => `// @flow
|
|
@@ -64,7 +65,9 @@ export const generateTypeFileContents = (
|
|
|
64
65
|
generated.forEach(({name, typeName, code, isFragment, extraTypes}) => {
|
|
65
66
|
// We write all generated files to a `__generated__` subdir to keep
|
|
66
67
|
// things tidy.
|
|
67
|
-
const targetFileName =
|
|
68
|
+
const targetFileName = options.typeFileName
|
|
69
|
+
? options.typeFileName.replace('[operationName]', name)
|
|
70
|
+
: `${name}.js`;
|
|
68
71
|
const targetPath = path.join(generatedDir, targetFileName);
|
|
69
72
|
|
|
70
73
|
let fileContents =
|
|
@@ -160,6 +163,7 @@ export const processPragmas = (
|
|
|
160
163
|
splitTypes: options.splitTypes,
|
|
161
164
|
generatedDirectory: options.generatedDirectory,
|
|
162
165
|
exportAllObjectTypes: options.exportAllObjectTypes,
|
|
166
|
+
typeFileName: options.typeFileName,
|
|
163
167
|
};
|
|
164
168
|
} else {
|
|
165
169
|
return null;
|