@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
package/esm/load.js ADDED
@@ -0,0 +1,97 @@
1
+ import { extname, join } from 'path';
2
+ import { ApolloEngineLoader } from '@graphql-tools/apollo-engine-loader';
3
+ import { CodeFileLoader } from '@graphql-tools/code-file-loader';
4
+ import { GitLoader } from '@graphql-tools/git-loader';
5
+ import { GithubLoader } from '@graphql-tools/github-loader';
6
+ import { GraphQLFileLoader } from '@graphql-tools/graphql-file-loader';
7
+ import { JsonFileLoader } from '@graphql-tools/json-file-loader';
8
+ import { loadDocuments as loadDocumentsToolkit, loadSchema as loadSchemaToolkit, NoTypeDefinitionsFound, } from '@graphql-tools/load';
9
+ import { UrlLoader } from '@graphql-tools/url-loader';
10
+ import { GraphQLError } from 'graphql';
11
+ export const defaultSchemaLoadOptions = {
12
+ assumeValidSDL: true,
13
+ sort: true,
14
+ convertExtensions: true,
15
+ includeSources: true,
16
+ };
17
+ export const defaultDocumentsLoadOptions = {
18
+ sort: true,
19
+ skipGraphQLImport: true,
20
+ };
21
+ export async function loadSchema(schemaPointers, config) {
22
+ try {
23
+ const loaders = [
24
+ new CodeFileLoader(),
25
+ new GitLoader(),
26
+ new GithubLoader(),
27
+ new GraphQLFileLoader(),
28
+ new JsonFileLoader(),
29
+ new UrlLoader(),
30
+ new ApolloEngineLoader(),
31
+ ];
32
+ const schema = await loadSchemaToolkit(schemaPointers, {
33
+ ...defaultSchemaLoadOptions,
34
+ loaders,
35
+ ...config,
36
+ ...config.config,
37
+ });
38
+ return schema;
39
+ }
40
+ catch (e) {
41
+ throw new Error([
42
+ `Failed to load schema from ${Object.keys(schemaPointers).join(',')}:`,
43
+ printError(e),
44
+ '\nGraphQL Code Generator supports:',
45
+ '\n- ES Modules and CommonJS exports (export as default or named export "schema")',
46
+ '- Introspection JSON File',
47
+ '- URL of GraphQL endpoint',
48
+ '- Multiple files with type definitions (glob expression)',
49
+ '- String in config file',
50
+ '\nTry to use one of above options and run codegen again.\n',
51
+ ].join('\n'));
52
+ }
53
+ }
54
+ export async function loadDocuments(documentPointers, config) {
55
+ const loaders = [
56
+ new CodeFileLoader({
57
+ pluckConfig: {
58
+ skipIndent: true,
59
+ },
60
+ }),
61
+ new GitLoader(),
62
+ new GithubLoader(),
63
+ new GraphQLFileLoader(),
64
+ ];
65
+ const ignore = [];
66
+ for (const generatePath of Object.keys(config.generates)) {
67
+ if (extname(generatePath) === '') {
68
+ // we omit paths that don't resolve to a specific file
69
+ continue;
70
+ }
71
+ ignore.push(join(process.cwd(), generatePath));
72
+ }
73
+ try {
74
+ const loadedFromToolkit = await loadDocumentsToolkit(documentPointers, {
75
+ ...defaultDocumentsLoadOptions,
76
+ ignore,
77
+ loaders,
78
+ ...config,
79
+ ...config.config,
80
+ });
81
+ return loadedFromToolkit;
82
+ }
83
+ catch (error) {
84
+ // NoTypeDefinitionsFound from `@graphql-tools/load` already has a message with pointer, so we can just rethrow the error
85
+ if (error instanceof NoTypeDefinitionsFound) {
86
+ throw error;
87
+ }
88
+ // For other errors, we need to add an error message with documentPointers, so it's better for DevX
89
+ throw new Error([`Failed to load documents from ${Object.keys(documentPointers).join(',')}:`, printError(error)].join('\n'));
90
+ }
91
+ }
92
+ const printError = (error) => {
93
+ if (error instanceof GraphQLError) {
94
+ return String(error);
95
+ }
96
+ return [String(error.message || error), String(error.stack)].join('\n');
97
+ };
package/esm/plugins.js ADDED
@@ -0,0 +1,40 @@
1
+ import { resolve } from 'path';
2
+ export async function getPluginByName(name, pluginLoader) {
3
+ const possibleNames = [
4
+ `@graphql-codegen/${name}`,
5
+ `@graphql-codegen/${name}-template`,
6
+ `@graphql-codegen/${name}-plugin`,
7
+ `graphql-codegen-${name}`,
8
+ `graphql-codegen-${name}-template`,
9
+ `graphql-codegen-${name}-plugin`,
10
+ `codegen-${name}`,
11
+ `codegen-${name}-template`,
12
+ name,
13
+ ];
14
+ const possibleModules = possibleNames.concat(resolve(process.cwd(), name));
15
+ for (const moduleName of possibleModules) {
16
+ try {
17
+ return await pluginLoader(moduleName);
18
+ }
19
+ catch (err) {
20
+ if (err.code !== 'MODULE_NOT_FOUND' && err.code !== 'ERR_MODULE_NOT_FOUND') {
21
+ throw new Error(`
22
+ Unable to load template plugin matching '${name}'.
23
+ Reason:
24
+ ${err.message}
25
+ `);
26
+ }
27
+ }
28
+ }
29
+ const possibleNamesMsg = possibleNames
30
+ .map(name => `
31
+ - ${name}
32
+ `.trimEnd())
33
+ .join('');
34
+ throw new Error(`
35
+ Unable to find template plugin matching '${name}'
36
+ Install one of the following packages:
37
+
38
+ ${possibleNamesMsg}
39
+ `);
40
+ }
package/esm/presets.js ADDED
@@ -0,0 +1,47 @@
1
+ import { resolve } from 'path';
2
+ export async function getPresetByName(name, loader) {
3
+ const possibleNames = [
4
+ `@graphql-codegen/${name}`,
5
+ `@graphql-codegen/${name}-preset`,
6
+ name,
7
+ resolve(process.cwd(), name),
8
+ ];
9
+ for (const moduleName of possibleNames) {
10
+ try {
11
+ const loaded = await loader(moduleName);
12
+ if (loaded?.preset) {
13
+ return loaded.preset;
14
+ }
15
+ if (loaded?.default) {
16
+ return loaded.default;
17
+ }
18
+ return loaded;
19
+ }
20
+ catch (err) {
21
+ if (
22
+ /** CJS Error code */
23
+ err.code !== 'MODULE_NOT_FOUND' &&
24
+ /** ESM Error code */
25
+ err.code !== 'ERR_MODULE_NOT_FOUND') {
26
+ throw new Error(`Unable to load preset matching ${name}
27
+
28
+ Unable to load preset matching '${name}'.
29
+ Reason:
30
+ ${err.message}
31
+ `);
32
+ }
33
+ }
34
+ }
35
+ const possibleNamesMsg = possibleNames
36
+ .map(name => `
37
+ - ${name}
38
+ `.trimEnd())
39
+ .join('');
40
+ throw new Error(`Unable to find preset matching ${name}
41
+
42
+ Unable to find preset matching '${name}'
43
+ Install one of the following packages:
44
+
45
+ ${possibleNamesMsg}
46
+ `);
47
+ }
@@ -0,0 +1,96 @@
1
+ import { EventEmitter } from 'events';
2
+ import { debugLog } from './debugging.js';
3
+ /**
4
+ * Node v14 does not have AbortSignal or AbortController, so to safely use it in
5
+ * another module, you can import it from here.
6
+ *
7
+ * Node v14.7+ does have it, but only with flag --experimental-abortcontroller
8
+ *
9
+ * We don't actually use AbortController anywhere except in tests, but it
10
+ * still gets called in watcher.ts, so by polyfilling it we can avoid breaking
11
+ * existing installations using Node v14 without flag --experimental-abortcontroller,
12
+ * and we also ensure that tests continue to pass under Node v14 without any new flags.
13
+ *
14
+ * This polyfill was adapted (TypeScript-ified) from here:
15
+ * https://github.com/southpolesteve/node-abort-controller/blob/master/index.js
16
+ */
17
+ class AbortSignalPolyfill {
18
+ eventEmitter;
19
+ onabort;
20
+ aborted;
21
+ reason;
22
+ constructor() {
23
+ this.eventEmitter = new EventEmitter();
24
+ this.onabort = null;
25
+ this.aborted = false;
26
+ this.reason = undefined;
27
+ }
28
+ toString() {
29
+ return '[object AbortSignal]';
30
+ }
31
+ get [Symbol.toStringTag]() {
32
+ return 'AbortSignal';
33
+ }
34
+ removeEventListener(name, handler) {
35
+ this.eventEmitter.removeListener(name, handler);
36
+ }
37
+ addEventListener(name, handler) {
38
+ this.eventEmitter.on(name, handler);
39
+ }
40
+ // @ts-expect-error No Event type in Node 14
41
+ dispatchEvent(type) {
42
+ const event = { type, target: this };
43
+ const handlerName = `on${event.type}`;
44
+ if (typeof this[handlerName] === 'function')
45
+ this[handlerName](event);
46
+ return this.eventEmitter.emit(event.type, event);
47
+ }
48
+ throwIfAborted() {
49
+ if (this.aborted) {
50
+ throw this.reason;
51
+ }
52
+ }
53
+ static abort(reason) {
54
+ const controller = new AbortController();
55
+ controller.abort(reason);
56
+ return controller.signal;
57
+ }
58
+ static timeout(time) {
59
+ const controller = new AbortController();
60
+ setTimeout(() => controller.abort(new Error('TimeoutError')), time);
61
+ return controller.signal;
62
+ }
63
+ }
64
+ const AbortSignal = global.AbortSignal ?? AbortSignalPolyfill;
65
+ class AbortControllerPolyfill {
66
+ signal;
67
+ constructor() {
68
+ debugLog('Using polyfilled AbortController');
69
+ // @ts-expect-error No Event type in Node 14
70
+ this.signal = new AbortSignal();
71
+ }
72
+ abort(reason) {
73
+ if (this.signal.aborted)
74
+ return;
75
+ // @ts-expect-error Not a read only property when polyfilling
76
+ this.signal.aborted = true;
77
+ if (reason) {
78
+ // @ts-expect-error Not a read only property when polyfilling
79
+ this.signal.reason = reason;
80
+ }
81
+ else {
82
+ // @ts-expect-error Not a read only property when polyfilling
83
+ this.signal.reason = new Error('AbortError');
84
+ }
85
+ // @ts-expect-error No Event type in Node 14
86
+ this.signal.dispatchEvent('abort');
87
+ }
88
+ toString() {
89
+ return '[object AbortController]';
90
+ }
91
+ get [Symbol.toStringTag]() {
92
+ return 'AbortController';
93
+ }
94
+ }
95
+ const AbortController = global.AbortController ?? AbortControllerPolyfill;
96
+ export { AbortController };
@@ -0,0 +1,20 @@
1
+ export function isListrError(err) {
2
+ return err.name === 'ListrError' && Array.isArray(err.errors) && err.errors.length > 0;
3
+ }
4
+ export function cliError(err, exitOnError = true) {
5
+ let msg;
6
+ if (err instanceof Error) {
7
+ msg = err;
8
+ }
9
+ else if (typeof err === 'string') {
10
+ msg = err;
11
+ }
12
+ else {
13
+ msg = JSON.stringify(err);
14
+ }
15
+ // eslint-disable-next-line no-console
16
+ console.error(msg);
17
+ if (exitOnError) {
18
+ process.exit(1);
19
+ }
20
+ }
@@ -0,0 +1,17 @@
1
+ import { getLogger } from './logger.js';
2
+ let queue = [];
3
+ export function debugLog(message, ...meta) {
4
+ queue.push({
5
+ message,
6
+ meta,
7
+ });
8
+ }
9
+ export function printLogs() {
10
+ for (const log of queue) {
11
+ getLogger().info(log.message, ...log.meta);
12
+ }
13
+ resetLogs();
14
+ }
15
+ export function resetLogs() {
16
+ queue = [];
17
+ }
@@ -0,0 +1,17 @@
1
+ import { promises, unlink as fsUnlink } from 'fs';
2
+ const { access: fsAccess, writeFile: fsWriteFile, readFile: fsReadFile, mkdir } = promises;
3
+ export function access(...args) {
4
+ return fsAccess(...args);
5
+ }
6
+ export function writeFile(filepath, content) {
7
+ return fsWriteFile(filepath, content);
8
+ }
9
+ export function readFile(filepath) {
10
+ return fsReadFile(filepath, 'utf-8');
11
+ }
12
+ export function unlinkFile(filePath, cb) {
13
+ fsUnlink(filePath, cb);
14
+ }
15
+ export function mkdirp(filePath) {
16
+ return mkdir(filePath, { recursive: true });
17
+ }
@@ -0,0 +1,11 @@
1
+ import { fetch } from '@whatwg-node/fetch';
2
+ /**
3
+ * Fetches the version directly from the registry instead of depending on
4
+ * an ESM only module as latest-version does.
5
+ * @param packageName
6
+ */
7
+ export async function getLatestVersion(packageName) {
8
+ return fetch(`https://unpkg.com/${packageName}/package.json`)
9
+ .then(res => res.json())
10
+ .then(pkg => pkg.version);
11
+ }
@@ -0,0 +1,9 @@
1
+ export function isURL(str) {
2
+ try {
3
+ const url = new URL(str);
4
+ return !!url;
5
+ }
6
+ catch {
7
+ return false;
8
+ }
9
+ }
@@ -0,0 +1,18 @@
1
+ import { dummyLogger } from 'ts-log';
2
+ let logger;
3
+ export function getLogger() {
4
+ return logger || dummyLogger;
5
+ }
6
+ useWinstonLogger();
7
+ export function setLogger(newLogger) {
8
+ logger = newLogger;
9
+ }
10
+ export function setSilentLogger() {
11
+ logger = dummyLogger;
12
+ }
13
+ export function useWinstonLogger() {
14
+ if (logger?.levels) {
15
+ return;
16
+ }
17
+ logger = console;
18
+ }
@@ -0,0 +1,226 @@
1
+ import { isAbsolute, relative } from 'path';
2
+ import { isValidPath } from '@graphql-tools/utils';
3
+ import { normalizeInstanceOrArray } from '@graphql-codegen/plugin-helpers';
4
+ import isGlob from 'is-glob';
5
+ import mm from 'micromatch';
6
+ import { isURL } from './helpers.js';
7
+ /**
8
+ * Flatten a list of pattern sets to be a list of only the affirmative patterns
9
+ * are contained in all of them.
10
+ *
11
+ * This can be used, for example, to find the "longest common prefix directory"
12
+ * by examining `mm.scan(pattern).base` for each `pattern`.
13
+ */
14
+ export const allAffirmativePatternsFromPatternSets = (patternSets) => {
15
+ return patternSets.flatMap(patternSet => [
16
+ ...patternSet.watch.affirmative,
17
+ ...patternSet.documents.affirmative,
18
+ ...patternSet.schemas.affirmative,
19
+ ]);
20
+ };
21
+ /**
22
+ * Create a rebuild trigger that follows the algorithm described here:
23
+ * https://github.com/dotansimha/graphql-code-generator/issues/9270#issuecomment-1496765045
24
+ *
25
+ * There is a flow chart diagram in that comment.
26
+ *
27
+ * Basically:
28
+ *
29
+ * * "Global" patterns are defined at top level of config file, and "local"
30
+ * patterns are defined for each output target
31
+ * * Each pattern can have "watch", "documents", and "schemas"
32
+ * * Watch patterns (global and local) always take precedence over documents and
33
+ * schemas patterns, i.e. a watch negation always negates, and a watch match is
34
+ * a match even if it would be negated by some pattern in documents or schemas
35
+ * * The trigger returns true if any output target's local patterns result in
36
+ * a match, after considering the precedence of any global and local negations
37
+ */
38
+ export const makeShouldRebuild = ({ globalPatternSet, localPatternSets, }) => {
39
+ const localMatchers = localPatternSets.map(localPatternSet => {
40
+ return (path) => {
41
+ // Is path negated by any negating watch pattern?
42
+ if (matchesAnyNegatedPattern(path, [...globalPatternSet.watch.negated, ...localPatternSet.watch.negated])) {
43
+ // Short circut: negations in watch patterns take priority
44
+ return false;
45
+ }
46
+ // Does path match any affirmative watch pattern?
47
+ if (matchesAnyAffirmativePattern(path, [
48
+ ...globalPatternSet.watch.affirmative,
49
+ ...localPatternSet.watch.affirmative,
50
+ ])) {
51
+ // Immediately return true: Watch pattern takes priority, even if documents or schema would negate it
52
+ return true;
53
+ }
54
+ // Does path match documents patterns (without being negated)?
55
+ if (matchesAnyAffirmativePattern(path, [
56
+ ...globalPatternSet.documents.affirmative,
57
+ ...localPatternSet.documents.affirmative,
58
+ ]) &&
59
+ !matchesAnyNegatedPattern(path, [...globalPatternSet.documents.negated, ...localPatternSet.documents.negated])) {
60
+ return true;
61
+ }
62
+ // Does path match schemas patterns (without being negated)?
63
+ if (matchesAnyAffirmativePattern(path, [
64
+ ...globalPatternSet.schemas.affirmative,
65
+ ...localPatternSet.schemas.affirmative,
66
+ ]) &&
67
+ !matchesAnyNegatedPattern(path, [...globalPatternSet.schemas.negated, ...localPatternSet.schemas.negated])) {
68
+ return true;
69
+ }
70
+ // Otherwise, there is no match
71
+ return false;
72
+ };
73
+ });
74
+ /**
75
+ * Return `true` if `path` should trigger a rebuild
76
+ */
77
+ return ({ path: absolutePath }) => {
78
+ if (!isAbsolute(absolutePath)) {
79
+ throw new Error('shouldRebuild trigger should be called with absolute path');
80
+ }
81
+ const path = relative(process.cwd(), absolutePath);
82
+ const shouldRebuild = localMatchers.some(matcher => matcher(path));
83
+ return shouldRebuild;
84
+ };
85
+ };
86
+ /**
87
+ * Create the pattern set for the "global" (top level) config.
88
+ *
89
+ * In the `shouldRebuild` algorithm, any of these watch patterns will take
90
+ * precedence over local configs, and any schemas and documents patterns will be
91
+ * mixed into the pattern set of each local config.
92
+ */
93
+ export const makeGlobalPatternSet = (initialContext) => {
94
+ const config = initialContext.getConfig();
95
+ return {
96
+ watch: sortPatterns([
97
+ ...(typeof config.watch === 'boolean' ? [] : normalizeInstanceOrArray(config.watch ?? [])),
98
+ relative(process.cwd(), initialContext.filepath),
99
+ ]),
100
+ schemas: sortPatterns(makePatternsFromSchemas(normalizeInstanceOrArray(config.schema))),
101
+ documents: sortPatterns(makePatternsFromDocuments(normalizeInstanceOrArray(config.documents))),
102
+ };
103
+ };
104
+ /**
105
+ * Create the pattern set for a "local" (output target) config
106
+ *
107
+ * In the `shouldRebuild` algorithm, any of these watch patterns will take
108
+ * precedence over documents or schemas patterns, and the documents and schemas
109
+ * patterns will be mixed into the pattern set of their respective gobal pattern
110
+ * set equivalents.
111
+ */
112
+ export const makeLocalPatternSet = (conf) => {
113
+ return {
114
+ watch: sortPatterns(normalizeInstanceOrArray(conf.watchPattern)),
115
+ documents: sortPatterns(makePatternsFromDocuments(normalizeInstanceOrArray(conf.documents))),
116
+ schemas: sortPatterns(makePatternsFromSchemas(normalizeInstanceOrArray(conf.schema))),
117
+ };
118
+ };
119
+ /**
120
+ * Parse a list of micromatch patterns from a list of documents, which should
121
+ * already have been normalized from their raw config values.
122
+ */
123
+ const makePatternsFromDocuments = (documents) => {
124
+ const patterns = [];
125
+ if (documents) {
126
+ for (const doc of documents) {
127
+ if (typeof doc === 'string') {
128
+ patterns.push(doc);
129
+ }
130
+ else {
131
+ patterns.push(...Object.keys(doc));
132
+ }
133
+ }
134
+ }
135
+ return patterns;
136
+ };
137
+ /**
138
+ * Parse a list of micromatch patterns from a list of schemas, which should
139
+ * already have been normalized from their raw config values.
140
+ */
141
+ const makePatternsFromSchemas = (schemas) => {
142
+ const patterns = [];
143
+ for (const s of schemas) {
144
+ const schema = s;
145
+ if (!isURL(schema) && (isGlob(schema) || isValidPath(schema))) {
146
+ patterns.push(schema);
147
+ }
148
+ }
149
+ return patterns;
150
+ };
151
+ /**
152
+ * Given a list of micromatch patterns, sort them into `patterns` (all of them),
153
+ * `affirmative` (only the affirmative patterns), and `negated` (only the negated patterns)
154
+ *
155
+ * @param patterns List of micromatch patterns
156
+ */
157
+ export const sortPatterns = (patterns) => ({
158
+ patterns,
159
+ affirmative: onlyAffirmativePatterns(patterns),
160
+ negated: onlyNegatedPatterns(patterns),
161
+ });
162
+ /**
163
+ * Filter the provided list of patterns to include only "affirmative" (non-negated) patterns.
164
+ *
165
+ * @param patterns List of micromatch patterns (or paths) to filter
166
+ */
167
+ const onlyAffirmativePatterns = (patterns) => {
168
+ return patterns.filter(pattern => !mm.scan(pattern).negated);
169
+ };
170
+ /**
171
+ * Filter the provided list of patterns to include only negated patterns.
172
+ *
173
+ * @param patterns List of micromatch patterns (or paths) to filter
174
+ */
175
+ const onlyNegatedPatterns = (patterns) => {
176
+ return patterns.filter(pattern => mm.scan(pattern).negated);
177
+ };
178
+ /**
179
+ * Given a list of negated patterns, invert them by removing their negation prefix
180
+ *
181
+ * If there is a non-negated pattern in the list, throw an error, because this
182
+ * function should only be called after filtering the list to be only negated patterns
183
+ *
184
+ * @param patterns List of negated micromatch patterns
185
+ */
186
+ const invertNegatedPatterns = (patterns) => {
187
+ return patterns.map(pattern => {
188
+ const scanned = mm.scan(pattern);
189
+ if (!scanned.negated) {
190
+ throw new Error(`onlyNegatedPatterns got a non-negated pattern: ${pattern}`);
191
+ }
192
+ // Remove the leading prefix (NOTE: this is not always "!")
193
+ // e.g. mm.scan("!./foo/bar/never-watch.graphql").prefix === '!./'
194
+ return pattern.slice(scanned.prefix.length);
195
+ });
196
+ };
197
+ /**
198
+ * Return true if relativeCandidatePath matches any of the affirmativePatterns
199
+ *
200
+ * @param relativeCandidatePath A relative path to evaluate against the supplied affirmativePatterns
201
+ * @param affirmativePatterns A list of patterns, containing no negated patterns, to evaluate
202
+ */
203
+ const matchesAnyAffirmativePattern = (relativeCandidatePath, affirmativePatterns) => {
204
+ if (isAbsolute(relativeCandidatePath)) {
205
+ throw new Error('matchesAny should only be called with relative candidate path');
206
+ }
207
+ // Developer error: This function is not intended to work with pattern sets including negations
208
+ if (affirmativePatterns.some(pattern => mm.scan(pattern).negated)) {
209
+ throw new Error('matchesAnyAffirmativePattern should only include affirmative patterns');
210
+ }
211
+ // micromatch.isMatch does not omit matches that are negated by negation patterns,
212
+ // which is why we require this function only examine affirmative patterns
213
+ return mm.isMatch(relativeCandidatePath, affirmativePatterns);
214
+ };
215
+ /**
216
+ * Return true if relativeCandidatePath matches any of the negatedPatterns
217
+ *
218
+ * This function will invert the negated patterns and then call matchesAnyAffirmativePattern
219
+ *
220
+ * @param relativeCandidatePath A relative path to evaluate against the suppliednegatedPatterns
221
+ * @param negatedPatterns A list of patterns, containing no negated patterns, to evaluate
222
+ */
223
+ const matchesAnyNegatedPattern = (relativeCandidatePath, negatedPatterns) => {
224
+ // NOTE: No safety check that negatedPatterns contains only negated, because that will happen in invertedNegatedPatterns
225
+ return matchesAnyAffirmativePattern(relativeCandidatePath, invertNegatedPatterns(negatedPatterns));
226
+ };