@graphql-codegen/plugin-helpers 2.5.0-alpha-252a8d50d.0 → 2.5.0-alpha-2fbcdb6d3.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.
package/index.mjs DELETED
@@ -1,560 +0,0 @@
1
- import { createRequire } from 'module';
2
- import { cwd } from 'process';
3
- import * as changeCaseAll from 'change-case-all';
4
- import { isListType, isNonNullType, visit, Kind, isObjectType, parse, GraphQLObjectType } from 'graphql';
5
- import merge from 'lodash/merge.js';
6
- import { mapSchema, MapperKind, astFromObjectType, getRootTypeNames, memoize1, getDocumentNodeFromSchema } from '@graphql-tools/utils';
7
-
8
- function resolveExternalModuleAndFn(pointer) {
9
- if (typeof pointer === 'function') {
10
- return pointer;
11
- }
12
- // eslint-disable-next-line prefer-const
13
- let [moduleName, functionName] = pointer.split('#');
14
- // Temp workaround until v2
15
- if (moduleName === 'change-case') {
16
- moduleName = 'change-case-all';
17
- }
18
- let loadedModule;
19
- if (moduleName === 'change-case-all') {
20
- loadedModule = changeCaseAll;
21
- }
22
- else {
23
- // we have to use a path to a filename here (it does not need to exist.)
24
- // https://github.com/dotansimha/graphql-code-generator/issues/6553
25
- const cwdRequire = createRequire(cwd() + '/index.js');
26
- loadedModule = cwdRequire(moduleName);
27
- if (!(functionName in loadedModule) && typeof loadedModule !== 'function') {
28
- throw new Error(`${functionName} couldn't be found in module ${moduleName}!`);
29
- }
30
- }
31
- return loadedModule[functionName] || loadedModule;
32
- }
33
-
34
- function isComplexPluginOutput(obj) {
35
- return typeof obj === 'object' && obj.hasOwnProperty('content');
36
- }
37
-
38
- function mergeOutputs(content) {
39
- const result = { content: '', prepend: [], append: [] };
40
- if (Array.isArray(content)) {
41
- content.forEach(item => {
42
- if (typeof item === 'string') {
43
- result.content += item;
44
- }
45
- else {
46
- result.content += item.content;
47
- result.prepend.push(...(item.prepend || []));
48
- result.append.push(...(item.append || []));
49
- }
50
- });
51
- }
52
- return [...result.prepend, result.content, ...result.append].join('\n');
53
- }
54
- function isWrapperType(t) {
55
- return isListType(t) || isNonNullType(t);
56
- }
57
- function getBaseType(type) {
58
- if (isWrapperType(type)) {
59
- return getBaseType(type.ofType);
60
- }
61
- else {
62
- return type;
63
- }
64
- }
65
- function removeNonNullWrapper(type) {
66
- return isNonNullType(type) ? type.ofType : type;
67
- }
68
-
69
- function isOutputConfigArray(type) {
70
- return Array.isArray(type);
71
- }
72
- function isConfiguredOutput(type) {
73
- return (typeof type === 'object' && type.plugins) || type.preset;
74
- }
75
- function normalizeOutputParam(config) {
76
- // In case of direct array with a list of plugins
77
- if (isOutputConfigArray(config)) {
78
- return {
79
- documents: [],
80
- schema: [],
81
- plugins: isConfiguredOutput(config) ? config.plugins : config,
82
- };
83
- }
84
- else if (isConfiguredOutput(config)) {
85
- return config;
86
- }
87
- else {
88
- throw new Error(`Invalid "generates" config!`);
89
- }
90
- }
91
- function normalizeInstanceOrArray(type) {
92
- if (Array.isArray(type)) {
93
- return type;
94
- }
95
- else if (!type) {
96
- return [];
97
- }
98
- return [type];
99
- }
100
- function normalizeConfig(config) {
101
- if (typeof config === 'string') {
102
- return [{ [config]: {} }];
103
- }
104
- else if (Array.isArray(config)) {
105
- return config.map(plugin => (typeof plugin === 'string' ? { [plugin]: {} } : plugin));
106
- }
107
- else if (typeof config === 'object') {
108
- return Object.keys(config).reduce((prev, pluginName) => [...prev, { [pluginName]: config[pluginName] }], []);
109
- }
110
- else {
111
- return [];
112
- }
113
- }
114
- function hasNullableTypeRecursively(type) {
115
- if (!isNonNullType(type)) {
116
- return true;
117
- }
118
- if (isListType(type) || isNonNullType(type)) {
119
- return hasNullableTypeRecursively(type.ofType);
120
- }
121
- return false;
122
- }
123
- function isUsingTypes(document, externalFragments, schema) {
124
- let foundFields = 0;
125
- const typesStack = [];
126
- visit(document, {
127
- SelectionSet: {
128
- enter(node, key, parent, anscestors) {
129
- const insideIgnoredFragment = anscestors.find((f) => f.kind && f.kind === 'FragmentDefinition' && externalFragments.includes(f.name.value));
130
- if (insideIgnoredFragment) {
131
- return;
132
- }
133
- const selections = node.selections || [];
134
- if (schema && selections.length > 0) {
135
- const nextTypeName = (() => {
136
- if (parent.kind === Kind.FRAGMENT_DEFINITION) {
137
- return parent.typeCondition.name.value;
138
- }
139
- else if (parent.kind === Kind.FIELD) {
140
- const lastType = typesStack[typesStack.length - 1];
141
- if (!lastType) {
142
- throw new Error(`Unable to find parent type! Please make sure you operation passes validation`);
143
- }
144
- const field = lastType.getFields()[parent.name.value];
145
- if (!field) {
146
- throw new Error(`Unable to find field "${parent.name.value}" on type "${lastType}"!`);
147
- }
148
- return getBaseType(field.type).name;
149
- }
150
- else if (parent.kind === Kind.OPERATION_DEFINITION) {
151
- if (parent.operation === 'query') {
152
- return schema.getQueryType().name;
153
- }
154
- else if (parent.operation === 'mutation') {
155
- return schema.getMutationType().name;
156
- }
157
- else if (parent.operation === 'subscription') {
158
- return schema.getSubscriptionType().name;
159
- }
160
- }
161
- else if (parent.kind === Kind.INLINE_FRAGMENT) {
162
- if (parent.typeCondition) {
163
- return parent.typeCondition.name.value;
164
- }
165
- else {
166
- return typesStack[typesStack.length - 1].name;
167
- }
168
- }
169
- return null;
170
- })();
171
- typesStack.push(schema.getType(nextTypeName));
172
- }
173
- },
174
- leave(node) {
175
- const selections = node.selections || [];
176
- if (schema && selections.length > 0) {
177
- typesStack.pop();
178
- }
179
- },
180
- },
181
- Field: {
182
- enter: (node, key, parent, path, anscestors) => {
183
- if (node.name.value.startsWith('__')) {
184
- return;
185
- }
186
- const insideIgnoredFragment = anscestors.find((f) => f.kind && f.kind === 'FragmentDefinition' && externalFragments.includes(f.name.value));
187
- if (insideIgnoredFragment) {
188
- return;
189
- }
190
- const selections = node.selectionSet ? node.selectionSet.selections || [] : [];
191
- const relevantFragmentSpreads = selections.filter(s => s.kind === Kind.FRAGMENT_SPREAD && !externalFragments.includes(s.name.value));
192
- if (selections.length === 0 || relevantFragmentSpreads.length > 0) {
193
- foundFields++;
194
- }
195
- if (schema) {
196
- const lastType = typesStack[typesStack.length - 1];
197
- if (lastType) {
198
- if (isObjectType(lastType)) {
199
- const field = lastType.getFields()[node.name.value];
200
- if (!field) {
201
- throw new Error(`Unable to find field "${node.name.value}" on type "${lastType}"!`);
202
- }
203
- const currentType = field.type;
204
- // To handle `Maybe` usage
205
- if (hasNullableTypeRecursively(currentType)) {
206
- foundFields++;
207
- }
208
- }
209
- }
210
- }
211
- },
212
- },
213
- VariableDefinition: {
214
- enter: (node, key, parent, path, anscestors) => {
215
- const insideIgnoredFragment = anscestors.find((f) => f.kind && f.kind === 'FragmentDefinition' && externalFragments.includes(f.name.value));
216
- if (insideIgnoredFragment) {
217
- return;
218
- }
219
- foundFields++;
220
- },
221
- },
222
- InputValueDefinition: {
223
- enter: (node, key, parent, path, anscestors) => {
224
- const insideIgnoredFragment = anscestors.find((f) => f.kind && f.kind === 'FragmentDefinition' && externalFragments.includes(f.name.value));
225
- if (insideIgnoredFragment) {
226
- return;
227
- }
228
- foundFields++;
229
- },
230
- },
231
- });
232
- return foundFields > 0;
233
- }
234
-
235
- /**
236
- * Federation Spec
237
- */
238
- const federationSpec = parse(/* GraphQL */ `
239
- scalar _FieldSet
240
-
241
- directive @external on FIELD_DEFINITION
242
- directive @requires(fields: _FieldSet!) on FIELD_DEFINITION
243
- directive @provides(fields: _FieldSet!) on FIELD_DEFINITION
244
- directive @key(fields: _FieldSet!) on OBJECT | INTERFACE
245
- `);
246
- /**
247
- * Adds `__resolveReference` in each ObjectType involved in Federation.
248
- * @param schema
249
- */
250
- function addFederationReferencesToSchema(schema) {
251
- return mapSchema(schema, {
252
- [MapperKind.OBJECT_TYPE]: type => {
253
- if (isFederationObjectType(type, schema)) {
254
- const typeConfig = type.toConfig();
255
- typeConfig.fields = {
256
- [resolveReferenceFieldName]: {
257
- type,
258
- },
259
- ...typeConfig.fields,
260
- };
261
- return new GraphQLObjectType(typeConfig);
262
- }
263
- return type;
264
- },
265
- });
266
- }
267
- /**
268
- * Removes Federation Spec from GraphQL Schema
269
- * @param schema
270
- * @param config
271
- */
272
- function removeFederation(schema) {
273
- return mapSchema(schema, {
274
- [MapperKind.QUERY]: queryType => {
275
- const queryTypeConfig = queryType.toConfig();
276
- delete queryTypeConfig.fields._entities;
277
- delete queryTypeConfig.fields._service;
278
- return new GraphQLObjectType(queryTypeConfig);
279
- },
280
- [MapperKind.UNION_TYPE]: unionType => {
281
- const unionTypeName = unionType.name;
282
- if (unionTypeName === '_Entity' || unionTypeName === '_Any') {
283
- return null;
284
- }
285
- return unionType;
286
- },
287
- [MapperKind.OBJECT_TYPE]: objectType => {
288
- if (objectType.name === '_Service') {
289
- return null;
290
- }
291
- return objectType;
292
- },
293
- });
294
- }
295
- const resolveReferenceFieldName = '__resolveReference';
296
- class ApolloFederation {
297
- constructor({ enabled, schema }) {
298
- this.enabled = false;
299
- this.enabled = enabled;
300
- this.schema = schema;
301
- this.providesMap = this.createMapOfProvides();
302
- }
303
- /**
304
- * Excludes types definde by Federation
305
- * @param typeNames List of type names
306
- */
307
- filterTypeNames(typeNames) {
308
- return this.enabled ? typeNames.filter(t => t !== '_FieldSet') : typeNames;
309
- }
310
- /**
311
- * Excludes `__resolveReference` fields
312
- * @param fieldNames List of field names
313
- */
314
- filterFieldNames(fieldNames) {
315
- return this.enabled ? fieldNames.filter(t => t !== resolveReferenceFieldName) : fieldNames;
316
- }
317
- /**
318
- * Decides if directive should not be generated
319
- * @param name directive's name
320
- */
321
- skipDirective(name) {
322
- return this.enabled && ['external', 'requires', 'provides', 'key'].includes(name);
323
- }
324
- /**
325
- * Decides if scalar should not be generated
326
- * @param name directive's name
327
- */
328
- skipScalar(name) {
329
- return this.enabled && name === '_FieldSet';
330
- }
331
- /**
332
- * Decides if field should not be generated
333
- * @param data
334
- */
335
- skipField({ fieldNode, parentType }) {
336
- if (!this.enabled || !isObjectType(parentType) || !isFederationObjectType(parentType, this.schema)) {
337
- return false;
338
- }
339
- return this.isExternalAndNotProvided(fieldNode, parentType);
340
- }
341
- isResolveReferenceField(fieldNode) {
342
- const name = typeof fieldNode.name === 'string' ? fieldNode.name : fieldNode.name.value;
343
- return this.enabled && name === resolveReferenceFieldName;
344
- }
345
- /**
346
- * Transforms ParentType signature in ObjectTypes involved in Federation
347
- * @param data
348
- */
349
- transformParentType({ fieldNode, parentType, parentTypeSignature, }) {
350
- if (this.enabled &&
351
- isObjectType(parentType) &&
352
- isFederationObjectType(parentType, this.schema) &&
353
- (isTypeExtension(parentType, this.schema) || fieldNode.name.value === resolveReferenceFieldName)) {
354
- const keys = getDirectivesByName('key', parentType);
355
- if (keys.length) {
356
- const outputs = [`{ __typename: '${parentType.name}' } &`];
357
- // Look for @requires and see what the service needs and gets
358
- const requires = getDirectivesByName('requires', fieldNode).map(this.extractKeyOrRequiresFieldSet);
359
- const requiredFields = this.translateFieldSet(merge({}, ...requires), parentTypeSignature);
360
- // @key() @key() - "primary keys" in Federation
361
- const primaryKeys = keys.map(def => {
362
- const fields = this.extractKeyOrRequiresFieldSet(def);
363
- return this.translateFieldSet(fields, parentTypeSignature);
364
- });
365
- const [open, close] = primaryKeys.length > 1 ? ['(', ')'] : ['', ''];
366
- outputs.push([open, primaryKeys.join(' | '), close].join(''));
367
- // include required fields
368
- if (requires.length) {
369
- outputs.push(`& ${requiredFields}`);
370
- }
371
- return outputs.join(' ');
372
- }
373
- }
374
- return parentTypeSignature;
375
- }
376
- isExternalAndNotProvided(fieldNode, objectType) {
377
- return this.isExternal(fieldNode) && !this.hasProvides(objectType, fieldNode);
378
- }
379
- isExternal(node) {
380
- return getDirectivesByName('external', node).length > 0;
381
- }
382
- hasProvides(objectType, node) {
383
- const fields = this.providesMap[isObjectType(objectType) ? objectType.name : objectType.name.value];
384
- if (fields && fields.length) {
385
- return fields.includes(node.name.value);
386
- }
387
- return false;
388
- }
389
- translateFieldSet(fields, parentTypeRef) {
390
- return `GraphQLRecursivePick<${parentTypeRef}, ${JSON.stringify(fields)}>`;
391
- }
392
- extractKeyOrRequiresFieldSet(directive) {
393
- const arg = directive.arguments.find(arg => arg.name.value === 'fields');
394
- const value = arg.value.value;
395
- return oldVisit(parse(`{${value}}`), {
396
- leave: {
397
- SelectionSet(node) {
398
- return node.selections.reduce((accum, field) => {
399
- accum[field.name] = field.selection;
400
- return accum;
401
- }, {});
402
- },
403
- Field(node) {
404
- return {
405
- name: node.name.value,
406
- selection: node.selectionSet ? node.selectionSet : true,
407
- };
408
- },
409
- Document(node) {
410
- return node.definitions.find((def) => def.kind === 'OperationDefinition' && def.operation === 'query').selectionSet;
411
- },
412
- },
413
- });
414
- }
415
- extractProvidesFieldSet(directive) {
416
- const arg = directive.arguments.find(arg => arg.name.value === 'fields');
417
- const value = arg.value.value;
418
- if (/[{}]/gi.test(value)) {
419
- throw new Error('Nested fields in _FieldSet is not supported in the @provides directive');
420
- }
421
- return value.split(/\s+/g);
422
- }
423
- createMapOfProvides() {
424
- const providesMap = {};
425
- Object.keys(this.schema.getTypeMap()).forEach(typename => {
426
- const objectType = this.schema.getType(typename);
427
- if (isObjectType(objectType)) {
428
- Object.values(objectType.getFields()).forEach(field => {
429
- const provides = getDirectivesByName('provides', field.astNode)
430
- .map(this.extractProvidesFieldSet)
431
- .reduce((prev, curr) => [...prev, ...curr], []);
432
- const ofType = getBaseType(field.type);
433
- if (!providesMap[ofType.name]) {
434
- providesMap[ofType.name] = [];
435
- }
436
- providesMap[ofType.name].push(...provides);
437
- });
438
- }
439
- });
440
- return providesMap;
441
- }
442
- }
443
- /**
444
- * Checks if Object Type is involved in Federation. Based on `@key` directive
445
- * @param node Type
446
- */
447
- function isFederationObjectType(node, schema) {
448
- const { name: { value: name }, directives, } = isObjectType(node) ? astFromObjectType(node, schema) : node;
449
- const rootTypeNames = getRootTypeNames(schema);
450
- const isNotRoot = !rootTypeNames.has(name);
451
- const isNotIntrospection = !name.startsWith('__');
452
- const hasKeyDirective = directives.some(d => d.name.value === 'key');
453
- return isNotRoot && isNotIntrospection && hasKeyDirective;
454
- }
455
- /**
456
- * Extracts directives from a node based on directive's name
457
- * @param name directive name
458
- * @param node ObjectType or Field
459
- */
460
- function getDirectivesByName(name, node) {
461
- var _a;
462
- let astNode;
463
- if (isObjectType(node)) {
464
- astNode = node.astNode;
465
- }
466
- else {
467
- astNode = node;
468
- }
469
- return ((_a = astNode === null || astNode === void 0 ? void 0 : astNode.directives) === null || _a === void 0 ? void 0 : _a.filter(d => d.name.value === name)) || [];
470
- }
471
- /**
472
- * Checks if the Object Type extends a federated type from a remote schema.
473
- * Based on if any of its fields contain the `@external` directive
474
- * @param node Type
475
- */
476
- function isTypeExtension(node, schema) {
477
- var _a;
478
- const definition = isObjectType(node) ? node.astNode || astFromObjectType(node, schema) : node;
479
- return (_a = definition.fields) === null || _a === void 0 ? void 0 : _a.some(field => getDirectivesByName('external', field).length);
480
- }
481
-
482
- class DetailedError extends Error {
483
- constructor(message, details, source) {
484
- super(message);
485
- this.message = message;
486
- this.details = details;
487
- this.source = source;
488
- Object.setPrototypeOf(this, DetailedError.prototype);
489
- Error.captureStackTrace(this, DetailedError);
490
- }
491
- }
492
- function isDetailedError(error) {
493
- return error.details;
494
- }
495
-
496
- const getCachedDocumentNodeFromSchema = memoize1(getDocumentNodeFromSchema);
497
-
498
- function oldVisit(root, { enter: enterVisitors, leave: leaveVisitors, ...newVisitor }) {
499
- if (typeof enterVisitors === 'object') {
500
- for (const key in enterVisitors) {
501
- newVisitor[key] = newVisitor[key] || {};
502
- newVisitor[key].enter = enterVisitors[key];
503
- }
504
- }
505
- if (typeof leaveVisitors === 'object') {
506
- for (const key in leaveVisitors) {
507
- newVisitor[key] = newVisitor[key] || {};
508
- newVisitor[key].leave = leaveVisitors[key];
509
- }
510
- }
511
- return visit(root, newVisitor);
512
- }
513
-
514
- function createNoopProfiler() {
515
- return {
516
- run(fn) {
517
- return Promise.resolve().then(() => fn());
518
- },
519
- collect() {
520
- return [];
521
- },
522
- };
523
- }
524
- function createProfiler() {
525
- const events = [];
526
- return {
527
- collect() {
528
- return events;
529
- },
530
- run(fn, name, cat) {
531
- let startTime;
532
- return Promise.resolve()
533
- .then(() => {
534
- startTime = process.hrtime();
535
- })
536
- .then(() => fn())
537
- .then(value => {
538
- const duration = process.hrtime(startTime);
539
- // Trace Event Format documentation:
540
- // https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview
541
- const event = {
542
- name,
543
- cat,
544
- ph: 'X',
545
- ts: hrtimeToMicroseconds(startTime),
546
- pid: 1,
547
- tid: 0,
548
- dur: hrtimeToMicroseconds(duration),
549
- };
550
- events.push(event);
551
- return value;
552
- });
553
- },
554
- };
555
- }
556
- function hrtimeToMicroseconds(hrtime) {
557
- return (hrtime[0] * 1e9 + hrtime[1]) / 1000;
558
- }
559
-
560
- export { ApolloFederation, DetailedError, addFederationReferencesToSchema, createNoopProfiler, createProfiler, federationSpec, getBaseType, getCachedDocumentNodeFromSchema, hasNullableTypeRecursively, isComplexPluginOutput, isConfiguredOutput, isDetailedError, isOutputConfigArray, isUsingTypes, isWrapperType, mergeOutputs, normalizeConfig, normalizeInstanceOrArray, normalizeOutputParam, oldVisit, removeFederation, removeNonNullWrapper, resolveExternalModuleAndFn };