@ocap/gql 1.30.24 → 1.30.26

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.
package/esm/http.mjs ADDED
@@ -0,0 +1,741 @@
1
+ import schemaSource from "@ocap/schema";
2
+ import { GraphQLError, NoSchemaIntrospectionCustomRule, buildSchema, execute, getOperationAST, parse, validate } from "graphql";
3
+ import get from "lodash/get.js";
4
+
5
+ //#region src/http.ts
6
+ const wrapResolver = async (_name, keys, callback) => {
7
+ const result = await callback();
8
+ const resultsMap = {};
9
+ if (Array.isArray(keys)) keys.forEach((key) => {
10
+ resultsMap[key] = result[key];
11
+ });
12
+ else resultsMap[keys] = result;
13
+ return {
14
+ code: "OK",
15
+ page: result ? result.paging || {} : null,
16
+ ...resultsMap
17
+ };
18
+ };
19
+ const formatContext = (ctx = {}) => {
20
+ return {
21
+ featureSwitch: {},
22
+ gasStakeHeaders: {
23
+ token: get(ctx, "headers[x-gas-payer-sig]", ""),
24
+ pk: get(ctx, "headers[x-gas-payer-pk]", "")
25
+ },
26
+ request: {
27
+ userAgent: get(ctx, "headers.user-agent"),
28
+ ip: get(ctx, "headers.x-real-ip") || ctx.ip || ctx._remoteAddress || ctx.connection?.remoteAddress || "-",
29
+ id: get(ctx, "headers[x-request-id]") || get(ctx, "headers[X-Request-ID]") || "-"
30
+ }
31
+ };
32
+ };
33
+ const resolvers = [
34
+ {
35
+ fn: "sendTx",
36
+ dataKey: "hash"
37
+ },
38
+ {
39
+ fn: "subscribe",
40
+ dataKey: "value"
41
+ },
42
+ {
43
+ fn: "unsubscribe",
44
+ dataKey: "result"
45
+ },
46
+ {
47
+ fn: "getAccountState",
48
+ dataKey: "state"
49
+ },
50
+ {
51
+ fn: "getAssetState",
52
+ dataKey: "state"
53
+ },
54
+ {
55
+ fn: "getFactoryState",
56
+ dataKey: "state"
57
+ },
58
+ {
59
+ fn: "getDelegateState",
60
+ dataKey: "state"
61
+ },
62
+ {
63
+ fn: "getTokenState",
64
+ dataKey: "state"
65
+ },
66
+ {
67
+ fn: "getForgeState",
68
+ dataKey: "state"
69
+ },
70
+ {
71
+ fn: "getStakeState",
72
+ dataKey: "state"
73
+ },
74
+ {
75
+ fn: "getEvidenceState",
76
+ dataKey: "state"
77
+ },
78
+ {
79
+ fn: "getRollupState",
80
+ dataKey: "state"
81
+ },
82
+ {
83
+ fn: "getRollupBlock",
84
+ dataKey: "block"
85
+ },
86
+ {
87
+ fn: "getTokenFactoryState",
88
+ dataKey: "state"
89
+ },
90
+ {
91
+ fn: "getAccountTokens",
92
+ dataKey: "tokens"
93
+ },
94
+ {
95
+ fn: "getBlock",
96
+ dataKey: "block"
97
+ },
98
+ {
99
+ fn: "getBlocks",
100
+ dataKey: "blocks"
101
+ },
102
+ {
103
+ fn: "getChainInfo",
104
+ dataKey: "info"
105
+ },
106
+ {
107
+ fn: "getConfig",
108
+ dataKey: "config"
109
+ },
110
+ {
111
+ fn: "getForgeStats",
112
+ dataKey: "forgeStats"
113
+ },
114
+ {
115
+ fn: "getNetInfo",
116
+ dataKey: "netInfo"
117
+ },
118
+ {
119
+ fn: "getNodeInfo",
120
+ dataKey: "info"
121
+ },
122
+ {
123
+ fn: "getTx",
124
+ dataKey: "info"
125
+ },
126
+ {
127
+ fn: "getUnconfirmedTxs",
128
+ dataKey: "unconfirmedTxs"
129
+ },
130
+ {
131
+ fn: "getValidatorsInfo",
132
+ dataKey: "validatorsInfo"
133
+ },
134
+ {
135
+ fn: "getLatestCheckpoint",
136
+ dataKey: "checkpoint"
137
+ },
138
+ {
139
+ fn: "getLedgerEntry",
140
+ dataKey: "entry"
141
+ },
142
+ {
143
+ fn: "getMerkleProof",
144
+ dataKey: ["proof", "checkpoint"]
145
+ },
146
+ {
147
+ fn: "getTokenDistribution",
148
+ dataKey: "data"
149
+ },
150
+ {
151
+ fn: "listTransactions",
152
+ dataKey: ["transactions"]
153
+ },
154
+ {
155
+ fn: "listAssets",
156
+ dataKey: ["assets", "account"]
157
+ },
158
+ {
159
+ fn: "listAssetTransactions",
160
+ dataKey: ["transactions"]
161
+ },
162
+ {
163
+ fn: "listFactories",
164
+ dataKey: ["factories"]
165
+ },
166
+ {
167
+ fn: "listTokens",
168
+ dataKey: ["tokens"]
169
+ },
170
+ {
171
+ fn: "listTokenFactories",
172
+ dataKey: ["tokenFactories"]
173
+ },
174
+ {
175
+ fn: "listTopAccounts",
176
+ dataKey: ["accounts"]
177
+ },
178
+ {
179
+ fn: "listBlocks",
180
+ dataKey: ["blocks"]
181
+ },
182
+ {
183
+ fn: "listStakes",
184
+ dataKey: ["stakes"]
185
+ },
186
+ {
187
+ fn: "listRollups",
188
+ dataKey: ["rollups"]
189
+ },
190
+ {
191
+ fn: "listRollupBlocks",
192
+ dataKey: ["blocks"]
193
+ },
194
+ {
195
+ fn: "listRollupValidators",
196
+ dataKey: ["validators"]
197
+ },
198
+ {
199
+ fn: "listDelegations",
200
+ dataKey: ["delegations"]
201
+ },
202
+ {
203
+ fn: "listTokenFlows",
204
+ dataKey: "data"
205
+ },
206
+ {
207
+ fn: "verifyAccountRisk",
208
+ dataKey: "data"
209
+ },
210
+ {
211
+ fn: "search",
212
+ dataKey: ["results"]
213
+ },
214
+ {
215
+ fn: "estimateGas",
216
+ dataKey: ["estimate"]
217
+ }
218
+ ];
219
+ const createResolvers = (resolver) => resolvers.reduce((acc, { fn, dataKey }) => {
220
+ acc[fn] = (args, ctx) => wrapResolver(fn, dataKey, () => {
221
+ const method = resolver[fn];
222
+ if (typeof method === "function") return method.call(resolver, args, formatContext(ctx));
223
+ return null;
224
+ });
225
+ return acc;
226
+ }, {});
227
+ const defaultErrorHandler = (err) => {
228
+ if (process.env.NODE_ENV !== "test") console.error("GraphQLError", err.originalError || err);
229
+ };
230
+ const MAX_BATCH_SIZE = 40;
231
+ const MAX_QUERY_DEPTH = 15;
232
+ const MAX_TOTAL_SELECTIONS = 1e3;
233
+ const MAX_ALIASES = 100;
234
+ const BODY_SIZE_LIMIT = 100 * 1024;
235
+ /**
236
+ * Read the raw express request body as a utf-8 string, enforcing the size limit.
237
+ * Mirrors express-graphql's parseBody behavior for the subset of content
238
+ * types we support (JSON and application/graphql).
239
+ */
240
+ async function readRawBody(req, limit) {
241
+ return new Promise((resolve, reject) => {
242
+ const chunks = [];
243
+ let size = 0;
244
+ req.on("data", (chunk) => {
245
+ size += chunk.length;
246
+ if (size > limit) {
247
+ const err = /* @__PURE__ */ new Error(`Request body too large (limit ${limit} bytes).`);
248
+ err.status = 413;
249
+ reject(err);
250
+ req.destroy();
251
+ return;
252
+ }
253
+ chunks.push(chunk);
254
+ });
255
+ req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
256
+ req.on("error", reject);
257
+ });
258
+ }
259
+ const isBuffer = (v) => typeof Buffer !== "undefined" && Buffer.isBuffer(v);
260
+ /**
261
+ * Extract GraphQL params from the request. URL query string takes precedence
262
+ * over the body so that callers can override fields via `?query=...` on a
263
+ * POST. Supports four body modes (matches upstream express-graphql):
264
+ * 1. Already parsed by upstream middleware (req.body is an object)
265
+ * 2. Content-Type: application/json — JSON.parse the raw body
266
+ * 3. Content-Type: application/graphql — raw body IS the query
267
+ * 4. Content-Type: application/x-www-form-urlencoded — parse as query string
268
+ */
269
+ async function parseGraphQLParams(req) {
270
+ const urlData = new URLSearchParams((req.url || "").split("?")[1] || "");
271
+ let query = urlData.get("query");
272
+ let variablesRaw = urlData.get("variables");
273
+ let operationName = urlData.get("operationName");
274
+ const raw = urlData.get("raw") != null;
275
+ if (req.method === "POST") {
276
+ const contentType = String(req.headers["content-type"] || "").split(";")[0].trim().toLowerCase();
277
+ const preparsed = req.body;
278
+ let bodyData = {};
279
+ if (preparsed != null && typeof preparsed === "object" && !isBuffer(preparsed)) bodyData = preparsed;
280
+ else if (typeof preparsed === "string" && contentType === "application/graphql") bodyData = { query: preparsed };
281
+ else if (preparsed == null && contentType) {
282
+ const rawBody = await req.readBody(BODY_SIZE_LIMIT);
283
+ if (contentType === "application/graphql") bodyData = { query: rawBody };
284
+ else if (contentType === "application/json") try {
285
+ bodyData = JSON.parse(rawBody);
286
+ } catch {
287
+ const err = /* @__PURE__ */ new Error("POST body sent invalid JSON.");
288
+ err.status = 400;
289
+ throw err;
290
+ }
291
+ else if (contentType === "application/x-www-form-urlencoded") {
292
+ const form = new URLSearchParams(rawBody);
293
+ const parsed = {};
294
+ for (const [k, v] of form) parsed[k] = v;
295
+ bodyData = parsed;
296
+ }
297
+ }
298
+ if (query == null && typeof bodyData.query === "string") query = bodyData.query;
299
+ if (variablesRaw == null && bodyData.variables != null) variablesRaw = bodyData.variables;
300
+ if (operationName == null && typeof bodyData.operationName === "string") operationName = bodyData.operationName;
301
+ }
302
+ let variables = null;
303
+ if (typeof variablesRaw === "string") try {
304
+ variables = JSON.parse(variablesRaw);
305
+ } catch {
306
+ const err = /* @__PURE__ */ new Error("Variables are invalid JSON.");
307
+ err.status = 400;
308
+ throw err;
309
+ }
310
+ else if (variablesRaw && typeof variablesRaw === "object") variables = variablesRaw;
311
+ return {
312
+ query,
313
+ variables,
314
+ operationName,
315
+ raw
316
+ };
317
+ }
318
+ /**
319
+ * Minimal GraphiQL HTML served on GET + Accept: text/html when graphiql=true.
320
+ * Loads GraphiQL 3.x from unpkg; consumers who need offline GraphiQL should
321
+ * configure their own static route.
322
+ */
323
+ const GRAPHIQL_HTML = `<!doctype html>
324
+ <html lang="en">
325
+ <head>
326
+ <meta charset="utf-8" />
327
+ <title>GraphiQL</title>
328
+ <link href="https://unpkg.com/graphiql@3/graphiql.min.css" rel="stylesheet" />
329
+ </head>
330
+ <body style="margin:0;height:100vh">
331
+ <div id="graphiql" style="height:100%">Loading...</div>
332
+ <script src="https://unpkg.com/react@18/umd/react.production.min.js" crossorigin><\/script>
333
+ <script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js" crossorigin><\/script>
334
+ <script src="https://unpkg.com/graphiql@3/graphiql.min.js" crossorigin><\/script>
335
+ <script>
336
+ const fetcher = GraphiQL.createFetcher({ url: window.location.pathname });
337
+ const root = ReactDOM.createRoot(document.getElementById('graphiql'));
338
+ root.render(React.createElement(GraphiQL, { fetcher }));
339
+ <\/script>
340
+ </body>
341
+ </html>`;
342
+ function shouldShowGraphiQL(req, params, graphiqlEnabled) {
343
+ if (!graphiqlEnabled || params.raw) return false;
344
+ if (req.method !== "GET") return false;
345
+ return String(req.headers.accept || "").includes("text/html");
346
+ }
347
+ /**
348
+ * Count the top-level field selections across all operation definitions
349
+ * in the document, recursively expanding inline and named fragments.
350
+ */
351
+ function countTopLevelSelections(documentAST, limit = MAX_BATCH_SIZE + 1) {
352
+ const fragments = /* @__PURE__ */ new Map();
353
+ const operations = [];
354
+ for (const def of documentAST.definitions) if (def.kind === "FragmentDefinition" && def.name?.value) fragments.set(def.name.value, def.selectionSet?.selections || []);
355
+ else if (def.kind === "OperationDefinition") operations.push(def);
356
+ const fragMemo = /* @__PURE__ */ new Map();
357
+ const countSelections = (selections, visited = /* @__PURE__ */ new Set()) => {
358
+ let total = 0;
359
+ const hitCycle = false;
360
+ for (const sel of selections) {
361
+ if (total >= limit) return {
362
+ count: limit,
363
+ hitCycle
364
+ };
365
+ if (sel.kind === "Field") total += 1;
366
+ else if (sel.kind === "InlineFragment") {
367
+ const sub = countSelections(sel.selectionSet?.selections || [], visited);
368
+ if (sub.hitCycle) return {
369
+ count: limit,
370
+ hitCycle: true
371
+ };
372
+ total += sub.count;
373
+ } else if (sel.kind === "FragmentSpread" && sel.name?.value) {
374
+ const fragName = sel.name.value;
375
+ if (visited.has(fragName)) return {
376
+ count: limit,
377
+ hitCycle: true
378
+ };
379
+ const cached = fragMemo.get(fragName);
380
+ if (cached !== void 0) {
381
+ total += cached;
382
+ continue;
383
+ }
384
+ const nextVisited = new Set(visited);
385
+ nextVisited.add(fragName);
386
+ const sub = countSelections(fragments.get(fragName) || [], nextVisited);
387
+ if (sub.hitCycle) return {
388
+ count: limit,
389
+ hitCycle: true
390
+ };
391
+ fragMemo.set(fragName, Math.min(sub.count, limit));
392
+ total += sub.count;
393
+ }
394
+ }
395
+ return {
396
+ count: Math.min(total, limit),
397
+ hitCycle
398
+ };
399
+ };
400
+ let sum = 0;
401
+ for (const op of operations) {
402
+ sum += countSelections(op.selectionSet?.selections || []).count;
403
+ if (sum >= limit) return limit;
404
+ }
405
+ return sum;
406
+ }
407
+ function getMaxSelectionDepth(documentAST, limit = MAX_QUERY_DEPTH + 1) {
408
+ const fragments = /* @__PURE__ */ new Map();
409
+ const operations = [];
410
+ for (const def of documentAST.definitions) if (def.kind === "FragmentDefinition" && def.name?.value) fragments.set(def.name.value, def.selectionSet?.selections || []);
411
+ else if (def.kind === "OperationDefinition") operations.push(def);
412
+ const fragDepthMemo = /* @__PURE__ */ new Map();
413
+ const measureDepth = (selections, visited = /* @__PURE__ */ new Set()) => {
414
+ let maxDepth = 0;
415
+ const hitCycle = false;
416
+ for (const sel of selections) {
417
+ if (maxDepth >= limit) return {
418
+ depth: limit,
419
+ hitCycle
420
+ };
421
+ if (sel.kind === "Field") {
422
+ const childSelections = sel.selectionSet?.selections || [];
423
+ let childDepth = 0;
424
+ if (childSelections.length > 0) {
425
+ const sub = measureDepth(childSelections, visited);
426
+ if (sub.hitCycle) return {
427
+ depth: limit,
428
+ hitCycle: true
429
+ };
430
+ childDepth = sub.depth;
431
+ }
432
+ const depth = 1 + childDepth;
433
+ if (depth > maxDepth) maxDepth = depth;
434
+ } else if (sel.kind === "InlineFragment") {
435
+ const sub = measureDepth(sel.selectionSet?.selections || [], visited);
436
+ if (sub.hitCycle) return {
437
+ depth: limit,
438
+ hitCycle: true
439
+ };
440
+ if (sub.depth > maxDepth) maxDepth = sub.depth;
441
+ } else if (sel.kind === "FragmentSpread" && sel.name?.value) {
442
+ const fragName = sel.name.value;
443
+ if (visited.has(fragName)) return {
444
+ depth: limit,
445
+ hitCycle: true
446
+ };
447
+ const cached = fragDepthMemo.get(fragName);
448
+ if (cached !== void 0) {
449
+ if (cached > maxDepth) maxDepth = cached;
450
+ continue;
451
+ }
452
+ const nextVisited = new Set(visited);
453
+ nextVisited.add(fragName);
454
+ const sub = measureDepth(fragments.get(fragName) || [], nextVisited);
455
+ if (sub.hitCycle) return {
456
+ depth: limit,
457
+ hitCycle: true
458
+ };
459
+ fragDepthMemo.set(fragName, Math.min(sub.depth, limit));
460
+ if (sub.depth > maxDepth) maxDepth = sub.depth;
461
+ }
462
+ }
463
+ return {
464
+ depth: Math.min(maxDepth, limit),
465
+ hitCycle
466
+ };
467
+ };
468
+ let max = 0;
469
+ for (const op of operations) {
470
+ const { depth } = measureDepth(op.selectionSet?.selections || []);
471
+ if (depth > max) max = depth;
472
+ if (max >= limit) return limit;
473
+ }
474
+ return max;
475
+ }
476
+ /**
477
+ * Count total expanded field selections and field aliases across all operations
478
+ * in the document, recursively expanding inline and named fragments with memoization.
479
+ * Bounds fragment + alias width amplification (e.g. K^D nested fragment spreads) in O(|AST|) time.
480
+ */
481
+ function countTotalSelectionsAndAliases(documentAST, selectionLimit = MAX_TOTAL_SELECTIONS + 1, aliasLimit = MAX_ALIASES + 1) {
482
+ const fragments = /* @__PURE__ */ new Map();
483
+ const operations = [];
484
+ for (const def of documentAST.definitions) if (def.kind === "FragmentDefinition" && def.name?.value) fragments.set(def.name.value, def.selectionSet?.selections || []);
485
+ else if (def.kind === "OperationDefinition") operations.push(def);
486
+ const fragMemo = /* @__PURE__ */ new Map();
487
+ const measure = (selections, visited = /* @__PURE__ */ new Set()) => {
488
+ let fields = 0;
489
+ let aliases = 0;
490
+ for (const sel of selections) {
491
+ if (fields >= selectionLimit && aliases >= aliasLimit) return {
492
+ fields: selectionLimit,
493
+ aliases: aliasLimit,
494
+ hitCycle: false
495
+ };
496
+ if (sel.kind === "Field") {
497
+ fields = Math.min(selectionLimit, fields + 1);
498
+ if (sel.alias?.value) aliases = Math.min(aliasLimit, aliases + 1);
499
+ const childSelections = sel.selectionSet?.selections || [];
500
+ if (childSelections.length > 0) {
501
+ const sub = measure(childSelections, visited);
502
+ if (sub.hitCycle) return {
503
+ fields: selectionLimit,
504
+ aliases: aliasLimit,
505
+ hitCycle: true
506
+ };
507
+ fields = Math.min(selectionLimit, fields + sub.fields);
508
+ aliases = Math.min(aliasLimit, aliases + sub.aliases);
509
+ }
510
+ } else if (sel.kind === "InlineFragment") {
511
+ const sub = measure(sel.selectionSet?.selections || [], visited);
512
+ if (sub.hitCycle) return {
513
+ fields: selectionLimit,
514
+ aliases: aliasLimit,
515
+ hitCycle: true
516
+ };
517
+ fields = Math.min(selectionLimit, fields + sub.fields);
518
+ aliases = Math.min(aliasLimit, aliases + sub.aliases);
519
+ } else if (sel.kind === "FragmentSpread" && sel.name?.value) {
520
+ const fragName = sel.name.value;
521
+ if (visited.has(fragName)) return {
522
+ fields: selectionLimit,
523
+ aliases: aliasLimit,
524
+ hitCycle: true
525
+ };
526
+ const cached = fragMemo.get(fragName);
527
+ if (cached !== void 0) {
528
+ fields = Math.min(selectionLimit, fields + cached.fields);
529
+ aliases = Math.min(aliasLimit, aliases + cached.aliases);
530
+ continue;
531
+ }
532
+ const nextVisited = new Set(visited);
533
+ nextVisited.add(fragName);
534
+ const sub = measure(fragments.get(fragName) || [], nextVisited);
535
+ if (sub.hitCycle) return {
536
+ fields: selectionLimit,
537
+ aliases: aliasLimit,
538
+ hitCycle: true
539
+ };
540
+ const clamped = {
541
+ fields: Math.min(selectionLimit, sub.fields),
542
+ aliases: Math.min(aliasLimit, sub.aliases)
543
+ };
544
+ fragMemo.set(fragName, clamped);
545
+ fields = Math.min(selectionLimit, fields + clamped.fields);
546
+ aliases = Math.min(aliasLimit, aliases + clamped.aliases);
547
+ }
548
+ }
549
+ return {
550
+ fields,
551
+ aliases,
552
+ hitCycle: false
553
+ };
554
+ };
555
+ let totalFields = 0;
556
+ let totalAliases = 0;
557
+ for (const op of operations) {
558
+ const sub = measure(op.selectionSet?.selections || []);
559
+ totalFields = Math.min(selectionLimit, totalFields + sub.fields);
560
+ totalAliases = Math.min(aliasLimit, totalAliases + sub.aliases);
561
+ if (totalFields >= selectionLimit && totalAliases >= aliasLimit) break;
562
+ }
563
+ return {
564
+ fields: totalFields,
565
+ aliases: totalAliases
566
+ };
567
+ }
568
+ const parseEnvPositiveInt = (raw) => {
569
+ if (raw === void 0 || raw.trim() === "") return void 0;
570
+ const parsed = Number.parseInt(raw.trim(), 10);
571
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : void 0;
572
+ };
573
+ const parseEnvBoolean = (raw) => {
574
+ if (raw === void 0 || raw.trim() === "") return void 0;
575
+ const normalized = raw.trim().toLowerCase();
576
+ if (normalized === "1" || normalized === "true") return true;
577
+ if (normalized === "0" || normalized === "false") return false;
578
+ };
579
+ const createGraphQLEngine = ({ resolver = {}, onError = defaultErrorHandler, graphiql = parseEnvBoolean(process.env.GQL_GRAPHIQL ?? process.env.GRAPHQL_GRAPHIQL) ?? process.env.NODE_ENV !== "production", introspection = parseEnvBoolean(process.env.GQL_INTROSPECTION ?? process.env.GRAPHQL_INTROSPECTION) ?? process.env.NODE_ENV !== "production", showStack = process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test", maxQueryDepth = MAX_QUERY_DEPTH, maxTotalSelections = parseEnvPositiveInt(process.env.GQL_MAX_TOTAL_SELECTIONS) ?? MAX_TOTAL_SELECTIONS, maxAliases = parseEnvPositiveInt(process.env.GQL_MAX_ALIASES) ?? MAX_ALIASES }) => {
580
+ const schema = buildSchema(schemaSource);
581
+ const rootValue = createResolvers(resolver);
582
+ const formatGraphQLError = (err) => {
583
+ onError(err);
584
+ const includeStack = showStack && process.env.NODE_ENV !== "production";
585
+ return {
586
+ code: get(err, "originalError.code", "INTERNAL"),
587
+ message: err.message,
588
+ locations: err.locations || [],
589
+ stack: includeStack ? get(err, "originalError.stack", "").split("\n") : [],
590
+ path: err.path
591
+ };
592
+ };
593
+ const formatAnyError = (input) => {
594
+ const message = typeof input === "string" ? input : input.message;
595
+ return formatGraphQLError(new GraphQLError(message, { originalError: typeof input === "string" ? new Error(message) : input }));
596
+ };
597
+ const sendJSON = (status, body, extra = {}) => ({
598
+ status,
599
+ headers: {
600
+ "content-type": "application/json; charset=utf-8",
601
+ ...extra
602
+ },
603
+ body: JSON.stringify(body)
604
+ });
605
+ const sendHTML = (html) => ({
606
+ status: 200,
607
+ headers: { "content-type": "text/html; charset=utf-8" },
608
+ body: html
609
+ });
610
+ return async (req, contextValue) => {
611
+ if (req.method !== "GET" && req.method !== "POST") return sendJSON(405, { errors: [formatAnyError("GraphQL only supports GET and POST requests.")] }, { Allow: "GET, POST" });
612
+ let params;
613
+ try {
614
+ params = await parseGraphQLParams(req);
615
+ } catch (err) {
616
+ return sendJSON(err.status ?? 500, { errors: [formatAnyError(err)] });
617
+ }
618
+ const showGraphiQL = shouldShowGraphiQL(req, params, graphiql);
619
+ if (params.query == null) {
620
+ if (showGraphiQL) return sendHTML(GRAPHIQL_HTML);
621
+ return sendJSON(400, { errors: [formatAnyError("Must provide query string.")] });
622
+ }
623
+ let documentAST;
624
+ try {
625
+ documentAST = parse(params.query);
626
+ } catch (syntaxError) {
627
+ return sendJSON(400, { errors: [formatGraphQLError(syntaxError)] });
628
+ }
629
+ if (!introspection) {
630
+ const validationErrors = validate(schema, documentAST, [NoSchemaIntrospectionCustomRule]);
631
+ if (validationErrors.length > 0) return sendJSON(400, { errors: validationErrors.map(formatGraphQLError) });
632
+ }
633
+ try {
634
+ if (countTopLevelSelections(documentAST) > MAX_BATCH_SIZE) throw new Error(`Batch query size exceeded allowed maximum batch size of ${MAX_BATCH_SIZE}`);
635
+ if (maxQueryDepth > 0) {
636
+ if (getMaxSelectionDepth(documentAST, maxQueryDepth + 1) > maxQueryDepth) throw new Error(`Query depth exceeded allowed maximum depth of ${maxQueryDepth}`);
637
+ }
638
+ if (maxTotalSelections > 0 || maxAliases > 0) {
639
+ const selLimit = maxTotalSelections > 0 ? maxTotalSelections + 1 : Number.MAX_SAFE_INTEGER;
640
+ const aliasLimit = maxAliases > 0 ? maxAliases + 1 : Number.MAX_SAFE_INTEGER;
641
+ const { fields, aliases } = countTotalSelectionsAndAliases(documentAST, selLimit, aliasLimit);
642
+ if (maxTotalSelections > 0 && fields > maxTotalSelections) throw new Error(`Query complexity exceeded allowed maximum of ${maxTotalSelections} total field selections`);
643
+ if (maxAliases > 0 && aliases > maxAliases) throw new Error(`Query aliases exceeded allowed maximum of ${maxAliases} aliases`);
644
+ }
645
+ } catch (batchError) {
646
+ return sendJSON(500, { errors: [formatAnyError(batchError)] });
647
+ }
648
+ if (req.method === "GET") {
649
+ const operationAST = getOperationAST(documentAST, params.operationName || void 0);
650
+ if (operationAST && operationAST.operation !== "query") return sendJSON(405, { errors: [formatAnyError(`Can only perform a ${operationAST.operation} operation from a POST request.`)] }, { Allow: "POST" });
651
+ }
652
+ let result;
653
+ try {
654
+ result = await execute({
655
+ schema,
656
+ document: documentAST,
657
+ rootValue,
658
+ contextValue,
659
+ variableValues: params.variables,
660
+ operationName: params.operationName
661
+ });
662
+ } catch (contextError) {
663
+ return sendJSON(400, { errors: [formatAnyError(contextError)] });
664
+ }
665
+ const formattedResult = { data: result.data };
666
+ if (result.errors && result.errors.length > 0) formattedResult.errors = result.errors.map(formatGraphQLError);
667
+ return sendJSON(result.data == null ? 500 : 200, formattedResult);
668
+ };
669
+ };
670
+ /** Express / connect adapter. Behavior is unchanged from the pre-split `createHttpHandler`. */
671
+ const createHttpHandler = (options) => {
672
+ const engine = createGraphQLEngine(options);
673
+ return async (req, res) => {
674
+ const result = await engine({
675
+ method: req.method,
676
+ url: req.url,
677
+ headers: req.headers,
678
+ body: req.body,
679
+ readBody: (limit) => readRawBody(req, limit)
680
+ }, req);
681
+ res.statusCode = result.status;
682
+ for (const [name, value] of Object.entries(result.headers)) res.setHeader(name, value);
683
+ res.end(result.body);
684
+ };
685
+ };
686
+ const readFetchBody = async (request, limit) => {
687
+ const tooLarge = () => {
688
+ const err = /* @__PURE__ */ new Error(`Request body too large (limit ${limit} bytes).`);
689
+ err.status = 413;
690
+ return err;
691
+ };
692
+ const declared = Number(request.headers.get("content-length"));
693
+ if (Number.isFinite(declared) && declared > limit) throw tooLarge();
694
+ if (!request.body) return "";
695
+ const reader = request.body.getReader();
696
+ const decoder = new TextDecoder();
697
+ let size = 0;
698
+ let text = "";
699
+ for (;;) {
700
+ const { done, value } = await reader.read();
701
+ if (done) break;
702
+ size += value.byteLength;
703
+ if (size > limit) {
704
+ await reader.cancel().catch(() => {});
705
+ throw tooLarge();
706
+ }
707
+ text += decoder.decode(value, { stream: true });
708
+ }
709
+ return text + decoder.decode();
710
+ };
711
+ /**
712
+ * Fetch-native adapter (Cloudflare Workers / Durable Objects, Deno, Bun): `(Request) => Promise<Response>`.
713
+ * Same engine, same guards (depth limit, batch guard, introspection off in production, 100kb body cap) as
714
+ * `createHttpHandler`; no `node:http`, no express and no WebSocket server are imported.
715
+ */
716
+ const createFetchHandler = (options) => {
717
+ const engine = createGraphQLEngine(options);
718
+ return async (request) => {
719
+ const headers = {};
720
+ request.headers.forEach((value, key) => {
721
+ headers[key.toLowerCase()] = value;
722
+ });
723
+ const url = new URL(request.url);
724
+ const result = await engine({
725
+ method: request.method,
726
+ url: `${url.pathname}${url.search}`,
727
+ headers,
728
+ readBody: (limit) => readFetchBody(request, limit)
729
+ }, {
730
+ headers,
731
+ ip: headers["cf-connecting-ip"] || headers["x-real-ip"]
732
+ });
733
+ return new Response(result.body, {
734
+ status: result.status,
735
+ headers: result.headers
736
+ });
737
+ };
738
+ };
739
+
740
+ //#endregion
741
+ export { createFetchHandler, createHttpHandler, createResolvers, formatContext, wrapResolver };