-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathindex.ts
More file actions
390 lines (355 loc) · 13.9 KB
/
index.ts
File metadata and controls
390 lines (355 loc) · 13.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
import * as addPlugin from '@graphql-codegen/add';
import * as gqlTagPlugin from '@graphql-codegen/gql-tag-operations';
import type { PluginFunction, Types } from '@graphql-codegen/plugin-helpers';
import * as typedDocumentNodePlugin from '@graphql-codegen/typed-document-node';
import * as typescriptPlugin from '@graphql-codegen/typescript';
import * as typescriptOperationPlugin from '@graphql-codegen/typescript-operations';
import { ClientSideBaseVisitor, DocumentMode } from '@graphql-codegen/visitor-plugin-common';
import { parse, printSchema, type DocumentNode, type GraphQLSchema } from 'graphql';
import * as fragmentMaskingPlugin from './fragment-masking-plugin.js';
import { generateDocumentHash, normalizeAndPrintDocumentNode } from './persisted-documents.js';
import { processSources } from './process-sources.js';
export { default as babelOptimizerPlugin } from './babel.js';
export type FragmentMaskingConfig = {
/** @description Name of the function that should be used for unmasking a masked fragment property.
* @default `'useFragment'`
*/
unmaskFunctionName?: string;
};
export type ClientPresetConfig = {
/**
* @description Fragment masking hides data from components and only allows accessing the data by using a unmasking function.
* @exampleMarkdown
* ```tsx
* const config = {
* schema: 'https://graphql.org/graphql/',
* documents: ['src/**\/*.tsx', '!src\/gql/**\/*'],
* generates: {
* './src/gql/': {
* preset: 'client',
* presetConfig: {
* fragmentMasking: false,
* }
* },
* },
* };
* export default config;
* ```
*/
fragmentMasking?: FragmentMaskingConfig | boolean;
/**
* @description Specify the name of the "graphql tag" function to use
* @default "graphql"
*
* E.g. `graphql` or `gql`.
*
* @exampleMarkdown
* ```tsx
* const config = {
* schema: 'https://graphql.org/graphql/',
* documents: ['src/**\/*.tsx', '!src\/gql/**\/*'],
* generates: {
* './src/gql/': {
* preset: 'client',
* presetConfig: {
* gqlTagName: 'gql',
* }
* },
* },
* };
* export default config;
* ```
*/
gqlTagName?: string;
/**
* Generate metadata for a executable document node and embed it in the emitted code.
*/
onExecutableDocumentNode?: (documentNode: DocumentNode) => void | Record<string, unknown>;
/** Persisted operations configuration. */
persistedDocuments?:
| boolean
| {
/**
* @description Behavior for the output file.
* @default 'embedHashInDocument'
* "embedHashInDocument" will add a property within the `DocumentNode` with the hash of the operation.
* "replaceDocumentWithHash" will fully drop the document definition.
*/
mode?: 'embedHashInDocument' | 'replaceDocumentWithHash';
/**
* @description Name of the property that will be added to the `DocumentNode` with the hash of the operation.
*/
hashPropertyName?: string;
/**
* @description Algorithm or function used to generate the hash, could be useful if your server expects something specific (e.g., Apollo Server expects `sha256`).
*
* A custom hash function can be provided to generate the hash if the preset algorithms don't fit your use case. The function receives the operation and should return the hash string.
*
* The algorithm parameter is typed with known algorithms and as a string rather than a union because it solely depends on Crypto's algorithms supported
* by the version of OpenSSL on the platform.
*
* @default `sha1`
*/
hashAlgorithm?: 'sha1' | 'sha256' | (string & {}) | ((operation: string) => string);
};
};
const isOutputFolderLike = (baseOutputDir: string) => baseOutputDir.endsWith('/');
export const preset: Types.OutputPreset<ClientPresetConfig> = {
prepareDocuments: (outputFilePath, outputSpecificDocuments) => [...outputSpecificDocuments, `!${outputFilePath}`],
buildGeneratesSection: async options => {
if (!isOutputFolderLike(options.baseOutputDir)) {
throw new Error(
'[client-preset] target output should be a directory, ex: "src/gql/". Make sure you add "/" at the end of the directory path'
);
}
if (options.plugins.length > 0 && Object.keys(options.plugins).some(p => p.startsWith('typescript'))) {
throw new Error(
'[client-preset] providing typescript-based `plugins` with `preset: "client" leads to duplicated generated types'
);
}
const isPersistedOperations = !!options.presetConfig?.persistedDocuments;
if (options.config.nullability?.errorHandlingClient) {
options.schemaAst = await semanticToStrict(options.schemaAst!);
options.schema = parse(printSchema(options.schemaAst));
}
const reexports: Array<string> = [];
// the `client` preset is restricting the config options inherited from `typescript`, `typescript-operations` and others.
const forwardedConfig = {
scalars: options.config.scalars,
defaultScalarType: options.config.defaultScalarType,
strictScalars: options.config.strictScalars,
namingConvention: options.config.namingConvention,
useTypeImports: options.config.useTypeImports,
skipTypename: options.config.skipTypename,
arrayInputCoercion: options.config.arrayInputCoercion,
enumsAsTypes: options.config.enumsAsTypes,
enumsAsConst: options.config.enumsAsConst,
enumValues: options.config.enumValues,
futureProofEnums: options.config.futureProofEnums,
dedupeFragments: options.config.dedupeFragments,
nonOptionalTypename: options.config.nonOptionalTypename,
avoidOptionals: options.config.avoidOptionals,
documentMode: options.config.documentMode,
skipTypeNameForRoot: options.config.skipTypeNameForRoot,
onlyOperationTypes: options.config.onlyOperationTypes,
onlyEnums: options.config.onlyEnums,
customDirectives: options.config.customDirectives,
preResolveTypes: options.config.preResolveTypes,
};
const visitor = new ClientSideBaseVisitor(options.schemaAst, [], options.config, options.config);
let fragmentMaskingConfig: FragmentMaskingConfig | null = null;
if (typeof options?.presetConfig?.fragmentMasking === 'object') {
fragmentMaskingConfig = options.presetConfig.fragmentMasking;
} else if (options?.presetConfig?.fragmentMasking !== false) {
// `true` by default
fragmentMaskingConfig = {};
}
const onExecutableDocumentNodeHook = options.presetConfig.onExecutableDocumentNode ?? null;
const isMaskingFragments = fragmentMaskingConfig != null;
const persistedDocuments = options.presetConfig.persistedDocuments
? {
hashPropertyName:
(typeof options.presetConfig.persistedDocuments === 'object' &&
options.presetConfig.persistedDocuments.hashPropertyName) ||
'hash',
omitDefinitions:
(typeof options.presetConfig.persistedDocuments === 'object' &&
options.presetConfig.persistedDocuments.mode) === 'replaceDocumentWithHash' || false,
hashAlgorithm:
(typeof options.presetConfig.persistedDocuments === 'object' &&
options.presetConfig.persistedDocuments.hashAlgorithm) ||
'sha1',
}
: null;
const sourcesWithOperations = processSources(options.documents, node => {
if (node.kind === 'FragmentDefinition') {
return visitor.getFragmentVariableName(node);
}
return visitor.getOperationVariableName(node);
});
const sources = sourcesWithOperations.map(({ source }) => source);
const tdnFinished = createDeferred();
const persistedDocumentsMap = new Map<string, string>();
const pluginMap = {
...options.pluginMap,
[`add`]: addPlugin,
[`typescript`]: typescriptPlugin,
[`typescript-operations`]: typescriptOperationPlugin,
[`typed-document-node`]: {
...typedDocumentNodePlugin,
plugin: async (...args: Parameters<PluginFunction>) => {
try {
return await typedDocumentNodePlugin.plugin(...args);
} finally {
tdnFinished.resolve();
}
},
},
[`gen-dts`]: gqlTagPlugin,
};
function onExecutableDocumentNode(documentNode: DocumentNode) {
const meta = onExecutableDocumentNodeHook?.(documentNode);
if (persistedDocuments) {
const documentString = normalizeAndPrintDocumentNode(documentNode);
const hash = generateDocumentHash(documentString, persistedDocuments.hashAlgorithm);
persistedDocumentsMap.set(hash, documentString);
return { ...meta, [persistedDocuments.hashPropertyName]: hash };
}
if (meta) {
return meta;
}
return undefined;
}
const plugins: Array<Types.ConfiguredPlugin> = [
{ [`add`]: { content: `/* eslint-disable */` } },
{ [`typescript`]: {} },
{ [`typescript-operations`]: {} },
{
[`typed-document-node`]: {
unstable_onExecutableDocumentNode: onExecutableDocumentNode,
unstable_omitDefinitions: persistedDocuments?.omitDefinitions ?? false,
},
},
...options.plugins,
];
const genDtsPlugins: Array<Types.ConfiguredPlugin> = [
{ [`add`]: { content: `/* eslint-disable */` } },
{ [`gen-dts`]: { sourcesWithOperations } },
];
const gqlArtifactFileExtension = '.ts';
reexports.push('gql');
const config = {
...options.config,
inlineFragmentTypes: isMaskingFragments ? 'mask' : options.config['inlineFragmentTypes'],
};
let fragmentMaskingFileGenerateConfig: Types.GenerateOptions | null = null;
if (isMaskingFragments === true) {
const fragmentMaskingArtifactFileExtension = '.ts';
reexports.push('fragment-masking');
fragmentMaskingFileGenerateConfig = {
filename: `${options.baseOutputDir}fragment-masking${fragmentMaskingArtifactFileExtension}`,
pluginMap: {
[`add`]: addPlugin,
[`fragment-masking`]: fragmentMaskingPlugin,
},
plugins: [
{ [`add`]: { content: `/* eslint-disable */` } },
{
[`fragment-masking`]: {},
},
],
schema: options.schema,
config: {
useTypeImports: options.config.useTypeImports,
unmaskFunctionName: fragmentMaskingConfig.unmaskFunctionName,
emitLegacyCommonJSImports: options.config.emitLegacyCommonJSImports,
isStringDocumentMode: options.config.documentMode === DocumentMode.string,
},
documents: [],
documentTransforms: options.documentTransforms,
};
}
let indexFileGenerateConfig: Types.GenerateOptions | null = null;
const reexportsExtension = options.config.emitLegacyCommonJSImports ? '' : '.js';
if (reexports.length) {
indexFileGenerateConfig = {
filename: `${options.baseOutputDir}index.ts`,
pluginMap: {
[`add`]: addPlugin,
},
plugins: [
{
[`add`]: {
content: reexports
.sort()
.map(moduleName => `export * from "./${moduleName}${reexportsExtension}";`)
.join('\n'),
},
},
],
schema: options.schema,
config: {},
documents: [],
documentTransforms: options.documentTransforms,
};
}
return [
{
filename: `${options.baseOutputDir}graphql.ts`,
plugins,
pluginMap,
schema: options.schema,
config: {
inlineFragmentTypes: isMaskingFragments ? 'mask' : options.config['inlineFragmentTypes'],
...forwardedConfig,
},
documents: sources,
documentTransforms: options.documentTransforms,
},
{
filename: `${options.baseOutputDir}gql${gqlArtifactFileExtension}`,
plugins: genDtsPlugins,
pluginMap,
schema: options.schema,
config: {
...config,
gqlTagName: options.presetConfig.gqlTagName || 'graphql',
},
documents: sources,
documentTransforms: options.documentTransforms,
},
...(isPersistedOperations
? [
{
filename: `${options.baseOutputDir}persisted-documents.json`,
plugins: [
{
[`persisted-operations`]: {},
},
],
pluginMap: {
[`persisted-operations`]: {
plugin: async () => {
await tdnFinished.promise;
return {
content: JSON.stringify(Object.fromEntries(persistedDocumentsMap.entries()), null, 2),
};
},
},
},
schema: options.schema,
config: {},
documents: sources,
documentTransforms: options.documentTransforms,
},
]
: []),
...(fragmentMaskingFileGenerateConfig ? [fragmentMaskingFileGenerateConfig] : []),
...(indexFileGenerateConfig ? [indexFileGenerateConfig] : []),
];
},
};
type Deferred<T = void> = {
resolve: (value: T) => void;
reject: (value: unknown) => void;
promise: Promise<T>;
};
function createDeferred<T = void>(): Deferred<T> {
const d = {} as Deferred<T>;
d.promise = new Promise<T>((resolve, reject) => {
d.resolve = resolve;
d.reject = reject;
});
return d;
}
const semanticToStrict = async (schema: GraphQLSchema): Promise<GraphQLSchema> => {
try {
const sock = await import('graphql-sock');
return sock.semanticToStrict(schema);
} catch {
throw new Error(
"To use the `nullability.errorHandlingClient` option, you must install the 'graphql-sock' package."
);
}
};
export { addTypenameSelectionDocumentTransform } from './add-typename-selection-document-transform.js';