@khanacademy/graphql-flow 0.1.0 → 0.2.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.
@@ -3,7 +3,15 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
- exports.processPragmas = exports.generateTypeFiles = void 0;
6
+ exports.processPragmas = exports.indexPrelude = exports.generateTypeFiles = exports.generateTypeFileContents = void 0;
7
+
8
+ var _fs = _interopRequireDefault(require("fs"));
9
+
10
+ var _path = _interopRequireDefault(require("path"));
11
+
12
+ var _ = require(".");
13
+
14
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
7
15
 
8
16
  // Import this in your jest setup, to mock out graphql-tag!
9
17
  const indexPrelude = regenerateCommand => `// @flow
@@ -16,63 +24,93 @@ const indexPrelude = regenerateCommand => `// @flow
16
24
 
17
25
  `;
18
26
 
19
- const generateTypeFiles = (fileName, schema, document, options) => {
20
- const {
21
- documentToFlowTypes
22
- } = require('.');
23
-
24
- const path = require('path');
27
+ exports.indexPrelude = indexPrelude;
25
28
 
26
- const fs = require('fs');
29
+ const generateTypeFileContents = (fileName, schema, document, options, generatedDir, indexContents) => {
30
+ const files = {}; /// Write export for __generated__/index.js if it doesn't exist
27
31
 
28
- const indexFile = generatedDir => path.join(generatedDir, 'index.js');
32
+ const addToIndex = (filePath, typeName) => {
33
+ const newLine = `export type {${typeName}} from './${_path.default.basename(filePath)}';`;
29
34
 
30
- const maybeCreateGeneratedDir = generatedDir => {
31
- if (!fs.existsSync(generatedDir)) {
32
- fs.mkdirSync(generatedDir, {
33
- recursive: true
34
- }); // Now write an index.js for each __generated__ dir.
35
-
36
- fs.writeFileSync(indexFile(generatedDir), indexPrelude(options.regenerateCommand));
37
- }
38
- }; /// Write export for __generated__/index.js if it doesn't exist
39
-
40
-
41
- const writeToIndex = (filePath, typeName) => {
42
- const index = indexFile(path.dirname(filePath));
43
- const indexContents = fs.readFileSync(index, 'utf8');
44
- const newLine = `export type {${typeName}} from './${path.basename(filePath)}';`;
45
-
46
- if (indexContents.indexOf(path.basename(filePath)) === -1) {
47
- fs.appendFileSync(index, newLine + '\n');
35
+ if (indexContents.indexOf('./' + _path.default.basename(filePath)) === -1) {
36
+ indexContents += newLine + '\n';
48
37
  } else {
49
38
  const lines = indexContents.split('\n').map(line => {
50
- if (line.includes(path.basename(filePath))) {
39
+ if (line.includes('./' + _path.default.basename(filePath))) {
51
40
  return newLine;
52
41
  }
53
42
 
54
43
  return line;
55
44
  });
56
- fs.writeFileSync(index, lines.join('\n'));
45
+ indexContents = lines.join('\n');
57
46
  }
58
47
  };
59
48
 
60
- const generated = documentToFlowTypes(document, schema, options);
49
+ const generated = (0, _.documentToFlowTypes)(document, schema, options);
61
50
  generated.forEach(({
62
51
  name,
63
52
  typeName,
64
- code
53
+ code,
54
+ isFragment,
55
+ extraTypes
65
56
  }) => {
66
57
  // We write all generated files to a `__generated__` subdir to keep
67
58
  // things tidy.
68
- const targetFileName = `${typeName}.js`;
69
- const generatedDir = path.join(path.dirname(fileName), '__generated__');
70
- const targetPath = path.join(generatedDir, targetFileName);
71
- maybeCreateGeneratedDir(generatedDir);
72
- const fileContents = '// @' + `flow\n// AUTOGENERATED -- DO NOT EDIT\n` + `// Generated for operation '${name}' in file '../${path.basename(fileName)}'\n` + (options.regenerateCommand ? `// To regenerate, run '${options.regenerateCommand}'.\n` : '') + code;
73
- fs.writeFileSync(targetPath, fileContents);
74
- writeToIndex(targetPath, typeName);
59
+ const targetFileName = `${name}.js`;
60
+
61
+ const targetPath = _path.default.join(generatedDir, targetFileName);
62
+
63
+ let fileContents = '// @' + `flow\n// AUTOGENERATED -- DO NOT EDIT\n` + `// Generated for operation '${name}' in file '../${_path.default.basename(fileName)}'\n` + (options.regenerateCommand ? `// To regenerate, run '${options.regenerateCommand}'.\n` : '') + code;
64
+
65
+ if (options.splitTypes && !isFragment) {
66
+ fileContents += `\nexport type ${name} = ${typeName}['response'];\n` + `export type ${name}Variables = ${typeName}['variables'];\n`;
67
+ }
68
+
69
+ Object.keys(extraTypes).forEach(name => {
70
+ fileContents += `\n\nexport type ${name} = ${extraTypes[name]};`;
71
+ });
72
+ addToIndex(targetPath, typeName);
73
+ files[targetPath] = fileContents // Remove whitespace from the ends of lines; babel's generate sometimes
74
+ // leaves them hanging around.
75
+ .replace(/\s+$/gm, '') + '\n';
75
76
  });
77
+ return {
78
+ files,
79
+ indexContents
80
+ };
81
+ };
82
+
83
+ exports.generateTypeFileContents = generateTypeFileContents;
84
+
85
+ const generateTypeFiles = (fileName, schema, document, options) => {
86
+ var _options$generatedDir;
87
+
88
+ const generatedDir = _path.default.join(_path.default.dirname(fileName), (_options$generatedDir = options.generatedDirectory) !== null && _options$generatedDir !== void 0 ? _options$generatedDir : '__generated__');
89
+
90
+ const indexFile = _path.default.join(generatedDir, 'index.js');
91
+
92
+ if (!_fs.default.existsSync(generatedDir)) {
93
+ _fs.default.mkdirSync(generatedDir, {
94
+ recursive: true
95
+ });
96
+ }
97
+
98
+ if (!_fs.default.existsSync(indexFile)) {
99
+ _fs.default.writeFileSync(indexFile, indexPrelude(options.regenerateCommand));
100
+ }
101
+
102
+ const {
103
+ indexContents,
104
+ files
105
+ } = generateTypeFileContents(fileName, schema, document, options, generatedDir, _fs.default.readFileSync(indexFile, 'utf8'));
106
+
107
+ _fs.default.writeFileSync(indexFile, indexContents);
108
+
109
+ Object.keys(files).forEach(key => {
110
+ _fs.default.writeFileSync(key, files[key]);
111
+ });
112
+
113
+ _fs.default.writeFileSync(indexFile, indexContents);
76
114
  };
77
115
 
78
116
  exports.generateTypeFiles = generateTypeFiles;
@@ -91,7 +129,10 @@ const processPragmas = (options, rawSource) => {
91
129
  regenerateCommand: options.regenerateCommand,
92
130
  strictNullability: noPragmas ? options.strictNullability : autogenStrict || !autogen,
93
131
  readOnlyArray: options.readOnlyArray,
94
- scalars: options.scalars
132
+ scalars: options.scalars,
133
+ splitTypes: options.splitTypes,
134
+ generatedDirectory: options.generatedDirectory,
135
+ exportAllObjectTypes: options.exportAllObjectTypes
95
136
  };
96
137
  } else {
97
138
  return null;
@@ -2,6 +2,9 @@
2
2
  // Import this in your jest setup, to mock out graphql-tag!
3
3
  import type {DocumentNode} from 'graphql';
4
4
  import type {Options, Schema, Scalars} from './types';
5
+ import fs from 'fs';
6
+ import path from 'path';
7
+ import {documentToFlowTypes} from '.';
5
8
 
6
9
  export type ExternalOptions = {
7
10
  pragma?: string,
@@ -14,9 +17,12 @@ export type ExternalOptions = {
14
17
  */
15
18
  regenerateCommand?: string,
16
19
  readOnlyArray?: boolean,
20
+ splitTypes?: boolean,
21
+ generatedDirectory?: string,
22
+ exportAllObjectTypes?: boolean,
17
23
  };
18
24
 
19
- const indexPrelude = (regenerateCommand?: string) => `// @flow
25
+ export const indexPrelude = (regenerateCommand?: string): string => `// @flow
20
26
  //
21
27
  // AUTOGENERATED
22
28
  // NOTE: New response types are added to this file automatically.
@@ -26,61 +32,42 @@ const indexPrelude = (regenerateCommand?: string) => `// @flow
26
32
 
27
33
  `;
28
34
 
29
- export const generateTypeFiles = (
35
+ export const generateTypeFileContents = (
30
36
  fileName: string,
31
37
  schema: Schema,
32
38
  document: DocumentNode,
33
39
  options: Options,
34
- ) => {
35
- const {documentToFlowTypes} = require('.');
36
- const path = require('path');
37
- const fs = require('fs');
38
-
39
- const indexFile = (generatedDir) => path.join(generatedDir, 'index.js');
40
-
41
- const maybeCreateGeneratedDir = (generatedDir) => {
42
- if (!fs.existsSync(generatedDir)) {
43
- fs.mkdirSync(generatedDir, {recursive: true});
44
-
45
- // Now write an index.js for each __generated__ dir.
46
- fs.writeFileSync(
47
- indexFile(generatedDir),
48
- indexPrelude(options.regenerateCommand),
49
- );
50
- }
51
- };
40
+ generatedDir: string,
41
+ indexContents: string,
42
+ ): {indexContents: string, files: {[key: string]: string}} => {
43
+ const files = {};
52
44
 
53
45
  /// Write export for __generated__/index.js if it doesn't exist
54
- const writeToIndex = (filePath, typeName) => {
55
- const index = indexFile(path.dirname(filePath));
56
- const indexContents = fs.readFileSync(index, 'utf8');
46
+ const addToIndex = (filePath, typeName) => {
57
47
  const newLine = `export type {${typeName}} from './${path.basename(
58
48
  filePath,
59
49
  )}';`;
60
- if (indexContents.indexOf(path.basename(filePath)) === -1) {
61
- fs.appendFileSync(index, newLine + '\n');
50
+ if (indexContents.indexOf('./' + path.basename(filePath)) === -1) {
51
+ indexContents += newLine + '\n';
62
52
  } else {
63
53
  const lines = indexContents.split('\n').map((line) => {
64
- if (line.includes(path.basename(filePath))) {
54
+ if (line.includes('./' + path.basename(filePath))) {
65
55
  return newLine;
66
56
  }
67
57
  return line;
68
58
  });
69
- fs.writeFileSync(index, lines.join('\n'));
59
+ indexContents = lines.join('\n');
70
60
  }
71
61
  };
72
62
 
73
63
  const generated = documentToFlowTypes(document, schema, options);
74
- generated.forEach(({name, typeName, code}) => {
64
+ generated.forEach(({name, typeName, code, isFragment, extraTypes}) => {
75
65
  // We write all generated files to a `__generated__` subdir to keep
76
66
  // things tidy.
77
- const targetFileName = `${typeName}.js`;
78
- const generatedDir = path.join(path.dirname(fileName), '__generated__');
67
+ const targetFileName = `${name}.js`;
79
68
  const targetPath = path.join(generatedDir, targetFileName);
80
69
 
81
- maybeCreateGeneratedDir(generatedDir);
82
-
83
- const fileContents =
70
+ let fileContents =
84
71
  '// @' +
85
72
  `flow\n// AUTOGENERATED -- DO NOT EDIT\n` +
86
73
  `// Generated for operation '${name}' in file '../${path.basename(
@@ -90,10 +77,60 @@ export const generateTypeFiles = (
90
77
  ? `// To regenerate, run '${options.regenerateCommand}'.\n`
91
78
  : '') +
92
79
  code;
93
- fs.writeFileSync(targetPath, fileContents);
80
+ if (options.splitTypes && !isFragment) {
81
+ fileContents +=
82
+ `\nexport type ${name} = ${typeName}['response'];\n` +
83
+ `export type ${name}Variables = ${typeName}['variables'];\n`;
84
+ }
85
+ Object.keys(extraTypes).forEach((name) => {
86
+ fileContents += `\n\nexport type ${name} = ${extraTypes[name]};`;
87
+ });
94
88
 
95
- writeToIndex(targetPath, typeName);
89
+ addToIndex(targetPath, typeName);
90
+ files[targetPath] =
91
+ fileContents
92
+ // Remove whitespace from the ends of lines; babel's generate sometimes
93
+ // leaves them hanging around.
94
+ .replace(/\s+$/gm, '') + '\n';
96
95
  });
96
+
97
+ return {files, indexContents};
98
+ };
99
+
100
+ export const generateTypeFiles = (
101
+ fileName: string,
102
+ schema: Schema,
103
+ document: DocumentNode,
104
+ options: Options,
105
+ ) => {
106
+ const generatedDir = path.join(
107
+ path.dirname(fileName),
108
+ options.generatedDirectory ?? '__generated__',
109
+ );
110
+ const indexFile = path.join(generatedDir, 'index.js');
111
+
112
+ if (!fs.existsSync(generatedDir)) {
113
+ fs.mkdirSync(generatedDir, {recursive: true});
114
+ }
115
+ if (!fs.existsSync(indexFile)) {
116
+ fs.writeFileSync(indexFile, indexPrelude(options.regenerateCommand));
117
+ }
118
+
119
+ const {indexContents, files} = generateTypeFileContents(
120
+ fileName,
121
+ schema,
122
+ document,
123
+ options,
124
+ generatedDir,
125
+ fs.readFileSync(indexFile, 'utf8'),
126
+ );
127
+
128
+ fs.writeFileSync(indexFile, indexContents);
129
+ Object.keys(files).forEach((key) => {
130
+ fs.writeFileSync(key, files[key]);
131
+ });
132
+
133
+ fs.writeFileSync(indexFile, indexContents);
97
134
  };
98
135
 
99
136
  export const processPragmas = (
@@ -120,6 +157,9 @@ export const processPragmas = (
120
157
  : autogenStrict || !autogen,
121
158
  readOnlyArray: options.readOnlyArray,
122
159
  scalars: options.scalars,
160
+ splitTypes: options.splitTypes,
161
+ generatedDirectory: options.generatedDirectory,
162
+ exportAllObjectTypes: options.exportAllObjectTypes,
123
163
  };
124
164
  } else {
125
165
  return null;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/generateTypeFiles.js"],"names":["indexPrelude","regenerateCommand","generateTypeFiles","fileName","schema","document","options","documentToFlowTypes","require","path","fs","indexFile","generatedDir","join","maybeCreateGeneratedDir","existsSync","mkdirSync","recursive","writeFileSync","writeToIndex","filePath","typeName","index","dirname","indexContents","readFileSync","newLine","basename","indexOf","appendFileSync","lines","split","map","line","includes","generated","forEach","name","code","targetFileName","targetPath","fileContents","processPragmas","rawSource","ignorePragma","autogen","loosePragma","autogenStrict","pragma","noPragmas","strictNullability","readOnlyArray","scalars"],"mappings":";;;;;;;AACA;AAiBA,MAAMA,YAAY,GAAIC,iBAAD,IAAiC;AACtD;AACA;AACA;AACA;AACA,IAAIA,iBAAiB,GAAG,8BAA8BA,iBAAjC,GAAqD,EAAG;AAC7E;AACA;AACA,CARA;;AAUO,MAAMC,iBAAiB,GAAG,CAC7BC,QAD6B,EAE7BC,MAF6B,EAG7BC,QAH6B,EAI7BC,OAJ6B,KAK5B;AACD,QAAM;AAACC,IAAAA;AAAD,MAAwBC,OAAO,CAAC,GAAD,CAArC;;AACA,QAAMC,IAAI,GAAGD,OAAO,CAAC,MAAD,CAApB;;AACA,QAAME,EAAE,GAAGF,OAAO,CAAC,IAAD,CAAlB;;AAEA,QAAMG,SAAS,GAAIC,YAAD,IAAkBH,IAAI,CAACI,IAAL,CAAUD,YAAV,EAAwB,UAAxB,CAApC;;AAEA,QAAME,uBAAuB,GAAIF,YAAD,IAAkB;AAC9C,QAAI,CAACF,EAAE,CAACK,UAAH,CAAcH,YAAd,CAAL,EAAkC;AAC9BF,MAAAA,EAAE,CAACM,SAAH,CAAaJ,YAAb,EAA2B;AAACK,QAAAA,SAAS,EAAE;AAAZ,OAA3B,EAD8B,CAG9B;;AACAP,MAAAA,EAAE,CAACQ,aAAH,CACIP,SAAS,CAACC,YAAD,CADb,EAEIZ,YAAY,CAACM,OAAO,CAACL,iBAAT,CAFhB;AAIH;AACJ,GAVD,CAPC,CAmBD;;;AACA,QAAMkB,YAAY,GAAG,CAACC,QAAD,EAAWC,QAAX,KAAwB;AACzC,UAAMC,KAAK,GAAGX,SAAS,CAACF,IAAI,CAACc,OAAL,CAAaH,QAAb,CAAD,CAAvB;AAC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WAAO,IAAP;AACH;AACJ,CA5BM","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';\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};\n\nconst indexPrelude = (regenerateCommand?: 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 generateTypeFiles = (\n fileName: string,\n schema: Schema,\n document: DocumentNode,\n options: Options,\n) => {\n const {documentToFlowTypes} = require('.');\n const path = require('path');\n const fs = require('fs');\n\n const indexFile = (generatedDir) => path.join(generatedDir, 'index.js');\n\n const maybeCreateGeneratedDir = (generatedDir) => {\n if (!fs.existsSync(generatedDir)) {\n fs.mkdirSync(generatedDir, {recursive: true});\n\n // Now write an index.js for each __generated__ dir.\n fs.writeFileSync(\n indexFile(generatedDir),\n indexPrelude(options.regenerateCommand),\n );\n }\n };\n\n /// Write export for __generated__/index.js if it doesn't exist\n const writeToIndex = (filePath, typeName) => {\n const index = indexFile(path.dirname(filePath));\n const indexContents = fs.readFileSync(index, 'utf8');\n const newLine = `export type {${typeName}} from './${path.basename(\n filePath,\n )}';`;\n if (indexContents.indexOf(path.basename(filePath)) === -1) {\n fs.appendFileSync(index, 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 fs.writeFileSync(index, lines.join('\\n'));\n }\n };\n\n const generated = documentToFlowTypes(document, schema, options);\n generated.forEach(({name, typeName, code}) => {\n // We write all generated files to a `__generated__` subdir to keep\n // things tidy.\n const targetFileName = `${typeName}.js`;\n const generatedDir = path.join(path.dirname(fileName), '__generated__');\n const targetPath = path.join(generatedDir, targetFileName);\n\n maybeCreateGeneratedDir(generatedDir);\n\n const 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 fs.writeFileSync(targetPath, fileContents);\n\n writeToIndex(targetPath, typeName);\n });\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 };\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","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;AAuBO,MAAMA,YAAY,GAAIC,iBAAD,IAAyC;AACrE;AACA;AACA;AACA;AACA,IAAIA,iBA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AC6C,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"}
package/dist/index.js CHANGED
@@ -11,12 +11,16 @@ Object.defineProperty(exports, "spyOnGraphqlTagToCollectQueries", {
11
11
  }
12
12
  });
13
13
 
14
+ var _generator = _interopRequireDefault(require("@babel/generator"));
15
+
14
16
  var _generateResponseType = require("./generateResponseType");
15
17
 
16
18
  var _generateVariablesType = require("./generateVariablesType");
17
19
 
18
20
  var _jestMockGraphqlTag = require("./jest-mock-graphql-tag");
19
21
 
22
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
23
+
20
24
  /* eslint-disable no-console */
21
25
 
22
26
  /* flow-uncovered-file */
@@ -27,11 +31,14 @@ var _jestMockGraphqlTag = require("./jest-mock-graphql-tag");
27
31
  * It relies on `introspection-query.json` existing in this directory,
28
32
  * which is produced by running `./tools/graphql-flow/sendIntrospection.js`.
29
33
  */
34
+ // eslint-disable-line flowtype-errors/uncovered
30
35
  const optionsToConfig = (schema, definitions, options, errors = []) => {
36
+ var _options$strictNullab, _options$readOnlyArra, _options$scalars;
37
+
31
38
  const internalOptions = {
32
- strictNullability: (options === null || options === void 0 ? void 0 : options.strictNullability) ?? true,
33
- readOnlyArray: (options === null || options === void 0 ? void 0 : options.readOnlyArray) ?? true,
34
- scalars: (options === null || options === void 0 ? void 0 : options.scalars) ?? {}
39
+ strictNullability: (_options$strictNullab = options === null || options === void 0 ? void 0 : options.strictNullability) !== null && _options$strictNullab !== void 0 ? _options$strictNullab : true,
40
+ readOnlyArray: (_options$readOnlyArra = options === null || options === void 0 ? void 0 : options.readOnlyArray) !== null && _options$readOnlyArra !== void 0 ? _options$readOnlyArra : true,
41
+ scalars: (_options$scalars = options === null || options === void 0 ? void 0 : options.scalars) !== null && _options$scalars !== void 0 ? _options$scalars : {}
35
42
  };
36
43
  const fragments = {};
37
44
  definitions.forEach(def => {
@@ -43,6 +50,8 @@ const optionsToConfig = (schema, definitions, options, errors = []) => {
43
50
  fragments,
44
51
  schema,
45
52
  errors,
53
+ allObjectTypes: null,
54
+ path: [],
46
55
  ...internalOptions
47
56
  };
48
57
  return config;
@@ -62,18 +71,51 @@ const documentToFlowTypes = (document, schema, options) => {
62
71
  const errors = [];
63
72
  const config = optionsToConfig(schema, document.definitions, options, errors);
64
73
  const result = document.definitions.map(item => {
74
+ if (item.kind === 'FragmentDefinition') {
75
+ const name = item.name.value;
76
+ const types = {};
77
+ const code = `export type ${name} = ${(0, _generateResponseType.generateFragmentType)(schema, item, { ...config,
78
+ path: [name],
79
+ allObjectTypes: options !== null && options !== void 0 && options.exportAllObjectTypes ? types : null
80
+ })};`;
81
+ const extraTypes = {};
82
+ Object.keys(types).forEach(k => {
83
+ // eslint-disable-next-line flowtype-errors/uncovered
84
+ extraTypes[k] = (0, _generator.default)(types[k]).code;
85
+ });
86
+ return {
87
+ name,
88
+ typeName: name,
89
+ code,
90
+ isFragment: true,
91
+ extraTypes
92
+ };
93
+ }
94
+
65
95
  if (item.kind === 'OperationDefinition' && (item.operation === 'query' || item.operation === 'mutation') && item.name) {
96
+ const types = {};
66
97
  const name = item.name.value;
67
- const response = (0, _generateResponseType.generateResponseType)(schema, item, config);
68
- const variables = (0, _generateVariablesType.generateVariablesType)(schema, item, config);
98
+ const response = (0, _generateResponseType.generateResponseType)(schema, item, { ...config,
99
+ path: [name],
100
+ allObjectTypes: options !== null && options !== void 0 && options.exportAllObjectTypes ? types : null
101
+ });
102
+ const variables = (0, _generateVariablesType.generateVariablesType)(schema, item, { ...config,
103
+ path: [name]
104
+ });
69
105
  const typeName = `${name}Type`; // TODO(jared): Maybe make this template configurable?
70
106
  // We'll see what's required to get webapp on board.
71
107
 
72
108
  const code = `export type ${typeName} = {|\n variables: ${variables},\n response: ${response}\n|};`;
109
+ const extraTypes = {};
110
+ Object.keys(types).forEach(k => {
111
+ // eslint-disable-next-line flowtype-errors/uncovered
112
+ extraTypes[k] = (0, _generator.default)(types[k]).code;
113
+ });
73
114
  return {
74
115
  name,
75
116
  typeName,
76
- code
117
+ code,
118
+ extraTypes
77
119
  };
78
120
  }
79
121
  }).filter(Boolean);
@@ -9,7 +9,11 @@
9
9
  */
10
10
  import type {DefinitionNode, DocumentNode} from 'graphql';
11
11
 
12
- import {generateResponseType} from './generateResponseType';
12
+ import generate from '@babel/generator'; // eslint-disable-line flowtype-errors/uncovered
13
+ import {
14
+ generateFragmentType,
15
+ generateResponseType,
16
+ } from './generateResponseType';
13
17
  import {generateVariablesType} from './generateVariablesType';
14
18
  export {spyOnGraphqlTagToCollectQueries} from './jest-mock-graphql-tag';
15
19
 
@@ -36,6 +40,8 @@ const optionsToConfig = (
36
40
  fragments,
37
41
  schema,
38
42
  errors,
43
+ allObjectTypes: null,
44
+ path: [],
39
45
  ...internalOptions,
40
46
  };
41
47
 
@@ -58,6 +64,8 @@ export const documentToFlowTypes = (
58
64
  name: string,
59
65
  typeName: string,
60
66
  code: string,
67
+ isFragment?: boolean,
68
+ extraTypes: {[key: string]: string},
61
69
  }> => {
62
70
  const errors: Array<string> = [];
63
71
  const config = optionsToConfig(
@@ -68,21 +76,63 @@ export const documentToFlowTypes = (
68
76
  );
69
77
  const result = document.definitions
70
78
  .map((item) => {
79
+ if (item.kind === 'FragmentDefinition') {
80
+ const name = item.name.value;
81
+ const types = {};
82
+ const code = `export type ${name} = ${generateFragmentType(
83
+ schema,
84
+ item,
85
+ {
86
+ ...config,
87
+ path: [name],
88
+ allObjectTypes: options?.exportAllObjectTypes
89
+ ? types
90
+ : null,
91
+ },
92
+ )};`;
93
+ const extraTypes: {[key: string]: string} = {};
94
+ Object.keys(types).forEach((k) => {
95
+ // eslint-disable-next-line flowtype-errors/uncovered
96
+ extraTypes[k] = generate(types[k]).code;
97
+ });
98
+ return {
99
+ name,
100
+ typeName: name,
101
+ code,
102
+ isFragment: true,
103
+ extraTypes,
104
+ };
105
+ }
71
106
  if (
72
107
  item.kind === 'OperationDefinition' &&
73
108
  (item.operation === 'query' || item.operation === 'mutation') &&
74
109
  item.name
75
110
  ) {
111
+ const types = {};
76
112
  const name = item.name.value;
77
- const response = generateResponseType(schema, item, config);
78
- const variables = generateVariablesType(schema, item, config);
113
+ const response = generateResponseType(schema, item, {
114
+ ...config,
115
+ path: [name],
116
+ allObjectTypes: options?.exportAllObjectTypes
117
+ ? types
118
+ : null,
119
+ });
120
+ const variables = generateVariablesType(schema, item, {
121
+ ...config,
122
+ path: [name],
123
+ });
79
124
 
80
125
  const typeName = `${name}Type`;
81
126
  // TODO(jared): Maybe make this template configurable?
82
127
  // We'll see what's required to get webapp on board.
83
128
  const code = `export type ${typeName} = {|\n variables: ${variables},\n response: ${response}\n|};`;
84
129
 
85
- return {name, typeName, code};
130
+ const extraTypes: {[key: string]: string} = {};
131
+ Object.keys(types).forEach((k) => {
132
+ // eslint-disable-next-line flowtype-errors/uncovered
133
+ extraTypes[k] = generate(types[k]).code;
134
+ });
135
+ return {name, typeName, code, extraTypes};
86
136
  }
87
137
  })
88
138
  .filter(Boolean);
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.js"],"names":["optionsToConfig","schema","definitions","options","errors","internalOptions","strictNullability","readOnlyArray","scalars","fragments","forEach","def","kind","name","value","config","FlowGenerationError","Error","constructor","join","messages","documentToFlowTypes","document","result","map","item","operation","response","variables","typeName","code","filter","Boolean","length"],"mappings":";;;;;;;;;;;;;AAWA;;AACA;;AACA;;AAbA;;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AASA,MAAMA,eAAe,GAAG,CACpBC,MADoB,EAEpBC,WAFoB,EAGpBC,OAHoB,EAIpBC,MAAqB,GAAG,EAJJ,KAKX;AACT,QAAMC,eAAe,GAAG;AACpBC,IAAAA,iBAAiB,EAAE,CAAAH,OAAO,SAAP,IAAAA,OAAO,WAAP,YAAAA,OAAO,CAAEG,iBAAT,KAA8B,IAD7B;AAEpBC,IAAAA,aAAa,EAAE,CAAAJ,OAAO,SAAP,IAAAA,OAAO,WAAP,YAAAA,OAAO,CAAEI,aAAT,KAA0B,IAFrB;AAGpBC,IAAAA,OAAO,EAAE,CAAAL,OAAO,SAAP,IAAAA,OAAO,WAAP,YAAAA,OAAO,CAAEK,OAAT,KAAoB;AAHT,GAAxB;AAKA,QAAMC,SAAS,GAAG,EAAlB;AACAP,EAAAA,WAAW,CAACQ,OAAZ,CAAqBC,GAAD,IAAS;AACzB,QAAIA,GAAG,CAACC,IAAJ,KAAa,oBAAjB,EAAuC;AACnCH,MAAAA,SAAS,CAACE,GAAG,CAACE,IAAJ,CAASC,KAAV,CAAT,GAA4BH,GAA5B;AACH;AACJ,GAJD;AAKA,QAAMI,MAAM,GAAG;AACXN,IAAAA,SADW;AAEXR,IAAAA,MAFW;AAGXG,IAAAA,MAHW;AAIX,OAAGC;AAJQ,GAAf;AAOA,SAAOU,MAAP;AACH,CAzBD;;AA2BO,MAAMC,mBAAN,SAAkCC,KAAlC,CAAwC;AAE3CC,EAAAA,WAAW,CAACd,MAAD,EAAwB;AAC/B,UAAO,wCAAuCA,MAAM,CAAC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@flow\n/**\n * This tool generates flowtype definitions from graphql queries.\n *\n * It relies on `introspection-query.json` existing in this directory,\n * which is produced by running `./tools/graphql-flow/sendIntrospection.js`.\n */\nimport type {DefinitionNode, DocumentNode} from 'graphql';\n\nimport {generateResponseType} from './generateResponseType';\nimport {generateVariablesType} from './generateVariablesType';\nexport {spyOnGraphqlTagToCollectQueries} from './jest-mock-graphql-tag';\n\nimport type {Config, Options, Schema} from './types';\n\nconst optionsToConfig = (\n schema: Schema,\n definitions: $ReadOnlyArray<DefinitionNode>,\n options?: Options,\n errors: Array<string> = [],\n): Config => {\n const internalOptions = {\n strictNullability: options?.strictNullability ?? true,\n readOnlyArray: options?.readOnlyArray ?? true,\n scalars: options?.scalars ?? {},\n };\n const fragments = {};\n definitions.forEach((def) => {\n if (def.kind === 'FragmentDefinition') {\n fragments[def.name.value] = def;\n }\n });\n const config = {\n fragments,\n schema,\n errors,\n ...internalOptions,\n };\n\n return config;\n};\n\nexport class FlowGenerationError extends Error {\n messages: Array<string>;\n constructor(errors: Array<string>) {\n super(`Graphql-flow type generation failed! ${errors.join('; ')}`);\n this.messages = errors;\n }\n}\n\nexport const documentToFlowTypes = (\n document: DocumentNode,\n schema: Schema,\n options?: Options,\n): $ReadOnlyArray<{\n name: string,\n typeName: string,\n code: string,\n}> => {\n const errors: Array<string> = [];\n const config = optionsToConfig(\n schema,\n document.definitions,\n options,\n errors,\n );\n const result = document.definitions\n .map((item) => {\n if (\n item.kind === 'OperationDefinition' &&\n (item.operation === 'query' || item.operation === 'mutation') &&\n item.name\n ) {\n const name = item.name.value;\n const response = generateResponseType(schema, item, config);\n const variables = generateVariablesType(schema, item, config);\n\n const typeName = `${name}Type`;\n // TODO(jared): Maybe make this template configurable?\n // We'll see what's required to get webapp on board.\n const code = `export type ${typeName} = {|\\n variables: ${variables},\\n response: ${response}\\n|};`;\n\n return {name, typeName, code};\n }\n })\n .filter(Boolean);\n if (errors.length) {\n throw new FlowGenerationError(errors);\n }\n return result;\n};\n"],"file":"index.js"}
1
+ {"version":3,"sources":["../src/index.js"],"names":["optionsToConfig","schema","definitions","options","errors","internalOptions","strictNullability","readOnlyArray","scalars","fragments","forEach","def","kind","name","value","config","allObjectTypes","path","FlowGenerationError","Error","constructor","join","messages","documentToFlowTypes","document","result","map","item","types","code","exportAllObjectTypes","extraTypes","Object","keys","k","typeName","isFragment","operation","response","variables","filter","Boolean","length"],"mappings":";;;;;;;;;;;;;AAWA;;AACA;;AAIA;;AACA;;;;AAjBA;;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AAGyC;AAUzC,MAAMA,eAAe,GAAG,CACpBC,MADoB,EAEpBC,WAFoB,EAGpBC,OAHoB,EAIpBC,MAAqB,GAAG,EAJJ,KAKX;AAAA;;AACT,QAAMC,eAAe,GAAG;AACpBC,IAAAA,iBAAiB,2BAAEH,OAAF,aAAEA,OAAF,uBAAEA,OAAO,CAAEG,iBAAX,yEAAgC,IAD7B;AAEpBC,IAAAA,aAAa,2BAAEJ,OAAF,aAAEA,OAAF,uBAAEA,OAAO,CAAEI,aAAX,yEAA4B,IAFrB;AAGpBC,IAAAA,OAAO,sBAAEL,OAAF,aAAEA,OAAF,uBAAEA,OAAO,CAAEK,OAAX,+DAAsB;AAHT,GAAxB;AAKA,QAAMC,SAAS,GAAG,EAAlB;AACAP,EAAAA,WAAW,CAACQ,OAAZ,CAAqBC,GAAD,IAAS;AACzB,QAAIA,GAAG,CAACC,IAAJ,KAAa,oBAAjB,EAAuC;AACnCH,MAAAA,SAAS,CAACE,GAAG,CAACE,IAAJ,CAASC,KAAV,CAAT,GAA4BH,GAA5B;AACH;AACJ,GAJD;AAKA,QAAMI,MAAM,GAAG;AACXN,IAAAA,SADW;AAEXR,IAAAA,MAFW;AAGXG,IAAAA,MAHW;AAIXY,IAAAA,cAAc,EAAE,IAJL;AAKXC,IAAAA,IAAI,EAAE,EALK;AAMX,OAAGZ;AANQ,GAAf;AASA,SAAOU,MAAP;AACH,CA3BD;;AA6BO,MAAMG,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S,MA7DU,CA6DHC,OA7DG,CAAf;;AA8DA,MAAIrC,MAAM,CAACsC,MAAX,EAAmB;AACf,UAAM,IAAIxB,mBAAJ,CAAwBd,MAAxB,CAAN;AACH;;AACD,SAAOqB,MAAP;AACH,CApFM","sourcesContent":["/* eslint-disable no-console */\n/* flow-uncovered-file */\n// @flow\n/**\n * This tool generates flowtype definitions from graphql queries.\n *\n * It relies on `introspection-query.json` existing in this directory,\n * which is produced by running `./tools/graphql-flow/sendIntrospection.js`.\n */\nimport type {DefinitionNode, DocumentNode} from 'graphql';\n\nimport generate from '@babel/generator'; // eslint-disable-line flowtype-errors/uncovered\nimport {\n generateFragmentType,\n generateResponseType,\n} from './generateResponseType';\nimport {generateVariablesType} from './generateVariablesType';\nexport {spyOnGraphqlTagToCollectQueries} from './jest-mock-graphql-tag';\n\nimport type {Config, Options, Schema} from './types';\n\nconst optionsToConfig = (\n schema: Schema,\n definitions: $ReadOnlyArray<DefinitionNode>,\n options?: Options,\n errors: Array<string> = [],\n): Config => {\n const internalOptions = {\n strictNullability: options?.strictNullability ?? true,\n readOnlyArray: options?.readOnlyArray ?? true,\n scalars: options?.scalars ?? {},\n };\n const fragments = {};\n definitions.forEach((def) => {\n if (def.kind === 'FragmentDefinition') {\n fragments[def.name.value] = def;\n }\n });\n const config = {\n fragments,\n schema,\n errors,\n allObjectTypes: null,\n path: [],\n ...internalOptions,\n };\n\n return config;\n};\n\nexport class FlowGenerationError extends Error {\n messages: Array<string>;\n constructor(errors: Array<string>) {\n super(`Graphql-flow type generation failed! ${errors.join('; ')}`);\n this.messages = errors;\n }\n}\n\nexport const documentToFlowTypes = (\n document: DocumentNode,\n schema: Schema,\n options?: Options,\n): $ReadOnlyArray<{\n name: string,\n typeName: string,\n code: string,\n isFragment?: boolean,\n extraTypes: {[key: string]: string},\n}> => {\n const errors: Array<string> = [];\n const config = optionsToConfig(\n schema,\n document.definitions,\n options,\n errors,\n );\n const result = document.definitions\n .map((item) => {\n if (item.kind === 'FragmentDefinition') {\n const name = item.name.value;\n const types = {};\n const code = `export type ${name} = ${generateFragmentType(\n schema,\n item,\n {\n ...config,\n path: [name],\n allObjectTypes: options?.exportAllObjectTypes\n ? types\n : null,\n },\n )};`;\n const extraTypes: {[key: string]: string} = {};\n Object.keys(types).forEach((k) => {\n // eslint-disable-next-line flowtype-errors/uncovered\n extraTypes[k] = generate(types[k]).code;\n });\n return {\n name,\n typeName: name,\n code,\n isFragment: true,\n extraTypes,\n };\n }\n if (\n item.kind === 'OperationDefinition' &&\n (item.operation === 'query' || item.operation === 'mutation') &&\n item.name\n ) {\n const types = {};\n const name = item.name.value;\n const response = generateResponseType(schema, item, {\n ...config,\n path: [name],\n allObjectTypes: options?.exportAllObjectTypes\n ? types\n : null,\n });\n const variables = generateVariablesType(schema, item, {\n ...config,\n path: [name],\n });\n\n const typeName = `${name}Type`;\n // TODO(jared): Maybe make this template configurable?\n // We'll see what's required to get webapp on board.\n const code = `export type ${typeName} = {|\\n variables: ${variables},\\n response: ${response}\\n|};`;\n\n const extraTypes: {[key: string]: string} = {};\n Object.keys(types).forEach((k) => {\n // eslint-disable-next-line flowtype-errors/uncovered\n extraTypes[k] = generate(types[k]).code;\n });\n return {name, typeName, code, extraTypes};\n }\n })\n .filter(Boolean);\n if (errors.length) {\n throw new FlowGenerationError(errors);\n }\n return result;\n};\n"],"file":"index.js"}