@powerhousedao/reactor-api 6.2.3-dev.79 → 6.2.3-dev.80
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter-gateway-apollo-D-EdZ4e-.mjs +2 -2
- package/dist/adapter-gateway-apollo-D-EdZ4e-.mjs.map +1 -1
- package/dist/{base-document-models-ux7TZ9X3.mjs → base-document-models-D-cmBBYJ.mjs} +116 -27
- package/dist/base-document-models-D-cmBBYJ.mjs.map +1 -0
- package/dist/{create-schema-BUk-IQCT.d.mts → create-schema-Dio_7akA.d.mts} +22 -7
- package/dist/create-schema-Dio_7akA.d.mts.map +1 -0
- package/dist/error-info-BaEL50f5.mjs +2 -2
- package/dist/error-info-BaEL50f5.mjs.map +1 -1
- package/dist/index.d.mts +297 -7
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +607 -138
- package/dist/index.mjs.map +1 -1
- package/dist/{package-subgraph-check-BGfeyfnc.mjs → package-subgraph-check-C0PD_Tj9.mjs} +4 -4
- package/dist/{package-subgraph-check-BGfeyfnc.mjs.map → package-subgraph-check-C0PD_Tj9.mjs.map} +1 -1
- package/dist/src/graphql/subgraph-types.d.mts +1 -1
- package/dist/src/graphql/subgraph-types.mjs +1 -1
- package/dist/src/packages/vite-loader.d.mts +4 -1
- package/dist/src/packages/vite-loader.d.mts.map +1 -1
- package/dist/src/packages/vite-loader.mjs +31 -13
- package/dist/src/packages/vite-loader.mjs.map +1 -1
- package/dist/{subgraph-extraction-BYKOycxo.mjs → subgraph-extraction-BA9WKjn1.mjs} +470 -10
- package/dist/subgraph-extraction-BA9WKjn1.mjs.map +1 -0
- package/dist/{types-BEpxtyKW.d.mts → types-PXB1ctpi.d.mts} +19 -2
- package/dist/types-PXB1ctpi.d.mts.map +1 -0
- package/package.json +13 -14
- package/dist/base-document-models-ux7TZ9X3.mjs.map +0 -1
- package/dist/create-schema-BUk-IQCT.d.mts.map +0 -1
- package/dist/subgraph-extraction-BYKOycxo.mjs.map +0 -1
- package/dist/types-BEpxtyKW.d.mts.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"base-document-models-ux7TZ9X3.mjs","sources":["../src/graphql/auth/schema.graphql","../src/utils/create-schema.ts","../src/graphql/subgraph-type-ownership.ts","../src/graphql/subgraph-admission.ts","../src/graphql/inspection/admin-schema.ts","../src/graphql/inspection/schema.ts","../src/graphql/reactor/schema.graphql","../src/graphql/system/schema.ts","../src/packages/base-document-models.ts"],"sourcesContent":["\"# 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\"","import {\n buildSubgraphSchema,\n type GraphQLResolverMap,\n type GraphQLSchemaModule,\n} from \"@apollo/subgraph\";\nimport { typeDefs as scalarsTypeDefs } from \"@powerhousedao/document-engineering/graphql\";\nimport type { Context } from \"@powerhousedao/reactor-api\";\nimport type {\n DocumentModelGlobalState,\n DocumentModelModule,\n} from \"@powerhousedao/shared/document-model\";\nimport { camelCase, kebabCase, pascalCase } from \"change-case\";\nimport { childLogger } from \"document-model\";\nimport {\n type ASTNode,\n type DefinitionNode,\n type DocumentNode,\n Kind,\n Lexer,\n type NameNode,\n parse,\n print,\n Source,\n TokenKind,\n visit,\n} from \"graphql\";\nimport { gql } from \"graphql-tag\";\nimport { GraphQLJSON, GraphQLJSONObject } from \"graphql-type-json\";\nimport { createHash } from \"node:crypto\";\n\nconst logger = childLogger([\"reactor-api\", \"create-schema\"]);\n\n/**\n * Revision type - matches the definition in reactor/schema.graphql.\n * Used by PHDocument and document mutation results.\n */\nconst RevisionType = `\n type Revision {\n scope: String!\n revision: Int!\n }\n`;\n\n/**\n * A subgraph defines a type whose name the generated document-model schema\n * owns, so one of the two definitions would be lost.\n */\nexport class SubgraphTypeCollisionError extends Error {\n readonly typeNames: string[];\n\n constructor(typeNames: string[]) {\n super(\n `Subgraph defines types reserved by the document-model schema: ${typeNames.join(\", \")}`,\n );\n this.name = \"SubgraphTypeCollisionError\";\n this.typeNames = typeNames;\n }\n}\n\n/**\n * Type-system definition kinds that GraphQL requires to be uniquely named.\n * A subgraph SDL with two definitions sharing a name fails federation\n * composition (\"There can be only one type named X\"), which is fatal to the\n * whole gateway. We dedupe these by name; field/operation/extension nodes are\n * left untouched.\n */\nconst TYPE_DEFINITION_KINDS = new Set<Kind>([\n Kind.OBJECT_TYPE_DEFINITION,\n Kind.ENUM_TYPE_DEFINITION,\n Kind.INPUT_OBJECT_TYPE_DEFINITION,\n Kind.INTERFACE_TYPE_DEFINITION,\n Kind.UNION_TYPE_DEFINITION,\n Kind.SCALAR_TYPE_DEFINITION,\n]);\n\n/**\n * Drop duplicate type-system definitions by name, keeping the first occurrence.\n * Deduping is by name across ALL kinds (a `type` and an `enum` sharing a name\n * collide in GraphQL too), so the first definition of a given name wins\n * regardless of kind. State types are emitted before operation types, so\n * keep-first preserves the authoritative state definition. This heals a document\n * model that defines the same name twice (global+local, state+operation, or\n * twice in one scope) so the assembled subgraph SDL composes instead of crashing\n * the gateway (Sentry #917).\n */\nconst dedupeTypeDefinitions = (\n definitions: readonly DefinitionNode[],\n seen = new Set<string>(),\n): DefinitionNode[] =>\n definitions.filter((def) => {\n const name = typeDefinitionName(def);\n if (name === undefined) return true;\n if (seen.has(name)) {\n // A duplicate here would otherwise crash supergraph composition; log it so\n // production has a breadcrumb of which model shipped a duplicate name.\n logger.debug(`Dropping duplicate type definition: ${name}`);\n return false;\n }\n seen.add(name);\n return true;\n });\n\nfunction typeDefinitionName(def: DefinitionNode): string | undefined {\n if (!TYPE_DEFINITION_KINDS.has(def.kind)) return undefined;\n return (def as { name?: { value: string } }).name?.value;\n}\n\nconst EMPTY_DOCUMENT: DocumentNode = { kind: Kind.DOCUMENT, definitions: [] };\n\nconst OUTPUT_TYPE_KINDS = [\n Kind.OBJECT_TYPE_DEFINITION,\n Kind.OBJECT_TYPE_EXTENSION,\n Kind.ENUM_TYPE_DEFINITION,\n Kind.ENUM_TYPE_EXTENSION,\n Kind.UNION_TYPE_DEFINITION,\n Kind.UNION_TYPE_EXTENSION,\n Kind.INTERFACE_TYPE_DEFINITION,\n Kind.INTERFACE_TYPE_EXTENSION,\n];\n\n// Kinds whose names get prefixed: state schemas (inputs stripped) and operation schemas.\nconst STATE_PREFIX_KINDS = new Set<Kind>(OUTPUT_TYPE_KINDS);\nconst ALL_PREFIX_KINDS = new Set<Kind>([\n ...OUTPUT_TYPE_KINDS,\n Kind.INPUT_OBJECT_TYPE_DEFINITION,\n Kind.INPUT_OBJECT_TYPE_EXTENSION,\n]);\n\n// Nodes whose `name` is a type name: definitions, extensions and references.\nconst TYPE_NAME_KINDS = new Set<Kind>([\n ...ALL_PREFIX_KINDS,\n Kind.SCALAR_TYPE_DEFINITION,\n Kind.SCALAR_TYPE_EXTENSION,\n Kind.NAMED_TYPE,\n]);\n\n// Stub local state types dropped from legacy models.\nconst LOCAL_STATE_STUBS = new Set([\n \"AccountSnapshotLocalState\",\n \"BudgetStatementLocalState\",\n \"ScopeFrameworkLocalState\",\n]);\n\n/** Parse SDL; blank or comment-only input yields an empty document. */\nfunction parseSdl(sdl: string): DocumentNode {\n const source = new Source(sdl);\n if (new Lexer(source).advance().kind === TokenKind.EOF) return EMPTY_DOCUMENT;\n try {\n return parse(source, { noLocation: true });\n } catch (error) {\n // Retry without stray semicolons, which GraphQL rejects.\n const withoutSemicolons = sdl.replaceAll(\";\", \"\");\n if (withoutSemicolons === sdl) throw error;\n return parse(withoutSemicolons, { noLocation: true });\n }\n}\n\nfunction definedTypeNames(\n doc: DocumentNode,\n kinds: ReadonlySet<Kind>,\n): string[] {\n return doc.definitions\n .filter((def) => kinds.has(def.kind))\n .map((def) => (def as DefinitionNode & { name: NameNode }).name.value);\n}\n\n/** Prefix type definition names and type references found in `names`. */\nfunction prefixTypeNames(\n doc: DocumentNode,\n prefix: string,\n names: ReadonlySet<string>,\n): DocumentNode {\n return visit(doc, {\n enter(node: ASTNode) {\n if (!TYPE_NAME_KINDS.has(node.kind)) return undefined;\n const { name } = node as ASTNode & { name: NameNode };\n if (!names.has(name.value)) return undefined;\n return { ...node, name: { ...name, value: `${prefix}_${name.value}` } };\n },\n });\n}\n\n/** State schema definitions without inputs, `DateTime` or the given object types. */\nfunction stateTypeDefinitions(\n sdl: string,\n droppedObjectTypes: ReadonlySet<string> = new Set(),\n): DefinitionNode[] {\n return parseSdl(sdl).definitions.filter(\n (def) =>\n def.kind !== Kind.INPUT_OBJECT_TYPE_DEFINITION &&\n def.kind !== Kind.INPUT_OBJECT_TYPE_EXTENSION &&\n !(\n def.kind === Kind.SCALAR_TYPE_DEFINITION &&\n def.name.value === \"DateTime\"\n ) &&\n !(\n def.kind === Kind.OBJECT_TYPE_DEFINITION &&\n droppedObjectTypes.has(def.name.value)\n ),\n );\n}\n\n/**\n * Prefixed operation schemas per module. The first definition of each module\n * carries a \"Module: <Name>\" description unless it has its own.\n */\nfunction buildModuleSchemas(\n specification: DocumentModelGlobalState[\"specifications\"][0] | undefined,\n documentName: string,\n allTypeNames: string[],\n hasValidSchema: (schema: string | null | undefined) => boolean,\n): string {\n const names = new Set(allTypeNames);\n return (\n specification?.modules\n .map((module) => {\n const definitions = module.operations\n .filter((op) => hasValidSchema(op.schema))\n .flatMap((op) => {\n const doc = parseSdl(op.schema ?? \"\");\n const opNames = new Set([\n ...names,\n ...definedTypeNames(doc, ALL_PREFIX_KINDS),\n ]);\n return prefixTypeNames(doc, documentName, opNames).definitions;\n });\n if (definitions.length === 0) return \"\";\n const [first, ...rest] = definitions;\n const header =\n \"description\" in first && !first.description\n ? {\n ...first,\n description: {\n kind: Kind.STRING,\n value: `Module: ${pascalCase(module.name)}`,\n block: true,\n },\n }\n : first;\n return print({\n kind: Kind.DOCUMENT,\n definitions: [header as DefinitionNode, ...rest],\n });\n })\n .filter(Boolean)\n .join(\"\\n\") ?? \"\"\n );\n}\n\nexport type SubgraphSchemaOptions = {\n /**\n * Types the subgraph's own schema generator emits, as a document model's\n * subgraph has. These may repeat a generated definition, which is kept.\n */\n ownTypeNames?: ReadonlySet<string>;\n /** Generated types already built for `documentModels`. */\n generated?: GeneratedDocumentModelTypes;\n};\n\nexport const buildSubgraphSchemaModule = (\n documentModels: DocumentModelModule[],\n resolvers: GraphQLResolverMap<Context>,\n typeDefs: DocumentNode,\n options: SubgraphSchemaOptions = {},\n): GraphQLSchemaModule => {\n const newResolvers = {\n ...resolvers,\n JSONObject: GraphQLJSONObject,\n Unknown: GraphQLJSON,\n };\n\n return {\n typeDefs: assembleSubgraphTypeDefs(\n options.generated ?? getGeneratedDocumentModelTypes(documentModels),\n typeDefs,\n options.ownTypeNames,\n ),\n resolvers: newResolvers,\n };\n};\nexport const createSchema = (\n documentModels: DocumentModelModule[],\n resolvers: GraphQLResolverMap<Context>,\n typeDefs: DocumentNode,\n options: SubgraphSchemaOptions = {},\n) => {\n // Array form: @apollo/subgraph 2.15 dropped the bare-module overload.\n return buildSubgraphSchema([\n buildSubgraphSchemaModule(documentModels, resolvers, typeDefs, options),\n ]);\n};\n\n/**\n * Create a merged GraphQL schema from multiple subgraph modules.\n * Uses buildSubgraphSchema's array overload to combine type definitions\n * and resolvers from multiple subgraphs into a single executable schema.\n */\nexport const createMergedSchema = (modules: GraphQLSchemaModule[]) => {\n return buildSubgraphSchema(modules);\n};\n\nexport function getDocumentModelSchemaName(\n documentModel: DocumentModelGlobalState,\n) {\n return pascalCase(documentModel.name.replaceAll(\"/\", \" \"));\n}\n\n/** The name the model's own subgraph registers under. */\nexport function getDocumentModelSubgraphName(\n documentModel: DocumentModelGlobalState,\n): string {\n return kebabCase(documentModel.name);\n}\n\n/**\n * The generated document-model types followed by the subgraph's own. Throws\n * {@link SubgraphTypeCollisionError} when the subgraph defines a generated\n * name not in `ownTypeNames`.\n */\nexport const getDocumentModelTypeDefs = (\n documentModels: DocumentModelModule[],\n typeDefs: DocumentNode,\n ownTypeNames?: ReadonlySet<string>,\n): DocumentNode =>\n assembleSubgraphTypeDefs(\n getGeneratedDocumentModelTypes(documentModels),\n typeDefs,\n ownTypeNames,\n );\n\n/** Names of the type definitions in `doc`. */\nexport function typeDefinitionNames(doc: DocumentNode): Set<string> {\n return new Set(\n doc.definitions\n .map(typeDefinitionName)\n .filter((name) => name !== undefined),\n );\n}\n\n/** The generated document-model schema every subgraph is assembled onto. */\nexport type GeneratedDocumentModelTypes = {\n definitions: readonly DefinitionNode[];\n names: ReadonlySet<string>;\n};\n\n/** The definitions `documentModel` adds to the generated schema. */\nfunction documentModelDefinitions(\n documentModel: DocumentModelGlobalState,\n): DefinitionNode[] {\n const dmSchemaName = getDocumentModelSchemaName(documentModel);\n // Use only the latest specification to avoid duplicate type definitions\n // when a document model has multiple versions (e.g. v1, v2).\n const latestSpec = documentModel.specifications.at(-1);\n const globalSchema = latestSpec?.state.global.schema ?? \"\";\n const localSchema = latestSpec?.state.local.schema ?? \"\";\n const definitions = [\n ...stateTypeDefinitions(globalSchema),\n ...stateTypeDefinitions(localSchema, LOCAL_STATE_STUBS),\n ];\n const stateDoc: DocumentNode = { kind: Kind.DOCUMENT, definitions };\n const prefixed = prefixTypeNames(\n stateDoc,\n dmSchemaName,\n new Set(definedTypeNames(stateDoc, STATE_PREFIX_KINDS)),\n );\n const documentType = parseSdl(`\n type ${dmSchemaName} implements IDocument {\n id: String!\n name: String!\n documentType: String!\n operations(skip: Int, first: Int): [Operation!]!\n revision: Int!\n createdAtUtcIso: DateTime!\n lastModifiedAtUtcIso: DateTime!\n ${dmSchemaName !== \"DocumentModel\" ? `initialState: ${dmSchemaName}_${dmSchemaName}State!` : \"\"}\n ${dmSchemaName !== \"DocumentModel\" ? `state: ${dmSchemaName}_${dmSchemaName}State!` : \"\"}\n stateJSON: JSONObject\n }`);\n return [...prefixed.definitions, ...documentType.definitions];\n}\n\n/** The part of a document model module its schema is built from. */\nexport type DocumentModelSource = {\n documentModel: { global: DocumentModelGlobalState };\n};\n\n/** Type name → whether every definition of that name is a scalar. */\nexport type ReservedTypeNames = ReadonlyMap<string, boolean>;\n\nfunction addScalarFlags(\n definitions: readonly DefinitionNode[],\n into: Map<string, boolean>,\n): Map<string, boolean> {\n for (const def of definitions) {\n const name = typeDefinitionName(def);\n if (name === undefined) continue;\n const scalar = def.kind === Kind.SCALAR_TYPE_DEFINITION;\n into.set(name, scalar && (into.get(name) ?? true));\n }\n return into;\n}\n\nlet fixedGeneratedTypes: ReservedTypeNames | undefined;\n\n/**\n * Type names no document model may generate: the root types, the generated\n * types every schema carries, and the types of `coreTypeDefs`.\n */\nexport function reservedTypeNames(\n coreTypeDefs: Iterable<DocumentNode>,\n): ReservedTypeNames {\n fixedGeneratedTypes ??= addScalarFlags(\n getGeneratedDocumentModelTypes([]).definitions,\n new Map(),\n );\n const reserved = new Map([\n [\"Query\", false],\n [\"Mutation\", false],\n [\"Subscription\", false],\n ...fixedGeneratedTypes,\n ]);\n for (const typeDefs of coreTypeDefs) {\n addScalarFlags(typeDefs.definitions, reserved);\n }\n return reserved;\n}\n\n/**\n * The reserved names `documentModel`'s generated types take. A scalar may\n * repeat a reserved scalar: the duplicate is dropped on assembly.\n */\nexport function reservedTypeNamesTaken(\n documentModel: DocumentModelSource,\n reserved: ReservedTypeNames,\n definitions: readonly DefinitionNode[] = documentModelDefinitions(\n documentModel.documentModel.global,\n ),\n): string[] {\n const generated = addScalarFlags(definitions, new Map());\n return Array.from(generated)\n .filter(\n ([name, scalar]) => reserved.has(name) && !(scalar && reserved.get(name)),\n )\n .map(([name]) => name);\n}\n\n// The generated schema around the document models' definitions.\nconst GENERATED_HEAD = gql`\n scalar JSONObject\n scalar AttachmentRef\n # Codegen scalars not in the document-engineering set.\n scalar Unknown\n scalar Address\n ${scalarsTypeDefs.join(\"\\n\").replaceAll(\";\", \"\")}\n\n type PHOperationContext {\n signer: Signer\n }\n\n type Signer {\n user: SignerUser\n app: SignerApp\n signatures: [String!]!\n }\n\n type SignerUser {\n address: String!\n networkId: String!\n chainId: Int!\n }\n\n type SignerApp {\n name: String!\n key: String!\n }\n\n type Operation {\n id: String!\n type: String!\n index: Int!\n timestampUtcMs: DateTime!\n hash: String!\n skip: Int\n inputText: String\n error: String\n context: PHOperationContext\n }\n\n interface IDocument {\n id: String!\n name: String!\n documentType: String!\n revision: Int!\n createdAtUtcIso: DateTime!\n lastModifiedAtUtcIso: DateTime!\n operations(first: Int, skip: Int): [Operation!]!\n stateJSON: JSONObject\n }\n`.definitions;\n\nconst GENERATED_TAIL = gql`\n type GqlDocument implements IDocument {\n id: String!\n name: String!\n documentType: String!\n revision: Int!\n createdAtUtcIso: DateTime!\n lastModifiedAtUtcIso: DateTime!\n operations(first: Int, skip: Int): [Operation!]!\n stateJSON: JSONObject\n }\n\n type DriveDocument implements IDocument {\n id: String!\n name: String!\n documentType: String!\n revision: Int!\n createdAtUtcIso: DateTime!\n lastModifiedAtUtcIso: DateTime!\n operations(first: Int, skip: Int): [Operation!]!\n stateJSON: JSONObject\n }\n`.definitions;\n\n/**\n * The generated schema for `documentModels`. `schemas` supplies models'\n * definitions already built; the others are built here.\n */\nexport function getGeneratedDocumentModelTypes(\n documentModels: readonly DocumentModelSource[],\n schemas?: ReadonlyMap<DocumentModelSource, DocumentModelSchema>,\n): GeneratedDocumentModelTypes {\n return generatedTypesFrom(\n documentModels.map((model) => ({\n global: model.documentModel.global,\n generated: schemas?.get(model)?.generated,\n })),\n );\n}\n\n/** {@link getGeneratedDocumentModelTypes} from the models' global states. */\nexport function generatedTypesOf(\n documentModels: readonly DocumentModelGlobalState[],\n): GeneratedDocumentModelTypes {\n return generatedTypesFrom(documentModels.map((global) => ({ global })));\n}\n\nfunction generatedTypesFrom(\n documentModels: readonly {\n global: DocumentModelGlobalState;\n generated?: readonly DefinitionNode[];\n }[],\n): GeneratedDocumentModelTypes {\n const modelDefinitions: DefinitionNode[] = [];\n const addedDocumentModels = new Set<string>();\n documentModels.forEach(({ global, generated }) => {\n const dmSchemaName = getDocumentModelSchemaName(global);\n if (addedDocumentModels.has(dmSchemaName)) {\n logger.debug(\n `Skipping document model with duplicate name: ${dmSchemaName}`,\n );\n return;\n }\n addedDocumentModels.add(dmSchemaName);\n modelDefinitions.push(...(generated ?? documentModelDefinitions(global)));\n });\n\n const definitions = dedupeTypeDefinitions([\n ...GENERATED_HEAD,\n ...modelDefinitions,\n ...GENERATED_TAIL,\n ]);\n const names = new Set(\n definitions.map(typeDefinitionName).filter((name) => name !== undefined),\n );\n return { definitions, names };\n}\n\n/** What a document model contributes to the GraphQL schema. */\nexport type DocumentModelSchema = {\n /** Its definitions in the generated schema every subgraph carries. */\n generated: readonly DefinitionNode[];\n /** Its own subgraph's types, when it has operations to serve. */\n subgraph?: { typeDefs: DocumentNode; typeNames: ReadonlySet<string> };\n /** Why its own subgraph cannot be served; its generated types still can. */\n subgraphError?: Error;\n};\n\nconst hasValidSchema = (schema: string | null | undefined): boolean =>\n !!(schema && /\\b(input|type|enum|union|interface)\\s+\\w+/.test(schema));\n\n/** Whether any operation of the latest specification has a schema. */\nexport function hasOperationSchemas(documentModel: DocumentModelGlobalState) {\n const specification = documentModel.specifications.at(-1);\n if (!specification) return false;\n return specification.modules.some((module) =>\n module.operations.some((op) => hasValidSchema(op.schema)),\n );\n}\n\n/** The types of a document model's own subgraph. */\nexport function documentModelSubgraphTypes(\n documentModel: DocumentModelGlobalState,\n): { typeDefs: DocumentNode; typeNames: ReadonlySet<string> } {\n const typeDefs = generateDocumentModelSchema(documentModel, {\n useNewApi: true,\n });\n return { typeDefs, typeNames: typeDefinitionNames(typeDefs) };\n}\n\nconst toError = (error: unknown): Error =>\n error instanceof Error ? error : new Error(String(error));\n\n/** Build `subgraph` over the generated types of `documentModel` alone. */\nfunction checkBuilds(\n documentModel: DocumentModelSource,\n generated: readonly DefinitionNode[],\n subgraph?: DocumentModelSchema[\"subgraph\"],\n): void {\n buildSubgraphSchema([\n {\n typeDefs: assembleSubgraphTypeDefs(\n getGeneratedDocumentModelTypes(\n [documentModel],\n new Map([[documentModel, { generated }]]),\n ),\n subgraph?.typeDefs ?? EMPTY_DOCUMENT,\n subgraph?.typeNames,\n ),\n },\n ]);\n}\n\n/** Throws when the generated types every subgraph carries do not build. */\nexport function buildDocumentModelSchema(\n documentModel: DocumentModelSource,\n options: { subgraph?: boolean } = {},\n): DocumentModelSchema {\n const generated = documentModelDefinitions(\n documentModel.documentModel.global,\n );\n if (\n options.subgraph === false ||\n !hasOperationSchemas(documentModel.documentModel.global)\n ) {\n checkBuilds(documentModel, generated);\n return { generated };\n }\n try {\n const subgraph = documentModelSubgraphTypes(\n documentModel.documentModel.global,\n );\n checkBuilds(documentModel, generated, subgraph);\n return { generated, subgraph };\n } catch (error) {\n checkBuilds(documentModel, generated);\n return { generated, subgraphError: toError(error) };\n }\n}\n\n/** A document model's schema, or why it is unusable, under its source key. */\nexport type ResolvedDocumentModelSchema<\n T extends DocumentModelSource = DocumentModelModule,\n> = {\n model: T;\n key: string;\n} & (\n | { schema: DocumentModelSchema; error?: undefined }\n | { schema?: undefined; error: Error }\n);\n\n/** Hash of everything {@link buildDocumentModelSchema} reads. */\nfunction schemaSourceKey(documentModel: DocumentModelSource): string {\n const { name, specifications } = documentModel.documentModel.global;\n return createHash(\"sha256\")\n .update(JSON.stringify([name, specifications.at(-1)]))\n .digest(\"base64\");\n}\n\n/** Schemas and failures by source hash, for the last resolve's models only. */\nexport class DocumentModelSchemaCache<\n T extends DocumentModelSource = DocumentModelModule,\n> {\n #entries = new Map<string, DocumentModelSchema | Error>();\n readonly #build: (documentModel: T) => DocumentModelSchema;\n\n constructor(\n build: (documentModel: T) => DocumentModelSchema = buildDocumentModelSchema,\n ) {\n this.#build = build;\n }\n\n resolve(documentModels: readonly T[]): ResolvedDocumentModelSchema<T>[] {\n const entries = new Map<string, DocumentModelSchema | Error>();\n const resolved = documentModels.map(\n (model): ResolvedDocumentModelSchema<T> => {\n let key: string;\n let entry: DocumentModelSchema | Error | undefined;\n try {\n key = schemaSourceKey(model);\n entry = entries.get(key) ?? this.#entries.get(key);\n } catch (error) {\n key = `unkeyed:${model.documentModel.global.id}`;\n entry = toError(error);\n }\n if (entry === undefined) {\n try {\n entry = this.#build(model);\n } catch (error) {\n entry = toError(error);\n }\n }\n entries.set(key, entry);\n return entry instanceof Error\n ? { model, key, error: entry }\n : { model, key, schema: entry };\n },\n );\n this.#entries = entries;\n return resolved;\n }\n}\n\n/**\n * Names of the generated types `typeDefs` redefines, other than those a\n * model's own subgraph may repeat. Scalars are dropped on assembly, so they\n * never collide.\n */\nexport function findSubgraphTypeCollisions(\n generated: GeneratedDocumentModelTypes,\n typeDefs: DocumentNode,\n ownTypeNames?: ReadonlySet<string>,\n): string[] {\n const collisions: string[] = [];\n for (const def of typeDefs.definitions) {\n if (def.kind === Kind.SCALAR_TYPE_DEFINITION) continue;\n const name = typeDefinitionName(def);\n if (name === undefined || !generated.names.has(name)) continue;\n if (ownTypeNames?.has(name)) continue;\n collisions.push(name);\n }\n return collisions;\n}\n\n/** Throws {@link SubgraphTypeCollisionError}; see {@link getDocumentModelTypeDefs}. */\nexport function assembleSubgraphTypeDefs(\n generated: GeneratedDocumentModelTypes,\n typeDefs: DocumentNode,\n ownTypeNames?: ReadonlySet<string>,\n): DocumentNode {\n const collisions = findSubgraphTypeCollisions(\n generated,\n typeDefs,\n ownTypeNames,\n );\n if (collisions.length > 0) {\n throw new SubgraphTypeCollisionError(collisions);\n }\n const subgraphDefinitions = typeDefs.definitions.filter(\n (def) => def.kind !== Kind.SCALAR_TYPE_DEFINITION,\n );\n\n return {\n kind: Kind.DOCUMENT,\n definitions: [\n ...generated.definitions,\n ...dedupeTypeDefinitions(subgraphDefinitions, new Set(generated.names)),\n ],\n };\n}\n\n/**\n * Extract the names of types defined in a GraphQL schema.\n * Unparseable schemas yield no names.\n */\nfunction extractTypeNames(schema: string): string[] {\n try {\n return definedTypeNames(parseSdl(schema), ALL_PREFIX_KINDS);\n } catch (error) {\n logger.debug(`Skipping unparseable schema: ${String(error)}`);\n return [];\n }\n}\n\n/**\n * Print the input type definitions of a GraphQL schema.\n * @param excludeTypeNames - Input type names to leave out\n */\nfunction extractInputTypeDefinitions(\n schema: string,\n excludeTypeNames: Set<string> = new Set(),\n): string {\n const definitions = parseSdl(schema).definitions.filter(\n (def) =>\n def.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION &&\n !excludeTypeNames.has(def.name.value),\n );\n if (definitions.length === 0) return \"\";\n return print({ kind: Kind.DOCUMENT, definitions });\n}\n\n/**\n * AST type node shape for recursive type conversion.\n */\ntype GraphQLTypeNode = {\n kind: Kind;\n name?: { value: string };\n type?: GraphQLTypeNode;\n};\n\n/**\n * Extract the root state type name from a scope's GraphQL schema.\n * Uses the naming convention: {DocumentName}State for global,\n * {DocumentName}{PascalScope}State for other scopes (e.g., DocumentDriveLocalState).\n * Falls back to the last ObjectTypeDefinition (root types are conventionally last).\n */\nfunction extractRootTypeName(\n schema: string,\n documentName: string,\n scopeName: string,\n): string | null {\n try {\n const ast = parse(schema);\n\n // Try conventions:\n // 1. {DocumentName}State for global, {DocumentName}{Scope}State otherwise\n // 2. {DocumentName}GlobalState (DocumentModel uses this variant)\n const scopeSuffix = scopeName === \"global\" ? \"\" : pascalCase(scopeName);\n const candidates = [\n `${documentName}${scopeSuffix}State`,\n `${documentName}${pascalCase(scopeName)}State`,\n ];\n\n let lastObjectType: string | null = null;\n for (const def of ast.definitions) {\n if (def.kind === Kind.OBJECT_TYPE_DEFINITION) {\n if (candidates.includes(def.name.value)) {\n return def.name.value;\n }\n lastObjectType = def.name.value;\n }\n }\n\n // Fallback: last object type (root state types are defined last by convention)\n return lastObjectType;\n } catch {\n // ignore parse errors\n }\n return null;\n}\n\n/**\n * Convert a GraphQL output type AST node to an optional input type string.\n * Strips non-null markers and converts object type references to Input suffix.\n */\nfunction convertTypeNodeToInput(\n typeNode: GraphQLTypeNode,\n objectNames: Set<string>,\n unionNames: Set<string>,\n interfaceNames: Set<string>,\n): string {\n if (typeNode.kind === Kind.NON_NULL_TYPE && typeNode.type) {\n return convertTypeNodeToInput(\n typeNode.type,\n objectNames,\n unionNames,\n interfaceNames,\n );\n }\n if (typeNode.kind === Kind.LIST_TYPE && typeNode.type) {\n const inner = convertTypeNodeToInput(\n typeNode.type,\n objectNames,\n unionNames,\n interfaceNames,\n );\n return `[${inner}]`;\n }\n if (typeNode.kind === Kind.NAMED_TYPE && typeNode.name) {\n const name = typeNode.name.value;\n if (objectNames.has(name)) return `${name}Input`;\n if (unionNames.has(name) || interfaceNames.has(name)) return \"JSONObject\";\n return name;\n }\n return \"JSONObject\";\n}\n\n/**\n * Generate GraphQL input type definitions from a state schema string.\n * Converts output type definitions to input types with all fields optional.\n * - Object type references get Input suffix\n * - Union/interface references become JSONObject\n * - Enums and scalars remain unchanged\n */\nfunction generateStateInputTypes(\n stateSchema: string,\n excludeTypeNames?: Set<string>,\n): string {\n if (!stateSchema || !stateSchema.trim()) return \"\";\n\n let ast;\n try {\n ast = parse(stateSchema);\n } catch {\n return \"\";\n }\n\n const enumNames = new Set<string>();\n const unionNames = new Set<string>();\n const interfaceNames = new Set<string>();\n const objectNames = new Set<string>();\n const existingInputNames = new Set<string>();\n\n for (const def of ast.definitions) {\n switch (def.kind) {\n case Kind.ENUM_TYPE_DEFINITION:\n enumNames.add(def.name.value);\n break;\n case Kind.UNION_TYPE_DEFINITION:\n unionNames.add(def.name.value);\n break;\n case Kind.INTERFACE_TYPE_DEFINITION:\n interfaceNames.add(def.name.value);\n break;\n case Kind.OBJECT_TYPE_DEFINITION:\n objectNames.add(def.name.value);\n break;\n case Kind.INPUT_OBJECT_TYPE_DEFINITION:\n existingInputNames.add(def.name.value);\n break;\n }\n }\n\n const inputTypes: string[] = [];\n\n for (const def of ast.definitions) {\n if (def.kind !== Kind.OBJECT_TYPE_DEFINITION) continue;\n // Skip if an input type with the same name already exists in the schema\n // or in operation schemas (to avoid duplicates with moduleSchemas)\n const inputName = `${def.name.value}Input`;\n if (existingInputNames.has(inputName)) continue;\n if (excludeTypeNames?.has(inputName)) continue;\n const fields = def.fields ?? [];\n if (fields.length === 0) continue;\n\n const inputFields = fields.map((field) => {\n const fieldName = field.name.value;\n const fieldType = convertTypeNodeToInput(\n field.type as GraphQLTypeNode,\n objectNames,\n unionNames,\n interfaceNames,\n );\n return ` ${fieldName}: ${fieldType}`;\n });\n\n inputTypes.push(\n `input ${def.name.value}Input {\\n${inputFields.join(\"\\n\")}\\n}`,\n );\n }\n\n return inputTypes.join(\"\\n\\n\");\n}\n\n/**\n * Apply type prefixes to GraphQL schema to namespace types and avoid collisions.\n * Inlined from @powerhousedao/common/utils to avoid ES module import issues.\n * @param {string} schema - GraphQL schema string\n * @param {string} prefix - Prefix to apply to type names\n * @param {string[]} externalTypeNames - Type names from other schemas to also prefix\n * @returns {string} Schema with prefixed types\n */\nfunction applyGraphQLTypePrefixes(\n schema: string,\n prefix: string,\n externalTypeNames: string[] = [],\n): string {\n if (!schema || !schema.trim()) {\n return schema;\n }\n\n const doc = parseSdl(schema);\n const names = new Set([\n ...definedTypeNames(doc, ALL_PREFIX_KINDS),\n ...externalTypeNames,\n ]);\n if (names.size === 0) return schema;\n return print(prefixTypeNames(doc, prefix, names));\n}\n\n/**\n * Options for generating document model GraphQL schemas.\n */\nexport interface DocumentModelSchemaOptions {\n /**\n * When true, generates new API patterns:\n * - Mutations return full document objects (MutationResult type)\n * - Adds createEmptyDocument mutation\n * - Makes docId and input parameters required\n * @default false\n */\n useNewApi?: boolean;\n}\n\n/**\n * Generate a GraphQL schema for a document model.\n *\n * @param documentModel - The document model global state\n * @param options - Schema generation options\n * @returns GraphQL DocumentNode\n */\nexport function generateDocumentModelSchema(\n documentModel: DocumentModelGlobalState,\n options: DocumentModelSchemaOptions = {},\n): DocumentNode {\n const { useNewApi = false } = options;\n\n const specification = documentModel.specifications.at(-1);\n const documentName = getDocumentModelSchemaName(documentModel);\n const globalStateSchema = specification?.state.global.schema;\n const localStateSchema = specification?.state.local.schema;\n const globalStateTypeNames = extractTypeNames(globalStateSchema ?? \"\");\n const localStateTypeNames = extractTypeNames(localStateSchema ?? \"\");\n const stateTypeNames = [...globalStateTypeNames, ...localStateTypeNames];\n\n // Collect ALL type names from all operations' schemas\n const allOperationTypeNames =\n specification?.modules.flatMap((module) =>\n module.operations.flatMap((op) => extractTypeNames(op.schema ?? \"\")),\n ) ?? [];\n\n // Combine state types and all operation types for prefixing\n const allTypeNames = [\n ...new Set([...stateTypeNames, ...allOperationTypeNames]),\n ];\n\n // Extract input type definitions from state schema, excluding operation-specific inputs\n // (those are already defined in op.schema)\n const operationInputTypeNames = new Set(allOperationTypeNames);\n const stateInputTypes = extractInputTypeDefinitions(\n globalStateSchema ?? \"\",\n operationInputTypeNames,\n );\n const prefixedStateInputTypes = applyGraphQLTypePrefixes(\n stateInputTypes,\n documentName,\n allTypeNames,\n );\n\n if (useNewApi) {\n // New API: flat queries, typed state, async mutations\n return generateNewApiSchema(\n documentName,\n specification,\n prefixedStateInputTypes,\n allTypeNames,\n hasValidSchema,\n );\n }\n\n // Legacy API\n return generateLegacyApiSchema(\n documentName,\n specification,\n prefixedStateInputTypes,\n allTypeNames,\n hasValidSchema,\n );\n}\n\n/**\n * Generate legacy API schema with nested queries\n */\nfunction generateLegacyApiSchema(\n documentName: string,\n specification: DocumentModelGlobalState[\"specifications\"][0] | undefined,\n prefixedStateInputTypes: string,\n allTypeNames: string[],\n hasValidSchema: (schema: string | null | undefined) => boolean,\n): DocumentNode {\n const createDocumentMutation = `${documentName}_createDocument(name:String!, driveId:String): String`;\n\n const operationMutations =\n specification?.modules\n .flatMap((module) =>\n module.operations\n .filter((op) => op.name && hasValidSchema(op.schema))\n .map(\n (op) =>\n `${documentName}_${camelCase(op.name!)}(\n driveId: String, docId: PHID, input: ${documentName}_${pascalCase(op.name!)}Input): Int`,\n ),\n )\n .join(\"\\n \") ?? \"\";\n\n const moduleSchemas = buildModuleSchemas(\n specification,\n documentName,\n allTypeNames,\n hasValidSchema,\n );\n\n return gql`\n \"\"\"\n Queries: ${documentName} Document\n \"\"\"\n\n type ${documentName}Queries {\n getDocument(docId: PHID!, driveId: PHID): ${documentName}\n getDocuments(driveId: String!): [${documentName}!]\n }\n\n type Query {\n ${documentName}: ${documentName}Queries\n }\n\n \"\"\"\n Mutations: ${documentName}\n \"\"\"\n type Mutation {\n ${createDocumentMutation}\n\n ${operationMutations}\n }\n\n ${\n prefixedStateInputTypes\n ? `\"\"\"\n Input Types from State Schema\n \"\"\"\n ${prefixedStateInputTypes}`\n : \"\"\n }\n\n ${moduleSchemas}`;\n}\n\n/**\n * Generate new API schema with flat queries, typed state, and async mutations.\n * Note: State schema types are NOT included here because they are already defined\n * in getDocumentModelTypeDefs() which is used during schema composition.\n * Including them here would cause duplicate type definitions.\n */\nfunction generateNewApiSchema(\n documentName: string,\n specification: DocumentModelGlobalState[\"specifications\"][0] | undefined,\n prefixedStateInputTypes: string,\n allTypeNames: string[],\n hasValidSchema: (schema: string | null | undefined) => boolean,\n): DocumentNode {\n // Use full state type for all document models\n const stateType = `${documentName}_FullState!`;\n\n // Shared base types for document state structure (same for all document types)\n const sharedBaseTypes = `\n \"\"\"Hash configuration for document state\"\"\"\n type ${documentName}_PHHashConfig {\n algorithm: String!\n encoding: String!\n }\n\n \"\"\"Document scope state (same for all document types)\"\"\"\n type ${documentName}_PHDocumentScopeState {\n version: Int!\n hash: ${documentName}_PHHashConfig!\n isDeleted: Boolean\n deletedAtUtcIso: String\n deletedBy: String\n deletionReason: String\n }\n `;\n\n // Full state type with all scopes (auth, document, global, local)\n // Note: DocumentModel uses different naming convention (GlobalState suffix instead of State)\n // For local state, check if the specification defines a local state type\n const localSchema = specification?.state.local.schema ?? \"\";\n const hasLocalStateType = localSchema.includes(\n `type ${documentName}LocalState`,\n );\n\n const globalStateType =\n documentName === \"DocumentModel\"\n ? `${documentName}_${documentName}GlobalState!`\n : `${documentName}_${documentName}State!`;\n const localStateType = !hasLocalStateType\n ? \"JSONObject!\"\n : `${documentName}_${documentName}LocalState!`;\n\n const fullStateType = `\n \"\"\"Full state with all scopes for ${documentName}\"\"\"\n type ${documentName}_FullState {\n auth: JSONObject!\n document: ${documentName}_PHDocumentScopeState!\n global: ${globalStateType}\n local: ${localStateType}\n }\n `;\n\n // Common input types - use extend to avoid conflicts with other subgraphs\n const commonInputTypes = `\n input ${documentName}_ViewFilterInput {\n branch: String\n scopes: [String!]\n }\n\n input ${documentName}_PagingInput {\n limit: Int\n offset: Int\n cursor: String\n }\n\n input ${documentName}_SearchFilterInput {\n parentId: String\n identifiers: [String!] @deprecated(reason: \"Ignored. Filter by parentId.\")\n }\n `;\n\n // Revision type - imported from shared-schema.ts for consistency with ReactorSubgraph\n // Must be defined in each subgraph for Apollo Federation\n const revisionType = RevisionType;\n\n // Result types with typed state (or JSONObject for DocumentModel)\n // The state type (${documentName}_${documentName}State) is defined in getDocumentModelTypeDefs()\n // Uses revisionsList with shared Revision type to match ReactorSubgraph pattern\n const resultTypes = `\n \"\"\"\n Mutation result type for ${documentName} operations with typed state.\n Matches ReactorSubgraph PHDocument pattern with revisionsList.\n \"\"\"\n type ${documentName}MutationResult {\n id: String!\n slug: String\n preferredEditor: String\n name: String!\n documentType: String!\n state: ${stateType}\n revisionsList: [Revision!]!\n createdAtUtcIso: DateTime!\n lastModifiedAtUtcIso: DateTime!\n }\n\n \"\"\"\n Document with children for ${documentName}\n \"\"\"\n type ${documentName}_DocumentWithChildren {\n document: ${documentName}MutationResult!\n childIds: [String!]!\n }\n\n \"\"\"\n Paginated result type for ${documentName} documents\n \"\"\"\n type ${documentName}_DocumentResultPage {\n items: [${documentName}MutationResult!]!\n hasNextPage: Boolean!\n hasPreviousPage: Boolean!\n cursor: String\n }\n `;\n\n // Queries nested under ${documentName} namespace\n const queries = `\n type ${documentName}Queries {\n \"\"\"Get a specific ${documentName} document by identifier\"\"\"\n document(idOrSlug: String, identifier: String @deprecated(reason: \"Use idOrSlug.\"), view: ${documentName}_ViewFilterInput): ${documentName}_DocumentWithChildren\n\n \"\"\"Get all ${documentName} documents (paged)\"\"\"\n documents(paging: ${documentName}_PagingInput): ${documentName}_DocumentResultPage!\n\n \"\"\"Find ${documentName} documents by search criteria\"\"\"\n findDocuments(search: ${documentName}_SearchFilterInput, view: ${documentName}_ViewFilterInput, paging: ${documentName}_PagingInput): ${documentName}_DocumentResultPage!\n\n \"\"\"Get outgoing relationships of a ${documentName} document\"\"\"\n documentOutgoingRelationships(sourceIdOrSlug: String, sourceIdentifier: String @deprecated(reason: \"Use sourceIdOrSlug.\"), relationshipType: String!, view: ${documentName}_ViewFilterInput, paging: ${documentName}_PagingInput): ${documentName}_DocumentResultPage!\n\n \"\"\"Get incoming relationships to a ${documentName} document\"\"\"\n documentIncomingRelationships(targetIdOrSlug: String, targetIdentifier: String @deprecated(reason: \"Use targetIdOrSlug.\"), relationshipType: String!, view: ${documentName}_ViewFilterInput, paging: ${documentName}_PagingInput): ${documentName}_DocumentResultPage!\n }\n `;\n\n // Generate initial state input types for each scope\n let initialStateInputSchema = \"\";\n if (specification) {\n const scopeFields: string[] = [];\n const generatedInputTypeParts: string[] = [];\n\n for (const [scopeName, scopeState] of Object.entries(specification.state)) {\n const schema = (scopeState as { schema?: string }).schema ?? \"\";\n if (hasValidSchema(schema)) {\n const rootTypeName = extractRootTypeName(\n schema,\n documentName,\n scopeName,\n );\n if (!rootTypeName) {\n scopeFields.push(` ${scopeName}: JSONObject`);\n continue;\n }\n const scopeInputTypes = generateStateInputTypes(\n schema,\n new Set(allTypeNames),\n );\n if (!scopeInputTypes) {\n scopeFields.push(` ${scopeName}: JSONObject`);\n continue;\n }\n const prefixedScopeInputTypes = applyGraphQLTypePrefixes(\n scopeInputTypes,\n documentName,\n allTypeNames,\n );\n scopeFields.push(\n ` ${scopeName}: ${documentName}_${rootTypeName}Input`,\n );\n generatedInputTypeParts.push(prefixedScopeInputTypes);\n } else {\n scopeFields.push(` ${scopeName}: JSONObject`);\n }\n }\n\n if (scopeFields.length > 0) {\n const inputTypeDefs = generatedInputTypeParts.join(\"\\n\\n\");\n const wrapper = `input ${documentName}_InitialStateInput {\\n${scopeFields.join(\"\\n\")}\\n}`;\n initialStateInputSchema = inputTypeDefs\n ? `${inputTypeDefs}\\n\\n${wrapper}`\n : wrapper;\n }\n }\n\n // Mutations nested under ${documentName} namespace\n const createDocumentMutation = initialStateInputSchema\n ? `createDocument(name: String!, parentIdOrSlug: String, parentIdentifier: String @deprecated(reason: \"Use parentIdOrSlug.\"), slug: String, preferredEditor: String, initialState: ${documentName}_InitialStateInput): ${documentName}MutationResult!`\n : `createDocument(name: String!, parentIdOrSlug: String, parentIdentifier: String @deprecated(reason: \"Use parentIdOrSlug.\"), preferredEditor: String): ${documentName}MutationResult!`;\n const createEmptyDocumentMutation = `createEmptyDocument(parentIdOrSlug: String, parentIdentifier: String @deprecated(reason: \"Use parentIdOrSlug.\")): ${documentName}MutationResult!`;\n\n const operationMutations =\n specification?.modules\n .flatMap((module) =>\n module.operations\n .filter((op) => op.name && hasValidSchema(op.schema))\n .flatMap((op) => [\n // Sync mutation\n `${camelCase(op.name!)}(documentIdOrSlug: String, docId: PHID @deprecated(reason: \"Use documentIdOrSlug.\"), input: ${documentName}_${pascalCase(op.name!)}Input!): ${documentName}MutationResult!`,\n // Async mutation\n `${camelCase(op.name!)}Async(documentIdOrSlug: String, docId: PHID @deprecated(reason: \"Use documentIdOrSlug.\"), input: ${documentName}_${pascalCase(op.name!)}Input!): String!`,\n ]),\n )\n .join(\"\\n \") ?? \"\";\n\n const moduleSchemas = buildModuleSchemas(\n specification,\n documentName,\n allTypeNames,\n hasValidSchema,\n );\n\n return gql`\n scalar DateTime\n scalar JSONObject\n scalar AttachmentRef\n\n ${revisionType}\n\n ${sharedBaseTypes}\n\n ${fullStateType}\n\n ${commonInputTypes}\n\n ${resultTypes}\n\n \"\"\"\n Queries: ${documentName} Document\n \"\"\"\n ${queries}\n\n \"\"\"\n Mutations: ${documentName}\n \"\"\"\n type ${documentName}Mutations {\n ${createDocumentMutation}\n ${createEmptyDocumentMutation}\n\n ${operationMutations}\n }\n\n type Query {\n ${documentName}: ${documentName}Queries!\n }\n\n type Mutation {\n ${documentName}: ${documentName}Mutations!\n }\n\n ${\n prefixedStateInputTypes\n ? `\"\"\"\n Input Types from State Schema\n \"\"\"\n ${prefixedStateInputTypes}`\n : \"\"\n }\n\n ${\n initialStateInputSchema\n ? `\"\"\"\n Input Types for Initial State\n \"\"\"\n ${initialStateInputSchema}`\n : \"\"\n }\n\n ${moduleSchemas}`;\n}\n","import {\n type ASTNode,\n type DefinitionNode,\n type DocumentNode,\n isTypeDefinitionNode,\n isTypeExtensionNode,\n Kind,\n type NamedTypeNode,\n type TypeDefinitionNode,\n type TypeExtensionNode,\n print,\n visit,\n} from \"graphql\";\n\nconst ROOT_TYPE_NAMES = new Set([\"Query\", \"Mutation\", \"Subscription\"]);\n\n/** Normalized definitions by type name or root field (`Query.field`). */\nexport type SubgraphClaims = ReadonlyMap<string, string>;\n\ntype Named = { name: { value: string } };\n\nconst byName = <T extends Named>(nodes: readonly T[] | undefined) =>\n nodes &&\n [...nodes].sort((a, b) =>\n a.name.value < b.name.value ? -1 : a.name.value > b.name.value ? 1 : 0,\n );\n\n/** Printed without descriptions, with named members in name order. */\nexport function normalizeDefinition(node: ASTNode): string {\n const normalized = visit(node, {\n leave(current) {\n const copy: Record<string, unknown> = { ...current };\n delete copy.loc;\n if (\"description\" in copy) copy.description = undefined;\n if (current.kind === Kind.STRING) copy.block = false;\n for (const key of [\"fields\", \"arguments\", \"interfaces\"]) {\n if (Array.isArray(copy[key])) {\n copy[key] = byName(copy[key] as Named[]);\n }\n }\n if (\n current.kind === Kind.ENUM_TYPE_DEFINITION ||\n current.kind === Kind.ENUM_TYPE_EXTENSION\n ) {\n copy.values = byName(current.values);\n }\n if (\n current.kind === Kind.UNION_TYPE_DEFINITION ||\n current.kind === Kind.UNION_TYPE_EXTENSION\n ) {\n copy.types = byName(current.types as readonly NamedTypeNode[]);\n }\n return copy as unknown as ASTNode;\n },\n });\n return print(normalized);\n}\n\nfunction isScalar(def: DefinitionNode): boolean {\n return (\n def.kind === Kind.SCALAR_TYPE_DEFINITION ||\n def.kind === Kind.SCALAR_TYPE_EXTENSION\n );\n}\n\n/** Type and root-field claims, without scalars or generated types. */\nexport function collectSubgraphClaims(\n typeDefs: DocumentNode,\n generatedNames: ReadonlySet<string>,\n): SubgraphClaims {\n const types = new Map<string, (TypeDefinitionNode | TypeExtensionNode)[]>();\n const claims = new Map<string, string>();\n for (const def of typeDefs.definitions) {\n if (!isTypeDefinitionNode(def) && !isTypeExtensionNode(def)) continue;\n if (isScalar(def)) continue;\n const node: TypeDefinitionNode | TypeExtensionNode = def;\n const name = node.name.value;\n if (ROOT_TYPE_NAMES.has(name)) {\n if (!(\"fields\" in node)) continue;\n for (const field of node.fields ?? []) {\n const key = `${name}.${field.name.value}`;\n const definition = normalizeDefinition(field);\n const previous = claims.get(key);\n claims.set(\n key,\n previous === undefined ? definition : `${previous}\\n${definition}`,\n );\n }\n continue;\n }\n if (isTypeDefinitionNode(node) && generatedNames.has(name)) continue;\n const nodes = types.get(name) ?? [];\n nodes.push(node);\n types.set(name, nodes);\n }\n for (const [name, nodes] of types) {\n const merged = mergeTypeNodes(nodes);\n claims.set(\n name,\n merged\n ? normalizeDefinition(merged)\n : nodes.map(normalizeDefinition).sort().join(\"\\n\"),\n );\n }\n return claims;\n}\n\nconst EXTENSION_KINDS: Partial<Record<Kind, Kind>> = {\n [Kind.OBJECT_TYPE_DEFINITION]: Kind.OBJECT_TYPE_EXTENSION,\n [Kind.INTERFACE_TYPE_DEFINITION]: Kind.INTERFACE_TYPE_EXTENSION,\n [Kind.UNION_TYPE_DEFINITION]: Kind.UNION_TYPE_EXTENSION,\n [Kind.ENUM_TYPE_DEFINITION]: Kind.ENUM_TYPE_EXTENSION,\n [Kind.INPUT_OBJECT_TYPE_DEFINITION]: Kind.INPUT_OBJECT_TYPE_EXTENSION,\n};\n\n/** One definition plus its same-kind extensions, as a single definition. */\nfunction mergeTypeNodes(\n nodes: readonly (TypeDefinitionNode | TypeExtensionNode)[],\n): ASTNode | undefined {\n if (nodes.length === 1) return nodes[0];\n const definitions = nodes.filter(isTypeDefinitionNode);\n if (definitions.length !== 1) return undefined;\n const [definition] = definitions;\n const extensionKind = EXTENSION_KINDS[definition.kind];\n const merged: Record<string, readonly unknown[] | undefined> = {\n ...(definition as unknown as Record<string, readonly unknown[]>),\n };\n for (const node of nodes) {\n if (node === definition) continue;\n if (node.kind !== extensionKind) return undefined;\n const members = node as unknown as Record<string, readonly unknown[]>;\n for (const key of [\n \"fields\",\n \"interfaces\",\n \"values\",\n \"types\",\n \"directives\",\n ]) {\n const extra = members[key] as readonly unknown[] | undefined;\n if (extra) merged[key] = [...(merged[key] ?? []), ...extra];\n }\n }\n return merged as unknown as ASTNode;\n}\n\nfunction isRootFieldClaim(claim: string): boolean {\n return claim.includes(\".\");\n}\n\nexport type OwnershipConflict = { claim: string; owner: string };\n\n/** Candidates, in priority order, that lose a claim to an earlier one. */\nexport function resolveClaimOwnership<T>(\n candidates: Iterable<{ candidate: T; name: string; claims: SubgraphClaims }>,\n): Map<T, OwnershipConflict[]> {\n const owners = new Map<string, { definition: string; owner: string }>();\n const excluded = new Map<T, OwnershipConflict[]>();\n for (const { candidate, name, claims } of candidates) {\n const conflicts: OwnershipConflict[] = [];\n for (const [claim, definition] of claims) {\n const owned = owners.get(claim);\n // A root field has one resolver, so only its owner may serve it.\n if (\n owned &&\n (isRootFieldClaim(claim) || owned.definition !== definition)\n ) {\n conflicts.push({ claim, owner: owned.owner });\n }\n }\n if (conflicts.length > 0) {\n excluded.set(candidate, conflicts);\n continue;\n }\n for (const [claim, definition] of claims) {\n if (!owners.has(claim)) owners.set(claim, { definition, owner: name });\n }\n }\n return excluded;\n}\n\nexport function describeOwnershipConflicts(\n conflicts: readonly OwnershipConflict[],\n): string {\n return `claims owned by another subgraph: ${conflicts\n .map(({ claim, owner }) => `${claim} (owned by \"${owner}\")`)\n .join(\", \")}`;\n}\n","import {\n type DocumentModelSchema,\n type DocumentModelSource,\n type ReservedTypeNames,\n type ResolvedDocumentModelSchema,\n reservedTypeNamesTaken,\n} from \"../utils/create-schema.js\";\nimport {\n type OwnershipConflict,\n resolveClaimOwnership,\n type SubgraphClaims,\n} from \"./subgraph-type-ownership.js\";\n\n/** Where a subgraph came from; a package origin is the package name. */\nexport const CORE_ORIGIN = Symbol(\"core\");\nexport const DOCUMENT_MODEL_ORIGIN = Symbol(\"document-models\");\nexport const HOST_ORIGIN = Symbol(\"host\");\nexport type SubgraphOrigin =\n | string\n | typeof CORE_ORIGIN\n | typeof DOCUMENT_MODEL_ORIGIN\n | typeof HOST_ORIGIN;\n\nexport function describeOrigin(origin: SubgraphOrigin): string {\n if (origin === CORE_ORIGIN) return \"core\";\n if (origin === DOCUMENT_MODEL_ORIGIN) return \"document models\";\n if (origin === HOST_ORIGIN) return \"the host\";\n return `package ${origin}`;\n}\n\nfunction rank(origin: SubgraphOrigin): number {\n if (origin === CORE_ORIGIN) return 3;\n if (origin === HOST_ORIGIN) return 2;\n if (origin === DOCUMENT_MODEL_ORIGIN) return 1;\n return 0;\n}\n\nexport type DocumentModelRefusal<T> = {\n model: T;\n key: string;\n /** Specification version of the refused model. */\n version: number;\n /** The latest version is refused, so no version of the model is served. */\n everyVersion: boolean;\n /** Only the model's own subgraph is refused; its generated types stay. */\n subgraphOnly: boolean;\n reason: string;\n};\n\nexport type DocumentModelAdmission<T> = {\n admitted: T[];\n schemas: Map<T, DocumentModelSchema>;\n refusals: DocumentModelRefusal<T>[];\n};\n\n/** Usable models; a refused latest version refuses every version of its model. */\nexport function admitDocumentModels<T extends DocumentModelSource>(\n resolved: readonly ResolvedDocumentModelSchema<T>[],\n reserved: ReservedTypeNames,\n): DocumentModelAdmission<T> {\n const latest = new Set(\n filterLatestDocumentModelVersions(resolved.map(({ model }) => model)),\n );\n const candidates: {\n model: T;\n key: string;\n schema?: DocumentModelSchema;\n refusal?: { reason: string; subgraphOnly: boolean };\n }[] = [];\n for (const { model, key, schema, error } of resolved) {\n if (!schema) {\n const reason = `has an unusable schema: ${error.message}`;\n candidates.push({ model, key, refusal: { reason, subgraphOnly: false } });\n continue;\n }\n const taken = reservedTypeNamesTaken(model, reserved, schema.generated);\n if (taken.length > 0) {\n const reason = `generates reserved type names: ${taken.join(\", \")}`;\n candidates.push({ model, key, refusal: { reason, subgraphOnly: false } });\n continue;\n }\n const refusal = schema.subgraphError && {\n reason: `has an unusable subgraph schema: ${schema.subgraphError.message}`,\n subgraphOnly: true,\n };\n candidates.push({ model, key, schema, refusal });\n }\n\n const refusedModels = new Set(\n candidates\n .filter(({ model, refusal }) => refusal && latest.has(model))\n .map(({ model }) => model.documentModel.global.name),\n );\n const admission: DocumentModelAdmission<T> = {\n admitted: [],\n schemas: new Map(),\n refusals: [],\n };\n for (const { model, key, schema, refusal } of candidates) {\n const everyVersion = latest.has(model);\n if (!everyVersion && refusedModels.has(model.documentModel.global.name)) {\n continue;\n }\n if (refusal) {\n admission.refusals.push({\n model,\n key,\n version: specVersion(model),\n everyVersion,\n ...refusal,\n });\n }\n if (schema) {\n admission.schemas.set(model, schema);\n admission.admitted.push(model);\n }\n }\n return admission;\n}\n\nconst DOCUMENT_MODELS_TO_EXCLUDE: string[] = [];\n\nconst specVersion = (model: DocumentModelSource) =>\n model.documentModel.global.specifications.at(-1)?.version ?? 0;\n\n/** The latest version of each document model. */\nfunction filterLatestDocumentModelVersions<T extends DocumentModelSource>(\n documentModels: readonly T[],\n): T[] {\n const latestByName = new Map<string, T>();\n\n for (const documentModel of documentModels) {\n const name = documentModel.documentModel.global.name;\n const existing = latestByName.get(name);\n\n if (!existing || specVersion(documentModel) > specVersion(existing)) {\n latestByName.set(name, documentModel);\n }\n }\n\n return Array.from(latestByName.values());\n}\n\n/** The admitted models that serve a subgraph of their own, with its types. */\nexport function documentModelSubgraphSources<T extends DocumentModelSource>(\n admitted: readonly T[],\n schemas: ReadonlyMap<T, DocumentModelSchema>,\n): { model: T; types: NonNullable<DocumentModelSchema[\"subgraph\"]> }[] {\n const sources: {\n model: T;\n types: NonNullable<DocumentModelSchema[\"subgraph\"]>;\n }[] = [];\n for (const model of filterLatestDocumentModelVersions(admitted)) {\n if (DOCUMENT_MODELS_TO_EXCLUDE.includes(model.documentModel.global.id)) {\n continue;\n }\n const types = schemas.get(model)?.subgraph;\n if (types) sources.push({ model, types });\n }\n return sources;\n}\n\nexport type Admission<T> =\n | { action: \"skip\" }\n | { action: \"reject\"; reason: \"core name\" }\n | { action: \"reject\"; reason: \"rank\"; holderOrigin: SubgraphOrigin }\n | { action: \"reject\"; reason: \"collision\"; collisions: string[] }\n | { action: \"add\"; replaces: T[]; evicts: T[] };\n\n/** Same origin replaces, higher rank evicts, else refused; core names never move (#2972). */\nexport function decideAdmission<T>(\n candidate: T,\n origin: SubgraphOrigin,\n holders: readonly { holder: T; origin: SubgraphOrigin }[],\n collisions: () => string[],\n): Admission<T> {\n if (\n origin !== CORE_ORIGIN &&\n holders.some((holder) => holder.origin === CORE_ORIGIN)\n ) {\n return { action: \"reject\", reason: \"core name\" };\n }\n if (holders.some(({ holder }) => holder === candidate)) {\n return { action: \"skip\" };\n }\n const rivals = holders.filter((holder) => holder.origin !== origin);\n for (const rival of rivals) {\n if (rank(origin) <= rank(rival.origin)) {\n return { action: \"reject\", reason: \"rank\", holderOrigin: rival.origin };\n }\n }\n const found = origin === CORE_ORIGIN ? [] : collisions();\n if (found.length > 0) {\n return { action: \"reject\", reason: \"collision\", collisions: found };\n }\n return {\n action: \"add\",\n replaces: holders\n .filter((holder) => holder.origin === origin)\n .map(({ holder }) => holder),\n evicts: rivals.map(({ holder }) => holder),\n };\n}\n\n/** The order origins first registered in, and names within each. */\nexport class RegistrationOrder {\n readonly #origins = new Map<\n SubgraphOrigin,\n { order: number; names: Map<string, number> }\n >();\n\n record(origin: SubgraphOrigin, name: string): void {\n let entry = this.#origins.get(origin);\n if (!entry) {\n entry = { order: this.#origins.size, names: new Map() };\n this.#origins.set(origin, entry);\n }\n if (!entry.names.has(name)) entry.names.set(name, entry.names.size);\n }\n\n of(origin: SubgraphOrigin, name: string): [number, number] {\n const entry = this.#origins.get(origin);\n return [entry?.order ?? Infinity, entry?.names.get(name) ?? Infinity];\n }\n}\n\nexport type SupergraphMember<T> = {\n member: T;\n name: string;\n origin: SubgraphOrigin;\n claims: SubgraphClaims;\n};\n\n/** Rank, then first registration. */\nexport function byClaimPriority<T>(\n members: Iterable<T>,\n originOf: (member: T) => SubgraphOrigin,\n nameOf: (member: T) => string,\n order: RegistrationOrder,\n): T[] {\n return Array.from(members, (member) => {\n const origin = originOf(member);\n return {\n member,\n priority: [-rank(origin), ...order.of(origin, nameOf(member))],\n };\n })\n .sort((a, b) => {\n const i = a.priority.findIndex((value, j) => value !== b.priority[j]);\n return i === -1 ? 0 : a.priority[i] - b.priority[i];\n })\n .map(({ member }) => member);\n}\n\n/** Members that lose a claim: claims go by byClaimPriority. */\nexport function supergraphClaimLosers<T>(\n members: Iterable<SupergraphMember<T>>,\n order: RegistrationOrder,\n): Map<T, OwnershipConflict[]> {\n return resolveClaimOwnership(\n byClaimPriority(\n members,\n (member) => member.origin,\n (member) => member.name,\n order,\n ).map((member) => ({\n candidate: member.member,\n name: member.name,\n claims: member.claims,\n })),\n );\n}\n","import { gql } from \"graphql-tag\";\n\nexport const inspectionAdminTypeDefs = gql`\n \"\"\"\n The levers a listed admin may pull. Only served when the host enables\n inspection-admin; every field refuses any other caller.\n \"\"\"\n type InspectionAdmin {\n \"Processor retry and rerun are served.\"\n processors: Boolean!\n \"The catch-up priority can be set.\"\n catchUpPriority: Boolean!\n }\n\n type Query {\n inspectionAdmin: InspectionAdmin!\n }\n\n type Mutation {\n \"Clears a processor's error and replays from its cursor.\"\n inspectionRetryProcessor(processorId: String!): Boolean!\n \"\"\"\n Replays a processor. With clear, it and the processors sharing its clear\n scope are cleared and replayed from their floor; otherwise its cursor moves\n back to fromOrdinal, between its floor and its cursor. Answers once the\n replay ends or has run for two seconds; its progress shows in the\n processor's lastOrdinal, and a later failure in its status and the log.\n \"\"\"\n inspectionRerunProcessor(\n processorId: String!\n clear: Boolean!\n fromOrdinal: Float!\n ): Boolean!\n \"\"\"\n Sets the pace of processor backfills: mode dynamic hands the level to the\n load controller (level must be absent); mode fixed holds level, 0-7.\n \"\"\"\n inspectionSetCatchUpPriority(mode: String!, level: Int): Boolean!\n }\n`;\n","import { gql } from \"graphql-tag\";\n\n// Pinned by test to INSPECTION_WIRE_FIELDS/ROOT_FIELDS; ordinals are Float.\nexport const inspectionTypeDefs = gql`\n type ReactorStorageFacts {\n engine: String!\n persistence: String!\n durable: Boolean!\n selfHeal: Boolean!\n }\n\n type InspectorAccess {\n admin: Boolean!\n sql: Boolean!\n }\n\n \"\"\"\n What this reactor reports about itself. access is null unless the caller is\n one of the host's admins.\n \"\"\"\n type ReactorInfo {\n storage: ReactorStorageFacts!\n workflows: Boolean!\n syncChannels: [String!]!\n access: InspectorAccess\n }\n\n type InspectionDocumentModel {\n documentType: String!\n name: String!\n version: Int!\n supportedVersions: [Int!]!\n }\n\n type InspectionDrive {\n driveId: String!\n name: String!\n branch: String!\n collectionId: String!\n documentType: String!\n nodeCount: Int!\n fileCount: Int!\n folderCount: Int!\n otherNodeCount: Int!\n unreadableNodeCount: Int!\n icon: String\n }\n\n type InspectionDrivePage {\n results: [InspectionDrive!]!\n nextCursor: String\n }\n\n type InspectionDriveIntegrityRef {\n id: String!\n documentType: String!\n }\n\n type InspectionDriveIntegrity {\n driveId: String!\n checkedNodeCount: Int!\n totalFileNodeCount: Int!\n \"\"\"\n File nodes whose document is missing or not served to you; the two are\n reported alike so a withheld document's existence does not leak.\n \"\"\"\n missingDocuments: [InspectionDriveIntegrityRef!]!\n unsupportedTypes: [InspectionDriveIntegrityRef!]!\n }\n\n type InspectionAttachmentInfo {\n present: Boolean!\n storeKind: String!\n hasReplicator: Boolean!\n replicatorRunning: Boolean!\n backlogScanned: Boolean!\n refsSeen: Int!\n held: Int!\n bytesHeld: Float!\n queued: Int!\n fetching: Int!\n pendingFetches: Int!\n waiting: Int!\n notFound: Int!\n failed: Int!\n lastError: String\n }\n\n \"\"\"\n A queued job without its actions or operations.\n \"\"\"\n type InspectionQueueJob {\n id: String!\n kind: String!\n documentId: String!\n scope: String!\n branch: String!\n status: String!\n actionCount: Int!\n operationCount: Int!\n retryCount: Int!\n }\n\n type InspectionQueueState {\n isPaused: Boolean!\n totalPending: Int!\n totalExecuting: Int!\n pendingJobs: [InspectionQueueJob!]!\n executingJobs: [InspectionQueueJob!]!\n }\n\n type InspectionProcessor {\n processorId: String!\n factoryId: String!\n driveId: String!\n processorIndex: Int!\n lastOrdinal: Float!\n status: String!\n lastError: String\n lastErrorTimestampUtcMs: Float\n floor: Float!\n clearable: Boolean!\n runFrom: Float!\n phase: String!\n }\n\n \"\"\"\n What one catch-up priority level sets. giveWay is stop (level 0: no page is\n read until the level rises), pause (pauseMs between pages), yield (one\n event-loop turn) or none.\n \"\"\"\n type InspectionCatchUpLevelSettings {\n slots: Int!\n pageSize: Int!\n pauseMs: Int!\n giveWay: String!\n }\n\n \"\"\"\n The host's load over its last window, as the dynamic controller read it.\n \"\"\"\n type InspectionCatchUpLoadSample {\n requests: Int!\n p95LatencyMs: Float!\n eventLoopDelayMs: Float!\n idleForMs: Float!\n }\n\n \"\"\"\n The pace of processor backfills. mode is fixed or dynamic; level is 0-7.\n sample is null until a dynamic tick has sampled the host's load.\n \"\"\"\n type InspectionCatchUpPriority {\n mode: String!\n level: Int!\n settings: InspectionCatchUpLevelSettings!\n reason: String!\n sample: InspectionCatchUpLoadSample\n }\n\n \"\"\"\n healthy means something only when tracked; an untracked store reports false.\n \"\"\"\n type InspectionStorageHealth {\n tracked: Boolean!\n healthy: Boolean!\n everRecreated: Boolean!\n recreateCount: Int!\n }\n\n \"\"\"\n Issues in scopes the caller may not read are left out.\n \"\"\"\n type InspectionValidation {\n documentId: String!\n isConsistent: Boolean!\n keyframeIssues: [JSONObject!]!\n snapshotIssues: [JSONObject!]!\n streamOrderIssues: [JSONObject!]!\n }\n\n type InspectionCursor {\n cursorType: String!\n cursorOrdinal: Float!\n lastSyncedAtUtcMs: Float\n liveAckOrdinal: Float!\n liveLatestOrdinal: Float!\n }\n\n type InspectionMailboxDepths {\n inbox: Int!\n outbox: Int!\n deadLetter: Int!\n }\n\n type InspectionConnectionHealth {\n snapshot: JSONObject!\n neverSucceeded: Boolean!\n stalenessMs: Float\n }\n\n type InspectionRemote {\n remoteName: String!\n remoteId: String!\n inboxCursor: InspectionCursor!\n outboxCursor: InspectionCursor!\n mailboxDepths: InspectionMailboxDepths!\n connection: InspectionConnectionHealth!\n meta: JSONObject!\n }\n\n \"\"\"\n A dead letter without its operations.\n \"\"\"\n type InspectionDeadLetter {\n id: String!\n jobId: String!\n documentId: String!\n branch: String!\n scopes: [String!]!\n errorType: String!\n errorMessage: String!\n operationCount: Int!\n }\n\n type InspectionDeadLetterPage {\n remoteName: String!\n results: [InspectionDeadLetter!]!\n nextCursor: String\n }\n\n \"\"\"\n Reads only. info and documentModels serve every caller; drive and document\n reads are made as the caller through the reactor read gate; the rest need\n one of the host's admins.\n \"\"\"\n type ReactorInspection {\n info: ReactorInfo!\n documentModels: [InspectionDocumentModel!]!\n drives(cursor: String, limit: Int): InspectionDrivePage!\n \"\"\"\n Reads every file node's document. Throttled per caller.\n \"\"\"\n driveIntegrity(driveId: String!, branch: String!): InspectionDriveIntegrity!\n attachmentInfo: InspectionAttachmentInfo!\n queueState: InspectionQueueState!\n processors: [InspectionProcessor!]!\n catchUpStatus: JSONObject!\n catchUpPriority: InspectionCatchUpPriority!\n storageHealth: InspectionStorageHealth!\n \"\"\"\n Replays the whole document; expensive. Throttled per caller.\n \"\"\"\n validateDocument(documentId: String!, branch: String): InspectionValidation!\n remotes: [InspectionRemote!]!\n remote(remoteName: String!): InspectionRemote!\n deadLetters(\n remoteName: String!\n cursor: String\n limit: Int\n ): InspectionDeadLetterPage!\n }\n\n type Query {\n inspection: ReactorInspection!\n }\n`;\n","\"# 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\\n\\\"A consistency token's coordinate, as ConsistencyCoordinate reports it.\\\"\\ninput ConsistencyCoordinateInput {\\n documentId: String!\\n scope: String!\\n branch: String!\\n operationIndex: Int!\\n}\\n\\n\\\"\\\"\\\"\\nA consistency token, as JobInfo.consistencyToken reports it. A read given one\\nwaits until the read models it reads from hold every coordinate it names.\\n\\\"\\\"\\\"\\ninput ConsistencyTokenInput {\\n version: Int!\\n createdAtUtcIso: String!\\n coordinates: [ConsistencyCoordinateInput!]!\\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\\n# The kind of a drive node.\\nenum DriveNodeKind {\\n FILE\\n FOLDER\\n}\\n\\n# A file node: the document it names, placed in a drive.\\ntype DriveFileNode {\\n id: ID!\\n driveId: ID!\\n name: String!\\n parentFolder: ID\\n documentType: String!\\n}\\n\\n# A folder node.\\ntype DriveFolderNode {\\n id: ID!\\n driveId: ID!\\n name: String!\\n parentFolder: ID\\n}\\n\\n# A drive node, of any drive document type.\\nunion DriveNode = DriveFileNode | DriveFolderNode\\n\\n# A page of drive nodes. nextCursor resumes after the last node served.\\ntype DriveNodePage {\\n results: [DriveNode!]!\\n nextCursor: String\\n hasMore: Boolean!\\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 consistency: ConsistencyTokenInput\\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 consistency: ConsistencyTokenInput\\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 consistency: ConsistencyTokenInput\\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 consistency: ConsistencyTokenInput\\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 consistency: ConsistencyTokenInput\\n ): DocumentRelationshipResultPage!\\n\\n # Find documents by search criteria\\n findDocuments(\\n search: SearchFilterInput\\n view: ViewFilterInput\\n paging: PagingInput\\n consistency: ConsistencyTokenInput\\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 # With documentType, protocolVersions fit that type's reducer.\\n createDefaults(parentIdOrSlug: String, documentType: 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 # A drive's nodes, for every drive document type. Omit parentFolder for every\\n # node in the drive; pass null for the root level. A drive the caller may not\\n # read lists nothing, and a file node is listed only with its document.\\n driveNodes(\\n driveId: ID!\\n parentFolder: ID\\n paging: PagingInput\\n kind: DriveNodeKind\\n ): DriveNodePage!\\n\\n # One drive node; null when absent or withheld from the caller.\\n driveNode(driveId: ID!, id: ID!): DriveNode\\n\\n # Every node under root (inclusive) the caller may read.\\n driveDescendants(driveId: ID!, root: ID!): [DriveNode!]!\\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\"","import { gql } from \"graphql-tag\";\n\nexport const systemTypeDefs = gql`\n type SystemInfo {\n version: String!\n gitHash: String!\n gitUrl: String\n }\n\n type Query {\n system: SystemInfo!\n }\n`;\n","import { reactorDriveDocumentModelModule } from \"@powerhousedao/reactor-drive\";\nimport { ReactorGroupV1 } from \"@powerhousedao/reactor-group\";\nimport { driveDocumentModelModule } from \"@powerhousedao/shared/document-drive\";\nimport type { DocumentModelModule } from \"@powerhousedao/shared/document-model\";\nimport { documentModelDocumentModelModule } from \"document-model\";\n\n/** The models every host loads before any package's, by source package. */\nexport const baseDocumentModels: ReadonlyArray<\n readonly [string, DocumentModelModule]\n> = [\n [\n \"document-drive\",\n driveDocumentModelModule as unknown as DocumentModelModule,\n ],\n [\n \"document-model\",\n documentModelDocumentModelModule as unknown as DocumentModelModule,\n ],\n [\n \"reactor-drive\",\n reactorDriveDocumentModelModule as unknown as DocumentModelModule,\n ],\n [\"reactor-group\", ReactorGroupV1 as unknown as DocumentModelModule],\n];\n"],"names":["scalarsTypeDefs"],"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AU,EAAE,SAAS,EAAE;EACpE,OAAO,MAAM,KAAK,IAAI,EAAE,SAAS,KAAK,EAAE,SAAS;CACnD,CAAC,CAAC,CACD,KAAK,EAAE,aAAa,MAAM;AAC/B;;AAGA,SAAgB,sBACd,SACA,OAC6B;CAC7B,OAAO,sBACL,gBACE,UACC,WAAW,OAAO,SAClB,WAAW,OAAO,MACnB,KACF,CAAC,CAAC,KAAK,YAAY;EACjB,WAAW,OAAO;EAClB,MAAM,OAAO;EACb,QAAQ,OAAO;CACjB,EAAE,CACJ;AACF;;;AC7QA,MAAa,0BAA0B,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACC1C,MAAa,qBAAqB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACHrC,IAAA,iBAAA;;;ACEA,MAAa,iBAAiB,GAAG;;;;;;;;;;;;;;ACKjC,MAAa,qBAET;CACF,CACE,kBACA,wBACF;CACA,CACE,kBACA,gCACF;CACA,CACE,iBACA,+BACF;CACA,CAAC,iBAAiB,cAAgD;AACpE","debug_id":"c7a5c71d-dd40-59a5-9d93-70f4ea42f7a7"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"create-schema-BUk-IQCT.d.mts","names":[],"sources":["../src/utils/create-schema.ts"],"mappings":";;;;;;;;;cA+Ca,mCAAmC;WACrC;EAET,YAAY;;KAuMF;;;;;EAKV,eAAe;;EAEf,YAAY;;cAGD,4BAAyB,gBACpB,uBAAqB,WAC1B,mBAAmB,UAAQ,UAC5B,cAAY,UACb,0BACR;cAgBU,eAAY,gBACP,uBAAqB,WAC1B,mBAAmB,UAAQ,UAC5B,cAAY,UACb,4CAAqB;;;;;;cAanB,qBAAkB,SAAa,4CAAqB;iBAIjD,2BACd,eAAe;;iBAMD,6BACd,eAAe;;;;;;cAUJ,2BAAwB,gBACnB,uBAAqB,UAC3B,cAAY,eACP,wBACd;;iBAQa,oBAAoB,KAAK,eAAe;;KAS5C;EACV,sBAAsB;EACtB,OAAO;;;KAwCG;EACV;IAAiB,QAAQ;;;;KAIf,oBAAoB;;;;;iBAqBhB,kBACd,cAAc,SAAS,gBACtB;;;;;iBAqBa,uBACd,eAAe,qBACf,UAAU,mBACV,uBAAsB;;;;;iBA8FR,+BACd,yBAAyB,uBACzB,UAAU,YAAY,qBAAqB,uBAC1C;;iBAUa,iBACd,yBAAyB,6BACxB;;KAoCS;;EAEV,oBAAoB;;EAEpB;IAAa,UAAU;IAAc,WAAW;;;EAEhD,gBAAgB;;;iBAOF,oBAAoB,eAAe;;iBASnC,2BACd,eAAe;EACZ,UAAU;EAAc,WAAW;;;iBA+BxB,yBACd,eAAe,qBACf;EAAW;IACV;;KAwBS,4BACV,UAAU,sBAAsB;EAEhC,OAAO;EACP;;EAEI,QAAQ;EAAqB;;EAC7B;EAAoB,OAAO;;;cAYpB,yBACX,UAAU,sBAAsB;;EAKhC,YACE,SAAQ,eAAe,MAAM;EAK/B,QAAQ,yBAAyB,MAAM,4BAA4B;;;;;;;iBAoCrD,2BACd,WAAW,6BACX,UAAU,cACV,eAAe;;iBAcD,yBACd,WAAW,6BACX,UAAU,cACV,eAAe,sBACd;;;;UAoPc;;;;;;;;EAQf;;;;;;;;;iBAUc,4BACd,eAAe,0BACf,UAAS,6BACR"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"subgraph-extraction-BYKOycxo.mjs","sources":["../src/graphql/errors.ts","../src/services/authorization.service.ts","../src/services/canonical-document-id.ts","../src/services/auth.service.ts","../src/graphql/request-clients.ts","../src/graphql/base-subgraph.ts","../src/packages/import-resolver.ts","../src/packages/util.ts","../src/utils/detached.ts","../src/graphql/utils.ts","../src/packages/document-model-detection.ts","../src/packages/pieces.ts","../src/packages/subgraph-extraction.ts"],"sourcesContent":["import { GraphQLError } from \"graphql\";\nimport {\n DRIVE_AUTH_ERROR_MESSAGES,\n RECOVERABLE_GRAPHQL_ERROR_CODES,\n} from \"@powerhousedao/reactor\";\n\n/** Caller (authenticated or anonymous) lacks permission for the document. */\nexport class ForbiddenError extends GraphQLError {\n constructor(detail = \"\") {\n const base = DRIVE_AUTH_ERROR_MESSAGES.forbidden;\n super(`${base}${detail ? ` ${detail}` : \"\"}`, {\n extensions: { code: \"FORBIDDEN\" },\n });\n }\n}\n\n/** Anonymous caller on an action that requires logging in. */\nexport class AuthenticationRequiredError extends GraphQLError {\n constructor(detail = \"\") {\n const base = DRIVE_AUTH_ERROR_MESSAGES.authenticationRequired;\n super(`${base}${detail ? ` ${detail}` : \"\"}`, {\n extensions: { code: \"UNAUTHENTICATED\" },\n });\n }\n}\n\n/**\n * The reactor holds no decision model, so no authorization preflight can be\n * answered.\n *\n * Distinct from a denial, and deliberately so: a caller that cannot get a\n * prediction should render its controls as it did before it asked and let the\n * submit path refuse. Reading this as a denial would disable every control on a\n * switchboard running without authEnforcement. The code is what a client\n * branches on, since the message is not a contract.\n */\nexport class AuthEvaluationUnsupportedError extends GraphQLError {\n constructor() {\n super(\n \"Authorization evaluation is unavailable: this reactor runs without the \" +\n \"authEnforcement feature flag, so it holds no decision model\",\n { extensions: { code: \"AUTH_EVALUATION_UNSUPPORTED\" } },\n );\n }\n}\n\n/**\n * A stored operation cannot be represented in the schema, so it is reported\n * rather than served.\n *\n * The schema declares an action's id, type, timestamp, input and scope\n * non-null; an operation written before the API rejected an action without an\n * id violates that. Left to the executor, the missing value nullifies the\n * action, which bubbles up through the non-null chain until it nullifies the\n * envelope's whole operation list, and the caller receives a partial response\n * beside \"Cannot return null for non-nullable field Action.id\" - which says\n * nothing about which operation, and which a sync client can only read as a\n * permanent GraphQL rejection, stopping its poll timer for good.\n *\n * Thrown instead, with a code that says the failure is worth polling through:\n * the document holding the operation needs repairing, but the channel serves\n * every other document, and a peer that stopped polling would stop receiving\n * those too. The code is what a client branches on, since the message is not a\n * contract.\n */\nexport class MalformedStoredOperationError extends GraphQLError {\n constructor(detail: string) {\n super(`Stored operation cannot be served: ${detail}`, {\n extensions: {\n code: RECOVERABLE_GRAPHQL_ERROR_CODES.malformedStoredOperation,\n },\n });\n }\n}\n\n/**\n * The marker refusals a poll carried were not recorded, so the poll fails.\n * The code is recoverable: the client keeps polling and reports them again.\n */\nexport class RefusalNotRecordedError extends GraphQLError {\n constructor(cause: unknown) {\n super(\"A reported marker refusal was not recorded; report it again\", {\n originalError: cause instanceof Error ? cause : new Error(String(cause)),\n extensions: {\n code: RECOVERABLE_GRAPHQL_ERROR_CODES.refusalNotRecorded,\n },\n });\n }\n}\n","import { PURGE_DOCUMENT } from \"@powerhousedao/shared/document-model\";\nimport type { DocumentPermissionLevel } from \"../utils/db.js\";\nimport type {\n DocumentPermissionService,\n GetParentIdsFn,\n} from \"./document-permission.service.js\";\n\n/**\n * A document id that has been resolved to its canonical form, never a slug.\n *\n * Protection and grant rows are written under the canonical id, while the\n * read/operation data paths accept an id-or-slug identifier. The decision layer\n * must key on the canonical id, so branding it forces every caller to resolve a\n * slug to its id before consulting this service, closing the slug-aliasing\n * bypass (S-C1). The only sanctioned cast from string to CanonicalDocumentId\n * lives in createCanonicalDocumentIdResolver, immediately after the shared\n * resolveIdOrSlug lookup returns.\n */\nexport type CanonicalDocumentId = string & {\n readonly __canonicalDocumentId: unique symbol;\n};\n\n/**\n * Result of a passed per-document authorization check. `fetchIdentifier` is\n * always safe for the data fetch: the canonical id when resolved, or the raw\n * identifier when the check was skipped for a policy-wide caller.\n */\nexport class AuthorizedDocumentHandle {\n private constructor(\n readonly fetchIdentifier: string,\n readonly isResolved: boolean,\n ) {}\n\n static resolved(documentId: CanonicalDocumentId): AuthorizedDocumentHandle {\n return new AuthorizedDocumentHandle(documentId, true);\n }\n\n static skipped(identifier: string): AuthorizedDocumentHandle {\n return new AuthorizedDocumentHandle(identifier, false);\n }\n\n /** The verified canonical id; throws when resolution was skipped. */\n canonicalId(): CanonicalDocumentId {\n if (!this.isResolved) {\n throw new Error(\n \"Canonical document id is unavailable: the authorization check was skipped for a policy-wide caller\",\n );\n }\n return this.fetchIdentifier as CanonicalDocumentId;\n }\n}\n\nexport const AuthorizationPolicy = {\n OPEN: \"OPEN\",\n ADMIN_ONLY: \"ADMIN_ONLY\",\n DOCUMENT_PERMISSIONS: \"DOCUMENT_PERMISSIONS\",\n} as const;\n\nexport type AuthorizationPolicy =\n (typeof AuthorizationPolicy)[keyof typeof AuthorizationPolicy];\n\nexport interface AuthorizationConfig {\n admins: string[];\n defaultProtection: boolean;\n policy: AuthorizationPolicy;\n}\n\n/**\n * Single source of truth for every permission decision. Always present (never\n * null) so callers branch on data, not on the existence of a service.\n *\n * The policy selects an implementation once at boot:\n * - OPEN: authentication disabled — everyone (incl. anonymous) is allowed.\n * - ADMIN_ONLY: authentication on, document permissions off — only ADMINS.\n * - DOCUMENT_PERMISSIONS: the full per-document protection + grant model.\n *\n * Permission inheritance walks the parent-document hierarchy through a\n * parent resolver injected at construction; callers never supply one.\n */\nexport interface IAuthorizationService {\n readonly config: AuthorizationConfig;\n\n /**\n * Whether the user has unrestricted, policy-wide access. Under OPEN this is\n * true for everyone (including anonymous callers) by design: OPEN means \"no\n * restrictions\", and consumers use this check to skip per-document\n * filtering. It does NOT mean the caller is in the ADMINS list.\n */\n isSupremeAdmin(userAddress?: string): boolean;\n\n /**\n * Whether the user may create new documents under the current policy:\n * everyone in OPEN, only admins in ADMIN_ONLY, any authenticated user in\n * DOCUMENT_PERMISSIONS.\n */\n canCreate(userAddress?: string): boolean;\n\n canRead(\n documentId: CanonicalDocumentId,\n userAddress?: string,\n ): Promise<boolean>;\n\n canWrite(\n documentId: CanonicalDocumentId,\n userAddress?: string,\n ): Promise<boolean>;\n\n /**\n * Whether the user administers the document: supreme admin, document\n * owner, or holder of an ADMIN grant.\n */\n canManage(\n documentId: CanonicalDocumentId,\n userAddress?: string,\n ): Promise<boolean>;\n\n canMutate(\n documentId: CanonicalDocumentId,\n operationType: string,\n userAddress?: string,\n ): Promise<boolean>;\n}\n\n/** Shared config holder and admin-list check for the policy strategies. */\nabstract class BaseAuthorizationService implements IAuthorizationService {\n constructor(readonly config: AuthorizationConfig) {}\n\n isSupremeAdmin(userAddress?: string): boolean {\n if (!userAddress) return false;\n return this.config.admins.includes(userAddress.toLowerCase());\n }\n\n abstract canCreate(userAddress?: string): boolean;\n\n abstract canRead(\n documentId: CanonicalDocumentId,\n userAddress?: string,\n ): Promise<boolean>;\n\n abstract canWrite(\n documentId: CanonicalDocumentId,\n userAddress?: string,\n ): Promise<boolean>;\n\n abstract canManage(\n documentId: CanonicalDocumentId,\n userAddress?: string,\n ): Promise<boolean>;\n\n abstract canMutate(\n documentId: CanonicalDocumentId,\n operationType: string,\n userAddress?: string,\n ): Promise<boolean>;\n}\n\n/** OPEN: authentication disabled — everyone (incl. anonymous) is allowed. */\nclass OpenAuthorizationService extends BaseAuthorizationService {\n isSupremeAdmin(): boolean {\n return true;\n }\n\n canCreate(): boolean {\n return true;\n }\n\n canRead(): Promise<boolean> {\n return Promise.resolve(true);\n }\n\n canWrite(): Promise<boolean> {\n return Promise.resolve(true);\n }\n\n canManage(): Promise<boolean> {\n return Promise.resolve(true);\n }\n\n canMutate(): Promise<boolean> {\n return Promise.resolve(true);\n }\n}\n\n/** ADMIN_ONLY: authentication on, document permissions off — only ADMINS. */\nclass AdminOnlyAuthorizationService extends BaseAuthorizationService {\n canCreate(userAddress?: string): boolean {\n return this.isSupremeAdmin(userAddress);\n }\n\n canRead(\n _documentId: CanonicalDocumentId,\n userAddress?: string,\n ): Promise<boolean> {\n return Promise.resolve(this.isSupremeAdmin(userAddress));\n }\n\n canWrite(\n _documentId: CanonicalDocumentId,\n userAddress?: string,\n ): Promise<boolean> {\n return Promise.resolve(this.isSupremeAdmin(userAddress));\n }\n\n canManage(\n _documentId: CanonicalDocumentId,\n userAddress?: string,\n ): Promise<boolean> {\n return Promise.resolve(this.isSupremeAdmin(userAddress));\n }\n\n canMutate(\n _documentId: CanonicalDocumentId,\n _operationType: string,\n userAddress?: string,\n ): Promise<boolean> {\n return Promise.resolve(this.isSupremeAdmin(userAddress));\n }\n}\n\nconst PERMISSION_RANK: Record<DocumentPermissionLevel, number> = {\n READ: 1,\n WRITE: 2,\n ADMIN: 3,\n};\n\nfunction satisfies(\n level: DocumentPermissionLevel | null,\n required: DocumentPermissionLevel,\n): boolean {\n return level !== null && PERMISSION_RANK[level] >= PERMISSION_RANK[required];\n}\n\n/**\n * DOCUMENT_PERMISSIONS: the full per-document protection + grant model.\n *\n * All decisions live here; DocumentPermissionService is the data-access\n * layer underneath (grants, protection rows, owners).\n */\nclass DocumentPermissionsAuthorizationService extends BaseAuthorizationService {\n readonly #permissions: DocumentPermissionService;\n readonly #getParentIds: GetParentIdsFn;\n\n constructor(\n permissions: DocumentPermissionService,\n getParentIds: GetParentIdsFn,\n config: AuthorizationConfig,\n ) {\n super(config);\n this.#permissions = permissions;\n this.#getParentIds = getParentIds;\n }\n\n canCreate(userAddress?: string): boolean {\n return this.isSupremeAdmin(userAddress) || !!userAddress;\n }\n\n canRead(\n documentId: CanonicalDocumentId,\n userAddress?: string,\n ): Promise<boolean> {\n return this.#canAccess(documentId, \"READ\", userAddress);\n }\n\n canWrite(\n documentId: CanonicalDocumentId,\n userAddress?: string,\n ): Promise<boolean> {\n return this.#canAccess(documentId, \"WRITE\", userAddress);\n }\n\n canManage(\n documentId: CanonicalDocumentId,\n userAddress?: string,\n ): Promise<boolean> {\n return this.#isDocumentAdmin(documentId, userAddress);\n }\n\n async canMutate(\n documentId: CanonicalDocumentId,\n operationType: string,\n userAddress?: string,\n ): Promise<boolean> {\n if (this.isSupremeAdmin(userAddress)) return true;\n // A purge marker needs a document admin whatever the operation rows say.\n if (operationType === PURGE_DOCUMENT) {\n return this.#isDocumentAdmin(documentId, userAddress);\n }\n\n const isRestricted = await this.#permissions.isOperationRestricted(\n documentId,\n operationType,\n );\n if (isRestricted) {\n if (!userAddress) return false;\n if (await this.#isDocumentAdmin(documentId, userAddress)) return true;\n return this.#permissions.hasOperationGrant(\n documentId,\n operationType,\n userAddress,\n );\n }\n\n return this.#canAccess(documentId, \"WRITE\", userAddress);\n }\n\n /**\n * The one \"administers this document\" predicate: supreme admin, document\n * owner, or ADMIN grant on the document itself.\n */\n async #isDocumentAdmin(\n documentId: string,\n userAddress?: string,\n ): Promise<boolean> {\n if (this.isSupremeAdmin(userAddress)) return true;\n if (!userAddress) return false;\n\n const owner = await this.#permissions.getDocumentOwner(documentId);\n if (owner && owner === userAddress.toLowerCase()) return true;\n\n return satisfies(await this.#grantLevel(documentId, userAddress), \"ADMIN\");\n }\n\n /**\n * The one read/write decision shape: supreme admin → unprotected (self or\n * ancestor) → owner → inherited grant of at least the required level.\n */\n async #canAccess(\n documentId: string,\n required: DocumentPermissionLevel,\n userAddress?: string,\n ): Promise<boolean> {\n if (this.isSupremeAdmin(userAddress)) return true;\n\n const isProtected = await this.#permissions.isProtectedWithAncestors(\n documentId,\n this.#getParentIds,\n );\n if (!isProtected) return true;\n if (!userAddress) return false;\n\n const owner = await this.#permissions.getDocumentOwner(documentId);\n if (owner && owner === userAddress.toLowerCase()) return true;\n\n return this.#hasGrantInHierarchy(documentId, userAddress, required);\n }\n\n /** Best grant the user holds on the document. */\n async #grantLevel(\n documentId: string,\n userAddress: string,\n ): Promise<DocumentPermissionLevel | null> {\n return this.#permissions.getUserPermission(documentId, userAddress);\n }\n\n /**\n * Walks the parent hierarchy (with cycle protection) looking for a grant of\n * at least the required level on the document or any ancestor.\n */\n async #hasGrantInHierarchy(\n documentId: string,\n userAddress: string,\n required: DocumentPermissionLevel,\n ): Promise<boolean> {\n const visited = new Set<string>();\n const queue = [documentId];\n\n while (queue.length > 0) {\n const current = queue.shift()!;\n if (visited.has(current)) continue;\n visited.add(current);\n\n const level = await this.#grantLevel(current, userAddress);\n if (satisfies(level, required)) return true;\n\n for (const parentId of await this.#getParentIds(current)) {\n if (!visited.has(parentId)) queue.push(parentId);\n }\n }\n\n return false;\n }\n}\n\n/**\n * Selects the strategy for the configured policy. The strategy classes are\n * not exported, so this guard is the only construction path.\n */\nexport function createAuthorizationService(\n config: AuthorizationConfig,\n documentPermissionService?: DocumentPermissionService,\n getParentIds?: GetParentIdsFn,\n): IAuthorizationService {\n if (config.policy === AuthorizationPolicy.OPEN) {\n return new OpenAuthorizationService(config);\n }\n if (config.policy === AuthorizationPolicy.ADMIN_ONLY) {\n return new AdminOnlyAuthorizationService(config);\n }\n if (!documentPermissionService) {\n throw new Error(\n \"DocumentPermissionService is required for the DOCUMENT_PERMISSIONS policy\",\n );\n }\n if (!getParentIds) {\n throw new Error(\n \"A getParentIds resolver is required for the DOCUMENT_PERMISSIONS policy\",\n );\n }\n return new DocumentPermissionsAuthorizationService(\n documentPermissionService,\n getParentIds,\n config,\n );\n}\n","import type {\n IReactorReadClient,\n IReactorWriteClient,\n} from \"@powerhousedao/reactor\";\nimport type { CanonicalDocumentId } from \"./authorization.service.js\";\n\n/**\n * Raised when a caller-supplied identifier cannot be resolved to a canonical\n * document id. Carries no detail on purpose: resolution failures must not act\n * as a document-existence oracle, so consumers map this to their generic\n * fail-closed response.\n */\nexport class CanonicalDocumentIdResolutionError extends Error {\n constructor() {\n super(\"Document identifier could not be resolved\");\n this.name = \"CanonicalDocumentIdResolutionError\";\n }\n}\n\nexport type CanonicalDocumentIdResolver = (\n identifier: string,\n) => Promise<CanonicalDocumentId>;\n\n/** Resolves an identifier the way the read side's data paths do. */\nexport type ReadSideIdentity = Pick<IReactorReadClient, \"resolveIdOrSlug\">;\n\n/** Resolves an identifier the way a mutation resolves its target. */\nexport type WriteSideIdentity = Pick<IReactorWriteClient, \"describe\">;\n\n/** The halves an identifier can be resolved on; mutations need `write`. */\nexport type CanonicalIdClients = {\n read: ReadSideIdentity;\n write?: WriteSideIdentity;\n};\n\n/** Which side resolves: a mutation resolves on the write side. */\nexport type CanonicalIdOperation = \"query\" | \"mutation\" | \"subscription\";\n\n/**\n * The sanctioned string-to-CanonicalDocumentId cast: both the GraphQL layer\n * and server routes must resolve caller identifiers through this helper so\n * decision and data layers always agree on the subject document.\n *\n * Queries and subscriptions resolve on the read half (`resolveIdOrSlug`, the\n * lookup their data fetch makes); mutations on the write half (`describe`, the\n * lookup their write makes). A bare read client (or the facade, whose\n * `write` is then used) is accepted as the read half.\n */\nexport function createCanonicalDocumentIdResolver(\n clients: CanonicalIdClients | ReadSideIdentity,\n operationType: CanonicalIdOperation = \"query\",\n): CanonicalDocumentIdResolver {\n const pair: CanonicalIdClients =\n \"resolveIdOrSlug\" in clients\n ? {\n read: clients,\n write: (clients as { write?: WriteSideIdentity }).write,\n }\n : clients;\n if (operationType === \"mutation\" && !pair.write) {\n throw new Error(\n \"A mutation resolves identifiers on the write half; none was given\",\n );\n }\n return async (identifier: string) => {\n let resolved: string;\n try {\n resolved =\n operationType === \"mutation\"\n ? (await pair.write!.describe(identifier)).documentId\n : await pair.read.resolveIdOrSlug(identifier);\n } catch {\n throw new CanonicalDocumentIdResolutionError();\n }\n return resolved as CanonicalDocumentId;\n };\n}\n","import type { RouteUser } from \"@powerhousedao/shared/processors\";\nimport { verifyAuthBearerToken } from \"@renown/sdk\";\n\ntype VerifiedCredential =\n Awaited<ReturnType<typeof verifyAuthBearerToken>> extends false | (infer T)\n ? T\n : never;\n\n// Confirms an authenticated signer's credential is still valid. Injected so\n// AuthService stays agnostic to how/where credentials are verified.\nexport type CredentialVerifier = (params: {\n address: string;\n chainId: number;\n appId: string;\n}) => Promise<boolean>;\n\nexport interface AuthConfig {\n /**\n * Whether the authorization policy enforces anything: it selects `ADMIN_ONLY`\n * over `OPEN`, and it is what `AuthContext.auth_enabled` reports to callers\n * that gate on \"is authentication being enforced\" (the attachment routes do).\n *\n * It does NOT decide whether the bearer is read — see {@link resolveIdentity}.\n */\n enabled: boolean;\n /**\n * Whether the bearer is verified and `AuthContext.user` populated at all.\n *\n * Defaults to {@link enabled}, which is the behaviour every deployment had\n * before this option existed. Setting it independently is what lets a server\n * know who is calling while leaving the policy `OPEN` — resolving an identity\n * and enforcing one are different concerns, and welding them together left\n * consumers choosing between an unauthenticated caller and locking every\n * non-admin out.\n *\n * It resolves an identity and enforces nothing: a request with no token is\n * still admitted, with no user.\n */\n resolveIdentity?: boolean;\n admins: string[];\n skipCredentialVerification?: boolean; // DANGER: removes identity verification; boot-gated to test/dev\n credentialVerificationCacheTtlMs?: number; // How long successful Renown credential checks are cached; 0 disables caching\n verifyCredential?: CredentialVerifier; // Injected credential check; required when verification is on\n}\n\nconst DEFAULT_CREDENTIAL_CACHE_TTL_MS = 60_000;\nconst CREDENTIAL_CACHE_MAX_ENTRIES = 1_000;\n\ninterface CredentialCacheEntry {\n exists: Promise<boolean>;\n expiresAt: number;\n address: string;\n chainId: number;\n appId: string;\n}\n\n/** What `invalidateCredential` was called with; `address` is lower-cased. */\nexport interface CredentialInvalidation {\n address: string;\n chainId?: number;\n appDid?: string;\n}\n\nexport type CredentialInvalidationListener = (\n invalidation: CredentialInvalidation,\n) => void;\n\n/**\n * The slice of {@link AuthService} handed to packages (as\n * `SubgraphArgs.credentials` / `BaseSubgraph.credentials`): a package that\n * revokes a credential calls this so the host stops honouring it at once\n * instead of after the credential cache TTL.\n */\nexport interface ICredentialInvalidator {\n /**\n * Evict cached credential checks for `address` (case-insensitive), narrowed\n * by `chainId` and the app DID (`did:key` of the app the credential\n * delegates to) when given, and re-verify open WebSocket connections of that\n * identity. Returns the number of cache entries evicted. Synchronous and\n * local to this process: other replicas still honour their cache until\n * their TTL lapses.\n */\n invalidateCredential(\n address: string,\n chainId?: number,\n appDid?: string,\n ): number;\n}\n\n/** The invalidator a subgraph receives: forwards to `authService`, or does\n * nothing when the host runs without one. */\nexport function createCredentialInvalidator(\n authService: AuthService | undefined,\n): ICredentialInvalidator {\n return {\n invalidateCredential: (address, chainId, appDid) =>\n authService?.invalidateCredential(address, chainId, appDid) ?? 0,\n };\n}\n\n/**\n * The authenticated principal. The shape is declared once in\n * `@powerhousedao/shared/processors` as `RouteUser`, so a route handler and a\n * resolver agree on it without either package redeclaring it.\n */\nexport type User = RouteUser;\n\nexport interface AuthContext {\n user?: User;\n admins: string[];\n auth_enabled: boolean;\n}\n\nexport class AuthService implements ICredentialInvalidator {\n private readonly config: AuthConfig;\n private readonly credentialCache = new Map<string, CredentialCacheEntry>();\n private readonly invalidationListeners =\n new Set<CredentialInvalidationListener>();\n\n constructor(config: AuthConfig) {\n this.config = config;\n }\n\n /**\n * Whether this service reads the bearer at all. Defaults to `enabled`, so a\n * config written before `resolveIdentity` existed behaves exactly as it did.\n */\n private get resolvesIdentity(): boolean {\n return this.config.resolveIdentity ?? this.config.enabled;\n }\n\n /** The context an unresolved request gets: no user, and no admin list to match against. */\n private anonymousContext(): AuthContext {\n return { user: undefined, admins: [], auth_enabled: this.config.enabled };\n }\n\n async authenticateRequest(\n request: globalThis.Request,\n ): Promise<AuthContext | globalThis.Response> {\n if (!this.resolvesIdentity) {\n return this.anonymousContext();\n }\n // OPTIONS is a CORS preflight: it never carries application auth. Every\n // other method verifies whatever token it carries -- a GET query's payload\n // can be an authorization verdict, so discarding its token would silently\n // answer for the anonymous subject instead of the authenticated caller.\n // A GET without a token stays anonymous, as verifyBearer already allows.\n if (request.method === \"OPTIONS\") {\n return {\n user: undefined,\n admins: this.config.admins,\n auth_enabled: this.config.enabled,\n };\n }\n return this.verifyBearer(request.headers.get(\"authorization\") ?? undefined);\n }\n\n /**\n * Verify a Bearer token regardless of HTTP method. Use this from non-GraphQL\n * middleware that must enforce authentication on every request.\n */\n async verifyBearer(\n authorization: string | undefined,\n ): Promise<AuthContext | globalThis.Response> {\n if (!this.resolvesIdentity) {\n return this.anonymousContext();\n }\n const token = authorization?.split(\" \")[1];\n if (!token) {\n return {\n user: undefined,\n admins: this.config.admins,\n auth_enabled: this.config.enabled,\n };\n }\n try {\n const verified = await this.verifyToken(token);\n if (!verified) {\n return new Response(JSON.stringify({ error: \"Verification failed\" }), {\n status: 401,\n });\n }\n const user = this.extractUserFromVerification(verified);\n if (!user) {\n return new Response(JSON.stringify({ error: \"Missing credentials\" }), {\n status: 401,\n });\n }\n if (!this.config.skipCredentialVerification) {\n const credentialExists = await this.verifyCredentialExists(\n user.address,\n user.chainId,\n verified.issuer,\n );\n if (!credentialExists) {\n return new Response(\n JSON.stringify({ error: \"Credentials no longer valid\" }),\n { status: 401 },\n );\n }\n }\n return {\n user,\n admins: this.config.admins,\n auth_enabled: this.config.enabled,\n };\n } catch {\n return new Response(JSON.stringify({ error: \"Authentication failed\" }), {\n status: 401,\n });\n }\n }\n\n // `null` when there is nobody to resolve: resolution off, or no bearer sent.\n\n /** Throws only for a bearer that is present and unusable, as HTTP 401s it. */\n async authenticateWebSocketConnection(\n connectionParams: Record<string, unknown>,\n ): Promise<User | null> {\n if (!this.resolvesIdentity) {\n return null;\n }\n\n const authHeader = connectionParams.authorization as string | undefined;\n if (!authHeader) {\n // Resolution, not enforcement: `verifyBearer` answers the same.\n\n // Refusing anonymous is onConnect's, keyed on REQUIRE_AUTHENTICATED_CALLER.\n\n // Subscriptions themselves authorize per document.\n return null;\n }\n\n const token = authHeader.split(\" \")[1];\n if (!token) {\n throw new Error(\"Invalid authorization format\");\n }\n\n const verified = await this.verifyToken(token);\n if (!verified) {\n throw new Error(\"Token verification failed\");\n }\n\n const user = this.extractUserFromVerification(verified);\n if (!user) {\n throw new Error(\"Invalid credentials\");\n }\n\n if (!this.config.skipCredentialVerification) {\n const credentialExists = await this.verifyCredentialExists(\n user.address,\n user.chainId,\n verified.issuer,\n );\n if (!credentialExists) {\n throw new Error(\"Credentials no longer valid\");\n }\n }\n\n // Note: We no longer block based on global allowed lists.\n // Authorization is handled at the resolver level based on document permissions.\n\n return user;\n }\n\n /** {@inheritDoc ICredentialInvalidator.invalidateCredential} */\n invalidateCredential(\n address: string,\n chainId?: number,\n appDid?: string,\n ): number {\n const normalized = address.toLowerCase();\n let evicted = 0;\n for (const [key, entry] of this.credentialCache) {\n if (\n entry.address === normalized &&\n (chainId === undefined || entry.chainId === chainId) &&\n (appDid === undefined || entry.appId === appDid)\n ) {\n this.credentialCache.delete(key);\n evicted++;\n }\n }\n const invalidation: CredentialInvalidation = { address: normalized };\n if (chainId !== undefined) invalidation.chainId = chainId;\n if (appDid !== undefined) invalidation.appDid = appDid;\n for (const listener of this.invalidationListeners) {\n try {\n listener(invalidation);\n } catch {\n // A listener's failure must not stop the eviction reaching the rest.\n }\n }\n return evicted;\n }\n\n /** Called after every `invalidateCredential`; returns an unsubscribe. */\n onCredentialInvalidated(\n listener: CredentialInvalidationListener,\n ): () => void {\n this.invalidationListeners.add(listener);\n return () => {\n this.invalidationListeners.delete(listener);\n };\n }\n\n /**\n * Whether an already-authenticated principal's credential still holds, for\n * re-checking long-lived connections. Goes through the same cache as\n * admission, so it costs at most one verifier call per identity per TTL.\n */\n async isCredentialValid(user: User): Promise<boolean> {\n if (this.config.skipCredentialVerification) {\n return true;\n }\n return this.verifyCredentialExists(user.address, user.chainId, user.appKey);\n }\n\n /**\n * Verify the auth bearer token\n */\n private async verifyToken(token: string) {\n return await verifyAuthBearerToken(token);\n }\n\n /**\n * Extract user information from verification result.\n *\n * The issuer is required along with the credential subject. A credential that\n * verified must carry one -- resolving it is how the signature was checked --\n * so this rejects a shape that cannot have come from verification rather than\n * admitting a keyless principal.\n */\n private extractUserFromVerification(\n verified: VerifiedCredential,\n ): User | null {\n try {\n const { address, chainId, networkId } =\n verified.verifiableCredential.credentialSubject;\n const appKey = verified.issuer;\n\n if (!address || !chainId || !networkId || !appKey) {\n return null;\n }\n\n return {\n address,\n chainId,\n networkId,\n appKey,\n };\n } catch {\n return null;\n }\n }\n\n /**\n * Verify that the credential still exists on the Renown API.\n *\n * Results are cached per (address, chainId, issuer) for a short TTL so the\n * blocking external round-trip is not paid on every request. Concurrent\n * checks for the same key share a single in-flight request, and entries\n * that resolve to false are evicted immediately so failed or revoked\n * credentials are re-checked on the next request.\n */\n private verifyCredentialExists(\n address: string,\n chainId: number,\n appId: string,\n ): Promise<boolean> {\n const ttlMs =\n this.config.credentialVerificationCacheTtlMs ??\n DEFAULT_CREDENTIAL_CACHE_TTL_MS;\n if (ttlMs <= 0) {\n return this.fetchCredentialExists(address, chainId, appId);\n }\n\n const key = `${address.toLowerCase()}:${chainId}:${appId}`;\n const now = Date.now();\n const cached = this.credentialCache.get(key);\n if (cached && cached.expiresAt > now) {\n return cached.exists;\n }\n\n this.pruneCredentialCache(now);\n const entry: CredentialCacheEntry = {\n exists: this.fetchCredentialExists(address, chainId, appId).then(\n (exists) => {\n if (!exists && this.credentialCache.get(key) === entry) {\n this.credentialCache.delete(key);\n }\n return exists;\n },\n ),\n expiresAt: now + ttlMs,\n address: address.toLowerCase(),\n chainId,\n appId,\n };\n this.credentialCache.set(key, entry);\n return entry.exists;\n }\n\n /**\n * Enforce the cache size cap before inserting a new entry: drop expired\n * entries first, then evict oldest-inserted entries (insertion order\n * matches expiry order since the TTL is constant) until under the cap, so\n * a flood of distinct keys cannot grow the map without bound.\n */\n private pruneCredentialCache(now: number): void {\n if (this.credentialCache.size < CREDENTIAL_CACHE_MAX_ENTRIES) {\n return;\n }\n for (const [key, entry] of this.credentialCache) {\n if (entry.expiresAt <= now) {\n this.credentialCache.delete(key);\n }\n }\n while (this.credentialCache.size >= CREDENTIAL_CACHE_MAX_ENTRIES) {\n const oldestKey = this.credentialCache.keys().next().value;\n if (oldestKey === undefined) {\n break;\n }\n this.credentialCache.delete(oldestKey);\n }\n }\n\n // Confirm the signer's credential is still valid via the injected verifier.\n // Reached only when verification is on, so a missing verifier is misconfig.\n private async fetchCredentialExists(\n address: string,\n chainId: number,\n appId: string,\n ): Promise<boolean> {\n if (!this.config.verifyCredential) {\n throw new Error(\n \"AuthService: credential verification is enabled but no verifyCredential was provided\",\n );\n }\n return this.config.verifyCredential({ address, chainId, appId });\n }\n}\n","import type {\n IReactorReadClient,\n IReactorWriteClient,\n} from \"@powerhousedao/reactor\";\nimport type { GraphQLResolveInfo } from \"graphql\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\n/**\n * The reactor client halves a resolver may use, carried on the GraphQL\n * context as `ctx.clients`.\n */\nexport interface RequestClients {\n /** Answers from read models; always present. */\n readonly read: IReactorReadClient;\n /**\n * Enqueues writes. Present while a mutation executes; reading it in a query\n * or a subscription throws {@link WriteClientUnavailableError}.\n */\n readonly write: IReactorWriteClient;\n}\n\n/**\n * The operation a context was built for. `unbound` is a context the host\n * built before it knew the operation, which may not write either.\n */\nexport type ClientOperation = \"query\" | \"mutation\" | \"subscription\" | \"unbound\";\n\n/** A resolver outside a mutation asked for the write client. */\nexport class WriteClientUnavailableError extends Error {\n readonly operation: ClientOperation;\n readonly field: string | undefined;\n\n constructor(operation: ClientOperation, field: string | undefined) {\n const where = field ? `field ${field}` : \"this resolver\";\n const running =\n operation === \"unbound\" ? \"outside a mutation\" : `in a ${operation}`;\n super(\n `ctx.clients.write is only available to Mutation fields; ${where} runs ${running}. Read through ctx.clients.read.`,\n );\n this.name = \"WriteClientUnavailableError\";\n this.operation = operation;\n this.field = field;\n }\n\n static isError(error: unknown): error is WriteClientUnavailableError {\n return (\n error instanceof Error && error.name === \"WriteClientUnavailableError\"\n );\n }\n}\n\n/** The field whose resolver is running, so a refusal can name it. */\nconst executingField = new AsyncLocalStorage<string>();\n\nconst operations = new WeakMap<RequestClients, ClientOperation>();\n\n/**\n * The clients for one operation: both halves for a mutation, the read half\n * and a refusing `write` for anything else. The refusing property is not\n * enumerable, so spreading or printing the clients does not trip it.\n */\nexport function createRequestClients(\n read: IReactorReadClient,\n write: IReactorWriteClient,\n operation: ClientOperation,\n): RequestClients {\n let clients: RequestClients;\n if (operation === \"mutation\") {\n clients = Object.freeze({ read, write });\n } else {\n const gated = { read } as { read: IReactorReadClient };\n Object.defineProperty(gated, \"write\", {\n enumerable: false,\n get(): never {\n throw new WriteClientUnavailableError(\n operation,\n executingField.getStore(),\n );\n },\n });\n clients = Object.freeze(gated) as RequestClients;\n }\n operations.set(clients, operation);\n return clients;\n}\n\n/**\n * The read half alone, for a context nobody bound to an operation (a resolver\n * called directly rather than through the GraphQL layer). `write` refuses.\n */\nexport function readOnlyClients(read: IReactorReadClient): RequestClients {\n return createRequestClients(read, UNAVAILABLE_WRITE, \"unbound\");\n}\n\n/** Never reached: a non-mutation client set refuses before handing it out. */\nconst UNAVAILABLE_WRITE = {} as IReactorWriteClient;\n\n/**\n * Both halves for a field that reads write-side state outside a mutation. The\n * clients still report `operation`, so identifiers resolve on the read side.\n */\nfunction createWriteSideClients(\n read: IReactorReadClient,\n write: IReactorWriteClient,\n operation: ClientOperation,\n): RequestClients {\n const clients: RequestClients = Object.freeze({ read, write });\n operations.set(clients, operation);\n return clients;\n}\n\n/**\n * The operation the clients were built for, or undefined for clients that\n * {@link createRequestClients} did not build (a hand-made pair in a test).\n */\nexport function operationOfClients(\n clients: RequestClients | undefined,\n): ClientOperation | undefined {\n return clients === undefined ? undefined : operations.get(clients);\n}\n\ntype ClientsContext = { clients: RequestClients };\n\ntype FieldResolver = (\n parent: unknown,\n args: unknown,\n context: unknown,\n info: GraphQLResolveInfo,\n) => unknown;\n\ntype TypeResolver = (\n value: unknown,\n context: unknown,\n info: GraphQLResolveInfo,\n) => unknown;\n\n/**\n * A resolver map's own object, as opposed to a scalar or another class\n * instance, which passes through. Checked by prototype rather than with\n * `isScalarType`, which refuses a scalar from another copy of graphql.\n */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\") {\n return false;\n }\n const prototype: unknown = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\n/** Type-level resolvers that receive the context; each is `(value, ctx, info)`. */\nconst TYPE_LEVEL_RESOLVERS = new Set([\n \"__resolveReference\",\n \"__resolveType\",\n \"__isTypeOf\",\n]);\n\n/**\n * Puts the client halves on the GraphQL context per operation. The host builds\n * one context per request (or per WebSocket operation) before it knows what\n * the operation is; every resolver this binder wraps receives instead a\n * context derived from that one for the operation it is running in, so a\n * mutation gets `ctx.clients.write` and a query or subscription does not.\n *\n * The derived context is memoized per request context and operation, so every\n * field of one operation sees the same object, which per-request memos key on.\n */\nexport class RequestClientBinder {\n readonly #read: IReactorReadClient;\n readonly #write: IReactorWriteClient;\n readonly #contexts = new WeakMap<object, Map<string, ClientsContext>>();\n readonly #derived = new WeakSet<object>();\n readonly #wrapped = new WeakMap<object, Record<string, unknown>>();\n\n constructor(read: IReactorReadClient, write: IReactorWriteClient) {\n this.#read = read;\n this.#write = write;\n }\n\n /** The clients for a context the host builds before the operation is known. */\n unboundClients(): RequestClients {\n return createRequestClients(this.#read, this.#write, \"unbound\");\n }\n\n /**\n * The context a resolver of `operation` receives for request context `base`.\n * `writeSide` hands a query field the write client too: a field declared to\n * read write-side state.\n */\n contextFor<TContext extends object>(\n base: TContext,\n operation: ClientOperation,\n writeSide = false,\n ): TContext & ClientsContext {\n if (this.#derived.has(base)) {\n return base as TContext & ClientsContext;\n }\n let byOperation = this.#contexts.get(base);\n if (!byOperation) {\n byOperation = new Map();\n this.#contexts.set(base, byOperation);\n }\n const key = writeSide ? `${operation}:write-side` : operation;\n let derived = byOperation.get(key);\n if (!derived) {\n derived = {\n ...base,\n clients: writeSide\n ? createWriteSideClients(this.#read, this.#write, operation)\n : createRequestClients(this.#read, this.#write, operation),\n };\n this.#derived.add(derived);\n byOperation.set(key, derived);\n }\n return derived as TContext & ClientsContext;\n }\n\n /**\n * A copy of a subgraph's resolver map whose resolvers receive the context\n * for their operation. Scalars, enums and non-function members pass through.\n * `writeSideFields` names the fields (`Type.field`) handed the write client\n * whatever their operation. The copy is memoized per map.\n */\n bindResolvers<TResolvers extends Record<string, unknown>>(\n resolvers: TResolvers,\n writeSideFields: ReadonlySet<string> = new Set(),\n ): TResolvers {\n const cached = this.#wrapped.get(resolvers);\n if (cached) {\n return cached as TResolvers;\n }\n const bound: Record<string, unknown> = {};\n for (const [typeName, typeResolvers] of Object.entries(resolvers)) {\n bound[typeName] = this.#bindType(\n typeName,\n typeResolvers,\n writeSideFields,\n );\n }\n this.#wrapped.set(resolvers, bound);\n return bound as TResolvers;\n }\n\n #bindType(\n typeName: string,\n typeResolvers: unknown,\n writeSideFields: ReadonlySet<string>,\n ): unknown {\n if (!isPlainObject(typeResolvers)) {\n return typeResolvers;\n }\n const bound: Record<string, unknown> = {};\n for (const [field, value] of Object.entries(typeResolvers)) {\n const writeSide = writeSideFields.has(`${typeName}.${field}`);\n if (typeof value === \"function\") {\n bound[field] = TYPE_LEVEL_RESOLVERS.has(field)\n ? this.#bindTypeResolver(value as TypeResolver)\n : field.startsWith(\"__\")\n ? value\n : this.#bindFieldResolver(value as FieldResolver, writeSide);\n } else if (isPlainObject(value)) {\n const config = { ...(value as Record<string, unknown>) };\n for (const key of [\"resolve\", \"subscribe\"]) {\n if (typeof config[key] === \"function\") {\n config[key] = this.#bindFieldResolver(\n config[key] as FieldResolver,\n writeSide,\n );\n }\n }\n bound[field] = config;\n } else {\n bound[field] = value;\n }\n }\n return bound;\n }\n\n #bindFieldResolver(\n resolver: FieldResolver,\n writeSide: boolean,\n ): FieldResolver {\n return (parent, args, context, info) => {\n if (!info?.operation) {\n return resolver(parent, args, context, info);\n }\n const derived = this.contextFor(\n (context ?? {}) as object,\n info.operation.operation as ClientOperation,\n writeSide,\n );\n return executingField.run(\n `${info.parentType.name}.${info.fieldName}`,\n () => resolver(parent, args, derived, info),\n );\n };\n }\n\n #bindTypeResolver(resolver: TypeResolver): TypeResolver {\n return (value, context, info) => {\n if (!info?.operation) {\n return resolver(value, context, info);\n }\n return resolver(\n value,\n this.contextFor(\n (context ?? {}) as object,\n info.operation.operation as ClientOperation,\n ),\n info,\n );\n };\n }\n}\n","import type {\n IReactorClient,\n IReactorReadClient,\n IRelationalDb,\n ISyncManager,\n SyncScopeGate,\n ViewFilter,\n} from \"@powerhousedao/reactor\";\nimport type { IAttachmentClient } from \"@powerhousedao/reactor-attachments/client\";\nimport type { AuthSubject } from \"@powerhousedao/shared/document-model\";\nimport type {\n GraphQLManager,\n ISubgraph,\n SubgraphArgs,\n} from \"@powerhousedao/reactor-api\";\nimport type { DocumentNode } from \"graphql\";\nimport { ForbiddenError, AuthenticationRequiredError } from \"./errors.js\";\nimport { gql } from \"graphql-tag\";\nimport {\n AuthorizationPolicy,\n AuthorizedDocumentHandle,\n type CanonicalDocumentId,\n type IAuthorizationService,\n} from \"../services/authorization.service.js\";\nimport { createCanonicalDocumentIdResolver } from \"../services/canonical-document-id.js\";\nimport type { IAttachmentClientProvider } from \"../services/authorized-attachment.service.js\";\nimport type { DocumentPermissionService } from \"../services/document-permission.service.js\";\nimport {\n createCredentialInvalidator,\n type ICredentialInvalidator,\n} from \"../services/auth.service.js\";\nimport {\n operationOfClients,\n readOnlyClients,\n type RequestClients,\n} from \"./request-clients.js\";\nimport type { Context } from \"./types.js\";\n\n/**\n * Stands in for a client the subgraph was not given: any use names what to\n * use instead rather than failing on `undefined`.\n */\nfunction missingClient<TClient extends object>(\n name: string,\n hint: string,\n): TClient {\n return new Proxy({} as TClient, {\n get(_target, property) {\n if (property === \"then\" || typeof property === \"symbol\") {\n return undefined;\n }\n throw new Error(`${name}.${String(property)}: ${hint}`);\n },\n });\n}\n\n/**\n * The subject a request reads as: its address and the app key its token\n * carries. Anonymous is an empty subject, never the host's signer.\n */\nexport function callerSubject(user: Context[\"user\"]): AuthSubject {\n return { address: user?.address, key: user?.appKey };\n}\n\nexport class BaseSubgraph implements ISubgraph {\n name = \"example\";\n // The host's base path as injected by the GraphQL manager. Routing\n // ignores it: the manager mounts every subgraph under its own base path.\n path = \"\";\n resolvers: Record<string, any> = {\n Query: {\n hello: () => this.name,\n },\n };\n typeDefs: DocumentNode = gql`\n type Query {\n hello: String\n }\n `;\n /**\n * The read half, for setup-time use (schema building, model lookup).\n * Resolvers read through `ctx.clients.read` instead.\n */\n readonly readClient: IReactorReadClient;\n /**\n * @deprecated The facade over both halves, for subgraphs that have not\n * moved. Resolvers use `ctx.clients.read` and, in a mutation,\n * `ctx.clients.write`; setup-time code uses {@link readClient}.\n */\n reactorClient: IReactorClient;\n /** This package's namespaced slice of the HTTP surface. */\n readonly http: SubgraphArgs[\"http\"];\n graphqlManager: GraphQLManager;\n relationalDb: IRelationalDb;\n syncManager: ISyncManager;\n documentPermissionService?: DocumentPermissionService;\n authorizationService: IAuthorizationService;\n syncServingGate?: SyncScopeGate;\n /**\n * The host's credential cache, for a package that revokes credentials:\n * call `this.credentials.invalidateCredential(address, chainId?, appDid?)`\n * right after the revocation is stored, so this host refuses the credential\n * on the next request and closes WebSocket connections that rely on it.\n * A no-op on a host without authentication.\n */\n readonly credentials: ICredentialInvalidator;\n\n /**\n * Per-request memo of raw identifier to canonical document id, keyed on the\n * request context object so entries are released when the request ends. Lets\n * batch resolvers resolve each distinct identifier at most once.\n */\n readonly #canonicalIdMemo = new WeakMap<\n object,\n Map<string, CanonicalDocumentId>\n >();\n\n readonly #unboundClients: RequestClients;\n\n readonly #attachments?: IAttachmentClientProvider;\n\n readonly #attachmentClientMemo = new WeakMap<object, IAttachmentClient>();\n\n constructor(args: SubgraphArgs) {\n // A facade without halves (an older implementation, a mock) is itself a\n // read client.\n const facadeRead = args.reactorClient?.read as\n | Partial<IReactorReadClient>\n | undefined;\n this.readClient =\n args.readClient ??\n (typeof facadeRead?.get === \"function\"\n ? (facadeRead as IReactorReadClient)\n : args.reactorClient) ??\n missingClient<IReactorReadClient>(\n \"BaseSubgraph.readClient\",\n \"this subgraph was constructed without a readClient.\",\n );\n this.reactorClient =\n args.reactorClient ??\n missingClient<IReactorClient>(\n \"BaseSubgraph.reactorClient\",\n \"this host passes no reactorClient facade. Read through ctx.clients.read (or this.readClient at setup) and write through ctx.clients.write in a mutation.\",\n );\n this.#unboundClients = readOnlyClients(this.readClient);\n this.http = args.http;\n this.graphqlManager = args.graphqlManager;\n this.relationalDb = args.relationalDb;\n this.syncManager = args.syncManager;\n this.documentPermissionService = args.documentPermissionService;\n this.authorizationService = args.authorizationService;\n this.syncServingGate = args.syncServingGate;\n this.path = args.path ?? \"\";\n this.#attachments = args.attachments;\n this.credentials =\n args.credentials ?? createCredentialInvalidator(undefined);\n }\n\n /**\n * An attachment client bound to this request's caller, memoized per request.\n *\n * @throws Error when the host provides no attachment client to subgraphs.\n */\n attachmentsFor(ctx: Context): IAttachmentClient {\n if (!this.#attachments) {\n throw new Error(\"This host provides no attachment client to subgraphs\");\n }\n let client = this.#attachmentClientMemo.get(ctx);\n if (!client) {\n client = this.#attachments.forSubject(callerSubject(ctx.user));\n this.#attachmentClientMemo.set(ctx, client);\n }\n return client;\n }\n\n /**\n * The clients this request's operation may use: those the GraphQL layer put\n * on the context. A context it never saw (a resolver called directly) reads\n * through {@link readClient} and may not write.\n */\n clientsOf(ctx: Context | undefined): RequestClients {\n return ctx?.clients ?? this.#unboundClients;\n }\n\n async onSetup() {\n // noop\n }\n\n async onDisconnect(): Promise<void> {\n // noop\n }\n\n // ============================================\n // Shared permission helpers\n // ============================================\n\n /**\n * Resolves a caller-supplied identifier (id or slug) to its canonical\n * document id, memoized per request. Both the decision layer and the data\n * layer must agree on the subject, so this runs the lookup the data path\n * uses: `resolveIdOrSlug` on the read half for a query, `describe` on the\n * write half for a mutation. A resolution failure (not found, ambiguous, or\n * transient) surfaces as a generic Forbidden, fail-closed, so a bad\n * identifier cannot be used as a document-existence oracle.\n */\n async resolveCanonicalDocumentId(\n identifier: string,\n requestKey: object,\n ): Promise<CanonicalDocumentId> {\n let cache = this.#canonicalIdMemo.get(requestKey);\n if (!cache) {\n cache = new Map<string, CanonicalDocumentId>();\n this.#canonicalIdMemo.set(requestKey, cache);\n }\n\n const cached = cache.get(identifier);\n if (cached !== undefined) return cached;\n\n const clients = this.clientsOf(requestKey as Context);\n const resolve =\n operationOfClients(clients) === \"mutation\"\n ? createCanonicalDocumentIdResolver(\n { read: clients.read, write: clients.write },\n \"mutation\",\n )\n : createCanonicalDocumentIdResolver({ read: clients.read }, \"query\");\n let canonical: CanonicalDocumentId;\n try {\n canonical = await resolve(identifier);\n } catch {\n throw new ForbiddenError();\n }\n\n cache.set(identifier, canonical);\n return canonical;\n }\n\n /**\n * Resolves the args' `documentId` to canonical form. Unconditional (unlike the\n * assertCan* helpers, no admin skip): ACL rows are keyed on the canonical id.\n */\n async withCanonicalDocumentId<T extends { documentId: string }>(\n args: T,\n requestKey: object,\n ): Promise<T & { documentId: CanonicalDocumentId }> {\n const documentId = await this.resolveCanonicalDocumentId(\n args.documentId,\n requestKey,\n );\n return { ...args, documentId };\n }\n\n /**\n * Resolves an identifier for a per-document check, or null when the caller has\n * policy-wide access (OPEN or supreme admin) and the check can be skipped.\n * Only DOCUMENT_PERMISSIONS keys on the document id, so other policies fail\n * closed without resolving.\n */\n async #resolveForCheck(\n identifier: string,\n ctx: Context,\n ): Promise<CanonicalDocumentId | null> {\n if (this.authorizationService.isSupremeAdmin(ctx.user?.address)) {\n return null;\n }\n if (\n this.authorizationService.config.policy !==\n AuthorizationPolicy.DOCUMENT_PERMISSIONS\n ) {\n throw new ForbiddenError();\n }\n return this.resolveCanonicalDocumentId(identifier, ctx);\n }\n\n /**\n * Read filter for an already-canonical document id (one sourced from the data\n * layer, such as a fetched document's id). Performs no slug resolution.\n */\n async canReadDocument(\n documentId: CanonicalDocumentId,\n ctx: Context,\n ): Promise<boolean> {\n return this.authorizationService.canRead(documentId, ctx.user?.address);\n }\n\n /** The ids or slugs in `ids` that {@link assertCanRead} admits, in order; the rest are dropped. */\n async filterReadableDocumentIds(\n ids: readonly string[],\n ctx: Context,\n ): Promise<string[]> {\n const readable: string[] = [];\n for (const id of ids) {\n try {\n await this.assertCanRead(id, ctx);\n } catch (error) {\n if (error instanceof ForbiddenError) {\n continue;\n }\n throw error;\n }\n readable.push(id);\n }\n return readable;\n }\n\n /** Drops the items the host's own ACL refuses the caller. */\n async readableByHost<T extends { id: string }>(\n items: readonly T[],\n ctx: Context,\n ): Promise<T[]> {\n if (this.authorizationService.isSupremeAdmin(ctx.user?.address)) {\n return [...items];\n }\n const readable: T[] = [];\n for (const item of items) {\n if (await this.canReadDocument(item.id as CanonicalDocumentId, ctx)) {\n readable.push(item);\n }\n }\n return readable;\n }\n\n /**\n * The principal a request decides as: the authenticated caller's address, and\n * the did:key of the app instance whose token authenticated it.\n *\n * Both, because a policy can name either. The key is what a document records\n * as its creator, so a subject built without one cannot match the creator's\n * standing permission over the auth scope -- the document's own creator would\n * be refused an operation the write path accepts, since a signed action\n * carries the same key. Anonymous callers supply neither.\n */\n protected viewSubject(ctx: Context): AuthSubject {\n return callerSubject(ctx.user);\n }\n\n /** Whether a listing would serve the document to the caller; fails closed. */\n protected async servesDocument(\n documentId: string,\n ctx: Context,\n ): Promise<boolean> {\n if (!documentId) {\n return false;\n }\n try {\n return await this.servesDocumentOrThrows(documentId, ctx);\n } catch {\n return false;\n }\n }\n\n /** {@link servesDocument}, but a reactor that cannot answer throws. */\n protected servesDocumentOrThrows(\n identifier: string,\n ctx: Context,\n view?: Pick<ViewFilter, \"branch\" | \"scopes\">,\n ): Promise<boolean> {\n return this.clientsOf(ctx).read.isServed(identifier, {\n ...view,\n subject: this.viewSubject(ctx),\n });\n }\n\n /**\n * Whether a listing would serve the document to the caller: the reactor read\n * gate, then the host's legacy layer, as `findDocuments` applies them. Absent\n * or withheld is `false`; a failure to decide throws.\n */\n protected async listsDocument(\n identifier: string,\n ctx: Context,\n view?: Pick<ViewFilter, \"branch\" | \"scopes\">,\n ): Promise<boolean> {\n if (!(await this.servesDocumentOrThrows(identifier, ctx, view))) {\n return false;\n }\n if (this.authorizationService.isSupremeAdmin(ctx.user?.address)) {\n return true;\n }\n return this.canReadDocument(\n await this.resolveCanonicalDocumentId(identifier, ctx),\n ctx,\n );\n }\n\n /**\n * Asserts read access, resolving a slug first. Returns a handle whose\n * `fetchIdentifier` the caller reuses for the data fetch; a denial throws.\n */\n async assertCanRead(\n identifier: string,\n ctx: Context,\n ): Promise<AuthorizedDocumentHandle> {\n const documentId = await this.#resolveForCheck(identifier, ctx);\n if (documentId === null)\n return AuthorizedDocumentHandle.skipped(identifier);\n await this.assertCanReadCanonical(documentId, ctx);\n return AuthorizedDocumentHandle.resolved(documentId);\n }\n\n async assertCanWrite(\n identifier: string,\n ctx: Context,\n ): Promise<AuthorizedDocumentHandle> {\n const documentId = await this.#resolveForCheck(identifier, ctx);\n if (documentId === null)\n return AuthorizedDocumentHandle.skipped(identifier);\n await this.assertCanWriteCanonical(documentId, ctx);\n return AuthorizedDocumentHandle.resolved(documentId);\n }\n\n async assertCanExecuteOperation(\n identifier: string,\n operationType: string,\n ctx: Context,\n ): Promise<AuthorizedDocumentHandle> {\n const documentId = await this.#resolveForCheck(identifier, ctx);\n if (documentId === null)\n return AuthorizedDocumentHandle.skipped(identifier);\n await this.assertCanExecuteOperationCanonical(\n documentId,\n operationType,\n ctx,\n );\n return AuthorizedDocumentHandle.resolved(documentId);\n }\n\n /**\n * Read assertion for an already-canonical document id. No slug resolution;\n * use only with ids sourced from the data layer or already resolved.\n */\n async assertCanReadCanonical(\n documentId: CanonicalDocumentId,\n ctx: Context,\n ): Promise<void> {\n const canRead = await this.authorizationService.canRead(\n documentId,\n ctx.user?.address,\n );\n if (!canRead) {\n throw new ForbiddenError(\"to read this document\");\n }\n }\n\n async assertCanWriteCanonical(\n documentId: CanonicalDocumentId,\n ctx: Context,\n ): Promise<void> {\n const canWrite = await this.authorizationService.canWrite(\n documentId,\n ctx.user?.address,\n );\n if (!canWrite) {\n throw new ForbiddenError(\"to write to this document\");\n }\n }\n\n async assertCanExecuteOperationCanonical(\n documentId: CanonicalDocumentId,\n operationType: string,\n ctx: Context,\n ): Promise<void> {\n const canMutate = await this.authorizationService.canMutate(\n documentId,\n operationType,\n ctx.user?.address,\n );\n if (!canMutate) {\n throw new ForbiddenError(\n `to execute operation \"${operationType}\" on this document`,\n );\n }\n }\n\n assertCanCreate(ctx: Context): void {\n if (this.authorizationService.canCreate(ctx.user?.address)) return;\n if (ctx.user?.address) {\n throw new ForbiddenError(\"to create documents\");\n }\n throw new AuthenticationRequiredError(\"to create documents\");\n }\n}\n","import path from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\n\n/**\n * Imports a specifier that may be either a bare package specifier or a\n * filesystem path. Absolute paths are converted to file:// URLs, because the\n * ESM loader reads the drive letter in a Windows path as a URL scheme\n * (`import('D:\\\\...')` fails with ERR_UNSUPPORTED_ESM_URL_SCHEME).\n */\nasync function importSpecifier<T>(target: string): Promise<T> {\n const specifier = path.isAbsolute(target)\n ? pathToFileURL(target).href\n : target;\n return (await import(/* @vite-ignore */ specifier)) as T;\n}\n\n/**\n * Attempts to import from suggested Node.js paths\n */\nasync function tryNodeSuggestedPaths<T>(\n packageName: string,\n subPath: string,\n): Promise<T | null> {\n const suggestedPaths = [\n `${packageName}/dist/node/${subPath}/index.mjs`,\n `${packageName}/dist/node/${subPath}.mjs`,\n `${packageName}/dist/${subPath}/index.js`,\n `${packageName}/dist/${subPath}.js`,\n ];\n\n for (const suggestedPath of suggestedPaths) {\n try {\n return await importSpecifier<T>(suggestedPath);\n } catch {\n // Continue to next attempt\n }\n }\n\n return null;\n}\n\n/**\n * Attempts to resolve package using import.meta.resolve\n */\nasync function tryImportMetaResolve<T>(\n packageName: string,\n subPath: string,\n): Promise<T | null> {\n try {\n const resolvedUrl = import.meta.resolve?.(`${packageName}/package.json`);\n if (!resolvedUrl) return null;\n\n // fileURLToPath, not URL.pathname: the latter yields \"/D:/...\" on Windows.\n const packageRoot = path.dirname(fileURLToPath(resolvedUrl));\n const pathsToTry = [\n path.join(packageRoot, \"dist\", \"node\", subPath, \"index.mjs\"),\n path.join(packageRoot, \"dist\", \"node\", `${subPath}.mjs`),\n path.join(packageRoot, \"dist\", subPath, \"index.js\"),\n path.join(packageRoot, \"dist\", `${subPath}.js`),\n path.join(packageRoot, subPath, \"index.js\"),\n path.join(packageRoot, `${subPath}.js`),\n ];\n\n for (const attemptPath of pathsToTry) {\n try {\n return await importSpecifier<T>(attemptPath);\n } catch {\n // Continue to next attempt\n }\n }\n } catch {\n // import.meta.resolve failed\n }\n\n return null;\n}\n\n/**\n * Resolves symlinks in node_modules to find the real package location\n */\nasync function resolveSymlinkedPaths(\n packageName: string,\n subPath: string,\n): Promise<string[]> {\n const packageBaseName = packageName.includes(\"/\")\n ? packageName.split(\"/\").pop()\n : packageName;\n const nodeModulesPatterns = [\n path.join(process.cwd(), \"node_modules\", packageName),\n path.join(process.cwd(), \"node_modules\", packageBaseName || packageName),\n ];\n\n const workspacePatterns: string[] = [];\n\n for (const nodeModulesPath of nodeModulesPatterns) {\n try {\n const fs = await import(\"node:fs\");\n if (fs.existsSync(nodeModulesPath)) {\n const realPath = fs.realpathSync(nodeModulesPath);\n\n workspacePatterns.push(\n path.join(realPath, \"dist\", \"node\", subPath, \"index.mjs\"),\n path.join(realPath, \"dist\", \"node\", `${subPath}.mjs`),\n path.join(realPath, \"dist\", subPath, \"index.js\"),\n path.join(realPath, \"dist\", `${subPath}.js`),\n path.join(realPath, subPath, \"index.js\"),\n path.join(realPath, `${subPath}.js`),\n );\n }\n } catch {\n // Continue to next attempt\n }\n }\n\n return workspacePatterns;\n}\n\n/**\n * Generates common workspace pattern paths\n */\nfunction getCommonWorkspacePaths(\n packageName: string,\n subPath: string,\n): string[] {\n const packageBaseName = packageName.includes(\"/\")\n ? packageName.split(\"/\").pop()\n : packageName;\n const commonRoots = [process.cwd(), path.dirname(process.cwd())];\n\n const workspacePatterns: string[] = [];\n for (const root of commonRoots) {\n workspacePatterns.push(\n path.join(\n root,\n \"packages\",\n packageBaseName || packageName,\n \"dist\",\n \"node\",\n subPath,\n \"index.mjs\",\n ),\n path.join(\n root,\n \"packages\",\n packageBaseName || packageName,\n \"dist\",\n \"node\",\n `${subPath}.mjs`,\n ),\n path.join(\n root,\n \"packages\",\n packageBaseName || packageName,\n \"dist\",\n subPath,\n \"index.js\",\n ),\n path.join(\n root,\n \"packages\",\n packageBaseName || packageName,\n \"dist\",\n `${subPath}.js`,\n ),\n );\n }\n\n return workspacePatterns;\n}\n\n/**\n * Attempts to import from a list of workspace patterns\n */\nasync function tryWorkspacePatterns<T>(patterns: string[]): Promise<T | null> {\n for (const workspacePath of patterns) {\n try {\n return await importSpecifier<T>(workspacePath);\n } catch {\n // Continue to next attempt\n }\n }\n\n return null;\n}\n\n/**\n * Attempts to resolve linked packages using various fallback strategies\n */\nexport async function resolveLinkedPackage<T>(\n packageName: string,\n subPath: string,\n): Promise<T | null> {\n // Try Node.js suggested paths first\n let result = await tryNodeSuggestedPaths<T>(packageName, subPath);\n if (result) return result;\n\n // Try import.meta.resolve\n result = await tryImportMetaResolve<T>(packageName, subPath);\n if (result) return result;\n\n // Try symlink resolution\n const symlinkPaths = await resolveSymlinkedPaths(packageName, subPath);\n result = await tryWorkspacePatterns<T>(symlinkPaths);\n if (result) return result;\n\n // Try common workspace patterns as final fallback\n const commonPaths = getCommonWorkspacePaths(packageName, subPath);\n result = await tryWorkspacePatterns<T>(commonPaths);\n if (result) return result;\n\n return null;\n}\n","import type {\n ProcessorFactoryBuilder,\n SubgraphClass,\n} from \"@powerhousedao/reactor-api\";\nimport type {\n DocumentModelModule,\n UpgradeManifest,\n} from \"@powerhousedao/shared/document-model\";\nimport { childLogger } from \"document-model\";\nimport { execSync } from \"node:child_process\";\nimport { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { resolveLinkedPackage } from \"./import-resolver.js\";\n\n// Define the expected module export structures\ntype DocumentModelsExport = Record<string, DocumentModelModule>;\ntype SubgraphsExport = Record<string, Record<string, SubgraphClass>>;\ntype ProcessorsExport = {\n processorFactory?: ProcessorFactoryBuilder;\n processorFactoryLegacy?: ProcessorFactoryBuilder;\n};\n\nconst _logger = childLogger([\"reactor-api\", \"packages/util\"]);\n\n// Error code for a package module that exists and failed to load; already logged.\nexport const PACKAGE_MODULE_FAILED = \"ERR_PACKAGE_MODULE_FAILED\";\n\nexport const installPackages = (packages: string[]): Promise<void> => {\n for (const packageName of packages) {\n execSync(`ph install ${packageName}`);\n }\n return Promise.resolve();\n};\n\nexport const readManifest = () => {\n const manifest = execSync(`ph manifest`).toString();\n return manifest;\n};\n\n/**\n * Tries to import document models from a package. This function cannot throw.\n */\nexport async function loadDocumentModels(\n packageName: string,\n): Promise<DocumentModelsExport | null> {\n return loadDependency(packageName, \"document-models\");\n}\n\n/**\n * Tries to import subgraphs from a package. This function cannot throw.\n */\nexport async function loadSubgraphs(\n packageName: string,\n): Promise<SubgraphsExport | null> {\n return loadDependency(packageName, \"subgraphs\");\n}\n\n/**\n * Tries to import processors from a package. This function cannot throw.\n */\nexport async function loadProcessors(\n packageName: string,\n): Promise<ProcessorsExport | null> {\n return loadDependency(packageName, \"processors\");\n}\n\n/**\n * Generic dependency loader - tries to import a dependency from a package. This function cannot throw.\n * Returns null if the dependency cannot be loaded.\n */\nasync function loadDependency<T = unknown>(\n packageName: string,\n subPath: string,\n): Promise<T> {\n // A local package is identified by an absolute path, which has to become a\n // file:// URL: the ESM loader reads the drive letter in a Windows path as a\n // URL scheme.\n const fullPath = path.isAbsolute(packageName)\n ? pathToFileURL(path.join(packageName, subPath)).href\n : `${packageName}/${subPath}`;\n\n // Try the standard import first\n try {\n // vite does not support this, but that's okay as we have provided the\n // vite-loader for this purpose\n\n const module = (await import(/* @vite-ignore */ fullPath)) as T;\n return module;\n } catch (e) {\n // Handle module not found errors with fallback resolution.\n // ERR_UNSUPPORTED_ESM_URL_SCHEME joins the list because a directory\n // specifier that is a plain path fails with it on Windows where POSIX\n // reports ERR_UNSUPPORTED_DIR_IMPORT.\n if (\n e instanceof Error &&\n \"code\" in e &&\n (e.code === \"ERR_MODULE_NOT_FOUND\" ||\n e.code === \"ERR_UNSUPPORTED_DIR_IMPORT\" ||\n e.code === \"ERR_UNSUPPORTED_ESM_URL_SCHEME\")\n ) {\n const result = await resolveLinkedPackage<T>(packageName, subPath);\n if (result) return result;\n }\n throw e;\n }\n}\n\n/**\n * The subgraphs a package's `powerhouse.manifest.json` declares, when the\n * manifest is reachable — which it is for a package identified by an\n * absolute path (how every local project reaches the loaders). Lets the\n * package manager warn when a manifest promises subgraphs and the loaders\n * deliver none, instead of failing silently. For a bare package name the\n * manifest would have to be resolved through the module system; until a\n * caller needs that, a bare name answers [] rather than guessing.\n */\nexport function manifestDeclaredSubgraphs(identifier: string): string[] {\n if (!path.isAbsolute(identifier)) return [];\n try {\n const raw = readFileSync(\n path.join(identifier, \"powerhouse.manifest.json\"),\n \"utf-8\",\n );\n const manifest = JSON.parse(raw) as { subgraphs?: unknown };\n if (!Array.isArray(manifest.subgraphs)) return [];\n return manifest.subgraphs\n .map((subgraph: unknown) => {\n if (typeof subgraph !== \"object\" || subgraph === null) {\n return undefined;\n }\n const { id, name } = subgraph as { id?: unknown; name?: unknown };\n return id ?? name;\n })\n .filter(\n (value): value is string =>\n typeof value === \"string\" && value.length > 0,\n );\n } catch {\n // No manifest, or an unreadable one: nothing was promised, so nothing\n // to warn about.\n return [];\n }\n}\n\nfunction isUpgradeManifest(\n value: unknown,\n): value is UpgradeManifest<readonly number[]> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"documentType\" in value &&\n \"supportedVersions\" in value &&\n \"upgrades\" in value\n );\n}\n\n/**\n * Collects upgrade manifests from a package's document-models namespace.\n * Handles both the aggregate `upgradeManifests` array export and individual\n * manifest exports; dedupes by documentType.\n */\nexport function extractUpgradeManifests(\n namespace: Record<string, unknown>,\n): UpgradeManifest<readonly number[]>[] {\n const manifests = new Map<string, UpgradeManifest<readonly number[]>>();\n const add = (value: unknown) => {\n if (isUpgradeManifest(value)) {\n manifests.set(value.documentType, value);\n }\n };\n for (const value of Object.values(namespace)) {\n if (Array.isArray(value)) {\n value.forEach(add);\n } else {\n add(value);\n }\n }\n return Array.from(manifests.values());\n}\n\n/** Calls superseded before the timer fires settle with the run that follows. */\nexport function debounce<R>(func: () => Promise<R>, delay = 250) {\n let timer: ReturnType<typeof setTimeout> | undefined;\n let waiting: {\n resolve: (value: R) => void;\n reject: (error: unknown) => void;\n }[] = [];\n\n const run = async () => {\n timer = undefined;\n const callers = waiting;\n waiting = [];\n try {\n const value = await func();\n callers.forEach((caller) => caller.resolve(value));\n } catch (error) {\n callers.forEach((caller) => caller.reject(error));\n }\n };\n\n return (immediate = false): Promise<R> => {\n clearTimeout(timer);\n return new Promise<R>((resolve, reject) => {\n waiting.push({ resolve, reject });\n if (immediate) {\n void run();\n } else {\n timer = setTimeout(() => void run(), delay);\n }\n });\n };\n}\n\nexport function isSubpath(parent: string, dir: string) {\n const relative = path.relative(parent, dir);\n return relative && !relative.startsWith(\"..\") && !path.isAbsolute(relative);\n}\n","import type { ILogger } from \"document-model\";\n\nexport type ReportError = (error: unknown) => void;\n\nexport type RunDetachedOptions = {\n logger: ILogger;\n report?: ReportError;\n};\n\n/** Logs `error` as the message's last replacement and reports it. */\nexport function reportFailure(\n { logger, report }: RunDetachedOptions,\n error: unknown,\n message: string,\n ...args: unknown[]\n): void {\n logger.error(message, ...args, error);\n try {\n report?.(error);\n } catch (reportError) {\n logger.error(\"Reporting a failure failed: @error\", reportError);\n }\n}\n\n/** Runs work nobody awaits: a failure is logged and reported, never thrown. */\nexport async function runDetached(\n label: string,\n task: () => unknown,\n options: RunDetachedOptions,\n): Promise<void> {\n try {\n await task();\n } catch (error) {\n reportFailure(options, error, \"@label failed: @error\", label);\n }\n}\n","import type {\n GqlDocument,\n GqlDriveDocument,\n GqlOperation,\n SubgraphClass,\n} from \"@powerhousedao/reactor-api\";\nimport type { DocumentDriveDocument } from \"@powerhousedao/shared/document-drive\";\nimport type {\n Operation,\n PHDocument,\n} from \"@powerhousedao/shared/document-model\";\nimport { BaseSubgraph } from \"./base-subgraph.js\";\n\nexport function isSubgraphClass(\n candidate: unknown,\n): candidate is SubgraphClass {\n if (typeof candidate !== \"function\") return false;\n\n // Walk the candidate's constructor chain. Identity first: package builds\n // keep `@powerhousedao/reactor-api` external precisely so every subgraph\n // extends this very BaseSubgraph (see nodeNeverBundle in\n // packages/shared/clis/build-config.mts). The name check is the fallback\n // for a module graph that carries its own copy — a project served by the\n // vite dev server resolves reactor-api from its own node_modules, which\n // need not be the host's instance.\n //\n // The previous version asked `isPrototypeOf` in the wrong direction\n // (whether the candidate's proto was in BaseSubgraph's chain), which\n // `Function.prototype` always satisfies — so every function passed, and\n // junk exports registered as subgraphs.\n let proto: unknown = Object.getPrototypeOf(candidate);\n while (typeof proto === \"function\") {\n if (proto === BaseSubgraph) return true;\n if (proto.name === \"BaseSubgraph\") return true;\n\n proto = Object.getPrototypeOf(proto);\n }\n\n return false;\n}\n\nexport function buildGraphqlOperations(\n operations: Operation[],\n skip: number,\n first: number,\n): GqlOperation[] {\n return operations.slice(skip, skip + first).map(buildGraphqlOperation);\n}\n\nexport function buildGraphqlOperation(operation: Operation): GqlOperation {\n const signer = operation.action.context?.signer;\n return {\n id: operation.id ?? \"\",\n type: operation.action.type,\n index: operation.index,\n timestampUtcMs: operation.timestampUtcMs,\n hash: operation.hash,\n skip: operation.skip,\n inputText:\n typeof operation.action.input === \"string\"\n ? operation.action.input\n : JSON.stringify(operation.action.input),\n error: operation.error,\n context: {\n signer: signer\n ? {\n user: signer.user,\n app: signer.app,\n signatures: signer.signatures.map((sig) =>\n Array.isArray(sig) ? sig.join(\", \") : sig,\n ),\n }\n : undefined,\n },\n };\n}\n\nexport function buildGraphQlDocument(doc: PHDocument): GqlDocument {\n // Return full state with all scopes (auth, document, global, local)\n // This matches the ReactorSubgraph pattern in adapters.ts\n const state = doc.state;\n const initialState = doc.initialState;\n // For stateJSON, use global state for backward compatibility\n const globalState = \"global\" in doc.state ? doc.state.global : {};\n return {\n id: doc.header.id,\n name: doc.header.name,\n documentType: doc.header.documentType,\n revision: doc.header.revision.global || 0,\n createdAtUtcIso: doc.header.createdAtUtcIso,\n lastModifiedAtUtcIso: doc.header.lastModifiedAtUtcIso,\n operations: [],\n stateJSON: globalState as JSON,\n state,\n initialState,\n };\n}\n\nexport function buildGraphQlDriveDocument(\n doc: DocumentDriveDocument,\n): GqlDriveDocument {\n const gqlDoc = buildGraphQlDocument(doc);\n return {\n ...gqlDoc,\n meta: {\n preferredEditor: doc.header.meta?.preferredEditor,\n },\n slug: doc.header.slug,\n state: doc.state.global,\n initialState: doc.state.global,\n };\n}\n","import type { DocumentModelModule } from \"@powerhousedao/shared/document-model\";\n\n/**\n * The one acceptance rule for a package's `document-models` module.\n *\n * The three package loaders duck-typed this independently and disagreed on\n * one case: the http loader required `documentModel` to be non-null, while\n * the import and vite loaders accepted any object merely carrying the key,\n * so an export shaped `{ documentModel: null }` registered as a model under\n * two loaders and vanished under the third. The strict rule is the correct\n * one — a module without its documentModel cannot define a document type —\n * and this predicate is now the single rule all three share, the same way\n * extractSubgraphs unified the subgraph rule.\n */\nexport function isDocumentModelModule(\n candidate: unknown,\n): candidate is DocumentModelModule {\n if (candidate === null || typeof candidate !== \"object\") return false;\n if (!(\"documentModel\" in candidate)) return false;\n const model = (candidate as { documentModel: unknown }).documentModel;\n return model !== null && model !== undefined;\n}\n\n/** Collects the document-model modules among a namespace's exports. */\nexport function extractDocumentModels(\n namespace: Record<string, unknown>,\n): DocumentModelModule[] {\n return Object.values(namespace).filter(isDocumentModelModule);\n}\n","// The pieces a package ships, located on disk for a host that never runs them.\n\n// Only the list module is ever imported here: it holds no piece code, and a\n// piece itself runs in a forked worker, handed the path this reports.\nimport { packageJsonExports } from \"@powerhousedao/shared/clis/constants\";\nimport type { ILogger } from \"document-model\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { dirname, isAbsolute, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { PackagePiece, PackagePieceEntry } from \"./types.js\";\n\n/** The sub-entry every loader asks a package for its pieces through. */\nexport const PIECES_SUBPATH = \"pieces\";\n\n// Where the node build leaves the list, read from the export map a generated\n// package ships so the build and the host cannot disagree about the path.\nexport const BUILT_PIECE_LIST = packageJsonExports[\"./pieces\"].node;\n\n/** Where a package keeps its piece sources, for telling unbuilt from absent. */\nexport const PIECE_SOURCE_LIST = join(PIECES_SUBPATH, \"index.ts\");\n\n/** The nearest enclosing package.json, which `exports` usually hides. */\nexport function packageRootOf(dir: string): string | undefined {\n let current = dir;\n while (!existsSync(join(current, \"package.json\"))) {\n const parent = dirname(current);\n if (parent === current) return undefined;\n current = parent;\n }\n return current;\n}\n\nexport interface PieceListLocation {\n /** Absolute; a declared entry is relative to it. */\n root: string;\n /** Absolute path of the list module, built or not. */\n listPath: string;\n}\n\n// Resolved from this module first, then from the host's own dependencies,\n// which is where document models are found too; the first error is the one kept.\nfunction resolvePieceList(specifier: string, hostDir: string): string {\n try {\n return fileURLToPath(import.meta.resolve(specifier));\n } catch (error) {\n try {\n return createRequire(join(hostDir, \"package.json\")).resolve(specifier);\n } catch {\n throw error;\n }\n }\n}\n\n// Where a package's piece list sits and what its entries are relative to. A\n// path identifier is its own root; a name resolves as a host would import it.\nexport function pieceListLocation(\n identifier: string,\n hostDir = process.cwd(),\n): PieceListLocation {\n if (isAbsolute(identifier)) {\n return { root: identifier, listPath: join(identifier, BUILT_PIECE_LIST) };\n }\n // Left to throw, with the ESM resolver's error codes: they're what the\n // package manager reads a miss from.\n const listPath = resolvePieceList(`${identifier}/${PIECES_SUBPATH}`, hostDir);\n const root = packageRootOf(dirname(listPath));\n if (!root) {\n throw new Error(`No package.json above ${listPath}`);\n }\n return { root, listPath };\n}\n\n// A piece's version is its package's, so it is read from the package root.\nexport function packageVersionAt(root: string): string | undefined {\n try {\n const pkg = JSON.parse(\n readFileSync(join(root, \"package.json\"), \"utf8\"),\n ) as { version?: unknown };\n return typeof pkg.version === \"string\" && pkg.version !== \"\"\n ? pkg.version\n : undefined;\n } catch {\n return undefined;\n }\n}\n\n// A declared piece counts only once its code is on disk: one nobody built is\n// reported rather than dropped, because a block type names it either way.\nexport function locatePieces(\n declared: readonly PackagePiece[],\n context: {\n root: string;\n identifier: string;\n logger: ILogger;\n version: string;\n },\n): PackagePieceEntry[] {\n const { root, identifier, logger, version } = context;\n const located: PackagePieceEntry[] = [];\n for (const piece of declared) {\n const where = piece.entry ?? piece.bundle;\n if (typeof where !== \"string\" || where === \"\") {\n // Every name goes through a logger value: `@`-prefixed tokens are\n // substituted, so a scoped one printed inline comes out as null/pack.\n logger.warn(\n \"Piece @piece of @pkg declares neither a bundle nor an entry\",\n piece.name,\n identifier,\n );\n continue;\n }\n const path = isAbsolute(where) ? where : join(root, where);\n const present = piece.entry\n ? existsSync(path)\n : existsSync(join(path, \"package.json\"));\n if (!present) {\n logger.warn(\n \"Piece @piece of @pkg is declared but not built at @path\",\n piece.name,\n identifier,\n path,\n );\n continue;\n }\n located.push({\n name: piece.name,\n version,\n ...(piece.entry ? { entryPath: path } : { bundleDir: path }),\n });\n }\n return located;\n}\n\n// A package's `pieces` array, however the list module was obtained.\nfunction declaredPieces(\n module: unknown,\n identifier: string,\n logger: ILogger,\n): PackagePiece[] | undefined {\n const namespace = (module ?? {}) as { pieces?: unknown; default?: unknown };\n const declared = namespace.pieces ?? namespace.default;\n if (!Array.isArray(declared)) {\n logger.warn(\n 'The pieces list of @pkg exports no \"pieces\" array; it contributes none',\n identifier,\n );\n return undefined;\n }\n return declared as PackagePiece[];\n}\n\n// The same list, served by a registry rather than read off a disk. Nothing is\n// checked for existence here: the CDN is asked when the piece is run.\n\n// `entry` is relative to the package root while the CDN serves beneath\n// `dist/`, so that prefix comes off before the base is applied.\nexport function piecesFromCdnList(\n module: unknown,\n baseUrl: string,\n identifier: string,\n logger: ILogger,\n version: string,\n): PackagePieceEntry[] {\n const declared = declaredPieces(module, identifier, logger);\n if (!declared) return [];\n const located: PackagePieceEntry[] = [];\n for (const piece of declared) {\n const where = piece.entry ?? piece.bundle;\n if (typeof where !== \"string\" || where === \"\") {\n logger.warn(\n \"Piece @piece of @pkg declares neither a bundle nor an entry\",\n piece.name,\n identifier,\n );\n continue;\n }\n located.push({\n name: piece.name,\n version,\n entryUrl: `${baseUrl}${where.replace(/^dist\\/node\\/pieces\\//, \"\")}`,\n });\n }\n return located;\n}\n\n// What a loaded list module contributes. A module without a `pieces` array is\n// not a list, and saying so beats reporting the package as shipping none.\nexport function piecesFromListModule(\n module: unknown,\n context: { root: string; identifier: string; logger: ILogger },\n): PackagePieceEntry[] {\n const namespace = (module ?? {}) as { pieces?: unknown; default?: unknown };\n const declared = namespace.pieces ?? namespace.default;\n if (!Array.isArray(declared)) {\n context.logger.warn(\n 'The pieces list of @pkg exports no \"pieces\" array; it contributes none',\n context.identifier,\n );\n return [];\n }\n const version = packageVersionAt(context.root);\n if (!version) {\n context.logger.warn(\n \"@pkg has no version in @root/package.json, and a piece takes its package's version; its pieces contribute none\",\n context.identifier,\n context.root,\n );\n return [];\n }\n return locatePieces(declared as PackagePiece[], { ...context, version });\n}\n","import type { SubgraphClass } from \"@powerhousedao/reactor-api\";\nimport { isSubgraphClass } from \"../graphql/utils.js\";\n\n/**\n * The one acceptance rule for a package's `subgraphs` module.\n *\n * All three package loaders (vite, import, http) consume the same generated\n * `subgraphs/index` file, and each used to apply its own rule — the vite\n * loader required a namespace whose alias equalled the class name inside it,\n * the http loader took any function one level deep, and the import loader\n * took every nested value. An export that registered under one loader could\n * silently vanish under another (the codegen-does-not-register-subgraphs\n * report). This is now the single rule they all share:\n *\n * - an export that is itself a subgraph class is accepted (named or default\n * export of the class);\n * - any subgraph class among the values of an exported object is accepted\n * (a `export * as Alias from ...` namespace under any alias, or a\n * default-exported object of classes);\n * - everything else — constants, configs, functions and classes that do not\n * extend BaseSubgraph — is dropped.\n *\n * Codegen emits `export * as <ClassName> from \"./<dir>/index.js\"`\n * (makeSubgraphsIndexFile in packages/codegen), which the namespace branch\n * accepts regardless of the alias; hand-written packages may re-export a\n * class directly, which the direct branch accepts. A class reached through\n * both branches is returned once.\n */\nexport function extractSubgraphs(\n namespace: Record<string, unknown>,\n): SubgraphClass[] {\n const found: SubgraphClass[] = [];\n const add = (candidate: unknown) => {\n if (isSubgraphClass(candidate) && !found.includes(candidate)) {\n found.push(candidate);\n }\n };\n for (const value of Object.values(namespace)) {\n add(value);\n if (value !== null && typeof value === \"object\") {\n for (const inner of Object.values(value)) {\n add(inner);\n }\n }\n }\n return found;\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAOA,IAAa,iBAAb,cAAoC,aAAa;CAC/C,YAAY,SAAS,IAAI;EACvB,MAAM,OAAO,0BAA0B;EACvC,MAAM,GAAG,OAAO,SAAS,IAAI,WAAW,MAAM,EAC5C,YAAY,EAAE,MAAM,YAAY,EAClC,CAAC;CACH;AACF;;AAGA,IAAa,8BAAb,cAAiD,aAAa;CAC5D,YAAY,SAAS,IAAI;EACvB,MAAM,OAAO,0BAA0B;EACvC,MAAM,GAAG,OAAO,SAAS,IAAI,WAAW,MAAM,EAC5C,YAAY,EAAE,MAAM,kBAAkB,EACxC,CAAC;CACH;AACF;;;;;;;;;;;AAYA,IAAa,iCAAb,cAAoD,aAAa;CAC/D,cAAc;EACZ,MACE,sIAEA,EAAE,YAAY,EAAE,MAAM,8BAA8B,EAAE,CACxD;CACF;AACF;;;;;;;;;;;;;;;;;;;;AAqBA,IAAa,gCAAb,cAAmD,aAAa;CAC9D,YAAY,QAAgB;EAC1B,MAAM,sCAAsC,UAAU,EACpD,YAAY,EACV,MAAM,gCAAgC,yBACxC,EACF,CAAC;CACH;AACF;;;;;AAMA,IAAa,0BAAb,cAA6C,aAAa;CACxD,YAAY,OAAgB;EAC1B,MAAM,+DAA+D;GACnE,eAAe,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;GACvE,YAAY,EACV,MAAM,gCAAgC,mBACxC;EACF,CAAC;CACH;AACF;;;;;;;;AC7DA,IAAa,2BAAb,MAAa,yBAAyB;C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ACd,WACiB;CACjB,MAAM,QAAyB,CAAC;CAChC,MAAM,OAAO,cAAuB;EAClC,IAAI,gBAAgB,SAAS,KAAK,CAAC,MAAM,SAAS,SAAS,GACzD,MAAM,KAAK,SAAS;CAExB;CACA,KAAK,MAAM,SAAS,OAAO,OAAO,SAAS,GAAG;EAC5C,IAAI,KAAK;EACT,IAAI,UAAU,QAAQ,OAAO,UAAU,UACrC,KAAK,MAAM,SAAS,OAAO,OAAO,KAAK,GACrC,IAAI,KAAK;CAGf;CACA,OAAO;AACT","debug_id":"60bff0fd-90c1-5fac-ab7d-2a49e4b9f4c3"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"types-BEpxtyKW.d.mts","names":[],"sources":["../src/utils/detached.ts","../src/packages/types.ts"],"mappings":";;;;KAEY,eAAe;KAEf;EACV,QAAQ;EACR,SAAS;;;iBAIK,gBACZ,QAAQ,UAAU,oBACpB,gBACA,oBACG;;iBAWiB,YACpB,eACA,qBACA,SAAS,qBACR;;;UChBc;EACf;;EAEA;;EAEA;;UAQe;EACf;;EAEA;EACA;EACA;EACA;;UAGe;EACf;EACA,mBACE,oBACA,sBACC,QAAQ;;;;;EAKX,sBACE,qBACC,QAAQ;EACX,cACE,oBACA,sBACC,QAAQ;EACX,eACE,oBACA,sBACC,QAAQ;;EAEX,WACE,oBACA,sBACC,QAAQ;;UAGI;EACf;;UAGe,mCAAmC;EAClD,wBACE,oBACA,UAAU,gBAAgB,gCAC1B,UAAU;EAEZ,mBACE,oBACA,UAAU,WAAW,0BACrB,UAAU;EAEZ,oBACE,oBACA,UAAU,YAAY,yCACtB,UAAU;EAEZ,gBACE,oBACA,UAAU,QAAQ,8BAClB,UAAU;;UAIG;EACf,uBACE,UAAU,gBAAgB,eAAe;;EAG3C,WAAW;;EAEX,cAAc;;KAGJ;EACV,SAAS;;KAGC;EACV;EACA;EACA,cAAc;;KAWJ;EACV,gBAAgB;EAChB,kBAAkB;EAClB,WAAW,YAAY;EACvB,YAAY,YAAY;EACxB,QAAQ,YAAY;;UAKL;EACf,aAAa,YAAY;EACzB,eACE,UAAU,QAAQ,YAAY"}
|