msw 0.40.1 → 0.41.1

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 (119) hide show
  1. package/config/constants.js +1 -3
  2. package/config/scripts/postinstall.js +32 -25
  3. package/lib/esm/index.js +1967 -1587
  4. package/lib/esm/index.js.map +1 -0
  5. package/lib/glossary-eda04a15.d.ts +331 -0
  6. package/lib/iife/index.js +9773 -21
  7. package/lib/iife/index.js.map +1 -0
  8. package/lib/index.d.ts +353 -0
  9. package/lib/index.js +2125 -0
  10. package/lib/index.js.map +1 -0
  11. package/lib/{esm/mockServiceWorker.js → mockServiceWorker.js} +1 -1
  12. package/lib/native/index.d.ts +9 -0
  13. package/lib/native/index.js +1532 -0
  14. package/lib/native/index.mjs +1532 -0
  15. package/lib/node/index.d.ts +15 -0
  16. package/lib/node/index.js +1601 -0
  17. package/lib/node/index.js.map +1 -0
  18. package/lib/node/index.mjs +1601 -0
  19. package/lib/node/index.mjs.map +1 -0
  20. package/native/package.json +3 -2
  21. package/node/package.json +3 -2
  22. package/package.json +13 -22
  23. package/lib/esm/errors-deps.js +0 -74
  24. package/lib/esm/fetch-deps.js +0 -1005
  25. package/lib/esm/graphql-deps.js +0 -3545
  26. package/lib/esm/graphql.js +0 -5
  27. package/lib/esm/index-deps.js +0 -21
  28. package/lib/esm/index2.js +0 -3
  29. package/lib/esm/matchRequestUrl-deps.js +0 -992
  30. package/lib/esm/rest-deps.js +0 -103
  31. package/lib/esm/rest.js +0 -5
  32. package/lib/esm/xml-deps.js +0 -44
  33. package/lib/iife/mockServiceWorker.js +0 -338
  34. package/lib/types/context/body.d.ts +0 -9
  35. package/lib/types/context/cookie.d.ts +0 -7
  36. package/lib/types/context/data.d.ts +0 -8
  37. package/lib/types/context/delay.d.ts +0 -15
  38. package/lib/types/context/errors.d.ts +0 -8
  39. package/lib/types/context/extensions.d.ts +0 -8
  40. package/lib/types/context/fetch.d.ts +0 -9
  41. package/lib/types/context/index.d.ts +0 -12
  42. package/lib/types/context/json.d.ts +0 -12
  43. package/lib/types/context/set.d.ts +0 -18
  44. package/lib/types/context/status.d.ts +0 -9
  45. package/lib/types/context/text.d.ts +0 -8
  46. package/lib/types/context/xml.d.ts +0 -9
  47. package/lib/types/graphql.d.ts +0 -74
  48. package/lib/types/handlers/GraphQLHandler.d.ts +0 -39
  49. package/lib/types/handlers/RequestHandler.d.ts +0 -103
  50. package/lib/types/handlers/RestHandler.d.ts +0 -47
  51. package/lib/types/index.d.ts +0 -26
  52. package/lib/types/native/index.d.ts +0 -1
  53. package/lib/types/node/createSetupServer.d.ts +0 -8
  54. package/lib/types/node/glossary.d.ts +0 -38
  55. package/lib/types/node/index.d.ts +0 -2
  56. package/lib/types/node/setupServer.d.ts +0 -6
  57. package/lib/types/response.d.ts +0 -35
  58. package/lib/types/rest.d.ts +0 -13
  59. package/lib/types/setupWorker/glossary.d.ts +0 -161
  60. package/lib/types/setupWorker/setupWorker.d.ts +0 -9
  61. package/lib/types/setupWorker/start/createFallbackStart.d.ts +0 -2
  62. package/lib/types/setupWorker/start/createStartHandler.d.ts +0 -2
  63. package/lib/types/setupWorker/start/utils/enableMocking.d.ts +0 -5
  64. package/lib/types/setupWorker/start/utils/getWorkerByRegistration.d.ts +0 -6
  65. package/lib/types/setupWorker/start/utils/getWorkerInstance.d.ts +0 -6
  66. package/lib/types/setupWorker/start/utils/prepareStartHandler.d.ts +0 -9
  67. package/lib/types/setupWorker/start/utils/printStartMessage.d.ts +0 -10
  68. package/lib/types/setupWorker/start/utils/validateWorkerScope.d.ts +0 -2
  69. package/lib/types/setupWorker/stop/createFallbackStop.d.ts +0 -2
  70. package/lib/types/setupWorker/stop/createStop.d.ts +0 -2
  71. package/lib/types/setupWorker/stop/utils/printStopMessage.d.ts +0 -3
  72. package/lib/types/sharedOptions.d.ts +0 -24
  73. package/lib/types/typeUtils.d.ts +0 -7
  74. package/lib/types/utils/NetworkError.d.ts +0 -3
  75. package/lib/types/utils/createBroadcastChannel.d.ts +0 -18
  76. package/lib/types/utils/deferNetworkRequestsUntil.d.ts +0 -6
  77. package/lib/types/utils/getResponse.d.ts +0 -15
  78. package/lib/types/utils/handleRequest.d.ts +0 -34
  79. package/lib/types/utils/internal/compose.d.ts +0 -14
  80. package/lib/types/utils/internal/devUtils.d.ts +0 -18
  81. package/lib/types/utils/internal/getCallFrame.d.ts +0 -4
  82. package/lib/types/utils/internal/isIterable.d.ts +0 -4
  83. package/lib/types/utils/internal/isObject.d.ts +0 -4
  84. package/lib/types/utils/internal/isStringEqual.d.ts +0 -4
  85. package/lib/types/utils/internal/jsonParse.d.ts +0 -5
  86. package/lib/types/utils/internal/mergeRight.d.ts +0 -5
  87. package/lib/types/utils/internal/parseGraphQLRequest.d.ts +0 -23
  88. package/lib/types/utils/internal/parseMultipartData.d.ts +0 -6
  89. package/lib/types/utils/internal/pipeEvents.d.ts +0 -6
  90. package/lib/types/utils/internal/requestHandlerUtils.d.ts +0 -4
  91. package/lib/types/utils/internal/requestIntegrityCheck.d.ts +0 -2
  92. package/lib/types/utils/internal/tryCatch.d.ts +0 -1
  93. package/lib/types/utils/internal/uuidv4.d.ts +0 -1
  94. package/lib/types/utils/logging/getStatusCodeColor.d.ts +0 -9
  95. package/lib/types/utils/logging/getTimestamp.d.ts +0 -4
  96. package/lib/types/utils/logging/prepareRequest.d.ts +0 -23
  97. package/lib/types/utils/logging/prepareResponse.d.ts +0 -10
  98. package/lib/types/utils/matching/matchRequestUrl.d.ts +0 -17
  99. package/lib/types/utils/matching/normalizePath.d.ts +0 -9
  100. package/lib/types/utils/request/getPublicUrlFromRequest.d.ts +0 -6
  101. package/lib/types/utils/request/getRequestCookies.d.ts +0 -7
  102. package/lib/types/utils/request/onUnhandledRequest.d.ts +0 -8
  103. package/lib/types/utils/request/parseBody.d.ts +0 -5
  104. package/lib/types/utils/request/parseIsomorphicRequest.d.ts +0 -6
  105. package/lib/types/utils/request/parseWorkerRequest.d.ts +0 -7
  106. package/lib/types/utils/request/pruneGetRequestBody.d.ts +0 -7
  107. package/lib/types/utils/request/readResponseCookies.d.ts +0 -3
  108. package/lib/types/utils/request/setRequestCookies.d.ts +0 -9
  109. package/lib/types/utils/url/cleanUrl.d.ts +0 -5
  110. package/lib/types/utils/url/getAbsoluteUrl.d.ts +0 -4
  111. package/lib/types/utils/url/getAbsoluteWorkerUrl.d.ts +0 -5
  112. package/lib/types/utils/url/isAbsoluteUrl.d.ts +0 -4
  113. package/lib/types/utils/worker/createFallbackRequestListener.d.ts +0 -4
  114. package/lib/types/utils/worker/createRequestListener.d.ts +0 -4
  115. package/lib/types/utils/worker/createResponseListener.d.ts +0 -3
  116. package/lib/umd/index.js +0 -31615
  117. package/lib/umd/mockServiceWorker.js +0 -338
  118. package/native/lib/index.js +0 -6384
  119. package/node/lib/index.js +0 -8276
@@ -1,3545 +0,0 @@
1
- import { d as data, e as extensions, a as errors } from './errors-deps.js';
2
- import { j as jsonParse, d as cookie } from './fetch-deps.js';
3
- import { g as getPublicUrlFromRequest, d as devUtils, o as __rest, e as defaultContext, R as RequestHandler, m as matchRequestUrl, j as prepareRequest, k as prepareResponse, l as getStatusCodeColor, n as getTimestamp } from './matchRequestUrl-deps.js';
4
-
5
- function devAssert(condition, message) {
6
- const booleanCondition = Boolean(condition);
7
-
8
- if (!booleanCondition) {
9
- throw new Error(message);
10
- }
11
- }
12
-
13
- /**
14
- * Return true if `value` is object-like. A value is object-like if it's not
15
- * `null` and has a `typeof` result of "object".
16
- */
17
- function isObjectLike(value) {
18
- return typeof value == 'object' && value !== null;
19
- }
20
-
21
- function invariant(condition, message) {
22
- const booleanCondition = Boolean(condition);
23
-
24
- if (!booleanCondition) {
25
- throw new Error(
26
- message != null ? message : 'Unexpected invariant triggered.',
27
- );
28
- }
29
- }
30
-
31
- const LineRegExp = /\r\n|[\n\r]/g;
32
- /**
33
- * Represents a location in a Source.
34
- */
35
-
36
- /**
37
- * Takes a Source and a UTF-8 character offset, and returns the corresponding
38
- * line and column as a SourceLocation.
39
- */
40
- function getLocation(source, position) {
41
- let lastLineStart = 0;
42
- let line = 1;
43
-
44
- for (const match of source.body.matchAll(LineRegExp)) {
45
- typeof match.index === 'number' || invariant(false);
46
-
47
- if (match.index >= position) {
48
- break;
49
- }
50
-
51
- lastLineStart = match.index + match[0].length;
52
- line += 1;
53
- }
54
-
55
- return {
56
- line,
57
- column: position + 1 - lastLineStart,
58
- };
59
- }
60
-
61
- /**
62
- * Render a helpful description of the location in the GraphQL Source document.
63
- */
64
- function printLocation(location) {
65
- return printSourceLocation(
66
- location.source,
67
- getLocation(location.source, location.start),
68
- );
69
- }
70
- /**
71
- * Render a helpful description of the location in the GraphQL Source document.
72
- */
73
-
74
- function printSourceLocation(source, sourceLocation) {
75
- const firstLineColumnOffset = source.locationOffset.column - 1;
76
- const body = ''.padStart(firstLineColumnOffset) + source.body;
77
- const lineIndex = sourceLocation.line - 1;
78
- const lineOffset = source.locationOffset.line - 1;
79
- const lineNum = sourceLocation.line + lineOffset;
80
- const columnOffset = sourceLocation.line === 1 ? firstLineColumnOffset : 0;
81
- const columnNum = sourceLocation.column + columnOffset;
82
- const locationStr = `${source.name}:${lineNum}:${columnNum}\n`;
83
- const lines = body.split(/\r\n|[\n\r]/g);
84
- const locationLine = lines[lineIndex]; // Special case for minified documents
85
-
86
- if (locationLine.length > 120) {
87
- const subLineIndex = Math.floor(columnNum / 80);
88
- const subLineColumnNum = columnNum % 80;
89
- const subLines = [];
90
-
91
- for (let i = 0; i < locationLine.length; i += 80) {
92
- subLines.push(locationLine.slice(i, i + 80));
93
- }
94
-
95
- return (
96
- locationStr +
97
- printPrefixedLines([
98
- [`${lineNum} |`, subLines[0]],
99
- ...subLines.slice(1, subLineIndex + 1).map((subLine) => ['|', subLine]),
100
- ['|', '^'.padStart(subLineColumnNum)],
101
- ['|', subLines[subLineIndex + 1]],
102
- ])
103
- );
104
- }
105
-
106
- return (
107
- locationStr +
108
- printPrefixedLines([
109
- // Lines specified like this: ["prefix", "string"],
110
- [`${lineNum - 1} |`, lines[lineIndex - 1]],
111
- [`${lineNum} |`, locationLine],
112
- ['|', '^'.padStart(columnNum)],
113
- [`${lineNum + 1} |`, lines[lineIndex + 1]],
114
- ])
115
- );
116
- }
117
-
118
- function printPrefixedLines(lines) {
119
- const existingLines = lines.filter(([_, line]) => line !== undefined);
120
- const padLen = Math.max(...existingLines.map(([prefix]) => prefix.length));
121
- return existingLines
122
- .map(([prefix, line]) => prefix.padStart(padLen) + (line ? ' ' + line : ''))
123
- .join('\n');
124
- }
125
-
126
- function toNormalizedArgs(args) {
127
- const firstArg = args[0];
128
-
129
- if (firstArg == null || 'kind' in firstArg || 'length' in firstArg) {
130
- return {
131
- nodes: firstArg,
132
- source: args[1],
133
- positions: args[2],
134
- path: args[3],
135
- originalError: args[4],
136
- extensions: args[5],
137
- };
138
- }
139
-
140
- return firstArg;
141
- }
142
- /**
143
- * A GraphQLError describes an Error found during the parse, validate, or
144
- * execute phases of performing a GraphQL operation. In addition to a message
145
- * and stack trace, it also includes information about the locations in a
146
- * GraphQL document and/or execution result that correspond to the Error.
147
- */
148
-
149
- class GraphQLError extends Error {
150
- /**
151
- * An array of `{ line, column }` locations within the source GraphQL document
152
- * which correspond to this error.
153
- *
154
- * Errors during validation often contain multiple locations, for example to
155
- * point out two things with the same name. Errors during execution include a
156
- * single location, the field which produced the error.
157
- *
158
- * Enumerable, and appears in the result of JSON.stringify().
159
- */
160
-
161
- /**
162
- * An array describing the JSON-path into the execution response which
163
- * corresponds to this error. Only included for errors during execution.
164
- *
165
- * Enumerable, and appears in the result of JSON.stringify().
166
- */
167
-
168
- /**
169
- * An array of GraphQL AST Nodes corresponding to this error.
170
- */
171
-
172
- /**
173
- * The source GraphQL document for the first location of this error.
174
- *
175
- * Note that if this Error represents more than one node, the source may not
176
- * represent nodes after the first node.
177
- */
178
-
179
- /**
180
- * An array of character offsets within the source GraphQL document
181
- * which correspond to this error.
182
- */
183
-
184
- /**
185
- * The original error thrown from a field resolver during execution.
186
- */
187
-
188
- /**
189
- * Extension fields to add to the formatted error.
190
- */
191
-
192
- /**
193
- * @deprecated Please use the `GraphQLErrorArgs` constructor overload instead.
194
- */
195
- constructor(message, ...rawArgs) {
196
- var _this$nodes, _nodeLocations$, _ref;
197
-
198
- const { nodes, source, positions, path, originalError, extensions } =
199
- toNormalizedArgs(rawArgs);
200
- super(message);
201
- this.name = 'GraphQLError';
202
- this.path = path !== null && path !== void 0 ? path : undefined;
203
- this.originalError =
204
- originalError !== null && originalError !== void 0
205
- ? originalError
206
- : undefined; // Compute list of blame nodes.
207
-
208
- this.nodes = undefinedIfEmpty(
209
- Array.isArray(nodes) ? nodes : nodes ? [nodes] : undefined,
210
- );
211
- const nodeLocations = undefinedIfEmpty(
212
- (_this$nodes = this.nodes) === null || _this$nodes === void 0
213
- ? void 0
214
- : _this$nodes.map((node) => node.loc).filter((loc) => loc != null),
215
- ); // Compute locations in the source for the given nodes/positions.
216
-
217
- this.source =
218
- source !== null && source !== void 0
219
- ? source
220
- : nodeLocations === null || nodeLocations === void 0
221
- ? void 0
222
- : (_nodeLocations$ = nodeLocations[0]) === null ||
223
- _nodeLocations$ === void 0
224
- ? void 0
225
- : _nodeLocations$.source;
226
- this.positions =
227
- positions !== null && positions !== void 0
228
- ? positions
229
- : nodeLocations === null || nodeLocations === void 0
230
- ? void 0
231
- : nodeLocations.map((loc) => loc.start);
232
- this.locations =
233
- positions && source
234
- ? positions.map((pos) => getLocation(source, pos))
235
- : nodeLocations === null || nodeLocations === void 0
236
- ? void 0
237
- : nodeLocations.map((loc) => getLocation(loc.source, loc.start));
238
- const originalExtensions = isObjectLike(
239
- originalError === null || originalError === void 0
240
- ? void 0
241
- : originalError.extensions,
242
- )
243
- ? originalError === null || originalError === void 0
244
- ? void 0
245
- : originalError.extensions
246
- : undefined;
247
- this.extensions =
248
- (_ref =
249
- extensions !== null && extensions !== void 0
250
- ? extensions
251
- : originalExtensions) !== null && _ref !== void 0
252
- ? _ref
253
- : Object.create(null); // Only properties prescribed by the spec should be enumerable.
254
- // Keep the rest as non-enumerable.
255
-
256
- Object.defineProperties(this, {
257
- message: {
258
- writable: true,
259
- enumerable: true,
260
- },
261
- name: {
262
- enumerable: false,
263
- },
264
- nodes: {
265
- enumerable: false,
266
- },
267
- source: {
268
- enumerable: false,
269
- },
270
- positions: {
271
- enumerable: false,
272
- },
273
- originalError: {
274
- enumerable: false,
275
- },
276
- }); // Include (non-enumerable) stack trace.
277
-
278
- /* c8 ignore start */
279
- // FIXME: https://github.com/graphql/graphql-js/issues/2317
280
-
281
- if (
282
- originalError !== null &&
283
- originalError !== void 0 &&
284
- originalError.stack
285
- ) {
286
- Object.defineProperty(this, 'stack', {
287
- value: originalError.stack,
288
- writable: true,
289
- configurable: true,
290
- });
291
- } else if (Error.captureStackTrace) {
292
- Error.captureStackTrace(this, GraphQLError);
293
- } else {
294
- Object.defineProperty(this, 'stack', {
295
- value: Error().stack,
296
- writable: true,
297
- configurable: true,
298
- });
299
- }
300
- /* c8 ignore stop */
301
- }
302
-
303
- get [Symbol.toStringTag]() {
304
- return 'GraphQLError';
305
- }
306
-
307
- toString() {
308
- let output = this.message;
309
-
310
- if (this.nodes) {
311
- for (const node of this.nodes) {
312
- if (node.loc) {
313
- output += '\n\n' + printLocation(node.loc);
314
- }
315
- }
316
- } else if (this.source && this.locations) {
317
- for (const location of this.locations) {
318
- output += '\n\n' + printSourceLocation(this.source, location);
319
- }
320
- }
321
-
322
- return output;
323
- }
324
-
325
- toJSON() {
326
- const formattedError = {
327
- message: this.message,
328
- };
329
-
330
- if (this.locations != null) {
331
- formattedError.locations = this.locations;
332
- }
333
-
334
- if (this.path != null) {
335
- formattedError.path = this.path;
336
- }
337
-
338
- if (this.extensions != null && Object.keys(this.extensions).length > 0) {
339
- formattedError.extensions = this.extensions;
340
- }
341
-
342
- return formattedError;
343
- }
344
- }
345
-
346
- function undefinedIfEmpty(array) {
347
- return array === undefined || array.length === 0 ? undefined : array;
348
- }
349
-
350
- /**
351
- * Produces a GraphQLError representing a syntax error, containing useful
352
- * descriptive information about the syntax error's position in the source.
353
- */
354
-
355
- function syntaxError(source, position, description) {
356
- return new GraphQLError(`Syntax Error: ${description}`, undefined, source, [
357
- position,
358
- ]);
359
- }
360
-
361
- /**
362
- * Contains a range of UTF-8 character offsets and token references that
363
- * identify the region of the source from which the AST derived.
364
- */
365
- class Location {
366
- /**
367
- * The character offset at which this Node begins.
368
- */
369
-
370
- /**
371
- * The character offset at which this Node ends.
372
- */
373
-
374
- /**
375
- * The Token at which this Node begins.
376
- */
377
-
378
- /**
379
- * The Token at which this Node ends.
380
- */
381
-
382
- /**
383
- * The Source document the AST represents.
384
- */
385
- constructor(startToken, endToken, source) {
386
- this.start = startToken.start;
387
- this.end = endToken.end;
388
- this.startToken = startToken;
389
- this.endToken = endToken;
390
- this.source = source;
391
- }
392
-
393
- get [Symbol.toStringTag]() {
394
- return 'Location';
395
- }
396
-
397
- toJSON() {
398
- return {
399
- start: this.start,
400
- end: this.end,
401
- };
402
- }
403
- }
404
- /**
405
- * Represents a range of characters represented by a lexical token
406
- * within a Source.
407
- */
408
-
409
- class Token {
410
- /**
411
- * The kind of Token.
412
- */
413
-
414
- /**
415
- * The character offset at which this Node begins.
416
- */
417
-
418
- /**
419
- * The character offset at which this Node ends.
420
- */
421
-
422
- /**
423
- * The 1-indexed line number on which this Token appears.
424
- */
425
-
426
- /**
427
- * The 1-indexed column number at which this Token begins.
428
- */
429
-
430
- /**
431
- * For non-punctuation tokens, represents the interpreted value of the token.
432
- *
433
- * Note: is undefined for punctuation tokens, but typed as string for
434
- * convenience in the parser.
435
- */
436
-
437
- /**
438
- * Tokens exist as nodes in a double-linked-list amongst all tokens
439
- * including ignored tokens. <SOF> is always the first node and <EOF>
440
- * the last.
441
- */
442
- constructor(kind, start, end, line, column, value) {
443
- this.kind = kind;
444
- this.start = start;
445
- this.end = end;
446
- this.line = line;
447
- this.column = column; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
448
-
449
- this.value = value;
450
- this.prev = null;
451
- this.next = null;
452
- }
453
-
454
- get [Symbol.toStringTag]() {
455
- return 'Token';
456
- }
457
-
458
- toJSON() {
459
- return {
460
- kind: this.kind,
461
- value: this.value,
462
- line: this.line,
463
- column: this.column,
464
- };
465
- }
466
- }
467
- /** Name */
468
-
469
- let OperationTypeNode;
470
-
471
- (function (OperationTypeNode) {
472
- OperationTypeNode['QUERY'] = 'query';
473
- OperationTypeNode['MUTATION'] = 'mutation';
474
- OperationTypeNode['SUBSCRIPTION'] = 'subscription';
475
- })(OperationTypeNode || (OperationTypeNode = {}));
476
-
477
- /**
478
- * The set of allowed directive location values.
479
- */
480
- let DirectiveLocation;
481
- /**
482
- * The enum type representing the directive location values.
483
- *
484
- * @deprecated Please use `DirectiveLocation`. Will be remove in v17.
485
- */
486
-
487
- (function (DirectiveLocation) {
488
- DirectiveLocation['QUERY'] = 'QUERY';
489
- DirectiveLocation['MUTATION'] = 'MUTATION';
490
- DirectiveLocation['SUBSCRIPTION'] = 'SUBSCRIPTION';
491
- DirectiveLocation['FIELD'] = 'FIELD';
492
- DirectiveLocation['FRAGMENT_DEFINITION'] = 'FRAGMENT_DEFINITION';
493
- DirectiveLocation['FRAGMENT_SPREAD'] = 'FRAGMENT_SPREAD';
494
- DirectiveLocation['INLINE_FRAGMENT'] = 'INLINE_FRAGMENT';
495
- DirectiveLocation['VARIABLE_DEFINITION'] = 'VARIABLE_DEFINITION';
496
- DirectiveLocation['SCHEMA'] = 'SCHEMA';
497
- DirectiveLocation['SCALAR'] = 'SCALAR';
498
- DirectiveLocation['OBJECT'] = 'OBJECT';
499
- DirectiveLocation['FIELD_DEFINITION'] = 'FIELD_DEFINITION';
500
- DirectiveLocation['ARGUMENT_DEFINITION'] = 'ARGUMENT_DEFINITION';
501
- DirectiveLocation['INTERFACE'] = 'INTERFACE';
502
- DirectiveLocation['UNION'] = 'UNION';
503
- DirectiveLocation['ENUM'] = 'ENUM';
504
- DirectiveLocation['ENUM_VALUE'] = 'ENUM_VALUE';
505
- DirectiveLocation['INPUT_OBJECT'] = 'INPUT_OBJECT';
506
- DirectiveLocation['INPUT_FIELD_DEFINITION'] = 'INPUT_FIELD_DEFINITION';
507
- })(DirectiveLocation || (DirectiveLocation = {}));
508
-
509
- /**
510
- * The set of allowed kind values for AST nodes.
511
- */
512
- let Kind;
513
- /**
514
- * The enum type representing the possible kind values of AST nodes.
515
- *
516
- * @deprecated Please use `Kind`. Will be remove in v17.
517
- */
518
-
519
- (function (Kind) {
520
- Kind['NAME'] = 'Name';
521
- Kind['DOCUMENT'] = 'Document';
522
- Kind['OPERATION_DEFINITION'] = 'OperationDefinition';
523
- Kind['VARIABLE_DEFINITION'] = 'VariableDefinition';
524
- Kind['SELECTION_SET'] = 'SelectionSet';
525
- Kind['FIELD'] = 'Field';
526
- Kind['ARGUMENT'] = 'Argument';
527
- Kind['FRAGMENT_SPREAD'] = 'FragmentSpread';
528
- Kind['INLINE_FRAGMENT'] = 'InlineFragment';
529
- Kind['FRAGMENT_DEFINITION'] = 'FragmentDefinition';
530
- Kind['VARIABLE'] = 'Variable';
531
- Kind['INT'] = 'IntValue';
532
- Kind['FLOAT'] = 'FloatValue';
533
- Kind['STRING'] = 'StringValue';
534
- Kind['BOOLEAN'] = 'BooleanValue';
535
- Kind['NULL'] = 'NullValue';
536
- Kind['ENUM'] = 'EnumValue';
537
- Kind['LIST'] = 'ListValue';
538
- Kind['OBJECT'] = 'ObjectValue';
539
- Kind['OBJECT_FIELD'] = 'ObjectField';
540
- Kind['DIRECTIVE'] = 'Directive';
541
- Kind['NAMED_TYPE'] = 'NamedType';
542
- Kind['LIST_TYPE'] = 'ListType';
543
- Kind['NON_NULL_TYPE'] = 'NonNullType';
544
- Kind['SCHEMA_DEFINITION'] = 'SchemaDefinition';
545
- Kind['OPERATION_TYPE_DEFINITION'] = 'OperationTypeDefinition';
546
- Kind['SCALAR_TYPE_DEFINITION'] = 'ScalarTypeDefinition';
547
- Kind['OBJECT_TYPE_DEFINITION'] = 'ObjectTypeDefinition';
548
- Kind['FIELD_DEFINITION'] = 'FieldDefinition';
549
- Kind['INPUT_VALUE_DEFINITION'] = 'InputValueDefinition';
550
- Kind['INTERFACE_TYPE_DEFINITION'] = 'InterfaceTypeDefinition';
551
- Kind['UNION_TYPE_DEFINITION'] = 'UnionTypeDefinition';
552
- Kind['ENUM_TYPE_DEFINITION'] = 'EnumTypeDefinition';
553
- Kind['ENUM_VALUE_DEFINITION'] = 'EnumValueDefinition';
554
- Kind['INPUT_OBJECT_TYPE_DEFINITION'] = 'InputObjectTypeDefinition';
555
- Kind['DIRECTIVE_DEFINITION'] = 'DirectiveDefinition';
556
- Kind['SCHEMA_EXTENSION'] = 'SchemaExtension';
557
- Kind['SCALAR_TYPE_EXTENSION'] = 'ScalarTypeExtension';
558
- Kind['OBJECT_TYPE_EXTENSION'] = 'ObjectTypeExtension';
559
- Kind['INTERFACE_TYPE_EXTENSION'] = 'InterfaceTypeExtension';
560
- Kind['UNION_TYPE_EXTENSION'] = 'UnionTypeExtension';
561
- Kind['ENUM_TYPE_EXTENSION'] = 'EnumTypeExtension';
562
- Kind['INPUT_OBJECT_TYPE_EXTENSION'] = 'InputObjectTypeExtension';
563
- })(Kind || (Kind = {}));
564
-
565
- /**
566
- * ```
567
- * WhiteSpace ::
568
- * - "Horizontal Tab (U+0009)"
569
- * - "Space (U+0020)"
570
- * ```
571
- * @internal
572
- */
573
- function isWhiteSpace(code) {
574
- return code === 0x0009 || code === 0x0020;
575
- }
576
- /**
577
- * ```
578
- * Digit :: one of
579
- * - `0` `1` `2` `3` `4` `5` `6` `7` `8` `9`
580
- * ```
581
- * @internal
582
- */
583
-
584
- function isDigit(code) {
585
- return code >= 0x0030 && code <= 0x0039;
586
- }
587
- /**
588
- * ```
589
- * Letter :: one of
590
- * - `A` `B` `C` `D` `E` `F` `G` `H` `I` `J` `K` `L` `M`
591
- * - `N` `O` `P` `Q` `R` `S` `T` `U` `V` `W` `X` `Y` `Z`
592
- * - `a` `b` `c` `d` `e` `f` `g` `h` `i` `j` `k` `l` `m`
593
- * - `n` `o` `p` `q` `r` `s` `t` `u` `v` `w` `x` `y` `z`
594
- * ```
595
- * @internal
596
- */
597
-
598
- function isLetter(code) {
599
- return (
600
- (code >= 0x0061 && code <= 0x007a) || // A-Z
601
- (code >= 0x0041 && code <= 0x005a) // a-z
602
- );
603
- }
604
- /**
605
- * ```
606
- * NameStart ::
607
- * - Letter
608
- * - `_`
609
- * ```
610
- * @internal
611
- */
612
-
613
- function isNameStart(code) {
614
- return isLetter(code) || code === 0x005f;
615
- }
616
- /**
617
- * ```
618
- * NameContinue ::
619
- * - Letter
620
- * - Digit
621
- * - `_`
622
- * ```
623
- * @internal
624
- */
625
-
626
- function isNameContinue(code) {
627
- return isLetter(code) || isDigit(code) || code === 0x005f;
628
- }
629
-
630
- /**
631
- * Produces the value of a block string from its parsed raw value, similar to
632
- * CoffeeScript's block string, Python's docstring trim or Ruby's strip_heredoc.
633
- *
634
- * This implements the GraphQL spec's BlockStringValue() static algorithm.
635
- *
636
- * @internal
637
- */
638
-
639
- function dedentBlockStringLines(lines) {
640
- var _firstNonEmptyLine2;
641
-
642
- let commonIndent = Number.MAX_SAFE_INTEGER;
643
- let firstNonEmptyLine = null;
644
- let lastNonEmptyLine = -1;
645
-
646
- for (let i = 0; i < lines.length; ++i) {
647
- var _firstNonEmptyLine;
648
-
649
- const line = lines[i];
650
- const indent = leadingWhitespace(line);
651
-
652
- if (indent === line.length) {
653
- continue; // skip empty lines
654
- }
655
-
656
- firstNonEmptyLine =
657
- (_firstNonEmptyLine = firstNonEmptyLine) !== null &&
658
- _firstNonEmptyLine !== void 0
659
- ? _firstNonEmptyLine
660
- : i;
661
- lastNonEmptyLine = i;
662
-
663
- if (i !== 0 && indent < commonIndent) {
664
- commonIndent = indent;
665
- }
666
- }
667
-
668
- return lines // Remove common indentation from all lines but first.
669
- .map((line, i) => (i === 0 ? line : line.slice(commonIndent))) // Remove leading and trailing blank lines.
670
- .slice(
671
- (_firstNonEmptyLine2 = firstNonEmptyLine) !== null &&
672
- _firstNonEmptyLine2 !== void 0
673
- ? _firstNonEmptyLine2
674
- : 0,
675
- lastNonEmptyLine + 1,
676
- );
677
- }
678
-
679
- function leadingWhitespace(str) {
680
- let i = 0;
681
-
682
- while (i < str.length && isWhiteSpace(str.charCodeAt(i))) {
683
- ++i;
684
- }
685
-
686
- return i;
687
- }
688
-
689
- /**
690
- * An exported enum describing the different kinds of tokens that the
691
- * lexer emits.
692
- */
693
- let TokenKind;
694
- /**
695
- * The enum type representing the token kinds values.
696
- *
697
- * @deprecated Please use `TokenKind`. Will be remove in v17.
698
- */
699
-
700
- (function (TokenKind) {
701
- TokenKind['SOF'] = '<SOF>';
702
- TokenKind['EOF'] = '<EOF>';
703
- TokenKind['BANG'] = '!';
704
- TokenKind['DOLLAR'] = '$';
705
- TokenKind['AMP'] = '&';
706
- TokenKind['PAREN_L'] = '(';
707
- TokenKind['PAREN_R'] = ')';
708
- TokenKind['SPREAD'] = '...';
709
- TokenKind['COLON'] = ':';
710
- TokenKind['EQUALS'] = '=';
711
- TokenKind['AT'] = '@';
712
- TokenKind['BRACKET_L'] = '[';
713
- TokenKind['BRACKET_R'] = ']';
714
- TokenKind['BRACE_L'] = '{';
715
- TokenKind['PIPE'] = '|';
716
- TokenKind['BRACE_R'] = '}';
717
- TokenKind['NAME'] = 'Name';
718
- TokenKind['INT'] = 'Int';
719
- TokenKind['FLOAT'] = 'Float';
720
- TokenKind['STRING'] = 'String';
721
- TokenKind['BLOCK_STRING'] = 'BlockString';
722
- TokenKind['COMMENT'] = 'Comment';
723
- })(TokenKind || (TokenKind = {}));
724
-
725
- /**
726
- * Given a Source object, creates a Lexer for that source.
727
- * A Lexer is a stateful stream generator in that every time
728
- * it is advanced, it returns the next token in the Source. Assuming the
729
- * source lexes, the final Token emitted by the lexer will be of kind
730
- * EOF, after which the lexer will repeatedly return the same EOF token
731
- * whenever called.
732
- */
733
-
734
- class Lexer {
735
- /**
736
- * The previously focused non-ignored token.
737
- */
738
-
739
- /**
740
- * The currently focused non-ignored token.
741
- */
742
-
743
- /**
744
- * The (1-indexed) line containing the current token.
745
- */
746
-
747
- /**
748
- * The character offset at which the current line begins.
749
- */
750
- constructor(source) {
751
- const startOfFileToken = new Token(TokenKind.SOF, 0, 0, 0, 0);
752
- this.source = source;
753
- this.lastToken = startOfFileToken;
754
- this.token = startOfFileToken;
755
- this.line = 1;
756
- this.lineStart = 0;
757
- }
758
-
759
- get [Symbol.toStringTag]() {
760
- return 'Lexer';
761
- }
762
- /**
763
- * Advances the token stream to the next non-ignored token.
764
- */
765
-
766
- advance() {
767
- this.lastToken = this.token;
768
- const token = (this.token = this.lookahead());
769
- return token;
770
- }
771
- /**
772
- * Looks ahead and returns the next non-ignored token, but does not change
773
- * the state of Lexer.
774
- */
775
-
776
- lookahead() {
777
- let token = this.token;
778
-
779
- if (token.kind !== TokenKind.EOF) {
780
- do {
781
- if (token.next) {
782
- token = token.next;
783
- } else {
784
- // Read the next token and form a link in the token linked-list.
785
- const nextToken = readNextToken(this, token.end); // @ts-expect-error next is only mutable during parsing.
786
-
787
- token.next = nextToken; // @ts-expect-error prev is only mutable during parsing.
788
-
789
- nextToken.prev = token;
790
- token = nextToken;
791
- }
792
- } while (token.kind === TokenKind.COMMENT);
793
- }
794
-
795
- return token;
796
- }
797
- }
798
- /**
799
- * @internal
800
- */
801
-
802
- function isPunctuatorTokenKind(kind) {
803
- return (
804
- kind === TokenKind.BANG ||
805
- kind === TokenKind.DOLLAR ||
806
- kind === TokenKind.AMP ||
807
- kind === TokenKind.PAREN_L ||
808
- kind === TokenKind.PAREN_R ||
809
- kind === TokenKind.SPREAD ||
810
- kind === TokenKind.COLON ||
811
- kind === TokenKind.EQUALS ||
812
- kind === TokenKind.AT ||
813
- kind === TokenKind.BRACKET_L ||
814
- kind === TokenKind.BRACKET_R ||
815
- kind === TokenKind.BRACE_L ||
816
- kind === TokenKind.PIPE ||
817
- kind === TokenKind.BRACE_R
818
- );
819
- }
820
- /**
821
- * A Unicode scalar value is any Unicode code point except surrogate code
822
- * points. In other words, the inclusive ranges of values 0x0000 to 0xD7FF and
823
- * 0xE000 to 0x10FFFF.
824
- *
825
- * SourceCharacter ::
826
- * - "Any Unicode scalar value"
827
- */
828
-
829
- function isUnicodeScalarValue(code) {
830
- return (
831
- (code >= 0x0000 && code <= 0xd7ff) || (code >= 0xe000 && code <= 0x10ffff)
832
- );
833
- }
834
- /**
835
- * The GraphQL specification defines source text as a sequence of unicode scalar
836
- * values (which Unicode defines to exclude surrogate code points). However
837
- * JavaScript defines strings as a sequence of UTF-16 code units which may
838
- * include surrogates. A surrogate pair is a valid source character as it
839
- * encodes a supplementary code point (above U+FFFF), but unpaired surrogate
840
- * code points are not valid source characters.
841
- */
842
-
843
- function isSupplementaryCodePoint(body, location) {
844
- return (
845
- isLeadingSurrogate(body.charCodeAt(location)) &&
846
- isTrailingSurrogate(body.charCodeAt(location + 1))
847
- );
848
- }
849
-
850
- function isLeadingSurrogate(code) {
851
- return code >= 0xd800 && code <= 0xdbff;
852
- }
853
-
854
- function isTrailingSurrogate(code) {
855
- return code >= 0xdc00 && code <= 0xdfff;
856
- }
857
- /**
858
- * Prints the code point (or end of file reference) at a given location in a
859
- * source for use in error messages.
860
- *
861
- * Printable ASCII is printed quoted, while other points are printed in Unicode
862
- * code point form (ie. U+1234).
863
- */
864
-
865
- function printCodePointAt(lexer, location) {
866
- const code = lexer.source.body.codePointAt(location);
867
-
868
- if (code === undefined) {
869
- return TokenKind.EOF;
870
- } else if (code >= 0x0020 && code <= 0x007e) {
871
- // Printable ASCII
872
- const char = String.fromCodePoint(code);
873
- return char === '"' ? "'\"'" : `"${char}"`;
874
- } // Unicode code point
875
-
876
- return 'U+' + code.toString(16).toUpperCase().padStart(4, '0');
877
- }
878
- /**
879
- * Create a token with line and column location information.
880
- */
881
-
882
- function createToken(lexer, kind, start, end, value) {
883
- const line = lexer.line;
884
- const col = 1 + start - lexer.lineStart;
885
- return new Token(kind, start, end, line, col, value);
886
- }
887
- /**
888
- * Gets the next token from the source starting at the given position.
889
- *
890
- * This skips over whitespace until it finds the next lexable token, then lexes
891
- * punctuators immediately or calls the appropriate helper function for more
892
- * complicated tokens.
893
- */
894
-
895
- function readNextToken(lexer, start) {
896
- const body = lexer.source.body;
897
- const bodyLength = body.length;
898
- let position = start;
899
-
900
- while (position < bodyLength) {
901
- const code = body.charCodeAt(position); // SourceCharacter
902
-
903
- switch (code) {
904
- // Ignored ::
905
- // - UnicodeBOM
906
- // - WhiteSpace
907
- // - LineTerminator
908
- // - Comment
909
- // - Comma
910
- //
911
- // UnicodeBOM :: "Byte Order Mark (U+FEFF)"
912
- //
913
- // WhiteSpace ::
914
- // - "Horizontal Tab (U+0009)"
915
- // - "Space (U+0020)"
916
- //
917
- // Comma :: ,
918
- case 0xfeff: // <BOM>
919
-
920
- case 0x0009: // \t
921
-
922
- case 0x0020: // <space>
923
-
924
- case 0x002c:
925
- // ,
926
- ++position;
927
- continue;
928
- // LineTerminator ::
929
- // - "New Line (U+000A)"
930
- // - "Carriage Return (U+000D)" [lookahead != "New Line (U+000A)"]
931
- // - "Carriage Return (U+000D)" "New Line (U+000A)"
932
-
933
- case 0x000a:
934
- // \n
935
- ++position;
936
- ++lexer.line;
937
- lexer.lineStart = position;
938
- continue;
939
-
940
- case 0x000d:
941
- // \r
942
- if (body.charCodeAt(position + 1) === 0x000a) {
943
- position += 2;
944
- } else {
945
- ++position;
946
- }
947
-
948
- ++lexer.line;
949
- lexer.lineStart = position;
950
- continue;
951
- // Comment
952
-
953
- case 0x0023:
954
- // #
955
- return readComment(lexer, position);
956
- // Token ::
957
- // - Punctuator
958
- // - Name
959
- // - IntValue
960
- // - FloatValue
961
- // - StringValue
962
- //
963
- // Punctuator :: one of ! $ & ( ) ... : = @ [ ] { | }
964
-
965
- case 0x0021:
966
- // !
967
- return createToken(lexer, TokenKind.BANG, position, position + 1);
968
-
969
- case 0x0024:
970
- // $
971
- return createToken(lexer, TokenKind.DOLLAR, position, position + 1);
972
-
973
- case 0x0026:
974
- // &
975
- return createToken(lexer, TokenKind.AMP, position, position + 1);
976
-
977
- case 0x0028:
978
- // (
979
- return createToken(lexer, TokenKind.PAREN_L, position, position + 1);
980
-
981
- case 0x0029:
982
- // )
983
- return createToken(lexer, TokenKind.PAREN_R, position, position + 1);
984
-
985
- case 0x002e:
986
- // .
987
- if (
988
- body.charCodeAt(position + 1) === 0x002e &&
989
- body.charCodeAt(position + 2) === 0x002e
990
- ) {
991
- return createToken(lexer, TokenKind.SPREAD, position, position + 3);
992
- }
993
-
994
- break;
995
-
996
- case 0x003a:
997
- // :
998
- return createToken(lexer, TokenKind.COLON, position, position + 1);
999
-
1000
- case 0x003d:
1001
- // =
1002
- return createToken(lexer, TokenKind.EQUALS, position, position + 1);
1003
-
1004
- case 0x0040:
1005
- // @
1006
- return createToken(lexer, TokenKind.AT, position, position + 1);
1007
-
1008
- case 0x005b:
1009
- // [
1010
- return createToken(lexer, TokenKind.BRACKET_L, position, position + 1);
1011
-
1012
- case 0x005d:
1013
- // ]
1014
- return createToken(lexer, TokenKind.BRACKET_R, position, position + 1);
1015
-
1016
- case 0x007b:
1017
- // {
1018
- return createToken(lexer, TokenKind.BRACE_L, position, position + 1);
1019
-
1020
- case 0x007c:
1021
- // |
1022
- return createToken(lexer, TokenKind.PIPE, position, position + 1);
1023
-
1024
- case 0x007d:
1025
- // }
1026
- return createToken(lexer, TokenKind.BRACE_R, position, position + 1);
1027
- // StringValue
1028
-
1029
- case 0x0022:
1030
- // "
1031
- if (
1032
- body.charCodeAt(position + 1) === 0x0022 &&
1033
- body.charCodeAt(position + 2) === 0x0022
1034
- ) {
1035
- return readBlockString(lexer, position);
1036
- }
1037
-
1038
- return readString(lexer, position);
1039
- } // IntValue | FloatValue (Digit | -)
1040
-
1041
- if (isDigit(code) || code === 0x002d) {
1042
- return readNumber(lexer, position, code);
1043
- } // Name
1044
-
1045
- if (isNameStart(code)) {
1046
- return readName(lexer, position);
1047
- }
1048
-
1049
- throw syntaxError(
1050
- lexer.source,
1051
- position,
1052
- code === 0x0027
1053
- ? 'Unexpected single quote character (\'), did you mean to use a double quote (")?'
1054
- : isUnicodeScalarValue(code) || isSupplementaryCodePoint(body, position)
1055
- ? `Unexpected character: ${printCodePointAt(lexer, position)}.`
1056
- : `Invalid character: ${printCodePointAt(lexer, position)}.`,
1057
- );
1058
- }
1059
-
1060
- return createToken(lexer, TokenKind.EOF, bodyLength, bodyLength);
1061
- }
1062
- /**
1063
- * Reads a comment token from the source file.
1064
- *
1065
- * ```
1066
- * Comment :: # CommentChar* [lookahead != CommentChar]
1067
- *
1068
- * CommentChar :: SourceCharacter but not LineTerminator
1069
- * ```
1070
- */
1071
-
1072
- function readComment(lexer, start) {
1073
- const body = lexer.source.body;
1074
- const bodyLength = body.length;
1075
- let position = start + 1;
1076
-
1077
- while (position < bodyLength) {
1078
- const code = body.charCodeAt(position); // LineTerminator (\n | \r)
1079
-
1080
- if (code === 0x000a || code === 0x000d) {
1081
- break;
1082
- } // SourceCharacter
1083
-
1084
- if (isUnicodeScalarValue(code)) {
1085
- ++position;
1086
- } else if (isSupplementaryCodePoint(body, position)) {
1087
- position += 2;
1088
- } else {
1089
- break;
1090
- }
1091
- }
1092
-
1093
- return createToken(
1094
- lexer,
1095
- TokenKind.COMMENT,
1096
- start,
1097
- position,
1098
- body.slice(start + 1, position),
1099
- );
1100
- }
1101
- /**
1102
- * Reads a number token from the source file, either a FloatValue or an IntValue
1103
- * depending on whether a FractionalPart or ExponentPart is encountered.
1104
- *
1105
- * ```
1106
- * IntValue :: IntegerPart [lookahead != {Digit, `.`, NameStart}]
1107
- *
1108
- * IntegerPart ::
1109
- * - NegativeSign? 0
1110
- * - NegativeSign? NonZeroDigit Digit*
1111
- *
1112
- * NegativeSign :: -
1113
- *
1114
- * NonZeroDigit :: Digit but not `0`
1115
- *
1116
- * FloatValue ::
1117
- * - IntegerPart FractionalPart ExponentPart [lookahead != {Digit, `.`, NameStart}]
1118
- * - IntegerPart FractionalPart [lookahead != {Digit, `.`, NameStart}]
1119
- * - IntegerPart ExponentPart [lookahead != {Digit, `.`, NameStart}]
1120
- *
1121
- * FractionalPart :: . Digit+
1122
- *
1123
- * ExponentPart :: ExponentIndicator Sign? Digit+
1124
- *
1125
- * ExponentIndicator :: one of `e` `E`
1126
- *
1127
- * Sign :: one of + -
1128
- * ```
1129
- */
1130
-
1131
- function readNumber(lexer, start, firstCode) {
1132
- const body = lexer.source.body;
1133
- let position = start;
1134
- let code = firstCode;
1135
- let isFloat = false; // NegativeSign (-)
1136
-
1137
- if (code === 0x002d) {
1138
- code = body.charCodeAt(++position);
1139
- } // Zero (0)
1140
-
1141
- if (code === 0x0030) {
1142
- code = body.charCodeAt(++position);
1143
-
1144
- if (isDigit(code)) {
1145
- throw syntaxError(
1146
- lexer.source,
1147
- position,
1148
- `Invalid number, unexpected digit after 0: ${printCodePointAt(
1149
- lexer,
1150
- position,
1151
- )}.`,
1152
- );
1153
- }
1154
- } else {
1155
- position = readDigits(lexer, position, code);
1156
- code = body.charCodeAt(position);
1157
- } // Full stop (.)
1158
-
1159
- if (code === 0x002e) {
1160
- isFloat = true;
1161
- code = body.charCodeAt(++position);
1162
- position = readDigits(lexer, position, code);
1163
- code = body.charCodeAt(position);
1164
- } // E e
1165
-
1166
- if (code === 0x0045 || code === 0x0065) {
1167
- isFloat = true;
1168
- code = body.charCodeAt(++position); // + -
1169
-
1170
- if (code === 0x002b || code === 0x002d) {
1171
- code = body.charCodeAt(++position);
1172
- }
1173
-
1174
- position = readDigits(lexer, position, code);
1175
- code = body.charCodeAt(position);
1176
- } // Numbers cannot be followed by . or NameStart
1177
-
1178
- if (code === 0x002e || isNameStart(code)) {
1179
- throw syntaxError(
1180
- lexer.source,
1181
- position,
1182
- `Invalid number, expected digit but got: ${printCodePointAt(
1183
- lexer,
1184
- position,
1185
- )}.`,
1186
- );
1187
- }
1188
-
1189
- return createToken(
1190
- lexer,
1191
- isFloat ? TokenKind.FLOAT : TokenKind.INT,
1192
- start,
1193
- position,
1194
- body.slice(start, position),
1195
- );
1196
- }
1197
- /**
1198
- * Returns the new position in the source after reading one or more digits.
1199
- */
1200
-
1201
- function readDigits(lexer, start, firstCode) {
1202
- if (!isDigit(firstCode)) {
1203
- throw syntaxError(
1204
- lexer.source,
1205
- start,
1206
- `Invalid number, expected digit but got: ${printCodePointAt(
1207
- lexer,
1208
- start,
1209
- )}.`,
1210
- );
1211
- }
1212
-
1213
- const body = lexer.source.body;
1214
- let position = start + 1; // +1 to skip first firstCode
1215
-
1216
- while (isDigit(body.charCodeAt(position))) {
1217
- ++position;
1218
- }
1219
-
1220
- return position;
1221
- }
1222
- /**
1223
- * Reads a single-quote string token from the source file.
1224
- *
1225
- * ```
1226
- * StringValue ::
1227
- * - `""` [lookahead != `"`]
1228
- * - `"` StringCharacter+ `"`
1229
- *
1230
- * StringCharacter ::
1231
- * - SourceCharacter but not `"` or `\` or LineTerminator
1232
- * - `\u` EscapedUnicode
1233
- * - `\` EscapedCharacter
1234
- *
1235
- * EscapedUnicode ::
1236
- * - `{` HexDigit+ `}`
1237
- * - HexDigit HexDigit HexDigit HexDigit
1238
- *
1239
- * EscapedCharacter :: one of `"` `\` `/` `b` `f` `n` `r` `t`
1240
- * ```
1241
- */
1242
-
1243
- function readString(lexer, start) {
1244
- const body = lexer.source.body;
1245
- const bodyLength = body.length;
1246
- let position = start + 1;
1247
- let chunkStart = position;
1248
- let value = '';
1249
-
1250
- while (position < bodyLength) {
1251
- const code = body.charCodeAt(position); // Closing Quote (")
1252
-
1253
- if (code === 0x0022) {
1254
- value += body.slice(chunkStart, position);
1255
- return createToken(lexer, TokenKind.STRING, start, position + 1, value);
1256
- } // Escape Sequence (\)
1257
-
1258
- if (code === 0x005c) {
1259
- value += body.slice(chunkStart, position);
1260
- const escape =
1261
- body.charCodeAt(position + 1) === 0x0075 // u
1262
- ? body.charCodeAt(position + 2) === 0x007b // {
1263
- ? readEscapedUnicodeVariableWidth(lexer, position)
1264
- : readEscapedUnicodeFixedWidth(lexer, position)
1265
- : readEscapedCharacter(lexer, position);
1266
- value += escape.value;
1267
- position += escape.size;
1268
- chunkStart = position;
1269
- continue;
1270
- } // LineTerminator (\n | \r)
1271
-
1272
- if (code === 0x000a || code === 0x000d) {
1273
- break;
1274
- } // SourceCharacter
1275
-
1276
- if (isUnicodeScalarValue(code)) {
1277
- ++position;
1278
- } else if (isSupplementaryCodePoint(body, position)) {
1279
- position += 2;
1280
- } else {
1281
- throw syntaxError(
1282
- lexer.source,
1283
- position,
1284
- `Invalid character within String: ${printCodePointAt(
1285
- lexer,
1286
- position,
1287
- )}.`,
1288
- );
1289
- }
1290
- }
1291
-
1292
- throw syntaxError(lexer.source, position, 'Unterminated string.');
1293
- } // The string value and lexed size of an escape sequence.
1294
-
1295
- function readEscapedUnicodeVariableWidth(lexer, position) {
1296
- const body = lexer.source.body;
1297
- let point = 0;
1298
- let size = 3; // Cannot be larger than 12 chars (\u{00000000}).
1299
-
1300
- while (size < 12) {
1301
- const code = body.charCodeAt(position + size++); // Closing Brace (})
1302
-
1303
- if (code === 0x007d) {
1304
- // Must be at least 5 chars (\u{0}) and encode a Unicode scalar value.
1305
- if (size < 5 || !isUnicodeScalarValue(point)) {
1306
- break;
1307
- }
1308
-
1309
- return {
1310
- value: String.fromCodePoint(point),
1311
- size,
1312
- };
1313
- } // Append this hex digit to the code point.
1314
-
1315
- point = (point << 4) | readHexDigit(code);
1316
-
1317
- if (point < 0) {
1318
- break;
1319
- }
1320
- }
1321
-
1322
- throw syntaxError(
1323
- lexer.source,
1324
- position,
1325
- `Invalid Unicode escape sequence: "${body.slice(
1326
- position,
1327
- position + size,
1328
- )}".`,
1329
- );
1330
- }
1331
-
1332
- function readEscapedUnicodeFixedWidth(lexer, position) {
1333
- const body = lexer.source.body;
1334
- const code = read16BitHexCode(body, position + 2);
1335
-
1336
- if (isUnicodeScalarValue(code)) {
1337
- return {
1338
- value: String.fromCodePoint(code),
1339
- size: 6,
1340
- };
1341
- } // GraphQL allows JSON-style surrogate pair escape sequences, but only when
1342
- // a valid pair is formed.
1343
-
1344
- if (isLeadingSurrogate(code)) {
1345
- // \u
1346
- if (
1347
- body.charCodeAt(position + 6) === 0x005c &&
1348
- body.charCodeAt(position + 7) === 0x0075
1349
- ) {
1350
- const trailingCode = read16BitHexCode(body, position + 8);
1351
-
1352
- if (isTrailingSurrogate(trailingCode)) {
1353
- // JavaScript defines strings as a sequence of UTF-16 code units and
1354
- // encodes Unicode code points above U+FFFF using a surrogate pair of
1355
- // code units. Since this is a surrogate pair escape sequence, just
1356
- // include both codes into the JavaScript string value. Had JavaScript
1357
- // not been internally based on UTF-16, then this surrogate pair would
1358
- // be decoded to retrieve the supplementary code point.
1359
- return {
1360
- value: String.fromCodePoint(code, trailingCode),
1361
- size: 12,
1362
- };
1363
- }
1364
- }
1365
- }
1366
-
1367
- throw syntaxError(
1368
- lexer.source,
1369
- position,
1370
- `Invalid Unicode escape sequence: "${body.slice(position, position + 6)}".`,
1371
- );
1372
- }
1373
- /**
1374
- * Reads four hexadecimal characters and returns the positive integer that 16bit
1375
- * hexadecimal string represents. For example, "000f" will return 15, and "dead"
1376
- * will return 57005.
1377
- *
1378
- * Returns a negative number if any char was not a valid hexadecimal digit.
1379
- */
1380
-
1381
- function read16BitHexCode(body, position) {
1382
- // readHexDigit() returns -1 on error. ORing a negative value with any other
1383
- // value always produces a negative value.
1384
- return (
1385
- (readHexDigit(body.charCodeAt(position)) << 12) |
1386
- (readHexDigit(body.charCodeAt(position + 1)) << 8) |
1387
- (readHexDigit(body.charCodeAt(position + 2)) << 4) |
1388
- readHexDigit(body.charCodeAt(position + 3))
1389
- );
1390
- }
1391
- /**
1392
- * Reads a hexadecimal character and returns its positive integer value (0-15).
1393
- *
1394
- * '0' becomes 0, '9' becomes 9
1395
- * 'A' becomes 10, 'F' becomes 15
1396
- * 'a' becomes 10, 'f' becomes 15
1397
- *
1398
- * Returns -1 if the provided character code was not a valid hexadecimal digit.
1399
- *
1400
- * HexDigit :: one of
1401
- * - `0` `1` `2` `3` `4` `5` `6` `7` `8` `9`
1402
- * - `A` `B` `C` `D` `E` `F`
1403
- * - `a` `b` `c` `d` `e` `f`
1404
- */
1405
-
1406
- function readHexDigit(code) {
1407
- return code >= 0x0030 && code <= 0x0039 // 0-9
1408
- ? code - 0x0030
1409
- : code >= 0x0041 && code <= 0x0046 // A-F
1410
- ? code - 0x0037
1411
- : code >= 0x0061 && code <= 0x0066 // a-f
1412
- ? code - 0x0057
1413
- : -1;
1414
- }
1415
- /**
1416
- * | Escaped Character | Code Point | Character Name |
1417
- * | ----------------- | ---------- | ---------------------------- |
1418
- * | `"` | U+0022 | double quote |
1419
- * | `\` | U+005C | reverse solidus (back slash) |
1420
- * | `/` | U+002F | solidus (forward slash) |
1421
- * | `b` | U+0008 | backspace |
1422
- * | `f` | U+000C | form feed |
1423
- * | `n` | U+000A | line feed (new line) |
1424
- * | `r` | U+000D | carriage return |
1425
- * | `t` | U+0009 | horizontal tab |
1426
- */
1427
-
1428
- function readEscapedCharacter(lexer, position) {
1429
- const body = lexer.source.body;
1430
- const code = body.charCodeAt(position + 1);
1431
-
1432
- switch (code) {
1433
- case 0x0022:
1434
- // "
1435
- return {
1436
- value: '\u0022',
1437
- size: 2,
1438
- };
1439
-
1440
- case 0x005c:
1441
- // \
1442
- return {
1443
- value: '\u005c',
1444
- size: 2,
1445
- };
1446
-
1447
- case 0x002f:
1448
- // /
1449
- return {
1450
- value: '\u002f',
1451
- size: 2,
1452
- };
1453
-
1454
- case 0x0062:
1455
- // b
1456
- return {
1457
- value: '\u0008',
1458
- size: 2,
1459
- };
1460
-
1461
- case 0x0066:
1462
- // f
1463
- return {
1464
- value: '\u000c',
1465
- size: 2,
1466
- };
1467
-
1468
- case 0x006e:
1469
- // n
1470
- return {
1471
- value: '\u000a',
1472
- size: 2,
1473
- };
1474
-
1475
- case 0x0072:
1476
- // r
1477
- return {
1478
- value: '\u000d',
1479
- size: 2,
1480
- };
1481
-
1482
- case 0x0074:
1483
- // t
1484
- return {
1485
- value: '\u0009',
1486
- size: 2,
1487
- };
1488
- }
1489
-
1490
- throw syntaxError(
1491
- lexer.source,
1492
- position,
1493
- `Invalid character escape sequence: "${body.slice(
1494
- position,
1495
- position + 2,
1496
- )}".`,
1497
- );
1498
- }
1499
- /**
1500
- * Reads a block string token from the source file.
1501
- *
1502
- * ```
1503
- * StringValue ::
1504
- * - `"""` BlockStringCharacter* `"""`
1505
- *
1506
- * BlockStringCharacter ::
1507
- * - SourceCharacter but not `"""` or `\"""`
1508
- * - `\"""`
1509
- * ```
1510
- */
1511
-
1512
- function readBlockString(lexer, start) {
1513
- const body = lexer.source.body;
1514
- const bodyLength = body.length;
1515
- let lineStart = lexer.lineStart;
1516
- let position = start + 3;
1517
- let chunkStart = position;
1518
- let currentLine = '';
1519
- const blockLines = [];
1520
-
1521
- while (position < bodyLength) {
1522
- const code = body.charCodeAt(position); // Closing Triple-Quote (""")
1523
-
1524
- if (
1525
- code === 0x0022 &&
1526
- body.charCodeAt(position + 1) === 0x0022 &&
1527
- body.charCodeAt(position + 2) === 0x0022
1528
- ) {
1529
- currentLine += body.slice(chunkStart, position);
1530
- blockLines.push(currentLine);
1531
- const token = createToken(
1532
- lexer,
1533
- TokenKind.BLOCK_STRING,
1534
- start,
1535
- position + 3, // Return a string of the lines joined with U+000A.
1536
- dedentBlockStringLines(blockLines).join('\n'),
1537
- );
1538
- lexer.line += blockLines.length - 1;
1539
- lexer.lineStart = lineStart;
1540
- return token;
1541
- } // Escaped Triple-Quote (\""")
1542
-
1543
- if (
1544
- code === 0x005c &&
1545
- body.charCodeAt(position + 1) === 0x0022 &&
1546
- body.charCodeAt(position + 2) === 0x0022 &&
1547
- body.charCodeAt(position + 3) === 0x0022
1548
- ) {
1549
- currentLine += body.slice(chunkStart, position);
1550
- chunkStart = position + 1; // skip only slash
1551
-
1552
- position += 4;
1553
- continue;
1554
- } // LineTerminator
1555
-
1556
- if (code === 0x000a || code === 0x000d) {
1557
- currentLine += body.slice(chunkStart, position);
1558
- blockLines.push(currentLine);
1559
-
1560
- if (code === 0x000d && body.charCodeAt(position + 1) === 0x000a) {
1561
- position += 2;
1562
- } else {
1563
- ++position;
1564
- }
1565
-
1566
- currentLine = '';
1567
- chunkStart = position;
1568
- lineStart = position;
1569
- continue;
1570
- } // SourceCharacter
1571
-
1572
- if (isUnicodeScalarValue(code)) {
1573
- ++position;
1574
- } else if (isSupplementaryCodePoint(body, position)) {
1575
- position += 2;
1576
- } else {
1577
- throw syntaxError(
1578
- lexer.source,
1579
- position,
1580
- `Invalid character within String: ${printCodePointAt(
1581
- lexer,
1582
- position,
1583
- )}.`,
1584
- );
1585
- }
1586
- }
1587
-
1588
- throw syntaxError(lexer.source, position, 'Unterminated string.');
1589
- }
1590
- /**
1591
- * Reads an alphanumeric + underscore name from the source.
1592
- *
1593
- * ```
1594
- * Name ::
1595
- * - NameStart NameContinue* [lookahead != NameContinue]
1596
- * ```
1597
- */
1598
-
1599
- function readName(lexer, start) {
1600
- const body = lexer.source.body;
1601
- const bodyLength = body.length;
1602
- let position = start + 1;
1603
-
1604
- while (position < bodyLength) {
1605
- const code = body.charCodeAt(position);
1606
-
1607
- if (isNameContinue(code)) {
1608
- ++position;
1609
- } else {
1610
- break;
1611
- }
1612
- }
1613
-
1614
- return createToken(
1615
- lexer,
1616
- TokenKind.NAME,
1617
- start,
1618
- position,
1619
- body.slice(start, position),
1620
- );
1621
- }
1622
-
1623
- const MAX_ARRAY_LENGTH = 10;
1624
- const MAX_RECURSIVE_DEPTH = 2;
1625
- /**
1626
- * Used to print values in error messages.
1627
- */
1628
-
1629
- function inspect(value) {
1630
- return formatValue(value, []);
1631
- }
1632
-
1633
- function formatValue(value, seenValues) {
1634
- switch (typeof value) {
1635
- case 'string':
1636
- return JSON.stringify(value);
1637
-
1638
- case 'function':
1639
- return value.name ? `[function ${value.name}]` : '[function]';
1640
-
1641
- case 'object':
1642
- return formatObjectValue(value, seenValues);
1643
-
1644
- default:
1645
- return String(value);
1646
- }
1647
- }
1648
-
1649
- function formatObjectValue(value, previouslySeenValues) {
1650
- if (value === null) {
1651
- return 'null';
1652
- }
1653
-
1654
- if (previouslySeenValues.includes(value)) {
1655
- return '[Circular]';
1656
- }
1657
-
1658
- const seenValues = [...previouslySeenValues, value];
1659
-
1660
- if (isJSONable(value)) {
1661
- const jsonValue = value.toJSON(); // check for infinite recursion
1662
-
1663
- if (jsonValue !== value) {
1664
- return typeof jsonValue === 'string'
1665
- ? jsonValue
1666
- : formatValue(jsonValue, seenValues);
1667
- }
1668
- } else if (Array.isArray(value)) {
1669
- return formatArray(value, seenValues);
1670
- }
1671
-
1672
- return formatObject(value, seenValues);
1673
- }
1674
-
1675
- function isJSONable(value) {
1676
- return typeof value.toJSON === 'function';
1677
- }
1678
-
1679
- function formatObject(object, seenValues) {
1680
- const entries = Object.entries(object);
1681
-
1682
- if (entries.length === 0) {
1683
- return '{}';
1684
- }
1685
-
1686
- if (seenValues.length > MAX_RECURSIVE_DEPTH) {
1687
- return '[' + getObjectTag(object) + ']';
1688
- }
1689
-
1690
- const properties = entries.map(
1691
- ([key, value]) => key + ': ' + formatValue(value, seenValues),
1692
- );
1693
- return '{ ' + properties.join(', ') + ' }';
1694
- }
1695
-
1696
- function formatArray(array, seenValues) {
1697
- if (array.length === 0) {
1698
- return '[]';
1699
- }
1700
-
1701
- if (seenValues.length > MAX_RECURSIVE_DEPTH) {
1702
- return '[Array]';
1703
- }
1704
-
1705
- const len = Math.min(MAX_ARRAY_LENGTH, array.length);
1706
- const remaining = array.length - len;
1707
- const items = [];
1708
-
1709
- for (let i = 0; i < len; ++i) {
1710
- items.push(formatValue(array[i], seenValues));
1711
- }
1712
-
1713
- if (remaining === 1) {
1714
- items.push('... 1 more item');
1715
- } else if (remaining > 1) {
1716
- items.push(`... ${remaining} more items`);
1717
- }
1718
-
1719
- return '[' + items.join(', ') + ']';
1720
- }
1721
-
1722
- function getObjectTag(object) {
1723
- const tag = Object.prototype.toString
1724
- .call(object)
1725
- .replace(/^\[object /, '')
1726
- .replace(/]$/, '');
1727
-
1728
- if (tag === 'Object' && typeof object.constructor === 'function') {
1729
- const name = object.constructor.name;
1730
-
1731
- if (typeof name === 'string' && name !== '') {
1732
- return name;
1733
- }
1734
- }
1735
-
1736
- return tag;
1737
- }
1738
-
1739
- /**
1740
- * A replacement for instanceof which includes an error warning when multi-realm
1741
- * constructors are detected.
1742
- * See: https://expressjs.com/en/advanced/best-practice-performance.html#set-node_env-to-production
1743
- * See: https://webpack.js.org/guides/production/
1744
- */
1745
-
1746
- const instanceOf =
1747
- /* c8 ignore next 5 */
1748
- // FIXME: https://github.com/graphql/graphql-js/issues/2317
1749
- function instanceOf(value, constructor) {
1750
- if (value instanceof constructor) {
1751
- return true;
1752
- }
1753
-
1754
- if (typeof value === 'object' && value !== null) {
1755
- var _value$constructor;
1756
-
1757
- // Prefer Symbol.toStringTag since it is immune to minification.
1758
- const className = constructor.prototype[Symbol.toStringTag];
1759
- const valueClassName = // We still need to support constructor's name to detect conflicts with older versions of this library.
1760
- Symbol.toStringTag in value // @ts-expect-error TS bug see, https://github.com/microsoft/TypeScript/issues/38009
1761
- ? value[Symbol.toStringTag]
1762
- : (_value$constructor = value.constructor) === null ||
1763
- _value$constructor === void 0
1764
- ? void 0
1765
- : _value$constructor.name;
1766
-
1767
- if (className === valueClassName) {
1768
- const stringifiedValue = inspect(value);
1769
- throw new Error(`Cannot use ${className} "${stringifiedValue}" from another module or realm.
1770
-
1771
- Ensure that there is only one instance of "graphql" in the node_modules
1772
- directory. If different versions of "graphql" are the dependencies of other
1773
- relied on modules, use "resolutions" to ensure only one version is installed.
1774
-
1775
- https://yarnpkg.com/en/docs/selective-version-resolutions
1776
-
1777
- Duplicate "graphql" modules cannot be used at the same time since different
1778
- versions may have different capabilities and behavior. The data from one
1779
- version used in the function from another could produce confusing and
1780
- spurious results.`);
1781
- }
1782
- }
1783
-
1784
- return false;
1785
- };
1786
-
1787
- /**
1788
- * A representation of source input to GraphQL. The `name` and `locationOffset` parameters are
1789
- * optional, but they are useful for clients who store GraphQL documents in source files.
1790
- * For example, if the GraphQL input starts at line 40 in a file named `Foo.graphql`, it might
1791
- * be useful for `name` to be `"Foo.graphql"` and location to be `{ line: 40, column: 1 }`.
1792
- * The `line` and `column` properties in `locationOffset` are 1-indexed.
1793
- */
1794
- class Source {
1795
- constructor(
1796
- body,
1797
- name = 'GraphQL request',
1798
- locationOffset = {
1799
- line: 1,
1800
- column: 1,
1801
- },
1802
- ) {
1803
- typeof body === 'string' ||
1804
- devAssert(false, `Body must be a string. Received: ${inspect(body)}.`);
1805
- this.body = body;
1806
- this.name = name;
1807
- this.locationOffset = locationOffset;
1808
- this.locationOffset.line > 0 ||
1809
- devAssert(
1810
- false,
1811
- 'line in locationOffset is 1-indexed and must be positive.',
1812
- );
1813
- this.locationOffset.column > 0 ||
1814
- devAssert(
1815
- false,
1816
- 'column in locationOffset is 1-indexed and must be positive.',
1817
- );
1818
- }
1819
-
1820
- get [Symbol.toStringTag]() {
1821
- return 'Source';
1822
- }
1823
- }
1824
- /**
1825
- * Test if the given value is a Source object.
1826
- *
1827
- * @internal
1828
- */
1829
-
1830
- function isSource(source) {
1831
- return instanceOf(source, Source);
1832
- }
1833
-
1834
- /**
1835
- * Configuration options to control parser behavior
1836
- */
1837
-
1838
- /**
1839
- * Given a GraphQL source, parses it into a Document.
1840
- * Throws GraphQLError if a syntax error is encountered.
1841
- */
1842
- function parse(source, options) {
1843
- const parser = new Parser(source, options);
1844
- return parser.parseDocument();
1845
- }
1846
- /**
1847
- * This class is exported only to assist people in implementing their own parsers
1848
- * without duplicating too much code and should be used only as last resort for cases
1849
- * such as experimental syntax or if certain features could not be contributed upstream.
1850
- *
1851
- * It is still part of the internal API and is versioned, so any changes to it are never
1852
- * considered breaking changes. If you still need to support multiple versions of the
1853
- * library, please use the `versionInfo` variable for version detection.
1854
- *
1855
- * @internal
1856
- */
1857
-
1858
- class Parser {
1859
- constructor(source, options) {
1860
- const sourceObj = isSource(source) ? source : new Source(source);
1861
- this._lexer = new Lexer(sourceObj);
1862
- this._options = options;
1863
- }
1864
- /**
1865
- * Converts a name lex token into a name parse node.
1866
- */
1867
-
1868
- parseName() {
1869
- const token = this.expectToken(TokenKind.NAME);
1870
- return this.node(token, {
1871
- kind: Kind.NAME,
1872
- value: token.value,
1873
- });
1874
- } // Implements the parsing rules in the Document section.
1875
-
1876
- /**
1877
- * Document : Definition+
1878
- */
1879
-
1880
- parseDocument() {
1881
- return this.node(this._lexer.token, {
1882
- kind: Kind.DOCUMENT,
1883
- definitions: this.many(
1884
- TokenKind.SOF,
1885
- this.parseDefinition,
1886
- TokenKind.EOF,
1887
- ),
1888
- });
1889
- }
1890
- /**
1891
- * Definition :
1892
- * - ExecutableDefinition
1893
- * - TypeSystemDefinition
1894
- * - TypeSystemExtension
1895
- *
1896
- * ExecutableDefinition :
1897
- * - OperationDefinition
1898
- * - FragmentDefinition
1899
- *
1900
- * TypeSystemDefinition :
1901
- * - SchemaDefinition
1902
- * - TypeDefinition
1903
- * - DirectiveDefinition
1904
- *
1905
- * TypeDefinition :
1906
- * - ScalarTypeDefinition
1907
- * - ObjectTypeDefinition
1908
- * - InterfaceTypeDefinition
1909
- * - UnionTypeDefinition
1910
- * - EnumTypeDefinition
1911
- * - InputObjectTypeDefinition
1912
- */
1913
-
1914
- parseDefinition() {
1915
- if (this.peek(TokenKind.BRACE_L)) {
1916
- return this.parseOperationDefinition();
1917
- } // Many definitions begin with a description and require a lookahead.
1918
-
1919
- const hasDescription = this.peekDescription();
1920
- const keywordToken = hasDescription
1921
- ? this._lexer.lookahead()
1922
- : this._lexer.token;
1923
-
1924
- if (keywordToken.kind === TokenKind.NAME) {
1925
- switch (keywordToken.value) {
1926
- case 'schema':
1927
- return this.parseSchemaDefinition();
1928
-
1929
- case 'scalar':
1930
- return this.parseScalarTypeDefinition();
1931
-
1932
- case 'type':
1933
- return this.parseObjectTypeDefinition();
1934
-
1935
- case 'interface':
1936
- return this.parseInterfaceTypeDefinition();
1937
-
1938
- case 'union':
1939
- return this.parseUnionTypeDefinition();
1940
-
1941
- case 'enum':
1942
- return this.parseEnumTypeDefinition();
1943
-
1944
- case 'input':
1945
- return this.parseInputObjectTypeDefinition();
1946
-
1947
- case 'directive':
1948
- return this.parseDirectiveDefinition();
1949
- }
1950
-
1951
- if (hasDescription) {
1952
- throw syntaxError(
1953
- this._lexer.source,
1954
- this._lexer.token.start,
1955
- 'Unexpected description, descriptions are supported only on type definitions.',
1956
- );
1957
- }
1958
-
1959
- switch (keywordToken.value) {
1960
- case 'query':
1961
- case 'mutation':
1962
- case 'subscription':
1963
- return this.parseOperationDefinition();
1964
-
1965
- case 'fragment':
1966
- return this.parseFragmentDefinition();
1967
-
1968
- case 'extend':
1969
- return this.parseTypeSystemExtension();
1970
- }
1971
- }
1972
-
1973
- throw this.unexpected(keywordToken);
1974
- } // Implements the parsing rules in the Operations section.
1975
-
1976
- /**
1977
- * OperationDefinition :
1978
- * - SelectionSet
1979
- * - OperationType Name? VariableDefinitions? Directives? SelectionSet
1980
- */
1981
-
1982
- parseOperationDefinition() {
1983
- const start = this._lexer.token;
1984
-
1985
- if (this.peek(TokenKind.BRACE_L)) {
1986
- return this.node(start, {
1987
- kind: Kind.OPERATION_DEFINITION,
1988
- operation: OperationTypeNode.QUERY,
1989
- name: undefined,
1990
- variableDefinitions: [],
1991
- directives: [],
1992
- selectionSet: this.parseSelectionSet(),
1993
- });
1994
- }
1995
-
1996
- const operation = this.parseOperationType();
1997
- let name;
1998
-
1999
- if (this.peek(TokenKind.NAME)) {
2000
- name = this.parseName();
2001
- }
2002
-
2003
- return this.node(start, {
2004
- kind: Kind.OPERATION_DEFINITION,
2005
- operation,
2006
- name,
2007
- variableDefinitions: this.parseVariableDefinitions(),
2008
- directives: this.parseDirectives(false),
2009
- selectionSet: this.parseSelectionSet(),
2010
- });
2011
- }
2012
- /**
2013
- * OperationType : one of query mutation subscription
2014
- */
2015
-
2016
- parseOperationType() {
2017
- const operationToken = this.expectToken(TokenKind.NAME);
2018
-
2019
- switch (operationToken.value) {
2020
- case 'query':
2021
- return OperationTypeNode.QUERY;
2022
-
2023
- case 'mutation':
2024
- return OperationTypeNode.MUTATION;
2025
-
2026
- case 'subscription':
2027
- return OperationTypeNode.SUBSCRIPTION;
2028
- }
2029
-
2030
- throw this.unexpected(operationToken);
2031
- }
2032
- /**
2033
- * VariableDefinitions : ( VariableDefinition+ )
2034
- */
2035
-
2036
- parseVariableDefinitions() {
2037
- return this.optionalMany(
2038
- TokenKind.PAREN_L,
2039
- this.parseVariableDefinition,
2040
- TokenKind.PAREN_R,
2041
- );
2042
- }
2043
- /**
2044
- * VariableDefinition : Variable : Type DefaultValue? Directives[Const]?
2045
- */
2046
-
2047
- parseVariableDefinition() {
2048
- return this.node(this._lexer.token, {
2049
- kind: Kind.VARIABLE_DEFINITION,
2050
- variable: this.parseVariable(),
2051
- type: (this.expectToken(TokenKind.COLON), this.parseTypeReference()),
2052
- defaultValue: this.expectOptionalToken(TokenKind.EQUALS)
2053
- ? this.parseConstValueLiteral()
2054
- : undefined,
2055
- directives: this.parseConstDirectives(),
2056
- });
2057
- }
2058
- /**
2059
- * Variable : $ Name
2060
- */
2061
-
2062
- parseVariable() {
2063
- const start = this._lexer.token;
2064
- this.expectToken(TokenKind.DOLLAR);
2065
- return this.node(start, {
2066
- kind: Kind.VARIABLE,
2067
- name: this.parseName(),
2068
- });
2069
- }
2070
- /**
2071
- * ```
2072
- * SelectionSet : { Selection+ }
2073
- * ```
2074
- */
2075
-
2076
- parseSelectionSet() {
2077
- return this.node(this._lexer.token, {
2078
- kind: Kind.SELECTION_SET,
2079
- selections: this.many(
2080
- TokenKind.BRACE_L,
2081
- this.parseSelection,
2082
- TokenKind.BRACE_R,
2083
- ),
2084
- });
2085
- }
2086
- /**
2087
- * Selection :
2088
- * - Field
2089
- * - FragmentSpread
2090
- * - InlineFragment
2091
- */
2092
-
2093
- parseSelection() {
2094
- return this.peek(TokenKind.SPREAD)
2095
- ? this.parseFragment()
2096
- : this.parseField();
2097
- }
2098
- /**
2099
- * Field : Alias? Name Arguments? Directives? SelectionSet?
2100
- *
2101
- * Alias : Name :
2102
- */
2103
-
2104
- parseField() {
2105
- const start = this._lexer.token;
2106
- const nameOrAlias = this.parseName();
2107
- let alias;
2108
- let name;
2109
-
2110
- if (this.expectOptionalToken(TokenKind.COLON)) {
2111
- alias = nameOrAlias;
2112
- name = this.parseName();
2113
- } else {
2114
- name = nameOrAlias;
2115
- }
2116
-
2117
- return this.node(start, {
2118
- kind: Kind.FIELD,
2119
- alias,
2120
- name,
2121
- arguments: this.parseArguments(false),
2122
- directives: this.parseDirectives(false),
2123
- selectionSet: this.peek(TokenKind.BRACE_L)
2124
- ? this.parseSelectionSet()
2125
- : undefined,
2126
- });
2127
- }
2128
- /**
2129
- * Arguments[Const] : ( Argument[?Const]+ )
2130
- */
2131
-
2132
- parseArguments(isConst) {
2133
- const item = isConst ? this.parseConstArgument : this.parseArgument;
2134
- return this.optionalMany(TokenKind.PAREN_L, item, TokenKind.PAREN_R);
2135
- }
2136
- /**
2137
- * Argument[Const] : Name : Value[?Const]
2138
- */
2139
-
2140
- parseArgument(isConst = false) {
2141
- const start = this._lexer.token;
2142
- const name = this.parseName();
2143
- this.expectToken(TokenKind.COLON);
2144
- return this.node(start, {
2145
- kind: Kind.ARGUMENT,
2146
- name,
2147
- value: this.parseValueLiteral(isConst),
2148
- });
2149
- }
2150
-
2151
- parseConstArgument() {
2152
- return this.parseArgument(true);
2153
- } // Implements the parsing rules in the Fragments section.
2154
-
2155
- /**
2156
- * Corresponds to both FragmentSpread and InlineFragment in the spec.
2157
- *
2158
- * FragmentSpread : ... FragmentName Directives?
2159
- *
2160
- * InlineFragment : ... TypeCondition? Directives? SelectionSet
2161
- */
2162
-
2163
- parseFragment() {
2164
- const start = this._lexer.token;
2165
- this.expectToken(TokenKind.SPREAD);
2166
- const hasTypeCondition = this.expectOptionalKeyword('on');
2167
-
2168
- if (!hasTypeCondition && this.peek(TokenKind.NAME)) {
2169
- return this.node(start, {
2170
- kind: Kind.FRAGMENT_SPREAD,
2171
- name: this.parseFragmentName(),
2172
- directives: this.parseDirectives(false),
2173
- });
2174
- }
2175
-
2176
- return this.node(start, {
2177
- kind: Kind.INLINE_FRAGMENT,
2178
- typeCondition: hasTypeCondition ? this.parseNamedType() : undefined,
2179
- directives: this.parseDirectives(false),
2180
- selectionSet: this.parseSelectionSet(),
2181
- });
2182
- }
2183
- /**
2184
- * FragmentDefinition :
2185
- * - fragment FragmentName on TypeCondition Directives? SelectionSet
2186
- *
2187
- * TypeCondition : NamedType
2188
- */
2189
-
2190
- parseFragmentDefinition() {
2191
- var _this$_options;
2192
-
2193
- const start = this._lexer.token;
2194
- this.expectKeyword('fragment'); // Legacy support for defining variables within fragments changes
2195
- // the grammar of FragmentDefinition:
2196
- // - fragment FragmentName VariableDefinitions? on TypeCondition Directives? SelectionSet
2197
-
2198
- if (
2199
- ((_this$_options = this._options) === null || _this$_options === void 0
2200
- ? void 0
2201
- : _this$_options.allowLegacyFragmentVariables) === true
2202
- ) {
2203
- return this.node(start, {
2204
- kind: Kind.FRAGMENT_DEFINITION,
2205
- name: this.parseFragmentName(),
2206
- variableDefinitions: this.parseVariableDefinitions(),
2207
- typeCondition: (this.expectKeyword('on'), this.parseNamedType()),
2208
- directives: this.parseDirectives(false),
2209
- selectionSet: this.parseSelectionSet(),
2210
- });
2211
- }
2212
-
2213
- return this.node(start, {
2214
- kind: Kind.FRAGMENT_DEFINITION,
2215
- name: this.parseFragmentName(),
2216
- typeCondition: (this.expectKeyword('on'), this.parseNamedType()),
2217
- directives: this.parseDirectives(false),
2218
- selectionSet: this.parseSelectionSet(),
2219
- });
2220
- }
2221
- /**
2222
- * FragmentName : Name but not `on`
2223
- */
2224
-
2225
- parseFragmentName() {
2226
- if (this._lexer.token.value === 'on') {
2227
- throw this.unexpected();
2228
- }
2229
-
2230
- return this.parseName();
2231
- } // Implements the parsing rules in the Values section.
2232
-
2233
- /**
2234
- * Value[Const] :
2235
- * - [~Const] Variable
2236
- * - IntValue
2237
- * - FloatValue
2238
- * - StringValue
2239
- * - BooleanValue
2240
- * - NullValue
2241
- * - EnumValue
2242
- * - ListValue[?Const]
2243
- * - ObjectValue[?Const]
2244
- *
2245
- * BooleanValue : one of `true` `false`
2246
- *
2247
- * NullValue : `null`
2248
- *
2249
- * EnumValue : Name but not `true`, `false` or `null`
2250
- */
2251
-
2252
- parseValueLiteral(isConst) {
2253
- const token = this._lexer.token;
2254
-
2255
- switch (token.kind) {
2256
- case TokenKind.BRACKET_L:
2257
- return this.parseList(isConst);
2258
-
2259
- case TokenKind.BRACE_L:
2260
- return this.parseObject(isConst);
2261
-
2262
- case TokenKind.INT:
2263
- this._lexer.advance();
2264
-
2265
- return this.node(token, {
2266
- kind: Kind.INT,
2267
- value: token.value,
2268
- });
2269
-
2270
- case TokenKind.FLOAT:
2271
- this._lexer.advance();
2272
-
2273
- return this.node(token, {
2274
- kind: Kind.FLOAT,
2275
- value: token.value,
2276
- });
2277
-
2278
- case TokenKind.STRING:
2279
- case TokenKind.BLOCK_STRING:
2280
- return this.parseStringLiteral();
2281
-
2282
- case TokenKind.NAME:
2283
- this._lexer.advance();
2284
-
2285
- switch (token.value) {
2286
- case 'true':
2287
- return this.node(token, {
2288
- kind: Kind.BOOLEAN,
2289
- value: true,
2290
- });
2291
-
2292
- case 'false':
2293
- return this.node(token, {
2294
- kind: Kind.BOOLEAN,
2295
- value: false,
2296
- });
2297
-
2298
- case 'null':
2299
- return this.node(token, {
2300
- kind: Kind.NULL,
2301
- });
2302
-
2303
- default:
2304
- return this.node(token, {
2305
- kind: Kind.ENUM,
2306
- value: token.value,
2307
- });
2308
- }
2309
-
2310
- case TokenKind.DOLLAR:
2311
- if (isConst) {
2312
- this.expectToken(TokenKind.DOLLAR);
2313
-
2314
- if (this._lexer.token.kind === TokenKind.NAME) {
2315
- const varName = this._lexer.token.value;
2316
- throw syntaxError(
2317
- this._lexer.source,
2318
- token.start,
2319
- `Unexpected variable "$${varName}" in constant value.`,
2320
- );
2321
- } else {
2322
- throw this.unexpected(token);
2323
- }
2324
- }
2325
-
2326
- return this.parseVariable();
2327
-
2328
- default:
2329
- throw this.unexpected();
2330
- }
2331
- }
2332
-
2333
- parseConstValueLiteral() {
2334
- return this.parseValueLiteral(true);
2335
- }
2336
-
2337
- parseStringLiteral() {
2338
- const token = this._lexer.token;
2339
-
2340
- this._lexer.advance();
2341
-
2342
- return this.node(token, {
2343
- kind: Kind.STRING,
2344
- value: token.value,
2345
- block: token.kind === TokenKind.BLOCK_STRING,
2346
- });
2347
- }
2348
- /**
2349
- * ListValue[Const] :
2350
- * - [ ]
2351
- * - [ Value[?Const]+ ]
2352
- */
2353
-
2354
- parseList(isConst) {
2355
- const item = () => this.parseValueLiteral(isConst);
2356
-
2357
- return this.node(this._lexer.token, {
2358
- kind: Kind.LIST,
2359
- values: this.any(TokenKind.BRACKET_L, item, TokenKind.BRACKET_R),
2360
- });
2361
- }
2362
- /**
2363
- * ```
2364
- * ObjectValue[Const] :
2365
- * - { }
2366
- * - { ObjectField[?Const]+ }
2367
- * ```
2368
- */
2369
-
2370
- parseObject(isConst) {
2371
- const item = () => this.parseObjectField(isConst);
2372
-
2373
- return this.node(this._lexer.token, {
2374
- kind: Kind.OBJECT,
2375
- fields: this.any(TokenKind.BRACE_L, item, TokenKind.BRACE_R),
2376
- });
2377
- }
2378
- /**
2379
- * ObjectField[Const] : Name : Value[?Const]
2380
- */
2381
-
2382
- parseObjectField(isConst) {
2383
- const start = this._lexer.token;
2384
- const name = this.parseName();
2385
- this.expectToken(TokenKind.COLON);
2386
- return this.node(start, {
2387
- kind: Kind.OBJECT_FIELD,
2388
- name,
2389
- value: this.parseValueLiteral(isConst),
2390
- });
2391
- } // Implements the parsing rules in the Directives section.
2392
-
2393
- /**
2394
- * Directives[Const] : Directive[?Const]+
2395
- */
2396
-
2397
- parseDirectives(isConst) {
2398
- const directives = [];
2399
-
2400
- while (this.peek(TokenKind.AT)) {
2401
- directives.push(this.parseDirective(isConst));
2402
- }
2403
-
2404
- return directives;
2405
- }
2406
-
2407
- parseConstDirectives() {
2408
- return this.parseDirectives(true);
2409
- }
2410
- /**
2411
- * ```
2412
- * Directive[Const] : @ Name Arguments[?Const]?
2413
- * ```
2414
- */
2415
-
2416
- parseDirective(isConst) {
2417
- const start = this._lexer.token;
2418
- this.expectToken(TokenKind.AT);
2419
- return this.node(start, {
2420
- kind: Kind.DIRECTIVE,
2421
- name: this.parseName(),
2422
- arguments: this.parseArguments(isConst),
2423
- });
2424
- } // Implements the parsing rules in the Types section.
2425
-
2426
- /**
2427
- * Type :
2428
- * - NamedType
2429
- * - ListType
2430
- * - NonNullType
2431
- */
2432
-
2433
- parseTypeReference() {
2434
- const start = this._lexer.token;
2435
- let type;
2436
-
2437
- if (this.expectOptionalToken(TokenKind.BRACKET_L)) {
2438
- const innerType = this.parseTypeReference();
2439
- this.expectToken(TokenKind.BRACKET_R);
2440
- type = this.node(start, {
2441
- kind: Kind.LIST_TYPE,
2442
- type: innerType,
2443
- });
2444
- } else {
2445
- type = this.parseNamedType();
2446
- }
2447
-
2448
- if (this.expectOptionalToken(TokenKind.BANG)) {
2449
- return this.node(start, {
2450
- kind: Kind.NON_NULL_TYPE,
2451
- type,
2452
- });
2453
- }
2454
-
2455
- return type;
2456
- }
2457
- /**
2458
- * NamedType : Name
2459
- */
2460
-
2461
- parseNamedType() {
2462
- return this.node(this._lexer.token, {
2463
- kind: Kind.NAMED_TYPE,
2464
- name: this.parseName(),
2465
- });
2466
- } // Implements the parsing rules in the Type Definition section.
2467
-
2468
- peekDescription() {
2469
- return this.peek(TokenKind.STRING) || this.peek(TokenKind.BLOCK_STRING);
2470
- }
2471
- /**
2472
- * Description : StringValue
2473
- */
2474
-
2475
- parseDescription() {
2476
- if (this.peekDescription()) {
2477
- return this.parseStringLiteral();
2478
- }
2479
- }
2480
- /**
2481
- * ```
2482
- * SchemaDefinition : Description? schema Directives[Const]? { OperationTypeDefinition+ }
2483
- * ```
2484
- */
2485
-
2486
- parseSchemaDefinition() {
2487
- const start = this._lexer.token;
2488
- const description = this.parseDescription();
2489
- this.expectKeyword('schema');
2490
- const directives = this.parseConstDirectives();
2491
- const operationTypes = this.many(
2492
- TokenKind.BRACE_L,
2493
- this.parseOperationTypeDefinition,
2494
- TokenKind.BRACE_R,
2495
- );
2496
- return this.node(start, {
2497
- kind: Kind.SCHEMA_DEFINITION,
2498
- description,
2499
- directives,
2500
- operationTypes,
2501
- });
2502
- }
2503
- /**
2504
- * OperationTypeDefinition : OperationType : NamedType
2505
- */
2506
-
2507
- parseOperationTypeDefinition() {
2508
- const start = this._lexer.token;
2509
- const operation = this.parseOperationType();
2510
- this.expectToken(TokenKind.COLON);
2511
- const type = this.parseNamedType();
2512
- return this.node(start, {
2513
- kind: Kind.OPERATION_TYPE_DEFINITION,
2514
- operation,
2515
- type,
2516
- });
2517
- }
2518
- /**
2519
- * ScalarTypeDefinition : Description? scalar Name Directives[Const]?
2520
- */
2521
-
2522
- parseScalarTypeDefinition() {
2523
- const start = this._lexer.token;
2524
- const description = this.parseDescription();
2525
- this.expectKeyword('scalar');
2526
- const name = this.parseName();
2527
- const directives = this.parseConstDirectives();
2528
- return this.node(start, {
2529
- kind: Kind.SCALAR_TYPE_DEFINITION,
2530
- description,
2531
- name,
2532
- directives,
2533
- });
2534
- }
2535
- /**
2536
- * ObjectTypeDefinition :
2537
- * Description?
2538
- * type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition?
2539
- */
2540
-
2541
- parseObjectTypeDefinition() {
2542
- const start = this._lexer.token;
2543
- const description = this.parseDescription();
2544
- this.expectKeyword('type');
2545
- const name = this.parseName();
2546
- const interfaces = this.parseImplementsInterfaces();
2547
- const directives = this.parseConstDirectives();
2548
- const fields = this.parseFieldsDefinition();
2549
- return this.node(start, {
2550
- kind: Kind.OBJECT_TYPE_DEFINITION,
2551
- description,
2552
- name,
2553
- interfaces,
2554
- directives,
2555
- fields,
2556
- });
2557
- }
2558
- /**
2559
- * ImplementsInterfaces :
2560
- * - implements `&`? NamedType
2561
- * - ImplementsInterfaces & NamedType
2562
- */
2563
-
2564
- parseImplementsInterfaces() {
2565
- return this.expectOptionalKeyword('implements')
2566
- ? this.delimitedMany(TokenKind.AMP, this.parseNamedType)
2567
- : [];
2568
- }
2569
- /**
2570
- * ```
2571
- * FieldsDefinition : { FieldDefinition+ }
2572
- * ```
2573
- */
2574
-
2575
- parseFieldsDefinition() {
2576
- return this.optionalMany(
2577
- TokenKind.BRACE_L,
2578
- this.parseFieldDefinition,
2579
- TokenKind.BRACE_R,
2580
- );
2581
- }
2582
- /**
2583
- * FieldDefinition :
2584
- * - Description? Name ArgumentsDefinition? : Type Directives[Const]?
2585
- */
2586
-
2587
- parseFieldDefinition() {
2588
- const start = this._lexer.token;
2589
- const description = this.parseDescription();
2590
- const name = this.parseName();
2591
- const args = this.parseArgumentDefs();
2592
- this.expectToken(TokenKind.COLON);
2593
- const type = this.parseTypeReference();
2594
- const directives = this.parseConstDirectives();
2595
- return this.node(start, {
2596
- kind: Kind.FIELD_DEFINITION,
2597
- description,
2598
- name,
2599
- arguments: args,
2600
- type,
2601
- directives,
2602
- });
2603
- }
2604
- /**
2605
- * ArgumentsDefinition : ( InputValueDefinition+ )
2606
- */
2607
-
2608
- parseArgumentDefs() {
2609
- return this.optionalMany(
2610
- TokenKind.PAREN_L,
2611
- this.parseInputValueDef,
2612
- TokenKind.PAREN_R,
2613
- );
2614
- }
2615
- /**
2616
- * InputValueDefinition :
2617
- * - Description? Name : Type DefaultValue? Directives[Const]?
2618
- */
2619
-
2620
- parseInputValueDef() {
2621
- const start = this._lexer.token;
2622
- const description = this.parseDescription();
2623
- const name = this.parseName();
2624
- this.expectToken(TokenKind.COLON);
2625
- const type = this.parseTypeReference();
2626
- let defaultValue;
2627
-
2628
- if (this.expectOptionalToken(TokenKind.EQUALS)) {
2629
- defaultValue = this.parseConstValueLiteral();
2630
- }
2631
-
2632
- const directives = this.parseConstDirectives();
2633
- return this.node(start, {
2634
- kind: Kind.INPUT_VALUE_DEFINITION,
2635
- description,
2636
- name,
2637
- type,
2638
- defaultValue,
2639
- directives,
2640
- });
2641
- }
2642
- /**
2643
- * InterfaceTypeDefinition :
2644
- * - Description? interface Name Directives[Const]? FieldsDefinition?
2645
- */
2646
-
2647
- parseInterfaceTypeDefinition() {
2648
- const start = this._lexer.token;
2649
- const description = this.parseDescription();
2650
- this.expectKeyword('interface');
2651
- const name = this.parseName();
2652
- const interfaces = this.parseImplementsInterfaces();
2653
- const directives = this.parseConstDirectives();
2654
- const fields = this.parseFieldsDefinition();
2655
- return this.node(start, {
2656
- kind: Kind.INTERFACE_TYPE_DEFINITION,
2657
- description,
2658
- name,
2659
- interfaces,
2660
- directives,
2661
- fields,
2662
- });
2663
- }
2664
- /**
2665
- * UnionTypeDefinition :
2666
- * - Description? union Name Directives[Const]? UnionMemberTypes?
2667
- */
2668
-
2669
- parseUnionTypeDefinition() {
2670
- const start = this._lexer.token;
2671
- const description = this.parseDescription();
2672
- this.expectKeyword('union');
2673
- const name = this.parseName();
2674
- const directives = this.parseConstDirectives();
2675
- const types = this.parseUnionMemberTypes();
2676
- return this.node(start, {
2677
- kind: Kind.UNION_TYPE_DEFINITION,
2678
- description,
2679
- name,
2680
- directives,
2681
- types,
2682
- });
2683
- }
2684
- /**
2685
- * UnionMemberTypes :
2686
- * - = `|`? NamedType
2687
- * - UnionMemberTypes | NamedType
2688
- */
2689
-
2690
- parseUnionMemberTypes() {
2691
- return this.expectOptionalToken(TokenKind.EQUALS)
2692
- ? this.delimitedMany(TokenKind.PIPE, this.parseNamedType)
2693
- : [];
2694
- }
2695
- /**
2696
- * EnumTypeDefinition :
2697
- * - Description? enum Name Directives[Const]? EnumValuesDefinition?
2698
- */
2699
-
2700
- parseEnumTypeDefinition() {
2701
- const start = this._lexer.token;
2702
- const description = this.parseDescription();
2703
- this.expectKeyword('enum');
2704
- const name = this.parseName();
2705
- const directives = this.parseConstDirectives();
2706
- const values = this.parseEnumValuesDefinition();
2707
- return this.node(start, {
2708
- kind: Kind.ENUM_TYPE_DEFINITION,
2709
- description,
2710
- name,
2711
- directives,
2712
- values,
2713
- });
2714
- }
2715
- /**
2716
- * ```
2717
- * EnumValuesDefinition : { EnumValueDefinition+ }
2718
- * ```
2719
- */
2720
-
2721
- parseEnumValuesDefinition() {
2722
- return this.optionalMany(
2723
- TokenKind.BRACE_L,
2724
- this.parseEnumValueDefinition,
2725
- TokenKind.BRACE_R,
2726
- );
2727
- }
2728
- /**
2729
- * EnumValueDefinition : Description? EnumValue Directives[Const]?
2730
- */
2731
-
2732
- parseEnumValueDefinition() {
2733
- const start = this._lexer.token;
2734
- const description = this.parseDescription();
2735
- const name = this.parseEnumValueName();
2736
- const directives = this.parseConstDirectives();
2737
- return this.node(start, {
2738
- kind: Kind.ENUM_VALUE_DEFINITION,
2739
- description,
2740
- name,
2741
- directives,
2742
- });
2743
- }
2744
- /**
2745
- * EnumValue : Name but not `true`, `false` or `null`
2746
- */
2747
-
2748
- parseEnumValueName() {
2749
- if (
2750
- this._lexer.token.value === 'true' ||
2751
- this._lexer.token.value === 'false' ||
2752
- this._lexer.token.value === 'null'
2753
- ) {
2754
- throw syntaxError(
2755
- this._lexer.source,
2756
- this._lexer.token.start,
2757
- `${getTokenDesc(
2758
- this._lexer.token,
2759
- )} is reserved and cannot be used for an enum value.`,
2760
- );
2761
- }
2762
-
2763
- return this.parseName();
2764
- }
2765
- /**
2766
- * InputObjectTypeDefinition :
2767
- * - Description? input Name Directives[Const]? InputFieldsDefinition?
2768
- */
2769
-
2770
- parseInputObjectTypeDefinition() {
2771
- const start = this._lexer.token;
2772
- const description = this.parseDescription();
2773
- this.expectKeyword('input');
2774
- const name = this.parseName();
2775
- const directives = this.parseConstDirectives();
2776
- const fields = this.parseInputFieldsDefinition();
2777
- return this.node(start, {
2778
- kind: Kind.INPUT_OBJECT_TYPE_DEFINITION,
2779
- description,
2780
- name,
2781
- directives,
2782
- fields,
2783
- });
2784
- }
2785
- /**
2786
- * ```
2787
- * InputFieldsDefinition : { InputValueDefinition+ }
2788
- * ```
2789
- */
2790
-
2791
- parseInputFieldsDefinition() {
2792
- return this.optionalMany(
2793
- TokenKind.BRACE_L,
2794
- this.parseInputValueDef,
2795
- TokenKind.BRACE_R,
2796
- );
2797
- }
2798
- /**
2799
- * TypeSystemExtension :
2800
- * - SchemaExtension
2801
- * - TypeExtension
2802
- *
2803
- * TypeExtension :
2804
- * - ScalarTypeExtension
2805
- * - ObjectTypeExtension
2806
- * - InterfaceTypeExtension
2807
- * - UnionTypeExtension
2808
- * - EnumTypeExtension
2809
- * - InputObjectTypeDefinition
2810
- */
2811
-
2812
- parseTypeSystemExtension() {
2813
- const keywordToken = this._lexer.lookahead();
2814
-
2815
- if (keywordToken.kind === TokenKind.NAME) {
2816
- switch (keywordToken.value) {
2817
- case 'schema':
2818
- return this.parseSchemaExtension();
2819
-
2820
- case 'scalar':
2821
- return this.parseScalarTypeExtension();
2822
-
2823
- case 'type':
2824
- return this.parseObjectTypeExtension();
2825
-
2826
- case 'interface':
2827
- return this.parseInterfaceTypeExtension();
2828
-
2829
- case 'union':
2830
- return this.parseUnionTypeExtension();
2831
-
2832
- case 'enum':
2833
- return this.parseEnumTypeExtension();
2834
-
2835
- case 'input':
2836
- return this.parseInputObjectTypeExtension();
2837
- }
2838
- }
2839
-
2840
- throw this.unexpected(keywordToken);
2841
- }
2842
- /**
2843
- * ```
2844
- * SchemaExtension :
2845
- * - extend schema Directives[Const]? { OperationTypeDefinition+ }
2846
- * - extend schema Directives[Const]
2847
- * ```
2848
- */
2849
-
2850
- parseSchemaExtension() {
2851
- const start = this._lexer.token;
2852
- this.expectKeyword('extend');
2853
- this.expectKeyword('schema');
2854
- const directives = this.parseConstDirectives();
2855
- const operationTypes = this.optionalMany(
2856
- TokenKind.BRACE_L,
2857
- this.parseOperationTypeDefinition,
2858
- TokenKind.BRACE_R,
2859
- );
2860
-
2861
- if (directives.length === 0 && operationTypes.length === 0) {
2862
- throw this.unexpected();
2863
- }
2864
-
2865
- return this.node(start, {
2866
- kind: Kind.SCHEMA_EXTENSION,
2867
- directives,
2868
- operationTypes,
2869
- });
2870
- }
2871
- /**
2872
- * ScalarTypeExtension :
2873
- * - extend scalar Name Directives[Const]
2874
- */
2875
-
2876
- parseScalarTypeExtension() {
2877
- const start = this._lexer.token;
2878
- this.expectKeyword('extend');
2879
- this.expectKeyword('scalar');
2880
- const name = this.parseName();
2881
- const directives = this.parseConstDirectives();
2882
-
2883
- if (directives.length === 0) {
2884
- throw this.unexpected();
2885
- }
2886
-
2887
- return this.node(start, {
2888
- kind: Kind.SCALAR_TYPE_EXTENSION,
2889
- name,
2890
- directives,
2891
- });
2892
- }
2893
- /**
2894
- * ObjectTypeExtension :
2895
- * - extend type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition
2896
- * - extend type Name ImplementsInterfaces? Directives[Const]
2897
- * - extend type Name ImplementsInterfaces
2898
- */
2899
-
2900
- parseObjectTypeExtension() {
2901
- const start = this._lexer.token;
2902
- this.expectKeyword('extend');
2903
- this.expectKeyword('type');
2904
- const name = this.parseName();
2905
- const interfaces = this.parseImplementsInterfaces();
2906
- const directives = this.parseConstDirectives();
2907
- const fields = this.parseFieldsDefinition();
2908
-
2909
- if (
2910
- interfaces.length === 0 &&
2911
- directives.length === 0 &&
2912
- fields.length === 0
2913
- ) {
2914
- throw this.unexpected();
2915
- }
2916
-
2917
- return this.node(start, {
2918
- kind: Kind.OBJECT_TYPE_EXTENSION,
2919
- name,
2920
- interfaces,
2921
- directives,
2922
- fields,
2923
- });
2924
- }
2925
- /**
2926
- * InterfaceTypeExtension :
2927
- * - extend interface Name ImplementsInterfaces? Directives[Const]? FieldsDefinition
2928
- * - extend interface Name ImplementsInterfaces? Directives[Const]
2929
- * - extend interface Name ImplementsInterfaces
2930
- */
2931
-
2932
- parseInterfaceTypeExtension() {
2933
- const start = this._lexer.token;
2934
- this.expectKeyword('extend');
2935
- this.expectKeyword('interface');
2936
- const name = this.parseName();
2937
- const interfaces = this.parseImplementsInterfaces();
2938
- const directives = this.parseConstDirectives();
2939
- const fields = this.parseFieldsDefinition();
2940
-
2941
- if (
2942
- interfaces.length === 0 &&
2943
- directives.length === 0 &&
2944
- fields.length === 0
2945
- ) {
2946
- throw this.unexpected();
2947
- }
2948
-
2949
- return this.node(start, {
2950
- kind: Kind.INTERFACE_TYPE_EXTENSION,
2951
- name,
2952
- interfaces,
2953
- directives,
2954
- fields,
2955
- });
2956
- }
2957
- /**
2958
- * UnionTypeExtension :
2959
- * - extend union Name Directives[Const]? UnionMemberTypes
2960
- * - extend union Name Directives[Const]
2961
- */
2962
-
2963
- parseUnionTypeExtension() {
2964
- const start = this._lexer.token;
2965
- this.expectKeyword('extend');
2966
- this.expectKeyword('union');
2967
- const name = this.parseName();
2968
- const directives = this.parseConstDirectives();
2969
- const types = this.parseUnionMemberTypes();
2970
-
2971
- if (directives.length === 0 && types.length === 0) {
2972
- throw this.unexpected();
2973
- }
2974
-
2975
- return this.node(start, {
2976
- kind: Kind.UNION_TYPE_EXTENSION,
2977
- name,
2978
- directives,
2979
- types,
2980
- });
2981
- }
2982
- /**
2983
- * EnumTypeExtension :
2984
- * - extend enum Name Directives[Const]? EnumValuesDefinition
2985
- * - extend enum Name Directives[Const]
2986
- */
2987
-
2988
- parseEnumTypeExtension() {
2989
- const start = this._lexer.token;
2990
- this.expectKeyword('extend');
2991
- this.expectKeyword('enum');
2992
- const name = this.parseName();
2993
- const directives = this.parseConstDirectives();
2994
- const values = this.parseEnumValuesDefinition();
2995
-
2996
- if (directives.length === 0 && values.length === 0) {
2997
- throw this.unexpected();
2998
- }
2999
-
3000
- return this.node(start, {
3001
- kind: Kind.ENUM_TYPE_EXTENSION,
3002
- name,
3003
- directives,
3004
- values,
3005
- });
3006
- }
3007
- /**
3008
- * InputObjectTypeExtension :
3009
- * - extend input Name Directives[Const]? InputFieldsDefinition
3010
- * - extend input Name Directives[Const]
3011
- */
3012
-
3013
- parseInputObjectTypeExtension() {
3014
- const start = this._lexer.token;
3015
- this.expectKeyword('extend');
3016
- this.expectKeyword('input');
3017
- const name = this.parseName();
3018
- const directives = this.parseConstDirectives();
3019
- const fields = this.parseInputFieldsDefinition();
3020
-
3021
- if (directives.length === 0 && fields.length === 0) {
3022
- throw this.unexpected();
3023
- }
3024
-
3025
- return this.node(start, {
3026
- kind: Kind.INPUT_OBJECT_TYPE_EXTENSION,
3027
- name,
3028
- directives,
3029
- fields,
3030
- });
3031
- }
3032
- /**
3033
- * ```
3034
- * DirectiveDefinition :
3035
- * - Description? directive @ Name ArgumentsDefinition? `repeatable`? on DirectiveLocations
3036
- * ```
3037
- */
3038
-
3039
- parseDirectiveDefinition() {
3040
- const start = this._lexer.token;
3041
- const description = this.parseDescription();
3042
- this.expectKeyword('directive');
3043
- this.expectToken(TokenKind.AT);
3044
- const name = this.parseName();
3045
- const args = this.parseArgumentDefs();
3046
- const repeatable = this.expectOptionalKeyword('repeatable');
3047
- this.expectKeyword('on');
3048
- const locations = this.parseDirectiveLocations();
3049
- return this.node(start, {
3050
- kind: Kind.DIRECTIVE_DEFINITION,
3051
- description,
3052
- name,
3053
- arguments: args,
3054
- repeatable,
3055
- locations,
3056
- });
3057
- }
3058
- /**
3059
- * DirectiveLocations :
3060
- * - `|`? DirectiveLocation
3061
- * - DirectiveLocations | DirectiveLocation
3062
- */
3063
-
3064
- parseDirectiveLocations() {
3065
- return this.delimitedMany(TokenKind.PIPE, this.parseDirectiveLocation);
3066
- }
3067
- /*
3068
- * DirectiveLocation :
3069
- * - ExecutableDirectiveLocation
3070
- * - TypeSystemDirectiveLocation
3071
- *
3072
- * ExecutableDirectiveLocation : one of
3073
- * `QUERY`
3074
- * `MUTATION`
3075
- * `SUBSCRIPTION`
3076
- * `FIELD`
3077
- * `FRAGMENT_DEFINITION`
3078
- * `FRAGMENT_SPREAD`
3079
- * `INLINE_FRAGMENT`
3080
- *
3081
- * TypeSystemDirectiveLocation : one of
3082
- * `SCHEMA`
3083
- * `SCALAR`
3084
- * `OBJECT`
3085
- * `FIELD_DEFINITION`
3086
- * `ARGUMENT_DEFINITION`
3087
- * `INTERFACE`
3088
- * `UNION`
3089
- * `ENUM`
3090
- * `ENUM_VALUE`
3091
- * `INPUT_OBJECT`
3092
- * `INPUT_FIELD_DEFINITION`
3093
- */
3094
-
3095
- parseDirectiveLocation() {
3096
- const start = this._lexer.token;
3097
- const name = this.parseName();
3098
-
3099
- if (Object.prototype.hasOwnProperty.call(DirectiveLocation, name.value)) {
3100
- return name;
3101
- }
3102
-
3103
- throw this.unexpected(start);
3104
- } // Core parsing utility functions
3105
-
3106
- /**
3107
- * Returns a node that, if configured to do so, sets a "loc" field as a
3108
- * location object, used to identify the place in the source that created a
3109
- * given parsed object.
3110
- */
3111
-
3112
- node(startToken, node) {
3113
- var _this$_options2;
3114
-
3115
- if (
3116
- ((_this$_options2 = this._options) === null || _this$_options2 === void 0
3117
- ? void 0
3118
- : _this$_options2.noLocation) !== true
3119
- ) {
3120
- node.loc = new Location(
3121
- startToken,
3122
- this._lexer.lastToken,
3123
- this._lexer.source,
3124
- );
3125
- }
3126
-
3127
- return node;
3128
- }
3129
- /**
3130
- * Determines if the next token is of a given kind
3131
- */
3132
-
3133
- peek(kind) {
3134
- return this._lexer.token.kind === kind;
3135
- }
3136
- /**
3137
- * If the next token is of the given kind, return that token after advancing the lexer.
3138
- * Otherwise, do not change the parser state and throw an error.
3139
- */
3140
-
3141
- expectToken(kind) {
3142
- const token = this._lexer.token;
3143
-
3144
- if (token.kind === kind) {
3145
- this._lexer.advance();
3146
-
3147
- return token;
3148
- }
3149
-
3150
- throw syntaxError(
3151
- this._lexer.source,
3152
- token.start,
3153
- `Expected ${getTokenKindDesc(kind)}, found ${getTokenDesc(token)}.`,
3154
- );
3155
- }
3156
- /**
3157
- * If the next token is of the given kind, return "true" after advancing the lexer.
3158
- * Otherwise, do not change the parser state and return "false".
3159
- */
3160
-
3161
- expectOptionalToken(kind) {
3162
- const token = this._lexer.token;
3163
-
3164
- if (token.kind === kind) {
3165
- this._lexer.advance();
3166
-
3167
- return true;
3168
- }
3169
-
3170
- return false;
3171
- }
3172
- /**
3173
- * If the next token is a given keyword, advance the lexer.
3174
- * Otherwise, do not change the parser state and throw an error.
3175
- */
3176
-
3177
- expectKeyword(value) {
3178
- const token = this._lexer.token;
3179
-
3180
- if (token.kind === TokenKind.NAME && token.value === value) {
3181
- this._lexer.advance();
3182
- } else {
3183
- throw syntaxError(
3184
- this._lexer.source,
3185
- token.start,
3186
- `Expected "${value}", found ${getTokenDesc(token)}.`,
3187
- );
3188
- }
3189
- }
3190
- /**
3191
- * If the next token is a given keyword, return "true" after advancing the lexer.
3192
- * Otherwise, do not change the parser state and return "false".
3193
- */
3194
-
3195
- expectOptionalKeyword(value) {
3196
- const token = this._lexer.token;
3197
-
3198
- if (token.kind === TokenKind.NAME && token.value === value) {
3199
- this._lexer.advance();
3200
-
3201
- return true;
3202
- }
3203
-
3204
- return false;
3205
- }
3206
- /**
3207
- * Helper function for creating an error when an unexpected lexed token is encountered.
3208
- */
3209
-
3210
- unexpected(atToken) {
3211
- const token =
3212
- atToken !== null && atToken !== void 0 ? atToken : this._lexer.token;
3213
- return syntaxError(
3214
- this._lexer.source,
3215
- token.start,
3216
- `Unexpected ${getTokenDesc(token)}.`,
3217
- );
3218
- }
3219
- /**
3220
- * Returns a possibly empty list of parse nodes, determined by the parseFn.
3221
- * This list begins with a lex token of openKind and ends with a lex token of closeKind.
3222
- * Advances the parser to the next lex token after the closing token.
3223
- */
3224
-
3225
- any(openKind, parseFn, closeKind) {
3226
- this.expectToken(openKind);
3227
- const nodes = [];
3228
-
3229
- while (!this.expectOptionalToken(closeKind)) {
3230
- nodes.push(parseFn.call(this));
3231
- }
3232
-
3233
- return nodes;
3234
- }
3235
- /**
3236
- * Returns a list of parse nodes, determined by the parseFn.
3237
- * It can be empty only if open token is missing otherwise it will always return non-empty list
3238
- * that begins with a lex token of openKind and ends with a lex token of closeKind.
3239
- * Advances the parser to the next lex token after the closing token.
3240
- */
3241
-
3242
- optionalMany(openKind, parseFn, closeKind) {
3243
- if (this.expectOptionalToken(openKind)) {
3244
- const nodes = [];
3245
-
3246
- do {
3247
- nodes.push(parseFn.call(this));
3248
- } while (!this.expectOptionalToken(closeKind));
3249
-
3250
- return nodes;
3251
- }
3252
-
3253
- return [];
3254
- }
3255
- /**
3256
- * Returns a non-empty list of parse nodes, determined by the parseFn.
3257
- * This list begins with a lex token of openKind and ends with a lex token of closeKind.
3258
- * Advances the parser to the next lex token after the closing token.
3259
- */
3260
-
3261
- many(openKind, parseFn, closeKind) {
3262
- this.expectToken(openKind);
3263
- const nodes = [];
3264
-
3265
- do {
3266
- nodes.push(parseFn.call(this));
3267
- } while (!this.expectOptionalToken(closeKind));
3268
-
3269
- return nodes;
3270
- }
3271
- /**
3272
- * Returns a non-empty list of parse nodes, determined by the parseFn.
3273
- * This list may begin with a lex token of delimiterKind followed by items separated by lex tokens of tokenKind.
3274
- * Advances the parser to the next lex token after last item in the list.
3275
- */
3276
-
3277
- delimitedMany(delimiterKind, parseFn) {
3278
- this.expectOptionalToken(delimiterKind);
3279
- const nodes = [];
3280
-
3281
- do {
3282
- nodes.push(parseFn.call(this));
3283
- } while (this.expectOptionalToken(delimiterKind));
3284
-
3285
- return nodes;
3286
- }
3287
- }
3288
- /**
3289
- * A helper function to describe a token as a string for debugging.
3290
- */
3291
-
3292
- function getTokenDesc(token) {
3293
- const value = token.value;
3294
- return getTokenKindDesc(token.kind) + (value != null ? ` "${value}"` : '');
3295
- }
3296
- /**
3297
- * A helper function to describe a token kind as a string for debugging.
3298
- */
3299
-
3300
- function getTokenKindDesc(kind) {
3301
- return isPunctuatorTokenKind(kind) ? `"${kind}"` : kind;
3302
- }
3303
-
3304
- function parseDocumentNode(node) {
3305
- var _a;
3306
- const operationDef = node.definitions.find((def) => {
3307
- return def.kind === 'OperationDefinition';
3308
- });
3309
- return {
3310
- operationType: operationDef === null || operationDef === void 0 ? void 0 : operationDef.operation,
3311
- operationName: (_a = operationDef === null || operationDef === void 0 ? void 0 : operationDef.name) === null || _a === void 0 ? void 0 : _a.value,
3312
- };
3313
- }
3314
- function parseQuery(query) {
3315
- try {
3316
- const ast = parse(query);
3317
- return parseDocumentNode(ast);
3318
- }
3319
- catch (error) {
3320
- return error;
3321
- }
3322
- }
3323
- function extractMultipartVariables(variables, map, files) {
3324
- const operations = { variables };
3325
- for (const [key, pathArray] of Object.entries(map)) {
3326
- if (!(key in files)) {
3327
- throw new Error(`Given files do not have a key '${key}' .`);
3328
- }
3329
- for (const dotPath of pathArray) {
3330
- const [lastPath, ...reversedPaths] = dotPath.split('.').reverse();
3331
- const paths = reversedPaths.reverse();
3332
- let target = operations;
3333
- for (const path of paths) {
3334
- if (!(path in target)) {
3335
- throw new Error(`Property '${paths}' is not in operations.`);
3336
- }
3337
- target = target[path];
3338
- }
3339
- target[lastPath] = files[key];
3340
- }
3341
- }
3342
- return operations.variables;
3343
- }
3344
- function getGraphQLInput(request) {
3345
- var _a, _b;
3346
- switch (request.method) {
3347
- case 'GET': {
3348
- const query = request.url.searchParams.get('query');
3349
- const variables = request.url.searchParams.get('variables') || '';
3350
- return {
3351
- query,
3352
- variables: jsonParse(variables),
3353
- };
3354
- }
3355
- case 'POST': {
3356
- if ((_a = request.body) === null || _a === void 0 ? void 0 : _a.query) {
3357
- const { query, variables } = request.body;
3358
- return {
3359
- query,
3360
- variables,
3361
- };
3362
- }
3363
- // Handle multipart body operations.
3364
- if ((_b = request.body) === null || _b === void 0 ? void 0 : _b.operations) {
3365
- const _c = request.body, { operations, map } = _c, files = __rest(_c, ["operations", "map"]);
3366
- const parsedOperations = jsonParse(operations) || {};
3367
- if (!parsedOperations.query) {
3368
- return null;
3369
- }
3370
- const parsedMap = jsonParse(map || '') || {};
3371
- const variables = parsedOperations.variables
3372
- ? extractMultipartVariables(parsedOperations.variables, parsedMap, files)
3373
- : {};
3374
- return {
3375
- query: parsedOperations.query,
3376
- variables,
3377
- };
3378
- }
3379
- }
3380
- default:
3381
- return null;
3382
- }
3383
- }
3384
- /**
3385
- * Determines if a given request can be considered a GraphQL request.
3386
- * Does not parse the query and does not guarantee its validity.
3387
- */
3388
- function parseGraphQLRequest(request) {
3389
- const input = getGraphQLInput(request);
3390
- if (!input || !input.query) {
3391
- return undefined;
3392
- }
3393
- const { query, variables } = input;
3394
- const parsedResult = parseQuery(query);
3395
- if (parsedResult instanceof Error) {
3396
- const requestPublicUrl = getPublicUrlFromRequest(request);
3397
- throw new Error(devUtils.formatMessage('Failed to intercept a GraphQL request to "%s %s": cannot parse query. See the error message from the parser below.\n\n%s', request.method, requestPublicUrl, parsedResult.message));
3398
- }
3399
- return {
3400
- operationType: parsedResult.operationType,
3401
- operationName: parsedResult.operationName,
3402
- variables,
3403
- };
3404
- }
3405
-
3406
- function tryCatch(fn, onException) {
3407
- try {
3408
- const result = fn();
3409
- return result;
3410
- }
3411
- catch (error) {
3412
- onException === null || onException === void 0 ? void 0 : onException(error);
3413
- }
3414
- }
3415
-
3416
- const graphqlContext = Object.assign(Object.assign({}, defaultContext), { data,
3417
- extensions,
3418
- errors,
3419
- cookie });
3420
- function isDocumentNode(value) {
3421
- if (value == null) {
3422
- return false;
3423
- }
3424
- return typeof value === 'object' && 'kind' in value && 'definitions' in value;
3425
- }
3426
- class GraphQLHandler extends RequestHandler {
3427
- constructor(operationType, operationName, endpoint, resolver) {
3428
- let resolvedOperationName = operationName;
3429
- if (isDocumentNode(operationName)) {
3430
- const parsedNode = parseDocumentNode(operationName);
3431
- if (parsedNode.operationType !== operationType) {
3432
- throw new Error(`Failed to create a GraphQL handler: provided a DocumentNode with a mismatched operation type (expected "${operationType}", but got "${parsedNode.operationType}").`);
3433
- }
3434
- if (!parsedNode.operationName) {
3435
- throw new Error(`Failed to create a GraphQL handler: provided a DocumentNode with no operation name.`);
3436
- }
3437
- resolvedOperationName = parsedNode.operationName;
3438
- }
3439
- const header = operationType === 'all'
3440
- ? `${operationType} (origin: ${endpoint.toString()})`
3441
- : `${operationType} ${resolvedOperationName} (origin: ${endpoint.toString()})`;
3442
- super({
3443
- info: {
3444
- header,
3445
- operationType,
3446
- operationName: resolvedOperationName,
3447
- },
3448
- ctx: graphqlContext,
3449
- resolver,
3450
- });
3451
- this.endpoint = endpoint;
3452
- }
3453
- parse(request) {
3454
- return tryCatch(() => parseGraphQLRequest(request), (error) => console.error(error.message));
3455
- }
3456
- getPublicRequest(request, parsedResult) {
3457
- return Object.assign(Object.assign({}, request), { variables: (parsedResult === null || parsedResult === void 0 ? void 0 : parsedResult.variables) || {} });
3458
- }
3459
- predicate(request, parsedResult) {
3460
- if (!parsedResult) {
3461
- return false;
3462
- }
3463
- if (!parsedResult.operationName && this.info.operationType !== 'all') {
3464
- const publicUrl = getPublicUrlFromRequest(request);
3465
- devUtils.warn(`\
3466
- Failed to intercept a GraphQL request at "${request.method} ${publicUrl}": anonymous GraphQL operations are not supported.
3467
-
3468
- Consider naming this operation or using "graphql.operation" request handler to intercept GraphQL requests regardless of their operation name/type. Read more: https://mswjs.io/docs/api/graphql/operation\
3469
- `);
3470
- return false;
3471
- }
3472
- const hasMatchingUrl = matchRequestUrl(request.url, this.endpoint);
3473
- const hasMatchingOperationType = this.info.operationType === 'all' ||
3474
- parsedResult.operationType === this.info.operationType;
3475
- const hasMatchingOperationName = this.info.operationName instanceof RegExp
3476
- ? this.info.operationName.test(parsedResult.operationName || '')
3477
- : parsedResult.operationName === this.info.operationName;
3478
- return (hasMatchingUrl.matches &&
3479
- hasMatchingOperationType &&
3480
- hasMatchingOperationName);
3481
- }
3482
- log(request, response, handler, parsedRequest) {
3483
- const loggedRequest = prepareRequest(request);
3484
- const loggedResponse = prepareResponse(response);
3485
- const statusColor = getStatusCodeColor(response.status);
3486
- const requestInfo = (parsedRequest === null || parsedRequest === void 0 ? void 0 : parsedRequest.operationName)
3487
- ? `${parsedRequest === null || parsedRequest === void 0 ? void 0 : parsedRequest.operationType} ${parsedRequest === null || parsedRequest === void 0 ? void 0 : parsedRequest.operationName}`
3488
- : `anonymous ${parsedRequest === null || parsedRequest === void 0 ? void 0 : parsedRequest.operationType}`;
3489
- console.groupCollapsed(devUtils.formatMessage('%s %s (%c%s%c)'), getTimestamp(), `${requestInfo}`, `color:${statusColor}`, `${response.status} ${response.statusText}`, 'color:inherit');
3490
- console.log('Request:', loggedRequest);
3491
- console.log('Handler:', this);
3492
- console.log('Response:', loggedResponse);
3493
- console.groupEnd();
3494
- }
3495
- }
3496
-
3497
- function createScopedGraphQLHandler(operationType, url) {
3498
- return (operationName, resolver) => {
3499
- return new GraphQLHandler(operationType, operationName, url, resolver);
3500
- };
3501
- }
3502
- function createGraphQLOperationHandler(url) {
3503
- return (resolver) => {
3504
- return new GraphQLHandler('all', new RegExp('.*'), url, resolver);
3505
- };
3506
- }
3507
- const standardGraphQLHandlers = {
3508
- /**
3509
- * Captures any GraphQL operation, regardless of its name, under the current scope.
3510
- * @example
3511
- * graphql.operation((req, res, ctx) => {
3512
- * return res(ctx.data({ name: 'John' }))
3513
- * })
3514
- * @see {@link https://mswjs.io/docs/api/graphql/operation `graphql.operation()`}
3515
- */
3516
- operation: createGraphQLOperationHandler('*'),
3517
- /**
3518
- * Captures a GraphQL query by a given name.
3519
- * @example
3520
- * graphql.query('GetUser', (req, res, ctx) => {
3521
- * return res(ctx.data({ user: { name: 'John' } }))
3522
- * })
3523
- * @see {@link https://mswjs.io/docs/api/graphql/query `graphql.query()`}
3524
- */
3525
- query: createScopedGraphQLHandler(OperationTypeNode.QUERY, '*'),
3526
- /**
3527
- * Captures a GraphQL mutation by a given name.
3528
- * @example
3529
- * graphql.mutation('SavePost', (req, res, ctx) => {
3530
- * return res(ctx.data({ post: { id: 'abc-123' } }))
3531
- * })
3532
- * @see {@link https://mswjs.io/docs/api/graphql/mutation `graphql.mutation()`}
3533
- */
3534
- mutation: createScopedGraphQLHandler(OperationTypeNode.MUTATION, '*'),
3535
- };
3536
- function createGraphQLLink(url) {
3537
- return {
3538
- operation: createGraphQLOperationHandler(url),
3539
- query: createScopedGraphQLHandler(OperationTypeNode.QUERY, url),
3540
- mutation: createScopedGraphQLHandler(OperationTypeNode.MUTATION, url),
3541
- };
3542
- }
3543
- const graphql = Object.assign(Object.assign({}, standardGraphQLHandlers), { link: createGraphQLLink });
3544
-
3545
- export { GraphQLHandler as G, graphqlContext as a, graphql as g, parseGraphQLRequest as p, tryCatch as t };