graphql-jit 0.8.9 → 0.9.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 (178) hide show
  1. package/README.md +25 -0
  2. package/dist/cjs/ast.d.ts +89 -0
  3. package/dist/cjs/ast.js +766 -0
  4. package/dist/cjs/ast.js.map +1 -0
  5. package/dist/cjs/compat.d.ts +70 -0
  6. package/dist/cjs/compat.js +144 -0
  7. package/dist/cjs/compat.js.map +1 -0
  8. package/dist/cjs/debug.d.ts +29 -0
  9. package/dist/cjs/debug.js +46 -0
  10. package/dist/cjs/debug.js.map +1 -0
  11. package/dist/cjs/error.d.ts +7 -0
  12. package/dist/cjs/error.js +58 -0
  13. package/dist/cjs/error.js.map +1 -0
  14. package/dist/cjs/execution.d.ts +154 -0
  15. package/dist/cjs/execution.js +1240 -0
  16. package/dist/cjs/execution.js.map +1 -0
  17. package/dist/cjs/generate.d.ts +4 -0
  18. package/dist/cjs/generate.js +13 -0
  19. package/dist/cjs/generate.js.map +1 -0
  20. package/dist/cjs/index.d.ts +3 -0
  21. package/dist/cjs/index.js +10 -0
  22. package/dist/cjs/index.js.map +1 -0
  23. package/dist/cjs/inspect.d.ts +5 -0
  24. package/dist/cjs/inspect.js +110 -0
  25. package/dist/cjs/inspect.js.map +1 -0
  26. package/dist/cjs/json.d.ts +9 -0
  27. package/dist/cjs/json.js +144 -0
  28. package/dist/cjs/json.js.map +1 -0
  29. package/dist/cjs/memoize.d.ts +5 -0
  30. package/dist/cjs/memoize.js +28 -0
  31. package/dist/cjs/memoize.js.map +1 -0
  32. package/dist/cjs/non-null.d.ts +9 -0
  33. package/dist/cjs/non-null.js +205 -0
  34. package/dist/cjs/non-null.js.map +1 -0
  35. package/dist/cjs/package.json +3 -0
  36. package/dist/{resolve-info.d.ts → cjs/resolve-info.d.ts} +10 -12
  37. package/dist/cjs/resolve-info.js +232 -0
  38. package/dist/cjs/resolve-info.js.map +1 -0
  39. package/dist/cjs/runtime.d.ts +14 -0
  40. package/dist/cjs/runtime.js +92 -0
  41. package/dist/cjs/runtime.js.map +1 -0
  42. package/dist/cjs/types.d.ts +1 -0
  43. package/dist/cjs/types.js +3 -0
  44. package/dist/cjs/types.js.map +1 -0
  45. package/dist/cjs/variables.d.ts +20 -0
  46. package/dist/cjs/variables.js +357 -0
  47. package/dist/cjs/variables.js.map +1 -0
  48. package/dist/esm/ast.d.ts +89 -0
  49. package/dist/esm/ast.js +751 -0
  50. package/dist/esm/ast.js.map +1 -0
  51. package/dist/esm/compat.d.ts +70 -0
  52. package/dist/esm/compat.js +102 -0
  53. package/dist/esm/compat.js.map +1 -0
  54. package/dist/esm/debug.d.ts +29 -0
  55. package/dist/esm/debug.js +40 -0
  56. package/dist/esm/debug.js.map +1 -0
  57. package/dist/esm/error.d.ts +7 -0
  58. package/dist/esm/error.js +55 -0
  59. package/dist/esm/error.js.map +1 -0
  60. package/dist/esm/execution.d.ts +154 -0
  61. package/dist/esm/execution.js +1227 -0
  62. package/dist/esm/execution.js.map +1 -0
  63. package/dist/esm/generate.d.ts +4 -0
  64. package/dist/esm/generate.js +10 -0
  65. package/dist/esm/generate.js.map +1 -0
  66. package/dist/esm/index.d.ts +3 -0
  67. package/dist/esm/index.js +3 -0
  68. package/dist/esm/index.js.map +1 -0
  69. package/dist/esm/inspect.d.ts +5 -0
  70. package/dist/esm/inspect.js +106 -0
  71. package/dist/esm/inspect.js.map +1 -0
  72. package/dist/esm/json.d.ts +9 -0
  73. package/dist/esm/json.js +141 -0
  74. package/dist/esm/json.js.map +1 -0
  75. package/dist/esm/memoize.d.ts +5 -0
  76. package/dist/esm/memoize.js +20 -0
  77. package/dist/esm/memoize.js.map +1 -0
  78. package/dist/esm/non-null.d.ts +9 -0
  79. package/dist/esm/non-null.js +199 -0
  80. package/dist/esm/non-null.js.map +1 -0
  81. package/dist/esm/package.json +3 -0
  82. package/dist/{resolve-info.d.mts → esm/resolve-info.d.ts} +10 -12
  83. package/dist/esm/resolve-info.js +224 -0
  84. package/dist/esm/resolve-info.js.map +1 -0
  85. package/dist/esm/runtime.d.ts +14 -0
  86. package/dist/esm/runtime.js +89 -0
  87. package/dist/esm/runtime.js.map +1 -0
  88. package/dist/esm/types.d.ts +1 -0
  89. package/dist/esm/types.js +2 -0
  90. package/dist/esm/types.js.map +1 -0
  91. package/dist/esm/variables.d.ts +20 -0
  92. package/dist/esm/variables.js +350 -0
  93. package/dist/esm/variables.js.map +1 -0
  94. package/package.json +39 -35
  95. package/dist/ast.d.mts +0 -7
  96. package/dist/ast.d.ts +0 -7
  97. package/dist/ast.js +0 -635
  98. package/dist/ast.js.map +0 -1
  99. package/dist/ast.mjs +0 -612
  100. package/dist/ast.mjs.map +0 -1
  101. package/dist/compat.d.mts +0 -7
  102. package/dist/compat.d.ts +0 -7
  103. package/dist/compat.js +0 -113
  104. package/dist/compat.js.map +0 -1
  105. package/dist/compat.mjs +0 -75
  106. package/dist/compat.mjs.map +0 -1
  107. package/dist/error.d.mts +0 -11
  108. package/dist/error.d.ts +0 -11
  109. package/dist/error.js +0 -79
  110. package/dist/error.js.map +0 -1
  111. package/dist/error.mjs +0 -57
  112. package/dist/error.mjs.map +0 -1
  113. package/dist/execution.d.mts +0 -7
  114. package/dist/execution.d.ts +0 -7
  115. package/dist/execution.js +0 -1262
  116. package/dist/execution.js.map +0 -1
  117. package/dist/execution.mjs +0 -1248
  118. package/dist/execution.mjs.map +0 -1
  119. package/dist/generate.d.mts +0 -6
  120. package/dist/generate.d.ts +0 -6
  121. package/dist/generate.js +0 -37
  122. package/dist/generate.js.map +0 -1
  123. package/dist/generate.mjs +0 -13
  124. package/dist/generate.mjs.map +0 -1
  125. package/dist/index-CeluTkd4.d.mts +0 -329
  126. package/dist/index-mKv2zpdA.d.ts +0 -329
  127. package/dist/index.d.mts +0 -7
  128. package/dist/index.d.ts +0 -7
  129. package/dist/index.js +0 -36
  130. package/dist/index.js.map +0 -1
  131. package/dist/index.mjs +0 -15
  132. package/dist/index.mjs.map +0 -1
  133. package/dist/inspect.d.mts +0 -7
  134. package/dist/inspect.d.ts +0 -7
  135. package/dist/inspect.js +0 -121
  136. package/dist/inspect.js.map +0 -1
  137. package/dist/inspect.mjs +0 -97
  138. package/dist/inspect.mjs.map +0 -1
  139. package/dist/json.d.mts +0 -18
  140. package/dist/json.d.ts +0 -18
  141. package/dist/json.js +0 -181
  142. package/dist/json.js.map +0 -1
  143. package/dist/json.mjs +0 -164
  144. package/dist/json.mjs.map +0 -1
  145. package/dist/memoize.d.mts +0 -6
  146. package/dist/memoize.d.ts +0 -6
  147. package/dist/memoize.js +0 -67
  148. package/dist/memoize.js.map +0 -1
  149. package/dist/memoize.mjs +0 -31
  150. package/dist/memoize.mjs.map +0 -1
  151. package/dist/non-null.d.mts +0 -7
  152. package/dist/non-null.d.ts +0 -7
  153. package/dist/non-null.js +0 -196
  154. package/dist/non-null.js.map +0 -1
  155. package/dist/non-null.mjs +0 -167
  156. package/dist/non-null.mjs.map +0 -1
  157. package/dist/resolve-info.js +0 -245
  158. package/dist/resolve-info.js.map +0 -1
  159. package/dist/resolve-info.mjs +0 -219
  160. package/dist/resolve-info.mjs.map +0 -1
  161. package/dist/runtime.d.mts +0 -7
  162. package/dist/runtime.d.ts +0 -7
  163. package/dist/runtime.js +0 -115
  164. package/dist/runtime.js.map +0 -1
  165. package/dist/runtime.mjs +0 -91
  166. package/dist/runtime.mjs.map +0 -1
  167. package/dist/types.d.mts +0 -3
  168. package/dist/types.d.ts +0 -3
  169. package/dist/types.js +0 -17
  170. package/dist/types.js.map +0 -1
  171. package/dist/types.mjs +0 -1
  172. package/dist/types.mjs.map +0 -1
  173. package/dist/variables.d.mts +0 -17
  174. package/dist/variables.d.ts +0 -17
  175. package/dist/variables.js +0 -412
  176. package/dist/variables.js.map +0 -1
  177. package/dist/variables.mjs +0 -391
  178. package/dist/variables.mjs.map +0 -1
@@ -1,1248 +0,0 @@
1
- import fastJson from "fast-json-stringify";
2
- import { genFn } from "./generate";
3
- import { jitRuntime } from "./runtime";
4
- const GLOBAL_RUNTIME_NAME = "__context.rt";
5
- import {
6
- GraphQLEnumType,
7
- GraphQLError,
8
- isAbstractType,
9
- isLeafType,
10
- isListType,
11
- isNonNullType,
12
- isObjectType,
13
- isSpecifiedScalarType,
14
- Kind,
15
- locatedError,
16
- TypeNameMetaFieldDef
17
- } from "graphql";
18
- import { pathToArray } from "graphql/jsutils/Path.js";
19
- import {
20
- addPath,
21
- collectFields,
22
- collectSubfields,
23
- computeLocations,
24
- flattenPath,
25
- getArgumentDefs,
26
- joinSkipIncludePath,
27
- resolveFieldDef,
28
- serializeObjectPathForSkipInclude
29
- } from "./ast.js";
30
- import { GraphQLError as GraphqlJitError } from "./error.js";
31
- import createInspect from "./inspect.js";
32
- import { queryToJSONSchema } from "./json.js";
33
- import { createNullTrimmer } from "./non-null.js";
34
- import {
35
- createResolveInfoThunk
36
- } from "./resolve-info.js";
37
- import {
38
- compileVariableParsing,
39
- failToParseVariables
40
- } from "./variables.js";
41
- import { getGraphQLErrorOptions, getOperationRootType } from "./compat.js";
42
- const inspect = createInspect();
43
- const SAFETY_CHECK_PREFIX = "__validNode";
44
- const GLOBAL_DATA_NAME = "__context.data";
45
- const GLOBAL_ERRORS_NAME = "__context.errors";
46
- const GLOBAL_NULL_ERRORS_NAME = "__context.nullErrors";
47
- const GLOBAL_ROOT_NAME = "__context.rootValue";
48
- const GLOBAL_VARIABLES_NAME = "__context.variables";
49
- const GLOBAL_CONTEXT_NAME = "__context.context";
50
- const GLOBAL_EXECUTION_CONTEXT = "__context";
51
- const GLOBAL_PROMISE_COUNTER = "__context.promiseCounter";
52
- const GLOBAL_INSPECT_NAME = "__context.inspect";
53
- const GLOBAL_SAFE_MAP_NAME = `${GLOBAL_RUNTIME_NAME}.safeMap`;
54
- const GRAPHQL_ERROR = "__context.GraphQLError";
55
- const GLOBAL_RESOLVE = "__context.resolve";
56
- const GLOBAL_PARENT_NAME = "__parent";
57
- const LOCAL_JS_FIELD_NAME_PREFIX = "__field";
58
- function compileQuery(schema, document, operationName, partialOptions) {
59
- if (!schema) {
60
- throw new Error(`Expected ${schema} to be a GraphQL schema.`);
61
- }
62
- if (!document) {
63
- throw new Error("Must provide document.");
64
- }
65
- if (partialOptions && partialOptions.resolverInfoEnricher && typeof partialOptions.resolverInfoEnricher !== "function") {
66
- throw new Error("resolverInfoEnricher must be a function");
67
- }
68
- try {
69
- const options = {
70
- disablingCapturingStackErrors: false,
71
- customJSONSerializer: false,
72
- disableLeafSerialization: false,
73
- customSerializers: {},
74
- useExperimentalPathBasedSkipInclude: false,
75
- ...partialOptions
76
- };
77
- const context = buildCompilationContext(
78
- schema,
79
- document,
80
- options,
81
- operationName
82
- );
83
- let stringify;
84
- if (options.customJSONSerializer) {
85
- const jsonSchema = queryToJSONSchema(context);
86
- stringify = fastJson(jsonSchema);
87
- } else {
88
- stringify = JSON.stringify;
89
- }
90
- const getVariables = compileVariableParsing(
91
- schema,
92
- context.operation.variableDefinitions || []
93
- );
94
- const type = getOperationRootType(context.schema, context.operation);
95
- const fieldMap = collectFields(
96
- context,
97
- type,
98
- context.operation.selectionSet,
99
- /* @__PURE__ */ Object.create(null),
100
- /* @__PURE__ */ Object.create(null)
101
- );
102
- const functionBody = compileOperation(context, type, fieldMap);
103
- const compiledQuery = {
104
- query: createBoundQuery(
105
- context,
106
- document,
107
- // eslint-disable-next-line no-new-func
108
- new Function("return " + functionBody)(),
109
- getVariables,
110
- context.operation.name != null ? context.operation.name.value : void 0
111
- ),
112
- stringify
113
- };
114
- if (context.operation.operation === "subscription") {
115
- compiledQuery.subscribe = createBoundSubscribe(
116
- context,
117
- document,
118
- compileSubscriptionOperation(
119
- context,
120
- type,
121
- fieldMap,
122
- compiledQuery.query
123
- ),
124
- getVariables,
125
- context.operation.name != null ? context.operation.name.value : void 0
126
- );
127
- }
128
- if (options.debug) {
129
- compiledQuery.__DO_NOT_USE_THIS_OR_YOU_WILL_BE_FIRED_compilation = functionBody;
130
- }
131
- return compiledQuery;
132
- } catch (err) {
133
- return {
134
- errors: normalizeErrors(err)
135
- };
136
- }
137
- }
138
- function isCompiledQuery(query) {
139
- return "query" in query && typeof query.query === "function";
140
- }
141
- function createBoundQuery(compilationContext, document, func, getVariableValues, operationName) {
142
- const { resolvers, typeResolvers, isTypeOfs, serializers, resolveInfos } = compilationContext;
143
- const trimmer = createNullTrimmer(compilationContext);
144
- const fnName = operationName || "query";
145
- const ret = {
146
- [fnName](rootValue, context, variables) {
147
- const parsedVariables = getVariableValues(variables || {});
148
- if (failToParseVariables(parsedVariables)) {
149
- return { errors: parsedVariables.errors };
150
- }
151
- const executionContext = {
152
- rootValue,
153
- context,
154
- variables: parsedVariables.coerced,
155
- inspect,
156
- GraphQLError: GraphqlJitError,
157
- resolvers,
158
- typeResolvers,
159
- isTypeOfs,
160
- serializers,
161
- resolveInfos,
162
- trimmer,
163
- rt: jitRuntime,
164
- promiseCounter: 0,
165
- data: {},
166
- nullErrors: [],
167
- errors: []
168
- };
169
- const result = func.call(null, executionContext);
170
- if (isPromise(result)) {
171
- return result.then(postProcessResult);
172
- }
173
- return postProcessResult(executionContext);
174
- }
175
- };
176
- return ret[fnName];
177
- }
178
- function postProcessResult({
179
- data,
180
- nullErrors,
181
- errors,
182
- trimmer
183
- }) {
184
- if (nullErrors.length > 0) {
185
- const trimmed = trimmer(data, nullErrors);
186
- return {
187
- data: trimmed.data,
188
- errors: errors.concat(trimmed.errors)
189
- };
190
- } else if (errors.length > 0) {
191
- return {
192
- data,
193
- errors
194
- };
195
- }
196
- return { data };
197
- }
198
- function compileOperation(context, type, fieldMap) {
199
- const serialExecution = context.operation.operation === "mutation";
200
- const topLevel = compileObjectType(
201
- context,
202
- type,
203
- [],
204
- [GLOBAL_ROOT_NAME],
205
- [GLOBAL_DATA_NAME],
206
- void 0,
207
- GLOBAL_ERRORS_NAME,
208
- fieldMap,
209
- true
210
- );
211
- let body = `function query (${GLOBAL_EXECUTION_CONTEXT}) {
212
- "use strict";
213
- `;
214
- if (serialExecution) {
215
- body += `${GLOBAL_EXECUTION_CONTEXT}.queue = [];`;
216
- }
217
- body += generateUniqueDeclarations(context, true);
218
- body += `${GLOBAL_DATA_NAME} = ${topLevel}
219
- `;
220
- if (serialExecution) {
221
- body += compileDeferredFieldsSerially(context);
222
- body += `
223
- ${GLOBAL_EXECUTION_CONTEXT}.finalResolve = () => {};
224
- ${GLOBAL_RESOLVE} = (context) => {
225
- if (context.jobCounter >= context.queue.length) {
226
- // All mutations have finished
227
- context.finalResolve(context);
228
- return;
229
- }
230
- context.queue[context.jobCounter++](context);
231
- };
232
- // There might not be a job to run due to invalid queries
233
- if (${GLOBAL_EXECUTION_CONTEXT}.queue.length > 0) {
234
- ${GLOBAL_EXECUTION_CONTEXT}.jobCounter = 1; // since the first one will be run manually
235
- ${GLOBAL_EXECUTION_CONTEXT}.queue[0](${GLOBAL_EXECUTION_CONTEXT});
236
- }
237
- if (${GLOBAL_PROMISE_COUNTER} > 0) {
238
- return new Promise(resolve => ${GLOBAL_EXECUTION_CONTEXT}.finalResolve = resolve);
239
- }
240
- `;
241
- } else {
242
- body += compileDeferredFields(context);
243
- body += `
244
- return ${GLOBAL_RUNTIME_NAME}.finalizeResult(${GLOBAL_EXECUTION_CONTEXT});`;
245
- }
246
- body += `
247
- // sync execution, the results are ready
248
- return undefined;
249
- }`;
250
- body += context.hoistedFunctions.join("\n");
251
- return body;
252
- }
253
- function compileDeferredFields(context) {
254
- let body = "";
255
- context.deferred.forEach((deferredField, index) => {
256
- body += `
257
- if (${SAFETY_CHECK_PREFIX}${index}) {
258
- ${compileDeferredField(context, deferredField)}
259
- }`;
260
- });
261
- return body;
262
- }
263
- function compileDeferredField(context, deferredField, appendix) {
264
- const {
265
- name,
266
- originPathsFormatted,
267
- destinationPaths,
268
- fieldNodes,
269
- fieldType,
270
- fieldName,
271
- jsFieldName,
272
- responsePath,
273
- parentType,
274
- args
275
- } = deferredField;
276
- const subContext = createSubCompilationContext(context);
277
- const nodeBody = compileType(
278
- subContext,
279
- parentType,
280
- fieldType,
281
- fieldNodes,
282
- [jsFieldName],
283
- [`${GLOBAL_PARENT_NAME}.${name}`],
284
- responsePath
285
- );
286
- const parentIndexes = getParentArgIndexes(context);
287
- const resolverName = getResolverName(parentType.name, fieldName);
288
- const resolverHandler = getHoistedFunctionName(
289
- context,
290
- `${name}${resolverName}Handler`
291
- );
292
- const topLevelArgs = getArgumentsName(resolverName);
293
- const validArgs = getValidArgumentsVarName(resolverName);
294
- const executionError = createErrorObject(
295
- context,
296
- fieldNodes,
297
- responsePath,
298
- "err.message != null ? err.message : err",
299
- "err"
300
- );
301
- const executionInfo = getExecutionInfo(
302
- subContext,
303
- parentType,
304
- fieldType,
305
- fieldName,
306
- fieldNodes,
307
- responsePath
308
- );
309
- const emptyError = createErrorObject(context, fieldNodes, responsePath, '""');
310
- const resolverParentPath = originPathsFormatted;
311
- const resolverCall = `${GLOBAL_EXECUTION_CONTEXT}.resolvers.${resolverName}(
312
- ${resolverParentPath},${topLevelArgs},${GLOBAL_CONTEXT_NAME}, ${executionInfo})`;
313
- const resultParentPath = destinationPaths.join(".");
314
- const compiledArgs = compileArguments(
315
- subContext,
316
- args,
317
- topLevelArgs,
318
- validArgs,
319
- fieldType,
320
- responsePath
321
- );
322
- const body = `
323
- ${compiledArgs}
324
- if (${validArgs} === true) {
325
- ${GLOBAL_RUNTIME_NAME}.callResolver(${GLOBAL_EXECUTION_CONTEXT},
326
- () => ${resolverCall},
327
- result => {
328
- ${resolverHandler}(${GLOBAL_EXECUTION_CONTEXT}, ${resultParentPath}, result, ${parentIndexes});
329
- },
330
- err => {
331
- if (err) {
332
- ${getErrorDestination(fieldType)}.push(${executionError});
333
- } else {
334
- ${getErrorDestination(fieldType)}.push(${emptyError});
335
- }
336
- }
337
- );
338
- }`;
339
- context.hoistedFunctions.push(`
340
- function ${resolverHandler}(${GLOBAL_EXECUTION_CONTEXT}, ${GLOBAL_PARENT_NAME}, ${jsFieldName}, ${parentIndexes}) {
341
- ${generateUniqueDeclarations(subContext)}
342
- ${GLOBAL_PARENT_NAME}.${name} = ${nodeBody};
343
- ${compileDeferredFields(subContext)}
344
- ${appendix || ""}
345
- }
346
- `);
347
- return body;
348
- }
349
- function compileDeferredFieldsSerially(context) {
350
- let body = "";
351
- context.deferred.forEach((deferredField, index) => {
352
- const { name, fieldName, parentType } = deferredField;
353
- const resolverName = getResolverName(parentType.name, fieldName);
354
- const mutationHandler = getHoistedFunctionName(
355
- context,
356
- `${name}${resolverName}Mutation`
357
- );
358
- body += `
359
- if (${SAFETY_CHECK_PREFIX}${index}) {
360
- ${GLOBAL_EXECUTION_CONTEXT}.queue.push(${mutationHandler});
361
- }
362
- `;
363
- const appendix = `
364
- if (${GLOBAL_PROMISE_COUNTER} === 0) {
365
- ${GLOBAL_RESOLVE}(${GLOBAL_EXECUTION_CONTEXT});
366
- }
367
- `;
368
- context.hoistedFunctions.push(`
369
- function ${mutationHandler}(${GLOBAL_EXECUTION_CONTEXT}) {
370
- ${compileDeferredField(context, deferredField, appendix)}
371
- }
372
- `);
373
- });
374
- return body;
375
- }
376
- function compileType(context, parentType, type, fieldNodes, originPaths, destinationPaths, previousPath) {
377
- const sourcePath = joinOriginPaths(originPaths);
378
- const isNonNull = isNonNullType(type);
379
- const innerType = isNonNull ? type.ofType : type;
380
- if (isLeafType(innerType) && !(context.options.disableLeafSerialization && (innerType instanceof GraphQLEnumType || isSpecifiedScalarType(innerType)))) {
381
- const dest = isNonNull ? GLOBAL_NULL_ERRORS_NAME : GLOBAL_ERRORS_NAME;
382
- const serializerName = getSerializerName(innerType.name);
383
- context.serializers[serializerName] = getSerializer(
384
- innerType,
385
- context.options.customSerializers[innerType.name]
386
- );
387
- const parentIndexes = getParentArgIndexes(context);
388
- const handlerBody = `${dest}.push(${createErrorObject(
389
- context,
390
- fieldNodes,
391
- previousPath,
392
- "message"
393
- )});`;
394
- const cachedHandler = context.leafErrHandlerCache.get(handlerBody);
395
- let errHandler;
396
- if (cachedHandler) {
397
- errHandler = cachedHandler;
398
- } else {
399
- errHandler = getHoistedFunctionName(
400
- context,
401
- `${innerType.name}${originPaths.join("")}SerializerErrorHandler`
402
- );
403
- context.hoistedFunctions.push(`
404
- function ${errHandler}(${GLOBAL_EXECUTION_CONTEXT}, message, ${parentIndexes}) {
405
- ${handlerBody}}
406
- `);
407
- context.leafErrHandlerCache.set(handlerBody, errHandler);
408
- }
409
- const locs = JSON.stringify(computeLocations(fieldNodes));
410
- const path = serializeResponsePathAsArray(previousPath);
411
- const capStack = context.options.disablingCapturingStackErrors ? "true" : "false";
412
- const serializerRef = `${GLOBAL_EXECUTION_CONTEXT}.serializers.${serializerName}`;
413
- const extraIndexes = parentIndexes ? `, ${parentIndexes}` : "";
414
- if (isNonNull) {
415
- const nullMsg = `"Cannot return null for non-nullable field ${parentType.name}.${getFieldNodesName(fieldNodes)}."`;
416
- return `${GLOBAL_RUNTIME_NAME}.checkNonNullLeaf(${GLOBAL_EXECUTION_CONTEXT}, ${sourcePath}, ${dest}, ${nullMsg}, ${locs}, ${path}, ${capStack}, ${serializerRef}, ${errHandler}${extraIndexes})`;
417
- } else {
418
- return `${GLOBAL_RUNTIME_NAME}.checkNullableLeaf(${GLOBAL_EXECUTION_CONTEXT}, ${sourcePath}, ${dest}, ${locs}, ${path}, ${capStack}, ${serializerRef}, ${errHandler}${extraIndexes})`;
419
- }
420
- }
421
- let body = `${sourcePath} == null ? `;
422
- let errorDestination;
423
- if (isNonNullType(type)) {
424
- type = type.ofType;
425
- const nullErrorStr = `"Cannot return null for non-nullable field ${parentType.name}.${getFieldNodesName(fieldNodes)}."`;
426
- body += `(${GLOBAL_NULL_ERRORS_NAME}.push(${createErrorObject(
427
- context,
428
- fieldNodes,
429
- previousPath,
430
- nullErrorStr
431
- )}), null) :`;
432
- errorDestination = GLOBAL_NULL_ERRORS_NAME;
433
- } else {
434
- body += "null : ";
435
- errorDestination = GLOBAL_ERRORS_NAME;
436
- }
437
- body += "(";
438
- const errorPath = `${sourcePath}.message != null ? ${sourcePath}.message : ${sourcePath}`;
439
- body += `${sourcePath} instanceof Error ? (${errorDestination}.push(${createErrorObject(
440
- context,
441
- fieldNodes,
442
- previousPath,
443
- errorPath,
444
- sourcePath
445
- )}), null) : `;
446
- if (isLeafType(type)) {
447
- body += compileLeafType(
448
- context,
449
- type,
450
- originPaths,
451
- fieldNodes,
452
- previousPath,
453
- errorDestination
454
- );
455
- } else if (isObjectType(type)) {
456
- const fieldMap = collectSubfields(context, type, fieldNodes, previousPath);
457
- body += compileObjectType(
458
- context,
459
- type,
460
- fieldNodes,
461
- originPaths,
462
- destinationPaths,
463
- previousPath,
464
- errorDestination,
465
- fieldMap,
466
- false
467
- );
468
- } else if (isAbstractType(type)) {
469
- body += compileAbstractType(
470
- context,
471
- parentType,
472
- type,
473
- fieldNodes,
474
- originPaths,
475
- previousPath,
476
- errorDestination
477
- );
478
- } else if (isListType(type)) {
479
- body += compileListType(
480
- context,
481
- parentType,
482
- type,
483
- fieldNodes,
484
- originPaths,
485
- previousPath,
486
- errorDestination
487
- );
488
- } else {
489
- throw new Error(`unsupported type: ${type.toString()}`);
490
- }
491
- body += ")";
492
- return body;
493
- }
494
- function compileLeafType(context, type, originPaths, fieldNodes, previousPath, errorDestination) {
495
- let body = "";
496
- if (context.options.disableLeafSerialization && (type instanceof GraphQLEnumType || isSpecifiedScalarType(type))) {
497
- body += `${joinOriginPaths(originPaths)}`;
498
- } else {
499
- const serializerName = getSerializerName(type.name);
500
- context.serializers[serializerName] = getSerializer(
501
- type,
502
- context.options.customSerializers[type.name]
503
- );
504
- const parentIndexes = getParentArgIndexes(context);
505
- const serializerErrorHandler = getHoistedFunctionName(
506
- context,
507
- `${type.name}${originPaths.join("")}SerializerErrorHandler`
508
- );
509
- context.hoistedFunctions.push(`
510
- function ${serializerErrorHandler}(${GLOBAL_EXECUTION_CONTEXT}, message, ${parentIndexes}) {
511
- ${errorDestination}.push(${createErrorObject(
512
- context,
513
- fieldNodes,
514
- previousPath,
515
- "message"
516
- )});}
517
- `);
518
- body += `${GLOBAL_EXECUTION_CONTEXT}.serializers.${serializerName}(${GLOBAL_EXECUTION_CONTEXT}, ${joinOriginPaths(
519
- originPaths
520
- )}, ${serializerErrorHandler}, ${parentIndexes})`;
521
- }
522
- return body;
523
- }
524
- function compileObjectType(context, type, fieldNodes, originPaths, destinationPaths, responsePath, errorDestination, fieldMap, alwaysDefer) {
525
- const trivialTypeNameVar = context.trivialTypeNameVar;
526
- context.trivialTypeNameVar = void 0;
527
- const body = genFn();
528
- body("(");
529
- if (typeof type.isTypeOf === "function" && !alwaysDefer) {
530
- context.isTypeOfs[type.name + "IsTypeOf"] = type.isTypeOf;
531
- body(
532
- `!${GLOBAL_EXECUTION_CONTEXT}.isTypeOfs["${type.name}IsTypeOf"](${joinOriginPaths(
533
- originPaths
534
- )}) ? (${errorDestination}.push(${createErrorObject(
535
- context,
536
- fieldNodes,
537
- responsePath,
538
- `\`Expected value of type "${type.name}" but got: \${${GLOBAL_INSPECT_NAME}(${joinOriginPaths(
539
- originPaths
540
- )})}.\``
541
- )}), null) :`
542
- );
543
- }
544
- body("{");
545
- for (const name of Object.keys(fieldMap)) {
546
- const fieldNodes2 = fieldMap[name];
547
- const field = resolveFieldDef(context, type, fieldNodes2);
548
- if (!field) {
549
- continue;
550
- }
551
- body(`"${name}": `);
552
- const serializedResponsePath = joinSkipIncludePath(
553
- serializeObjectPathForSkipInclude(responsePath),
554
- name
555
- );
556
- const fieldConditionsList = (context.options.useExperimentalPathBasedSkipInclude ? fieldNodes2.map(
557
- (it) => it.__internalShouldIncludePath?.[serializedResponsePath]
558
- ) : fieldNodes2.map((it) => it.__internalShouldInclude)).filter(isNotNull);
559
- let fieldCondition = fieldConditionsList.map((it) => {
560
- if (it.length > 0) {
561
- return `(${it.join(" && ")})`;
562
- }
563
- return "true";
564
- }).filter(isNotNull).join(" || ");
565
- if (!fieldCondition) {
566
- fieldCondition = "true";
567
- }
568
- const alwaysIncluded = fieldCondition.split(" || ").every((p) => p === "true");
569
- if (!alwaysIncluded) {
570
- body(`(${fieldCondition})`);
571
- }
572
- if (field === TypeNameMetaFieldDef) {
573
- const typenameValue = trivialTypeNameVar ?? `"${type.name}"`;
574
- body(
575
- alwaysIncluded ? `${typenameValue},` : `? ${typenameValue} : undefined,`
576
- );
577
- continue;
578
- }
579
- let resolver = field.resolve;
580
- if (!resolver && alwaysDefer) {
581
- const fieldName = field.name;
582
- resolver = (parent) => parent && parent[fieldName];
583
- }
584
- if (resolver) {
585
- context.deferred.push({
586
- name,
587
- responsePath: addPath(responsePath, name),
588
- originPaths,
589
- originPathsFormatted: joinOriginPaths(originPaths),
590
- destinationPaths,
591
- parentType: type,
592
- fieldName: field.name,
593
- jsFieldName: getJsFieldName(field.name),
594
- fieldType: field.type,
595
- fieldNodes: fieldNodes2,
596
- args: getArgumentDefs(field, fieldNodes2[0])
597
- });
598
- context.resolvers[getResolverName(type.name, field.name)] = resolver;
599
- const idx = context.deferred.length - 1;
600
- if (alwaysIncluded) {
601
- body(`(${SAFETY_CHECK_PREFIX}${idx} = true, null)`);
602
- } else {
603
- body(
604
- `? (${SAFETY_CHECK_PREFIX}${idx} = true, null) : (${SAFETY_CHECK_PREFIX}${idx} = false, undefined)`
605
- );
606
- }
607
- } else {
608
- const compiledFieldType = compileType(
609
- context,
610
- type,
611
- field.type,
612
- fieldNodes2,
613
- originPaths.concat(field.name),
614
- destinationPaths.concat(name),
615
- addPath(responsePath, name)
616
- );
617
- if (alwaysIncluded) {
618
- body(compiledFieldType);
619
- } else {
620
- body(`? ${compiledFieldType} : undefined`);
621
- }
622
- }
623
- body(",");
624
- }
625
- body("}");
626
- body(")");
627
- return body.toString();
628
- }
629
- function compileAbstractType(context, parentType, type, fieldNodes, originPaths, previousPath, errorDestination) {
630
- let resolveType;
631
- if (type.resolveType) {
632
- resolveType = type.resolveType;
633
- } else {
634
- resolveType = (value, context2, info) => defaultResolveTypeFn(value, context2, info, type);
635
- }
636
- const typeResolverName = getTypeResolverName(type.name);
637
- context.typeResolvers[typeResolverName] = resolveType;
638
- const finalTypeName = "finalType";
639
- const trivialGroups = /* @__PURE__ */ new Map();
640
- const nonTrivialCases = [];
641
- for (const objectType of context.schema.getPossibleTypes(type)) {
642
- const subContext = createSubCompilationContext(context);
643
- subContext.trivialTypeNameVar = finalTypeName;
644
- const object = compileType(
645
- subContext,
646
- parentType,
647
- objectType,
648
- fieldNodes,
649
- originPaths,
650
- ["__concrete"],
651
- addPath(previousPath, objectType.name, "meta")
652
- );
653
- if (subContext.deferred.length === 0) {
654
- const group = trivialGroups.get(object) ?? [];
655
- group.push(objectType.name);
656
- trivialGroups.set(object, group);
657
- } else {
658
- nonTrivialCases.push(`case "${objectType.name}": {
659
- ${generateUniqueDeclarations(subContext)}
660
- const __concrete = ${object};
661
- ${compileDeferredFields(subContext)}
662
- return __concrete;
663
- }`);
664
- }
665
- }
666
- const trivialCases = Array.from(trivialGroups.entries()).map(
667
- ([sharedObj, typeNames]) => {
668
- const caseLabels = typeNames.map((n) => `case "${n}"`).join(": ");
669
- return `${caseLabels}: {
670
- const __concrete = ${sharedObj};
671
- return __concrete;
672
- }`;
673
- }
674
- );
675
- const collectedTypes = [...nonTrivialCases, ...trivialCases].join("\n");
676
- const nullTypeError = `"Runtime Object type is not a possible type for \\"${type.name}\\"."`;
677
- const notPossibleTypeError = (
678
- // eslint-disable-next-line no-template-curly-in-string
679
- '`Runtime Object type "${nodeType}" is not a possible type for "' + type.name + '".`'
680
- );
681
- const noTypeError = `${finalTypeName} ? ${notPossibleTypeError} : "Abstract type ${type.name} must resolve to an Object type at runtime for field ${parentType.name}.${getFieldNodesName(fieldNodes)}. Either the ${type.name} type should provide a \\"resolveType\\" function or each possible types should provide an \\"isTypeOf\\" function."`;
682
- return `((nodeType, err) =>
683
- {
684
- if (err != null) {
685
- ${errorDestination}.push(${createErrorObject(
686
- context,
687
- fieldNodes,
688
- previousPath,
689
- "err.message != null ? err.message : err",
690
- "err"
691
- )});
692
- return null;
693
- }
694
- if (nodeType == null) {
695
- ${errorDestination}.push(${createErrorObject(
696
- context,
697
- fieldNodes,
698
- previousPath,
699
- nullTypeError
700
- )})
701
- return null;
702
- }
703
- const ${finalTypeName} = typeof nodeType === "string" ? nodeType : nodeType.name;
704
- switch(${finalTypeName}) {
705
- ${collectedTypes}
706
- default:
707
- ${errorDestination}.push(${createErrorObject(
708
- context,
709
- fieldNodes,
710
- previousPath,
711
- noTypeError
712
- )})
713
- return null;
714
- }
715
- })(
716
- ${GLOBAL_EXECUTION_CONTEXT}.typeResolvers.${typeResolverName}(${joinOriginPaths(
717
- originPaths
718
- )},
719
- ${GLOBAL_CONTEXT_NAME},
720
- ${getExecutionInfo(
721
- context,
722
- parentType,
723
- type,
724
- type.name,
725
- fieldNodes,
726
- previousPath
727
- )}))`;
728
- }
729
- function compileListType(context, parentType, type, fieldNodes, originalObjectPaths, responsePath, errorDestination) {
730
- const name = originalObjectPaths.join(".");
731
- const listContext = createSubCompilationContext(context);
732
- const newDepth = ++listContext.depth;
733
- const fieldType = type.ofType;
734
- const dataBody = compileType(
735
- listContext,
736
- parentType,
737
- fieldType,
738
- fieldNodes,
739
- ["__currentItem"],
740
- [`${GLOBAL_PARENT_NAME}[idx${newDepth}]`],
741
- addPath(responsePath, "idx" + newDepth, "variable")
742
- );
743
- const errorMessage = `"Expected Iterable, but did not find one for field ${parentType.name}.${getFieldNodesName(fieldNodes)}."`;
744
- const errorCase = `(${errorDestination}.push(${createErrorObject(
745
- context,
746
- fieldNodes,
747
- responsePath,
748
- errorMessage
749
- )}), null)`;
750
- const executionError = createErrorObject(
751
- context,
752
- fieldNodes,
753
- addPath(responsePath, "idx" + newDepth, "variable"),
754
- "err.message != null ? err.message : err",
755
- "err"
756
- );
757
- const emptyError = createErrorObject(context, fieldNodes, responsePath, '""');
758
- const uniqueDeclarations = generateUniqueDeclarations(listContext);
759
- const deferredFields = compileDeferredFields(listContext);
760
- const itemHandler = getHoistedFunctionName(
761
- context,
762
- `${parentType.name}${originalObjectPaths.join("")}MapItemHandler`
763
- );
764
- const childIndexes = getParentArgIndexes(listContext);
765
- listContext.hoistedFunctions.push(`
766
- function ${itemHandler}(${GLOBAL_EXECUTION_CONTEXT}, ${GLOBAL_PARENT_NAME}, __currentItem, ${childIndexes}) {
767
- ${uniqueDeclarations}
768
- ${GLOBAL_PARENT_NAME}[idx${newDepth}] = ${dataBody};
769
- ${deferredFields}
770
- }
771
- `);
772
- const safeMapHandler = getHoistedFunctionName(
773
- context,
774
- `${parentType.name}${originalObjectPaths.join("")}MapHandler`
775
- );
776
- const parentIndexes = getParentArgIndexes(context);
777
- listContext.hoistedFunctions.push(`
778
- function ${safeMapHandler}(${GLOBAL_EXECUTION_CONTEXT}, __currentItem, idx${newDepth}, resultArray, ${parentIndexes}) {
779
- ${GLOBAL_RUNTIME_NAME}.handleListItemResult(${GLOBAL_EXECUTION_CONTEXT}, __currentItem,
780
- result => {
781
- ${itemHandler}(${GLOBAL_EXECUTION_CONTEXT}, resultArray, result, ${childIndexes});
782
- },
783
- err => {
784
- resultArray.push(null);
785
- if (err) {
786
- ${getErrorDestination(fieldType)}.push(${executionError});
787
- } else {
788
- ${getErrorDestination(fieldType)}.push(${emptyError});
789
- }
790
- }
791
- );
792
- }
793
- `);
794
- return `(typeof ${name} === "string" || typeof ${name}[Symbol.iterator] !== "function") ? ${errorCase} :
795
- ${GLOBAL_SAFE_MAP_NAME}(${GLOBAL_EXECUTION_CONTEXT}, ${name}, ${safeMapHandler}, ${parentIndexes})`;
796
- }
797
- const MAGIC_MINUS_INFINITY = "__MAGIC_MINUS_INFINITY__71d4310a_d4a3_4a05_b1fe_e60779d24998";
798
- const MAGIC_PLUS_INFINITY = "__MAGIC_PLUS_INFINITY__bb201c39_3333_4695_b4ad_7f1722e7aa7a";
799
- const MAGIC_NAN = "__MAGIC_NAN__57f286b9_4c20_487f_b409_79804ddcb4f8";
800
- const MAGIC_DATE = "__MAGIC_DATE__33a9e76d_02e0_4128_8e92_3530ad3da74d";
801
- function specialValueReplacer(key, value) {
802
- if (Number.isNaN(value)) {
803
- return MAGIC_NAN;
804
- }
805
- if (value === Infinity) {
806
- return MAGIC_PLUS_INFINITY;
807
- }
808
- if (value === -Infinity) {
809
- return MAGIC_MINUS_INFINITY;
810
- }
811
- if (this[key] instanceof Date) {
812
- return MAGIC_DATE + this[key].getTime();
813
- }
814
- return value;
815
- }
816
- function objectStringify(val) {
817
- return JSON.stringify(val, specialValueReplacer).replace(new RegExp(`"${MAGIC_NAN}"`, "g"), "NaN").replace(new RegExp(`"${MAGIC_PLUS_INFINITY}"`, "g"), "Infinity").replace(new RegExp(`"${MAGIC_MINUS_INFINITY}"`, "g"), "-Infinity").replace(new RegExp(`"${MAGIC_DATE}([^"]+)"`, "g"), "new Date($1)");
818
- }
819
- function getExecutionInfo(context, parentType, fieldType, fieldName, fieldNodes, responsePath) {
820
- const resolveInfoName = createResolveInfoName(responsePath);
821
- const { schema, fragments, operation } = context;
822
- context.resolveInfos[resolveInfoName] = createResolveInfoThunk(
823
- {
824
- schema,
825
- fragments,
826
- operation,
827
- parentType,
828
- fieldName,
829
- fieldType,
830
- fieldNodes
831
- },
832
- context.options.resolverInfoEnricher
833
- );
834
- return `${GLOBAL_EXECUTION_CONTEXT}.resolveInfos.${resolveInfoName}(${GLOBAL_ROOT_NAME}, ${GLOBAL_VARIABLES_NAME}, ${serializeResponsePath(
835
- responsePath
836
- )})`;
837
- }
838
- function getArgumentsName(prefixName) {
839
- return `${prefixName}Args`;
840
- }
841
- function getValidArgumentsVarName(prefixName) {
842
- return `${prefixName}ValidArgs`;
843
- }
844
- function objectPath(topLevel, path) {
845
- if (!path) {
846
- return topLevel;
847
- }
848
- let objectPath2 = topLevel;
849
- const flattened = flattenPath(path);
850
- for (const section of flattened) {
851
- if (section.type === "literal") {
852
- objectPath2 += `["${section.key}"]`;
853
- } else {
854
- throw new Error("should only have received literal paths");
855
- }
856
- }
857
- return objectPath2;
858
- }
859
- function compileArguments(context, args, topLevelArg, validArgs, returnType, path) {
860
- let body = `
861
- let ${validArgs} = true;
862
- const ${topLevelArg} = ${objectStringify(args.values)};
863
- `;
864
- const errorDestination = getErrorDestination(returnType);
865
- for (const variable of args.missing) {
866
- const varName = variable.valueNode.name.value;
867
- body += `if (Object.prototype.hasOwnProperty.call(${GLOBAL_VARIABLES_NAME}, "${varName}")) {`;
868
- if (variable.argument && isNonNullType(variable.argument.definition.type)) {
869
- const message = `'Argument "${variable.argument.definition.name}" of non-null type "${variable.argument.definition.type.toString()}" must not be null.'`;
870
- body += `if (${GLOBAL_VARIABLES_NAME}['${variable.valueNode.name.value}'] == null) {
871
- ${errorDestination}.push(${createErrorObject(
872
- context,
873
- [variable.argument.node.value],
874
- path,
875
- message
876
- )});
877
- ${validArgs} = false;
878
- }`;
879
- }
880
- body += `
881
- ${objectPath(topLevelArg, variable.path)} = ${GLOBAL_VARIABLES_NAME}['${variable.valueNode.name.value}'];
882
- }`;
883
- if (variable.argument && isNonNullType(variable.argument.definition.type) && variable.argument.definition.defaultValue === void 0) {
884
- const message = `'Argument "${variable.argument.definition.name}" of required type "${variable.argument.definition.type.toString()}" was provided the variable "$${varName}" which was not provided a runtime value.'`;
885
- body += ` else {
886
- ${errorDestination}.push(${createErrorObject(
887
- context,
888
- [variable.argument.node.value],
889
- path,
890
- message
891
- )});
892
- ${validArgs} = false;
893
- }`;
894
- }
895
- }
896
- return body;
897
- }
898
- function generateUniqueDeclarations(context, defaultValue = false) {
899
- return context.deferred.map(
900
- (_, idx) => `
901
- let ${SAFETY_CHECK_PREFIX}${idx} = ${defaultValue};
902
- `
903
- ).join("\n");
904
- }
905
- function createSubCompilationContext(context) {
906
- return { ...context, deferred: [] };
907
- }
908
- function isPromise(value) {
909
- return value != null && typeof value === "object" && typeof value.then === "function";
910
- }
911
- function isPromiseInliner(value) {
912
- return `${GLOBAL_RUNTIME_NAME}.isPromise(${value})`;
913
- }
914
- function serializeResponsePathAsArray(path) {
915
- const flattened = flattenPath(path);
916
- let src = "[";
917
- for (let i = flattened.length - 1; i >= 0; i--) {
918
- if (flattened[i].type === "meta") {
919
- continue;
920
- }
921
- src += flattened[i].type === "literal" ? `"${flattened[i].key}",` : `${flattened[i].key},`;
922
- }
923
- return src + "]";
924
- }
925
- function getErrorDestination(type) {
926
- return isNonNullType(type) ? GLOBAL_NULL_ERRORS_NAME : GLOBAL_ERRORS_NAME;
927
- }
928
- function createResolveInfoName(path) {
929
- return flattenPath(path).map((p) => p.key).join("_") + "Info";
930
- }
931
- function serializeResponsePath(path) {
932
- if (!path) {
933
- return "undefined";
934
- }
935
- if (path.type === "meta") {
936
- return serializeResponsePath(path.prev);
937
- }
938
- const literalValue = `"${path.key}"`;
939
- return `{
940
- key: ${path.type === "literal" ? literalValue : path.key},
941
- prev: ${serializeResponsePath(path.prev)}
942
- }`;
943
- }
944
- function getSerializer(scalar, customSerializer) {
945
- const { name } = scalar;
946
- const serialize = customSerializer || ((val) => scalar.serialize(val));
947
- return function leafSerializer(context, v, onError, ...idx) {
948
- try {
949
- const value = serialize(v);
950
- if (isInvalid(value)) {
951
- onError(
952
- context,
953
- `Expected a value of type "${name}" but received: ${v}`,
954
- ...idx
955
- );
956
- return null;
957
- }
958
- return value;
959
- } catch (e) {
960
- onError(
961
- context,
962
- e && e.message || `Expected a value of type "${name}" but received an Error`,
963
- ...idx
964
- );
965
- return null;
966
- }
967
- };
968
- }
969
- function defaultResolveTypeFn(value, contextValue, info, abstractType) {
970
- if (value != null && typeof value === "object" && typeof value.__typename === "string") {
971
- return value.__typename;
972
- }
973
- const possibleTypes = info.schema.getPossibleTypes(abstractType);
974
- for (const type of possibleTypes) {
975
- if (type.isTypeOf) {
976
- const isTypeOfResult = type.isTypeOf(value, contextValue, info);
977
- if (isPromise(isTypeOfResult)) {
978
- throw new Error(
979
- `Promises are not supported for resolving type of ${value}`
980
- );
981
- } else if (isTypeOfResult) {
982
- return type.name;
983
- }
984
- }
985
- }
986
- throw new Error(
987
- `Could not resolve the object type in possible types of ${abstractType.name} for the value: ` + inspect(value)
988
- );
989
- }
990
- function buildCompilationContext(schema, document, options, operationName) {
991
- const errors = [];
992
- let operation = void 0;
993
- let hasMultipleAssumedOperations = false;
994
- const fragments = /* @__PURE__ */ Object.create(null);
995
- for (const definition of document.definitions) {
996
- switch (definition.kind) {
997
- case Kind.OPERATION_DEFINITION:
998
- if (!operationName && operation) {
999
- hasMultipleAssumedOperations = true;
1000
- } else if (!operationName || definition.name && definition.name.value === operationName) {
1001
- operation = definition;
1002
- }
1003
- break;
1004
- case Kind.FRAGMENT_DEFINITION:
1005
- fragments[definition.name.value] = definition;
1006
- break;
1007
- }
1008
- }
1009
- if (!operation) {
1010
- if (operationName) {
1011
- throw new GraphQLError(`Unknown operation named "${operationName}".`);
1012
- } else {
1013
- throw new GraphQLError("Must provide an operation.");
1014
- }
1015
- } else if (hasMultipleAssumedOperations) {
1016
- throw new GraphQLError(
1017
- "Must provide operation name if query contains multiple operations."
1018
- );
1019
- }
1020
- return {
1021
- schema,
1022
- fragments,
1023
- rootValue: null,
1024
- contextValue: null,
1025
- operation,
1026
- options,
1027
- resolvers: {},
1028
- serializers: {},
1029
- typeResolvers: {},
1030
- isTypeOfs: {},
1031
- resolveInfos: {},
1032
- hoistedFunctions: [],
1033
- hoistedFunctionNames: /* @__PURE__ */ new Map(),
1034
- leafErrHandlerCache: /* @__PURE__ */ new Map(),
1035
- deferred: [],
1036
- depth: -1,
1037
- variableValues: {},
1038
- errors
1039
- };
1040
- }
1041
- function getFieldNodesName(nodes) {
1042
- return nodes.length > 1 ? "(" + nodes.map(({ name }) => name.value).join(",") + ")" : nodes[0].name.value;
1043
- }
1044
- function getHoistedFunctionName(context, name) {
1045
- const count = context.hoistedFunctionNames.get(name);
1046
- if (count === void 0) {
1047
- context.hoistedFunctionNames.set(name, 0);
1048
- return name;
1049
- }
1050
- context.hoistedFunctionNames.set(name, count + 1);
1051
- return `${name}${count + 1}`;
1052
- }
1053
- function createErrorObject(context, nodes, path, message, originalError) {
1054
- return `new ${GRAPHQL_ERROR}(${message},
1055
- ${JSON.stringify(computeLocations(nodes))},
1056
- ${serializeResponsePathAsArray(path)},
1057
- ${originalError || "undefined"},
1058
- ${context.options.disablingCapturingStackErrors ? "true" : "false"})`;
1059
- }
1060
- function getResolverName(parentName, name) {
1061
- return parentName + name + "Resolver";
1062
- }
1063
- function getTypeResolverName(name) {
1064
- return name + "TypeResolver";
1065
- }
1066
- function getSerializerName(name) {
1067
- return name + "Serializer";
1068
- }
1069
- function normalizeErrors(err) {
1070
- if (Array.isArray(err)) {
1071
- return err.map((e) => normalizeError(e));
1072
- }
1073
- return [normalizeError(err)];
1074
- }
1075
- function normalizeError(err) {
1076
- return err instanceof GraphQLError ? err : new GraphqlJitError(
1077
- err.message,
1078
- err.locations,
1079
- err.path,
1080
- err
1081
- );
1082
- }
1083
- function isInvalid(value) {
1084
- return value === void 0 || value !== value;
1085
- }
1086
- function getParentArgIndexes(context) {
1087
- let args = "";
1088
- for (let i = 0; i <= context.depth; ++i) {
1089
- if (i > 0) {
1090
- args += ", ";
1091
- }
1092
- args += `idx${i}`;
1093
- }
1094
- return args;
1095
- }
1096
- function getJsFieldName(fieldName) {
1097
- return `${LOCAL_JS_FIELD_NAME_PREFIX}${fieldName}`;
1098
- }
1099
- function isAsyncIterable(val) {
1100
- return typeof Object(val)[Symbol.asyncIterator] === "function";
1101
- }
1102
- function compileSubscriptionOperation(context, type, fieldMap, queryFn) {
1103
- const fieldNodes = Object.values(fieldMap)[0];
1104
- const fieldNode = fieldNodes[0];
1105
- const fieldName = fieldNode.name.value;
1106
- const field = resolveFieldDef(context, type, fieldNodes);
1107
- if (!field) {
1108
- throw new GraphQLError(
1109
- `The subscription field "${fieldName}" is not defined.`,
1110
- getGraphQLErrorOptions(fieldNodes)
1111
- );
1112
- }
1113
- const responsePath = addPath(void 0, fieldName);
1114
- const resolveInfoName = createResolveInfoName(responsePath);
1115
- const subscriber = field.subscribe;
1116
- async function executeSubscription(executionContext) {
1117
- const resolveInfo = executionContext.resolveInfos[resolveInfoName](
1118
- executionContext.rootValue,
1119
- executionContext.variables,
1120
- responsePath
1121
- );
1122
- try {
1123
- const eventStream = await subscriber?.(
1124
- executionContext.rootValue,
1125
- executionContext.variables,
1126
- executionContext.context,
1127
- resolveInfo
1128
- );
1129
- if (eventStream instanceof Error) {
1130
- throw eventStream;
1131
- }
1132
- return eventStream;
1133
- } catch (error) {
1134
- throw locatedError(
1135
- error,
1136
- resolveInfo.fieldNodes,
1137
- pathToArray(resolveInfo.path)
1138
- );
1139
- }
1140
- }
1141
- async function createSourceEventStream(executionContext) {
1142
- try {
1143
- const eventStream = await executeSubscription(executionContext);
1144
- if (!isAsyncIterable(eventStream)) {
1145
- throw new Error(
1146
- `Subscription field must return Async Iterable. Received: ${inspect(eventStream)}.`
1147
- );
1148
- }
1149
- return eventStream;
1150
- } catch (error) {
1151
- if (error instanceof GraphQLError) {
1152
- return { errors: [error] };
1153
- }
1154
- throw error;
1155
- }
1156
- }
1157
- return async function subscribe(executionContext) {
1158
- const resultOrStream = await createSourceEventStream(executionContext);
1159
- if (!isAsyncIterable(resultOrStream)) {
1160
- return resultOrStream;
1161
- }
1162
- const mapSourceToResponse = (payload) => queryFn(payload, executionContext.context, executionContext.variables);
1163
- return mapAsyncIterator(resultOrStream, mapSourceToResponse);
1164
- };
1165
- }
1166
- function createBoundSubscribe(compilationContext, document, func, getVariableValues, operationName) {
1167
- const { resolvers, typeResolvers, isTypeOfs, serializers, resolveInfos } = compilationContext;
1168
- const trimmer = createNullTrimmer(compilationContext);
1169
- const fnName = operationName || "subscribe";
1170
- const ret = {
1171
- async [fnName](rootValue, context, variables) {
1172
- const parsedVariables = getVariableValues(variables || {});
1173
- if (failToParseVariables(parsedVariables)) {
1174
- return { errors: parsedVariables.errors };
1175
- }
1176
- const executionContext = {
1177
- rootValue,
1178
- context,
1179
- variables: parsedVariables.coerced,
1180
- inspect,
1181
- GraphQLError: GraphqlJitError,
1182
- resolvers,
1183
- typeResolvers,
1184
- isTypeOfs,
1185
- serializers,
1186
- resolveInfos,
1187
- trimmer,
1188
- rt: jitRuntime,
1189
- promiseCounter: 0,
1190
- nullErrors: [],
1191
- errors: [],
1192
- data: {}
1193
- };
1194
- return func.call(null, executionContext);
1195
- }
1196
- };
1197
- return ret[fnName];
1198
- }
1199
- function mapAsyncIterator(iterable, callback) {
1200
- const iterator = iterable[Symbol.asyncIterator]();
1201
- async function mapResult(result) {
1202
- if (result.done) {
1203
- return result;
1204
- }
1205
- try {
1206
- return { value: await callback(result.value), done: false };
1207
- } catch (error) {
1208
- if (typeof iterator.return === "function") {
1209
- try {
1210
- await iterator.return();
1211
- } catch (e) {
1212
- }
1213
- }
1214
- throw error;
1215
- }
1216
- }
1217
- return {
1218
- async next() {
1219
- return mapResult(await iterator.next());
1220
- },
1221
- async return() {
1222
- return typeof iterator.return === "function" ? mapResult(await iterator.return()) : { value: void 0, done: true };
1223
- },
1224
- async throw(error) {
1225
- return typeof iterator.throw === "function" ? mapResult(await iterator.throw(error)) : Promise.reject(error);
1226
- },
1227
- [Symbol.asyncIterator]() {
1228
- return this;
1229
- }
1230
- };
1231
- }
1232
- function joinOriginPaths(originPaths) {
1233
- return originPaths.join(".");
1234
- }
1235
- function isNotNull(it) {
1236
- return it != null;
1237
- }
1238
- export {
1239
- GLOBAL_VARIABLES_NAME,
1240
- buildCompilationContext,
1241
- compileQuery,
1242
- createBoundQuery,
1243
- isAsyncIterable,
1244
- isCompiledQuery,
1245
- isPromise,
1246
- isPromiseInliner
1247
- };
1248
- //# sourceMappingURL=execution.mjs.map