@powerhousedao/reactor-api 6.2.2-dev.7 → 6.2.2-dev.70

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,11 +1,11 @@
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]="e58cea2c-2319-52a8-90cd-3e99d94ba98f")}catch(e){}}();
3
- import { a as isSubgraphClass, c as loadDocumentModels, d as BaseSubgraph, f as AuthorizationPolicy, i as buildGraphqlOperations, l as loadProcessors, m as createAuthorizationService, n as buildGraphQlDriveDocument, o as debounce, p as AuthorizedDocumentHandle, r as buildGraphqlOperation, t as buildGraphQlDocument, u as loadSubgraphs } from "./utils-iibOQ50e.mjs";
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="42c7ea6f-655f-5a4b-84ac-b7870ee17334")}catch(e){}}();
3
+ import { _ as createAuthorizationService, a as isSubgraphClass, b as MalformedStoredOperationError, d as loadSubgraphs, f as BaseSubgraph, g as AuthorizedDocumentHandle, h as AuthorizationPolicy, i as buildGraphqlOperations, l as loadDocumentModels, m as createCanonicalDocumentIdResolver, n as buildGraphQlDriveDocument, o as debounce, p as CanonicalDocumentIdResolutionError, r as buildGraphqlOperation, s as extractUpgradeManifests, t as buildGraphQlDocument, u as loadProcessors, v as AuthEvaluationUnsupportedError, y as ForbiddenError } from "./utils-DeM5P0e8.mjs";
4
4
  import { AnalyticsQueryEngine } from "@powerhousedao/analytics-engine-core";
5
5
  import { AnalyticsModel, AnalyticsResolvers, typedefs } from "@powerhousedao/analytics-engine-graphql";
6
6
  import { gql } from "graphql-tag";
7
7
  import { GraphQLError, Kind, parse, print } from "graphql";
8
- import { DEFAULT_DRIVE_CONTAINER_TYPES, DriveCollectionId, PropagationMode as PropagationMode$1, consolidateSyncOperations, driveIdFromUrl, envelopesToSyncOperations, parseDriveUrl } from "@powerhousedao/reactor";
8
+ import { AuthEnforcementDisabledError, DEFAULT_DRIVE_CONTAINER_TYPES, DriveCollectionId, ModelReadGate, PropagationMode as PropagationMode$1, SyncScopeGate, consolidateSyncOperations, createReactorHostModuleBase, driveIdFromUrl, envelopesToSyncOperations, parseDriveUrl, readDecisionModel, syncOperationErrorType } from "@powerhousedao/reactor";
9
9
  import { ConsoleLogger, childLogger, documentModelDocumentModelModule } from "document-model";
10
10
  import path from "node:path";
11
11
  import { match } from "path-to-regexp";
@@ -13,7 +13,7 @@ import { buildSubgraphSchema } from "@apollo/subgraph";
13
13
  import { typeDefs } from "@powerhousedao/document-engineering/graphql";
14
14
  import { camelCase, kebabCase, pascalCase } from "change-case";
15
15
  import { GraphQLJSONObject } from "graphql-type-json";
16
- import { setName } from "@powerhousedao/shared/document-model";
16
+ import { deserializeSignature, serializeSignature, setName } from "@powerhousedao/shared/document-model";
17
17
  import * as z$1 from "zod";
18
18
  import { z } from "zod";
19
19
  import { createHandler } from "graphql-sse/lib/use/fetch";
@@ -22,11 +22,12 @@ import dotenv from "dotenv";
22
22
  import { buildTreeUrl } from "@powerhousedao/shared";
23
23
  import { getConfig } from "@powerhousedao/config/node";
24
24
  import { reactorDriveDocumentModelModule } from "@powerhousedao/reactor-drive";
25
+ import { ReactorGroupV1 } from "@powerhousedao/reactor-group";
25
26
  import { driveDocumentModelModule } from "@powerhousedao/shared/document-drive";
26
27
  import EventEmitter from "node:events";
27
28
  import fs, { watchFile } from "node:fs";
28
29
  import { PostgresAnalyticsStore } from "@powerhousedao/analytics-engine-pg";
29
- import { AttachmentBuilder } from "@powerhousedao/reactor-attachments";
30
+ import { AttachmentBuilder, AttachmentReferenceIndexBuilder, createRef, createS3AttachmentBackend, parseAttachmentStorageConfig, parseRef } from "@powerhousedao/reactor-attachments";
30
31
  import { createAttachmentClient } from "@powerhousedao/reactor-attachments/client";
31
32
  import { setupMcpServer } from "@powerhousedao/reactor-mcp";
32
33
  import { mkdir } from "node:fs/promises";
@@ -34,7 +35,7 @@ import { tmpdir } from "node:os";
34
35
  import { WebSocketServer } from "ws";
35
36
  import { createRelationalDb } from "@powerhousedao/shared/processors";
36
37
  import { Kysely, Migrator, sql } from "kysely";
37
- import { fetchDelegationCredential, verifyAuthBearerToken } from "@renown/sdk";
38
+ import { fetchDelegationCredential, resolveSwitchboardEndpoint, verifyAuthBearerToken } from "@renown/sdk";
38
39
  import { PGlite } from "@electric-sql/pglite";
39
40
  import { AtomicNodeFs } from "@powerhousedao/pglite-fs";
40
41
  import knex from "knex";
@@ -305,7 +306,7 @@ function createAuthFetchMiddleware(authService) {
305
306
  async function createGatewayAdapter(type, logger) {
306
307
  switch (type) {
307
308
  case "apollo": {
308
- const { ApolloGatewayAdapter } = await import("./adapter-gateway-apollo-CxV_hMTv.mjs");
309
+ const { ApolloGatewayAdapter } = await import("./adapter-gateway-apollo-DKR6jpFf.mjs");
309
310
  return new ApolloGatewayAdapter(logger);
310
311
  }
311
312
  case "mercurius": {
@@ -404,7 +405,7 @@ const buildSubgraphSchemaModule = (documentModels, resolvers, typeDefs) => {
404
405
  };
405
406
  };
406
407
  const createSchema = (documentModels, resolvers, typeDefs) => {
407
- return buildSubgraphSchema(buildSubgraphSchemaModule(documentModels, resolvers, typeDefs));
408
+ return buildSubgraphSchema([buildSubgraphSchemaModule(documentModels, resolvers, typeDefs)]);
408
409
  };
409
410
  /**
410
411
  * Create a merged GraphQL schema from multiple subgraph modules.
@@ -460,6 +461,7 @@ const getDocumentModelTypeDefs = (documentModels, typeDefs$1) => {
460
461
  });
461
462
  return dedupeTypeDefinitions(gql`
462
463
  scalar JSONObject
464
+ scalar AttachmentRef
463
465
  ${typeDefs.join("\n").replaceAll(";", "")}
464
466
 
465
467
  type PHOperationContext {
@@ -878,6 +880,7 @@ function generateNewApiSchema(documentName, specification, _stateSchemaTypes, pr
878
880
  return gql`
879
881
  scalar DateTime
880
882
  scalar JSONObject
883
+ scalar AttachmentRef
881
884
 
882
885
  ${revisionType}
883
886
 
@@ -926,6 +929,11 @@ function generateNewApiSchema(documentName, specification, _stateSchemaTypes, pr
926
929
  }
927
930
  //#endregion
928
931
  //#region src/graphql/reactor/gen/graphql.ts
932
+ let AuthDecision = /* @__PURE__ */ function(AuthDecision) {
933
+ AuthDecision["Allow"] = "ALLOW";
934
+ AuthDecision["Deny"] = "DENY";
935
+ return AuthDecision;
936
+ }({});
929
937
  let DocumentChangeType = /* @__PURE__ */ function(DocumentChangeType) {
930
938
  DocumentChangeType["ChildAdded"] = "CHILD_ADDED";
931
939
  DocumentChangeType["ChildRemoved"] = "CHILD_REMOVED";
@@ -948,11 +956,24 @@ let SyncEnvelopeType = /* @__PURE__ */ function(SyncEnvelopeType) {
948
956
  }({});
949
957
  const isDefinedNonNullAny = (v) => v !== void 0 && v !== null;
950
958
  const definedNonNullAnySchema = z$1.any().refine((v) => isDefinedNonNullAny(v));
959
+ const AuthDecisionSchema = z$1.enum(AuthDecision);
951
960
  const DocumentChangeTypeSchema = z$1.enum(DocumentChangeType);
952
961
  const PropagationModeSchema = z$1.enum(PropagationMode);
953
962
  const SyncEnvelopeTypeSchema = z$1.enum(SyncEnvelopeType);
963
+ function ActionCandidateInputSchema() {
964
+ return z$1.object({
965
+ input: z$1.custom((v) => v != null).nullish(),
966
+ scope: z$1.string(),
967
+ type: z$1.string()
968
+ });
969
+ }
954
970
  function ActionContextInputSchema() {
955
- return z$1.object({ signer: z$1.lazy(() => ReactorSignerInputSchema().nullish()) });
971
+ return z$1.object({
972
+ nonce: z$1.string().nullish(),
973
+ prevOpHash: z$1.string().nullish(),
974
+ prevOpIndex: z$1.number().nullish(),
975
+ signer: z$1.lazy(() => ReactorSignerInputSchema().nullish())
976
+ });
956
977
  }
957
978
  function ActionInputSchema() {
958
979
  return z$1.object({
@@ -989,6 +1010,7 @@ function OperationContextInputSchema() {
989
1010
  function OperationInputSchema() {
990
1011
  return z$1.object({
991
1012
  action: z$1.lazy(() => ActionInputSchema()),
1013
+ deniedReason: z$1.string().nullish(),
992
1014
  error: z$1.string().nullish(),
993
1015
  hash: z$1.string(),
994
1016
  id: z$1.string().nullish(),
@@ -1147,6 +1169,7 @@ const GetDocumentWithOperationsDocument = gql`
1147
1169
  hash
1148
1170
  skip
1149
1171
  error
1172
+ deniedReason
1150
1173
  id
1151
1174
  action {
1152
1175
  id
@@ -1259,6 +1282,7 @@ const GetDocumentOperationsDocument = gql`
1259
1282
  hash
1260
1283
  skip
1261
1284
  error
1285
+ deniedReason
1262
1286
  id
1263
1287
  action {
1264
1288
  id
@@ -1301,6 +1325,28 @@ const GetJobStatusDocument = gql`
1301
1325
  }
1302
1326
  }
1303
1327
  `;
1328
+ const EvaluateActionsDocument = gql`
1329
+ query EvaluateActions(
1330
+ $documentIdentifier: String!
1331
+ $branch: String
1332
+ $candidates: [ActionCandidateInput!]!
1333
+ ) {
1334
+ evaluateActions(
1335
+ documentIdentifier: $documentIdentifier
1336
+ branch: $branch
1337
+ candidates: $candidates
1338
+ ) {
1339
+ evaluations {
1340
+ decision
1341
+ reason
1342
+ }
1343
+ allAllowed
1344
+ anyAllowed
1345
+ allDenied
1346
+ anyDenied
1347
+ }
1348
+ }
1349
+ `;
1304
1350
  const CreateDocumentDocument = gql`
1305
1351
  mutation CreateDocument($document: JSONObject!, $parentIdentifier: String) {
1306
1352
  createDocument(document: $document, parentIdentifier: $parentIdentifier) {
@@ -1326,13 +1372,13 @@ const CreateEmptyDocumentDocument = gql`
1326
1372
  const MutateDocumentDocument = gql`
1327
1373
  mutation MutateDocument(
1328
1374
  $documentIdentifier: String!
1329
- $actions: [JSONObject!]!
1330
- $view: ViewFilterInput
1375
+ $actions: [ActionInput!]!
1376
+ $branch: String
1331
1377
  ) {
1332
- mutateDocument(
1378
+ mutateDocument: execute(
1333
1379
  documentIdentifier: $documentIdentifier
1334
1380
  actions: $actions
1335
- view: $view
1381
+ branch: $branch
1336
1382
  ) {
1337
1383
  ...PHDocumentFields
1338
1384
  }
@@ -1342,14 +1388,21 @@ const MutateDocumentDocument = gql`
1342
1388
  const MutateDocumentAsyncDocument = gql`
1343
1389
  mutation MutateDocumentAsync(
1344
1390
  $documentIdentifier: String!
1345
- $actions: [JSONObject!]!
1346
- $view: ViewFilterInput
1391
+ $actions: [ActionInput!]!
1392
+ $branch: String
1347
1393
  ) {
1348
- mutateDocumentAsync(
1394
+ mutateDocumentAsync: executeAsync(
1349
1395
  documentIdentifier: $documentIdentifier
1350
1396
  actions: $actions
1351
- view: $view
1352
- )
1397
+ branch: $branch
1398
+ ) {
1399
+ id
1400
+ status
1401
+ result
1402
+ error
1403
+ createdAt
1404
+ completedAt
1405
+ }
1353
1406
  }
1354
1407
  `;
1355
1408
  const RenameDocumentDocument = gql`
@@ -1509,6 +1562,7 @@ const PollSyncEnvelopesDocument = gql`
1509
1562
  hash
1510
1563
  skip
1511
1564
  error
1565
+ deniedReason
1512
1566
  id
1513
1567
  action {
1514
1568
  id
@@ -1551,6 +1605,7 @@ const PollSyncEnvelopesDocument = gql`
1551
1605
  deadLetters {
1552
1606
  documentId
1553
1607
  error
1608
+ errorType
1554
1609
  }
1555
1610
  hasMore
1556
1611
  }
@@ -1595,6 +1650,9 @@ function getSdk(requester) {
1595
1650
  GetJobStatus(variables, options) {
1596
1651
  return requester(GetJobStatusDocument, variables, options);
1597
1652
  },
1653
+ EvaluateActions(variables, options) {
1654
+ return requester(EvaluateActionsDocument, variables, options);
1655
+ },
1598
1656
  CreateDocument(variables, options) {
1599
1657
  return requester(CreateDocumentDocument, variables, options);
1600
1658
  },
@@ -1745,28 +1803,132 @@ function toReactorPropagationMode(gqlMode) {
1745
1803
  }
1746
1804
  }
1747
1805
  /**
1806
+ * Maps one predicted verdict to its GraphQL shape. A refusal's reason is the
1807
+ * consensus string the reactor would record for it, carried through verbatim so
1808
+ * a client can tell a deletion refusal from a missing grant; an allow has none.
1809
+ */
1810
+ function toGqlActionEvaluation(evaluation) {
1811
+ return evaluation.decision === "allow" ? {
1812
+ decision: AuthDecision.Allow,
1813
+ reason: null
1814
+ } : {
1815
+ decision: AuthDecision.Deny,
1816
+ reason: evaluation.reason
1817
+ };
1818
+ }
1819
+ /**
1748
1820
  * Converts readonly arrays to mutable arrays for ReactorClient
1749
1821
  */
1750
1822
  function toMutableArray(arr) {
1751
1823
  return arr ? [...arr] : void 0;
1752
1824
  }
1753
1825
  /**
1754
- * Validates that a JSONObject represents a valid Action structure
1826
+ * Validates that an incoming value has the structure of an Action.
1827
+ *
1828
+ * This is the whole guard on the way in. `mutateDocument` takes untyped JSON, so
1829
+ * nothing has checked these fields before a resolver runs, and the id in
1830
+ * particular has to be checked here: it is hashed into the operation id and
1831
+ * replay dedupes by it, so an action without one is stored under an operation id
1832
+ * shared by every id-less operation on the same document, scope and branch.
1833
+ *
1834
+ * The storage constraint would refuse such a row anyway, but only after a job
1835
+ * has been enqueued and failed. Refusing here answers the caller instead.
1755
1836
  */
1756
1837
  function validateActionStructure(obj) {
1757
1838
  if (!obj || typeof obj !== "object") return false;
1758
1839
  const action = obj;
1840
+ if (typeof action.id !== "string" || !action.id) return false;
1759
1841
  if (typeof action.type !== "string" || !action.type) return false;
1760
1842
  if (typeof action.scope !== "string" || !action.scope) return false;
1843
+ if (typeof action.timestampUtcMs !== "string" || !action.timestampUtcMs) return false;
1761
1844
  if (!("input" in action)) return false;
1762
1845
  return true;
1763
1846
  }
1764
1847
  /**
1848
+ * Restores an action's signatures to the tuples verification reads.
1849
+ *
1850
+ * A signature is a five-param tuple, and GraphQL declares `signatures` as a
1851
+ * list of strings, so a client joins each one for transport. The sync path
1852
+ * already splits them on arrival; this is the same step for the mutation path,
1853
+ * which had none - an action submitted there kept whatever shape it arrived in,
1854
+ * so the same signature was persisted as a tuple or as one joined string
1855
+ * depending on which door it came through.
1856
+ *
1857
+ * A tuple passes through untouched, so an in-process caller handing over real
1858
+ * signatures is unaffected.
1859
+ */
1860
+ function withDeserializedSignatures(action) {
1861
+ const signer = action.context?.signer;
1862
+ if (!signer?.signatures || signer.signatures.length === 0) return action;
1863
+ return {
1864
+ ...action,
1865
+ context: {
1866
+ ...action.context,
1867
+ signer: {
1868
+ ...signer,
1869
+ signatures: signer.signatures.map(deserializeSignature)
1870
+ }
1871
+ }
1872
+ };
1873
+ }
1874
+ /**
1875
+ * Converts actions the schema has already coerced into the actions the reactor
1876
+ * applies.
1877
+ *
1878
+ * The one conversion the schema cannot express is the signature: GraphQL
1879
+ * declares `signatures` as a list of strings, not of lists, so each arrives
1880
+ * joined and has to be read back as the tuple verification indexes into.
1881
+ *
1882
+ * Nothing is validated here. `ActionInput` states every field the reactor needs,
1883
+ * so anything that reached this point has them - unlike the untyped path, which
1884
+ * has to check by hand.
1885
+ */
1886
+ function toSubmittableActions(actions) {
1887
+ return actions.map((action) => {
1888
+ const context = toSubmittableContext(action.context);
1889
+ const submittable = {
1890
+ id: action.id,
1891
+ type: action.type,
1892
+ timestampUtcMs: action.timestampUtcMs,
1893
+ input: action.input,
1894
+ scope: action.scope
1895
+ };
1896
+ return context ? {
1897
+ ...submittable,
1898
+ context
1899
+ } : submittable;
1900
+ });
1901
+ }
1902
+ /**
1903
+ * `ReactorSignerInput` leaves `user` and `app` optional where `ActionSigner`
1904
+ * requires them, so an incomplete signer cannot be represented. It is carried
1905
+ * through as it arrived rather than filled in: the signature verifier is what
1906
+ * should refuse it, and inventing either field here would be inventing the part
1907
+ * that says who signed.
1908
+ */
1909
+ function toSubmittableContext(context) {
1910
+ if (!context) return;
1911
+ const submittable = {};
1912
+ const prevOpIndex = fromInputMaybe(context.prevOpIndex);
1913
+ if (prevOpIndex !== void 0) submittable.prevOpIndex = prevOpIndex;
1914
+ const prevOpHash = fromInputMaybe(context.prevOpHash);
1915
+ if (prevOpHash !== void 0) submittable.prevOpHash = prevOpHash;
1916
+ const nonce = fromInputMaybe(context.nonce);
1917
+ if (nonce !== void 0) submittable.nonce = nonce;
1918
+ const signer = fromInputMaybe(context.signer);
1919
+ if (signer) submittable.signer = {
1920
+ user: fromInputMaybe(signer.user),
1921
+ app: fromInputMaybe(signer.app),
1922
+ signatures: signer.signatures.map(deserializeSignature)
1923
+ };
1924
+ return Object.keys(submittable).length > 0 ? submittable : void 0;
1925
+ }
1926
+ /**
1765
1927
  * Converts a JSONObject to an Action, validating basic structure
1766
1928
  */
1767
1929
  function jsonObjectToAction(obj) {
1768
- if (!validateActionStructure(obj)) throw new GraphQLError("Invalid action structure. Actions must have: type (string), scope (string), and input (any)");
1769
- return obj;
1930
+ if (!validateActionStructure(obj)) throw new GraphQLError("Invalid action structure. Actions must have: id (string), type (string), scope (string), timestampUtcMs (string), and input (any)");
1931
+ return withDeserializedSignatures(obj);
1770
1932
  }
1771
1933
  /**
1772
1934
  * Validates a list of actions by converting them from JSON and checking structure
@@ -1780,10 +1942,57 @@ function validateActions(actions) {
1780
1942
  }
1781
1943
  return convertedActions;
1782
1944
  }
1945
+ /** The operation fields the schema declares non-null. */
1946
+ const REQUIRED_OPERATION_FIELDS = [
1947
+ "index",
1948
+ "timestampUtcMs",
1949
+ "hash",
1950
+ "skip"
1951
+ ];
1952
+ /** The action fields the schema declares non-null. */
1953
+ const REQUIRED_ACTION_FIELDS = [
1954
+ "id",
1955
+ "type",
1956
+ "timestampUtcMs",
1957
+ "input",
1958
+ "scope"
1959
+ ];
1960
+ /**
1961
+ * Names an operation well enough to find the row it came from, without assuming
1962
+ * the fields that might be the missing ones.
1963
+ */
1964
+ function describeOperation(stored) {
1965
+ const parts = [typeof stored.id === "string" && stored.id ? `operation ${stored.id}` : "operation with no id"];
1966
+ if (typeof stored.index === "number") parts.push(`index ${stored.index}`);
1967
+ const scope = stored.action?.scope;
1968
+ if (typeof scope === "string" && scope) parts.push(`scope ${scope}`);
1969
+ return parts.join(", ");
1970
+ }
1971
+ /**
1972
+ * Refuses an operation the schema cannot represent, naming the field.
1973
+ *
1974
+ * The alternative is what execution does unaided: nullify the field, bubble that
1975
+ * up the non-null chain until it takes out the envelope's whole operation list,
1976
+ * and report a bare "Cannot return null for non-nullable field" with no way to
1977
+ * tell which of a hundred operations was at fault. Checked before the response
1978
+ * is built so the failure is typed and attributable.
1979
+ *
1980
+ * Presence is all that is checked. The schema's own serialization still rejects
1981
+ * a value of the wrong type, and inventing further rules here would put a second
1982
+ * contract beside the one the schema already states.
1983
+ */
1984
+ function assertServable(operation) {
1985
+ const stored = operation;
1986
+ for (const field of REQUIRED_OPERATION_FIELDS) if (stored[field] === void 0 || stored[field] === null) throw new MalformedStoredOperationError(`${describeOperation(stored)} has no ${field}`);
1987
+ const action = stored.action;
1988
+ if (action === void 0 || action === null) throw new MalformedStoredOperationError(`${describeOperation(stored)} has no action`);
1989
+ for (const field of REQUIRED_ACTION_FIELDS) if (action[field] === void 0 || action[field] === null) throw new MalformedStoredOperationError(`${describeOperation(stored)} has an action with no ${field}`);
1990
+ }
1783
1991
  /**
1784
1992
  * Transforms an operation to serialize signatures from tuples to strings for GraphQL compatibility.
1785
1993
  */
1786
1994
  function serializeOperationForGraphQL(operation) {
1995
+ assertServable(operation);
1787
1996
  const signer = operation.action.context?.signer;
1788
1997
  if (!signer?.signatures) return operation;
1789
1998
  return {
@@ -1794,7 +2003,7 @@ function serializeOperationForGraphQL(operation) {
1794
2003
  ...operation.action.context,
1795
2004
  signer: {
1796
2005
  ...signer,
1797
- signatures: signer.signatures.map((sig) => Array.isArray(sig) ? sig.join(", ") : sig)
2006
+ signatures: signer.signatures.map(serializeSignature)
1798
2007
  }
1799
2008
  }
1800
2009
  }
@@ -1904,9 +2113,10 @@ async function documentModels(reactorClient, args) {
1904
2113
  throw new GraphQLError(`Failed to convert document models to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
1905
2114
  }
1906
2115
  }
1907
- async function document(reactorClient, args) {
1908
- let view;
2116
+ async function document(reactorClient, args, subject) {
2117
+ let view = subject ? { subject } : void 0;
1909
2118
  if (args.view) view = {
2119
+ subject,
1910
2120
  branch: fromInputMaybe(args.view.branch),
1911
2121
  scopes: toMutableArray(fromInputMaybe(args.view.scopes))
1912
2122
  };
@@ -1931,9 +2141,10 @@ async function document(reactorClient, args) {
1931
2141
  throw new GraphQLError(`Failed to convert document to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
1932
2142
  }
1933
2143
  }
1934
- async function documentOutgoingRelationships(reactorClient, args) {
1935
- let view;
2144
+ async function documentOutgoingRelationships(reactorClient, args, subject) {
2145
+ let view = subject ? { subject } : void 0;
1936
2146
  if (args.view) view = {
2147
+ subject,
1937
2148
  branch: fromInputMaybe(args.view.branch),
1938
2149
  scopes: toMutableArray(fromInputMaybe(args.view.scopes))
1939
2150
  };
@@ -1958,9 +2169,10 @@ async function documentOutgoingRelationships(reactorClient, args) {
1958
2169
  throw new GraphQLError(`Failed to convert outgoing relationships to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
1959
2170
  }
1960
2171
  }
1961
- async function documentIncomingRelationships(reactorClient, args) {
1962
- let view;
2172
+ async function documentIncomingRelationships(reactorClient, args, subject) {
2173
+ let view = subject ? { subject } : void 0;
1963
2174
  if (args.view) view = {
2175
+ subject,
1964
2176
  branch: fromInputMaybe(args.view.branch),
1965
2177
  scopes: toMutableArray(fromInputMaybe(args.view.scopes))
1966
2178
  };
@@ -1985,9 +2197,10 @@ async function documentIncomingRelationships(reactorClient, args) {
1985
2197
  throw new GraphQLError(`Failed to convert incoming relationships to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
1986
2198
  }
1987
2199
  }
1988
- async function findDocuments(reactorClient, args) {
1989
- let view;
2200
+ async function findDocuments(reactorClient, args, subject) {
2201
+ let view = subject ? { subject } : void 0;
1990
2202
  if (args.view) view = {
2203
+ subject,
1991
2204
  branch: fromInputMaybe(args.view.branch),
1992
2205
  scopes: toMutableArray(fromInputMaybe(args.view.scopes))
1993
2206
  };
@@ -2029,11 +2242,12 @@ async function jobStatus(reactorClient, args) {
2029
2242
  throw new GraphQLError(`Failed to convert job status to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
2030
2243
  }
2031
2244
  }
2032
- async function documentOperations(reactorClient, args) {
2033
- let view;
2245
+ async function documentOperations(reactorClient, args, subject) {
2246
+ let view = subject ? { subject } : void 0;
2034
2247
  const branch = fromInputMaybe(args.filter.branch);
2035
2248
  const scopes = toMutableArray(fromInputMaybe(args.filter.scopes));
2036
2249
  if (branch || scopes) view = {
2250
+ subject,
2037
2251
  branch,
2038
2252
  scopes
2039
2253
  };
@@ -2069,6 +2283,41 @@ async function documentOperations(reactorClient, args) {
2069
2283
  throw new GraphQLError(`Failed to convert operations to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
2070
2284
  }
2071
2285
  }
2286
+ /**
2287
+ * Predicts the admission verdict for each candidate operation, deciding against
2288
+ * the document policy through the reactor's own decision model.
2289
+ *
2290
+ * The subject is supplied by the subgraph from the authenticated request, never
2291
+ * by the caller: answering for an arbitrary subject would disclose what a policy
2292
+ * grants somebody else. It carries the caller's address and the app key their
2293
+ * token authenticated with, which is the same pair a signed action presents, so
2294
+ * a grant naming either matches here exactly as it would at admission.
2295
+ *
2296
+ * A reactor without authEnforcement raises the named error, which becomes an
2297
+ * "unsupported" code rather than a denial.
2298
+ */
2299
+ async function evaluateActions(reactorClient, args, subject) {
2300
+ const branch = fromInputMaybe(args.branch) ?? "main";
2301
+ const candidates = args.candidates.map((candidate) => ({
2302
+ scope: candidate.scope,
2303
+ type: candidate.type,
2304
+ input: fromInputMaybe(candidate.input)
2305
+ }));
2306
+ let result;
2307
+ try {
2308
+ result = await reactorClient.evaluateActions(args.documentIdentifier, branch, candidates, subject);
2309
+ } catch (error) {
2310
+ if (AuthEnforcementDisabledError.isError(error)) throw new AuthEvaluationUnsupportedError();
2311
+ throw new GraphQLError(`Failed to evaluate actions: ${error instanceof Error ? error.message : "Unknown error"}`);
2312
+ }
2313
+ return {
2314
+ evaluations: result.evaluations.map(toGqlActionEvaluation),
2315
+ allAllowed: result.allAllowed,
2316
+ anyAllowed: result.anyAllowed,
2317
+ allDenied: result.allDenied,
2318
+ anyDenied: result.anyDenied
2319
+ };
2320
+ }
2072
2321
  async function createDocument(reactorClient, args, reactorDriveClient) {
2073
2322
  if (!args.document || typeof args.document !== "object") throw new GraphQLError("Invalid document: must be an object");
2074
2323
  const document = args.document;
@@ -2167,6 +2416,49 @@ async function createDocumentWithInitialState(reactorClient, args, reactorDriveC
2167
2416
  throw new GraphQLError(`Failed to convert created document to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
2168
2417
  }
2169
2418
  }
2419
+ /** The branch a mutation applies to when the caller names none. */
2420
+ const DEFAULT_BRANCH = "main";
2421
+ /**
2422
+ * Applies actions to a document and waits for the result.
2423
+ *
2424
+ * The wire form of `IReactorClient.execute`, and named for it. Takes the actions
2425
+ * already coerced against `ActionInput`, so the only conversion left is the one
2426
+ * the schema cannot express: a signature travels as one string, and verification
2427
+ * reads it as the tuple it was.
2428
+ */
2429
+ async function execute(reactorClient, args) {
2430
+ const actions = toSubmittableActions(args.actions);
2431
+ const branch = fromInputMaybe(args.branch) ?? DEFAULT_BRANCH;
2432
+ let result;
2433
+ try {
2434
+ result = await reactorClient.execute(args.documentIdentifier, branch, actions);
2435
+ } catch (error) {
2436
+ throw new GraphQLError(`Failed to execute actions: ${error instanceof Error ? error.message : "Unknown error"}`);
2437
+ }
2438
+ try {
2439
+ return toGqlPhDocument(result);
2440
+ } catch (error) {
2441
+ throw new GraphQLError(`Failed to convert executed document to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
2442
+ }
2443
+ }
2444
+ /**
2445
+ * Submits actions to a document and returns the job that will apply them.
2446
+ *
2447
+ * Returns the job rather than only its id, matching
2448
+ * `IReactorClient.executeAsync`. A job handed back from a submission has no
2449
+ * result yet, which is why `JobInfo.result` is nullable.
2450
+ */
2451
+ async function executeAsync(reactorClient, args) {
2452
+ const actions = toSubmittableActions(args.actions);
2453
+ const branch = fromInputMaybe(args.branch) ?? DEFAULT_BRANCH;
2454
+ let job;
2455
+ try {
2456
+ job = await reactorClient.executeAsync(args.documentIdentifier, branch, actions);
2457
+ } catch (error) {
2458
+ throw new GraphQLError(`Failed to submit actions: ${error instanceof Error ? error.message : "Unknown error"}`);
2459
+ }
2460
+ return toGqlJobInfo(job);
2461
+ }
2170
2462
  async function mutateDocument(reactorClient, args) {
2171
2463
  let validatedActions;
2172
2464
  try {
@@ -2300,7 +2592,14 @@ async function deleteDocuments(reactorClient, args) {
2300
2592
  throw new GraphQLError(`Failed to delete documents: ${error instanceof Error ? error.message : "Unknown error"}`);
2301
2593
  }
2302
2594
  }
2303
- async function touchChannel(syncManager, args) {
2595
+ /**
2596
+ * Registers a sync channel, or reports the state of one already registered.
2597
+ *
2598
+ * `boundAddress` claims a channel at creation for the subject that created it.
2599
+ * An anonymously created channel is left unbound, which is not a permission but
2600
+ * an unanswered question: the first authenticated subject to use it adopts it.
2601
+ */
2602
+ async function touchChannel(syncManager, args, boundAddress) {
2304
2603
  try {
2305
2604
  return {
2306
2605
  success: true,
@@ -2312,7 +2611,10 @@ async function touchChannel(syncManager, args) {
2312
2611
  scope: [...args.input.filter.scope],
2313
2612
  branch: args.input.filter.branch
2314
2613
  };
2315
- const options = { sinceTimestampUtcMs: args.input.sinceTimestampUtcMs };
2614
+ const options = {
2615
+ sinceTimestampUtcMs: args.input.sinceTimestampUtcMs,
2616
+ boundAddress
2617
+ };
2316
2618
  try {
2317
2619
  await syncManager.add(args.input.name, DriveCollectionId.fromKey(args.input.collectionId), {
2318
2620
  type: "polling",
@@ -2327,9 +2629,50 @@ async function touchChannel(syncManager, args) {
2327
2629
  };
2328
2630
  }
2329
2631
  /**
2632
+ * The sync operations in `syncOps` this subject may not be served.
2633
+ *
2634
+ * A sync operation is one document, one branch and (from the outbox) one scope,
2635
+ * so the answer is per entry rather than per operation: an entry is withheld
2636
+ * whole or served whole, which is what keeps a scope's operation sequence
2637
+ * unbroken for whoever does receive it. A dead letter can name several scopes,
2638
+ * and is withheld only when the policy serves none of them -- the metadata
2639
+ * scopes are readable by every holder, so in practice a dead letter naming one
2640
+ * is always served.
2641
+ *
2642
+ * The policy is read once per document and branch, and the memo lives no longer
2643
+ * than this call: a poll must not answer from a policy that changed between
2644
+ * polls, since the widening case is exactly the one holding exists to serve.
2645
+ *
2646
+ * A read that fails for any reason other than the document being absent is
2647
+ * allowed to propagate. The poll then fails, the puller retries, and nothing is
2648
+ * served in the meantime -- which is the safe direction, and a visible one.
2649
+ */
2650
+ async function collectHeldSyncOperations(syncOps, gate, subject, signal) {
2651
+ const held = /* @__PURE__ */ new Set();
2652
+ const predicates = /* @__PURE__ */ new Map();
2653
+ for (const syncOp of syncOps) {
2654
+ const key = `${syncOp.documentId}\u0000${syncOp.branch}`;
2655
+ let predicate = predicates.get(key);
2656
+ if (!predicate) {
2657
+ predicate = gate.scopePredicateById(syncOp.documentId, subject, syncOp.branch, signal);
2658
+ predicates.set(key, predicate);
2659
+ }
2660
+ const readable = await predicate;
2661
+ if (!syncOp.scopes.some((scope) => readable(scope))) held.add(syncOp.id);
2662
+ }
2663
+ return held;
2664
+ }
2665
+ /**
2330
2666
  * Polls the switchboard for new sync envelopes and acknowledges previously
2331
2667
  * received operations.
2332
2668
  *
2669
+ * `forbiddenIds` and `heldOpIds` are two different refusals. A forbidden
2670
+ * document is consumed: its delivery counters are advanced as though it had
2671
+ * been sent, so it is never reconsidered. A held sync operation is withheld:
2672
+ * nothing about it is touched, so a policy that later widens serves it whole on
2673
+ * a subsequent poll. Which one applies is the caller's decision, and the two
2674
+ * are intersected, so a document refused either way is not served.
2675
+ *
2333
2676
  * Ordinal frames of reference:
2334
2677
  * - `outboxAck` / `outboxLatest`: switchboard's ordinals (used to trim/filter
2335
2678
  * the switchboard's outbox)
@@ -2337,16 +2680,17 @@ async function touchChannel(syncManager, args) {
2337
2680
  * client ordinal the switchboard has successfully applied, so the client
2338
2681
  * can trim its own outbox)
2339
2682
  */
2340
- function pollSyncEnvelopes(syncManager, args, forbiddenIds = /* @__PURE__ */ new Set()) {
2683
+ function pollSyncEnvelopes(syncManager, args, forbiddenIds = /* @__PURE__ */ new Set(), heldOpIds = /* @__PURE__ */ new Set()) {
2341
2684
  let remote;
2342
2685
  try {
2343
2686
  remote = syncManager.getById(args.channelId);
2344
2687
  } catch (error) {
2345
2688
  throw new GraphQLError(`Channel not found: ${error instanceof Error ? error.message : "Unknown error"}`);
2346
2689
  }
2347
- const deadLetters = remote.channel.deadLetter.items.filter((syncOp) => !forbiddenIds.has(syncOp.documentId)).map((syncOp) => ({
2690
+ const deadLetters = remote.channel.deadLetter.items.filter((syncOp) => !forbiddenIds.has(syncOp.documentId) && !heldOpIds.has(syncOp.id)).map((syncOp) => ({
2348
2691
  documentId: syncOp.documentId,
2349
2692
  error: syncOp.error?.message ?? "Unknown error",
2693
+ errorType: syncOperationErrorType(syncOp.error),
2350
2694
  jobId: syncOp.jobId,
2351
2695
  branch: syncOp.branch,
2352
2696
  scopes: syncOp.scopes,
@@ -2392,6 +2736,7 @@ function pollSyncEnvelopes(syncManager, args, forbiddenIds = /* @__PURE__ */ new
2392
2736
  hasMore = true;
2393
2737
  break;
2394
2738
  }
2739
+ if (heldOpIds.has(syncOp.id)) continue;
2395
2740
  syncOp.deliveredCount ??= 0;
2396
2741
  syncOp.emittedCount ??= 0;
2397
2742
  while (syncOp.deliveredCount < syncOp.emittedCount && syncOp.operations[syncOp.deliveredCount].context.ordinal <= args.outboxLatest) syncOp.deliveredCount += 1;
@@ -2875,6 +3220,9 @@ var GraphQLManager = class {
2875
3220
  /** Cached document models for schema generation - updated on init and regenerate */
2876
3221
  cachedDocumentModels = [];
2877
3222
  subgraphHandlerCache = /* @__PURE__ */ new Map();
3223
+ /** Per-subgraph handlers by name, before auth/drive middleware is applied,
3224
+ * for in-process queries by trusted internals. */
3225
+ #internalSubgraphHandlers = /* @__PURE__ */ new Map();
2878
3226
  /**
2879
3227
  * Optional reactor-drive client. When the switchboard is configured with a
2880
3228
  * reactor-drive container, this is provided and the resolvers dispatch to
@@ -2882,7 +3230,7 @@ var GraphQLManager = class {
2882
3230
  */
2883
3231
  reactorDriveClient;
2884
3232
  authorizationService;
2885
- constructor(path, httpServer, wsServer, reactorClient, relationalDb, analyticsStore, syncManager, logger, httpAdapter, gatewayAdapter, authService, documentPermissionService, featureFlags = DefaultFeatureFlags, port = 4001, authorizationService, reactorDriveClient) {
3233
+ constructor(path, httpServer, wsServer, reactorClient, relationalDb, analyticsStore, syncManager, logger, httpAdapter, gatewayAdapter, authService, documentPermissionService, featureFlags = DefaultFeatureFlags, port = 4001, authorizationService, reactorDriveClient, syncServingGate) {
2886
3234
  this.path = path;
2887
3235
  this.httpServer = httpServer;
2888
3236
  this.wsServer = wsServer;
@@ -2897,6 +3245,7 @@ var GraphQLManager = class {
2897
3245
  this.documentPermissionService = documentPermissionService;
2898
3246
  this.featureFlags = featureFlags;
2899
3247
  this.port = port;
3248
+ this.syncServingGate = syncServingGate;
2900
3249
  if (!authorizationService) throw new Error("GraphQLManager requires an authorizationService");
2901
3250
  this.authorizationService = authorizationService;
2902
3251
  this.reactorDriveClient = reactorDriveClient;
@@ -2914,7 +3263,7 @@ var GraphQLManager = class {
2914
3263
  if (!models.find((it) => it.documentModel.global.name === "DocumentDrive")) throw new Error("DocumentDrive model required");
2915
3264
  await this.gatewayAdapter.start(this.httpServer);
2916
3265
  this.httpAdapter.setupMiddleware({ bodyLimit: "50mb" });
2917
- const driveRoutePath = path.join(this.path, "d/:drive");
3266
+ const driveRoutePath = path.posix.join(this.path, "d/:drive");
2918
3267
  const driveMatcher = match(driveRoutePath);
2919
3268
  this.httpAdapter.mount(driveRoutePath, async (request) => {
2920
3269
  const url = new URL(request.url);
@@ -2982,7 +3331,8 @@ var GraphQLManager = class {
2982
3331
  syncManager: this.syncManager,
2983
3332
  path: this.path,
2984
3333
  documentPermissionService: this.documentPermissionService,
2985
- authorizationService: this.authorizationService
3334
+ authorizationService: this.authorizationService,
3335
+ syncServingGate: this.syncServingGate
2986
3336
  });
2987
3337
  await this.#addSubgraphInstance(subgraphInstance, supergraph, false);
2988
3338
  } catch (error) {
@@ -3036,10 +3386,49 @@ var GraphQLManager = class {
3036
3386
  syncManager: this.syncManager,
3037
3387
  path: this.path,
3038
3388
  documentPermissionService: this.documentPermissionService,
3039
- authorizationService: this.authorizationService
3389
+ authorizationService: this.authorizationService,
3390
+ syncServingGate: this.syncServingGate
3040
3391
  });
3041
3392
  return this.#addSubgraphInstance(subgraphInstance, supergraph, core);
3042
3393
  }
3394
+ /** Find a registered subgraph by name, core or package-contributed. */
3395
+ getSubgraphByName(name) {
3396
+ for (const subgraphs of [...this.coreSubgraphsMap.values(), ...this.subgraphs.values()]) {
3397
+ const found = subgraphs.find((subgraph) => subgraph.name === name);
3398
+ if (found) return found;
3399
+ }
3400
+ }
3401
+ /** Whether a registered subgraph has a live handler, i.e. whether
3402
+ * {@link executeSubgraphQuery} can reach it right now. */
3403
+ hasSubgraphHandler(name) {
3404
+ return this.#internalSubgraphHandlers.has(name);
3405
+ }
3406
+ /** Run a query against one registered subgraph in-process: the subgraph's own
3407
+ * handler, without a socket or the auth/drive middleware. Trusted callers. */
3408
+ async executeSubgraphQuery(subgraphName, query, variables) {
3409
+ const entry = this.#internalSubgraphHandlers.get(subgraphName);
3410
+ if (!entry) throw new Error(this.getSubgraphByName(subgraphName) ? `Subgraph "${subgraphName}" is registered but has no handler yet` : `Subgraph "${subgraphName}" is not registered`);
3411
+ const url = new URL(entry.path, `http://localhost:${this.port}/`);
3412
+ const response = await entry.handler(new Request(url, {
3413
+ method: "POST",
3414
+ headers: {
3415
+ "content-type": "application/json",
3416
+ accept: "application/json"
3417
+ },
3418
+ body: JSON.stringify({
3419
+ query,
3420
+ variables
3421
+ })
3422
+ }));
3423
+ if (!response.ok) {
3424
+ const detail = await response.text().catch(() => "");
3425
+ throw new Error(`Subgraph "${subgraphName}" query failed: ${response.status}${detail ? ` ${detail}` : ""}`);
3426
+ }
3427
+ const body = await response.json();
3428
+ if (body.errors?.length) throw new Error(body.errors.map((error) => error.message).join("; "));
3429
+ if (!body.data) throw new Error(`Subgraph "${subgraphName}" returned no data`);
3430
+ return body.data;
3431
+ }
3043
3432
  updateRouter = debounce(this._updateRouter.bind(this), 1e3);
3044
3433
  async _updateRouter() {
3045
3434
  this.logger.debug("Updating router");
@@ -3050,7 +3439,7 @@ var GraphQLManager = class {
3050
3439
  } catch (error) {
3051
3440
  this.logger.error("Failed to update Apollo Gateway supergraph: @error", error);
3052
3441
  }
3053
- const superGraphPath = path.join(this.path, "graphql");
3442
+ const superGraphPath = path.posix.join(this.path, "graphql");
3054
3443
  this.#setupSupergraphSSE(superGraphPath);
3055
3444
  }
3056
3445
  getAdditionalContextFields = () => {
@@ -3113,7 +3502,21 @@ var GraphQLManager = class {
3113
3502
  });
3114
3503
  }
3115
3504
  #getSubgraphPath(subgraph, supergraph) {
3116
- return path.join(subgraph.path ?? "", supergraph, subgraph.name);
3505
+ return path.posix.join(subgraph.path ?? "", supergraph, subgraph.name);
3506
+ }
3507
+ /** The in-process handler map is keyed by bare name, so two distinct
3508
+ * subgraphs sharing one name would shadow each other: keep the first. */
3509
+ #setInternalSubgraphHandler(subgraph, subgraphPath, handler) {
3510
+ const existing = this.#internalSubgraphHandlers.get(subgraph.name);
3511
+ if (existing && existing.subgraph !== subgraph) {
3512
+ this.logger.warn("Two subgraphs are named @name (@kept and @ignored); in-process queries keep the first", subgraph.name, existing.path, subgraphPath);
3513
+ return;
3514
+ }
3515
+ this.#internalSubgraphHandlers.set(subgraph.name, {
3516
+ subgraph,
3517
+ path: subgraphPath,
3518
+ handler
3519
+ });
3117
3520
  }
3118
3521
  async #setupSubgraphs(subgraphsMap) {
3119
3522
  for (const [supergraph, subgraphs] of subgraphsMap.entries()) for (const subgraph of subgraphs) {
@@ -3125,6 +3528,7 @@ var GraphQLManager = class {
3125
3528
  const rawHandler = await this.gatewayAdapter.createHandler(schema, this.#makeContextFactory());
3126
3529
  const fetchHandler = this.#composeFetchMiddleware(rawHandler);
3127
3530
  this.subgraphHandlerCache.set(subgraphPath, fetchHandler);
3531
+ this.#setInternalSubgraphHandler(subgraph, subgraphPath, rawHandler);
3128
3532
  this.httpAdapter.mount(subgraphPath, fetchHandler);
3129
3533
  if (subgraph.hasSubscriptions) {
3130
3534
  try {
@@ -3171,7 +3575,7 @@ var GraphQLManager = class {
3171
3575
  }));
3172
3576
  }
3173
3577
  async #createSupergraphGateway() {
3174
- const superGraphPath = path.join(this.path, "graphql");
3578
+ const superGraphPath = path.posix.join(this.path, "graphql");
3175
3579
  const rawHandler = await this.gatewayAdapter.createSupergraphHandler(() => this.#getSubgraphDefinitions(), this.httpServer, this.#makeContextFactory());
3176
3580
  const fetchHandler = this.#composeFetchMiddleware(rawHandler);
3177
3581
  this.httpAdapter.mount(superGraphPath, fetchHandler);
@@ -3536,6 +3940,17 @@ const DocumentChangeEventDTO = z.object({
3536
3940
  documents: z.array(PHDocumentDTO),
3537
3941
  context: DocumentChangeContextDTO.nullable().optional()
3538
3942
  }).strip();
3943
+ const ActionEvaluationDTO = z.object({
3944
+ decision: z.enum(["ALLOW", "DENY"]),
3945
+ reason: z.string().nullable().optional()
3946
+ }).strip();
3947
+ const ActionEvaluationsDTO = z.object({
3948
+ evaluations: z.array(ActionEvaluationDTO),
3949
+ allAllowed: z.boolean(),
3950
+ anyAllowed: z.boolean(),
3951
+ allDenied: z.boolean(),
3952
+ anyDenied: z.boolean()
3953
+ }).strip();
3539
3954
  const JobChangeEventDTO = z.object({
3540
3955
  jobId: z.string(),
3541
3956
  status: z.string(),
@@ -3569,6 +3984,9 @@ const operationValidators = {
3569
3984
  GetJobStatus: (data) => {
3570
3985
  if (data.jobStatus) JobInfoDTO.parse(data.jobStatus);
3571
3986
  },
3987
+ EvaluateActions: (data) => {
3988
+ if (data.evaluateActions) ActionEvaluationsDTO.parse(data.evaluateActions);
3989
+ },
3572
3990
  CreateDocument: (data) => {
3573
3991
  if (data.createDocument) PHDocumentDTO.parse(data.createDocument);
3574
3992
  },
@@ -3631,7 +4049,7 @@ function createReactorGraphQLClient(url, fetchImpl = fetch, headers) {
3631
4049
  }
3632
4050
  //#endregion
3633
4051
  //#region src/graphql/reactor/schema.graphql
3634
- 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}\n\ninput OperationsFilterInput {\n documentId: String!\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 totalCount: Int!\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 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 totalCount: Int!\n hasNextPage: Boolean!\n hasPreviousPage: Boolean!\n cursor: String\n}\n\ntype ReactorOperationResultPage {\n items: [ReactorOperation!]!\n totalCount: Int!\n hasNextPage: Boolean!\n hasPreviousPage: Boolean!\n cursor: String\n}\n\ntype DeadLetterInfo {\n documentId: String!\n error: 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}\n\ntype DocumentWithChildren {\n document: PHDocument!\n childIds: [String!]!\n}\n\ntype MoveRelationshipResult {\n source: PHDocument!\n target: PHDocument!\n}\n\ntype JobInfo {\n id: String!\n status: String!\n result: JSONObject!\n error: String\n createdAt: DateTime!\n completedAt: DateTime\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 result: JSONObject!\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# Input types for sync operations\ninput ActionContextInput {\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# Synchronization types\ntype ReactorOperation {\n index: Int!\n timestampUtcMs: String!\n hash: String!\n skip: Int!\n error: 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 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 TouchChannelInput {\n id: String!\n name: String!\n collectionId: String!\n filter: RemoteFilterInput!\n sinceTimestampUtcMs: String!\n}\n\ntype TouchChannelResult {\n success: Boolean!\n ackOrdinal: Int!\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(identifier: String!, view: ViewFilterInput): DocumentWithChildren\n\n # Get outgoing relationships of a given type from a source document\n documentOutgoingRelationships(\n sourceIdentifier: String!\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 targetIdentifier: String!\n relationshipType: String!\n view: ViewFilterInput\n paging: PagingInput\n ): PHDocumentResultPage!\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 # Get operations for a document with filtering and pagination\n documentOperations(\n filter: OperationsFilterInput!\n paging: PagingInput\n ): ReactorOperationResultPage!\n\n # Poll for sync envelopes from a channel\n pollSyncEnvelopes(\n channelId: String!\n outboxAck: Int!\n outboxLatest: Int!\n ): PollSyncEnvelopesResult!\n}\n\ntype Mutation {\n # Create a new document\n createDocument(document: JSONObject!, parentIdentifier: String): PHDocument!\n\n # Create an empty document of specified type\n createEmptyDocument(\n documentType: String!\n parentIdentifier: String\n ): PHDocument!\n\n # Apply actions to a document (synchronous)\n mutateDocument(\n documentIdentifier: String!\n actions: [JSONObject!]!\n view: ViewFilterInput\n ): PHDocument!\n\n # Submit actions to a document (asynchronous)\n mutateDocumentAsync(\n documentIdentifier: String!\n actions: [JSONObject!]!\n view: ViewFilterInput\n ): String!\n\n # Rename a document\n renameDocument(\n documentIdentifier: String!\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 documentIdentifier: String!\n preferredEditor: String\n branch: String\n ): PHDocument!\n\n # Add a relationship between two documents\n addRelationship(\n sourceIdentifier: String!\n targetIdentifier: String!\n relationshipType: String!\n branch: String\n ): PHDocument!\n\n # Remove a relationship between two documents\n removeRelationship(\n sourceIdentifier: String!\n targetIdentifier: String!\n relationshipType: String!\n branch: String\n ): PHDocument!\n\n # Move a relationship from one source to another\n moveRelationship(\n sourceParentIdentifier: String!\n targetParentIdentifier: String!\n targetIdentifier: String!\n relationshipType: String!\n branch: String\n ): MoveRelationshipResult!\n\n # Delete a single document\n deleteDocument(identifier: String!, propagate: PropagationMode): Boolean!\n\n # Delete multiple documents\n deleteDocuments(identifiers: [String!]!, propagate: PropagationMode): 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(envelopes: [SyncEnvelopeInput!]!): 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";
4052
+ 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}\n\ninput OperationsFilterInput {\n documentId: String!\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 totalCount: Int!\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 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 totalCount: Int!\n hasNextPage: Boolean!\n hasPreviousPage: Boolean!\n cursor: String\n}\n\ntype ReactorOperationResultPage {\n items: [ReactorOperation!]!\n totalCount: Int!\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}\n\ntype DocumentWithChildren {\n document: PHDocument!\n childIds: [String!]!\n}\n\ntype MoveRelationshipResult {\n source: PHDocument!\n target: PHDocument!\n}\n\ntype JobInfo {\n id: 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 createdAt: DateTime!\n completedAt: DateTime\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 result: JSONObject!\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 \"\"\"The index of the last operation in the scope the action applies to.\"\"\"\n prevOpIndex: Int\n\n \"\"\"The hash of the state the action applies to.\"\"\"\n prevOpHash: String\n\n \"\"\"Covers replay of an operation that would otherwise be a no-op.\"\"\"\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# 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 TouchChannelInput {\n id: String!\n name: String!\n collectionId: String!\n filter: RemoteFilterInput!\n sinceTimestampUtcMs: String!\n}\n\ntype TouchChannelResult {\n success: Boolean!\n ackOrdinal: Int!\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(identifier: String!, view: ViewFilterInput): DocumentWithChildren\n\n # Get outgoing relationships of a given type from a source document\n documentOutgoingRelationships(\n sourceIdentifier: String!\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 targetIdentifier: String!\n relationshipType: String!\n view: ViewFilterInput\n paging: PagingInput\n ): PHDocumentResultPage!\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 # 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 documentIdentifier: String!\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 ): PollSyncEnvelopesResult!\n}\n\ntype Mutation {\n # Create a new document\n createDocument(document: JSONObject!, parentIdentifier: String): PHDocument!\n\n # Create an empty document of specified type\n createEmptyDocument(\n documentType: String!\n parentIdentifier: String\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 documentIdentifier: String!\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 documentIdentifier: String!\n actions: [ActionInput!]!\n branch: String\n ): JobInfo!\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 documentIdentifier: String!\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 documentIdentifier: String!\n preferredEditor: String\n branch: String\n ): PHDocument!\n\n # Add a relationship between two documents\n addRelationship(\n sourceIdentifier: String!\n targetIdentifier: String!\n relationshipType: String!\n branch: String\n ): PHDocument!\n\n # Remove a relationship between two documents\n removeRelationship(\n sourceIdentifier: String!\n targetIdentifier: String!\n relationshipType: String!\n branch: String\n ): PHDocument!\n\n # Move a relationship from one source to another\n moveRelationship(\n sourceParentIdentifier: String!\n targetParentIdentifier: String!\n targetIdentifier: String!\n relationshipType: String!\n branch: String\n ): MoveRelationshipResult!\n\n # Delete a single document\n deleteDocument(identifier: String!, propagate: PropagationMode): Boolean!\n\n # Delete multiple documents\n deleteDocuments(identifiers: [String!]!, propagate: PropagationMode): 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(envelopes: [SyncEnvelopeInput!]!): 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";
3635
4053
  //#endregion
3636
4054
  //#region src/graphql/reactor/pubsub.ts
3637
4055
  const pubSub = new PubSub();
@@ -3769,6 +4187,46 @@ var ReactorSubgraph = class extends BaseSubgraph {
3769
4187
  if (!await this.canReadDocument(documentId, ctx)) forbidden.add(documentId);
3770
4188
  }
3771
4189
  }
4190
+ /**
4191
+ * Enforces which subject a sync channel answers to, adopting an unclaimed one.
4192
+ *
4193
+ * A channel is a private queue: it names a collection, and it accumulates
4194
+ * exactly the operations one subject is owed, so serving it to a second
4195
+ * subject would hand over that subject's cursor as well as its contents. An
4196
+ * unbound channel -- created anonymously, or created before binding existed --
4197
+ * is claimed by the first authenticated subject to use it, and answers to that
4198
+ * address alone thereafter. Adoption is safe precisely because serving
4199
+ * withholds rather than consumes: before it was claimed the channel served
4200
+ * only what an anonymous subject may read, and everything withheld is still
4201
+ * queued for the adopter.
4202
+ *
4203
+ * The refusal is the shape a read denial takes, so a puller treats it as a
4204
+ * signal to authenticate again rather than as a transport failure.
4205
+ *
4206
+ * Nothing is enforced or adopted without a serving gate. Below
4207
+ * `authEnforcement` there is no policy being enforced for the channel to
4208
+ * belong to, and refusing a poll there would break sync for no gain.
4209
+ */
4210
+ async #bindOrRefuseChannel(channelId, ctx) {
4211
+ if (!this.syncServingGate) return;
4212
+ let remote;
4213
+ try {
4214
+ remote = this.syncManager.getById(channelId);
4215
+ } catch {
4216
+ return;
4217
+ }
4218
+ const bound = remote.meta.options.boundAddress;
4219
+ const address = ctx.user?.address;
4220
+ if (bound === void 0) {
4221
+ if (address !== void 0) await this.syncManager.bindRemote(channelId, address);
4222
+ return;
4223
+ }
4224
+ if (bound !== address) throw new ForbiddenError("to poll this sync channel");
4225
+ }
4226
+ /** The address a channel created by this request belongs to, if any. */
4227
+ #creatorBinding(ctx) {
4228
+ return this.syncServingGate ? ctx.user?.address : void 0;
4229
+ }
3772
4230
  typeDefs = gql(schema_default);
3773
4231
  resolvers = {
3774
4232
  PHDocument: { operations: async (parent, args, ctx) => {
@@ -3787,7 +4245,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
3787
4245
  return await documentOperations(this.reactorClient, {
3788
4246
  filter,
3789
4247
  paging: args.paging
3790
- });
4248
+ }, this.viewSubject(ctx));
3791
4249
  } catch (error) {
3792
4250
  this.logger.error("Error in PHDocument.operations: @Error", error);
3793
4251
  throw error;
@@ -3810,7 +4268,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
3810
4268
  return await document(this.reactorClient, {
3811
4269
  ...args,
3812
4270
  identifier: handle.fetchIdentifier
3813
- });
4271
+ }, this.viewSubject(ctx));
3814
4272
  } catch (error) {
3815
4273
  this.logger.error("Error in document: @Error", error);
3816
4274
  throw error;
@@ -3823,7 +4281,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
3823
4281
  return await documentOutgoingRelationships(this.reactorClient, {
3824
4282
  ...args,
3825
4283
  sourceIdentifier: handle.fetchIdentifier
3826
- });
4284
+ }, this.viewSubject(ctx));
3827
4285
  } catch (error) {
3828
4286
  this.logger.error("Error in documentOutgoingRelationships: @Error", error);
3829
4287
  throw error;
@@ -3836,7 +4294,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
3836
4294
  const result = await documentIncomingRelationships(this.reactorClient, {
3837
4295
  ...args,
3838
4296
  targetIdentifier: handle.fetchIdentifier
3839
- });
4297
+ }, this.viewSubject(ctx));
3840
4298
  if (!this.authorizationService.isSupremeAdmin(ctx.user?.address)) {
3841
4299
  const filteredItems = [];
3842
4300
  for (const item of result.items) if (await this.canReadDocument(item.id, ctx)) filteredItems.push(item);
@@ -3857,7 +4315,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
3857
4315
  const result = await findDocuments(this.reactorClient, {
3858
4316
  ...args,
3859
4317
  search: args.search ?? {}
3860
- });
4318
+ }, this.viewSubject(ctx));
3861
4319
  if (!this.authorizationService.isSupremeAdmin(ctx.user?.address)) {
3862
4320
  const filteredItems = [];
3863
4321
  for (const item of result.items) if (await this.canReadDocument(item.id, ctx)) filteredItems.push(item);
@@ -3891,12 +4349,25 @@ var ReactorSubgraph = class extends BaseSubgraph {
3891
4349
  ...args.filter,
3892
4350
  documentId: handle.fetchIdentifier
3893
4351
  }
3894
- });
4352
+ }, this.viewSubject(ctx));
3895
4353
  } catch (error) {
3896
4354
  this.logger.error("Error in documentOperations: @Error", error);
3897
4355
  throw error;
3898
4356
  }
3899
4357
  },
4358
+ evaluateActions: async (_parent, args, ctx) => {
4359
+ this.logger.debug("evaluateActions(@args)", args);
4360
+ try {
4361
+ const handle = await this.assertCanRead(args.documentIdentifier, ctx);
4362
+ return await evaluateActions(this.reactorClient, {
4363
+ ...args,
4364
+ documentIdentifier: handle.fetchIdentifier
4365
+ }, this.viewSubject(ctx));
4366
+ } catch (error) {
4367
+ this.logger.error("Error in evaluateActions: @Error", error);
4368
+ throw error;
4369
+ }
4370
+ },
3900
4371
  pollSyncEnvelopes: async (_parent, args, ctx) => {
3901
4372
  this.logger.debug("pollSyncEnvelopes(@args)", args);
3902
4373
  try {
@@ -3909,12 +4380,14 @@ var ReactorSubgraph = class extends BaseSubgraph {
3909
4380
  const driveId = remote.meta.collectionId.driveId;
3910
4381
  const isAdmin = this.authorizationService.isSupremeAdmin(ctx.user?.address);
3911
4382
  if (!isAdmin) await this.assertCanReadCanonical(driveId, ctx);
4383
+ await this.#bindOrRefuseChannel(args.channelId, ctx);
3912
4384
  const forbiddenIds = /* @__PURE__ */ new Set();
3913
4385
  if (!isAdmin) {
3914
4386
  if (await this.authorizationService.canRead(driveId, void 0)) await this.#collectForbiddenDocuments(remote.channel.outbox.items, forbiddenIds, ctx);
3915
4387
  await this.#collectForbiddenDocuments(remote.channel.deadLetter.items, forbiddenIds, ctx);
3916
4388
  }
3917
- const { envelopes, ackOrdinal, deadLetters, hasMore } = pollSyncEnvelopes(this.syncManager, args, forbiddenIds);
4389
+ const heldOpIds = this.syncServingGate ? await collectHeldSyncOperations([...remote.channel.outbox.items, ...remote.channel.deadLetter.items], this.syncServingGate, this.viewSubject(ctx)) : /* @__PURE__ */ new Set();
4390
+ const { envelopes, ackOrdinal, deadLetters, hasMore } = pollSyncEnvelopes(this.syncManager, args, forbiddenIds, heldOpIds);
3918
4391
  return {
3919
4392
  envelopes,
3920
4393
  ackOrdinal,
@@ -3960,6 +4433,32 @@ var ReactorSubgraph = class extends BaseSubgraph {
3960
4433
  throw error;
3961
4434
  }
3962
4435
  },
4436
+ execute: async (_parent, args, ctx) => {
4437
+ this.logger.debug("execute(@args)", args);
4438
+ try {
4439
+ const handle = await this.assertCanExecuteOperations(args.documentIdentifier, args.actions, ctx);
4440
+ return await execute(this.reactorClient, {
4441
+ ...args,
4442
+ documentIdentifier: handle.fetchIdentifier
4443
+ });
4444
+ } catch (error) {
4445
+ this.logger.error("Error in execute(@args): @Error", args, error);
4446
+ throw error;
4447
+ }
4448
+ },
4449
+ executeAsync: async (_parent, args, ctx) => {
4450
+ this.logger.debug("executeAsync(@args)", args);
4451
+ try {
4452
+ const handle = await this.assertCanExecuteOperations(args.documentIdentifier, args.actions, ctx);
4453
+ return await executeAsync(this.reactorClient, {
4454
+ ...args,
4455
+ documentIdentifier: handle.fetchIdentifier
4456
+ });
4457
+ } catch (error) {
4458
+ this.logger.error("Error in executeAsync(@args): @Error", args, error);
4459
+ throw error;
4460
+ }
4461
+ },
3963
4462
  mutateDocument: async (_parent, args, ctx) => {
3964
4463
  this.logger.debug("mutateDocument(@args)", args);
3965
4464
  try {
@@ -4093,7 +4592,8 @@ var ReactorSubgraph = class extends BaseSubgraph {
4093
4592
  const driveId = DriveCollectionId.fromKey(args.input.collectionId).driveId;
4094
4593
  await this.assertCanReadCanonical(driveId, ctx);
4095
4594
  }
4096
- return await touchChannel(this.syncManager, args);
4595
+ await this.#bindOrRefuseChannel(args.input.id, ctx);
4596
+ return await touchChannel(this.syncManager, args, this.#creatorBinding(ctx));
4097
4597
  } catch (error) {
4098
4598
  this.logger.error("Error in touchChannel(@args): @Error", args, error);
4099
4599
  throw error;
@@ -4205,10 +4705,10 @@ const ADMIN_USERS = getAdminUsers();
4205
4705
  //#endregion
4206
4706
  //#region src/graphql/system/version.ts
4207
4707
  function getVersion() {
4208
- return "6.2.2-dev.7";
4708
+ return "6.2.2-dev.70";
4209
4709
  }
4210
4710
  function getGitHash() {
4211
- return "cf61e36ec3ba12c9edb828e6e9870842ce2388e4";
4711
+ return "da05f917d6912bc30c5c944823c216ec47e19fa8";
4212
4712
  }
4213
4713
  function getGitUrl() {
4214
4714
  return buildTreeUrl(getGitHash());
@@ -4306,6 +4806,13 @@ var HttpPackageLoader = class {
4306
4806
  this.logger.verbose(`Loaded ${models.length} document models from ${packageName}`);
4307
4807
  return models;
4308
4808
  }
4809
+ async loadUpgradeManifests(packageSpec) {
4810
+ const { name: packageName } = this.parsePackageSpec(packageSpec);
4811
+ if (!this.isValidPackageName(packageName)) throw new Error(`Invalid package name: ${packageName}`);
4812
+ const manifests = extractUpgradeManifests(await import(`${this.registryUrl}-/cdn/${packageSpec}/node/document-models/index.mjs`));
4813
+ if (manifests.length > 0) this.logger.verbose(`Loaded ${manifests.length} upgrade manifests from ${packageName}`);
4814
+ return manifests;
4815
+ }
4309
4816
  async loadSubgraphs(packageSpec) {
4310
4817
  const { name: packageName } = this.parsePackageSpec(packageSpec);
4311
4818
  if (!this.isValidPackageName(packageName)) throw new Error(`Invalid package name: ${packageName}`);
@@ -4431,7 +4938,7 @@ var ImportPackageLoader = class {
4431
4938
  this.logger.verbose(`Loading document models from package: ${identifier}`);
4432
4939
  const pkgModule = await loadDocumentModels(identifier);
4433
4940
  if (pkgModule) {
4434
- const models = Object.values(pkgModule);
4941
+ const models = Object.values(pkgModule).filter((m) => m !== null && typeof m === "object" && "documentModel" in m);
4435
4942
  this.logger.verbose(` ➜ Loaded ${models.length} Document Models from: ${identifier}`);
4436
4943
  return models;
4437
4944
  } else {
@@ -4439,6 +4946,13 @@ var ImportPackageLoader = class {
4439
4946
  return [];
4440
4947
  }
4441
4948
  }
4949
+ async loadUpgradeManifests(identifier) {
4950
+ const pkgModule = await loadDocumentModels(identifier);
4951
+ if (!pkgModule) return [];
4952
+ const manifests = extractUpgradeManifests(pkgModule);
4953
+ if (manifests.length > 0) this.logger.verbose(` ➜ Loaded ${manifests.length} Upgrade Manifests from: ${identifier}`);
4954
+ return manifests;
4955
+ }
4442
4956
  async loadSubgraphs(identifier) {
4443
4957
  this.logger.verbose(`Loading subgraphs from package: ${identifier}`);
4444
4958
  const pkgModule = await loadSubgraphs(identifier);
@@ -4487,13 +5001,19 @@ function isExpectedLoaderMiss(error, pkg) {
4487
5001
  }
4488
5002
  function getUniqueDocumentModels(...documentModels) {
4489
5003
  const uniqueModels = /* @__PURE__ */ new Map();
4490
- for (const models of documentModels) for (const model of models) uniqueModels.set(model.documentModel.global.id, model);
5004
+ for (const models of documentModels) for (const model of models) uniqueModels.set(`${model.documentModel.global.id}@${model.version ?? 1}`, model);
4491
5005
  return Array.from(uniqueModels.values());
4492
5006
  }
5007
+ function getUniqueUpgradeManifests(...upgradeManifests) {
5008
+ const uniqueManifests = /* @__PURE__ */ new Map();
5009
+ for (const manifests of upgradeManifests) for (const manifest of manifests) uniqueManifests.set(manifest.documentType, manifest);
5010
+ return Array.from(uniqueManifests.values());
5011
+ }
4493
5012
  var PackageManager = class {
4494
5013
  logger = childLogger(["reactor-api", "package-manager"]);
4495
5014
  loaders;
4496
5015
  docModelsMap = /* @__PURE__ */ new Map();
5016
+ upgradeManifestsMap = /* @__PURE__ */ new Map();
4497
5017
  subgraphsMap = /* @__PURE__ */ new Map();
4498
5018
  processorMap = /* @__PURE__ */ new Map();
4499
5019
  configWatcher;
@@ -4511,8 +5031,10 @@ var PackageManager = class {
4511
5031
  async loadPackages(packages) {
4512
5032
  this.logger.info("Loading packages: @packages", packages.join(", "));
4513
5033
  const documentModelsMap = await this.loadDocumentModels(packages);
5034
+ const upgradeManifestsMap = await this.loadUpgradeManifests(packages);
4514
5035
  const subgraphsMap = await this.loadSubgraphs(packages);
4515
5036
  const processorsMap = await this.loadProcessors(packages);
5037
+ this.upgradeManifestsMap = upgradeManifestsMap;
4516
5038
  this.updatePackagesMap(documentModelsMap);
4517
5039
  this.updateSubgraphsMap(subgraphsMap);
4518
5040
  this.updateProcessorsMap(processorsMap);
@@ -4523,6 +5045,7 @@ var PackageManager = class {
4523
5045
  }
4524
5046
  return {
4525
5047
  documentModels: getUniqueDocumentModels(...Array.from(documentModelsMap.values())),
5048
+ upgradeManifests: this.getUniqueUpgradeManifests(),
4526
5049
  subgraphs: subgraphsMap,
4527
5050
  processors: processorsMap
4528
5051
  };
@@ -4533,6 +5056,7 @@ var PackageManager = class {
4533
5056
  documentModelModuleMap.set("document-drive", [driveDocumentModelModule]);
4534
5057
  documentModelModuleMap.set("document-model", [documentModelDocumentModelModule]);
4535
5058
  documentModelModuleMap.set("reactor-drive", [reactorDriveDocumentModelModule]);
5059
+ documentModelModuleMap.set("reactor-group", [ReactorGroupV1]);
4536
5060
  for (const pkg of packages) {
4537
5061
  const allDocumentModels = [];
4538
5062
  const failures = [];
@@ -4555,6 +5079,26 @@ var PackageManager = class {
4555
5079
  }
4556
5080
  return documentModelModuleMap;
4557
5081
  }
5082
+ /** Upgrade manifests currently loaded across all packages, one per type. */
5083
+ getUniqueUpgradeManifests() {
5084
+ return getUniqueUpgradeManifests(...Array.from(this.upgradeManifestsMap.values()));
5085
+ }
5086
+ async loadUpgradeManifests(packages) {
5087
+ const manifestsMap = /* @__PURE__ */ new Map();
5088
+ for (const pkg of packages) for (const loader of this.loaders) {
5089
+ if (!loader.loadUpgradeManifests) continue;
5090
+ try {
5091
+ const manifests = await loader.loadUpgradeManifests(pkg);
5092
+ if (manifests.length > 0) {
5093
+ manifestsMap.set(pkg, manifests);
5094
+ break;
5095
+ }
5096
+ } catch (error) {
5097
+ this.logger.debug(`[${loader.name}] Failed to load upgrade manifests from package @pkg: @error`, pkg, error);
5098
+ }
5099
+ }
5100
+ return manifestsMap;
5101
+ }
4558
5102
  async loadSubgraphs(packages) {
4559
5103
  this.logger.debug(`Loading subgraphs from packages: ${packages.join(", ")}`);
4560
5104
  const subgraphsMap = /* @__PURE__ */ new Map();
@@ -4616,6 +5160,10 @@ var PackageManager = class {
4616
5160
  async updateDocumentModelsForPackage(pkg) {
4617
5161
  this.logger.debug(`Updating document models for package: ${pkg}`);
4618
5162
  const documentModels = await this.loadDocumentModels([pkg]);
5163
+ const upgradeManifests = await this.loadUpgradeManifests([pkg]);
5164
+ const upgradeManifestsMap = new Map(this.upgradeManifestsMap);
5165
+ upgradeManifestsMap.set(pkg, upgradeManifests.get(pkg) ?? []);
5166
+ this.upgradeManifestsMap = upgradeManifestsMap;
4619
5167
  const documentModelsMap = new Map(this.docModelsMap);
4620
5168
  documentModelsMap.set(pkg, documentModels.get(pkg) ?? []);
4621
5169
  this.updatePackagesMap(documentModelsMap);
@@ -4695,6 +5243,70 @@ var PackageManager = class {
4695
5243
  const config = { basePath: process.env.BASE_PATH || "/" };
4696
5244
  const DefaultCoreSubgraphs = [AnalyticsSubgraph, SystemSubgraph];
4697
5245
  //#endregion
5246
+ //#region src/attachment-backend.ts
5247
+ /** Filesystem is the default; explicit S3 is readiness-gated without fallback. */
5248
+ async function createStartupAttachmentBackend({ db, env = process.env, s3Dependencies }) {
5249
+ const storage = parseAttachmentStorageConfig(env);
5250
+ if (storage.kind === "filesystem") return void 0;
5251
+ const backend = createS3AttachmentBackend(db.withSchema("attachments"), storage.s3, s3Dependencies);
5252
+ if (!(await backend.health()).ready) throw new Error("S3 attachment backend readiness check failed");
5253
+ return backend;
5254
+ }
5255
+ //#endregion
5256
+ //#region src/services/attachment-access.service.ts
5257
+ const HASH_PATTERN = /^[a-f0-9]{64}$/;
5258
+ /**
5259
+ * Composes document authorization with the projected document/ref
5260
+ * relationship. Order is fixed: validate ref, resolve the canonical document
5261
+ * id, check `canRead`, then check the reference index. A denied document
5262
+ * never reaches the reference reader, and the facade never touches
5263
+ * attachment metadata, storage backends, or presigners.
5264
+ */
5265
+ var AttachmentAccessService = class {
5266
+ constructor(resolveCanonicalId, authorization, references, projection) {
5267
+ this.resolveCanonicalId = resolveCanonicalId;
5268
+ this.authorization = authorization;
5269
+ this.references = references;
5270
+ this.projection = projection;
5271
+ }
5272
+ async canReadAttachment(request) {
5273
+ if (this.projection.status !== "available") return { kind: "projection-unavailable" };
5274
+ const ref = normalizeAttachmentRef(request.attachmentRef);
5275
+ if (ref === null) return { kind: "denied" };
5276
+ let documentId;
5277
+ try {
5278
+ documentId = await this.resolveCanonicalId(request.documentId);
5279
+ } catch {
5280
+ return { kind: "denied" };
5281
+ }
5282
+ if (!await this.authorization.canRead(documentId, request.userAddress)) return { kind: "denied" };
5283
+ if (!await this.references.hasReference(documentId, ref)) return { kind: "denied" };
5284
+ return {
5285
+ kind: "allowed",
5286
+ documentId,
5287
+ ref
5288
+ };
5289
+ }
5290
+ };
5291
+ /**
5292
+ * Parses and canonicalizes a caller-supplied ref through the shared parser.
5293
+ * Returns null for anything that is not a v1 ref over a 64-char SHA-256 hex
5294
+ * hash; hex case is normalized so index lookups use the canonical form.
5295
+ */
5296
+ function normalizeAttachmentRef(value) {
5297
+ let hash;
5298
+ let version;
5299
+ try {
5300
+ const parsed = parseRef(value);
5301
+ hash = parsed.hash.toLowerCase();
5302
+ version = parsed.version;
5303
+ } catch {
5304
+ return null;
5305
+ }
5306
+ if (version !== 1 || !HASH_PATTERN.test(hash)) return null;
5307
+ return createRef(hash, version);
5308
+ }
5309
+ //#endregion
4698
5310
  //#region src/migrations/001_create_document_permissions.ts
4699
5311
  var _001_create_document_permissions_exports = /* @__PURE__ */ __exportAll({
4700
5312
  down: () => down$2,
@@ -4921,8 +5533,7 @@ var AuthService = class {
4921
5533
  admins: [],
4922
5534
  auth_enabled: false
4923
5535
  };
4924
- const method = request.method;
4925
- if (method === "OPTIONS" || method === "GET") return {
5536
+ if (request.method === "OPTIONS") return {
4926
5537
  user: void 0,
4927
5538
  admins: this.config.admins,
4928
5539
  auth_enabled: true
@@ -4984,16 +5595,23 @@ var AuthService = class {
4984
5595
  return await verifyAuthBearerToken(token);
4985
5596
  }
4986
5597
  /**
4987
- * Extract user information from verification result
5598
+ * Extract user information from verification result.
5599
+ *
5600
+ * The issuer is required along with the credential subject. A credential that
5601
+ * verified must carry one -- resolving it is how the signature was checked --
5602
+ * so this rejects a shape that cannot have come from verification rather than
5603
+ * admitting a keyless principal.
4988
5604
  */
4989
5605
  extractUserFromVerification(verified) {
4990
5606
  try {
4991
5607
  const { address, chainId, networkId } = verified.verifiableCredential.credentialSubject;
4992
- if (!address || !chainId || !networkId) return null;
5608
+ const appKey = verified.issuer;
5609
+ if (!address || !chainId || !networkId || !appKey) return null;
4993
5610
  return {
4994
5611
  address,
4995
5612
  chainId,
4996
- networkId
5613
+ networkId,
5614
+ appKey
4997
5615
  };
4998
5616
  } catch {
4999
5617
  return null;
@@ -5042,14 +5660,33 @@ var AuthService = class {
5042
5660
  }
5043
5661
  }
5044
5662
  async fetchCredentialExists(address, chainId, appId) {
5045
- return await fetchDelegationCredential({
5663
+ if (!this.config.verifyCredential) throw new Error("AuthService: credential verification is enabled but no verifyCredential was provided");
5664
+ return this.config.verifyCredential({
5046
5665
  address,
5047
5666
  chainId,
5048
- appDid: appId
5049
- }) !== void 0;
5667
+ appId
5668
+ });
5050
5669
  }
5051
5670
  };
5052
5671
  //#endregion
5672
+ //#region src/services/renown-credential-verifier.ts
5673
+ async function createRenownCredentialVerifier(config = {}) {
5674
+ const switchboardUrl = await resolveSwitchboardEndpoint({
5675
+ switchboardUrl: config.switchboardUrl,
5676
+ baseUrl: config.renownUrl
5677
+ });
5678
+ return async ({ address, chainId, appId }) => {
5679
+ return await fetchDelegationCredential({
5680
+ address,
5681
+ chainId,
5682
+ appDid: appId,
5683
+ switchboardUrl,
5684
+ baseUrl: switchboardUrl ? void 0 : config.renownUrl,
5685
+ discover: false
5686
+ }) !== void 0;
5687
+ };
5688
+ }
5689
+ //#endregion
5053
5690
  //#region src/services/document-permission.service.ts
5054
5691
  /**
5055
5692
  * Service for managing document-level permissions.
@@ -5365,7 +6002,35 @@ function createMcpRequestAuthorizer(authService, authorizationService) {
5365
6002
  };
5366
6003
  }
5367
6004
  //#endregion
6005
+ //#region src/services/renown-config.ts
6006
+ /** Reading credentials from this reactor's own read model needs a host-supplied
6007
+ * verifier: core has no idea which subgraph serves that read model. */
6008
+ function assertCredentialVerifierForSource(source, hasVerifier) {
6009
+ if (source !== "self" || hasVerifier) return;
6010
+ throw new Error("Renown credential verification is set to \"self\" (auth.renown.source or RENOWN_SOURCE) but no verifyCredential was provided. A host that reads its own read model must pass one — see apps/switchboard, which builds it from @renown/sdk createLocalCredentialVerifier — or set RENOWN_SOURCE=remote to verify against a Renown instance.");
6011
+ }
6012
+ function envOverride(value) {
6013
+ const trimmed = value?.trim();
6014
+ return trimmed ? trimmed : void 0;
6015
+ }
6016
+ /** Resolve `auth.renown`; RENOWN_SOURCE / RENOWN_URL / SWITCHBOARD_URL win
6017
+ * over the config file, which wins over the SDK defaults. */
6018
+ function resolveRenownConfig(configured, env, logger) {
6019
+ return {
6020
+ source: resolveRenownSource(envOverride(env.RENOWN_SOURCE) ?? configured?.source, logger),
6021
+ url: envOverride(env.RENOWN_URL) ?? configured?.url,
6022
+ switchboardUrl: envOverride(env.SWITCHBOARD_URL) ?? configured?.switchboardUrl
6023
+ };
6024
+ }
6025
+ function resolveRenownSource(value, logger) {
6026
+ if (value === void 0 || value === null) return "remote";
6027
+ if (value === "self" || value === "remote") return value;
6028
+ logger.warn(`Ignoring invalid renown source "${value}" (expected "self" or "remote") — using "remote"`);
6029
+ return "remote";
6030
+ }
6031
+ //#endregion
5368
6032
  //#region src/utils/db.ts
6033
+ const PGLITE_UTC_PARSERS = { 1114: (value) => /* @__PURE__ */ new Date(`${value.replace(" ", "T")}Z`) };
5369
6034
  function isPG(connectionString) {
5370
6035
  if (connectionString.startsWith("postgresql://") || connectionString.startsWith("postgres://")) return true;
5371
6036
  return false;
@@ -5396,7 +6061,10 @@ function getDbClient(connectionString = void 0, pgliteFactory) {
5396
6061
  if (cached) return cached;
5397
6062
  const isPg = connectionString && isPG(connectionString);
5398
6063
  const client = isPg ? "pg" : ClientPgLite;
5399
- const pgliteInstance = isPg ? void 0 : pgliteFactory ? pgliteFactory(connectionString) : connectionString ? new PGlite({ fs: new AtomicNodeFs(connectionString) }) : new PGlite();
6064
+ const pgliteInstance = isPg ? void 0 : pgliteFactory ? pgliteFactory(connectionString) : connectionString ? new PGlite({
6065
+ fs: new AtomicNodeFs(connectionString),
6066
+ parsers: PGLITE_UTC_PARSERS
6067
+ }) : new PGlite({ parsers: PGLITE_UTC_PARSERS });
5400
6068
  const connection = isPg ? { connectionString } : { pglite: pgliteInstance };
5401
6069
  if (connectionString && !isPg) {
5402
6070
  const dirPath = path.resolve(connectionString, "..");
@@ -5553,10 +6221,31 @@ function makeDbClosers(knexInstance, pglite) {
5553
6221
  return closers;
5554
6222
  }
5555
6223
  /**
6224
+ * The gate sync serving evaluates a document's own policy through, or undefined
6225
+ * when there is none to evaluate.
6226
+ *
6227
+ * It is built here rather than taken off the reactor client because it is not
6228
+ * the same gate reads use: it carries the host's closes-by-default setting,
6229
+ * which withholds the domain scopes of a document nobody has policied yet. That
6230
+ * answer belongs to serving alone -- replay must keep reading an uninitialized
6231
+ * document in full -- so the two gates are deliberately separate objects over
6232
+ * the same model.
6233
+ *
6234
+ * Undefined below `authEnforcement`, where the registered model ignores the auth
6235
+ * scope: gating through it would serve every domain scope of a policied document
6236
+ * to anyone, which is worse than not gating at all.
6237
+ */
6238
+ function buildSyncServingGate(reactorModule, authorizationConfig, logger) {
6239
+ if (!reactorModule) return;
6240
+ const model = readDecisionModel(reactorModule.featureFlags, reactorModule.documentModelRegistry);
6241
+ if (!model) return;
6242
+ return new SyncScopeGate(new ModelReadGate(model, reactorModule.documentView, reactorModule.featureFlags.authGroups, reactorModule.operationIndex, logger, { withholdUninitialized: authorizationConfig.defaultProtection }), reactorModule.documentView, logger);
6243
+ }
6244
+ /**
5556
6245
  * Sets up the subgraph manager and registers subgraphs
5557
6246
  */
5558
- async function setupGraphQLManager(httpAdapter, authFetchMiddleware, httpServer, wsServer, client, relationalDb, analyticsStore, syncManager, subgraphs, logger, authorizationService, authService, documentPermissionService, enableDocumentModelSubgraphs, port, reactorDriveClient) {
5559
- const graphqlManager = new GraphQLManager(config.basePath, httpServer, wsServer, client, relationalDb, analyticsStore, syncManager, logger, httpAdapter, await createGatewayAdapter("apollo", logger), authService, documentPermissionService, { enableDocumentModelSubgraphs }, port, authorizationService, reactorDriveClient);
6247
+ async function setupGraphQLManager(httpAdapter, authFetchMiddleware, httpServer, wsServer, client, relationalDb, analyticsStore, syncManager, subgraphs, logger, authorizationService, authService, documentPermissionService, enableDocumentModelSubgraphs, port, reactorDriveClient, syncServingGate) {
6248
+ const graphqlManager = new GraphQLManager(config.basePath, httpServer, wsServer, client, relationalDb, analyticsStore, syncManager, logger, httpAdapter, await createGatewayAdapter("apollo", logger), authService, documentPermissionService, { enableDocumentModelSubgraphs }, port, authorizationService, reactorDriveClient, syncServingGate);
5560
6249
  await graphqlManager.init(subgraphs.core, authFetchMiddleware);
5561
6250
  for (const [, collection] of subgraphs.extended.entries()) for (const subgraph of collection) await graphqlManager.registerSubgraph(subgraph, "graphql");
5562
6251
  await graphqlManager.updateRouter();
@@ -5568,15 +6257,20 @@ async function setupGraphQLManager(httpAdapter, authFetchMiddleware, httpServer,
5568
6257
  function setupEventListeners(pkgManager, graphqlManager, reactorProcessorManager, module, documentModelRegistry) {
5569
6258
  pkgManager.onDocumentModelsChange((packagedModels) => {
5570
6259
  if (documentModelRegistry) {
5571
- const newModules = Object.values(packagedModels).flat();
5572
- const registeredModules = documentModelRegistry.getAllModules();
5573
- const registeredTypes = new Set(registeredModules.map((m) => m.documentModel.global.id));
5574
- const modulesToRegister = newModules.filter((mod) => !registeredTypes.has(mod.documentModel.global.id));
5575
- if (modulesToRegister.length > 0) {
5576
- const results = documentModelRegistry.registerModules(...modulesToRegister);
5577
- for (const result of results) if (result.status === "success") defaultLogger.info(`Registered new document model: ${result.item.documentModel.global.id}`);
6260
+ const newModules = getUniqueDocumentModels(Object.values(packagedModels).flat());
6261
+ const incomingTypes = new Set(newModules.map((m) => m.documentModel.global.id));
6262
+ if (incomingTypes.size > 0) {
6263
+ documentModelRegistry.unregisterModules(...incomingTypes);
6264
+ const results = documentModelRegistry.registerModules(...newModules);
6265
+ for (const result of results) if (result.status === "success") defaultLogger.info(`Registered document model: ${result.item.documentModel.global.id} v${result.item.version ?? 1}`);
5578
6266
  else defaultLogger.error(`Failed to register document model: ${result.error.message}`);
5579
6267
  }
6268
+ const manifests = pkgManager.getUniqueUpgradeManifests();
6269
+ if (manifests.length > 0) {
6270
+ documentModelRegistry.unregisterUpgradeManifests(...manifests.map((m) => m.documentType));
6271
+ const manifestResults = documentModelRegistry.registerUpgradeManifests(...manifests);
6272
+ for (const result of manifestResults) if (result.status === "error") defaultLogger.error(`Failed to register upgrade manifest: ${result.error.message}`);
6273
+ }
5580
6274
  }
5581
6275
  graphqlManager.regenerateDocumentModelSubgraphs();
5582
6276
  });
@@ -5633,10 +6327,12 @@ async function _setupCommonInfrastructure(options) {
5633
6327
  const logger = options.logger ?? defaultLogger;
5634
6328
  let admins = [];
5635
6329
  let authEnabled = false;
6330
+ let configuredRenown;
5636
6331
  if (options.configFile) {
5637
6332
  const config = getConfig(options.configFile);
5638
6333
  admins = config.auth?.admins.map((a) => a.toLowerCase()) ?? [];
5639
6334
  authEnabled = config.auth?.enabled ?? false;
6335
+ configuredRenown = config.auth?.renown;
5640
6336
  } else if (options.auth) {
5641
6337
  admins = options.auth.admins.map((a) => a.toLowerCase());
5642
6338
  authEnabled = options.auth.enabled;
@@ -5673,11 +6369,19 @@ async function _setupCommonInfrastructure(options) {
5673
6369
  let authService;
5674
6370
  if (authEnabled) {
5675
6371
  logger.info("Setting up Auth middleware");
6372
+ const renown = options.renown ?? resolveRenownConfig(configuredRenown, process.env, logger);
6373
+ assertCredentialVerifierForSource(renown.source, options.verifyCredential !== void 0);
6374
+ if (options.verifyCredential) logger.info("Renown credentials will be verified by the host's verifier");
6375
+ else logger.info("Renown credentials will be verified against @url", renown.switchboardUrl ?? renown.url ?? "the default Renown instance");
5676
6376
  authService = new AuthService({
5677
6377
  enabled: authEnabled,
5678
6378
  admins,
5679
6379
  skipCredentialVerification,
5680
- credentialVerificationCacheTtlMs
6380
+ credentialVerificationCacheTtlMs,
6381
+ verifyCredential: options.verifyCredential ?? await createRenownCredentialVerifier({
6382
+ renownUrl: renown.url,
6383
+ switchboardUrl: renown.switchboardUrl
6384
+ })
5681
6385
  });
5682
6386
  authFetchMiddleware = createAuthFetchMiddleware(authService);
5683
6387
  }
@@ -5703,7 +6407,12 @@ async function _setupCommonInfrastructure(options) {
5703
6407
  await mkdir(attachmentStoragePath, { recursive: true });
5704
6408
  const { db: attachmentDb, knex: attachmentKnex, pglite: attachmentPglite } = getDbClient(options.dbPath, options.pgliteFactory);
5705
6409
  dbClosers.push(...makeDbClosers(attachmentKnex, attachmentPglite));
5706
- const attachments = await new AttachmentBuilder(attachmentDb, attachmentStoragePath).withReservationSweepMs(3600 * 1e3).build();
6410
+ const ATTACHMENT_SWEEP_INTERVAL_MS = 3600 * 1e3;
6411
+ const attachmentBackend = await createStartupAttachmentBackend({ db: attachmentDb });
6412
+ const attachmentBuilder = new AttachmentBuilder(attachmentDb, attachmentStoragePath).withReservationSweepMs(ATTACHMENT_SWEEP_INTERVAL_MS);
6413
+ if (attachmentBackend) attachmentBuilder.withBackend(attachmentBackend);
6414
+ const attachments = await attachmentBuilder.build();
6415
+ const attachmentReferenceIndex = await new AttachmentReferenceIndexBuilder(attachmentDb).build();
5707
6416
  dbClosers.push(() => {
5708
6417
  attachments.destroy();
5709
6418
  return Promise.resolve();
@@ -5723,6 +6432,7 @@ async function _setupCommonInfrastructure(options) {
5723
6432
  documentPermissionService,
5724
6433
  authorizationConfig,
5725
6434
  attachments,
6435
+ attachmentReferenceIndex,
5726
6436
  packages,
5727
6437
  dbClosers,
5728
6438
  readiness
@@ -5731,26 +6441,17 @@ async function _setupCommonInfrastructure(options) {
5731
6441
  /**
5732
6442
  * Private helper function containing common setup logic for API initialization
5733
6443
  */
5734
- async function _setupAPI(reactorClient, syncManager, reactorProcessorManager, httpAdapter, authFetchMiddleware, authService, port, packages, relationalDb, analyticsStore, documentPermissionService, processors, subgraphs, options, processorApp, readModels, attachments, authorizationConfig, documentModelRegistry, dbClosers = [], reactorDriveClient) {
6444
+ async function _setupAPI(reactorClient, syncManager, reactorProcessorManager, httpAdapter, authFetchMiddleware, authService, port, packages, relationalDb, analyticsStore, documentPermissionService, processors, subgraphs, options, processorApp, readModels, attachments, attachmentReferenceIndex, attachmentReferenceProjection, authorizationConfig, documentModelRegistry, dbClosers = [], reactorDriveClient, syncServingGate) {
5735
6445
  const hostModule = {
5736
- relationalDb,
5737
- analyticsStore,
5738
- processorApp,
5739
- config: options.processorConfig,
5740
- client: reactorClient,
5741
- attachments: createAttachmentClient(attachments.service),
5742
- dispatch: { async execute(docId, branch, actions, signal) {
5743
- const jobInfo = await reactorClient.executeAsync(docId, branch, actions, signal);
5744
- return {
5745
- id: jobInfo.id,
5746
- status: jobInfo.status
5747
- };
5748
- } },
5749
- getReadModel(name) {
5750
- const model = readModels.find((m) => m.name === name);
5751
- if (!model) throw new Error(`Read model "${name}" not found`);
5752
- return model;
5753
- }
6446
+ ...createReactorHostModuleBase({
6447
+ client: reactorClient,
6448
+ readModels,
6449
+ relationalDb,
6450
+ analyticsStore,
6451
+ processorApp,
6452
+ config: options.processorConfig
6453
+ }),
6454
+ attachments: createAttachmentClient(attachments.service)
5754
6455
  };
5755
6456
  const mcpServerEnabled = options.mcp ?? true;
5756
6457
  const logger = options.logger ?? defaultLogger;
@@ -5778,6 +6479,7 @@ async function _setupAPI(reactorClient, syncManager, reactorProcessorManager, ht
5778
6479
  const { httpServer, wsServer } = await startServer(httpAdapter, port, options.https, logger);
5779
6480
  const authorizationService = createAuthorizationService(authorizationConfig, documentPermissionService, createGetParentIdsFn(reactorClient));
5780
6481
  logger.info(`Authorization service initialized (policy: ${authorizationConfig.policy})`);
6482
+ const attachmentAccess = new AttachmentAccessService(createCanonicalDocumentIdResolver(reactorClient), authorizationService, attachmentReferenceIndex.store, attachmentReferenceProjection);
5781
6483
  const coreSubgraphs = DefaultCoreSubgraphs.slice();
5782
6484
  coreSubgraphs.push(ReactorSubgraph);
5783
6485
  if (documentPermissionService) {
@@ -5787,7 +6489,7 @@ async function _setupAPI(reactorClient, syncManager, reactorProcessorManager, ht
5787
6489
  const graphqlManager = await setupGraphQLManager(httpAdapter, authFetchMiddleware, httpServer, wsServer, reactorClient, relationalDb, analyticsStore, syncManager, {
5788
6490
  extended: subgraphs,
5789
6491
  core: coreSubgraphs
5790
- }, logger.child(["graphql-manager"]), authorizationService, authService, documentPermissionService, options.enableDocumentModelSubgraphs, port, reactorDriveClient);
6492
+ }, logger.child(["graphql-manager"]), authorizationService, authService, documentPermissionService, options.enableDocumentModelSubgraphs, port, reactorDriveClient, syncServingGate);
5791
6493
  setupEventListeners(packages, graphqlManager, reactorProcessorManager, hostModule, documentModelRegistry);
5792
6494
  if (mcpServerEnabled) {
5793
6495
  await setupMcpServer({
@@ -5802,6 +6504,8 @@ async function _setupAPI(reactorClient, syncManager, reactorProcessorManager, ht
5802
6504
  graphqlManager,
5803
6505
  packages,
5804
6506
  attachments,
6507
+ attachmentReferenceIndex,
6508
+ attachmentAccess,
5805
6509
  authService,
5806
6510
  dispose: buildApiDispose({
5807
6511
  graphqlManager,
@@ -5850,9 +6554,15 @@ function buildApiDispose(args) {
5850
6554
  };
5851
6555
  }
5852
6556
  async function initializeAndStartAPI(clientInitializer, options, processorApp) {
5853
- const { port, httpAdapter, authFetchMiddleware, authService, relationalDb, analyticsStore, documentPermissionService, authorizationConfig, attachments, packages, dbClosers, readiness } = await _setupCommonInfrastructure(options);
5854
- const { documentModels, processors, subgraphs } = await packages.init();
5855
- const { module: reactorClientModule, reactorDriveClient } = await clientInitializer(documentModels);
6557
+ const { port, httpAdapter, authFetchMiddleware, authService, relationalDb, analyticsStore, documentPermissionService, authorizationConfig, attachments, attachmentReferenceIndex, packages, dbClosers, readiness } = await _setupCommonInfrastructure(options);
6558
+ const { documentModels, upgradeManifests, processors, subgraphs } = await packages.init();
6559
+ const { module: reactorClientModule, reactorDriveClient, attachmentReferenceProjection = {
6560
+ status: "unavailable",
6561
+ reason: "initializer-did-not-report"
6562
+ } } = await clientInitializer(documentModels, {
6563
+ attachmentReferenceWriter: attachmentReferenceIndex.store,
6564
+ upgradeManifests
6565
+ });
5856
6566
  const reactorClient = reactorClientModule.client;
5857
6567
  const syncManager = reactorClientModule.reactorModule?.syncModule?.syncManager;
5858
6568
  if (!syncManager) throw new Error("SyncManager not available from InProcessReactorClientModule");
@@ -5861,11 +6571,12 @@ async function initializeAndStartAPI(clientInitializer, options, processorApp) {
5861
6571
  const documentModelRegistry = reactorClientModule.reactorModule?.documentModelRegistry;
5862
6572
  if (!documentModelRegistry) throw new Error("DocumentModelRegistry not available from InProcessReactorClientModule");
5863
6573
  return {
5864
- ...await _setupAPI(reactorClient, syncManager, reactorProcessorManager, httpAdapter, authFetchMiddleware, authService, port, packages, relationalDb, analyticsStore, documentPermissionService, processors, subgraphs, options, processorApp, (reactorClientModule.reactorModule?.readModelCoordinator)?.readModels ?? [], attachments, authorizationConfig, documentModelRegistry, dbClosers, reactorDriveClient),
6574
+ ...await _setupAPI(reactorClient, syncManager, reactorProcessorManager, httpAdapter, authFetchMiddleware, 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)),
5865
6575
  client: reactorClient,
5866
6576
  syncManager,
5867
6577
  documentModelRegistry,
5868
- readiness
6578
+ readiness,
6579
+ attachmentReferenceProjection
5869
6580
  };
5870
6581
  }
5871
6582
  //#endregion
@@ -5969,7 +6680,7 @@ var PackageManagementService = class {
5969
6680
  }
5970
6681
  };
5971
6682
  //#endregion
5972
- export { ADMIN_USERS, ActionContextInputSchema, ActionInputSchema, AddRelationshipDocument, AnalyticsSubgraph, AuthService, AuthSubgraph, AuthorizationPolicy, AuthorizedDocumentHandle, BaseSubgraph, ChannelMetaInputSchema, CreateDocumentDocument, CreateEmptyDocumentDocument, DeleteDocumentDocument, DeleteDocumentsDocument, DocumentChangeType, DocumentChangeTypeSchema, DocumentChangesDocument, DocumentOperationsFilterInputSchema, DocumentPermissionService, FindDocumentsDocument, GetDocumentDocument, GetDocumentIncomingRelationshipsDocument, GetDocumentModelsDocument, GetDocumentOperationsDocument, GetDocumentOutgoingRelationshipsDocument, GetDocumentWithOperationsDocument, GetJobStatusDocument, GraphQLManager, HttpDocumentModelLoader, HttpPackageLoader, ImportPackageLoader, InMemoryPackageStorage, JobChangesDocument, MoveRelationshipDocument, MutateDocumentAsyncDocument, MutateDocumentDocument, OperationContextInputSchema, OperationInputSchema, OperationWithContextInputSchema, OperationsFilterInputSchema, PackageManagementService, PackageManager, PackagesSubgraph, PagingInputSchema, PhDocumentFieldsFragmentDoc, PollSyncEnvelopesDocument, PropagationMode, PropagationModeSchema, PushSyncEnvelopesDocument, ReactorSignerAppInputSchema, ReactorSignerInputSchema, ReactorSignerUserInputSchema, ReactorSubgraph, RemoteCursorInputSchema, RemoteFilterInputSchema, RemoveRelationshipDocument, RenameDocumentDocument, SearchFilterInputSchema, SetPreferredEditorDocument, SyncEnvelopeInputSchema, SyncEnvelopeType, SyncEnvelopeTypeSchema, SystemSubgraph, TouchChannelDocument, TouchChannelInputSchema, ViewFilterInputSchema, assertAuthRequiredForDocumentPermissions, assertSkipCredentialVerificationAllowed, buildGraphQlDocument, buildGraphQlDriveDocument, buildGraphqlOperation, buildGraphqlOperations, buildSubgraphSchemaModule, createAuthFetchMiddleware, createGatewayAdapter, createHttpAdapter, createMergedSchema, createReactorGraphQLClient, createSchema, definedNonNullAnySchema, driveIdFromUrl, extractSubgraphsFromModule, generateDocumentModelSchema, getAuthContext, getDbClient, getDocumentModelSchemaName, getDocumentModelTypeDefs, getGitHash, getGitUrl, getSdk, getUniqueDocumentModels, getVersion, initAnalyticsStoreSql, initializeAndStartAPI, isDefinedNonNullAny, isExpectedLoaderMiss, isSubgraphClass, parseDriveUrl, renderGraphqlPlayground };
6683
+ export { ADMIN_USERS, ActionCandidateInputSchema, ActionContextInputSchema, ActionInputSchema, AddRelationshipDocument, AnalyticsSubgraph, AttachmentAccessService, AuthDecision, AuthDecisionSchema, AuthService, AuthSubgraph, AuthorizationPolicy, AuthorizedDocumentHandle, BaseSubgraph, CanonicalDocumentIdResolutionError, ChannelMetaInputSchema, CreateDocumentDocument, CreateEmptyDocumentDocument, DeleteDocumentDocument, DeleteDocumentsDocument, DocumentChangeType, DocumentChangeTypeSchema, DocumentChangesDocument, DocumentOperationsFilterInputSchema, DocumentPermissionService, EvaluateActionsDocument, FindDocumentsDocument, GetDocumentDocument, GetDocumentIncomingRelationshipsDocument, GetDocumentModelsDocument, GetDocumentOperationsDocument, GetDocumentOutgoingRelationshipsDocument, GetDocumentWithOperationsDocument, GetJobStatusDocument, GraphQLManager, HttpDocumentModelLoader, HttpPackageLoader, ImportPackageLoader, InMemoryPackageStorage, JobChangesDocument, MoveRelationshipDocument, MutateDocumentAsyncDocument, MutateDocumentDocument, OperationContextInputSchema, OperationInputSchema, OperationWithContextInputSchema, OperationsFilterInputSchema, PGLITE_UTC_PARSERS, PackageManagementService, PackageManager, PackagesSubgraph, PagingInputSchema, PhDocumentFieldsFragmentDoc, PollSyncEnvelopesDocument, PropagationMode, PropagationModeSchema, PushSyncEnvelopesDocument, ReactorSignerAppInputSchema, ReactorSignerInputSchema, ReactorSignerUserInputSchema, ReactorSubgraph, RemoteCursorInputSchema, RemoteFilterInputSchema, RemoveRelationshipDocument, RenameDocumentDocument, SearchFilterInputSchema, SetPreferredEditorDocument, SyncEnvelopeInputSchema, SyncEnvelopeType, SyncEnvelopeTypeSchema, SystemSubgraph, TouchChannelDocument, TouchChannelInputSchema, ViewFilterInputSchema, assertAuthRequiredForDocumentPermissions, assertCredentialVerifierForSource, assertSkipCredentialVerificationAllowed, buildGraphQlDocument, buildGraphQlDriveDocument, buildGraphqlOperation, buildGraphqlOperations, buildSubgraphSchemaModule, createAuthFetchMiddleware, createCanonicalDocumentIdResolver, createGatewayAdapter, createHttpAdapter, createMergedSchema, createReactorGraphQLClient, createRenownCredentialVerifier, createSchema, definedNonNullAnySchema, driveIdFromUrl, extractSubgraphsFromModule, generateDocumentModelSchema, getAuthContext, getDbClient, getDocumentModelSchemaName, getDocumentModelTypeDefs, getGitHash, getGitUrl, getSdk, getUniqueDocumentModels, getUniqueUpgradeManifests, getVersion, initAnalyticsStoreSql, initializeAndStartAPI, isDefinedNonNullAny, isExpectedLoaderMiss, isSubgraphClass, parseDriveUrl, renderGraphqlPlayground, resolveRenownConfig };
5973
6684
 
5974
6685
  //# sourceMappingURL=index.mjs.map
5975
- //# debugId=e58cea2c-2319-52a8-90cd-3e99d94ba98f
6686
+ //# debugId=42c7ea6f-655f-5a4b-84ac-b7870ee17334