@powerhousedao/reactor-api 6.0.2-staging.9 → 6.1.0-dev.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,32 +1,13 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="def0f6e3-b149-5760-8c0c-611814c2a321")}catch(e){}}();
3
- import { a as isSubgraphClass, c as loadDocumentModels, d as BaseSubgraph, i as buildGraphqlOperations, l as loadProcessors, n as buildGraphQlDriveDocument, o as debounce, r as buildGraphqlOperation, t as buildGraphQlDocument, u as loadSubgraphs } from "./utils-CHCRSWig.mjs";
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="54de2de8-0918-5f80-961f-f2a72e390510")}catch(e){}}();
3
+ import { a as isSubgraphClass, c as loadDocumentModels, d as BaseSubgraph, i as buildGraphqlOperations, l as loadProcessors, n as buildGraphQlDriveDocument, o as debounce, r as buildGraphqlOperation, t as buildGraphQlDocument, u as loadSubgraphs } from "./utils-BFkbSO_H.mjs";
4
4
  import { AnalyticsQueryEngine } from "@powerhousedao/analytics-engine-core";
5
5
  import { AnalyticsModel, AnalyticsResolvers, typedefs } from "@powerhousedao/analytics-engine-graphql";
6
6
  import { gql } from "graphql-tag";
7
7
  import { GraphQLError, Kind, parse, print } from "graphql";
8
8
  import { ConsoleLogger, childLogger, documentModelDocumentModelModule } from "document-model";
9
- import { ApolloGateway, LocalCompose, RemoteGraphQLDataSource } from "@apollo/gateway";
10
- import { ApolloServer, HeaderMap } from "@apollo/server";
11
- import { ApolloServerPluginInlineTraceDisabled } from "@apollo/server/plugin/disabled";
12
- import { ApolloServerPluginDrainHttpServer } from "@apollo/server/plugin/drainHttpServer";
13
- import { ApolloServerPluginLandingPageLocalDefault } from "@apollo/server/plugin/landingPage/default";
14
- import mercuriusGateway from "@mercuriusjs/gateway";
15
- import Fastify from "fastify";
16
- import mercurius from "mercurius";
17
- import { AsyncLocalStorage } from "node:async_hooks";
18
- import bodyParser from "body-parser";
19
- import cors from "cors";
20
- import devcert from "devcert";
21
- import expressLib, { Router } from "express";
22
- import fs, { watchFile } from "node:fs";
23
- import http from "node:http";
24
- import https from "node:https";
25
9
  import path from "node:path";
26
10
  import { match } from "path-to-regexp";
27
- import fastifyCors from "@fastify/cors";
28
- import fastifyFormbody from "@fastify/formbody";
29
- import fastifyMiddie from "@fastify/middie";
30
11
  import { verifyAuthBearerToken } from "@renown/sdk";
31
12
  import { buildSubgraphSchema } from "@apollo/subgraph";
32
13
  import { typeDefs } from "@powerhousedao/document-engineering/graphql";
@@ -44,6 +25,7 @@ import { getConfig } from "@powerhousedao/config/node";
44
25
  import { reactorDriveDocumentModelModule } from "@powerhousedao/reactor-drive";
45
26
  import { driveDocumentModelModule } from "@powerhousedao/shared/document-drive";
46
27
  import EventEmitter from "node:events";
28
+ import fs, { watchFile } from "node:fs";
47
29
  import { PostgresAnalyticsStore } from "@powerhousedao/analytics-engine-pg";
48
30
  import { AttachmentBuilder } from "@powerhousedao/reactor-attachments";
49
31
  import { setupMcpServer } from "@powerhousedao/reactor-mcp";
@@ -252,12 +234,12 @@ var AuthSubgraph = class extends BaseSubgraph {
252
234
  resolvers = {
253
235
  Query: {
254
236
  documentAccess: async (_parent, args) => {
255
- this.logger.debug("documentAccess", args);
237
+ this.logger.debug("documentAccess(@args)", args);
256
238
  if (!this.documentPermissionService) throw new GraphQLError("DocumentPermissionService not available");
257
239
  try {
258
240
  return await documentAccess(this.documentPermissionService, args);
259
241
  } catch (error) {
260
- this.logger.error("Error in documentAccess:", error);
242
+ this.logger.error("Error in documentAccess: @error", error);
261
243
  throw error;
262
244
  }
263
245
  },
@@ -268,7 +250,7 @@ var AuthSubgraph = class extends BaseSubgraph {
268
250
  try {
269
251
  return await userDocumentPermissions(this.documentPermissionService, ctx.user.address);
270
252
  } catch (error) {
271
- this.logger.error("Error in userDocumentPermissions:", error);
253
+ this.logger.error("Error in userDocumentPermissions: @error", error);
272
254
  throw error;
273
255
  }
274
256
  },
@@ -278,210 +260,210 @@ var AuthSubgraph = class extends BaseSubgraph {
278
260
  try {
279
261
  return await groups(this.documentPermissionService);
280
262
  } catch (error) {
281
- this.logger.error("Error in groups:", error);
263
+ this.logger.error("Error in groups: @error", error);
282
264
  throw error;
283
265
  }
284
266
  },
285
267
  group: async (_parent, args) => {
286
- this.logger.debug("group", args);
268
+ this.logger.debug("group(@args)", args);
287
269
  if (!this.documentPermissionService) throw new GraphQLError("DocumentPermissionService not available");
288
270
  try {
289
271
  return await group(this.documentPermissionService, args);
290
272
  } catch (error) {
291
- this.logger.error("Error in group:", error);
273
+ this.logger.error("Error in group: @error", error);
292
274
  throw error;
293
275
  }
294
276
  },
295
277
  userGroups: async (_parent, args) => {
296
- this.logger.debug("userGroups", args);
278
+ this.logger.debug("userGroups(@args)", args);
297
279
  if (!this.documentPermissionService) throw new GraphQLError("DocumentPermissionService not available");
298
280
  try {
299
281
  return await userGroups(this.documentPermissionService, args);
300
282
  } catch (error) {
301
- this.logger.error("Error in userGroups:", error);
283
+ this.logger.error("Error in userGroups: @error", error);
302
284
  throw error;
303
285
  }
304
286
  },
305
287
  operationPermissions: async (_parent, args) => {
306
- this.logger.debug("operationPermissions", args);
288
+ this.logger.debug("operationPermissions(@args)", args);
307
289
  if (!this.documentPermissionService) throw new GraphQLError("DocumentPermissionService not available");
308
290
  try {
309
291
  return await operationPermissions(this.documentPermissionService, args);
310
292
  } catch (error) {
311
- this.logger.error("Error in operationPermissions:", error);
293
+ this.logger.error("Error in operationPermissions: @error", error);
312
294
  throw error;
313
295
  }
314
296
  },
315
297
  canExecuteOperation: async (_parent, args, ctx) => {
316
- this.logger.debug("canExecuteOperation", args);
298
+ this.logger.debug("canExecuteOperation(@args)", args);
317
299
  if (!this.documentPermissionService) throw new GraphQLError("DocumentPermissionService not available");
318
300
  try {
319
301
  return await canExecuteOperation(this.documentPermissionService, args, ctx.user?.address);
320
302
  } catch (error) {
321
- this.logger.error("Error in canExecuteOperation:", error);
303
+ this.logger.error("Error in canExecuteOperation: @error", error);
322
304
  throw error;
323
305
  }
324
306
  },
325
307
  documentProtection: async (_parent, args, ctx) => {
326
- this.logger.debug("documentProtection", args);
308
+ this.logger.debug("documentProtection(@args)", args);
327
309
  if (!this.documentPermissionService) throw new GraphQLError("DocumentPermissionService not available");
328
310
  if (!ctx.user?.address) throw new GraphQLError("Authentication required to view document protection info");
329
311
  try {
330
312
  return await documentProtection(this.documentPermissionService, args);
331
313
  } catch (error) {
332
- this.logger.error("Error in documentProtection:", error);
314
+ this.logger.error("Error in documentProtection: @error", error);
333
315
  throw error;
334
316
  }
335
317
  }
336
318
  },
337
319
  Mutation: {
338
320
  setDocumentProtection: async (_parent, args, ctx) => {
339
- this.logger.debug("setDocumentProtection", args);
321
+ this.logger.debug("setDocumentProtection(@args)", args);
340
322
  if (!this.documentPermissionService) throw new GraphQLError("DocumentPermissionService not available");
341
323
  try {
342
324
  const isGlobalAdmin = ctx.isAdmin?.(ctx.user?.address ?? "") ?? false;
343
325
  return await setDocumentProtection(this.documentPermissionService, this.authorizationService, args, ctx.user?.address, isGlobalAdmin);
344
326
  } catch (error) {
345
- this.logger.error("Error in setDocumentProtection:", error);
327
+ this.logger.error("Error in setDocumentProtection: @error", error);
346
328
  throw error;
347
329
  }
348
330
  },
349
331
  transferDocumentOwnership: async (_parent, args, ctx) => {
350
- this.logger.debug("transferDocumentOwnership", args);
332
+ this.logger.debug("transferDocumentOwnership(@args)", args);
351
333
  if (!this.documentPermissionService) throw new GraphQLError("DocumentPermissionService not available");
352
334
  try {
353
335
  const isGlobalAdmin = ctx.isAdmin?.(ctx.user?.address ?? "") ?? false;
354
336
  return await transferDocumentOwnership(this.documentPermissionService, this.authorizationService, args, ctx.user?.address, isGlobalAdmin);
355
337
  } catch (error) {
356
- this.logger.error("Error in transferDocumentOwnership:", error);
338
+ this.logger.error("Error in transferDocumentOwnership: @error", error);
357
339
  throw error;
358
340
  }
359
341
  },
360
342
  grantDocumentPermission: async (_parent, args, ctx) => {
361
- this.logger.debug("grantDocumentPermission", args);
343
+ this.logger.debug("grantDocumentPermission(@args)", args);
362
344
  if (!this.documentPermissionService) throw new GraphQLError("DocumentPermissionService not available");
363
345
  try {
364
346
  const isGlobalAdmin = ctx.isAdmin?.(ctx.user?.address ?? "") ?? false;
365
347
  return await grantDocumentPermission(this.documentPermissionService, args, ctx.user?.address, isGlobalAdmin);
366
348
  } catch (error) {
367
- this.logger.error("Error in grantDocumentPermission:", error);
349
+ this.logger.error("Error in grantDocumentPermission: @error", error);
368
350
  throw error;
369
351
  }
370
352
  },
371
353
  revokeDocumentPermission: async (_parent, args, ctx) => {
372
- this.logger.debug("revokeDocumentPermission", args);
354
+ this.logger.debug("revokeDocumentPermission(@args)", args);
373
355
  if (!this.documentPermissionService) throw new GraphQLError("DocumentPermissionService not available");
374
356
  try {
375
357
  const isGlobalAdmin = ctx.isAdmin?.(ctx.user?.address ?? "") ?? false;
376
358
  return await revokeDocumentPermission(this.documentPermissionService, args, ctx.user?.address, isGlobalAdmin);
377
359
  } catch (error) {
378
- this.logger.error("Error in revokeDocumentPermission:", error);
360
+ this.logger.error("Error in revokeDocumentPermission: @error", error);
379
361
  throw error;
380
362
  }
381
363
  },
382
364
  createGroup: async (_parent, args) => {
383
- this.logger.debug("createGroup", args);
365
+ this.logger.debug("createGroup(@args)", args);
384
366
  if (!this.documentPermissionService) throw new GraphQLError("DocumentPermissionService not available");
385
367
  try {
386
368
  return await createGroup(this.documentPermissionService, args);
387
369
  } catch (error) {
388
- this.logger.error("Error in createGroup:", error);
370
+ this.logger.error("Error in createGroup: @error", error);
389
371
  throw error;
390
372
  }
391
373
  },
392
374
  deleteGroup: async (_parent, args) => {
393
- this.logger.debug("deleteGroup", args);
375
+ this.logger.debug("deleteGroup(@args)", args);
394
376
  if (!this.documentPermissionService) throw new GraphQLError("DocumentPermissionService not available");
395
377
  try {
396
378
  return await deleteGroup(this.documentPermissionService, args);
397
379
  } catch (error) {
398
- this.logger.error("Error in deleteGroup:", error);
380
+ this.logger.error("Error in deleteGroup: @error", error);
399
381
  throw error;
400
382
  }
401
383
  },
402
384
  addUserToGroup: async (_parent, args) => {
403
- this.logger.debug("addUserToGroup", args);
385
+ this.logger.debug("addUserToGroup(@args)", args);
404
386
  if (!this.documentPermissionService) throw new GraphQLError("DocumentPermissionService not available");
405
387
  try {
406
388
  return await addUserToGroup(this.documentPermissionService, args);
407
389
  } catch (error) {
408
- this.logger.error("Error in addUserToGroup:", error);
390
+ this.logger.error("Error in addUserToGroup: @error", error);
409
391
  throw error;
410
392
  }
411
393
  },
412
394
  removeUserFromGroup: async (_parent, args) => {
413
- this.logger.debug("removeUserFromGroup", args);
395
+ this.logger.debug("removeUserFromGroup(@args)", args);
414
396
  if (!this.documentPermissionService) throw new GraphQLError("DocumentPermissionService not available");
415
397
  try {
416
398
  return await removeUserFromGroup(this.documentPermissionService, args);
417
399
  } catch (error) {
418
- this.logger.error("Error in removeUserFromGroup:", error);
400
+ this.logger.error("Error in removeUserFromGroup: @error", error);
419
401
  throw error;
420
402
  }
421
403
  },
422
404
  grantGroupPermission: async (_parent, args, ctx) => {
423
- this.logger.debug("grantGroupPermission", args);
405
+ this.logger.debug("grantGroupPermission(@args)", args);
424
406
  if (!this.documentPermissionService) throw new GraphQLError("DocumentPermissionService not available");
425
407
  try {
426
408
  const isGlobalAdmin = ctx.isAdmin?.(ctx.user?.address ?? "") ?? false;
427
409
  return await grantGroupPermission(this.documentPermissionService, args, ctx.user?.address, isGlobalAdmin);
428
410
  } catch (error) {
429
- this.logger.error("Error in grantGroupPermission:", error);
411
+ this.logger.error("Error in grantGroupPermission: @error", error);
430
412
  throw error;
431
413
  }
432
414
  },
433
415
  revokeGroupPermission: async (_parent, args, ctx) => {
434
- this.logger.debug("revokeGroupPermission", args);
416
+ this.logger.debug("revokeGroupPermission(@args)", args);
435
417
  if (!this.documentPermissionService) throw new GraphQLError("DocumentPermissionService not available");
436
418
  try {
437
419
  const isGlobalAdmin = ctx.isAdmin?.(ctx.user?.address ?? "") ?? false;
438
420
  return await revokeGroupPermission(this.documentPermissionService, args, ctx.user?.address, isGlobalAdmin);
439
421
  } catch (error) {
440
- this.logger.error("Error in revokeGroupPermission:", error);
422
+ this.logger.error("Error in revokeGroupPermission: @error", error);
441
423
  throw error;
442
424
  }
443
425
  },
444
426
  grantOperationPermission: async (_parent, args, ctx) => {
445
- this.logger.debug("grantOperationPermission", args);
427
+ this.logger.debug("grantOperationPermission(@args)", args);
446
428
  if (!this.documentPermissionService) throw new GraphQLError("DocumentPermissionService not available");
447
429
  try {
448
430
  const isGlobalAdmin = ctx.isAdmin?.(ctx.user?.address ?? "") ?? false;
449
431
  return await grantOperationPermission(this.documentPermissionService, args, ctx.user?.address, isGlobalAdmin);
450
432
  } catch (error) {
451
- this.logger.error("Error in grantOperationPermission:", error);
433
+ this.logger.error("Error in grantOperationPermission: @error", error);
452
434
  throw error;
453
435
  }
454
436
  },
455
437
  revokeOperationPermission: async (_parent, args, ctx) => {
456
- this.logger.debug("revokeOperationPermission", args);
438
+ this.logger.debug("revokeOperationPermission(@args)", args);
457
439
  if (!this.documentPermissionService) throw new GraphQLError("DocumentPermissionService not available");
458
440
  try {
459
441
  const isGlobalAdmin = ctx.isAdmin?.(ctx.user?.address ?? "") ?? false;
460
442
  return await revokeOperationPermission(this.documentPermissionService, args, ctx.user?.address, isGlobalAdmin);
461
443
  } catch (error) {
462
- this.logger.error("Error in revokeOperationPermission:", error);
444
+ this.logger.error("Error in revokeOperationPermission: @error", error);
463
445
  throw error;
464
446
  }
465
447
  },
466
448
  grantGroupOperationPermission: async (_parent, args, ctx) => {
467
- this.logger.debug("grantGroupOperationPermission", args);
449
+ this.logger.debug("grantGroupOperationPermission(@args)", args);
468
450
  if (!this.documentPermissionService) throw new GraphQLError("DocumentPermissionService not available");
469
451
  try {
470
452
  const isGlobalAdmin = ctx.isAdmin?.(ctx.user?.address ?? "") ?? false;
471
453
  return await grantGroupOperationPermission(this.documentPermissionService, args, ctx.user?.address, isGlobalAdmin);
472
454
  } catch (error) {
473
- this.logger.error("Error in grantGroupOperationPermission:", error);
455
+ this.logger.error("Error in grantGroupOperationPermission: @error", error);
474
456
  throw error;
475
457
  }
476
458
  },
477
459
  revokeGroupOperationPermission: async (_parent, args, ctx) => {
478
- this.logger.debug("revokeGroupOperationPermission", args);
460
+ this.logger.debug("revokeGroupOperationPermission(@args)", args);
479
461
  if (!this.documentPermissionService) throw new GraphQLError("DocumentPermissionService not available");
480
462
  try {
481
463
  const isGlobalAdmin = ctx.isAdmin?.(ctx.user?.address ?? "") ?? false;
482
464
  return await revokeGroupOperationPermission(this.documentPermissionService, args, ctx.user?.address, isGlobalAdmin);
483
465
  } catch (error) {
484
- this.logger.error("Error in revokeGroupOperationPermission:", error);
466
+ this.logger.error("Error in revokeGroupOperationPermission: @error", error);
485
467
  throw error;
486
468
  }
487
469
  }
@@ -524,584 +506,29 @@ function createAuthFetchMiddleware(authService) {
524
506
  };
525
507
  }
526
508
  //#endregion
527
- //#region src/graphql/websocket.ts
528
- let useServerImpl = null;
529
- if (process.env.VITEST !== "true" && process.env.NODE_ENV !== "test") try {
530
- const { useServer } = await import("graphql-ws/use/ws");
531
- useServerImpl = useServer;
532
- } catch (error) {
533
- console.warn("Failed to load graphql-ws WebSocket server. Subscriptions will not work.", error);
534
- }
535
- const useServer = useServerImpl || (() => {
536
- throw new Error("WebSocket server not available in test mode. Set NODE_ENV=production to enable.");
537
- });
538
- //#endregion
539
- //#region src/graphql/gateway/adapter-gateway-apollo.ts
540
- var AuthenticatedDataSource = class extends RemoteGraphQLDataSource {
541
- willSendRequest(options) {
542
- const { authorization } = options.context.headers;
543
- if (authorization && options?.request.http) options.request.http.headers.set("authorization", authorization);
544
- }
545
- };
546
- var ApolloGatewayAdapter = class {
547
- #logger;
548
- #servers = [];
549
- #supergraphServer = null;
550
- #gatewayOptions = null;
551
- #getSubgraphs = null;
552
- constructor(logger) {
553
- this.#logger = logger;
554
- }
555
- async start(_httpServer) {}
556
- async createHandler(schema, contextFactory) {
557
- const server = new ApolloServer({
558
- schema,
559
- logger: this.#logger,
560
- introspection: true,
561
- stopOnTerminationSignals: false,
562
- plugins: [ApolloServerPluginInlineTraceDisabled(), ApolloServerPluginLandingPageLocalDefault()]
563
- });
564
- await server.start();
565
- this.#servers.push(server);
566
- return createApolloFetchHandler(server, contextFactory);
567
- }
568
- async createSupergraphHandler(getSubgraphs, httpServer, contextFactory) {
569
- if (this.#supergraphServer) throw new Error("Supergraph server is already running");
570
- this.#getSubgraphs = getSubgraphs;
571
- this.#supergraphServer = new ApolloServer({
572
- gateway: new ApolloGateway({
573
- supergraphSdl: async (options) => {
574
- this.#gatewayOptions = options;
575
- return await this.#buildSupergraphSdl();
576
- },
577
- buildService: (serviceConfig) => new AuthenticatedDataSource(serviceConfig)
578
- }),
579
- logger: this.#logger,
580
- introspection: true,
581
- stopOnTerminationSignals: false,
582
- plugins: [
583
- ApolloServerPluginDrainHttpServer({ httpServer }),
584
- ApolloServerPluginInlineTraceDisabled(),
585
- ApolloServerPluginLandingPageLocalDefault()
586
- ]
587
- });
588
- await this.#supergraphServer.start();
589
- return createApolloFetchHandler(this.#supergraphServer, contextFactory);
590
- }
591
- async updateSupergraph() {
592
- if (!this.#gatewayOptions || !this.#getSubgraphs) return;
593
- const { supergraphSdl } = await this.#buildSupergraphSdl();
594
- this.#gatewayOptions.update(supergraphSdl);
595
- }
596
- async #buildSupergraphSdl() {
597
- if (!this.#gatewayOptions || !this.#getSubgraphs) throw new Error("Gateway is not ready");
598
- return new LocalCompose({ localServiceList: this.#getSubgraphs().map((s) => ({
599
- name: s.name,
600
- typeDefs: s.typeDefs,
601
- url: s.url
602
- })) }).initialize(this.#gatewayOptions);
603
- }
604
- attachWebSocket(wsServer, schema, contextFactory) {
605
- return useServer({
606
- schema,
607
- context: async (ctx) => {
608
- return contextFactory(ctx.connectionParams ?? {});
609
- }
610
- }, wsServer);
611
- }
612
- async stop() {
613
- await Promise.all(this.#servers.map((s) => s.stop()));
614
- this.#servers.length = 0;
615
- if (this.#supergraphServer) {
616
- await this.#supergraphServer.stop();
617
- this.#supergraphServer = null;
618
- }
619
- this.#gatewayOptions = null;
620
- this.#getSubgraphs = null;
621
- }
622
- };
623
- /**
624
- * Wrap an existing ApolloServer as a Fetch API handler.
625
- * Does not manage server lifecycle; caller is responsible for start/stop.
626
- */
627
- function createApolloFetchHandler(server, contextFactory) {
628
- return async (request) => {
629
- const url = new URL(request.url);
630
- const headers = new HeaderMap();
631
- request.headers.forEach((value, key) => headers.set(key, value));
632
- let body = void 0;
633
- if (request.method !== "GET" && request.method !== "HEAD") try {
634
- body = await request.json();
635
- } catch {}
636
- const result = await server.executeHTTPGraphQLRequest({
637
- httpGraphQLRequest: {
638
- method: request.method.toUpperCase(),
639
- headers,
640
- search: url.search,
641
- body
642
- },
643
- context: () => contextFactory(request)
644
- });
645
- const responseHeaders = new Headers();
646
- for (const [key, value] of result.headers) responseHeaders.set(key, value);
647
- let responseBody;
648
- if (result.body.kind === "complete") responseBody = result.body.string;
649
- else {
650
- const chunks = [];
651
- for await (const chunk of result.body.asyncIterator) chunks.push(chunk);
652
- responseBody = chunks.join("");
653
- }
654
- return new Response(responseBody, {
655
- status: result.status ?? 200,
656
- headers: responseHeaders
657
- });
658
- };
659
- }
660
- //#endregion
661
- //#region src/graphql/gateway/adapter-gateway-mercurius.ts
662
- /**
663
- * Threads the original Fetch API Request through Mercurius's internal
664
- * fastify.inject() call so that contextFactory (which uses the auth WeakMap
665
- * from auth-middleware.ts) receives the same Request object that auth
666
- * middleware populated before calling the handler.
667
- */
668
- const requestAls = new AsyncLocalStorage();
669
- const mercuriusGatewayPlugin = mercuriusGateway;
670
- var MercuriusGatewayAdapter = class {
671
- #logger;
672
- #subgraphApps = [];
673
- #supergraphApp = null;
674
- #getSubgraphs = null;
675
- #supergraphContextFactory = null;
676
- constructor(logger) {
677
- this.#logger = logger;
678
- }
679
- async start(_httpServer) {}
680
- async createHandler(schema, contextFactory) {
681
- const app = await buildMercuriusApp(schema, contextFactory, this.#logger);
682
- this.#subgraphApps.push(app);
683
- return buildFetchHandler(app);
684
- }
685
- async createSupergraphHandler(getSubgraphs, _httpServer, contextFactory) {
686
- if (this.#supergraphApp) throw new Error("Supergraph is already running");
687
- this.#getSubgraphs = getSubgraphs;
688
- this.#supergraphContextFactory = contextFactory;
689
- this.#supergraphApp = await buildGatewayApp(getSubgraphs(), contextFactory, this.#logger);
690
- const adapter = this;
691
- return (request) => {
692
- if (!adapter.#supergraphApp) return Promise.resolve(new Response("Gateway not ready", { status: 503 }));
693
- return requestAls.run(request, () => injectRequest(adapter.#supergraphApp, request));
694
- };
695
- }
696
- async updateSupergraph() {
697
- if (!this.#getSubgraphs || !this.#supergraphContextFactory) return;
698
- const newApp = await buildGatewayApp(this.#getSubgraphs(), this.#supergraphContextFactory, this.#logger);
699
- const oldApp = this.#supergraphApp;
700
- this.#supergraphApp = newApp;
701
- if (oldApp) await oldApp.close();
702
- }
703
- attachWebSocket(wsServer, schema, contextFactory) {
704
- return useServer({
705
- schema,
706
- context: async (ctx) => contextFactory(ctx.connectionParams ?? {})
707
- }, wsServer);
708
- }
709
- async stop() {
710
- await Promise.all(this.#subgraphApps.map((app) => app.close()));
711
- this.#subgraphApps.length = 0;
712
- if (this.#supergraphApp) {
713
- await this.#supergraphApp.close();
714
- this.#supergraphApp = null;
509
+ //#region src/graphql/gateway/factory.ts
510
+ async function createGatewayAdapter(type, logger) {
511
+ switch (type) {
512
+ case "apollo": {
513
+ const { ApolloGatewayAdapter } = await import("./adapter-gateway-apollo-IZuGzFaY.mjs");
514
+ return new ApolloGatewayAdapter(logger);
715
515
  }
716
- this.#getSubgraphs = null;
717
- this.#supergraphContextFactory = null;
718
- }
719
- };
720
- function makeContextFn(contextFactory, logger) {
721
- return (_req, _reply) => {
722
- const request = requestAls.getStore();
723
- if (!request) {
724
- logger.error("[mercurius] No Fetch Request in AsyncLocalStorage");
725
- throw new Error("No Fetch Request in AsyncLocalStorage");
516
+ case "mercurius": {
517
+ const { MercuriusGatewayAdapter } = await import("./adapter-gateway-mercurius-CLmTtNJC.mjs");
518
+ return new MercuriusGatewayAdapter(logger);
726
519
  }
727
- return contextFactory(request);
728
- };
729
- }
730
- async function buildMercuriusApp(schema, contextFactory, logger) {
731
- const app = Fastify({ logger: false });
732
- await app.register(mercurius, {
733
- schema,
734
- graphiql: false,
735
- context: makeContextFn(contextFactory, logger),
736
- resolvers: { _Service: { sdl: (parent) => (parent.sdl ?? "").replace(/\btype\s+(Query|Mutation|Subscription)\s*\{/g, "extend type $1 {") } }
737
- });
738
- await app.ready();
739
- return app;
740
- }
741
- /**
742
- * Builds a Mercurius federation gateway that composes the given subgraph
743
- * services. Each service URL must be reachable so that the gateway can fetch
744
- * its SDL via `_service { sdl }` (Apollo Federation protocol).
745
- */
746
- async function buildGatewayApp(subgraphs, contextFactory, logger) {
747
- const app = Fastify({ logger: false });
748
- await app.register(mercuriusGatewayPlugin, {
749
- gateway: { services: subgraphs.map((s) => ({
750
- name: s.name,
751
- url: s.url
752
- })) },
753
- graphiql: false,
754
- context: makeContextFn(contextFactory, logger)
755
- });
756
- await app.ready();
757
- return app;
758
- }
759
- function buildFetchHandler(app) {
760
- return (request) => requestAls.run(request, () => injectRequest(app, request));
761
- }
762
- async function injectRequest(app, request) {
763
- const body = request.method !== "GET" && request.method !== "HEAD" ? await request.text() : void 0;
764
- const headers = {};
765
- request.headers.forEach((value, key) => {
766
- headers[key] = value;
767
- });
768
- const response = await app.inject({
769
- method: request.method,
770
- url: "/graphql",
771
- headers,
772
- payload: body
773
- });
774
- const responseHeaders = {};
775
- for (const [key, value] of Object.entries(response.headers)) if (value !== void 0) responseHeaders[key] = String(value);
776
- return new Response(response.payload, {
777
- status: response.statusCode,
778
- headers: responseHeaders
779
- });
780
- }
781
- //#endregion
782
- //#region src/graphql/gateway/adapter-http-express.ts
783
- var ExpressHttpAdapter = class {
784
- #app;
785
- #router;
786
- #handlers = /* @__PURE__ */ new Map();
787
- constructor(existingApp) {
788
- this.#app = existingApp ?? expressLib();
789
- this.#router = Router();
790
- this.#app.use(this.#router);
791
- }
792
- setupSentryErrorHandler(sentry) {
793
- sentry.setupExpressErrorHandler(this.#app);
794
- }
795
- get handle() {
796
- return this.#app;
797
- }
798
- mountRawMiddleware(middleware) {
799
- this.#app.use(middleware);
800
- }
801
- mountNodeRoute(method, path, handler) {
802
- const m = method.toLowerCase();
803
- this.#app[m](path, (req, res) => handler(req, res, req.body));
804
- }
805
- setupMiddleware({ corsOptions, bodyLimit = "50mb" }) {
806
- this.#router.use(cors(corsOptions));
807
- this.#router.use(bodyParser.json({ limit: bodyLimit }));
808
- this.#router.use(bodyParser.urlencoded({
809
- extended: true,
810
- limit: bodyLimit
811
- }));
812
- this.#router.use((req, res, next) => {
813
- for (const { handler, matcher } of this.#handlers.values()) if (matcher(req.path)) {
814
- this.#serveFetchHandler(handler, req, res, next);
815
- return;
816
- }
817
- next();
818
- });
819
- }
820
- mount(path, handler, { exact = false } = {}) {
821
- if (exact) this.#router.use(path, (req, res, next) => this.#serveFetchHandler(handler, req, res, next));
822
- else this.#handlers.set(path, {
823
- handler,
824
- matcher: match(path)
825
- });
826
520
  }
827
- getRoute(routePath, handler) {
828
- this.#app.get(routePath, (req, res) => {
829
- const url = `${req.protocol}://${req.get("host") ?? "localhost"}${req.originalUrl}`;
830
- const headers = new Headers();
831
- for (const [key, value] of Object.entries(req.headers)) if (typeof value === "string") headers.set(key, value);
832
- else if (Array.isArray(value)) headers.set(key, value.join(", "));
833
- const fetchRequest = new Request(url, {
834
- method: "GET",
835
- headers
836
- });
837
- Promise.resolve(handler(fetchRequest)).then(async (response) => {
838
- res.status(response.status);
839
- response.headers.forEach((value, key) => {
840
- res.setHeader(key, value);
841
- });
842
- res.send(await response.text());
843
- }).catch((err) => {
844
- res.status(500).send(String(err));
845
- });
846
- });
847
- }
848
- async listen(port, tls) {
849
- let server;
850
- if (tls === true) {
851
- const { cert, key } = await devcert.certificateFor("localhost");
852
- if (!cert || !key) throw new Error("Invalid certificate generated");
853
- server = https.createServer({
854
- cert,
855
- key
856
- }, this.#app);
857
- } else if (tls && "keyPath" in tls) {
858
- const currentDir = process.cwd();
859
- server = https.createServer({
860
- key: fs.readFileSync(path.join(currentDir, tls.keyPath)),
861
- cert: fs.readFileSync(path.join(currentDir, tls.certPath))
862
- }, this.#app);
863
- } else if (tls && "cert" in tls) server = https.createServer({
864
- cert: tls.cert,
865
- key: tls.key
866
- }, this.#app);
867
- else server = http.createServer(this.#app);
868
- return new Promise((resolve, reject) => {
869
- server.once("error", reject);
870
- server.listen(port, () => {
871
- server.off("error", reject);
872
- resolve(server);
873
- });
874
- });
875
- }
876
- #serveFetchHandler(handler, req, res, next) {
877
- const url = `${req.protocol}://${req.get("host") ?? "localhost"}${req.originalUrl}`;
878
- const headers = new Headers();
879
- for (const [key, value] of Object.entries(req.headers)) if (typeof value === "string") headers.set(key, value);
880
- else if (Array.isArray(value)) headers.set(key, value.join(", "));
881
- let body;
882
- if (req.method !== "GET" && req.method !== "HEAD" && req.body !== void 0) body = JSON.stringify(req.body);
883
- const fetchRequest = new Request(url, {
884
- method: req.method,
885
- headers,
886
- body
887
- });
888
- Promise.resolve(handler(fetchRequest)).then(async (response) => {
889
- res.status(response.status);
890
- response.headers.forEach((value, key) => {
891
- res.setHeader(key, value);
892
- });
893
- const responseBody = await response.text();
894
- res.send(responseBody);
895
- }).catch(next);
896
- }
897
- };
898
- function createExpressHttpAdapter(existingApp) {
899
- return { adapter: new ExpressHttpAdapter(existingApp) };
900
521
  }
901
- //#endregion
902
- //#region src/graphql/gateway/adapter-http-fastify.ts
903
- /**
904
- * Normalises a route path for path-to-regexp v8:
905
- * - Collapses duplicate slashes (e.g. "//explorer" → "/explorer")
906
- * - Converts legacy optional-param syntax ":param?" → "{/:param}?"
907
- */
908
- function normalizePath(path) {
909
- return path.replace(/\/+/g, "/").replace(/:(\w+)\?/g, "{/:$1}");
910
- }
911
- /** Parses body-limit strings like "50mb" to bytes. */
912
- function parseBodyLimit(limit) {
913
- const m = /^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb)?$/i.exec(limit.trim());
914
- if (!m) return 52428800;
915
- const n = parseFloat(m[1]);
916
- return Math.round(n * ({
917
- b: 1,
918
- kb: 1024,
919
- mb: 1048576,
920
- gb: 1073741824
921
- }[(m[2] ?? "b").toLowerCase()] ?? 1));
922
- }
923
- var FastifyHttpAdapter = class {
924
- #fetchRoutes = [];
925
- #getRoutes = /* @__PURE__ */ new Map();
926
- #nodeRoutes = [];
927
- #setupOps = [];
928
- #instance;
929
- get handle() {
930
- return this.#instance;
931
- }
932
- setupMiddleware({ corsOptions, bodyLimit = "50mb" }) {
933
- this.#setupOps.push({
934
- kind: "cors",
935
- options: corsOptions,
936
- bodyLimit: parseBodyLimit(bodyLimit)
937
- });
938
- }
939
- mount(path, handler, { exact = false } = {}) {
940
- this.#fetchRoutes.push({
941
- handler,
942
- matcher: match(normalizePath(path), { end: !exact }),
943
- prefix: exact
944
- });
945
- }
946
- getRoute(path, handler) {
947
- this.#getRoutes.set(path, {
948
- handler,
949
- matcher: match(normalizePath(path))
950
- });
951
- }
952
- mountNodeRoute(method, path, handler) {
953
- this.#nodeRoutes.push({
954
- method,
955
- matcher: match(normalizePath(path)),
956
- handler
957
- });
958
- }
959
- mountRawMiddleware(middleware) {
960
- if (this.#instance) this.#instance.use(middleware);
961
- else this.#setupOps.push({
962
- kind: "middie",
963
- middleware
964
- });
965
- }
966
- setupSentryErrorHandler(sentry) {
967
- if (!this.#instance) return;
968
- sentry.setupFastifyErrorHandler(this.#instance);
969
- }
970
- async listen(port, tls) {
971
- let httpServer;
972
- if (tls === true) {
973
- const { cert, key } = await devcert.certificateFor("localhost");
974
- if (!cert || !key) throw new Error("Invalid certificate generated");
975
- httpServer = https.createServer({
976
- cert,
977
- key
978
- });
979
- } else if (tls && "keyPath" in tls) {
980
- const cwd = process.cwd();
981
- httpServer = https.createServer({
982
- key: fs.readFileSync(path.join(cwd, tls.keyPath)),
983
- cert: fs.readFileSync(path.join(cwd, tls.certPath))
984
- });
985
- } else if (tls && "cert" in tls) httpServer = https.createServer({
986
- cert: tls.cert,
987
- key: tls.key
988
- });
989
- else httpServer = http.createServer();
990
- const instance = Fastify({
991
- serverFactory: (handler) => {
992
- httpServer.on("request", handler);
993
- return httpServer;
994
- },
995
- bodyLimit: this.#setupOps.find((op) => op.kind === "cors")?.bodyLimit ?? 52428800,
996
- logger: false
997
- });
998
- this.#instance = instance;
999
- await instance.register(fastifyMiddie);
1000
- await instance.register(fastifyFormbody);
1001
- for (const op of this.#setupOps) if (op.kind === "cors") await instance.register(fastifyCors, op.options);
1002
- else instance.use(op.middleware);
1003
- instance.route({
1004
- method: [
1005
- "DELETE",
1006
- "GET",
1007
- "HEAD",
1008
- "PATCH",
1009
- "POST",
1010
- "PUT"
1011
- ],
1012
- url: "/*",
1013
- handler: (req, reply) => this.#dispatch(req, reply)
1014
- });
1015
- await instance.ready();
1016
- return new Promise((resolve, reject) => {
1017
- httpServer.once("error", reject);
1018
- httpServer.listen(port, () => {
1019
- httpServer.off("error", reject);
1020
- resolve(httpServer);
1021
- });
1022
- });
1023
- }
1024
- #dispatch(req, reply) {
1025
- const pathname = new URL(req.url, "http://localhost").pathname;
1026
- const method = req.method.toUpperCase();
1027
- for (const entry of this.#nodeRoutes) {
1028
- if (entry.method !== method) continue;
1029
- const result = entry.matcher(pathname);
1030
- if (!result) continue;
1031
- req.raw.params = result.params;
1032
- reply.hijack();
1033
- entry.handler(req.raw, reply.raw, req.body);
1034
- return;
1035
- }
1036
- if (method === "GET") {
1037
- for (const entry of this.#getRoutes.values()) if (entry.matcher(pathname)) return this.#serveGetEntry(entry, req, reply);
522
+ async function createHttpAdapter(type) {
523
+ switch (type) {
524
+ case "express": {
525
+ const { createExpressHttpAdapter } = await import("./adapter-http-express-DO4ui7AV.mjs");
526
+ return createExpressHttpAdapter();
1038
527
  }
1039
- for (let i = this.#fetchRoutes.length - 1; i >= 0; i--) {
1040
- const entry = this.#fetchRoutes[i];
1041
- if (entry.matcher(pathname)) return serveFetchHandler(entry.handler, req, reply);
528
+ case "fastify": {
529
+ const { createFastifyHttpAdapter } = await import("./adapter-http-fastify-B248RJtm.mjs");
530
+ return createFastifyHttpAdapter();
1042
531
  }
1043
- reply.status(404).send({
1044
- message: `Route ${req.method}:${pathname} not found`,
1045
- error: "Not Found",
1046
- statusCode: 404
1047
- });
1048
- }
1049
- async #serveGetEntry(entry, req, reply) {
1050
- const url = buildUrl(req);
1051
- const headers = buildHeaders(req);
1052
- const fetchReq = new Request(url, {
1053
- method: "GET",
1054
- headers
1055
- });
1056
- const response = await entry.handler(fetchReq);
1057
- writeResponse(reply, response);
1058
- return reply.send(await response.text());
1059
- }
1060
- };
1061
- async function serveFetchHandler(handler, req, reply) {
1062
- const url = buildUrl(req);
1063
- const headers = buildHeaders(req);
1064
- let body;
1065
- if (req.method !== "GET" && req.method !== "HEAD" && req.body !== void 0) body = JSON.stringify(req.body);
1066
- const response = await handler(new Request(url, {
1067
- method: req.method,
1068
- headers,
1069
- body
1070
- }));
1071
- writeResponse(reply, response);
1072
- return reply.send(await response.text());
1073
- }
1074
- function buildUrl(req) {
1075
- const host = req.headers.host ?? "localhost";
1076
- return `${req.protocol}://${host}${req.url}`;
1077
- }
1078
- function buildHeaders(req) {
1079
- const headers = new Headers();
1080
- for (const [key, value] of Object.entries(req.headers)) if (typeof value === "string") headers.set(key, value);
1081
- else if (Array.isArray(value)) headers.set(key, value.join(", "));
1082
- return headers;
1083
- }
1084
- function writeResponse(reply, response) {
1085
- reply.status(response.status);
1086
- response.headers.forEach((value, key) => {
1087
- reply.header(key, value);
1088
- });
1089
- }
1090
- function createFastifyHttpAdapter() {
1091
- return { adapter: new FastifyHttpAdapter() };
1092
- }
1093
- //#endregion
1094
- //#region src/graphql/gateway/factory.ts
1095
- function createGatewayAdapter(type, logger) {
1096
- switch (type) {
1097
- case "apollo": return new ApolloGatewayAdapter(logger);
1098
- case "mercurius": return new MercuriusGatewayAdapter(logger);
1099
- }
1100
- }
1101
- function createHttpAdapter(type) {
1102
- switch (type) {
1103
- case "express": return createExpressHttpAdapter();
1104
- case "fastify": return createFastifyHttpAdapter();
1105
532
  }
1106
533
  }
1107
534
  //#endregion
@@ -3837,7 +3264,7 @@ var GraphQLManager = class {
3837
3264
  await this.updateRouter();
3838
3265
  this.logger.info("Regenerated document model subgraphs with @count models", models.length);
3839
3266
  } catch (error) {
3840
- this.logger.error("Failed to regenerate document model subgraphs", error);
3267
+ this.logger.error("Failed to regenerate document model subgraphs: @error", error);
3841
3268
  throw error;
3842
3269
  }
3843
3270
  }
@@ -3921,7 +3348,7 @@ var GraphQLManager = class {
3921
3348
  await this.gatewayAdapter.updateSupergraph();
3922
3349
  this.logger.debug("Updated Apollo Gateway supergraph");
3923
3350
  } catch (error) {
3924
- this.logger.error("Failed to update Apollo Gateway supergraph", error);
3351
+ this.logger.error("Failed to update Apollo Gateway supergraph: @error", error);
3925
3352
  }
3926
3353
  const superGraphPath = path.join(this.path, "graphql");
3927
3354
  this.#setupSupergraphSSE(superGraphPath);
@@ -4159,16 +3586,16 @@ var PackagesSubgraph = class extends BaseSubgraph {
4159
3586
  try {
4160
3587
  return await installedPackages(this.packageManagementService);
4161
3588
  } catch (error) {
4162
- this.logger.error("Error in installedPackages:", error);
3589
+ this.logger.error("Error in installedPackages: @error", error);
4163
3590
  throw error;
4164
3591
  }
4165
3592
  },
4166
3593
  installedPackage: async (_parent, args) => {
4167
- this.logger.debug("installedPackage", args);
3594
+ this.logger.debug("installedPackage(@args)", args);
4168
3595
  try {
4169
3596
  return await installedPackage(this.packageManagementService, args);
4170
3597
  } catch (error) {
4171
- this.logger.error("Error in installedPackage:", error);
3598
+ this.logger.error("Error in installedPackage: @error", error);
4172
3599
  throw error;
4173
3600
  }
4174
3601
  }
@@ -4176,20 +3603,20 @@ var PackagesSubgraph = class extends BaseSubgraph {
4176
3603
  Mutation: { Packages: () => ({}) },
4177
3604
  PackagesMutations: {
4178
3605
  installPackage: async (_parent, args, ctx) => {
4179
- this.logger.debug("installPackage", args);
3606
+ this.logger.debug("installPackage(@args)", args);
4180
3607
  try {
4181
3608
  return await installPackage(this.packageManagementService, args, ctx);
4182
3609
  } catch (error) {
4183
- this.logger.error("Error in installPackage:", error);
3610
+ this.logger.error("Error in installPackage: @error", error);
4184
3611
  throw error;
4185
3612
  }
4186
3613
  },
4187
3614
  uninstallPackage: async (_parent, args, ctx) => {
4188
- this.logger.debug("uninstallPackage", args);
3615
+ this.logger.debug("uninstallPackage(@args)", args);
4189
3616
  try {
4190
3617
  return await uninstallPackage(this.packageManagementService, args, ctx);
4191
3618
  } catch (error) {
4192
- this.logger.error("Error in uninstallPackage:", error);
3619
+ this.logger.error("Error in uninstallPackage: @error", error);
4193
3620
  throw error;
4194
3621
  }
4195
3622
  }
@@ -4758,7 +4185,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
4758
4185
  hasMore
4759
4186
  };
4760
4187
  } catch (error) {
4761
- this.logger.error("Error in pollSyncEnvelopes(@args): @Error", error);
4188
+ this.logger.error("Error in pollSyncEnvelopes(@args): @Error", args, error);
4762
4189
  throw error;
4763
4190
  }
4764
4191
  }
@@ -4778,7 +4205,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
4778
4205
  if (this.authorizationService && ctx.user?.address && result?.id) await this.documentPermissionService?.initializeDocumentProtection(result.id, ctx.user.address, this.authorizationService.config.defaultProtection);
4779
4206
  return result;
4780
4207
  } catch (error) {
4781
- this.logger.error("Error in createDocument(@args): @Error", error);
4208
+ this.logger.error("Error in createDocument(@args): @Error", args, error);
4782
4209
  throw error;
4783
4210
  }
4784
4211
  },
@@ -4796,7 +4223,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
4796
4223
  if (this.authorizationService && ctx.user?.address && result?.id) await this.documentPermissionService?.initializeDocumentProtection(result.id, ctx.user.address, this.authorizationService.config.defaultProtection);
4797
4224
  return result;
4798
4225
  } catch (error) {
4799
- this.logger.error("Error in createEmptyDocument(@args): @Error", error);
4226
+ this.logger.error("Error in createEmptyDocument(@args): @Error", args, error);
4800
4227
  throw error;
4801
4228
  }
4802
4229
  },
@@ -4807,7 +4234,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
4807
4234
  await this.assertCanExecuteOperations(args.documentIdentifier, args.actions, ctx);
4808
4235
  return await mutateDocument(this.reactorClient, args);
4809
4236
  } catch (error) {
4810
- this.logger.error("Error in mutateDocument(@args): @Error", error);
4237
+ this.logger.error("Error in mutateDocument(@args): @Error", args, error);
4811
4238
  throw error;
4812
4239
  }
4813
4240
  },
@@ -4818,7 +4245,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
4818
4245
  await this.assertCanExecuteOperations(args.documentIdentifier, args.actions, ctx);
4819
4246
  return await mutateDocumentAsync(this.reactorClient, args);
4820
4247
  } catch (error) {
4821
- this.logger.error("Error in mutateDocumentAsync(@args): @Error", error);
4248
+ this.logger.error("Error in mutateDocumentAsync(@args): @Error", args, error);
4822
4249
  throw error;
4823
4250
  }
4824
4251
  },
@@ -4828,7 +4255,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
4828
4255
  await this.assertCanWrite(args.documentIdentifier, ctx);
4829
4256
  return await renameDocument(this.reactorClient, args);
4830
4257
  } catch (error) {
4831
- this.logger.error("Error in renameDocument(@args): @Error", error);
4258
+ this.logger.error("Error in renameDocument(@args): @Error", args, error);
4832
4259
  throw error;
4833
4260
  }
4834
4261
  },
@@ -4838,7 +4265,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
4838
4265
  await this.assertCanWrite(args.documentIdentifier, ctx);
4839
4266
  return await setPreferredEditor(this.reactorClient, args);
4840
4267
  } catch (error) {
4841
- this.logger.error("Error in setPreferredEditor(@args): @Error", error);
4268
+ this.logger.error("Error in setPreferredEditor(@args): @Error", args, error);
4842
4269
  throw error;
4843
4270
  }
4844
4271
  },
@@ -4848,7 +4275,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
4848
4275
  await this.assertCanWrite(args.sourceIdentifier, ctx);
4849
4276
  return await addRelationship(this.reactorClient, args);
4850
4277
  } catch (error) {
4851
- this.logger.error("Error in addRelationship(@args): @Error", error);
4278
+ this.logger.error("Error in addRelationship(@args): @Error", args, error);
4852
4279
  throw error;
4853
4280
  }
4854
4281
  },
@@ -4858,7 +4285,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
4858
4285
  await this.assertCanWrite(args.sourceIdentifier, ctx);
4859
4286
  return await removeRelationship(this.reactorClient, args);
4860
4287
  } catch (error) {
4861
- this.logger.error("Error in removeRelationship(@args): @Error", error);
4288
+ this.logger.error("Error in removeRelationship(@args): @Error", args, error);
4862
4289
  throw error;
4863
4290
  }
4864
4291
  },
@@ -4882,7 +4309,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
4882
4309
  if (result && driveIdToInvalidate) this.graphqlManager.driveOwnershipCache.remove(driveIdToInvalidate);
4883
4310
  return result;
4884
4311
  } catch (error) {
4885
- this.logger.error("Error in deleteDocument(@args): @Error", error);
4312
+ this.logger.error("Error in deleteDocument(@args): @Error", args, error);
4886
4313
  throw error;
4887
4314
  }
4888
4315
  },
@@ -4892,7 +4319,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
4892
4319
  for (const identifier of args.identifiers) await this.assertCanWrite(identifier, ctx);
4893
4320
  return await deleteDocuments(this.reactorClient, args);
4894
4321
  } catch (error) {
4895
- this.logger.error("Error in deleteDocuments(@args): @Error", error);
4322
+ this.logger.error("Error in deleteDocuments(@args): @Error", args, error);
4896
4323
  throw error;
4897
4324
  }
4898
4325
  },
@@ -4901,7 +4328,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
4901
4328
  try {
4902
4329
  return await touchChannel(this.syncManager, args);
4903
4330
  } catch (error) {
4904
- this.logger.error("Error in touchChannel(@args): @Error", error);
4331
+ this.logger.error("Error in touchChannel(@args): @Error", args, error);
4905
4332
  throw error;
4906
4333
  }
4907
4334
  },
@@ -4931,7 +4358,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
4931
4358
  })) };
4932
4359
  return await pushSyncEnvelopes(this.syncManager, mutableArgs);
4933
4360
  } catch (error) {
4934
- this.logger.error("Error in pushSyncEnvelopes(@args): @Error", error);
4361
+ this.logger.error("Error in pushSyncEnvelopes(@args): @Error", args, error);
4935
4362
  throw error;
4936
4363
  }
4937
4364
  }
@@ -4939,7 +4366,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
4939
4366
  Subscription: {
4940
4367
  documentChanges: {
4941
4368
  subscribe: withFilter((() => {
4942
- this.logger.debug("documentChanges(@args) subscription started");
4369
+ this.logger.debug("documentChanges subscription started");
4943
4370
  ensureGlobalDocumentSubscription(this.reactorClient);
4944
4371
  return getPubSub().asyncIterableIterator(SUBSCRIPTION_TRIGGERS.DOCUMENT_CHANGES);
4945
4372
  }), ((payload, args) => {
@@ -4986,10 +4413,10 @@ const ADMIN_USERS = getAdminUsers();
4986
4413
  //#endregion
4987
4414
  //#region src/graphql/system/version.ts
4988
4415
  function getVersion() {
4989
- return "6.0.2-staging.9";
4416
+ return "6.1.0-dev.0";
4990
4417
  }
4991
4418
  function getGitHash() {
4992
- return "409a67a6d3aa6be3f6700dc0ae2045ecd8556e74";
4419
+ return "13db8e511349eed4c0973adf153cc9ace7c0b3aa";
4993
4420
  }
4994
4421
  function getGitUrl() {
4995
4422
  return buildTreeUrl(getGitHash());
@@ -5266,7 +4693,7 @@ var PackageManager = class {
5266
4693
  try {
5267
4694
  this.subscribePackages(packages);
5268
4695
  } catch (error) {
5269
- this.logger.error("Failed to subscribe to packages", error);
4696
+ this.logger.error("Failed to subscribe to packages: @error", error);
5270
4697
  }
5271
4698
  return {
5272
4699
  documentModels: getUniqueDocumentModels(...Array.from(documentModelsMap.values())),
@@ -6160,7 +5587,30 @@ function isPG(connectionString) {
6160
5587
  if (connectionString.startsWith("postgresql://") || connectionString.startsWith("postgres://")) return true;
6161
5588
  return false;
6162
5589
  }
5590
+ /**
5591
+ * Cache of DB clients keyed by connection string. Reactor-api's read-model
5592
+ * layer wires analytics, attachments, and document-permissions as separate
5593
+ * consumers but they all target the same logical database (one postgres
5594
+ * instance, many schemas). Without caching:
5595
+ * - PGlite: two `new PGlite(samePath)` calls mean two embedded postgres
5596
+ * processes contending for the same data dir, racing shutdown syncs
5597
+ * and silently losing writes — a correctness bug.
5598
+ * - Postgres: each consumer opens an independent pool against the same
5599
+ * backend — wasteful but correct.
5600
+ * Caching by connection string returns the same knex/PGlite pair to every
5601
+ * consumer so writes coexist in one MemoryFS and one atomic snapshot, and
5602
+ * postgres callers get connection-pool dedup for free.
5603
+ *
5604
+ * Entries are evicted from inside the wrapped `knex.destroy()` below, so a
5605
+ * teardown + re-init in the same process (tests, hot-reloads) constructs
5606
+ * a fresh client instead of returning a closed pool.
5607
+ */
5608
+ const IN_MEMORY_CACHE_KEY = Symbol("getDbClient:in-memory");
5609
+ const dbClientCache = /* @__PURE__ */ new Map();
6163
5610
  function getDbClient(connectionString = void 0, pgliteFactory) {
5611
+ const cacheKey = connectionString ?? IN_MEMORY_CACHE_KEY;
5612
+ const cached = dbClientCache.get(cacheKey);
5613
+ if (cached) return cached;
6164
5614
  const isPg = connectionString && isPG(connectionString);
6165
5615
  const client = isPg ? "pg" : ClientPgLite;
6166
5616
  const pgliteInstance = isPg ? void 0 : pgliteFactory ? pgliteFactory(connectionString) : connectionString ? new PGlite({ fs: new AtomicNodeFs(connectionString) }) : new PGlite();
@@ -6173,7 +5623,7 @@ function getDbClient(connectionString = void 0, pgliteFactory) {
6173
5623
  client,
6174
5624
  connection
6175
5625
  });
6176
- return {
5626
+ const dbClient = {
6177
5627
  db: new Kysely({ dialect: new KyselyKnexDialect({
6178
5628
  knex: knexInstance,
6179
5629
  kyselySubDialect: new PGColdDialect()
@@ -6181,6 +5631,17 @@ function getDbClient(connectionString = void 0, pgliteFactory) {
6181
5631
  knex: knexInstance,
6182
5632
  pglite: pgliteInstance
6183
5633
  };
5634
+ const originalDestroy = knexInstance.destroy.bind(knexInstance);
5635
+ Object.defineProperty(knexInstance, "destroy", {
5636
+ configurable: true,
5637
+ writable: true,
5638
+ value: async (...args) => {
5639
+ if (dbClientCache.get(cacheKey) === dbClient) dbClientCache.delete(cacheKey);
5640
+ return originalDestroy(...args);
5641
+ }
5642
+ });
5643
+ dbClientCache.set(cacheKey, dbClient);
5644
+ return dbClient;
6184
5645
  }
6185
5646
  const initAnalyticsStoreSql = [
6186
5647
  `create table if not exists "AnalyticsSeries"
@@ -6285,7 +5746,7 @@ function makeDbClosers(knexInstance, pglite) {
6285
5746
  * Sets up the subgraph manager and registers subgraphs
6286
5747
  */
6287
5748
  async function setupGraphQLManager(httpAdapter, authFetchMiddleware, httpServer, wsServer, client, relationalDb, analyticsStore, syncManager, subgraphs, logger, auth, documentPermissionService, enableDocumentModelSubgraphs, port, authorizationService, reactorDriveClient) {
6288
- const graphqlManager = new GraphQLManager(config.basePath, httpServer, wsServer, client, relationalDb, analyticsStore, syncManager, logger, httpAdapter, createGatewayAdapter("apollo", logger), {
5749
+ const graphqlManager = new GraphQLManager(config.basePath, httpServer, wsServer, client, relationalDb, analyticsStore, syncManager, logger, httpAdapter, await createGatewayAdapter("apollo", logger), {
6289
5750
  enabled: auth?.enabled ?? false,
6290
5751
  admins: auth?.admins ?? []
6291
5752
  }, documentPermissionService, { enableDocumentModelSubgraphs }, port, authorizationService, reactorDriveClient);
@@ -6357,7 +5818,7 @@ async function startServer(httpAdapter, port, httpsOptions, logger) {
6357
5818
  */
6358
5819
  async function _setupCommonInfrastructure(options) {
6359
5820
  const port = options.port ?? DEFAULT_PORT;
6360
- const { adapter: httpAdapter } = createHttpAdapter("express");
5821
+ const { adapter: httpAdapter } = await createHttpAdapter("express");
6361
5822
  let admins = [];
6362
5823
  let authEnabled = false;
6363
5824
  if (options.configFile) {
@@ -6541,24 +6002,24 @@ function buildApiDispose(args) {
6541
6002
  try {
6542
6003
  await graphqlManager.shutdown();
6543
6004
  } catch (error) {
6544
- logger.error("API dispose: graphqlManager.shutdown failed:", error);
6005
+ logger.error("API dispose: graphqlManager.shutdown failed: @error", error);
6545
6006
  }
6546
6007
  try {
6547
6008
  for (const client of wsServer.clients) client.terminate();
6548
6009
  await new Promise((resolve) => wsServer.close(() => resolve()));
6549
6010
  } catch (error) {
6550
- logger.error("API dispose: wsServer.close failed:", error);
6011
+ logger.error("API dispose: wsServer.close failed: @error", error);
6551
6012
  }
6552
6013
  if (httpServer.listening) try {
6553
6014
  httpServer.closeAllConnections();
6554
6015
  await new Promise((resolve, reject) => httpServer.close((err) => err ? reject(err) : resolve()));
6555
6016
  } catch (error) {
6556
- logger.error("API dispose: httpServer.close failed:", error);
6017
+ logger.error("API dispose: httpServer.close failed: @error", error);
6557
6018
  }
6558
6019
  for (const close of dbClosers) try {
6559
6020
  await close();
6560
6021
  } catch (error) {
6561
- logger.error("API dispose: db closer failed:", error);
6022
+ logger.error("API dispose: db closer failed: @error", error);
6562
6023
  }
6563
6024
  };
6564
6025
  }
@@ -6683,4 +6144,4 @@ var PackageManagementService = class {
6683
6144
  export { ADMIN_USERS, ActionContextInputSchema, ActionInputSchema, AddRelationshipDocument, AnalyticsSubgraph, AttachmentInputSchema, AuthService, AuthSubgraph, BaseSubgraph, ChannelMetaInputSchema, CreateDocumentDocument, CreateEmptyDocumentDocument, DeleteDocumentDocument, DeleteDocumentsDocument, DocumentChangeType, DocumentChangeTypeSchema, DocumentChangesDocument, DocumentOperationsFilterInputSchema, DocumentPermissionService, FindDocumentsDocument, GetDocumentDocument, GetDocumentIncomingRelationshipsDocument, GetDocumentModelsDocument, GetDocumentOperationsDocument, GetDocumentOutgoingRelationshipsDocument, GetDocumentWithOperationsDocument, GetJobStatusDocument, GraphQLManager, HttpDocumentModelLoader, HttpPackageLoader, ImportPackageLoader, InMemoryPackageStorage, JobChangesDocument, MoveRelationshipDocument, MutateDocumentAsyncDocument, MutateDocumentDocument, OperationContextInputSchema, OperationInputSchema, OperationWithContextInputSchema, OperationsFilterInputSchema, PackageManagementService, PackageManager, PackagesSubgraph, PagingInputSchema, PhDocumentFieldsFragmentDoc, PollSyncEnvelopesDocument, PropagationMode, PropagationModeSchema, PushSyncEnvelopesDocument, ReactorSignerAppInputSchema, ReactorSignerInputSchema, ReactorSignerUserInputSchema, ReactorSubgraph, RemoteCursorInputSchema, RemoteFilterInputSchema, RemoveRelationshipDocument, RenameDocumentDocument, SearchFilterInputSchema, SetPreferredEditorDocument, SyncEnvelopeInputSchema, SyncEnvelopeType, SyncEnvelopeTypeSchema, SystemSubgraph, TouchChannelDocument, TouchChannelInputSchema, ViewFilterInputSchema, buildGraphQlDocument, buildGraphQlDriveDocument, buildGraphqlOperation, buildGraphqlOperations, buildSubgraphSchemaModule, createAuthFetchMiddleware, createGatewayAdapter, createHttpAdapter, createMergedSchema, createReactorGraphQLClient, createSchema, definedNonNullAnySchema, driveIdFromUrl, generateDocumentModelSchema, getAuthContext, getDbClient, getDocumentModelSchemaName, getDocumentModelTypeDefs, getGitHash, getGitUrl, getSdk, getUniqueDocumentModels, getVersion, initAnalyticsStoreSql, initializeAndStartAPI, isDefinedNonNullAny, isSubgraphClass, parseDriveUrl, renderGraphqlPlayground };
6684
6145
 
6685
6146
  //# sourceMappingURL=index.mjs.map
6686
- //# debugId=def0f6e3-b149-5760-8c0c-611814c2a321
6147
+ //# debugId=54de2de8-0918-5f80-961f-f2a72e390510