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