@envelop/core 2.4.0-alpha-c0cc559.0 → 2.4.0-alpha-e9434aa.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 (54) hide show
  1. package/cjs/create.js +28 -0
  2. package/cjs/enable-if.js +24 -0
  3. package/cjs/index.js +16 -0
  4. package/cjs/orchestrator.js +451 -0
  5. package/cjs/package.json +1 -0
  6. package/cjs/plugins/use-envelop.js +13 -0
  7. package/cjs/plugins/use-error-handler.js +21 -0
  8. package/cjs/plugins/use-extend-context.js +9 -0
  9. package/cjs/plugins/use-immediate-introspection.js +50 -0
  10. package/cjs/plugins/use-logger.js +45 -0
  11. package/cjs/plugins/use-masked-errors.js +90 -0
  12. package/cjs/plugins/use-payload-formatter.js +21 -0
  13. package/cjs/plugins/use-schema.js +29 -0
  14. package/cjs/plugins/use-timing.js +138 -0
  15. package/cjs/traced-orchestrator.js +134 -0
  16. package/cjs/traced-schema.js +68 -0
  17. package/cjs/utils.js +221 -0
  18. package/esm/create.js +28 -0
  19. package/esm/enable-if.js +24 -0
  20. package/esm/index.js +29 -0
  21. package/esm/orchestrator.js +451 -0
  22. package/esm/plugins/use-envelop.js +13 -0
  23. package/esm/plugins/use-error-handler.js +21 -0
  24. package/esm/plugins/use-extend-context.js +9 -0
  25. package/esm/plugins/use-immediate-introspection.js +50 -0
  26. package/esm/plugins/use-logger.js +45 -0
  27. package/esm/plugins/use-masked-errors.js +90 -0
  28. package/esm/plugins/use-payload-formatter.js +21 -0
  29. package/esm/plugins/use-schema.js +29 -0
  30. package/esm/plugins/use-timing.js +138 -0
  31. package/esm/traced-orchestrator.js +134 -0
  32. package/esm/traced-schema.js +68 -0
  33. package/esm/utils.js +221 -0
  34. package/package.json +33 -12
  35. package/{create.d.ts → typings/create.d.ts} +1 -1
  36. package/{enable-if.d.ts → typings/enable-if.d.ts} +0 -0
  37. package/typings/index.d.ts +13 -0
  38. package/{orchestrator.d.ts → typings/orchestrator.d.ts} +0 -0
  39. package/{plugins → typings/plugins}/use-envelop.d.ts +0 -0
  40. package/{plugins → typings/plugins}/use-error-handler.d.ts +0 -0
  41. package/{plugins → typings/plugins}/use-extend-context.d.ts +0 -0
  42. package/{plugins → typings/plugins}/use-immediate-introspection.d.ts +0 -0
  43. package/{plugins → typings/plugins}/use-logger.d.ts +1 -1
  44. package/{plugins → typings/plugins}/use-masked-errors.d.ts +3 -3
  45. package/{plugins → typings/plugins}/use-payload-formatter.d.ts +0 -0
  46. package/{plugins → typings/plugins}/use-schema.d.ts +0 -0
  47. package/{plugins → typings/plugins}/use-timing.d.ts +2 -2
  48. package/{traced-orchestrator.d.ts → typings/traced-orchestrator.d.ts} +1 -1
  49. package/{traced-schema.d.ts → typings/traced-schema.d.ts} +0 -0
  50. package/{utils.d.ts → typings/utils.d.ts} +0 -13
  51. package/README.md +0 -15
  52. package/index.d.ts +0 -13
  53. package/index.js +0 -1359
  54. package/index.mjs +0 -1317
package/index.mjs DELETED
@@ -1,1317 +0,0 @@
1
- export * from '@envelop/types';
2
- import { isIntrospectionType, isObjectType, defaultFieldResolver, Kind, visit, BREAK, parse, specifiedRules, validate, subscribe, execute, GraphQLSchema, getOperationAST, GraphQLError } from 'graphql';
3
-
4
- /**
5
- * This enum is used only internally in order to create nominal type for the disabled plugin
6
- */
7
- var EnableIfBranded;
8
- (function (EnableIfBranded) {
9
- EnableIfBranded[EnableIfBranded["DisabledPlugin"] = 0] = "DisabledPlugin";
10
- })(EnableIfBranded || (EnableIfBranded = {}));
11
- function isPluginEnabled(t) {
12
- return t !== EnableIfBranded.DisabledPlugin && t !== null;
13
- }
14
- /**
15
- * Utility function to enable a plugin.
16
- */
17
- function enableIf(condition, plugin) {
18
- if (condition) {
19
- return typeof plugin === 'function' ? plugin() : plugin;
20
- }
21
- else {
22
- return EnableIfBranded.DisabledPlugin;
23
- }
24
- }
25
-
26
- const trackedSchemaSymbol = Symbol('TRACKED_SCHEMA');
27
- const resolversHooksSymbol = Symbol('RESOLVERS_HOOKS');
28
- function prepareTracedSchema(schema) {
29
- if (!schema || schema[trackedSchemaSymbol]) {
30
- return;
31
- }
32
- schema[trackedSchemaSymbol] = true;
33
- const entries = Object.values(schema.getTypeMap());
34
- for (const type of entries) {
35
- if (!isIntrospectionType(type) && isObjectType(type)) {
36
- const fields = Object.values(type.getFields());
37
- for (const field of fields) {
38
- let resolverFn = (field.resolve || defaultFieldResolver);
39
- field.resolve = async (root, args, context, info) => {
40
- if (context && context[resolversHooksSymbol]) {
41
- const hooks = context[resolversHooksSymbol];
42
- const afterCalls = [];
43
- for (const hook of hooks) {
44
- const afterFn = await hook({
45
- root,
46
- args,
47
- context,
48
- info,
49
- resolverFn,
50
- replaceResolverFn: newFn => {
51
- resolverFn = newFn;
52
- },
53
- });
54
- afterFn && afterCalls.push(afterFn);
55
- }
56
- try {
57
- let result = await resolverFn(root, args, context, info);
58
- for (const afterFn of afterCalls) {
59
- afterFn({
60
- result,
61
- setResult: newResult => {
62
- result = newResult;
63
- },
64
- });
65
- }
66
- return result;
67
- }
68
- catch (e) {
69
- let resultErr = e;
70
- for (const afterFn of afterCalls) {
71
- afterFn({
72
- result: resultErr,
73
- setResult: newResult => {
74
- resultErr = newResult;
75
- },
76
- });
77
- }
78
- throw resultErr;
79
- }
80
- }
81
- else {
82
- return resolverFn(root, args, context, info);
83
- }
84
- };
85
- }
86
- }
87
- }
88
- }
89
-
90
- const envelopIsIntrospectionSymbol = Symbol('ENVELOP_IS_INTROSPECTION');
91
- function isOperationDefinition(def) {
92
- return def.kind === Kind.OPERATION_DEFINITION;
93
- }
94
- function isIntrospectionOperation(operation) {
95
- if (operation.kind === 'OperationDefinition') {
96
- let hasIntrospectionField = false;
97
- visit(operation, {
98
- Field: node => {
99
- if (node.name.value === '__schema') {
100
- hasIntrospectionField = true;
101
- return BREAK;
102
- }
103
- },
104
- });
105
- return hasIntrospectionField;
106
- }
107
- return false;
108
- }
109
- function isIntrospectionDocument(document) {
110
- const operations = document.definitions.filter(isOperationDefinition);
111
- return operations.some(op => isIntrospectionOperation(op));
112
- }
113
- function isIntrospectionOperationString(operation) {
114
- return (typeof operation === 'string' ? operation : operation.body).indexOf('__schema') !== -1;
115
- }
116
- function getSubscribeArgs(args) {
117
- return args.length === 1
118
- ? args[0]
119
- : {
120
- schema: args[0],
121
- document: args[1],
122
- rootValue: args[2],
123
- contextValue: args[3],
124
- variableValues: args[4],
125
- operationName: args[5],
126
- fieldResolver: args[6],
127
- subscribeFieldResolver: args[7],
128
- };
129
- }
130
- /**
131
- * Utility function for making a subscribe function that handles polymorphic arguments.
132
- */
133
- const makeSubscribe = (subscribeFn) => ((...polyArgs) => subscribeFn(getSubscribeArgs(polyArgs)));
134
- function mapAsyncIterator(source, mapper) {
135
- const iterator = source[Symbol.asyncIterator]();
136
- async function mapResult(result) {
137
- var _a;
138
- if (result.done) {
139
- return result;
140
- }
141
- try {
142
- return { value: await mapper(result.value), done: false };
143
- }
144
- catch (error) {
145
- try {
146
- await ((_a = iterator.return) === null || _a === void 0 ? void 0 : _a.call(iterator));
147
- }
148
- catch (_error) {
149
- /* ignore error */
150
- }
151
- throw error;
152
- }
153
- }
154
- const stream = {
155
- [Symbol.asyncIterator]() {
156
- return stream;
157
- },
158
- async next() {
159
- return await mapResult(await iterator.next());
160
- },
161
- async return() {
162
- var _a;
163
- const promise = (_a = iterator.return) === null || _a === void 0 ? void 0 : _a.call(iterator);
164
- return promise ? await mapResult(await promise) : { value: undefined, done: true };
165
- },
166
- async throw(error) {
167
- var _a;
168
- const promise = (_a = iterator.throw) === null || _a === void 0 ? void 0 : _a.call(iterator);
169
- if (promise) {
170
- return await mapResult(await promise);
171
- }
172
- // if the source has no throw method we just re-throw error
173
- // usually throw is not called anyways
174
- throw error;
175
- },
176
- };
177
- return stream;
178
- }
179
- function getExecuteArgs(args) {
180
- return args.length === 1
181
- ? args[0]
182
- : {
183
- schema: args[0],
184
- document: args[1],
185
- rootValue: args[2],
186
- contextValue: args[3],
187
- variableValues: args[4],
188
- operationName: args[5],
189
- fieldResolver: args[6],
190
- typeResolver: args[7],
191
- };
192
- }
193
- /**
194
- * Utility function for making a execute function that handles polymorphic arguments.
195
- */
196
- const makeExecute = (executeFn) => ((...polyArgs) => executeFn(getExecuteArgs(polyArgs)));
197
- /**
198
- * Returns true if the provided object implements the AsyncIterator protocol via
199
- * implementing a `Symbol.asyncIterator` method.
200
- *
201
- * Source: https://github.com/graphql/graphql-js/blob/main/src/jsutils/isAsyncIterable.ts
202
- */
203
- function isAsyncIterable(maybeAsyncIterable) {
204
- return (typeof maybeAsyncIterable === 'object' &&
205
- maybeAsyncIterable != null &&
206
- typeof maybeAsyncIterable[Symbol.asyncIterator] === 'function');
207
- }
208
- /**
209
- * A utility function for handling `onExecuteDone` hook result, for simplifying the handling of AsyncIterable returned from `execute`.
210
- *
211
- * @param payload The payload send to `onExecuteDone` hook function
212
- * @param fn The handler to be executed on each result
213
- * @returns a subscription for streamed results, or undefined in case of an non-async
214
- */
215
- function handleStreamOrSingleExecutionResult(payload, fn) {
216
- if (isAsyncIterable(payload.result)) {
217
- return { onNext: fn };
218
- }
219
- else {
220
- fn({
221
- args: payload.args,
222
- result: payload.result,
223
- setResult: payload.setResult,
224
- });
225
- return undefined;
226
- }
227
- }
228
- function finalAsyncIterator(source, onFinal) {
229
- const iterator = source[Symbol.asyncIterator]();
230
- let isDone = false;
231
- const stream = {
232
- [Symbol.asyncIterator]() {
233
- return stream;
234
- },
235
- async next() {
236
- const result = await iterator.next();
237
- if (result.done && isDone === false) {
238
- isDone = true;
239
- onFinal();
240
- }
241
- return result;
242
- },
243
- async return() {
244
- var _a;
245
- const promise = (_a = iterator.return) === null || _a === void 0 ? void 0 : _a.call(iterator);
246
- if (isDone === false) {
247
- isDone = true;
248
- onFinal();
249
- }
250
- return promise ? await promise : { done: true, value: undefined };
251
- },
252
- async throw(error) {
253
- var _a;
254
- const promise = (_a = iterator.throw) === null || _a === void 0 ? void 0 : _a.call(iterator);
255
- if (promise) {
256
- return await promise;
257
- }
258
- // if the source has no throw method we just re-throw error
259
- // usually throw is not called anyways
260
- throw error;
261
- },
262
- };
263
- return stream;
264
- }
265
- function errorAsyncIterator(source, onError) {
266
- const iterator = source[Symbol.asyncIterator]();
267
- const stream = {
268
- [Symbol.asyncIterator]() {
269
- return stream;
270
- },
271
- async next() {
272
- try {
273
- return await iterator.next();
274
- }
275
- catch (error) {
276
- onError(error);
277
- return { done: true, value: undefined };
278
- }
279
- },
280
- async return() {
281
- var _a;
282
- const promise = (_a = iterator.return) === null || _a === void 0 ? void 0 : _a.call(iterator);
283
- return promise ? await promise : { done: true, value: undefined };
284
- },
285
- async throw(error) {
286
- var _a;
287
- const promise = (_a = iterator.throw) === null || _a === void 0 ? void 0 : _a.call(iterator);
288
- if (promise) {
289
- return await promise;
290
- }
291
- // if the source has no throw method we just re-throw error
292
- // usually throw is not called anyways
293
- throw error;
294
- },
295
- };
296
- return stream;
297
- }
298
- function getInMemoryLRUCache({ max = 1000, onDelete = () => { }, } = {}) {
299
- let storage = {};
300
- let keys = [];
301
- return {
302
- get(key) {
303
- return storage[key];
304
- },
305
- set(key, value) {
306
- queueMicrotask(() => {
307
- if (storage[key] != null) {
308
- if (keys.indexOf(key)) {
309
- keys.splice(keys.indexOf(key), 1);
310
- }
311
- }
312
- keys.push(key);
313
- storage[key] = value;
314
- while (keys.length > max) {
315
- const key = keys.shift();
316
- if (key != null) {
317
- onDelete(key, storage[key]);
318
- delete storage[key];
319
- }
320
- }
321
- });
322
- },
323
- delete(key) {
324
- queueMicrotask(() => {
325
- if (storage[key] != null) {
326
- keys.splice(keys.indexOf(key), 1);
327
- onDelete(key, storage[key]);
328
- delete storage[key];
329
- }
330
- });
331
- },
332
- clear() {
333
- queueMicrotask(() => {
334
- storage = {};
335
- keys = [];
336
- });
337
- },
338
- };
339
- }
340
- // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
341
- function isSourceObject(maybeSource) {
342
- return maybeSource != null && maybeSource.body != null;
343
- }
344
-
345
- function createEnvelopOrchestrator(plugins) {
346
- let schema = null;
347
- let initDone = false;
348
- const onResolversHandlers = [];
349
- for (const plugin of plugins) {
350
- if (plugin.onResolverCalled) {
351
- onResolversHandlers.push(plugin.onResolverCalled);
352
- }
353
- }
354
- // Define the initial method for replacing the GraphQL schema, this is needed in order
355
- // to allow setting the schema from the onPluginInit callback. We also need to make sure
356
- // here not to call the same plugin that initiated the schema switch.
357
- const replaceSchema = (newSchema, ignorePluginIndex = -1) => {
358
- if (onResolversHandlers.length) {
359
- prepareTracedSchema(newSchema);
360
- }
361
- schema = newSchema;
362
- if (initDone) {
363
- for (const [i, plugin] of plugins.entries()) {
364
- if (i !== ignorePluginIndex) {
365
- plugin.onSchemaChange &&
366
- plugin.onSchemaChange({
367
- schema,
368
- replaceSchema: schemaToSet => {
369
- replaceSchema(schemaToSet, i);
370
- },
371
- });
372
- }
373
- }
374
- }
375
- };
376
- const contextErrorHandlers = [];
377
- // Iterate all plugins and trigger onPluginInit
378
- for (const [i, plugin] of plugins.entries()) {
379
- plugin.onPluginInit &&
380
- plugin.onPluginInit({
381
- plugins,
382
- addPlugin: newPlugin => {
383
- plugins.push(newPlugin);
384
- },
385
- setSchema: modifiedSchema => replaceSchema(modifiedSchema, i),
386
- registerContextErrorHandler: handler => contextErrorHandlers.push(handler),
387
- });
388
- }
389
- // A set of before callbacks defined here in order to allow it to be used later
390
- const beforeCallbacks = {
391
- init: [],
392
- parse: [],
393
- validate: [],
394
- subscribe: [],
395
- execute: [],
396
- context: [],
397
- };
398
- for (const { onContextBuilding, onExecute, onParse, onSubscribe, onValidate, onEnveloped } of plugins) {
399
- onEnveloped && beforeCallbacks.init.push(onEnveloped);
400
- onContextBuilding && beforeCallbacks.context.push(onContextBuilding);
401
- onExecute && beforeCallbacks.execute.push(onExecute);
402
- onParse && beforeCallbacks.parse.push(onParse);
403
- onSubscribe && beforeCallbacks.subscribe.push(onSubscribe);
404
- onValidate && beforeCallbacks.validate.push(onValidate);
405
- }
406
- const init = initialContext => {
407
- for (const [i, onEnveloped] of beforeCallbacks.init.entries()) {
408
- onEnveloped({
409
- context: initialContext,
410
- extendContext: extension => {
411
- if (!initialContext) {
412
- return;
413
- }
414
- Object.assign(initialContext, extension);
415
- },
416
- setSchema: modifiedSchema => replaceSchema(modifiedSchema, i),
417
- });
418
- }
419
- };
420
- const customParse = beforeCallbacks.parse.length
421
- ? initialContext => (source, parseOptions) => {
422
- let result = null;
423
- let parseFn = parse;
424
- const context = initialContext;
425
- const afterCalls = [];
426
- for (const onParse of beforeCallbacks.parse) {
427
- const afterFn = onParse({
428
- context,
429
- extendContext: extension => {
430
- Object.assign(context, extension);
431
- },
432
- params: { source, options: parseOptions },
433
- parseFn,
434
- setParseFn: newFn => {
435
- parseFn = newFn;
436
- },
437
- setParsedDocument: newDoc => {
438
- result = newDoc;
439
- },
440
- });
441
- afterFn && afterCalls.push(afterFn);
442
- }
443
- if (result === null) {
444
- try {
445
- result = parseFn(source, parseOptions);
446
- }
447
- catch (e) {
448
- result = e;
449
- }
450
- }
451
- for (const afterCb of afterCalls) {
452
- afterCb({
453
- context,
454
- extendContext: extension => {
455
- Object.assign(context, extension);
456
- },
457
- replaceParseResult: newResult => {
458
- result = newResult;
459
- },
460
- result,
461
- });
462
- }
463
- if (result === null) {
464
- throw new Error(`Failed to parse document.`);
465
- }
466
- if (result instanceof Error) {
467
- throw result;
468
- }
469
- return result;
470
- }
471
- : () => parse;
472
- const customValidate = beforeCallbacks.validate.length
473
- ? initialContext => (schema, documentAST, rules, typeInfo, validationOptions) => {
474
- let actualRules = rules ? [...rules] : undefined;
475
- let validateFn = validate;
476
- let result = null;
477
- const context = initialContext;
478
- const afterCalls = [];
479
- for (const onValidate of beforeCallbacks.validate) {
480
- const afterFn = onValidate({
481
- context,
482
- extendContext: extension => {
483
- Object.assign(context, extension);
484
- },
485
- params: {
486
- schema,
487
- documentAST,
488
- rules: actualRules,
489
- typeInfo,
490
- options: validationOptions,
491
- },
492
- validateFn,
493
- addValidationRule: rule => {
494
- if (!actualRules) {
495
- actualRules = [...specifiedRules];
496
- }
497
- actualRules.push(rule);
498
- },
499
- setValidationFn: newFn => {
500
- validateFn = newFn;
501
- },
502
- setResult: newResults => {
503
- result = newResults;
504
- },
505
- });
506
- afterFn && afterCalls.push(afterFn);
507
- }
508
- if (!result) {
509
- result = validateFn(schema, documentAST, actualRules, typeInfo, validationOptions);
510
- }
511
- const valid = result.length === 0;
512
- for (const afterCb of afterCalls) {
513
- afterCb({
514
- valid,
515
- result,
516
- context,
517
- extendContext: extension => {
518
- Object.assign(context, extension);
519
- },
520
- setResult: newResult => {
521
- result = newResult;
522
- },
523
- });
524
- }
525
- return result;
526
- }
527
- : () => validate;
528
- const customContextFactory = beforeCallbacks.context.length
529
- ? initialContext => async (orchestratorCtx) => {
530
- const afterCalls = [];
531
- // In order to have access to the "last working" context object we keep this outside of the try block:
532
- let context = orchestratorCtx ? { ...initialContext, ...orchestratorCtx } : initialContext;
533
- try {
534
- let isBreakingContextBuilding = false;
535
- for (const onContext of beforeCallbacks.context) {
536
- const afterHookResult = await onContext({
537
- context,
538
- extendContext: extension => {
539
- context = { ...context, ...extension };
540
- },
541
- breakContextBuilding: () => {
542
- isBreakingContextBuilding = true;
543
- },
544
- });
545
- if (typeof afterHookResult === 'function') {
546
- afterCalls.push(afterHookResult);
547
- }
548
- if (isBreakingContextBuilding === true) {
549
- break;
550
- }
551
- }
552
- for (const afterCb of afterCalls) {
553
- afterCb({
554
- context,
555
- extendContext: extension => {
556
- context = { ...context, ...extension };
557
- },
558
- });
559
- }
560
- return context;
561
- }
562
- catch (err) {
563
- let error = err;
564
- for (const errorCb of contextErrorHandlers) {
565
- errorCb({
566
- context,
567
- error,
568
- setError: err => {
569
- error = err;
570
- },
571
- });
572
- }
573
- throw error;
574
- }
575
- }
576
- : initialContext => orchestratorCtx => orchestratorCtx ? { ...initialContext, ...orchestratorCtx } : initialContext;
577
- const useCustomSubscribe = beforeCallbacks.subscribe.length || onResolversHandlers.length;
578
- const customSubscribe = useCustomSubscribe
579
- ? makeSubscribe(async (args) => {
580
- let subscribeFn = subscribe;
581
- const afterCalls = [];
582
- const subscribeErrorHandlers = [];
583
- let context = args.contextValue || {};
584
- let result;
585
- for (const onSubscribe of beforeCallbacks.subscribe) {
586
- const after = await onSubscribe({
587
- subscribeFn,
588
- setSubscribeFn: newSubscribeFn => {
589
- subscribeFn = newSubscribeFn;
590
- },
591
- extendContext: extension => {
592
- context = { ...context, ...extension };
593
- },
594
- args: args,
595
- setResultAndStopExecution: stopResult => {
596
- result = stopResult;
597
- },
598
- });
599
- if (after) {
600
- if (after.onSubscribeResult) {
601
- afterCalls.push(after.onSubscribeResult);
602
- }
603
- if (after.onSubscribeError) {
604
- subscribeErrorHandlers.push(after.onSubscribeError);
605
- }
606
- }
607
- if (result !== undefined) {
608
- break;
609
- }
610
- }
611
- if (onResolversHandlers.length) {
612
- context[resolversHooksSymbol] = onResolversHandlers;
613
- }
614
- if (result === undefined) {
615
- result = await subscribeFn({
616
- ...args,
617
- contextValue: context,
618
- // Casted for GraphQL.js 15 compatibility
619
- // Can be removed once we drop support for GraphQL.js 15
620
- });
621
- }
622
- const onNextHandler = [];
623
- const onEndHandler = [];
624
- for (const afterCb of afterCalls) {
625
- const hookResult = afterCb({
626
- args: args,
627
- result,
628
- setResult: newResult => {
629
- result = newResult;
630
- },
631
- });
632
- if (hookResult) {
633
- if (hookResult.onNext) {
634
- onNextHandler.push(hookResult.onNext);
635
- }
636
- if (hookResult.onEnd) {
637
- onEndHandler.push(hookResult.onEnd);
638
- }
639
- }
640
- }
641
- if (onNextHandler.length && isAsyncIterable(result)) {
642
- result = mapAsyncIterator(result, async (result) => {
643
- for (const onNext of onNextHandler) {
644
- await onNext({
645
- args: args,
646
- result,
647
- setResult: newResult => (result = newResult),
648
- });
649
- }
650
- return result;
651
- });
652
- }
653
- if (onEndHandler.length && isAsyncIterable(result)) {
654
- result = finalAsyncIterator(result, () => {
655
- for (const onEnd of onEndHandler) {
656
- onEnd();
657
- }
658
- });
659
- }
660
- if (subscribeErrorHandlers.length && isAsyncIterable(result)) {
661
- result = errorAsyncIterator(result, err => {
662
- let error = err;
663
- for (const handler of subscribeErrorHandlers) {
664
- handler({
665
- error,
666
- setError: err => {
667
- error = err;
668
- },
669
- });
670
- }
671
- throw error;
672
- });
673
- }
674
- return result;
675
- })
676
- : makeSubscribe(subscribe);
677
- const useCustomExecute = beforeCallbacks.execute.length || onResolversHandlers.length;
678
- const customExecute = useCustomExecute
679
- ? makeExecute(async (args) => {
680
- let executeFn = execute;
681
- let result;
682
- const afterCalls = [];
683
- let context = args.contextValue || {};
684
- for (const onExecute of beforeCallbacks.execute) {
685
- const after = await onExecute({
686
- executeFn,
687
- setExecuteFn: newExecuteFn => {
688
- executeFn = newExecuteFn;
689
- },
690
- setResultAndStopExecution: stopResult => {
691
- result = stopResult;
692
- },
693
- extendContext: extension => {
694
- if (typeof extension === 'object') {
695
- context = {
696
- ...(context || {}),
697
- ...extension,
698
- };
699
- }
700
- else {
701
- throw new Error(`Invalid context extension provided! Expected "object", got: "${JSON.stringify(extension)}" (${typeof extension})`);
702
- }
703
- },
704
- args: args,
705
- });
706
- if (after === null || after === void 0 ? void 0 : after.onExecuteDone) {
707
- afterCalls.push(after.onExecuteDone);
708
- }
709
- if (result !== undefined) {
710
- break;
711
- }
712
- }
713
- if (onResolversHandlers.length) {
714
- context[resolversHooksSymbol] = onResolversHandlers;
715
- }
716
- if (result === undefined) {
717
- result = (await executeFn({
718
- ...args,
719
- contextValue: context,
720
- }));
721
- }
722
- const onNextHandler = [];
723
- const onEndHandler = [];
724
- for (const afterCb of afterCalls) {
725
- const hookResult = await afterCb({
726
- args: args,
727
- result,
728
- setResult: newResult => {
729
- result = newResult;
730
- },
731
- });
732
- if (hookResult) {
733
- if (hookResult.onNext) {
734
- onNextHandler.push(hookResult.onNext);
735
- }
736
- if (hookResult.onEnd) {
737
- onEndHandler.push(hookResult.onEnd);
738
- }
739
- }
740
- }
741
- if (onNextHandler.length && isAsyncIterable(result)) {
742
- result = mapAsyncIterator(result, async (result) => {
743
- for (const onNext of onNextHandler) {
744
- await onNext({
745
- args: args,
746
- result,
747
- setResult: newResult => {
748
- result = newResult;
749
- },
750
- });
751
- }
752
- return result;
753
- });
754
- }
755
- if (onEndHandler.length && isAsyncIterable(result)) {
756
- result = finalAsyncIterator(result, () => {
757
- for (const onEnd of onEndHandler) {
758
- onEnd();
759
- }
760
- });
761
- }
762
- return result;
763
- })
764
- : makeExecute(execute);
765
- initDone = true;
766
- // This is done in order to trigger the first schema available, to allow plugins that needs the schema
767
- // eagerly to have it.
768
- if (schema) {
769
- for (const [i, plugin] of plugins.entries()) {
770
- plugin.onSchemaChange &&
771
- plugin.onSchemaChange({
772
- schema,
773
- replaceSchema: modifiedSchema => replaceSchema(modifiedSchema, i),
774
- });
775
- }
776
- }
777
- return {
778
- getCurrentSchema() {
779
- return schema;
780
- },
781
- init,
782
- parse: customParse,
783
- validate: customValidate,
784
- execute: customExecute,
785
- subscribe: customSubscribe,
786
- contextFactory: customContextFactory,
787
- };
788
- }
789
-
790
- const getTimestamp = typeof performance !== 'undefined' && performance.now ? () => performance.now() : () => Date.now();
791
- const measure = () => {
792
- const start = getTimestamp();
793
- return () => {
794
- const end = getTimestamp();
795
- return end - start;
796
- };
797
- };
798
- const tracingSymbol = Symbol('envelopTracing');
799
- function traceOrchestrator(orchestrator) {
800
- const createTracer = (name, ctx) => {
801
- const end = measure();
802
- return () => {
803
- ctx[tracingSymbol][name] = end();
804
- };
805
- };
806
- return {
807
- ...orchestrator,
808
- init: (ctx = {}) => {
809
- ctx[tracingSymbol] = ctx[tracingSymbol] || {};
810
- const done = createTracer('init', ctx || {});
811
- try {
812
- return orchestrator.init(ctx);
813
- }
814
- finally {
815
- done();
816
- }
817
- },
818
- parse: (ctx = {}) => {
819
- ctx[tracingSymbol] = ctx[tracingSymbol] || {};
820
- const actualFn = orchestrator.parse(ctx);
821
- return (...args) => {
822
- const done = createTracer('parse', ctx);
823
- try {
824
- return actualFn(...args);
825
- }
826
- finally {
827
- done();
828
- }
829
- };
830
- },
831
- validate: (ctx = {}) => {
832
- ctx[tracingSymbol] = ctx[tracingSymbol] || {};
833
- const actualFn = orchestrator.validate(ctx);
834
- return (...args) => {
835
- const done = createTracer('validate', ctx);
836
- try {
837
- return actualFn(...args);
838
- }
839
- finally {
840
- done();
841
- }
842
- };
843
- },
844
- execute: async (argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, typeResolver) => {
845
- const args = argsOrSchema instanceof GraphQLSchema
846
- ? {
847
- schema: argsOrSchema,
848
- document: document,
849
- rootValue,
850
- contextValue,
851
- variableValues,
852
- operationName,
853
- fieldResolver,
854
- typeResolver,
855
- }
856
- : argsOrSchema;
857
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
858
- // @ts-ignore GraphQL.js types contextValue as unknown
859
- const done = createTracer('execute', args.contextValue || {});
860
- try {
861
- const result = await orchestrator.execute(args);
862
- done();
863
- if (!isAsyncIterable(result)) {
864
- result.extensions = result.extensions || {};
865
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
866
- // @ts-ignore GraphQL.js types contextValue as unknown
867
- result.extensions.envelopTracing = args.contextValue[tracingSymbol];
868
- }
869
- else {
870
- // eslint-disable-next-line no-console
871
- console.warn(`"traceOrchestrator" encountered a AsyncIterator which is not supported yet, so tracing data is not available for the operation.`);
872
- }
873
- return result;
874
- }
875
- catch (e) {
876
- done();
877
- throw e;
878
- }
879
- },
880
- subscribe: async (argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, subscribeFieldResolver) => {
881
- const args = argsOrSchema instanceof GraphQLSchema
882
- ? {
883
- schema: argsOrSchema,
884
- document: document,
885
- rootValue,
886
- contextValue,
887
- variableValues,
888
- operationName,
889
- fieldResolver,
890
- subscribeFieldResolver,
891
- }
892
- : argsOrSchema;
893
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
894
- // @ts-ignore GraphQL.js types contextValue as unknown
895
- const done = createTracer('subscribe', args.contextValue || {});
896
- try {
897
- return await orchestrator.subscribe(args);
898
- }
899
- finally {
900
- done();
901
- }
902
- },
903
- contextFactory: (ctx = {}) => {
904
- const actualFn = orchestrator.contextFactory(ctx);
905
- return async (childCtx) => {
906
- const done = createTracer('contextFactory', ctx);
907
- try {
908
- return await actualFn(childCtx);
909
- }
910
- finally {
911
- done();
912
- }
913
- };
914
- },
915
- };
916
- }
917
-
918
- function envelop(options) {
919
- const plugins = options.plugins.filter(isPluginEnabled);
920
- let orchestrator = createEnvelopOrchestrator(plugins);
921
- if (options.enableInternalTracing) {
922
- orchestrator = traceOrchestrator(orchestrator);
923
- }
924
- const getEnveloped = (initialContext = {}) => {
925
- const typedOrchestrator = orchestrator;
926
- typedOrchestrator.init(initialContext);
927
- return {
928
- parse: typedOrchestrator.parse(initialContext),
929
- validate: typedOrchestrator.validate(initialContext),
930
- contextFactory: typedOrchestrator.contextFactory(initialContext),
931
- execute: typedOrchestrator.execute,
932
- subscribe: typedOrchestrator.subscribe,
933
- schema: typedOrchestrator.getCurrentSchema(),
934
- };
935
- };
936
- getEnveloped._plugins = plugins;
937
- return getEnveloped;
938
- }
939
-
940
- const useEnvelop = (envelop) => {
941
- return {
942
- onPluginInit({ addPlugin }) {
943
- for (const plugin of envelop._plugins) {
944
- addPlugin(plugin);
945
- }
946
- },
947
- };
948
- };
949
-
950
- const DEFAULT_OPTIONS = {
951
- logFn: console.log,
952
- };
953
- const useLogger = (rawOptions = DEFAULT_OPTIONS) => {
954
- const options = {
955
- DEFAULT_OPTIONS,
956
- ...rawOptions,
957
- };
958
- return {
959
- onParse({ extendContext, params }) {
960
- if (options.skipIntrospection && isIntrospectionOperationString(params.source)) {
961
- extendContext({
962
- [envelopIsIntrospectionSymbol]: true,
963
- });
964
- }
965
- },
966
- onExecute({ args }) {
967
- if (args.contextValue[envelopIsIntrospectionSymbol]) {
968
- return;
969
- }
970
- options.logFn('execute-start', { args });
971
- return {
972
- onExecuteDone: ({ result }) => {
973
- options.logFn('execute-end', { args, result });
974
- },
975
- };
976
- },
977
- onSubscribe({ args }) {
978
- if (args.contextValue[envelopIsIntrospectionSymbol]) {
979
- return;
980
- }
981
- options.logFn('subscribe-start', { args });
982
- return {
983
- onSubscribeResult: ({ result }) => {
984
- options.logFn('subscribe-end', { args, result });
985
- },
986
- };
987
- },
988
- };
989
- };
990
-
991
- const HR_TO_NS = 1e9;
992
- const NS_TO_MS = 1e6;
993
- const DEFAULT_OPTIONS$1 = {
994
- onExecutionMeasurement: (args, timing) => console.log(`Operation execution "${args.operationName}" done in ${timing.ms}ms`),
995
- onSubscriptionMeasurement: (args, timing) => console.log(`Operation subscription "${args.operationName}" done in ${timing.ms}ms`),
996
- onParsingMeasurement: (source, timing) => console.log(`Parsing "${source}" done in ${timing.ms}ms`),
997
- onValidationMeasurement: (document, timing) => { var _a, _b; return console.log(`Validation "${((_b = (_a = getOperationAST(document)) === null || _a === void 0 ? void 0 : _a.name) === null || _b === void 0 ? void 0 : _b.value) || '-'}" done in ${timing.ms}ms`); },
998
- onResolverMeasurement: (info, timing) => console.log(`\tResolver of "${info.parentType.toString()}.${info.fieldName}" done in ${timing.ms}ms`),
999
- onContextBuildingMeasurement: (timing) => console.log(`Context building done in ${timing.ms}ms`),
1000
- };
1001
- const deltaFrom = (hrtime) => {
1002
- const delta = process.hrtime(hrtime);
1003
- const ns = delta[0] * HR_TO_NS + delta[1];
1004
- return {
1005
- ns,
1006
- get ms() {
1007
- return ns / NS_TO_MS;
1008
- },
1009
- };
1010
- };
1011
- const useTiming = (rawOptions) => {
1012
- const options = {
1013
- ...DEFAULT_OPTIONS$1,
1014
- ...(rawOptions || {}),
1015
- };
1016
- const result = {};
1017
- if (options.onContextBuildingMeasurement) {
1018
- result.onContextBuilding = ({ context }) => {
1019
- if (context[envelopIsIntrospectionSymbol]) {
1020
- return;
1021
- }
1022
- const contextStartTime = process.hrtime();
1023
- return () => {
1024
- options.onContextBuildingMeasurement(deltaFrom(contextStartTime));
1025
- };
1026
- };
1027
- }
1028
- if (options.onParsingMeasurement) {
1029
- result.onParse = ({ params, extendContext }) => {
1030
- if (options.skipIntrospection && isIntrospectionOperationString(params.source)) {
1031
- extendContext({
1032
- [envelopIsIntrospectionSymbol]: true,
1033
- });
1034
- return;
1035
- }
1036
- const parseStartTime = process.hrtime();
1037
- return () => {
1038
- options.onParsingMeasurement(params.source, deltaFrom(parseStartTime));
1039
- };
1040
- };
1041
- }
1042
- if (options.onValidationMeasurement) {
1043
- result.onValidate = ({ params, context }) => {
1044
- if (context[envelopIsIntrospectionSymbol]) {
1045
- return;
1046
- }
1047
- const validateStartTime = process.hrtime();
1048
- return () => {
1049
- options.onValidationMeasurement(params.documentAST, deltaFrom(validateStartTime));
1050
- };
1051
- };
1052
- }
1053
- if (options.onExecutionMeasurement) {
1054
- if (options.onResolverMeasurement) {
1055
- result.onExecute = ({ args }) => {
1056
- if (args.contextValue[envelopIsIntrospectionSymbol]) {
1057
- return;
1058
- }
1059
- const executeStartTime = process.hrtime();
1060
- return {
1061
- onExecuteDone: () => {
1062
- options.onExecutionMeasurement(args, deltaFrom(executeStartTime));
1063
- },
1064
- };
1065
- };
1066
- result.onResolverCalled = ({ info }) => {
1067
- const resolverStartTime = process.hrtime();
1068
- return () => {
1069
- options.onResolverMeasurement(info, deltaFrom(resolverStartTime));
1070
- };
1071
- };
1072
- }
1073
- else {
1074
- result.onExecute = ({ args }) => {
1075
- if (args.contextValue[envelopIsIntrospectionSymbol]) {
1076
- return;
1077
- }
1078
- const executeStartTime = process.hrtime();
1079
- return {
1080
- onExecuteDone: () => {
1081
- options.onExecutionMeasurement(args, deltaFrom(executeStartTime));
1082
- },
1083
- };
1084
- };
1085
- }
1086
- }
1087
- if (options.onSubscriptionMeasurement) {
1088
- if (options.onResolverMeasurement) {
1089
- result.onSubscribe = ({ args }) => {
1090
- if (args.contextValue[envelopIsIntrospectionSymbol]) {
1091
- return;
1092
- }
1093
- const subscribeStartTime = process.hrtime();
1094
- return {
1095
- onSubscribeResult: () => {
1096
- options.onSubscriptionMeasurement && options.onSubscriptionMeasurement(args, deltaFrom(subscribeStartTime));
1097
- },
1098
- };
1099
- };
1100
- result.onResolverCalled = ({ info }) => {
1101
- const resolverStartTime = process.hrtime();
1102
- return () => {
1103
- options.onResolverMeasurement && options.onResolverMeasurement(info, deltaFrom(resolverStartTime));
1104
- };
1105
- };
1106
- }
1107
- else {
1108
- result.onSubscribe = ({ args }) => {
1109
- if (args.contextValue[envelopIsIntrospectionSymbol]) {
1110
- return;
1111
- }
1112
- const subscribeStartTime = process.hrtime();
1113
- return {
1114
- onSubscribeResult: () => {
1115
- options.onSubscriptionMeasurement && options.onSubscriptionMeasurement(args, deltaFrom(subscribeStartTime));
1116
- },
1117
- };
1118
- };
1119
- }
1120
- }
1121
- return result;
1122
- };
1123
-
1124
- const useSchema = (schema) => {
1125
- return {
1126
- onPluginInit({ setSchema }) {
1127
- setSchema(schema);
1128
- },
1129
- };
1130
- };
1131
- const useLazyLoadedSchema = (schemaLoader) => {
1132
- return {
1133
- onEnveloped({ setSchema, context }) {
1134
- setSchema(schemaLoader(context));
1135
- },
1136
- };
1137
- };
1138
- const useAsyncSchema = (schemaPromise) => {
1139
- return {
1140
- onPluginInit({ setSchema }) {
1141
- schemaPromise.then(schemaObj => {
1142
- setSchema(schemaObj);
1143
- });
1144
- },
1145
- };
1146
- };
1147
-
1148
- const makeHandleResult = (errorHandler) => ({ result, args }) => {
1149
- var _a;
1150
- if ((_a = result.errors) === null || _a === void 0 ? void 0 : _a.length) {
1151
- errorHandler(result.errors, args);
1152
- }
1153
- };
1154
- const useErrorHandler = (errorHandler) => ({
1155
- onExecute() {
1156
- const handleResult = makeHandleResult(errorHandler);
1157
- return {
1158
- onExecuteDone(payload) {
1159
- return handleStreamOrSingleExecutionResult(payload, handleResult);
1160
- },
1161
- };
1162
- },
1163
- });
1164
-
1165
- const useExtendContext = (contextFactory) => ({
1166
- async onContextBuilding({ context, extendContext }) {
1167
- extendContext((await contextFactory(context)));
1168
- },
1169
- });
1170
-
1171
- const makeHandleResult$1 = (formatter) => ({ args, result, setResult, }) => {
1172
- const modified = formatter(result, args);
1173
- if (modified !== false) {
1174
- setResult(modified);
1175
- }
1176
- };
1177
- const usePayloadFormatter = (formatter) => ({
1178
- onExecute() {
1179
- const handleResult = makeHandleResult$1(formatter);
1180
- return {
1181
- onExecuteDone(payload) {
1182
- return handleStreamOrSingleExecutionResult(payload, handleResult);
1183
- },
1184
- };
1185
- },
1186
- });
1187
-
1188
- const DEFAULT_ERROR_MESSAGE = 'Unexpected error.';
1189
- class EnvelopError extends GraphQLError {
1190
- constructor(message, extensions) {
1191
- super(message, undefined, undefined, undefined, undefined, undefined, extensions);
1192
- }
1193
- }
1194
- const formatError = (err, message, isDev) => {
1195
- var _a, _b, _c, _d;
1196
- if (err instanceof GraphQLError) {
1197
- if (
1198
- /** execution error */
1199
- (err.originalError && err.originalError instanceof EnvelopError === false) ||
1200
- /** validate and parse errors */
1201
- (err.originalError === undefined && err instanceof EnvelopError === false)) {
1202
- return new GraphQLError(message, err.nodes, err.source, err.positions, err.path, undefined, isDev
1203
- ? {
1204
- originalError: {
1205
- message: (_b = (_a = err.originalError) === null || _a === void 0 ? void 0 : _a.message) !== null && _b !== void 0 ? _b : err.message,
1206
- stack: (_d = (_c = err.originalError) === null || _c === void 0 ? void 0 : _c.stack) !== null && _d !== void 0 ? _d : err.stack,
1207
- },
1208
- }
1209
- : undefined);
1210
- }
1211
- return err;
1212
- }
1213
- return new GraphQLError(message);
1214
- };
1215
- const makeHandleResult$2 = (format, message, isDev) => ({ result, setResult }) => {
1216
- if (result.errors != null) {
1217
- setResult({ ...result, errors: result.errors.map(error => format(error, message, isDev)) });
1218
- }
1219
- };
1220
- const useMaskedErrors = (opts) => {
1221
- var _a, _b;
1222
- const format = (_a = opts === null || opts === void 0 ? void 0 : opts.formatError) !== null && _a !== void 0 ? _a : formatError;
1223
- const message = (opts === null || opts === void 0 ? void 0 : opts.errorMessage) || DEFAULT_ERROR_MESSAGE;
1224
- // eslint-disable-next-line dot-notation
1225
- const isDev = (_b = opts === null || opts === void 0 ? void 0 : opts.isDev) !== null && _b !== void 0 ? _b : (typeof process !== 'undefined' ? process.env['NODE_ENV'] === 'development' : false);
1226
- const handleResult = makeHandleResult$2(format, message, isDev);
1227
- return {
1228
- onParse: (opts === null || opts === void 0 ? void 0 : opts.handleParseErrors) === true
1229
- ? function onParse() {
1230
- return function onParseEnd({ result, replaceParseResult }) {
1231
- if (result instanceof Error) {
1232
- replaceParseResult(format(result, message, isDev));
1233
- }
1234
- };
1235
- }
1236
- : undefined,
1237
- onValidate: (opts === null || opts === void 0 ? void 0 : opts.handleValidationErrors) === true
1238
- ? function onValidate() {
1239
- return function onValidateEnd({ valid, result, setResult }) {
1240
- if (valid === false) {
1241
- setResult(result.map(error => format(error, message, isDev)));
1242
- }
1243
- };
1244
- }
1245
- : undefined,
1246
- onPluginInit(context) {
1247
- context.registerContextErrorHandler(({ error, setError }) => {
1248
- setError(formatError(error, message, isDev));
1249
- });
1250
- },
1251
- onExecute() {
1252
- return {
1253
- onExecuteDone(payload) {
1254
- return handleStreamOrSingleExecutionResult(payload, handleResult);
1255
- },
1256
- };
1257
- },
1258
- onSubscribe() {
1259
- return {
1260
- onSubscribeResult(payload) {
1261
- return handleStreamOrSingleExecutionResult(payload, handleResult);
1262
- },
1263
- onSubscribeError({ error, setError }) {
1264
- setError(formatError(error, message, isDev));
1265
- },
1266
- };
1267
- },
1268
- };
1269
- };
1270
-
1271
- const OnNonIntrospectionFieldReachedValidationRule = (onNonIntrospectionField) => ctx => {
1272
- const rootQueryType = ctx.getSchema().getQueryType();
1273
- const rootMutationType = ctx.getSchema().getMutationType();
1274
- const rootSubscriptionType = ctx.getSchema().getSubscriptionType();
1275
- return {
1276
- Field(field) {
1277
- const parentType = ctx.getParentType();
1278
- const isQuery = parentType === rootQueryType;
1279
- const isMutation = parentType === rootMutationType;
1280
- const isSubscription = parentType === rootSubscriptionType;
1281
- if ((isQuery && !field.name.value.startsWith('__')) || isMutation || isSubscription) {
1282
- onNonIntrospectionField();
1283
- return BREAK;
1284
- }
1285
- return undefined;
1286
- },
1287
- };
1288
- };
1289
- const fastIntroSpectionSymbol = Symbol('fastIntrospection');
1290
- /**
1291
- * In case a GraphQL operation only contains introspection fields the context building can be skipped completely.
1292
- * With this plugin any further context extensions will be skipped.
1293
- */
1294
- const useImmediateIntrospection = () => {
1295
- return {
1296
- onValidate({ addValidationRule }) {
1297
- let isIntrospectionOnly = true;
1298
- addValidationRule(OnNonIntrospectionFieldReachedValidationRule(() => {
1299
- isIntrospectionOnly = false;
1300
- }));
1301
- return function afterValidate({ extendContext }) {
1302
- if (isIntrospectionOnly) {
1303
- extendContext({ [fastIntroSpectionSymbol]: true });
1304
- }
1305
- };
1306
- },
1307
- onContextBuilding({ context, breakContextBuilding }) {
1308
- if (context[fastIntroSpectionSymbol]) {
1309
- // hijack and skip all other context related stuff.
1310
- // We dont need a context!
1311
- breakContextBuilding();
1312
- }
1313
- },
1314
- };
1315
- };
1316
-
1317
- export { DEFAULT_ERROR_MESSAGE, EnvelopError, enableIf, envelop, envelopIsIntrospectionSymbol, errorAsyncIterator, finalAsyncIterator, formatError, getInMemoryLRUCache, handleStreamOrSingleExecutionResult, isAsyncIterable, isIntrospectionDocument, isIntrospectionOperation, isIntrospectionOperationString, isOperationDefinition, isPluginEnabled, isSourceObject, makeExecute, makeSubscribe, mapAsyncIterator, useAsyncSchema, useEnvelop, useErrorHandler, useExtendContext, useImmediateIntrospection, useLazyLoadedSchema, useLogger, useMaskedErrors, usePayloadFormatter, useSchema, useTiming };