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