@powerhousedao/reactor-api 6.2.3-dev.55 → 6.2.3-dev.57

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/dist/{adapter-gateway-apollo-D2DNlPY0.mjs → adapter-gateway-apollo-DTcAJpfN.mjs} +3 -3
  2. package/dist/{adapter-gateway-apollo-B54G_cXT.mjs → adapter-gateway-apollo-DwAmdCYz.mjs} +5 -5
  3. package/dist/{adapter-gateway-apollo-B54G_cXT.mjs.map → adapter-gateway-apollo-DwAmdCYz.mjs.map} +1 -1
  4. package/dist/adapter-gateway-stitching-969ZPot-.mjs +4 -0
  5. package/dist/{adapter-gateway-stitching-Dzv10u8D.mjs → adapter-gateway-stitching-ClVkjojb.mjs} +20 -8
  6. package/dist/adapter-gateway-stitching-ClVkjojb.mjs.map +1 -0
  7. package/dist/base-document-models-69WRTSfH.mjs +1243 -0
  8. package/dist/base-document-models-69WRTSfH.mjs.map +1 -0
  9. package/dist/create-schema-DLTPkNpK.d.mts +138 -0
  10. package/dist/create-schema-DLTPkNpK.d.mts.map +1 -0
  11. package/dist/index.d.mts +46 -99
  12. package/dist/index.d.mts.map +1 -1
  13. package/dist/index.mjs +526 -1180
  14. package/dist/index.mjs.map +1 -1
  15. package/dist/src/graphql/subgraph-types.d.mts +37 -0
  16. package/dist/src/graphql/subgraph-types.d.mts.map +1 -0
  17. package/dist/src/graphql/subgraph-types.mjs +105 -0
  18. package/dist/src/graphql/subgraph-types.mjs.map +1 -0
  19. package/dist/src/packages/vite-loader.d.mts +3 -2
  20. package/dist/src/packages/vite-loader.d.mts.map +1 -1
  21. package/dist/src/packages/vite-loader.mjs +20 -22
  22. package/dist/src/packages/vite-loader.mjs.map +1 -1
  23. package/dist/{subgraph-extraction-sQlZLLPH.mjs → subgraph-extraction-CPtTeQAT.mjs} +44 -10
  24. package/dist/subgraph-extraction-CPtTeQAT.mjs.map +1 -0
  25. package/dist/{types-DlTiz6AA.d.mts → types-D3pD6fvQ.d.mts} +15 -3
  26. package/dist/types-D3pD6fvQ.d.mts.map +1 -0
  27. package/package.json +18 -13
  28. package/dist/adapter-gateway-stitching-Dzv10u8D.mjs.map +0 -1
  29. package/dist/subgraph-extraction-sQlZLLPH.mjs.map +0 -1
  30. package/dist/types-DlTiz6AA.d.mts.map +0 -1
@@ -0,0 +1,1243 @@
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]="bd7672af-0ac4-5f07-901b-3577215a9c3f")}catch(e){}}();
3
+ import { gql } from "graphql-tag";
4
+ import { Kind, Lexer, Source, TokenKind, isTypeDefinitionNode, isTypeExtensionNode, parse, print, visit } from "graphql";
5
+ import { childLogger, documentModelDocumentModelModule } from "document-model";
6
+ import { createHash } from "node:crypto";
7
+ import { buildSubgraphSchema } from "@apollo/subgraph";
8
+ import { typeDefs } from "@powerhousedao/document-engineering/graphql";
9
+ import { camelCase, kebabCase, pascalCase } from "change-case";
10
+ import { GraphQLJSON, GraphQLJSONObject } from "graphql-type-json";
11
+ import { reactorDriveDocumentModelModule } from "@powerhousedao/reactor-drive";
12
+ import { ReactorGroupV1 } from "@powerhousedao/reactor-group";
13
+ import { driveDocumentModelModule } from "@powerhousedao/shared/document-drive";
14
+ //#region src/graphql/auth/schema.graphql
15
+ var schema_default$1 = "# Auth Subgraph Schema\n# Contains all document permission and authorization related types\n\nscalar DateTime\n\n# Permission levels for documents\nenum DocumentPermissionLevel {\n # Can fetch and read the document\n READ\n # Can push updates and modify the document\n WRITE\n # Can manage document permissions and settings\n ADMIN\n}\n\n# Document permission entry\ntype DocumentPermissionEntry {\n documentId: String!\n userAddress: String!\n permission: DocumentPermissionLevel!\n grantedBy: String!\n createdAt: DateTime!\n updatedAt: DateTime!\n}\n\n# Operation user permission entry\ntype OperationUserPermission {\n documentId: String!\n operationType: String!\n userAddress: String!\n grantedBy: String!\n createdAt: DateTime!\n}\n\n# Combined document access info\ntype DocumentAccessInfo {\n documentId: String!\n permissions: [DocumentPermissionEntry!]!\n}\n\n# Operation permissions info\ntype OperationPermissionsInfo {\n documentId: String!\n operationType: String!\n userPermissions: [OperationUserPermission!]!\n}\n\n# Document protection info\ntype DocumentProtectionInfo {\n documentId: String!\n protected: Boolean!\n ownerAddress: String\n}\n\ntype Query {\n # Get permissions for a document (requires ADMIN permission or global admin)\n documentAccess(\n documentIdOrSlug: String\n documentId: String @deprecated(reason: \"Use documentIdOrSlug.\")\n ): DocumentAccessInfo!\n\n # Get protection status for a document (requires ADMIN permission or global admin)\n documentProtection(\n documentIdOrSlug: String\n documentId: String @deprecated(reason: \"Use documentIdOrSlug.\")\n ): DocumentProtectionInfo!\n\n # Get all documents the current user has explicit access to\n userDocumentPermissions: [DocumentPermissionEntry!]!\n\n # Get operation permissions for a document and operation type\n # (requires ADMIN permission or global admin)\n operationPermissions(\n documentIdOrSlug: String\n documentId: String @deprecated(reason: \"Use documentIdOrSlug.\")\n operationType: String!\n ): OperationPermissionsInfo!\n\n # Check if the current user can execute a specific operation on a document\n canExecuteOperation(\n documentIdOrSlug: String\n documentId: String @deprecated(reason: \"Use documentIdOrSlug.\")\n operationType: String!\n ): Boolean!\n}\n\ntype Mutation {\n # Set document protection status (requires ADMIN permission or global admin)\n setDocumentProtection(\n documentIdOrSlug: String\n documentId: String @deprecated(reason: \"Use documentIdOrSlug.\")\n protected: Boolean!\n ): DocumentProtectionInfo!\n\n # Transfer document ownership (requires ADMIN permission or global admin)\n transferDocumentOwnership(\n documentIdOrSlug: String\n documentId: String @deprecated(reason: \"Use documentIdOrSlug.\")\n newOwnerAddress: String!\n ): DocumentProtectionInfo!\n\n # Grant a user permission on a document (requires ADMIN permission or global admin)\n grantDocumentPermission(\n documentIdOrSlug: String\n documentId: String @deprecated(reason: \"Use documentIdOrSlug.\")\n userAddress: String!\n permission: DocumentPermissionLevel!\n ): DocumentPermissionEntry!\n\n # Revoke a user's permission on a document (requires ADMIN permission or global admin)\n revokeDocumentPermission(\n documentIdOrSlug: String\n documentId: String @deprecated(reason: \"Use documentIdOrSlug.\")\n userAddress: String!\n ): Boolean!\n\n # --- Operation Permissions ---\n\n # Grant a user permission to execute an operation on a document\n grantOperationPermission(\n documentIdOrSlug: String\n documentId: String @deprecated(reason: \"Use documentIdOrSlug.\")\n operationType: String!\n userAddress: String!\n ): OperationUserPermission!\n\n # Revoke a user's permission to execute an operation\n revokeOperationPermission(\n documentIdOrSlug: String\n documentId: String @deprecated(reason: \"Use documentIdOrSlug.\")\n operationType: String!\n userAddress: String!\n ): Boolean!\n}\n";
16
+ //#endregion
17
+ //#region src/utils/create-schema.ts
18
+ const logger = childLogger(["reactor-api", "create-schema"]);
19
+ /**
20
+ * Revision type - matches the definition in reactor/schema.graphql.
21
+ * Used by PHDocument and document mutation results.
22
+ */
23
+ const RevisionType = `
24
+ type Revision {
25
+ scope: String!
26
+ revision: Int!
27
+ }
28
+ `;
29
+ /**
30
+ * A subgraph defines a type whose name the generated document-model schema
31
+ * owns, so one of the two definitions would be lost.
32
+ */
33
+ var SubgraphTypeCollisionError = class extends Error {
34
+ typeNames;
35
+ constructor(typeNames) {
36
+ super(`Subgraph defines types reserved by the document-model schema: ${typeNames.join(", ")}`);
37
+ this.name = "SubgraphTypeCollisionError";
38
+ this.typeNames = typeNames;
39
+ }
40
+ };
41
+ /**
42
+ * Type-system definition kinds that GraphQL requires to be uniquely named.
43
+ * A subgraph SDL with two definitions sharing a name fails federation
44
+ * composition ("There can be only one type named X"), which is fatal to the
45
+ * whole gateway. We dedupe these by name; field/operation/extension nodes are
46
+ * left untouched.
47
+ */
48
+ const TYPE_DEFINITION_KINDS = /* @__PURE__ */ new Set([
49
+ Kind.OBJECT_TYPE_DEFINITION,
50
+ Kind.ENUM_TYPE_DEFINITION,
51
+ Kind.INPUT_OBJECT_TYPE_DEFINITION,
52
+ Kind.INTERFACE_TYPE_DEFINITION,
53
+ Kind.UNION_TYPE_DEFINITION,
54
+ Kind.SCALAR_TYPE_DEFINITION
55
+ ]);
56
+ /**
57
+ * Drop duplicate type-system definitions by name, keeping the first occurrence.
58
+ * Deduping is by name across ALL kinds (a `type` and an `enum` sharing a name
59
+ * collide in GraphQL too), so the first definition of a given name wins
60
+ * regardless of kind. State types are emitted before operation types, so
61
+ * keep-first preserves the authoritative state definition. This heals a document
62
+ * model that defines the same name twice (global+local, state+operation, or
63
+ * twice in one scope) so the assembled subgraph SDL composes instead of crashing
64
+ * the gateway (Sentry #917).
65
+ */
66
+ const dedupeTypeDefinitions = (definitions, seen = /* @__PURE__ */ new Set()) => definitions.filter((def) => {
67
+ const name = typeDefinitionName(def);
68
+ if (name === void 0) return true;
69
+ if (seen.has(name)) {
70
+ logger.debug(`Dropping duplicate type definition: ${name}`);
71
+ return false;
72
+ }
73
+ seen.add(name);
74
+ return true;
75
+ });
76
+ function typeDefinitionName(def) {
77
+ if (!TYPE_DEFINITION_KINDS.has(def.kind)) return void 0;
78
+ return def.name?.value;
79
+ }
80
+ const EMPTY_DOCUMENT = {
81
+ kind: Kind.DOCUMENT,
82
+ definitions: []
83
+ };
84
+ const OUTPUT_TYPE_KINDS = [
85
+ Kind.OBJECT_TYPE_DEFINITION,
86
+ Kind.OBJECT_TYPE_EXTENSION,
87
+ Kind.ENUM_TYPE_DEFINITION,
88
+ Kind.ENUM_TYPE_EXTENSION,
89
+ Kind.UNION_TYPE_DEFINITION,
90
+ Kind.UNION_TYPE_EXTENSION,
91
+ Kind.INTERFACE_TYPE_DEFINITION,
92
+ Kind.INTERFACE_TYPE_EXTENSION
93
+ ];
94
+ const STATE_PREFIX_KINDS = new Set(OUTPUT_TYPE_KINDS);
95
+ const ALL_PREFIX_KINDS = /* @__PURE__ */ new Set([
96
+ ...OUTPUT_TYPE_KINDS,
97
+ Kind.INPUT_OBJECT_TYPE_DEFINITION,
98
+ Kind.INPUT_OBJECT_TYPE_EXTENSION
99
+ ]);
100
+ const TYPE_NAME_KINDS = /* @__PURE__ */ new Set([
101
+ ...ALL_PREFIX_KINDS,
102
+ Kind.SCALAR_TYPE_DEFINITION,
103
+ Kind.SCALAR_TYPE_EXTENSION,
104
+ Kind.NAMED_TYPE
105
+ ]);
106
+ const LOCAL_STATE_STUBS = /* @__PURE__ */ new Set([
107
+ "AccountSnapshotLocalState",
108
+ "BudgetStatementLocalState",
109
+ "ScopeFrameworkLocalState"
110
+ ]);
111
+ /** Parse SDL; blank or comment-only input yields an empty document. */
112
+ function parseSdl(sdl) {
113
+ const source = new Source(sdl);
114
+ if (new Lexer(source).advance().kind === TokenKind.EOF) return EMPTY_DOCUMENT;
115
+ try {
116
+ return parse(source, { noLocation: true });
117
+ } catch (error) {
118
+ const withoutSemicolons = sdl.replaceAll(";", "");
119
+ if (withoutSemicolons === sdl) throw error;
120
+ return parse(withoutSemicolons, { noLocation: true });
121
+ }
122
+ }
123
+ function definedTypeNames(doc, kinds) {
124
+ return doc.definitions.filter((def) => kinds.has(def.kind)).map((def) => def.name.value);
125
+ }
126
+ /** Prefix type definition names and type references found in `names`. */
127
+ function prefixTypeNames(doc, prefix, names) {
128
+ return visit(doc, { enter(node) {
129
+ if (!TYPE_NAME_KINDS.has(node.kind)) return void 0;
130
+ const { name } = node;
131
+ if (!names.has(name.value)) return void 0;
132
+ return {
133
+ ...node,
134
+ name: {
135
+ ...name,
136
+ value: `${prefix}_${name.value}`
137
+ }
138
+ };
139
+ } });
140
+ }
141
+ /** State schema definitions without inputs, `DateTime` or the given object types. */
142
+ function stateTypeDefinitions(sdl, droppedObjectTypes = /* @__PURE__ */ new Set()) {
143
+ return parseSdl(sdl).definitions.filter((def) => def.kind !== Kind.INPUT_OBJECT_TYPE_DEFINITION && def.kind !== Kind.INPUT_OBJECT_TYPE_EXTENSION && !(def.kind === Kind.SCALAR_TYPE_DEFINITION && def.name.value === "DateTime") && !(def.kind === Kind.OBJECT_TYPE_DEFINITION && droppedObjectTypes.has(def.name.value)));
144
+ }
145
+ /**
146
+ * Prefixed operation schemas per module. The first definition of each module
147
+ * carries a "Module: <Name>" description unless it has its own.
148
+ */
149
+ function buildModuleSchemas(specification, documentName, allTypeNames, hasValidSchema) {
150
+ const names = new Set(allTypeNames);
151
+ return specification?.modules.map((module) => {
152
+ const definitions = module.operations.filter((op) => hasValidSchema(op.schema)).flatMap((op) => {
153
+ const doc = parseSdl(op.schema ?? "");
154
+ return prefixTypeNames(doc, documentName, /* @__PURE__ */ new Set([...names, ...definedTypeNames(doc, ALL_PREFIX_KINDS)])).definitions;
155
+ });
156
+ if (definitions.length === 0) return "";
157
+ const [first, ...rest] = definitions;
158
+ const header = "description" in first && !first.description ? {
159
+ ...first,
160
+ description: {
161
+ kind: Kind.STRING,
162
+ value: `Module: ${pascalCase(module.name)}`,
163
+ block: true
164
+ }
165
+ } : first;
166
+ return print({
167
+ kind: Kind.DOCUMENT,
168
+ definitions: [header, ...rest]
169
+ });
170
+ }).filter(Boolean).join("\n") ?? "";
171
+ }
172
+ const buildSubgraphSchemaModule = (documentModels, resolvers, typeDefs, options = {}) => {
173
+ const newResolvers = {
174
+ ...resolvers,
175
+ JSONObject: GraphQLJSONObject,
176
+ Unknown: GraphQLJSON
177
+ };
178
+ return {
179
+ typeDefs: assembleSubgraphTypeDefs(options.generated ?? getGeneratedDocumentModelTypes(documentModels), typeDefs, options.ownTypeNames),
180
+ resolvers: newResolvers
181
+ };
182
+ };
183
+ const createSchema = (documentModels, resolvers, typeDefs, options = {}) => {
184
+ return buildSubgraphSchema([buildSubgraphSchemaModule(documentModels, resolvers, typeDefs, options)]);
185
+ };
186
+ /**
187
+ * Create a merged GraphQL schema from multiple subgraph modules.
188
+ * Uses buildSubgraphSchema's array overload to combine type definitions
189
+ * and resolvers from multiple subgraphs into a single executable schema.
190
+ */
191
+ const createMergedSchema = (modules) => {
192
+ return buildSubgraphSchema(modules);
193
+ };
194
+ function getDocumentModelSchemaName(documentModel) {
195
+ return pascalCase(documentModel.name.replaceAll("/", " "));
196
+ }
197
+ /** The name the model's own subgraph registers under. */
198
+ function getDocumentModelSubgraphName(documentModel) {
199
+ return kebabCase(documentModel.name);
200
+ }
201
+ /**
202
+ * The generated document-model types followed by the subgraph's own. Throws
203
+ * {@link SubgraphTypeCollisionError} when the subgraph defines a generated
204
+ * name not in `ownTypeNames`.
205
+ */
206
+ const getDocumentModelTypeDefs = (documentModels, typeDefs, ownTypeNames) => assembleSubgraphTypeDefs(getGeneratedDocumentModelTypes(documentModels), typeDefs, ownTypeNames);
207
+ /** Names of the type definitions in `doc`. */
208
+ function typeDefinitionNames(doc) {
209
+ return new Set(doc.definitions.map(typeDefinitionName).filter((name) => name !== void 0));
210
+ }
211
+ /** The definitions `documentModel` adds to the generated schema. */
212
+ function documentModelDefinitions(documentModel) {
213
+ const dmSchemaName = getDocumentModelSchemaName(documentModel);
214
+ const latestSpec = documentModel.specifications.at(-1);
215
+ const globalSchema = latestSpec?.state.global.schema ?? "";
216
+ const localSchema = latestSpec?.state.local.schema ?? "";
217
+ const definitions = [...stateTypeDefinitions(globalSchema), ...stateTypeDefinitions(localSchema, LOCAL_STATE_STUBS)];
218
+ const stateDoc = {
219
+ kind: Kind.DOCUMENT,
220
+ definitions
221
+ };
222
+ const prefixed = prefixTypeNames(stateDoc, dmSchemaName, new Set(definedTypeNames(stateDoc, STATE_PREFIX_KINDS)));
223
+ const documentType = parseSdl(`
224
+ type ${dmSchemaName} implements IDocument {
225
+ id: String!
226
+ name: String!
227
+ documentType: String!
228
+ operations(skip: Int, first: Int): [Operation!]!
229
+ revision: Int!
230
+ createdAtUtcIso: DateTime!
231
+ lastModifiedAtUtcIso: DateTime!
232
+ ${dmSchemaName !== "DocumentModel" ? `initialState: ${dmSchemaName}_${dmSchemaName}State!` : ""}
233
+ ${dmSchemaName !== "DocumentModel" ? `state: ${dmSchemaName}_${dmSchemaName}State!` : ""}
234
+ stateJSON: JSONObject
235
+ }`);
236
+ return [...prefixed.definitions, ...documentType.definitions];
237
+ }
238
+ function addScalarFlags(definitions, into) {
239
+ for (const def of definitions) {
240
+ const name = typeDefinitionName(def);
241
+ if (name === void 0) continue;
242
+ const scalar = def.kind === Kind.SCALAR_TYPE_DEFINITION;
243
+ into.set(name, scalar && (into.get(name) ?? true));
244
+ }
245
+ return into;
246
+ }
247
+ let fixedGeneratedTypes;
248
+ /**
249
+ * Type names no document model may generate: the root types, the generated
250
+ * types every schema carries, and the types of `coreTypeDefs`.
251
+ */
252
+ function reservedTypeNames(coreTypeDefs) {
253
+ fixedGeneratedTypes ??= addScalarFlags(getGeneratedDocumentModelTypes([]).definitions, /* @__PURE__ */ new Map());
254
+ const reserved = new Map([
255
+ ["Query", false],
256
+ ["Mutation", false],
257
+ ["Subscription", false],
258
+ ...fixedGeneratedTypes
259
+ ]);
260
+ for (const typeDefs of coreTypeDefs) addScalarFlags(typeDefs.definitions, reserved);
261
+ return reserved;
262
+ }
263
+ /**
264
+ * The reserved names `documentModel`'s generated types take. A scalar may
265
+ * repeat a reserved scalar: the duplicate is dropped on assembly.
266
+ */
267
+ function reservedTypeNamesTaken(documentModel, reserved, definitions = documentModelDefinitions(documentModel.documentModel.global)) {
268
+ const generated = addScalarFlags(definitions, /* @__PURE__ */ new Map());
269
+ return Array.from(generated).filter(([name, scalar]) => reserved.has(name) && !(scalar && reserved.get(name))).map(([name]) => name);
270
+ }
271
+ const GENERATED_HEAD = gql`
272
+ scalar JSONObject
273
+ scalar AttachmentRef
274
+ # Codegen scalars not in the document-engineering set.
275
+ scalar Unknown
276
+ scalar Address
277
+ ${typeDefs.join("\n").replaceAll(";", "")}
278
+
279
+ type PHOperationContext {
280
+ signer: Signer
281
+ }
282
+
283
+ type Signer {
284
+ user: SignerUser
285
+ app: SignerApp
286
+ signatures: [String!]!
287
+ }
288
+
289
+ type SignerUser {
290
+ address: String!
291
+ networkId: String!
292
+ chainId: Int!
293
+ }
294
+
295
+ type SignerApp {
296
+ name: String!
297
+ key: String!
298
+ }
299
+
300
+ type Operation {
301
+ id: String!
302
+ type: String!
303
+ index: Int!
304
+ timestampUtcMs: DateTime!
305
+ hash: String!
306
+ skip: Int
307
+ inputText: String
308
+ error: String
309
+ context: PHOperationContext
310
+ }
311
+
312
+ interface IDocument {
313
+ id: String!
314
+ name: String!
315
+ documentType: String!
316
+ revision: Int!
317
+ createdAtUtcIso: DateTime!
318
+ lastModifiedAtUtcIso: DateTime!
319
+ operations(first: Int, skip: Int): [Operation!]!
320
+ stateJSON: JSONObject
321
+ }
322
+ `.definitions;
323
+ const GENERATED_TAIL = gql`
324
+ type GqlDocument implements IDocument {
325
+ id: String!
326
+ name: String!
327
+ documentType: String!
328
+ revision: Int!
329
+ createdAtUtcIso: DateTime!
330
+ lastModifiedAtUtcIso: DateTime!
331
+ operations(first: Int, skip: Int): [Operation!]!
332
+ stateJSON: JSONObject
333
+ }
334
+
335
+ type DriveDocument implements IDocument {
336
+ id: String!
337
+ name: String!
338
+ documentType: String!
339
+ revision: Int!
340
+ createdAtUtcIso: DateTime!
341
+ lastModifiedAtUtcIso: DateTime!
342
+ operations(first: Int, skip: Int): [Operation!]!
343
+ stateJSON: JSONObject
344
+ }
345
+ `.definitions;
346
+ /**
347
+ * The generated schema for `documentModels`. `schemas` supplies models'
348
+ * definitions already built; the others are built here.
349
+ */
350
+ function getGeneratedDocumentModelTypes(documentModels, schemas) {
351
+ return generatedTypesFrom(documentModels.map((model) => ({
352
+ global: model.documentModel.global,
353
+ generated: schemas?.get(model)?.generated
354
+ })));
355
+ }
356
+ /** {@link getGeneratedDocumentModelTypes} from the models' global states. */
357
+ function generatedTypesOf(documentModels) {
358
+ return generatedTypesFrom(documentModels.map((global) => ({ global })));
359
+ }
360
+ function generatedTypesFrom(documentModels) {
361
+ const modelDefinitions = [];
362
+ const addedDocumentModels = /* @__PURE__ */ new Set();
363
+ documentModels.forEach(({ global, generated }) => {
364
+ const dmSchemaName = getDocumentModelSchemaName(global);
365
+ if (addedDocumentModels.has(dmSchemaName)) {
366
+ logger.debug(`Skipping document model with duplicate name: ${dmSchemaName}`);
367
+ return;
368
+ }
369
+ addedDocumentModels.add(dmSchemaName);
370
+ modelDefinitions.push(...generated ?? documentModelDefinitions(global));
371
+ });
372
+ const definitions = dedupeTypeDefinitions([
373
+ ...GENERATED_HEAD,
374
+ ...modelDefinitions,
375
+ ...GENERATED_TAIL
376
+ ]);
377
+ return {
378
+ definitions,
379
+ names: new Set(definitions.map(typeDefinitionName).filter((name) => name !== void 0))
380
+ };
381
+ }
382
+ const hasValidSchema = (schema) => !!(schema && /\b(input|type|enum|union|interface)\s+\w+/.test(schema));
383
+ /** Whether any operation of the latest specification has a schema. */
384
+ function hasOperationSchemas(documentModel) {
385
+ const specification = documentModel.specifications.at(-1);
386
+ if (!specification) return false;
387
+ return specification.modules.some((module) => module.operations.some((op) => hasValidSchema(op.schema)));
388
+ }
389
+ /** The types of a document model's own subgraph. */
390
+ function documentModelSubgraphTypes(documentModel) {
391
+ const typeDefs = generateDocumentModelSchema(documentModel, { useNewApi: true });
392
+ return {
393
+ typeDefs,
394
+ typeNames: typeDefinitionNames(typeDefs)
395
+ };
396
+ }
397
+ const toError = (error) => error instanceof Error ? error : new Error(String(error));
398
+ /** Build `subgraph` over the generated types of `documentModel` alone. */
399
+ function checkBuilds(documentModel, generated, subgraph) {
400
+ buildSubgraphSchema([{ typeDefs: assembleSubgraphTypeDefs(getGeneratedDocumentModelTypes([documentModel], /* @__PURE__ */ new Map([[documentModel, { generated }]])), subgraph?.typeDefs ?? EMPTY_DOCUMENT, subgraph?.typeNames) }]);
401
+ }
402
+ /** Throws when the generated types every subgraph carries do not build. */
403
+ function buildDocumentModelSchema(documentModel, options = {}) {
404
+ const generated = documentModelDefinitions(documentModel.documentModel.global);
405
+ if (options.subgraph === false || !hasOperationSchemas(documentModel.documentModel.global)) {
406
+ checkBuilds(documentModel, generated);
407
+ return { generated };
408
+ }
409
+ try {
410
+ const subgraph = documentModelSubgraphTypes(documentModel.documentModel.global);
411
+ checkBuilds(documentModel, generated, subgraph);
412
+ return {
413
+ generated,
414
+ subgraph
415
+ };
416
+ } catch (error) {
417
+ checkBuilds(documentModel, generated);
418
+ return {
419
+ generated,
420
+ subgraphError: toError(error)
421
+ };
422
+ }
423
+ }
424
+ /** Hash of everything {@link buildDocumentModelSchema} reads. */
425
+ function schemaSourceKey(documentModel) {
426
+ const { name, specifications } = documentModel.documentModel.global;
427
+ return createHash("sha256").update(JSON.stringify([name, specifications.at(-1)])).digest("base64");
428
+ }
429
+ /** Schemas and failures by source hash, for the last resolve's models only. */
430
+ var DocumentModelSchemaCache = class {
431
+ #entries = /* @__PURE__ */ new Map();
432
+ #build;
433
+ constructor(build = buildDocumentModelSchema) {
434
+ this.#build = build;
435
+ }
436
+ resolve(documentModels) {
437
+ const entries = /* @__PURE__ */ new Map();
438
+ const resolved = documentModels.map((model) => {
439
+ let key;
440
+ let entry;
441
+ try {
442
+ key = schemaSourceKey(model);
443
+ entry = entries.get(key) ?? this.#entries.get(key);
444
+ } catch (error) {
445
+ key = `unkeyed:${model.documentModel.global.id}`;
446
+ entry = toError(error);
447
+ }
448
+ if (entry === void 0) try {
449
+ entry = this.#build(model);
450
+ } catch (error) {
451
+ entry = toError(error);
452
+ }
453
+ entries.set(key, entry);
454
+ return entry instanceof Error ? {
455
+ model,
456
+ key,
457
+ error: entry
458
+ } : {
459
+ model,
460
+ key,
461
+ schema: entry
462
+ };
463
+ });
464
+ this.#entries = entries;
465
+ return resolved;
466
+ }
467
+ };
468
+ /**
469
+ * Names of the generated types `typeDefs` redefines, other than those a
470
+ * model's own subgraph may repeat. Scalars are dropped on assembly, so they
471
+ * never collide.
472
+ */
473
+ function findSubgraphTypeCollisions(generated, typeDefs, ownTypeNames) {
474
+ const collisions = [];
475
+ for (const def of typeDefs.definitions) {
476
+ if (def.kind === Kind.SCALAR_TYPE_DEFINITION) continue;
477
+ const name = typeDefinitionName(def);
478
+ if (name === void 0 || !generated.names.has(name)) continue;
479
+ if (ownTypeNames?.has(name)) continue;
480
+ collisions.push(name);
481
+ }
482
+ return collisions;
483
+ }
484
+ /** Throws {@link SubgraphTypeCollisionError}; see {@link getDocumentModelTypeDefs}. */
485
+ function assembleSubgraphTypeDefs(generated, typeDefs, ownTypeNames) {
486
+ const collisions = findSubgraphTypeCollisions(generated, typeDefs, ownTypeNames);
487
+ if (collisions.length > 0) throw new SubgraphTypeCollisionError(collisions);
488
+ const subgraphDefinitions = typeDefs.definitions.filter((def) => def.kind !== Kind.SCALAR_TYPE_DEFINITION);
489
+ return {
490
+ kind: Kind.DOCUMENT,
491
+ definitions: [...generated.definitions, ...dedupeTypeDefinitions(subgraphDefinitions, new Set(generated.names))]
492
+ };
493
+ }
494
+ /**
495
+ * Extract the names of types defined in a GraphQL schema.
496
+ * Unparseable schemas yield no names.
497
+ */
498
+ function extractTypeNames(schema) {
499
+ try {
500
+ return definedTypeNames(parseSdl(schema), ALL_PREFIX_KINDS);
501
+ } catch (error) {
502
+ logger.debug(`Skipping unparseable schema: ${String(error)}`);
503
+ return [];
504
+ }
505
+ }
506
+ /**
507
+ * Print the input type definitions of a GraphQL schema.
508
+ * @param excludeTypeNames - Input type names to leave out
509
+ */
510
+ function extractInputTypeDefinitions(schema, excludeTypeNames = /* @__PURE__ */ new Set()) {
511
+ const definitions = parseSdl(schema).definitions.filter((def) => def.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION && !excludeTypeNames.has(def.name.value));
512
+ if (definitions.length === 0) return "";
513
+ return print({
514
+ kind: Kind.DOCUMENT,
515
+ definitions
516
+ });
517
+ }
518
+ /**
519
+ * Extract the root state type name from a scope's GraphQL schema.
520
+ * Uses the naming convention: {DocumentName}State for global,
521
+ * {DocumentName}{PascalScope}State for other scopes (e.g., DocumentDriveLocalState).
522
+ * Falls back to the last ObjectTypeDefinition (root types are conventionally last).
523
+ */
524
+ function extractRootTypeName(schema, documentName, scopeName) {
525
+ try {
526
+ const ast = parse(schema);
527
+ const candidates = [`${documentName}${scopeName === "global" ? "" : pascalCase(scopeName)}State`, `${documentName}${pascalCase(scopeName)}State`];
528
+ let lastObjectType = null;
529
+ for (const def of ast.definitions) if (def.kind === Kind.OBJECT_TYPE_DEFINITION) {
530
+ if (candidates.includes(def.name.value)) return def.name.value;
531
+ lastObjectType = def.name.value;
532
+ }
533
+ return lastObjectType;
534
+ } catch {}
535
+ return null;
536
+ }
537
+ /**
538
+ * Convert a GraphQL output type AST node to an optional input type string.
539
+ * Strips non-null markers and converts object type references to Input suffix.
540
+ */
541
+ function convertTypeNodeToInput(typeNode, objectNames, unionNames, interfaceNames) {
542
+ if (typeNode.kind === Kind.NON_NULL_TYPE && typeNode.type) return convertTypeNodeToInput(typeNode.type, objectNames, unionNames, interfaceNames);
543
+ if (typeNode.kind === Kind.LIST_TYPE && typeNode.type) return `[${convertTypeNodeToInput(typeNode.type, objectNames, unionNames, interfaceNames)}]`;
544
+ if (typeNode.kind === Kind.NAMED_TYPE && typeNode.name) {
545
+ const name = typeNode.name.value;
546
+ if (objectNames.has(name)) return `${name}Input`;
547
+ if (unionNames.has(name) || interfaceNames.has(name)) return "JSONObject";
548
+ return name;
549
+ }
550
+ return "JSONObject";
551
+ }
552
+ /**
553
+ * Generate GraphQL input type definitions from a state schema string.
554
+ * Converts output type definitions to input types with all fields optional.
555
+ * - Object type references get Input suffix
556
+ * - Union/interface references become JSONObject
557
+ * - Enums and scalars remain unchanged
558
+ */
559
+ function generateStateInputTypes(stateSchema, excludeTypeNames) {
560
+ if (!stateSchema || !stateSchema.trim()) return "";
561
+ let ast;
562
+ try {
563
+ ast = parse(stateSchema);
564
+ } catch {
565
+ return "";
566
+ }
567
+ const enumNames = /* @__PURE__ */ new Set();
568
+ const unionNames = /* @__PURE__ */ new Set();
569
+ const interfaceNames = /* @__PURE__ */ new Set();
570
+ const objectNames = /* @__PURE__ */ new Set();
571
+ const existingInputNames = /* @__PURE__ */ new Set();
572
+ for (const def of ast.definitions) switch (def.kind) {
573
+ case Kind.ENUM_TYPE_DEFINITION:
574
+ enumNames.add(def.name.value);
575
+ break;
576
+ case Kind.UNION_TYPE_DEFINITION:
577
+ unionNames.add(def.name.value);
578
+ break;
579
+ case Kind.INTERFACE_TYPE_DEFINITION:
580
+ interfaceNames.add(def.name.value);
581
+ break;
582
+ case Kind.OBJECT_TYPE_DEFINITION:
583
+ objectNames.add(def.name.value);
584
+ break;
585
+ case Kind.INPUT_OBJECT_TYPE_DEFINITION: existingInputNames.add(def.name.value);
586
+ }
587
+ const inputTypes = [];
588
+ for (const def of ast.definitions) {
589
+ if (def.kind !== Kind.OBJECT_TYPE_DEFINITION) continue;
590
+ const inputName = `${def.name.value}Input`;
591
+ if (existingInputNames.has(inputName)) continue;
592
+ if (excludeTypeNames?.has(inputName)) continue;
593
+ const fields = def.fields ?? [];
594
+ if (fields.length === 0) continue;
595
+ const inputFields = fields.map((field) => {
596
+ return ` ${field.name.value}: ${convertTypeNodeToInput(field.type, objectNames, unionNames, interfaceNames)}`;
597
+ });
598
+ inputTypes.push(`input ${def.name.value}Input {\n${inputFields.join("\n")}\n}`);
599
+ }
600
+ return inputTypes.join("\n\n");
601
+ }
602
+ /**
603
+ * Apply type prefixes to GraphQL schema to namespace types and avoid collisions.
604
+ * Inlined from @powerhousedao/common/utils to avoid ES module import issues.
605
+ * @param {string} schema - GraphQL schema string
606
+ * @param {string} prefix - Prefix to apply to type names
607
+ * @param {string[]} externalTypeNames - Type names from other schemas to also prefix
608
+ * @returns {string} Schema with prefixed types
609
+ */
610
+ function applyGraphQLTypePrefixes(schema, prefix, externalTypeNames = []) {
611
+ if (!schema || !schema.trim()) return schema;
612
+ const doc = parseSdl(schema);
613
+ const names = /* @__PURE__ */ new Set([...definedTypeNames(doc, ALL_PREFIX_KINDS), ...externalTypeNames]);
614
+ if (names.size === 0) return schema;
615
+ return print(prefixTypeNames(doc, prefix, names));
616
+ }
617
+ /**
618
+ * Generate a GraphQL schema for a document model.
619
+ *
620
+ * @param documentModel - The document model global state
621
+ * @param options - Schema generation options
622
+ * @returns GraphQL DocumentNode
623
+ */
624
+ function generateDocumentModelSchema(documentModel, options = {}) {
625
+ const { useNewApi = false } = options;
626
+ const specification = documentModel.specifications.at(-1);
627
+ const documentName = getDocumentModelSchemaName(documentModel);
628
+ const globalStateSchema = specification?.state.global.schema;
629
+ const localStateSchema = specification?.state.local.schema;
630
+ const globalStateTypeNames = extractTypeNames(globalStateSchema ?? "");
631
+ const localStateTypeNames = extractTypeNames(localStateSchema ?? "");
632
+ const stateTypeNames = [...globalStateTypeNames, ...localStateTypeNames];
633
+ const allOperationTypeNames = specification?.modules.flatMap((module) => module.operations.flatMap((op) => extractTypeNames(op.schema ?? ""))) ?? [];
634
+ const allTypeNames = [.../* @__PURE__ */ new Set([...stateTypeNames, ...allOperationTypeNames])];
635
+ const operationInputTypeNames = new Set(allOperationTypeNames);
636
+ const prefixedStateInputTypes = applyGraphQLTypePrefixes(extractInputTypeDefinitions(globalStateSchema ?? "", operationInputTypeNames), documentName, allTypeNames);
637
+ if (useNewApi) return generateNewApiSchema(documentName, specification, prefixedStateInputTypes, allTypeNames, hasValidSchema);
638
+ return generateLegacyApiSchema(documentName, specification, prefixedStateInputTypes, allTypeNames, hasValidSchema);
639
+ }
640
+ /**
641
+ * Generate legacy API schema with nested queries
642
+ */
643
+ function generateLegacyApiSchema(documentName, specification, prefixedStateInputTypes, allTypeNames, hasValidSchema) {
644
+ const createDocumentMutation = `${documentName}_createDocument(name:String!, driveId:String): String`;
645
+ const operationMutations = specification?.modules.flatMap((module) => module.operations.filter((op) => op.name && hasValidSchema(op.schema)).map((op) => `${documentName}_${camelCase(op.name)}(
646
+ driveId: String, docId: PHID, input: ${documentName}_${pascalCase(op.name)}Input): Int`)).join("\n ") ?? "";
647
+ const moduleSchemas = buildModuleSchemas(specification, documentName, allTypeNames, hasValidSchema);
648
+ return gql`
649
+ """
650
+ Queries: ${documentName} Document
651
+ """
652
+
653
+ type ${documentName}Queries {
654
+ getDocument(docId: PHID!, driveId: PHID): ${documentName}
655
+ getDocuments(driveId: String!): [${documentName}!]
656
+ }
657
+
658
+ type Query {
659
+ ${documentName}: ${documentName}Queries
660
+ }
661
+
662
+ """
663
+ Mutations: ${documentName}
664
+ """
665
+ type Mutation {
666
+ ${createDocumentMutation}
667
+
668
+ ${operationMutations}
669
+ }
670
+
671
+ ${prefixedStateInputTypes ? `"""
672
+ Input Types from State Schema
673
+ """
674
+ ${prefixedStateInputTypes}` : ""}
675
+
676
+ ${moduleSchemas}`;
677
+ }
678
+ /**
679
+ * Generate new API schema with flat queries, typed state, and async mutations.
680
+ * Note: State schema types are NOT included here because they are already defined
681
+ * in getDocumentModelTypeDefs() which is used during schema composition.
682
+ * Including them here would cause duplicate type definitions.
683
+ */
684
+ function generateNewApiSchema(documentName, specification, prefixedStateInputTypes, allTypeNames, hasValidSchema) {
685
+ const stateType = `${documentName}_FullState!`;
686
+ const sharedBaseTypes = `
687
+ """Hash configuration for document state"""
688
+ type ${documentName}_PHHashConfig {
689
+ algorithm: String!
690
+ encoding: String!
691
+ }
692
+
693
+ """Document scope state (same for all document types)"""
694
+ type ${documentName}_PHDocumentScopeState {
695
+ version: Int!
696
+ hash: ${documentName}_PHHashConfig!
697
+ isDeleted: Boolean
698
+ deletedAtUtcIso: String
699
+ deletedBy: String
700
+ deletionReason: String
701
+ }
702
+ `;
703
+ const hasLocalStateType = (specification?.state.local.schema ?? "").includes(`type ${documentName}LocalState`);
704
+ const fullStateType = `
705
+ """Full state with all scopes for ${documentName}"""
706
+ type ${documentName}_FullState {
707
+ auth: JSONObject!
708
+ document: ${documentName}_PHDocumentScopeState!
709
+ global: ${documentName === "DocumentModel" ? `${documentName}_${documentName}GlobalState!` : `${documentName}_${documentName}State!`}
710
+ local: ${!hasLocalStateType ? "JSONObject!" : `${documentName}_${documentName}LocalState!`}
711
+ }
712
+ `;
713
+ const commonInputTypes = `
714
+ input ${documentName}_ViewFilterInput {
715
+ branch: String
716
+ scopes: [String!]
717
+ }
718
+
719
+ input ${documentName}_PagingInput {
720
+ limit: Int
721
+ offset: Int
722
+ cursor: String
723
+ }
724
+
725
+ input ${documentName}_SearchFilterInput {
726
+ parentId: String
727
+ identifiers: [String!] @deprecated(reason: "Ignored. Filter by parentId.")
728
+ }
729
+ `;
730
+ const revisionType = RevisionType;
731
+ const resultTypes = `
732
+ """
733
+ Mutation result type for ${documentName} operations with typed state.
734
+ Matches ReactorSubgraph PHDocument pattern with revisionsList.
735
+ """
736
+ type ${documentName}MutationResult {
737
+ id: String!
738
+ slug: String
739
+ preferredEditor: String
740
+ name: String!
741
+ documentType: String!
742
+ state: ${stateType}
743
+ revisionsList: [Revision!]!
744
+ createdAtUtcIso: DateTime!
745
+ lastModifiedAtUtcIso: DateTime!
746
+ }
747
+
748
+ """
749
+ Document with children for ${documentName}
750
+ """
751
+ type ${documentName}_DocumentWithChildren {
752
+ document: ${documentName}MutationResult!
753
+ childIds: [String!]!
754
+ }
755
+
756
+ """
757
+ Paginated result type for ${documentName} documents
758
+ """
759
+ type ${documentName}_DocumentResultPage {
760
+ items: [${documentName}MutationResult!]!
761
+ hasNextPage: Boolean!
762
+ hasPreviousPage: Boolean!
763
+ cursor: String
764
+ }
765
+ `;
766
+ const queries = `
767
+ type ${documentName}Queries {
768
+ """Get a specific ${documentName} document by identifier"""
769
+ document(idOrSlug: String, identifier: String @deprecated(reason: "Use idOrSlug."), view: ${documentName}_ViewFilterInput): ${documentName}_DocumentWithChildren
770
+
771
+ """Get all ${documentName} documents (paged)"""
772
+ documents(paging: ${documentName}_PagingInput): ${documentName}_DocumentResultPage!
773
+
774
+ """Find ${documentName} documents by search criteria"""
775
+ findDocuments(search: ${documentName}_SearchFilterInput, view: ${documentName}_ViewFilterInput, paging: ${documentName}_PagingInput): ${documentName}_DocumentResultPage!
776
+
777
+ """Get outgoing relationships of a ${documentName} document"""
778
+ documentOutgoingRelationships(sourceIdOrSlug: String, sourceIdentifier: String @deprecated(reason: "Use sourceIdOrSlug."), relationshipType: String!, view: ${documentName}_ViewFilterInput, paging: ${documentName}_PagingInput): ${documentName}_DocumentResultPage!
779
+
780
+ """Get incoming relationships to a ${documentName} document"""
781
+ documentIncomingRelationships(targetIdOrSlug: String, targetIdentifier: String @deprecated(reason: "Use targetIdOrSlug."), relationshipType: String!, view: ${documentName}_ViewFilterInput, paging: ${documentName}_PagingInput): ${documentName}_DocumentResultPage!
782
+ }
783
+ `;
784
+ let initialStateInputSchema = "";
785
+ if (specification) {
786
+ const scopeFields = [];
787
+ const generatedInputTypeParts = [];
788
+ for (const [scopeName, scopeState] of Object.entries(specification.state)) {
789
+ const schema = scopeState.schema ?? "";
790
+ if (hasValidSchema(schema)) {
791
+ const rootTypeName = extractRootTypeName(schema, documentName, scopeName);
792
+ if (!rootTypeName) {
793
+ scopeFields.push(` ${scopeName}: JSONObject`);
794
+ continue;
795
+ }
796
+ const scopeInputTypes = generateStateInputTypes(schema, new Set(allTypeNames));
797
+ if (!scopeInputTypes) {
798
+ scopeFields.push(` ${scopeName}: JSONObject`);
799
+ continue;
800
+ }
801
+ const prefixedScopeInputTypes = applyGraphQLTypePrefixes(scopeInputTypes, documentName, allTypeNames);
802
+ scopeFields.push(` ${scopeName}: ${documentName}_${rootTypeName}Input`);
803
+ generatedInputTypeParts.push(prefixedScopeInputTypes);
804
+ } else scopeFields.push(` ${scopeName}: JSONObject`);
805
+ }
806
+ if (scopeFields.length > 0) {
807
+ const inputTypeDefs = generatedInputTypeParts.join("\n\n");
808
+ const wrapper = `input ${documentName}_InitialStateInput {\n${scopeFields.join("\n")}\n}`;
809
+ initialStateInputSchema = inputTypeDefs ? `${inputTypeDefs}\n\n${wrapper}` : wrapper;
810
+ }
811
+ }
812
+ const createDocumentMutation = initialStateInputSchema ? `createDocument(name: String!, parentIdOrSlug: String, parentIdentifier: String @deprecated(reason: "Use parentIdOrSlug."), slug: String, preferredEditor: String, initialState: ${documentName}_InitialStateInput): ${documentName}MutationResult!` : `createDocument(name: String!, parentIdOrSlug: String, parentIdentifier: String @deprecated(reason: "Use parentIdOrSlug."), preferredEditor: String): ${documentName}MutationResult!`;
813
+ const createEmptyDocumentMutation = `createEmptyDocument(parentIdOrSlug: String, parentIdentifier: String @deprecated(reason: "Use parentIdOrSlug.")): ${documentName}MutationResult!`;
814
+ const operationMutations = specification?.modules.flatMap((module) => module.operations.filter((op) => op.name && hasValidSchema(op.schema)).flatMap((op) => [`${camelCase(op.name)}(documentIdOrSlug: String, docId: PHID @deprecated(reason: "Use documentIdOrSlug."), input: ${documentName}_${pascalCase(op.name)}Input!): ${documentName}MutationResult!`, `${camelCase(op.name)}Async(documentIdOrSlug: String, docId: PHID @deprecated(reason: "Use documentIdOrSlug."), input: ${documentName}_${pascalCase(op.name)}Input!): String!`])).join("\n ") ?? "";
815
+ const moduleSchemas = buildModuleSchemas(specification, documentName, allTypeNames, hasValidSchema);
816
+ return gql`
817
+ scalar DateTime
818
+ scalar JSONObject
819
+ scalar AttachmentRef
820
+
821
+ ${revisionType}
822
+
823
+ ${sharedBaseTypes}
824
+
825
+ ${fullStateType}
826
+
827
+ ${commonInputTypes}
828
+
829
+ ${resultTypes}
830
+
831
+ """
832
+ Queries: ${documentName} Document
833
+ """
834
+ ${queries}
835
+
836
+ """
837
+ Mutations: ${documentName}
838
+ """
839
+ type ${documentName}Mutations {
840
+ ${createDocumentMutation}
841
+ ${createEmptyDocumentMutation}
842
+
843
+ ${operationMutations}
844
+ }
845
+
846
+ type Query {
847
+ ${documentName}: ${documentName}Queries!
848
+ }
849
+
850
+ type Mutation {
851
+ ${documentName}: ${documentName}Mutations!
852
+ }
853
+
854
+ ${prefixedStateInputTypes ? `"""
855
+ Input Types from State Schema
856
+ """
857
+ ${prefixedStateInputTypes}` : ""}
858
+
859
+ ${initialStateInputSchema ? `"""
860
+ Input Types for Initial State
861
+ """
862
+ ${initialStateInputSchema}` : ""}
863
+
864
+ ${moduleSchemas}`;
865
+ }
866
+ //#endregion
867
+ //#region src/graphql/subgraph-type-ownership.ts
868
+ const ROOT_TYPE_NAMES = /* @__PURE__ */ new Set([
869
+ "Query",
870
+ "Mutation",
871
+ "Subscription"
872
+ ]);
873
+ const byName = (nodes) => nodes && [...nodes].sort((a, b) => a.name.value < b.name.value ? -1 : a.name.value > b.name.value ? 1 : 0);
874
+ /** Printed without descriptions, with named members in name order. */
875
+ function normalizeDefinition(node) {
876
+ const normalized = visit(node, { leave(current) {
877
+ const copy = { ...current };
878
+ delete copy.loc;
879
+ if ("description" in copy) copy.description = void 0;
880
+ if (current.kind === Kind.STRING) copy.block = false;
881
+ for (const key of [
882
+ "fields",
883
+ "arguments",
884
+ "interfaces"
885
+ ]) if (Array.isArray(copy[key])) copy[key] = byName(copy[key]);
886
+ if (current.kind === Kind.ENUM_TYPE_DEFINITION || current.kind === Kind.ENUM_TYPE_EXTENSION) copy.values = byName(current.values);
887
+ if (current.kind === Kind.UNION_TYPE_DEFINITION || current.kind === Kind.UNION_TYPE_EXTENSION) copy.types = byName(current.types);
888
+ return copy;
889
+ } });
890
+ return print(normalized);
891
+ }
892
+ function isScalar(def) {
893
+ return def.kind === Kind.SCALAR_TYPE_DEFINITION || def.kind === Kind.SCALAR_TYPE_EXTENSION;
894
+ }
895
+ /** Type and root-field claims, without scalars or generated types. */
896
+ function collectSubgraphClaims(typeDefs, generatedNames) {
897
+ const types = /* @__PURE__ */ new Map();
898
+ const claims = /* @__PURE__ */ new Map();
899
+ for (const def of typeDefs.definitions) {
900
+ if (!isTypeDefinitionNode(def) && !isTypeExtensionNode(def)) continue;
901
+ if (isScalar(def)) continue;
902
+ const node = def;
903
+ const name = node.name.value;
904
+ if (ROOT_TYPE_NAMES.has(name)) {
905
+ if (!("fields" in node)) continue;
906
+ for (const field of node.fields ?? []) {
907
+ const key = `${name}.${field.name.value}`;
908
+ const definition = normalizeDefinition(field);
909
+ const previous = claims.get(key);
910
+ claims.set(key, previous === void 0 ? definition : `${previous}\n${definition}`);
911
+ }
912
+ continue;
913
+ }
914
+ if (isTypeDefinitionNode(node) && generatedNames.has(name)) continue;
915
+ const nodes = types.get(name) ?? [];
916
+ nodes.push(node);
917
+ types.set(name, nodes);
918
+ }
919
+ for (const [name, nodes] of types) {
920
+ const merged = mergeTypeNodes(nodes);
921
+ claims.set(name, merged ? normalizeDefinition(merged) : nodes.map(normalizeDefinition).sort().join("\n"));
922
+ }
923
+ return claims;
924
+ }
925
+ const EXTENSION_KINDS = {
926
+ [Kind.OBJECT_TYPE_DEFINITION]: Kind.OBJECT_TYPE_EXTENSION,
927
+ [Kind.INTERFACE_TYPE_DEFINITION]: Kind.INTERFACE_TYPE_EXTENSION,
928
+ [Kind.UNION_TYPE_DEFINITION]: Kind.UNION_TYPE_EXTENSION,
929
+ [Kind.ENUM_TYPE_DEFINITION]: Kind.ENUM_TYPE_EXTENSION,
930
+ [Kind.INPUT_OBJECT_TYPE_DEFINITION]: Kind.INPUT_OBJECT_TYPE_EXTENSION
931
+ };
932
+ /** One definition plus its same-kind extensions, as a single definition. */
933
+ function mergeTypeNodes(nodes) {
934
+ if (nodes.length === 1) return nodes[0];
935
+ const definitions = nodes.filter(isTypeDefinitionNode);
936
+ if (definitions.length !== 1) return void 0;
937
+ const [definition] = definitions;
938
+ const extensionKind = EXTENSION_KINDS[definition.kind];
939
+ const merged = { ...definition };
940
+ for (const node of nodes) {
941
+ if (node === definition) continue;
942
+ if (node.kind !== extensionKind) return void 0;
943
+ const members = node;
944
+ for (const key of [
945
+ "fields",
946
+ "interfaces",
947
+ "values",
948
+ "types",
949
+ "directives"
950
+ ]) {
951
+ const extra = members[key];
952
+ if (extra) merged[key] = [...merged[key] ?? [], ...extra];
953
+ }
954
+ }
955
+ return merged;
956
+ }
957
+ function isRootFieldClaim(claim) {
958
+ return claim.includes(".");
959
+ }
960
+ /** Candidates, in priority order, that lose a claim to an earlier one. */
961
+ function resolveClaimOwnership(candidates) {
962
+ const owners = /* @__PURE__ */ new Map();
963
+ const excluded = /* @__PURE__ */ new Map();
964
+ for (const { candidate, name, claims } of candidates) {
965
+ const conflicts = [];
966
+ for (const [claim, definition] of claims) {
967
+ const owned = owners.get(claim);
968
+ if (owned && (isRootFieldClaim(claim) || owned.definition !== definition)) conflicts.push({
969
+ claim,
970
+ owner: owned.owner
971
+ });
972
+ }
973
+ if (conflicts.length > 0) {
974
+ excluded.set(candidate, conflicts);
975
+ continue;
976
+ }
977
+ for (const [claim, definition] of claims) if (!owners.has(claim)) owners.set(claim, {
978
+ definition,
979
+ owner: name
980
+ });
981
+ }
982
+ return excluded;
983
+ }
984
+ function describeOwnershipConflicts(conflicts) {
985
+ return `claims owned by another subgraph: ${conflicts.map(({ claim, owner }) => `${claim} (owned by "${owner}")`).join(", ")}`;
986
+ }
987
+ //#endregion
988
+ //#region src/graphql/inspection/schema.ts
989
+ const inspectionTypeDefs = gql`
990
+ type ReactorStorageFacts {
991
+ engine: String!
992
+ persistence: String!
993
+ durable: Boolean!
994
+ selfHeal: Boolean!
995
+ }
996
+
997
+ type InspectorAccess {
998
+ admin: Boolean!
999
+ sql: Boolean!
1000
+ }
1001
+
1002
+ """
1003
+ What this reactor reports about itself. access is null unless the caller is
1004
+ one of the host's admins.
1005
+ """
1006
+ type ReactorInfo {
1007
+ storage: ReactorStorageFacts!
1008
+ workflows: Boolean!
1009
+ syncChannels: [String!]!
1010
+ access: InspectorAccess
1011
+ }
1012
+
1013
+ type InspectionDocumentModel {
1014
+ documentType: String!
1015
+ name: String!
1016
+ version: Int!
1017
+ supportedVersions: [Int!]!
1018
+ }
1019
+
1020
+ type InspectionDrive {
1021
+ driveId: String!
1022
+ name: String!
1023
+ branch: String!
1024
+ collectionId: String!
1025
+ documentType: String!
1026
+ nodeCount: Int!
1027
+ fileCount: Int!
1028
+ folderCount: Int!
1029
+ otherNodeCount: Int!
1030
+ unreadableNodeCount: Int!
1031
+ icon: String
1032
+ }
1033
+
1034
+ type InspectionDrivePage {
1035
+ results: [InspectionDrive!]!
1036
+ nextCursor: String
1037
+ }
1038
+
1039
+ type InspectionDriveIntegrityRef {
1040
+ id: String!
1041
+ documentType: String!
1042
+ }
1043
+
1044
+ type InspectionDriveIntegrity {
1045
+ driveId: String!
1046
+ checkedNodeCount: Int!
1047
+ totalFileNodeCount: Int!
1048
+ """
1049
+ File nodes whose document is missing or not served to you; the two are
1050
+ reported alike so a withheld document's existence does not leak.
1051
+ """
1052
+ missingDocuments: [InspectionDriveIntegrityRef!]!
1053
+ unsupportedTypes: [InspectionDriveIntegrityRef!]!
1054
+ }
1055
+
1056
+ type InspectionAttachmentInfo {
1057
+ present: Boolean!
1058
+ storeKind: String!
1059
+ hasReplicator: Boolean!
1060
+ replicatorRunning: Boolean!
1061
+ backlogScanned: Boolean!
1062
+ refsSeen: Int!
1063
+ held: Int!
1064
+ bytesHeld: Float!
1065
+ queued: Int!
1066
+ fetching: Int!
1067
+ pendingFetches: Int!
1068
+ waiting: Int!
1069
+ notFound: Int!
1070
+ failed: Int!
1071
+ lastError: String
1072
+ }
1073
+
1074
+ """
1075
+ A queued job without its actions or operations.
1076
+ """
1077
+ type InspectionQueueJob {
1078
+ id: String!
1079
+ kind: String!
1080
+ documentId: String!
1081
+ scope: String!
1082
+ branch: String!
1083
+ status: String!
1084
+ actionCount: Int!
1085
+ operationCount: Int!
1086
+ retryCount: Int!
1087
+ }
1088
+
1089
+ type InspectionQueueState {
1090
+ isPaused: Boolean!
1091
+ totalPending: Int!
1092
+ totalExecuting: Int!
1093
+ pendingJobs: [InspectionQueueJob!]!
1094
+ executingJobs: [InspectionQueueJob!]!
1095
+ }
1096
+
1097
+ type InspectionProcessor {
1098
+ processorId: String!
1099
+ factoryId: String!
1100
+ driveId: String!
1101
+ processorIndex: Int!
1102
+ lastOrdinal: Float!
1103
+ status: String!
1104
+ lastError: String
1105
+ lastErrorTimestampUtcMs: Float
1106
+ }
1107
+
1108
+ """
1109
+ healthy means something only when tracked; an untracked store reports false.
1110
+ """
1111
+ type InspectionStorageHealth {
1112
+ tracked: Boolean!
1113
+ healthy: Boolean!
1114
+ everRecreated: Boolean!
1115
+ recreateCount: Int!
1116
+ }
1117
+
1118
+ """
1119
+ Issues in scopes the caller may not read are left out.
1120
+ """
1121
+ type InspectionValidation {
1122
+ documentId: String!
1123
+ isConsistent: Boolean!
1124
+ keyframeIssues: [JSONObject!]!
1125
+ snapshotIssues: [JSONObject!]!
1126
+ streamOrderIssues: [JSONObject!]!
1127
+ }
1128
+
1129
+ type InspectionCursor {
1130
+ cursorType: String!
1131
+ cursorOrdinal: Float!
1132
+ lastSyncedAtUtcMs: Float
1133
+ liveAckOrdinal: Float!
1134
+ liveLatestOrdinal: Float!
1135
+ }
1136
+
1137
+ type InspectionMailboxDepths {
1138
+ inbox: Int!
1139
+ outbox: Int!
1140
+ deadLetter: Int!
1141
+ }
1142
+
1143
+ type InspectionConnectionHealth {
1144
+ snapshot: JSONObject!
1145
+ neverSucceeded: Boolean!
1146
+ stalenessMs: Float
1147
+ }
1148
+
1149
+ type InspectionRemote {
1150
+ remoteName: String!
1151
+ remoteId: String!
1152
+ inboxCursor: InspectionCursor!
1153
+ outboxCursor: InspectionCursor!
1154
+ mailboxDepths: InspectionMailboxDepths!
1155
+ connection: InspectionConnectionHealth!
1156
+ meta: JSONObject!
1157
+ }
1158
+
1159
+ """
1160
+ A dead letter without its operations.
1161
+ """
1162
+ type InspectionDeadLetter {
1163
+ id: String!
1164
+ jobId: String!
1165
+ documentId: String!
1166
+ branch: String!
1167
+ scopes: [String!]!
1168
+ errorType: String!
1169
+ errorMessage: String!
1170
+ operationCount: Int!
1171
+ }
1172
+
1173
+ type InspectionDeadLetterPage {
1174
+ remoteName: String!
1175
+ results: [InspectionDeadLetter!]!
1176
+ nextCursor: String
1177
+ }
1178
+
1179
+ """
1180
+ Reads only. info and documentModels serve every caller; drive and document
1181
+ reads are made as the caller through the reactor read gate; the rest need
1182
+ one of the host's admins.
1183
+ """
1184
+ type ReactorInspection {
1185
+ info: ReactorInfo!
1186
+ documentModels: [InspectionDocumentModel!]!
1187
+ drives(cursor: String, limit: Int): InspectionDrivePage!
1188
+ """
1189
+ Reads every file node's document. Throttled per caller.
1190
+ """
1191
+ driveIntegrity(driveId: String!, branch: String!): InspectionDriveIntegrity!
1192
+ attachmentInfo: InspectionAttachmentInfo!
1193
+ queueState: InspectionQueueState!
1194
+ processors: [InspectionProcessor!]!
1195
+ catchUpStatus: JSONObject!
1196
+ storageHealth: InspectionStorageHealth!
1197
+ """
1198
+ Replays the whole document; expensive. Throttled per caller.
1199
+ """
1200
+ validateDocument(documentId: String!, branch: String): InspectionValidation!
1201
+ remotes: [InspectionRemote!]!
1202
+ remote(remoteName: String!): InspectionRemote!
1203
+ deadLetters(
1204
+ remoteName: String!
1205
+ cursor: String
1206
+ limit: Int
1207
+ ): InspectionDeadLetterPage!
1208
+ }
1209
+
1210
+ type Query {
1211
+ inspection: ReactorInspection!
1212
+ }
1213
+ `;
1214
+ //#endregion
1215
+ //#region src/graphql/reactor/schema.graphql
1216
+ var schema_default = "# Scalar types (for codegen - also defined in create-schema.ts)\nscalar JSONObject\nscalar DateTime\n\n# Input types\ninput PagingInput {\n limit: Int\n offset: Int\n cursor: String\n}\n\ninput ViewFilterInput {\n branch: String\n scopes: [String!]\n}\n\ninput SearchFilterInput {\n type: String\n parentId: String\n identifiers: [String!]\n @deprecated(reason: \"Ignored. Filter by type or parentId.\")\n}\n\ninput OperationsFilterInput {\n documentIdOrSlug: String\n documentId: String @deprecated(reason: \"Use documentIdOrSlug.\")\n branch: String\n scopes: [String!]\n actionTypes: [String!]\n sinceRevision: Int\n timestampFrom: String\n timestampTo: String\n}\n\ninput DocumentOperationsFilterInput {\n branch: String\n scopes: [String!]\n actionTypes: [String!]\n sinceRevision: Int\n timestampFrom: String\n timestampTo: String\n}\n\n# Enums\nenum PropagationMode {\n CASCADE\n ORPHAN\n}\n\nenum DocumentChangeType {\n CREATED\n DELETED\n UPDATED\n PARENT_ADDED\n PARENT_REMOVED\n CHILD_ADDED\n CHILD_REMOVED\n}\n\n# Object types\ntype DocumentModelGlobalState {\n id: String!\n name: String!\n namespace: String\n version: String\n specification: JSONObject!\n}\n\ntype DocumentModelResultPage {\n items: [DocumentModelGlobalState!]!\n hasNextPage: Boolean!\n hasPreviousPage: Boolean!\n cursor: String\n}\n\ntype Revision {\n scope: String!\n revision: Int!\n}\n\ntype PHDocument {\n id: String!\n slug: String\n preferredEditor: String\n meta: JSONObject\n protocolVersions: JSONObject\n name: String!\n documentType: String!\n state: JSONObject!\n revisionsList: [Revision!]!\n createdAtUtcIso: DateTime!\n lastModifiedAtUtcIso: DateTime!\n operations(\n filter: DocumentOperationsFilterInput\n paging: PagingInput\n ): ReactorOperationResultPage\n}\n\ntype PHDocumentResultPage {\n items: [PHDocument!]!\n hasNextPage: Boolean!\n hasPreviousPage: Boolean!\n cursor: String\n}\n\n# A directed edge between two documents, with the metadata recorded against it.\ntype DocumentRelationship {\n sourceId: String!\n targetId: String!\n relationshipType: String!\n metadata: JSONObject\n createdAt: DateTime!\n updatedAt: DateTime!\n}\n\ntype DocumentRelationshipResultPage {\n items: [DocumentRelationship!]!\n hasNextPage: Boolean!\n hasPreviousPage: Boolean!\n cursor: String\n}\n\ntype ReactorOperationResultPage {\n items: [ReactorOperation!]!\n hasNextPage: Boolean!\n hasPreviousPage: Boolean!\n cursor: String\n}\n\ntype DeadLetterInfo {\n documentId: String!\n error: String!\n \"\"\"\n How the origin classified the failure. A peer needs this to mirror the origin's\n quarantine decision; without it a held auth operation would freeze the document\n on the peer side while the origin kept syncing.\n \"\"\"\n errorType: String\n jobId: String!\n branch: String!\n scopes: [String!]!\n operationCount: Int!\n}\n\ntype PollSyncEnvelopesResult {\n envelopes: [SyncEnvelope!]!\n ackOrdinal: Int!\n deadLetters: [DeadLetterInfo!]!\n hasMore: Boolean!\n # The server's current manifest revision\n manifestRevision: String\n # The client's manifest revision as the server holds it\n peerManifestRevision: String\n}\n\ntype SyncHoldReason {\n protocol: String!\n version: Int!\n peerSupports: [Int!]!\n}\n\n# A document held back from a remote whose peer cannot run its versions\ntype SyncHold {\n remoteName: String!\n documentId: String!\n branch: String!\n reason: SyncHoldReason!\n heldAtUtcMs: String!\n}\n\ntype PeerAgreementMember {\n remoteName: String!\n # False for a peer that announced nothing: it gets the baselines\n announced: Boolean!\n protocols: JSONObject!\n features: JSONObject!\n}\n\ntype PeerAgreementLimit {\n protocol: String!\n # The remotes whose peers lack the version new documents would take\n remoteNames: [String!]!\n}\n\ntype PeerAgreement {\n collectionId: String!\n local: JSONObject!\n members: [PeerAgreementMember!]!\n limitedBy: [PeerAgreementLimit!]!\n}\n\ntype DocumentWithChildren {\n document: PHDocument!\n childIds: [String!]!\n}\n\n# What a new document gets when its creator chooses nothing\ntype CreateDefaults {\n # \"legacy\" or \"v2-required\"; a client refuses a value it does not know\n signaturePolicy: String!\n protocolVersions: JSONObject!\n}\n\ntype MoveRelationshipResult {\n source: PHDocument!\n target: PHDocument!\n}\n\ntype ConsistencyCoordinate {\n documentId: String!\n scope: String!\n branch: String!\n operationIndex: Int!\n}\n\n\"\"\"\nThe write positions a job reached, for read-after-write. Only meaningful once\nthe job has completed.\n\"\"\"\ntype ConsistencyToken {\n version: Int!\n createdAtUtcIso: String!\n coordinates: [ConsistencyCoordinate!]!\n}\n\n\"The batch a job was submitted in.\"\ntype JobBatchMeta {\n batchId: String!\n batchJobIds: [String!]!\n}\n\ntype JobInfo {\n id: String!\n\n \"\"\"\n The document the job operates on. Empty for a job this server does not know,\n which then comes back FAILED with \"Job not found\".\n \"\"\"\n documentId: String!\n status: String!\n\n \"\"\"\n What the job produced, once it has produced anything. Null until then, which\n is the state every job is in when it is handed back from a submission.\n \"\"\"\n result: JSONObject\n\n error: String\n\n \"The error's class name, such as `DocumentAlreadyExistsError`, when it failed.\"\n errorName: String\n createdAt: DateTime!\n completedAt: DateTime\n consistencyToken: ConsistencyToken!\n meta: JobBatchMeta!\n}\n\n\"\"\"\nOne job's outcome within a batch, pairing the plan key the caller gave with the\njob that applied it. Mirrors one entry of the `Record<string, JobInfo>` that\n`IReactor.executeBatch` returns (packages/reactor/src/core/types.ts).\n\"\"\"\ntype BatchJobResult {\n key: String!\n job: JobInfo!\n}\n\n\"\"\"\nThe outcome of a batch mutation, one entry per job the request named. The wire\nshape of `BatchExecutionResult` (`{ jobs }`), keyed on each entry by the plan\nkey rather than by position so the client can rebuild the record. The batch is\nnot atomic: each job commits on its own and a failed job releases its\ndependents, so each entry's status says what happened to that job, and\nre-submitting re-applies the jobs that succeeded.\n\"\"\"\ntype BatchExecutionResult {\n jobs: [BatchJobResult!]!\n}\n\ntype DocumentChangeEvent {\n type: DocumentChangeType!\n documents: [PHDocument!]!\n context: DocumentChangeContext\n}\n\ntype DocumentChangeContext {\n parentId: String\n childId: String\n}\n\ntype JobChangeEvent {\n jobId: String!\n status: String!\n\n \"\"\"\n What the job produced, once it has produced anything. Nullable for the same\n reason as `JobInfo.result`: a job that has not written yet has produced\n nothing, and an empty object would claim otherwise.\n \"\"\"\n result: JSONObject\n\n error: String\n}\n\ntype ReactorSignerUser {\n address: String!\n networkId: String!\n chainId: Int!\n}\n\ntype ReactorSignerApp {\n name: String!\n key: String!\n}\n\ntype ReactorSigner {\n user: ReactorSignerUser\n app: ReactorSignerApp\n signatures: [String!]!\n}\n\ntype ActionContext {\n signer: ReactorSigner\n}\n\ntype Action {\n id: String!\n type: String!\n timestampUtcMs: String!\n input: JSONObject!\n scope: String!\n context: ActionContext\n}\n\n\"\"\"\nOne operation an authorization preflight predicts a verdict for.\n\n`input` is what a conditional grant reads, so a candidate standing for a\nfilled-in form carries that form's input. Omitting it predicts the verdict an\nempty input earns, not the verdict the filled-in form will get.\n\"\"\"\ninput ActionCandidateInput {\n scope: String!\n type: String!\n input: JSONObject\n}\n\nenum AuthDecision {\n ALLOW\n DENY\n}\n\n\"\"\"\nOne candidate's predicted verdict. `reason` carries the refusal a DENY is\nrecorded with, and is null on an ALLOW.\n\"\"\"\ntype ActionEvaluation {\n decision: AuthDecision!\n reason: String\n}\n\n\"\"\"\nThe predicted verdicts for a set of candidates, in the order they were given,\nwith the aggregates a caller branches on.\n\nThe aggregates are redundant -- a verdict is binary -- and all four are returned\nso a caller reads the one its question is phrased in rather than negating\nanother. Over no candidates every aggregate is false: nothing is allowed and\nnothing is denied.\n\"\"\"\ntype ActionEvaluations {\n evaluations: [ActionEvaluation!]!\n allAllowed: Boolean!\n anyAllowed: Boolean!\n allDenied: Boolean!\n anyDenied: Boolean!\n}\n\n# Input types for sync operations\n\"\"\"\nAn action's context, as a caller submits it.\n\nDeclares every field `ActionContext` carries, because an input object rejects a\nfield it does not declare: an action stamped with the head it applies to - which\nis what a signing client sends - is refused outright if these are missing, and\nthat refusal is a whole-request one, not a per-field one.\n\n`prevOpHash` and `prevOpIndex` are the scope head the action was composed\nagainst. They are recorded rather than enforced; a signature is verified from\nthe params carried in its own tuple, which do not include them.\n\"\"\"\ninput ActionContextInput {\n \"\"\"\n The index of the last operation in the scope the action applies to.\n \"\"\"\n prevOpIndex: Int\n\n \"\"\"\n The hash of the state the action applies to.\n \"\"\"\n prevOpHash: String\n\n \"\"\"\n Covers replay of an operation that would otherwise be a no-op.\n \"\"\"\n nonce: String\n\n signer: ReactorSignerInput\n}\n\ninput ReactorSignerInput {\n user: ReactorSignerUserInput\n app: ReactorSignerAppInput\n signatures: [String!]!\n}\n\ninput ReactorSignerUserInput {\n address: String!\n networkId: String!\n chainId: Int!\n}\n\ninput ReactorSignerAppInput {\n name: String!\n key: String!\n}\n\ninput ActionInput {\n id: String!\n type: String!\n timestampUtcMs: String!\n input: JSONObject!\n scope: String!\n context: ActionContextInput\n}\n\n\"\"\"\nOne mutation job of a batch, mirroring the reactor's `ExecutionJobPlan`\n(packages/reactor/src/core/types.ts). The batch runs its jobs in dependency\norder only, not atomically: each job commits on its own with no batch rollback,\nand a failed job still releases its dependents.\n\n`documentIdOrSlug` is the document the job's actions apply to -- an id that does\nnot yet exist when the job's actions create it. `actions` are coerced against\n`ActionInput` and passed through exactly as `execute` does, so a client-signed\naction keeps its signature. `scope` is the single scope every action in the job\nshares, and `dependsOn` names the plan keys this job is ordered after. `branch`\ndefaults to `main`.\n\"\"\"\ninput ExecutionJobInput {\n key: String!\n documentIdOrSlug: String!\n scope: String!\n branch: String\n actions: [ActionInput!]!\n dependsOn: [String!]!\n}\n\n# Synchronization types\ntype ReactorOperation {\n index: Int!\n timestampUtcMs: String!\n hash: String!\n skip: Int!\n error: String\n deniedReason: String\n id: String\n action: Action!\n}\n\ninput OperationInput {\n index: Int!\n timestampUtcMs: String!\n hash: String!\n skip: Int!\n error: String\n deniedReason: String\n id: String\n action: ActionInput!\n}\n\ntype OperationContext {\n documentId: String!\n documentType: String!\n scope: String!\n branch: String!\n ordinal: Int!\n}\n\ninput OperationContextInput {\n documentId: String!\n documentType: String!\n scope: String!\n branch: String!\n ordinal: Int!\n}\n\ntype OperationWithContext {\n operation: ReactorOperation!\n context: OperationContext!\n}\n\ninput OperationWithContextInput {\n operation: OperationInput!\n context: OperationContextInput!\n}\n\ntype ChannelMeta {\n id: String!\n}\n\ninput ChannelMetaInput {\n id: String!\n}\n\ntype RemoteCursor {\n remoteName: String!\n cursorOrdinal: Int!\n lastSyncedAtUtcMs: String\n}\n\ninput RemoteCursorInput {\n remoteName: String!\n cursorOrdinal: Int!\n lastSyncedAtUtcMs: String\n}\n\nenum SyncEnvelopeType {\n OPERATIONS\n ACK\n}\n\ntype SyncEnvelope {\n type: SyncEnvelopeType!\n channelMeta: ChannelMeta!\n operations: [OperationWithContext!]\n cursor: RemoteCursor\n key: String\n dependsOn: [String!]\n}\n\ninput SyncEnvelopeInput {\n type: SyncEnvelopeType!\n channelMeta: ChannelMetaInput!\n operations: [OperationWithContextInput!]\n cursor: RemoteCursorInput\n key: String\n dependsOn: [String!]\n}\n\ninput RemoteFilterInput {\n documentId: [String!]!\n scope: [String!]!\n branch: String!\n}\n\ninput SyncRefusalInput {\n documentId: String!\n branch: String!\n # \"marker\" for a refused purge marker; absent for UNSUPPORTED_PROTOCOL\n kind: String\n}\n\ninput TouchChannelInput {\n id: String!\n name: String!\n collectionId: String!\n filter: RemoteFilterInput!\n sinceTimestampUtcMs: String!\n # The client's peer manifest; absent from a client without peer agreement\n manifest: JSONObject\n}\n\ntype TouchChannelResult {\n success: Boolean!\n ackOrdinal: Int!\n # The server's peer manifest\n manifest: JSONObject\n}\n\ntype Query {\n # Get document models for a namespace\n documentModels(\n namespace: String\n paging: PagingInput\n ): DocumentModelResultPage!\n\n # Get a specific document by ID or slug\n document(\n idOrSlug: String\n identifier: String @deprecated(reason: \"Use idOrSlug.\")\n view: ViewFilterInput\n ): DocumentWithChildren\n\n # Get outgoing relationships of a given type from a source document\n documentOutgoingRelationships(\n sourceIdOrSlug: String\n sourceIdentifier: String @deprecated(reason: \"Use sourceIdOrSlug.\")\n relationshipType: String!\n view: ViewFilterInput\n paging: PagingInput\n ): PHDocumentResultPage!\n\n # Get incoming relationships of a given type to a target document\n documentIncomingRelationships(\n targetIdOrSlug: String\n targetIdentifier: String @deprecated(reason: \"Use targetIdOrSlug.\")\n relationshipType: String!\n view: ViewFilterInput\n paging: PagingInput\n ): PHDocumentResultPage!\n\n # Get the outgoing relationship edges of a source document. Unlike\n # documentOutgoingRelationships, which returns the documents at the far end,\n # this returns the edges themselves, carrying their metadata and timestamps.\n # Omit relationshipType to return edges of every type.\n documentOutgoingRelationshipEdges(\n sourceIdOrSlug: String\n sourceIdentifier: String @deprecated(reason: \"Use sourceIdOrSlug.\")\n relationshipType: String\n view: ViewFilterInput\n paging: PagingInput\n ): DocumentRelationshipResultPage!\n\n # Get the incoming relationship edges of a target document. Unlike\n # documentIncomingRelationships, which returns the documents at the far end,\n # this returns the edges themselves, carrying their metadata and timestamps.\n # Omit relationshipType to return edges of every type.\n documentIncomingRelationshipEdges(\n targetIdOrSlug: String\n targetIdentifier: String @deprecated(reason: \"Use targetIdOrSlug.\")\n relationshipType: String\n view: ViewFilterInput\n paging: PagingInput\n ): DocumentRelationshipResultPage!\n\n # Find documents by search criteria\n findDocuments(\n search: SearchFilterInput\n view: ViewFilterInput\n paging: PagingInput\n ): PHDocumentResultPage!\n\n # Get job status\n jobStatus(jobId: String!): JobInfo\n\n # Whether findDocuments would serve the document to the caller. Absent or\n # withheld is false; a server that cannot decide answers with an error.\n documentServed(idOrSlug: String!, view: ViewFilterInput): Boolean!\n\n # The signature policy and protocol versions a new document gets, under the\n # parent when one is named. A parent the caller may not read is refused.\n createDefaults(parentIdOrSlug: String): CreateDefaults!\n\n # Get operations for a document with filtering and pagination\n documentOperations(\n filter: OperationsFilterInput!\n paging: PagingInput\n ): ReactorOperationResultPage!\n\n \"\"\"\n Predicts whether the calling subject would be admitted to execute each of a\n set of candidate operations, without submitting any of them. A UI asks this to\n disable a control rather than offer an action that fails on submit.\n\n The answer is a prediction, not a promise:\n\n - Real admission compiles an append condition over everything it read and the\n store enforces it at write time. A preflight reads no future, so a policy\n change landing between this answer and the submit changes the verdict. The\n submit path stays the only authority.\n - The verdict is evaluated at the stream heads, so it is correct for a\n candidate about to be submitted. A backdated submission is out of contract;\n the reactor decides that one by position.\n - A candidate whose verdict depends on its input has to carry that input, since\n a conditional grant reads it.\n\n The subject is the authenticated caller and cannot be named in the request:\n answering for an arbitrary subject would disclose what a policy grants\n somebody else. It carries both the caller's address and the did:key of the app\n instance whose token authenticated the request, so a policy naming either\n matches the same principal the write path presents.\n\n Requires the reactor's authEnforcement feature flag. Without it the reactor\n holds no decision model, so this fails with extensions.code\n AUTH_EVALUATION_UNSUPPORTED rather than guessing.\n \"\"\"\n evaluateActions(\n documentIdOrSlug: String\n documentIdentifier: String @deprecated(reason: \"Use documentIdOrSlug.\")\n branch: String\n candidates: [ActionCandidateInput!]!\n ): ActionEvaluations!\n\n \"\"\"\n Polls for sync envelopes from a channel.\n\n An operation stored before the API required an action id cannot be\n represented by this schema, and rather than serving a partial response beside\n a bare non-null violation, this fails with extensions.code\n MALFORMED_STORED_OPERATION naming the operation. That code means the failure\n is worth polling through: the document holding the operation needs repairing,\n but the channel serves every other document, and a peer that stopped polling\n would stop receiving those too.\n \"\"\"\n pollSyncEnvelopes(\n channelId: String!\n outboxAck: Int!\n outboxLatest: Int!\n # The client's manifest revision; absent from a client without peer agreement\n manifestRevision: String\n # Documents the client refused from earlier polls: held, or a refused marker\n refusals: [SyncRefusalInput!]\n ): PollSyncEnvelopesResult!\n\n # Supreme admin, or the address the named remote's channel is bound to\n syncHolds(remoteName: String, documentId: String): [SyncHold!]!\n\n # Supreme admin, or an address bound to a channel in the collection\n peerAgreement(collectionId: String!): PeerAgreement!\n}\n\ntype Mutation {\n # Create a new document\n createDocument(\n document: JSONObject!\n parentIdOrSlug: String\n parentIdentifier: String @deprecated(reason: \"Use parentIdOrSlug.\")\n ): PHDocument!\n\n # Create an empty document of specified type\n createEmptyDocument(\n documentType: String!\n parentIdOrSlug: String\n parentIdentifier: String @deprecated(reason: \"Use parentIdOrSlug.\")\n ): PHDocument!\n\n \"\"\"\n Applies actions to a document and waits for the result.\n\n Each action is coerced against `ActionInput`, so one missing a field the wire\n declares is refused before any work starts. The id in particular: it is hashed\n into the operation id and replay dedupes by it, so an action without one is\n stored under an operation id shared by every id-less operation on the same\n document, scope and branch.\n\n Named for `IReactorClient.execute`, which this is the wire form of. `branch`\n defaults to `main`.\n \"\"\"\n execute(\n documentIdOrSlug: String\n documentIdentifier: String @deprecated(reason: \"Use documentIdOrSlug.\")\n actions: [ActionInput!]!\n branch: String\n ): PHDocument!\n\n \"\"\"\n Submits actions to a document and returns the job that will apply them.\n\n Coerced exactly as `execute` is, so a malformed action is refused here rather\n than surfacing later as a failed job. Returns the job rather than only its id,\n so a caller has the status and the creation time it would otherwise have to\n ask for; `result` is null until the job produces one.\n \"\"\"\n executeAsync(\n documentIdOrSlug: String\n documentIdentifier: String @deprecated(reason: \"Use documentIdOrSlug.\")\n actions: [ActionInput!]!\n branch: String\n ): JobInfo!\n\n \"\"\"\n Applies multiple mutation jobs in dependency order and waits for all of them,\n the wire form of `IReactorClient.executeBatch`. Each job's actions are coerced\n against `ActionInput` exactly as `execute` is, so client-signed actions pass\n through unchanged, and `dependsOn` orders the jobs. It is synchronous: the jobs\n are applied and awaited before the result returns, so every returned `JobInfo`\n is a completed one rather than the pending receipt the in-process reactor hands\n back. A batch is ordering, not a transaction: each job commits on its own, and\n a failed job still releases the jobs that depend on it, so any job, before or\n after a failure, may have committed. A failed job is therefore returned as a\n FAILED entry with its `error` and `errorName`, beside the final state of every\n other job, rather than failing the mutation. The mutation itself fails only\n when no job state can be reported.\n\n A job carrying `CREATE_DOCUMENT` must be the batch's only job, with the create\n as its first action naming the job's document. Its other actions may only be\n an `UPGRADE_DOCUMENT` of the new document and `ADD_RELATIONSHIP`s targeting\n it. It is authorized like `createDocument`: write on every source of those\n relationships, or the right to create when there is none.\n \"\"\"\n executeBatch(jobs: [ExecutionJobInput!]!): BatchExecutionResult!\n\n # Apply actions to a document (synchronous)\n mutateDocument(\n documentIdentifier: String!\n actions: [JSONObject!]!\n view: ViewFilterInput\n ): PHDocument!\n @deprecated(\n reason: \"Use execute. Actions here are untyped, so a malformed one is refused by a hand-written check rather than by the schema, and `view.scopes` is accepted but ignored.\"\n )\n\n # Submit actions to a document (asynchronous)\n mutateDocumentAsync(\n documentIdentifier: String!\n actions: [JSONObject!]!\n view: ViewFilterInput\n ): String!\n @deprecated(\n reason: \"Use executeAsync, which is typed and returns the job rather than only its id.\"\n )\n\n # Rename a document\n renameDocument(\n documentIdOrSlug: String\n documentIdentifier: String @deprecated(reason: \"Use documentIdOrSlug.\")\n name: String!\n branch: String\n ): PHDocument!\n\n # Update the preferred editor recorded in the document header meta.\n # Pass null/omit to clear it.\n setPreferredEditor(\n documentIdOrSlug: String\n documentIdentifier: String @deprecated(reason: \"Use documentIdOrSlug.\")\n preferredEditor: String\n branch: String\n ): PHDocument!\n\n # Add a relationship between two documents. Adding one that already exists is\n # a no-op, metadata included -- use updateRelationship to change an edge.\n addRelationship(\n sourceIdOrSlug: String\n sourceIdentifier: String @deprecated(reason: \"Use sourceIdOrSlug.\")\n targetIdOrSlug: String\n targetIdentifier: String @deprecated(reason: \"Use targetIdOrSlug.\")\n relationshipType: String!\n metadata: JSONObject\n branch: String\n ): PHDocument!\n\n # Replace the metadata of an existing relationship, preserving its createdAt.\n # Omitting metadata, or passing null, clears it.\n updateRelationship(\n sourceIdOrSlug: String\n sourceIdentifier: String @deprecated(reason: \"Use sourceIdOrSlug.\")\n targetIdOrSlug: String\n targetIdentifier: String @deprecated(reason: \"Use targetIdOrSlug.\")\n relationshipType: String!\n metadata: JSONObject\n branch: String\n ): PHDocument!\n\n # Remove a relationship between two documents\n removeRelationship(\n sourceIdOrSlug: String\n sourceIdentifier: String @deprecated(reason: \"Use sourceIdOrSlug.\")\n targetIdOrSlug: String\n targetIdentifier: String @deprecated(reason: \"Use targetIdOrSlug.\")\n relationshipType: String!\n branch: String\n ): PHDocument!\n\n # Move a relationship from one source to another\n moveRelationship(\n sourceParentIdOrSlug: String\n sourceParentIdentifier: String\n @deprecated(reason: \"Use sourceParentIdOrSlug.\")\n targetParentIdOrSlug: String\n targetParentIdentifier: String\n @deprecated(reason: \"Use targetParentIdOrSlug.\")\n targetIdOrSlug: String\n targetIdentifier: String @deprecated(reason: \"Use targetIdOrSlug.\")\n relationshipType: String!\n branch: String\n ): MoveRelationshipResult!\n\n # Delete a single document\n deleteDocument(\n idOrSlug: String\n identifier: String @deprecated(reason: \"Use idOrSlug.\")\n propagate: PropagationMode\n ): Boolean!\n\n # Delete multiple documents\n deleteDocuments(\n idsOrSlugs: [String!]\n identifiers: [String!] @deprecated(reason: \"Use idsOrSlugs.\")\n propagate: PropagationMode\n ): Boolean!\n\n # Touch (create or update) a channel for sync\n touchChannel(input: TouchChannelInput!): TouchChannelResult!\n\n # Push sync envelopes to a channel\n pushSyncEnvelopes(\n envelopes: [SyncEnvelopeInput!]!\n # The server's manifest revision the client gated these envelopes under\n peerManifestRevision: String\n ): Boolean!\n}\n\ntype Subscription {\n # Subscribe to document changes\n documentChanges(\n search: SearchFilterInput\n view: ViewFilterInput\n ): DocumentChangeEvent!\n\n # Subscribe to job changes\n jobChanges(jobId: String!): JobChangeEvent!\n}\n";
1217
+ //#endregion
1218
+ //#region src/graphql/system/schema.ts
1219
+ const systemTypeDefs = gql`
1220
+ type SystemInfo {
1221
+ version: String!
1222
+ gitHash: String!
1223
+ gitUrl: String
1224
+ }
1225
+
1226
+ type Query {
1227
+ system: SystemInfo!
1228
+ }
1229
+ `;
1230
+ //#endregion
1231
+ //#region src/packages/base-document-models.ts
1232
+ /** The models every host loads before any package's, by source package. */
1233
+ const baseDocumentModels = [
1234
+ ["document-drive", driveDocumentModelModule],
1235
+ ["document-model", documentModelDocumentModelModule],
1236
+ ["reactor-drive", reactorDriveDocumentModelModule],
1237
+ ["reactor-group", ReactorGroupV1]
1238
+ ];
1239
+ //#endregion
1240
+ export { hasOperationSchemas as C, schema_default$1 as D, typeDefinitionNames as E, getGeneratedDocumentModelTypes as S, reservedTypeNamesTaken as T, generateDocumentModelSchema as _, collectSubgraphClaims as a, getDocumentModelSubgraphName as b, DocumentModelSchemaCache as c, buildDocumentModelSchema as d, buildSubgraphSchemaModule as f, findSubgraphTypeCollisions as g, documentModelSubgraphTypes as h, inspectionTypeDefs as i, SubgraphTypeCollisionError as l, createSchema as m, systemTypeDefs as n, describeOwnershipConflicts as o, createMergedSchema as p, schema_default as r, resolveClaimOwnership as s, baseDocumentModels as t, assembleSubgraphTypeDefs as u, generatedTypesOf as v, reservedTypeNames as w, getDocumentModelTypeDefs as x, getDocumentModelSchemaName as y };
1241
+
1242
+ //# sourceMappingURL=base-document-models-69WRTSfH.mjs.map
1243
+ //# debugId=bd7672af-0ac4-5f07-901b-3577215a9c3f