@powerhousedao/reactor-api 6.2.3-dev.54 → 6.2.3-dev.56

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/dist/{adapter-gateway-apollo-D2DNlPY0.mjs → adapter-gateway-apollo-DTcAJpfN.mjs} +3 -3
  2. package/dist/{adapter-gateway-apollo-B54G_cXT.mjs → adapter-gateway-apollo-DwAmdCYz.mjs} +5 -5
  3. package/dist/{adapter-gateway-apollo-B54G_cXT.mjs.map → adapter-gateway-apollo-DwAmdCYz.mjs.map} +1 -1
  4. package/dist/{adapter-gateway-mercurius-rbKlwF9m.mjs → adapter-gateway-mercurius-BhO0nwH_.mjs} +4 -4
  5. package/dist/{adapter-gateway-mercurius-rbKlwF9m.mjs.map → adapter-gateway-mercurius-BhO0nwH_.mjs.map} +1 -1
  6. package/dist/adapter-gateway-stitching-969ZPot-.mjs +4 -0
  7. package/dist/{adapter-gateway-stitching-Dzv10u8D.mjs → adapter-gateway-stitching-ClVkjojb.mjs} +20 -8
  8. package/dist/adapter-gateway-stitching-ClVkjojb.mjs.map +1 -0
  9. package/dist/base-document-models-69WRTSfH.mjs +1243 -0
  10. package/dist/base-document-models-69WRTSfH.mjs.map +1 -0
  11. package/dist/create-schema-DLTPkNpK.d.mts +138 -0
  12. package/dist/create-schema-DLTPkNpK.d.mts.map +1 -0
  13. package/dist/index.d.mts +57 -46
  14. package/dist/index.d.mts.map +1 -1
  15. package/dist/index.mjs +936 -1168
  16. package/dist/index.mjs.map +1 -1
  17. package/dist/src/graphql/subgraph-types.d.mts +37 -0
  18. package/dist/src/graphql/subgraph-types.d.mts.map +1 -0
  19. package/dist/src/graphql/subgraph-types.mjs +105 -0
  20. package/dist/src/graphql/subgraph-types.mjs.map +1 -0
  21. package/dist/src/packages/vite-loader.d.mts +3 -2
  22. package/dist/src/packages/vite-loader.d.mts.map +1 -1
  23. package/dist/src/packages/vite-loader.mjs +20 -22
  24. package/dist/src/packages/vite-loader.mjs.map +1 -1
  25. package/dist/{subgraph-extraction-sQlZLLPH.mjs → subgraph-extraction-CPtTeQAT.mjs} +44 -10
  26. package/dist/subgraph-extraction-CPtTeQAT.mjs.map +1 -0
  27. package/dist/{types-DlTiz6AA.d.mts → types-D3pD6fvQ.d.mts} +15 -3
  28. package/dist/types-D3pD6fvQ.d.mts.map +1 -0
  29. package/package.json +18 -13
  30. package/dist/adapter-gateway-stitching-Dzv10u8D.mjs.map +0 -1
  31. package/dist/subgraph-extraction-sQlZLLPH.mjs.map +0 -1
  32. package/dist/types-DlTiz6AA.d.mts.map +0 -1
package/dist/index.mjs CHANGED
@@ -1,16 +1,19 @@
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]="980be7cc-16d9-5965-b60e-0c7ca7a4e3c8")}catch(e){}}();
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]="5a6cd51c-1122-5d95-9bcf-8cf26e403d05")}catch(e){}}();
3
3
  import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.mjs";
4
- import { A as AuthenticationRequiredError, C as callerSubject, D as AuthorizedDocumentHandle, E as AuthorizationPolicy, M as MalformedStoredOperationError, N as RefusalNotRecordedError, O as createAuthorizationService, S as BaseSubgraph, T as createCanonicalDocumentIdResolver, b as loadSubgraphs, c as piecesFromListModule, d as buildGraphQlDriveDocument, f as buildGraphqlOperation, g as extractUpgradeManifests, h as debounce, i as PIECE_SOURCE_LIST, j as ForbiddenError, k as AuthEvaluationUnsupportedError, l as extractDocumentModels, m as isSubgraphClass, o as pieceListLocation, p as buildGraphqlOperations, s as piecesFromCdnList, t as extractSubgraphs, u as buildGraphQlDocument, v as loadDocumentModels, w as CanonicalDocumentIdResolutionError, x as manifestDeclaredSubgraphs, y as loadProcessors } from "./subgraph-extraction-sQlZLLPH.mjs";
4
+ import { A as createAuthorizationService, C as manifestDeclaredSubgraphs, D as createCanonicalDocumentIdResolver, E as CanonicalDocumentIdResolutionError, F as RefusalNotRecordedError, M as AuthenticationRequiredError, N as ForbiddenError, O as AuthorizationPolicy, P as MalformedStoredOperationError, S as loadSubgraphs, T as callerSubject, _ as debounce, b as loadDocumentModels, c as piecesFromListModule, d as buildGraphQlDriveDocument, f as buildGraphqlOperation, g as runDetached, h as reportFailure, i as PIECE_SOURCE_LIST, j as AuthEvaluationUnsupportedError, k as AuthorizedDocumentHandle, l as extractDocumentModels, m as isSubgraphClass, o as pieceListLocation, p as buildGraphqlOperations, s as piecesFromCdnList, t as extractSubgraphs, u as buildGraphQlDocument, v as extractUpgradeManifests, w as BaseSubgraph, x as loadProcessors } from "./subgraph-extraction-CPtTeQAT.mjs";
5
+ import { C as hasOperationSchemas, D as schema_default$1, E as typeDefinitionNames, S as getGeneratedDocumentModelTypes, T as reservedTypeNamesTaken, _ as generateDocumentModelSchema, a as collectSubgraphClaims, b as getDocumentModelSubgraphName, c as DocumentModelSchemaCache, d as buildDocumentModelSchema, f as buildSubgraphSchemaModule, g as findSubgraphTypeCollisions, h as documentModelSubgraphTypes, i as inspectionTypeDefs, l as SubgraphTypeCollisionError, m as createSchema, n as systemTypeDefs, o as describeOwnershipConflicts, p as createMergedSchema, r as schema_default$2, s as resolveClaimOwnership, t as baseDocumentModels, u as assembleSubgraphTypeDefs, v as generatedTypesOf, w as reservedTypeNames, x as getDocumentModelTypeDefs, y as getDocumentModelSchemaName } from "./base-document-models-69WRTSfH.mjs";
6
+ import { n as filterBuildableSubgraphs, r as mergeSubgraphSchemas } from "./adapter-gateway-stitching-ClVkjojb.mjs";
5
7
  import { l as createDurableNodeFs, n as openCurrentPgliteForVerify, r as preparePgliteDataDir, u as resolvePgliteFsync } from "./pglite-node-Ow9i5Rb4.mjs";
6
8
  import { findPackageJSON, isBuiltin } from "node:module";
7
9
  import { AnalyticsQueryEngine } from "@powerhousedao/analytics-engine-core";
8
10
  import { AnalyticsModel, AnalyticsResolvers, typedefs } from "@powerhousedao/analytics-engine-graphql";
9
11
  import { gql } from "graphql-tag";
10
- import { GraphQLError, Kind, Lexer, OperationTypeNode, Source, TokenKind, parse, print, valueFromASTUntyped, visit } from "graphql";
12
+ import { GraphQLError, Kind, OperationTypeNode, parse, print, valueFromASTUntyped, visit } from "graphql";
11
13
  import { AuthEnforcementDisabledError, BareReadGate, BatchJobFailedError, ChannelError, ChannelErrorSource, DEFAULT_DRIVE_CONTAINER_TYPES, DriveCollectionId, DriveInspection, InvalidDeadLetterCursorError, JOB_NOT_FOUND_ERROR_NAME, JobStatus, ModelReadGate, PropagationMode as PropagationMode$1, READ_ONLY_ACCESS, SyncOperation, SyncScopeGate, consolidateSyncOperations, createReactorHostModuleBase, createReactorInspector, driveIdFromUrl, envelopesToSyncOperations, parseDriveUrl, readDecisionModel, supportsPurgeRefusals, syncOperationErrorType, toWireDeadLetter, toWireQueueState } from "@powerhousedao/reactor";
12
14
  import { deserializeSignature, readPeerManifest, serializeSignature, setName, withSignaturePolicy } from "@powerhousedao/shared/document-model";
13
- import { ConsoleLogger, childLogger, documentModelDocumentModelModule } from "document-model";
15
+ import { ConsoleLogger, childLogger } from "document-model";
16
+ import { AsyncLocalStorage } from "node:async_hooks";
14
17
  import path, { isAbsolute, join } from "node:path";
15
18
  import { match } from "path-to-regexp";
16
19
  import posix from "node:path/posix";
@@ -19,10 +22,7 @@ import nodeFs, { existsSync, readFileSync, watchFile } from "node:fs";
19
22
  import { pipeline } from "node:stream/promises";
20
23
  import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
21
24
  import { pathToFileURL } from "node:url";
22
- import { buildSubgraphSchema } from "@apollo/subgraph";
23
- import { typeDefs } from "@powerhousedao/document-engineering/graphql";
24
- import { camelCase, kebabCase, pascalCase } from "change-case";
25
- import { GraphQLJSON, GraphQLJSONObject } from "graphql-type-json";
25
+ import { camelCase } from "change-case";
26
26
  import * as z$1 from "zod";
27
27
  import { z } from "zod";
28
28
  import { createHandler } from "graphql-sse/lib/use/fetch";
@@ -33,9 +33,6 @@ import { buildTreeUrl } from "@powerhousedao/shared";
33
33
  import { init, parse as parse$1 } from "es-module-lexer";
34
34
  import { chmod, lstat, mkdir, readFile, readdir, readlink, realpath, rename, rm, stat, symlink, writeFile } from "node:fs/promises";
35
35
  import { getConfig } from "@powerhousedao/config/node";
36
- import { reactorDriveDocumentModelModule } from "@powerhousedao/reactor-drive";
37
- import { ReactorGroupV1 } from "@powerhousedao/reactor-group";
38
- import { driveDocumentModelModule } from "@powerhousedao/shared/document-drive";
39
36
  import EventEmitter from "node:events";
40
37
  import { PostgresAnalyticsStore } from "@powerhousedao/analytics-engine-pg";
41
38
  import { AttachmentBuilder, AttachmentNotFound, AttachmentReferenceIndexBuilder, createRef, createS3AttachmentBackend, parseAttachmentStorageConfig, parseRef, validateReserveMetadata } from "@powerhousedao/reactor-attachments";
@@ -90,9 +87,6 @@ var AnalyticsSubgraph = class extends BaseSubgraph {
90
87
  }
91
88
  };
92
89
  //#endregion
93
- //#region src/graphql/auth/schema.graphql
94
- var schema_default$2 = "# Auth Subgraph Schema\n# Contains all document permission and authorization related types\n\nscalar DateTime\n\n# Permission levels for documents\nenum DocumentPermissionLevel {\n # Can fetch and read the document\n READ\n # Can push updates and modify the document\n WRITE\n # Can manage document permissions and settings\n ADMIN\n}\n\n# Document permission entry\ntype DocumentPermissionEntry {\n documentId: String!\n userAddress: String!\n permission: DocumentPermissionLevel!\n grantedBy: String!\n createdAt: DateTime!\n updatedAt: DateTime!\n}\n\n# Operation user permission entry\ntype OperationUserPermission {\n documentId: String!\n operationType: String!\n userAddress: String!\n grantedBy: String!\n createdAt: DateTime!\n}\n\n# Combined document access info\ntype DocumentAccessInfo {\n documentId: String!\n permissions: [DocumentPermissionEntry!]!\n}\n\n# Operation permissions info\ntype OperationPermissionsInfo {\n documentId: String!\n operationType: String!\n userPermissions: [OperationUserPermission!]!\n}\n\n# Document protection info\ntype DocumentProtectionInfo {\n documentId: String!\n protected: Boolean!\n ownerAddress: String\n}\n\ntype Query {\n # Get permissions for a document (requires ADMIN permission or global admin)\n documentAccess(\n documentIdOrSlug: String\n documentId: String @deprecated(reason: \"Use documentIdOrSlug.\")\n ): DocumentAccessInfo!\n\n # Get protection status for a document (requires ADMIN permission or global admin)\n documentProtection(\n documentIdOrSlug: String\n documentId: String @deprecated(reason: \"Use documentIdOrSlug.\")\n ): DocumentProtectionInfo!\n\n # Get all documents the current user has explicit access to\n userDocumentPermissions: [DocumentPermissionEntry!]!\n\n # Get operation permissions for a document and operation type\n # (requires ADMIN permission or global admin)\n operationPermissions(\n documentIdOrSlug: String\n documentId: String @deprecated(reason: \"Use documentIdOrSlug.\")\n operationType: String!\n ): OperationPermissionsInfo!\n\n # Check if the current user can execute a specific operation on a document\n canExecuteOperation(\n documentIdOrSlug: String\n documentId: String @deprecated(reason: \"Use documentIdOrSlug.\")\n operationType: String!\n ): Boolean!\n}\n\ntype Mutation {\n # Set document protection status (requires ADMIN permission or global admin)\n setDocumentProtection(\n documentIdOrSlug: String\n documentId: String @deprecated(reason: \"Use documentIdOrSlug.\")\n protected: Boolean!\n ): DocumentProtectionInfo!\n\n # Transfer document ownership (requires ADMIN permission or global admin)\n transferDocumentOwnership(\n documentIdOrSlug: String\n documentId: String @deprecated(reason: \"Use documentIdOrSlug.\")\n newOwnerAddress: String!\n ): DocumentProtectionInfo!\n\n # Grant a user permission on a document (requires ADMIN permission or global admin)\n grantDocumentPermission(\n documentIdOrSlug: String\n documentId: String @deprecated(reason: \"Use documentIdOrSlug.\")\n userAddress: String!\n permission: DocumentPermissionLevel!\n ): DocumentPermissionEntry!\n\n # Revoke a user's permission on a document (requires ADMIN permission or global admin)\n revokeDocumentPermission(\n documentIdOrSlug: String\n documentId: String @deprecated(reason: \"Use documentIdOrSlug.\")\n userAddress: String!\n ): Boolean!\n\n # --- Operation Permissions ---\n\n # Grant a user permission to execute an operation on a document\n grantOperationPermission(\n documentIdOrSlug: String\n documentId: String @deprecated(reason: \"Use documentIdOrSlug.\")\n operationType: String!\n userAddress: String!\n ): OperationUserPermission!\n\n # Revoke a user's permission to execute an operation\n revokeOperationPermission(\n documentIdOrSlug: String\n documentId: String @deprecated(reason: \"Use documentIdOrSlug.\")\n operationType: String!\n userAddress: String!\n ): Boolean!\n}\n";
95
- //#endregion
96
90
  //#region src/graphql/argument-aliases.ts
97
91
  /** A renamed argument given under both names, or a required one under neither. */
98
92
  var ArgumentAliasError = class extends GraphQLError {
@@ -203,7 +197,7 @@ var AuthSubgraph = class extends BaseSubgraph {
203
197
  }
204
198
  name = "auth";
205
199
  hasSubscriptions = false;
206
- typeDefs = gql(schema_default$2);
200
+ typeDefs = gql(schema_default$1);
207
201
  resolvers = {
208
202
  Query: {
209
203
  documentAccess: async (_parent, args, ctx) => {
@@ -359,15 +353,15 @@ function createAuthFetchMiddleware(authService) {
359
353
  async function createGatewayAdapter(type, logger) {
360
354
  switch (type) {
361
355
  case "apollo": {
362
- const { ApolloGatewayAdapter } = await import("./adapter-gateway-apollo-D2DNlPY0.mjs");
356
+ const { ApolloGatewayAdapter } = await import("./adapter-gateway-apollo-DTcAJpfN.mjs");
363
357
  return new ApolloGatewayAdapter(logger);
364
358
  }
365
359
  case "mercurius": {
366
- const { MercuriusGatewayAdapter } = await import("./adapter-gateway-mercurius-rbKlwF9m.mjs");
360
+ const { MercuriusGatewayAdapter } = await import("./adapter-gateway-mercurius-BhO0nwH_.mjs");
367
361
  return new MercuriusGatewayAdapter(logger);
368
362
  }
369
363
  case "stitching": {
370
- const { StitchingGatewayAdapter } = await import("./adapter-gateway-stitching-Dzv10u8D.mjs");
364
+ const { StitchingGatewayAdapter } = await import("./adapter-gateway-stitching-969ZPot-.mjs");
371
365
  return new StitchingGatewayAdapter(logger);
372
366
  }
373
367
  }
@@ -624,7 +618,7 @@ function writeError(res, status, message) {
624
618
  }
625
619
  //#endregion
626
620
  //#region src/http/route-service.ts
627
- const logger$3 = childLogger(["reactor-api", "http-routes"]);
621
+ const logger$2 = childLogger(["reactor-api", "http-routes"]);
628
622
  /** The segment package routes live under, inside the host's base path. */
629
623
  const PACKAGE_ROUTE_SEGMENT = "api";
630
624
  /** The namespace core's own subgraphs and services register under. */
@@ -719,7 +713,7 @@ var HttpRouteService = class {
719
713
  return this.scopeFor(packageKey);
720
714
  } catch (error) {
721
715
  if (!(error instanceof InvalidNamespaceError)) throw error;
722
- logger$3.warn("Package \"@package\" cannot host HTTP routes: @reason", packageKey, error.message);
716
+ logger$2.warn("Package \"@package\" cannot host HTTP routes: @reason", packageKey, error.message);
723
717
  return new UnroutableScope(packageKey, error.message);
724
718
  }
725
719
  }
@@ -826,7 +820,7 @@ var HttpScope = class {
826
820
  path: routePath,
827
821
  handles
828
822
  });
829
- logger$3.debug("Registered @route for @package", key, this.owner);
823
+ logger$2.debug("Registered @route for @package", key, this.owner);
830
824
  return {
831
825
  url: `${this.#publicUrl}${routePath}`,
832
826
  dispose: () => {
@@ -849,7 +843,7 @@ var HttpScope = class {
849
843
  transport: resolveTransport(req, this.#trustProxy)
850
844
  });
851
845
  } catch (error) {
852
- logger$3.error("Route handler failed for @package", this.owner, error);
846
+ logger$2.error("Route handler failed for @package", this.owner, error);
853
847
  writeError(res, 500, "Internal server error");
854
848
  }
855
849
  }
@@ -1129,7 +1123,7 @@ function parseWebhookBody(raw, contentType) {
1129
1123
  }
1130
1124
  //#endregion
1131
1125
  //#region src/http/webhook-service.ts
1132
- const logger$2 = childLogger(["reactor-api", "webhooks"]);
1126
+ const logger$1 = childLogger(["reactor-api", "webhooks"]);
1133
1127
  /** The flat, token-addressed path family. */
1134
1128
  const WEBHOOK_SEGMENT = "webhooks";
1135
1129
  const DEFAULT_MAX_BODY_BYTES = 1048576;
@@ -1274,7 +1268,7 @@ var WebhookService = class {
1274
1268
  raw
1275
1269
  });
1276
1270
  if (!result.ok) {
1277
- logger$2.warn("Rejected webhook delivery for @package/@endpoint: @reason", row.namespace, row.endpoint, result.reason);
1271
+ logger$1.warn("Rejected webhook delivery for @package/@endpoint: @reason", row.namespace, row.endpoint, result.reason);
1278
1272
  writeError(res, 401, "Signature verification failed");
1279
1273
  return;
1280
1274
  }
@@ -1313,7 +1307,7 @@ var WebhookService = class {
1313
1307
  if (reply.unprocessed === true && recordedKey !== void 0) try {
1314
1308
  await this.#store.forget(token, recordedKey);
1315
1309
  } catch (error) {
1316
- logger$2.warn("Could not forget an unprocessed webhook delivery: @error", error);
1310
+ logger$1.warn("Could not forget an unprocessed webhook delivery: @error", error);
1317
1311
  }
1318
1312
  res.statusCode = reply.status;
1319
1313
  if (reply.body !== void 0 && method !== "HEAD") {
@@ -1321,7 +1315,7 @@ var WebhookService = class {
1321
1315
  res.end(reply.body);
1322
1316
  } else res.end();
1323
1317
  } catch (error) {
1324
- logger$2.error("Webhook delivery failed for @method", req.method, error);
1318
+ logger$1.error("Webhook delivery failed for @method", req.method, error);
1325
1319
  writeError(res, 500, "Internal server error");
1326
1320
  }
1327
1321
  }
@@ -1506,676 +1500,6 @@ var MemoryWebhookStore = class {
1506
1500
  }
1507
1501
  };
1508
1502
  //#endregion
1509
- //#region src/utils/create-schema.ts
1510
- const logger$1 = childLogger(["reactor-api", "create-schema"]);
1511
- /**
1512
- * Revision type - matches the definition in reactor/schema.graphql.
1513
- * Used by PHDocument and document mutation results.
1514
- */
1515
- const RevisionType = `
1516
- type Revision {
1517
- scope: String!
1518
- revision: Int!
1519
- }
1520
- `;
1521
- /**
1522
- * Strip scalar definitions from a DocumentNode to avoid duplicates
1523
- * when combining with other schemas that define the same scalars.
1524
- */
1525
- const stripScalarDefinitions = (doc) => {
1526
- const filteredDefinitions = doc.definitions.filter((def) => def.kind !== Kind.SCALAR_TYPE_DEFINITION);
1527
- return print({
1528
- kind: Kind.DOCUMENT,
1529
- definitions: filteredDefinitions
1530
- });
1531
- };
1532
- /**
1533
- * Type-system definition kinds that GraphQL requires to be uniquely named.
1534
- * A subgraph SDL with two definitions sharing a name fails federation
1535
- * composition ("There can be only one type named X"), which is fatal to the
1536
- * whole gateway. We dedupe these by name; field/operation/extension nodes are
1537
- * left untouched.
1538
- */
1539
- const TYPE_DEFINITION_KINDS = /* @__PURE__ */ new Set([
1540
- Kind.OBJECT_TYPE_DEFINITION,
1541
- Kind.ENUM_TYPE_DEFINITION,
1542
- Kind.INPUT_OBJECT_TYPE_DEFINITION,
1543
- Kind.INTERFACE_TYPE_DEFINITION,
1544
- Kind.UNION_TYPE_DEFINITION,
1545
- Kind.SCALAR_TYPE_DEFINITION
1546
- ]);
1547
- /**
1548
- * Drop duplicate type-system definitions by name, keeping the first occurrence.
1549
- * Deduping is by name across ALL kinds (a `type` and an `enum` sharing a name
1550
- * collide in GraphQL too), so the first definition of a given name wins
1551
- * regardless of kind. State types are emitted before operation types, so
1552
- * keep-first preserves the authoritative state definition. This heals a document
1553
- * model that defines the same name twice (global+local, state+operation, or
1554
- * twice in one scope) so the assembled subgraph SDL composes instead of crashing
1555
- * the gateway (Sentry #917).
1556
- */
1557
- const dedupeTypeDefinitions = (doc) => {
1558
- const seen = /* @__PURE__ */ new Set();
1559
- const definitions = doc.definitions.filter((def) => {
1560
- if (!TYPE_DEFINITION_KINDS.has(def.kind)) return true;
1561
- const name = def.name?.value;
1562
- if (!name) return true;
1563
- if (seen.has(name)) {
1564
- logger$1.debug(`Dropping duplicate type definition: ${name}`);
1565
- return false;
1566
- }
1567
- seen.add(name);
1568
- return true;
1569
- });
1570
- return {
1571
- kind: Kind.DOCUMENT,
1572
- definitions
1573
- };
1574
- };
1575
- const EMPTY_DOCUMENT = {
1576
- kind: Kind.DOCUMENT,
1577
- definitions: []
1578
- };
1579
- const OUTPUT_TYPE_KINDS = [
1580
- Kind.OBJECT_TYPE_DEFINITION,
1581
- Kind.OBJECT_TYPE_EXTENSION,
1582
- Kind.ENUM_TYPE_DEFINITION,
1583
- Kind.ENUM_TYPE_EXTENSION,
1584
- Kind.UNION_TYPE_DEFINITION,
1585
- Kind.UNION_TYPE_EXTENSION,
1586
- Kind.INTERFACE_TYPE_DEFINITION,
1587
- Kind.INTERFACE_TYPE_EXTENSION
1588
- ];
1589
- const STATE_PREFIX_KINDS = new Set(OUTPUT_TYPE_KINDS);
1590
- const ALL_PREFIX_KINDS = /* @__PURE__ */ new Set([
1591
- ...OUTPUT_TYPE_KINDS,
1592
- Kind.INPUT_OBJECT_TYPE_DEFINITION,
1593
- Kind.INPUT_OBJECT_TYPE_EXTENSION
1594
- ]);
1595
- const TYPE_NAME_KINDS = /* @__PURE__ */ new Set([
1596
- ...ALL_PREFIX_KINDS,
1597
- Kind.SCALAR_TYPE_DEFINITION,
1598
- Kind.SCALAR_TYPE_EXTENSION,
1599
- Kind.NAMED_TYPE
1600
- ]);
1601
- const LOCAL_STATE_STUBS = /* @__PURE__ */ new Set([
1602
- "AccountSnapshotLocalState",
1603
- "BudgetStatementLocalState",
1604
- "ScopeFrameworkLocalState"
1605
- ]);
1606
- /** Parse SDL; blank or comment-only input yields an empty document. */
1607
- function parseSdl(sdl) {
1608
- const source = new Source(sdl);
1609
- if (new Lexer(source).advance().kind === TokenKind.EOF) return EMPTY_DOCUMENT;
1610
- try {
1611
- return parse(source, { noLocation: true });
1612
- } catch (error) {
1613
- const withoutSemicolons = sdl.replaceAll(";", "");
1614
- if (withoutSemicolons === sdl) throw error;
1615
- return parse(withoutSemicolons, { noLocation: true });
1616
- }
1617
- }
1618
- function definedTypeNames(doc, kinds) {
1619
- return doc.definitions.filter((def) => kinds.has(def.kind)).map((def) => def.name.value);
1620
- }
1621
- /** Prefix type definition names and type references found in `names`. */
1622
- function prefixTypeNames(doc, prefix, names) {
1623
- return visit(doc, { enter(node) {
1624
- if (!TYPE_NAME_KINDS.has(node.kind)) return void 0;
1625
- const { name } = node;
1626
- if (!names.has(name.value)) return void 0;
1627
- return {
1628
- ...node,
1629
- name: {
1630
- ...name,
1631
- value: `${prefix}_${name.value}`
1632
- }
1633
- };
1634
- } });
1635
- }
1636
- /** State schema definitions without inputs, `DateTime` or the given object types. */
1637
- function stateTypeDefinitions(sdl, droppedObjectTypes = /* @__PURE__ */ new Set()) {
1638
- return parseSdl(sdl).definitions.filter((def) => def.kind !== Kind.INPUT_OBJECT_TYPE_DEFINITION && def.kind !== Kind.INPUT_OBJECT_TYPE_EXTENSION && !(def.kind === Kind.SCALAR_TYPE_DEFINITION && def.name.value === "DateTime") && !(def.kind === Kind.OBJECT_TYPE_DEFINITION && droppedObjectTypes.has(def.name.value)));
1639
- }
1640
- /**
1641
- * Prefixed operation schemas per module. The first definition of each module
1642
- * carries a "Module: <Name>" description unless it has its own.
1643
- */
1644
- function buildModuleSchemas(specification, documentName, allTypeNames, hasValidSchema) {
1645
- const names = new Set(allTypeNames);
1646
- return specification?.modules.map((module) => {
1647
- const definitions = module.operations.filter((op) => hasValidSchema(op.schema)).flatMap((op) => {
1648
- const doc = parseSdl(op.schema ?? "");
1649
- return prefixTypeNames(doc, documentName, /* @__PURE__ */ new Set([...names, ...definedTypeNames(doc, ALL_PREFIX_KINDS)])).definitions;
1650
- });
1651
- if (definitions.length === 0) return "";
1652
- const [first, ...rest] = definitions;
1653
- const header = "description" in first && !first.description ? {
1654
- ...first,
1655
- description: {
1656
- kind: Kind.STRING,
1657
- value: `Module: ${pascalCase(module.name)}`,
1658
- block: true
1659
- }
1660
- } : first;
1661
- return print({
1662
- kind: Kind.DOCUMENT,
1663
- definitions: [header, ...rest]
1664
- });
1665
- }).filter(Boolean).join("\n") ?? "";
1666
- }
1667
- const buildSubgraphSchemaModule = (documentModels, resolvers, typeDefs) => {
1668
- const newResolvers = {
1669
- ...resolvers,
1670
- JSONObject: GraphQLJSONObject,
1671
- Unknown: GraphQLJSON
1672
- };
1673
- return {
1674
- typeDefs: getDocumentModelTypeDefs(documentModels, typeDefs),
1675
- resolvers: newResolvers
1676
- };
1677
- };
1678
- const createSchema = (documentModels, resolvers, typeDefs) => {
1679
- return buildSubgraphSchema([buildSubgraphSchemaModule(documentModels, resolvers, typeDefs)]);
1680
- };
1681
- /**
1682
- * Create a merged GraphQL schema from multiple subgraph modules.
1683
- * Uses buildSubgraphSchema's array overload to combine type definitions
1684
- * and resolvers from multiple subgraphs into a single executable schema.
1685
- */
1686
- const createMergedSchema = (modules) => {
1687
- return buildSubgraphSchema(modules);
1688
- };
1689
- function getDocumentModelSchemaName(documentModel) {
1690
- return pascalCase(documentModel.name.replaceAll("/", " "));
1691
- }
1692
- const getDocumentModelTypeDefs = (documentModels, typeDefs$1) => {
1693
- let dmSchema = "";
1694
- const addedDocumentModels = /* @__PURE__ */ new Set();
1695
- documentModels.forEach(({ documentModel }) => {
1696
- const dmSchemaName = getDocumentModelSchemaName(documentModel.global);
1697
- if (addedDocumentModels.has(dmSchemaName)) {
1698
- logger$1.debug(`Skipping document model with duplicate name: ${dmSchemaName}`);
1699
- return;
1700
- }
1701
- addedDocumentModels.add(dmSchemaName);
1702
- const latestSpec = documentModel.global.specifications.at(-1);
1703
- const globalSchema = latestSpec?.state.global.schema ?? "";
1704
- const localSchema = latestSpec?.state.local.schema ?? "";
1705
- const definitions = [...stateTypeDefinitions(globalSchema), ...stateTypeDefinitions(localSchema, LOCAL_STATE_STUBS)];
1706
- const stateDoc = {
1707
- kind: Kind.DOCUMENT,
1708
- definitions
1709
- };
1710
- const prefixed = prefixTypeNames(stateDoc, dmSchemaName, new Set(definedTypeNames(stateDoc, STATE_PREFIX_KINDS)));
1711
- if (definitions.length > 0) dmSchema += `${print(prefixed)}\n`;
1712
- dmSchema += `
1713
- type ${dmSchemaName} implements IDocument {
1714
- id: String!
1715
- name: String!
1716
- documentType: String!
1717
- operations(skip: Int, first: Int): [Operation!]!
1718
- revision: Int!
1719
- createdAtUtcIso: DateTime!
1720
- lastModifiedAtUtcIso: DateTime!
1721
- ${dmSchemaName !== "DocumentModel" ? `initialState: ${dmSchemaName}_${dmSchemaName}State!` : ""}
1722
- ${dmSchemaName !== "DocumentModel" ? `state: ${dmSchemaName}_${dmSchemaName}State!` : ""}
1723
- stateJSON: JSONObject
1724
- }\n`;
1725
- });
1726
- const schema = gql`
1727
- scalar JSONObject
1728
- scalar AttachmentRef
1729
- # Codegen scalars not in the document-engineering set.
1730
- scalar Unknown
1731
- scalar Address
1732
- ${typeDefs.join("\n").replaceAll(";", "")}
1733
-
1734
- type PHOperationContext {
1735
- signer: Signer
1736
- }
1737
-
1738
- type Signer {
1739
- user: SignerUser
1740
- app: SignerApp
1741
- signatures: [String!]!
1742
- }
1743
-
1744
- type SignerUser {
1745
- address: String!
1746
- networkId: String!
1747
- chainId: Int!
1748
- }
1749
-
1750
- type SignerApp {
1751
- name: String!
1752
- key: String!
1753
- }
1754
-
1755
- type Operation {
1756
- id: String!
1757
- type: String!
1758
- index: Int!
1759
- timestampUtcMs: DateTime!
1760
- hash: String!
1761
- skip: Int
1762
- inputText: String
1763
- error: String
1764
- context: PHOperationContext
1765
- }
1766
-
1767
- interface IDocument {
1768
- id: String!
1769
- name: String!
1770
- documentType: String!
1771
- revision: Int!
1772
- createdAtUtcIso: DateTime!
1773
- lastModifiedAtUtcIso: DateTime!
1774
- operations(first: Int, skip: Int): [Operation!]!
1775
- stateJSON: JSONObject
1776
- }
1777
- ${dmSchema}
1778
-
1779
- type GqlDocument implements IDocument {
1780
- id: String!
1781
- name: String!
1782
- documentType: String!
1783
- revision: Int!
1784
- createdAtUtcIso: DateTime!
1785
- lastModifiedAtUtcIso: DateTime!
1786
- operations(first: Int, skip: Int): [Operation!]!
1787
- stateJSON: JSONObject
1788
- }
1789
-
1790
- type DriveDocument implements IDocument {
1791
- id: String!
1792
- name: String!
1793
- documentType: String!
1794
- revision: Int!
1795
- createdAtUtcIso: DateTime!
1796
- lastModifiedAtUtcIso: DateTime!
1797
- operations(first: Int, skip: Int): [Operation!]!
1798
- stateJSON: JSONObject
1799
- }
1800
-
1801
- ${stripScalarDefinitions(typeDefs$1)}
1802
- `;
1803
- return dedupeTypeDefinitions(schema);
1804
- };
1805
- /**
1806
- * Extract the names of types defined in a GraphQL schema.
1807
- * Unparseable schemas yield no names.
1808
- */
1809
- function extractTypeNames(schema) {
1810
- try {
1811
- return definedTypeNames(parseSdl(schema), ALL_PREFIX_KINDS);
1812
- } catch (error) {
1813
- logger$1.debug(`Skipping unparseable schema: ${String(error)}`);
1814
- return [];
1815
- }
1816
- }
1817
- /**
1818
- * Print the input type definitions of a GraphQL schema.
1819
- * @param excludeTypeNames - Input type names to leave out
1820
- */
1821
- function extractInputTypeDefinitions(schema, excludeTypeNames = /* @__PURE__ */ new Set()) {
1822
- const definitions = parseSdl(schema).definitions.filter((def) => def.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION && !excludeTypeNames.has(def.name.value));
1823
- if (definitions.length === 0) return "";
1824
- return print({
1825
- kind: Kind.DOCUMENT,
1826
- definitions
1827
- });
1828
- }
1829
- /**
1830
- * Extract the root state type name from a scope's GraphQL schema.
1831
- * Uses the naming convention: {DocumentName}State for global,
1832
- * {DocumentName}{PascalScope}State for other scopes (e.g., DocumentDriveLocalState).
1833
- * Falls back to the last ObjectTypeDefinition (root types are conventionally last).
1834
- */
1835
- function extractRootTypeName(schema, documentName, scopeName) {
1836
- try {
1837
- const ast = parse(schema);
1838
- const candidates = [`${documentName}${scopeName === "global" ? "" : pascalCase(scopeName)}State`, `${documentName}${pascalCase(scopeName)}State`];
1839
- let lastObjectType = null;
1840
- for (const def of ast.definitions) if (def.kind === Kind.OBJECT_TYPE_DEFINITION) {
1841
- if (candidates.includes(def.name.value)) return def.name.value;
1842
- lastObjectType = def.name.value;
1843
- }
1844
- return lastObjectType;
1845
- } catch {}
1846
- return null;
1847
- }
1848
- /**
1849
- * Convert a GraphQL output type AST node to an optional input type string.
1850
- * Strips non-null markers and converts object type references to Input suffix.
1851
- */
1852
- function convertTypeNodeToInput(typeNode, objectNames, unionNames, interfaceNames) {
1853
- if (typeNode.kind === Kind.NON_NULL_TYPE && typeNode.type) return convertTypeNodeToInput(typeNode.type, objectNames, unionNames, interfaceNames);
1854
- if (typeNode.kind === Kind.LIST_TYPE && typeNode.type) return `[${convertTypeNodeToInput(typeNode.type, objectNames, unionNames, interfaceNames)}]`;
1855
- if (typeNode.kind === Kind.NAMED_TYPE && typeNode.name) {
1856
- const name = typeNode.name.value;
1857
- if (objectNames.has(name)) return `${name}Input`;
1858
- if (unionNames.has(name) || interfaceNames.has(name)) return "JSONObject";
1859
- return name;
1860
- }
1861
- return "JSONObject";
1862
- }
1863
- /**
1864
- * Generate GraphQL input type definitions from a state schema string.
1865
- * Converts output type definitions to input types with all fields optional.
1866
- * - Object type references get Input suffix
1867
- * - Union/interface references become JSONObject
1868
- * - Enums and scalars remain unchanged
1869
- */
1870
- function generateStateInputTypes(stateSchema, excludeTypeNames) {
1871
- if (!stateSchema || !stateSchema.trim()) return "";
1872
- let ast;
1873
- try {
1874
- ast = parse(stateSchema);
1875
- } catch {
1876
- return "";
1877
- }
1878
- const enumNames = /* @__PURE__ */ new Set();
1879
- const unionNames = /* @__PURE__ */ new Set();
1880
- const interfaceNames = /* @__PURE__ */ new Set();
1881
- const objectNames = /* @__PURE__ */ new Set();
1882
- const existingInputNames = /* @__PURE__ */ new Set();
1883
- for (const def of ast.definitions) switch (def.kind) {
1884
- case Kind.ENUM_TYPE_DEFINITION:
1885
- enumNames.add(def.name.value);
1886
- break;
1887
- case Kind.UNION_TYPE_DEFINITION:
1888
- unionNames.add(def.name.value);
1889
- break;
1890
- case Kind.INTERFACE_TYPE_DEFINITION:
1891
- interfaceNames.add(def.name.value);
1892
- break;
1893
- case Kind.OBJECT_TYPE_DEFINITION:
1894
- objectNames.add(def.name.value);
1895
- break;
1896
- case Kind.INPUT_OBJECT_TYPE_DEFINITION: existingInputNames.add(def.name.value);
1897
- }
1898
- const inputTypes = [];
1899
- for (const def of ast.definitions) {
1900
- if (def.kind !== Kind.OBJECT_TYPE_DEFINITION) continue;
1901
- const inputName = `${def.name.value}Input`;
1902
- if (existingInputNames.has(inputName)) continue;
1903
- if (excludeTypeNames?.has(inputName)) continue;
1904
- const fields = def.fields ?? [];
1905
- if (fields.length === 0) continue;
1906
- const inputFields = fields.map((field) => {
1907
- return ` ${field.name.value}: ${convertTypeNodeToInput(field.type, objectNames, unionNames, interfaceNames)}`;
1908
- });
1909
- inputTypes.push(`input ${def.name.value}Input {\n${inputFields.join("\n")}\n}`);
1910
- }
1911
- return inputTypes.join("\n\n");
1912
- }
1913
- /**
1914
- * Apply type prefixes to GraphQL schema to namespace types and avoid collisions.
1915
- * Inlined from @powerhousedao/common/utils to avoid ES module import issues.
1916
- * @param {string} schema - GraphQL schema string
1917
- * @param {string} prefix - Prefix to apply to type names
1918
- * @param {string[]} externalTypeNames - Type names from other schemas to also prefix
1919
- * @returns {string} Schema with prefixed types
1920
- */
1921
- function applyGraphQLTypePrefixes(schema, prefix, externalTypeNames = []) {
1922
- if (!schema || !schema.trim()) return schema;
1923
- const doc = parseSdl(schema);
1924
- const names = /* @__PURE__ */ new Set([...definedTypeNames(doc, ALL_PREFIX_KINDS), ...externalTypeNames]);
1925
- if (names.size === 0) return schema;
1926
- return print(prefixTypeNames(doc, prefix, names));
1927
- }
1928
- /**
1929
- * Generate a GraphQL schema for a document model.
1930
- *
1931
- * @param documentModel - The document model global state
1932
- * @param options - Schema generation options
1933
- * @returns GraphQL DocumentNode
1934
- */
1935
- function generateDocumentModelSchema(documentModel, options = {}) {
1936
- const { useNewApi = false } = options;
1937
- const specification = documentModel.specifications.at(-1);
1938
- const documentName = getDocumentModelSchemaName(documentModel);
1939
- const globalStateSchema = specification?.state.global.schema;
1940
- const localStateSchema = specification?.state.local.schema;
1941
- const globalStateTypeNames = extractTypeNames(globalStateSchema ?? "");
1942
- const localStateTypeNames = extractTypeNames(localStateSchema ?? "");
1943
- const stateTypeNames = [...globalStateTypeNames, ...localStateTypeNames];
1944
- const allOperationTypeNames = specification?.modules.flatMap((module) => module.operations.flatMap((op) => extractTypeNames(op.schema ?? ""))) ?? [];
1945
- const allTypeNames = [.../* @__PURE__ */ new Set([...stateTypeNames, ...allOperationTypeNames])];
1946
- const operationInputTypeNames = new Set(allOperationTypeNames);
1947
- const prefixedStateInputTypes = applyGraphQLTypePrefixes(extractInputTypeDefinitions(globalStateSchema ?? "", operationInputTypeNames), documentName, allTypeNames);
1948
- const hasValidSchema = (schema) => !!(schema && /\b(input|type|enum|union|interface)\s+\w+/.test(schema));
1949
- if (useNewApi) return generateNewApiSchema(documentName, specification, prefixedStateInputTypes, allTypeNames, hasValidSchema);
1950
- return generateLegacyApiSchema(documentName, specification, prefixedStateInputTypes, allTypeNames, hasValidSchema);
1951
- }
1952
- /**
1953
- * Generate legacy API schema with nested queries
1954
- */
1955
- function generateLegacyApiSchema(documentName, specification, prefixedStateInputTypes, allTypeNames, hasValidSchema) {
1956
- const createDocumentMutation = `${documentName}_createDocument(name:String!, driveId:String): String`;
1957
- const operationMutations = specification?.modules.flatMap((module) => module.operations.filter((op) => op.name && hasValidSchema(op.schema)).map((op) => `${documentName}_${camelCase(op.name)}(
1958
- driveId: String, docId: PHID, input: ${documentName}_${pascalCase(op.name)}Input): Int`)).join("\n ") ?? "";
1959
- const moduleSchemas = buildModuleSchemas(specification, documentName, allTypeNames, hasValidSchema);
1960
- return gql`
1961
- """
1962
- Queries: ${documentName} Document
1963
- """
1964
-
1965
- type ${documentName}Queries {
1966
- getDocument(docId: PHID!, driveId: PHID): ${documentName}
1967
- getDocuments(driveId: String!): [${documentName}!]
1968
- }
1969
-
1970
- type Query {
1971
- ${documentName}: ${documentName}Queries
1972
- }
1973
-
1974
- """
1975
- Mutations: ${documentName}
1976
- """
1977
- type Mutation {
1978
- ${createDocumentMutation}
1979
-
1980
- ${operationMutations}
1981
- }
1982
-
1983
- ${prefixedStateInputTypes ? `"""
1984
- Input Types from State Schema
1985
- """
1986
- ${prefixedStateInputTypes}` : ""}
1987
-
1988
- ${moduleSchemas}`;
1989
- }
1990
- /**
1991
- * Generate new API schema with flat queries, typed state, and async mutations.
1992
- * Note: State schema types are NOT included here because they are already defined
1993
- * in getDocumentModelTypeDefs() which is used during schema composition.
1994
- * Including them here would cause duplicate type definitions.
1995
- */
1996
- function generateNewApiSchema(documentName, specification, prefixedStateInputTypes, allTypeNames, hasValidSchema) {
1997
- const stateType = `${documentName}_FullState!`;
1998
- const sharedBaseTypes = `
1999
- """Hash configuration for document state"""
2000
- type ${documentName}_PHHashConfig {
2001
- algorithm: String!
2002
- encoding: String!
2003
- }
2004
-
2005
- """Document scope state (same for all document types)"""
2006
- type ${documentName}_PHDocumentScopeState {
2007
- version: Int!
2008
- hash: ${documentName}_PHHashConfig!
2009
- isDeleted: Boolean
2010
- deletedAtUtcIso: String
2011
- deletedBy: String
2012
- deletionReason: String
2013
- }
2014
- `;
2015
- const hasLocalStateType = (specification?.state.local.schema ?? "").includes(`type ${documentName}LocalState`);
2016
- const fullStateType = `
2017
- """Full state with all scopes for ${documentName}"""
2018
- type ${documentName}_FullState {
2019
- auth: JSONObject!
2020
- document: ${documentName}_PHDocumentScopeState!
2021
- global: ${documentName === "DocumentModel" ? `${documentName}_${documentName}GlobalState!` : `${documentName}_${documentName}State!`}
2022
- local: ${!hasLocalStateType ? "JSONObject!" : `${documentName}_${documentName}LocalState!`}
2023
- }
2024
- `;
2025
- const commonInputTypes = `
2026
- input ${documentName}_ViewFilterInput {
2027
- branch: String
2028
- scopes: [String!]
2029
- }
2030
-
2031
- input ${documentName}_PagingInput {
2032
- limit: Int
2033
- offset: Int
2034
- cursor: String
2035
- }
2036
-
2037
- input ${documentName}_SearchFilterInput {
2038
- parentId: String
2039
- identifiers: [String!] @deprecated(reason: "Ignored. Filter by parentId.")
2040
- }
2041
- `;
2042
- const revisionType = RevisionType;
2043
- const resultTypes = `
2044
- """
2045
- Mutation result type for ${documentName} operations with typed state.
2046
- Matches ReactorSubgraph PHDocument pattern with revisionsList.
2047
- """
2048
- type ${documentName}MutationResult {
2049
- id: String!
2050
- slug: String
2051
- preferredEditor: String
2052
- name: String!
2053
- documentType: String!
2054
- state: ${stateType}
2055
- revisionsList: [Revision!]!
2056
- createdAtUtcIso: DateTime!
2057
- lastModifiedAtUtcIso: DateTime!
2058
- }
2059
-
2060
- """
2061
- Document with children for ${documentName}
2062
- """
2063
- type ${documentName}_DocumentWithChildren {
2064
- document: ${documentName}MutationResult!
2065
- childIds: [String!]!
2066
- }
2067
-
2068
- """
2069
- Paginated result type for ${documentName} documents
2070
- """
2071
- type ${documentName}_DocumentResultPage {
2072
- items: [${documentName}MutationResult!]!
2073
- hasNextPage: Boolean!
2074
- hasPreviousPage: Boolean!
2075
- cursor: String
2076
- }
2077
- `;
2078
- const queries = `
2079
- type ${documentName}Queries {
2080
- """Get a specific ${documentName} document by identifier"""
2081
- document(idOrSlug: String, identifier: String @deprecated(reason: "Use idOrSlug."), view: ${documentName}_ViewFilterInput): ${documentName}_DocumentWithChildren
2082
-
2083
- """Get all ${documentName} documents (paged)"""
2084
- documents(paging: ${documentName}_PagingInput): ${documentName}_DocumentResultPage!
2085
-
2086
- """Find ${documentName} documents by search criteria"""
2087
- findDocuments(search: ${documentName}_SearchFilterInput, view: ${documentName}_ViewFilterInput, paging: ${documentName}_PagingInput): ${documentName}_DocumentResultPage!
2088
-
2089
- """Get outgoing relationships of a ${documentName} document"""
2090
- documentOutgoingRelationships(sourceIdOrSlug: String, sourceIdentifier: String @deprecated(reason: "Use sourceIdOrSlug."), relationshipType: String!, view: ${documentName}_ViewFilterInput, paging: ${documentName}_PagingInput): ${documentName}_DocumentResultPage!
2091
-
2092
- """Get incoming relationships to a ${documentName} document"""
2093
- documentIncomingRelationships(targetIdOrSlug: String, targetIdentifier: String @deprecated(reason: "Use targetIdOrSlug."), relationshipType: String!, view: ${documentName}_ViewFilterInput, paging: ${documentName}_PagingInput): ${documentName}_DocumentResultPage!
2094
- }
2095
- `;
2096
- let initialStateInputSchema = "";
2097
- if (specification) {
2098
- const scopeFields = [];
2099
- const generatedInputTypeParts = [];
2100
- for (const [scopeName, scopeState] of Object.entries(specification.state)) {
2101
- const schema = scopeState.schema ?? "";
2102
- if (hasValidSchema(schema)) {
2103
- const rootTypeName = extractRootTypeName(schema, documentName, scopeName);
2104
- if (!rootTypeName) {
2105
- scopeFields.push(` ${scopeName}: JSONObject`);
2106
- continue;
2107
- }
2108
- const scopeInputTypes = generateStateInputTypes(schema, new Set(allTypeNames));
2109
- if (!scopeInputTypes) {
2110
- scopeFields.push(` ${scopeName}: JSONObject`);
2111
- continue;
2112
- }
2113
- const prefixedScopeInputTypes = applyGraphQLTypePrefixes(scopeInputTypes, documentName, allTypeNames);
2114
- scopeFields.push(` ${scopeName}: ${documentName}_${rootTypeName}Input`);
2115
- generatedInputTypeParts.push(prefixedScopeInputTypes);
2116
- } else scopeFields.push(` ${scopeName}: JSONObject`);
2117
- }
2118
- if (scopeFields.length > 0) {
2119
- const inputTypeDefs = generatedInputTypeParts.join("\n\n");
2120
- const wrapper = `input ${documentName}_InitialStateInput {\n${scopeFields.join("\n")}\n}`;
2121
- initialStateInputSchema = inputTypeDefs ? `${inputTypeDefs}\n\n${wrapper}` : wrapper;
2122
- }
2123
- }
2124
- const createDocumentMutation = initialStateInputSchema ? `createDocument(name: String!, parentIdOrSlug: String, parentIdentifier: String @deprecated(reason: "Use parentIdOrSlug."), slug: String, preferredEditor: String, initialState: ${documentName}_InitialStateInput): ${documentName}MutationResult!` : `createDocument(name: String!, parentIdOrSlug: String, parentIdentifier: String @deprecated(reason: "Use parentIdOrSlug."), preferredEditor: String): ${documentName}MutationResult!`;
2125
- const createEmptyDocumentMutation = `createEmptyDocument(parentIdOrSlug: String, parentIdentifier: String @deprecated(reason: "Use parentIdOrSlug.")): ${documentName}MutationResult!`;
2126
- const operationMutations = specification?.modules.flatMap((module) => module.operations.filter((op) => op.name && hasValidSchema(op.schema)).flatMap((op) => [`${camelCase(op.name)}(documentIdOrSlug: String, docId: PHID @deprecated(reason: "Use documentIdOrSlug."), input: ${documentName}_${pascalCase(op.name)}Input!): ${documentName}MutationResult!`, `${camelCase(op.name)}Async(documentIdOrSlug: String, docId: PHID @deprecated(reason: "Use documentIdOrSlug."), input: ${documentName}_${pascalCase(op.name)}Input!): String!`])).join("\n ") ?? "";
2127
- const moduleSchemas = buildModuleSchemas(specification, documentName, allTypeNames, hasValidSchema);
2128
- return gql`
2129
- scalar DateTime
2130
- scalar JSONObject
2131
- scalar AttachmentRef
2132
-
2133
- ${revisionType}
2134
-
2135
- ${sharedBaseTypes}
2136
-
2137
- ${fullStateType}
2138
-
2139
- ${commonInputTypes}
2140
-
2141
- ${resultTypes}
2142
-
2143
- """
2144
- Queries: ${documentName} Document
2145
- """
2146
- ${queries}
2147
-
2148
- """
2149
- Mutations: ${documentName}
2150
- """
2151
- type ${documentName}Mutations {
2152
- ${createDocumentMutation}
2153
- ${createEmptyDocumentMutation}
2154
-
2155
- ${operationMutations}
2156
- }
2157
-
2158
- type Query {
2159
- ${documentName}: ${documentName}Queries!
2160
- }
2161
-
2162
- type Mutation {
2163
- ${documentName}: ${documentName}Mutations!
2164
- }
2165
-
2166
- ${prefixedStateInputTypes ? `"""
2167
- Input Types from State Schema
2168
- """
2169
- ${prefixedStateInputTypes}` : ""}
2170
-
2171
- ${initialStateInputSchema ? `"""
2172
- Input Types for Initial State
2173
- """
2174
- ${initialStateInputSchema}` : ""}
2175
-
2176
- ${moduleSchemas}`;
2177
- }
2178
- //#endregion
2179
1503
  //#region src/graphql/reactor/gen/graphql.ts
2180
1504
  let AuthDecision = /* @__PURE__ */ function(AuthDecision) {
2181
1505
  AuthDecision["Allow"] = "ALLOW";
@@ -4625,11 +3949,15 @@ async function pushSyncEnvelopes(syncManager, args) {
4625
3949
  */
4626
3950
  var DocumentModelSubgraph = class extends BaseSubgraph {
4627
3951
  documentModel;
4628
- constructor(documentModel, args) {
3952
+ /** Names of the types its schema generator emits for the model. */
3953
+ generatedTypeNames;
3954
+ /** `types` are the model's subgraph types, when already built. */
3955
+ constructor(documentModel, args, types = documentModelSubgraphTypes(documentModel.documentModel.global)) {
4629
3956
  super(args);
4630
3957
  this.documentModel = documentModel;
4631
- this.name = kebabCase(documentModel.documentModel.global.name);
4632
- this.typeDefs = generateDocumentModelSchema(this.documentModel.documentModel.global, { useNewApi: true });
3958
+ this.name = getDocumentModelSubgraphName(documentModel.documentModel.global);
3959
+ this.typeDefs = types.typeDefs;
3960
+ this.generatedTypeNames = types.typeNames;
4633
3961
  this.resolvers = this.generateResolvers();
4634
3962
  }
4635
3963
  /** Returns the typed query resolvers for this document model. */
@@ -5015,19 +4343,89 @@ function createGraphQLSSEHandler(options) {
5015
4343
  context: (req) => contextFactory(req.raw)
5016
4344
  });
5017
4345
  }
5018
- //#endregion
5019
- //#region src/graphql/graphql-manager.ts
5020
- const DOCUMENT_MODELS_TO_EXCLUDE = [];
4346
+ const FEDERATION_DIRECTIVES = /* @__PURE__ */ new Set([
4347
+ "authenticated",
4348
+ "composeDirective",
4349
+ "context",
4350
+ "cost",
4351
+ "extends",
4352
+ "external",
4353
+ "fromContext",
4354
+ "inaccessible",
4355
+ "interfaceObject",
4356
+ "key",
4357
+ "link",
4358
+ "listSize",
4359
+ "override",
4360
+ "policy",
4361
+ "provides",
4362
+ "requires",
4363
+ "requiresScopes",
4364
+ "shareable",
4365
+ "tag"
4366
+ ]);
4367
+ function isFederationDirective(name, declared) {
4368
+ if (declared.has(name)) return false;
4369
+ return FEDERATION_DIRECTIVES.has(name) || name.startsWith("federation__");
4370
+ }
4371
+ function stripFederationDirectives(typeDefs) {
4372
+ const declared = /* @__PURE__ */ new Set();
4373
+ for (const def of typeDefs.definitions) if (def.kind === Kind.DIRECTIVE_DEFINITION) declared.add(def.name.value);
4374
+ return visit(typeDefs, {
4375
+ Directive: (node) => isFederationDirective(node.name.value, declared) ? null : void 0,
4376
+ SchemaExtension: { leave: (node) => !node.directives?.length && !node.operationTypes?.length ? null : void 0 }
4377
+ });
4378
+ }
4379
+ /**
4380
+ * The subgraphs with federation directives removed: the stream schema is
4381
+ * merged in-process, where those directives are undeclared.
4382
+ */
4383
+ function withoutFederationDirectives(subgraphs) {
4384
+ return subgraphs.map((subgraph) => ({
4385
+ ...subgraph,
4386
+ typeDefs: stripFederationDirectives(subgraph.typeDefs)
4387
+ }));
4388
+ }
4389
+ const STREAM_ROOTS = [
4390
+ "Query",
4391
+ "Mutation",
4392
+ "Subscription"
4393
+ ];
5021
4394
  /**
5022
- * Check if a document model has any operations with valid schemas.
5023
- * Document models without valid operation schemas cannot generate valid subgraph schemas.
4395
+ * Merges subscription subgraphs into one stream schema, or `undefined` when no
4396
+ * subgraph contributes the Query root a schema requires. A root the subgraphs
4397
+ * only extend gets an empty definition to extend.
5024
4398
  */
5025
- function hasOperationSchemas(documentModel) {
5026
- const specification = documentModel.documentModel.global.specifications.at(-1);
5027
- if (!specification) return false;
5028
- const hasValidSchema = (schema) => schema && /\b(input|type|enum|union|interface)\s+\w+/.test(schema);
5029
- return specification.modules.some((module) => module.operations.some((op) => hasValidSchema(op.schema)));
4399
+ function mergeStreamSubgraphs(subgraphs) {
4400
+ const defined = /* @__PURE__ */ new Set();
4401
+ const extended = /* @__PURE__ */ new Set();
4402
+ for (const subgraph of subgraphs) for (const def of subgraph.typeDefs.definitions) if (def.kind === Kind.OBJECT_TYPE_DEFINITION) defined.add(def.name.value);
4403
+ else if (def.kind === Kind.OBJECT_TYPE_EXTENSION) extended.add(def.name.value);
4404
+ if (!defined.has("Query") && !extended.has("Query")) return;
4405
+ const placeholders = STREAM_ROOTS.filter((root) => extended.has(root) && !defined.has(root)).flatMap((root) => parse(`type ${root}`).definitions);
4406
+ const roots = placeholders.length > 0 ? [{
4407
+ name: "stream-roots",
4408
+ typeDefs: {
4409
+ kind: Kind.DOCUMENT,
4410
+ definitions: placeholders
4411
+ },
4412
+ url: ""
4413
+ }] : [];
4414
+ return mergeSubgraphSchemas([...roots, ...subgraphs], "last");
5030
4415
  }
4416
+ //#endregion
4417
+ //#region src/graphql/graphql-manager.ts
4418
+ const DOCUMENT_MODELS_TO_EXCLUDE = [];
4419
+ const NON_MODEL_TYPE_NAMES = /* @__PURE__ */ new Set([
4420
+ "String",
4421
+ "Int",
4422
+ "Float",
4423
+ "Boolean",
4424
+ "ID",
4425
+ "Query",
4426
+ "Mutation",
4427
+ "Subscription"
4428
+ ]);
5031
4429
  /**
5032
4430
  * Filter document models to keep only the latest version of each unique document model.
5033
4431
  */
@@ -5046,11 +4444,26 @@ function filterLatestDocumentModelVersions(documentModels) {
5046
4444
  }
5047
4445
  const DefaultFeatureFlags = { enableDocumentModelSubgraphs: true };
5048
4446
  /**
5049
- * The registration-source label for document-model-generated subgraphs, so
5050
- * they can be pruned like package-contributed ones (see
5051
- * regenerateDocumentModelSubgraphs).
4447
+ * Where a subgraph came from: a core subgraph, the host, the generated
4448
+ * document-model subgraphs, or a package name. A name belongs to one origin:
4449
+ * the same origin replaces it, a higher-ranked one evicts it, and any other is
4450
+ * refused.
5052
4451
  */
5053
- const DOCUMENT_MODEL_SUBGRAPH_SOURCE = "document-models";
4452
+ const CORE_ORIGIN = Symbol("core");
4453
+ const DOCUMENT_MODEL_ORIGIN = Symbol("document-models");
4454
+ const HOST_ORIGIN = Symbol("host");
4455
+ function describeOrigin(origin) {
4456
+ if (origin === CORE_ORIGIN) return "core";
4457
+ if (origin === DOCUMENT_MODEL_ORIGIN) return "document models";
4458
+ if (origin === HOST_ORIGIN) return "the host";
4459
+ return `package ${origin}`;
4460
+ }
4461
+ function rank(origin) {
4462
+ if (origin === CORE_ORIGIN) return 3;
4463
+ if (origin === HOST_ORIGIN) return 2;
4464
+ if (origin === DOCUMENT_MODEL_ORIGIN) return 1;
4465
+ return 0;
4466
+ }
5054
4467
  function refuseConnection(connection, reason) {
5055
4468
  const { socket } = connection;
5056
4469
  socket?.close?.(4403, reason);
@@ -5095,11 +4508,46 @@ var GraphQLManager = class {
5095
4508
  /** Mounted SSE routes, keyed by path: the supergraph's and each subgraph's. */
5096
4509
  sseRouteHandles = /* @__PURE__ */ new Map();
5097
4510
  /**
5098
- * Package name → the subgraph instances registered from it, keyed by
5099
- * subgraph name. Tracks the package association so that removed packages
5100
- * can be torn down (see unregisterPackage / prunePackageSubgraphs).
4511
+ * Origin → the subgraph instances registered from it. Core and host
4512
+ * subgraphs are not tracked. Tracks the package association so that
4513
+ * removed packages can be torn down (see unregisterPackage /
4514
+ * prunePackageSubgraphs).
5101
4515
  */
5102
4516
  packageSubgraphs = /* @__PURE__ */ new Map();
4517
+ #origins = /* @__PURE__ */ new WeakMap();
4518
+ /**
4519
+ * Package → the supergraph and subgraph classes (by subgraph name) it last
4520
+ * provided, so a subgraph refused or evicted for its name can register once
4521
+ * the name is free. `refused` keeps each one's instance until it is set
4522
+ * up, so the next attempt reuses it and a refusal that still holds logs
4523
+ * once.
4524
+ */
4525
+ #packageClasses = /* @__PURE__ */ new Map();
4526
+ /** Registry changes run one at a time: a registration is admitted before
4527
+ * the awaits that complete it. */
4528
+ #registryChanges = Promise.resolve();
4529
+ /** Active while a subgraph hook runs, so a registry change the hook makes
4530
+ * runs inline instead of waiting on the change that called the hook. Work
4531
+ * the hook detaches, such as a timer, enqueues as usual once the hook has
4532
+ * settled; while the hook is pending it cannot be told from awaited work
4533
+ * and runs inline too. */
4534
+ #inHook = new AsyncLocalStorage();
4535
+ #generatedTypes;
4536
+ /** Generated types no document model contributes, but `IDocument`. */
4537
+ #modelFreeTypeNames;
4538
+ #usesModelTypesMemo = /* @__PURE__ */ new WeakMap();
4539
+ /** Refusals logged: model id, source key and reason. */
4540
+ #refusals = /* @__PURE__ */ new Set();
4541
+ #schemaCache;
4542
+ /** The schemas of the admitted document models. */
4543
+ #modelSchemas = /* @__PURE__ */ new Map();
4544
+ /** Subgraphs excluded for a type collision, with the reason last logged. */
4545
+ #loggedCollisions = /* @__PURE__ */ new WeakMap();
4546
+ /** Supergraph exclusions for a lost claim, with the reason last logged. */
4547
+ #loggedOwnershipExclusions = /* @__PURE__ */ new WeakMap();
4548
+ #claims = /* @__PURE__ */ new WeakMap();
4549
+ /** Claim tie-break: kept across re-registration, so HMR keeps the owner. */
4550
+ #registrationOrder = /* @__PURE__ */ new Map();
5103
4551
  /** Per-subgraph handlers by name, before auth/drive middleware is applied,
5104
4552
  * for in-process queries by trusted internals. */
5105
4553
  #internalSubgraphHandlers = /* @__PURE__ */ new Map();
@@ -5130,6 +4578,7 @@ var GraphQLManager = class {
5130
4578
  httpRoutes;
5131
4579
  attachments;
5132
4580
  inspection;
4581
+ #reporting;
5133
4582
  constructor(options) {
5134
4583
  this.path = options.path;
5135
4584
  this.httpServer = options.httpServer;
@@ -5144,6 +4593,8 @@ var GraphQLManager = class {
5144
4593
  this.authService = options.authService;
5145
4594
  this.documentPermissionService = options.documentPermissionService;
5146
4595
  this.featureFlags = options.featureFlags ?? DefaultFeatureFlags;
4596
+ const subgraph = !!this.featureFlags.enableDocumentModelSubgraphs;
4597
+ this.#schemaCache = new DocumentModelSchemaCache((model) => buildDocumentModelSchema(model, { subgraph }));
5147
4598
  this.port = options.port ?? 4001;
5148
4599
  this.authorizationService = options.authorizationService;
5149
4600
  this.reactorDriveClient = options.reactorDriveClient;
@@ -5151,6 +4602,10 @@ var GraphQLManager = class {
5151
4602
  this.httpRoutes = options.httpRoutes;
5152
4603
  this.attachments = options.attachments;
5153
4604
  this.inspection = options.inspection;
4605
+ this.#reporting = {
4606
+ logger: options.logger,
4607
+ report: options.reportError
4608
+ };
5154
4609
  this.driveOwnershipCache = new DriveOwnershipCache(options.driveStore ?? this.reactorClient);
5155
4610
  this.wsServer.setMaxListeners(0);
5156
4611
  }
@@ -5162,7 +4617,6 @@ var GraphQLManager = class {
5162
4617
  this.#driveMiddleware = createDriveFetchMiddleware(this.driveOwnershipCache);
5163
4618
  this.logger.debug(`Drive ownership cache populated with ${this.driveOwnershipCache.size()} drives`);
5164
4619
  const models = (await this.reactorClient.getDocumentModelModules()).results;
5165
- this.cachedDocumentModels = models;
5166
4620
  if (!models.find((it) => it.documentModel.global.name === "DocumentDrive")) throw new Error("DocumentDrive model required");
5167
4621
  await this.gatewayAdapter.start(this.httpServer);
5168
4622
  this.httpAdapter.setupMiddleware({ bodyLimit: "50mb" });
@@ -5197,8 +4651,8 @@ var GraphQLManager = class {
5197
4651
  };
5198
4652
  this.httpAdapter.mount(driveRoutePath, this.#authMiddleware ? this.#authMiddleware(driveInfoHandler) : driveInfoHandler);
5199
4653
  this.logger.info(`Registered REST endpoint: GET ${driveRoutePath}`);
5200
- await this.#setupCoreSubgraphs("graphql", coreSubgraphs);
5201
- if (this.featureFlags.enableDocumentModelSubgraphs) await this.#setupDocumentModelSubgraphs("graphql", models);
4654
+ await this.#setupCoreSubgraphs("graphql", coreSubgraphs, models);
4655
+ if (this.featureFlags.enableDocumentModelSubgraphs) await this.#setupDocumentModelSubgraphs("graphql", this.cachedDocumentModels);
5202
4656
  await this.#createSupergraphGateway();
5203
4657
  return this.updateRouter();
5204
4658
  }
@@ -5208,32 +4662,73 @@ var GraphQLManager = class {
5208
4662
  */
5209
4663
  async regenerateDocumentModelSubgraphs() {
5210
4664
  if (!this.featureFlags.enableDocumentModelSubgraphs) return;
4665
+ await this.#serialize(() => this.#regenerateDocumentModelSubgraphs());
4666
+ }
4667
+ async #regenerateDocumentModelSubgraphs() {
5211
4668
  try {
5212
4669
  const models = (await this.reactorClient.getDocumentModelModules()).results;
5213
- this.cachedDocumentModels = models;
5214
- const registeredNames = await this.#setupDocumentModelSubgraphs("graphql", models);
5215
- await this.prunePackageSubgraphs(DOCUMENT_MODEL_SUBGRAPH_SOURCE, registeredNames);
5216
- await this.updateRouter();
4670
+ this.cachedDocumentModels = this.#admitModels(models);
4671
+ const registeredNames = await this.#setupDocumentModelSubgraphs("graphql", this.cachedDocumentModels);
4672
+ await this.#pruneOrigin(DOCUMENT_MODEL_ORIGIN, registeredNames);
4673
+ await this.#restorePackageSubgraphs();
4674
+ this.#scheduleRouterUpdate();
5217
4675
  this.logger.info("Regenerated document model subgraphs with @count models", models.length);
5218
4676
  } catch (error) {
5219
4677
  this.logger.error("Failed to regenerate document model subgraphs: @error", error);
5220
4678
  throw error;
5221
4679
  }
5222
4680
  }
5223
- async #setupCoreSubgraphs(supergraph, coreSubgraphs) {
4681
+ async #setupCoreSubgraphs(supergraph, coreSubgraphs, models) {
5224
4682
  for (const subgraph of coreSubgraphs) try {
5225
4683
  await this.registerSubgraph(subgraph, supergraph, true);
5226
4684
  } catch (error) {
5227
4685
  this.logger.error("Failed to setup core subgraph @subgraph: @error", subgraph.name, error);
5228
4686
  }
4687
+ this.cachedDocumentModels = this.#admitModels(models);
5229
4688
  return this.#setupSubgraphs(this.coreSubgraphsMap);
5230
4689
  }
4690
+ /** Models whose schemas build and take no reserved name. */
4691
+ #admitModels(models) {
4692
+ const reserved = reservedTypeNames(Array.from(this.coreSubgraphsMap.values(), (subgraphs) => subgraphs.map((subgraph) => subgraph.typeDefs)).flat());
4693
+ const refusals = /* @__PURE__ */ new Set();
4694
+ const schemas = /* @__PURE__ */ new Map();
4695
+ const admitted = [];
4696
+ for (const { model, key, schema, error } of this.#schemaCache.resolve(models)) {
4697
+ const id = model.documentModel.global.id;
4698
+ const refuse = (message, reason) => {
4699
+ const refusal = `${id}\n${key}\n${reason}`;
4700
+ refusals.add(refusal);
4701
+ if (!this.#refusals.has(refusal)) this.logger.error(message, id, reason);
4702
+ };
4703
+ const refuseModel = (reason) => refuse("Refusing document model @documentType from the GraphQL schema: @reason", reason);
4704
+ if (!schema) {
4705
+ refuseModel(`has an unusable schema: ${error.message}`);
4706
+ continue;
4707
+ }
4708
+ const taken = this.#reservedNamesReason(model, schema, reserved);
4709
+ if (taken !== void 0) {
4710
+ refuseModel(taken);
4711
+ continue;
4712
+ }
4713
+ if (schema.subgraphError) refuse("Refusing the subgraph of document model @documentType: @reason", `has an unusable subgraph schema: ${schema.subgraphError.message}`);
4714
+ schemas.set(model, schema);
4715
+ admitted.push(model);
4716
+ }
4717
+ this.#refusals = refusals;
4718
+ this.#modelSchemas = schemas;
4719
+ return admitted;
4720
+ }
4721
+ #reservedNamesReason(model, schema, reserved) {
4722
+ const taken = reservedTypeNamesTaken(model, reserved, schema.generated);
4723
+ return taken.length > 0 ? `generates reserved type names: ${taken.join(", ")}` : void 0;
4724
+ }
5231
4725
  async #setupDocumentModelSubgraphs(supergraph, documentModels) {
5232
4726
  const latestDocumentModels = filterLatestDocumentModelVersions(documentModels);
5233
4727
  const registeredNames = /* @__PURE__ */ new Set();
5234
4728
  for (const documentModel of latestDocumentModels) {
5235
4729
  if (DOCUMENT_MODELS_TO_EXCLUDE.includes(documentModel.documentModel.global.id)) continue;
5236
- if (!hasOperationSchemas(documentModel)) continue;
4730
+ const types = this.#modelSchemas.get(documentModel)?.subgraph;
4731
+ if (!types) continue;
5237
4732
  try {
5238
4733
  const subgraphInstance = new DocumentModelSubgraph(documentModel, {
5239
4734
  http: this.scopeForPackage(CORE_PACKAGE_NAME),
@@ -5248,9 +4743,9 @@ var GraphQLManager = class {
5248
4743
  syncServingGate: this.syncServingGate,
5249
4744
  attachments: this.attachments,
5250
4745
  inspection: this.inspection
5251
- });
5252
- await this.#addSubgraphInstance(subgraphInstance, supergraph, false, DOCUMENT_MODEL_SUBGRAPH_SOURCE);
5253
- registeredNames.add(subgraphInstance.name);
4746
+ }, types);
4747
+ const registered = await this.#addSubgraphInstance(subgraphInstance, supergraph, false, DOCUMENT_MODEL_ORIGIN);
4748
+ if (registered) registeredNames.add(registered.name);
5254
4749
  } catch (error) {
5255
4750
  this.logger.error("Failed to setup document model subgraph for @documentType: @error", documentModel.documentModel.global.id, error instanceof Error ? error.message : error);
5256
4751
  this.logger.debug("@error", error);
@@ -5258,40 +4753,228 @@ var GraphQLManager = class {
5258
4753
  }
5259
4754
  return registeredNames;
5260
4755
  }
5261
- /** Core subgraph names are reserved: they register with core=true during
5262
- * init() and no package subgraph may take one of their names. */
4756
+ /** The first subgraph named `name` in `subgraphsMap`. */
4757
+ #findByName(subgraphsMap, name) {
4758
+ for (const subgraphs of subgraphsMap.values()) {
4759
+ const found = subgraphs.find((it) => it.name === name);
4760
+ if (found) return found;
4761
+ }
4762
+ }
4763
+ /** Every registered subgraph named `name`, core or not, in any bucket: the
4764
+ * in-process handler map is keyed by bare name, so a name has one owner. */
4765
+ #holdersOf(name) {
4766
+ const holders = /* @__PURE__ */ new Set();
4767
+ for (const subgraphsMap of [this.coreSubgraphsMap, this.subgraphs]) for (const subgraphs of subgraphsMap.values()) for (const subgraph of subgraphs) if (subgraph.name === name) holders.add(subgraph);
4768
+ return holders;
4769
+ }
4770
+ /** Core subgraph names are reserved: no other subgraph may take one. */
5263
4771
  #isCoreNameReserved(name) {
5264
- for (const subgraphs of this.coreSubgraphsMap.values()) if (subgraphs.some((it) => it.name === name)) return true;
5265
- return false;
4772
+ return this.#findByName(this.coreSubgraphsMap, name) !== void 0;
4773
+ }
4774
+ /** Buckets whose mount paths a registration into `supergraph` occupies: a
4775
+ * named supergraph's subgraphs are mounted under `graphql` as well. */
4776
+ #mountBuckets(supergraph) {
4777
+ return supergraph === "" || supergraph === "graphql" ? [supergraph] : [supergraph, "graphql"];
4778
+ }
4779
+ #generated() {
4780
+ if (this.#generatedTypes?.models !== this.cachedDocumentModels) {
4781
+ const types = getGeneratedDocumentModelTypes(this.cachedDocumentModels, this.#modelSchemas);
4782
+ const sdl = print({
4783
+ kind: Kind.DOCUMENT,
4784
+ definitions: types.definitions
4785
+ });
4786
+ this.#generatedTypes = {
4787
+ models: this.cachedDocumentModels,
4788
+ types: sdl === this.#generatedTypes?.sdl ? this.#generatedTypes.types : types,
4789
+ sdl
4790
+ };
4791
+ }
4792
+ return this.#generatedTypes.types;
5266
4793
  }
5267
- async #addSubgraphInstance(subgraphInstance, supergraph = "", core = false, packageName) {
5268
- if (!core && this.#isCoreNameReserved(subgraphInstance.name)) {
5269
- this.logger.error("Rejecting subgraph @name: name is reserved by a registered core subgraph", subgraphInstance.name);
5270
- return;
4794
+ #schemaOptions(subgraph) {
4795
+ return {
4796
+ generated: this.#generated(),
4797
+ ownTypeNames: subgraph instanceof DocumentModelSubgraph ? subgraph.generatedTypeNames : void 0
4798
+ };
4799
+ }
4800
+ /** Whether `subgraph`'s own typeDefs refer to a document model's types. */
4801
+ #usesModelTypes(subgraph) {
4802
+ const memo = this.#usesModelTypesMemo.get(subgraph);
4803
+ if (memo !== void 0) return memo;
4804
+ if (!this.#modelFreeTypeNames) {
4805
+ const names = new Set(getGeneratedDocumentModelTypes([]).names);
4806
+ names.delete("IDocument");
4807
+ this.#modelFreeTypeNames = names;
4808
+ }
4809
+ const modelFree = this.#modelFreeTypeNames;
4810
+ const own = typeDefinitionNames(subgraph.typeDefs);
4811
+ const referenced = [];
4812
+ const collect = (node) => {
4813
+ referenced.push(node.name.value);
4814
+ };
4815
+ visit(subgraph.typeDefs, {
4816
+ NamedType: collect,
4817
+ ScalarTypeExtension: collect,
4818
+ ObjectTypeExtension: collect,
4819
+ InterfaceTypeExtension: collect,
4820
+ UnionTypeExtension: collect,
4821
+ EnumTypeExtension: collect,
4822
+ InputObjectTypeExtension: collect
4823
+ });
4824
+ const uses = referenced.some((name) => !own.has(name) && !modelFree.has(name) && !NON_MODEL_TYPE_NAMES.has(name));
4825
+ this.#usesModelTypesMemo.set(subgraph, uses);
4826
+ return uses;
4827
+ }
4828
+ /** The generated type names `subgraph` redefines under the current models. */
4829
+ #typeCollisions(subgraph) {
4830
+ try {
4831
+ return findSubgraphTypeCollisions(this.#generated(), subgraph.typeDefs, this.#schemaOptions(subgraph).ownTypeNames);
4832
+ } catch {
4833
+ return [];
5271
4834
  }
5272
- const subgraphsMap = core ? this.coreSubgraphsMap : this.subgraphs;
5273
- const existingSubgraph = subgraphsMap.get(supergraph)?.find((it) => it.name === subgraphInstance.name);
5274
- if (existingSubgraph === subgraphInstance) {
4835
+ }
4836
+ /** Whether a model loaded since registration collides with `subgraph`'s
4837
+ * types. Each new collision is logged once. */
4838
+ #isExcludedForTypes(subgraph) {
4839
+ const collisions = this.#typeCollisions(subgraph);
4840
+ if (collisions.length === 0) {
4841
+ this.#loggedCollisions.delete(subgraph);
4842
+ return false;
4843
+ }
4844
+ const reason = new SubgraphTypeCollisionError(collisions).message;
4845
+ if (this.#loggedCollisions.get(subgraph) !== reason) {
4846
+ this.#loggedCollisions.set(subgraph, reason);
4847
+ this.logger.error("Excluding subgraph @name: @error", subgraph.name, reason);
4848
+ }
4849
+ return true;
4850
+ }
4851
+ /**
4852
+ * Whether `instance` may register, and what it replaces. A name has one
4853
+ * holder across every bucket: the same origin replaces it, a higher rank
4854
+ * (core > host > document models > package) evicts it, and anything else is
4855
+ * refused.
4856
+ */
4857
+ #admit(instance, core, origin) {
4858
+ if (!core && this.#isCoreNameReserved(instance.name)) {
4859
+ this.logger.error("Rejecting subgraph @name: name is reserved by a registered core subgraph", instance.name);
4860
+ return { action: "reject" };
4861
+ }
4862
+ const holders = this.#holdersOf(instance.name);
4863
+ if (holders.has(instance)) return {
4864
+ action: "skip",
4865
+ existing: instance
4866
+ };
4867
+ const rivals = Array.from(holders).filter((holder) => this.#originOf(holder) !== origin);
4868
+ for (const holder of rivals) {
4869
+ const holderOrigin = this.#originOf(holder);
4870
+ if (rank(origin) <= rank(holderOrigin)) {
4871
+ this.logger.error("Rejecting subgraph @name from @origin: name is taken by a subgraph from @existing", instance.name, describeOrigin(origin), describeOrigin(holderOrigin));
4872
+ return { action: "reject" };
4873
+ }
4874
+ }
4875
+ const collisions = core ? [] : this.#typeCollisions(instance);
4876
+ if (collisions.length > 0) {
4877
+ const reason = new SubgraphTypeCollisionError(collisions).message;
4878
+ if (this.#loggedCollisions.get(instance) !== reason) {
4879
+ this.#loggedCollisions.set(instance, reason);
4880
+ this.logger.error("Rejecting subgraph @name: @error", instance.name, reason);
4881
+ }
4882
+ return { action: "reject" };
4883
+ }
4884
+ return {
4885
+ action: "add",
4886
+ replaces: Array.from(holders).filter((it) => !rivals.includes(it)),
4887
+ evicts: rivals
4888
+ };
4889
+ }
4890
+ #originOf(instance) {
4891
+ return this.#origins.get(instance) ?? HOST_ORIGIN;
4892
+ }
4893
+ async #addSubgraphInstance(subgraphInstance, supergraph = "", core = false, origin = HOST_ORIGIN) {
4894
+ if (core) origin = CORE_ORIGIN;
4895
+ const admission = this.#admit(subgraphInstance, core, origin);
4896
+ if (admission.action === "reject") return void 0;
4897
+ if (admission.action === "skip") {
5275
4898
  this.logger.debug(`Skipping duplicate subgraph: ${subgraphInstance.name}`);
5276
- return existingSubgraph;
5277
- }
5278
- if (existingSubgraph) await this.#removeSubgraphInstance(existingSubgraph);
5279
- await subgraphInstance.onSetup?.();
5280
- const subgraphs = subgraphsMap.get(supergraph) ?? [];
5281
- subgraphs.push(subgraphInstance);
5282
- subgraphsMap.set(supergraph, subgraphs);
5283
- if (supergraph !== "" && supergraph !== "graphql") subgraphsMap.get("graphql")?.push(subgraphInstance);
5284
- if (packageName !== void 0) {
5285
- let byName = this.packageSubgraphs.get(packageName);
5286
- if (!byName) {
5287
- byName = /* @__PURE__ */ new Map();
5288
- this.packageSubgraphs.set(packageName, byName);
4899
+ return admission.existing;
4900
+ }
4901
+ const { replaces, evicts } = admission;
4902
+ for (const replaced of replaces) await this.#removeSubgraphInstance(replaced);
4903
+ if (typeof origin === "string") {
4904
+ const refused = this.#packageClasses.get(origin)?.refused;
4905
+ if (refused?.get(subgraphInstance.name) === subgraphInstance) refused.delete(subgraphInstance.name);
4906
+ }
4907
+ await this.#runHook(() => subgraphInstance.onSetup?.());
4908
+ for (const evicted of evicts) {
4909
+ this.logger.error("Evicting subgraph @name from @existing: @origin outranks it", subgraphInstance.name, describeOrigin(this.#originOf(evicted)), describeOrigin(origin));
4910
+ await this.#removeSubgraphInstance(evicted);
4911
+ }
4912
+ const subgraphsMap = core ? this.coreSubgraphsMap : this.subgraphs;
4913
+ for (const bucket of this.#mountBuckets(supergraph)) {
4914
+ const subgraphs = subgraphsMap.get(bucket);
4915
+ if (subgraphs) subgraphs.push(subgraphInstance);
4916
+ else if (bucket === supergraph) subgraphsMap.set(bucket, [subgraphInstance]);
4917
+ }
4918
+ this.#origins.set(subgraphInstance, origin);
4919
+ this.#recordRegistrationOrder(origin, subgraphInstance.name);
4920
+ if (origin !== HOST_ORIGIN && origin !== CORE_ORIGIN) {
4921
+ let instances = this.packageSubgraphs.get(origin);
4922
+ if (!instances) {
4923
+ instances = /* @__PURE__ */ new Set();
4924
+ this.packageSubgraphs.set(origin, instances);
5289
4925
  }
5290
- byName.set(subgraphInstance.name, subgraphInstance);
4926
+ instances.add(subgraphInstance);
5291
4927
  }
5292
- this.logger.info(`${existingSubgraph ? "Replaced" : "Registered"} ${this.path.endsWith("/") ? this.path : this.path + "/"}${supergraph ? supergraph + "/" : ""}${subgraphInstance.name} subgraph.`);
4928
+ this.logger.info(`${replaces.length + evicts.length > 0 ? "Replaced" : "Registered"} ${this.path.endsWith("/") ? this.path : this.path + "/"}${supergraph ? supergraph + "/" : ""}${subgraphInstance.name} subgraph.`);
5293
4929
  return subgraphInstance;
5294
4930
  }
4931
+ #recordRegistrationOrder(origin, name) {
4932
+ let entry = this.#registrationOrder.get(origin);
4933
+ if (!entry) {
4934
+ entry = {
4935
+ order: this.#registrationOrder.size,
4936
+ names: /* @__PURE__ */ new Map()
4937
+ };
4938
+ this.#registrationOrder.set(origin, entry);
4939
+ }
4940
+ if (!entry.names.has(name)) entry.names.set(name, entry.names.size);
4941
+ }
4942
+ /**
4943
+ * Take `instance` off the mount paths of `buckets`. It is torn down
4944
+ * entirely unless it is still registered in another bucket.
4945
+ */
4946
+ async #detachSubgraph(instance, buckets) {
4947
+ if (![this.coreSubgraphsMap, this.subgraphs].some((map) => Array.from(map).some(([bucket, subgraphs]) => !buckets.includes(bucket) && subgraphs.includes(instance)))) return this.#removeSubgraphInstance(instance);
4948
+ for (const subgraphsMap of [this.coreSubgraphsMap, this.subgraphs]) for (const bucket of buckets) {
4949
+ const subgraphs = subgraphsMap.get(bucket);
4950
+ if (!subgraphs?.includes(instance)) continue;
4951
+ subgraphsMap.set(bucket, subgraphs.filter((it) => it !== instance));
4952
+ await this.#unmountSubgraph(instance, bucket);
4953
+ }
4954
+ }
4955
+ /** Unmount what `instance` serves at its path in `bucket`: route, handler
4956
+ * cache, SSE route, WebSocket handler and in-process handler. */
4957
+ async #unmountSubgraph(instance, bucket) {
4958
+ const subgraphPath = this.#getSubgraphPath(instance, bucket);
4959
+ if (this.subgraphHandlerCache.get(subgraphPath)?.subgraph !== instance) return;
4960
+ this.subgraphHandlerCache.delete(subgraphPath);
4961
+ const routeHandle = this.subgraphRouteHandles.get(subgraphPath);
4962
+ if (routeHandle !== void 0) {
4963
+ routeHandle.dispose();
4964
+ this.subgraphRouteHandles.delete(subgraphPath);
4965
+ }
4966
+ this.#disposeSSERoute(subgraphPath);
4967
+ if (this.#internalSubgraphHandlers.get(instance.name)?.path === subgraphPath) this.#internalSubgraphHandlers.delete(instance.name);
4968
+ const wsDisposer = this.subgraphWsDisposers.get(subgraphPath);
4969
+ if (wsDisposer) {
4970
+ this.subgraphWsDisposers.delete(subgraphPath);
4971
+ try {
4972
+ await wsDisposer.dispose();
4973
+ } catch (error) {
4974
+ this.logger.error("Error disposing subgraph websocket @name: @error", instance.name, error);
4975
+ }
4976
+ }
4977
+ }
5295
4978
  /**
5296
4979
  * Tear down a subgraph instance: disconnect it, drop it from every
5297
4980
  * bucket, unmount its route, dispose its WebSocket handler, and remove
@@ -5300,44 +4983,58 @@ var GraphQLManager = class {
5300
4983
  */
5301
4984
  async #removeSubgraphInstance(instance) {
5302
4985
  try {
5303
- await instance.onDisconnect?.();
4986
+ await this.#runHook(() => instance.onDisconnect?.());
5304
4987
  } catch (error) {
5305
4988
  this.logger.error("Error disconnecting subgraph @name: @error", instance.name, error);
5306
4989
  }
5307
4990
  for (const subgraphsMap of [this.coreSubgraphsMap, this.subgraphs]) for (const [bucket, subgraphs] of subgraphsMap.entries()) {
5308
4991
  if (!subgraphs.includes(instance)) continue;
5309
4992
  subgraphsMap.set(bucket, subgraphs.filter((it) => it !== instance));
5310
- const subgraphPath = this.#getSubgraphPath(instance, bucket);
5311
- this.subgraphHandlerCache.delete(subgraphPath);
5312
- const routeHandle = this.subgraphRouteHandles.get(subgraphPath);
5313
- if (routeHandle !== void 0) {
5314
- routeHandle.dispose();
5315
- this.subgraphRouteHandles.delete(subgraphPath);
5316
- }
5317
- this.#disposeSSERoute(subgraphPath);
5318
- const wsDisposer = this.subgraphWsDisposers.get(subgraphPath);
5319
- if (wsDisposer) {
5320
- this.subgraphWsDisposers.delete(subgraphPath);
5321
- try {
5322
- await wsDisposer.dispose();
5323
- } catch (error) {
5324
- this.logger.error("Error disposing subgraph websocket @name: @error", instance.name, error);
5325
- }
5326
- }
4993
+ await this.#unmountSubgraph(instance, bucket);
5327
4994
  }
5328
4995
  if (this.#internalSubgraphHandlers.get(instance.name)?.subgraph === instance) this.#internalSubgraphHandlers.delete(instance.name);
5329
- for (const [packageName, byName] of this.packageSubgraphs) {
5330
- if (byName.get(instance.name) !== instance) continue;
5331
- byName.delete(instance.name);
5332
- if (byName.size === 0) this.packageSubgraphs.delete(packageName);
5333
- }
4996
+ const origin = this.#origins.get(instance);
4997
+ this.#origins.delete(instance);
4998
+ if (origin === void 0 || origin === HOST_ORIGIN || origin === CORE_ORIGIN) return;
4999
+ const instances = this.packageSubgraphs.get(origin);
5000
+ instances?.delete(instance);
5001
+ if (instances?.size === 0) this.packageSubgraphs.delete(origin);
5334
5002
  }
5335
5003
  /**
5336
5004
  * Register a pre-constructed subgraph instance.
5337
5005
  * Use this when you need to pass custom dependencies to a subgraph.
5338
5006
  */
5339
5007
  async registerSubgraphInstance(subgraphInstance, supergraph = "", core = false) {
5340
- return this.#addSubgraphInstance(subgraphInstance, supergraph, core);
5008
+ return this.#serialize(() => this.#addSubgraphInstance(subgraphInstance, supergraph, core));
5009
+ }
5010
+ #serialize(task) {
5011
+ if (this.#inHook.getStore()?.active) return task();
5012
+ const run = this.#registryChanges.then(() => this.#inHook.exit(task));
5013
+ this.#registryChanges = run.catch(() => void 0);
5014
+ return run;
5015
+ }
5016
+ async #runHook(hook) {
5017
+ const scope = { active: true };
5018
+ try {
5019
+ await this.#inHook.run(scope, hook);
5020
+ } finally {
5021
+ scope.active = false;
5022
+ }
5023
+ }
5024
+ /** Refresh the router after a registry change; scheduled rather than
5025
+ * awaited when called from inside one. */
5026
+ async #refreshRouter() {
5027
+ if (this.#inHook.getStore()?.active) {
5028
+ this.#scheduleRouterUpdate();
5029
+ return;
5030
+ }
5031
+ await this.updateRouter();
5032
+ }
5033
+ /** Not awaited: a registry change does not wait out the debounce. */
5034
+ #scheduleRouterUpdate() {
5035
+ this.#inHook.exit(() => {
5036
+ runDetached("Router update", () => this.updateRouter(), this.#reporting);
5037
+ });
5341
5038
  }
5342
5039
  /**
5343
5040
  * Get the base path used for subgraph registration.
@@ -5374,7 +5071,45 @@ var GraphQLManager = class {
5374
5071
  * webhooks live under.
5375
5072
  */
5376
5073
  async registerSubgraph(subgraph, supergraph = "", core = false, packageName) {
5377
- const subgraphInstance = new subgraph({
5074
+ return this.#serialize(() => {
5075
+ const instance = this.#createSubgraphInstance(subgraph, packageName);
5076
+ if (packageName !== void 0 && !core) this.#recordPackageClass(packageName, supergraph, instance, subgraph);
5077
+ return this.#addSubgraphInstance(instance, supergraph, core, packageName ?? HOST_ORIGIN);
5078
+ });
5079
+ }
5080
+ #recordPackageClass(packageName, supergraph, instance, subgraph) {
5081
+ let entry = this.#packageClasses.get(packageName);
5082
+ if (!entry) {
5083
+ entry = {
5084
+ supergraph,
5085
+ classes: /* @__PURE__ */ new Map(),
5086
+ refused: /* @__PURE__ */ new Map()
5087
+ };
5088
+ this.#packageClasses.set(packageName, entry);
5089
+ }
5090
+ entry.classes.set(instance.name, subgraph);
5091
+ entry.refused.set(instance.name, instance);
5092
+ }
5093
+ /** Register package subgraphs that are missing because their name was
5094
+ * taken when they last tried, now that the name may be free. */
5095
+ async #restorePackageSubgraphs() {
5096
+ for (const [packageName, { supergraph, classes, refused }] of this.#packageClasses) {
5097
+ const registered = Array.from(this.packageSubgraphs.get(packageName) ?? [], (it) => it.name);
5098
+ for (const [name, subgraph] of classes) {
5099
+ if (registered.includes(name)) continue;
5100
+ if (this.#holdersOf(name).size > 0) continue;
5101
+ try {
5102
+ const instance = refused.get(name) ?? this.#createSubgraphInstance(subgraph, packageName);
5103
+ refused.set(name, instance);
5104
+ await this.#addSubgraphInstance(instance, supergraph, false, packageName);
5105
+ } catch (error) {
5106
+ this.logger.error("Failed to restore subgraph @name from @package: @error", name, packageName, error);
5107
+ }
5108
+ }
5109
+ }
5110
+ }
5111
+ #createSubgraphInstance(subgraph, packageName) {
5112
+ return new subgraph({
5378
5113
  http: this.scopeForPackage(packageName ?? "@powerhousedao/reactor-api"),
5379
5114
  relationalDb: this.relationalDb,
5380
5115
  analyticsStore: this.analyticsStore,
@@ -5388,7 +5123,44 @@ var GraphQLManager = class {
5388
5123
  attachments: this.attachments,
5389
5124
  inspection: this.inspection
5390
5125
  });
5391
- return this.#addSubgraphInstance(subgraphInstance, supergraph, core, packageName);
5126
+ }
5127
+ /**
5128
+ * Apply a package change: `packaged` holds every loaded package's subgraph
5129
+ * classes. Removals run before additions, so a name one package gives up
5130
+ * can be taken by another in the same change. Changes apply one at a time;
5131
+ * the router refresh is scheduled, not awaited.
5132
+ */
5133
+ applyPackageSubgraphs(packaged, supergraph = "graphql") {
5134
+ return this.#serialize(() => this.#applyPackageSubgraphs(packaged, supergraph));
5135
+ }
5136
+ async #applyPackageSubgraphs(packaged, supergraph) {
5137
+ const known = /* @__PURE__ */ new Set([...this.#packageClasses.keys(), ...Array.from(this.packageSubgraphs.keys()).filter((origin) => typeof origin === "string")]);
5138
+ for (const packageName of known) if (!packaged.has(packageName)) await this.#teardownPackage(packageName);
5139
+ this.#packageClasses = /* @__PURE__ */ new Map();
5140
+ const incoming = /* @__PURE__ */ new Map();
5141
+ for (const [packageName, classes] of packaged) {
5142
+ const instances = [];
5143
+ for (const subgraph of classes) try {
5144
+ const instance = this.#createSubgraphInstance(subgraph, packageName);
5145
+ this.#recordPackageClass(packageName, supergraph, instance, subgraph);
5146
+ instances.push(instance);
5147
+ } catch (error) {
5148
+ this.logger.error("Failed to create subgraph @subgraph from @package: @error", subgraph.name, packageName, error);
5149
+ }
5150
+ incoming.set(packageName, instances);
5151
+ await this.#pruneOrigin(packageName, new Set(instances.map((it) => it.name)));
5152
+ }
5153
+ for (const [packageName, instances] of incoming) {
5154
+ const registered = /* @__PURE__ */ new Set();
5155
+ for (const instance of instances) try {
5156
+ const result = await this.#addSubgraphInstance(instance, supergraph, false, packageName);
5157
+ if (result) registered.add(result.name);
5158
+ } catch (error) {
5159
+ this.logger.error("Failed to register subgraph @name from @package: @error", instance.name, packageName, error);
5160
+ }
5161
+ await this.#pruneOrigin(packageName, registered);
5162
+ }
5163
+ this.#scheduleRouterUpdate();
5392
5164
  }
5393
5165
  /**
5394
5166
  * Tear down every subgraph instance registered from `packageName`:
@@ -5398,11 +5170,20 @@ var GraphQLManager = class {
5398
5170
  * package has no registered subgraphs.
5399
5171
  */
5400
5172
  async unregisterPackage(packageName) {
5173
+ if (await this.#serialize(async () => {
5174
+ if (!await this.#teardownPackage(packageName)) return false;
5175
+ await this.#restorePackageSubgraphs();
5176
+ return true;
5177
+ })) await this.#refreshRouter();
5178
+ }
5179
+ /** Release the package's routes and subgraphs; whether any subgraph went. */
5180
+ async #teardownPackage(packageName) {
5401
5181
  this.#disposeHttpScope(packageName);
5402
- const byName = this.packageSubgraphs.get(packageName);
5403
- if (!byName || byName.size === 0) return;
5404
- for (const instance of Array.from(byName.values())) await this.#removeSubgraphInstance(instance);
5405
- await this.updateRouter();
5182
+ this.#packageClasses.delete(packageName);
5183
+ const instances = this.packageSubgraphs.get(packageName);
5184
+ if (!instances || instances.size === 0) return false;
5185
+ for (const instance of Array.from(instances)) await this.#removeSubgraphInstance(instance);
5186
+ return true;
5406
5187
  }
5407
5188
  /**
5408
5189
  * Releases the package's HTTP scope: every route it mounted, and its webhook
@@ -5422,21 +5203,28 @@ var GraphQLManager = class {
5422
5203
  * subgraphs. Refreshes the router if anything was removed.
5423
5204
  */
5424
5205
  async prunePackageSubgraphs(packageName, keepNames) {
5425
- const byName = this.packageSubgraphs.get(packageName);
5426
- if (!byName) return;
5206
+ if (await this.#serialize(async () => {
5207
+ const classes = this.#packageClasses.get(packageName)?.classes;
5208
+ for (const name of Array.from(classes?.keys() ?? [])) if (!keepNames.has(name)) classes?.delete(name);
5209
+ const pruned = await this.#pruneOrigin(packageName, keepNames);
5210
+ if (pruned > 0) await this.#restorePackageSubgraphs();
5211
+ return pruned;
5212
+ }) > 0) await this.#refreshRouter();
5213
+ }
5214
+ /** Remove the origin's subgraphs not named in `keepNames`; how many went. */
5215
+ async #pruneOrigin(origin, keepNames) {
5216
+ const instances = this.packageSubgraphs.get(origin);
5217
+ if (!instances) return 0;
5427
5218
  let removed = 0;
5428
- for (const [name, instance] of Array.from(byName.entries())) if (!keepNames.has(name)) {
5219
+ for (const instance of Array.from(instances)) if (!keepNames.has(instance.name)) {
5429
5220
  await this.#removeSubgraphInstance(instance);
5430
5221
  removed++;
5431
5222
  }
5432
- if (removed > 0) await this.updateRouter();
5223
+ return removed;
5433
5224
  }
5434
5225
  /** Find a registered subgraph by name, core or package-contributed. */
5435
5226
  getSubgraphByName(name) {
5436
- for (const subgraphs of [...this.coreSubgraphsMap.values(), ...this.subgraphs.values()]) {
5437
- const found = subgraphs.find((subgraph) => subgraph.name === name);
5438
- if (found) return found;
5439
- }
5227
+ return this.#findByName(this.coreSubgraphsMap, name) ?? this.#findByName(this.subgraphs, name);
5440
5228
  }
5441
5229
  /** Whether a registered subgraph has a live handler, i.e. whether
5442
5230
  * {@link executeSubgraphQuery} can reach it right now. */
@@ -5472,12 +5260,13 @@ var GraphQLManager = class {
5472
5260
  updateRouter = debounce(this._updateRouter.bind(this), 1e3);
5473
5261
  async _updateRouter() {
5474
5262
  this.logger.debug("Updating router");
5263
+ await this.#setupSubgraphs(this.coreSubgraphsMap);
5475
5264
  await this.#setupSubgraphs(this.subgraphs);
5476
5265
  try {
5477
5266
  await this.gatewayAdapter.updateSupergraph();
5478
5267
  this.logger.debug("Updated Apollo Gateway supergraph");
5479
5268
  } catch (error) {
5480
- this.logger.error("Failed to update Apollo Gateway supergraph: @error", error);
5269
+ reportFailure(this.#reporting, error, "Failed to update Apollo Gateway supergraph: @error");
5481
5270
  }
5482
5271
  const superGraphPath = path.posix.join(this.path, "graphql");
5483
5272
  this.#setupSupergraphSSE(superGraphPath);
@@ -5521,20 +5310,20 @@ var GraphQLManager = class {
5521
5310
  })
5522
5311
  });
5523
5312
  }
5524
- setSupergraph(supergraph, subgraphs) {
5525
- const accepted = [];
5526
- for (const subgraph of subgraphs) {
5527
- if (this.#isCoreNameReserved(subgraph.name)) {
5528
- this.logger.error("Rejecting subgraph @name: name is reserved by a registered core subgraph", subgraph.name);
5529
- continue;
5313
+ /** Replace the subgraphs of `supergraph` with `subgraphs`, under the same
5314
+ * name and type guards as any registration. */
5315
+ async setSupergraph(supergraph, subgraphs) {
5316
+ await this.#serialize(async () => {
5317
+ if (supergraph !== "" && !this.subgraphs.has("graphql")) this.subgraphs.set("graphql", []);
5318
+ let detached = false;
5319
+ for (const previous of [...this.subgraphs.get(supergraph) ?? []]) if (!subgraphs.includes(previous)) {
5320
+ await this.#detachSubgraph(previous, this.#mountBuckets(supergraph));
5321
+ detached = true;
5530
5322
  }
5531
- accepted.push(subgraph);
5532
- }
5533
- this.subgraphs.set(supergraph, accepted);
5534
- const globalSubgraphs = this.subgraphs.get("graphql");
5535
- if (globalSubgraphs) this.subgraphs.set("graphql", [...globalSubgraphs, ...accepted]);
5536
- else this.subgraphs.set("graphql", accepted);
5537
- return this.updateRouter();
5323
+ for (const subgraph of subgraphs) await this.#addSubgraphInstance(subgraph, supergraph, false, HOST_ORIGIN);
5324
+ if (detached) await this.#restorePackageSubgraphs();
5325
+ });
5326
+ return this.#refreshRouter();
5538
5327
  }
5539
5328
  async shutdown() {
5540
5329
  this.logger.info("Shutting down GraphQL Manager");
@@ -5569,18 +5358,33 @@ var GraphQLManager = class {
5569
5358
  for (const [supergraph, subgraphs] of subgraphsMap.entries()) for (const subgraph of subgraphs) {
5570
5359
  this.logger.debug(`Setting up subgraph ${subgraph.name}`);
5571
5360
  const subgraphPath = this.#getSubgraphPath(subgraph, supergraph);
5361
+ if (this.#isExcludedForTypes(subgraph)) {
5362
+ await this.#unmountSubgraph(subgraph, supergraph);
5363
+ continue;
5364
+ }
5572
5365
  try {
5573
5366
  const cached = this.subgraphHandlerCache.get(subgraphPath);
5574
5367
  if (cached) {
5575
- if (cached.subgraph !== subgraph) this.logger.warn("Subgraph path @path already mounted by @kept; @name is shadowed and will not be mounted", subgraphPath, cached.subgraph.name, subgraph.name);
5576
- continue;
5368
+ if (cached.subgraph === subgraph) {
5369
+ if (cached.generated === this.#generated() || !this.#usesModelTypes(subgraph)) continue;
5370
+ } else if (this.#origins.has(cached.subgraph)) {
5371
+ this.logger.warn("Subgraph path @path already mounted by @kept; @name is shadowed and will not be mounted", subgraphPath, cached.subgraph.name, subgraph.name);
5372
+ continue;
5373
+ } else await this.#unmountSubgraph(cached.subgraph, supergraph);
5577
5374
  }
5578
- const schema = createSchema(this.cachedDocumentModels, subgraph.resolvers, subgraph.typeDefs);
5375
+ const generated = this.#generated();
5376
+ const schema = createSchema(this.cachedDocumentModels, subgraph.resolvers, subgraph.typeDefs, this.#schemaOptions(subgraph));
5579
5377
  const rawHandler = await this.gatewayAdapter.createHandler(schema, this.#makeContextFactory());
5378
+ if (!subgraphsMap.get(supergraph)?.includes(subgraph)) continue;
5379
+ if (generated !== this.#generated()) continue;
5380
+ const previous = this.subgraphHandlerCache.get(subgraphPath);
5381
+ if (previous?.subgraph === subgraph && previous.generated === generated) continue;
5382
+ if (previous) await this.#unmountSubgraph(previous.subgraph, supergraph);
5580
5383
  const fetchHandler = this.#composeFetchMiddleware(rawHandler);
5581
5384
  this.subgraphHandlerCache.set(subgraphPath, {
5582
5385
  handler: fetchHandler,
5583
- subgraph
5386
+ subgraph,
5387
+ generated
5584
5388
  });
5585
5389
  this.#setInternalSubgraphHandler(subgraph, subgraphPath, rawHandler);
5586
5390
  this.subgraphRouteHandles.set(subgraphPath, this.httpAdapter.mount(subgraphPath, fetchHandler));
@@ -5611,26 +5415,97 @@ var GraphQLManager = class {
5611
5415
  if (supergraph === "") continue;
5612
5416
  for (const subgraph of subgraphs) {
5613
5417
  const subgraphPath = this.#getSubgraphPath(subgraph, supergraph);
5614
- subgraphsMap.set(subgraphPath, subgraph);
5418
+ if (!subgraphsMap.has(subgraphPath)) subgraphsMap.set(subgraphPath, subgraph);
5615
5419
  }
5616
5420
  }
5617
5421
  return subgraphsMap;
5618
5422
  }
5423
+ /** Excluded subgraphs leave the supergraph only: their routes stay. */
5424
+ #getSupergraphSubgraphs() {
5425
+ const members = /* @__PURE__ */ new Map();
5426
+ for (const [subgraphPath, subgraph] of this.#getAllSubgraphs()) if (!this.#isExcludedForTypes(subgraph)) members.set(subgraphPath, subgraph);
5427
+ const built = new Set(Array.from(members).filter(([subgraphPath, subgraph]) => this.subgraphHandlerCache.get(subgraphPath)?.subgraph === subgraph).map(([, subgraph]) => subgraph));
5428
+ const losers = this.#claimLosers(built);
5429
+ for (const [subgraphPath, subgraph] of members) if (losers.has(subgraph)) members.delete(subgraphPath);
5430
+ return members;
5431
+ }
5432
+ /** Claims go by rank, then first registration; each exclusion logs once. */
5433
+ #claimLosers(subgraphs) {
5434
+ const priority = (subgraph) => {
5435
+ const origin = this.#originOf(subgraph);
5436
+ const order = this.#registrationOrder.get(origin);
5437
+ return [
5438
+ -rank(origin),
5439
+ order?.order ?? Infinity,
5440
+ order?.names.get(subgraph.name) ?? Infinity
5441
+ ];
5442
+ };
5443
+ const ranked = Array.from(subgraphs, (subgraph) => ({
5444
+ subgraph,
5445
+ priority: priority(subgraph)
5446
+ })).sort((a, b) => {
5447
+ const i = a.priority.findIndex((value, j) => value !== b.priority[j]);
5448
+ return i === -1 ? 0 : a.priority[i] - b.priority[i];
5449
+ });
5450
+ const excluded = resolveClaimOwnership(ranked.map(({ subgraph }) => ({
5451
+ candidate: subgraph,
5452
+ name: subgraph.name,
5453
+ claims: this.#claimsOf(subgraph)
5454
+ })));
5455
+ for (const subgraph of subgraphs) {
5456
+ const conflicts = excluded.get(subgraph);
5457
+ if (!conflicts) {
5458
+ this.#loggedOwnershipExclusions.delete(subgraph);
5459
+ continue;
5460
+ }
5461
+ const reason = describeOwnershipConflicts(conflicts);
5462
+ if (this.#loggedOwnershipExclusions.get(subgraph) !== reason) {
5463
+ this.#loggedOwnershipExclusions.set(subgraph, reason);
5464
+ this.logger.error("Excluding subgraph @name from the supergraph: @error", subgraph.name, reason);
5465
+ }
5466
+ }
5467
+ return new Set(excluded.keys());
5468
+ }
5469
+ #claimsOf(subgraph) {
5470
+ const generated = this.#generated();
5471
+ const cached = this.#claims.get(subgraph);
5472
+ if (cached?.typeDefs === subgraph.typeDefs && cached.generated === generated) return cached.claims;
5473
+ let claims;
5474
+ try {
5475
+ claims = collectSubgraphClaims(subgraph.typeDefs, generated.names);
5476
+ } catch {
5477
+ claims = /* @__PURE__ */ new Map();
5478
+ }
5479
+ this.#claims.set(subgraph, {
5480
+ typeDefs: subgraph.typeDefs,
5481
+ generated,
5482
+ claims
5483
+ });
5484
+ return claims;
5485
+ }
5619
5486
  #buildSubgraphSchemaModule(subgraph) {
5620
- return buildSubgraphSchemaModule(this.cachedDocumentModels, subgraph.resolvers, subgraph.typeDefs);
5487
+ return buildSubgraphSchemaModule(this.cachedDocumentModels, subgraph.resolvers, subgraph.typeDefs, this.#schemaOptions(subgraph));
5621
5488
  }
5622
5489
  #getSubgraphDefinitions() {
5623
- const subgraphs = this.#getAllSubgraphs();
5490
+ const subgraphs = this.#getSupergraphSubgraphs();
5624
5491
  const herokuOrLocal = process.env.HEROKU_APP_DEFAULT_DOMAIN_NAME ? `https://${process.env.HEROKU_APP_DEFAULT_DOMAIN_NAME}` : `http://localhost:${this.port}`;
5625
- return Array.from(subgraphs.entries()).map(([subgraphPath, subgraph]) => {
5626
- const module = this.#buildSubgraphSchemaModule(subgraph);
5627
- return {
5492
+ const definitions = [];
5493
+ for (const [subgraphPath, subgraph] of subgraphs) {
5494
+ let module;
5495
+ try {
5496
+ module = this.#buildSubgraphSchemaModule(subgraph);
5497
+ } catch (error) {
5498
+ this.logger.error("Excluding subgraph @name from the supergraph: @error", subgraph.name, error instanceof Error ? error.message : error);
5499
+ continue;
5500
+ }
5501
+ definitions.push({
5628
5502
  name: subgraphPath.replace("/", ":"),
5629
5503
  typeDefs: module.typeDefs,
5630
5504
  resolvers: module.resolvers,
5631
5505
  url: `${herokuOrLocal}${subgraphPath}`
5632
- };
5633
- });
5506
+ });
5507
+ }
5508
+ return definitions;
5634
5509
  }
5635
5510
  async #createSupergraphGateway() {
5636
5511
  const superGraphPath = path.posix.join(this.path, "graphql");
@@ -5643,6 +5518,7 @@ var GraphQLManager = class {
5643
5518
  this.initialized = true;
5644
5519
  }
5645
5520
  }
5521
+ #loggedSSEExclusions = /* @__PURE__ */ new Set();
5646
5522
  /**
5647
5523
  * Set up an SSE subscription endpoint at the supergraph level.
5648
5524
  * Merges the schemas of all subscription-enabled subgraphs so that
@@ -5650,16 +5526,35 @@ var GraphQLManager = class {
5650
5526
  * subgraph paths.
5651
5527
  */
5652
5528
  #setupSupergraphSSE(superGraphPath) {
5653
- const allSubgraphs = this.#getAllSubgraphs();
5654
- const modules = Array.from(allSubgraphs.values()).filter((subgraph) => subgraph.hasSubscriptions).map((subgraph) => this.#buildSubgraphSchemaModule(subgraph));
5655
- if (modules.length === 0) {
5656
- this.#disposeSSERoute(superGraphPath);
5657
- return;
5529
+ const definitions = [];
5530
+ for (const [subgraphPath, subgraph] of this.#getSupergraphSubgraphs()) {
5531
+ if (!subgraph.hasSubscriptions) continue;
5532
+ try {
5533
+ const module = this.#buildSubgraphSchemaModule(subgraph);
5534
+ definitions.push({
5535
+ name: subgraph.name,
5536
+ typeDefs: module.typeDefs,
5537
+ resolvers: module.resolvers,
5538
+ url: subgraphPath
5539
+ });
5540
+ } catch (error) {
5541
+ this.logger.error("Excluding subgraph @name from supergraph SSE: @error", subgraph.name, error instanceof Error ? error.message : error);
5542
+ }
5658
5543
  }
5544
+ const excluded = /* @__PURE__ */ new Set();
5545
+ const buildable = filterBuildableSubgraphs(withoutFederationDirectives(definitions), { error: (message) => {
5546
+ excluded.add(message);
5547
+ if (!this.#loggedSSEExclusions.has(message)) this.logger.error(message);
5548
+ } }, "Supergraph SSE");
5549
+ this.#loggedSSEExclusions = excluded;
5659
5550
  try {
5660
- const mergedSchema = createMergedSchema(modules);
5551
+ const mergedSchema = mergeStreamSubgraphs(buildable);
5552
+ if (mergedSchema === void 0) {
5553
+ this.#disposeSSERoute(superGraphPath);
5554
+ return;
5555
+ }
5661
5556
  this.#setupSSEHandler(mergedSchema, superGraphPath);
5662
- this.logger.debug(`SSE subscriptions enabled at supergraph level (merged from ${modules.length} subgraph(s))`);
5557
+ this.logger.debug(`SSE subscriptions enabled at supergraph level (merged from ${buildable.length} subgraph(s))`);
5663
5558
  } catch (error) {
5664
5559
  this.logger.error("Failed to setup supergraph SSE: @error", error);
5665
5560
  }
@@ -5786,6 +5681,10 @@ function createInspectionResolvers(source, sync, gate) {
5786
5681
  return source.syncInspector;
5787
5682
  };
5788
5683
  const accessFor = (ctx, access) => gate.isOperator(ctx) ? access : null;
5684
+ const throttle = source.throttle;
5685
+ const admit = (ctx) => {
5686
+ if (!gate.isOperator(ctx)) throttle.charge(ctx.user?.address.toLowerCase() ?? "anonymous");
5687
+ };
5789
5688
  return {
5790
5689
  Query: { inspection: () => ({}) },
5791
5690
  ReactorInspection: {
@@ -5806,6 +5705,7 @@ function createInspectionResolvers(source, sync, gate) {
5806
5705
  };
5807
5706
  },
5808
5707
  driveIntegrity: async (_parent, args, ctx) => {
5708
+ admit(ctx);
5809
5709
  const identifier = await gate.assertCanRead(args.driveId, ctx);
5810
5710
  const served = await gate.servedDocument(identifier, args.branch, ctx);
5811
5711
  if (!served) throw new ForbiddenError("to read this document");
@@ -5823,6 +5723,7 @@ function createInspectionResolvers(source, sync, gate) {
5823
5723
  catchUpStatus: operator(() => inspector.getCatchUpStatus()),
5824
5724
  storageHealth: operator(() => inspector.getStorageHealth()),
5825
5725
  validateDocument: async (_parent, args, ctx) => {
5726
+ admit(ctx);
5826
5727
  const branch = args.branch ?? void 0;
5827
5728
  const identifier = await gate.assertCanRead(args.documentId, ctx);
5828
5729
  const served = await gate.servedDocument(identifier, branch, ctx);
@@ -5851,229 +5752,51 @@ function createInspectionResolvers(source, sync, gate) {
5851
5752
  };
5852
5753
  }
5853
5754
  //#endregion
5854
- //#region src/graphql/inspection/schema.ts
5855
- const inspectionTypeDefs = gql`
5856
- type ReactorStorageFacts {
5857
- engine: String!
5858
- persistence: String!
5859
- durable: Boolean!
5860
- selfHeal: Boolean!
5861
- }
5862
-
5863
- type InspectorAccess {
5864
- admin: Boolean!
5865
- sql: Boolean!
5866
- }
5867
-
5868
- """
5869
- What this reactor reports about itself. access is null unless the caller is
5870
- one of the host's admins.
5871
- """
5872
- type ReactorInfo {
5873
- storage: ReactorStorageFacts!
5874
- workflows: Boolean!
5875
- syncChannels: [String!]!
5876
- access: InspectorAccess
5877
- }
5878
-
5879
- type InspectionDocumentModel {
5880
- documentType: String!
5881
- name: String!
5882
- version: Int!
5883
- supportedVersions: [Int!]!
5884
- }
5885
-
5886
- type InspectionDrive {
5887
- driveId: String!
5888
- name: String!
5889
- branch: String!
5890
- collectionId: String!
5891
- documentType: String!
5892
- nodeCount: Int!
5893
- fileCount: Int!
5894
- folderCount: Int!
5895
- otherNodeCount: Int!
5896
- unreadableNodeCount: Int!
5897
- icon: String
5898
- }
5899
-
5900
- type InspectionDrivePage {
5901
- results: [InspectionDrive!]!
5902
- nextCursor: String
5903
- }
5904
-
5905
- type InspectionDriveIntegrityRef {
5906
- id: String!
5907
- documentType: String!
5908
- }
5909
-
5910
- type InspectionDriveIntegrity {
5911
- driveId: String!
5912
- checkedNodeCount: Int!
5913
- totalFileNodeCount: Int!
5914
- """
5915
- File nodes whose document is missing or not served to you; the two are
5916
- reported alike so a withheld document's existence does not leak.
5917
- """
5918
- missingDocuments: [InspectionDriveIntegrityRef!]!
5919
- unsupportedTypes: [InspectionDriveIntegrityRef!]!
5920
- }
5921
-
5922
- type InspectionAttachmentInfo {
5923
- present: Boolean!
5924
- storeKind: String!
5925
- hasReplicator: Boolean!
5926
- replicatorRunning: Boolean!
5927
- backlogScanned: Boolean!
5928
- refsSeen: Int!
5929
- held: Int!
5930
- bytesHeld: Float!
5931
- queued: Int!
5932
- fetching: Int!
5933
- pendingFetches: Int!
5934
- waiting: Int!
5935
- notFound: Int!
5936
- failed: Int!
5937
- lastError: String
5938
- }
5939
-
5940
- """
5941
- A queued job without its actions or operations.
5942
- """
5943
- type InspectionQueueJob {
5944
- id: String!
5945
- kind: String!
5946
- documentId: String!
5947
- scope: String!
5948
- branch: String!
5949
- status: String!
5950
- actionCount: Int!
5951
- operationCount: Int!
5952
- retryCount: Int!
5953
- }
5954
-
5955
- type InspectionQueueState {
5956
- isPaused: Boolean!
5957
- totalPending: Int!
5958
- totalExecuting: Int!
5959
- pendingJobs: [InspectionQueueJob!]!
5960
- executingJobs: [InspectionQueueJob!]!
5961
- }
5962
-
5963
- type InspectionProcessor {
5964
- processorId: String!
5965
- factoryId: String!
5966
- driveId: String!
5967
- processorIndex: Int!
5968
- lastOrdinal: Float!
5969
- status: String!
5970
- lastError: String
5971
- lastErrorTimestampUtcMs: Float
5972
- }
5973
-
5974
- """
5975
- healthy means something only when tracked; an untracked store reports false.
5976
- """
5977
- type InspectionStorageHealth {
5978
- tracked: Boolean!
5979
- healthy: Boolean!
5980
- everRecreated: Boolean!
5981
- recreateCount: Int!
5982
- }
5983
-
5984
- """
5985
- Issues in scopes the caller may not read are left out.
5986
- """
5987
- type InspectionValidation {
5988
- documentId: String!
5989
- isConsistent: Boolean!
5990
- keyframeIssues: [JSONObject!]!
5991
- snapshotIssues: [JSONObject!]!
5992
- streamOrderIssues: [JSONObject!]!
5993
- }
5994
-
5995
- type InspectionCursor {
5996
- cursorType: String!
5997
- cursorOrdinal: Float!
5998
- lastSyncedAtUtcMs: Float
5999
- liveAckOrdinal: Float!
6000
- liveLatestOrdinal: Float!
6001
- }
6002
-
6003
- type InspectionMailboxDepths {
6004
- inbox: Int!
6005
- outbox: Int!
6006
- deadLetter: Int!
6007
- }
6008
-
6009
- type InspectionConnectionHealth {
6010
- snapshot: JSONObject!
6011
- neverSucceeded: Boolean!
6012
- stalenessMs: Float
6013
- }
6014
-
6015
- type InspectionRemote {
6016
- remoteName: String!
6017
- remoteId: String!
6018
- inboxCursor: InspectionCursor!
6019
- outboxCursor: InspectionCursor!
6020
- mailboxDepths: InspectionMailboxDepths!
6021
- connection: InspectionConnectionHealth!
6022
- meta: JSONObject!
6023
- }
6024
-
6025
- """
6026
- A dead letter without its operations.
6027
- """
6028
- type InspectionDeadLetter {
6029
- id: String!
6030
- jobId: String!
6031
- documentId: String!
6032
- branch: String!
6033
- scopes: [String!]!
6034
- errorType: String!
6035
- errorMessage: String!
6036
- operationCount: Int!
6037
- }
6038
-
6039
- type InspectionDeadLetterPage {
6040
- remoteName: String!
6041
- results: [InspectionDeadLetter!]!
6042
- nextCursor: String
6043
- }
6044
-
6045
- """
6046
- Reads only. info and documentModels serve every caller; drive and document
6047
- reads are made as the caller through the reactor read gate; the rest need
6048
- one of the host's admins.
6049
- """
6050
- type ReactorInspection {
6051
- info: ReactorInfo!
6052
- documentModels: [InspectionDocumentModel!]!
6053
- drives(cursor: String, limit: Int): InspectionDrivePage!
6054
- driveIntegrity(driveId: String!, branch: String!): InspectionDriveIntegrity!
6055
- attachmentInfo: InspectionAttachmentInfo!
6056
- queueState: InspectionQueueState!
6057
- processors: [InspectionProcessor!]!
6058
- catchUpStatus: JSONObject!
6059
- storageHealth: InspectionStorageHealth!
6060
- """
6061
- Replays the whole document; expensive.
6062
- """
6063
- validateDocument(documentId: String!, branch: String): InspectionValidation!
6064
- remotes: [InspectionRemote!]!
6065
- remote(remoteName: String!): InspectionRemote!
6066
- deadLetters(
6067
- remoteName: String!
6068
- cursor: String
6069
- limit: Int
6070
- ): InspectionDeadLetterPage!
6071
- }
6072
-
6073
- type Query {
6074
- inspection: ReactorInspection!
6075
- }
6076
- `;
5755
+ //#region src/graphql/inspection/throttle.ts
5756
+ const DEFAULT_INSPECTION_THROTTLE = { callsPerMinute: 6 };
5757
+ const MAX_TRACKED_CALLERS = 1e4;
5758
+ var InspectionThrottledError = class extends GraphQLError {
5759
+ constructor(retryAfterMs) {
5760
+ super("Too many inspection reads; retry later", { extensions: {
5761
+ code: "TOO_MANY_REQUESTS",
5762
+ retryAfterMs
5763
+ } });
5764
+ }
5765
+ };
5766
+ var InspectionThrottle = class {
5767
+ #cap;
5768
+ #buckets = /* @__PURE__ */ new Map();
5769
+ constructor(config = {}) {
5770
+ const cap = config.callsPerMinute ?? DEFAULT_INSPECTION_THROTTLE.callsPerMinute;
5771
+ if (!Number.isFinite(cap) || cap < 1) throw new Error(`Inspection throttle callsPerMinute must be a finite number >= 1, got ${cap}`);
5772
+ this.#cap = cap;
5773
+ }
5774
+ /** Callers with a bucket, at most the 10,000 most recently seen. */
5775
+ get trackedCallers() {
5776
+ return this.#buckets.size;
5777
+ }
5778
+ /** Spends one of the caller's calls; throws when none is left. */
5779
+ charge(caller) {
5780
+ const cap = this.#cap;
5781
+ const perMs = cap / 6e4;
5782
+ const now = performance.now();
5783
+ const bucket = this.#buckets.get(caller);
5784
+ const tokens = bucket ? Math.min(cap, bucket.tokens + (now - bucket.at) * perMs) : cap;
5785
+ this.#buckets.delete(caller);
5786
+ if (tokens < .999999999) {
5787
+ this.#buckets.set(caller, {
5788
+ tokens,
5789
+ at: now
5790
+ });
5791
+ throw new InspectionThrottledError(Math.ceil((1 - tokens) / perMs));
5792
+ }
5793
+ this.#buckets.set(caller, {
5794
+ tokens: Math.max(0, tokens - 1),
5795
+ at: now
5796
+ });
5797
+ if (this.#buckets.size > MAX_TRACKED_CALLERS) this.#buckets.delete(this.#buckets.keys().next().value);
5798
+ }
5799
+ };
6077
5800
  //#endregion
6078
5801
  //#region src/graphql/inspection/source.ts
6079
5802
  function createReactorInspectionSource(module, options = {}) {
@@ -6087,7 +5810,8 @@ function createReactorInspectionSource(module, options = {}) {
6087
5810
  inspector,
6088
5811
  syncInspector: module.syncModule?.syncInspector,
6089
5812
  documentModelRegistry: module.documentModelRegistry,
6090
- facts: inspector
5813
+ facts: inspector,
5814
+ throttle: new InspectionThrottle(options.throttle)
6091
5815
  };
6092
5816
  }
6093
5817
  //#endregion
@@ -6187,7 +5911,7 @@ async function uninstallPackage(service, authorizationService, args, ctx) {
6187
5911
  }
6188
5912
  //#endregion
6189
5913
  //#region src/graphql/packages/schema.graphql
6190
- var schema_default$1 = "# Packages Subgraph Schema\n# Provides operations for runtime package management\n\nscalar DateTime\n\n# Information about an installed package\ntype InstalledPackage {\n # Package name (e.g., \"@powerhousedao/vetra\")\n name: String!\n # Package version if known\n version: String\n # Registry URL where the package was installed from\n registryUrl: String!\n # Timestamp when the package was installed\n installedAt: DateTime!\n # Document type IDs provided by this package\n documentTypes: [String!]!\n}\n\n# Result returned after installing a package\ntype InstallPackageResult {\n # The installed package information\n package: InstalledPackage!\n # Number of document models loaded from the package\n documentModelsLoaded: Int!\n}\n\ntype PackagesQueries {\n # Get all installed packages\n installedPackages: [InstalledPackage!]!\n\n # Get information about a specific installed package\n installedPackage(name: String!): InstalledPackage\n}\n\ntype PackagesMutations {\n # Install a package from the registry (requires admin access)\n installPackage(\n # Package name (e.g., \"@powerhousedao/vetra\")\n name: String!\n # Registry URL (uses default if not provided)\n registryUrl: String\n ): InstallPackageResult!\n\n # Uninstall a package (requires admin access)\n uninstallPackage(\n # Package name to uninstall\n name: String!\n ): Boolean!\n}\n\ntype Query {\n Packages: PackagesQueries!\n}\n\ntype Mutation {\n Packages: PackagesMutations!\n}\n";
5914
+ var schema_default = "# Packages Subgraph Schema\n# Provides operations for runtime package management\n\nscalar DateTime\n\n# Information about an installed package\ntype InstalledPackage {\n # Package name (e.g., \"@powerhousedao/vetra\")\n name: String!\n # Package version if known\n version: String\n # Registry URL where the package was installed from\n registryUrl: String!\n # Timestamp when the package was installed\n installedAt: DateTime!\n # Document type IDs provided by this package\n documentTypes: [String!]!\n}\n\n# Result returned after installing a package\ntype InstallPackageResult {\n # The installed package information\n package: InstalledPackage!\n # Number of document models loaded from the package\n documentModelsLoaded: Int!\n}\n\ntype PackagesQueries {\n # Get all installed packages\n installedPackages: [InstalledPackage!]!\n\n # Get information about a specific installed package\n installedPackage(name: String!): InstalledPackage\n}\n\ntype PackagesMutations {\n # Install a package from the registry (requires admin access)\n installPackage(\n # Package name (e.g., \"@powerhousedao/vetra\")\n name: String!\n # Registry URL (uses default if not provided)\n registryUrl: String\n ): InstallPackageResult!\n\n # Uninstall a package (requires admin access)\n uninstallPackage(\n # Package name to uninstall\n name: String!\n ): Boolean!\n}\n\ntype Query {\n Packages: PackagesQueries!\n}\n\ntype Mutation {\n Packages: PackagesMutations!\n}\n";
6191
5915
  //#endregion
6192
5916
  //#region src/graphql/packages/subgraph.ts
6193
5917
  var PackagesSubgraph = class extends BaseSubgraph {
@@ -6200,7 +5924,7 @@ var PackagesSubgraph = class extends BaseSubgraph {
6200
5924
  }
6201
5925
  name = "packages";
6202
5926
  hasSubscriptions = false;
6203
- typeDefs = gql(schema_default$1);
5927
+ typeDefs = gql(schema_default);
6204
5928
  resolvers = {
6205
5929
  Query: { Packages: () => ({}) },
6206
5930
  PackagesQueries: {
@@ -6674,9 +6398,6 @@ function createReactorGraphQLClient(url, fetchImpl = fetch, headers) {
6674
6398
  return getSdk(createValidatingRequester(url, fetchImpl, headers));
6675
6399
  }
6676
6400
  //#endregion
6677
- //#region src/graphql/reactor/schema.graphql
6678
- var schema_default = "# Scalar types (for codegen - also defined in create-schema.ts)\nscalar JSONObject\nscalar DateTime\n\n# Input types\ninput PagingInput {\n limit: Int\n offset: Int\n cursor: String\n}\n\ninput ViewFilterInput {\n branch: String\n scopes: [String!]\n}\n\ninput SearchFilterInput {\n type: String\n parentId: String\n identifiers: [String!]\n @deprecated(reason: \"Ignored. Filter by type or parentId.\")\n}\n\ninput OperationsFilterInput {\n documentIdOrSlug: String\n documentId: String @deprecated(reason: \"Use documentIdOrSlug.\")\n branch: String\n scopes: [String!]\n actionTypes: [String!]\n sinceRevision: Int\n timestampFrom: String\n timestampTo: String\n}\n\ninput DocumentOperationsFilterInput {\n branch: String\n scopes: [String!]\n actionTypes: [String!]\n sinceRevision: Int\n timestampFrom: String\n timestampTo: String\n}\n\n# Enums\nenum PropagationMode {\n CASCADE\n ORPHAN\n}\n\nenum DocumentChangeType {\n CREATED\n DELETED\n UPDATED\n PARENT_ADDED\n PARENT_REMOVED\n CHILD_ADDED\n CHILD_REMOVED\n}\n\n# Object types\ntype DocumentModelGlobalState {\n id: String!\n name: String!\n namespace: String\n version: String\n specification: JSONObject!\n}\n\ntype DocumentModelResultPage {\n items: [DocumentModelGlobalState!]!\n hasNextPage: Boolean!\n hasPreviousPage: Boolean!\n cursor: String\n}\n\ntype Revision {\n scope: String!\n revision: Int!\n}\n\ntype PHDocument {\n id: String!\n slug: String\n preferredEditor: String\n meta: JSONObject\n protocolVersions: JSONObject\n name: String!\n documentType: String!\n state: JSONObject!\n revisionsList: [Revision!]!\n createdAtUtcIso: DateTime!\n lastModifiedAtUtcIso: DateTime!\n operations(\n filter: DocumentOperationsFilterInput\n paging: PagingInput\n ): ReactorOperationResultPage\n}\n\ntype PHDocumentResultPage {\n items: [PHDocument!]!\n hasNextPage: Boolean!\n hasPreviousPage: Boolean!\n cursor: String\n}\n\n# A directed edge between two documents, with the metadata recorded against it.\ntype DocumentRelationship {\n sourceId: String!\n targetId: String!\n relationshipType: String!\n metadata: JSONObject\n createdAt: DateTime!\n updatedAt: DateTime!\n}\n\ntype DocumentRelationshipResultPage {\n items: [DocumentRelationship!]!\n hasNextPage: Boolean!\n hasPreviousPage: Boolean!\n cursor: String\n}\n\ntype ReactorOperationResultPage {\n items: [ReactorOperation!]!\n hasNextPage: Boolean!\n hasPreviousPage: Boolean!\n cursor: String\n}\n\ntype DeadLetterInfo {\n documentId: String!\n error: String!\n \"\"\"\n How the origin classified the failure. A peer needs this to mirror the origin's\n quarantine decision; without it a held auth operation would freeze the document\n on the peer side while the origin kept syncing.\n \"\"\"\n errorType: String\n jobId: String!\n branch: String!\n scopes: [String!]!\n operationCount: Int!\n}\n\ntype PollSyncEnvelopesResult {\n envelopes: [SyncEnvelope!]!\n ackOrdinal: Int!\n deadLetters: [DeadLetterInfo!]!\n hasMore: Boolean!\n # The server's current manifest revision\n manifestRevision: String\n # The client's manifest revision as the server holds it\n peerManifestRevision: String\n}\n\ntype SyncHoldReason {\n protocol: String!\n version: Int!\n peerSupports: [Int!]!\n}\n\n# A document held back from a remote whose peer cannot run its versions\ntype SyncHold {\n remoteName: String!\n documentId: String!\n branch: String!\n reason: SyncHoldReason!\n heldAtUtcMs: String!\n}\n\ntype PeerAgreementMember {\n remoteName: String!\n # False for a peer that announced nothing: it gets the baselines\n announced: Boolean!\n protocols: JSONObject!\n features: JSONObject!\n}\n\ntype PeerAgreementLimit {\n protocol: String!\n # The remotes whose peers lack the version new documents would take\n remoteNames: [String!]!\n}\n\ntype PeerAgreement {\n collectionId: String!\n local: JSONObject!\n members: [PeerAgreementMember!]!\n limitedBy: [PeerAgreementLimit!]!\n}\n\ntype DocumentWithChildren {\n document: PHDocument!\n childIds: [String!]!\n}\n\n# What a new document gets when its creator chooses nothing\ntype CreateDefaults {\n # \"legacy\" or \"v2-required\"; a client refuses a value it does not know\n signaturePolicy: String!\n protocolVersions: JSONObject!\n}\n\ntype MoveRelationshipResult {\n source: PHDocument!\n target: PHDocument!\n}\n\ntype ConsistencyCoordinate {\n documentId: String!\n scope: String!\n branch: String!\n operationIndex: Int!\n}\n\n\"\"\"\nThe write positions a job reached, for read-after-write. Only meaningful once\nthe job has completed.\n\"\"\"\ntype ConsistencyToken {\n version: Int!\n createdAtUtcIso: String!\n coordinates: [ConsistencyCoordinate!]!\n}\n\n\"The batch a job was submitted in.\"\ntype JobBatchMeta {\n batchId: String!\n batchJobIds: [String!]!\n}\n\ntype JobInfo {\n id: String!\n\n \"\"\"\n The document the job operates on. Empty for a job this server does not know,\n which then comes back FAILED with \"Job not found\".\n \"\"\"\n documentId: String!\n status: String!\n\n \"\"\"\n What the job produced, once it has produced anything. Null until then, which\n is the state every job is in when it is handed back from a submission.\n \"\"\"\n result: JSONObject\n\n error: String\n\n \"The error's class name, such as `DocumentAlreadyExistsError`, when it failed.\"\n errorName: String\n createdAt: DateTime!\n completedAt: DateTime\n consistencyToken: ConsistencyToken!\n meta: JobBatchMeta!\n}\n\n\"\"\"\nOne job's outcome within a batch, pairing the plan key the caller gave with the\njob that applied it. Mirrors one entry of the `Record<string, JobInfo>` that\n`IReactor.executeBatch` returns (packages/reactor/src/core/types.ts).\n\"\"\"\ntype BatchJobResult {\n key: String!\n job: JobInfo!\n}\n\n\"\"\"\nThe outcome of a batch mutation, one entry per job the request named. The wire\nshape of `BatchExecutionResult` (`{ jobs }`), keyed on each entry by the plan\nkey rather than by position so the client can rebuild the record. The batch is\nnot atomic: each job commits on its own and a failed job releases its\ndependents, so each entry's status says what happened to that job, and\nre-submitting re-applies the jobs that succeeded.\n\"\"\"\ntype BatchExecutionResult {\n jobs: [BatchJobResult!]!\n}\n\ntype DocumentChangeEvent {\n type: DocumentChangeType!\n documents: [PHDocument!]!\n context: DocumentChangeContext\n}\n\ntype DocumentChangeContext {\n parentId: String\n childId: String\n}\n\ntype JobChangeEvent {\n jobId: String!\n status: String!\n\n \"\"\"\n What the job produced, once it has produced anything. Nullable for the same\n reason as `JobInfo.result`: a job that has not written yet has produced\n nothing, and an empty object would claim otherwise.\n \"\"\"\n result: JSONObject\n\n error: String\n}\n\ntype ReactorSignerUser {\n address: String!\n networkId: String!\n chainId: Int!\n}\n\ntype ReactorSignerApp {\n name: String!\n key: String!\n}\n\ntype ReactorSigner {\n user: ReactorSignerUser\n app: ReactorSignerApp\n signatures: [String!]!\n}\n\ntype ActionContext {\n signer: ReactorSigner\n}\n\ntype Action {\n id: String!\n type: String!\n timestampUtcMs: String!\n input: JSONObject!\n scope: String!\n context: ActionContext\n}\n\n\"\"\"\nOne operation an authorization preflight predicts a verdict for.\n\n`input` is what a conditional grant reads, so a candidate standing for a\nfilled-in form carries that form's input. Omitting it predicts the verdict an\nempty input earns, not the verdict the filled-in form will get.\n\"\"\"\ninput ActionCandidateInput {\n scope: String!\n type: String!\n input: JSONObject\n}\n\nenum AuthDecision {\n ALLOW\n DENY\n}\n\n\"\"\"\nOne candidate's predicted verdict. `reason` carries the refusal a DENY is\nrecorded with, and is null on an ALLOW.\n\"\"\"\ntype ActionEvaluation {\n decision: AuthDecision!\n reason: String\n}\n\n\"\"\"\nThe predicted verdicts for a set of candidates, in the order they were given,\nwith the aggregates a caller branches on.\n\nThe aggregates are redundant -- a verdict is binary -- and all four are returned\nso a caller reads the one its question is phrased in rather than negating\nanother. Over no candidates every aggregate is false: nothing is allowed and\nnothing is denied.\n\"\"\"\ntype ActionEvaluations {\n evaluations: [ActionEvaluation!]!\n allAllowed: Boolean!\n anyAllowed: Boolean!\n allDenied: Boolean!\n anyDenied: Boolean!\n}\n\n# Input types for sync operations\n\"\"\"\nAn action's context, as a caller submits it.\n\nDeclares every field `ActionContext` carries, because an input object rejects a\nfield it does not declare: an action stamped with the head it applies to - which\nis what a signing client sends - is refused outright if these are missing, and\nthat refusal is a whole-request one, not a per-field one.\n\n`prevOpHash` and `prevOpIndex` are the scope head the action was composed\nagainst. They are recorded rather than enforced; a signature is verified from\nthe params carried in its own tuple, which do not include them.\n\"\"\"\ninput ActionContextInput {\n \"\"\"\n The index of the last operation in the scope the action applies to.\n \"\"\"\n prevOpIndex: Int\n\n \"\"\"\n The hash of the state the action applies to.\n \"\"\"\n prevOpHash: String\n\n \"\"\"\n Covers replay of an operation that would otherwise be a no-op.\n \"\"\"\n nonce: String\n\n signer: ReactorSignerInput\n}\n\ninput ReactorSignerInput {\n user: ReactorSignerUserInput\n app: ReactorSignerAppInput\n signatures: [String!]!\n}\n\ninput ReactorSignerUserInput {\n address: String!\n networkId: String!\n chainId: Int!\n}\n\ninput ReactorSignerAppInput {\n name: String!\n key: String!\n}\n\ninput ActionInput {\n id: String!\n type: String!\n timestampUtcMs: String!\n input: JSONObject!\n scope: String!\n context: ActionContextInput\n}\n\n\"\"\"\nOne mutation job of a batch, mirroring the reactor's `ExecutionJobPlan`\n(packages/reactor/src/core/types.ts). The batch runs its jobs in dependency\norder only, not atomically: each job commits on its own with no batch rollback,\nand a failed job still releases its dependents.\n\n`documentIdOrSlug` is the document the job's actions apply to -- an id that does\nnot yet exist when the job's actions create it. `actions` are coerced against\n`ActionInput` and passed through exactly as `execute` does, so a client-signed\naction keeps its signature. `scope` is the single scope every action in the job\nshares, and `dependsOn` names the plan keys this job is ordered after. `branch`\ndefaults to `main`.\n\"\"\"\ninput ExecutionJobInput {\n key: String!\n documentIdOrSlug: String!\n scope: String!\n branch: String\n actions: [ActionInput!]!\n dependsOn: [String!]!\n}\n\n# Synchronization types\ntype ReactorOperation {\n index: Int!\n timestampUtcMs: String!\n hash: String!\n skip: Int!\n error: String\n deniedReason: String\n id: String\n action: Action!\n}\n\ninput OperationInput {\n index: Int!\n timestampUtcMs: String!\n hash: String!\n skip: Int!\n error: String\n deniedReason: String\n id: String\n action: ActionInput!\n}\n\ntype OperationContext {\n documentId: String!\n documentType: String!\n scope: String!\n branch: String!\n ordinal: Int!\n}\n\ninput OperationContextInput {\n documentId: String!\n documentType: String!\n scope: String!\n branch: String!\n ordinal: Int!\n}\n\ntype OperationWithContext {\n operation: ReactorOperation!\n context: OperationContext!\n}\n\ninput OperationWithContextInput {\n operation: OperationInput!\n context: OperationContextInput!\n}\n\ntype ChannelMeta {\n id: String!\n}\n\ninput ChannelMetaInput {\n id: String!\n}\n\ntype RemoteCursor {\n remoteName: String!\n cursorOrdinal: Int!\n lastSyncedAtUtcMs: String\n}\n\ninput RemoteCursorInput {\n remoteName: String!\n cursorOrdinal: Int!\n lastSyncedAtUtcMs: String\n}\n\nenum SyncEnvelopeType {\n OPERATIONS\n ACK\n}\n\ntype SyncEnvelope {\n type: SyncEnvelopeType!\n channelMeta: ChannelMeta!\n operations: [OperationWithContext!]\n cursor: RemoteCursor\n key: String\n dependsOn: [String!]\n}\n\ninput SyncEnvelopeInput {\n type: SyncEnvelopeType!\n channelMeta: ChannelMetaInput!\n operations: [OperationWithContextInput!]\n cursor: RemoteCursorInput\n key: String\n dependsOn: [String!]\n}\n\ninput RemoteFilterInput {\n documentId: [String!]!\n scope: [String!]!\n branch: String!\n}\n\ninput SyncRefusalInput {\n documentId: String!\n branch: String!\n # \"marker\" for a refused purge marker; absent for UNSUPPORTED_PROTOCOL\n kind: String\n}\n\ninput TouchChannelInput {\n id: String!\n name: String!\n collectionId: String!\n filter: RemoteFilterInput!\n sinceTimestampUtcMs: String!\n # The client's peer manifest; absent from a client without peer agreement\n manifest: JSONObject\n}\n\ntype TouchChannelResult {\n success: Boolean!\n ackOrdinal: Int!\n # The server's peer manifest\n manifest: JSONObject\n}\n\ntype Query {\n # Get document models for a namespace\n documentModels(\n namespace: String\n paging: PagingInput\n ): DocumentModelResultPage!\n\n # Get a specific document by ID or slug\n document(\n idOrSlug: String\n identifier: String @deprecated(reason: \"Use idOrSlug.\")\n view: ViewFilterInput\n ): DocumentWithChildren\n\n # Get outgoing relationships of a given type from a source document\n documentOutgoingRelationships(\n sourceIdOrSlug: String\n sourceIdentifier: String @deprecated(reason: \"Use sourceIdOrSlug.\")\n relationshipType: String!\n view: ViewFilterInput\n paging: PagingInput\n ): PHDocumentResultPage!\n\n # Get incoming relationships of a given type to a target document\n documentIncomingRelationships(\n targetIdOrSlug: String\n targetIdentifier: String @deprecated(reason: \"Use targetIdOrSlug.\")\n relationshipType: String!\n view: ViewFilterInput\n paging: PagingInput\n ): PHDocumentResultPage!\n\n # Get the outgoing relationship edges of a source document. Unlike\n # documentOutgoingRelationships, which returns the documents at the far end,\n # this returns the edges themselves, carrying their metadata and timestamps.\n # Omit relationshipType to return edges of every type.\n documentOutgoingRelationshipEdges(\n sourceIdOrSlug: String\n sourceIdentifier: String @deprecated(reason: \"Use sourceIdOrSlug.\")\n relationshipType: String\n view: ViewFilterInput\n paging: PagingInput\n ): DocumentRelationshipResultPage!\n\n # Get the incoming relationship edges of a target document. Unlike\n # documentIncomingRelationships, which returns the documents at the far end,\n # this returns the edges themselves, carrying their metadata and timestamps.\n # Omit relationshipType to return edges of every type.\n documentIncomingRelationshipEdges(\n targetIdOrSlug: String\n targetIdentifier: String @deprecated(reason: \"Use targetIdOrSlug.\")\n relationshipType: String\n view: ViewFilterInput\n paging: PagingInput\n ): DocumentRelationshipResultPage!\n\n # Find documents by search criteria\n findDocuments(\n search: SearchFilterInput\n view: ViewFilterInput\n paging: PagingInput\n ): PHDocumentResultPage!\n\n # Get job status\n jobStatus(jobId: String!): JobInfo\n\n # Whether findDocuments would serve the document to the caller. Absent or\n # withheld is false; a server that cannot decide answers with an error.\n documentServed(idOrSlug: String!, view: ViewFilterInput): Boolean!\n\n # The signature policy and protocol versions a new document gets, under the\n # parent when one is named. A parent the caller may not read is refused.\n createDefaults(parentIdOrSlug: String): CreateDefaults!\n\n # Get operations for a document with filtering and pagination\n documentOperations(\n filter: OperationsFilterInput!\n paging: PagingInput\n ): ReactorOperationResultPage!\n\n \"\"\"\n Predicts whether the calling subject would be admitted to execute each of a\n set of candidate operations, without submitting any of them. A UI asks this to\n disable a control rather than offer an action that fails on submit.\n\n The answer is a prediction, not a promise:\n\n - Real admission compiles an append condition over everything it read and the\n store enforces it at write time. A preflight reads no future, so a policy\n change landing between this answer and the submit changes the verdict. The\n submit path stays the only authority.\n - The verdict is evaluated at the stream heads, so it is correct for a\n candidate about to be submitted. A backdated submission is out of contract;\n the reactor decides that one by position.\n - A candidate whose verdict depends on its input has to carry that input, since\n a conditional grant reads it.\n\n The subject is the authenticated caller and cannot be named in the request:\n answering for an arbitrary subject would disclose what a policy grants\n somebody else. It carries both the caller's address and the did:key of the app\n instance whose token authenticated the request, so a policy naming either\n matches the same principal the write path presents.\n\n Requires the reactor's authEnforcement feature flag. Without it the reactor\n holds no decision model, so this fails with extensions.code\n AUTH_EVALUATION_UNSUPPORTED rather than guessing.\n \"\"\"\n evaluateActions(\n documentIdOrSlug: String\n documentIdentifier: String @deprecated(reason: \"Use documentIdOrSlug.\")\n branch: String\n candidates: [ActionCandidateInput!]!\n ): ActionEvaluations!\n\n \"\"\"\n Polls for sync envelopes from a channel.\n\n An operation stored before the API required an action id cannot be\n represented by this schema, and rather than serving a partial response beside\n a bare non-null violation, this fails with extensions.code\n MALFORMED_STORED_OPERATION naming the operation. That code means the failure\n is worth polling through: the document holding the operation needs repairing,\n but the channel serves every other document, and a peer that stopped polling\n would stop receiving those too.\n \"\"\"\n pollSyncEnvelopes(\n channelId: String!\n outboxAck: Int!\n outboxLatest: Int!\n # The client's manifest revision; absent from a client without peer agreement\n manifestRevision: String\n # Documents the client refused from earlier polls: held, or a refused marker\n refusals: [SyncRefusalInput!]\n ): PollSyncEnvelopesResult!\n\n # Supreme admin, or the address the named remote's channel is bound to\n syncHolds(remoteName: String, documentId: String): [SyncHold!]!\n\n # Supreme admin, or an address bound to a channel in the collection\n peerAgreement(collectionId: String!): PeerAgreement!\n}\n\ntype Mutation {\n # Create a new document\n createDocument(\n document: JSONObject!\n parentIdOrSlug: String\n parentIdentifier: String @deprecated(reason: \"Use parentIdOrSlug.\")\n ): PHDocument!\n\n # Create an empty document of specified type\n createEmptyDocument(\n documentType: String!\n parentIdOrSlug: String\n parentIdentifier: String @deprecated(reason: \"Use parentIdOrSlug.\")\n ): PHDocument!\n\n \"\"\"\n Applies actions to a document and waits for the result.\n\n Each action is coerced against `ActionInput`, so one missing a field the wire\n declares is refused before any work starts. The id in particular: it is hashed\n into the operation id and replay dedupes by it, so an action without one is\n stored under an operation id shared by every id-less operation on the same\n document, scope and branch.\n\n Named for `IReactorClient.execute`, which this is the wire form of. `branch`\n defaults to `main`.\n \"\"\"\n execute(\n documentIdOrSlug: String\n documentIdentifier: String @deprecated(reason: \"Use documentIdOrSlug.\")\n actions: [ActionInput!]!\n branch: String\n ): PHDocument!\n\n \"\"\"\n Submits actions to a document and returns the job that will apply them.\n\n Coerced exactly as `execute` is, so a malformed action is refused here rather\n than surfacing later as a failed job. Returns the job rather than only its id,\n so a caller has the status and the creation time it would otherwise have to\n ask for; `result` is null until the job produces one.\n \"\"\"\n executeAsync(\n documentIdOrSlug: String\n documentIdentifier: String @deprecated(reason: \"Use documentIdOrSlug.\")\n actions: [ActionInput!]!\n branch: String\n ): JobInfo!\n\n \"\"\"\n Applies multiple mutation jobs in dependency order and waits for all of them,\n the wire form of `IReactorClient.executeBatch`. Each job's actions are coerced\n against `ActionInput` exactly as `execute` is, so client-signed actions pass\n through unchanged, and `dependsOn` orders the jobs. It is synchronous: the jobs\n are applied and awaited before the result returns, so every returned `JobInfo`\n is a completed one rather than the pending receipt the in-process reactor hands\n back. A batch is ordering, not a transaction: each job commits on its own, and\n a failed job still releases the jobs that depend on it, so any job, before or\n after a failure, may have committed. A failed job is therefore returned as a\n FAILED entry with its `error` and `errorName`, beside the final state of every\n other job, rather than failing the mutation. The mutation itself fails only\n when no job state can be reported.\n\n A job carrying `CREATE_DOCUMENT` must be the batch's only job, with the create\n as its first action naming the job's document. Its other actions may only be\n an `UPGRADE_DOCUMENT` of the new document and `ADD_RELATIONSHIP`s targeting\n it. It is authorized like `createDocument`: write on every source of those\n relationships, or the right to create when there is none.\n \"\"\"\n executeBatch(jobs: [ExecutionJobInput!]!): BatchExecutionResult!\n\n # Apply actions to a document (synchronous)\n mutateDocument(\n documentIdentifier: String!\n actions: [JSONObject!]!\n view: ViewFilterInput\n ): PHDocument!\n @deprecated(\n reason: \"Use execute. Actions here are untyped, so a malformed one is refused by a hand-written check rather than by the schema, and `view.scopes` is accepted but ignored.\"\n )\n\n # Submit actions to a document (asynchronous)\n mutateDocumentAsync(\n documentIdentifier: String!\n actions: [JSONObject!]!\n view: ViewFilterInput\n ): String!\n @deprecated(\n reason: \"Use executeAsync, which is typed and returns the job rather than only its id.\"\n )\n\n # Rename a document\n renameDocument(\n documentIdOrSlug: String\n documentIdentifier: String @deprecated(reason: \"Use documentIdOrSlug.\")\n name: String!\n branch: String\n ): PHDocument!\n\n # Update the preferred editor recorded in the document header meta.\n # Pass null/omit to clear it.\n setPreferredEditor(\n documentIdOrSlug: String\n documentIdentifier: String @deprecated(reason: \"Use documentIdOrSlug.\")\n preferredEditor: String\n branch: String\n ): PHDocument!\n\n # Add a relationship between two documents. Adding one that already exists is\n # a no-op, metadata included -- use updateRelationship to change an edge.\n addRelationship(\n sourceIdOrSlug: String\n sourceIdentifier: String @deprecated(reason: \"Use sourceIdOrSlug.\")\n targetIdOrSlug: String\n targetIdentifier: String @deprecated(reason: \"Use targetIdOrSlug.\")\n relationshipType: String!\n metadata: JSONObject\n branch: String\n ): PHDocument!\n\n # Replace the metadata of an existing relationship, preserving its createdAt.\n # Omitting metadata, or passing null, clears it.\n updateRelationship(\n sourceIdOrSlug: String\n sourceIdentifier: String @deprecated(reason: \"Use sourceIdOrSlug.\")\n targetIdOrSlug: String\n targetIdentifier: String @deprecated(reason: \"Use targetIdOrSlug.\")\n relationshipType: String!\n metadata: JSONObject\n branch: String\n ): PHDocument!\n\n # Remove a relationship between two documents\n removeRelationship(\n sourceIdOrSlug: String\n sourceIdentifier: String @deprecated(reason: \"Use sourceIdOrSlug.\")\n targetIdOrSlug: String\n targetIdentifier: String @deprecated(reason: \"Use targetIdOrSlug.\")\n relationshipType: String!\n branch: String\n ): PHDocument!\n\n # Move a relationship from one source to another\n moveRelationship(\n sourceParentIdOrSlug: String\n sourceParentIdentifier: String\n @deprecated(reason: \"Use sourceParentIdOrSlug.\")\n targetParentIdOrSlug: String\n targetParentIdentifier: String\n @deprecated(reason: \"Use targetParentIdOrSlug.\")\n targetIdOrSlug: String\n targetIdentifier: String @deprecated(reason: \"Use targetIdOrSlug.\")\n relationshipType: String!\n branch: String\n ): MoveRelationshipResult!\n\n # Delete a single document\n deleteDocument(\n idOrSlug: String\n identifier: String @deprecated(reason: \"Use idOrSlug.\")\n propagate: PropagationMode\n ): Boolean!\n\n # Delete multiple documents\n deleteDocuments(\n idsOrSlugs: [String!]\n identifiers: [String!] @deprecated(reason: \"Use idsOrSlugs.\")\n propagate: PropagationMode\n ): Boolean!\n\n # Touch (create or update) a channel for sync\n touchChannel(input: TouchChannelInput!): TouchChannelResult!\n\n # Push sync envelopes to a channel\n pushSyncEnvelopes(\n envelopes: [SyncEnvelopeInput!]!\n # The server's manifest revision the client gated these envelopes under\n peerManifestRevision: String\n ): Boolean!\n}\n\ntype Subscription {\n # Subscribe to document changes\n documentChanges(\n search: SearchFilterInput\n view: ViewFilterInput\n ): DocumentChangeEvent!\n\n # Subscribe to job changes\n jobChanges(jobId: String!): JobChangeEvent!\n}\n";
6679
- //#endregion
6680
6401
  //#region src/graphql/reactor/pubsub.ts
6681
6402
  const pubSub = new PubSub();
6682
6403
  function getPubSub() {
@@ -6947,7 +6668,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
6947
6668
  #creatorBinding(ctx) {
6948
6669
  return this.syncServingGate ? ctx.user?.address : void 0;
6949
6670
  }
6950
- typeDefs = gql(schema_default);
6671
+ typeDefs = gql(schema_default$2);
6951
6672
  resolvers = {
6952
6673
  PHDocument: { operations: async (parent, args, ctx) => {
6953
6674
  this.logger.debug("PHDocument.operations(@parent.id, @args)", parent.id, args);
@@ -7602,10 +7323,10 @@ const ADMIN_USERS = getAdminUsers();
7602
7323
  //#endregion
7603
7324
  //#region src/graphql/system/version.ts
7604
7325
  function getVersion() {
7605
- return "6.2.3-dev.54";
7326
+ return "6.2.3-dev.56";
7606
7327
  }
7607
7328
  function getGitHash() {
7608
- return "8383227da9d127169a762bd664609b8e1fce635c";
7329
+ return "5664e2daef8c915c7f66a1f9a92c65d92bfebf0e";
7609
7330
  }
7610
7331
  function getGitUrl() {
7611
7332
  return buildTreeUrl(getGitHash());
@@ -7615,17 +7336,7 @@ function getGitUrl() {
7615
7336
  var SystemSubgraph = class extends BaseSubgraph {
7616
7337
  name = "system";
7617
7338
  hasSubscriptions = false;
7618
- typeDefs = gql`
7619
- type SystemInfo {
7620
- version: String!
7621
- gitHash: String!
7622
- gitUrl: String
7623
- }
7624
-
7625
- type Query {
7626
- system: SystemInfo!
7627
- }
7628
- `;
7339
+ typeDefs = systemTypeDefs;
7629
7340
  resolvers = { Query: { system: () => ({
7630
7341
  version: getVersion(),
7631
7342
  gitHash: getGitHash(),
@@ -8520,8 +8231,16 @@ var PackageManager = class {
8520
8231
  processorMap = /* @__PURE__ */ new Map();
8521
8232
  piecesMap = /* @__PURE__ */ new Map();
8522
8233
  configWatcher;
8234
+ unsubscribePackages;
8235
+ subscribedPackages = /* @__PURE__ */ new Set();
8523
8236
  debouncedUpdateCallbacks = /* @__PURE__ */ new Map();
8524
8237
  eventEmitter = new EventEmitter();
8238
+ get detached() {
8239
+ return {
8240
+ logger: this.logger,
8241
+ report: this.options.reportError
8242
+ };
8243
+ }
8525
8244
  constructor(loaders, options) {
8526
8245
  this.options = options;
8527
8246
  this.loaders = loaders;
@@ -8543,8 +8262,11 @@ var PackageManager = class {
8543
8262
  this.updateSubgraphsMap(subgraphsMap);
8544
8263
  this.updateProcessorsMap(processorsMap);
8545
8264
  this.updatePiecesMap(piecesMap);
8265
+ this.unsubscribePackages?.();
8266
+ this.unsubscribePackages = void 0;
8267
+ this.subscribedPackages = new Set(packages);
8546
8268
  try {
8547
- this.subscribePackages(packages);
8269
+ this.unsubscribePackages = this.subscribePackages(packages);
8548
8270
  } catch (error) {
8549
8271
  this.logger.error("Failed to subscribe to packages: @error", error);
8550
8272
  }
@@ -8559,10 +8281,7 @@ var PackageManager = class {
8559
8281
  async loadDocumentModels(packages) {
8560
8282
  this.logger.debug(`Loading document models from packages: ${packages.join(", ")}`);
8561
8283
  const documentModelModuleMap = /* @__PURE__ */ new Map();
8562
- documentModelModuleMap.set("document-drive", [driveDocumentModelModule]);
8563
- documentModelModuleMap.set("document-model", [documentModelDocumentModelModule]);
8564
- documentModelModuleMap.set("reactor-drive", [reactorDriveDocumentModelModule]);
8565
- documentModelModuleMap.set("reactor-group", [ReactorGroupV1]);
8284
+ for (const [source, model] of baseDocumentModels) documentModelModuleMap.set(source, [model]);
8566
8285
  for (const pkg of packages) {
8567
8286
  const allDocumentModels = [];
8568
8287
  const failures = [];
@@ -8734,13 +8453,13 @@ var PackageManager = class {
8734
8453
  this.updatePiecesMap(piecesMap);
8735
8454
  }
8736
8455
  /** Debounced per key so repeated subscribePackages calls reuse one timer. */
8737
- getDebouncedUpdateCallback(key, update) {
8456
+ getDebouncedUpdateCallback(pkg, kind, update) {
8457
+ const key = `${pkg}:${kind}`;
8738
8458
  if (!this.debouncedUpdateCallbacks.has(key)) {
8739
- const debouncedFn = debounce(update, 1e3);
8459
+ const updateIfSubscribed = () => this.subscribedPackages.has(pkg) ? update() : void 0;
8460
+ const debouncedFn = debounce(() => runDetached(`Updating ${key}`, updateIfSubscribed, this.detached), 1e3);
8740
8461
  this.debouncedUpdateCallbacks.set(key, () => {
8741
- debouncedFn().catch((error) => {
8742
- this.logger.error("Failed to update package: @error", error);
8743
- });
8462
+ debouncedFn();
8744
8463
  });
8745
8464
  }
8746
8465
  return this.debouncedUpdateCallbacks.get(key);
@@ -8748,10 +8467,10 @@ var PackageManager = class {
8748
8467
  subscribePackages(packages) {
8749
8468
  const unsubs = [];
8750
8469
  for (const pkg of packages) {
8751
- const onDocumentModels = this.getDebouncedUpdateCallback(`${pkg}:document-models`, () => this.updateDocumentModelsForPackage(pkg));
8752
- const onSubgraphs = this.getDebouncedUpdateCallback(`${pkg}:subgraphs`, () => this.updateSubgraphsForPackage(pkg));
8753
- const onProcessors = this.getDebouncedUpdateCallback(`${pkg}:processors`, () => this.updateProcessorsForPackage(pkg));
8754
- const onPieces = this.getDebouncedUpdateCallback(`${pkg}:pieces`, () => this.updatePiecesForPackage(pkg));
8470
+ const onDocumentModels = this.getDebouncedUpdateCallback(pkg, "document-models", () => this.updateDocumentModelsForPackage(pkg));
8471
+ const onSubgraphs = this.getDebouncedUpdateCallback(pkg, "subgraphs", () => this.updateSubgraphsForPackage(pkg));
8472
+ const onProcessors = this.getDebouncedUpdateCallback(pkg, "processors", () => this.updateProcessorsForPackage(pkg));
8473
+ const onPieces = this.getDebouncedUpdateCallback(pkg, "pieces", () => this.updatePiecesForPackage(pkg));
8755
8474
  for (const loader of this.loaders) {
8756
8475
  if (loader.onDocumentModelsChange) unsubs.push(loader.onDocumentModelsChange(pkg, onDocumentModels));
8757
8476
  if (loader.onSubgraphsChange) unsubs.push(loader.onSubgraphsChange(pkg, onSubgraphs));
@@ -8764,17 +8483,17 @@ var PackageManager = class {
8764
8483
  };
8765
8484
  }
8766
8485
  getAllPackageNames() {
8767
- const packageNames = this.options.packages ?? [];
8768
- if (this.options.configFile) packageNames.push(...this.getPackageNamesFromConfigFile(this.options.configFile));
8769
- return packageNames;
8486
+ const packageNames = new Set(this.options.packages);
8487
+ if (this.options.configFile) for (const name of this.getPackageNamesFromConfigFile(this.options.configFile)) packageNames.add(name);
8488
+ return Array.from(packageNames);
8770
8489
  }
8771
8490
  getPackageNamesFromConfigFile(configFile) {
8772
8491
  return getConfig(configFile).packages?.map((pkg) => pkg.packageName) ?? [];
8773
8492
  }
8774
8493
  initConfigFileWatcher(configFile) {
8775
8494
  if (!this.configWatcher) this.configWatcher = watchFile(configFile, { interval: 100 }, (curr, prev) => {
8776
- if (curr.mtime === prev.mtime) return;
8777
- this.loadPackages(this.getAllPackageNames());
8495
+ if (curr.mtimeMs === prev.mtimeMs) return;
8496
+ runDetached("Reloading packages from the config file", () => this.loadPackages(this.getAllPackageNames()), this.detached);
8778
8497
  });
8779
8498
  }
8780
8499
  updatePackagesMap(packagesMap) {
@@ -8813,6 +8532,10 @@ var PackageManager = class {
8813
8532
  this.piecesMap = piecesMap;
8814
8533
  this.eventEmitter.emit("piecesChange", piecesMap);
8815
8534
  }
8535
+ /** The document models every loaded package ships, keyed by the package. */
8536
+ getDocumentModels() {
8537
+ return new Map(this.docModelsMap);
8538
+ }
8816
8539
  /** The pieces every loaded package ships, keyed by the package. */
8817
8540
  getPieces() {
8818
8541
  return new Map(this.piecesMap);
@@ -8825,6 +8548,7 @@ var PackageManager = class {
8825
8548
  */
8826
8549
  removePackage(pkg) {
8827
8550
  this.logger.info(`Removing package: ${pkg}`);
8551
+ this.subscribedPackages.delete(pkg);
8828
8552
  const dropKey = (map) => {
8829
8553
  if (!map.has(pkg)) return map;
8830
8554
  const next = new Map(map);
@@ -8842,22 +8566,39 @@ var PackageManager = class {
8842
8566
  this.updatePiecesMap(this.piecesMap);
8843
8567
  }
8844
8568
  onDocumentModelsChange(handler) {
8845
- this.eventEmitter.on("documentModelsChange", handler);
8569
+ this.eventEmitter.on("documentModelsChange", (documentModels) => {
8570
+ runDetached("Document models change listener", () => handler(documentModels), this.detached);
8571
+ });
8846
8572
  }
8847
8573
  onSubgraphsChange(handler) {
8848
- this.eventEmitter.on("subgraphsChange", handler);
8574
+ this.eventEmitter.on("subgraphsChange", (subgraphs) => {
8575
+ runDetached("Subgraphs change listener", () => handler(subgraphs), this.detached);
8576
+ });
8849
8577
  }
8850
8578
  onProcessorsChange(handler) {
8851
- this.eventEmitter.on("processorsChange", handler);
8579
+ this.eventEmitter.on("processorsChange", (processors) => {
8580
+ runDetached("Processors change listener", () => handler(processors), this.detached);
8581
+ });
8852
8582
  }
8853
8583
  onPiecesChange(handler) {
8854
- this.eventEmitter.on("piecesChange", handler);
8584
+ this.eventEmitter.on("piecesChange", (pieces) => {
8585
+ runDetached("Pieces change listener", () => handler(pieces), this.detached);
8586
+ });
8855
8587
  }
8856
8588
  };
8857
8589
  //#endregion
8858
8590
  //#region src/config.ts
8859
8591
  const config = { basePath: process.env.BASE_PATH || "/" };
8860
8592
  const DefaultCoreSubgraphs = [AnalyticsSubgraph, SystemSubgraph];
8593
+ /** The core subgraphs a server registers, given its optional services. */
8594
+ function coreSubgraphClasses(options) {
8595
+ return [
8596
+ ...DefaultCoreSubgraphs,
8597
+ ReactorSubgraph,
8598
+ ...options.inspection ? [InspectionSubgraph] : [],
8599
+ ...options.documentPermissions ? [AuthSubgraph] : []
8600
+ ];
8601
+ }
8861
8602
  //#endregion
8862
8603
  //#region src/attachment-backend.ts
8863
8604
  /** Filesystem is the default; explicit S3 is readiness-gated without fallback. */
@@ -9378,6 +9119,90 @@ async function runMigrations(db) {
9378
9119
  }
9379
9120
  }
9380
9121
  //#endregion
9122
+ //#region src/packages/package-listeners.ts
9123
+ function setupEventListeners(pkgManager, graphqlManager, reactorProcessorManager, moduleFor, documentModelRegistry, { logger = childLogger(["reactor-api", "package-listeners"]), reportError } = {}) {
9124
+ const reporting = {
9125
+ logger,
9126
+ report: reportError
9127
+ };
9128
+ const typesOf = (models) => new Set(models.map((m) => m.documentModel.global.id));
9129
+ const packagedTypes = new Map(Array.from(pkgManager.getDocumentModels(), ([pkg, models]) => [pkg, typesOf(models)]));
9130
+ pkgManager.onDocumentModelsChange(async (packagedModels) => {
9131
+ if (documentModelRegistry) {
9132
+ const newModules = getUniqueDocumentModels(Object.values(packagedModels).flat());
9133
+ const incomingTypes = typesOf(newModules);
9134
+ const removedTypes = /* @__PURE__ */ new Set();
9135
+ for (const [pkg, models] of Object.entries(packagedModels)) {
9136
+ if (models.length === 0) continue;
9137
+ for (const type of packagedTypes.get(pkg) ?? []) if (!incomingTypes.has(type)) removedTypes.add(type);
9138
+ packagedTypes.set(pkg, typesOf(models));
9139
+ }
9140
+ if (removedTypes.size > 0) {
9141
+ documentModelRegistry.unregisterModules(...removedTypes);
9142
+ documentModelRegistry.unregisterUpgradeManifests(...removedTypes);
9143
+ logger.info("Unregistered document models: @types", Array.from(removedTypes).join(", "));
9144
+ }
9145
+ if (incomingTypes.size > 0) {
9146
+ documentModelRegistry.unregisterModules(...incomingTypes);
9147
+ const results = documentModelRegistry.registerModules(...newModules);
9148
+ for (const result of results) if (result.status === "success") logger.info(`Registered document model: ${result.item.documentModel.global.id} v${result.item.version ?? 1}`);
9149
+ else logger.error(`Failed to register document model: ${result.error.message}`);
9150
+ }
9151
+ const manifests = pkgManager.getUniqueUpgradeManifests();
9152
+ if (manifests.length > 0) {
9153
+ documentModelRegistry.unregisterUpgradeManifests(...manifests.map((m) => m.documentType));
9154
+ const manifestResults = documentModelRegistry.registerUpgradeManifests(...manifests);
9155
+ for (const result of manifestResults) if (result.status === "error") logger.error(`Failed to register upgrade manifest: ${result.error.message}`);
9156
+ }
9157
+ }
9158
+ try {
9159
+ await graphqlManager.regenerateDocumentModelSubgraphs();
9160
+ } catch (error) {
9161
+ reportFailure(reporting, error, "Document model change left subgraphs stale: @error");
9162
+ }
9163
+ });
9164
+ pkgManager.onSubgraphsChange(async (packagedSubgraphs) => {
9165
+ try {
9166
+ await graphqlManager.applyPackageSubgraphs(packagedSubgraphs);
9167
+ } catch (error) {
9168
+ reportFailure(reporting, error, "Failed to apply package subgraphs: @error");
9169
+ }
9170
+ });
9171
+ let knownProcessorPackages = /* @__PURE__ */ new Set();
9172
+ pkgManager.onProcessorsChange(async (processors) => {
9173
+ for (const packageName of knownProcessorPackages) if (!processors.has(packageName)) try {
9174
+ await reactorProcessorManager.unregisterFactory(packageName);
9175
+ } catch (error) {
9176
+ reportFailure(reporting, error, "Failed to unregister processors of @package: @error", packageName);
9177
+ }
9178
+ knownProcessorPackages = new Set(processors.keys());
9179
+ for (const [packageName, fns] of processors) {
9180
+ try {
9181
+ await reactorProcessorManager.unregisterFactory(packageName);
9182
+ } catch (error) {
9183
+ reportFailure(reporting, error, "Failed to unregister processors of @package: @error", packageName);
9184
+ }
9185
+ const factories = await Promise.allSettled(fns.map(async (fn) => fn(moduleFor(packageName))));
9186
+ const validBuilders = [];
9187
+ for (const factory of factories) if (factory.status === "rejected") reportFailure(reporting, factory.reason, "Processor factory builder of @package failed: @error", packageName);
9188
+ else if (typeof factory.value === "function") validBuilders.push(factory.value);
9189
+ if (!validBuilders.length) continue;
9190
+ try {
9191
+ await reactorProcessorManager.registerFactory(packageName, async (driveHeader) => (await Promise.all(validBuilders.map(async (driveFactory) => {
9192
+ try {
9193
+ return await driveFactory(driveHeader);
9194
+ } catch (error) {
9195
+ reportFailure(reporting, error, "Creating a processor of @package for drive @drive failed: @error", packageName, driveHeader.id);
9196
+ return [];
9197
+ }
9198
+ }))).flat());
9199
+ } catch (error) {
9200
+ reportFailure(reporting, error, "Failed to register processors of @package: @error", packageName);
9201
+ }
9202
+ }
9203
+ });
9204
+ }
9205
+ //#endregion
9381
9206
  //#region src/services/auth.service.ts
9382
9207
  const DEFAULT_CREDENTIAL_CACHE_TTL_MS = 6e4;
9383
9208
  const CREDENTIAL_CACHE_MAX_ENTRIES = 1e3;
@@ -10227,7 +10052,7 @@ function resolveGatewayAdapterType(logger) {
10227
10052
  /**
10228
10053
  * Sets up the subgraph manager and registers subgraphs
10229
10054
  */
10230
- async function setupGraphQLManager({ httpAdapter, authFetchMiddleware, requireAuthFetchMiddleware, httpServer, wsServer, client, relationalDb, analyticsStore, syncManager, subgraphs, logger, authorizationService, authService, documentPermissionService, enableDocumentModelSubgraphs, port, reactorDriveClient, syncServingGate, httpRoutes, attachments, inspection, driveStore }) {
10055
+ async function setupGraphQLManager({ httpAdapter, authFetchMiddleware, requireAuthFetchMiddleware, httpServer, wsServer, client, relationalDb, analyticsStore, syncManager, subgraphs, logger, authorizationService, authService, documentPermissionService, enableDocumentModelSubgraphs, port, reactorDriveClient, syncServingGate, httpRoutes, attachments, inspection, driveStore, reportError }) {
10231
10056
  const graphqlManager = new GraphQLManager({
10232
10057
  path: config.basePath,
10233
10058
  httpServer,
@@ -10249,75 +10074,15 @@ async function setupGraphQLManager({ httpAdapter, authFetchMiddleware, requireAu
10249
10074
  httpRoutes,
10250
10075
  attachments,
10251
10076
  inspection,
10252
- driveStore
10077
+ driveStore,
10078
+ reportError
10253
10079
  });
10254
10080
  await graphqlManager.init(subgraphs.core, authFetchMiddleware, requireAuthFetchMiddleware);
10255
- for (const [packageName, collection] of subgraphs.extended.entries()) for (const subgraph of collection) await graphqlManager.registerSubgraph(subgraph, "graphql", false, packageName);
10081
+ await graphqlManager.applyPackageSubgraphs(subgraphs.extended);
10256
10082
  await graphqlManager.updateRouter();
10257
10083
  return graphqlManager;
10258
10084
  }
10259
10085
  /**
10260
- * Sets up event listeners for package manager changes
10261
- */
10262
- function setupEventListeners(pkgManager, graphqlManager, reactorProcessorManager, moduleFor, documentModelRegistry) {
10263
- pkgManager.onDocumentModelsChange((packagedModels) => {
10264
- if (documentModelRegistry) {
10265
- const newModules = getUniqueDocumentModels(Object.values(packagedModels).flat());
10266
- const incomingTypes = new Set(newModules.map((m) => m.documentModel.global.id));
10267
- if (incomingTypes.size > 0) {
10268
- documentModelRegistry.unregisterModules(...incomingTypes);
10269
- const results = documentModelRegistry.registerModules(...newModules);
10270
- for (const result of results) if (result.status === "success") defaultLogger.info(`Registered document model: ${result.item.documentModel.global.id} v${result.item.version ?? 1}`);
10271
- else defaultLogger.error(`Failed to register document model: ${result.error.message}`);
10272
- }
10273
- const manifests = pkgManager.getUniqueUpgradeManifests();
10274
- if (manifests.length > 0) {
10275
- documentModelRegistry.unregisterUpgradeManifests(...manifests.map((m) => m.documentType));
10276
- const manifestResults = documentModelRegistry.registerUpgradeManifests(...manifests);
10277
- for (const result of manifestResults) if (result.status === "error") defaultLogger.error(`Failed to register upgrade manifest: ${result.error.message}`);
10278
- }
10279
- }
10280
- graphqlManager.regenerateDocumentModelSubgraphs();
10281
- });
10282
- let knownSubgraphPackages = /* @__PURE__ */ new Set();
10283
- pkgManager.onSubgraphsChange((packagedSubgraphs) => {
10284
- (async () => {
10285
- for (const [packageName, subgraphs] of packagedSubgraphs) {
10286
- const incomingNames = /* @__PURE__ */ new Set();
10287
- for (const subgraph of subgraphs) {
10288
- const instance = await graphqlManager.registerSubgraph(subgraph, "graphql", false, packageName);
10289
- if (!instance) continue;
10290
- incomingNames.add(instance.name);
10291
- }
10292
- await graphqlManager.prunePackageSubgraphs(packageName, incomingNames);
10293
- }
10294
- for (const packageName of knownSubgraphPackages) if (!packagedSubgraphs.has(packageName)) await graphqlManager.unregisterPackage(packageName);
10295
- knownSubgraphPackages = new Set(packagedSubgraphs.keys());
10296
- await graphqlManager.updateRouter();
10297
- })();
10298
- });
10299
- let knownProcessorPackages = /* @__PURE__ */ new Set();
10300
- pkgManager.onProcessorsChange((processors) => {
10301
- (async () => {
10302
- for (const packageName of knownProcessorPackages) if (!processors.has(packageName)) await reactorProcessorManager.unregisterFactory(packageName);
10303
- knownProcessorPackages = new Set(processors.keys());
10304
- for (const [packageName, fns] of processors) {
10305
- await reactorProcessorManager.unregisterFactory(packageName);
10306
- const validBuilders = fns.map((fn) => fn(moduleFor(packageName))).filter((factory) => typeof factory === "function");
10307
- if (!validBuilders.length) continue;
10308
- await reactorProcessorManager.registerFactory(packageName, async (driveHeader) => (await Promise.all(validBuilders.map(async (driveFactory) => {
10309
- try {
10310
- return await driveFactory(driveHeader);
10311
- } catch (e) {
10312
- defaultLogger.error(`Error creating processor for drive ${driveHeader.id}:`, e);
10313
- return [];
10314
- }
10315
- }))).flat());
10316
- }
10317
- })();
10318
- });
10319
- }
10320
- /**
10321
10086
  * Starts the server (HTTP or HTTPS) and attaches WebSocket server
10322
10087
  */
10323
10088
  async function startServer(httpAdapter, port, httpsOptions, logger) {
@@ -10508,7 +10273,8 @@ async function _setupCommonInfrastructure(options) {
10508
10273
  logger.info("Attachment service initialized");
10509
10274
  const packages = new PackageManager(options.packageLoaders ?? [new ImportPackageLoader()], {
10510
10275
  configFile: options.configFile,
10511
- packages: options.packages ?? []
10276
+ packages: options.packages ?? [],
10277
+ reportError: options.reportError
10512
10278
  });
10513
10279
  const publicUrl = resolvePublicOrigin(port);
10514
10280
  const webhooks = new WebhookService({
@@ -10597,13 +10363,11 @@ async function _setupAPI(reactorClient, syncManager, reactorProcessorManager, ht
10597
10363
  refuseAnonymousReads: floor
10598
10364
  });
10599
10365
  const attachmentClientProvider = new AttachmentClientProvider(attachments.service, attachmentAccess, logger);
10600
- const coreSubgraphs = DefaultCoreSubgraphs.slice();
10601
- coreSubgraphs.push(ReactorSubgraph);
10602
- if (inspection) coreSubgraphs.push(InspectionSubgraph);
10603
- if (documentPermissionService) {
10604
- coreSubgraphs.push(AuthSubgraph);
10605
- logger.info("Auth subgraph registered (document permissions enabled)");
10606
- }
10366
+ const coreSubgraphs = coreSubgraphClasses({
10367
+ inspection: !!inspection,
10368
+ documentPermissions: !!documentPermissionService
10369
+ });
10370
+ if (documentPermissionService) logger.info("Auth subgraph registered (document permissions enabled)");
10607
10371
  const graphqlManager = await setupGraphQLManager({
10608
10372
  httpAdapter,
10609
10373
  authFetchMiddleware,
@@ -10629,9 +10393,13 @@ async function _setupAPI(reactorClient, syncManager, reactorProcessorManager, ht
10629
10393
  httpRoutes,
10630
10394
  attachments: attachmentClientProvider,
10631
10395
  inspection,
10632
- driveStore
10396
+ driveStore,
10397
+ reportError: options.reportError
10398
+ });
10399
+ setupEventListeners(packages, graphqlManager, reactorProcessorManager, moduleFor, documentModelRegistry, {
10400
+ logger,
10401
+ reportError: options.reportError
10633
10402
  });
10634
- setupEventListeners(packages, graphqlManager, reactorProcessorManager, moduleFor, documentModelRegistry);
10635
10403
  if (mcpServerEnabled) {
10636
10404
  await setupMcpServer({
10637
10405
  client: reactorClient,
@@ -10725,7 +10493,7 @@ async function initializeAndStartAPI(clientInitializer, options, processorApp) {
10725
10493
  const documentModelRegistry = reactorClientModule.reactorModule?.documentModelRegistry;
10726
10494
  if (!documentModelRegistry) throw new Error("DocumentModelRegistry not available from InProcessReactorClientModule");
10727
10495
  return {
10728
- ...await _setupAPI(reactorClient, syncManager, reactorProcessorManager, httpAdapter, authFetchMiddleware, requireAuthFetchMiddleware, authEnabled, authService, port, packages, relationalDb, analyticsStore, documentPermissionService, processors, subgraphs, options, processorApp, (reactorClientModule.reactorModule?.readModelCoordinator)?.readModels ?? [], attachments, attachmentReferenceIndex, attachmentReferenceProjection, authorizationConfig, documentModelRegistry, dbClosers, reactorDriveClient, buildSyncServingGate(reactorClientModule.reactorModule, authorizationConfig, options.logger ?? defaultLogger), httpRoutes, attachmentReadsFollowDocumentPolicy, reactorClientModule.reactorModule ? createReactorInspectionSource(reactorClientModule.reactorModule, {
10496
+ ...await _setupAPI(reactorClient, syncManager, reactorProcessorManager, httpAdapter, authFetchMiddleware, requireAuthFetchMiddleware, authEnabled, authService, port, packages, relationalDb, analyticsStore, documentPermissionService, processors, subgraphs, options, processorApp, (reactorClientModule.reactorModule?.readModelCoordinator)?.readModels ?? [], attachments, attachmentReferenceIndex, attachmentReferenceProjection, authorizationConfig, documentModelRegistry, dbClosers, reactorDriveClient, buildSyncServingGate(reactorClientModule.reactorModule, authorizationConfig, options.logger ?? defaultLogger), httpRoutes, attachmentReadsFollowDocumentPolicy, reactorClientModule.reactorModule && options.inspection !== false ? createReactorInspectionSource(reactorClientModule.reactorModule, {
10729
10497
  ...options.inspection,
10730
10498
  attachmentStore: attachmentInspectionStore(attachments)
10731
10499
  }) : void 0, reactorClientModule.reactorModule?.reactor),
@@ -10911,7 +10679,7 @@ var PackageManagementService = class {
10911
10679
  }
10912
10680
  };
10913
10681
  //#endregion
10914
- export { ADMIN_USERS, ActionCandidateInputSchema, ActionContextInputSchema, ActionInputSchema, AddRelationshipDocument, AnalyticsSubgraph, AttachmentAccessFailed, AttachmentAccessService, AttachmentAccessUnavailable, AttachmentClientProvider, AuthDecision, AuthDecisionSchema, AuthEvaluationUnsupportedError, AuthService, AuthSubgraph, AuthenticationRequiredError, AuthorizationPolicy, AuthorizedAttachmentService, AuthorizedDocumentHandle, BaseSubgraph, CORE_PACKAGE_NAME, CanonicalDocumentIdResolutionError, ChannelMetaInputSchema, CreateDocumentDocument, CreateEmptyDocumentDocument, DeleteDocumentDocument, DeleteDocumentsDocument, DocumentChangeType, DocumentChangeTypeSchema, DocumentChangesDocument, DocumentOperationsFilterInputSchema, DocumentPermissionService, DocumentRelationshipFieldsFragmentDoc, EvaluateActionsDocument, ExecuteBatchDocument, ExecutionJobInputSchema, FindDocumentsDocument, ForbiddenError, GetCreateDefaultsDocument, GetDocumentDocument, GetDocumentIncomingRelationshipEdgesDocument, GetDocumentIncomingRelationshipsDocument, GetDocumentModelsDocument, GetDocumentOperationsDocument, GetDocumentOutgoingRelationshipEdgesDocument, GetDocumentOutgoingRelationshipsDocument, GetDocumentServedDocument, GetDocumentWithOperationsDocument, GetJobStatusDocument, GraphQLManager, HttpDocumentModelLoader, HttpPackageLoader, HttpRouteService, ImportPackageLoader, InMemoryPackageStorage, InspectionSubgraph, InvalidNamespaceError, JobChangesDocument, JobInfoFieldsFragmentDoc, MalformedStoredOperationError, MemoryWebhookStore, MoveRelationshipDocument, MutateDocumentAsyncDocument, MutateDocumentDocument, OperationContextInputSchema, OperationInputSchema, OperationWithContextInputSchema, OperationsFilterInputSchema, PACKAGE_ROUTE_SEGMENT, PGLITE_UTC_PARSERS, PackageManagementService, PackageManager, PackagesSubgraph, PagingInputSchema, PhDocumentFieldsFragmentDoc, PollSyncEnvelopesDocument, PrivacyPermissionAdapter, PropagationMode, PropagationModeSchema, PushSyncEnvelopesDocument, ReactorSignerAppInputSchema, ReactorSignerInputSchema, ReactorSignerUserInputSchema, ReactorSubgraph, RefusalNotRecordedError, RelationalWebhookStore, RemoteCursorInputSchema, RemoteFilterInputSchema, RemoveRelationshipDocument, RenameDocumentDocument, SearchFilterInputSchema, SetPreferredEditorDocument, SyncEnvelopeInputSchema, SyncEnvelopeType, SyncEnvelopeTypeSchema, SyncRefusalInputSchema, SystemSubgraph, TouchChannelDocument, TouchChannelInputSchema, UpdateRelationshipDocument, ViewFilterInputSchema, WEBHOOK_SEGMENT, WS_AUTH_CLOSE_REASONS, WS_CLOSE_REASON_AUTHENTICATION_REQUIRED, WS_CLOSE_REASON_BEARER_REJECTED, WebhookService, assertAttachmentPolicyReadsAllowed, assertAuthRequiredForDocumentPermissions, assertCredentialVerifierForSource, assertHostMountPath, assertRequireAuthenticatedCallerAllowed, assertSkipCredentialVerificationAllowed, buildGraphQlDocument, buildGraphQlDriveDocument, buildGraphqlOperation, buildGraphqlOperations, buildSubgraphSchemaModule, callerSubject, createAuthFetchMiddleware, createCanonicalDocumentIdResolver, createGatewayAdapter, createHttpAdapter, createInspectionResolvers, createMergedSchema, createReactorGraphQLClient, createReactorInspectionSource, createRenownCredentialVerifier, createSchema, createWsAuthHandlers, decodeExplorerUrlState, definedNonNullAnySchema, driveIdFromUrl, extractSubgraphs, extractSubgraphsFromModule, generateDocumentModelSchema, getAuthContext, getDbClient, getDocumentModelSchemaName, getDocumentModelTypeDefs, getExplorerPrefix, getGitHash, getGitUrl, getSdk, getUniqueDocumentModels, getUniqueUpgradeManifests, getVersion, initAnalyticsStoreSql, initializeAndStartAPI, inspectionTypeDefs, isDefinedNonNullAny, isExpectedLoaderMiss, isListedAdmin, isPostgresConnectionString, isSubgraphClass, namespacePath, namespaceSegments, newWebhookToken, parseDriveUrl, parseWebhookBody, piecesBaseUrl, redactHeaders, renderGraphqlPlayground, resolvePackageName, resolveRenownConfig, verifyWebhook };
10682
+ export { ADMIN_USERS, ActionCandidateInputSchema, ActionContextInputSchema, ActionInputSchema, AddRelationshipDocument, AnalyticsSubgraph, AttachmentAccessFailed, AttachmentAccessService, AttachmentAccessUnavailable, AttachmentClientProvider, AuthDecision, AuthDecisionSchema, AuthEvaluationUnsupportedError, AuthService, AuthSubgraph, AuthenticationRequiredError, AuthorizationPolicy, AuthorizedAttachmentService, AuthorizedDocumentHandle, BaseSubgraph, CORE_PACKAGE_NAME, CanonicalDocumentIdResolutionError, ChannelMetaInputSchema, CreateDocumentDocument, CreateEmptyDocumentDocument, DEFAULT_INSPECTION_THROTTLE, DeleteDocumentDocument, DeleteDocumentsDocument, DocumentChangeType, DocumentChangeTypeSchema, DocumentChangesDocument, DocumentModelSchemaCache, DocumentOperationsFilterInputSchema, DocumentPermissionService, DocumentRelationshipFieldsFragmentDoc, EvaluateActionsDocument, ExecuteBatchDocument, ExecutionJobInputSchema, FindDocumentsDocument, ForbiddenError, GetCreateDefaultsDocument, GetDocumentDocument, GetDocumentIncomingRelationshipEdgesDocument, GetDocumentIncomingRelationshipsDocument, GetDocumentModelsDocument, GetDocumentOperationsDocument, GetDocumentOutgoingRelationshipEdgesDocument, GetDocumentOutgoingRelationshipsDocument, GetDocumentServedDocument, GetDocumentWithOperationsDocument, GetJobStatusDocument, GraphQLManager, HttpDocumentModelLoader, HttpPackageLoader, HttpRouteService, ImportPackageLoader, InMemoryPackageStorage, InspectionSubgraph, InspectionThrottle, InspectionThrottledError, InvalidNamespaceError, JobChangesDocument, JobInfoFieldsFragmentDoc, MalformedStoredOperationError, MemoryWebhookStore, MoveRelationshipDocument, MutateDocumentAsyncDocument, MutateDocumentDocument, OperationContextInputSchema, OperationInputSchema, OperationWithContextInputSchema, OperationsFilterInputSchema, PACKAGE_ROUTE_SEGMENT, PGLITE_UTC_PARSERS, PackageManagementService, PackageManager, PackagesSubgraph, PagingInputSchema, PhDocumentFieldsFragmentDoc, PollSyncEnvelopesDocument, PrivacyPermissionAdapter, PropagationMode, PropagationModeSchema, PushSyncEnvelopesDocument, ReactorSignerAppInputSchema, ReactorSignerInputSchema, ReactorSignerUserInputSchema, ReactorSubgraph, RefusalNotRecordedError, RelationalWebhookStore, RemoteCursorInputSchema, RemoteFilterInputSchema, RemoveRelationshipDocument, RenameDocumentDocument, SearchFilterInputSchema, SetPreferredEditorDocument, SubgraphTypeCollisionError, SyncEnvelopeInputSchema, SyncEnvelopeType, SyncEnvelopeTypeSchema, SyncRefusalInputSchema, SystemSubgraph, TouchChannelDocument, TouchChannelInputSchema, UpdateRelationshipDocument, ViewFilterInputSchema, WEBHOOK_SEGMENT, WS_AUTH_CLOSE_REASONS, WS_CLOSE_REASON_AUTHENTICATION_REQUIRED, WS_CLOSE_REASON_BEARER_REJECTED, WebhookService, assembleSubgraphTypeDefs, assertAttachmentPolicyReadsAllowed, assertAuthRequiredForDocumentPermissions, assertCredentialVerifierForSource, assertHostMountPath, assertRequireAuthenticatedCallerAllowed, assertSkipCredentialVerificationAllowed, baseDocumentModels, buildDocumentModelSchema, buildGraphQlDocument, buildGraphQlDriveDocument, buildGraphqlOperation, buildGraphqlOperations, buildSubgraphSchemaModule, callerSubject, createAuthFetchMiddleware, createCanonicalDocumentIdResolver, createGatewayAdapter, createHttpAdapter, createInspectionResolvers, createMergedSchema, createReactorGraphQLClient, createReactorInspectionSource, createRenownCredentialVerifier, createSchema, createWsAuthHandlers, decodeExplorerUrlState, definedNonNullAnySchema, documentModelSubgraphTypes, driveIdFromUrl, extractSubgraphs, extractSubgraphsFromModule, findSubgraphTypeCollisions, generateDocumentModelSchema, generatedTypesOf, getAuthContext, getDbClient, getDocumentModelSchemaName, getDocumentModelSubgraphName, getDocumentModelTypeDefs, getExplorerPrefix, getGeneratedDocumentModelTypes, getGitHash, getGitUrl, getSdk, getUniqueDocumentModels, getUniqueUpgradeManifests, getVersion, hasOperationSchemas, initAnalyticsStoreSql, initializeAndStartAPI, inspectionTypeDefs, isDefinedNonNullAny, isExpectedLoaderMiss, isListedAdmin, isPostgresConnectionString, isSubgraphClass, namespacePath, namespaceSegments, newWebhookToken, parseDriveUrl, parseWebhookBody, piecesBaseUrl, redactHeaders, renderGraphqlPlayground, reportFailure, reservedTypeNames, reservedTypeNamesTaken, resolvePackageName, resolveRenownConfig, runDetached, typeDefinitionNames, verifyWebhook };
10915
10683
 
10916
10684
  //# sourceMappingURL=index.mjs.map
10917
- //# debugId=980be7cc-16d9-5965-b60e-0c7ca7a4e3c8
10685
+ //# debugId=5a6cd51c-1122-5d95-9bcf-8cf26e403d05