@depup/graphql-codegen__cli 6.2.1-depup.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/README.md +51 -0
  2. package/changes.json +90 -0
  3. package/cjs/bin.js +13 -0
  4. package/cjs/cli.js +64 -0
  5. package/cjs/codegen.js +388 -0
  6. package/cjs/config.js +370 -0
  7. package/cjs/documentTransforms.js +63 -0
  8. package/cjs/generate-and-save.js +153 -0
  9. package/cjs/graphql-config.js +67 -0
  10. package/cjs/hooks.js +93 -0
  11. package/cjs/index.js +13 -0
  12. package/cjs/init/helpers.js +90 -0
  13. package/cjs/init/index.js +62 -0
  14. package/cjs/init/plugins.js +136 -0
  15. package/cjs/init/questions.js +177 -0
  16. package/cjs/init/targets.js +45 -0
  17. package/cjs/init/types.js +15 -0
  18. package/cjs/load.js +102 -0
  19. package/cjs/package.json +1 -0
  20. package/cjs/plugins.js +43 -0
  21. package/cjs/presets.js +50 -0
  22. package/cjs/utils/abort-controller-polyfill.js +99 -0
  23. package/cjs/utils/cli-error.js +24 -0
  24. package/cjs/utils/debugging.js +22 -0
  25. package/cjs/utils/file-system.js +24 -0
  26. package/cjs/utils/get-latest-version.js +14 -0
  27. package/cjs/utils/helpers.js +12 -0
  28. package/cjs/utils/logger.js +24 -0
  29. package/cjs/utils/patterns.js +235 -0
  30. package/cjs/utils/watcher.js +244 -0
  31. package/esm/bin.js +11 -0
  32. package/esm/cli.js +37 -0
  33. package/esm/codegen.js +384 -0
  34. package/esm/config.js +357 -0
  35. package/esm/documentTransforms.js +59 -0
  36. package/esm/generate-and-save.js +149 -0
  37. package/esm/graphql-config.js +62 -0
  38. package/esm/hooks.js +89 -0
  39. package/esm/index.js +7 -0
  40. package/esm/init/helpers.js +82 -0
  41. package/esm/init/index.js +59 -0
  42. package/esm/init/plugins.js +133 -0
  43. package/esm/init/questions.js +172 -0
  44. package/esm/init/targets.js +42 -0
  45. package/esm/init/types.js +12 -0
  46. package/esm/load.js +97 -0
  47. package/esm/plugins.js +40 -0
  48. package/esm/presets.js +47 -0
  49. package/esm/utils/abort-controller-polyfill.js +96 -0
  50. package/esm/utils/cli-error.js +20 -0
  51. package/esm/utils/debugging.js +17 -0
  52. package/esm/utils/file-system.js +17 -0
  53. package/esm/utils/get-latest-version.js +11 -0
  54. package/esm/utils/helpers.js +9 -0
  55. package/esm/utils/logger.js +18 -0
  56. package/esm/utils/patterns.js +226 -0
  57. package/esm/utils/watcher.js +239 -0
  58. package/package.json +205 -0
  59. package/typings/bin.d.cts +2 -0
  60. package/typings/bin.d.ts +2 -0
  61. package/typings/cli.d.cts +2 -0
  62. package/typings/cli.d.ts +2 -0
  63. package/typings/codegen.d.cts +6 -0
  64. package/typings/codegen.d.ts +6 -0
  65. package/typings/config.d.cts +152 -0
  66. package/typings/config.d.ts +152 -0
  67. package/typings/documentTransforms.d.cts +3 -0
  68. package/typings/documentTransforms.d.ts +3 -0
  69. package/typings/generate-and-save.d.cts +10 -0
  70. package/typings/generate-and-save.d.ts +10 -0
  71. package/typings/graphql-config.d.cts +3 -0
  72. package/typings/graphql-config.d.ts +3 -0
  73. package/typings/hooks.d.cts +11 -0
  74. package/typings/hooks.d.ts +11 -0
  75. package/typings/index.d.cts +8 -0
  76. package/typings/index.d.ts +8 -0
  77. package/typings/init/helpers.d.cts +10 -0
  78. package/typings/init/helpers.d.ts +10 -0
  79. package/typings/init/index.d.cts +1 -0
  80. package/typings/init/index.d.ts +1 -0
  81. package/typings/init/plugins.d.cts +2 -0
  82. package/typings/init/plugins.d.ts +2 -0
  83. package/typings/init/questions.d.cts +13 -0
  84. package/typings/init/questions.d.ts +13 -0
  85. package/typings/init/targets.d.cts +2 -0
  86. package/typings/init/targets.d.ts +2 -0
  87. package/typings/init/types.d.cts +30 -0
  88. package/typings/init/types.d.ts +30 -0
  89. package/typings/load.d.cts +15 -0
  90. package/typings/load.d.ts +15 -0
  91. package/typings/plugins.d.cts +2 -0
  92. package/typings/plugins.d.ts +2 -0
  93. package/typings/presets.d.cts +5 -0
  94. package/typings/presets.d.ts +5 -0
  95. package/typings/utils/abort-controller-polyfill.d.cts +5 -0
  96. package/typings/utils/abort-controller-polyfill.d.ts +5 -0
  97. package/typings/utils/cli-error.d.cts +10 -0
  98. package/typings/utils/cli-error.d.ts +10 -0
  99. package/typings/utils/debugging.d.cts +3 -0
  100. package/typings/utils/debugging.d.ts +3 -0
  101. package/typings/utils/file-system.d.cts +8 -0
  102. package/typings/utils/file-system.d.ts +8 -0
  103. package/typings/utils/get-latest-version.d.cts +6 -0
  104. package/typings/utils/get-latest-version.d.ts +6 -0
  105. package/typings/utils/helpers.d.cts +1 -0
  106. package/typings/utils/helpers.d.ts +1 -0
  107. package/typings/utils/logger.d.cts +5 -0
  108. package/typings/utils/logger.d.ts +5 -0
  109. package/typings/utils/patterns.d.cts +91 -0
  110. package/typings/utils/patterns.d.ts +91 -0
  111. package/typings/utils/watcher.d.cts +16 -0
  112. package/typings/utils/watcher.d.ts +16 -0
@@ -0,0 +1,244 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createWatcher = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const path_1 = require("path");
6
+ const plugin_helpers_1 = require("@graphql-codegen/plugin-helpers");
7
+ const debounce_1 = tslib_1.__importDefault(require("debounce"));
8
+ const micromatch_1 = tslib_1.__importDefault(require("micromatch"));
9
+ const log_symbols_1 = tslib_1.__importDefault(require("log-symbols"));
10
+ const codegen_js_1 = require("../codegen.js");
11
+ const config_js_1 = require("../config.js");
12
+ const hooks_js_1 = require("../hooks.js");
13
+ const file_system_js_1 = require("./file-system.js");
14
+ const debugging_js_1 = require("./debugging.js");
15
+ const logger_js_1 = require("./logger.js");
16
+ const patterns_js_1 = require("./patterns.js");
17
+ const abort_controller_polyfill_js_1 = require("./abort-controller-polyfill.js");
18
+ function log(msg) {
19
+ // double spaces to inline the message with Listr
20
+ (0, logger_js_1.getLogger)().info(` ${msg}`);
21
+ }
22
+ function emitWatching(watchDir) {
23
+ log(`${log_symbols_1.default.info} Watching for changes in ${watchDir}...`);
24
+ }
25
+ const createWatcher = (initialContext, onNext) => {
26
+ (0, debugging_js_1.debugLog)(`[Watcher] Starting watcher...`);
27
+ let config = initialContext.getConfig();
28
+ const globalPatternSet = (0, patterns_js_1.makeGlobalPatternSet)(initialContext);
29
+ const localPatternSets = Object.keys(config.generates)
30
+ .map(filename => (0, plugin_helpers_1.normalizeOutputParam)(config.generates[filename]))
31
+ .map(conf => (0, patterns_js_1.makeLocalPatternSet)(conf));
32
+ const allAffirmativePatterns = (0, patterns_js_1.allAffirmativePatternsFromPatternSets)([globalPatternSet, ...localPatternSets]);
33
+ const shouldRebuild = (0, patterns_js_1.makeShouldRebuild)({ globalPatternSet, localPatternSets });
34
+ let watcherSubscription;
35
+ const runWatcher = async (abortSignal) => {
36
+ const watchDirectory = await findHighestCommonDirectory(allAffirmativePatterns);
37
+ // Try to load the parcel watcher, but don't fail if it's not available.
38
+ let parcelWatcher;
39
+ try {
40
+ parcelWatcher = await Promise.resolve().then(() => tslib_1.__importStar(require('@parcel/watcher')));
41
+ }
42
+ catch {
43
+ log('Failed to import @parcel/watcher.\n To use watch mode, install https://www.npmjs.com/package/@parcel/watcher.');
44
+ return;
45
+ }
46
+ (0, debugging_js_1.debugLog)(`[Watcher] Parcel watcher loaded...`);
47
+ let isShutdown = false;
48
+ const debouncedExec = (0, debounce_1.default)(() => {
49
+ if (!isShutdown) {
50
+ (0, codegen_js_1.executeCodegen)(initialContext)
51
+ .then(({ result, error }) => {
52
+ // FIXME: this is a quick fix to stop `onNext` (writeOutput) from
53
+ // removing all files when there is an error.
54
+ //
55
+ // This is because `removeStaleFiles()` will remove files if the
56
+ // generated files are different between runs. And on error, it
57
+ // returns an empty array i.e. will remove all generated files from
58
+ // the previous run
59
+ //
60
+ // This also means we don't have config.allowPartialOutputs in watch mode
61
+ if (error) {
62
+ return;
63
+ }
64
+ onNext(result);
65
+ }, () => Promise.resolve())
66
+ .then(() => emitWatching(watchDirectory));
67
+ }
68
+ }, 100);
69
+ emitWatching(watchDirectory);
70
+ const ignored = ['**/.git/**'];
71
+ for (const entry of Object.keys(config.generates).map(filename => ({
72
+ filename,
73
+ config: (0, plugin_helpers_1.normalizeOutputParam)(config.generates[filename]),
74
+ }))) {
75
+ // ParcelWatcher expects relative ignore patterns to be relative from watchDirectory,
76
+ // but we expect filename from config to be relative from cwd, so we need to convert
77
+ const filenameRelativeFromWatchDirectory = (0, path_1.relative)(watchDirectory, (0, path_1.resolve)(process.cwd(), entry.filename));
78
+ if (entry.config.preset) {
79
+ const extension = entry.config.presetConfig?.extension;
80
+ if (extension) {
81
+ ignored.push((0, path_1.join)(filenameRelativeFromWatchDirectory, '**', '*' + extension));
82
+ }
83
+ }
84
+ else {
85
+ ignored.push(filenameRelativeFromWatchDirectory);
86
+ }
87
+ }
88
+ watcherSubscription = await parcelWatcher.subscribe(watchDirectory, async (_, events) => {
89
+ // it doesn't matter what has changed, need to run whole process anyway
90
+ await Promise.all(
91
+ // NOTE: @parcel/watcher always provides path as an absolute path
92
+ events.map(async ({ type: eventName, path }) => {
93
+ if (!shouldRebuild({ path })) {
94
+ return;
95
+ }
96
+ (0, hooks_js_1.lifecycleHooks)(config.hooks).onWatchTriggered(eventName, path);
97
+ (0, debugging_js_1.debugLog)(`[Watcher] triggered due to a file ${eventName} event: ${path}`);
98
+ // In ESM require is not defined
99
+ try {
100
+ delete require.cache[path];
101
+ }
102
+ catch { }
103
+ if (eventName === 'update' && config.configFilePath && path === config.configFilePath) {
104
+ log(`${log_symbols_1.default.info} Config file has changed, reloading...`);
105
+ const context = await (0, config_js_1.loadContext)(config.configFilePath);
106
+ const newParsedConfig = context.getConfig();
107
+ newParsedConfig.watch = config.watch;
108
+ newParsedConfig.silent = config.silent;
109
+ newParsedConfig.overwrite = config.overwrite;
110
+ newParsedConfig.configFilePath = config.configFilePath;
111
+ config = newParsedConfig;
112
+ initialContext.updateConfig(config);
113
+ }
114
+ debouncedExec();
115
+ }));
116
+ }, { ignore: ignored });
117
+ (0, debugging_js_1.debugLog)(`[Watcher] Started`);
118
+ const shutdown = (
119
+ /** Optional callback to execute after shutdown has completed its async tasks */
120
+ afterShutdown) => {
121
+ isShutdown = true;
122
+ (0, debugging_js_1.debugLog)(`[Watcher] Shutting down`);
123
+ log(`Shutting down watch...`);
124
+ const pendingUnsubscribe = watcherSubscription.unsubscribe();
125
+ const pendingBeforeDoneHook = (0, hooks_js_1.lifecycleHooks)(config.hooks).beforeDone();
126
+ if (afterShutdown && typeof afterShutdown === 'function') {
127
+ Promise.allSettled([pendingUnsubscribe, pendingBeforeDoneHook]).then(afterShutdown);
128
+ }
129
+ };
130
+ abortSignal.addEventListener('abort', () => shutdown(abortSignal.reason));
131
+ process.once('SIGINT', () => shutdown());
132
+ process.once('SIGTERM', () => shutdown());
133
+ };
134
+ // Use an AbortController for shutdown signals
135
+ // NOTE: This will be polyfilled on Node 14 (or any environment without it defined)
136
+ const abortController = new abort_controller_polyfill_js_1.AbortController();
137
+ /**
138
+ * Send shutdown signal and return a promise that only resolves after the
139
+ * runningWatcher has resolved, which only resolved after the shutdown signal has been handled
140
+ */
141
+ const stopWatching = async function () {
142
+ // stopWatching.afterShutdown is lazily set to resolve pendingShutdown promise
143
+ abortController.abort(stopWatching.afterShutdown);
144
+ // SUBTLE: runningWatcher waits for pendingShutdown before it resolves itself, so
145
+ // by awaiting it here, we are awaiting both the shutdown handler, and runningWatcher itself
146
+ await stopWatching.runningWatcher;
147
+ };
148
+ stopWatching.afterShutdown = () => {
149
+ (0, debugging_js_1.debugLog)('Shutdown watcher before it started');
150
+ };
151
+ stopWatching.runningWatcher = Promise.resolve();
152
+ /** Promise will resolve after the shutdown() handler completes */
153
+ const pendingShutdown = new Promise(afterShutdown => {
154
+ // afterShutdown will be passed to shutdown() handler via abortSignal.reason
155
+ stopWatching.afterShutdown = afterShutdown;
156
+ });
157
+ /**
158
+ * Promise that resolves after the watch server has shutdown, either because
159
+ * stopWatching() was called or there was an error inside it
160
+ */
161
+ stopWatching.runningWatcher = new Promise((resolve, reject) => {
162
+ (0, codegen_js_1.executeCodegen)(initialContext)
163
+ .then(({ result, error }) => {
164
+ // TODO: this is the initial run, the logic here mimics the above watcher logic.
165
+ // We need to check whether it's ok to deviate between these two.
166
+ if (error) {
167
+ return;
168
+ }
169
+ onNext(result);
170
+ }, () => Promise.resolve())
171
+ .then(() => runWatcher(abortController.signal))
172
+ .catch(err => {
173
+ watcherSubscription.unsubscribe();
174
+ reject(err);
175
+ })
176
+ .then(() => pendingShutdown)
177
+ .finally(() => {
178
+ (0, debugging_js_1.debugLog)('Done watching.');
179
+ resolve();
180
+ });
181
+ });
182
+ return {
183
+ stopWatching,
184
+ runningWatcher: stopWatching.runningWatcher,
185
+ };
186
+ };
187
+ exports.createWatcher = createWatcher;
188
+ /**
189
+ * Given a list of file paths (each of which may be absolute, or relative from
190
+ * `process.cwd()`), find absolute path of the "highest" common directory,
191
+ * i.e. the directory that contains all the files in the list.
192
+ *
193
+ * @param files List of relative and/or absolute file paths (or micromatch patterns)
194
+ */
195
+ const findHighestCommonDirectory = async (files) => {
196
+ // Map files to a list of basePaths, where "base" is the result of mm.scan(pathOrPattern)
197
+ // e.g. mm.scan("/**/foo/bar").base -> "/" ; mm.scan("/foo/bar/**/fizz/*.graphql") -> /foo/bar
198
+ const dirPaths = files
199
+ .map(filePath => ((0, path_1.isAbsolute)(filePath) ? filePath : (0, path_1.resolve)(filePath)))
200
+ // mm.scan doesn't know how to handle Windows \ path separator
201
+ .map(patterned => patterned.replace(/\\/g, '/'))
202
+ .map(patterned => micromatch_1.default.scan(patterned).base)
203
+ // revert the separators to the platform-supported ones
204
+ .map(base => base.replace(/\//g, path_1.sep));
205
+ // Return longest common prefix if it's accessible, otherwise process.cwd()
206
+ return (async (maybeValidPath) => {
207
+ (0, debugging_js_1.debugLog)(`[Watcher] Longest common prefix of all files: ${maybeValidPath}...`);
208
+ try {
209
+ await (0, file_system_js_1.access)(maybeValidPath);
210
+ return maybeValidPath;
211
+ }
212
+ catch {
213
+ log(`[Watcher] Longest common prefix (${maybeValidPath}) is not accessible`);
214
+ log(`[Watcher] Watching current working directory (${process.cwd()}) instead`);
215
+ return process.cwd();
216
+ }
217
+ })(longestCommonPrefix(dirPaths.map(path => path.split(path_1.sep))).join(path_1.sep));
218
+ };
219
+ /**
220
+ * Find the longest common prefix of an array of paths, where each item in
221
+ * the array an array of path segments which comprise an absolute path when
222
+ * joined together by a path separator
223
+ *
224
+ * Adapted from:
225
+ * https://duncan-mcardle.medium.com/leetcode-problem-14-longest-common-prefix-javascript-3bc6a2f777c4
226
+ *
227
+ * @param splitPaths An array of arrays, where each item is a path split by its separator
228
+ * @returns An array of path segments representing the longest common prefix of splitPaths
229
+ */
230
+ const longestCommonPrefix = (splitPaths) => {
231
+ // Return early on empty input
232
+ if (!splitPaths.length) {
233
+ return [];
234
+ }
235
+ // Loop through the segments of the first path
236
+ for (let i = 0; i <= splitPaths[0].length; i++) {
237
+ // Check if this path segment is present in the same position of every path
238
+ if (!splitPaths.every(string => string[i] === splitPaths[0][i])) {
239
+ // If not, return the path segments up to and including the previous segment
240
+ return splitPaths[0].slice(0, i);
241
+ }
242
+ }
243
+ return splitPaths[0];
244
+ };
package/esm/bin.js ADDED
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+ import { runCli } from './cli.js';
3
+ import { cliError } from './utils/cli-error.js';
4
+ const [, , cmd] = process.argv;
5
+ runCli(cmd)
6
+ .then(returnCode => {
7
+ process.exit(returnCode);
8
+ })
9
+ .catch(error => {
10
+ cliError(error);
11
+ });
package/esm/cli.js ADDED
@@ -0,0 +1,37 @@
1
+ import { createContext } from './config.js';
2
+ import { generate } from './generate-and-save.js';
3
+ import { lifecycleHooks } from './hooks.js';
4
+ import { init } from './init/index.js';
5
+ export async function runCli(cmd) {
6
+ await ensureGraphQlPackage();
7
+ if (cmd === 'init') {
8
+ await init();
9
+ return 0;
10
+ }
11
+ const context = await createContext();
12
+ try {
13
+ await generate(context);
14
+ if (context.checkMode && context.checkModeStaleFiles.length > 0) {
15
+ // eslint-disable-next-line no-console
16
+ console.log(`The following stale files were detected:\n${context.checkModeStaleFiles.map(file => ` - ${file}\n`)}`);
17
+ return 1;
18
+ }
19
+ return 0;
20
+ }
21
+ catch (error) {
22
+ await lifecycleHooks(context.getConfig().hooks).onError(error.toString());
23
+ return 1;
24
+ }
25
+ }
26
+ export async function ensureGraphQlPackage() {
27
+ try {
28
+ await import('graphql');
29
+ }
30
+ catch {
31
+ throw new Error(`Unable to load "graphql" package. Please make sure to install "graphql" as a dependency! \n
32
+ To install "graphql", run:
33
+ yarn add graphql
34
+ Or, with NPM:
35
+ npm install --save graphql`);
36
+ }
37
+ }