@ocap/gql 1.30.23 → 1.30.25

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/index.mjs CHANGED
@@ -1,438 +1,16 @@
1
+ import { createFetchHandler, createHttpHandler, createResolvers, formatContext, wrapResolver } from "./http.mjs";
1
2
  import createWebsocketServer from "./ws.mjs";
2
3
  import { createServer } from "node:http";
3
- import schemaSource from "@ocap/schema";
4
- import { GraphQLError, buildSchema, execute, getOperationAST, parse } from "graphql";
5
- import get from "lodash/get.js";
6
4
 
7
5
  //#region src/index.ts
8
- const wrapResolver = async (_name, keys, callback) => {
9
- const result = await callback();
10
- const resultsMap = {};
11
- if (Array.isArray(keys)) keys.forEach((key) => {
12
- resultsMap[key] = result[key];
13
- });
14
- else resultsMap[keys] = result;
15
- return {
16
- code: "OK",
17
- page: result ? result.paging || {} : null,
18
- ...resultsMap
19
- };
20
- };
21
- const formatContext = (ctx = {}) => {
22
- return {
23
- featureSwitch: {},
24
- gasStakeHeaders: {
25
- token: get(ctx, "headers[x-gas-payer-sig]", ""),
26
- pk: get(ctx, "headers[x-gas-payer-pk]", "")
27
- },
28
- request: {
29
- userAgent: get(ctx, "headers.user-agent"),
30
- ip: get(ctx, "headers.x-real-ip") || ctx.ip || ctx._remoteAddress || ctx.connection?.remoteAddress || "-",
31
- id: get(ctx, "headers[x-request-id]") || get(ctx, "headers[X-Request-ID]") || "-"
32
- }
33
- };
34
- };
35
- const resolvers = [
36
- {
37
- fn: "sendTx",
38
- dataKey: "hash"
39
- },
40
- {
41
- fn: "subscribe",
42
- dataKey: "value"
43
- },
44
- {
45
- fn: "unsubscribe",
46
- dataKey: "result"
47
- },
48
- {
49
- fn: "getAccountState",
50
- dataKey: "state"
51
- },
52
- {
53
- fn: "getAssetState",
54
- dataKey: "state"
55
- },
56
- {
57
- fn: "getFactoryState",
58
- dataKey: "state"
59
- },
60
- {
61
- fn: "getDelegateState",
62
- dataKey: "state"
63
- },
64
- {
65
- fn: "getTokenState",
66
- dataKey: "state"
67
- },
68
- {
69
- fn: "getForgeState",
70
- dataKey: "state"
71
- },
72
- {
73
- fn: "getStakeState",
74
- dataKey: "state"
75
- },
76
- {
77
- fn: "getEvidenceState",
78
- dataKey: "state"
79
- },
80
- {
81
- fn: "getRollupState",
82
- dataKey: "state"
83
- },
84
- {
85
- fn: "getRollupBlock",
86
- dataKey: "block"
87
- },
88
- {
89
- fn: "getTokenFactoryState",
90
- dataKey: "state"
91
- },
92
- {
93
- fn: "getAccountTokens",
94
- dataKey: "tokens"
95
- },
96
- {
97
- fn: "getBlock",
98
- dataKey: "block"
99
- },
100
- {
101
- fn: "getBlocks",
102
- dataKey: "blocks"
103
- },
104
- {
105
- fn: "getChainInfo",
106
- dataKey: "info"
107
- },
108
- {
109
- fn: "getConfig",
110
- dataKey: "config"
111
- },
112
- {
113
- fn: "getForgeStats",
114
- dataKey: "forgeStats"
115
- },
116
- {
117
- fn: "getNetInfo",
118
- dataKey: "netInfo"
119
- },
120
- {
121
- fn: "getNodeInfo",
122
- dataKey: "info"
123
- },
124
- {
125
- fn: "getTx",
126
- dataKey: "info"
127
- },
128
- {
129
- fn: "getUnconfirmedTxs",
130
- dataKey: "unconfirmedTxs"
131
- },
132
- {
133
- fn: "getValidatorsInfo",
134
- dataKey: "validatorsInfo"
135
- },
136
- {
137
- fn: "getTokenDistribution",
138
- dataKey: "data"
139
- },
140
- {
141
- fn: "listTransactions",
142
- dataKey: ["transactions"]
143
- },
144
- {
145
- fn: "listAssets",
146
- dataKey: ["assets", "account"]
147
- },
148
- {
149
- fn: "listAssetTransactions",
150
- dataKey: ["transactions"]
151
- },
152
- {
153
- fn: "listFactories",
154
- dataKey: ["factories"]
155
- },
156
- {
157
- fn: "listTokens",
158
- dataKey: ["tokens"]
159
- },
160
- {
161
- fn: "listTokenFactories",
162
- dataKey: ["tokenFactories"]
163
- },
164
- {
165
- fn: "listTopAccounts",
166
- dataKey: ["accounts"]
167
- },
168
- {
169
- fn: "listBlocks",
170
- dataKey: ["blocks"]
171
- },
172
- {
173
- fn: "listStakes",
174
- dataKey: ["stakes"]
175
- },
176
- {
177
- fn: "listRollups",
178
- dataKey: ["rollups"]
179
- },
180
- {
181
- fn: "listRollupBlocks",
182
- dataKey: ["blocks"]
183
- },
184
- {
185
- fn: "listRollupValidators",
186
- dataKey: ["validators"]
187
- },
188
- {
189
- fn: "listDelegations",
190
- dataKey: ["delegations"]
191
- },
192
- {
193
- fn: "listTokenFlows",
194
- dataKey: "data"
195
- },
196
- {
197
- fn: "verifyAccountRisk",
198
- dataKey: "data"
199
- },
200
- {
201
- fn: "search",
202
- dataKey: ["results"]
203
- },
204
- {
205
- fn: "estimateGas",
206
- dataKey: ["estimate"]
207
- }
208
- ];
209
- const createResolvers = (resolver) => resolvers.reduce((acc, { fn, dataKey }) => {
210
- acc[fn] = (args, ctx) => wrapResolver(fn, dataKey, () => {
211
- const method = resolver[fn];
212
- if (typeof method === "function") return method.call(resolver, args, formatContext(ctx));
213
- return null;
214
- });
215
- return acc;
216
- }, {});
217
- const defaultErrorHandler = (err) => {
218
- if (process.env.NODE_ENV !== "test") console.error("GraphQLError", err.originalError || err);
219
- };
220
- const MAX_BATCH_SIZE = 40;
221
- const BODY_SIZE_LIMIT = 100 * 1024;
222
- /**
223
- * Read the raw request body as a utf-8 string, enforcing the size limit.
224
- * Mirrors express-graphql's parseBody behavior for the subset of content
225
- * types we support (JSON and application/graphql).
226
- */
227
- async function readRawBody(req, limit) {
228
- return new Promise((resolve, reject) => {
229
- const chunks = [];
230
- let size = 0;
231
- req.on("data", (chunk) => {
232
- size += chunk.length;
233
- if (size > limit) {
234
- const err = /* @__PURE__ */ new Error(`Request body too large (limit ${limit} bytes).`);
235
- err.status = 413;
236
- reject(err);
237
- req.destroy();
238
- return;
239
- }
240
- chunks.push(chunk);
241
- });
242
- req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
243
- req.on("error", reject);
244
- });
245
- }
246
- /**
247
- * Extract GraphQL params from the request. URL query string takes precedence
248
- * over the body so that callers can override fields via `?query=...` on a
249
- * POST. Supports four body modes (matches upstream express-graphql):
250
- * 1. Already parsed by upstream middleware (req.body is an object)
251
- * 2. Content-Type: application/json — JSON.parse the raw body
252
- * 3. Content-Type: application/graphql — raw body IS the query
253
- * 4. Content-Type: application/x-www-form-urlencoded — parse as query string
254
- */
255
- async function parseGraphQLParams(req) {
256
- const urlData = new URLSearchParams((req.url || "").split("?")[1] || "");
257
- let query = urlData.get("query");
258
- let variablesRaw = urlData.get("variables");
259
- let operationName = urlData.get("operationName");
260
- const raw = urlData.get("raw") != null;
261
- if (req.method === "POST") {
262
- const contentType = String(req.headers["content-type"] || "").split(";")[0].trim().toLowerCase();
263
- const preparsed = req.body;
264
- let bodyData = {};
265
- if (preparsed != null && typeof preparsed === "object" && !Buffer.isBuffer(preparsed)) bodyData = preparsed;
266
- else if (typeof preparsed === "string" && contentType === "application/graphql") bodyData = { query: preparsed };
267
- else if (preparsed == null && contentType) {
268
- const rawBody = await readRawBody(req, BODY_SIZE_LIMIT);
269
- if (contentType === "application/graphql") bodyData = { query: rawBody };
270
- else if (contentType === "application/json") try {
271
- bodyData = JSON.parse(rawBody);
272
- } catch {
273
- const err = /* @__PURE__ */ new Error("POST body sent invalid JSON.");
274
- err.status = 400;
275
- throw err;
276
- }
277
- else if (contentType === "application/x-www-form-urlencoded") {
278
- const form = new URLSearchParams(rawBody);
279
- const parsed = {};
280
- for (const [k, v] of form) parsed[k] = v;
281
- bodyData = parsed;
282
- }
283
- }
284
- if (query == null && typeof bodyData.query === "string") query = bodyData.query;
285
- if (variablesRaw == null && bodyData.variables != null) variablesRaw = bodyData.variables;
286
- if (operationName == null && typeof bodyData.operationName === "string") operationName = bodyData.operationName;
287
- }
288
- let variables = null;
289
- if (typeof variablesRaw === "string") try {
290
- variables = JSON.parse(variablesRaw);
291
- } catch {
292
- const err = /* @__PURE__ */ new Error("Variables are invalid JSON.");
293
- err.status = 400;
294
- throw err;
295
- }
296
- else if (variablesRaw && typeof variablesRaw === "object") variables = variablesRaw;
297
- return {
298
- query,
299
- variables,
300
- operationName,
301
- raw
302
- };
303
- }
304
- /**
305
- * Minimal GraphiQL HTML served on GET + Accept: text/html when graphiql=true.
306
- * Loads GraphiQL 3.x from unpkg; consumers who need offline GraphiQL should
307
- * configure their own static route.
308
- */
309
- const GRAPHIQL_HTML = `<!doctype html>
310
- <html lang="en">
311
- <head>
312
- <meta charset="utf-8" />
313
- <title>GraphiQL</title>
314
- <link href="https://unpkg.com/graphiql@3/graphiql.min.css" rel="stylesheet" />
315
- </head>
316
- <body style="margin:0;height:100vh">
317
- <div id="graphiql" style="height:100%">Loading...</div>
318
- <script src="https://unpkg.com/react@18/umd/react.production.min.js" crossorigin><\/script>
319
- <script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js" crossorigin><\/script>
320
- <script src="https://unpkg.com/graphiql@3/graphiql.min.js" crossorigin><\/script>
321
- <script>
322
- const fetcher = GraphiQL.createFetcher({ url: window.location.pathname });
323
- const root = ReactDOM.createRoot(document.getElementById('graphiql'));
324
- root.render(React.createElement(GraphiQL, { fetcher }));
325
- <\/script>
326
- </body>
327
- </html>`;
328
- function shouldShowGraphiQL(req, params, graphiqlEnabled) {
329
- if (!graphiqlEnabled || params.raw) return false;
330
- if (req.method !== "GET") return false;
331
- return String(req.headers.accept || "").includes("text/html");
332
- }
333
- /**
334
- * Count the top-level field selections across all operation definitions
335
- * in the document. Matches the behavior of the previous express-graphql
336
- * customValidateFn exactly.
337
- */
338
- function countTopLevelSelections(documentAST) {
339
- return documentAST.definitions.flatMap((def) => get(def, "selectionSet.selections") || []).map((sel) => get(sel, "name.value")).filter((name) => typeof name === "string").length;
340
- }
341
- const createHttpHandler = ({ resolver = {}, onError = defaultErrorHandler, graphiql = true }) => {
342
- const schema = buildSchema(schemaSource);
343
- const rootValue = createResolvers(resolver);
344
- const formatGraphQLError = (err) => {
345
- onError(err);
346
- const isProd = process.env.NODE_ENV === "production";
347
- return {
348
- code: get(err, "originalError.code", "INTERNAL"),
349
- message: err.message,
350
- locations: err.locations || [],
351
- stack: isProd ? [] : get(err, "originalError.stack", "").split("\n"),
352
- path: err.path
353
- };
354
- };
355
- const formatAnyError = (input) => {
356
- const message = typeof input === "string" ? input : input.message;
357
- return formatGraphQLError(new GraphQLError(message, { originalError: typeof input === "string" ? new Error(message) : input }));
358
- };
359
- const sendJSON = (res, status, body) => {
360
- res.statusCode = status;
361
- res.setHeader("Content-Type", "application/json; charset=utf-8");
362
- res.end(JSON.stringify(body));
363
- };
364
- const sendHTML = (res, html) => {
365
- res.statusCode = 200;
366
- res.setHeader("Content-Type", "text/html; charset=utf-8");
367
- res.end(html);
368
- };
369
- return async (req, res) => {
370
- if (req.method !== "GET" && req.method !== "POST") {
371
- res.setHeader("Allow", "GET, POST");
372
- sendJSON(res, 405, { errors: [formatAnyError("GraphQL only supports GET and POST requests.")] });
373
- return;
374
- }
375
- let params;
376
- try {
377
- params = await parseGraphQLParams(req);
378
- } catch (err) {
379
- sendJSON(res, err.status ?? 500, { errors: [formatAnyError(err)] });
380
- return;
381
- }
382
- const showGraphiQL = shouldShowGraphiQL(req, params, graphiql);
383
- if (params.query == null) {
384
- if (showGraphiQL) {
385
- sendHTML(res, GRAPHIQL_HTML);
386
- return;
387
- }
388
- sendJSON(res, 400, { errors: [formatAnyError("Must provide query string.")] });
389
- return;
390
- }
391
- let documentAST;
392
- try {
393
- documentAST = parse(params.query);
394
- } catch (syntaxError) {
395
- sendJSON(res, 400, { errors: [formatGraphQLError(syntaxError)] });
396
- return;
397
- }
398
- try {
399
- if (countTopLevelSelections(documentAST) > MAX_BATCH_SIZE) throw new Error(`Batch query size exceeded allowed maximum batch size of ${MAX_BATCH_SIZE}`);
400
- } catch (batchError) {
401
- sendJSON(res, 500, { errors: [formatAnyError(batchError)] });
402
- return;
403
- }
404
- if (req.method === "GET") {
405
- const operationAST = getOperationAST(documentAST, params.operationName || void 0);
406
- if (operationAST && operationAST.operation !== "query") {
407
- res.setHeader("Allow", "POST");
408
- sendJSON(res, 405, { errors: [formatAnyError(`Can only perform a ${operationAST.operation} operation from a POST request.`)] });
409
- return;
410
- }
411
- }
412
- let result;
413
- try {
414
- result = await execute({
415
- schema,
416
- document: documentAST,
417
- rootValue,
418
- contextValue: req,
419
- variableValues: params.variables,
420
- operationName: params.operationName
421
- });
422
- } catch (contextError) {
423
- sendJSON(res, 400, { errors: [formatAnyError(contextError)] });
424
- return;
425
- }
426
- const formattedResult = { data: result.data };
427
- if (result.errors && result.errors.length > 0) formattedResult.errors = result.errors.map(formatGraphQLError);
428
- sendJSON(res, result.data == null ? 500 : 200, formattedResult);
429
- };
430
- };
431
- const createSocketHandler = ({ app, indexdb }) => {
6
+ const createSocketHandler = ({ app, indexdb, wsOptions }) => {
432
7
  const httpServer = createServer(app);
433
- createWebsocketServer({ indexdb }).attach(httpServer);
8
+ createWebsocketServer({
9
+ indexdb,
10
+ wsOptions
11
+ }).attach(httpServer);
434
12
  return httpServer;
435
13
  };
436
14
 
437
15
  //#endregion
438
- export { createHttpHandler, createResolvers, createSocketHandler, formatContext, wrapResolver };
16
+ export { createFetchHandler, createHttpHandler, createResolvers, createSocketHandler, formatContext, wrapResolver };
package/esm/ws.d.mts CHANGED
@@ -29,9 +29,11 @@ interface WsServerInstance {
29
29
  attach: (server: Server) => void;
30
30
  }
31
31
  declare function createWebsocketServer({
32
- indexdb
32
+ indexdb,
33
+ wsOptions
33
34
  }: {
34
35
  indexdb: Indexdb;
36
+ wsOptions?: Record<string, unknown>;
35
37
  }): WsServerInstance;
36
38
  //#endregion
37
39
  export { createWebsocketServer as default };
package/esm/ws.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
  import { WsServer } from "@arcblock/ws";
2
2
 
3
3
  //#region src/ws.ts
4
- function createWebsocketServer({ indexdb }) {
5
- const wsServer = new WsServer({});
4
+ function createWebsocketServer({ indexdb, wsOptions = {} }) {
5
+ const wsServer = new WsServer(wsOptions);
6
6
  const mutableTables = [
7
7
  "account",
8
8
  "asset",