@powerhousedao/reactor-api 6.2.3-dev.55 → 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.
- package/dist/{adapter-gateway-apollo-D2DNlPY0.mjs → adapter-gateway-apollo-DTcAJpfN.mjs} +3 -3
- package/dist/{adapter-gateway-apollo-B54G_cXT.mjs → adapter-gateway-apollo-DwAmdCYz.mjs} +5 -5
- package/dist/{adapter-gateway-apollo-B54G_cXT.mjs.map → adapter-gateway-apollo-DwAmdCYz.mjs.map} +1 -1
- package/dist/adapter-gateway-stitching-969ZPot-.mjs +4 -0
- package/dist/{adapter-gateway-stitching-Dzv10u8D.mjs → adapter-gateway-stitching-ClVkjojb.mjs} +20 -8
- package/dist/adapter-gateway-stitching-ClVkjojb.mjs.map +1 -0
- package/dist/base-document-models-69WRTSfH.mjs +1243 -0
- package/dist/base-document-models-69WRTSfH.mjs.map +1 -0
- package/dist/create-schema-DLTPkNpK.d.mts +138 -0
- package/dist/create-schema-DLTPkNpK.d.mts.map +1 -0
- package/dist/index.d.mts +46 -99
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +526 -1180
- package/dist/index.mjs.map +1 -1
- package/dist/src/graphql/subgraph-types.d.mts +37 -0
- package/dist/src/graphql/subgraph-types.d.mts.map +1 -0
- package/dist/src/graphql/subgraph-types.mjs +105 -0
- package/dist/src/graphql/subgraph-types.mjs.map +1 -0
- package/dist/src/packages/vite-loader.d.mts +3 -2
- package/dist/src/packages/vite-loader.d.mts.map +1 -1
- package/dist/src/packages/vite-loader.mjs +20 -22
- package/dist/src/packages/vite-loader.mjs.map +1 -1
- package/dist/{subgraph-extraction-sQlZLLPH.mjs → subgraph-extraction-CPtTeQAT.mjs} +44 -10
- package/dist/subgraph-extraction-CPtTeQAT.mjs.map +1 -0
- package/dist/{types-DlTiz6AA.d.mts → types-D3pD6fvQ.d.mts} +15 -3
- package/dist/types-D3pD6fvQ.d.mts.map +1 -0
- package/package.json +18 -13
- package/dist/adapter-gateway-stitching-Dzv10u8D.mjs.map +0 -1
- package/dist/subgraph-extraction-sQlZLLPH.mjs.map +0 -1
- package/dist/types-DlTiz6AA.d.mts.map +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1,16 +1,18 @@
|
|
|
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]="
|
|
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
|
|
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,
|
|
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
|
|
15
|
+
import { ConsoleLogger, childLogger } from "document-model";
|
|
14
16
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
15
17
|
import path, { isAbsolute, join } from "node:path";
|
|
16
18
|
import { match } from "path-to-regexp";
|
|
@@ -20,10 +22,7 @@ import nodeFs, { existsSync, readFileSync, watchFile } from "node:fs";
|
|
|
20
22
|
import { pipeline } from "node:stream/promises";
|
|
21
23
|
import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
22
24
|
import { pathToFileURL } from "node:url";
|
|
23
|
-
import {
|
|
24
|
-
import { typeDefs } from "@powerhousedao/document-engineering/graphql";
|
|
25
|
-
import { camelCase, kebabCase, pascalCase } from "change-case";
|
|
26
|
-
import { GraphQLJSON, GraphQLJSONObject } from "graphql-type-json";
|
|
25
|
+
import { camelCase } from "change-case";
|
|
27
26
|
import * as z$1 from "zod";
|
|
28
27
|
import { z } from "zod";
|
|
29
28
|
import { createHandler } from "graphql-sse/lib/use/fetch";
|
|
@@ -34,9 +33,6 @@ import { buildTreeUrl } from "@powerhousedao/shared";
|
|
|
34
33
|
import { init, parse as parse$1 } from "es-module-lexer";
|
|
35
34
|
import { chmod, lstat, mkdir, readFile, readdir, readlink, realpath, rename, rm, stat, symlink, writeFile } from "node:fs/promises";
|
|
36
35
|
import { getConfig } from "@powerhousedao/config/node";
|
|
37
|
-
import { reactorDriveDocumentModelModule } from "@powerhousedao/reactor-drive";
|
|
38
|
-
import { ReactorGroupV1 } from "@powerhousedao/reactor-group";
|
|
39
|
-
import { driveDocumentModelModule } from "@powerhousedao/shared/document-drive";
|
|
40
36
|
import EventEmitter from "node:events";
|
|
41
37
|
import { PostgresAnalyticsStore } from "@powerhousedao/analytics-engine-pg";
|
|
42
38
|
import { AttachmentBuilder, AttachmentNotFound, AttachmentReferenceIndexBuilder, createRef, createS3AttachmentBackend, parseAttachmentStorageConfig, parseRef, validateReserveMetadata } from "@powerhousedao/reactor-attachments";
|
|
@@ -91,9 +87,6 @@ var AnalyticsSubgraph = class extends BaseSubgraph {
|
|
|
91
87
|
}
|
|
92
88
|
};
|
|
93
89
|
//#endregion
|
|
94
|
-
//#region src/graphql/auth/schema.graphql
|
|
95
|
-
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";
|
|
96
|
-
//#endregion
|
|
97
90
|
//#region src/graphql/argument-aliases.ts
|
|
98
91
|
/** A renamed argument given under both names, or a required one under neither. */
|
|
99
92
|
var ArgumentAliasError = class extends GraphQLError {
|
|
@@ -204,7 +197,7 @@ var AuthSubgraph = class extends BaseSubgraph {
|
|
|
204
197
|
}
|
|
205
198
|
name = "auth";
|
|
206
199
|
hasSubscriptions = false;
|
|
207
|
-
typeDefs = gql(schema_default$
|
|
200
|
+
typeDefs = gql(schema_default$1);
|
|
208
201
|
resolvers = {
|
|
209
202
|
Query: {
|
|
210
203
|
documentAccess: async (_parent, args, ctx) => {
|
|
@@ -360,7 +353,7 @@ function createAuthFetchMiddleware(authService) {
|
|
|
360
353
|
async function createGatewayAdapter(type, logger) {
|
|
361
354
|
switch (type) {
|
|
362
355
|
case "apollo": {
|
|
363
|
-
const { ApolloGatewayAdapter } = await import("./adapter-gateway-apollo-
|
|
356
|
+
const { ApolloGatewayAdapter } = await import("./adapter-gateway-apollo-DTcAJpfN.mjs");
|
|
364
357
|
return new ApolloGatewayAdapter(logger);
|
|
365
358
|
}
|
|
366
359
|
case "mercurius": {
|
|
@@ -368,7 +361,7 @@ async function createGatewayAdapter(type, logger) {
|
|
|
368
361
|
return new MercuriusGatewayAdapter(logger);
|
|
369
362
|
}
|
|
370
363
|
case "stitching": {
|
|
371
|
-
const { StitchingGatewayAdapter } = await import("./adapter-gateway-stitching-
|
|
364
|
+
const { StitchingGatewayAdapter } = await import("./adapter-gateway-stitching-969ZPot-.mjs");
|
|
372
365
|
return new StitchingGatewayAdapter(logger);
|
|
373
366
|
}
|
|
374
367
|
}
|
|
@@ -625,7 +618,7 @@ function writeError(res, status, message) {
|
|
|
625
618
|
}
|
|
626
619
|
//#endregion
|
|
627
620
|
//#region src/http/route-service.ts
|
|
628
|
-
const logger$
|
|
621
|
+
const logger$2 = childLogger(["reactor-api", "http-routes"]);
|
|
629
622
|
/** The segment package routes live under, inside the host's base path. */
|
|
630
623
|
const PACKAGE_ROUTE_SEGMENT = "api";
|
|
631
624
|
/** The namespace core's own subgraphs and services register under. */
|
|
@@ -720,7 +713,7 @@ var HttpRouteService = class {
|
|
|
720
713
|
return this.scopeFor(packageKey);
|
|
721
714
|
} catch (error) {
|
|
722
715
|
if (!(error instanceof InvalidNamespaceError)) throw error;
|
|
723
|
-
logger$
|
|
716
|
+
logger$2.warn("Package \"@package\" cannot host HTTP routes: @reason", packageKey, error.message);
|
|
724
717
|
return new UnroutableScope(packageKey, error.message);
|
|
725
718
|
}
|
|
726
719
|
}
|
|
@@ -827,7 +820,7 @@ var HttpScope = class {
|
|
|
827
820
|
path: routePath,
|
|
828
821
|
handles
|
|
829
822
|
});
|
|
830
|
-
logger$
|
|
823
|
+
logger$2.debug("Registered @route for @package", key, this.owner);
|
|
831
824
|
return {
|
|
832
825
|
url: `${this.#publicUrl}${routePath}`,
|
|
833
826
|
dispose: () => {
|
|
@@ -850,7 +843,7 @@ var HttpScope = class {
|
|
|
850
843
|
transport: resolveTransport(req, this.#trustProxy)
|
|
851
844
|
});
|
|
852
845
|
} catch (error) {
|
|
853
|
-
logger$
|
|
846
|
+
logger$2.error("Route handler failed for @package", this.owner, error);
|
|
854
847
|
writeError(res, 500, "Internal server error");
|
|
855
848
|
}
|
|
856
849
|
}
|
|
@@ -1130,7 +1123,7 @@ function parseWebhookBody(raw, contentType) {
|
|
|
1130
1123
|
}
|
|
1131
1124
|
//#endregion
|
|
1132
1125
|
//#region src/http/webhook-service.ts
|
|
1133
|
-
const logger$
|
|
1126
|
+
const logger$1 = childLogger(["reactor-api", "webhooks"]);
|
|
1134
1127
|
/** The flat, token-addressed path family. */
|
|
1135
1128
|
const WEBHOOK_SEGMENT = "webhooks";
|
|
1136
1129
|
const DEFAULT_MAX_BODY_BYTES = 1048576;
|
|
@@ -1275,7 +1268,7 @@ var WebhookService = class {
|
|
|
1275
1268
|
raw
|
|
1276
1269
|
});
|
|
1277
1270
|
if (!result.ok) {
|
|
1278
|
-
logger$
|
|
1271
|
+
logger$1.warn("Rejected webhook delivery for @package/@endpoint: @reason", row.namespace, row.endpoint, result.reason);
|
|
1279
1272
|
writeError(res, 401, "Signature verification failed");
|
|
1280
1273
|
return;
|
|
1281
1274
|
}
|
|
@@ -1314,7 +1307,7 @@ var WebhookService = class {
|
|
|
1314
1307
|
if (reply.unprocessed === true && recordedKey !== void 0) try {
|
|
1315
1308
|
await this.#store.forget(token, recordedKey);
|
|
1316
1309
|
} catch (error) {
|
|
1317
|
-
logger$
|
|
1310
|
+
logger$1.warn("Could not forget an unprocessed webhook delivery: @error", error);
|
|
1318
1311
|
}
|
|
1319
1312
|
res.statusCode = reply.status;
|
|
1320
1313
|
if (reply.body !== void 0 && method !== "HEAD") {
|
|
@@ -1322,7 +1315,7 @@ var WebhookService = class {
|
|
|
1322
1315
|
res.end(reply.body);
|
|
1323
1316
|
} else res.end();
|
|
1324
1317
|
} catch (error) {
|
|
1325
|
-
logger$
|
|
1318
|
+
logger$1.error("Webhook delivery failed for @method", req.method, error);
|
|
1326
1319
|
writeError(res, 500, "Internal server error");
|
|
1327
1320
|
}
|
|
1328
1321
|
}
|
|
@@ -1507,750 +1500,6 @@ var MemoryWebhookStore = class {
|
|
|
1507
1500
|
}
|
|
1508
1501
|
};
|
|
1509
1502
|
//#endregion
|
|
1510
|
-
//#region src/utils/create-schema.ts
|
|
1511
|
-
const logger$1 = childLogger(["reactor-api", "create-schema"]);
|
|
1512
|
-
/**
|
|
1513
|
-
* Revision type - matches the definition in reactor/schema.graphql.
|
|
1514
|
-
* Used by PHDocument and document mutation results.
|
|
1515
|
-
*/
|
|
1516
|
-
const RevisionType = `
|
|
1517
|
-
type Revision {
|
|
1518
|
-
scope: String!
|
|
1519
|
-
revision: Int!
|
|
1520
|
-
}
|
|
1521
|
-
`;
|
|
1522
|
-
/**
|
|
1523
|
-
* A subgraph defines a type whose name the generated document-model schema
|
|
1524
|
-
* owns, so one of the two definitions would be lost.
|
|
1525
|
-
*/
|
|
1526
|
-
var SubgraphTypeCollisionError = class extends Error {
|
|
1527
|
-
typeNames;
|
|
1528
|
-
constructor(typeNames) {
|
|
1529
|
-
super(`Subgraph defines types reserved by the document-model schema: ${typeNames.join(", ")}`);
|
|
1530
|
-
this.name = "SubgraphTypeCollisionError";
|
|
1531
|
-
this.typeNames = typeNames;
|
|
1532
|
-
}
|
|
1533
|
-
};
|
|
1534
|
-
/**
|
|
1535
|
-
* Type-system definition kinds that GraphQL requires to be uniquely named.
|
|
1536
|
-
* A subgraph SDL with two definitions sharing a name fails federation
|
|
1537
|
-
* composition ("There can be only one type named X"), which is fatal to the
|
|
1538
|
-
* whole gateway. We dedupe these by name; field/operation/extension nodes are
|
|
1539
|
-
* left untouched.
|
|
1540
|
-
*/
|
|
1541
|
-
const TYPE_DEFINITION_KINDS = /* @__PURE__ */ new Set([
|
|
1542
|
-
Kind.OBJECT_TYPE_DEFINITION,
|
|
1543
|
-
Kind.ENUM_TYPE_DEFINITION,
|
|
1544
|
-
Kind.INPUT_OBJECT_TYPE_DEFINITION,
|
|
1545
|
-
Kind.INTERFACE_TYPE_DEFINITION,
|
|
1546
|
-
Kind.UNION_TYPE_DEFINITION,
|
|
1547
|
-
Kind.SCALAR_TYPE_DEFINITION
|
|
1548
|
-
]);
|
|
1549
|
-
/**
|
|
1550
|
-
* Drop duplicate type-system definitions by name, keeping the first occurrence.
|
|
1551
|
-
* Deduping is by name across ALL kinds (a `type` and an `enum` sharing a name
|
|
1552
|
-
* collide in GraphQL too), so the first definition of a given name wins
|
|
1553
|
-
* regardless of kind. State types are emitted before operation types, so
|
|
1554
|
-
* keep-first preserves the authoritative state definition. This heals a document
|
|
1555
|
-
* model that defines the same name twice (global+local, state+operation, or
|
|
1556
|
-
* twice in one scope) so the assembled subgraph SDL composes instead of crashing
|
|
1557
|
-
* the gateway (Sentry #917).
|
|
1558
|
-
*/
|
|
1559
|
-
const dedupeTypeDefinitions = (definitions, seen = /* @__PURE__ */ new Set()) => definitions.filter((def) => {
|
|
1560
|
-
const name = typeDefinitionName(def);
|
|
1561
|
-
if (name === void 0) return true;
|
|
1562
|
-
if (seen.has(name)) {
|
|
1563
|
-
logger$1.debug(`Dropping duplicate type definition: ${name}`);
|
|
1564
|
-
return false;
|
|
1565
|
-
}
|
|
1566
|
-
seen.add(name);
|
|
1567
|
-
return true;
|
|
1568
|
-
});
|
|
1569
|
-
function typeDefinitionName(def) {
|
|
1570
|
-
if (!TYPE_DEFINITION_KINDS.has(def.kind)) return void 0;
|
|
1571
|
-
return def.name?.value;
|
|
1572
|
-
}
|
|
1573
|
-
const EMPTY_DOCUMENT = {
|
|
1574
|
-
kind: Kind.DOCUMENT,
|
|
1575
|
-
definitions: []
|
|
1576
|
-
};
|
|
1577
|
-
const OUTPUT_TYPE_KINDS = [
|
|
1578
|
-
Kind.OBJECT_TYPE_DEFINITION,
|
|
1579
|
-
Kind.OBJECT_TYPE_EXTENSION,
|
|
1580
|
-
Kind.ENUM_TYPE_DEFINITION,
|
|
1581
|
-
Kind.ENUM_TYPE_EXTENSION,
|
|
1582
|
-
Kind.UNION_TYPE_DEFINITION,
|
|
1583
|
-
Kind.UNION_TYPE_EXTENSION,
|
|
1584
|
-
Kind.INTERFACE_TYPE_DEFINITION,
|
|
1585
|
-
Kind.INTERFACE_TYPE_EXTENSION
|
|
1586
|
-
];
|
|
1587
|
-
const STATE_PREFIX_KINDS = new Set(OUTPUT_TYPE_KINDS);
|
|
1588
|
-
const ALL_PREFIX_KINDS = /* @__PURE__ */ new Set([
|
|
1589
|
-
...OUTPUT_TYPE_KINDS,
|
|
1590
|
-
Kind.INPUT_OBJECT_TYPE_DEFINITION,
|
|
1591
|
-
Kind.INPUT_OBJECT_TYPE_EXTENSION
|
|
1592
|
-
]);
|
|
1593
|
-
const TYPE_NAME_KINDS = /* @__PURE__ */ new Set([
|
|
1594
|
-
...ALL_PREFIX_KINDS,
|
|
1595
|
-
Kind.SCALAR_TYPE_DEFINITION,
|
|
1596
|
-
Kind.SCALAR_TYPE_EXTENSION,
|
|
1597
|
-
Kind.NAMED_TYPE
|
|
1598
|
-
]);
|
|
1599
|
-
const LOCAL_STATE_STUBS = /* @__PURE__ */ new Set([
|
|
1600
|
-
"AccountSnapshotLocalState",
|
|
1601
|
-
"BudgetStatementLocalState",
|
|
1602
|
-
"ScopeFrameworkLocalState"
|
|
1603
|
-
]);
|
|
1604
|
-
/** Parse SDL; blank or comment-only input yields an empty document. */
|
|
1605
|
-
function parseSdl(sdl) {
|
|
1606
|
-
const source = new Source(sdl);
|
|
1607
|
-
if (new Lexer(source).advance().kind === TokenKind.EOF) return EMPTY_DOCUMENT;
|
|
1608
|
-
try {
|
|
1609
|
-
return parse(source, { noLocation: true });
|
|
1610
|
-
} catch (error) {
|
|
1611
|
-
const withoutSemicolons = sdl.replaceAll(";", "");
|
|
1612
|
-
if (withoutSemicolons === sdl) throw error;
|
|
1613
|
-
return parse(withoutSemicolons, { noLocation: true });
|
|
1614
|
-
}
|
|
1615
|
-
}
|
|
1616
|
-
function definedTypeNames(doc, kinds) {
|
|
1617
|
-
return doc.definitions.filter((def) => kinds.has(def.kind)).map((def) => def.name.value);
|
|
1618
|
-
}
|
|
1619
|
-
/** Prefix type definition names and type references found in `names`. */
|
|
1620
|
-
function prefixTypeNames(doc, prefix, names) {
|
|
1621
|
-
return visit(doc, { enter(node) {
|
|
1622
|
-
if (!TYPE_NAME_KINDS.has(node.kind)) return void 0;
|
|
1623
|
-
const { name } = node;
|
|
1624
|
-
if (!names.has(name.value)) return void 0;
|
|
1625
|
-
return {
|
|
1626
|
-
...node,
|
|
1627
|
-
name: {
|
|
1628
|
-
...name,
|
|
1629
|
-
value: `${prefix}_${name.value}`
|
|
1630
|
-
}
|
|
1631
|
-
};
|
|
1632
|
-
} });
|
|
1633
|
-
}
|
|
1634
|
-
/** State schema definitions without inputs, `DateTime` or the given object types. */
|
|
1635
|
-
function stateTypeDefinitions(sdl, droppedObjectTypes = /* @__PURE__ */ new Set()) {
|
|
1636
|
-
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)));
|
|
1637
|
-
}
|
|
1638
|
-
/**
|
|
1639
|
-
* Prefixed operation schemas per module. The first definition of each module
|
|
1640
|
-
* carries a "Module: <Name>" description unless it has its own.
|
|
1641
|
-
*/
|
|
1642
|
-
function buildModuleSchemas(specification, documentName, allTypeNames, hasValidSchema) {
|
|
1643
|
-
const names = new Set(allTypeNames);
|
|
1644
|
-
return specification?.modules.map((module) => {
|
|
1645
|
-
const definitions = module.operations.filter((op) => hasValidSchema(op.schema)).flatMap((op) => {
|
|
1646
|
-
const doc = parseSdl(op.schema ?? "");
|
|
1647
|
-
return prefixTypeNames(doc, documentName, /* @__PURE__ */ new Set([...names, ...definedTypeNames(doc, ALL_PREFIX_KINDS)])).definitions;
|
|
1648
|
-
});
|
|
1649
|
-
if (definitions.length === 0) return "";
|
|
1650
|
-
const [first, ...rest] = definitions;
|
|
1651
|
-
const header = "description" in first && !first.description ? {
|
|
1652
|
-
...first,
|
|
1653
|
-
description: {
|
|
1654
|
-
kind: Kind.STRING,
|
|
1655
|
-
value: `Module: ${pascalCase(module.name)}`,
|
|
1656
|
-
block: true
|
|
1657
|
-
}
|
|
1658
|
-
} : first;
|
|
1659
|
-
return print({
|
|
1660
|
-
kind: Kind.DOCUMENT,
|
|
1661
|
-
definitions: [header, ...rest]
|
|
1662
|
-
});
|
|
1663
|
-
}).filter(Boolean).join("\n") ?? "";
|
|
1664
|
-
}
|
|
1665
|
-
const buildSubgraphSchemaModule = (documentModels, resolvers, typeDefs, options = {}) => {
|
|
1666
|
-
const newResolvers = {
|
|
1667
|
-
...resolvers,
|
|
1668
|
-
JSONObject: GraphQLJSONObject,
|
|
1669
|
-
Unknown: GraphQLJSON
|
|
1670
|
-
};
|
|
1671
|
-
return {
|
|
1672
|
-
typeDefs: assembleSubgraphTypeDefs(options.generated ?? getGeneratedDocumentModelTypes(documentModels), typeDefs, options.ownTypeNames),
|
|
1673
|
-
resolvers: newResolvers
|
|
1674
|
-
};
|
|
1675
|
-
};
|
|
1676
|
-
const createSchema = (documentModels, resolvers, typeDefs, options = {}) => {
|
|
1677
|
-
return buildSubgraphSchema([buildSubgraphSchemaModule(documentModels, resolvers, typeDefs, options)]);
|
|
1678
|
-
};
|
|
1679
|
-
/**
|
|
1680
|
-
* Create a merged GraphQL schema from multiple subgraph modules.
|
|
1681
|
-
* Uses buildSubgraphSchema's array overload to combine type definitions
|
|
1682
|
-
* and resolvers from multiple subgraphs into a single executable schema.
|
|
1683
|
-
*/
|
|
1684
|
-
const createMergedSchema = (modules) => {
|
|
1685
|
-
return buildSubgraphSchema(modules);
|
|
1686
|
-
};
|
|
1687
|
-
function getDocumentModelSchemaName(documentModel) {
|
|
1688
|
-
return pascalCase(documentModel.name.replaceAll("/", " "));
|
|
1689
|
-
}
|
|
1690
|
-
/**
|
|
1691
|
-
* The generated document-model types followed by the subgraph's own. Throws
|
|
1692
|
-
* {@link SubgraphTypeCollisionError} when the subgraph defines a generated
|
|
1693
|
-
* name not in `ownTypeNames`.
|
|
1694
|
-
*/
|
|
1695
|
-
const getDocumentModelTypeDefs = (documentModels, typeDefs, ownTypeNames) => assembleSubgraphTypeDefs(getGeneratedDocumentModelTypes(documentModels), typeDefs, ownTypeNames);
|
|
1696
|
-
/** Names of the type definitions in `doc`. */
|
|
1697
|
-
function typeDefinitionNames(doc) {
|
|
1698
|
-
return new Set(doc.definitions.map(typeDefinitionName).filter((name) => name !== void 0));
|
|
1699
|
-
}
|
|
1700
|
-
/** The SDL `documentModel` adds to the generated schema, under `dmSchemaName`. */
|
|
1701
|
-
function documentModelTypesSdl(documentModel, dmSchemaName) {
|
|
1702
|
-
const latestSpec = documentModel.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
|
-
let sdl = definitions.length > 0 ? `${print(prefixed)}\n` : "";
|
|
1712
|
-
sdl += `
|
|
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
|
-
return sdl;
|
|
1726
|
-
}
|
|
1727
|
-
function addScalarFlags(definitions, into) {
|
|
1728
|
-
for (const def of definitions) {
|
|
1729
|
-
const name = typeDefinitionName(def);
|
|
1730
|
-
if (name === void 0) continue;
|
|
1731
|
-
const scalar = def.kind === Kind.SCALAR_TYPE_DEFINITION;
|
|
1732
|
-
into.set(name, scalar && (into.get(name) ?? true));
|
|
1733
|
-
}
|
|
1734
|
-
return into;
|
|
1735
|
-
}
|
|
1736
|
-
let fixedGeneratedTypes;
|
|
1737
|
-
/**
|
|
1738
|
-
* Type names no document model may generate: the root types, the generated
|
|
1739
|
-
* types every schema carries, and the types of `coreTypeDefs`.
|
|
1740
|
-
*/
|
|
1741
|
-
function reservedTypeNames(coreTypeDefs) {
|
|
1742
|
-
fixedGeneratedTypes ??= addScalarFlags(getGeneratedDocumentModelTypes([]).definitions, /* @__PURE__ */ new Map());
|
|
1743
|
-
const reserved = new Map([
|
|
1744
|
-
["Query", false],
|
|
1745
|
-
["Mutation", false],
|
|
1746
|
-
["Subscription", false],
|
|
1747
|
-
...fixedGeneratedTypes
|
|
1748
|
-
]);
|
|
1749
|
-
for (const typeDefs of coreTypeDefs) addScalarFlags(typeDefs.definitions, reserved);
|
|
1750
|
-
return reserved;
|
|
1751
|
-
}
|
|
1752
|
-
/**
|
|
1753
|
-
* The reserved names `documentModel`'s generated types take. A scalar may
|
|
1754
|
-
* repeat a reserved scalar: the duplicate is dropped on assembly.
|
|
1755
|
-
*/
|
|
1756
|
-
function reservedTypeNamesTaken(documentModel, reserved) {
|
|
1757
|
-
const global = documentModel.documentModel.global;
|
|
1758
|
-
const generated = addScalarFlags(parseSdl(documentModelTypesSdl(global, getDocumentModelSchemaName(global))).definitions, /* @__PURE__ */ new Map());
|
|
1759
|
-
return Array.from(generated).filter(([name, scalar]) => reserved.has(name) && !(scalar && reserved.get(name))).map(([name]) => name);
|
|
1760
|
-
}
|
|
1761
|
-
function getGeneratedDocumentModelTypes(documentModels) {
|
|
1762
|
-
let dmSchema = "";
|
|
1763
|
-
const addedDocumentModels = /* @__PURE__ */ new Set();
|
|
1764
|
-
documentModels.forEach(({ documentModel }) => {
|
|
1765
|
-
const dmSchemaName = getDocumentModelSchemaName(documentModel.global);
|
|
1766
|
-
if (addedDocumentModels.has(dmSchemaName)) {
|
|
1767
|
-
logger$1.debug(`Skipping document model with duplicate name: ${dmSchemaName}`);
|
|
1768
|
-
return;
|
|
1769
|
-
}
|
|
1770
|
-
addedDocumentModels.add(dmSchemaName);
|
|
1771
|
-
dmSchema += documentModelTypesSdl(documentModel.global, dmSchemaName);
|
|
1772
|
-
});
|
|
1773
|
-
const schema = gql`
|
|
1774
|
-
scalar JSONObject
|
|
1775
|
-
scalar AttachmentRef
|
|
1776
|
-
# Codegen scalars not in the document-engineering set.
|
|
1777
|
-
scalar Unknown
|
|
1778
|
-
scalar Address
|
|
1779
|
-
${typeDefs.join("\n").replaceAll(";", "")}
|
|
1780
|
-
|
|
1781
|
-
type PHOperationContext {
|
|
1782
|
-
signer: Signer
|
|
1783
|
-
}
|
|
1784
|
-
|
|
1785
|
-
type Signer {
|
|
1786
|
-
user: SignerUser
|
|
1787
|
-
app: SignerApp
|
|
1788
|
-
signatures: [String!]!
|
|
1789
|
-
}
|
|
1790
|
-
|
|
1791
|
-
type SignerUser {
|
|
1792
|
-
address: String!
|
|
1793
|
-
networkId: String!
|
|
1794
|
-
chainId: Int!
|
|
1795
|
-
}
|
|
1796
|
-
|
|
1797
|
-
type SignerApp {
|
|
1798
|
-
name: String!
|
|
1799
|
-
key: String!
|
|
1800
|
-
}
|
|
1801
|
-
|
|
1802
|
-
type Operation {
|
|
1803
|
-
id: String!
|
|
1804
|
-
type: String!
|
|
1805
|
-
index: Int!
|
|
1806
|
-
timestampUtcMs: DateTime!
|
|
1807
|
-
hash: String!
|
|
1808
|
-
skip: Int
|
|
1809
|
-
inputText: String
|
|
1810
|
-
error: String
|
|
1811
|
-
context: PHOperationContext
|
|
1812
|
-
}
|
|
1813
|
-
|
|
1814
|
-
interface IDocument {
|
|
1815
|
-
id: String!
|
|
1816
|
-
name: String!
|
|
1817
|
-
documentType: String!
|
|
1818
|
-
revision: Int!
|
|
1819
|
-
createdAtUtcIso: DateTime!
|
|
1820
|
-
lastModifiedAtUtcIso: DateTime!
|
|
1821
|
-
operations(first: Int, skip: Int): [Operation!]!
|
|
1822
|
-
stateJSON: JSONObject
|
|
1823
|
-
}
|
|
1824
|
-
${dmSchema}
|
|
1825
|
-
|
|
1826
|
-
type GqlDocument implements IDocument {
|
|
1827
|
-
id: String!
|
|
1828
|
-
name: String!
|
|
1829
|
-
documentType: String!
|
|
1830
|
-
revision: Int!
|
|
1831
|
-
createdAtUtcIso: DateTime!
|
|
1832
|
-
lastModifiedAtUtcIso: DateTime!
|
|
1833
|
-
operations(first: Int, skip: Int): [Operation!]!
|
|
1834
|
-
stateJSON: JSONObject
|
|
1835
|
-
}
|
|
1836
|
-
|
|
1837
|
-
type DriveDocument implements IDocument {
|
|
1838
|
-
id: String!
|
|
1839
|
-
name: String!
|
|
1840
|
-
documentType: String!
|
|
1841
|
-
revision: Int!
|
|
1842
|
-
createdAtUtcIso: DateTime!
|
|
1843
|
-
lastModifiedAtUtcIso: DateTime!
|
|
1844
|
-
operations(first: Int, skip: Int): [Operation!]!
|
|
1845
|
-
stateJSON: JSONObject
|
|
1846
|
-
}
|
|
1847
|
-
`;
|
|
1848
|
-
const definitions = dedupeTypeDefinitions(schema.definitions);
|
|
1849
|
-
return {
|
|
1850
|
-
definitions,
|
|
1851
|
-
names: new Set(definitions.map(typeDefinitionName).filter((name) => name !== void 0))
|
|
1852
|
-
};
|
|
1853
|
-
}
|
|
1854
|
-
/**
|
|
1855
|
-
* Names of the generated types `typeDefs` redefines, other than those a
|
|
1856
|
-
* model's own subgraph may repeat. Scalars are dropped on assembly, so they
|
|
1857
|
-
* never collide.
|
|
1858
|
-
*/
|
|
1859
|
-
function findSubgraphTypeCollisions(generated, typeDefs, ownTypeNames) {
|
|
1860
|
-
const collisions = [];
|
|
1861
|
-
for (const def of typeDefs.definitions) {
|
|
1862
|
-
if (def.kind === Kind.SCALAR_TYPE_DEFINITION) continue;
|
|
1863
|
-
const name = typeDefinitionName(def);
|
|
1864
|
-
if (name === void 0 || !generated.names.has(name)) continue;
|
|
1865
|
-
if (ownTypeNames?.has(name)) continue;
|
|
1866
|
-
collisions.push(name);
|
|
1867
|
-
}
|
|
1868
|
-
return collisions;
|
|
1869
|
-
}
|
|
1870
|
-
/** Throws {@link SubgraphTypeCollisionError}; see {@link getDocumentModelTypeDefs}. */
|
|
1871
|
-
function assembleSubgraphTypeDefs(generated, typeDefs, ownTypeNames) {
|
|
1872
|
-
const collisions = findSubgraphTypeCollisions(generated, typeDefs, ownTypeNames);
|
|
1873
|
-
if (collisions.length > 0) throw new SubgraphTypeCollisionError(collisions);
|
|
1874
|
-
const subgraphDefinitions = typeDefs.definitions.filter((def) => def.kind !== Kind.SCALAR_TYPE_DEFINITION);
|
|
1875
|
-
return {
|
|
1876
|
-
kind: Kind.DOCUMENT,
|
|
1877
|
-
definitions: [...generated.definitions, ...dedupeTypeDefinitions(subgraphDefinitions, new Set(generated.names))]
|
|
1878
|
-
};
|
|
1879
|
-
}
|
|
1880
|
-
/**
|
|
1881
|
-
* Extract the names of types defined in a GraphQL schema.
|
|
1882
|
-
* Unparseable schemas yield no names.
|
|
1883
|
-
*/
|
|
1884
|
-
function extractTypeNames(schema) {
|
|
1885
|
-
try {
|
|
1886
|
-
return definedTypeNames(parseSdl(schema), ALL_PREFIX_KINDS);
|
|
1887
|
-
} catch (error) {
|
|
1888
|
-
logger$1.debug(`Skipping unparseable schema: ${String(error)}`);
|
|
1889
|
-
return [];
|
|
1890
|
-
}
|
|
1891
|
-
}
|
|
1892
|
-
/**
|
|
1893
|
-
* Print the input type definitions of a GraphQL schema.
|
|
1894
|
-
* @param excludeTypeNames - Input type names to leave out
|
|
1895
|
-
*/
|
|
1896
|
-
function extractInputTypeDefinitions(schema, excludeTypeNames = /* @__PURE__ */ new Set()) {
|
|
1897
|
-
const definitions = parseSdl(schema).definitions.filter((def) => def.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION && !excludeTypeNames.has(def.name.value));
|
|
1898
|
-
if (definitions.length === 0) return "";
|
|
1899
|
-
return print({
|
|
1900
|
-
kind: Kind.DOCUMENT,
|
|
1901
|
-
definitions
|
|
1902
|
-
});
|
|
1903
|
-
}
|
|
1904
|
-
/**
|
|
1905
|
-
* Extract the root state type name from a scope's GraphQL schema.
|
|
1906
|
-
* Uses the naming convention: {DocumentName}State for global,
|
|
1907
|
-
* {DocumentName}{PascalScope}State for other scopes (e.g., DocumentDriveLocalState).
|
|
1908
|
-
* Falls back to the last ObjectTypeDefinition (root types are conventionally last).
|
|
1909
|
-
*/
|
|
1910
|
-
function extractRootTypeName(schema, documentName, scopeName) {
|
|
1911
|
-
try {
|
|
1912
|
-
const ast = parse(schema);
|
|
1913
|
-
const candidates = [`${documentName}${scopeName === "global" ? "" : pascalCase(scopeName)}State`, `${documentName}${pascalCase(scopeName)}State`];
|
|
1914
|
-
let lastObjectType = null;
|
|
1915
|
-
for (const def of ast.definitions) if (def.kind === Kind.OBJECT_TYPE_DEFINITION) {
|
|
1916
|
-
if (candidates.includes(def.name.value)) return def.name.value;
|
|
1917
|
-
lastObjectType = def.name.value;
|
|
1918
|
-
}
|
|
1919
|
-
return lastObjectType;
|
|
1920
|
-
} catch {}
|
|
1921
|
-
return null;
|
|
1922
|
-
}
|
|
1923
|
-
/**
|
|
1924
|
-
* Convert a GraphQL output type AST node to an optional input type string.
|
|
1925
|
-
* Strips non-null markers and converts object type references to Input suffix.
|
|
1926
|
-
*/
|
|
1927
|
-
function convertTypeNodeToInput(typeNode, objectNames, unionNames, interfaceNames) {
|
|
1928
|
-
if (typeNode.kind === Kind.NON_NULL_TYPE && typeNode.type) return convertTypeNodeToInput(typeNode.type, objectNames, unionNames, interfaceNames);
|
|
1929
|
-
if (typeNode.kind === Kind.LIST_TYPE && typeNode.type) return `[${convertTypeNodeToInput(typeNode.type, objectNames, unionNames, interfaceNames)}]`;
|
|
1930
|
-
if (typeNode.kind === Kind.NAMED_TYPE && typeNode.name) {
|
|
1931
|
-
const name = typeNode.name.value;
|
|
1932
|
-
if (objectNames.has(name)) return `${name}Input`;
|
|
1933
|
-
if (unionNames.has(name) || interfaceNames.has(name)) return "JSONObject";
|
|
1934
|
-
return name;
|
|
1935
|
-
}
|
|
1936
|
-
return "JSONObject";
|
|
1937
|
-
}
|
|
1938
|
-
/**
|
|
1939
|
-
* Generate GraphQL input type definitions from a state schema string.
|
|
1940
|
-
* Converts output type definitions to input types with all fields optional.
|
|
1941
|
-
* - Object type references get Input suffix
|
|
1942
|
-
* - Union/interface references become JSONObject
|
|
1943
|
-
* - Enums and scalars remain unchanged
|
|
1944
|
-
*/
|
|
1945
|
-
function generateStateInputTypes(stateSchema, excludeTypeNames) {
|
|
1946
|
-
if (!stateSchema || !stateSchema.trim()) return "";
|
|
1947
|
-
let ast;
|
|
1948
|
-
try {
|
|
1949
|
-
ast = parse(stateSchema);
|
|
1950
|
-
} catch {
|
|
1951
|
-
return "";
|
|
1952
|
-
}
|
|
1953
|
-
const enumNames = /* @__PURE__ */ new Set();
|
|
1954
|
-
const unionNames = /* @__PURE__ */ new Set();
|
|
1955
|
-
const interfaceNames = /* @__PURE__ */ new Set();
|
|
1956
|
-
const objectNames = /* @__PURE__ */ new Set();
|
|
1957
|
-
const existingInputNames = /* @__PURE__ */ new Set();
|
|
1958
|
-
for (const def of ast.definitions) switch (def.kind) {
|
|
1959
|
-
case Kind.ENUM_TYPE_DEFINITION:
|
|
1960
|
-
enumNames.add(def.name.value);
|
|
1961
|
-
break;
|
|
1962
|
-
case Kind.UNION_TYPE_DEFINITION:
|
|
1963
|
-
unionNames.add(def.name.value);
|
|
1964
|
-
break;
|
|
1965
|
-
case Kind.INTERFACE_TYPE_DEFINITION:
|
|
1966
|
-
interfaceNames.add(def.name.value);
|
|
1967
|
-
break;
|
|
1968
|
-
case Kind.OBJECT_TYPE_DEFINITION:
|
|
1969
|
-
objectNames.add(def.name.value);
|
|
1970
|
-
break;
|
|
1971
|
-
case Kind.INPUT_OBJECT_TYPE_DEFINITION: existingInputNames.add(def.name.value);
|
|
1972
|
-
}
|
|
1973
|
-
const inputTypes = [];
|
|
1974
|
-
for (const def of ast.definitions) {
|
|
1975
|
-
if (def.kind !== Kind.OBJECT_TYPE_DEFINITION) continue;
|
|
1976
|
-
const inputName = `${def.name.value}Input`;
|
|
1977
|
-
if (existingInputNames.has(inputName)) continue;
|
|
1978
|
-
if (excludeTypeNames?.has(inputName)) continue;
|
|
1979
|
-
const fields = def.fields ?? [];
|
|
1980
|
-
if (fields.length === 0) continue;
|
|
1981
|
-
const inputFields = fields.map((field) => {
|
|
1982
|
-
return ` ${field.name.value}: ${convertTypeNodeToInput(field.type, objectNames, unionNames, interfaceNames)}`;
|
|
1983
|
-
});
|
|
1984
|
-
inputTypes.push(`input ${def.name.value}Input {\n${inputFields.join("\n")}\n}`);
|
|
1985
|
-
}
|
|
1986
|
-
return inputTypes.join("\n\n");
|
|
1987
|
-
}
|
|
1988
|
-
/**
|
|
1989
|
-
* Apply type prefixes to GraphQL schema to namespace types and avoid collisions.
|
|
1990
|
-
* Inlined from @powerhousedao/common/utils to avoid ES module import issues.
|
|
1991
|
-
* @param {string} schema - GraphQL schema string
|
|
1992
|
-
* @param {string} prefix - Prefix to apply to type names
|
|
1993
|
-
* @param {string[]} externalTypeNames - Type names from other schemas to also prefix
|
|
1994
|
-
* @returns {string} Schema with prefixed types
|
|
1995
|
-
*/
|
|
1996
|
-
function applyGraphQLTypePrefixes(schema, prefix, externalTypeNames = []) {
|
|
1997
|
-
if (!schema || !schema.trim()) return schema;
|
|
1998
|
-
const doc = parseSdl(schema);
|
|
1999
|
-
const names = /* @__PURE__ */ new Set([...definedTypeNames(doc, ALL_PREFIX_KINDS), ...externalTypeNames]);
|
|
2000
|
-
if (names.size === 0) return schema;
|
|
2001
|
-
return print(prefixTypeNames(doc, prefix, names));
|
|
2002
|
-
}
|
|
2003
|
-
/**
|
|
2004
|
-
* Generate a GraphQL schema for a document model.
|
|
2005
|
-
*
|
|
2006
|
-
* @param documentModel - The document model global state
|
|
2007
|
-
* @param options - Schema generation options
|
|
2008
|
-
* @returns GraphQL DocumentNode
|
|
2009
|
-
*/
|
|
2010
|
-
function generateDocumentModelSchema(documentModel, options = {}) {
|
|
2011
|
-
const { useNewApi = false } = options;
|
|
2012
|
-
const specification = documentModel.specifications.at(-1);
|
|
2013
|
-
const documentName = getDocumentModelSchemaName(documentModel);
|
|
2014
|
-
const globalStateSchema = specification?.state.global.schema;
|
|
2015
|
-
const localStateSchema = specification?.state.local.schema;
|
|
2016
|
-
const globalStateTypeNames = extractTypeNames(globalStateSchema ?? "");
|
|
2017
|
-
const localStateTypeNames = extractTypeNames(localStateSchema ?? "");
|
|
2018
|
-
const stateTypeNames = [...globalStateTypeNames, ...localStateTypeNames];
|
|
2019
|
-
const allOperationTypeNames = specification?.modules.flatMap((module) => module.operations.flatMap((op) => extractTypeNames(op.schema ?? ""))) ?? [];
|
|
2020
|
-
const allTypeNames = [.../* @__PURE__ */ new Set([...stateTypeNames, ...allOperationTypeNames])];
|
|
2021
|
-
const operationInputTypeNames = new Set(allOperationTypeNames);
|
|
2022
|
-
const prefixedStateInputTypes = applyGraphQLTypePrefixes(extractInputTypeDefinitions(globalStateSchema ?? "", operationInputTypeNames), documentName, allTypeNames);
|
|
2023
|
-
const hasValidSchema = (schema) => !!(schema && /\b(input|type|enum|union|interface)\s+\w+/.test(schema));
|
|
2024
|
-
if (useNewApi) return generateNewApiSchema(documentName, specification, prefixedStateInputTypes, allTypeNames, hasValidSchema);
|
|
2025
|
-
return generateLegacyApiSchema(documentName, specification, prefixedStateInputTypes, allTypeNames, hasValidSchema);
|
|
2026
|
-
}
|
|
2027
|
-
/**
|
|
2028
|
-
* Generate legacy API schema with nested queries
|
|
2029
|
-
*/
|
|
2030
|
-
function generateLegacyApiSchema(documentName, specification, prefixedStateInputTypes, allTypeNames, hasValidSchema) {
|
|
2031
|
-
const createDocumentMutation = `${documentName}_createDocument(name:String!, driveId:String): String`;
|
|
2032
|
-
const operationMutations = specification?.modules.flatMap((module) => module.operations.filter((op) => op.name && hasValidSchema(op.schema)).map((op) => `${documentName}_${camelCase(op.name)}(
|
|
2033
|
-
driveId: String, docId: PHID, input: ${documentName}_${pascalCase(op.name)}Input): Int`)).join("\n ") ?? "";
|
|
2034
|
-
const moduleSchemas = buildModuleSchemas(specification, documentName, allTypeNames, hasValidSchema);
|
|
2035
|
-
return gql`
|
|
2036
|
-
"""
|
|
2037
|
-
Queries: ${documentName} Document
|
|
2038
|
-
"""
|
|
2039
|
-
|
|
2040
|
-
type ${documentName}Queries {
|
|
2041
|
-
getDocument(docId: PHID!, driveId: PHID): ${documentName}
|
|
2042
|
-
getDocuments(driveId: String!): [${documentName}!]
|
|
2043
|
-
}
|
|
2044
|
-
|
|
2045
|
-
type Query {
|
|
2046
|
-
${documentName}: ${documentName}Queries
|
|
2047
|
-
}
|
|
2048
|
-
|
|
2049
|
-
"""
|
|
2050
|
-
Mutations: ${documentName}
|
|
2051
|
-
"""
|
|
2052
|
-
type Mutation {
|
|
2053
|
-
${createDocumentMutation}
|
|
2054
|
-
|
|
2055
|
-
${operationMutations}
|
|
2056
|
-
}
|
|
2057
|
-
|
|
2058
|
-
${prefixedStateInputTypes ? `"""
|
|
2059
|
-
Input Types from State Schema
|
|
2060
|
-
"""
|
|
2061
|
-
${prefixedStateInputTypes}` : ""}
|
|
2062
|
-
|
|
2063
|
-
${moduleSchemas}`;
|
|
2064
|
-
}
|
|
2065
|
-
/**
|
|
2066
|
-
* Generate new API schema with flat queries, typed state, and async mutations.
|
|
2067
|
-
* Note: State schema types are NOT included here because they are already defined
|
|
2068
|
-
* in getDocumentModelTypeDefs() which is used during schema composition.
|
|
2069
|
-
* Including them here would cause duplicate type definitions.
|
|
2070
|
-
*/
|
|
2071
|
-
function generateNewApiSchema(documentName, specification, prefixedStateInputTypes, allTypeNames, hasValidSchema) {
|
|
2072
|
-
const stateType = `${documentName}_FullState!`;
|
|
2073
|
-
const sharedBaseTypes = `
|
|
2074
|
-
"""Hash configuration for document state"""
|
|
2075
|
-
type ${documentName}_PHHashConfig {
|
|
2076
|
-
algorithm: String!
|
|
2077
|
-
encoding: String!
|
|
2078
|
-
}
|
|
2079
|
-
|
|
2080
|
-
"""Document scope state (same for all document types)"""
|
|
2081
|
-
type ${documentName}_PHDocumentScopeState {
|
|
2082
|
-
version: Int!
|
|
2083
|
-
hash: ${documentName}_PHHashConfig!
|
|
2084
|
-
isDeleted: Boolean
|
|
2085
|
-
deletedAtUtcIso: String
|
|
2086
|
-
deletedBy: String
|
|
2087
|
-
deletionReason: String
|
|
2088
|
-
}
|
|
2089
|
-
`;
|
|
2090
|
-
const hasLocalStateType = (specification?.state.local.schema ?? "").includes(`type ${documentName}LocalState`);
|
|
2091
|
-
const fullStateType = `
|
|
2092
|
-
"""Full state with all scopes for ${documentName}"""
|
|
2093
|
-
type ${documentName}_FullState {
|
|
2094
|
-
auth: JSONObject!
|
|
2095
|
-
document: ${documentName}_PHDocumentScopeState!
|
|
2096
|
-
global: ${documentName === "DocumentModel" ? `${documentName}_${documentName}GlobalState!` : `${documentName}_${documentName}State!`}
|
|
2097
|
-
local: ${!hasLocalStateType ? "JSONObject!" : `${documentName}_${documentName}LocalState!`}
|
|
2098
|
-
}
|
|
2099
|
-
`;
|
|
2100
|
-
const commonInputTypes = `
|
|
2101
|
-
input ${documentName}_ViewFilterInput {
|
|
2102
|
-
branch: String
|
|
2103
|
-
scopes: [String!]
|
|
2104
|
-
}
|
|
2105
|
-
|
|
2106
|
-
input ${documentName}_PagingInput {
|
|
2107
|
-
limit: Int
|
|
2108
|
-
offset: Int
|
|
2109
|
-
cursor: String
|
|
2110
|
-
}
|
|
2111
|
-
|
|
2112
|
-
input ${documentName}_SearchFilterInput {
|
|
2113
|
-
parentId: String
|
|
2114
|
-
identifiers: [String!] @deprecated(reason: "Ignored. Filter by parentId.")
|
|
2115
|
-
}
|
|
2116
|
-
`;
|
|
2117
|
-
const revisionType = RevisionType;
|
|
2118
|
-
const resultTypes = `
|
|
2119
|
-
"""
|
|
2120
|
-
Mutation result type for ${documentName} operations with typed state.
|
|
2121
|
-
Matches ReactorSubgraph PHDocument pattern with revisionsList.
|
|
2122
|
-
"""
|
|
2123
|
-
type ${documentName}MutationResult {
|
|
2124
|
-
id: String!
|
|
2125
|
-
slug: String
|
|
2126
|
-
preferredEditor: String
|
|
2127
|
-
name: String!
|
|
2128
|
-
documentType: String!
|
|
2129
|
-
state: ${stateType}
|
|
2130
|
-
revisionsList: [Revision!]!
|
|
2131
|
-
createdAtUtcIso: DateTime!
|
|
2132
|
-
lastModifiedAtUtcIso: DateTime!
|
|
2133
|
-
}
|
|
2134
|
-
|
|
2135
|
-
"""
|
|
2136
|
-
Document with children for ${documentName}
|
|
2137
|
-
"""
|
|
2138
|
-
type ${documentName}_DocumentWithChildren {
|
|
2139
|
-
document: ${documentName}MutationResult!
|
|
2140
|
-
childIds: [String!]!
|
|
2141
|
-
}
|
|
2142
|
-
|
|
2143
|
-
"""
|
|
2144
|
-
Paginated result type for ${documentName} documents
|
|
2145
|
-
"""
|
|
2146
|
-
type ${documentName}_DocumentResultPage {
|
|
2147
|
-
items: [${documentName}MutationResult!]!
|
|
2148
|
-
hasNextPage: Boolean!
|
|
2149
|
-
hasPreviousPage: Boolean!
|
|
2150
|
-
cursor: String
|
|
2151
|
-
}
|
|
2152
|
-
`;
|
|
2153
|
-
const queries = `
|
|
2154
|
-
type ${documentName}Queries {
|
|
2155
|
-
"""Get a specific ${documentName} document by identifier"""
|
|
2156
|
-
document(idOrSlug: String, identifier: String @deprecated(reason: "Use idOrSlug."), view: ${documentName}_ViewFilterInput): ${documentName}_DocumentWithChildren
|
|
2157
|
-
|
|
2158
|
-
"""Get all ${documentName} documents (paged)"""
|
|
2159
|
-
documents(paging: ${documentName}_PagingInput): ${documentName}_DocumentResultPage!
|
|
2160
|
-
|
|
2161
|
-
"""Find ${documentName} documents by search criteria"""
|
|
2162
|
-
findDocuments(search: ${documentName}_SearchFilterInput, view: ${documentName}_ViewFilterInput, paging: ${documentName}_PagingInput): ${documentName}_DocumentResultPage!
|
|
2163
|
-
|
|
2164
|
-
"""Get outgoing relationships of a ${documentName} document"""
|
|
2165
|
-
documentOutgoingRelationships(sourceIdOrSlug: String, sourceIdentifier: String @deprecated(reason: "Use sourceIdOrSlug."), relationshipType: String!, view: ${documentName}_ViewFilterInput, paging: ${documentName}_PagingInput): ${documentName}_DocumentResultPage!
|
|
2166
|
-
|
|
2167
|
-
"""Get incoming relationships to a ${documentName} document"""
|
|
2168
|
-
documentIncomingRelationships(targetIdOrSlug: String, targetIdentifier: String @deprecated(reason: "Use targetIdOrSlug."), relationshipType: String!, view: ${documentName}_ViewFilterInput, paging: ${documentName}_PagingInput): ${documentName}_DocumentResultPage!
|
|
2169
|
-
}
|
|
2170
|
-
`;
|
|
2171
|
-
let initialStateInputSchema = "";
|
|
2172
|
-
if (specification) {
|
|
2173
|
-
const scopeFields = [];
|
|
2174
|
-
const generatedInputTypeParts = [];
|
|
2175
|
-
for (const [scopeName, scopeState] of Object.entries(specification.state)) {
|
|
2176
|
-
const schema = scopeState.schema ?? "";
|
|
2177
|
-
if (hasValidSchema(schema)) {
|
|
2178
|
-
const rootTypeName = extractRootTypeName(schema, documentName, scopeName);
|
|
2179
|
-
if (!rootTypeName) {
|
|
2180
|
-
scopeFields.push(` ${scopeName}: JSONObject`);
|
|
2181
|
-
continue;
|
|
2182
|
-
}
|
|
2183
|
-
const scopeInputTypes = generateStateInputTypes(schema, new Set(allTypeNames));
|
|
2184
|
-
if (!scopeInputTypes) {
|
|
2185
|
-
scopeFields.push(` ${scopeName}: JSONObject`);
|
|
2186
|
-
continue;
|
|
2187
|
-
}
|
|
2188
|
-
const prefixedScopeInputTypes = applyGraphQLTypePrefixes(scopeInputTypes, documentName, allTypeNames);
|
|
2189
|
-
scopeFields.push(` ${scopeName}: ${documentName}_${rootTypeName}Input`);
|
|
2190
|
-
generatedInputTypeParts.push(prefixedScopeInputTypes);
|
|
2191
|
-
} else scopeFields.push(` ${scopeName}: JSONObject`);
|
|
2192
|
-
}
|
|
2193
|
-
if (scopeFields.length > 0) {
|
|
2194
|
-
const inputTypeDefs = generatedInputTypeParts.join("\n\n");
|
|
2195
|
-
const wrapper = `input ${documentName}_InitialStateInput {\n${scopeFields.join("\n")}\n}`;
|
|
2196
|
-
initialStateInputSchema = inputTypeDefs ? `${inputTypeDefs}\n\n${wrapper}` : wrapper;
|
|
2197
|
-
}
|
|
2198
|
-
}
|
|
2199
|
-
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!`;
|
|
2200
|
-
const createEmptyDocumentMutation = `createEmptyDocument(parentIdOrSlug: String, parentIdentifier: String @deprecated(reason: "Use parentIdOrSlug.")): ${documentName}MutationResult!`;
|
|
2201
|
-
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 ") ?? "";
|
|
2202
|
-
const moduleSchemas = buildModuleSchemas(specification, documentName, allTypeNames, hasValidSchema);
|
|
2203
|
-
return gql`
|
|
2204
|
-
scalar DateTime
|
|
2205
|
-
scalar JSONObject
|
|
2206
|
-
scalar AttachmentRef
|
|
2207
|
-
|
|
2208
|
-
${revisionType}
|
|
2209
|
-
|
|
2210
|
-
${sharedBaseTypes}
|
|
2211
|
-
|
|
2212
|
-
${fullStateType}
|
|
2213
|
-
|
|
2214
|
-
${commonInputTypes}
|
|
2215
|
-
|
|
2216
|
-
${resultTypes}
|
|
2217
|
-
|
|
2218
|
-
"""
|
|
2219
|
-
Queries: ${documentName} Document
|
|
2220
|
-
"""
|
|
2221
|
-
${queries}
|
|
2222
|
-
|
|
2223
|
-
"""
|
|
2224
|
-
Mutations: ${documentName}
|
|
2225
|
-
"""
|
|
2226
|
-
type ${documentName}Mutations {
|
|
2227
|
-
${createDocumentMutation}
|
|
2228
|
-
${createEmptyDocumentMutation}
|
|
2229
|
-
|
|
2230
|
-
${operationMutations}
|
|
2231
|
-
}
|
|
2232
|
-
|
|
2233
|
-
type Query {
|
|
2234
|
-
${documentName}: ${documentName}Queries!
|
|
2235
|
-
}
|
|
2236
|
-
|
|
2237
|
-
type Mutation {
|
|
2238
|
-
${documentName}: ${documentName}Mutations!
|
|
2239
|
-
}
|
|
2240
|
-
|
|
2241
|
-
${prefixedStateInputTypes ? `"""
|
|
2242
|
-
Input Types from State Schema
|
|
2243
|
-
"""
|
|
2244
|
-
${prefixedStateInputTypes}` : ""}
|
|
2245
|
-
|
|
2246
|
-
${initialStateInputSchema ? `"""
|
|
2247
|
-
Input Types for Initial State
|
|
2248
|
-
"""
|
|
2249
|
-
${initialStateInputSchema}` : ""}
|
|
2250
|
-
|
|
2251
|
-
${moduleSchemas}`;
|
|
2252
|
-
}
|
|
2253
|
-
//#endregion
|
|
2254
1503
|
//#region src/graphql/reactor/gen/graphql.ts
|
|
2255
1504
|
let AuthDecision = /* @__PURE__ */ function(AuthDecision) {
|
|
2256
1505
|
AuthDecision["Allow"] = "ALLOW";
|
|
@@ -4702,12 +3951,13 @@ var DocumentModelSubgraph = class extends BaseSubgraph {
|
|
|
4702
3951
|
documentModel;
|
|
4703
3952
|
/** Names of the types its schema generator emits for the model. */
|
|
4704
3953
|
generatedTypeNames;
|
|
4705
|
-
|
|
3954
|
+
/** `types` are the model's subgraph types, when already built. */
|
|
3955
|
+
constructor(documentModel, args, types = documentModelSubgraphTypes(documentModel.documentModel.global)) {
|
|
4706
3956
|
super(args);
|
|
4707
3957
|
this.documentModel = documentModel;
|
|
4708
|
-
this.name =
|
|
4709
|
-
this.typeDefs =
|
|
4710
|
-
this.generatedTypeNames =
|
|
3958
|
+
this.name = getDocumentModelSubgraphName(documentModel.documentModel.global);
|
|
3959
|
+
this.typeDefs = types.typeDefs;
|
|
3960
|
+
this.generatedTypeNames = types.typeNames;
|
|
4711
3961
|
this.resolvers = this.generateResolvers();
|
|
4712
3962
|
}
|
|
4713
3963
|
/** Returns the typed query resolvers for this document model. */
|
|
@@ -5093,19 +4343,89 @@ function createGraphQLSSEHandler(options) {
|
|
|
5093
4343
|
context: (req) => contextFactory(req.raw)
|
|
5094
4344
|
});
|
|
5095
4345
|
}
|
|
5096
|
-
|
|
5097
|
-
|
|
5098
|
-
|
|
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
|
+
];
|
|
5099
4394
|
/**
|
|
5100
|
-
*
|
|
5101
|
-
*
|
|
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.
|
|
5102
4398
|
*/
|
|
5103
|
-
function
|
|
5104
|
-
const
|
|
5105
|
-
|
|
5106
|
-
const
|
|
5107
|
-
|
|
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");
|
|
5108
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
|
+
]);
|
|
5109
4429
|
/**
|
|
5110
4430
|
* Filter document models to keep only the latest version of each unique document model.
|
|
5111
4431
|
*/
|
|
@@ -5213,10 +4533,21 @@ var GraphQLManager = class {
|
|
|
5213
4533
|
* and runs inline too. */
|
|
5214
4534
|
#inHook = new AsyncLocalStorage();
|
|
5215
4535
|
#generatedTypes;
|
|
5216
|
-
/**
|
|
5217
|
-
#
|
|
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();
|
|
5218
4544
|
/** Subgraphs excluded for a type collision, with the reason last logged. */
|
|
5219
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();
|
|
5220
4551
|
/** Per-subgraph handlers by name, before auth/drive middleware is applied,
|
|
5221
4552
|
* for in-process queries by trusted internals. */
|
|
5222
4553
|
#internalSubgraphHandlers = /* @__PURE__ */ new Map();
|
|
@@ -5247,6 +4578,7 @@ var GraphQLManager = class {
|
|
|
5247
4578
|
httpRoutes;
|
|
5248
4579
|
attachments;
|
|
5249
4580
|
inspection;
|
|
4581
|
+
#reporting;
|
|
5250
4582
|
constructor(options) {
|
|
5251
4583
|
this.path = options.path;
|
|
5252
4584
|
this.httpServer = options.httpServer;
|
|
@@ -5261,6 +4593,8 @@ var GraphQLManager = class {
|
|
|
5261
4593
|
this.authService = options.authService;
|
|
5262
4594
|
this.documentPermissionService = options.documentPermissionService;
|
|
5263
4595
|
this.featureFlags = options.featureFlags ?? DefaultFeatureFlags;
|
|
4596
|
+
const subgraph = !!this.featureFlags.enableDocumentModelSubgraphs;
|
|
4597
|
+
this.#schemaCache = new DocumentModelSchemaCache((model) => buildDocumentModelSchema(model, { subgraph }));
|
|
5264
4598
|
this.port = options.port ?? 4001;
|
|
5265
4599
|
this.authorizationService = options.authorizationService;
|
|
5266
4600
|
this.reactorDriveClient = options.reactorDriveClient;
|
|
@@ -5268,6 +4602,10 @@ var GraphQLManager = class {
|
|
|
5268
4602
|
this.httpRoutes = options.httpRoutes;
|
|
5269
4603
|
this.attachments = options.attachments;
|
|
5270
4604
|
this.inspection = options.inspection;
|
|
4605
|
+
this.#reporting = {
|
|
4606
|
+
logger: options.logger,
|
|
4607
|
+
report: options.reportError
|
|
4608
|
+
};
|
|
5271
4609
|
this.driveOwnershipCache = new DriveOwnershipCache(options.driveStore ?? this.reactorClient);
|
|
5272
4610
|
this.wsServer.setMaxListeners(0);
|
|
5273
4611
|
}
|
|
@@ -5349,36 +4687,48 @@ var GraphQLManager = class {
|
|
|
5349
4687
|
this.cachedDocumentModels = this.#admitModels(models);
|
|
5350
4688
|
return this.#setupSubgraphs(this.coreSubgraphsMap);
|
|
5351
4689
|
}
|
|
5352
|
-
/**
|
|
5353
|
-
* The models whose generated types take no reserved name. The others stay
|
|
5354
|
-
* in the reactor but are left out of the schema.
|
|
5355
|
-
*/
|
|
4690
|
+
/** Models whose schemas build and take no reserved name. */
|
|
5356
4691
|
#admitModels(models) {
|
|
5357
4692
|
const reserved = reservedTypeNames(Array.from(this.coreSubgraphsMap.values(), (subgraphs) => subgraphs.map((subgraph) => subgraph.typeDefs)).flat());
|
|
5358
|
-
const
|
|
5359
|
-
const
|
|
5360
|
-
|
|
5361
|
-
|
|
5362
|
-
taken = reservedTypeNamesTaken(model, reserved);
|
|
5363
|
-
} catch {
|
|
5364
|
-
return true;
|
|
5365
|
-
}
|
|
5366
|
-
if (taken.length === 0) return true;
|
|
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)) {
|
|
5367
4697
|
const id = model.documentModel.global.id;
|
|
5368
|
-
const
|
|
5369
|
-
|
|
5370
|
-
|
|
5371
|
-
|
|
5372
|
-
|
|
5373
|
-
|
|
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;
|
|
5374
4719
|
return admitted;
|
|
5375
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
|
+
}
|
|
5376
4725
|
async #setupDocumentModelSubgraphs(supergraph, documentModels) {
|
|
5377
4726
|
const latestDocumentModels = filterLatestDocumentModelVersions(documentModels);
|
|
5378
4727
|
const registeredNames = /* @__PURE__ */ new Set();
|
|
5379
4728
|
for (const documentModel of latestDocumentModels) {
|
|
5380
4729
|
if (DOCUMENT_MODELS_TO_EXCLUDE.includes(documentModel.documentModel.global.id)) continue;
|
|
5381
|
-
|
|
4730
|
+
const types = this.#modelSchemas.get(documentModel)?.subgraph;
|
|
4731
|
+
if (!types) continue;
|
|
5382
4732
|
try {
|
|
5383
4733
|
const subgraphInstance = new DocumentModelSubgraph(documentModel, {
|
|
5384
4734
|
http: this.scopeForPackage(CORE_PACKAGE_NAME),
|
|
@@ -5393,7 +4743,7 @@ var GraphQLManager = class {
|
|
|
5393
4743
|
syncServingGate: this.syncServingGate,
|
|
5394
4744
|
attachments: this.attachments,
|
|
5395
4745
|
inspection: this.inspection
|
|
5396
|
-
});
|
|
4746
|
+
}, types);
|
|
5397
4747
|
const registered = await this.#addSubgraphInstance(subgraphInstance, supergraph, false, DOCUMENT_MODEL_ORIGIN);
|
|
5398
4748
|
if (registered) registeredNames.add(registered.name);
|
|
5399
4749
|
} catch (error) {
|
|
@@ -5427,10 +4777,18 @@ var GraphQLManager = class {
|
|
|
5427
4777
|
return supergraph === "" || supergraph === "graphql" ? [supergraph] : [supergraph, "graphql"];
|
|
5428
4778
|
}
|
|
5429
4779
|
#generated() {
|
|
5430
|
-
if (this.#generatedTypes?.models !== this.cachedDocumentModels)
|
|
5431
|
-
|
|
5432
|
-
|
|
5433
|
-
|
|
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
|
+
}
|
|
5434
4792
|
return this.#generatedTypes.types;
|
|
5435
4793
|
}
|
|
5436
4794
|
#schemaOptions(subgraph) {
|
|
@@ -5439,6 +4797,34 @@ var GraphQLManager = class {
|
|
|
5439
4797
|
ownTypeNames: subgraph instanceof DocumentModelSubgraph ? subgraph.generatedTypeNames : void 0
|
|
5440
4798
|
};
|
|
5441
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
|
+
}
|
|
5442
4828
|
/** The generated type names `subgraph` redefines under the current models. */
|
|
5443
4829
|
#typeCollisions(subgraph) {
|
|
5444
4830
|
try {
|
|
@@ -5530,6 +4916,7 @@ var GraphQLManager = class {
|
|
|
5530
4916
|
else if (bucket === supergraph) subgraphsMap.set(bucket, [subgraphInstance]);
|
|
5531
4917
|
}
|
|
5532
4918
|
this.#origins.set(subgraphInstance, origin);
|
|
4919
|
+
this.#recordRegistrationOrder(origin, subgraphInstance.name);
|
|
5533
4920
|
if (origin !== HOST_ORIGIN && origin !== CORE_ORIGIN) {
|
|
5534
4921
|
let instances = this.packageSubgraphs.get(origin);
|
|
5535
4922
|
if (!instances) {
|
|
@@ -5541,6 +4928,17 @@ var GraphQLManager = class {
|
|
|
5541
4928
|
this.logger.info(`${replaces.length + evicts.length > 0 ? "Replaced" : "Registered"} ${this.path.endsWith("/") ? this.path : this.path + "/"}${supergraph ? supergraph + "/" : ""}${subgraphInstance.name} subgraph.`);
|
|
5542
4929
|
return subgraphInstance;
|
|
5543
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
|
+
}
|
|
5544
4942
|
/**
|
|
5545
4943
|
* Take `instance` off the mount paths of `buckets`. It is torn down
|
|
5546
4944
|
* entirely unless it is still registered in another bucket.
|
|
@@ -5632,14 +5030,10 @@ var GraphQLManager = class {
|
|
|
5632
5030
|
}
|
|
5633
5031
|
await this.updateRouter();
|
|
5634
5032
|
}
|
|
5635
|
-
/** Not awaited:
|
|
5636
|
-
* later call replaced, so awaiting it in a registry change could wedge the
|
|
5637
|
-
* queue. */
|
|
5033
|
+
/** Not awaited: a registry change does not wait out the debounce. */
|
|
5638
5034
|
#scheduleRouterUpdate() {
|
|
5639
5035
|
this.#inHook.exit(() => {
|
|
5640
|
-
this.updateRouter()
|
|
5641
|
-
this.logger.error("Failed to update router: @error", error);
|
|
5642
|
-
});
|
|
5036
|
+
runDetached("Router update", () => this.updateRouter(), this.#reporting);
|
|
5643
5037
|
});
|
|
5644
5038
|
}
|
|
5645
5039
|
/**
|
|
@@ -5872,7 +5266,7 @@ var GraphQLManager = class {
|
|
|
5872
5266
|
await this.gatewayAdapter.updateSupergraph();
|
|
5873
5267
|
this.logger.debug("Updated Apollo Gateway supergraph");
|
|
5874
5268
|
} catch (error) {
|
|
5875
|
-
this
|
|
5269
|
+
reportFailure(this.#reporting, error, "Failed to update Apollo Gateway supergraph: @error");
|
|
5876
5270
|
}
|
|
5877
5271
|
const superGraphPath = path.posix.join(this.path, "graphql");
|
|
5878
5272
|
this.#setupSupergraphSSE(superGraphPath);
|
|
@@ -5971,15 +5365,26 @@ var GraphQLManager = class {
|
|
|
5971
5365
|
try {
|
|
5972
5366
|
const cached = this.subgraphHandlerCache.get(subgraphPath);
|
|
5973
5367
|
if (cached) {
|
|
5974
|
-
if (cached.subgraph
|
|
5975
|
-
|
|
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);
|
|
5976
5374
|
}
|
|
5375
|
+
const generated = this.#generated();
|
|
5977
5376
|
const schema = createSchema(this.cachedDocumentModels, subgraph.resolvers, subgraph.typeDefs, this.#schemaOptions(subgraph));
|
|
5978
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);
|
|
5979
5383
|
const fetchHandler = this.#composeFetchMiddleware(rawHandler);
|
|
5980
5384
|
this.subgraphHandlerCache.set(subgraphPath, {
|
|
5981
5385
|
handler: fetchHandler,
|
|
5982
|
-
subgraph
|
|
5386
|
+
subgraph,
|
|
5387
|
+
generated
|
|
5983
5388
|
});
|
|
5984
5389
|
this.#setInternalSubgraphHandler(subgraph, subgraphPath, rawHandler);
|
|
5985
5390
|
this.subgraphRouteHandles.set(subgraphPath, this.httpAdapter.mount(subgraphPath, fetchHandler));
|
|
@@ -6015,15 +5420,77 @@ var GraphQLManager = class {
|
|
|
6015
5420
|
}
|
|
6016
5421
|
return subgraphsMap;
|
|
6017
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
|
+
}
|
|
6018
5486
|
#buildSubgraphSchemaModule(subgraph) {
|
|
6019
5487
|
return buildSubgraphSchemaModule(this.cachedDocumentModels, subgraph.resolvers, subgraph.typeDefs, this.#schemaOptions(subgraph));
|
|
6020
5488
|
}
|
|
6021
5489
|
#getSubgraphDefinitions() {
|
|
6022
|
-
const subgraphs = this.#
|
|
5490
|
+
const subgraphs = this.#getSupergraphSubgraphs();
|
|
6023
5491
|
const herokuOrLocal = process.env.HEROKU_APP_DEFAULT_DOMAIN_NAME ? `https://${process.env.HEROKU_APP_DEFAULT_DOMAIN_NAME}` : `http://localhost:${this.port}`;
|
|
6024
5492
|
const definitions = [];
|
|
6025
5493
|
for (const [subgraphPath, subgraph] of subgraphs) {
|
|
6026
|
-
if (this.#isExcludedForTypes(subgraph)) continue;
|
|
6027
5494
|
let module;
|
|
6028
5495
|
try {
|
|
6029
5496
|
module = this.#buildSubgraphSchemaModule(subgraph);
|
|
@@ -6051,6 +5518,7 @@ var GraphQLManager = class {
|
|
|
6051
5518
|
this.initialized = true;
|
|
6052
5519
|
}
|
|
6053
5520
|
}
|
|
5521
|
+
#loggedSSEExclusions = /* @__PURE__ */ new Set();
|
|
6054
5522
|
/**
|
|
6055
5523
|
* Set up an SSE subscription endpoint at the supergraph level.
|
|
6056
5524
|
* Merges the schemas of all subscription-enabled subgraphs so that
|
|
@@ -6058,25 +5526,35 @@ var GraphQLManager = class {
|
|
|
6058
5526
|
* subgraph paths.
|
|
6059
5527
|
*/
|
|
6060
5528
|
#setupSupergraphSSE(superGraphPath) {
|
|
6061
|
-
const
|
|
6062
|
-
const
|
|
6063
|
-
for (const subgraph of allSubgraphs.values()) {
|
|
5529
|
+
const definitions = [];
|
|
5530
|
+
for (const [subgraphPath, subgraph] of this.#getSupergraphSubgraphs()) {
|
|
6064
5531
|
if (!subgraph.hasSubscriptions) continue;
|
|
6065
|
-
if (this.#isExcludedForTypes(subgraph)) continue;
|
|
6066
5532
|
try {
|
|
6067
|
-
|
|
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
|
+
});
|
|
6068
5540
|
} catch (error) {
|
|
6069
5541
|
this.logger.error("Excluding subgraph @name from supergraph SSE: @error", subgraph.name, error instanceof Error ? error.message : error);
|
|
6070
5542
|
}
|
|
6071
5543
|
}
|
|
6072
|
-
|
|
6073
|
-
|
|
6074
|
-
|
|
6075
|
-
|
|
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;
|
|
6076
5550
|
try {
|
|
6077
|
-
const mergedSchema =
|
|
5551
|
+
const mergedSchema = mergeStreamSubgraphs(buildable);
|
|
5552
|
+
if (mergedSchema === void 0) {
|
|
5553
|
+
this.#disposeSSERoute(superGraphPath);
|
|
5554
|
+
return;
|
|
5555
|
+
}
|
|
6078
5556
|
this.#setupSSEHandler(mergedSchema, superGraphPath);
|
|
6079
|
-
this.logger.debug(`SSE subscriptions enabled at supergraph level (merged from ${
|
|
5557
|
+
this.logger.debug(`SSE subscriptions enabled at supergraph level (merged from ${buildable.length} subgraph(s))`);
|
|
6080
5558
|
} catch (error) {
|
|
6081
5559
|
this.logger.error("Failed to setup supergraph SSE: @error", error);
|
|
6082
5560
|
}
|
|
@@ -6203,6 +5681,10 @@ function createInspectionResolvers(source, sync, gate) {
|
|
|
6203
5681
|
return source.syncInspector;
|
|
6204
5682
|
};
|
|
6205
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
|
+
};
|
|
6206
5688
|
return {
|
|
6207
5689
|
Query: { inspection: () => ({}) },
|
|
6208
5690
|
ReactorInspection: {
|
|
@@ -6223,6 +5705,7 @@ function createInspectionResolvers(source, sync, gate) {
|
|
|
6223
5705
|
};
|
|
6224
5706
|
},
|
|
6225
5707
|
driveIntegrity: async (_parent, args, ctx) => {
|
|
5708
|
+
admit(ctx);
|
|
6226
5709
|
const identifier = await gate.assertCanRead(args.driveId, ctx);
|
|
6227
5710
|
const served = await gate.servedDocument(identifier, args.branch, ctx);
|
|
6228
5711
|
if (!served) throw new ForbiddenError("to read this document");
|
|
@@ -6240,6 +5723,7 @@ function createInspectionResolvers(source, sync, gate) {
|
|
|
6240
5723
|
catchUpStatus: operator(() => inspector.getCatchUpStatus()),
|
|
6241
5724
|
storageHealth: operator(() => inspector.getStorageHealth()),
|
|
6242
5725
|
validateDocument: async (_parent, args, ctx) => {
|
|
5726
|
+
admit(ctx);
|
|
6243
5727
|
const branch = args.branch ?? void 0;
|
|
6244
5728
|
const identifier = await gate.assertCanRead(args.documentId, ctx);
|
|
6245
5729
|
const served = await gate.servedDocument(identifier, branch, ctx);
|
|
@@ -6268,229 +5752,51 @@ function createInspectionResolvers(source, sync, gate) {
|
|
|
6268
5752
|
};
|
|
6269
5753
|
}
|
|
6270
5754
|
//#endregion
|
|
6271
|
-
//#region src/graphql/inspection/
|
|
6272
|
-
const
|
|
6273
|
-
|
|
6274
|
-
|
|
6275
|
-
|
|
6276
|
-
|
|
6277
|
-
|
|
6278
|
-
|
|
6279
|
-
|
|
6280
|
-
|
|
6281
|
-
|
|
6282
|
-
|
|
6283
|
-
|
|
6284
|
-
|
|
6285
|
-
|
|
6286
|
-
|
|
6287
|
-
|
|
6288
|
-
|
|
6289
|
-
|
|
6290
|
-
|
|
6291
|
-
|
|
6292
|
-
|
|
6293
|
-
|
|
6294
|
-
|
|
6295
|
-
|
|
6296
|
-
|
|
6297
|
-
|
|
6298
|
-
|
|
6299
|
-
|
|
6300
|
-
|
|
6301
|
-
|
|
6302
|
-
|
|
6303
|
-
|
|
6304
|
-
|
|
6305
|
-
|
|
6306
|
-
|
|
6307
|
-
|
|
6308
|
-
|
|
6309
|
-
|
|
6310
|
-
|
|
6311
|
-
|
|
6312
|
-
|
|
6313
|
-
|
|
6314
|
-
|
|
6315
|
-
|
|
6316
|
-
|
|
6317
|
-
type InspectionDrivePage {
|
|
6318
|
-
results: [InspectionDrive!]!
|
|
6319
|
-
nextCursor: String
|
|
6320
|
-
}
|
|
6321
|
-
|
|
6322
|
-
type InspectionDriveIntegrityRef {
|
|
6323
|
-
id: String!
|
|
6324
|
-
documentType: String!
|
|
6325
|
-
}
|
|
6326
|
-
|
|
6327
|
-
type InspectionDriveIntegrity {
|
|
6328
|
-
driveId: String!
|
|
6329
|
-
checkedNodeCount: Int!
|
|
6330
|
-
totalFileNodeCount: Int!
|
|
6331
|
-
"""
|
|
6332
|
-
File nodes whose document is missing or not served to you; the two are
|
|
6333
|
-
reported alike so a withheld document's existence does not leak.
|
|
6334
|
-
"""
|
|
6335
|
-
missingDocuments: [InspectionDriveIntegrityRef!]!
|
|
6336
|
-
unsupportedTypes: [InspectionDriveIntegrityRef!]!
|
|
6337
|
-
}
|
|
6338
|
-
|
|
6339
|
-
type InspectionAttachmentInfo {
|
|
6340
|
-
present: Boolean!
|
|
6341
|
-
storeKind: String!
|
|
6342
|
-
hasReplicator: Boolean!
|
|
6343
|
-
replicatorRunning: Boolean!
|
|
6344
|
-
backlogScanned: Boolean!
|
|
6345
|
-
refsSeen: Int!
|
|
6346
|
-
held: Int!
|
|
6347
|
-
bytesHeld: Float!
|
|
6348
|
-
queued: Int!
|
|
6349
|
-
fetching: Int!
|
|
6350
|
-
pendingFetches: Int!
|
|
6351
|
-
waiting: Int!
|
|
6352
|
-
notFound: Int!
|
|
6353
|
-
failed: Int!
|
|
6354
|
-
lastError: String
|
|
6355
|
-
}
|
|
6356
|
-
|
|
6357
|
-
"""
|
|
6358
|
-
A queued job without its actions or operations.
|
|
6359
|
-
"""
|
|
6360
|
-
type InspectionQueueJob {
|
|
6361
|
-
id: String!
|
|
6362
|
-
kind: String!
|
|
6363
|
-
documentId: String!
|
|
6364
|
-
scope: String!
|
|
6365
|
-
branch: String!
|
|
6366
|
-
status: String!
|
|
6367
|
-
actionCount: Int!
|
|
6368
|
-
operationCount: Int!
|
|
6369
|
-
retryCount: Int!
|
|
6370
|
-
}
|
|
6371
|
-
|
|
6372
|
-
type InspectionQueueState {
|
|
6373
|
-
isPaused: Boolean!
|
|
6374
|
-
totalPending: Int!
|
|
6375
|
-
totalExecuting: Int!
|
|
6376
|
-
pendingJobs: [InspectionQueueJob!]!
|
|
6377
|
-
executingJobs: [InspectionQueueJob!]!
|
|
6378
|
-
}
|
|
6379
|
-
|
|
6380
|
-
type InspectionProcessor {
|
|
6381
|
-
processorId: String!
|
|
6382
|
-
factoryId: String!
|
|
6383
|
-
driveId: String!
|
|
6384
|
-
processorIndex: Int!
|
|
6385
|
-
lastOrdinal: Float!
|
|
6386
|
-
status: String!
|
|
6387
|
-
lastError: String
|
|
6388
|
-
lastErrorTimestampUtcMs: Float
|
|
6389
|
-
}
|
|
6390
|
-
|
|
6391
|
-
"""
|
|
6392
|
-
healthy means something only when tracked; an untracked store reports false.
|
|
6393
|
-
"""
|
|
6394
|
-
type InspectionStorageHealth {
|
|
6395
|
-
tracked: Boolean!
|
|
6396
|
-
healthy: Boolean!
|
|
6397
|
-
everRecreated: Boolean!
|
|
6398
|
-
recreateCount: Int!
|
|
6399
|
-
}
|
|
6400
|
-
|
|
6401
|
-
"""
|
|
6402
|
-
Issues in scopes the caller may not read are left out.
|
|
6403
|
-
"""
|
|
6404
|
-
type InspectionValidation {
|
|
6405
|
-
documentId: String!
|
|
6406
|
-
isConsistent: Boolean!
|
|
6407
|
-
keyframeIssues: [JSONObject!]!
|
|
6408
|
-
snapshotIssues: [JSONObject!]!
|
|
6409
|
-
streamOrderIssues: [JSONObject!]!
|
|
6410
|
-
}
|
|
6411
|
-
|
|
6412
|
-
type InspectionCursor {
|
|
6413
|
-
cursorType: String!
|
|
6414
|
-
cursorOrdinal: Float!
|
|
6415
|
-
lastSyncedAtUtcMs: Float
|
|
6416
|
-
liveAckOrdinal: Float!
|
|
6417
|
-
liveLatestOrdinal: Float!
|
|
6418
|
-
}
|
|
6419
|
-
|
|
6420
|
-
type InspectionMailboxDepths {
|
|
6421
|
-
inbox: Int!
|
|
6422
|
-
outbox: Int!
|
|
6423
|
-
deadLetter: Int!
|
|
6424
|
-
}
|
|
6425
|
-
|
|
6426
|
-
type InspectionConnectionHealth {
|
|
6427
|
-
snapshot: JSONObject!
|
|
6428
|
-
neverSucceeded: Boolean!
|
|
6429
|
-
stalenessMs: Float
|
|
6430
|
-
}
|
|
6431
|
-
|
|
6432
|
-
type InspectionRemote {
|
|
6433
|
-
remoteName: String!
|
|
6434
|
-
remoteId: String!
|
|
6435
|
-
inboxCursor: InspectionCursor!
|
|
6436
|
-
outboxCursor: InspectionCursor!
|
|
6437
|
-
mailboxDepths: InspectionMailboxDepths!
|
|
6438
|
-
connection: InspectionConnectionHealth!
|
|
6439
|
-
meta: JSONObject!
|
|
6440
|
-
}
|
|
6441
|
-
|
|
6442
|
-
"""
|
|
6443
|
-
A dead letter without its operations.
|
|
6444
|
-
"""
|
|
6445
|
-
type InspectionDeadLetter {
|
|
6446
|
-
id: String!
|
|
6447
|
-
jobId: String!
|
|
6448
|
-
documentId: String!
|
|
6449
|
-
branch: String!
|
|
6450
|
-
scopes: [String!]!
|
|
6451
|
-
errorType: String!
|
|
6452
|
-
errorMessage: String!
|
|
6453
|
-
operationCount: Int!
|
|
6454
|
-
}
|
|
6455
|
-
|
|
6456
|
-
type InspectionDeadLetterPage {
|
|
6457
|
-
remoteName: String!
|
|
6458
|
-
results: [InspectionDeadLetter!]!
|
|
6459
|
-
nextCursor: String
|
|
6460
|
-
}
|
|
6461
|
-
|
|
6462
|
-
"""
|
|
6463
|
-
Reads only. info and documentModels serve every caller; drive and document
|
|
6464
|
-
reads are made as the caller through the reactor read gate; the rest need
|
|
6465
|
-
one of the host's admins.
|
|
6466
|
-
"""
|
|
6467
|
-
type ReactorInspection {
|
|
6468
|
-
info: ReactorInfo!
|
|
6469
|
-
documentModels: [InspectionDocumentModel!]!
|
|
6470
|
-
drives(cursor: String, limit: Int): InspectionDrivePage!
|
|
6471
|
-
driveIntegrity(driveId: String!, branch: String!): InspectionDriveIntegrity!
|
|
6472
|
-
attachmentInfo: InspectionAttachmentInfo!
|
|
6473
|
-
queueState: InspectionQueueState!
|
|
6474
|
-
processors: [InspectionProcessor!]!
|
|
6475
|
-
catchUpStatus: JSONObject!
|
|
6476
|
-
storageHealth: InspectionStorageHealth!
|
|
6477
|
-
"""
|
|
6478
|
-
Replays the whole document; expensive.
|
|
6479
|
-
"""
|
|
6480
|
-
validateDocument(documentId: String!, branch: String): InspectionValidation!
|
|
6481
|
-
remotes: [InspectionRemote!]!
|
|
6482
|
-
remote(remoteName: String!): InspectionRemote!
|
|
6483
|
-
deadLetters(
|
|
6484
|
-
remoteName: String!
|
|
6485
|
-
cursor: String
|
|
6486
|
-
limit: Int
|
|
6487
|
-
): InspectionDeadLetterPage!
|
|
6488
|
-
}
|
|
6489
|
-
|
|
6490
|
-
type Query {
|
|
6491
|
-
inspection: ReactorInspection!
|
|
6492
|
-
}
|
|
6493
|
-
`;
|
|
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
|
+
};
|
|
6494
5800
|
//#endregion
|
|
6495
5801
|
//#region src/graphql/inspection/source.ts
|
|
6496
5802
|
function createReactorInspectionSource(module, options = {}) {
|
|
@@ -6504,7 +5810,8 @@ function createReactorInspectionSource(module, options = {}) {
|
|
|
6504
5810
|
inspector,
|
|
6505
5811
|
syncInspector: module.syncModule?.syncInspector,
|
|
6506
5812
|
documentModelRegistry: module.documentModelRegistry,
|
|
6507
|
-
facts: inspector
|
|
5813
|
+
facts: inspector,
|
|
5814
|
+
throttle: new InspectionThrottle(options.throttle)
|
|
6508
5815
|
};
|
|
6509
5816
|
}
|
|
6510
5817
|
//#endregion
|
|
@@ -6604,7 +5911,7 @@ async function uninstallPackage(service, authorizationService, args, ctx) {
|
|
|
6604
5911
|
}
|
|
6605
5912
|
//#endregion
|
|
6606
5913
|
//#region src/graphql/packages/schema.graphql
|
|
6607
|
-
var schema_default
|
|
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";
|
|
6608
5915
|
//#endregion
|
|
6609
5916
|
//#region src/graphql/packages/subgraph.ts
|
|
6610
5917
|
var PackagesSubgraph = class extends BaseSubgraph {
|
|
@@ -6617,7 +5924,7 @@ var PackagesSubgraph = class extends BaseSubgraph {
|
|
|
6617
5924
|
}
|
|
6618
5925
|
name = "packages";
|
|
6619
5926
|
hasSubscriptions = false;
|
|
6620
|
-
typeDefs = gql(schema_default
|
|
5927
|
+
typeDefs = gql(schema_default);
|
|
6621
5928
|
resolvers = {
|
|
6622
5929
|
Query: { Packages: () => ({}) },
|
|
6623
5930
|
PackagesQueries: {
|
|
@@ -7091,9 +6398,6 @@ function createReactorGraphQLClient(url, fetchImpl = fetch, headers) {
|
|
|
7091
6398
|
return getSdk(createValidatingRequester(url, fetchImpl, headers));
|
|
7092
6399
|
}
|
|
7093
6400
|
//#endregion
|
|
7094
|
-
//#region src/graphql/reactor/schema.graphql
|
|
7095
|
-
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";
|
|
7096
|
-
//#endregion
|
|
7097
6401
|
//#region src/graphql/reactor/pubsub.ts
|
|
7098
6402
|
const pubSub = new PubSub();
|
|
7099
6403
|
function getPubSub() {
|
|
@@ -7364,7 +6668,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
|
|
|
7364
6668
|
#creatorBinding(ctx) {
|
|
7365
6669
|
return this.syncServingGate ? ctx.user?.address : void 0;
|
|
7366
6670
|
}
|
|
7367
|
-
typeDefs = gql(schema_default);
|
|
6671
|
+
typeDefs = gql(schema_default$2);
|
|
7368
6672
|
resolvers = {
|
|
7369
6673
|
PHDocument: { operations: async (parent, args, ctx) => {
|
|
7370
6674
|
this.logger.debug("PHDocument.operations(@parent.id, @args)", parent.id, args);
|
|
@@ -8019,10 +7323,10 @@ const ADMIN_USERS = getAdminUsers();
|
|
|
8019
7323
|
//#endregion
|
|
8020
7324
|
//#region src/graphql/system/version.ts
|
|
8021
7325
|
function getVersion() {
|
|
8022
|
-
return "6.2.3-dev.
|
|
7326
|
+
return "6.2.3-dev.56";
|
|
8023
7327
|
}
|
|
8024
7328
|
function getGitHash() {
|
|
8025
|
-
return "
|
|
7329
|
+
return "5664e2daef8c915c7f66a1f9a92c65d92bfebf0e";
|
|
8026
7330
|
}
|
|
8027
7331
|
function getGitUrl() {
|
|
8028
7332
|
return buildTreeUrl(getGitHash());
|
|
@@ -8032,17 +7336,7 @@ function getGitUrl() {
|
|
|
8032
7336
|
var SystemSubgraph = class extends BaseSubgraph {
|
|
8033
7337
|
name = "system";
|
|
8034
7338
|
hasSubscriptions = false;
|
|
8035
|
-
typeDefs =
|
|
8036
|
-
type SystemInfo {
|
|
8037
|
-
version: String!
|
|
8038
|
-
gitHash: String!
|
|
8039
|
-
gitUrl: String
|
|
8040
|
-
}
|
|
8041
|
-
|
|
8042
|
-
type Query {
|
|
8043
|
-
system: SystemInfo!
|
|
8044
|
-
}
|
|
8045
|
-
`;
|
|
7339
|
+
typeDefs = systemTypeDefs;
|
|
8046
7340
|
resolvers = { Query: { system: () => ({
|
|
8047
7341
|
version: getVersion(),
|
|
8048
7342
|
gitHash: getGitHash(),
|
|
@@ -8937,8 +8231,16 @@ var PackageManager = class {
|
|
|
8937
8231
|
processorMap = /* @__PURE__ */ new Map();
|
|
8938
8232
|
piecesMap = /* @__PURE__ */ new Map();
|
|
8939
8233
|
configWatcher;
|
|
8234
|
+
unsubscribePackages;
|
|
8235
|
+
subscribedPackages = /* @__PURE__ */ new Set();
|
|
8940
8236
|
debouncedUpdateCallbacks = /* @__PURE__ */ new Map();
|
|
8941
8237
|
eventEmitter = new EventEmitter();
|
|
8238
|
+
get detached() {
|
|
8239
|
+
return {
|
|
8240
|
+
logger: this.logger,
|
|
8241
|
+
report: this.options.reportError
|
|
8242
|
+
};
|
|
8243
|
+
}
|
|
8942
8244
|
constructor(loaders, options) {
|
|
8943
8245
|
this.options = options;
|
|
8944
8246
|
this.loaders = loaders;
|
|
@@ -8960,8 +8262,11 @@ var PackageManager = class {
|
|
|
8960
8262
|
this.updateSubgraphsMap(subgraphsMap);
|
|
8961
8263
|
this.updateProcessorsMap(processorsMap);
|
|
8962
8264
|
this.updatePiecesMap(piecesMap);
|
|
8265
|
+
this.unsubscribePackages?.();
|
|
8266
|
+
this.unsubscribePackages = void 0;
|
|
8267
|
+
this.subscribedPackages = new Set(packages);
|
|
8963
8268
|
try {
|
|
8964
|
-
this.subscribePackages(packages);
|
|
8269
|
+
this.unsubscribePackages = this.subscribePackages(packages);
|
|
8965
8270
|
} catch (error) {
|
|
8966
8271
|
this.logger.error("Failed to subscribe to packages: @error", error);
|
|
8967
8272
|
}
|
|
@@ -8976,10 +8281,7 @@ var PackageManager = class {
|
|
|
8976
8281
|
async loadDocumentModels(packages) {
|
|
8977
8282
|
this.logger.debug(`Loading document models from packages: ${packages.join(", ")}`);
|
|
8978
8283
|
const documentModelModuleMap = /* @__PURE__ */ new Map();
|
|
8979
|
-
documentModelModuleMap.set(
|
|
8980
|
-
documentModelModuleMap.set("document-model", [documentModelDocumentModelModule]);
|
|
8981
|
-
documentModelModuleMap.set("reactor-drive", [reactorDriveDocumentModelModule]);
|
|
8982
|
-
documentModelModuleMap.set("reactor-group", [ReactorGroupV1]);
|
|
8284
|
+
for (const [source, model] of baseDocumentModels) documentModelModuleMap.set(source, [model]);
|
|
8983
8285
|
for (const pkg of packages) {
|
|
8984
8286
|
const allDocumentModels = [];
|
|
8985
8287
|
const failures = [];
|
|
@@ -9151,13 +8453,13 @@ var PackageManager = class {
|
|
|
9151
8453
|
this.updatePiecesMap(piecesMap);
|
|
9152
8454
|
}
|
|
9153
8455
|
/** Debounced per key so repeated subscribePackages calls reuse one timer. */
|
|
9154
|
-
getDebouncedUpdateCallback(
|
|
8456
|
+
getDebouncedUpdateCallback(pkg, kind, update) {
|
|
8457
|
+
const key = `${pkg}:${kind}`;
|
|
9155
8458
|
if (!this.debouncedUpdateCallbacks.has(key)) {
|
|
9156
|
-
const
|
|
8459
|
+
const updateIfSubscribed = () => this.subscribedPackages.has(pkg) ? update() : void 0;
|
|
8460
|
+
const debouncedFn = debounce(() => runDetached(`Updating ${key}`, updateIfSubscribed, this.detached), 1e3);
|
|
9157
8461
|
this.debouncedUpdateCallbacks.set(key, () => {
|
|
9158
|
-
debouncedFn()
|
|
9159
|
-
this.logger.error("Failed to update package: @error", error);
|
|
9160
|
-
});
|
|
8462
|
+
debouncedFn();
|
|
9161
8463
|
});
|
|
9162
8464
|
}
|
|
9163
8465
|
return this.debouncedUpdateCallbacks.get(key);
|
|
@@ -9165,10 +8467,10 @@ var PackageManager = class {
|
|
|
9165
8467
|
subscribePackages(packages) {
|
|
9166
8468
|
const unsubs = [];
|
|
9167
8469
|
for (const pkg of packages) {
|
|
9168
|
-
const onDocumentModels = this.getDebouncedUpdateCallback(
|
|
9169
|
-
const onSubgraphs = this.getDebouncedUpdateCallback(
|
|
9170
|
-
const onProcessors = this.getDebouncedUpdateCallback(
|
|
9171
|
-
const onPieces = this.getDebouncedUpdateCallback(
|
|
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));
|
|
9172
8474
|
for (const loader of this.loaders) {
|
|
9173
8475
|
if (loader.onDocumentModelsChange) unsubs.push(loader.onDocumentModelsChange(pkg, onDocumentModels));
|
|
9174
8476
|
if (loader.onSubgraphsChange) unsubs.push(loader.onSubgraphsChange(pkg, onSubgraphs));
|
|
@@ -9181,17 +8483,17 @@ var PackageManager = class {
|
|
|
9181
8483
|
};
|
|
9182
8484
|
}
|
|
9183
8485
|
getAllPackageNames() {
|
|
9184
|
-
const packageNames = this.options.packages
|
|
9185
|
-
if (this.options.configFile)
|
|
9186
|
-
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);
|
|
9187
8489
|
}
|
|
9188
8490
|
getPackageNamesFromConfigFile(configFile) {
|
|
9189
8491
|
return getConfig(configFile).packages?.map((pkg) => pkg.packageName) ?? [];
|
|
9190
8492
|
}
|
|
9191
8493
|
initConfigFileWatcher(configFile) {
|
|
9192
8494
|
if (!this.configWatcher) this.configWatcher = watchFile(configFile, { interval: 100 }, (curr, prev) => {
|
|
9193
|
-
if (curr.
|
|
9194
|
-
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);
|
|
9195
8497
|
});
|
|
9196
8498
|
}
|
|
9197
8499
|
updatePackagesMap(packagesMap) {
|
|
@@ -9230,6 +8532,10 @@ var PackageManager = class {
|
|
|
9230
8532
|
this.piecesMap = piecesMap;
|
|
9231
8533
|
this.eventEmitter.emit("piecesChange", piecesMap);
|
|
9232
8534
|
}
|
|
8535
|
+
/** The document models every loaded package ships, keyed by the package. */
|
|
8536
|
+
getDocumentModels() {
|
|
8537
|
+
return new Map(this.docModelsMap);
|
|
8538
|
+
}
|
|
9233
8539
|
/** The pieces every loaded package ships, keyed by the package. */
|
|
9234
8540
|
getPieces() {
|
|
9235
8541
|
return new Map(this.piecesMap);
|
|
@@ -9242,6 +8548,7 @@ var PackageManager = class {
|
|
|
9242
8548
|
*/
|
|
9243
8549
|
removePackage(pkg) {
|
|
9244
8550
|
this.logger.info(`Removing package: ${pkg}`);
|
|
8551
|
+
this.subscribedPackages.delete(pkg);
|
|
9245
8552
|
const dropKey = (map) => {
|
|
9246
8553
|
if (!map.has(pkg)) return map;
|
|
9247
8554
|
const next = new Map(map);
|
|
@@ -9259,22 +8566,39 @@ var PackageManager = class {
|
|
|
9259
8566
|
this.updatePiecesMap(this.piecesMap);
|
|
9260
8567
|
}
|
|
9261
8568
|
onDocumentModelsChange(handler) {
|
|
9262
|
-
this.eventEmitter.on("documentModelsChange",
|
|
8569
|
+
this.eventEmitter.on("documentModelsChange", (documentModels) => {
|
|
8570
|
+
runDetached("Document models change listener", () => handler(documentModels), this.detached);
|
|
8571
|
+
});
|
|
9263
8572
|
}
|
|
9264
8573
|
onSubgraphsChange(handler) {
|
|
9265
|
-
this.eventEmitter.on("subgraphsChange",
|
|
8574
|
+
this.eventEmitter.on("subgraphsChange", (subgraphs) => {
|
|
8575
|
+
runDetached("Subgraphs change listener", () => handler(subgraphs), this.detached);
|
|
8576
|
+
});
|
|
9266
8577
|
}
|
|
9267
8578
|
onProcessorsChange(handler) {
|
|
9268
|
-
this.eventEmitter.on("processorsChange",
|
|
8579
|
+
this.eventEmitter.on("processorsChange", (processors) => {
|
|
8580
|
+
runDetached("Processors change listener", () => handler(processors), this.detached);
|
|
8581
|
+
});
|
|
9269
8582
|
}
|
|
9270
8583
|
onPiecesChange(handler) {
|
|
9271
|
-
this.eventEmitter.on("piecesChange",
|
|
8584
|
+
this.eventEmitter.on("piecesChange", (pieces) => {
|
|
8585
|
+
runDetached("Pieces change listener", () => handler(pieces), this.detached);
|
|
8586
|
+
});
|
|
9272
8587
|
}
|
|
9273
8588
|
};
|
|
9274
8589
|
//#endregion
|
|
9275
8590
|
//#region src/config.ts
|
|
9276
8591
|
const config = { basePath: process.env.BASE_PATH || "/" };
|
|
9277
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
|
+
}
|
|
9278
8602
|
//#endregion
|
|
9279
8603
|
//#region src/attachment-backend.ts
|
|
9280
8604
|
/** Filesystem is the default; explicit S3 is readiness-gated without fallback. */
|
|
@@ -9795,6 +9119,90 @@ async function runMigrations(db) {
|
|
|
9795
9119
|
}
|
|
9796
9120
|
}
|
|
9797
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
|
|
9798
9206
|
//#region src/services/auth.service.ts
|
|
9799
9207
|
const DEFAULT_CREDENTIAL_CACHE_TTL_MS = 6e4;
|
|
9800
9208
|
const CREDENTIAL_CACHE_MAX_ENTRIES = 1e3;
|
|
@@ -10644,7 +10052,7 @@ function resolveGatewayAdapterType(logger) {
|
|
|
10644
10052
|
/**
|
|
10645
10053
|
* Sets up the subgraph manager and registers subgraphs
|
|
10646
10054
|
*/
|
|
10647
|
-
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 }) {
|
|
10648
10056
|
const graphqlManager = new GraphQLManager({
|
|
10649
10057
|
path: config.basePath,
|
|
10650
10058
|
httpServer,
|
|
@@ -10666,7 +10074,8 @@ async function setupGraphQLManager({ httpAdapter, authFetchMiddleware, requireAu
|
|
|
10666
10074
|
httpRoutes,
|
|
10667
10075
|
attachments,
|
|
10668
10076
|
inspection,
|
|
10669
|
-
driveStore
|
|
10077
|
+
driveStore,
|
|
10078
|
+
reportError
|
|
10670
10079
|
});
|
|
10671
10080
|
await graphqlManager.init(subgraphs.core, authFetchMiddleware, requireAuthFetchMiddleware);
|
|
10672
10081
|
await graphqlManager.applyPackageSubgraphs(subgraphs.extended);
|
|
@@ -10674,72 +10083,6 @@ async function setupGraphQLManager({ httpAdapter, authFetchMiddleware, requireAu
|
|
|
10674
10083
|
return graphqlManager;
|
|
10675
10084
|
}
|
|
10676
10085
|
/**
|
|
10677
|
-
* Sets up event listeners for package manager changes
|
|
10678
|
-
*/
|
|
10679
|
-
function setupEventListeners(pkgManager, graphqlManager, reactorProcessorManager, moduleFor, documentModelRegistry) {
|
|
10680
|
-
pkgManager.onDocumentModelsChange((packagedModels) => {
|
|
10681
|
-
if (documentModelRegistry) {
|
|
10682
|
-
const newModules = getUniqueDocumentModels(Object.values(packagedModels).flat());
|
|
10683
|
-
const incomingTypes = new Set(newModules.map((m) => m.documentModel.global.id));
|
|
10684
|
-
if (incomingTypes.size > 0) {
|
|
10685
|
-
documentModelRegistry.unregisterModules(...incomingTypes);
|
|
10686
|
-
const results = documentModelRegistry.registerModules(...newModules);
|
|
10687
|
-
for (const result of results) if (result.status === "success") defaultLogger.info(`Registered document model: ${result.item.documentModel.global.id} v${result.item.version ?? 1}`);
|
|
10688
|
-
else defaultLogger.error(`Failed to register document model: ${result.error.message}`);
|
|
10689
|
-
}
|
|
10690
|
-
const manifests = pkgManager.getUniqueUpgradeManifests();
|
|
10691
|
-
if (manifests.length > 0) {
|
|
10692
|
-
documentModelRegistry.unregisterUpgradeManifests(...manifests.map((m) => m.documentType));
|
|
10693
|
-
const manifestResults = documentModelRegistry.registerUpgradeManifests(...manifests);
|
|
10694
|
-
for (const result of manifestResults) if (result.status === "error") defaultLogger.error(`Failed to register upgrade manifest: ${result.error.message}`);
|
|
10695
|
-
}
|
|
10696
|
-
}
|
|
10697
|
-
graphqlManager.regenerateDocumentModelSubgraphs().catch((error) => {
|
|
10698
|
-
defaultLogger.error("Document model change left subgraphs stale: @error", error);
|
|
10699
|
-
});
|
|
10700
|
-
});
|
|
10701
|
-
pkgManager.onSubgraphsChange((packagedSubgraphs) => {
|
|
10702
|
-
graphqlManager.applyPackageSubgraphs(packagedSubgraphs).catch((error) => {
|
|
10703
|
-
defaultLogger.error("Failed to apply package subgraphs: @error", error);
|
|
10704
|
-
});
|
|
10705
|
-
});
|
|
10706
|
-
let knownProcessorPackages = /* @__PURE__ */ new Set();
|
|
10707
|
-
pkgManager.onProcessorsChange((processors) => {
|
|
10708
|
-
(async () => {
|
|
10709
|
-
for (const packageName of knownProcessorPackages) if (!processors.has(packageName)) try {
|
|
10710
|
-
await reactorProcessorManager.unregisterFactory(packageName);
|
|
10711
|
-
} catch (error) {
|
|
10712
|
-
defaultLogger.error("Failed to unregister processors of @package: @error", packageName, error);
|
|
10713
|
-
}
|
|
10714
|
-
knownProcessorPackages = new Set(processors.keys());
|
|
10715
|
-
for (const [packageName, fns] of processors) {
|
|
10716
|
-
try {
|
|
10717
|
-
await reactorProcessorManager.unregisterFactory(packageName);
|
|
10718
|
-
} catch (error) {
|
|
10719
|
-
defaultLogger.error("Failed to unregister processors of @package: @error", packageName, error);
|
|
10720
|
-
}
|
|
10721
|
-
const factories = await Promise.allSettled(fns.map(async (fn) => fn(moduleFor(packageName))));
|
|
10722
|
-
const validBuilders = [];
|
|
10723
|
-
for (const factory of factories) if (factory.status === "rejected") defaultLogger.error("Processor factory builder of @package failed: @error", packageName, factory.reason);
|
|
10724
|
-
else if (typeof factory.value === "function") validBuilders.push(factory.value);
|
|
10725
|
-
if (!validBuilders.length) continue;
|
|
10726
|
-
try {
|
|
10727
|
-
await reactorProcessorManager.registerFactory(packageName, async (driveHeader) => (await Promise.all(validBuilders.map(async (driveFactory) => {
|
|
10728
|
-
try {
|
|
10729
|
-
return await driveFactory(driveHeader);
|
|
10730
|
-
} catch (e) {
|
|
10731
|
-
defaultLogger.error(`Error creating processor for drive ${driveHeader.id}:`, e);
|
|
10732
|
-
return [];
|
|
10733
|
-
}
|
|
10734
|
-
}))).flat());
|
|
10735
|
-
} catch (error) {
|
|
10736
|
-
defaultLogger.error("Failed to register processors of @package: @error", packageName, error);
|
|
10737
|
-
}
|
|
10738
|
-
}
|
|
10739
|
-
})();
|
|
10740
|
-
});
|
|
10741
|
-
}
|
|
10742
|
-
/**
|
|
10743
10086
|
* Starts the server (HTTP or HTTPS) and attaches WebSocket server
|
|
10744
10087
|
*/
|
|
10745
10088
|
async function startServer(httpAdapter, port, httpsOptions, logger) {
|
|
@@ -10930,7 +10273,8 @@ async function _setupCommonInfrastructure(options) {
|
|
|
10930
10273
|
logger.info("Attachment service initialized");
|
|
10931
10274
|
const packages = new PackageManager(options.packageLoaders ?? [new ImportPackageLoader()], {
|
|
10932
10275
|
configFile: options.configFile,
|
|
10933
|
-
packages: options.packages ?? []
|
|
10276
|
+
packages: options.packages ?? [],
|
|
10277
|
+
reportError: options.reportError
|
|
10934
10278
|
});
|
|
10935
10279
|
const publicUrl = resolvePublicOrigin(port);
|
|
10936
10280
|
const webhooks = new WebhookService({
|
|
@@ -11019,13 +10363,11 @@ async function _setupAPI(reactorClient, syncManager, reactorProcessorManager, ht
|
|
|
11019
10363
|
refuseAnonymousReads: floor
|
|
11020
10364
|
});
|
|
11021
10365
|
const attachmentClientProvider = new AttachmentClientProvider(attachments.service, attachmentAccess, logger);
|
|
11022
|
-
const coreSubgraphs =
|
|
11023
|
-
|
|
11024
|
-
|
|
11025
|
-
|
|
11026
|
-
|
|
11027
|
-
logger.info("Auth subgraph registered (document permissions enabled)");
|
|
11028
|
-
}
|
|
10366
|
+
const coreSubgraphs = coreSubgraphClasses({
|
|
10367
|
+
inspection: !!inspection,
|
|
10368
|
+
documentPermissions: !!documentPermissionService
|
|
10369
|
+
});
|
|
10370
|
+
if (documentPermissionService) logger.info("Auth subgraph registered (document permissions enabled)");
|
|
11029
10371
|
const graphqlManager = await setupGraphQLManager({
|
|
11030
10372
|
httpAdapter,
|
|
11031
10373
|
authFetchMiddleware,
|
|
@@ -11051,9 +10393,13 @@ async function _setupAPI(reactorClient, syncManager, reactorProcessorManager, ht
|
|
|
11051
10393
|
httpRoutes,
|
|
11052
10394
|
attachments: attachmentClientProvider,
|
|
11053
10395
|
inspection,
|
|
11054
|
-
driveStore
|
|
10396
|
+
driveStore,
|
|
10397
|
+
reportError: options.reportError
|
|
10398
|
+
});
|
|
10399
|
+
setupEventListeners(packages, graphqlManager, reactorProcessorManager, moduleFor, documentModelRegistry, {
|
|
10400
|
+
logger,
|
|
10401
|
+
reportError: options.reportError
|
|
11055
10402
|
});
|
|
11056
|
-
setupEventListeners(packages, graphqlManager, reactorProcessorManager, moduleFor, documentModelRegistry);
|
|
11057
10403
|
if (mcpServerEnabled) {
|
|
11058
10404
|
await setupMcpServer({
|
|
11059
10405
|
client: reactorClient,
|
|
@@ -11147,7 +10493,7 @@ async function initializeAndStartAPI(clientInitializer, options, processorApp) {
|
|
|
11147
10493
|
const documentModelRegistry = reactorClientModule.reactorModule?.documentModelRegistry;
|
|
11148
10494
|
if (!documentModelRegistry) throw new Error("DocumentModelRegistry not available from InProcessReactorClientModule");
|
|
11149
10495
|
return {
|
|
11150
|
-
...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, {
|
|
11151
10497
|
...options.inspection,
|
|
11152
10498
|
attachmentStore: attachmentInspectionStore(attachments)
|
|
11153
10499
|
}) : void 0, reactorClientModule.reactorModule?.reactor),
|
|
@@ -11333,7 +10679,7 @@ var PackageManagementService = class {
|
|
|
11333
10679
|
}
|
|
11334
10680
|
};
|
|
11335
10681
|
//#endregion
|
|
11336
|
-
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, 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, buildGraphQlDocument, buildGraphQlDriveDocument, buildGraphqlOperation, buildGraphqlOperations, buildSubgraphSchemaModule, callerSubject, createAuthFetchMiddleware, createCanonicalDocumentIdResolver, createGatewayAdapter, createHttpAdapter, createInspectionResolvers, createMergedSchema, createReactorGraphQLClient, createReactorInspectionSource, createRenownCredentialVerifier, createSchema, createWsAuthHandlers, decodeExplorerUrlState, definedNonNullAnySchema, driveIdFromUrl, extractSubgraphs, extractSubgraphsFromModule, findSubgraphTypeCollisions, generateDocumentModelSchema, getAuthContext, getDbClient, getDocumentModelSchemaName, getDocumentModelTypeDefs, getExplorerPrefix, getGeneratedDocumentModelTypes, getGitHash, getGitUrl, getSdk, getUniqueDocumentModels, getUniqueUpgradeManifests, getVersion, initAnalyticsStoreSql, initializeAndStartAPI, inspectionTypeDefs, isDefinedNonNullAny, isExpectedLoaderMiss, isListedAdmin, isPostgresConnectionString, isSubgraphClass, namespacePath, namespaceSegments, newWebhookToken, parseDriveUrl, parseWebhookBody, piecesBaseUrl, redactHeaders, renderGraphqlPlayground, reservedTypeNames, reservedTypeNamesTaken, resolvePackageName, resolveRenownConfig,
|
|
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 };
|
|
11337
10683
|
|
|
11338
10684
|
//# sourceMappingURL=index.mjs.map
|
|
11339
|
-
//# debugId=
|
|
10685
|
+
//# debugId=5a6cd51c-1122-5d95-9bcf-8cf26e403d05
|