document-model 6.2.3-dev.93 → 6.2.3-dev.95

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.
@@ -1 +1 @@
1
- {"version":3,"file":"tooling.mjs","names":["schema","schema","schema","schema","schema","schema","BUILT_IN_SCALARS","CATALOG_SCALARS","typeReference","enumValue","namedType","examples","checkArtifact"],"sources":["../src/definition/kernel/hashes.ts","../src/definition/kernel/primitives.ts","../src/definition/kernel/diagnostics.ts","../src/scalars/types.ts","../src/scalars/define-catalog-scalar.ts","../src/scalars/scalar-literal.ts","../src/scalars/declarations/unknown.ts","../src/scalars/declarations/date-time.ts","../src/scalars/pattern.ts","../src/scalars/declarations/address.ts","../src/scalars/declarations/attachment-ref.ts","../src/scalars/coercion.ts","../src/scalars/declarations/amounts.ts","../src/scalars/declarations/amount-tokens.ts","../src/scalars/declarations/ethereum-address.ts","../src/scalars/declarations/email-address.ts","../src/scalars/declarations/amount-percentage.ts","../src/scalars/declarations/date.ts","../src/scalars/declarations/url.ts","../src/scalars/declarations/amount-money.ts","../src/scalars/declarations/olabel.ts","../src/scalars/declarations/currency.ts","../src/scalars/declarations/phid.ts","../src/scalars/declarations/oid.ts","../src/scalars/declarations/amount-fiat.ts","../src/scalars/declarations/amount-currency.ts","../src/scalars/declarations/amount-crypto.ts","../src/scalars/declarations/amount.ts","../src/scalars/declarations/upload.ts","../src/scalars/declarations/json-object.ts","../src/scalars/catalog.ts","../src/definition/kernel/diagnostic-collector.ts","../src/definition/kernel/data-properties.ts","../src/definition/kernel/diagnostic-codes.ts","../src/definition/kernel/graphql-ast.ts","../src/definition/dsl/diagnostic-codes.ts","../src/definition/compiler/diagnostic-codes.ts","../src/definition/compiler/wire-shape.ts","../src/definition/model/diagnostic-codes.ts","../src/definition/tooling/diagnostic-codes.ts","../src/definition/tooling/adapters/code-first-document-model-source-adapter.ts","../src/definition/tooling/definition-source-resolution.ts","../src/definition/tooling/structured-diagnostics.ts","../src/definition/tooling/definition-source-loader.ts","../src/definition/compiler/naming.ts","../src/definition/tooling/check/diagnostic-codes.ts","../src/definition/tooling/report/served-specification.ts","../src/definition/tooling/check/checks/duplicate-identities.ts","../src/definition/tooling/graphql/parse-schema.ts","../src/definition/tooling/check/checks/graphql-schema.ts","../src/definition/tooling/report/logical-collisions.ts","../src/definition/tooling/check/checks/logical-collisions.ts","../src/definition/tooling/check/checks/package-scalar-names.ts","../src/definition/compiler/segments.ts","../src/definition/tooling/graphql/ast-to-structured.ts","../src/definition/tooling/check/stored-specification.ts","../src/definition/tooling/check/checks/retained-serialization.ts","../src/definition/tooling/check/checks/stored-materialization.ts","../src/definition/tooling/check/checks/unregistered-definitions.ts","../src/definition/tooling/report/status.ts","../src/definition/tooling/check/check-project-definitions.ts","../src/definition/tooling/inspect/diagnostic-codes.ts","../src/definition/tooling/inspect/inspect-project-definitions.ts","../src/definition/tooling/schema-first/project-scalars.ts","../src/definition/compiler/stored-scalar.ts","../src/definition/tooling/schema-first/schema-first-document-model-module-adapter.ts","../src/definition/tooling/schema-first/stored-locations.ts","../src/definition/tooling/schema-first/stored-models.ts","../src/definition/tooling/project/unregistered-definitions.ts","../src/definition/tooling/project/project-definitions.ts"],"sourcesContent":["import type { Sha256Digest } from \"@powerhousedao/shared/document-model\";\n\n// Hand-written so Node and browser builds derive the same digests and IDs\n// synchronously, with no host crypto.\n\nfunction rotateRight(value: number, shift: number): number {\n return ((value >>> shift) | (value << (32 - shift))) >>> 0;\n}\n\nconst SHA256_CONSTANTS = new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,\n 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,\n 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,\n 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,\n 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,\n 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,\n 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,\n 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,\n 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,\n]);\n\nexport function sha256(value: string): Sha256Digest {\n const bytes = new TextEncoder().encode(value);\n const paddedLength = Math.ceil((bytes.length + 9) / 64) * 64;\n const input = new Uint8Array(paddedLength);\n input.set(bytes);\n input[bytes.length] = 0x80;\n const view = new DataView(input.buffer);\n const bitLength = BigInt(bytes.length) * 8n;\n view.setUint32(paddedLength - 8, Number(bitLength >> 32n), false);\n view.setUint32(paddedLength - 4, Number(bitLength & 0xffff_ffffn), false);\n\n const state = new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c,\n 0x1f83d9ab, 0x5be0cd19,\n ]);\n const words = new Uint32Array(64);\n\n for (let offset = 0; offset < paddedLength; offset += 64) {\n for (let index = 0; index < 16; index += 1) {\n words[index] = view.getUint32(offset + index * 4, false);\n }\n for (let index = 16; index < 64; index += 1) {\n const previous15 = words[index - 15];\n const previous2 = words[index - 2];\n const sigma0 =\n rotateRight(previous15, 7) ^\n rotateRight(previous15, 18) ^\n (previous15 >>> 3);\n const sigma1 =\n rotateRight(previous2, 17) ^\n rotateRight(previous2, 19) ^\n (previous2 >>> 10);\n words[index] =\n (words[index - 16] + sigma0 + words[index - 7] + sigma1) >>> 0;\n }\n\n let a = state[0];\n let b = state[1];\n let c = state[2];\n let d = state[3];\n let e = state[4];\n let f = state[5];\n let g = state[6];\n let h = state[7];\n\n for (let index = 0; index < 64; index += 1) {\n const sigma1 =\n rotateRight(e, 6) ^ rotateRight(e, 11) ^ rotateRight(e, 25);\n const choice = (e & f) ^ (~e & g);\n const temporary1 =\n (h + sigma1 + choice + SHA256_CONSTANTS[index] + words[index]) >>> 0;\n const sigma0 =\n rotateRight(a, 2) ^ rotateRight(a, 13) ^ rotateRight(a, 22);\n const majority = (a & b) ^ (a & c) ^ (b & c);\n const temporary2 = (sigma0 + majority) >>> 0;\n h = g;\n g = f;\n f = e;\n e = (d + temporary1) >>> 0;\n d = c;\n c = b;\n b = a;\n a = (temporary1 + temporary2) >>> 0;\n }\n\n state[0] = (state[0] + a) >>> 0;\n state[1] = (state[1] + b) >>> 0;\n state[2] = (state[2] + c) >>> 0;\n state[3] = (state[3] + d) >>> 0;\n state[4] = (state[4] + e) >>> 0;\n state[5] = (state[5] + f) >>> 0;\n state[6] = (state[6] + g) >>> 0;\n state[7] = (state[7] + h) >>> 0;\n }\n\n const hex = [...state]\n .map((word) => word.toString(16).padStart(8, \"0\"))\n .join(\"\");\n return `sha256:${hex}`;\n}\n\nconst UUID_PATTERN =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nfunction uuidBytes(uuid: string): Uint8Array {\n if (!UUID_PATTERN.test(uuid)) {\n throw new TypeError(\n `UUID namespace ${JSON.stringify(uuid)} is not canonical.`,\n );\n }\n const hex = uuid.replaceAll(\"-\", \"\");\n return Uint8Array.from({ length: 16 }, (_, index) =>\n Number.parseInt(hex.slice(index * 2, index * 2 + 2), 16),\n );\n}\n\nfunction formatUuid(bytes: Uint8Array): string {\n const hex = [...bytes]\n .map((byte) => byte.toString(16).padStart(2, \"0\"))\n .join(\"\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;\n}\n\nexport function uuidV5(namespace: string, name: string): string {\n const namespaceBytes = uuidBytes(namespace);\n const nameBytes = new TextEncoder().encode(name);\n const input = new Uint8Array(namespaceBytes.length + nameBytes.length);\n input.set(namespaceBytes);\n input.set(nameBytes, namespaceBytes.length);\n const digest = sha1(input).slice(0, 16);\n digest[6] = (digest[6] & 0x0f) | 0x50;\n digest[8] = (digest[8] & 0x3f) | 0x80;\n return formatUuid(digest);\n}\n\nfunction rotateLeft(value: number, shift: number): number {\n return ((value << shift) | (value >>> (32 - shift))) >>> 0;\n}\n\nfunction sha1(bytes: Uint8Array): Uint8Array {\n const paddedLength = Math.ceil((bytes.length + 9) / 64) * 64;\n const input = new Uint8Array(paddedLength);\n input.set(bytes);\n input[bytes.length] = 0x80;\n const view = new DataView(input.buffer);\n const bitLength = BigInt(bytes.length) * 8n;\n view.setUint32(paddedLength - 8, Number(bitLength >> 32n), false);\n view.setUint32(paddedLength - 4, Number(bitLength & 0xffff_ffffn), false);\n\n const state = new Uint32Array([\n 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0,\n ]);\n const words = new Uint32Array(80);\n\n for (let offset = 0; offset < paddedLength; offset += 64) {\n for (let index = 0; index < 16; index += 1) {\n words[index] = view.getUint32(offset + index * 4, false);\n }\n for (let index = 16; index < 80; index += 1) {\n words[index] = rotateLeft(\n words[index - 3] ^\n words[index - 8] ^\n words[index - 14] ^\n words[index - 16],\n 1,\n );\n }\n\n let a = state[0];\n let b = state[1];\n let c = state[2];\n let d = state[3];\n let e = state[4];\n\n for (let index = 0; index < 80; index += 1) {\n let f: number;\n let k: number;\n if (index < 20) {\n f = (b & c) | (~b & d);\n k = 0x5a827999;\n } else if (index < 40) {\n f = b ^ c ^ d;\n k = 0x6ed9eba1;\n } else if (index < 60) {\n f = (b & c) | (b & d) | (c & d);\n k = 0x8f1bbcdc;\n } else {\n f = b ^ c ^ d;\n k = 0xca62c1d6;\n }\n const next = (rotateLeft(a, 5) + f + e + k + words[index]) >>> 0;\n e = d;\n d = c;\n c = rotateLeft(b, 30);\n b = a;\n a = next;\n }\n\n state[0] = (state[0] + a) >>> 0;\n state[1] = (state[1] + b) >>> 0;\n state[2] = (state[2] + c) >>> 0;\n state[3] = (state[3] + d) >>> 0;\n state[4] = (state[4] + e) >>> 0;\n }\n\n const digest = new Uint8Array(20);\n const digestView = new DataView(digest.buffer);\n state.forEach((word, index) => {\n digestView.setUint32(index * 4, word, false);\n });\n return digest;\n}\n","import type { Sha256Digest } from \"@powerhousedao/shared/document-model\";\nimport { sha256 } from \"./hashes.js\";\n\nfunction memberPath(parent: string, key: string | number): string {\n if (typeof key === \"number\") {\n return `${parent}[${key}]`;\n }\n return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key)\n ? `${parent}.${key}`\n : `${parent}[${JSON.stringify(key)}]`;\n}\n\nfunction encodeProperty(\n descriptor: PropertyDescriptor,\n path: string,\n ancestors: Set<object>,\n): string {\n if (!(\"value\" in descriptor)) {\n throw new TypeError(`${path} must be a data property, not an accessor.`);\n }\n if (descriptor.enumerable !== true) {\n throw new TypeError(`${path} must be enumerable.`);\n }\n return encode(descriptor.value, path, ancestors);\n}\n\nfunction encodeArray(\n value: readonly unknown[],\n path: string,\n ancestors: Set<object>,\n): string {\n if (Object.getPrototypeOf(value) !== Array.prototype) {\n throw new TypeError(`${path} must be a plain array.`);\n }\n for (const key of Reflect.ownKeys(value)) {\n if (key === \"length\") {\n continue;\n }\n if (typeof key === \"symbol\") {\n throw new TypeError(`${path} must not have symbol keys.`);\n }\n if (!/^(?:0|[1-9][0-9]*)$/.test(key) || Number(key) >= value.length) {\n throw new TypeError(\n `${path} must not have a non-index property ${JSON.stringify(key)}.`,\n );\n }\n }\n const members: string[] = [];\n for (let index = 0; index < value.length; index += 1) {\n const descriptor = Object.getOwnPropertyDescriptor(value, index);\n if (descriptor === undefined) {\n throw new TypeError(\n `${memberPath(path, index)} must not be an array hole.`,\n );\n }\n members.push(\n encodeProperty(descriptor, memberPath(path, index), ancestors),\n );\n }\n return `[${members.join(\",\")}]`;\n}\n\nfunction encodeObject(\n value: object,\n path: string,\n ancestors: Set<object>,\n): string {\n const prototype: unknown = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) {\n throw new TypeError(`${path} must be a plain object.`);\n }\n const keys: string[] = [];\n for (const key of Reflect.ownKeys(value)) {\n if (typeof key === \"symbol\") {\n throw new TypeError(`${path} must not have symbol keys.`);\n }\n keys.push(key);\n }\n keys.sort(compareCodeUnits);\n const members: string[] = [];\n for (const key of keys) {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor === undefined) {\n throw new TypeError(`${memberPath(path, key)} must be an own property.`);\n }\n members.push(\n `${JSON.stringify(key)}:${encodeProperty(descriptor, memberPath(path, key), ancestors)}`,\n );\n }\n return `{${members.join(\",\")}}`;\n}\n\nfunction encode(value: unknown, path: string, ancestors: Set<object>): string {\n switch (typeof value) {\n case \"string\":\n case \"boolean\":\n return JSON.stringify(value);\n case \"number\":\n if (Number.isFinite(value)) {\n return JSON.stringify(value);\n }\n throw new TypeError(`${path} must be a finite number.`);\n case \"object\": {\n if (value === null) {\n return \"null\";\n }\n if (ancestors.has(value)) {\n throw new TypeError(`${path} must not contain a cycle.`);\n }\n ancestors.add(value);\n const encoded = Array.isArray(value)\n ? encodeArray(value, path, ancestors)\n : encodeObject(value, path, ancestors);\n ancestors.delete(value);\n return encoded;\n }\n default:\n throw new TypeError(\n `${path} must be a JSON value, received ${typeof value}.`,\n );\n }\n}\n\nexport function canonicalJson(value: unknown): string {\n return encode(value, \"$\", new Set());\n}\n\nexport function canonicalDigest(value: unknown): Sha256Digest {\n return sha256(canonicalJson(value));\n}\n\nexport function compareCodeUnits(a: string, b: string): -1 | 0 | 1 {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\nconst DIGIT_0 = 48;\nconst DIGIT_9 = 57;\n\nfunction isDigit(code: number): boolean {\n return DIGIT_0 <= code && code <= DIGIT_9;\n}\n\n/**\n * graphql-js's `naturalCompare`, which `lexicographicSortSchema` sorts a\n * generated schema with: runs of digits compare as numbers, so `item2`\n * precedes `item10`. Copied, not imported, so a model never loads `graphql`.\n */\nexport function compareGeneratedOrder(a: string, b: string): number {\n let aIndex = 0;\n let bIndex = 0;\n while (aIndex < a.length && bIndex < b.length) {\n let aChar = a.charCodeAt(aIndex);\n let bChar = b.charCodeAt(bIndex);\n if (isDigit(aChar) && isDigit(bChar)) {\n let aNumber = 0;\n do {\n ++aIndex;\n aNumber = aNumber * 10 + aChar - DIGIT_0;\n aChar = a.charCodeAt(aIndex);\n } while (isDigit(aChar) && aNumber > 0);\n let bNumber = 0;\n do {\n ++bIndex;\n bNumber = bNumber * 10 + bChar - DIGIT_0;\n bChar = b.charCodeAt(bIndex);\n } while (isDigit(bChar) && bNumber > 0);\n if (aNumber !== bNumber) return aNumber < bNumber ? -1 : 1;\n } else {\n if (aChar !== bChar) return aChar < bChar ? -1 : 1;\n ++aIndex;\n ++bIndex;\n }\n }\n return a.length - b.length;\n}\n\nexport const EMPTY_INPUT_FIELD_NAME = \"_empty\";\n\nexport function isGraphQLName(value: unknown): value is string {\n return typeof value === \"string\" && /^[_A-Za-z][_0-9A-Za-z]*$/.test(value);\n}\n\nexport function isAuthoredSchemaName(value: unknown): value is string {\n return isGraphQLName(value) && !value.startsWith(\"__\");\n}\n\nexport function isEnumValueName(value: unknown): value is string {\n return (\n isAuthoredSchemaName(value) &&\n value !== \"true\" &&\n value !== \"false\" &&\n value !== \"null\"\n );\n}\n\nexport function isNFC(value: string): boolean {\n return value.normalize(\"NFC\") === value;\n}\n","import type {\n DefinitionDiagnostic,\n DefinitionDiagnosticPhase,\n DefinitionDiagnosticSeverity,\n DefinitionPath,\n DefinitionRef,\n DefinitionRelatedLocation,\n DefinitionSource,\n} from \"@powerhousedao/shared/document-model\";\nimport { compareCodeUnits } from \"./primitives.js\";\n\nexport type DiagnosticCode = `PH-${string}`;\n\ntype DiagnosticCodeEntry = {\n readonly severity: DefinitionDiagnosticSeverity;\n readonly phase: DefinitionDiagnosticPhase;\n readonly meaning: string;\n};\n\nconst MAX_SUMMARY_CODE_POINTS = 512;\n\nexport function capCodePoints(\n value: string,\n max: number = MAX_SUMMARY_CODE_POINTS,\n): string {\n const points = [...value];\n const limit = Math.max(0, max);\n return points.length <= limit ? value : points.slice(0, limit).join(\"\");\n}\n\nexport type DefinitionDiagnosticInput<TCode extends string = DiagnosticCode> = {\n readonly code: TCode;\n readonly path: DefinitionPath;\n readonly message: string;\n readonly repair: string;\n readonly source?: DefinitionSource;\n readonly definition?: DefinitionRef;\n readonly expected?: string;\n readonly received?: string;\n readonly related?: readonly DefinitionRelatedLocation[];\n};\n\nfunction copySource(source: DefinitionSource): DefinitionSource {\n return {\n specifier: source.specifier,\n ...(source.exportPath !== undefined && {\n exportPath: [...source.exportPath],\n }),\n };\n}\n\nfunction copyDefinitionRef(definition: DefinitionRef): DefinitionRef {\n return {\n kind: definition.kind,\n key: definition.key,\n ...(definition.version !== undefined && { version: definition.version }),\n };\n}\n\nfunction createDiagnostic(\n input: DefinitionDiagnosticInput,\n { severity, phase }: DiagnosticCodeEntry,\n): DefinitionDiagnostic {\n return {\n code: input.code,\n severity,\n phase,\n ...(input.source !== undefined && { source: copySource(input.source) }),\n ...(input.definition !== undefined && {\n definition: copyDefinitionRef(input.definition),\n }),\n path: [...input.path],\n message: input.message,\n ...(input.expected !== undefined && {\n expected: capCodePoints(input.expected),\n }),\n ...(input.received !== undefined && {\n received: capCodePoints(input.received),\n }),\n repair: input.repair,\n ...(input.related !== undefined && {\n related: input.related.map((location) => ({\n ...(location.source !== undefined && {\n source: copySource(location.source),\n }),\n path: [...location.path],\n message: location.message,\n })),\n }),\n };\n}\n\nexport function describeReceived(value: unknown): string {\n if (value === null) return \"null\";\n try {\n return Array.isArray(value) ? \"array\" : typeof value;\n } catch {\n return \"inspection-failed\";\n }\n}\n\n/** The codes one layer emits, and the builders that fill in each code's severity and phase. */\nexport type DiagnosticCatalog<TCode extends DiagnosticCode> = {\n readonly codes: { readonly [K in TCode]: DiagnosticCodeEntry };\n create(input: DefinitionDiagnosticInput<TCode>): DefinitionDiagnostic;\n fail(input: DefinitionDiagnosticInput<TCode>): never;\n};\n\n/**\n * A layer's catalog: its own codes plus the codes of the catalog below it,\n * which already holds every lower layer's codes. A code keeps the meaning its\n * owning layer gave it, so an own code the lower catalog declares is refused.\n */\nexport function defineDiagnosticCatalog<\n TOwn extends DiagnosticCode = never,\n TLower extends DiagnosticCode = never,\n>(\n own: { readonly [K in TOwn]: DiagnosticCodeEntry } & {\n readonly [K in NoInfer<TLower>]?: never;\n },\n lower?: DiagnosticCatalog<TLower>,\n): DiagnosticCatalog<TOwn | TLower> {\n const lowerCodes: Readonly<Record<string, DiagnosticCodeEntry>> =\n lower?.codes ?? {};\n const ownEntries = Object.entries<DiagnosticCodeEntry>(own).map(\n ([code, entry]) => [code, Object.freeze({ ...entry })] as const,\n );\n const redefined = ownEntries\n .map(([code]) => code)\n .filter((code) => Object.hasOwn(lowerCodes, code));\n if (redefined.length > 0) {\n throw new TypeError(\n `Diagnostic code ${redefined.join(\", \")} is already declared by a lower layer.`,\n );\n }\n const codes = Object.freeze({\n ...lowerCodes,\n ...Object.fromEntries(ownEntries),\n }) as { readonly [K in TOwn | TLower]: DiagnosticCodeEntry };\n const create = (input: DefinitionDiagnosticInput<TOwn | TLower>) =>\n createDiagnostic(input, codes[input.code]);\n return Object.freeze({\n codes,\n create,\n fail(input: DefinitionDiagnosticInput<TOwn | TLower>): never {\n throw new DefinitionError([create(input)]);\n },\n });\n}\n\ntype Ordering = -1 | 0 | 1;\n\nfunction compareNumbers(a: number, b: number): Ordering {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\nfunction compareOptional<T>(\n a: T | undefined,\n b: T | undefined,\n compare: (x: T, y: T) => Ordering,\n): Ordering {\n if (a === undefined) return b === undefined ? 0 : -1;\n if (b === undefined) return 1;\n return compare(a, b);\n}\n\nfunction compareLists<T>(\n a: readonly T[],\n b: readonly T[],\n compare: (x: T, y: T) => Ordering,\n): Ordering {\n const shared = Math.min(a.length, b.length);\n for (let index = 0; index < shared; index += 1) {\n const result = compare(a[index], b[index]);\n if (result !== 0) return result;\n }\n return compareNumbers(a.length, b.length);\n}\n\nfunction comparePathSegments(a: string | number, b: string | number): Ordering {\n if (typeof a === \"number\") {\n return typeof b === \"number\" ? compareNumbers(a, b) : -1;\n }\n if (typeof b === \"number\") return 1;\n return compareCodeUnits(a, b);\n}\n\nexport function compareDefinitionPaths(\n a: DefinitionPath,\n b: DefinitionPath,\n): Ordering {\n return compareLists(a, b, comparePathSegments);\n}\n\nfunction compareSources(a: DefinitionSource, b: DefinitionSource): Ordering {\n const specifier = compareCodeUnits(a.specifier, b.specifier);\n if (specifier !== 0) return specifier;\n return compareOptional(a.exportPath, b.exportPath, (x, y) =>\n compareLists(x, y, compareCodeUnits),\n );\n}\n\nfunction compareDefinitionRefs(a: DefinitionRef, b: DefinitionRef): Ordering {\n const kind = compareCodeUnits(a.kind, b.kind);\n if (kind !== 0) return kind;\n const key = compareCodeUnits(a.key, b.key);\n if (key !== 0) return key;\n return compareOptional(a.version, b.version, compareNumbers);\n}\n\nexport function compareDefinitionDiagnostics(\n a: DefinitionDiagnostic,\n b: DefinitionDiagnostic,\n): Ordering {\n const source = compareOptional(a.source, b.source, compareSources);\n if (source !== 0) return source;\n const definition = compareOptional(\n a.definition,\n b.definition,\n compareDefinitionRefs,\n );\n if (definition !== 0) return definition;\n const path = compareDefinitionPaths(a.path, b.path);\n if (path !== 0) return path;\n return compareCodeUnits(a.code, b.code);\n}\n\nexport function sortDefinitionDiagnostics(\n diagnostics: readonly DefinitionDiagnostic[],\n): readonly DefinitionDiagnostic[] {\n return [...diagnostics].sort(compareDefinitionDiagnostics);\n}\n\nfunction formatPointer(path: DefinitionPath): string {\n if (path.length === 0) return \"(root)\";\n return path\n .map(\n (segment) =>\n `/${String(segment).replaceAll(\"~\", \"~0\").replaceAll(\"/\", \"~1\")}`,\n )\n .join(\"\");\n}\n\nfunction formatSource(source: DefinitionSource | undefined): string {\n if (source === undefined) return \"(no source)\";\n const exportPath = source.exportPath ?? [];\n return exportPath.length === 0\n ? source.specifier\n : `${source.specifier}#${formatPointer(exportPath)}`;\n}\n\nfunction formatDefinitionRef(definition: DefinitionRef | undefined): string {\n if (definition === undefined) return \"\";\n const version =\n definition.version === undefined ? \"\" : `@${definition.version}`;\n return ` ${definition.kind} ${definition.key}${version}`;\n}\n\nfunction oneLine(value: string): string {\n return value.replace(/\\s+/g, \" \");\n}\n\n/** @experimental One line: code, severity and phase, location, message, expected, received, related and repair. */\nexport function formatDefinitionDiagnostic(\n diagnostic: DefinitionDiagnostic,\n): string {\n const where = `${formatSource(diagnostic.source)}${formatDefinitionRef(diagnostic.definition)} ${formatPointer(diagnostic.path)}`;\n const expected =\n diagnostic.expected === undefined\n ? \"\"\n : ` Expected: ${oneLine(diagnostic.expected)}`;\n const received =\n diagnostic.received === undefined\n ? \"\"\n : ` Received: ${oneLine(diagnostic.received)}`;\n const related = (diagnostic.related ?? [])\n .map(\n (location) =>\n ` Related: ${formatSource(location.source)} ${formatPointer(location.path)}: ${oneLine(location.message)}`,\n )\n .join(\"\");\n return `${diagnostic.code} [${diagnostic.severity}/${diagnostic.phase}] ${where}: ${oneLine(diagnostic.message)}${expected}${received}${related} Repair: ${oneLine(diagnostic.repair)}`;\n}\n\n/**\n * @experimental Thrown when a code-first declaration is refused. `diagnostics`\n * holds every problem found, sorted, each with its code, path and repair.\n */\nexport class DefinitionError extends Error {\n readonly diagnostics: readonly DefinitionDiagnostic[];\n\n constructor(\n diagnostics: readonly [DefinitionDiagnostic, ...DefinitionDiagnostic[]],\n ) {\n if (diagnostics.length === 0) {\n throw new TypeError(\"DefinitionError requires at least one diagnostic.\");\n }\n const sorted = sortDefinitionDiagnostics(diagnostics);\n const noun = sorted.length === 1 ? \"diagnostic\" : \"diagnostics\";\n super(\n [\n `Definition failed with ${sorted.length} ${noun}:`,\n ...sorted.map(formatDefinitionDiagnostic),\n ].join(\"\\n\"),\n );\n this.name = \"DefinitionError\";\n this.diagnostics = sorted;\n }\n}\n","import type { z } from \"zod\";\nimport type { ScalarLiteralNode } from \"./scalar-literal.js\";\n\nexport const SCALAR_DEFINITION = Symbol.for(\"powerhouse.scalar-definition\");\nexport const SCALAR_DEFINITION_VERSION = 1;\n\n/** The wire shape of a scalar's values. */\nexport type ScalarRepresentation =\n | \"string\"\n | \"number\"\n | \"boolean\"\n | \"json-object\"\n | \"json\"\n | \"opaque\";\n\n/** The GraphQL coercion of a scalar: variables, inline literals, and output. */\nexport type ScalarCoercion<TValue> = {\n readonly parseValue: (input: unknown) => TValue;\n readonly parseLiteral: (node: ScalarLiteralNode) => TValue;\n readonly serialize: (value: unknown) => unknown;\n};\n\nexport type ScalarDefinition<\n TName extends string = string,\n TValue = unknown,\n> = {\n readonly [SCALAR_DEFINITION]: typeof SCALAR_DEFINITION_VERSION;\n readonly name: TName;\n readonly description?: string;\n readonly schema: z.ZodType<TValue>;\n readonly typescriptType: string | null;\n readonly zodSource: string | null;\n readonly example?: TValue;\n /**\n * The wire shape of a value. It picks the literal kinds a derived coercion\n * accepts. A definition from a release before this field lacks it.\n */\n readonly representation?: ScalarRepresentation;\n /** Absent means derived: `schema` runs on every path and only the literal kinds of `representation` parse. */\n readonly coercion?: ScalarCoercion<TValue>;\n};\n\n/** A definition this release made, with its representation filled. */\nexport type DescribedScalarDefinition<\n TName extends string = string,\n TValue = unknown,\n> = ScalarDefinition<TName, TValue> & {\n readonly representation: ScalarRepresentation;\n};\n\nexport type ScalarValue<T> =\n T extends ScalarDefinition<string, infer V> ? V : never;\n\n/** The definition format version `value` is branded with, if it has a brand. */\nexport function scalarDefinitionVersion(value: unknown): unknown {\n return typeof value === \"object\" &&\n value !== null &&\n SCALAR_DEFINITION in value\n ? value[SCALAR_DEFINITION]\n : undefined;\n}\n\nexport function isScalarDefinition(value: unknown): value is ScalarDefinition {\n return scalarDefinitionVersion(value) === SCALAR_DEFINITION_VERSION;\n}\n","import {\n type DescribedScalarDefinition,\n SCALAR_DEFINITION,\n SCALAR_DEFINITION_VERSION,\n} from \"./types.js\";\n\nexport function defineCatalogScalar<TName extends string, TValue>(\n input: Omit<\n DescribedScalarDefinition<TName, TValue>,\n typeof SCALAR_DEFINITION\n >,\n): DescribedScalarDefinition<TName, TValue> {\n return Object.freeze({\n ...input,\n [SCALAR_DEFINITION]: SCALAR_DEFINITION_VERSION,\n } satisfies DescribedScalarDefinition<TName, TValue>);\n}\n","/**\n * Closed literal grammar handed to `parseLiteral`. It mirrors the GraphQL\n * literal kinds the catalog supports so a declaration never needs graphql-js.\n */\nexport type ScalarLiteralNode =\n | { readonly kind: \"string\"; readonly value: string }\n | { readonly kind: \"int\"; readonly value: string }\n | { readonly kind: \"float\"; readonly value: string }\n | { readonly kind: \"boolean\"; readonly value: boolean }\n | { readonly kind: \"null\" }\n | { readonly kind: \"enum\"; readonly value: string }\n | { readonly kind: \"list\"; readonly values: readonly ScalarLiteralNode[] }\n | {\n readonly kind: \"object\";\n readonly fields: readonly {\n readonly name: string;\n readonly value: ScalarLiteralNode;\n }[];\n }\n | { readonly kind: \"variable\"; readonly name: string };\n\nexport class ScalarLiteralVariableError extends TypeError {\n constructor(name: string) {\n super(\n `Variable $${name} cannot appear inside a scalar literal; GraphQL resolves variables before literal coercion.`,\n );\n this.name = \"ScalarLiteralVariableError\";\n }\n}\n\n/** Converts a literal node to its runtime value. A variable anywhere throws. */\nexport function scalarLiteralValue(node: ScalarLiteralNode): unknown {\n switch (node.kind) {\n case \"string\":\n case \"enum\":\n return node.value;\n case \"int\":\n case \"float\":\n return Number(node.value);\n case \"boolean\":\n return node.value;\n case \"null\":\n return null;\n case \"list\":\n return node.values.map(scalarLiteralValue);\n case \"object\":\n return Object.fromEntries(\n node.fields.map((field) => [\n field.name,\n scalarLiteralValue(field.value),\n ]),\n );\n case \"variable\":\n throw new ScalarLiteralVariableError(node.name);\n }\n}\n\nexport function objectFields(\n node: ScalarLiteralNode,\n): ReadonlyMap<string, ScalarLiteralNode> {\n if (node.kind !== \"object\")\n throw new TypeError(\"Value must be an object literal.\");\n return new Map(node.fields.map((field) => [field.name, field.value]));\n}\n\nexport function literalString(\n node: ScalarLiteralNode | undefined,\n field: string,\n): string {\n if (node?.kind !== \"string\")\n throw new TypeError(`${field} must be a string literal.`);\n return node.value;\n}\n\nexport function floatOnlyNumber(\n node: ScalarLiteralNode | undefined,\n field: string,\n): number {\n if (node?.kind !== \"float\")\n throw new TypeError(`${field} must be a float literal.`);\n return Number.parseFloat(node.value);\n}\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\nimport { scalarLiteralValue } from \"../scalar-literal.js\";\n\nexport const unknownScalar = defineCatalogScalar({\n name: \"Unknown\",\n typescriptType: \"unknown\",\n zodSource: \"z.unknown()\",\n schema: z.unknown(),\n representation: \"opaque\",\n coercion: {\n parseValue: (value) => value,\n parseLiteral: scalarLiteralValue,\n serialize: (value) => value,\n },\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const dateTimeScalar = defineCatalogScalar({\n example: \"2024-01-01T00:00:00.000Z\",\n name: \"DateTime\",\n typescriptType: \"string\",\n zodSource: \"z.iso.datetime()\",\n schema: z.iso.datetime(),\n representation: \"string\",\n});\n","export function matchesScalarPattern(pattern: RegExp, value: unknown): boolean {\n return Reflect.apply(pattern.test.bind(pattern), undefined, [value]) === true;\n}\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\nimport { matchesScalarPattern } from \"../pattern.js\";\n\nexport const addressScalar = defineCatalogScalar({\n example: \"eip155:0x0000000000000000000000000000000000000000\",\n name: \"Address\",\n typescriptType: \"`${string}:0x${string}`\",\n zodSource:\n \"z.custom<`${string}:0x${string}`>((val) => /^[a-zA-Z0-9]+:0x[a-fA-F0-9]{40}$/.test(val as string))\",\n schema: z.custom<`${string}:0x${string}`>((val) =>\n matchesScalarPattern(/^[a-zA-Z0-9]+:0x[a-fA-F0-9]{40}$/, val),\n ),\n representation: \"string\",\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\nimport { matchesScalarPattern } from \"../pattern.js\";\n\nexport const attachmentRefScalar = defineCatalogScalar({\n example:\n \"attachment://v1:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n name: \"AttachmentRef\",\n typescriptType: \"`attachment://v${number}:${string}`\",\n zodSource:\n \"z.custom<`attachment://v${number}:${string}`>((val) => /^attachment:\\\\/\\\\/v\\\\d+:.+$/.test(val as string))\",\n schema: z.custom<`attachment://v${number}:${string}`>((val) =>\n matchesScalarPattern(/^attachment:\\/\\/v\\d+:.+$/, val),\n ),\n representation: \"string\",\n});\n","import type { z } from \"zod\";\nimport type { ScalarLiteralNode } from \"./scalar-literal.js\";\nimport type { ScalarCoercion } from \"./types.js\";\n\n/** Runs `schema` on every path; `readLiteral` turns an inline literal into its value first. */\nexport function validatingCoercion<TValue>(\n schema: z.ZodType<TValue>,\n readLiteral: (node: ScalarLiteralNode) => unknown,\n): ScalarCoercion<TValue> {\n const parse = (value: unknown): TValue => schema.parse(value);\n return {\n parseValue: parse,\n parseLiteral: (node) => parse(readLiteral(node)),\n serialize: parse,\n };\n}\n","import type { z } from \"zod\";\nimport { validatingCoercion } from \"../coercion.js\";\nimport {\n floatOnlyNumber,\n literalString,\n objectFields,\n} from \"../scalar-literal.js\";\n\n// The document-engineering scalar resolvers this catalog replaced parsed an\n// amount's number only from a float literal, so an integer literal such as 5\n// is refused even though the schema accepts 5. The host does not use this\n// coercion yet; it accepts 5.\nexport function floatAmountCoercion(schema: z.ZodType<number>) {\n return validatingCoercion(schema, (node) => floatOnlyNumber(node, \"value\"));\n}\n\nexport function stringAmountCoercion<TValue>(schema: z.ZodType<TValue>) {\n return validatingCoercion(schema, (node) => {\n const fields = objectFields(node);\n const value = literalString(fields.get(\"value\"), \"value\");\n if (!/^\\d+(\\.\\d+)?$/.test(value)) {\n throw new TypeError(\"value must be a numeric string.\");\n }\n return { unit: literalString(fields.get(\"unit\"), \"unit\"), value };\n });\n}\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\nimport { floatAmountCoercion } from \"./amounts.js\";\n\nconst schema = z.number();\n\nexport const amountTokensScalar = defineCatalogScalar({\n name: \"Amount_Tokens\",\n typescriptType: \"number\",\n zodSource: \"z.number()\",\n schema,\n representation: \"number\",\n coercion: floatAmountCoercion(schema),\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const ethereumAddressScalar = defineCatalogScalar({\n name: \"EthereumAddress\",\n typescriptType: \"string\",\n zodSource:\n \"z.string().regex(/^0x[a-fA-F0-9]{40}$/, { error: 'Invalid Ethereum address format' })\",\n schema: z.string().regex(/^0x[a-fA-F0-9]{40}$/, {\n error: \"Invalid Ethereum address format\",\n }),\n representation: \"string\",\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const emailAddressScalar = defineCatalogScalar({\n name: \"EmailAddress\",\n typescriptType: \"string\",\n zodSource: \"z.email()\",\n schema: z.email(),\n representation: \"string\",\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\nimport { floatAmountCoercion } from \"./amounts.js\";\n\nconst schema = z.number();\n\nexport const amountPercentageScalar = defineCatalogScalar({\n name: \"Amount_Percentage\",\n typescriptType: \"number\",\n zodSource: \"z.number()\",\n schema,\n representation: \"number\",\n coercion: floatAmountCoercion(schema),\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const dateScalar = defineCatalogScalar({\n example: \"2024-01-01T00:00:00.000Z\",\n name: \"Date\",\n typescriptType: \"string\",\n zodSource: \"z.iso.datetime()\",\n schema: z.iso.datetime(),\n representation: \"string\",\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const urlScalar = defineCatalogScalar({\n example: \"https://example.com\",\n name: \"URL\",\n typescriptType: \"string\",\n zodSource: \"z.url()\",\n schema: z.url(),\n representation: \"string\",\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\nimport { floatAmountCoercion } from \"./amounts.js\";\n\nconst schema = z.number();\n\nexport const amountMoneyScalar = defineCatalogScalar({\n name: \"Amount_Money\",\n typescriptType: \"number\",\n zodSource: \"z.number()\",\n schema,\n representation: \"number\",\n coercion: floatAmountCoercion(schema),\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const olabelScalar = defineCatalogScalar({\n name: \"OLabel\",\n typescriptType: \"string\",\n zodSource: \"z.string()\",\n schema: z.string(),\n representation: \"string\",\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const currencyScalar = defineCatalogScalar({\n name: \"Currency\",\n typescriptType: \"string\",\n zodSource: \"z.string()\",\n schema: z.string(),\n representation: \"string\",\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const phidScalar = defineCatalogScalar({\n name: \"PHID\",\n typescriptType: \"string\",\n zodSource: \"z.string()\",\n schema: z.string(),\n representation: \"string\",\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const oidScalar = defineCatalogScalar({\n name: \"OID\",\n typescriptType: \"string\",\n zodSource: \"z.string()\",\n schema: z.string(),\n representation: \"string\",\n});\n","import { z } from \"zod\";\nimport { validatingCoercion } from \"../coercion.js\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\nimport {\n floatOnlyNumber,\n literalString,\n objectFields,\n} from \"../scalar-literal.js\";\n\nconst schema = z.object({ unit: z.string(), value: z.number() });\n\nexport const amountFiatScalar = defineCatalogScalar({\n name: \"Amount_Fiat\",\n typescriptType: \"{ unit: string, value: number }\",\n zodSource: \"z.object({ unit: z.string(), value: z.number() })\",\n schema,\n representation: \"json-object\",\n coercion: validatingCoercion(schema, (node) => {\n const fields = objectFields(node);\n return {\n unit: literalString(fields.get(\"unit\"), \"unit\"),\n value: floatOnlyNumber(fields.get(\"value\"), \"value\"),\n };\n }),\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\nimport { stringAmountCoercion } from \"./amounts.js\";\n\nconst schema = z.object({ unit: z.string(), value: z.string() });\n\nexport const amountCurrencyScalar = defineCatalogScalar({\n name: \"Amount_Currency\",\n typescriptType: \"{ unit: string, value: string }\",\n zodSource: \"z.object({ unit: z.string(), value: z.string()})\",\n schema,\n representation: \"json-object\",\n coercion: stringAmountCoercion(schema),\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\nimport { stringAmountCoercion } from \"./amounts.js\";\n\nconst schema = z.object({ unit: z.string(), value: z.string() });\n\nexport const amountCryptoScalar = defineCatalogScalar({\n name: \"Amount_Crypto\",\n typescriptType: \"{ unit: string, value: string }\",\n zodSource: \"z.object({ unit: z.string(), value: z.string() })\",\n schema,\n representation: \"json-object\",\n coercion: stringAmountCoercion(schema),\n});\n","import { z } from \"zod\";\nimport { validatingCoercion } from \"../coercion.js\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\nimport {\n floatOnlyNumber,\n literalString,\n objectFields,\n} from \"../scalar-literal.js\";\n\nconst schema = z.object({ unit: z.string().optional(), value: z.number() });\n\nexport const amountScalar = defineCatalogScalar({\n name: \"Amount\",\n typescriptType: \"{ unit?: string, value?: number }\",\n zodSource: \"z.object({ unit: z.string().optional(), value: z.number() })\",\n schema,\n representation: \"json-object\",\n coercion: validatingCoercion(schema, (node) => {\n const fields = objectFields(node);\n const unit = fields.get(\"unit\");\n return {\n unit: unit === undefined ? undefined : literalString(unit, \"unit\"),\n value: floatOnlyNumber(fields.get(\"value\"), \"value\"),\n };\n }),\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const uploadScalar = defineCatalogScalar({\n name: \"Upload\",\n typescriptType: \"File\",\n zodSource: \"z.any()\",\n schema: z.any(),\n representation: \"opaque\",\n coercion: {\n parseValue: (value) => value,\n parseLiteral: () => {\n throw new TypeError(\"Upload literals are not supported.\");\n },\n serialize: (value) => value,\n },\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const jsonObjectScalar = defineCatalogScalar({\n name: \"JSONObject\",\n typescriptType: null,\n zodSource: null,\n schema: z.record(z.string(), z.unknown()),\n representation: \"json-object\",\n});\n","import { unknownScalar } from \"./declarations/unknown.js\";\nimport { dateTimeScalar } from \"./declarations/date-time.js\";\nimport { addressScalar } from \"./declarations/address.js\";\nimport { attachmentRefScalar } from \"./declarations/attachment-ref.js\";\nimport { amountTokensScalar } from \"./declarations/amount-tokens.js\";\nimport { ethereumAddressScalar } from \"./declarations/ethereum-address.js\";\nimport { emailAddressScalar } from \"./declarations/email-address.js\";\nimport { amountPercentageScalar } from \"./declarations/amount-percentage.js\";\nimport { dateScalar } from \"./declarations/date.js\";\nimport { urlScalar } from \"./declarations/url.js\";\nimport { amountMoneyScalar } from \"./declarations/amount-money.js\";\nimport { olabelScalar } from \"./declarations/olabel.js\";\nimport { currencyScalar } from \"./declarations/currency.js\";\nimport { phidScalar } from \"./declarations/phid.js\";\nimport { oidScalar } from \"./declarations/oid.js\";\nimport { amountFiatScalar } from \"./declarations/amount-fiat.js\";\nimport { amountCurrencyScalar } from \"./declarations/amount-currency.js\";\nimport { amountCryptoScalar } from \"./declarations/amount-crypto.js\";\nimport { amountScalar } from \"./declarations/amount.js\";\nimport { uploadScalar } from \"./declarations/upload.js\";\nimport { jsonObjectScalar } from \"./declarations/json-object.js\";\nimport type { DescribedScalarDefinition } from \"./types.js\";\n\nconst declarations = [\n unknownScalar,\n dateTimeScalar,\n addressScalar,\n attachmentRefScalar,\n amountTokensScalar,\n ethereumAddressScalar,\n emailAddressScalar,\n amountPercentageScalar,\n dateScalar,\n urlScalar,\n amountMoneyScalar,\n olabelScalar,\n currencyScalar,\n phidScalar,\n oidScalar,\n amountFiatScalar,\n amountCurrencyScalar,\n amountCryptoScalar,\n amountScalar,\n uploadScalar,\n jsonObjectScalar,\n] as const;\n\nexport type CatalogScalarDefinition = (typeof declarations)[number];\n\nexport const scalarCatalog: readonly DescribedScalarDefinition[] =\n Object.freeze([...declarations]);\n\nconst byName = new Map(\n scalarCatalog.map((definition) => [definition.name, definition]),\n);\n\nexport function getCatalogScalar(\n name: string,\n): DescribedScalarDefinition | undefined {\n return byName.get(name);\n}\n\ntype DocumentModelScalar = DescribedScalarDefinition & {\n readonly typescriptType: string;\n readonly zodSource: string;\n};\n\n// A model's SDL may use every catalog scalar codegen can type. JSONObject is\n// host-only, so it has neither a TypeScript type nor a zod source.\nexport const documentModelScalars: readonly DocumentModelScalar[] =\n Object.freeze(\n scalarCatalog.filter(\n (definition): definition is DocumentModelScalar =>\n definition.typescriptType !== null && definition.zodSource !== null,\n ),\n );\n","import type {\n DefinitionDiagnostic,\n DefinitionRef,\n} from \"@powerhousedao/shared/document-model\";\nimport {\n type DefinitionDiagnosticInput,\n DefinitionError,\n type DiagnosticCatalog,\n type DiagnosticCode,\n sortDefinitionDiagnostics,\n} from \"./diagnostics.js\";\n\nexport class DefinitionDiagnosticCollector<TCode extends DiagnosticCode> {\n readonly #catalog: DiagnosticCatalog<TCode>;\n readonly #definition: DefinitionRef | undefined;\n readonly #diagnostics: DefinitionDiagnostic[] = [];\n\n constructor(catalog: DiagnosticCatalog<TCode>, definition?: DefinitionRef) {\n this.#catalog = catalog;\n this.#definition = definition;\n }\n\n get diagnostics(): readonly DefinitionDiagnostic[] {\n return sortDefinitionDiagnostics(this.#diagnostics);\n }\n\n add(input: DefinitionDiagnosticInput<TCode>): void {\n this.#diagnostics.push(\n this.#catalog.create({\n ...(this.#definition !== undefined && { definition: this.#definition }),\n ...input,\n }),\n );\n }\n\n merge(diagnostics: readonly DefinitionDiagnostic[]): void {\n for (const diagnostic of diagnostics) {\n this.#diagnostics.push(\n this.#definition === undefined || diagnostic.definition !== undefined\n ? diagnostic\n : { ...diagnostic, definition: { ...this.#definition } },\n );\n }\n }\n\n capture<T>(attempt: () => T): T | undefined {\n try {\n return attempt();\n } catch (error) {\n if (!(error instanceof DefinitionError)) throw error;\n this.merge(error.diagnostics);\n return undefined;\n }\n }\n\n throwIfFailed(): void {\n if (!this.#diagnostics.some((entry) => entry.severity === \"error\")) return;\n throw new DefinitionError(\n this.#diagnostics as [DefinitionDiagnostic, ...DefinitionDiagnostic[]],\n );\n }\n}\n","import type { DefinitionPath } from \"@powerhousedao/shared/document-model\";\nimport { describeReceived } from \"./diagnostics.js\";\n\ntype DataLeaf = string | number | boolean | bigint | null | undefined;\n\nexport type DataValue =\n | DataLeaf\n | readonly DataValue[]\n | { readonly [key: string]: DataValue };\n\nexport type DataSnapshotRejection =\n | {\n readonly ok: false;\n readonly reason: \"not-record\";\n readonly path: DefinitionPath;\n readonly received: string;\n }\n | {\n readonly ok: false;\n readonly reason: \"not-array\";\n readonly path: DefinitionPath;\n readonly received: string;\n }\n | {\n readonly ok: false;\n readonly reason: \"custom-prototype\";\n readonly path: DefinitionPath;\n readonly expected: \"record\" | \"array\";\n readonly received: string;\n }\n | {\n readonly ok: false;\n readonly reason: \"symbol-key\";\n readonly path: DefinitionPath;\n readonly key: symbol;\n }\n | {\n readonly ok: false;\n readonly reason: \"unknown-key\";\n readonly path: DefinitionPath;\n readonly key: string;\n readonly allowedKeys: readonly string[];\n }\n | {\n readonly ok: false;\n readonly reason: \"accessor\";\n readonly path: DefinitionPath;\n readonly key: string | number;\n }\n | {\n readonly ok: false;\n readonly reason: \"non-enumerable\";\n readonly path: DefinitionPath;\n readonly key: string | number;\n }\n | {\n readonly ok: false;\n readonly reason: \"sparse\";\n readonly path: DefinitionPath;\n readonly key: number;\n }\n | {\n readonly ok: false;\n readonly reason: \"array-property\";\n readonly path: DefinitionPath;\n readonly key: string;\n }\n | {\n readonly ok: false;\n readonly reason: \"cycle\";\n readonly path: DefinitionPath;\n }\n | {\n readonly ok: false;\n readonly reason: \"not-data\";\n readonly path: DefinitionPath;\n readonly received: string;\n }\n | {\n readonly ok: false;\n readonly reason: \"inspection-failed\";\n readonly path: DefinitionPath;\n };\n\nexport type DataSnapshot<T> =\n | { readonly ok: true; readonly value: T }\n | DataSnapshotRejection;\n\nexport function rejectionReceived(rejection: DataSnapshotRejection): string {\n return \"received\" in rejection ? rejection.received : rejection.reason;\n}\n\nconst CANONICAL_INDEX = /^(?:0|[1-9][0-9]*)$/;\n\nexport function snapshotDataRecord(\n value: unknown,\n allowedKeys: readonly string[] | undefined,\n path: DefinitionPath,\n): DataSnapshot<{ readonly [key: string]: DataValue }> {\n return snapshotPlainObject(\n value,\n allowedKeys,\n path,\n snapshotDataValue,\n new Set(),\n );\n}\n\nexport function snapshotDataArray(\n value: unknown,\n path: DefinitionPath,\n): DataSnapshot<readonly DataValue[]> {\n return snapshotArrayValue(value, path, snapshotDataValue, new Set());\n}\n\nexport function snapshotArray(\n value: unknown,\n path: DefinitionPath,\n): DataSnapshot<readonly unknown[]> {\n return snapshotArrayValue<unknown>(\n value,\n path,\n (member) => ({ ok: true, value: member }),\n new Set(),\n );\n}\n\ntype MemberSnapshot<T> = (\n value: unknown,\n path: DefinitionPath,\n ancestors: Set<object>,\n) => DataSnapshot<T>;\n\nfunction snapshotArrayValue<T>(\n value: unknown,\n path: DefinitionPath,\n member: MemberSnapshot<T>,\n ancestors: Set<object>,\n): DataSnapshot<readonly T[]> {\n try {\n if (!Array.isArray(value)) {\n return {\n ok: false,\n reason: \"not-array\",\n path,\n received: describeReceived(value),\n };\n }\n } catch {\n return { ok: false, reason: \"inspection-failed\", path };\n }\n if (ancestors.has(value)) {\n return { ok: false, reason: \"cycle\", path };\n }\n ancestors.add(value);\n try {\n return snapshotArrayMembers(value, path, member, ancestors);\n } finally {\n ancestors.delete(value);\n }\n}\n\nfunction snapshotArrayMembers<T>(\n value: readonly unknown[],\n path: DefinitionPath,\n member: MemberSnapshot<T>,\n ancestors: Set<object>,\n): DataSnapshot<readonly T[]> {\n let prototype: unknown;\n let keys: readonly (string | symbol)[];\n let lengthDescriptor: PropertyDescriptor | undefined;\n try {\n prototype = Object.getPrototypeOf(value);\n keys = Reflect.ownKeys(value);\n lengthDescriptor = Object.getOwnPropertyDescriptor(value, \"length\");\n } catch {\n return { ok: false, reason: \"inspection-failed\", path };\n }\n if (prototype !== Array.prototype) {\n return {\n ok: false,\n reason: \"custom-prototype\",\n path,\n expected: \"array\",\n received: \"array of another prototype or realm\",\n };\n }\n const length: unknown = lengthDescriptor?.value;\n if (\n typeof length !== \"number\" ||\n !Number.isSafeInteger(length) ||\n length < 0\n ) {\n return { ok: false, reason: \"inspection-failed\", path };\n }\n for (const key of keys) {\n if (key === \"length\") continue;\n if (typeof key === \"symbol\") {\n return { ok: false, reason: \"symbol-key\", path, key };\n }\n if (!CANONICAL_INDEX.test(key) || Number(key) >= length) {\n return { ok: false, reason: \"array-property\", path: [...path, key], key };\n }\n }\n const elements: T[] = [];\n for (let index = 0; index < length; index += 1) {\n const elementPath = [...path, index];\n let descriptor: PropertyDescriptor | undefined;\n try {\n descriptor = Object.getOwnPropertyDescriptor(value, index);\n } catch {\n return { ok: false, reason: \"inspection-failed\", path: elementPath };\n }\n if (descriptor === undefined) {\n return { ok: false, reason: \"sparse\", path: elementPath, key: index };\n }\n const propertyValue = dataPropertyValue(descriptor, index, elementPath);\n if (!propertyValue.ok) return propertyValue;\n const element = member(propertyValue.value, elementPath, ancestors);\n if (!element.ok) return element;\n elements.push(element.value);\n }\n return { ok: true, value: Object.freeze(elements) };\n}\n\nexport function snapshotRecord(\n value: unknown,\n allowedKeys: readonly string[] | undefined,\n path: DefinitionPath,\n ignoredKeys: readonly string[] = [],\n): DataSnapshot<{ readonly [key: string]: unknown }> {\n return snapshotPlainObject<unknown>(\n value,\n allowedKeys,\n path,\n (member) => ({ ok: true, value: member }),\n new Set(),\n ignoredKeys,\n );\n}\n\nfunction snapshotPlainObject<T>(\n value: unknown,\n allowedKeys: readonly string[] | undefined,\n path: DefinitionPath,\n member: (\n value: unknown,\n path: DefinitionPath,\n ancestors: Set<object>,\n ) => DataSnapshot<T>,\n ancestors: Set<object>,\n ignoredKeys: readonly string[] = [],\n): DataSnapshot<{ readonly [key: string]: T }> {\n if (value === null || typeof value !== \"object\") {\n return {\n ok: false,\n reason: \"not-record\",\n path,\n received: describeReceived(value),\n };\n }\n if (ancestors.has(value)) {\n return { ok: false, reason: \"cycle\", path };\n }\n ancestors.add(value);\n try {\n return snapshotPlainObjectMembers(\n value,\n allowedKeys,\n path,\n member,\n ancestors,\n ignoredKeys,\n );\n } finally {\n ancestors.delete(value);\n }\n}\n\nfunction snapshotPlainObjectMembers<T>(\n value: object,\n allowedKeys: readonly string[] | undefined,\n path: DefinitionPath,\n member: (\n value: unknown,\n path: DefinitionPath,\n ancestors: Set<object>,\n ) => DataSnapshot<T>,\n ancestors: Set<object>,\n ignoredKeys: readonly string[],\n): DataSnapshot<{ readonly [key: string]: T }> {\n let isArray: boolean;\n let prototype: unknown;\n let keys: readonly (string | symbol)[];\n try {\n isArray = Array.isArray(value);\n prototype = Object.getPrototypeOf(value);\n keys = Reflect.ownKeys(value);\n } catch {\n return { ok: false, reason: \"inspection-failed\", path };\n }\n if (isArray) {\n return { ok: false, reason: \"not-record\", path, received: \"array\" };\n }\n if (prototype !== Object.prototype && prototype !== null) {\n return {\n ok: false,\n reason: \"custom-prototype\",\n path,\n expected: \"record\",\n received: \"object\",\n };\n }\n const entries: [string, T][] = [];\n for (const key of keys) {\n if (typeof key === \"symbol\") {\n return { ok: false, reason: \"symbol-key\", path, key };\n }\n if (ignoredKeys.includes(key)) continue;\n const memberPath = [...path, key];\n if (allowedKeys !== undefined && !allowedKeys.includes(key)) {\n return {\n ok: false,\n reason: \"unknown-key\",\n path: memberPath,\n key,\n allowedKeys,\n };\n }\n let descriptor: PropertyDescriptor | undefined;\n try {\n descriptor = Object.getOwnPropertyDescriptor(value, key);\n } catch {\n return { ok: false, reason: \"inspection-failed\", path: memberPath };\n }\n if (descriptor === undefined) {\n return { ok: false, reason: \"inspection-failed\", path: memberPath };\n }\n const propertyValue = dataPropertyValue(descriptor, key, memberPath);\n if (!propertyValue.ok) return propertyValue;\n const snapshot = member(propertyValue.value, memberPath, ancestors);\n if (!snapshot.ok) return snapshot;\n entries.push([key, snapshot.value]);\n }\n // `Object.fromEntries` defines own properties, so an own \"__proto__\" key stays\n // an own key instead of silently becoming the prototype as plain assignment would.\n return { ok: true, value: Object.freeze(Object.fromEntries(entries)) };\n}\n\nfunction dataPropertyValue(\n descriptor: PropertyDescriptor,\n key: string | number,\n path: DefinitionPath,\n): DataSnapshot<unknown> {\n if (!(\"value\" in descriptor)) {\n return { ok: false, reason: \"accessor\", path, key };\n }\n if (!descriptor.enumerable) {\n return { ok: false, reason: \"non-enumerable\", path, key };\n }\n const value: unknown = descriptor.value;\n return { ok: true, value };\n}\n\nfunction snapshotDataValue(\n value: unknown,\n path: DefinitionPath,\n ancestors: Set<object>,\n): DataSnapshot<DataValue> {\n switch (typeof value) {\n case \"string\":\n case \"number\":\n case \"boolean\":\n case \"bigint\":\n case \"undefined\":\n return { ok: true, value };\n case \"function\":\n return { ok: false, reason: \"not-data\", path, received: \"function\" };\n case \"symbol\":\n return { ok: false, reason: \"not-data\", path, received: \"symbol\" };\n case \"object\": {\n if (value === null) return { ok: true, value };\n let isArray: boolean;\n try {\n isArray = Array.isArray(value);\n } catch {\n return { ok: false, reason: \"inspection-failed\", path };\n }\n return isArray\n ? snapshotArrayValue(value, path, snapshotDataValue, ancestors)\n : snapshotPlainObject(\n value,\n undefined,\n path,\n snapshotDataValue,\n ancestors,\n );\n }\n }\n}\n","import { defineDiagnosticCatalog } from \"./diagnostics.js\";\n\nexport const kernelDiagnostics = defineDiagnosticCatalog({\n \"PH-DEF-OPTION-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"An option is malformed: wrong type, accessor, symbol key, non-plain object, an explicit undefined or non-JSON default, or an @equals pattern the generator cannot write\",\n },\n \"PH-DEF-COMPATIBILITY-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"A location-free GraphQL compatibility AST is malformed or disagrees with the stored definitions it accompanies\",\n },\n});\n","import { kernelDiagnostics } from \"./diagnostic-codes.js\";\nimport type {\n DefinitionDiagnostic,\n DefinitionPath,\n DefinitionRelatedLocation,\n DirectiveUseDefinition,\n GraphQLConstValueNode,\n GraphQLDirectiveNode,\n GraphQLEnumValueDefinitionNode,\n GraphQLFieldDefinitionNode,\n GraphQLInputValueDefinitionNode,\n GraphQLStringValueNode,\n GraphQLTypeNode,\n GraphQLTypeSystemDefinitionNode,\n GraphQLTypeSystemExtensionNode,\n JsonValue,\n LocationFreeGraphQLDocumentNode,\n NamedGraphQLTypeDefinition,\n SchemaFirstGraphQLDocumentCompatibility,\n} from \"@powerhousedao/shared/document-model\";\nimport { rejectionReceived, snapshotRecord } from \"./data-properties.js\";\nimport { describeReceived } from \"./diagnostics.js\";\nimport { equalsPatternProblem } from \"./equals-pattern.js\";\nimport {\n canonicalJson,\n compareCodeUnits,\n EMPTY_INPUT_FIELD_NAME,\n} from \"./primitives.js\";\nimport { printTypeReference } from \"./printer.js\";\n\nconst AST_KINDS = {\n object: \"ObjectTypeDefinition\",\n interface: \"InterfaceTypeDefinition\",\n enum: \"EnumTypeDefinition\",\n union: \"UnionTypeDefinition\",\n input: \"InputObjectTypeDefinition\",\n} as const satisfies Record<NamedGraphQLTypeDefinition[\"kind\"], string>;\n\ntype NamedDefinitionKind = (typeof AST_KINDS)[keyof typeof AST_KINDS];\n\ntype NamedDefinitionNode = Extract<\n GraphQLTypeSystemDefinitionNode,\n { readonly kind: NamedDefinitionKind }\n>;\n\ntype NamedAstDefinition = {\n readonly kind: NamedDefinitionKind;\n readonly name: { readonly value: string };\n readonly description?: GraphQLStringValueNode;\n readonly directives?: readonly GraphQLDirectiveNode[];\n readonly interfaces?: readonly {\n readonly name: { readonly value: string };\n }[];\n readonly fields?: readonly (\n | GraphQLFieldDefinitionNode\n | GraphQLInputValueDefinitionNode\n )[];\n readonly values?: readonly GraphQLEnumValueDefinitionNode[];\n readonly types?: readonly { readonly name: { readonly value: string } }[];\n};\n\nconst EXTENSION_TARGETS = {\n ObjectTypeExtension: \"ObjectTypeDefinition\",\n InterfaceTypeExtension: \"InterfaceTypeDefinition\",\n EnumTypeExtension: \"EnumTypeDefinition\",\n UnionTypeExtension: \"UnionTypeDefinition\",\n InputObjectTypeExtension: \"InputObjectTypeDefinition\",\n} as const satisfies Record<string, NamedDefinitionKind>;\n\ntype NamedExtensionNode = Extract<\n GraphQLTypeSystemExtensionNode,\n { readonly kind: keyof typeof EXTENSION_TARGETS }\n>;\n\nconst KIND_SPELLING: Record<\n NamedDefinitionKind | \"ScalarTypeDefinition\",\n { readonly noun: string; readonly keyword: string }\n> = {\n ScalarTypeDefinition: { noun: \"a scalar\", keyword: \"scalar\" },\n ObjectTypeDefinition: { noun: \"an object type\", keyword: \"type\" },\n InterfaceTypeDefinition: { noun: \"an interface\", keyword: \"interface\" },\n EnumTypeDefinition: { noun: \"an enum\", keyword: \"enum\" },\n UnionTypeDefinition: { noun: \"a union\", keyword: \"union\" },\n InputObjectTypeDefinition: { noun: \"an input\", keyword: \"input\" },\n};\n\nconst MEMBER_LISTS = [\"fields\", \"values\", \"interfaces\", \"types\"] as const;\n\ntype MemberList = (typeof MEMBER_LISTS)[number];\n\ntype Member = { readonly name: { readonly value: string } };\n\ntype EffectiveTypeDefinition = {\n readonly node: NamedAstDefinition;\n readonly index: number;\n readonly contributors: ReadonlyMap<`${MemberList}:${string}`, number>;\n};\n\ntype FoldedTypeDefinitions = {\n readonly types: ReadonlyMap<string, EffectiveTypeDefinition>;\n readonly redefinitions: readonly {\n readonly name: string;\n readonly index: number;\n }[];\n readonly diagnostics: readonly DefinitionDiagnostic[];\n};\n\ntype TypeUnderFold = {\n readonly base: Omit<NamedAstDefinition, \"kind\">;\n readonly kind: NamedDefinitionKind;\n readonly index: number;\n readonly contributors: Map<`${MemberList}:${string}`, number>;\n readonly lists: Partial<Record<MemberList, Member[]>>;\n readonly directives: GraphQLDirectiveNode[];\n};\n\nfunction isNamedDefinition(node: {\n readonly kind: string;\n}): node is NamedDefinitionNode {\n return Object.values(AST_KINDS).includes(node.kind as NamedDefinitionKind);\n}\n\nfunction isNamedExtension(node: {\n readonly kind: string;\n}): node is NamedExtensionNode {\n return Object.hasOwn(EXTENSION_TARGETS, node.kind);\n}\n\n/**\n * Folds every extension into the type it extends. A repeated definition or\n * member keeps its first occurrence and is reported; an extension-only type\n * starts from its first extension.\n */\nexport function foldTypeExtensions(\n definitions: LocationFreeGraphQLDocumentNode[\"definitions\"],\n path: DefinitionPath,\n): FoldedTypeDefinitions {\n const types = new Map<string, TypeUnderFold>();\n const redefinitions: { name: string; index: number }[] = [];\n const diagnostics: DefinitionDiagnostic[] = [];\n const memberPath = (index: number, list: MemberList, name: string) => [\n ...path,\n \"definitions\",\n index,\n list,\n name,\n ];\n const addMembers = (\n target: TypeUnderFold,\n node: Partial<Record<MemberList, readonly Member[]>>,\n index: number,\n ): void => {\n for (const list of MEMBER_LISTS) {\n const members = node[list];\n if (members === undefined) continue;\n for (const member of members) {\n const name = member.name.value;\n const key = `${list}:${name}` as const;\n const first = target.contributors.get(key);\n if (first !== undefined) {\n const coordinate = `${target.base.name.value}.${name}`;\n diagnostics.push(\n compatibilityDiagnostic(\n memberPath(index, list, name),\n `${coordinate} is defined more than once.`,\n {\n expected: \"one definition per member\",\n received: \"a second definition\",\n repair: `Remove the repeated ${name}; the host rejects a member defined twice.`,\n related: [\n {\n path: memberPath(first, list, name),\n message: `${coordinate} is first defined here.`,\n },\n ],\n },\n ),\n );\n continue;\n }\n target.contributors.set(key, index);\n target.lists[list]?.push(member);\n }\n }\n };\n const start = (\n node: Omit<NamedAstDefinition, \"kind\">,\n kind: NamedDefinitionKind,\n index: number,\n ): TypeUnderFold => {\n const folding: TypeUnderFold = {\n base: node,\n kind,\n index,\n contributors: new Map(),\n lists: Object.fromEntries(\n MEMBER_LISTS.filter((list) => node[list] !== undefined).map((list) => [\n list,\n [],\n ]),\n ),\n directives: [...(node.directives ?? [])],\n };\n addMembers(folding, node, index);\n return folding;\n };\n\n const scalars = new Set<string>();\n const wrongKind = (\n index: number,\n name: string,\n defined: keyof typeof KIND_SPELLING,\n extension: { readonly kind: string },\n extendedAs: keyof typeof KIND_SPELLING,\n ): void => {\n diagnostics.push(\n compatibilityDiagnostic(\n [...path, \"definitions\", index],\n `${name} is ${KIND_SPELLING[defined].noun}, so it cannot be extended as ${KIND_SPELLING[extendedAs].noun}.`,\n {\n expected: defined.replace(\"Definition\", \"Extension\"),\n received: extension.kind,\n repair: `Extend ${name} with \"extend ${KIND_SPELLING[defined].keyword}\", or remove the extension; the host rejects an extension of a different kind.`,\n },\n ),\n );\n };\n const foldScalarExtensions = (\n foldedTypes: ReadonlyMap<string, TypeUnderFold>,\n ): void => {\n definitions.forEach((node, index) => {\n if (node.kind !== \"ScalarTypeExtension\") return;\n const target = foldedTypes.get(node.name.value);\n if (target !== undefined) {\n wrongKind(\n index,\n node.name.value,\n target.kind,\n node,\n \"ScalarTypeDefinition\",\n );\n }\n });\n };\n\n definitions.forEach((node, index) => {\n if (node.kind === \"ScalarTypeDefinition\") {\n scalars.add(\n (node as GraphQLTypeSystemDefinitionNode & Member).name.value,\n );\n return;\n }\n if (!isNamedDefinition(node)) return;\n const name = node.name.value;\n if (types.has(name)) {\n redefinitions.push({ name, index });\n return;\n }\n types.set(name, start(node, node.kind, index));\n });\n\n definitions.forEach((node, index) => {\n if (!isNamedExtension(node)) return;\n const kind = EXTENSION_TARGETS[node.kind];\n const name = node.name.value;\n const target = types.get(name);\n if (target === undefined) {\n if (scalars.has(name)) {\n wrongKind(index, name, \"ScalarTypeDefinition\", node, kind);\n return;\n }\n types.set(name, start(node, kind, index));\n return;\n }\n if (target.kind !== kind) {\n wrongKind(index, name, target.kind, node, kind);\n return;\n }\n target.directives.push(...node.directives);\n addMembers(target, node, index);\n });\n\n foldScalarExtensions(types);\n\n return {\n types: new Map(\n [...types].map(\n ([name, { base, kind, index, contributors, lists, directives }]) => [\n name,\n {\n node: { ...base, kind, directives, ...lists } as NamedAstDefinition,\n index,\n contributors,\n },\n ],\n ),\n ),\n redefinitions,\n diagnostics,\n };\n}\n\nfunction compatibilityDiagnostic(\n path: DefinitionPath,\n message: string,\n detail: {\n readonly expected?: string;\n readonly received?: string;\n readonly repair?: string;\n readonly related?: readonly DefinitionRelatedLocation[];\n } = {},\n): DefinitionDiagnostic {\n return kernelDiagnostics.create({\n code: \"PH-DEF-COMPATIBILITY-INVALID\",\n path,\n message,\n ...(detail.expected !== undefined && { expected: detail.expected }),\n ...(detail.received !== undefined && { received: detail.received }),\n ...(detail.related !== undefined && { related: detail.related }),\n repair:\n detail.repair ??\n \"Regenerate the compatibility AST from the schema this declaration replaces, or change the descriptors to agree with it.\",\n });\n}\n\nconst ARRAY_INDEX = /^(?:0|[1-9][0-9]*)$/;\n\nexport function validateLocationFreeDocument(\n value: unknown,\n path: DefinitionPath,\n): readonly DefinitionDiagnostic[] {\n const diagnostics: DefinitionDiagnostic[] = [];\n const refuse = (at: DefinitionPath, message: string, received: string) =>\n diagnostics.push(\n compatibilityDiagnostic(at, message, {\n expected: \"JSON data\",\n received,\n repair:\n \"Keep only JSON data in the AST: strings, finite numbers, booleans, null, plain arrays and plain objects with data properties.\",\n }),\n );\n const ancestors = new Set<object>();\n const visitProperty = (\n owner: object,\n key: string | number,\n at: DefinitionPath,\n ): void => {\n const descriptor = Object.getOwnPropertyDescriptor(owner, key);\n if (descriptor === undefined) {\n refuse(at, \"A compatibility AST array must not have holes.\", \"hole\");\n } else if (!(\"value\" in descriptor)) {\n refuse(\n at,\n \"A compatibility AST must hold data properties, not accessors.\",\n \"accessor\",\n );\n } else {\n visit(descriptor.value, at);\n }\n };\n const visit = (node: unknown, at: DefinitionPath): void => {\n if (\n node === null ||\n typeof node === \"string\" ||\n typeof node === \"boolean\"\n ) {\n return;\n }\n if (typeof node === \"number\") {\n if (!Number.isFinite(node)) {\n refuse(at, \"A compatibility AST number must be finite.\", String(node));\n }\n return;\n }\n if (typeof node !== \"object\") {\n refuse(\n at,\n `A compatibility AST must contain JSON data only, received ${typeof node}.`,\n typeof node,\n );\n return;\n }\n if (ancestors.has(node)) {\n refuse(at, \"A compatibility AST must not contain a cycle.\", \"cycle\");\n return;\n }\n const prototype: unknown = Object.getPrototypeOf(node);\n const isArray = Array.isArray(node);\n if (\n isArray\n ? prototype !== Array.prototype\n : prototype !== Object.prototype && prototype !== null\n ) {\n refuse(\n at,\n \"A compatibility AST must hold plain arrays and plain objects only.\",\n describeReceived(node),\n );\n return;\n }\n ancestors.add(node);\n for (const key of Reflect.ownKeys(node)) {\n if (typeof key === \"symbol\") {\n refuse(at, \"A compatibility AST must not have symbol keys.\", \"symbol\");\n } else if (isArray) {\n if (key !== \"length\" && !ARRAY_INDEX.test(key)) {\n refuse(\n [...at, key],\n \"A compatibility AST array must hold only its items.\",\n key,\n );\n }\n } else if (key === \"loc\") {\n diagnostics.push(\n compatibilityDiagnostic(\n [...at, key],\n \"A compatibility AST must be location free.\",\n {\n expected: \"no loc property\",\n received: \"loc\",\n repair: \"Strip every loc property from the AST.\",\n },\n ),\n );\n } else {\n visitProperty(node, key, [...at, key]);\n }\n }\n if (isArray) {\n for (let index = 0; index < node.length; index += 1) {\n visitProperty(node, index, [...at, index]);\n }\n }\n ancestors.delete(node);\n };\n visit(value, path);\n return diagnostics;\n}\n\nfunction printAstType(node: GraphQLTypeNode): string {\n switch (node.kind) {\n case \"NamedType\":\n return node.name.value;\n case \"ListType\":\n return `[${printAstType(node.type)}]`;\n case \"NonNullType\":\n return `${printAstType(node.type)}!`;\n }\n}\n\nfunction astValue(node: GraphQLConstValueNode): JsonValue {\n switch (node.kind) {\n case \"IntValue\":\n case \"FloatValue\":\n return Number(node.value);\n case \"StringValue\":\n case \"EnumValue\":\n return node.value;\n case \"BooleanValue\":\n return node.value;\n case \"NullValue\":\n return null;\n case \"ListValue\":\n return node.values.map(astValue);\n case \"ObjectValue\":\n return Object.fromEntries(\n node.fields.map((field) => [field.name.value, astValue(field.value)]),\n );\n }\n}\n\nconst DEFAULT_DEPRECATION_REASON = \"No longer supported\";\n\nfunction astDeprecation(\n directives: readonly GraphQLDirectiveNode[] | undefined,\n): string | null {\n const directive = (directives ?? []).find(\n (candidate) => candidate.name.value === \"deprecated\",\n );\n if (directive === undefined) return null;\n const reason = directive.arguments.find(\n (argument) => argument.name.value === \"reason\",\n );\n if (reason === undefined) return DEFAULT_DEPRECATION_REASON;\n return reason.value.kind === \"StringValue\" ? reason.value.value : null;\n}\n\nfunction astEquals(\n directives: readonly GraphQLDirectiveNode[] | undefined,\n): string | null {\n const value = (directives ?? [])\n .find((directive) => directive.name.value === \"equals\")\n ?.arguments.find((argument) => argument.name.value === \"value\")?.value;\n return value !== undefined &&\n \"value\" in value &&\n typeof value.value === \"string\"\n ? value.value\n : null;\n}\n\nfunction definitionEquals(field: {\n readonly directives?: readonly DirectiveUseDefinition[];\n}): string | null {\n const value = field.directives\n ?.find((directive) => directive.name === \"equals\")\n ?.arguments.find((argument) => argument.name === \"value\")?.value;\n return typeof value === \"string\" ? value : null;\n}\n\nfunction printEquals(equals: string | null): string {\n return equals === null\n ? \"no @equals\"\n : `@equals(value: ${JSON.stringify(equals)})`;\n}\n\ntype FieldFingerprint = {\n readonly name: string;\n readonly type: string;\n readonly defaultValue: string | null;\n readonly description: string | null;\n readonly deprecated: string | null;\n readonly equals: string | null;\n};\n\ntype TypeFingerprint = {\n readonly kind: string;\n readonly name: string;\n readonly description: string | null;\n readonly implemented: readonly string[];\n readonly fields: readonly FieldFingerprint[];\n readonly members: readonly string[];\n};\n\nfunction descriptorFingerprint(\n definition: NamedGraphQLTypeDefinition,\n): TypeFingerprint {\n const fields =\n definition.kind === \"enum\"\n ? definition.values.map((value): FieldFingerprint => ({\n name: value.name,\n type: \"\",\n defaultValue: null,\n description: value.description,\n deprecated: value.deprecated,\n equals: null,\n }))\n : definition.kind === \"union\"\n ? []\n : definition.kind === \"input\" && definition.fields.length === 0\n ? [\n {\n name: EMPTY_INPUT_FIELD_NAME,\n type: \"Boolean\",\n defaultValue: null,\n description: null,\n deprecated: null,\n equals: null,\n },\n ]\n : definition.fields.map((field): FieldFingerprint => {\n const hasDefault = Object.hasOwn(field, \"defaultValue\");\n return {\n name: field.name,\n type: printTypeReference(field.type),\n defaultValue: hasDefault\n ? canonicalJson(\n (field as { readonly defaultValue: JsonValue })\n .defaultValue,\n )\n : null,\n description: field.description,\n deprecated: field.deprecated,\n equals: definitionEquals(field),\n };\n });\n return {\n kind: AST_KINDS[definition.kind],\n name: definition.name,\n description: definition.description,\n implemented:\n definition.kind === \"object\" || definition.kind === \"interface\"\n ? (definition.implements ?? [])\n : [],\n fields,\n members: definition.kind === \"union\" ? definition.members : [],\n };\n}\n\nfunction astFingerprint(node: NamedAstDefinition): TypeFingerprint {\n const fields =\n node.kind === AST_KINDS.enum\n ? (node.values ?? []).map((value): FieldFingerprint => ({\n name: value.name.value,\n type: \"\",\n defaultValue: null,\n description: value.description?.value ?? null,\n deprecated: astDeprecation(value.directives),\n equals: null,\n }))\n : (node.fields ?? []).map((field): FieldFingerprint => {\n const defaultValue = (field as GraphQLInputValueDefinitionNode)\n .defaultValue;\n return {\n name: field.name.value,\n type: printAstType(field.type),\n defaultValue:\n defaultValue === undefined\n ? null\n : canonicalJson(astValue(defaultValue)),\n description: field.description?.value ?? null,\n deprecated: astDeprecation(field.directives),\n equals: astEquals(field.directives),\n };\n });\n return {\n kind: node.kind,\n name: node.name.value,\n description: node.description?.value ?? null,\n implemented: (node.interfaces ?? []).map(\n (implemented) => implemented.name.value,\n ),\n fields,\n members: (node.types ?? []).map((member) => member.name.value),\n };\n}\n\ntype ExtensionSource = {\n readonly documentPath: DefinitionPath;\n readonly effective: EffectiveTypeDefinition;\n};\n\nfunction missingMemberRepair(\n kind: NamedDefinitionKind,\n typeName: string,\n member: string,\n): string {\n switch (kind) {\n case \"EnumTypeDefinition\":\n return `Add the value \"${member}\" to the definition of enum ${typeName}.`;\n case \"UnionTypeDefinition\":\n return `Add the member ${member} to the definition of union ${typeName}.`;\n default:\n return `Add a \"${member}\" field to the definition of ${typeName}.`;\n }\n}\n\nfunction compareFields(\n descriptor: TypeFingerprint,\n ast: TypeFingerprint,\n path: DefinitionPath,\n memberNoun: \"field\" | \"enum value\",\n source: ExtensionSource,\n): readonly DefinitionDiagnostic[] {\n const diagnostics: DefinitionDiagnostic[] = [];\n const astFields = new Map(ast.fields.map((field) => [field.name, field]));\n const list: MemberList = memberNoun === \"enum value\" ? \"values\" : \"fields\";\n for (const field of descriptor.fields) {\n const match = astFields.get(field.name);\n if (match === undefined) {\n diagnostics.push(\n compatibilityDiagnostic(\n [...path, field.name],\n `${descriptor.name}.${field.name} is declared by the descriptors and absent from the compatibility AST.`,\n {\n expected: `${memberNoun} ${field.name}`,\n received: \"absent\",\n },\n ),\n );\n continue;\n }\n astFields.delete(field.name);\n const contributor = source.effective.contributors.get(\n `${list}:${field.name}`,\n );\n const coordinate =\n contributor === undefined || contributor === source.effective.index\n ? [...path, field.name]\n : [\n ...source.documentPath,\n \"definitions\",\n contributor,\n list,\n field.name,\n ];\n if (field.type !== match.type) {\n diagnostics.push(\n compatibilityDiagnostic(\n [...coordinate, \"type\"],\n `${descriptor.name}.${field.name} has a different type in the compatibility AST.`,\n { expected: field.type, received: match.type },\n ),\n );\n }\n if (field.defaultValue !== match.defaultValue) {\n diagnostics.push(\n compatibilityDiagnostic(\n [...coordinate, \"defaultValue\"],\n `${descriptor.name}.${field.name} has a different default value in the compatibility AST.`,\n {\n expected: field.defaultValue ?? \"no default\",\n received: match.defaultValue ?? \"no default\",\n repair: `Remove the default from the compatibility AST, or declare a defaultValue the field's type accepts on the descriptor field ${descriptor.name}.${field.name}.`,\n },\n ),\n );\n }\n if (field.description !== match.description) {\n diagnostics.push(\n compatibilityDiagnostic(\n [...coordinate, \"description\"],\n `${descriptor.name}.${field.name} has a different description in the compatibility AST.`,\n {\n expected: field.description ?? \"no description\",\n received: match.description ?? \"no description\",\n },\n ),\n );\n }\n if (field.deprecated !== match.deprecated) {\n diagnostics.push(\n compatibilityDiagnostic(\n [...coordinate, \"deprecated\"],\n `${descriptor.name}.${field.name} has a different deprecation in the compatibility AST.`,\n {\n expected: field.deprecated ?? \"not deprecated\",\n received: match.deprecated ?? \"not deprecated\",\n },\n ),\n );\n }\n const astProblem =\n match.equals === null ? undefined : equalsPatternProblem(match.equals);\n if (match.equals !== null && astProblem !== undefined) {\n diagnostics.push(\n kernelDiagnostics.create({\n code: \"PH-DEF-OPTION-INVALID\",\n path: [...coordinate, \"equals\"],\n received: match.equals,\n ...astProblem,\n }),\n );\n } else if (field.equals !== match.equals) {\n diagnostics.push(\n compatibilityDiagnostic(\n [...coordinate, \"equals\"],\n `${descriptor.name}.${field.name} has a different @equals in the compatibility AST.`,\n {\n expected: printEquals(field.equals),\n received: printEquals(match.equals),\n repair:\n match.equals === null\n ? `Remove @equals from the definition of ${descriptor.name}.${field.name}, or add ${printEquals(field.equals)} to the field in the AST.`\n : `Give the definition of ${descriptor.name}.${field.name} ${printEquals(match.equals)}.`,\n },\n ),\n );\n }\n }\n for (const extra of astFields.keys()) {\n const received = `${memberNoun} ${extra}`;\n diagnostics.push(\n extensionMemberDiagnostic(\n descriptor.name,\n list,\n extra,\n received,\n source,\n ) ??\n compatibilityDiagnostic(\n [...path, extra],\n `${descriptor.name}.${extra} is in the compatibility AST and not in the descriptors.`,\n { expected: \"absent\", received },\n ),\n );\n }\n return diagnostics;\n}\n\nfunction extensionMemberDiagnostic(\n typeName: string,\n list: MemberList,\n member: string,\n received: string,\n { documentPath, effective }: ExtensionSource,\n): DefinitionDiagnostic | undefined {\n const index = effective.contributors.get(`${list}:${member}`);\n if (index === undefined || index === effective.index) return undefined;\n const keyword = KIND_SPELLING[effective.node.kind].keyword;\n return compatibilityDiagnostic(\n [...documentPath, \"definitions\", index, list, member],\n `${typeName}.${member} is added by \"extend ${keyword} ${typeName}\" and missing from the descriptors.`,\n {\n expected: \"absent\",\n received,\n repair: missingMemberRepair(effective.node.kind, typeName, member),\n },\n );\n}\n\nfunction refusedV1Member(record: {\n readonly [key: string]: unknown;\n}): { readonly member: string; readonly received: string } | undefined {\n if (record.kind !== \"graphql-ast-v1\") {\n return { member: \"kind\", received: spelledMember(record.kind) };\n }\n if (record.preserveDefinitionOrder !== true) {\n return {\n member: \"preserveDefinitionOrder\",\n received: spelledMember(record.preserveDefinitionOrder),\n };\n }\n return undefined;\n}\n\nfunction spelledMember(value: unknown): string {\n return typeof value === \"string\" || typeof value === \"boolean\"\n ? String(value)\n : describeReceived(value);\n}\n\nfunction sameMembers(\n left: readonly string[],\n right: readonly string[],\n): boolean {\n return (\n canonicalJson([...left].sort(compareCodeUnits)) ===\n canonicalJson([...right].sort(compareCodeUnits))\n );\n}\n\nfunction dataProperty(owner: object, key: string): unknown {\n const descriptor = Object.getOwnPropertyDescriptor(owner, key);\n return descriptor !== undefined && \"value\" in descriptor\n ? descriptor.value\n : undefined;\n}\n\nfunction rootOperationTypeNames(\n document: LocationFreeGraphQLDocumentNode,\n): ReadonlySet<string> {\n const names = new Set<string>([\"Query\", \"Mutation\", \"Subscription\"]);\n for (const node of document.definitions) {\n if (node.kind !== \"SchemaDefinition\" && node.kind !== \"SchemaExtension\") {\n continue;\n }\n for (const operationType of node.operationTypes) {\n names.add(operationType.type.name.value);\n }\n }\n return names;\n}\n\nexport function checkGraphQLDocumentAgreement(options: {\n readonly compatibility: SchemaFirstGraphQLDocumentCompatibility;\n readonly definitions: readonly NamedGraphQLTypeDefinition[];\n readonly path: DefinitionPath;\n}): readonly DefinitionDiagnostic[] {\n const { definitions, path } = options;\n const compatibility = snapshotRecord(options.compatibility, undefined, path);\n const refuse = (at: DefinitionPath, received: string) => [\n compatibilityDiagnostic(\n at,\n \"A GraphQL compatibility declaration must be a V1 location-free document with preserveDefinitionOrder.\",\n {\n expected: 'kind \"graphql-ast-v1\" with preserveDefinitionOrder: true',\n received,\n repair:\n 'Pass a location-free GraphQL document as { kind: \"graphql-ast-v1\", document, preserveDefinitionOrder: true }.',\n },\n ),\n ];\n if (!compatibility.ok) {\n return refuse(compatibility.path, rejectionReceived(compatibility));\n }\n const refused = refusedV1Member(compatibility.value);\n if (refused !== undefined) {\n return refuse([...path, refused.member], refused.received);\n }\n const document: unknown = compatibility.value.document;\n if (\n document === null ||\n typeof document !== \"object\" ||\n dataProperty(document, \"kind\") !== \"Document\" ||\n !Array.isArray(dataProperty(document, \"definitions\"))\n ) {\n return [\n compatibilityDiagnostic(\n [...path, \"document\"],\n \"A GraphQL compatibility document must be a location-free Document node.\",\n {\n expected: 'a { kind: \"Document\", definitions: [...] } node',\n received: describeReceived(document),\n },\n ),\n ];\n }\n const shape = validateLocationFreeDocument(document, [...path, \"document\"]);\n if (shape.length > 0) return shape;\n const validated = document as LocationFreeGraphQLDocumentNode;\n\n const documentPath = [...path, \"document\"];\n const folded = foldTypeExtensions(validated.definitions, documentPath);\n const diagnostics: DefinitionDiagnostic[] = [\n ...folded.redefinitions.map(({ name }) =>\n compatibilityDiagnostic(\n [...documentPath, name],\n `The compatibility AST defines ${name} twice.`,\n { expected: \"one definition per type name\", received: \"two\" },\n ),\n ),\n ...folded.diagnostics,\n ];\n\n const compared = new Set<string>();\n for (const definition of definitions) {\n if (compared.has(definition.name)) continue;\n compared.add(definition.name);\n const coordinate = [...path, \"document\", definition.name];\n const effective = folded.types.get(definition.name);\n if (effective === undefined) {\n diagnostics.push(\n compatibilityDiagnostic(\n coordinate,\n `${definition.name} is declared by the descriptors and absent from the compatibility AST.`,\n { expected: definition.name, received: \"absent\" },\n ),\n );\n continue;\n }\n const descriptor = descriptorFingerprint(definition);\n const ast = astFingerprint(effective.node);\n if (descriptor.kind !== ast.kind) {\n diagnostics.push(\n compatibilityDiagnostic(\n coordinate,\n `${definition.name} is a different kind of type in the compatibility AST.`,\n { expected: descriptor.kind, received: ast.kind },\n ),\n );\n continue;\n }\n if (descriptor.description !== ast.description) {\n diagnostics.push(\n compatibilityDiagnostic(\n [...coordinate, \"description\"],\n `${definition.name} has a different description in the compatibility AST.`,\n {\n expected: descriptor.description ?? \"no description\",\n received: ast.description ?? \"no description\",\n },\n ),\n );\n }\n if (!sameMembers(descriptor.implemented, ast.implemented)) {\n diagnostics.push(\n compatibilityDiagnostic(\n [...coordinate, \"implements\"],\n `${definition.name} implements different interfaces in the compatibility AST.`,\n {\n expected: descriptor.implemented.join(\" & \") || \"none\",\n received: ast.implemented.join(\" & \") || \"none\",\n },\n ),\n );\n }\n if (!sameMembers(descriptor.members, ast.members)) {\n diagnostics.push(\n compatibilityDiagnostic(\n [...coordinate, \"members\"],\n `${definition.name} has different union members in the compatibility AST.`,\n {\n expected: descriptor.members.join(\" | \") || \"none\",\n received: ast.members.join(\" | \") || \"none\",\n },\n ),\n );\n }\n diagnostics.push(\n ...compareFields(\n descriptor,\n ast,\n [...coordinate, definition.kind === \"enum\" ? \"values\" : \"fields\"],\n definition.kind === \"enum\" ? \"enum value\" : \"field\",\n { documentPath, effective },\n ),\n );\n }\n\n const rootTypes = rootOperationTypeNames(validated);\n for (const [name, { node }] of folded.types) {\n if (compared.has(name) || rootTypes.has(name)) continue;\n diagnostics.push(\n compatibilityDiagnostic(\n [...path, \"document\", name],\n `The compatibility AST declares ${name}, which no descriptor represents.`,\n {\n expected: \"a descriptor for every named type in the AST\",\n received: node.kind,\n repair: `Add a definition for ${name}, or remove it from the AST.`,\n },\n ),\n );\n }\n return diagnostics;\n}\n","import { kernelDiagnostics } from \"../kernel/diagnostic-codes.js\";\nimport { defineDiagnosticCatalog } from \"../kernel/diagnostics.js\";\n\nexport const dslDiagnostics = defineDiagnosticCatalog(\n {\n \"PH-DEF-FIELD-OPTION-UNSUPPORTED\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"A field use contains an option its builder or its position does not support\",\n },\n \"PH-DEF-TYPE-AS-FIELD\": {\n severity: \"error\",\n phase: \"definition\",\n meaning: \"A named type is used as a field without ph.ref\",\n },\n \"PH-DEF-NAME-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"An authored GraphQL type, field, or enum value name is lexically invalid or reserved\",\n },\n \"PH-DEF-FIELD-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"A field position holds a value that is neither a field use nor a named type\",\n },\n \"PH-DEF-REFERENCE-TARGET-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"A ph.ref target is not a named type: a field use, another reference, undefined, or an anonymous input\",\n },\n \"PH-DEF-ENUM-VALUES-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"An enum declares no values, a duplicate value, or a reserved value\",\n },\n \"PH-DEF-UNION-MEMBERS-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"A union declares no members, a duplicate member, or a member that is not a ph.object\",\n },\n \"PH-DEF-IMPLEMENTS-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"An object or an interface implements something that is not a ph.interface, or the same interface twice\",\n },\n \"PH-SCALAR-FACTORY-AS-FIELD\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"A scalar field-use factory is used as a field without being called\",\n },\n \"PH-SCALAR-INTERNAL\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"A field uses a catalog scalar that only the reactor host declares, such as JSONObject\",\n },\n \"PH-SCALAR-DEFINITION-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"ph.scalar received a value that is not a scalar definition of this release's format\",\n },\n },\n kernelDiagnostics,\n);\n\nexport type DslDiagnosticCode = keyof typeof dslDiagnostics.codes;\n","import { dslDiagnostics } from \"../dsl/diagnostic-codes.js\";\nimport { defineDiagnosticCatalog } from \"../kernel/diagnostics.js\";\n\nexport const compilerDiagnostics = defineDiagnosticCatalog(\n {\n \"PH-DM-DUPLICATE-ACTION\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"Two operations derive the same persisted action type, or an operation derives one the document runtime owns\",\n },\n \"PH-DM-DUPLICATE-NAME\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"Two declarations derive the same module, GraphQL type, or creator name\",\n },\n \"PH-DM-IDENTITY-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"An identity segment, compatibility ID, or derived UUID violates the V1 contract\",\n },\n \"PH-DM-DECLARATION-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"A model, module, operation, error, example, version, or family declaration member is absent, malformed, unsupported, or forged\",\n },\n \"PH-DM-DEFAULT-UNSUPPORTED\": {\n severity: \"error\",\n phase: \"definition\",\n meaning: \"A document state field declares a GraphQL default value\",\n },\n \"PH-DM-INTERFACE-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"An object or interface does not satisfy an implemented interface's fields or ancestor requirements\",\n },\n \"PH-DM-INPUT-CYCLE\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"An input type contains itself through singular non-null input fields, so no finite value satisfies it\",\n },\n \"PH-DM-TYPE-POSITION-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"An input type is referenced from an output position, or an output type from an input position\",\n },\n \"PH-DM-INITIAL-VALUE-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"A scope initial value cannot produce a stored JSON string, or its own state validator rejects it\",\n },\n \"PH-SCALAR-DUPLICATE-NAME\": {\n severity: \"error\",\n phase: \"definition\",\n meaning: \"Two different project scalars of one model claim one name\",\n },\n },\n dslDiagnostics,\n);\n\nexport type CompilerDiagnosticCode = keyof typeof compilerDiagnostics.codes;\n","import type {\n DefinitionDiagnostic,\n DefinitionPath,\n JsonValue,\n} from \"@powerhousedao/shared/document-model\";\nimport { documentModelScalars, scalarCatalog } from \"../../scalars/catalog.js\";\nimport { DefinitionDiagnosticCollector } from \"../kernel/diagnostic-collector.js\";\nimport {\n rejectionReceived,\n snapshotArray,\n snapshotRecord,\n} from \"../kernel/data-properties.js\";\nimport { describeReceived } from \"../kernel/diagnostics.js\";\nimport { validateLocationFreeDocument } from \"../kernel/graphql-ast.js\";\nimport { canonicalJson, isGraphQLName } from \"../kernel/primitives.js\";\nimport {\n type CompilerDiagnosticCode,\n compilerDiagnostics,\n} from \"./diagnostic-codes.js\";\n\ntype Node = { readonly [key: string]: unknown };\n\nconst BUILT_IN_SCALARS = [\"ID\", \"String\", \"Boolean\", \"Int\", \"Float\"] as const;\nconst CATALOG_SCALARS = documentModelScalars.map(({ name }) => name);\nconst MODEL_SCALARS: ReadonlySet<string> = new Set([\n ...BUILT_IN_SCALARS,\n ...CATALOG_SCALARS,\n]);\nconst HOST_ONLY_SCALARS: ReadonlySet<string> = new Set(\n scalarCatalog\n .map(({ name }) => name)\n .filter((name) => !MODEL_SCALARS.has(name)),\n);\nconst SCALAR_REPRESENTATIONS = [\n \"string\",\n \"number\",\n \"boolean\",\n \"json-object\",\n \"json\",\n \"opaque\",\n] as const;\n\nclass ShapeChecker {\n readonly collector =\n new DefinitionDiagnosticCollector<CompilerDiagnosticCode>(\n compilerDiagnostics,\n );\n\n packageScalars: ReadonlySet<string> = new Set();\n\n fail(\n path: DefinitionPath,\n message: string,\n expected: string,\n received: unknown,\n ): undefined {\n this.collector.add({\n code: \"PH-DM-DECLARATION-INVALID\",\n path,\n message,\n expected,\n received:\n typeof received === \"string\"\n ? received\n : typeof received === \"number\" || typeof received === \"boolean\"\n ? String(received)\n : describeReceived(received),\n repair:\n \"Produce the definition with materialize or a document-model/tooling adapter; a hand-edited wire definition is not accepted.\",\n });\n return undefined;\n }\n\n record(\n value: unknown,\n keys: readonly string[],\n path: DefinitionPath,\n ): Node | undefined {\n const snapshot = snapshotRecord(value, keys, path);\n if (snapshot.ok) return snapshot.value;\n return this.fail(\n snapshot.path,\n `This node is not a plain object with the V1 members (${snapshot.reason}).`,\n keys.join(\", \"),\n rejectionReceived(snapshot),\n );\n }\n\n array(value: unknown, path: DefinitionPath): readonly unknown[] | undefined {\n const snapshot = snapshotArray(value, path);\n if (snapshot.ok) return snapshot.value;\n return this.fail(\n snapshot.path,\n \"This node must be an array.\",\n \"an array\",\n rejectionReceived(snapshot),\n );\n }\n\n string(value: unknown, path: DefinitionPath): string | undefined {\n if (typeof value === \"string\") return value;\n return this.fail(path, \"This member must be a string.\", \"string\", value);\n }\n\n nullableString(value: unknown, path: DefinitionPath): void {\n if (value === null || typeof value === \"string\") return;\n this.fail(\n path,\n \"This member must be a string or null.\",\n \"string | null\",\n value,\n );\n }\n\n literal(\n value: unknown,\n expected: string | number | boolean,\n path: DefinitionPath,\n ): void {\n if (value === expected) return;\n this.fail(path, \"This member has a fixed value.\", String(expected), value);\n }\n\n oneOf<T extends string>(\n value: unknown,\n allowed: readonly T[],\n path: DefinitionPath,\n ): T | undefined {\n if ((allowed as readonly unknown[]).includes(value)) return value as T;\n return this.fail(\n path,\n \"This member is outside its closed set.\",\n allowed.join(\" | \"),\n value,\n );\n }\n\n json(value: unknown, path: DefinitionPath): JsonValue | undefined {\n try {\n canonicalJson(value);\n } catch (error) {\n return this.fail(\n path,\n `This member must be a JSON value: ${error instanceof Error ? error.message : String(error)}`,\n \"a JSON value\",\n value,\n );\n }\n return value as JsonValue;\n }\n\n graphQLName(value: unknown, path: DefinitionPath): string | undefined {\n if (isGraphQLName(value)) return value;\n return this.fail(\n path,\n \"This member must be a GraphQL name.\",\n \"a GraphQL name\",\n value,\n );\n }\n\n rejectHostOnlyScalar(value: unknown, path: DefinitionPath): boolean {\n if (typeof value !== \"string\" || !HOST_ONLY_SCALARS.has(value)) {\n return false;\n }\n this.collector.add({\n code: \"PH-SCALAR-INTERNAL\",\n definition: { kind: \"scalar\", key: value },\n path,\n message: `${value} is internal to the reactor host. A document model cannot use it.`,\n received: value,\n repair:\n \"Use ph.Unknown() for an unconstrained value, or ph.object(...) for a structured one.\",\n });\n return true;\n }\n}\n\nfunction typeReference(\n check: ShapeChecker,\n value: unknown,\n path: DefinitionPath,\n): void {\n const kind = (value as Node | null)?.kind;\n const node =\n kind === \"list\"\n ? check.record(value, [\"kind\", \"required\", \"item\"], path)\n : check.record(value, [\"kind\", \"name\", \"required\"], path);\n if (node === undefined) return;\n if (typeof node.required !== \"boolean\") {\n check.fail(\n [...path, \"required\"],\n \"A type reference records nullability.\",\n \"boolean\",\n node.required,\n );\n }\n if (kind === \"list\") {\n typeReference(check, node.item, [...path, \"item\"]);\n } else if (kind === \"scalar\") {\n if (check.rejectHostOnlyScalar(node.name, [...path, \"name\"])) return;\n if (\n typeof node.name !== \"string\" ||\n !(MODEL_SCALARS.has(node.name) || check.packageScalars.has(node.name))\n ) {\n check.fail(\n [...path, \"name\"],\n \"A scalar reference names a catalog scalar, a GraphQL built-in, or a package scalar the specification declares.\",\n [...MODEL_SCALARS, ...check.packageScalars].join(\" | \"),\n node.name,\n );\n }\n } else if (kind === \"named\") {\n check.graphQLName(node.name, [...path, \"name\"]);\n } else {\n check.fail(\n [...path, \"kind\"],\n \"A type reference has three kinds.\",\n \"scalar | named | list\",\n kind,\n );\n }\n}\n\nfunction directiveUses(\n check: ShapeChecker,\n value: unknown,\n path: DefinitionPath,\n): void {\n check.array(value, path)?.forEach((use, index) => {\n const node = check.record(use, [\"name\", \"arguments\"], [...path, index]);\n if (node === undefined) return;\n check.graphQLName(node.name, [...path, index, \"name\"]);\n const args = check.array(node.arguments, [...path, index, \"arguments\"]);\n args?.forEach((argument, argumentIndex) => {\n const at = [...path, index, \"arguments\", argumentIndex];\n const entry = check.record(argument, [\"name\", \"value\"], at);\n if (entry === undefined) return;\n check.graphQLName(entry.name, [...at, \"name\"]);\n check.json(entry.value, [...at, \"value\"]);\n });\n });\n}\n\nconst FIELD_KEYS = [\"key\", \"name\", \"description\", \"deprecated\", \"type\"];\n\nfunction field(\n check: ShapeChecker,\n value: unknown,\n path: DefinitionPath,\n input: boolean,\n): void {\n const node = check.record(\n value,\n [...FIELD_KEYS, \"directives\", input ? \"defaultValue\" : \"args\"],\n path,\n );\n if (node === undefined) return;\n check.string(node.key, [...path, \"key\"]);\n check.graphQLName(node.name, [...path, \"name\"]);\n check.nullableString(node.description, [...path, \"description\"]);\n check.nullableString(node.deprecated, [...path, \"deprecated\"]);\n typeReference(check, node.type, [...path, \"type\"]);\n if (node.directives !== undefined) {\n directiveUses(check, node.directives, [...path, \"directives\"]);\n }\n if (input) {\n if (Object.hasOwn(node, \"defaultValue\")) {\n check.json(node.defaultValue, [...path, \"defaultValue\"]);\n }\n } else if (node.args !== undefined) {\n check\n .array(node.args, [...path, \"args\"])\n ?.forEach((argument, index) =>\n field(check, argument, [...path, \"args\", index], true),\n );\n }\n}\n\nfunction fields(\n check: ShapeChecker,\n value: unknown,\n path: DefinitionPath,\n input: boolean,\n): void {\n check\n .array(value, path)\n ?.forEach((entry, index) => field(check, entry, [...path, index], input));\n}\n\nfunction enumValue(\n check: ShapeChecker,\n value: unknown,\n path: DefinitionPath,\n): void {\n const node = check.record(\n value,\n [\"name\", \"description\", \"deprecated\", \"directives\"],\n path,\n );\n if (node === undefined) return;\n check.graphQLName(node.name, [...path, \"name\"]);\n check.nullableString(node.description, [...path, \"description\"]);\n check.nullableString(node.deprecated, [...path, \"deprecated\"]);\n if (node.directives !== undefined) {\n directiveUses(check, node.directives, [...path, \"directives\"]);\n }\n}\n\nconst NAMED_TYPE_MEMBERS = {\n enum: \"values\",\n object: \"fields\",\n interface: \"fields\",\n input: \"fields\",\n union: \"members\",\n} as const;\n\nfunction namedType(\n check: ShapeChecker,\n value: unknown,\n path: DefinitionPath,\n): string | undefined {\n const kind = (value as Node | null)?.kind;\n if (typeof kind !== \"string\" || !Object.hasOwn(NAMED_TYPE_MEMBERS, kind)) {\n return check.fail(\n [...path, \"kind\"],\n \"A named type has five kinds.\",\n Object.keys(NAMED_TYPE_MEMBERS).join(\" | \"),\n kind,\n );\n }\n const typed = kind as keyof typeof NAMED_TYPE_MEMBERS;\n const member = NAMED_TYPE_MEMBERS[typed];\n const extra =\n typed === \"object\" || typed === \"interface\"\n ? [\"implements\"]\n : typed === \"input\"\n ? [\"unknownKeys\"]\n : [];\n const node = check.record(\n value,\n [\"kind\", \"name\", \"description\", ...extra, member],\n path,\n );\n if (node === undefined) return undefined;\n check.nullableString(node.description, [...path, \"description\"]);\n const members = check.array(node[member], [...path, member]);\n switch (typed) {\n case \"enum\":\n members?.forEach((entry, index) =>\n enumValue(check, entry, [...path, \"values\", index]),\n );\n break;\n case \"union\":\n members?.forEach((entry, index) =>\n check.graphQLName(entry, [...path, \"members\", index]),\n );\n break;\n case \"input\":\n check.oneOf(\n node.unknownKeys,\n [\"preserve\", \"reject\"],\n [...path, \"unknownKeys\"],\n );\n fields(check, node.fields, [...path, \"fields\"], true);\n break;\n default:\n if (node.implements !== undefined) {\n check\n .array(node.implements, [...path, \"implements\"])\n ?.forEach((entry, index) =>\n check.graphQLName(entry, [...path, \"implements\", index]),\n );\n }\n fields(check, node.fields, [...path, \"fields\"], false);\n }\n return check.graphQLName(node.name, [...path, \"name\"]);\n}\n\nfunction examples(\n check: ShapeChecker,\n value: unknown,\n path: DefinitionPath,\n keys: readonly string[],\n): void {\n check.array(value, path)?.forEach((entry, index) => {\n const node = check.record(entry, keys, [...path, index]);\n if (node === undefined) return;\n for (const key of keys) check.string(node[key], [...path, index, key]);\n });\n}\n\nfunction state(\n check: ShapeChecker,\n value: unknown,\n path: DefinitionPath,\n scope: \"global\" | \"local\",\n): void {\n const node = check.record(\n value,\n [\"root\", \"initialValue\", \"examples\", \"unknownKeys\", \"materialized\"],\n path,\n );\n if (node === undefined) return;\n if (node.root === null) {\n if (scope === \"global\") {\n check.fail(\n [...path, \"root\"],\n \"A global state always has a root.\",\n \"a named type reference\",\n null,\n );\n }\n if (\n check.json(node.initialValue, [...path, \"initialValue\"]) !== undefined\n ) {\n if (canonicalJson(node.initialValue) !== \"{}\") {\n check.fail(\n [...path, \"initialValue\"],\n \"An empty local state carries an exact empty object.\",\n \"{}\",\n node.initialValue,\n );\n }\n }\n } else {\n typeReference(check, node.root, [...path, \"root\"]);\n check.json(node.initialValue, [...path, \"initialValue\"]);\n }\n check.literal(node.unknownKeys, \"preserve\", [...path, \"unknownKeys\"]);\n examples(check, node.examples, [...path, \"examples\"], [\"id\", \"key\", \"value\"]);\n const materializedPath = [...path, \"materialized\"];\n const materialized = check.record(\n node.materialized,\n [\"schema\", \"initialValue\", \"examples\"],\n materializedPath,\n );\n if (materialized === undefined) return;\n const schema = check.string(materialized.schema, [\n ...materializedPath,\n \"schema\",\n ]);\n if (node.root === null && schema !== undefined && schema !== \"\") {\n check.fail(\n [...materializedPath, \"schema\"],\n \"An empty local state materializes an empty schema.\",\n '\"\"',\n schema,\n );\n }\n check.string(materialized.initialValue, [\n ...materializedPath,\n \"initialValue\",\n ]);\n examples(\n check,\n materialized.examples,\n [...materializedPath, \"examples\"],\n [\"id\", \"value\"],\n );\n}\n\nconst OPERATION_KEYS = [\n \"id\",\n \"key\",\n \"name\",\n \"description\",\n \"actionType\",\n \"creatorKey\",\n \"scope\",\n \"input\",\n \"errors\",\n \"examples\",\n \"template\",\n \"reducer\",\n];\nconst ERROR_KEYS = [\"id\", \"key\", \"code\", \"name\", \"description\", \"template\"];\n\nfunction operation(\n check: ShapeChecker,\n value: unknown,\n path: DefinitionPath,\n): void {\n const node = check.record(value, OPERATION_KEYS, path);\n if (node === undefined) return;\n for (const key of [\"id\", \"key\", \"actionType\", \"creatorKey\"]) {\n check.string(node[key], [...path, key]);\n }\n for (const key of [\"name\", \"description\", \"template\", \"reducer\"]) {\n check.nullableString(node[key], [...path, key]);\n }\n check.oneOf(node.scope, [\"global\", \"local\"], [...path, \"scope\"]);\n if (node.input !== null) {\n const kind = (node.input as Node | null)?.kind;\n if (kind !== \"input\") {\n check.fail(\n [...path, \"input\", \"kind\"],\n \"An operation input is an input type.\",\n \"input\",\n kind,\n );\n } else {\n namedType(check, node.input, [...path, \"input\"]);\n }\n }\n check.array(node.errors, [...path, \"errors\"])?.forEach((entry, index) => {\n const at = [...path, \"errors\", index];\n const error = check.record(entry, ERROR_KEYS, at);\n if (error === undefined) return;\n check.string(error.id, [...at, \"id\"]);\n check.string(error.key, [...at, \"key\"]);\n for (const key of [\"code\", \"name\", \"description\", \"template\"]) {\n check.nullableString(error[key], [...at, key]);\n }\n });\n examples(check, node.examples, [...path, \"examples\"], [\"id\", \"key\", \"value\"]);\n}\n\nfunction storedScalar(\n check: ShapeChecker,\n value: unknown,\n name: string,\n path: DefinitionPath,\n): void {\n const node = check.record(\n value,\n [\n \"kind\",\n \"formatVersion\",\n \"name\",\n \"representation\",\n \"description\",\n \"coercion\",\n \"coercionProfile\",\n ],\n path,\n );\n if (node === undefined) return;\n check.literal(node.kind, \"powerhouse.scalar\", [...path, \"kind\"]);\n check.literal(node.formatVersion, 1, [...path, \"formatVersion\"]);\n check.literal(node.name, name, [...path, \"name\"]);\n check.oneOf(node.representation, SCALAR_REPRESENTATIONS, [\n ...path,\n \"representation\",\n ]);\n check.string(node.description, [...path, \"description\"]);\n check.literal(node.coercionProfile, \"catalog-v1\", [\n ...path,\n \"coercionProfile\",\n ]);\n const coercion = check.record(\n node.coercion,\n [\"source\"],\n [...path, \"coercion\"],\n );\n if (coercion !== undefined) {\n check.oneOf(\n coercion.source,\n [\"derived\", \"explicit\"],\n [...path, \"coercion\", \"source\"],\n );\n }\n}\n\nfunction scalars(\n check: ShapeChecker,\n value: unknown,\n path: DefinitionPath,\n): ReadonlySet<string> {\n const declared = new Set<string>();\n check.array(value, path)?.forEach((entry, index) => {\n const at = [...path, index];\n const isPackage =\n typeof entry === \"object\" &&\n entry !== null &&\n Object.hasOwn(entry, \"definition\");\n const scalar = check.record(\n entry,\n [\"name\", \"implementation\", \"coercionProfile\", \"definition\"],\n at,\n );\n if (scalar === undefined) return;\n check.literal(scalar.coercionProfile, \"catalog-v1\", [\n ...at,\n \"coercionProfile\",\n ]);\n if (check.rejectHostOnlyScalar(scalar.name, [...at, \"name\"])) return;\n if (!isPackage) {\n const name = check.oneOf(scalar.name, CATALOG_SCALARS, [...at, \"name\"]);\n if (name !== undefined) {\n check.literal(scalar.implementation, `powerhouse.catalog#${name}`, [\n ...at,\n \"implementation\",\n ]);\n }\n return;\n }\n const name = check.graphQLName(scalar.name, [...at, \"name\"]);\n if (name === undefined) return;\n if (MODEL_SCALARS.has(name) || declared.has(name)) {\n check.fail(\n [...at, \"name\"],\n \"A package scalar has a name no catalog scalar, GraphQL built-in, or other package scalar uses.\",\n \"an unused GraphQL name\",\n name,\n );\n return;\n }\n check.literal(scalar.implementation, `package#${name}`, [\n ...at,\n \"implementation\",\n ]);\n storedScalar(check, scalar.definition, name, [...at, \"definition\"]);\n declared.add(name);\n });\n return declared;\n}\n\nfunction specification(\n check: ShapeChecker,\n value: unknown,\n path: DefinitionPath,\n): void {\n const node = check.record(\n value,\n [\n \"version\",\n \"scalars\",\n \"graphQLCompatibility\",\n \"types\",\n \"state\",\n \"modules\",\n \"changeLog\",\n ],\n path,\n );\n if (node === undefined) return;\n if (\n typeof node.version !== \"number\" ||\n !Number.isSafeInteger(node.version) ||\n node.version <= 0\n ) {\n check.fail(\n [...path, \"version\"],\n \"A specification version is a positive safe integer.\",\n \"a positive safe integer\",\n node.version,\n );\n }\n check.packageScalars = scalars(check, node.scalars, [...path, \"scalars\"]);\n\n if (node.graphQLCompatibility !== null) {\n const at = [...path, \"graphQLCompatibility\"];\n const compatibility = check.record(\n node.graphQLCompatibility,\n [\"kind\", \"document\", \"preserveDefinitionOrder\"],\n at,\n );\n if (compatibility !== undefined) {\n check.literal(compatibility.kind, \"graphql-ast-v1\", [...at, \"kind\"]);\n check.literal(compatibility.preserveDefinitionOrder, true, [\n ...at,\n \"preserveDefinitionOrder\",\n ]);\n check.collector.merge(\n validateLocationFreeDocument(compatibility.document, [\n ...at,\n \"document\",\n ]),\n );\n }\n }\n\n const declared = new Set<string>();\n check.array(node.types, [...path, \"types\"])?.forEach((entry, index) => {\n const name = namedType(check, entry, [...path, \"types\", index]);\n if (name === undefined) return;\n if (declared.has(name) || check.packageScalars.has(name)) {\n check.fail(\n [...path, \"types\", index, \"name\"],\n \"A named type is declared once per specification, and never under a package scalar's name.\",\n \"one definition per name\",\n name,\n );\n }\n declared.add(name);\n });\n\n const stateNode = check.record(\n node.state,\n [\"global\", \"local\"],\n [...path, \"state\"],\n );\n if (stateNode !== undefined) {\n for (const scope of [\"global\", \"local\"] as const) {\n state(check, stateNode[scope], [...path, \"state\", scope], scope);\n const root = (stateNode[scope] as Node | undefined)?.root as\n | Node\n | null\n | undefined;\n if (typeof root?.name === \"string\" && !declared.has(root.name)) {\n check.fail(\n [...path, \"state\", scope, \"root\", \"name\"],\n \"A state root is declared in this specification's types.\",\n [...declared].join(\" | \"),\n root.name,\n );\n }\n }\n }\n\n check.array(node.modules, [...path, \"modules\"])?.forEach((entry, index) => {\n const at = [...path, \"modules\", index];\n const module = check.record(\n entry,\n [\"id\", \"key\", \"name\", \"description\", \"operations\"],\n at,\n );\n if (module === undefined) return;\n check.string(module.id, [...at, \"id\"]);\n check.string(module.key, [...at, \"key\"]);\n check.string(module.name, [...at, \"name\"]);\n check.nullableString(module.description, [...at, \"description\"]);\n check\n .array(module.operations, [...at, \"operations\"])\n ?.forEach((candidate, operationIndex) =>\n operation(check, candidate, [...at, \"operations\", operationIndex]),\n );\n });\n\n check\n .array(node.changeLog, [...path, \"changeLog\"])\n ?.forEach((entry, index) =>\n check.string(entry, [...path, \"changeLog\", index]),\n );\n}\n\nexport function checkDocumentModelDefinitionShape(\n value: unknown,\n path: DefinitionPath = [],\n): readonly DefinitionDiagnostic[] {\n const check = new ShapeChecker();\n const node = check.record(\n value,\n [\"kind\", \"formatVersion\", \"compatibility\", \"model\", \"specifications\"],\n path,\n );\n if (node === undefined) return check.collector.diagnostics;\n check.literal(node.kind, \"powerhouse.document-model\", [...path, \"kind\"]);\n check.literal(node.formatVersion, 1, [...path, \"formatVersion\"]);\n\n const compatibilityPath = [...path, \"compatibility\"];\n const compatibility = check.record(\n node.compatibility,\n [\"identity\", \"scalarCoercion\", \"serialization\"],\n compatibilityPath,\n );\n if (compatibility !== undefined) {\n check.oneOf(\n compatibility.identity,\n [\"derived-v1\", \"explicit-schema-first\"],\n [...compatibilityPath, \"identity\"],\n );\n check.literal(compatibility.scalarCoercion, \"catalog-v1\", [\n ...compatibilityPath,\n \"scalarCoercion\",\n ]);\n check.oneOf(\n compatibility.serialization,\n [\"canonical-v1\", \"explicit-schema-first\"],\n [...compatibilityPath, \"serialization\"],\n );\n }\n\n const modelPath = [...path, \"model\"];\n const model = check.record(\n node.model,\n [\n \"documentType\",\n \"graphQLName\",\n \"name\",\n \"description\",\n \"extension\",\n \"author\",\n ],\n modelPath,\n );\n if (model !== undefined) {\n if (\n check.string(model.documentType, [...modelPath, \"documentType\"]) === \"\"\n ) {\n check.fail(\n [...modelPath, \"documentType\"],\n \"A document type is not empty.\",\n \"a document type\",\n '\"\"',\n );\n }\n check.graphQLName(model.graphQLName, [...modelPath, \"graphQLName\"]);\n for (const key of [\"name\", \"description\", \"extension\"]) {\n check.string(model[key], [...modelPath, key]);\n }\n const author = check.record(\n model.author,\n [\"name\", \"website\"],\n [...modelPath, \"author\"],\n );\n if (author !== undefined) {\n check.string(author.name, [...modelPath, \"author\", \"name\"]);\n check.nullableString(author.website, [...modelPath, \"author\", \"website\"]);\n }\n }\n\n const specifications = check.array(node.specifications, [\n ...path,\n \"specifications\",\n ]);\n if (specifications?.length === 0) {\n check.fail(\n [...path, \"specifications\"],\n \"A definition carries at least one specification.\",\n \"a nonempty specification history\",\n \"an empty array\",\n );\n }\n specifications?.forEach((entry, index) =>\n specification(check, entry, [...path, \"specifications\", index]),\n );\n return check.collector.diagnostics;\n}\n","import { compilerDiagnostics } from \"../compiler/diagnostic-codes.js\";\nimport { defineDiagnosticCatalog } from \"../kernel/diagnostics.js\";\n\nexport const modelDiagnostics = defineDiagnosticCatalog(\n {\n \"PH-DM-STATE-ROOT-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"A required state root is absent, is not an object, or has the wrong canonical name\",\n },\n \"PH-DM-SCOPE-UNSUPPORTED\": {\n severity: \"error\",\n phase: \"definition\",\n meaning: \"A definition requests a scope outside global or local\",\n },\n \"PH-AUTH-UNSUPPORTED\": {\n severity: \"error\",\n phase: \"authorization\",\n meaning: \"A document model declares authorization, which core v1 rejects\",\n },\n },\n compilerDiagnostics,\n);\n\nexport type ModelDiagnosticCode = keyof typeof modelDiagnostics.codes;\n","import { defineDiagnosticCatalog } from \"../kernel/diagnostics.js\";\nimport { modelDiagnostics } from \"../model/diagnostic-codes.js\";\n\nexport const toolingDiagnostics = defineDiagnosticCatalog(\n {\n \"PH-CONFIG-SOURCE-INVALID\": {\n severity: \"error\",\n phase: \"configuration\",\n meaning:\n \"The config file, a definition source entry, or an export pointer cannot select a module export\",\n },\n \"PH-CONFIG-SOURCE-OUTSIDE-PACKAGE\": {\n severity: \"error\",\n phase: \"configuration\",\n meaning:\n \"A definition source path, or the real path behind its symlinks, leaves the package root\",\n },\n \"PH-CONFIG-DUPLICATE-SOURCE\": {\n severity: \"error\",\n phase: \"configuration\",\n meaning: \"Two entries select the same module and export path\",\n },\n \"PH-CONFIG-VERSION-UNSUPPORTED\": {\n severity: \"error\",\n phase: \"configuration\",\n meaning:\n \"definitionSources declares a format version this release does not read\",\n },\n \"PH-IMPORT-FAILED\": {\n severity: \"error\",\n phase: \"import\",\n meaning:\n \"A selected module is missing, throws while it is evaluated, or the import adapter returned no namespace\",\n },\n \"PH-PKG-DEFINITION-UNRECOGNIZED\": {\n severity: \"error\",\n phase: \"package\",\n meaning:\n \"A selected export holds no materialized document model, family, or upgrade manifest\",\n },\n \"PH-PKG-DEFINITION-UNINSPECTABLE\": {\n severity: \"error\",\n phase: \"package\",\n meaning:\n \"A selected export hides its members behind an accessor or a Proxy\",\n },\n \"PH-PKG-LOGICAL-COLLISION\": {\n severity: \"error\",\n phase: \"package\",\n meaning:\n \"Two distinct values claim one document type and version, or one upgrade manifest document type\",\n },\n },\n modelDiagnostics,\n);\n\nexport type ToolingDiagnosticCode = keyof typeof toolingDiagnostics.codes;\n","import type {\n DefinitionPath,\n DefinitionSource,\n DocumentModelDefinition,\n DocumentModelPHState,\n UpgradeManifest,\n} from \"@powerhousedao/shared/document-model\";\nimport { checkDocumentModelDefinitionShape } from \"../../compiler/wire-shape.js\";\nimport {\n rejectionReceived,\n snapshotArray,\n snapshotRecord,\n} from \"../../kernel/data-properties.js\";\nimport { DefinitionDiagnosticCollector } from \"../../kernel/diagnostic-collector.js\";\nimport { describeReceived } from \"../../kernel/diagnostics.js\";\nimport { canonicalDigest, canonicalJson } from \"../../kernel/primitives.js\";\nimport {\n type ToolingDiagnosticCode,\n toolingDiagnostics,\n} from \"../diagnostic-codes.js\";\nimport type {\n NormalizedDocumentModelArtifact,\n NormalizedDocumentModelResult,\n} from \"./types.js\";\n\ntype Collector = DefinitionDiagnosticCollector<ToolingDiagnosticCode>;\n\nconst MODULE_KEYS =\n \"version, reducer, actions, utils, documentModel, definition\";\nconst REPAIR =\n \"Export the module materialize returned, or family.at(version), without replacing its members.\";\n\nfunction sourceOf(\n source: DefinitionSource,\n exportPath: readonly string[],\n): DefinitionSource {\n const path = [...(source.exportPath ?? []), ...exportPath];\n return {\n specifier: source.specifier,\n ...(path.length > 0 && { exportPath: path }),\n };\n}\n\nfunction invalid(\n collector: Collector,\n path: DefinitionPath,\n message: string,\n expected: string,\n received: string,\n repair = REPAIR,\n): undefined {\n collector.add({\n code: \"PH-DM-DECLARATION-INVALID\",\n path,\n message,\n expected,\n received,\n repair,\n });\n return undefined;\n}\n\nfunction storedDocumentType(\n collector: Collector,\n value: unknown,\n path: DefinitionPath,\n): string | undefined {\n const documentModel = snapshotRecord(value, undefined, path);\n const global = documentModel.ok\n ? snapshotRecord(documentModel.value.global, undefined, [...path, \"global\"])\n : documentModel;\n if (!global.ok) {\n return invalid(\n collector,\n global.path,\n `A module keeps its stored model in documentModel.global as plain data, and it cannot be read (${global.reason}).`,\n \"documentModel.global as a plain record of data properties\",\n rejectionReceived(global),\n );\n }\n const id = global.value.id;\n if (typeof id !== \"string\" || id === \"\") {\n return invalid(\n collector,\n [...path, \"global\", \"id\"],\n \"A module has a stored model ID.\",\n \"a nonempty document type\",\n typeof id === \"string\" ? '\"\"' : describeReceived(id),\n \"Declare id in defineDocumentModel; the stored model ID is the document type every consumer registers.\",\n );\n }\n return id;\n}\n\nfunction artifact(\n collector: Collector,\n value: unknown,\n source: DefinitionSource,\n path: DefinitionPath,\n): NormalizedDocumentModelArtifact | undefined {\n const snapshot = snapshotRecord(value, undefined, path);\n if (!snapshot.ok) {\n return invalid(\n collector,\n snapshot.path,\n `This export is not a document-model module (${snapshot.reason}).`,\n MODULE_KEYS,\n rejectionReceived(snapshot),\n );\n }\n const module = snapshot.value;\n let usable = true;\n if (typeof module.reducer !== \"function\") {\n usable = false;\n invalid(\n collector,\n [...path, \"reducer\"],\n \"A module has a callable reducer.\",\n \"a reducer function\",\n describeReceived(module.reducer),\n );\n }\n const version = module.version;\n if (\n typeof version !== \"number\" ||\n !Number.isSafeInteger(version) ||\n version <= 0\n ) {\n usable = false;\n invalid(\n collector,\n [...path, \"version\"],\n \"A code-first module declares its registry version as a positive safe integer.\",\n \"a positive safe integer\",\n typeof version === \"number\" ? String(version) : describeReceived(version),\n );\n }\n const documentType = storedDocumentType(collector, module.documentModel, [\n ...path,\n \"documentModel\",\n ]);\n if (module.definition === undefined) {\n return invalid(\n collector,\n [...path, \"definition\"],\n \"This module carries no structured definition, so it was not made by materialize.\",\n \"the definition materialize attaches\",\n \"undefined\",\n \"Export the module materialize returned.\",\n );\n }\n const shape = checkDocumentModelDefinitionShape(module.definition, [\n ...path,\n \"definition\",\n ]);\n collector.merge(shape);\n if (\n !usable ||\n documentType === undefined ||\n shape.length > 0 ||\n typeof version !== \"number\"\n ) {\n return undefined;\n }\n const definition = module.definition as DocumentModelDefinition;\n\n if (definition.model.documentType !== documentType) {\n return invalid(\n collector,\n [...path, \"definition\", \"model\", \"documentType\"],\n \"The structured definition and the stored model describe different document types.\",\n documentType,\n definition.model.documentType,\n \"Materialize the module and its definition from the same declaration.\",\n );\n }\n if (!definition.specifications.some((entry) => entry.version === version)) {\n return invalid(\n collector,\n [...path, \"definition\", \"specifications\"],\n `The specification history carries no version ${version}, which is the version this module serves.`,\n `a specification for version ${version}`,\n definition.specifications\n .map((entry) => String(entry.version))\n .join(\", \"),\n \"Compose the versions with defineDocumentModelFamily so every module carries the complete history.\",\n );\n }\n return {\n kind: \"powerhouse.document-model-artifact\",\n source,\n documentType,\n version,\n definition,\n digest: canonicalDigest(definition),\n documentModel: module.documentModel as DocumentModelPHState,\n };\n}\n\nfunction familyManifest(\n collector: Collector,\n value: unknown,\n artifacts: readonly NormalizedDocumentModelArtifact[],\n path: DefinitionPath,\n): UpgradeManifest<readonly number[]> | null {\n const snapshot = snapshotRecord(value, undefined, path);\n const manifest = snapshot.ok ? snapshot.value : undefined;\n const versions = artifacts.map((entry) => entry.version);\n const supported = manifest?.supportedVersions;\n const declared =\n Array.isArray(supported) && supported.every(Number.isSafeInteger)\n ? canonicalJson(supported)\n : describeReceived(supported);\n if (\n manifest === undefined ||\n declared !== canonicalJson(versions) ||\n manifest.latestVersion !== versions.at(-1)\n ) {\n invalid(\n collector,\n snapshot.ok ? path : snapshot.path,\n \"A family's upgrade manifest covers exactly the versions its modules serve.\",\n canonicalJson(versions),\n snapshot.ok ? declared : rejectionReceived(snapshot),\n \"Export the family materialize returned, so its manifest and modules stay one declaration.\",\n );\n return null;\n }\n const documentTypes = new Set(artifacts.map((entry) => entry.documentType));\n if (\n documentTypes.size !== 1 ||\n !documentTypes.has(manifest.documentType as string)\n ) {\n invalid(\n collector,\n [...path, \"documentType\"],\n \"A family's upgrade manifest and its modules name one document type.\",\n [...documentTypes].join(\", \"),\n String(manifest.documentType),\n \"Compose one family per document type.\",\n );\n return null;\n }\n return value as UpgradeManifest<readonly number[]>;\n}\n\n/**\n * @experimental Normalizes one materialized code-first module, or a family\n * and its versions in order. A family reports every malformed member: a\n * valid sibling never makes a broken one pass.\n */\nexport function adaptCodeFirstDocumentModelSource(\n value: unknown,\n source: DefinitionSource,\n): NormalizedDocumentModelResult {\n const collector: Collector = new DefinitionDiagnosticCollector(\n toolingDiagnostics,\n );\n const family = snapshotRecord(value, undefined, []);\n const modules =\n family.ok && typeof family.value.at === \"function\"\n ? snapshotArray(family.value.modules, [\"modules\"])\n : undefined;\n if (family.ok && modules?.ok === true) {\n const artifacts = modules.value.flatMap((module, index) => {\n const entry = artifact(\n collector,\n module,\n sourceOf(source, [\"modules\", String(index)]),\n [\"modules\", index],\n );\n return entry === undefined ? [] : [entry];\n });\n const manifest =\n artifacts.length === modules.value.length\n ? familyManifest(collector, family.value.upgradeManifest, artifacts, [\n \"upgradeManifest\",\n ])\n : null;\n return {\n artifacts,\n upgradeManifest: manifest,\n diagnostics: collector.diagnostics,\n };\n }\n const single = artifact(collector, value, source, []);\n return {\n artifacts: single === undefined ? [] : [single],\n upgradeManifest: null,\n diagnostics: collector.diagnostics,\n };\n}\n","import {\n DEFAULT_AUTHORING_MODE,\n parseDefinitionSourcesConfig,\n} from \"@powerhousedao/shared/clis/definition-sources\";\nimport type {\n DefinitionCheckSkipReason,\n DefinitionDiagnostic,\n DefinitionPath,\n DefinitionSource,\n} from \"@powerhousedao/shared/document-model\";\nimport { existsSync, readFileSync, realpathSync } from \"node:fs\";\nimport { dirname, isAbsolute, posix, relative, resolve, sep } from \"node:path\";\nimport {\n compareDefinitionPaths,\n sortDefinitionDiagnostics,\n} from \"../kernel/diagnostics.js\";\nimport {\n canonicalDigest,\n compareCodeUnits,\n isNFC,\n} from \"../kernel/primitives.js\";\nimport type {\n DefinitionSourceOrigin,\n DefinitionSourceResolution,\n DefinitionSourceSelectionRequest,\n DefinitionSourceSet,\n} from \"./definition-source-types.js\";\nimport { toolingDiagnostics } from \"./diagnostic-codes.js\";\n\nexport type ResolvedDefinitionSource = {\n readonly source: DefinitionSource;\n\n readonly position: DefinitionPath;\n\n readonly moduleIdentity: string;\n};\n\nexport type InternalResolution = DefinitionSourceResolution & {\n readonly packageRootIdentity: string;\n readonly resolved: readonly ResolvedDefinitionSource[];\n};\n\nconst CONFIG_FILE_NAME = \"./powerhouse.config.json\";\n\nconst IDENTITY_SEPARATOR = String.fromCharCode(0);\n\nfunction render(value: unknown): string {\n if (typeof value === \"string\") return value;\n if (value === undefined) return \"undefined\";\n try {\n // `JSON.stringify` returns `undefined` for a function or a symbol.\n const json = JSON.stringify(value) as string | undefined;\n return json ?? typeof value;\n } catch {\n return typeof value;\n }\n}\n\nfunction sourceSet(\n mode: DefinitionSourceSet[\"mode\"],\n origin: DefinitionSourceOrigin,\n sources: readonly DefinitionSource[],\n): DefinitionSourceSet {\n const value = { mode, origin, sources };\n return { ...value, digest: canonicalDigest(value) };\n}\n\nexport function compareDefinitionSources(\n left: DefinitionSource,\n right: DefinitionSource,\n): number {\n const specifier = compareCodeUnits(left.specifier, right.specifier);\n if (specifier !== 0) return specifier;\n const leftPath = left.exportPath ?? [];\n const rightPath = right.exportPath ?? [];\n for (\n let index = 0;\n index < Math.min(leftPath.length, rightPath.length);\n index += 1\n ) {\n const segment = compareCodeUnits(leftPath[index], rightPath[index]);\n if (segment !== 0) return segment;\n }\n return leftPath.length - rightPath.length;\n}\n\nfunction isCanonicalText(value: string): boolean {\n for (const character of value) {\n const codePoint = character.codePointAt(0) ?? 0;\n if (codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f)) {\n return false;\n }\n }\n return isNFC(value);\n}\n\nexport function isWithin(root: string, path: string): boolean {\n const child = relative(root, path);\n return child !== \"..\" && !child.startsWith(`..${sep}`) && !isAbsolute(child);\n}\n\ntype SpecifierResult =\n | { readonly ok: true; readonly specifier: `./${string}` }\n | {\n readonly ok: false;\n readonly code:\n | \"PH-CONFIG-SOURCE-INVALID\"\n | \"PH-CONFIG-SOURCE-OUTSIDE-PACKAGE\";\n readonly message: string;\n };\n\nexport function normalizeSpecifier(value: string): SpecifierResult {\n if (\n !value.startsWith(\"./\") ||\n /[\\\\#?]/.test(value) ||\n !isCanonicalText(value)\n ) {\n return {\n ok: false,\n code: \"PH-CONFIG-SOURCE-INVALID\",\n message:\n \"A definition source is a POSIX package-relative path beginning with './'.\",\n };\n }\n const normalized = posix.normalize(value.slice(2));\n if (normalized === \".\" || normalized === \"./\") {\n return {\n ok: false,\n code: \"PH-CONFIG-SOURCE-INVALID\",\n message: \"A definition source names a module file, not the package root.\",\n };\n }\n if (normalized === \"..\" || normalized.startsWith(\"../\")) {\n return {\n ok: false,\n code: \"PH-CONFIG-SOURCE-OUTSIDE-PACKAGE\",\n message: \"The normalized definition source path leaves the package root.\",\n };\n }\n if (!/\\.(?:[cm]?[jt]s|[jt]sx)$/.test(value)) {\n return {\n ok: false,\n code: \"PH-CONFIG-SOURCE-INVALID\",\n message:\n \"A definition source names a JavaScript or TypeScript module file with its extension.\",\n };\n }\n return { ok: true, specifier: `./${normalized}` };\n}\n\n/**\n * Resolves symlinks as far as the path exists, so a source that is not\n * written yet is still judged against the real package root.\n */\nexport function realPathThroughExistingParent(path: string): string {\n let current = path;\n const suffix: string[] = [];\n while (!existsSync(current)) {\n const parent = dirname(current);\n if (parent === current) return path;\n suffix.unshift(relative(parent, current));\n current = parent;\n }\n return resolve(realpathSync.native(current), ...suffix);\n}\n\n/** Where a lexically contained module really lives, unless a symlink takes it out of the package. */\nexport function realModulePath(\n packageRoot: string,\n packageRootIdentity: string,\n specifier: `./${string}`,\n):\n | { readonly ok: true; readonly moduleIdentity: string }\n | { readonly ok: false; readonly reason: \"unresolvable\" | \"outside\" } {\n let moduleIdentity: string;\n try {\n moduleIdentity = realPathThroughExistingParent(\n resolve(packageRoot, ...specifier.slice(2).split(\"/\")),\n );\n } catch {\n return { ok: false, reason: \"unresolvable\" };\n }\n return isWithin(packageRootIdentity, moduleIdentity)\n ? { ok: true, moduleIdentity }\n : { ok: false, reason: \"outside\" };\n}\n\ntype EntryResult =\n | { readonly source: ResolvedDefinitionSource }\n | { readonly diagnostic: DefinitionDiagnostic };\n\nfunction invalidEntry(\n path: DefinitionPath,\n message: string,\n expected: string,\n received: string,\n repair: string,\n source?: DefinitionSource,\n): EntryResult {\n return {\n diagnostic: toolingDiagnostics.create({\n code: \"PH-CONFIG-SOURCE-INVALID\",\n ...(source !== undefined && { source }),\n path,\n message,\n expected,\n received,\n repair,\n }),\n };\n}\n\nfunction normalizeEntry(\n value: unknown,\n position: DefinitionPath,\n packageRoot: string,\n packageRootIdentity: string,\n): EntryResult {\n if (\n value === null ||\n typeof value !== \"object\" ||\n Object.getPrototypeOf(value) !== Object.prototype\n ) {\n return invalidEntry(\n position,\n \"A definition source entry must be a plain object.\",\n \"{ specifier, exportPath? }\",\n render(value),\n 'Replace this entry with { \"specifier\": \"./src/<module>.ts\" }.',\n );\n }\n const entry = value as Record<string, unknown>;\n const extra = Object.keys(entry)\n .filter((key) => key !== \"specifier\" && key !== \"exportPath\")\n .sort(compareCodeUnits);\n if (extra.length > 0) {\n return invalidEntry(\n position,\n \"A definition source entry carries unsupported properties.\",\n \"specifier and optional exportPath\",\n extra.join(\", \"),\n `Remove ${extra.join(\", \")} from this entry.`,\n );\n }\n const specifierPath = [...position, \"specifier\"];\n if (typeof entry.specifier !== \"string\") {\n return invalidEntry(\n specifierPath,\n \"A definition source specifier must be a string.\",\n \"a './' POSIX package-relative path\",\n render(entry.specifier),\n \"Set specifier to the package-relative TypeScript module path.\",\n );\n }\n const normalized = normalizeSpecifier(entry.specifier);\n if (!normalized.ok) {\n return {\n diagnostic: toolingDiagnostics.create({\n code: normalized.code,\n path: specifierPath,\n message: normalized.message,\n expected: \"a './' path contained by the selected package root\",\n received: entry.specifier,\n repair:\n \"Move the module inside the package and spell its path relative to the config file.\",\n }),\n };\n }\n const { specifier } = normalized;\n\n let exportPath: readonly string[] | undefined;\n if (entry.exportPath !== undefined) {\n const valid =\n Array.isArray(entry.exportPath) &&\n entry.exportPath.every(\n (segment) => typeof segment === \"string\" && isCanonicalText(segment),\n );\n if (!valid) {\n return invalidEntry(\n [...position, \"exportPath\"],\n \"An exportPath is an array of exact property keys in NFC, without control characters.\",\n \"an array of property-key strings\",\n render(entry.exportPath),\n \"Replace exportPath with the exported property keys, outermost first.\",\n { specifier },\n );\n }\n const segments = entry.exportPath as readonly string[];\n if (segments.length > 0) exportPath = [...segments];\n }\n\n const source: DefinitionSource =\n exportPath === undefined ? { specifier } : { specifier, exportPath };\n const real = realModulePath(packageRoot, packageRootIdentity, specifier);\n if (!real.ok && real.reason === \"unresolvable\") {\n return invalidEntry(\n specifierPath,\n \"The definition source path could not be resolved.\",\n \"a resolvable path inside the package root\",\n specifier,\n \"Fix the path, or the permissions of a directory on the way to it.\",\n source,\n );\n }\n if (!real.ok) {\n return {\n diagnostic: toolingDiagnostics.create({\n code: \"PH-CONFIG-SOURCE-OUTSIDE-PACKAGE\",\n source,\n path: specifierPath,\n message:\n \"The definition source resolves through a symlink that leaves the package root.\",\n expected: \"a real path contained by the package root\",\n received: specifier,\n repair:\n \"Replace the symlink with a module that really lives in this package.\",\n }),\n };\n }\n return { source: { source, position, moduleIdentity: real.moduleIdentity } };\n}\n\nfunction duplicateDiagnostics(\n sources: readonly ResolvedDefinitionSource[],\n): readonly DefinitionDiagnostic[] {\n const groups = new Map<string, ResolvedDefinitionSource[]>();\n for (const entry of sources) {\n const key = [\n entry.moduleIdentity,\n JSON.stringify(entry.source.exportPath ?? []),\n ].join(IDENTITY_SEPARATOR);\n groups.set(key, [...(groups.get(key) ?? []), entry]);\n }\n return [...groups.values()]\n .filter((group) => group.length > 1)\n .map((group) => {\n const [first, ...rest] = [...group].sort(\n (left, right) =>\n compareDefinitionSources(left.source, right.source) ||\n compareDefinitionPaths(left.position, right.position),\n );\n return toolingDiagnostics.create({\n code: \"PH-CONFIG-DUPLICATE-SOURCE\",\n source: first.source,\n path: first.position,\n message:\n \"Several entries select the same module and export path, so one of them can only repeat the other's definitions.\",\n expected: \"one entry per module and export path\",\n received: `${group.length} entries`,\n repair: \"Remove every duplicate entry except one.\",\n related: rest.map((entry) => ({\n source: entry.source,\n path: entry.position,\n message: \"This entry resolves to the same module and export path.\",\n })),\n });\n });\n}\n\ntype Roots = {\n readonly packageRoot: string;\n readonly packageRootIdentity: string;\n};\n\nfunction failed(\n roots: Roots,\n diagnostics: readonly DefinitionDiagnostic[],\n origin: DefinitionSourceOrigin = \"config\",\n sources: readonly DefinitionSource[] = [],\n): InternalResolution {\n return {\n ...roots,\n status: \"failed\",\n sourceSet: sourceSet(\"code-first\", origin, sources),\n diagnostics: sortDefinitionDiagnostics(diagnostics),\n resolved: [],\n };\n}\n\nfunction skipped(\n roots: Roots,\n skipReason: DefinitionCheckSkipReason,\n mode: DefinitionSourceSet[\"mode\"],\n): InternalResolution {\n return {\n ...roots,\n status: \"skipped\",\n skipReason,\n sourceSet: sourceSet(mode, \"config\", []),\n diagnostics: [],\n resolved: [],\n };\n}\n\ntype ConfigReadFailure =\n | \"missing\"\n | \"read-failed\"\n | \"parse-failed\"\n | \"not-an-object\";\n\nconst CONFIG_FAILURE_REPAIR: Record<ConfigReadFailure, string> = {\n missing:\n \"Create the config file, or point --config-file at the package's existing one.\",\n \"read-failed\": \"Fix the permissions of the selected config file.\",\n \"parse-failed\": \"Repair the JSON in the selected config file.\",\n \"not-an-object\": \"Make the config file a single JSON object.\",\n};\n\nexport function readConfigObject(\n configFile: string,\n):\n | { readonly ok: true; readonly value: Readonly<Record<string, unknown>> }\n | { readonly ok: false; readonly reason: ConfigReadFailure } {\n let text: string;\n try {\n text = readFileSync(configFile, \"utf8\");\n } catch (error) {\n const code = (error as { code?: unknown } | null)?.code;\n return {\n ok: false,\n reason:\n code === \"ENOENT\" || code === \"ENOTDIR\" ? \"missing\" : \"read-failed\",\n };\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return { ok: false, reason: \"parse-failed\" };\n }\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n return { ok: false, reason: \"not-an-object\" };\n }\n return { ok: true, value: parsed as Readonly<Record<string, unknown>> };\n}\n\nfunction selectionDiagnostic(\n narrowed: Exclude<\n ReturnType<typeof parseDefinitionSourcesConfig>,\n { ok: true } | { reason: \"missing\" }\n >,\n): DefinitionDiagnostic {\n if (narrowed.reason === \"unsupported-version\") {\n return toolingDiagnostics.create({\n code: \"PH-CONFIG-VERSION-UNSUPPORTED\",\n path: narrowed.path,\n message:\n \"The definitionSources format version is not one this release reads.\",\n expected: \"1\",\n received: render(narrowed.received),\n repair: \"Set definitionSources.formatVersion to 1, or upgrade ph.\",\n });\n }\n return toolingDiagnostics.create({\n code: \"PH-CONFIG-SOURCE-INVALID\",\n path: narrowed.path,\n message: \"The definitionSources selection is malformed.\",\n expected: narrowed.expected,\n received: render(narrowed.received),\n repair: `Set this member to ${narrowed.expected}.`,\n });\n}\n\n/** The selected config file, its directory, and that directory's real path when it exists. */\nexport function packageRoots(request: DefinitionSourceSelectionRequest): {\n readonly configFile: string;\n readonly packageRoot: string;\n readonly packageRootIdentity: string;\n} {\n const configFile = resolve(request.configFile ?? CONFIG_FILE_NAME);\n const packageRoot = dirname(configFile);\n try {\n const packageRootIdentity = realpathSync.native(packageRoot);\n return { configFile, packageRoot, packageRootIdentity };\n } catch {\n // Reading the config reports the missing directory.\n return { configFile, packageRoot, packageRootIdentity: packageRoot };\n }\n}\n\nexport function resolveDefinitionSources(\n request: DefinitionSourceSelectionRequest,\n): InternalResolution {\n const { configFile, ...roots } = packageRoots(request);\n const { packageRoot, packageRootIdentity } = roots;\n\n if (request.allowMissingConfig === true && !existsSync(configFile)) {\n return skipped(roots, \"definition-sources-absent\", DEFAULT_AUTHORING_MODE);\n }\n\n const config = readConfigObject(configFile);\n if (!config.ok) {\n return failed(roots, [\n toolingDiagnostics.create({\n code: \"PH-CONFIG-SOURCE-INVALID\",\n path: [\"configFile\"],\n message:\n \"The selected Powerhouse config file could not be read; its directory is the package root.\",\n expected: \"an existing config file holding one JSON object\",\n received: config.reason,\n repair: CONFIG_FAILURE_REPAIR[config.reason],\n }),\n ]);\n }\n\n const origin = \"config\";\n const narrowed = parseDefinitionSourcesConfig(config.value.definitionSources);\n if (!narrowed.ok) {\n return narrowed.reason === \"missing\"\n ? skipped(roots, \"definition-sources-absent\", DEFAULT_AUTHORING_MODE)\n : failed(roots, [selectionDiagnostic(narrowed)], origin);\n }\n if (narrowed.mode === \"schema-first\") {\n return skipped(roots, \"explicit-schema-first-mode\", \"schema-first\");\n }\n if (narrowed.entries.length === 0) {\n return skipped(roots, \"definition-sources-empty\", \"code-first\");\n }\n const entries = narrowed.entries;\n\n const normalized = entries.map((value, index) =>\n normalizeEntry(\n value,\n [\"definitionSources\", \"entries\", index],\n packageRoot,\n packageRootIdentity,\n ),\n );\n\n const resolved = normalized\n .flatMap((result) => (\"source\" in result ? [result.source] : []))\n .sort((left, right) => compareDefinitionSources(left.source, right.source));\n const sources = resolved.map((entry) => entry.source);\n const entryDiagnostics = normalized.flatMap((result) =>\n \"diagnostic\" in result ? [result.diagnostic] : [],\n );\n if (entryDiagnostics.length > 0) {\n return failed(roots, entryDiagnostics, origin, sources);\n }\n const duplicates = duplicateDiagnostics(resolved);\n if (duplicates.length > 0) {\n return failed(roots, duplicates, origin, sources);\n }\n return {\n ...roots,\n status: \"ready\",\n sourceSet: sourceSet(\"code-first\", origin, sources),\n diagnostics: [],\n resolved,\n };\n}\n\nexport function publicResolution(\n value: InternalResolution,\n): DefinitionSourceResolution {\n const common = {\n packageRoot: value.packageRoot,\n sourceSet: value.sourceSet,\n diagnostics: value.diagnostics,\n };\n return value.status === \"skipped\"\n ? { ...common, status: \"skipped\", skipReason: value.skipReason }\n : { ...common, status: value.status };\n}\n\n/**\n * @experimental The selection a command would load, resolved without\n * importing anything and without any machine-specific path but the root.\n */\nexport function resolveDefinitionSelection(\n request: DefinitionSourceSelectionRequest,\n): DefinitionSourceResolution {\n return publicResolution(resolveDefinitionSources(request));\n}\n","import type {\n DefinitionDiagnostic,\n DefinitionPath,\n DefinitionRef,\n DefinitionSource,\n} from \"@powerhousedao/shared/document-model\";\nimport { snapshotArray, snapshotRecord } from \"../kernel/data-properties.js\";\nimport {\n type ToolingDiagnosticCode,\n toolingDiagnostics,\n} from \"./diagnostic-codes.js\";\n\nexport function describeThrown(error: unknown): string {\n if (error === null) return \"null\";\n try {\n if (error instanceof Error) return `${error.name}: ${error.message}`;\n } catch {\n // A revoked Proxy or a throwing getter makes these reads throw.\n }\n return typeof error;\n}\n\n/** Reads an own data property without running a getter or a Proxy trap twice. */\nexport function readProperty(\n value: object,\n key: string,\n): { readonly ok: true; readonly value: unknown } | { readonly ok: false } {\n try {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor === undefined || !(\"value\" in descriptor)) {\n return { ok: false };\n }\n return { ok: true, value: descriptor.value as unknown };\n } catch {\n return { ok: false };\n }\n}\n\nconst DEFINITION_KINDS: readonly unknown[] = [\n \"document-model\",\n \"subgraph\",\n \"scalar\",\n \"package\",\n];\n\nfunction definitionRef(value: unknown): DefinitionRef | undefined {\n const snapshot = snapshotRecord(value, undefined, []);\n if (!snapshot.ok) return undefined;\n const { kind, key, version } = snapshot.value;\n if (\n typeof key !== \"string\" ||\n key === \"\" ||\n !DEFINITION_KINDS.includes(kind)\n ) {\n return undefined;\n }\n return {\n kind: kind as DefinitionRef[\"kind\"],\n key,\n ...(typeof version === \"number\" && { version }),\n };\n}\n\nfunction isPathSegment(segment: unknown): boolean {\n return (\n typeof segment === \"string\" ||\n (typeof segment === \"number\" && Number.isSafeInteger(segment))\n );\n}\n\nexport function structuredDiagnostics(\n value: unknown,\n source: DefinitionSource,\n): readonly DefinitionDiagnostic[] | undefined {\n if (\n value === null ||\n (typeof value !== \"object\" && typeof value !== \"function\")\n ) {\n return undefined;\n }\n const list = readProperty(value, \"diagnostics\");\n if (!list.ok) return undefined;\n const snapshot = snapshotArray(list.value, []);\n if (!snapshot.ok || snapshot.value.length === 0) return undefined;\n\n const rebuilt: DefinitionDiagnostic[] = [];\n for (const candidate of snapshot.value) {\n const entry = snapshotRecord(candidate, undefined, []);\n if (!entry.ok) return undefined;\n const { code, message, repair, expected, received } = entry.value;\n const path = snapshotArray(entry.value.path, []);\n if (\n typeof code !== \"string\" ||\n !Object.hasOwn(toolingDiagnostics.codes, code) ||\n typeof message !== \"string\" ||\n typeof repair !== \"string\" ||\n !path.ok ||\n !path.value.every(isPathSegment) ||\n (expected !== undefined && typeof expected !== \"string\") ||\n (received !== undefined && typeof received !== \"string\")\n ) {\n return undefined;\n }\n const definition = definitionRef(entry.value.definition);\n rebuilt.push(\n toolingDiagnostics.create({\n code: code as ToolingDiagnosticCode,\n source,\n ...(definition !== undefined && { definition }),\n path: path.value as DefinitionPath,\n message,\n ...(expected !== undefined && { expected }),\n ...(received !== undefined && { received }),\n repair,\n }),\n );\n }\n return rebuilt;\n}\n","import type {\n DefinitionDiagnostic,\n DefinitionPath,\n DefinitionSource,\n DocumentModelModule,\n Sha256Digest,\n UpgradeManifest,\n} from \"@powerhousedao/shared/document-model\";\nimport { existsSync } from \"node:fs\";\nimport { dirname, isAbsolute, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport {\n rejectionReceived,\n snapshotArray,\n snapshotRecord,\n} from \"../kernel/data-properties.js\";\nimport {\n compareDefinitionPaths,\n describeReceived,\n sortDefinitionDiagnostics,\n} from \"../kernel/diagnostics.js\";\nimport { compareCodeUnits } from \"../kernel/primitives.js\";\nimport {\n compareDefinitionSources,\n type InternalResolution,\n normalizeSpecifier,\n packageRoots,\n publicResolution,\n realModulePath,\n resolveDefinitionSources,\n} from \"./definition-source-resolution.js\";\nimport type {\n DefinitionSourceLoadRequest,\n DefinitionSourceResolution,\n DefinitionSourceSelectionRequest,\n LoadedDefinition,\n LoadedDefinitionSet,\n TypeScriptSourceImportInterface,\n} from \"./definition-source-types.js\";\nimport { toolingDiagnostics } from \"./diagnostic-codes.js\";\nimport {\n describeThrown,\n readProperty,\n structuredDiagnostics,\n} from \"./structured-diagnostics.js\";\n\ntype Manifest = UpgradeManifest<readonly number[]>;\n\ntype Collected = {\n readonly documentModels: LoadedDefinition<DocumentModelModule>[];\n readonly upgradeManifests: LoadedDefinition<Manifest>[];\n readonly diagnostics: DefinitionDiagnostic[];\n\n readonly visited: Map<object, number>;\n readonly claimed: Map<\n string,\n { readonly source: DefinitionSource; readonly path: DefinitionPath }\n >;\n};\n\ntype ImportedNamespace =\n | { readonly ok: true; readonly value: Readonly<Record<string, unknown>> }\n | {\n readonly ok: false;\n readonly diagnostics: (\n source: DefinitionSource,\n ) => readonly DefinitionDiagnostic[];\n };\n\nconst KEY_SEPARATOR = String.fromCharCode(0);\n\nfunction isSha256Digest(value: unknown): value is Sha256Digest {\n return typeof value === \"string\" && /^sha256:[0-9a-f]{64}$/.test(value);\n}\n\nfunction isVersionList(value: unknown): value is readonly number[] {\n return (\n Array.isArray(value) &&\n value.every(\n (version) => Number.isSafeInteger(version) && (version as number) > 0,\n )\n );\n}\n\nfunction isDocumentModelModule(record: Readonly<Record<string, unknown>>) {\n return (\n typeof record.reducer === \"function\" &&\n snapshotRecord(record.documentModel, undefined, []).ok\n );\n}\n\nfunction isUpgradeManifest(record: Readonly<Record<string, unknown>>) {\n return (\n typeof record.documentType === \"string\" &&\n Number.isSafeInteger(record.latestVersion) &&\n isVersionList(record.supportedVersions) &&\n snapshotRecord(record.upgrades, undefined, []).ok\n );\n}\n\nfunction familyMembers(\n record: Readonly<Record<string, unknown>>,\n): readonly unknown[] | undefined {\n if (typeof record.at !== \"function\" || record.upgradeManifest === undefined) {\n return undefined;\n }\n const modules = snapshotArray(record.modules, []);\n return modules.ok ? modules.value : undefined;\n}\n\nfunction documentTypeOf(module: unknown): string {\n const stored = snapshotRecord(\n (module as { documentModel?: unknown }).documentModel,\n undefined,\n [],\n );\n const global = stored.ok\n ? snapshotRecord(stored.value.global, undefined, [])\n : undefined;\n return global?.ok === true && typeof global.value.id === \"string\"\n ? global.value.id\n : \"\";\n}\n\nfunction extendSource(\n source: DefinitionSource,\n path: DefinitionPath,\n): DefinitionSource {\n const exportPath = [...(source.exportPath ?? []), ...path.map(String)];\n return {\n specifier: source.specifier,\n ...(exportPath.length > 0 && { exportPath }),\n };\n}\n\nfunction claim(\n collected: Collected,\n logicalKey: string,\n describe: string,\n source: DefinitionSource,\n path: DefinitionPath,\n): void {\n const existing = collected.claimed.get(logicalKey);\n if (existing === undefined) {\n collected.claimed.set(logicalKey, { source, path });\n return;\n }\n collected.diagnostics.push(\n toolingDiagnostics.create({\n code: \"PH-PKG-LOGICAL-COLLISION\",\n source,\n path,\n message: `Two different values both declare ${describe}, so a host registering this package would keep only one of them.`,\n expected: \"one value per logical definition\",\n received: describe,\n repair:\n \"Export one canonical value for this definition and remove the other source entry.\",\n related: [\n {\n source: existing.source,\n path: existing.path,\n message: \"The first value claiming it is here.\",\n },\n ],\n }),\n );\n}\n\nfunction collectDocumentModel(\n collected: Collected,\n value: object,\n source: DefinitionSource,\n path: DefinitionPath,\n): void {\n const module = value as DocumentModelModule;\n collected.documentModels.push({ source, path, value: module });\n const documentType = documentTypeOf(module);\n const version = (module as { version?: unknown }).version;\n\n if (documentType === \"\" || typeof version !== \"number\") return;\n claim(\n collected,\n [\"document-model\", documentType, String(version)].join(KEY_SEPARATOR),\n `document model ${documentType} version ${String(version)}`,\n source,\n path,\n );\n}\n\nfunction collectUpgradeManifest(\n collected: Collected,\n value: object,\n source: DefinitionSource,\n path: DefinitionPath,\n): void {\n const manifest = value as Manifest;\n collected.upgradeManifests.push({ source, path, value: manifest });\n claim(\n collected,\n [\"upgrade-manifest\", manifest.documentType].join(KEY_SEPARATOR),\n `the upgrade manifest of ${manifest.documentType}`,\n source,\n path,\n );\n}\n\nfunction visit(\n collected: Collected,\n value: unknown,\n source: DefinitionSource,\n path: DefinitionPath,\n): number {\n if (value === null || typeof value !== \"object\") return 0;\n const alias = collected.visited.get(value);\n if (alias !== undefined) return alias;\n\n collected.visited.set(value, 0);\n const found = walk(collected, value, source, path);\n collected.visited.set(value, found);\n return found;\n}\n\nfunction walk(\n collected: Collected,\n value: object,\n source: DefinitionSource,\n path: DefinitionPath,\n): number {\n const array = snapshotArray(value, path);\n if (array.ok) {\n return array.value.reduce<number>(\n (count, member, index) =>\n count + visit(collected, member, source, [...path, index]),\n 0,\n );\n }\n const plain = snapshotRecord(value, undefined, path);\n if (!plain.ok) {\n if (plain.reason !== \"accessor\" && plain.reason !== \"inspection-failed\") {\n return 0;\n }\n collected.diagnostics.push(\n toolingDiagnostics.create({\n code: \"PH-PKG-DEFINITION-UNINSPECTABLE\",\n source: extendSource(source, path),\n path,\n message: `This export could not be read safely (${plain.reason}).`,\n expected: \"a plain object, an array, or a materialized definition\",\n received: rejectionReceived(plain),\n repair:\n \"Export plain values: a getter or a Proxy hides what the loader reads.\",\n }),\n );\n return 0;\n }\n const record = plain.value;\n const members = familyMembers(record);\n if (members !== undefined) {\n const count = members.reduce<number>(\n (total, member, index) =>\n total + visit(collected, member, source, [...path, \"modules\", index]),\n 0,\n );\n return (\n count +\n visit(collected, record.upgradeManifest, source, [\n ...path,\n \"upgradeManifest\",\n ])\n );\n }\n if (isDocumentModelModule(record)) {\n collectDocumentModel(collected, value, extendSource(source, path), path);\n return 1;\n }\n if (isUpgradeManifest(record)) {\n collectUpgradeManifest(collected, value, extendSource(source, path), path);\n return 1;\n }\n return Object.keys(record)\n .sort(compareCodeUnits)\n .reduce<number>(\n (count, key) =>\n count + visit(collected, record[key], source, [...path, key]),\n 0,\n );\n}\n\nfunction checkManifestCoverage(collected: Collected): void {\n const versionsByType = new Map<string, number[]>();\n for (const entry of collected.documentModels) {\n const documentType = documentTypeOf(entry.value);\n const version = (entry.value as { version?: unknown }).version;\n if (documentType === \"\" || typeof version !== \"number\") continue;\n versionsByType.set(documentType, [\n ...(versionsByType.get(documentType) ?? []),\n version,\n ]);\n }\n const ascending = (left: number, right: number) => left - right;\n for (const manifest of collected.upgradeManifests) {\n const { documentType, supportedVersions, latestVersion, upgrades } =\n manifest.value;\n const definition = { kind: \"document-model\", key: documentType } as const;\n const loaded = [...(versionsByType.get(documentType) ?? [])].sort(\n ascending,\n );\n const declared = [...supportedVersions].sort(ascending);\n if (\n JSON.stringify(loaded) !== JSON.stringify(declared) ||\n latestVersion !== declared.at(-1)\n ) {\n collected.diagnostics.push(\n toolingDiagnostics.create({\n code: \"PH-DM-DECLARATION-INVALID\",\n source: manifest.source,\n definition,\n path: manifest.path,\n message:\n \"The upgrade manifest and the selected modules of this document type describe different version sets.\",\n expected: `supportedVersions ${JSON.stringify(loaded)} with latestVersion ${String(loaded.at(-1))}`,\n received: `supportedVersions ${JSON.stringify(declared)} with latestVersion ${String(latestVersion)}`,\n repair:\n \"Select the whole family that materialize returned, so its modules and its manifest stay one declaration.\",\n }),\n );\n continue;\n }\n const expected = declared.slice(1).map((version) => `v${version}`);\n const actual = Object.keys(upgrades).sort(compareCodeUnits);\n if (\n JSON.stringify(actual) !==\n JSON.stringify([...expected].sort(compareCodeUnits))\n ) {\n collected.diagnostics.push(\n toolingDiagnostics.create({\n code: \"PH-DM-DECLARATION-INVALID\",\n source: manifest.source,\n definition,\n path: [...manifest.path, \"upgrades\"],\n message:\n \"The upgrade manifest does not carry exactly one transition for each version after the first.\",\n expected: expected.join(\", \") || \"no transitions\",\n received: actual.join(\", \") || \"no transitions\",\n repair: \"Publish the manifest materialize returned, unmodified.\",\n }),\n );\n }\n }\n}\n\n/**\n * A native namespace carries a `Symbol.toStringTag` key and Vite's SSR\n * namespace exposes exports through getters; the data-property rules would\n * reject both without this flattening.\n */\nfunction namespaceSnapshot(value: unknown): Readonly<Record<string, unknown>> {\n if (\n value === null ||\n (typeof value !== \"object\" && typeof value !== \"function\")\n ) {\n throw new TypeError(\n `The import adapter returned ${describeReceived(value)} instead of a module namespace.`,\n );\n }\n return Object.freeze({ ...(value as Record<string, unknown>) });\n}\n\nfunction unresolvedBareImportOf(error: unknown): string | undefined {\n if (!(error instanceof Error)) return undefined;\n const match =\n /^Cannot find (?:package|module) '([^']+)' imported from '?(.+?)'?$/m.exec(\n error.message,\n );\n if (match === null) return undefined;\n const [, specifier, importer] = match;\n if (/^(?:[./\\\\]|[a-zA-Z][\\w+.-]*:)/.test(specifier)) return undefined;\n const name = specifier\n .split(\"/\")\n .slice(0, specifier.startsWith(\"@\") ? 2 : 1)\n .join(\"/\");\n const from = importer.startsWith(\"file:\")\n ? fileURLToPath(importer)\n : importer;\n if (!isAbsolute(from)) return undefined;\n for (let directory = dirname(from); ; directory = dirname(directory)) {\n if (existsSync(join(directory, \"node_modules\", name))) return undefined;\n if (dirname(directory) === directory) return name;\n }\n}\n\nfunction importDiagnostics(\n error: unknown,\n source: DefinitionSource,\n missing: boolean,\n): readonly DefinitionDiagnostic[] {\n if (missing) {\n return [\n toolingDiagnostics.create({\n code: \"PH-IMPORT-FAILED\",\n source,\n path: [],\n message: \"definitionSources lists a module that does not exist.\",\n expected: \"an existing module inside the package\",\n received: source.specifier,\n repair:\n \"Fix the specifier, or remove the entry from definitionSources.entries in powerhouse.config.json.\",\n }),\n ];\n }\n const structured = structuredDiagnostics(error, source);\n if (structured !== undefined) return structured;\n const unresolved = unresolvedBareImportOf(error);\n return [\n toolingDiagnostics.create({\n code: \"PH-IMPORT-FAILED\",\n source,\n path: [],\n message:\n unresolved === undefined\n ? \"This definition source could not be imported.\"\n : `This definition source could not resolve the import ${unresolved}.`,\n expected:\n unresolved === undefined\n ? \"an importable TypeScript module\"\n : `a project alias or installed dependency resolving ${unresolved}`,\n received: describeThrown(error),\n repair:\n unresolved === undefined\n ? \"Fix this module or one of its imports, then load it again.\"\n : `Check the project tsconfig paths and package dependencies for ${unresolved}. If it is an npm package, list it in package.json and install dependencies.`,\n }),\n ];\n}\n\ntype SelectedExport =\n | { readonly ok: true; readonly value: unknown }\n | { readonly ok: false; readonly diagnostic: DefinitionDiagnostic };\n\nfunction selectExport(\n source: DefinitionSource,\n namespace: Readonly<Record<string, unknown>>,\n): SelectedExport {\n let current: unknown = namespace;\n const exportPath = source.exportPath ?? [];\n for (const [index, key] of exportPath.entries()) {\n const read =\n current !== null &&\n (typeof current === \"object\" || typeof current === \"function\")\n ? readProperty(current, key)\n : undefined;\n if (read?.ok !== true) {\n return {\n ok: false,\n diagnostic: toolingDiagnostics.create({\n code: \"PH-CONFIG-SOURCE-INVALID\",\n source,\n path: [\"exportPath\", index],\n message:\n read === undefined\n ? `The export pointer reads \"${key}\" from a value that has no properties.`\n : `The configured export \"${key}\" is absent, or is not a plain readable property.`,\n expected: read === undefined ? \"an object or a namespace\" : key,\n received: read === undefined ? describeReceived(current) : \"missing\",\n repair:\n \"Point the export pointer at an exact exported property, spelled as it is exported.\",\n }),\n };\n }\n current = read.value;\n }\n return { ok: true, value: current };\n}\n\nfunction sortBySource<T>(\n entries: readonly LoadedDefinition<T>[],\n): readonly LoadedDefinition<T>[] {\n return [...entries].sort(\n (left, right) =>\n compareDefinitionSources(left.source, right.source) ||\n compareDefinitionPaths(left.path, right.path),\n );\n}\n\nfunction revisionDiagnostic(revision: unknown): DefinitionDiagnostic {\n return toolingDiagnostics.create({\n code: \"PH-CONFIG-SOURCE-INVALID\",\n path: [\"packageRevision\"],\n message:\n \"The package revision is not a SHA-256 identifier, so no import can be bound to it.\",\n expected: \"sha256: followed by 64 lowercase hexadecimal digits\",\n received:\n typeof revision === \"string\" ? revision : describeReceived(revision),\n repair: \"Pass a revision digest of the package's current files.\",\n });\n}\n\nfunction refusedModule(\n specifier: `./${string}`,\n code: \"PH-CONFIG-SOURCE-INVALID\" | \"PH-CONFIG-SOURCE-OUTSIDE-PACKAGE\",\n message: string,\n): { readonly ok: false; readonly diagnostic: DefinitionDiagnostic } {\n return {\n ok: false,\n diagnostic: toolingDiagnostics.create({\n code,\n source: { specifier },\n path: [],\n message,\n expected:\n \"a './' module path whose real path stays inside the package root\",\n received: specifier,\n repair:\n \"Keep the module inside the package, and do not reach it through a symlink that leaves the package.\",\n }),\n };\n}\n\ntype PackageModule = {\n readonly specifier: `./${string}`;\n readonly packageRootIdentity: string;\n readonly moduleIdentity: string;\n};\n\n/** The selected sources' containment rules, so a module outside the package is never imported. */\nfunction containedPackageModule(\n request: DefinitionSourceSelectionRequest & {\n readonly specifier: `./${string}`;\n },\n):\n | ({ readonly ok: true } & PackageModule)\n | { readonly ok: false; readonly diagnostic: DefinitionDiagnostic } {\n const { packageRoot, packageRootIdentity } = packageRoots(request);\n const normalized = normalizeSpecifier(request.specifier);\n if (!normalized.ok) {\n return refusedModule(\n request.specifier,\n normalized.code,\n normalized.message,\n );\n }\n const real = realModulePath(\n packageRoot,\n packageRootIdentity,\n normalized.specifier,\n );\n if (real.ok) {\n return {\n ok: true,\n specifier: normalized.specifier,\n packageRootIdentity,\n moduleIdentity: real.moduleIdentity,\n };\n }\n return real.reason === \"outside\"\n ? refusedModule(\n request.specifier,\n \"PH-CONFIG-SOURCE-OUTSIDE-PACKAGE\",\n \"The package module resolves through a symlink that leaves the package root.\",\n )\n : refusedModule(\n request.specifier,\n \"PH-CONFIG-SOURCE-INVALID\",\n \"The package module path could not be resolved.\",\n );\n}\n\nfunction empty(resolution: DefinitionSourceResolution): LoadedDefinitionSet {\n return { ...resolution, documentModels: [], upgradeManifests: [] };\n}\n\n/**\n * @experimental Imports the selected definition sources and finds the\n * materialized document models, families and upgrade manifests they export.\n * It folds aliases, reports two values that claim one `documentType@version`,\n * and returns everything sorted by source, so neither config order nor\n * import completion order changes a result. Validity belongs to the\n * adapters; registration belongs to the host.\n */\nexport class DefinitionSourceLoader {\n readonly #importer: TypeScriptSourceImportInterface;\n readonly #imports = new Map<\n string,\n Promise<Readonly<Record<string, unknown>>>\n >();\n #revision: Sha256Digest | undefined;\n\n constructor(importer: TypeScriptSourceImportInterface) {\n this.#importer = importer;\n }\n\n resolve(\n request: DefinitionSourceSelectionRequest,\n ): DefinitionSourceResolution {\n return publicResolution(resolveDefinitionSources(request));\n }\n\n async normalizeDefinitionSources(\n request: DefinitionSourceLoadRequest,\n ): Promise<LoadedDefinitionSet> {\n request.signal?.throwIfAborted();\n const resolution = resolveDefinitionSources(request);\n if (resolution.status !== \"ready\") {\n return empty(publicResolution(resolution));\n }\n if (!isSha256Digest(request.packageRevision)) {\n return empty({\n packageRoot: resolution.packageRoot,\n sourceSet: resolution.sourceSet,\n status: \"failed\",\n diagnostics: [revisionDiagnostic(request.packageRevision)],\n });\n }\n await this.#retainRevision(request.packageRevision);\n const namespaces = await this.#importModules(resolution, request);\n request.signal?.throwIfAborted();\n\n const collected: Collected = {\n documentModels: [],\n upgradeManifests: [],\n diagnostics: [],\n visited: new Map(),\n claimed: new Map(),\n };\n\n for (const entry of resolution.resolved) {\n const namespace = namespaces.get(entry.moduleIdentity);\n if (namespace === undefined) continue;\n if (!namespace.ok) {\n collected.diagnostics.push(...namespace.diagnostics(entry.source));\n continue;\n }\n const selected = selectExport(entry.source, namespace.value);\n if (!selected.ok) {\n collected.diagnostics.push(selected.diagnostic);\n continue;\n }\n if (visit(collected, selected.value, entry.source, []) === 0) {\n collected.diagnostics.push(\n toolingDiagnostics.create({\n code: \"PH-PKG-DEFINITION-UNRECOGNIZED\",\n source: entry.source,\n path: [],\n message:\n \"This source exports no materialized document model, so selecting it loads nothing.\",\n expected:\n \"a module or family materialize returned, or a collection holding them\",\n received: \"no recognized definition\",\n repair:\n \"Point this entry at the export that materialize(...) returned.\",\n }),\n );\n }\n }\n checkManifestCoverage(collected);\n\n const diagnostics = sortDefinitionDiagnostics(collected.diagnostics);\n return {\n packageRoot: resolution.packageRoot,\n sourceSet: resolution.sourceSet,\n status: diagnostics.some(({ severity }) => severity === \"error\")\n ? \"failed\"\n : \"ready\",\n diagnostics,\n documentModels: sortBySource(collected.documentModels),\n upgradeManifests: sortBySource(collected.upgradeManifests),\n };\n }\n\n /**\n * @experimental Imports one package module through the same importer and\n * package revision as the selected sources, so a module both reach is\n * evaluated once. A module outside the package root is refused as an\n * outside source is. Experimental: tooling uses it for the project scalars\n * module while code-first projects are introduced.\n */\n async importPackageModule(\n request: DefinitionSourceLoadRequest & {\n readonly specifier: `./${string}`;\n },\n ): Promise<\n | {\n readonly ok: true;\n readonly namespace: Readonly<Record<string, unknown>>;\n }\n | {\n readonly ok: false;\n readonly diagnostics: readonly DefinitionDiagnostic[];\n }\n > {\n request.signal?.throwIfAborted();\n if (!isSha256Digest(request.packageRevision)) {\n return {\n ok: false,\n diagnostics: [revisionDiagnostic(request.packageRevision)],\n };\n }\n const contained = containedPackageModule(request);\n if (!contained.ok)\n return { ok: false, diagnostics: [contained.diagnostic] };\n await this.#retainRevision(request.packageRevision);\n const imported = await this.#import(contained, request);\n return imported.ok\n ? { ok: true, namespace: imported.value }\n : {\n ok: false,\n diagnostics: imported.diagnostics({ specifier: request.specifier }),\n };\n }\n\n async dispose(): Promise<void> {\n const revision = this.#revision;\n this.#imports.clear();\n this.#revision = undefined;\n if (revision !== undefined) {\n await this.#importer.disposeRevision?.(revision);\n }\n }\n\n async #retainRevision(revision: Sha256Digest): Promise<void> {\n if (this.#revision === revision) return;\n const superseded = this.#revision;\n this.#imports.clear();\n this.#revision = revision;\n if (superseded !== undefined) {\n await this.#importer.disposeRevision?.(superseded);\n }\n }\n\n /** One evaluation per module and revision, whichever path asks first. */\n async #import(\n module: PackageModule,\n request: DefinitionSourceLoadRequest,\n ): Promise<ImportedNamespace> {\n const { moduleIdentity } = module;\n let namespace = this.#imports.get(moduleIdentity);\n if (namespace === undefined) {\n namespace = this.#importer.importModule({\n // Use the real root so symlink aliases cannot evaluate the module twice.\n packageRoot: module.packageRootIdentity,\n specifier: module.specifier,\n packageRevision: request.packageRevision,\n ...(request.signal !== undefined && { signal: request.signal }),\n });\n this.#imports.set(moduleIdentity, namespace);\n void namespace.catch(() => this.#imports.delete(moduleIdentity));\n }\n try {\n return { ok: true, value: namespaceSnapshot(await namespace) };\n } catch (error) {\n const missing = !existsSync(moduleIdentity);\n return {\n ok: false,\n diagnostics: (source) => importDiagnostics(error, source, missing),\n };\n }\n }\n\n async #importModules(\n resolution: InternalResolution,\n request: DefinitionSourceLoadRequest,\n ): Promise<Map<string, ImportedNamespace>> {\n const results = new Map<string, ImportedNamespace>();\n // Evaluate serially so aliases and their family share one module evaluation.\n for (const { moduleIdentity, source } of resolution.resolved) {\n if (results.has(moduleIdentity)) continue;\n const module = {\n specifier: source.specifier,\n packageRootIdentity: resolution.packageRootIdentity,\n moduleIdentity,\n };\n results.set(moduleIdentity, await this.#import(module, request));\n }\n return results;\n }\n}\n","import { compilerDiagnostics } from \"./diagnostic-codes.js\";\nimport type { DefinitionDiagnostic } from \"@powerhousedao/shared/document-model\";\nimport { camelCase, constantCase, pascalCase } from \"change-case\";\n\ntype Digit = \"0\" | \"1\" | \"2\" | \"3\" | \"4\" | \"5\" | \"6\" | \"7\" | \"8\" | \"9\";\n\ntype ActionTypeWords<\n TKey extends string,\n TPrevious extends string = \"\",\n TResult extends string = \"\",\n TSeparator extends string = \"\",\n> = TKey extends `${infer TFirst}${infer TRest}`\n ? TFirst extends \"_\"\n ? ActionTypeWords<TRest, \"\", TResult, TResult extends \"\" ? \"\" : \"_\">\n : ActionTypeWords<\n TRest,\n TFirst,\n `${TResult}${TSeparator extends \"_\"\n ? \"_\"\n : TFirst extends Lowercase<TFirst>\n ? \"\"\n : TPrevious extends \"\"\n ? \"\"\n : TPrevious extends Digit\n ? \"_\"\n : TPrevious extends Uppercase<TPrevious>\n ? TRest extends `${infer TNext}${string}`\n ? TNext extends Uppercase<TNext>\n ? \"\"\n : \"_\"\n : \"\"\n : \"_\"}${Uppercase<TFirst>}`\n >\n : TResult;\n\nexport type DocumentModelActionType<TKey extends string> = string extends TKey\n ? string\n : ActionTypeWords<TKey>;\n\nexport type DocumentModelNames = {\n readonly documentType: string;\n readonly graphQLName: string;\n readonly globalStateRootName: string;\n readonly localStateRootName: string;\n};\n\ntype DocumentModelModuleNames = {\n readonly storedName: string;\n readonly operationsInterfaceName: string;\n readonly actionNamespaceName: string;\n};\n\ntype DocumentModelOperationNames = {\n readonly storedName: string;\n readonly actionType: string;\n readonly inputTypeName: string;\n readonly creatorKey: string;\n readonly reducerMethod: string;\n};\n\ntype DocumentModelErrorNames = {\n readonly key: string;\n readonly storedName: string;\n readonly storedCode: string;\n};\n\nexport function deriveDocumentModelNames(\n model: { readonly id: string; readonly name: string },\n overrides: Partial<DocumentModelNames> = {},\n): DocumentModelNames {\n const graphQLName = overrides.graphQLName ?? pascalCase(model.name);\n return {\n documentType: overrides.documentType ?? model.id,\n graphQLName,\n globalStateRootName: overrides.globalStateRootName ?? `${graphQLName}State`,\n localStateRootName:\n overrides.localStateRootName ?? `${graphQLName}LocalState`,\n };\n}\n\nexport function deriveDocumentModelModuleNames(\n modelName: string,\n moduleKey: string,\n overrides: Partial<DocumentModelModuleNames> = {},\n): DocumentModelModuleNames {\n const modulePascal = pascalCase(moduleKey);\n return {\n storedName: overrides.storedName ?? modulePascal,\n operationsInterfaceName:\n overrides.operationsInterfaceName ??\n `${pascalCase(modelName)}${modulePascal}Operations`,\n actionNamespaceName:\n overrides.actionNamespaceName ??\n `${camelCase(modelName)}${modulePascal}Actions`,\n };\n}\n\nexport function deriveDocumentModelOperationNames(\n operationKey: string,\n overrides: Partial<DocumentModelOperationNames> = {},\n): DocumentModelOperationNames {\n const operationPascal = pascalCase(operationKey);\n const actionType = overrides.actionType ?? constantCase(operationKey);\n return {\n storedName: overrides.storedName ?? operationPascal,\n actionType,\n inputTypeName: overrides.inputTypeName ?? `${operationPascal}Input`,\n creatorKey: overrides.creatorKey ?? camelCase(constantCase(operationKey)),\n reducerMethod:\n overrides.reducerMethod ?? `${camelCase(operationKey)}Operation`,\n };\n}\n\n// Action types the base reducer or the reactor reduces before a model's own\n// reducer sees them, and RETRACT, which replay reads as a retraction. NOOP is\n// left out because the model's reducer still runs.\nexport const PLATFORM_ACTION_TYPES: ReadonlySet<string> = new Set([\n \"SET_NAME\",\n \"SET_PREFERRED_EDITOR\",\n \"UNDO\",\n \"REDO\",\n \"RETRACT\",\n \"CREATE_DOCUMENT\",\n \"DELETE_DOCUMENT\",\n \"UPGRADE_DOCUMENT\",\n \"ADD_RELATIONSHIP\",\n \"REMOVE_RELATIONSHIP\",\n \"UPDATE_RELATIONSHIP\",\n \"PURGE_DOCUMENT\",\n]);\n\nexport function deriveOperationErrorClassName(errorKey: string): string {\n return pascalCase(errorKey);\n}\n\nexport function deriveDocumentModelErrorNames(\n errorKey: string,\n authored: {\n readonly name?: string | null;\n readonly code?: string | null;\n } = {},\n): DocumentModelErrorNames {\n return {\n key: errorKey,\n storedName: authored.name ?? errorKey,\n storedCode: authored.code ?? errorKey,\n };\n}\n\nexport type DerivedOperationNames = {\n readonly key: string;\n readonly names: DocumentModelOperationNames;\n};\n\nexport type DerivedModuleNames = {\n readonly key: string;\n readonly names: DocumentModelModuleNames;\n readonly operations: readonly DerivedOperationNames[];\n};\n\ntype Claim = {\n readonly path: readonly string[];\n readonly label: string;\n};\n\ntype NameClaim = {\n readonly kind: string;\n readonly slot: string;\n readonly value: string;\n};\n\ntype Collision = {\n readonly first: Claim;\n readonly names: string[];\n actionType: boolean;\n};\n\nconst MODULE_NAME_KINDS = [\n \"storedName\",\n \"operationsInterfaceName\",\n \"actionNamespaceName\",\n] as const satisfies readonly (keyof DocumentModelModuleNames)[];\n\nconst OPERATION_NAME_KINDS = [\n \"actionType\",\n \"storedName\",\n \"inputTypeName\",\n \"creatorKey\",\n \"reducerMethod\",\n] as const satisfies readonly (keyof DocumentModelOperationNames)[];\n\nfunction nameSlot(\n owner: \"module\" | \"operation\",\n scope: string,\n kind: string,\n value: string,\n): string {\n return JSON.stringify([owner, scope, kind, value]);\n}\n\nfunction moduleNameClaims(\n names: DocumentModelModuleNames,\n): readonly NameClaim[] {\n return MODULE_NAME_KINDS.map((kind) => ({\n kind,\n slot: nameSlot(\"module\", \"model\", kind, names[kind]),\n value: names[kind],\n }));\n}\n\nfunction operationNameClaims(\n moduleKey: string,\n names: DocumentModelOperationNames,\n): readonly NameClaim[] {\n return OPERATION_NAME_KINDS.map((kind) => {\n const scope =\n kind === \"storedName\" || kind === \"reducerMethod\" ? moduleKey : \"model\";\n return {\n kind,\n slot: nameSlot(\"operation\", scope, kind, names[kind]),\n value: names[kind],\n };\n });\n}\n\nfunction claim(\n claims: Map<string, Claim>,\n claimant: Claim,\n nameClaims: readonly NameClaim[],\n): readonly Collision[] {\n const collisions = new Map<Claim, Collision>();\n for (const { kind, slot, value } of nameClaims) {\n const first = claims.get(slot);\n if (first === undefined) {\n claims.set(slot, claimant);\n continue;\n }\n const collision = collisions.get(first) ?? {\n first,\n names: [],\n actionType: false,\n };\n collision.names.push(`${kind} ${JSON.stringify(value)}`);\n if (kind === \"actionType\") collision.actionType = true;\n collisions.set(first, collision);\n }\n return [...collisions.values()];\n}\n\nfunction collisionDiagnostic(\n claimant: Claim,\n collision: Collision,\n): DefinitionDiagnostic {\n const list = collision.names.join(\", \");\n return compilerDiagnostics.create({\n code: collision.actionType\n ? \"PH-DM-DUPLICATE-ACTION\"\n : \"PH-DM-DUPLICATE-NAME\",\n path: claimant.path,\n message: `${claimant.label} derives ${list}, already derived by ${collision.first.label}.`,\n expected: `distinct derived names for ${claimant.label} and ${collision.first.label}`,\n received: list,\n repair: `Rename ${claimant.label} or ${collision.first.label} so their derived names differ.`,\n related: [\n {\n path: collision.first.path,\n message: `${collision.first.label} derives the same ${collision.names.length === 1 ? \"name\" : \"names\"}.`,\n },\n ],\n });\n}\n\nexport function checkDerivedNameCollisions(\n modules: readonly DerivedModuleNames[],\n): readonly DefinitionDiagnostic[] {\n const claims = new Map<string, Claim>();\n const diagnostics: DefinitionDiagnostic[] = [];\n for (const module of modules) {\n const moduleClaim: Claim = {\n path: [\"modules\", module.key],\n label: `module ${JSON.stringify(module.key)}`,\n };\n for (const collision of claim(\n claims,\n moduleClaim,\n moduleNameClaims(module.names),\n )) {\n diagnostics.push(collisionDiagnostic(moduleClaim, collision));\n }\n for (const operation of module.operations) {\n const operationClaim: Claim = {\n path: [\"modules\", module.key, \"operations\", operation.key],\n label: `operation ${JSON.stringify(`${module.key}.${operation.key}`)}`,\n };\n for (const collision of claim(\n claims,\n operationClaim,\n operationNameClaims(module.key, operation.names),\n )) {\n diagnostics.push(collisionDiagnostic(operationClaim, collision));\n }\n }\n }\n return diagnostics;\n}\n\n/** The symbol spellings codegen derives from a stored schema-first name. */\nexport function deriveDocumentModelSymbolNames(name: string) {\n return {\n typeName: pascalCase(name),\n memberName: camelCase(name),\n constantName: constantCase(name),\n };\n}\n","import { defineDiagnosticCatalog } from \"../../kernel/diagnostics.js\";\nimport { toolingDiagnostics } from \"../diagnostic-codes.js\";\n\nexport const checkDiagnostics = defineDiagnosticCatalog(\n {\n \"PH-DM-DUPLICATE-ERROR-CODE\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"Two errors of one operation persist the same error code, so a caller cannot tell them apart\",\n },\n \"PH-DM-ERROR-CLASS-CONFLICT\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"Two errors of one module generate the same error class with different codes\",\n },\n \"PH-PKG-SCALAR-CONFLICT\": {\n severity: \"error\",\n phase: \"package\",\n meaning:\n \"Two models of one package use different project scalars with one name, and a host declares each scalar once\",\n },\n \"PH-PKG-DEFINITION-UNREGISTERED\": {\n severity: \"error\",\n phase: \"package\",\n meaning:\n \"A code-first document model under the document models directory is reached by no definitionSources entry, so the package leaves it out\",\n },\n },\n toolingDiagnostics,\n);\n\nexport type CheckDiagnosticCode = keyof typeof checkDiagnostics.codes;\n","import type {\n DefinitionRef,\n DocumentModelSpecificationDefinition,\n} from \"@powerhousedao/shared/document-model\";\nimport type { NormalizedDocumentModelArtifact } from \"../adapters/types.js\";\n\n/**\n * The specification an artifact serves, and its index in the history. Every\n * member of a family carries the whole history, so a check that read every\n * specification of every artifact would report one defect once per member.\n */\nexport function servedSpecification(artifact: NormalizedDocumentModelArtifact):\n | {\n readonly specification: DocumentModelSpecificationDefinition;\n readonly index: number;\n }\n | undefined {\n const index = artifact.definition.specifications.findIndex(\n ({ version }) => version === artifact.version,\n );\n return index === -1\n ? undefined\n : { specification: artifact.definition.specifications[index], index };\n}\n\nexport function documentModelRef(\n artifact: NormalizedDocumentModelArtifact,\n): DefinitionRef {\n return {\n kind: \"document-model\",\n key: artifact.documentType,\n version: artifact.version,\n };\n}\n","import type {\n DefinitionDiagnostic,\n DefinitionPath,\n} from \"@powerhousedao/shared/document-model\";\nimport {\n deriveOperationErrorClassName,\n PLATFORM_ACTION_TYPES,\n} from \"../../../compiler/naming.js\";\nimport type { NormalizedDocumentModelArtifact } from \"../../adapters/types.js\";\nimport {\n type CheckDiagnosticCode,\n checkDiagnostics,\n} from \"../diagnostic-codes.js\";\nimport {\n documentModelRef,\n servedSpecification,\n} from \"../../report/served-specification.js\";\nimport type { DefinitionCheck } from \"../types.js\";\n\ntype Claim = { readonly path: DefinitionPath; readonly label: string };\n\n/** Codegen's rule: an empty or absent code falls back to the class name. */\nfunction effectiveErrorCode(code: string | null, className: string): string {\n return code?.trim() || className;\n}\n\n/**\n * The compiler refuses duplicate module keys, action types and creator keys,\n * an action type the document runtime owns, and an error class with two codes\n * in one module, before a code-first module exists, so for those this check fires only on a stored schema-first model.\n * Two errors of one operation sharing a code pass the compiler in both modes.\n */\nfunction duplicates(\n artifact: NormalizedDocumentModelArtifact,\n): readonly DefinitionDiagnostic[] {\n const served = servedSpecification(artifact);\n if (served === undefined) return [];\n const { specification, index } = served;\n const diagnostics: DefinitionDiagnostic[] = [];\n const report = (\n code: CheckDiagnosticCode,\n claimant: Claim,\n first: Claim,\n detail: {\n readonly message: string;\n readonly expected: string;\n readonly received: string;\n readonly repair: string;\n },\n ) =>\n diagnostics.push(\n checkDiagnostics.create({\n code,\n source: artifact.source,\n definition: documentModelRef(artifact),\n path: claimant.path,\n ...detail,\n related: [\n {\n source: artifact.source,\n path: first.path,\n message: `${first.label} claims it first.`,\n },\n ],\n }),\n );\n const shared = (\n code: CheckDiagnosticCode,\n claimant: Claim,\n first: Claim,\n [kind, value]: readonly [string, string],\n repair: string,\n ) =>\n report(code, claimant, first, {\n message: `${claimant.label} and ${first.label} share the ${kind} ${value}.`,\n expected: `one declaration per ${kind}`,\n received: value,\n repair,\n });\n\n const modules = new Map<string, Claim>();\n const actionTypes = new Map<string, Claim>();\n const operationKeys = new Map<string, Claim>();\n specification.modules.forEach((module, moduleIndex) => {\n const modulePath = [\"specifications\", index, \"modules\", moduleIndex];\n const moduleClaim = {\n path: modulePath,\n label: `module ${JSON.stringify(module.key)}`,\n };\n const firstModule = modules.get(module.key);\n if (firstModule === undefined) modules.set(module.key, moduleClaim);\n else {\n shared(\n \"PH-DM-DUPLICATE-NAME\",\n moduleClaim,\n firstModule,\n [\"key\", module.key],\n \"Rename one of the modules.\",\n );\n }\n const errorClasses = new Map<string, Claim & { readonly code: string }>();\n module.operations.forEach((operation, operationIndex) => {\n const operationPath = [...modulePath, \"operations\", operationIndex];\n const claim = {\n path: operationPath,\n label: `operation ${JSON.stringify(`${module.key}.${operation.key}`)}`,\n };\n if (PLATFORM_ACTION_TYPES.has(operation.actionType)) {\n diagnostics.push(\n checkDiagnostics.create({\n code: \"PH-DM-DUPLICATE-ACTION\",\n source: artifact.source,\n definition: documentModelRef(artifact),\n path: [...operationPath, \"key\"],\n message: `${claim.label} has action type ${operation.actionType}, which the document runtime reduces itself, so this operation's reducer would never run.`,\n expected: \"an action type the document runtime does not own\",\n received: operation.actionType,\n repair: \"Rename the operation.\",\n }),\n );\n }\n const firstAction = actionTypes.get(operation.actionType);\n const firstKey = operationKeys.get(operation.key);\n if (firstAction !== undefined) {\n shared(\n \"PH-DM-DUPLICATE-ACTION\",\n claim,\n firstAction,\n [\"action type\", operation.actionType],\n \"Rename one of the operations; a replayed history cannot tell which reducer wrote a shared action type.\",\n );\n } else if (firstKey !== undefined) {\n shared(\n \"PH-DM-DUPLICATE-NAME\",\n claim,\n firstKey,\n [\"creator key\", operation.key],\n \"Rename one of the operations; action creators share one namespace.\",\n );\n }\n actionTypes.set(operation.actionType, firstAction ?? claim);\n operationKeys.set(operation.key, firstKey ?? claim);\n\n const errorKeys = new Map<string, Claim>();\n const errorCodes = new Map<string, Claim>();\n operation.errors.forEach((error, errorIndex) => {\n const errorClaim = {\n path: [...operationPath, \"errors\", errorIndex],\n label: `error ${JSON.stringify(error.key)}`,\n };\n const className = deriveOperationErrorClassName(\n error.name ?? error.key,\n );\n const code = effectiveErrorCode(error.code, className);\n const sameKey = errorKeys.get(error.key);\n const sameCode = errorCodes.get(code);\n const sameClass = errorClasses.get(className);\n if (sameKey !== undefined) {\n shared(\n \"PH-DM-DUPLICATE-NAME\",\n errorClaim,\n sameKey,\n [\"key\", error.key],\n \"Rename one of the errors; each generates its own class.\",\n );\n } else if (sameCode !== undefined) {\n shared(\n \"PH-DM-DUPLICATE-ERROR-CODE\",\n errorClaim,\n sameCode,\n [\"code\", code],\n \"Give each error of the operation its own code, so a caller can tell them apart.\",\n );\n } else if (sameClass !== undefined && sameClass.code !== code) {\n report(\"PH-DM-ERROR-CLASS-CONFLICT\", errorClaim, sameClass, {\n message: `${errorClaim.label} of ${claim.label} gives the error class ${className} the code ${JSON.stringify(code)}, and ${sameClass.label} gives it ${JSON.stringify(sameClass.code)}.`,\n expected: sameClass.code,\n received: code,\n repair: `Give both ${className} errors the same code, or give one another name; a module generates one ${className} class.`,\n });\n }\n errorKeys.set(error.key, sameKey ?? errorClaim);\n errorCodes.set(code, sameCode ?? errorClaim);\n if (sameClass === undefined) {\n errorClasses.set(className, {\n ...errorClaim,\n label: `${errorClaim.label} of ${claim.label}`,\n code,\n });\n }\n });\n });\n });\n return diagnostics;\n}\n\nexport const duplicateIdentitiesCheck: DefinitionCheck = {\n name: \"duplicate-identities\",\n run: ({ artifacts }) => artifacts.flatMap(duplicates),\n};\n","import type { LocationFreeGraphQLDocumentNode } from \"@powerhousedao/shared/document-model\";\nimport type * as GraphQL from \"graphql\";\nimport type { validateSDL } from \"graphql/validation/validate.js\";\nimport { createRequire } from \"node:module\";\n\n/** graphql-js, plus the SDL validation its package index does not export. */\nexport type GraphQLModule = typeof GraphQL & {\n readonly validateSDL: typeof validateSDL;\n};\n\nlet graphql: GraphQLModule | undefined;\n\n/**\n * `graphql` is an optional peer: only tooling that reads SDL needs it, and a\n * package that imports document-model at runtime must not pay for it.\n */\nexport function loadGraphQL(): GraphQLModule {\n if (graphql !== undefined) return graphql;\n const require = createRequire(import.meta.url);\n let loaded: unknown;\n let validation: Partial<Pick<GraphQLModule, \"validateSDL\">>;\n try {\n loaded = require(\"graphql\");\n validation = require(\"graphql/validation/validate.js\") as typeof validation;\n } catch (error) {\n throw new Error(\n \"Reading GraphQL SDL needs the optional peer dependency graphql@^16. Install it in the package that runs this tool.\",\n { cause: error },\n );\n }\n if (\n loaded === null ||\n typeof loaded !== \"object\" ||\n typeof (loaded as Partial<GraphQLModule>).parse !== \"function\" ||\n typeof (loaded as Partial<GraphQLModule>).buildASTSchema !== \"function\" ||\n typeof validation.validateSDL !== \"function\"\n ) {\n throw new Error(\n \"The installed graphql package does not export parse, buildASTSchema and validateSDL; install graphql@^16.\",\n );\n }\n graphql = {\n ...(loaded as typeof GraphQL),\n validateSDL: validation.validateSDL,\n };\n return graphql;\n}\n\nfunction withoutLocations(node: unknown): unknown {\n if (Array.isArray(node)) return node.map(withoutLocations);\n if (node === null || typeof node !== \"object\") return node;\n return Object.fromEntries(\n Object.entries(node)\n .filter(([key, value]) => key !== \"loc\" && value !== undefined)\n .map(([key, value]) => [key, withoutLocations(value)]),\n );\n}\n\nexport const EMPTY_DOCUMENT: LocationFreeGraphQLDocumentNode = {\n kind: \"Document\",\n definitions: [],\n};\n\n/** Parses one stored SDL segment. A missing `graphql` peer throws; bad SDL does not. */\nexport function parseSchema(\n sdl: string,\n):\n | { readonly ok: true; readonly document: LocationFreeGraphQLDocumentNode }\n | { readonly ok: false; readonly message: string } {\n if (sdl.trim() === \"\") return { ok: true, document: EMPTY_DOCUMENT };\n const { parse } = loadGraphQL();\n try {\n return {\n ok: true,\n document: withoutLocations(\n parse(sdl, { noLocation: true }),\n ) as LocationFreeGraphQLDocumentNode,\n };\n } catch (error) {\n return {\n ok: false,\n message: error instanceof Error ? error.message : String(error),\n };\n }\n}\n","import type {\n DefinitionDiagnostic,\n DefinitionPath,\n DocumentModelSpecificationDefinition,\n} from \"@powerhousedao/shared/document-model\";\nimport type { DocumentNode, GraphQLError } from \"graphql\";\nimport { scalarCatalog } from \"../../../../scalars/catalog.js\";\nimport type { NormalizedDocumentModelArtifact } from \"../../adapters/types.js\";\nimport { type GraphQLModule, loadGraphQL } from \"../../graphql/parse-schema.js\";\nimport {\n type CheckDiagnosticCode,\n checkDiagnostics,\n} from \"../diagnostic-codes.js\";\nimport {\n documentModelRef,\n servedSpecification,\n} from \"../../report/served-specification.js\";\nimport type { DefinitionCheck } from \"../types.js\";\n\ntype Node = {\n readonly kind: string;\n readonly name?: { readonly value: string };\n readonly interfaces?: readonly {\n readonly name: { readonly value: string };\n }[];\n};\n\n/** The top-level node an error node sits in, and where a diagnostic points for it. */\ntype Owner = {\n readonly name: string | undefined;\n readonly implements: readonly string[];\n readonly path: DefinitionPath;\n};\n\ntype ErrorCode = {\n readonly code: CheckDiagnosticCode;\n readonly repair: string;\n};\n\n/** The first graphql-js message pattern that matches picks the code. */\nconst ERROR_CODES: readonly (ErrorCode & { readonly pattern: RegExp })[] = [\n {\n pattern:\n /^(?:Interface field |Object field \\S+ includes required argument |Type \\S+ (?:must only implement|cannot implement|can only implement|must implement) )/,\n code: \"PH-DM-INTERFACE-INVALID\",\n repair:\n \"Give the type every field, argument and ancestor interface its interfaces declare, with compatible types.\",\n },\n {\n pattern: / must be (?:Input|Output) Type but got: /,\n code: \"PH-DM-TYPE-POSITION-INVALID\",\n repair:\n \"Reference input types only from input fields and arguments, and output types only from output fields.\",\n },\n {\n pattern: / within itself through a series of non-null fields: /,\n code: \"PH-DM-INPUT-CYCLE\",\n repair: \"Make one input field on the cycle nullable or a list.\",\n },\n];\n\nconst OTHER_ERROR: ErrorCode = {\n code: \"PH-DEF-COMPATIBILITY-INVALID\",\n repair:\n \"Correct the stored schema so graphql-js builds it; codegen and hosts build the same schema.\",\n};\n\n/** A model's schema has no operations, so graphql-js has no Query root to require. */\nconst NO_QUERY_ROOT = \"Query root type must be provided.\";\n\n/**\n * The SDL rules graphql-js applies, minus the directive rules: a stored\n * schema carries directive uses such as `@equals` without declaring them,\n * and codegen and hosts read them as annotations.\n */\nfunction sdlRules(graphql: GraphQLModule) {\n return [\n graphql.LoneSchemaDefinitionRule,\n graphql.UniqueOperationTypesRule,\n graphql.UniqueTypeNamesRule,\n graphql.UniqueEnumValueNamesRule,\n graphql.UniqueFieldDefinitionNamesRule,\n graphql.UniqueArgumentDefinitionNamesRule,\n graphql.UniqueDirectiveNamesRule,\n graphql.KnownTypeNamesRule,\n graphql.PossibleTypeExtensionsRule,\n graphql.UniqueArgumentNamesRule,\n graphql.UniqueInputFieldNamesRule,\n ];\n}\n\nconst NAMED_DEFINITION =\n /^(?:Scalar|Object|Interface|InputObject|Enum|Union)TypeDefinition$/;\n\n/**\n * Hosts keep the first definition of a repeated type name and codegen merges\n * the repeats, so a repeat is not an error here. Catalog and project scalars\n * the document uses without declaring become stub declarations, and a type\n * the document only extends gets an empty base to extend.\n */\nfunction validationDocument(\n nodes: readonly Node[],\n specification: DocumentModelSpecificationDefinition,\n): DocumentNode {\n const defined = new Set<string>();\n const definitions: object[] = nodes.filter((node) => {\n if (!NAMED_DEFINITION.test(node.kind) || node.name === undefined) {\n return true;\n }\n if (defined.has(node.name.value)) return false;\n defined.add(node.name.value);\n return true;\n });\n const define = (kind: string, value: string) => {\n if (defined.has(value)) return;\n defined.add(value);\n definitions.push({\n kind,\n name: { kind: \"Name\", value },\n directives: [],\n interfaces: [],\n fields: [],\n values: [],\n types: [],\n });\n };\n for (const name of [\n ...scalarCatalog.map((scalar) => scalar.name),\n ...specification.scalars.map((scalar) => scalar.name),\n ]) {\n define(\"ScalarTypeDefinition\", name);\n }\n for (const node of nodes) {\n if (node.kind.endsWith(\"TypeExtension\") && node.name !== undefined) {\n define(node.kind.replace(/Extension$/, \"Definition\"), node.name.value);\n }\n }\n return { kind: \"Document\", definitions } as unknown as DocumentNode;\n}\n\n/**\n * Maps every object inside each top-level node to that node's owner. A\n * type's first definition points at its structured type; any other node\n * points at its place in the retained document.\n */\nfunction ownersByNode(\n nodes: readonly Node[],\n specification: DocumentModelSpecificationDefinition,\n index: number,\n): ReadonlyMap<object, Owner> {\n const typeIndex = new Map(\n specification.types.map((type, position) => [type.name, position]),\n );\n const firstDefinitions = new Set<string>();\n const owners = new Map<object, Owner>();\n nodes.forEach((node, nodeIndex) => {\n const name = node.name?.value;\n const position = name === undefined ? undefined : typeIndex.get(name);\n const first =\n name !== undefined &&\n NAMED_DEFINITION.test(node.kind) &&\n !firstDefinitions.has(name);\n if (first) firstDefinitions.add(name);\n const owner: Owner = {\n name,\n implements: (node.interfaces ?? []).map((entry) => entry.name.value),\n path:\n first && position !== undefined\n ? [\"specifications\", index, \"types\", position]\n : [\n \"specifications\",\n index,\n \"graphQLCompatibility\",\n \"document\",\n \"definitions\",\n nodeIndex,\n ],\n };\n const visit = (value: unknown): void => {\n if (value === null || typeof value !== \"object\") return;\n owners.set(value, owner);\n for (const child of Object.values(value)) visit(child);\n };\n visit(node);\n });\n return owners;\n}\n\n/**\n * The owner of an error's last node, except that an interface error belongs\n * to the type that implements another owner of the error, which graphql-js\n * may list before or after the interface's own nodes.\n */\nfunction ownerOf(\n error: GraphQLError,\n owners: ReadonlyMap<object, Owner>,\n): Owner | undefined {\n const candidates = (error.nodes ?? []).flatMap(\n (node) => owners.get(node) ?? [],\n );\n const names = new Set(candidates.map(({ name }) => name));\n return (\n candidates.findLast((owner) =>\n owner.implements.some((name) => names.has(name)),\n ) ?? candidates.at(-1)\n );\n}\n\nfunction checkArtifact(\n artifact: NormalizedDocumentModelArtifact,\n): readonly DefinitionDiagnostic[] {\n const served = servedSpecification(artifact);\n const retained = served?.specification.graphQLCompatibility;\n if (served === undefined || retained === undefined || retained === null) {\n return [];\n }\n const { specification, index } = served;\n const graphql = loadGraphQL();\n const nodes = retained.document.definitions as readonly Node[];\n const document = validationDocument(nodes, specification);\n let errors: readonly GraphQLError[] = graphql.validateSDL(\n document,\n undefined,\n sdlRules(graphql),\n );\n if (errors.length === 0) {\n errors = graphql\n .validateSchema(\n graphql.buildASTSchema(document, { assumeValidSDL: true }),\n )\n .filter(({ message }) => message !== NO_QUERY_ROOT);\n }\n const owners = ownersByNode(nodes, specification, index);\n return errors.map((error) => {\n const { code, repair } =\n ERROR_CODES.find(({ pattern }) => pattern.test(error.message)) ??\n OTHER_ERROR;\n return checkDiagnostics.create({\n code,\n source: artifact.source,\n definition: documentModelRef(artifact),\n path: ownerOf(error, owners)?.path ?? [\n \"specifications\",\n index,\n \"graphQLCompatibility\",\n ],\n message: error.message,\n repair,\n });\n });\n}\n\n/**\n * The compiler validates every type it declares. A retained GraphQL document\n * is the schema codegen and hosts build, so graphql-js validates it as they\n * would.\n */\nexport const graphqlSchemaCheck: DefinitionCheck = {\n name: \"graphql-schema\",\n run: ({ artifacts }) => artifacts.flatMap(checkArtifact),\n};\n","import type { DefinitionDiagnostic } from \"@powerhousedao/shared/document-model\";\nimport type { NormalizedDocumentModelArtifact } from \"../adapters/types.js\";\nimport type { DefinitionSourceSet } from \"../definition-source-types.js\";\nimport { toolingDiagnostics } from \"../diagnostic-codes.js\";\nimport { documentModelRef } from \"./served-specification.js\";\n\n/**\n * A host registers one module per `documentType@version`. The loader already\n * reports two selected sources that claim one, so a claimant is reported here\n * only when it or the anchor comes from outside the selection.\n */\nexport function logicalCollisionDiagnostics(\n sourceSet: DefinitionSourceSet,\n [anchor, ...claimants]: readonly NormalizedDocumentModelArtifact[],\n): readonly DefinitionDiagnostic[] {\n const selected = new Set(sourceSet.sources.map(({ specifier }) => specifier));\n const isSelected = (artifact: NormalizedDocumentModelArtifact) =>\n selected.has(artifact.source.specifier);\n const key = `${anchor.documentType}@${anchor.version}`;\n return claimants\n .filter((claimant) => !(isSelected(claimant) && isSelected(anchor)))\n .map((claimant) =>\n toolingDiagnostics.create({\n code: \"PH-PKG-LOGICAL-COLLISION\",\n source: claimant.source,\n definition: documentModelRef(claimant),\n path: [],\n message: `Two sources claim ${key}, and a host registers one module per document type and version.`,\n expected: `one source for ${key}`,\n received: `${anchor.source.specifier} and ${claimant.source.specifier}`,\n repair:\n \"Keep one of the two models, or give one of them another document type.\",\n related: [\n {\n source: anchor.source,\n path: [],\n message: `This source also claims ${key}.`,\n },\n ],\n }),\n );\n}\n","import type { NormalizedDocumentModelArtifact } from \"../../adapters/types.js\";\nimport { logicalCollisionDiagnostics } from \"../../report/logical-collisions.js\";\nimport type { DefinitionCheck } from \"../types.js\";\n\nexport const logicalCollisionsCheck: DefinitionCheck = {\n name: \"logical-collisions\",\n run: ({ sourceSet, artifacts }) => {\n const groups = new Map<string, NormalizedDocumentModelArtifact[]>();\n for (const artifact of artifacts) {\n const key = `${artifact.documentType}@${artifact.version}`;\n groups.set(key, [...(groups.get(key) ?? []), artifact]);\n }\n return [...groups.values()].flatMap((group) =>\n logicalCollisionDiagnostics(sourceSet, group),\n );\n },\n};\n","import type {\n DefinitionDiagnostic,\n DefinitionPath,\n DefinitionSource,\n Sha256Digest,\n} from \"@powerhousedao/shared/document-model\";\nimport { canonicalDigest } from \"../../../kernel/primitives.js\";\nimport { checkDiagnostics } from \"../diagnostic-codes.js\";\nimport { servedSpecification } from \"../../report/served-specification.js\";\nimport type { DefinitionCheck } from \"../types.js\";\n\ntype Use = {\n readonly digest: Sha256Digest;\n readonly source: DefinitionSource;\n readonly path: DefinitionPath;\n};\n\n/**\n * A host serves every model of a package and declares each scalar once, so\n * two package scalars that share a name but not a definition collide there.\n * The compiler sees one model at a time and cannot catch this.\n */\nexport const packageScalarNamesCheck: DefinitionCheck = {\n name: \"package-scalar-names\",\n run: ({ artifacts }) => {\n const first = new Map<string, Use>();\n const diagnostics: DefinitionDiagnostic[] = [];\n for (const artifact of artifacts) {\n const served = servedSpecification(artifact);\n if (served === undefined) continue;\n served.specification.scalars.forEach((scalar, scalarIndex) => {\n if (!(\"definition\" in scalar)) return;\n const use = {\n digest: canonicalDigest(scalar.definition),\n source: artifact.source,\n path: [\"specifications\", served.index, \"scalars\", scalarIndex],\n };\n const known = first.get(scalar.name);\n if (known === undefined) {\n first.set(scalar.name, use);\n return;\n }\n if (known.digest === use.digest) return;\n diagnostics.push(\n checkDiagnostics.create({\n code: \"PH-PKG-SCALAR-CONFLICT\",\n source: use.source,\n definition: { kind: \"scalar\", key: scalar.name },\n path: use.path,\n message: `Two different package scalars are named ${scalar.name}.`,\n expected: \"one definition per package scalar name\",\n received: scalar.name,\n repair: `Declare ${scalar.name} once with defineScalar in scalars/index.ts and import it everywhere it is used.`,\n related: [\n {\n source: known.source,\n path: known.path,\n message: `The other ${scalar.name} is used here.`,\n },\n ],\n }),\n );\n });\n }\n return diagnostics;\n },\n};\n","import type {\n InputTypeDefinition,\n NamedGraphQLTypeDefinition,\n TypeReferenceDefinition,\n} from \"@powerhousedao/shared/document-model\";\n\ntype SegmentOperation = {\n readonly key: string;\n readonly input: InputTypeDefinition | null;\n};\n\ntype StoredSegments = {\n readonly global: readonly NamedGraphQLTypeDefinition[];\n readonly local: readonly NamedGraphQLTypeDefinition[];\n readonly operations: ReadonlyMap<\n string,\n readonly NamedGraphQLTypeDefinition[]\n >;\n};\n\nfunction referencedNames(\n definition: NamedGraphQLTypeDefinition,\n): readonly string[] {\n const names: string[] = [];\n const visit = (reference: TypeReferenceDefinition): void => {\n if (reference.kind === \"list\") {\n visit(reference.item);\n return;\n }\n if (reference.kind === \"named\") names.push(reference.name);\n };\n switch (definition.kind) {\n case \"enum\":\n return names;\n case \"union\":\n return definition.members;\n case \"input\":\n definition.fields.forEach((field) => visit(field.type));\n return names;\n case \"object\":\n case \"interface\":\n names.push(...(definition.implements ?? []));\n for (const field of definition.fields) {\n field.args?.forEach((argument) => visit(argument.type));\n visit(field.type);\n }\n return names;\n }\n}\n\nfunction reachableFrom(\n rootName: string | null,\n index: ReadonlyMap<string, NamedGraphQLTypeDefinition>,\n): ReadonlySet<string> {\n const reached = new Set<string>();\n if (rootName === null) return reached;\n const queue = [rootName];\n while (queue.length > 0) {\n const name = queue.pop() as string;\n if (reached.has(name)) continue;\n const definition = index.get(name);\n if (definition === undefined) continue;\n reached.add(name);\n queue.push(...referencedNames(definition));\n }\n return reached;\n}\n\nexport function assignStoredSegments(input: {\n readonly types: readonly NamedGraphQLTypeDefinition[];\n readonly globalRoot: string;\n readonly localRoot: string | null;\n readonly operations: readonly SegmentOperation[];\n}): StoredSegments {\n const stateIndex = new Map(\n input.types.map((definition) => [definition.name, definition]),\n );\n const globalReach = reachableFrom(input.globalRoot, stateIndex);\n const localReach = reachableFrom(input.localRoot, stateIndex);\n\n const operationIndex = new Map(stateIndex);\n for (const operation of input.operations) {\n if (operation.input !== null) {\n operationIndex.set(operation.input.name, operation.input);\n }\n }\n\n const claimed = new Set<string>();\n const operations = new Map<string, readonly NamedGraphQLTypeDefinition[]>();\n for (const operation of input.operations) {\n if (operation.input === null) continue;\n claimed.add(operation.input.name);\n const reached = reachableFrom(operation.input.name, operationIndex);\n const supporting = input.types.filter(\n (definition) =>\n definition.kind === \"input\" &&\n reached.has(definition.name) &&\n !claimed.has(definition.name),\n );\n for (const definition of supporting) claimed.add(definition.name);\n operations.set(operation.key, [operation.input, ...supporting]);\n }\n\n const local = input.types.filter(\n (definition) =>\n definition.kind !== \"input\" &&\n localReach.has(definition.name) &&\n !globalReach.has(definition.name),\n );\n const localDeclared = new Set(local.map((definition) => definition.name));\n // An input no operation reaches stays global, because the host re-extracts\n // input definitions from the state schema (create-schema.ts).\n const global = input.types.filter(\n (definition) =>\n !localDeclared.has(definition.name) && !claimed.has(definition.name),\n );\n return { global, local, operations };\n}\n","import type {\n DirectiveUseDefinition,\n EnumValueDefinition,\n FieldDefinition,\n GraphQLConstValueNode,\n GraphQLDirectiveNode,\n GraphQLFieldDefinitionNode,\n GraphQLInputValueDefinitionNode,\n GraphQLStringValueNode,\n GraphQLTypeNode,\n InputFieldDefinition,\n JsonValue,\n LocationFreeGraphQLDocumentNode,\n NamedGraphQLTypeDefinition,\n TypeReferenceDefinition,\n} from \"@powerhousedao/shared/document-model\";\nimport { foldTypeExtensions } from \"../../kernel/graphql-ast.js\";\n\n/** graphql-js's reason for a bare `@deprecated`. */\nconst DEFAULT_DEPRECATION_REASON = \"No longer supported\";\n\nexport type GraphQLDefinitionNode =\n LocationFreeGraphQLDocumentNode[\"definitions\"][number];\n\ntype NamedDefinitionNode = Extract<\n GraphQLDefinitionNode,\n {\n readonly kind:\n | \"ObjectTypeDefinition\"\n | \"InterfaceTypeDefinition\"\n | \"InputObjectTypeDefinition\"\n | \"EnumTypeDefinition\"\n | \"UnionTypeDefinition\";\n }\n>;\n\nconst NAMED_TYPE_NODE =\n /^(?:Object|Interface|InputObject|Enum|Union)Type(?:Definition|Extension)$/;\n\nfunction description(node: GraphQLStringValueNode | undefined): string | null {\n return node === undefined ? null : node.value;\n}\n\nfunction constValue(node: GraphQLConstValueNode): JsonValue {\n switch (node.kind) {\n case \"IntValue\":\n case \"FloatValue\":\n return Number(node.value);\n case \"StringValue\":\n case \"EnumValue\":\n case \"BooleanValue\":\n return node.value;\n case \"NullValue\":\n return null;\n case \"ListValue\":\n return node.values.map(constValue);\n case \"ObjectValue\":\n return Object.fromEntries(\n node.fields.map((field) => [field.name.value, constValue(field.value)]),\n );\n }\n}\n\nfunction typeReference(\n node: GraphQLTypeNode,\n declared: ReadonlySet<string>,\n required = false,\n): TypeReferenceDefinition {\n switch (node.kind) {\n case \"NonNullType\":\n return typeReference(node.type, declared, true);\n case \"ListType\":\n return {\n kind: \"list\",\n required,\n item: typeReference(node.type, declared),\n };\n case \"NamedType\":\n return {\n kind: declared.has(node.name.value) ? \"named\" : \"scalar\",\n name: node.name.value,\n required,\n };\n }\n}\n\nfunction directives(nodes: readonly GraphQLDirectiveNode[]): {\n readonly deprecated: string | null;\n readonly uses?: readonly DirectiveUseDefinition[];\n} {\n const index = nodes.findIndex(\n (node) =>\n node.name.value === \"deprecated\" &&\n node.arguments.every(\n (argument) =>\n argument.name.value === \"reason\" &&\n argument.value.kind === \"StringValue\",\n ),\n );\n const reason = nodes[index]?.arguments[0]?.value as\n | GraphQLStringValueNode\n | undefined;\n const rest = nodes.filter((_, position) => position !== index);\n return {\n deprecated:\n index === -1 ? null : (reason?.value ?? DEFAULT_DEPRECATION_REASON),\n ...(rest.length > 0 && {\n uses: rest.map((node) => ({\n name: node.name.value,\n arguments: node.arguments.map((argument) => ({\n name: argument.name.value,\n value: constValue(argument.value),\n })),\n })),\n }),\n };\n}\n\nfunction inputField(\n node: GraphQLInputValueDefinitionNode,\n declared: ReadonlySet<string>,\n): InputFieldDefinition {\n const { deprecated, uses } = directives(node.directives);\n return {\n key: node.name.value,\n name: node.name.value,\n description: description(node.description),\n deprecated,\n type: typeReference(node.type, declared),\n ...(node.defaultValue !== undefined && {\n defaultValue: constValue(node.defaultValue),\n }),\n ...(uses !== undefined && { directives: uses }),\n };\n}\n\nfunction outputField(\n node: GraphQLFieldDefinitionNode,\n declared: ReadonlySet<string>,\n): FieldDefinition {\n const { deprecated, uses } = directives(node.directives);\n return {\n key: node.name.value,\n name: node.name.value,\n description: description(node.description),\n deprecated,\n ...(node.arguments.length > 0 && {\n args: node.arguments.map((argument) => inputField(argument, declared)),\n }),\n type: typeReference(node.type, declared),\n ...(uses !== undefined && { directives: uses }),\n };\n}\n\nfunction enumValue(\n node: Extract<\n GraphQLDefinitionNode,\n { kind: \"EnumTypeDefinition\" }\n >[\"values\"][number],\n): EnumValueDefinition {\n const { deprecated, uses } = directives(node.directives);\n return {\n name: node.name.value,\n description: description(node.description),\n deprecated,\n ...(uses !== undefined && { directives: uses }),\n };\n}\n\nfunction namedType(\n node: NamedDefinitionNode,\n declared: ReadonlySet<string>,\n): NamedGraphQLTypeDefinition {\n switch (node.kind) {\n case \"ObjectTypeDefinition\":\n case \"InterfaceTypeDefinition\":\n return {\n kind: node.kind === \"ObjectTypeDefinition\" ? \"object\" : \"interface\",\n name: node.name.value,\n description: description(node.description),\n ...(node.interfaces.length > 0 && {\n implements: node.interfaces.map((entry) => entry.name.value),\n }),\n fields: node.fields.map((field) => outputField(field, declared)),\n };\n case \"InputObjectTypeDefinition\":\n return {\n kind: \"input\",\n name: node.name.value,\n description: description(node.description),\n unknownKeys: \"preserve\",\n fields: node.fields.map((field) => inputField(field, declared)),\n };\n case \"EnumTypeDefinition\":\n return {\n kind: \"enum\",\n name: node.name.value,\n description: description(node.description),\n values: node.values.map(enumValue),\n };\n case \"UnionTypeDefinition\":\n return {\n kind: \"union\",\n name: node.name.value,\n description: description(node.description),\n members: node.types.map((member) => member.name.value),\n };\n }\n}\n\n/** Names of the object, interface, input, enum and union types the nodes define or extend. */\nexport function declaredTypeNames(\n definitions: readonly GraphQLDefinitionNode[],\n): ReadonlySet<string> {\n const declared = new Set<string>();\n for (const node of definitions) {\n if (NAMED_TYPE_NODE.test(node.kind) && \"name\" in node) {\n declared.add(node.name.value);\n }\n }\n return declared;\n}\n\n/**\n * Every object, interface, input, enum and union type the nodes define or\n * extend, with each extension folded into its type: defined types in\n * document order, then types the nodes only extend. A repeated definition or\n * member keeps its first occurrence; graphql-js validation reports the\n * repeat. A reference to a name in `declared` is a named type; any other\n * reference is a scalar.\n */\nexport function structuredTypes(\n definitions: readonly GraphQLDefinitionNode[],\n declared: ReadonlySet<string> = declaredTypeNames(definitions),\n): readonly NamedGraphQLTypeDefinition[] {\n // A folded node is its first definition or extension with the member\n // nodes of every extension appended, under the definition's kind.\n return [...foldTypeExtensions(definitions, []).types.values()].map(\n ({ node }) => namedType(node as unknown as NamedDefinitionNode, declared),\n );\n}\n\nfunction namedTypeName(node: GraphQLTypeNode): string {\n return node.kind === \"NamedType\" ? node.name.value : namedTypeName(node.type);\n}\n\n/**\n * The type name every field and field argument of the nodes refers to,\n * extensions included, in document order and with repeats.\n */\nexport function referencedTypeNames(\n definitions: readonly GraphQLDefinitionNode[],\n): readonly string[] {\n const names: string[] = [];\n for (const node of definitions) {\n if (!(\"fields\" in node)) continue;\n for (const field of node.fields) {\n names.push(namedTypeName(field.type));\n for (const argument of \"arguments\" in field ? field.arguments : []) {\n names.push(namedTypeName(argument.type));\n }\n }\n }\n return names;\n}\n","import type {\n DefinitionDiagnostic,\n DefinitionPath,\n} from \"@powerhousedao/shared/document-model\";\nimport {\n rejectionReceived,\n snapshotArray,\n snapshotRecord,\n} from \"../../kernel/data-properties.js\";\nimport { describeReceived } from \"../../kernel/diagnostics.js\";\nimport type { NormalizedDocumentModelArtifact } from \"../adapters/types.js\";\nimport { checkDiagnostics } from \"./diagnostic-codes.js\";\nimport { documentModelRef } from \"../report/served-specification.js\";\n\ntype Scope = \"global\" | \"local\";\n\n/** A stored SDL string, where it sits in the source, and what it describes. */\nexport type StoredSchemaSegment = {\n readonly path: DefinitionPath;\n readonly schema: string;\n readonly of:\n | { readonly scope: Scope }\n | { readonly module: number; readonly operation: number };\n};\n\n/** The stored strings of the specification an artifact serves. */\nexport type ServedStoredSpecification = {\n readonly path: DefinitionPath;\n readonly initialValues: Readonly<Record<Scope, string>>;\n /** In the order the stored model lists them: global, local, then operations. */\n readonly segments: readonly StoredSchemaSegment[];\n};\n\ntype StoredHistory = {\n readonly path: DefinitionPath;\n readonly versions: readonly number[];\n /** Undefined when the stored history has no specification for the served version. */\n readonly served: ServedStoredSpecification | undefined;\n};\n\nexport type StoredModelRead =\n | ({ readonly ok: true } & StoredHistory)\n | { readonly ok: false; readonly diagnostic: DefinitionDiagnostic };\n\ntype Read<T> =\n | { readonly ok: true; readonly value: T }\n | {\n readonly ok: false;\n readonly path: DefinitionPath;\n readonly expected: string;\n readonly received: string;\n };\n\nfunction record(\n value: unknown,\n path: DefinitionPath,\n): Read<{ readonly [key: string]: unknown }> {\n const snapshot = snapshotRecord(value, undefined, path);\n return snapshot.ok\n ? snapshot\n : {\n ok: false,\n path: snapshot.path,\n expected: \"a plain record\",\n received: rejectionReceived(snapshot),\n };\n}\n\nfunction array(value: unknown, path: DefinitionPath): Read<readonly unknown[]> {\n const snapshot = snapshotArray(value, path);\n return snapshot.ok\n ? snapshot\n : {\n ok: false,\n path: snapshot.path,\n expected: \"an array\",\n received: rejectionReceived(snapshot),\n };\n}\n\nfunction text(value: unknown, path: DefinitionPath): Read<string> {\n return typeof value === \"string\"\n ? { ok: true, value }\n : {\n ok: false,\n path,\n expected: \"a string\",\n received: describeReceived(value),\n };\n}\n\nfunction readServedStoredSpecification(\n value: unknown,\n path: DefinitionPath,\n): Read<ServedStoredSpecification> {\n const specification = record(value, path);\n if (!specification.ok) return specification;\n const state = record(specification.value.state, [...path, \"state\"]);\n if (!state.ok) return state;\n const initialValues: Partial<Record<Scope, string>> = {};\n const segments: StoredSchemaSegment[] = [];\n for (const scope of [\"global\", \"local\"] as const) {\n const at = [...path, \"state\", scope];\n const stored = record(state.value[scope], at);\n if (!stored.ok) return stored;\n const schema = text(stored.value.schema, [...at, \"schema\"]);\n if (!schema.ok) return schema;\n const initialValue = text(stored.value.initialValue, [\n ...at,\n \"initialValue\",\n ]);\n if (!initialValue.ok) return initialValue;\n initialValues[scope] = initialValue.value;\n segments.push({\n path: [...at, \"schema\"],\n schema: schema.value,\n of: { scope },\n });\n }\n const modules = array(specification.value.modules, [...path, \"modules\"]);\n if (!modules.ok) return modules;\n for (const [moduleIndex, entry] of modules.value.entries()) {\n const at = [...path, \"modules\", moduleIndex];\n const module = record(entry, at);\n if (!module.ok) return module;\n const operations = array(module.value.operations, [...at, \"operations\"]);\n if (!operations.ok) return operations;\n for (const [operationIndex, member] of operations.value.entries()) {\n const operationPath = [...at, \"operations\", operationIndex];\n const operation = record(member, operationPath);\n if (!operation.ok) return operation;\n if (operation.value.schema === null) continue;\n const schema = text(operation.value.schema, [...operationPath, \"schema\"]);\n if (!schema.ok) return schema;\n segments.push({\n path: [...operationPath, \"schema\"],\n schema: schema.value,\n of: { module: moduleIndex, operation: operationIndex },\n });\n }\n }\n return {\n ok: true,\n value: {\n path,\n initialValues: initialValues as Record<Scope, string>,\n segments,\n },\n };\n}\n\nfunction storedHistory(\n artifact: NormalizedDocumentModelArtifact,\n): Read<StoredHistory> {\n const documentModel = record(artifact.documentModel, [\"documentModel\"]);\n const global = documentModel.ok\n ? record(documentModel.value.global, [\"documentModel\", \"global\"])\n : documentModel;\n if (!global.ok) return global;\n const path = [\"documentModel\", \"global\", \"specifications\"];\n const specifications = array(global.value.specifications, path);\n if (!specifications.ok) return specifications;\n const versions: number[] = [];\n let served: unknown;\n let servedIndex = -1;\n for (const [index, entry] of specifications.value.entries()) {\n const specification = record(entry, [...path, index]);\n if (!specification.ok) return specification;\n const { version } = specification.value;\n if (typeof version !== \"number\") {\n return {\n ok: false,\n path: [...path, index, \"version\"],\n expected: \"a version number\",\n received: describeReceived(version),\n };\n }\n versions.push(version);\n if (version === artifact.version && servedIndex === -1) {\n served = entry;\n servedIndex = index;\n }\n }\n if (servedIndex === -1) {\n return { ok: true, value: { path, versions, served: undefined } };\n }\n const specification = readServedStoredSpecification(served, [\n ...path,\n servedIndex,\n ]);\n return specification.ok\n ? { ok: true, value: { path, versions, served: specification.value } }\n : specification;\n}\n\n/**\n * Reads the stored model an artifact serves without trusting its shape: a\n * module assembled by hand can carry anything there. Every check that reads\n * stored strings goes through this, so each reports one malformed member the\n * same way and the report keeps it once.\n */\nexport function readStoredModel(\n artifact: NormalizedDocumentModelArtifact,\n): StoredModelRead {\n const read = storedHistory(artifact);\n if (read.ok) return { ok: true, ...read.value };\n return {\n ok: false,\n diagnostic: checkDiagnostics.create({\n code: \"PH-DM-DECLARATION-INVALID\",\n source: artifact.source,\n definition: documentModelRef(artifact),\n path: read.path,\n message:\n \"The stored document model this source serves is malformed, so hosts and codegen cannot read it.\",\n expected: read.expected,\n received: read.received,\n repair:\n \"Export the module materialize returned, or save the model again from the document model editor; the stored model is not edited by hand.\",\n }),\n };\n}\n","import type {\n DefinitionDiagnostic,\n DefinitionPath,\n NamedGraphQLTypeDefinition,\n} from \"@powerhousedao/shared/document-model\";\nimport { assignStoredSegments } from \"../../../compiler/segments.js\";\nimport {\n canonicalJson,\n compareCodeUnits,\n EMPTY_INPUT_FIELD_NAME,\n} from \"../../../kernel/primitives.js\";\nimport type { NormalizedDocumentModelArtifact } from \"../../adapters/types.js\";\nimport {\n declaredTypeNames,\n type GraphQLDefinitionNode,\n structuredTypes,\n} from \"../../graphql/ast-to-structured.js\";\nimport { parseSchema } from \"../../graphql/parse-schema.js\";\nimport { checkDiagnostics } from \"../diagnostic-codes.js\";\nimport {\n documentModelRef,\n servedSpecification,\n} from \"../../report/served-specification.js\";\nimport { readStoredModel } from \"../stored-specification.js\";\nimport type { DefinitionCheck } from \"../types.js\";\n\ntype Segment = {\n readonly path: DefinitionPath;\n readonly stored: string;\n /** What the canonical printer puts in this segment. */\n readonly printed: readonly NamedGraphQLTypeDefinition[];\n};\n\ntype Report = (\n path: DefinitionPath,\n message: string,\n expected: string,\n received: string,\n) => void;\n\n/**\n * SDL cannot spell an input without fields, a field key apart from its name,\n * or a member order that means nothing, so those are not compared.\n */\nfunction comparable(type: NamedGraphQLTypeDefinition): string {\n if (type.kind === \"enum\") return canonicalJson(type);\n if (type.kind === \"union\") {\n return canonicalJson({\n ...type,\n members: [...type.members].sort(compareCodeUnits),\n });\n }\n const fields = type.fields.map((field) => {\n const { key: _key, ...rest } = field;\n return \"args\" in field && field.args !== undefined\n ? {\n ...rest,\n args: field.args.map(({ key: _argKey, ...arg }) => arg),\n }\n : rest;\n });\n const [only] = fields;\n const emptyMarker =\n type.kind === \"input\" &&\n fields.length === 1 &&\n only.name === EMPTY_INPUT_FIELD_NAME &&\n only.type.kind === \"scalar\" &&\n only.type.name === \"Boolean\" &&\n !only.type.required;\n return canonicalJson({\n ...type,\n ...(\"implements\" in type &&\n type.implements !== undefined && {\n implements: [...type.implements].sort(compareCodeUnits),\n }),\n fields: emptyMarker ? [] : fields,\n });\n}\n\nfunction differs(\n stored: NamedGraphQLTypeDefinition,\n declared: NamedGraphQLTypeDefinition,\n): boolean {\n return comparable(stored) !== comparable(declared);\n}\n\n/** The canonical printer owns each segment, so every segment holds exactly its printed types. */\nfunction compareCanonical(\n report: Report,\n segment: Segment,\n stored: readonly NamedGraphQLTypeDefinition[],\n): void {\n const expected = segment.printed.map(({ name }) => name);\n const received = stored.map(({ name }) => name);\n const missing = expected.find((name) => !received.includes(name));\n const surplus = received.find((name) => !expected.includes(name));\n if (missing !== undefined || surplus !== undefined) {\n report(\n segment.path,\n missing !== undefined\n ? `The stored schema segment does not declare ${missing}.`\n : `The stored schema segment declares ${surplus}, which the definition places elsewhere or not at all.`,\n expected.join(\", \"),\n received.join(\", \"),\n );\n return;\n }\n for (const declared of segment.printed) {\n const copy = stored.find(({ name }) => name === declared.name);\n if (copy === undefined || !differs(copy, declared)) continue;\n report(\n [...segment.path, declared.name],\n `The stored schema segment describes ${declared.name} differently than the definition.`,\n canonicalJson(declared),\n canonicalJson(copy),\n );\n }\n}\n\ntype ParsedSegment = {\n readonly segment: Segment;\n readonly definitions: readonly GraphQLDefinitionNode[];\n};\n\n/**\n * A schema-first model keeps its own split, and a segment may extend a type\n * another declares, so the union of segments is folded and compared.\n */\nfunction compareExplicit(\n report: Report,\n path: DefinitionPath,\n segments: readonly ParsedSegment[],\n declaration: ReadonlyMap<string, NamedGraphQLTypeDefinition>,\n): void {\n const types = structuredTypes(\n segments.flatMap(({ definitions }) => definitions),\n new Set(declaration.keys()),\n );\n const segmentOf = (name: string): DefinitionPath =>\n segments.find(({ definitions }) => declaredTypeNames(definitions).has(name))\n ?.segment.path ?? path;\n const seen = new Set<string>();\n for (const type of types) {\n seen.add(type.name);\n const declared = declaration.get(type.name);\n if (declared === undefined) {\n report(\n segmentOf(type.name),\n `The stored schema segment declares ${type.name}, which the definition does not describe.`,\n [...declaration.keys()].join(\", \"),\n type.name,\n );\n } else if (differs(type, declared)) {\n report(\n [...segmentOf(type.name), type.name],\n `The stored schema segment describes ${type.name} differently than the definition.`,\n canonicalJson(declared),\n canonicalJson(type),\n );\n }\n }\n for (const name of declaration.keys()) {\n if (seen.has(name)) continue;\n report(\n path,\n `No stored schema segment declares ${name}.`,\n name,\n [...seen].join(\", \"),\n );\n }\n}\n\nfunction checkArtifact(\n artifact: NormalizedDocumentModelArtifact,\n): readonly DefinitionDiagnostic[] {\n const served = servedSpecification(artifact);\n if (served === undefined) return [];\n const { specification, index } = served;\n const at: DefinitionPath = [\"specifications\", index];\n const diagnostics: DefinitionDiagnostic[] = [];\n const report: Report = (path, message, expected, received) =>\n diagnostics.push(\n checkDiagnostics.create({\n code: \"PH-DEF-COMPATIBILITY-INVALID\",\n source: artifact.source,\n definition: documentModelRef(artifact),\n path,\n message,\n expected,\n received,\n repair:\n \"Export the module materialize returned, or save the model again from the document model editor; a stored string that describes another structure is a definition error.\",\n }),\n );\n\n const operations = specification.modules.flatMap((module) =>\n module.operations.map((operation) => ({\n key: `${module.key}/${operation.key}`,\n input: operation.input,\n })),\n );\n const printed = assignStoredSegments({\n types: specification.types,\n globalRoot: specification.state.global.root.name,\n localRoot: specification.state.local.root?.name ?? null,\n operations,\n });\n const declaration = new Map<string, NamedGraphQLTypeDefinition>(\n [\n ...specification.types,\n ...operations.flatMap(({ input }) => (input === null ? [] : [input])),\n ].map((type) => [type.name, type]),\n );\n const stored = readStoredModel(artifact);\n if (!stored.ok) diagnostics.push(stored.diagnostic);\n const storedSpecification = stored.ok ? stored.served : undefined;\n const canonical =\n artifact.definition.compatibility.serialization === \"canonical-v1\";\n\n // The materializer writes every operation's segment; a schema-first\n // operation without an input may store none.\n const missing = new Map<string, string>();\n specification.modules.forEach((module, moduleIndex) =>\n module.operations.forEach((operation, operationIndex) => {\n if (canonical || operation.input !== null) {\n missing.set(\n `${moduleIndex}/${operationIndex}`,\n `${module.key}.${operation.key}`,\n );\n }\n }),\n );\n const segments: Segment[] = [];\n for (const { path, schema, of } of storedSpecification?.segments ?? []) {\n if (\"scope\" in of) {\n segments.push({ path, stored: schema, printed: printed[of.scope] });\n continue;\n }\n const module = specification.modules.at(of.module);\n const operation = module?.operations.at(of.operation);\n if (module === undefined || operation === undefined) {\n report(\n path,\n \"The stored schema segment belongs to an operation the definition does not declare.\",\n \"a segment of a declared operation\",\n schema,\n );\n continue;\n }\n missing.delete(`${of.module}/${of.operation}`);\n segments.push({\n path,\n stored: schema,\n printed:\n printed.operations.get(`${module.key}/${operation.key}`) ??\n (operation.input === null ? [] : [operation.input]),\n });\n }\n if (storedSpecification !== undefined) {\n for (const operation of missing.values()) {\n report(\n storedSpecification.path,\n `The stored model has no schema segment for operation ${operation}.`,\n `a schema segment for ${operation}`,\n \"absent\",\n );\n }\n }\n\n const parsed = segments.flatMap((segment): ParsedSegment[] => {\n const result = parseSchema(segment.stored);\n if (result.ok) {\n return [{ segment, definitions: result.document.definitions }];\n }\n report(\n segment.path,\n `The stored schema segment is not GraphQL SDL: ${result.message}`,\n \"GraphQL SDL\",\n segment.stored,\n );\n return [];\n });\n if (canonical) {\n const declared = new Set(declaration.keys());\n for (const { segment, definitions } of parsed) {\n compareCanonical(report, segment, structuredTypes(definitions, declared));\n }\n } else if (\n storedSpecification !== undefined &&\n parsed.length === segments.length\n ) {\n compareExplicit(report, storedSpecification.path, parsed, declaration);\n }\n\n for (const scope of [\"global\", \"local\"] as const) {\n const state = specification.state[scope];\n const text = state.materialized.initialValue;\n if (text.trim() === \"\") continue;\n let value: unknown;\n try {\n value = JSON.parse(text);\n } catch {\n value = undefined;\n }\n const received = value === undefined ? text : canonicalJson(value);\n if (received === canonicalJson(state.initialValue)) continue;\n report(\n [...at, \"state\", scope, \"initialValue\"],\n `The stored ${scope} initial value describes a different value than the definition.`,\n canonicalJson(state.initialValue),\n received,\n );\n }\n return diagnostics;\n}\n\n/**\n * Hosts and codegen read the stored SDL strings; the definition carries the\n * structure. Every segment is checked: for a canonical model the strings are\n * the printer's output, so a mismatch is a forged module or a compiler defect.\n */\nexport const retainedSerializationCheck: DefinitionCheck = {\n name: \"retained-serialization\",\n run: ({ artifacts }) => artifacts.flatMap(checkArtifact),\n};\n","import type { DefinitionDiagnostic } from \"@powerhousedao/shared/document-model\";\nimport { canonicalJson } from \"../../../kernel/primitives.js\";\nimport { checkDiagnostics } from \"../diagnostic-codes.js\";\nimport {\n documentModelRef,\n servedSpecification,\n} from \"../../report/served-specification.js\";\nimport { readStoredModel } from \"../stored-specification.js\";\nimport type { DefinitionCheck } from \"../types.js\";\n\n/**\n * Hosts read the stored model; consumers of the definition read the\n * structure. A module assembled by hand can make the two disagree.\n */\nexport const storedMaterializationCheck: DefinitionCheck = {\n name: \"stored-materialization\",\n run: ({ artifacts }) =>\n artifacts.flatMap((artifact): DefinitionDiagnostic[] => {\n const stored = readStoredModel(artifact);\n if (!stored.ok) return [stored.diagnostic];\n const storedVersions = canonicalJson(stored.versions);\n const declaredVersions = canonicalJson(\n artifact.definition.specifications.map(({ version }) => version),\n );\n const at = {\n source: artifact.source,\n definition: documentModelRef(artifact),\n };\n if (storedVersions !== declaredVersions) {\n return [\n checkDiagnostics.create({\n ...at,\n code: \"PH-DM-DECLARATION-INVALID\",\n path: stored.path,\n message:\n \"The stored specification history and the structured definition cover different versions.\",\n expected: declaredVersions,\n received: storedVersions,\n repair:\n \"Export the module materialize returned; do not assemble the stored model or its definition by hand.\",\n }),\n ];\n }\n const served = servedSpecification(artifact);\n if (served === undefined || stored.served === undefined) return [];\n const { path, initialValues } = stored.served;\n return ([\"global\", \"local\"] as const).flatMap((scope) => {\n const expected =\n served.specification.state[scope].materialized.initialValue;\n const received = initialValues[scope];\n if (received === expected) return [];\n return [\n checkDiagnostics.create({\n ...at,\n code: \"PH-DM-INITIAL-VALUE-INVALID\",\n path: [...path, \"state\", scope, \"initialValue\"],\n message: `The stored ${scope} initial value is not the one the definition materializes.`,\n expected,\n received,\n repair:\n \"Export the module materialize returned; a stored initial value is not an independent setting.\",\n }),\n ];\n });\n }),\n};\n","import { checkDiagnostics } from \"../diagnostic-codes.js\";\nimport type { DefinitionCheck } from \"../types.js\";\n\n/** Turns each declaration the project scan found unregistered into one diagnostic. */\nexport const unregisteredDefinitionsCheck: DefinitionCheck = {\n name: \"unregistered-definitions\",\n run: ({ unregistered }) =>\n unregistered.map(({ unit, specifier }) => {\n const entry = `{ \"specifier\": \"${specifier}\" }`;\n return checkDiagnostics.create({\n code: \"PH-PKG-DEFINITION-UNREGISTERED\",\n source: { specifier },\n path: [],\n message: `${unit} declares a code-first document model that no definitionSources entry reaches, so the package leaves it out.`,\n expected: `a definitionSources entry that reaches ${specifier}`,\n received: \"no entry\",\n repair: `Add ${entry} to definitionSources.entries in powerhouse.config.json. If definitionSources is absent or schema-first, set it to { \"formatVersion\": 1, \"mode\": \"code-first\", \"entries\": [${entry}] }; schema-first models keep generating from their stored files.`,\n });\n }),\n};\n","import type {\n DefinitionCheckReport,\n DefinitionCheckSkipReason,\n DefinitionDiagnostic,\n} from \"@powerhousedao/shared/document-model\";\nimport { compareDefinitionDiagnostics } from \"../../kernel/diagnostics.js\";\nimport { canonicalJson, compareCodeUnits } from \"../../kernel/primitives.js\";\nimport type { NormalizedDocumentModelArtifact } from \"../adapters/types.js\";\nimport type { DefinitionSourceSet } from \"../definition-source-types.js\";\n\nexport type DefinitionStatus = DefinitionCheckReport[\"status\"];\n\n/** These phases mean the tool could not read the package, not that a model is wrong. */\nconst FAILURE_PHASES: ReadonlySet<string> = new Set([\n \"configuration\",\n \"import\",\n]);\n\n/** Drops exact repeats and orders the rest independently of input order. */\nexport function sortedUniqueDiagnostics(\n diagnostics: readonly DefinitionDiagnostic[],\n): readonly DefinitionDiagnostic[] {\n const unique = new Map<string, DefinitionDiagnostic>();\n for (const diagnostic of diagnostics) {\n unique.set(canonicalJson(diagnostic), diagnostic);\n }\n return [...unique]\n .sort(\n ([leftKey, left], [rightKey, right]) =>\n compareDefinitionDiagnostics(left, right) ||\n compareCodeUnits(leftKey, rightKey),\n )\n .map(([, diagnostic]) => diagnostic);\n}\n\nexport function definitionStatus(input: {\n readonly skipReason?: DefinitionCheckSkipReason;\n readonly definitions: readonly unknown[];\n readonly diagnostics: readonly DefinitionDiagnostic[];\n}): DefinitionStatus {\n const errors = input.diagnostics.filter(\n ({ severity }) => severity === \"error\",\n );\n if (errors.some(({ phase }) => FAILURE_PHASES.has(phase))) return \"failed\";\n if (errors.length > 0) return \"invalid\";\n if (\n input.skipReason !== undefined &&\n input.definitions.length === 0 &&\n input.diagnostics.length === 0\n ) {\n return \"skipped\";\n }\n return \"ok\";\n}\n\nexport function compareArtifacts(\n left: NormalizedDocumentModelArtifact,\n right: NormalizedDocumentModelArtifact,\n): number {\n return (\n compareCodeUnits(left.documentType, right.documentType) ||\n left.version - right.version ||\n compareCodeUnits(left.source.specifier, right.source.specifier) ||\n compareCodeUnits(\n canonicalJson(left.source.exportPath ?? []),\n canonicalJson(right.source.exportPath ?? []),\n )\n );\n}\n\ntype InventoryEntry = DefinitionCheckReport[\"definitions\"][number];\n\n/** The artifact order, extended to every kind of inventory entry. */\nfunction compareInventoryEntries(\n left: InventoryEntry,\n right: InventoryEntry,\n): number {\n return (\n compareCodeUnits(left.key, right.key) ||\n (left.version ?? 0) - (right.version ?? 0) ||\n compareCodeUnits(left.source.specifier, right.source.specifier) ||\n compareCodeUnits(\n canonicalJson(left.source.exportPath ?? []),\n canonicalJson(right.source.exportPath ?? []),\n ) ||\n compareCodeUnits(left.kind, right.kind)\n );\n}\n\n/** Builds the stored check report. Profile is `edit`: release checks come later. */\nexport function definitionCheckReport(input: {\n readonly sourceSet: DefinitionSourceSet;\n readonly skipReason?: DefinitionCheckSkipReason;\n readonly artifacts: readonly NormalizedDocumentModelArtifact[];\n /** Inventory entries besides the artifacts. */\n readonly definitions: readonly InventoryEntry[];\n readonly diagnostics: readonly DefinitionDiagnostic[];\n}): DefinitionCheckReport {\n const diagnostics = sortedUniqueDiagnostics(input.diagnostics);\n const definitions = [\n ...input.artifacts.map((artifact): InventoryEntry => ({\n kind: \"document-model\",\n key: artifact.documentType,\n version: artifact.version,\n digest: artifact.digest,\n source: artifact.source,\n })),\n ...input.definitions,\n ].sort(compareInventoryEntries);\n const status = definitionStatus({\n ...(input.skipReason !== undefined && { skipReason: input.skipReason }),\n definitions,\n diagnostics,\n });\n const errors = diagnostics.filter(\n ({ severity }) => severity === \"error\",\n ).length;\n const common = {\n kind: \"powerhouse.definition-check\",\n formatVersion: 1,\n profile: \"edit\",\n sourceSet: input.sourceSet,\n definitions,\n diagnostics,\n summary: { errors, warnings: diagnostics.length - errors },\n } as const;\n if (status === \"skipped\") {\n // definitionStatus answers skipped only when a skip reason is present.\n return {\n ...common,\n status,\n skipReason: input.skipReason as DefinitionCheckSkipReason,\n };\n }\n return { ...common, status };\n}\n","import type {\n DefinitionCheckReport,\n DefinitionDiagnostic,\n DefinitionPath,\n DefinitionSource,\n} from \"@powerhousedao/shared/document-model\";\nimport type { DefinitionRelocation } from \"../adapters/producer.js\";\nimport { duplicateIdentitiesCheck } from \"./checks/duplicate-identities.js\";\nimport { graphqlSchemaCheck } from \"./checks/graphql-schema.js\";\nimport { logicalCollisionsCheck } from \"./checks/logical-collisions.js\";\nimport { packageScalarNamesCheck } from \"./checks/package-scalar-names.js\";\nimport { retainedSerializationCheck } from \"./checks/retained-serialization.js\";\nimport { storedMaterializationCheck } from \"./checks/stored-materialization.js\";\nimport { unregisteredDefinitionsCheck } from \"./checks/unregistered-definitions.js\";\nimport { definitionCheckReport } from \"../report/status.js\";\nimport type {\n DefinitionCheckInput,\n LoadedDefinitionProject,\n} from \"../report/types.js\";\nimport type { DefinitionCheck } from \"./types.js\";\n\n/**\n * The checks `ph model check` runs on document models. A later layer adds its\n * own with `[...documentModelChecks, ...theirs]`.\n */\nexport const documentModelChecks: readonly DefinitionCheck[] = Object.freeze([\n storedMaterializationCheck,\n duplicateIdentitiesCheck,\n packageScalarNamesCheck,\n logicalCollisionsCheck,\n graphqlSchemaCheck,\n retainedSerializationCheck,\n unregisteredDefinitionsCheck,\n]);\n\n/** Moves a check's normalized paths to where each source's author edits them. */\nfunction relocated(\n diagnostic: DefinitionDiagnostic,\n relocations: ReadonlyMap<string, DefinitionRelocation>,\n): DefinitionDiagnostic {\n const at = (source: DefinitionSource | undefined, path: DefinitionPath) =>\n (source === undefined ? undefined : relocations.get(source.specifier))?.(\n path,\n ) ?? path;\n return {\n ...diagnostic,\n path: at(diagnostic.source, diagnostic.path),\n ...(diagnostic.related !== undefined && {\n related: diagnostic.related.map((location) => ({\n ...location,\n path: at(location.source, location.path),\n })),\n }),\n };\n}\n\n/**\n * @experimental Runs every check over a loaded project and builds the stored\n * check report with the project's load diagnostics. `definitions` adds\n * inventory entries a caller checked itself. Experimental while code-first\n * projects are introduced.\n */\nexport async function checkProjectDefinitions<\n TInput extends DefinitionCheckInput = DefinitionCheckInput,\n>(\n project: LoadedDefinitionProject & TInput,\n options: {\n readonly checks?: readonly DefinitionCheck<TInput>[];\n readonly definitions?: DefinitionCheckReport[\"definitions\"];\n } = {},\n): Promise<DefinitionCheckReport> {\n const relocations = project.relocations ?? new Map();\n const diagnostics = [...project.diagnostics];\n for (const check of options.checks ?? documentModelChecks) {\n for (const diagnostic of await check.run(project)) {\n diagnostics.push(relocated(diagnostic, relocations));\n }\n }\n return definitionCheckReport({\n sourceSet: project.sourceSet,\n ...(project.skipReason !== undefined && {\n skipReason: project.skipReason,\n }),\n artifacts: project.artifacts,\n definitions: options.definitions ?? [],\n diagnostics,\n });\n}\n","import { defineDiagnosticCatalog } from \"../../kernel/diagnostics.js\";\nimport { toolingDiagnostics } from \"../diagnostic-codes.js\";\n\nexport const inspectDiagnostics = defineDiagnosticCatalog(\n {\n \"PH-INSPECT-SELECTION-UNKNOWN\": {\n severity: \"error\",\n // A mistyped selection is a usage error, not a defect of the package.\n phase: \"configuration\",\n meaning:\n \"The selected document type and version is not served by any model of the package\",\n },\n },\n toolingDiagnostics,\n);\n","import type {\n DefinitionDiagnostic,\n Sha256Digest,\n} from \"@powerhousedao/shared/document-model\";\nimport type { NormalizedDocumentModelArtifact } from \"../adapters/types.js\";\nimport { servedSpecification } from \"../report/served-specification.js\";\nimport {\n compareArtifacts,\n definitionStatus,\n sortedUniqueDiagnostics,\n} from \"../report/status.js\";\nimport { logicalCollisionDiagnostics } from \"../report/logical-collisions.js\";\nimport type { LoadedDefinitionProject } from \"../report/types.js\";\nimport { inspectDiagnostics } from \"./diagnostic-codes.js\";\nimport type {\n DefinitionInspectionReport,\n DefinitionInspectionSelection,\n DocumentModelFamilyInspection,\n DocumentModelInspection,\n} from \"./types.js\";\n\n/** Keeps the capped `expected` text from cutting a key in half. */\nconst MAX_LISTED = 20;\n\nfunction inspection(\n artifact: NormalizedDocumentModelArtifact,\n): DocumentModelInspection | undefined {\n const served = servedSpecification(artifact);\n if (served === undefined) return undefined;\n const { specification } = served;\n return {\n version: artifact.version,\n source: artifact.source,\n scopes: {\n global: specification.state.global.root.name,\n local: specification.state.local.root?.name ?? null,\n },\n modules: specification.modules.map((module) => ({\n key: module.key,\n name: module.name,\n operations: module.operations.map((operation) => ({\n key: operation.key,\n name: operation.name,\n actionType: operation.actionType,\n scope: operation.scope,\n input: operation.input?.name ?? null,\n errors: operation.errors.map(({ key, code }) => ({ key, code })),\n })),\n })),\n scalars: specification.scalars.map(({ name, implementation }) => ({\n name,\n implementation,\n })),\n types: specification.types.map(({ name }) => name),\n };\n}\n\n/** Artifacts that carry one definition, and so one digest, form one family. */\nfunction families(\n artifacts: readonly NormalizedDocumentModelArtifact[],\n): readonly DocumentModelFamilyInspection[] {\n const grouped = new Map<\n Sha256Digest,\n {\n readonly first: NormalizedDocumentModelArtifact;\n readonly versions: DocumentModelInspection[];\n }\n >();\n for (const artifact of artifacts) {\n const version = inspection(artifact);\n if (version === undefined) continue;\n const family = grouped.get(artifact.digest);\n if (family === undefined) {\n grouped.set(artifact.digest, { first: artifact, versions: [version] });\n } else {\n family.versions.push(version);\n }\n }\n return [...grouped.values()].map(({ first, versions }) => ({\n documentType: first.documentType,\n name: first.definition.model.name,\n extension: first.definition.model.extension,\n digest: first.digest,\n compatibility: first.definition.compatibility,\n versions,\n }));\n}\n\nfunction unknownSelection(\n selection: DefinitionInspectionSelection,\n artifacts: readonly NormalizedDocumentModelArtifact[],\n): DefinitionDiagnostic {\n const available = [\n ...new Set(\n artifacts.map(\n ({ documentType, version }) => `${documentType}@${version}`,\n ),\n ),\n ];\n const listed =\n available.length <= MAX_LISTED\n ? available.join(\", \")\n : `${available.slice(0, MAX_LISTED).join(\", \")}, and ${available.length - MAX_LISTED} more`;\n const selected = `${selection.documentType}@${selection.version}`;\n return inspectDiagnostics.create({\n code: \"PH-INSPECT-SELECTION-UNKNOWN\",\n path: [\"selection\"],\n message: `No model of this package serves ${selected}.`,\n expected: available.length === 0 ? \"a package with a model\" : listed,\n received: selected,\n repair:\n available.length === 0\n ? \"Add a document model to the package, or register its code-first source in definitionSources.\"\n : `Inspect one of: ${listed}.`,\n });\n}\n\n/**\n * @experimental Describes the loaded models without running checks. With a\n * selection it answers for that model only, and adds its full definition\n * when exactly one model serves it. Experimental while code-first projects\n * are introduced.\n */\nexport function inspectProjectDefinitions(\n project: LoadedDefinitionProject,\n options: { readonly selection?: DefinitionInspectionSelection } = {},\n): DefinitionInspectionReport {\n const artifacts = [...project.artifacts].sort(compareArtifacts);\n const { selection } = options;\n const selected =\n selection === undefined\n ? artifacts\n : artifacts.filter(\n ({ documentType, version }) =>\n documentType === selection.documentType &&\n version === selection.version,\n );\n const diagnostics = sortedUniqueDiagnostics([\n ...project.diagnostics,\n ...(selection === undefined\n ? []\n : selected.length === 0\n ? [unknownSelection(selection, artifacts)]\n : logicalCollisionDiagnostics(project.sourceSet, selected)),\n ]);\n return {\n kind: \"powerhouse.definition-inspection\",\n formatVersion: 1,\n status: definitionStatus({\n ...(project.skipReason !== undefined && {\n skipReason: project.skipReason,\n }),\n definitions: artifacts,\n diagnostics,\n }),\n sourceSet: project.sourceSet,\n families: families(selected),\n diagnostics,\n ...(selection !== undefined &&\n selected.length === 1 && { definition: selected[0].definition }),\n };\n}\n","import type {\n DefinitionDiagnostic,\n Sha256Digest,\n} from \"@powerhousedao/shared/document-model\";\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport {\n isScalarDefinition,\n type ScalarDefinition,\n} from \"../../../scalars/types.js\";\nimport { compareCodeUnits } from \"../../kernel/primitives.js\";\nimport type { DefinitionSourceLoader } from \"../definition-source-loader.js\";\n\n/** Where codegen reads a package's `defineScalar` exports from. */\nconst PROJECT_SCALARS_SPECIFIER = \"./scalars/index.ts\";\n\n/** The scalars `scalars/index.ts` exports, imported like the selected sources. */\nexport async function loadProjectScalars(request: {\n readonly loader: DefinitionSourceLoader;\n readonly packageRoot: string;\n readonly configFile: string;\n readonly packageRevision: Sha256Digest;\n readonly signal?: AbortSignal;\n}): Promise<{\n readonly definitions: readonly ScalarDefinition[];\n readonly diagnostics: readonly DefinitionDiagnostic[];\n}> {\n const { loader, packageRoot, configFile, packageRevision, signal } = request;\n if (!existsSync(join(packageRoot, \"scalars\", \"index.ts\"))) {\n return { definitions: [], diagnostics: [] };\n }\n const imported = await loader.importPackageModule({\n configFile,\n packageRevision,\n ...(signal !== undefined && { signal }),\n specifier: PROJECT_SCALARS_SPECIFIER,\n });\n if (!imported.ok) {\n return { definitions: [], diagnostics: imported.diagnostics };\n }\n // Codegen emits `import { <name> } from \"scalars\"`, so only an export bound\n // under the scalar's own name makes it available.\n const definitions = Object.entries(imported.namespace)\n .flatMap(([exportName, value]) =>\n isScalarDefinition(value) && value.name === exportName ? [value] : [],\n )\n .sort((left, right) => compareCodeUnits(left.name, right.name));\n return { definitions, diagnostics: [] };\n}\n","import type {\n DocumentScalarReferenceDefinition,\n InputTypeDefinition,\n NamedGraphQLTypeDefinition,\n PowerhouseScalarName,\n StoredScalarDefinition,\n TypeReferenceDefinition,\n} from \"@powerhousedao/shared/document-model\";\nimport { documentModelScalars } from \"../../scalars/catalog.js\";\nimport type { ScalarDefinition } from \"../../scalars/types.js\";\nimport { compareCodeUnits } from \"../kernel/primitives.js\";\n\nfunction storedScalarDefinition(\n definition: ScalarDefinition,\n): StoredScalarDefinition {\n return {\n kind: \"powerhouse.scalar\",\n formatVersion: 1,\n name: definition.name,\n representation: definition.representation ?? \"json\",\n description: definition.description ?? \"\",\n coercion: {\n source: definition.coercion === undefined ? \"derived\" : \"explicit\",\n },\n coercionProfile: \"catalog-v1\",\n };\n}\n\nexport function scalarReferences(\n catalogScalars: ReadonlySet<string>,\n packageScalars: ReadonlyMap<string, ScalarDefinition>,\n): readonly DocumentScalarReferenceDefinition[] {\n const catalog = documentModelScalars\n .map(({ name }) => name as PowerhouseScalarName)\n .filter((name) => catalogScalars.has(name))\n .map(\n (name) =>\n ({\n name,\n implementation: `powerhouse.catalog#${name}`,\n coercionProfile: \"catalog-v1\",\n }) as DocumentScalarReferenceDefinition,\n );\n const declared = [...packageScalars]\n .sort(([left], [right]) => compareCodeUnits(left, right))\n .map(([name, definition]): DocumentScalarReferenceDefinition => ({\n name,\n implementation: `package#${name}`,\n coercionProfile: \"catalog-v1\",\n definition: storedScalarDefinition(definition),\n }));\n return [...catalog, ...declared];\n}\n\n// The host builds its schema from state SDL and drops scalar declarations from\n// operation SDL, so a scalar only local state or an operation input uses is\n// declared in the global segment too.\nexport function declareProjectScalars(\n segment: string,\n packageScalars: ReadonlyMap<string, ScalarDefinition>,\n): string {\n return [\n ...[...packageScalars.keys()]\n .sort(compareCodeUnits)\n .map((name) => `scalar ${name}`),\n segment,\n ].join(\"\\n\\n\");\n}\n\nfunction namedTypeOf(type: TypeReferenceDefinition): string {\n return type.kind === \"list\" ? namedTypeOf(type.item) : type.name;\n}\n\nexport function inputReachesProjectScalar(\n input: InputTypeDefinition,\n types: readonly NamedGraphQLTypeDefinition[],\n packageScalars: ReadonlyMap<string, ScalarDefinition>,\n): boolean {\n const visited = new Set<string>();\n const reaches = (candidate: InputTypeDefinition): boolean => {\n if (visited.has(candidate.name)) return false;\n visited.add(candidate.name);\n return candidate.fields.some((field) => {\n const name = namedTypeOf(field.type);\n if (packageScalars.has(name)) return true;\n const target = types.find((type) => type.name === name);\n return target?.kind === \"input\" && reaches(target);\n });\n };\n return reaches(input);\n}\n","import { DocumentModelGlobalStateSchema } from \"@powerhousedao/shared/document-model\";\nimport type {\n CompiledErrorDefinition,\n DefinitionExample,\n DefinitionPath,\n DefinitionSource,\n DocumentModelDefinition,\n DocumentModelGlobalState,\n DocumentModelModuleDefinition,\n DocumentModelOperationDefinition,\n DocumentModelPHState,\n DocumentModelSpecificationDefinition,\n DocumentSpecification,\n InputTypeDefinition,\n JsonValue,\n NamedGraphQLTypeDefinition,\n OperationSpecification,\n StateDefinition,\n} from \"@powerhousedao/shared/document-model\";\nimport { scalarCatalog } from \"../../../scalars/catalog.js\";\nimport type { ScalarDefinition } from \"../../../scalars/types.js\";\nimport { scalarReferences } from \"../../compiler/stored-scalar.js\";\nimport {\n deriveDocumentModelNames,\n deriveDocumentModelSymbolNames,\n} from \"../../compiler/naming.js\";\nimport { checkDocumentModelDefinitionShape } from \"../../compiler/wire-shape.js\";\nimport {\n rejectionReceived,\n snapshotRecord,\n snapshotDataRecord,\n} from \"../../kernel/data-properties.js\";\nimport { DefinitionDiagnosticCollector } from \"../../kernel/diagnostic-collector.js\";\nimport { describeReceived } from \"../../kernel/diagnostics.js\";\nimport {\n canonicalDigest,\n EMPTY_INPUT_FIELD_NAME,\n} from \"../../kernel/primitives.js\";\nimport type { NormalizedDocumentModelResult } from \"../adapters/types.js\";\nimport {\n type ToolingDiagnosticCode,\n toolingDiagnostics,\n} from \"../diagnostic-codes.js\";\nimport {\n declaredTypeNames,\n type GraphQLDefinitionNode,\n referencedTypeNames,\n structuredTypes,\n} from \"../graphql/ast-to-structured.js\";\nimport { parseSchema } from \"../graphql/parse-schema.js\";\n\ntype Collector = DefinitionDiagnosticCollector<ToolingDiagnosticCode>;\n\n/** @experimental Options for {@link adaptSchemaFirstDocumentModelModule}. */\nexport type SchemaFirstAdapterOptions = {\n readonly version?: number;\n\n readonly scalars?: readonly ScalarDefinition[];\n};\n\nconst EXAMPLE_KEY_PREFIX = \"schema-first-id:\";\n\nfunction producesRuntimeSymbol(name: unknown): name is string {\n if (typeof name !== \"string\" || name.trim() === \"\") return false;\n const { typeName, memberName, constantName } =\n deriveDocumentModelSymbolNames(name);\n return typeName !== \"\" && memberName !== \"\" && constantName !== \"\";\n}\n\nfunction blocked(\n collector: Collector,\n kind: \"module\" | \"operation\" | \"error\",\n value: unknown,\n path: DefinitionPath,\n): undefined {\n const received =\n typeof value === \"string\" ? JSON.stringify(value) : String(value);\n collector.add({\n code: \"PH-DM-DECLARATION-INVALID\",\n path,\n message: `The stored ${kind} name ${received} never produced a runtime symbol, so there is no generated ${kind} to describe.`,\n expected: \"a name with at least one letter or digit\",\n received,\n repair: `Name the ${kind} in the document model editor and generate again.`,\n });\n return undefined;\n}\n\nfunction examples(\n stored: readonly { readonly id: string; readonly value: string }[],\n): readonly DefinitionExample[] {\n return stored.map(({ id, value }) => ({\n id,\n key: `${EXAMPLE_KEY_PREFIX}${id}`,\n value,\n }));\n}\n\nfunction parseInitialValue(\n collector: Collector,\n stored: string,\n path: DefinitionPath,\n emptyIsObject: boolean,\n): JsonValue | undefined {\n if (emptyIsObject && stored.trim() === \"\") return {};\n let parsed: unknown;\n try {\n parsed = JSON.parse(stored);\n } catch {\n parsed = undefined;\n }\n if (parsed !== null && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n return parsed as JsonValue;\n }\n collector.add({\n code: \"PH-DM-INITIAL-VALUE-INVALID\",\n path,\n message:\n \"The stored initial value does not parse to a JSON object, so it cannot be the value its state root holds.\",\n expected: \"a JSON object, encoded once\",\n received: stored,\n repair: \"Store the scope's initial value as a JSON object.\",\n });\n return undefined;\n}\n\nfunction emptyInputProjection(input: InputTypeDefinition): InputTypeDefinition {\n const [only] = input.fields;\n const empty =\n input.fields.length === 1 &&\n only.name === EMPTY_INPUT_FIELD_NAME &&\n only.type.kind === \"scalar\" &&\n only.type.name === \"Boolean\" &&\n !only.type.required;\n return empty ? { ...input, fields: [] } : input;\n}\n\nfunction modelScalarReferences(\n definitions: readonly GraphQLDefinitionNode[],\n scalars: readonly ScalarDefinition[],\n): DocumentModelSpecificationDefinition[\"scalars\"] {\n const used = new Set(referencedTypeNames(definitions));\n return scalarReferences(\n used,\n new Map(\n scalars\n .filter(({ name }) => used.has(name))\n .map((definition) => [definition.name, definition]),\n ),\n );\n}\n\nfunction normalizeOperation(\n collector: Collector,\n operation: OperationSpecification,\n typesByName: ReadonlyMap<string, NamedGraphQLTypeDefinition>,\n path: DefinitionPath,\n): DocumentModelOperationDefinition | undefined {\n if (!producesRuntimeSymbol(operation.name)) {\n return blocked(collector, \"operation\", operation.name, [...path, \"name\"]);\n }\n if (operation.scope !== \"global\" && operation.scope !== \"local\") {\n collector.add({\n code: \"PH-DM-SCOPE-UNSUPPORTED\",\n path: [...path, \"scope\"],\n message: `Operation ${JSON.stringify(operation.name)} is stored in scope ${JSON.stringify(operation.scope)}, which a V1 definition cannot record.`,\n expected: \"global | local\",\n received: String(operation.scope),\n repair: \"Store the operation in the global or local scope.\",\n });\n return undefined;\n }\n const names = deriveDocumentModelSymbolNames(operation.name);\n const inputName = `${names.typeName}Input`;\n const hasSchema = operation.schema !== null && operation.schema.trim() !== \"\";\n const declared = hasSchema ? typesByName.get(inputName) : undefined;\n if (hasSchema && declared?.kind !== \"input\") {\n collector.add({\n code: \"PH-DM-DECLARATION-INVALID\",\n path: [...path, \"schema\"],\n message: `The stored schema of operation ${JSON.stringify(operation.name)} declares no input type ${inputName}, which codegen and the host read its input from.`,\n expected: `input ${inputName} { ... }`,\n received: declared === undefined ? \"absent\" : declared.kind,\n repair: `Declare input ${inputName} in the operation's schema.`,\n });\n return undefined;\n }\n const errors = operation.errors.map(\n (error, index): CompiledErrorDefinition | undefined =>\n producesRuntimeSymbol(error.name)\n ? {\n id: error.id,\n key: deriveDocumentModelSymbolNames(error.name).typeName,\n code: error.code,\n name: error.name,\n description: error.description,\n template: error.template,\n }\n : blocked(collector, \"error\", error.name, [\n ...path,\n \"errors\",\n index,\n \"name\",\n ]),\n );\n if (errors.includes(undefined)) return undefined;\n return {\n id: operation.id,\n key: names.memberName,\n name: operation.name,\n description: operation.description,\n actionType: names.constantName,\n creatorKey: names.memberName,\n scope: operation.scope,\n input: declared?.kind === \"input\" ? emptyInputProjection(declared) : null,\n errors: errors as readonly CompiledErrorDefinition[],\n examples: examples(operation.examples),\n template: operation.template,\n reducer: operation.reducer,\n };\n}\n\nfunction rootState(\n collector: Collector,\n stored: DocumentSpecification[\"state\"][\"global\"],\n root: string | null,\n path: DefinitionPath,\n scope: \"global\" | \"local\",\n): StateDefinition | undefined {\n const initialValue = parseInitialValue(\n collector,\n stored.initialValue,\n [...path, \"initialValue\"],\n scope === \"local\",\n );\n if (initialValue === undefined) return undefined;\n const materialized = {\n initialValue: stored.initialValue,\n examples: stored.examples.map(({ id, value }) => ({ id, value })),\n };\n return root === null\n ? {\n root: null,\n initialValue: {},\n examples: examples(stored.examples),\n unknownKeys: \"preserve\",\n materialized: { ...materialized, schema: \"\" },\n }\n : {\n root: { kind: \"named\", name: root, required: true },\n initialValue,\n examples: examples(stored.examples),\n unknownKeys: \"preserve\",\n materialized: { ...materialized, schema: stored.schema },\n };\n}\n\nconst BUILT_IN_SCALARS: ReadonlySet<string> = new Set([\n \"ID\",\n \"String\",\n \"Boolean\",\n \"Int\",\n \"Float\",\n]);\n\nconst CATALOG_SCALARS: ReadonlySet<string> = new Set(\n scalarCatalog.map(({ name }) => name),\n);\n\n/**\n * Codegen imports every scalar a stored schema declares or uses from\n * scalars/index.ts unless it is built in or in the catalog. A missing export\n * would otherwise surface later as an error that never names it.\n */\nfunction knownScalars(\n collector: Collector,\n segments: readonly {\n readonly path: DefinitionPath;\n readonly definitions: readonly GraphQLDefinitionNode[];\n }[],\n declared: ReadonlySet<string>,\n scalars: readonly ScalarDefinition[],\n): boolean {\n const project = new Set(scalars.map(({ name }) => name));\n const reported = new Set<string>();\n for (const segment of segments) {\n const names = [\n ...referencedTypeNames(segment.definitions)\n .filter((name) => !declared.has(name))\n .map((name) => ({ name, verb: \"uses\" })),\n ...segment.definitions.flatMap((node) =>\n node.kind === \"ScalarTypeDefinition\"\n ? [{ name: node.name.value, verb: \"declares\" }]\n : [],\n ),\n ];\n for (const { name, verb } of names) {\n if (\n BUILT_IN_SCALARS.has(name) ||\n CATALOG_SCALARS.has(name) ||\n project.has(name) ||\n reported.has(name)\n ) {\n continue;\n }\n reported.add(name);\n collector.add({\n code: \"PH-DM-DECLARATION-INVALID\",\n path: segment.path,\n message: `The stored schema ${verb} scalar ${name}, which is not a GraphQL built-in, a catalog scalar, or a project scalar exported from scalars/index.ts.`,\n expected: \"a scalar defined with defineScalar in scalars/index.ts\",\n received: name,\n repair: `Export ${name} from scalars/index.ts with defineScalar, or use a catalog scalar.`,\n });\n }\n }\n return reported.size === 0;\n}\n\n/** A specification's stored SDL strings, in the order its retained document concatenates them. */\nexport function storedSchemaSegments(\n specification: DocumentSpecification,\n path: DefinitionPath,\n): readonly { readonly schema: string; readonly path: DefinitionPath }[] {\n return [\n {\n schema: specification.state.global.schema,\n path: [...path, \"state\", \"global\", \"schema\"],\n },\n {\n schema: specification.state.local.schema,\n path: [...path, \"state\", \"local\", \"schema\"],\n },\n ...specification.modules.flatMap((module, moduleIndex) =>\n module.operations.map((operation, operationIndex) => ({\n schema: operation.schema ?? \"\",\n path: [\n ...path,\n \"modules\",\n moduleIndex,\n \"operations\",\n operationIndex,\n \"schema\",\n ],\n })),\n ),\n ];\n}\n\nfunction normalizeSpecification(\n collector: Collector,\n specification: DocumentSpecification,\n roots: { readonly global: string; readonly local: string },\n path: DefinitionPath,\n scalars: readonly ScalarDefinition[],\n): DocumentModelSpecificationDefinition | undefined {\n const segments = storedSchemaSegments(specification, path);\n const parsedSegments: {\n readonly path: DefinitionPath;\n readonly definitions: readonly GraphQLDefinitionNode[];\n }[] = [];\n for (const segment of segments) {\n const parsed = parseSchema(segment.schema);\n if (!parsed.ok) {\n collector.add({\n code: \"PH-DM-DECLARATION-INVALID\",\n path: segment.path,\n message: `The stored schema is not GraphQL SDL: ${parsed.message}`,\n expected: \"GraphQL SDL\",\n received: segment.schema,\n repair: \"Fix the schema in the document model editor.\",\n });\n return undefined;\n }\n parsedSegments.push({\n path: segment.path,\n definitions: parsed.document.definitions,\n });\n }\n const definitions = parsedSegments.flatMap((segment) => segment.definitions);\n const declared = declaredTypeNames(definitions);\n if (!knownScalars(collector, parsedSegments, declared, scalars)) {\n return undefined;\n }\n const allTypes = structuredTypes(definitions, declared);\n const typesByName: ReadonlyMap<string, NamedGraphQLTypeDefinition> = new Map(\n allTypes.map((type) => [type.name, type]),\n );\n\n const hasLocalRoot = specification.state.local.schema.trim() !== \"\";\n for (const scope of [\"global\", \"local\"] as const) {\n if (scope === \"local\" && !hasLocalRoot) continue;\n if (typesByName.get(roots[scope])?.kind !== \"object\") {\n collector.add({\n code: \"PH-DM-STATE-ROOT-INVALID\",\n path: [...path, \"state\", scope, \"schema\"],\n message: `The stored ${scope} state schema declares no object type named ${roots[scope]}.`,\n expected: `type ${roots[scope]} { ... }`,\n received: [...typesByName.keys()].join(\", \"),\n repair: `Name the ${scope} state root after the model; every consumer resolves it by that name.`,\n });\n return undefined;\n }\n }\n\n const modules: DocumentModelModuleDefinition[] = [];\n for (const [moduleIndex, module] of specification.modules.entries()) {\n const modulePath = [...path, \"modules\", moduleIndex];\n if (!producesRuntimeSymbol(module.name)) {\n return blocked(collector, \"module\", module.name, [...modulePath, \"name\"]);\n }\n const operations = module.operations.map((operation, operationIndex) =>\n normalizeOperation(collector, operation, typesByName, [\n ...modulePath,\n \"operations\",\n operationIndex,\n ]),\n );\n if (operations.includes(undefined)) return undefined;\n modules.push({\n id: module.id,\n key: deriveDocumentModelSymbolNames(module.name).memberName,\n name: module.name,\n description: module.description,\n operations: operations as readonly DocumentModelOperationDefinition[],\n });\n }\n\n const global = rootState(\n collector,\n specification.state.global,\n roots.global,\n [...path, \"state\", \"global\"],\n \"global\",\n );\n const local = rootState(\n collector,\n specification.state.local,\n hasLocalRoot ? roots.local : null,\n [...path, \"state\", \"local\"],\n \"local\",\n );\n if (global === undefined || global.root === null || local === undefined) {\n return undefined;\n }\n\n const inputs = new Set(\n modules.flatMap((module) =>\n module.operations.flatMap((operation) =>\n operation.input === null ? [] : [operation.input.name],\n ),\n ),\n );\n return {\n version: specification.version,\n scalars: modelScalarReferences(definitions, scalars),\n graphQLCompatibility: {\n kind: \"graphql-ast-v1\",\n document: { kind: \"Document\", definitions },\n preserveDefinitionOrder: true,\n },\n types: allTypes.filter((type) => !inputs.has(type.name)),\n state: { global, local },\n modules,\n changeLog: [...specification.changeLog],\n };\n}\n\ntype StoredModel = {\n readonly global: DocumentModelGlobalState;\n readonly documentModel: DocumentModelPHState;\n readonly version: number;\n};\n\nfunction storedModel(\n collector: Collector,\n value: unknown,\n options: SchemaFirstAdapterOptions,\n): StoredModel | undefined {\n const root = snapshotRecord(value, undefined, []);\n const module =\n root.ok && root.value.documentModel !== undefined ? root.value : undefined;\n const documentModel = module === undefined ? value : module.documentModel;\n const path = module === undefined ? [] : [\"documentModel\"];\n const state = snapshotRecord(documentModel, undefined, path);\n const global = state.ok\n ? snapshotDataRecord(state.value.global, undefined, [...path, \"global\"])\n : state;\n if (!global.ok) {\n collector.add({\n code: \"PH-DM-DECLARATION-INVALID\",\n path: global.path,\n message: `This export is neither a generated document-model module nor its stored state (${global.reason}).`,\n expected: \"a module with documentModel.global, or a DocumentModelPHState\",\n received: rejectionReceived(global),\n repair: \"Pass the module ph generate produced, or its documentModel.\",\n });\n return undefined;\n }\n const parsed = DocumentModelGlobalStateSchema().safeParse(global.value);\n if (!parsed.success) {\n for (const issue of parsed.error.issues) {\n collector.add({\n code: \"PH-DM-DECLARATION-INVALID\",\n path: [\n ...path,\n \"global\",\n ...issue.path.map((segment) =>\n typeof segment === \"symbol\" ? String(segment) : segment,\n ),\n ],\n message: issue.message,\n expected: \"a stored document model matching DocumentModelGlobalState\",\n received: \"a malformed stored model\",\n repair:\n \"Pass the module ph generate produced, or its stored documentModel.\",\n });\n }\n return undefined;\n }\n const declared: unknown = options.version ?? module?.version ?? 1;\n if (\n typeof declared !== \"number\" ||\n !Number.isSafeInteger(declared) ||\n declared <= 0\n ) {\n collector.add({\n code: \"PH-DM-DECLARATION-INVALID\",\n path: [\"version\"],\n message: \"A module's registry version is a positive safe integer.\",\n expected: \"a positive safe integer\",\n received:\n typeof declared === \"number\"\n ? String(declared)\n : describeReceived(declared),\n repair: \"Pass the version this module registers.\",\n });\n return undefined;\n }\n return {\n global: parsed.data,\n documentModel: documentModel as DocumentModelPHState,\n version: declared,\n };\n}\n\n/**\n * @experimental Normalizes one generated schema-first module, or one stored\n * `DocumentModelPHState`, into the V1 wire shape. A model it cannot\n * normalize is reported in `diagnostics`; the stored members it trusts are\n * the ones `ph generate` writes. Experimental: it exists so code-first and\n * schema-first models can be read through one shape while code-first\n * projects are introduced.\n */\nexport function adaptSchemaFirstDocumentModelModule(\n value: unknown,\n source: DefinitionSource,\n options: SchemaFirstAdapterOptions = {},\n): NormalizedDocumentModelResult {\n const probe: Collector = new DefinitionDiagnosticCollector(\n toolingDiagnostics,\n );\n const stored = storedModel(probe, value, options);\n if (stored === undefined) {\n return {\n artifacts: [],\n upgradeManifest: null,\n diagnostics: probe.diagnostics,\n };\n }\n const { global, version } = stored;\n const collector: Collector = new DefinitionDiagnosticCollector(\n toolingDiagnostics,\n { kind: \"document-model\", key: global.id, version },\n );\n const failed = (): NormalizedDocumentModelResult => ({\n artifacts: [],\n upgradeManifest: null,\n diagnostics: collector.diagnostics,\n });\n const names = deriveDocumentModelNames({ id: global.id, name: global.name });\n const specifications = global.specifications.map((specification, index) =>\n normalizeSpecification(\n collector,\n specification,\n { global: names.globalStateRootName, local: names.localStateRootName },\n [\"specifications\", index],\n options.scalars ?? [],\n ),\n );\n if (specifications.includes(undefined)) return failed();\n\n const definition: DocumentModelDefinition = {\n kind: \"powerhouse.document-model\",\n formatVersion: 1,\n compatibility: {\n identity: \"explicit-schema-first\",\n scalarCoercion: \"catalog-v1\",\n serialization: \"explicit-schema-first\",\n },\n model: {\n documentType: global.id,\n graphQLName: names.graphQLName,\n name: global.name,\n description: global.description,\n extension: global.extension,\n author: { name: global.author.name, website: global.author.website },\n },\n specifications: specifications as DocumentModelSpecificationDefinition[],\n };\n const shape = checkDocumentModelDefinitionShape(definition);\n collector.merge(shape);\n if (shape.length > 0) return failed();\n if (!definition.specifications.some((entry) => entry.version === version)) {\n collector.add({\n code: \"PH-DM-DECLARATION-INVALID\",\n path: [\"specifications\"],\n message: `The stored history carries no version ${version}, which is the version this module serves.`,\n expected: `a specification for version ${version}`,\n received: definition.specifications\n .map((entry) => String(entry.version))\n .join(\", \"),\n repair:\n \"Pass the version this module registers, or the module that serves a stored version.\",\n });\n return failed();\n }\n return {\n artifacts: [\n {\n kind: \"powerhouse.document-model-artifact\",\n source,\n documentType: global.id,\n version,\n definition,\n digest: canonicalDigest(definition),\n documentModel: stored.documentModel,\n },\n ],\n upgradeManifest: null,\n diagnostics: collector.diagnostics,\n };\n}\n","import type {\n DefinitionPath,\n DocumentSpecification,\n} from \"@powerhousedao/shared/document-model\";\nimport type { DefinitionRelocation } from \"../adapters/producer.js\";\nimport type { NormalizedDocumentModelArtifact } from \"../adapters/types.js\";\nimport { parseSchema } from \"../graphql/parse-schema.js\";\nimport { storedSchemaSegments } from \"./schema-first-document-model-module-adapter.js\";\n\ntype SegmentDeclarations = {\n /** The segment of each node of the retained document, in document order. */\n readonly nodes: readonly DefinitionPath[];\n /** The first segment that defines each type, else the first that extends it. */\n readonly types: ReadonlyMap<string, DefinitionPath>;\n};\n\nfunction segmentDeclarations(\n specification: DocumentSpecification,\n path: DefinitionPath,\n): SegmentDeclarations {\n const nodes: DefinitionPath[] = [];\n const defined = new Map<string, DefinitionPath>();\n const extended = new Map<string, DefinitionPath>();\n for (const segment of storedSchemaSegments(specification, path)) {\n // The adapter produced an artifact, so every segment parsed.\n const parsed = parseSchema(segment.schema);\n if (!parsed.ok) continue;\n for (const node of parsed.document.definitions) {\n nodes.push(segment.path);\n const name = \"name\" in node ? node.name.value : undefined;\n if (name === undefined) continue;\n const first = node.kind.endsWith(\"Extension\") ? extended : defined;\n if (!first.has(name)) first.set(name, segment.path);\n }\n }\n return { nodes, types: new Map([...extended, ...defined]) };\n}\n\n/**\n * A schema-first author edits the stored file, which is the served global\n * state, and declares types in its SDL segments rather than as structured\n * types. Served paths lose their `documentModel/global` prefix; a type, a\n * scalar or a retained document node points at the segment that declares it.\n * Every result is cut back to the deepest member the stored file has, so no\n * location names a normalized-only member or reaches inside an SDL string.\n */\nexport function storedModelRelocation(\n artifact: NormalizedDocumentModelArtifact,\n): DefinitionRelocation {\n const stored = artifact.documentModel.global.specifications;\n const declarations = new Map<number, SegmentDeclarations>();\n const declared = (index: number): SegmentDeclarations => {\n let found = declarations.get(index);\n if (found === undefined) {\n found = segmentDeclarations(stored[index], [\"specifications\", index]);\n declarations.set(index, found);\n }\n return found;\n };\n const relocate = (path: DefinitionPath): DefinitionPath => {\n if (path[0] === \"documentModel\" && path[1] === \"global\") {\n return path.slice(2);\n }\n const [root, index, member, ...rest] = path;\n if (\n root !== \"specifications\" ||\n typeof index !== \"number\" ||\n stored.at(index) === undefined\n ) {\n return path;\n }\n const specification: DefinitionPath = [\"specifications\", index];\n if (member === \"types\") {\n const name =\n typeof rest[0] === \"number\"\n ? artifact.definition.specifications.at(index)?.types.at(rest[0])\n ?.name\n : undefined;\n return (\n (name === undefined ? undefined : declared(index).types.get(name)) ??\n specification\n );\n }\n if (member === \"scalars\") {\n const name =\n typeof rest[0] === \"number\"\n ? artifact.definition.specifications.at(index)?.scalars.at(rest[0])\n ?.name\n : undefined;\n return (\n (name === undefined ? undefined : declared(index).types.get(name)) ??\n specification\n );\n }\n if (member === \"graphQLCompatibility\") {\n const [document, definitions, node] = rest;\n return (\n (document === \"document\" &&\n definitions === \"definitions\" &&\n typeof node === \"number\"\n ? declared(index).nodes.at(node)\n : undefined) ?? specification\n );\n }\n return path;\n };\n return (path) => storedPrefix(artifact.documentModel.global, relocate(path));\n}\n\nfunction storedPrefix(stored: unknown, path: DefinitionPath): DefinitionPath {\n let value = stored;\n let depth = 0;\n for (const segment of path) {\n if (typeof value !== \"object\" || value === null) break;\n if (!Object.hasOwn(value, segment)) break;\n value = (value as Readonly<Record<string | number, unknown>>)[segment];\n depth += 1;\n }\n return path.slice(0, depth);\n}\n","import {\n defaultBaseState,\n type DefinitionDiagnostic,\n type DefinitionSource,\n} from \"@powerhousedao/shared/document-model\";\nimport { readdirSync, readFileSync, realpathSync, statSync } from \"node:fs\";\nimport { join, relative, sep } from \"node:path\";\nimport type { ScalarDefinition } from \"../../../scalars/types.js\";\nimport { compareCodeUnits } from \"../../kernel/primitives.js\";\nimport type {\n DefinitionProducer,\n DefinitionRelocation,\n ProducedDefinitions,\n} from \"../adapters/producer.js\";\nimport { isWithin } from \"../definition-source-resolution.js\";\nimport { toolingDiagnostics } from \"../diagnostic-codes.js\";\nimport { describeThrown } from \"../structured-diagnostics.js\";\nimport { loadProjectScalars } from \"./project-scalars.js\";\nimport { adaptSchemaFirstDocumentModelModule } from \"./schema-first-document-model-module-adapter.js\";\nimport { storedModelRelocation } from \"./stored-locations.js\";\n\ntype StoredModelFiles = {\n readonly files: readonly string[];\n readonly diagnostics: readonly DefinitionDiagnostic[];\n};\n\nfunction unreadable(\n packageRoot: string,\n path: string,\n what: string,\n error: unknown,\n): DefinitionDiagnostic {\n return toolingDiagnostics.create({\n code: \"PH-IMPORT-FAILED\",\n source: { specifier: packageSpecifier(packageRoot, path) },\n path: [],\n message: `The ${what} could not be read, so the stored models in it are not checked.`,\n expected: `a readable ${what}`,\n received: describeThrown(error),\n repair: \"Fix the permissions of the path.\",\n });\n}\n\nfunction outsidePackage(specifier: `./${string}`): DefinitionDiagnostic {\n return toolingDiagnostics.create({\n code: \"PH-CONFIG-SOURCE-OUTSIDE-PACKAGE\",\n source: { specifier },\n path: [],\n message:\n \"The stored document model resolves through a symlink that leaves the package root, so it is not this package's model.\",\n expected: \"a real path contained by the package root\",\n received: specifier,\n repair:\n \"Replace the symlink with a model file that really lives in this package.\",\n });\n}\n\n/**\n * A missing models directory holds no models; any other read failure is\n * reported. A symlinked model directory or file counts when its real path\n * stays in the package.\n */\nfunction storedModelFiles(\n packageRoot: string,\n documentModelsDir: string,\n): StoredModelFiles {\n let names: string[];\n let packageRootIdentity: string;\n try {\n packageRootIdentity = realpathSync.native(packageRoot);\n names = readdirSync(documentModelsDir).sort(compareCodeUnits);\n } catch (error) {\n return {\n files: [],\n diagnostics:\n (error as NodeJS.ErrnoException).code === \"ENOENT\"\n ? []\n : [\n unreadable(\n packageRoot,\n documentModelsDir,\n \"document models directory\",\n error,\n ),\n ],\n };\n }\n const files: string[] = [];\n const diagnostics: DefinitionDiagnostic[] = [];\n for (const name of names) {\n const directory = join(documentModelsDir, name);\n const file = join(directory, `${name}.json`);\n let real: string;\n try {\n if (\n !statSync(directory, { throwIfNoEntry: false })?.isDirectory() ||\n !statSync(file, { throwIfNoEntry: false })?.isFile()\n ) {\n continue;\n }\n real = realpathSync.native(file);\n } catch (error) {\n diagnostics.push(\n unreadable(packageRoot, directory, \"document model directory\", error),\n );\n continue;\n }\n if (isWithin(packageRootIdentity, real)) files.push(file);\n else diagnostics.push(outsidePackage(packageSpecifier(packageRoot, file)));\n }\n return { files, diagnostics };\n}\n\nfunction packageSpecifier(packageRoot: string, file: string): `./${string}` {\n return `./${relative(packageRoot, file).split(sep).join(\"/\")}`;\n}\n\nfunction storedVersion(value: unknown): number | undefined {\n const specifications = (value as { specifications?: unknown } | null)\n ?.specifications;\n if (!Array.isArray(specifications)) return undefined;\n const version = (specifications.at(-1) as { version?: unknown } | undefined)\n ?.version;\n return typeof version === \"number\" ? version : undefined;\n}\n\nfunction adaptStoredModelFile(\n file: string,\n source: DefinitionSource,\n scalars: readonly ScalarDefinition[],\n): Omit<ProducedDefinitions, \"relocations\"> & {\n readonly relocation?: DefinitionRelocation;\n} {\n let text: string;\n try {\n text = readFileSync(file, \"utf8\");\n } catch (error) {\n return {\n artifacts: [],\n diagnostics: [\n toolingDiagnostics.create({\n code: \"PH-IMPORT-FAILED\",\n source,\n path: [],\n message: \"The stored document model file could not be read.\",\n expected: \"a readable JSON file\",\n received: describeThrown(error),\n repair: \"Fix the file's permissions.\",\n }),\n ],\n };\n }\n let stored: unknown;\n try {\n stored = JSON.parse(text);\n } catch (error) {\n return {\n artifacts: [],\n diagnostics: [\n toolingDiagnostics.create({\n code: \"PH-DM-DECLARATION-INVALID\",\n source,\n path: [],\n message: \"The stored document model is not JSON.\",\n expected: \"the JSON the document model editor saves\",\n received: describeThrown(error),\n repair:\n \"Repair the JSON, or save the model again from the document model editor.\",\n }),\n ],\n };\n }\n const version = storedVersion(stored);\n // Not createState: it fills absent members with defaults, which would hide\n // a malformed file.\n const result = adaptSchemaFirstDocumentModelModule(\n { ...defaultBaseState(), global: stored, local: {} },\n source,\n { scalars, ...(version !== undefined && { version }) },\n );\n const artifact = result.artifacts.at(0);\n return {\n // Every stored version is served, and each carries the whole history.\n artifacts:\n artifact === undefined\n ? []\n : artifact.definition.specifications.map((specification) => ({\n ...artifact,\n version: specification.version,\n })),\n ...(artifact !== undefined && {\n relocation: storedModelRelocation(artifact),\n }),\n // The adapter roots shape errors at the wrapping state's `global`, which\n // is the file itself.\n diagnostics: result.diagnostics.map((diagnostic) => ({\n ...diagnostic,\n source,\n path:\n diagnostic.path[0] === \"global\"\n ? diagnostic.path.slice(1)\n : diagnostic.path,\n })),\n };\n}\n\n/**\n * Normalizes every `<documentModelsDir>/<name>/<name>.json` a schema-first\n * package stores, with the project scalars `scalars/index.ts` exports. A\n * directory or file that cannot be read, or a file that cannot be adapted,\n * is a diagnostic.\n */\nexport const readStoredDocumentModels: DefinitionProducer = async (input) => {\n const { packageRoot, documentModelsDir } = input;\n if (documentModelsDir === undefined) {\n return { artifacts: [], diagnostics: [], relocations: new Map() };\n }\n const { files, diagnostics } = storedModelFiles(\n packageRoot,\n documentModelsDir,\n );\n if (files.length === 0) {\n return { artifacts: [], diagnostics, relocations: new Map() };\n }\n const scalars = await loadProjectScalars(input);\n const relocations = new Map<string, DefinitionRelocation>();\n const results = files.map((file) => {\n const specifier = packageSpecifier(packageRoot, file);\n const result = adaptStoredModelFile(\n file,\n { specifier },\n scalars.definitions,\n );\n if (result.relocation !== undefined) {\n relocations.set(specifier, result.relocation);\n }\n return result;\n });\n return {\n artifacts: results.flatMap((result) => result.artifacts),\n diagnostics: [\n ...diagnostics,\n ...scalars.diagnostics,\n ...results.flatMap((result) => result.diagnostics),\n ],\n relocations,\n };\n};\n","import type { DefinitionSource } from \"@powerhousedao/shared/document-model\";\nimport { readdirSync, readFileSync, realpathSync, statSync } from \"node:fs\";\nimport { join, relative, sep } from \"node:path\";\nimport { compareCodeUnits } from \"../../kernel/primitives.js\";\nimport type { UnregisteredDefinition } from \"../report/types.js\";\nimport { isWithin } from \"../definition-source-resolution.js\";\n\n/**\n * Finds `defineDocumentModel(Family)` calls under the document models\n * directory that no selected source reaches. Declarations are read from\n * source text, never run, so an unregistered model cannot fail the scan by\n * throwing. What a source reaches is the module graph its import evaluated.\n */\n\ntype Unit = UnregisteredDefinition & {\n /** Real paths. */\n readonly declaring: readonly string[];\n};\n\ntype Entry = {\n readonly name: string;\n /** As spelled under the models directory. */\n readonly path: string;\n readonly real: string;\n readonly isDirectory: boolean;\n};\n\nconst DECLARATION = {\n module: /^document-model(?:\\/|$)/,\n factory: \"defineDocumentModel(?:Family)?\",\n} as const;\n\nconst NAMED_IMPORT = /\\bimport\\s*\\{([^}]*)\\}\\s*from\\s*\"#(\\d+)\"/g;\n\nconst NAMESPACE_IMPORT = /\\bimport\\s*\\*\\s*as\\s+([\\w$]+)\\s*from\\s*\"#(\\d+)\"/g;\n\ntype Lexed = { readonly code: string; readonly strings: readonly string[] };\n\nfunction startsRegExp(code: string): boolean {\n const before = code.slice(-64).trimEnd();\n return (\n before === \"\" ||\n /[(,=:[!&|?{};+\\-*%<>~^}]$/.test(before) ||\n /(?:^|[^\\w$])(?:return|typeof|case|do|else|in|of|new|delete|void|throw|yield|await)$/.test(\n before,\n )\n );\n}\n\nfunction readCodeAndStrings(file: string): Lexed {\n let text: string;\n try {\n text = readFileSync(file, \"utf8\");\n } catch {\n return { code: \"\", strings: [] };\n }\n let code = \"\";\n const strings: string[] = [];\n const literal = (contents: string) => {\n code += `\"#${strings.length}\"`;\n strings.push(contents);\n };\n let braces = 0;\n const templates: number[] = [];\n let i = 0;\n const skipQuoted = (end: (index: number) => boolean) => {\n while (i < text.length && !end(i)) i += text[i] === \"\\\\\" ? 2 : 1;\n };\n while (i < text.length) {\n const char = text[i];\n if (char === \"/\" && text[i + 1] === \"/\") {\n i = text.indexOf(\"\\n\", i);\n if (i === -1) i = text.length;\n } else if (char === \"/\" && text[i + 1] === \"*\") {\n const end = text.indexOf(\"*/\", i + 2);\n i = end === -1 ? text.length : end + 2;\n code += \" \";\n } else if (char === \"/\" && startsRegExp(code)) {\n i += 1;\n let inClass = false;\n while (i < text.length && text[i] !== \"\\n\") {\n if (text[i] === \"\\\\\") i += 1;\n else if (text[i] === \"[\") inClass = true;\n else if (text[i] === \"]\") inClass = false;\n else if (text[i] === \"/\" && !inClass) break;\n i += 1;\n }\n i += 1;\n while (/[a-z]/.test(text[i] ?? \"\")) i += 1;\n code += \" \";\n } else if (char === '\"' || char === \"'\") {\n const start = (i += 1);\n skipQuoted((at) => text[at] === char || text[at] === \"\\n\");\n literal(text.slice(start, i));\n i += 1;\n } else if (char === \"`\" || (char === \"}\" && templates.at(-1) === braces)) {\n const whole = char === \"`\";\n if (!whole) templates.pop();\n const start = (i += 1);\n skipQuoted(\n (at) => text[at] === \"`\" || (text[at] === \"$\" && text[at + 1] === \"{\"),\n );\n const closed = text[i] === \"`\";\n literal(whole && closed ? text.slice(start, i) : \"\");\n if (closed) {\n i += 1;\n } else {\n templates.push(braces);\n i += 2;\n }\n } else {\n if (char === \"{\") braces += 1;\n if (char === \"}\") braces -= 1;\n code += char;\n i += 1;\n }\n }\n return { code, strings };\n}\n\n/** `type as e` imports a value named `type`. */\nfunction valueBindings(\n clause: string,\n): { readonly imported: string; readonly local: string }[] {\n return clause\n .split(\",\")\n .map((part) => part.trim())\n .filter((part) => part !== \"\" && !/^type\\s+(?!as\\b)/.test(part))\n .map((part) => {\n const [imported, local = imported] = part.split(/\\s+as\\s+/);\n return { imported, local };\n });\n}\n\nfunction isSourceFile(name: string): boolean {\n return /\\.m?tsx?$/.test(name) && !/\\.d\\.m?ts$/.test(name);\n}\n\nfunction isTestFile(name: string): boolean {\n return /\\.(?:test|spec)\\.m?tsx?$/.test(name);\n}\n\n/**\n * Sorted, with symlinks followed. An entry that cannot be read, or whose real\n * path leaves the package, is not the package's and is skipped.\n */\nfunction packageEntries(path: string, packageRootIdentity: string): Entry[] {\n let names: string[];\n try {\n names = readdirSync(path);\n } catch {\n return [];\n }\n return names\n .filter((name) => name !== \"node_modules\" && !name.startsWith(\".\"))\n .sort(compareCodeUnits)\n .flatMap((name) => {\n const child = join(path, name);\n try {\n const real = realpathSync.native(child);\n if (!isWithin(packageRootIdentity, real)) return [];\n const isDirectory = statSync(real).isDirectory();\n return [{ name, path: child, real, isDirectory }];\n } catch {\n return [];\n }\n });\n}\n\n/** `visited` holds real directories, so a symlink cycle ends. */\nfunction sourceFilesUnder(\n directory: Entry,\n packageRootIdentity: string,\n visited: Set<string>,\n): Entry[] {\n if (visited.has(directory.real)) return [];\n visited.add(directory.real);\n return packageEntries(directory.path, packageRootIdentity).flatMap(\n (entry) => {\n if (entry.isDirectory) {\n return entry.name === \"__tests__\"\n ? []\n : sourceFilesUnder(entry, packageRootIdentity, visited);\n }\n return isSourceFile(entry.name) && !isTestFile(entry.name) ? [entry] : [];\n },\n );\n}\n\nfunction declares(file: string): boolean {\n const { module, factory } = DECLARATION;\n const { code, strings } = readCodeAndStrings(file);\n const isFactory = new RegExp(`^${factory}$`);\n const callees = [\n ...[...code.matchAll(NAMED_IMPORT)]\n .filter(([, , index]) => module.test(strings[Number(index)]))\n .flatMap(([, clause]) =>\n valueBindings(clause)\n .filter(({ imported }) => isFactory.test(imported))\n .map(({ local }) => escapeRegExp(local)),\n ),\n ...[...code.matchAll(NAMESPACE_IMPORT)]\n .filter(([, , index]) => module.test(strings[Number(index)]))\n .map(\n ([, namespace]) => `${escapeRegExp(namespace)}\\\\s*\\\\.\\\\s*${factory}`,\n ),\n ];\n return callees.some((callee) =>\n new RegExp(`(?<![\\\\w$.])${callee}\\\\s*(?:<[^;()]*>\\\\s*)?\\\\(`).test(code),\n );\n}\n\nfunction escapeRegExp(name: string): string {\n return name.replaceAll(\"$\", \"\\\\$\");\n}\n\nfunction packagePath(root: string, path: string): `./${string}` {\n return `./${relative(root, path).split(sep).join(\"/\")}`;\n}\n\nfunction realPathOrSelf(path: string): string {\n try {\n return realpathSync.native(path);\n } catch {\n return path;\n }\n}\n\n/** The suggested specifier is the folder's `index.ts` when it declares, else the first declaring file. */\nfunction modelUnit(\n packageRoot: string,\n packageRootIdentity: string,\n directory: Entry,\n): Unit | undefined {\n const declaring = sourceFilesUnder(\n directory,\n packageRootIdentity,\n new Set(),\n ).filter(({ real }) => declares(real));\n const index = join(directory.path, \"index.ts\");\n const suggested =\n declaring.find(({ path }) => path === index) ?? declaring.at(0);\n if (suggested === undefined) return undefined;\n return {\n kind: \"document-model\",\n unit: `${packagePath(packageRoot, directory.path)}/`,\n specifier: packagePath(packageRoot, suggested.path),\n declaring: declaring.map(({ real }) => real),\n };\n}\n\n/**\n * Each `<documentModelsDir>/<name>/` whose sources declare a code-first model\n * that no selected source's import reached. A selected source that did not\n * import reaches files no one can name, so the scan then reports nothing.\n */\nexport function findUnregisteredDefinitions(request: {\n readonly packageRoot: string;\n /** Absolute, and already checked to stay inside the package root. */\n readonly documentModelsDir: string;\n readonly sources: readonly DefinitionSource[];\n /** Absolute paths of every module the import of `specifier` evaluated, its own included. */\n readonly importedFiles: (specifier: string) => readonly string[];\n}): readonly UnregisteredDefinition[] {\n const { packageRoot, documentModelsDir, sources, importedFiles } = request;\n const imported = sources.map(({ specifier }) => importedFiles(specifier));\n if (imported.some((files) => files.length === 0)) return [];\n const reached = new Set(imported.flat().map(realPathOrSelf));\n const packageRootIdentity = realPathOrSelf(packageRoot);\n return packageEntries(documentModelsDir, packageRootIdentity)\n .flatMap((entry) =>\n entry.isDirectory\n ? (modelUnit(packageRoot, packageRootIdentity, entry) ?? [])\n : [],\n )\n .filter((unit) => !unit.declaring.some((file) => reached.has(file)))\n .map(({ kind, unit, specifier }) => ({ kind, unit, specifier }));\n}\n","import type {\n DefinitionDiagnostic,\n Sha256Digest,\n} from \"@powerhousedao/shared/document-model\";\nimport { realpathSync, statSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { adaptCodeFirstDocumentModelSource } from \"../adapters/code-first-document-model-source-adapter.js\";\nimport type {\n DefinitionProducer,\n ProducedDefinitions,\n} from \"../adapters/producer.js\";\nimport { compareArtifacts, sortedUniqueDiagnostics } from \"../report/status.js\";\nimport type { LoadedDefinitionProject } from \"../report/types.js\";\nimport type { DefinitionSourceLoader } from \"../definition-source-loader.js\";\nimport {\n isWithin,\n readConfigObject,\n realPathThroughExistingParent,\n} from \"../definition-source-resolution.js\";\nimport { toolingDiagnostics } from \"../diagnostic-codes.js\";\nimport { readStoredDocumentModels } from \"../schema-first/stored-models.js\";\nimport { findUnregisteredDefinitions } from \"./unregistered-definitions.js\";\n\n/**\n * @experimental A package's document models, loaded once and read by both\n * `ph model check` and `ph model inspect`. Experimental while code-first\n * projects are introduced.\n */\nexport type ProjectDefinitions = LoadedDefinitionProject & {\n /** Absolute. No report carries it. */\n readonly packageRoot: string;\n};\n\nconst DEFAULT_DOCUMENT_MODELS_DIR = \"./document-models\";\n\n/** Code-first sources are authored in normalized coordinates, so they need no relocation. */\nconst adaptSelectedModules: DefinitionProducer = ({ loaded }) => {\n const results = loaded.documentModels.map(({ value, source }) => {\n const result = adaptCodeFirstDocumentModelSource(value, source);\n return {\n artifacts: result.artifacts,\n diagnostics: result.diagnostics.map((diagnostic) =>\n diagnostic.source === undefined\n ? { ...diagnostic, source }\n : diagnostic,\n ),\n };\n });\n return {\n artifacts: results.flatMap(({ artifacts }) => artifacts),\n diagnostics: results.flatMap(({ diagnostics }) => diagnostics),\n relocations: new Map(),\n };\n};\n\n/** The readers a project loads with unless a caller passes its own; the one place an authoring mode is named. */\nexport const defaultDefinitionProducers: readonly DefinitionProducer[] =\n Object.freeze([adaptSelectedModules, readStoredDocumentModels]);\n\n/** A path that cannot be inspected is left to the readers, which report it. */\nfunction namesNonDirectory(path: string): boolean {\n try {\n return statSync(path, { throwIfNoEntry: false })?.isDirectory() === false;\n } catch {\n return false;\n }\n}\n\n/** The configured models directory, or why it cannot be scanned. */\nfunction documentModelsDirectory(\n packageRoot: string,\n configFile: string,\n): {\n readonly path?: string;\n readonly diagnostics: readonly DefinitionDiagnostic[];\n} {\n const config = readConfigObject(resolve(configFile));\n // The loader already reported an unreadable config.\n if (!config.ok) return { diagnostics: [] };\n const configured =\n config.value.documentModelsDir ?? DEFAULT_DOCUMENT_MODELS_DIR;\n if (typeof configured !== \"string\" || configured.trim() === \"\") {\n return {\n diagnostics: [\n toolingDiagnostics.create({\n code: \"PH-CONFIG-SOURCE-INVALID\",\n path: [\"documentModelsDir\"],\n message: \"documentModelsDir is not a directory path.\",\n expected: \"a package-relative path such as ./document-models\",\n received: JSON.stringify(configured),\n repair:\n \"Set documentModelsDir to a package-relative directory, or remove it to use ./document-models.\",\n }),\n ],\n };\n }\n const path = resolve(packageRoot, configured);\n let inside = isWithin(packageRoot, path);\n try {\n inside &&= isWithin(\n realpathSync.native(packageRoot),\n realPathThroughExistingParent(path),\n );\n } catch {\n inside = false;\n }\n if (!inside) {\n return {\n diagnostics: [\n toolingDiagnostics.create({\n code: \"PH-CONFIG-SOURCE-OUTSIDE-PACKAGE\",\n path: [\"documentModelsDir\"],\n message:\n \"documentModelsDir leaves the package root, so its models are not this package's.\",\n expected: \"a directory inside the package\",\n received: configured,\n repair: \"Point documentModelsDir at a directory inside the package.\",\n }),\n ],\n };\n }\n if (namesNonDirectory(path)) {\n return {\n diagnostics: [\n toolingDiagnostics.create({\n code: \"PH-CONFIG-SOURCE-INVALID\",\n path: [\"documentModelsDir\"],\n message: \"documentModelsDir names a file, not a directory.\",\n expected: \"a package-relative directory such as ./document-models\",\n received: configured,\n repair:\n \"Point documentModelsDir at the directory that holds the models, or remove it to use ./document-models.\",\n }),\n ],\n };\n }\n return { path, diagnostics: [] };\n}\n\n/** Tool and Node messages can quote the machine path a package lives at. */\nfunction packageRelative(\n diagnostics: readonly DefinitionDiagnostic[],\n packageRoot: string,\n): readonly DefinitionDiagnostic[] {\n let real = packageRoot;\n try {\n real = realpathSync.native(packageRoot);\n } catch {\n // An unreadable root keeps its spelled path only.\n }\n const roots = [...new Set([packageRoot, real])]\n .sort((left, right) => right.length - left.length)\n .flatMap((root) => [pathToFileURL(root).href, root]);\n const rewrite = (text: string) =>\n roots.reduce((result, root) => result.replaceAll(root, \".\"), text);\n return diagnostics.map((diagnostic) => ({\n ...diagnostic,\n message: rewrite(diagnostic.message),\n repair: rewrite(diagnostic.repair),\n ...(diagnostic.expected !== undefined && {\n expected: rewrite(diagnostic.expected),\n }),\n ...(diagnostic.received !== undefined && {\n received: rewrite(diagnostic.received),\n }),\n ...(diagnostic.related !== undefined && {\n related: diagnostic.related.map((location) => ({\n ...location,\n message: rewrite(location.message),\n })),\n }),\n }));\n}\n\n/**\n * @experimental Loads the selected code-first sources and the package's stored\n * schema-first models, and scans for code-first declarations no source\n * reaches. Artifacts and diagnostics are sorted and package relative.\n * `producers` replaces the default readers. `importedFiles` names the\n * absolute paths of every module the loader's import of a selected\n * specifier evaluated, so reach follows whatever the importer resolved.\n * Experimental while code-first projects are introduced.\n */\nexport async function loadProjectDefinitions(request: {\n readonly loader: DefinitionSourceLoader;\n readonly configFile: string;\n readonly packageRevision: Sha256Digest;\n readonly signal?: AbortSignal;\n readonly producers?: readonly DefinitionProducer[];\n readonly importedFiles: (specifier: string) => readonly string[];\n}): Promise<ProjectDefinitions> {\n const {\n loader,\n producers = defaultDefinitionProducers,\n importedFiles,\n ...load\n } = request;\n const loaded = await loader.normalizeDefinitionSources(load);\n request.signal?.throwIfAborted();\n const { packageRoot } = loaded;\n const directory = documentModelsDirectory(packageRoot, request.configFile);\n const modelsDir = directory.path;\n const input = {\n ...load,\n loader,\n packageRoot,\n loaded,\n ...(modelsDir !== undefined && { documentModelsDir: modelsDir }),\n };\n const produced: ProducedDefinitions[] = [];\n for (const producer of producers) produced.push(await producer(input));\n request.signal?.throwIfAborted();\n const selectionKnown = !loaded.diagnostics.some(\n ({ phase, severity }) => phase === \"configuration\" && severity === \"error\",\n );\n return {\n packageRoot,\n sourceSet: loaded.sourceSet,\n ...(loaded.status === \"skipped\" && { skipReason: loaded.skipReason }),\n artifacts: produced\n .flatMap(({ artifacts }) => artifacts)\n .sort(compareArtifacts),\n relocations: new Map(\n produced.flatMap(({ relocations }) => [...relocations]),\n ),\n diagnostics: sortedUniqueDiagnostics(\n packageRelative(\n [\n ...loaded.diagnostics,\n ...directory.diagnostics,\n ...produced.flatMap(({ diagnostics }) => diagnostics),\n ],\n packageRoot,\n ),\n ),\n unregistered:\n selectionKnown && modelsDir !== undefined\n ? findUnregisteredDefinitions({\n packageRoot,\n documentModelsDir: modelsDir,\n sources: loaded.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SAAS,EAAE,gBAAgB,SAAS,CAAC,CACrC,KAAK,gBAAgB;EACxB,aAAa,IAAI,IACf,SAAS,SAAS,EAAE,kBAAkB,CAAC,GAAG,WAAW,CAAC,CACxD;EACA,aAAa,wBACX,gBACE;GACE,GAAG,OAAO;GACV,GAAG,UAAU;GACb,GAAG,SAAS,SAAS,EAAE,kBAAkB,WAAW;EACtD,GACA,WACF,CACF;EACA,cACE,kBAAkB,cAAc,KAAA,IAC5B,4BAA4B;GAC1B;GACA,mBAAmB;GACnB,SAAS,OAAO,UAAU;GAC1B;EACF,CAAC,IACD,CAAC;CACT;AACF"}
1
+ {"version":3,"file":"tooling.mjs","names":["schema","schema","schema","schema","schema","schema","BUILT_IN_SCALARS","CATALOG_SCALARS","typeReference","enumValue","namedType","examples","checkArtifact"],"sources":["../src/definition/kernel/hashes.ts","../src/definition/kernel/primitives.ts","../src/definition/kernel/diagnostics.ts","../src/definition/compiler/module-definition.ts","../src/scalars/types.ts","../src/scalars/define-catalog-scalar.ts","../src/scalars/scalar-literal.ts","../src/scalars/declarations/unknown.ts","../src/scalars/declarations/date-time.ts","../src/scalars/pattern.ts","../src/scalars/declarations/address.ts","../src/scalars/declarations/attachment-ref.ts","../src/scalars/coercion.ts","../src/scalars/declarations/amounts.ts","../src/scalars/declarations/amount-tokens.ts","../src/scalars/declarations/ethereum-address.ts","../src/scalars/declarations/email-address.ts","../src/scalars/declarations/amount-percentage.ts","../src/scalars/declarations/date.ts","../src/scalars/declarations/url.ts","../src/scalars/declarations/amount-money.ts","../src/scalars/declarations/olabel.ts","../src/scalars/declarations/currency.ts","../src/scalars/declarations/phid.ts","../src/scalars/declarations/oid.ts","../src/scalars/declarations/amount-fiat.ts","../src/scalars/declarations/amount-currency.ts","../src/scalars/declarations/amount-crypto.ts","../src/scalars/declarations/amount.ts","../src/scalars/declarations/upload.ts","../src/scalars/declarations/json-object.ts","../src/scalars/catalog.ts","../src/definition/kernel/diagnostic-collector.ts","../src/definition/kernel/data-properties.ts","../src/definition/kernel/diagnostic-codes.ts","../src/definition/kernel/graphql-ast.ts","../src/definition/dsl/diagnostic-codes.ts","../src/definition/compiler/diagnostic-codes.ts","../src/definition/compiler/wire-shape.ts","../src/definition/model/diagnostic-codes.ts","../src/definition/tooling/diagnostic-codes.ts","../src/definition/tooling/adapters/code-first-document-model-source-adapter.ts","../src/definition/tooling/definition-source-resolution.ts","../src/definition/tooling/structured-diagnostics.ts","../src/definition/tooling/definition-source-loader.ts","../src/definition/compiler/naming.ts","../src/definition/tooling/check/diagnostic-codes.ts","../src/definition/tooling/report/served-specification.ts","../src/definition/tooling/check/checks/duplicate-identities.ts","../src/definition/tooling/graphql/parse-schema.ts","../src/definition/tooling/check/checks/graphql-schema.ts","../src/definition/tooling/report/logical-collisions.ts","../src/definition/tooling/check/checks/logical-collisions.ts","../src/definition/tooling/check/checks/package-scalar-names.ts","../src/definition/compiler/segments.ts","../src/definition/tooling/graphql/ast-to-structured.ts","../src/definition/tooling/check/stored-specification.ts","../src/definition/tooling/check/checks/retained-serialization.ts","../src/definition/tooling/check/checks/stored-materialization.ts","../src/definition/tooling/check/checks/unregistered-definitions.ts","../src/definition/tooling/report/status.ts","../src/definition/tooling/check/check-project-definitions.ts","../src/definition/tooling/release/diagnostic-codes.ts","../src/definition/tooling/release/checks/host-validation.ts","../src/definition/tooling/release/release-checks.ts","../src/definition/tooling/inspect/diagnostic-codes.ts","../src/definition/tooling/inspect/inspect-project-definitions.ts","../src/definition/tooling/schema-first/project-scalars.ts","../src/scalars/stored-definition.ts","../src/definition/compiler/stored-scalar.ts","../src/definition/tooling/schema-first/schema-first-document-model-module-adapter.ts","../src/definition/tooling/schema-first/stored-locations.ts","../src/definition/tooling/schema-first/stored-models.ts","../src/definition/tooling/project/unregistered-definitions.ts","../src/definition/tooling/project/project-definitions.ts"],"sourcesContent":["import type { Sha256Digest } from \"@powerhousedao/shared/document-model\";\n\n// Hand-written so Node and browser builds derive the same digests and IDs\n// synchronously, with no host crypto.\n\nfunction rotateRight(value: number, shift: number): number {\n return ((value >>> shift) | (value << (32 - shift))) >>> 0;\n}\n\nconst SHA256_CONSTANTS = new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,\n 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,\n 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,\n 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,\n 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,\n 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,\n 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,\n 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,\n 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,\n]);\n\nexport function sha256(value: string): Sha256Digest {\n const bytes = new TextEncoder().encode(value);\n const paddedLength = Math.ceil((bytes.length + 9) / 64) * 64;\n const input = new Uint8Array(paddedLength);\n input.set(bytes);\n input[bytes.length] = 0x80;\n const view = new DataView(input.buffer);\n const bitLength = BigInt(bytes.length) * 8n;\n view.setUint32(paddedLength - 8, Number(bitLength >> 32n), false);\n view.setUint32(paddedLength - 4, Number(bitLength & 0xffff_ffffn), false);\n\n const state = new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c,\n 0x1f83d9ab, 0x5be0cd19,\n ]);\n const words = new Uint32Array(64);\n\n for (let offset = 0; offset < paddedLength; offset += 64) {\n for (let index = 0; index < 16; index += 1) {\n words[index] = view.getUint32(offset + index * 4, false);\n }\n for (let index = 16; index < 64; index += 1) {\n const previous15 = words[index - 15];\n const previous2 = words[index - 2];\n const sigma0 =\n rotateRight(previous15, 7) ^\n rotateRight(previous15, 18) ^\n (previous15 >>> 3);\n const sigma1 =\n rotateRight(previous2, 17) ^\n rotateRight(previous2, 19) ^\n (previous2 >>> 10);\n words[index] =\n (words[index - 16] + sigma0 + words[index - 7] + sigma1) >>> 0;\n }\n\n let a = state[0];\n let b = state[1];\n let c = state[2];\n let d = state[3];\n let e = state[4];\n let f = state[5];\n let g = state[6];\n let h = state[7];\n\n for (let index = 0; index < 64; index += 1) {\n const sigma1 =\n rotateRight(e, 6) ^ rotateRight(e, 11) ^ rotateRight(e, 25);\n const choice = (e & f) ^ (~e & g);\n const temporary1 =\n (h + sigma1 + choice + SHA256_CONSTANTS[index] + words[index]) >>> 0;\n const sigma0 =\n rotateRight(a, 2) ^ rotateRight(a, 13) ^ rotateRight(a, 22);\n const majority = (a & b) ^ (a & c) ^ (b & c);\n const temporary2 = (sigma0 + majority) >>> 0;\n h = g;\n g = f;\n f = e;\n e = (d + temporary1) >>> 0;\n d = c;\n c = b;\n b = a;\n a = (temporary1 + temporary2) >>> 0;\n }\n\n state[0] = (state[0] + a) >>> 0;\n state[1] = (state[1] + b) >>> 0;\n state[2] = (state[2] + c) >>> 0;\n state[3] = (state[3] + d) >>> 0;\n state[4] = (state[4] + e) >>> 0;\n state[5] = (state[5] + f) >>> 0;\n state[6] = (state[6] + g) >>> 0;\n state[7] = (state[7] + h) >>> 0;\n }\n\n const hex = [...state]\n .map((word) => word.toString(16).padStart(8, \"0\"))\n .join(\"\");\n return `sha256:${hex}`;\n}\n\nconst UUID_PATTERN =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nfunction uuidBytes(uuid: string): Uint8Array {\n if (!UUID_PATTERN.test(uuid)) {\n throw new TypeError(\n `UUID namespace ${JSON.stringify(uuid)} is not canonical.`,\n );\n }\n const hex = uuid.replaceAll(\"-\", \"\");\n return Uint8Array.from({ length: 16 }, (_, index) =>\n Number.parseInt(hex.slice(index * 2, index * 2 + 2), 16),\n );\n}\n\nfunction formatUuid(bytes: Uint8Array): string {\n const hex = [...bytes]\n .map((byte) => byte.toString(16).padStart(2, \"0\"))\n .join(\"\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;\n}\n\nexport function uuidV5(namespace: string, name: string): string {\n const namespaceBytes = uuidBytes(namespace);\n const nameBytes = new TextEncoder().encode(name);\n const input = new Uint8Array(namespaceBytes.length + nameBytes.length);\n input.set(namespaceBytes);\n input.set(nameBytes, namespaceBytes.length);\n const digest = sha1(input).slice(0, 16);\n digest[6] = (digest[6] & 0x0f) | 0x50;\n digest[8] = (digest[8] & 0x3f) | 0x80;\n return formatUuid(digest);\n}\n\nfunction rotateLeft(value: number, shift: number): number {\n return ((value << shift) | (value >>> (32 - shift))) >>> 0;\n}\n\nfunction sha1(bytes: Uint8Array): Uint8Array {\n const paddedLength = Math.ceil((bytes.length + 9) / 64) * 64;\n const input = new Uint8Array(paddedLength);\n input.set(bytes);\n input[bytes.length] = 0x80;\n const view = new DataView(input.buffer);\n const bitLength = BigInt(bytes.length) * 8n;\n view.setUint32(paddedLength - 8, Number(bitLength >> 32n), false);\n view.setUint32(paddedLength - 4, Number(bitLength & 0xffff_ffffn), false);\n\n const state = new Uint32Array([\n 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0,\n ]);\n const words = new Uint32Array(80);\n\n for (let offset = 0; offset < paddedLength; offset += 64) {\n for (let index = 0; index < 16; index += 1) {\n words[index] = view.getUint32(offset + index * 4, false);\n }\n for (let index = 16; index < 80; index += 1) {\n words[index] = rotateLeft(\n words[index - 3] ^\n words[index - 8] ^\n words[index - 14] ^\n words[index - 16],\n 1,\n );\n }\n\n let a = state[0];\n let b = state[1];\n let c = state[2];\n let d = state[3];\n let e = state[4];\n\n for (let index = 0; index < 80; index += 1) {\n let f: number;\n let k: number;\n if (index < 20) {\n f = (b & c) | (~b & d);\n k = 0x5a827999;\n } else if (index < 40) {\n f = b ^ c ^ d;\n k = 0x6ed9eba1;\n } else if (index < 60) {\n f = (b & c) | (b & d) | (c & d);\n k = 0x8f1bbcdc;\n } else {\n f = b ^ c ^ d;\n k = 0xca62c1d6;\n }\n const next = (rotateLeft(a, 5) + f + e + k + words[index]) >>> 0;\n e = d;\n d = c;\n c = rotateLeft(b, 30);\n b = a;\n a = next;\n }\n\n state[0] = (state[0] + a) >>> 0;\n state[1] = (state[1] + b) >>> 0;\n state[2] = (state[2] + c) >>> 0;\n state[3] = (state[3] + d) >>> 0;\n state[4] = (state[4] + e) >>> 0;\n }\n\n const digest = new Uint8Array(20);\n const digestView = new DataView(digest.buffer);\n state.forEach((word, index) => {\n digestView.setUint32(index * 4, word, false);\n });\n return digest;\n}\n","import type { Sha256Digest } from \"@powerhousedao/shared/document-model\";\nimport { sha256 } from \"./hashes.js\";\n\nfunction memberPath(parent: string, key: string | number): string {\n if (typeof key === \"number\") {\n return `${parent}[${key}]`;\n }\n return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key)\n ? `${parent}.${key}`\n : `${parent}[${JSON.stringify(key)}]`;\n}\n\nfunction encodeProperty(\n descriptor: PropertyDescriptor,\n path: string,\n ancestors: Set<object>,\n): string {\n if (!(\"value\" in descriptor)) {\n throw new TypeError(`${path} must be a data property, not an accessor.`);\n }\n if (descriptor.enumerable !== true) {\n throw new TypeError(`${path} must be enumerable.`);\n }\n return encode(descriptor.value, path, ancestors);\n}\n\nfunction encodeArray(\n value: readonly unknown[],\n path: string,\n ancestors: Set<object>,\n): string {\n if (Object.getPrototypeOf(value) !== Array.prototype) {\n throw new TypeError(`${path} must be a plain array.`);\n }\n for (const key of Reflect.ownKeys(value)) {\n if (key === \"length\") {\n continue;\n }\n if (typeof key === \"symbol\") {\n throw new TypeError(`${path} must not have symbol keys.`);\n }\n if (!/^(?:0|[1-9][0-9]*)$/.test(key) || Number(key) >= value.length) {\n throw new TypeError(\n `${path} must not have a non-index property ${JSON.stringify(key)}.`,\n );\n }\n }\n const members: string[] = [];\n for (let index = 0; index < value.length; index += 1) {\n const descriptor = Object.getOwnPropertyDescriptor(value, index);\n if (descriptor === undefined) {\n throw new TypeError(\n `${memberPath(path, index)} must not be an array hole.`,\n );\n }\n members.push(\n encodeProperty(descriptor, memberPath(path, index), ancestors),\n );\n }\n return `[${members.join(\",\")}]`;\n}\n\nfunction encodeObject(\n value: object,\n path: string,\n ancestors: Set<object>,\n): string {\n const prototype: unknown = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) {\n throw new TypeError(`${path} must be a plain object.`);\n }\n const keys: string[] = [];\n for (const key of Reflect.ownKeys(value)) {\n if (typeof key === \"symbol\") {\n throw new TypeError(`${path} must not have symbol keys.`);\n }\n keys.push(key);\n }\n keys.sort(compareCodeUnits);\n const members: string[] = [];\n for (const key of keys) {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor === undefined) {\n throw new TypeError(`${memberPath(path, key)} must be an own property.`);\n }\n members.push(\n `${JSON.stringify(key)}:${encodeProperty(descriptor, memberPath(path, key), ancestors)}`,\n );\n }\n return `{${members.join(\",\")}}`;\n}\n\nfunction encode(value: unknown, path: string, ancestors: Set<object>): string {\n switch (typeof value) {\n case \"string\":\n case \"boolean\":\n return JSON.stringify(value);\n case \"number\":\n if (Number.isFinite(value)) {\n return JSON.stringify(value);\n }\n throw new TypeError(`${path} must be a finite number.`);\n case \"object\": {\n if (value === null) {\n return \"null\";\n }\n if (ancestors.has(value)) {\n throw new TypeError(`${path} must not contain a cycle.`);\n }\n ancestors.add(value);\n const encoded = Array.isArray(value)\n ? encodeArray(value, path, ancestors)\n : encodeObject(value, path, ancestors);\n ancestors.delete(value);\n return encoded;\n }\n default:\n throw new TypeError(\n `${path} must be a JSON value, received ${typeof value}.`,\n );\n }\n}\n\nexport function canonicalJson(value: unknown): string {\n return encode(value, \"$\", new Set());\n}\n\nexport function canonicalDigest(value: unknown): Sha256Digest {\n return sha256(canonicalJson(value));\n}\n\nexport function compareCodeUnits(a: string, b: string): -1 | 0 | 1 {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\nconst DIGIT_0 = 48;\nconst DIGIT_9 = 57;\n\nfunction isDigit(code: number): boolean {\n return DIGIT_0 <= code && code <= DIGIT_9;\n}\n\n/**\n * graphql-js's `naturalCompare`, which `lexicographicSortSchema` sorts a\n * generated schema with: runs of digits compare as numbers, so `item2`\n * precedes `item10`. Copied, not imported, so a model never loads `graphql`.\n */\nexport function compareGeneratedOrder(a: string, b: string): number {\n let aIndex = 0;\n let bIndex = 0;\n while (aIndex < a.length && bIndex < b.length) {\n let aChar = a.charCodeAt(aIndex);\n let bChar = b.charCodeAt(bIndex);\n if (isDigit(aChar) && isDigit(bChar)) {\n let aNumber = 0;\n do {\n ++aIndex;\n aNumber = aNumber * 10 + aChar - DIGIT_0;\n aChar = a.charCodeAt(aIndex);\n } while (isDigit(aChar) && aNumber > 0);\n let bNumber = 0;\n do {\n ++bIndex;\n bNumber = bNumber * 10 + bChar - DIGIT_0;\n bChar = b.charCodeAt(bIndex);\n } while (isDigit(bChar) && bNumber > 0);\n if (aNumber !== bNumber) return aNumber < bNumber ? -1 : 1;\n } else {\n if (aChar !== bChar) return aChar < bChar ? -1 : 1;\n ++aIndex;\n ++bIndex;\n }\n }\n return a.length - b.length;\n}\n\nexport const EMPTY_INPUT_FIELD_NAME = \"_empty\";\n\nexport function isGraphQLName(value: unknown): value is string {\n return typeof value === \"string\" && /^[_A-Za-z][_0-9A-Za-z]*$/.test(value);\n}\n\nexport function isAuthoredSchemaName(value: unknown): value is string {\n return isGraphQLName(value) && !value.startsWith(\"__\");\n}\n\nexport function isEnumValueName(value: unknown): value is string {\n return (\n isAuthoredSchemaName(value) &&\n value !== \"true\" &&\n value !== \"false\" &&\n value !== \"null\"\n );\n}\n\nexport function isNFC(value: string): boolean {\n return value.normalize(\"NFC\") === value;\n}\n","import type {\n DefinitionDiagnostic,\n DefinitionDiagnosticPhase,\n DefinitionDiagnosticSeverity,\n DefinitionPath,\n DefinitionRef,\n DefinitionRelatedLocation,\n DefinitionSource,\n} from \"@powerhousedao/shared/document-model\";\nimport { compareCodeUnits } from \"./primitives.js\";\n\nexport type DiagnosticCode = `PH-${string}`;\n\ntype DiagnosticCodeEntry = {\n readonly severity: DefinitionDiagnosticSeverity;\n readonly phase: DefinitionDiagnosticPhase;\n readonly meaning: string;\n};\n\nconst MAX_SUMMARY_CODE_POINTS = 512;\n\nexport function capCodePoints(\n value: string,\n max: number = MAX_SUMMARY_CODE_POINTS,\n): string {\n const points = [...value];\n const limit = Math.max(0, max);\n return points.length <= limit ? value : points.slice(0, limit).join(\"\");\n}\n\nexport type DefinitionDiagnosticInput<TCode extends string = DiagnosticCode> = {\n readonly code: TCode;\n readonly path: DefinitionPath;\n readonly message: string;\n readonly repair: string;\n readonly source?: DefinitionSource;\n readonly definition?: DefinitionRef;\n readonly expected?: string;\n readonly received?: string;\n readonly related?: readonly DefinitionRelatedLocation[];\n};\n\nfunction copySource(source: DefinitionSource): DefinitionSource {\n return {\n specifier: source.specifier,\n ...(source.exportPath !== undefined && {\n exportPath: [...source.exportPath],\n }),\n };\n}\n\nfunction copyDefinitionRef(definition: DefinitionRef): DefinitionRef {\n return {\n kind: definition.kind,\n key: definition.key,\n ...(definition.version !== undefined && { version: definition.version }),\n };\n}\n\nfunction createDiagnostic(\n input: DefinitionDiagnosticInput,\n { severity, phase }: DiagnosticCodeEntry,\n): DefinitionDiagnostic {\n return {\n code: input.code,\n severity,\n phase,\n ...(input.source !== undefined && { source: copySource(input.source) }),\n ...(input.definition !== undefined && {\n definition: copyDefinitionRef(input.definition),\n }),\n path: [...input.path],\n message: input.message,\n ...(input.expected !== undefined && {\n expected: capCodePoints(input.expected),\n }),\n ...(input.received !== undefined && {\n received: capCodePoints(input.received),\n }),\n repair: input.repair,\n ...(input.related !== undefined && {\n related: input.related.map((location) => ({\n ...(location.source !== undefined && {\n source: copySource(location.source),\n }),\n path: [...location.path],\n message: location.message,\n })),\n }),\n };\n}\n\nexport function describeReceived(value: unknown): string {\n if (value === null) return \"null\";\n try {\n return Array.isArray(value) ? \"array\" : typeof value;\n } catch {\n return \"inspection-failed\";\n }\n}\n\n/** The codes one layer emits, and the builders that fill in each code's severity and phase. */\nexport type DiagnosticCatalog<TCode extends DiagnosticCode> = {\n readonly codes: { readonly [K in TCode]: DiagnosticCodeEntry };\n create(input: DefinitionDiagnosticInput<TCode>): DefinitionDiagnostic;\n fail(input: DefinitionDiagnosticInput<TCode>): never;\n};\n\n/**\n * A layer's catalog: its own codes plus the codes of the catalog below it,\n * which already holds every lower layer's codes. A code keeps the meaning its\n * owning layer gave it, so an own code the lower catalog declares is refused.\n */\nexport function defineDiagnosticCatalog<\n TOwn extends DiagnosticCode = never,\n TLower extends DiagnosticCode = never,\n>(\n own: { readonly [K in TOwn]: DiagnosticCodeEntry } & {\n readonly [K in NoInfer<TLower>]?: never;\n },\n lower?: DiagnosticCatalog<TLower>,\n): DiagnosticCatalog<TOwn | TLower> {\n const lowerCodes: Readonly<Record<string, DiagnosticCodeEntry>> =\n lower?.codes ?? {};\n const ownEntries = Object.entries<DiagnosticCodeEntry>(own).map(\n ([code, entry]) => [code, Object.freeze({ ...entry })] as const,\n );\n const redefined = ownEntries\n .map(([code]) => code)\n .filter((code) => Object.hasOwn(lowerCodes, code));\n if (redefined.length > 0) {\n throw new TypeError(\n `Diagnostic code ${redefined.join(\", \")} is already declared by a lower layer.`,\n );\n }\n const codes = Object.freeze({\n ...lowerCodes,\n ...Object.fromEntries(ownEntries),\n }) as { readonly [K in TOwn | TLower]: DiagnosticCodeEntry };\n const create = (input: DefinitionDiagnosticInput<TOwn | TLower>) =>\n createDiagnostic(input, codes[input.code]);\n return Object.freeze({\n codes,\n create,\n fail(input: DefinitionDiagnosticInput<TOwn | TLower>): never {\n throw new DefinitionError([create(input)]);\n },\n });\n}\n\ntype Ordering = -1 | 0 | 1;\n\nfunction compareNumbers(a: number, b: number): Ordering {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\nfunction compareOptional<T>(\n a: T | undefined,\n b: T | undefined,\n compare: (x: T, y: T) => Ordering,\n): Ordering {\n if (a === undefined) return b === undefined ? 0 : -1;\n if (b === undefined) return 1;\n return compare(a, b);\n}\n\nfunction compareLists<T>(\n a: readonly T[],\n b: readonly T[],\n compare: (x: T, y: T) => Ordering,\n): Ordering {\n const shared = Math.min(a.length, b.length);\n for (let index = 0; index < shared; index += 1) {\n const result = compare(a[index], b[index]);\n if (result !== 0) return result;\n }\n return compareNumbers(a.length, b.length);\n}\n\nfunction comparePathSegments(a: string | number, b: string | number): Ordering {\n if (typeof a === \"number\") {\n return typeof b === \"number\" ? compareNumbers(a, b) : -1;\n }\n if (typeof b === \"number\") return 1;\n return compareCodeUnits(a, b);\n}\n\nexport function compareDefinitionPaths(\n a: DefinitionPath,\n b: DefinitionPath,\n): Ordering {\n return compareLists(a, b, comparePathSegments);\n}\n\nfunction compareSources(a: DefinitionSource, b: DefinitionSource): Ordering {\n const specifier = compareCodeUnits(a.specifier, b.specifier);\n if (specifier !== 0) return specifier;\n return compareOptional(a.exportPath, b.exportPath, (x, y) =>\n compareLists(x, y, compareCodeUnits),\n );\n}\n\nfunction compareDefinitionRefs(a: DefinitionRef, b: DefinitionRef): Ordering {\n const kind = compareCodeUnits(a.kind, b.kind);\n if (kind !== 0) return kind;\n const key = compareCodeUnits(a.key, b.key);\n if (key !== 0) return key;\n return compareOptional(a.version, b.version, compareNumbers);\n}\n\nexport function compareDefinitionDiagnostics(\n a: DefinitionDiagnostic,\n b: DefinitionDiagnostic,\n): Ordering {\n const source = compareOptional(a.source, b.source, compareSources);\n if (source !== 0) return source;\n const definition = compareOptional(\n a.definition,\n b.definition,\n compareDefinitionRefs,\n );\n if (definition !== 0) return definition;\n const path = compareDefinitionPaths(a.path, b.path);\n if (path !== 0) return path;\n return compareCodeUnits(a.code, b.code);\n}\n\nexport function sortDefinitionDiagnostics(\n diagnostics: readonly DefinitionDiagnostic[],\n): readonly DefinitionDiagnostic[] {\n return [...diagnostics].sort(compareDefinitionDiagnostics);\n}\n\nfunction formatPointer(path: DefinitionPath): string {\n if (path.length === 0) return \"(root)\";\n return path\n .map(\n (segment) =>\n `/${String(segment).replaceAll(\"~\", \"~0\").replaceAll(\"/\", \"~1\")}`,\n )\n .join(\"\");\n}\n\nfunction formatSource(source: DefinitionSource | undefined): string {\n if (source === undefined) return \"(no source)\";\n const exportPath = source.exportPath ?? [];\n return exportPath.length === 0\n ? source.specifier\n : `${source.specifier}#${formatPointer(exportPath)}`;\n}\n\nfunction formatDefinitionRef(definition: DefinitionRef | undefined): string {\n if (definition === undefined) return \"\";\n const version =\n definition.version === undefined ? \"\" : `@${definition.version}`;\n return ` ${definition.kind} ${definition.key}${version}`;\n}\n\nfunction oneLine(value: string): string {\n return value.replace(/\\s+/g, \" \");\n}\n\n/** @experimental One line: code, severity and phase, location, message, expected, received, related and repair. */\nexport function formatDefinitionDiagnostic(\n diagnostic: DefinitionDiagnostic,\n): string {\n const where = `${formatSource(diagnostic.source)}${formatDefinitionRef(diagnostic.definition)} ${formatPointer(diagnostic.path)}`;\n const expected =\n diagnostic.expected === undefined\n ? \"\"\n : ` Expected: ${oneLine(diagnostic.expected)}`;\n const received =\n diagnostic.received === undefined\n ? \"\"\n : ` Received: ${oneLine(diagnostic.received)}`;\n const related = (diagnostic.related ?? [])\n .map(\n (location) =>\n ` Related: ${formatSource(location.source)} ${formatPointer(location.path)}: ${oneLine(location.message)}`,\n )\n .join(\"\");\n return `${diagnostic.code} [${diagnostic.severity}/${diagnostic.phase}] ${where}: ${oneLine(diagnostic.message)}${expected}${received}${related} Repair: ${oneLine(diagnostic.repair)}`;\n}\n\n/**\n * @experimental Thrown when a code-first declaration is refused. `diagnostics`\n * holds every problem found, sorted, each with its code, path and repair.\n */\nexport class DefinitionError extends Error {\n readonly diagnostics: readonly DefinitionDiagnostic[];\n\n constructor(\n diagnostics: readonly [DefinitionDiagnostic, ...DefinitionDiagnostic[]],\n ) {\n if (diagnostics.length === 0) {\n throw new TypeError(\"DefinitionError requires at least one diagnostic.\");\n }\n const sorted = sortDefinitionDiagnostics(diagnostics);\n const noun = sorted.length === 1 ? \"diagnostic\" : \"diagnostics\";\n super(\n [\n `Definition failed with ${sorted.length} ${noun}:`,\n ...sorted.map(formatDefinitionDiagnostic),\n ].join(\"\\n\"),\n );\n this.name = \"DefinitionError\";\n this.diagnostics = sorted;\n }\n}\n","import type {\n DefinitionPath,\n DocumentModelDefinition,\n} from \"@powerhousedao/shared/document-model\";\nimport type { DefinitionDiagnosticInput } from \"../kernel/diagnostics.js\";\nimport type { CompilerDiagnosticCode } from \"./diagnostic-codes.js\";\n\n/**\n * Why `definition` cannot serve the module it is attached to: another\n * document type, or no specification for the module's version.\n */\nexport function definitionModuleMismatch(\n definition: DocumentModelDefinition,\n module: { readonly documentType: string; readonly version?: number },\n path: DefinitionPath,\n): DefinitionDiagnosticInput<CompilerDiagnosticCode> | undefined {\n if (definition.model.documentType !== module.documentType) {\n return {\n code: \"PH-DM-DECLARATION-INVALID\",\n path: [...path, \"model\", \"documentType\"],\n message:\n \"The structured definition and the stored model describe different document types.\",\n expected: module.documentType,\n received: definition.model.documentType,\n repair:\n \"Materialize the module and its definition from the same declaration.\",\n };\n }\n const { version } = module;\n if (\n version !== undefined &&\n !definition.specifications.some((entry) => entry.version === version)\n ) {\n return {\n code: \"PH-DM-DECLARATION-INVALID\",\n path: [...path, \"specifications\"],\n message: `The specification history carries no version ${version}, which is the version this module serves.`,\n expected: `a specification for version ${version}`,\n received: definition.specifications\n .map((entry) => String(entry.version))\n .join(\", \"),\n repair:\n \"Compose the versions with defineDocumentModelFamily so every module carries the complete history.\",\n };\n }\n return undefined;\n}\n","import type { z } from \"zod\";\nimport type { ScalarLiteralNode } from \"./scalar-literal.js\";\n\nexport const SCALAR_DEFINITION = Symbol.for(\"powerhouse.scalar-definition\");\nexport const SCALAR_DEFINITION_VERSION = 1;\n\n/** The wire shape of a scalar's values. */\nexport type ScalarRepresentation =\n | \"string\"\n | \"number\"\n | \"boolean\"\n | \"json-object\"\n | \"json\"\n | \"opaque\";\n\n/** The GraphQL coercion of a scalar: variables, inline literals, and output. */\nexport type ScalarCoercion<TValue> = {\n readonly parseValue: (input: unknown) => TValue;\n readonly parseLiteral: (node: ScalarLiteralNode) => TValue;\n readonly serialize: (value: unknown) => unknown;\n};\n\nexport type ScalarDefinition<\n TName extends string = string,\n TValue = unknown,\n> = {\n readonly [SCALAR_DEFINITION]: typeof SCALAR_DEFINITION_VERSION;\n readonly name: TName;\n readonly description?: string;\n readonly schema: z.ZodType<TValue>;\n readonly typescriptType: string | null;\n readonly zodSource: string | null;\n readonly example?: TValue;\n /**\n * The wire shape of a value. It picks the literal kinds a derived coercion\n * accepts. A definition from a release before this field lacks it.\n */\n readonly representation?: ScalarRepresentation;\n /** Absent means derived: `schema` runs on every path and only the literal kinds of `representation` parse. */\n readonly coercion?: ScalarCoercion<TValue>;\n};\n\n/** A definition this release made, with its representation filled. */\nexport type DescribedScalarDefinition<\n TName extends string = string,\n TValue = unknown,\n> = ScalarDefinition<TName, TValue> & {\n readonly representation: ScalarRepresentation;\n};\n\nexport type ScalarValue<T> =\n T extends ScalarDefinition<string, infer V> ? V : never;\n\n/** The definition format version `value` is branded with, if it has a brand. */\nexport function scalarDefinitionVersion(value: unknown): unknown {\n return typeof value === \"object\" &&\n value !== null &&\n SCALAR_DEFINITION in value\n ? value[SCALAR_DEFINITION]\n : undefined;\n}\n\nexport function isScalarDefinition(value: unknown): value is ScalarDefinition {\n return scalarDefinitionVersion(value) === SCALAR_DEFINITION_VERSION;\n}\n","import {\n type DescribedScalarDefinition,\n SCALAR_DEFINITION,\n SCALAR_DEFINITION_VERSION,\n} from \"./types.js\";\n\nexport function defineCatalogScalar<TName extends string, TValue>(\n input: Omit<\n DescribedScalarDefinition<TName, TValue>,\n typeof SCALAR_DEFINITION\n >,\n): DescribedScalarDefinition<TName, TValue> {\n return Object.freeze({\n ...input,\n [SCALAR_DEFINITION]: SCALAR_DEFINITION_VERSION,\n } satisfies DescribedScalarDefinition<TName, TValue>);\n}\n","/**\n * Closed literal grammar handed to `parseLiteral`. It mirrors the GraphQL\n * literal kinds the catalog supports so a declaration never needs graphql-js.\n */\nexport type ScalarLiteralNode =\n | { readonly kind: \"string\"; readonly value: string }\n | { readonly kind: \"int\"; readonly value: string }\n | { readonly kind: \"float\"; readonly value: string }\n | { readonly kind: \"boolean\"; readonly value: boolean }\n | { readonly kind: \"null\" }\n | { readonly kind: \"enum\"; readonly value: string }\n | { readonly kind: \"list\"; readonly values: readonly ScalarLiteralNode[] }\n | {\n readonly kind: \"object\";\n readonly fields: readonly {\n readonly name: string;\n readonly value: ScalarLiteralNode;\n }[];\n }\n | { readonly kind: \"variable\"; readonly name: string };\n\nexport class ScalarLiteralVariableError extends TypeError {\n constructor(name: string) {\n super(\n `Variable $${name} cannot appear inside a scalar literal; GraphQL resolves variables before literal coercion.`,\n );\n this.name = \"ScalarLiteralVariableError\";\n }\n}\n\n/** Converts a literal node to its runtime value. A variable anywhere throws. */\nexport function scalarLiteralValue(node: ScalarLiteralNode): unknown {\n switch (node.kind) {\n case \"string\":\n case \"enum\":\n return node.value;\n case \"int\":\n case \"float\":\n return Number(node.value);\n case \"boolean\":\n return node.value;\n case \"null\":\n return null;\n case \"list\":\n return node.values.map(scalarLiteralValue);\n case \"object\":\n return Object.fromEntries(\n node.fields.map((field) => [\n field.name,\n scalarLiteralValue(field.value),\n ]),\n );\n case \"variable\":\n throw new ScalarLiteralVariableError(node.name);\n }\n}\n\nexport function objectFields(\n node: ScalarLiteralNode,\n): ReadonlyMap<string, ScalarLiteralNode> {\n if (node.kind !== \"object\")\n throw new TypeError(\"Value must be an object literal.\");\n return new Map(node.fields.map((field) => [field.name, field.value]));\n}\n\nexport function literalString(\n node: ScalarLiteralNode | undefined,\n field: string,\n): string {\n if (node?.kind !== \"string\")\n throw new TypeError(`${field} must be a string literal.`);\n return node.value;\n}\n\nexport function floatOnlyNumber(\n node: ScalarLiteralNode | undefined,\n field: string,\n): number {\n if (node?.kind !== \"float\")\n throw new TypeError(`${field} must be a float literal.`);\n return Number.parseFloat(node.value);\n}\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\nimport { scalarLiteralValue } from \"../scalar-literal.js\";\n\nexport const unknownScalar = defineCatalogScalar({\n name: \"Unknown\",\n typescriptType: \"unknown\",\n zodSource: \"z.unknown()\",\n schema: z.unknown(),\n representation: \"opaque\",\n coercion: {\n parseValue: (value) => value,\n parseLiteral: scalarLiteralValue,\n serialize: (value) => value,\n },\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const dateTimeScalar = defineCatalogScalar({\n example: \"2024-01-01T00:00:00.000Z\",\n name: \"DateTime\",\n typescriptType: \"string\",\n zodSource: \"z.iso.datetime()\",\n schema: z.iso.datetime(),\n representation: \"string\",\n});\n","export function matchesScalarPattern(pattern: RegExp, value: unknown): boolean {\n return Reflect.apply(pattern.test.bind(pattern), undefined, [value]) === true;\n}\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\nimport { matchesScalarPattern } from \"../pattern.js\";\n\nexport const addressScalar = defineCatalogScalar({\n example: \"eip155:0x0000000000000000000000000000000000000000\",\n name: \"Address\",\n typescriptType: \"`${string}:0x${string}`\",\n zodSource:\n \"z.custom<`${string}:0x${string}`>((val) => /^[a-zA-Z0-9]+:0x[a-fA-F0-9]{40}$/.test(val as string))\",\n schema: z.custom<`${string}:0x${string}`>((val) =>\n matchesScalarPattern(/^[a-zA-Z0-9]+:0x[a-fA-F0-9]{40}$/, val),\n ),\n representation: \"string\",\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\nimport { matchesScalarPattern } from \"../pattern.js\";\n\nexport const attachmentRefScalar = defineCatalogScalar({\n example:\n \"attachment://v1:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n name: \"AttachmentRef\",\n typescriptType: \"`attachment://v${number}:${string}`\",\n zodSource:\n \"z.custom<`attachment://v${number}:${string}`>((val) => /^attachment:\\\\/\\\\/v\\\\d+:.+$/.test(val as string))\",\n schema: z.custom<`attachment://v${number}:${string}`>((val) =>\n matchesScalarPattern(/^attachment:\\/\\/v\\d+:.+$/, val),\n ),\n representation: \"string\",\n});\n","import type { z } from \"zod\";\nimport type { ScalarLiteralNode } from \"./scalar-literal.js\";\nimport type { ScalarCoercion } from \"./types.js\";\n\n/** Runs `schema` on every path; `readLiteral` turns an inline literal into its value first. */\nexport function validatingCoercion<TValue>(\n schema: z.ZodType<TValue>,\n readLiteral: (node: ScalarLiteralNode) => unknown,\n): ScalarCoercion<TValue> {\n const parse = (value: unknown): TValue => schema.parse(value);\n return {\n parseValue: parse,\n parseLiteral: (node) => parse(readLiteral(node)),\n serialize: parse,\n };\n}\n","import type { z } from \"zod\";\nimport { validatingCoercion } from \"../coercion.js\";\nimport {\n floatOnlyNumber,\n literalString,\n objectFields,\n} from \"../scalar-literal.js\";\n\n// The document-engineering scalar resolvers this catalog replaced parsed an\n// amount's number only from a float literal, so an integer literal such as 5\n// is refused even though the schema accepts 5. The host does not use this\n// coercion yet; it accepts 5.\nexport function floatAmountCoercion(schema: z.ZodType<number>) {\n return validatingCoercion(schema, (node) => floatOnlyNumber(node, \"value\"));\n}\n\nexport function stringAmountCoercion<TValue>(schema: z.ZodType<TValue>) {\n return validatingCoercion(schema, (node) => {\n const fields = objectFields(node);\n const value = literalString(fields.get(\"value\"), \"value\");\n if (!/^\\d+(\\.\\d+)?$/.test(value)) {\n throw new TypeError(\"value must be a numeric string.\");\n }\n return { unit: literalString(fields.get(\"unit\"), \"unit\"), value };\n });\n}\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\nimport { floatAmountCoercion } from \"./amounts.js\";\n\nconst schema = z.number();\n\nexport const amountTokensScalar = defineCatalogScalar({\n name: \"Amount_Tokens\",\n typescriptType: \"number\",\n zodSource: \"z.number()\",\n schema,\n representation: \"number\",\n coercion: floatAmountCoercion(schema),\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const ethereumAddressScalar = defineCatalogScalar({\n name: \"EthereumAddress\",\n typescriptType: \"string\",\n zodSource:\n \"z.string().regex(/^0x[a-fA-F0-9]{40}$/, { error: 'Invalid Ethereum address format' })\",\n schema: z.string().regex(/^0x[a-fA-F0-9]{40}$/, {\n error: \"Invalid Ethereum address format\",\n }),\n representation: \"string\",\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const emailAddressScalar = defineCatalogScalar({\n name: \"EmailAddress\",\n typescriptType: \"string\",\n zodSource: \"z.email()\",\n schema: z.email(),\n representation: \"string\",\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\nimport { floatAmountCoercion } from \"./amounts.js\";\n\nconst schema = z.number();\n\nexport const amountPercentageScalar = defineCatalogScalar({\n name: \"Amount_Percentage\",\n typescriptType: \"number\",\n zodSource: \"z.number()\",\n schema,\n representation: \"number\",\n coercion: floatAmountCoercion(schema),\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const dateScalar = defineCatalogScalar({\n example: \"2024-01-01T00:00:00.000Z\",\n name: \"Date\",\n typescriptType: \"string\",\n zodSource: \"z.iso.datetime()\",\n schema: z.iso.datetime(),\n representation: \"string\",\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const urlScalar = defineCatalogScalar({\n example: \"https://example.com\",\n name: \"URL\",\n typescriptType: \"string\",\n zodSource: \"z.url()\",\n schema: z.url(),\n representation: \"string\",\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\nimport { floatAmountCoercion } from \"./amounts.js\";\n\nconst schema = z.number();\n\nexport const amountMoneyScalar = defineCatalogScalar({\n name: \"Amount_Money\",\n typescriptType: \"number\",\n zodSource: \"z.number()\",\n schema,\n representation: \"number\",\n coercion: floatAmountCoercion(schema),\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const olabelScalar = defineCatalogScalar({\n name: \"OLabel\",\n typescriptType: \"string\",\n zodSource: \"z.string()\",\n schema: z.string(),\n representation: \"string\",\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const currencyScalar = defineCatalogScalar({\n name: \"Currency\",\n typescriptType: \"string\",\n zodSource: \"z.string()\",\n schema: z.string(),\n representation: \"string\",\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const phidScalar = defineCatalogScalar({\n name: \"PHID\",\n typescriptType: \"string\",\n zodSource: \"z.string()\",\n schema: z.string(),\n representation: \"string\",\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const oidScalar = defineCatalogScalar({\n name: \"OID\",\n typescriptType: \"string\",\n zodSource: \"z.string()\",\n schema: z.string(),\n representation: \"string\",\n});\n","import { z } from \"zod\";\nimport { validatingCoercion } from \"../coercion.js\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\nimport {\n floatOnlyNumber,\n literalString,\n objectFields,\n} from \"../scalar-literal.js\";\n\nconst schema = z.object({ unit: z.string(), value: z.number() });\n\nexport const amountFiatScalar = defineCatalogScalar({\n name: \"Amount_Fiat\",\n typescriptType: \"{ unit: string, value: number }\",\n zodSource: \"z.object({ unit: z.string(), value: z.number() })\",\n schema,\n representation: \"json-object\",\n coercion: validatingCoercion(schema, (node) => {\n const fields = objectFields(node);\n return {\n unit: literalString(fields.get(\"unit\"), \"unit\"),\n value: floatOnlyNumber(fields.get(\"value\"), \"value\"),\n };\n }),\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\nimport { stringAmountCoercion } from \"./amounts.js\";\n\nconst schema = z.object({ unit: z.string(), value: z.string() });\n\nexport const amountCurrencyScalar = defineCatalogScalar({\n name: \"Amount_Currency\",\n typescriptType: \"{ unit: string, value: string }\",\n zodSource: \"z.object({ unit: z.string(), value: z.string()})\",\n schema,\n representation: \"json-object\",\n coercion: stringAmountCoercion(schema),\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\nimport { stringAmountCoercion } from \"./amounts.js\";\n\nconst schema = z.object({ unit: z.string(), value: z.string() });\n\nexport const amountCryptoScalar = defineCatalogScalar({\n name: \"Amount_Crypto\",\n typescriptType: \"{ unit: string, value: string }\",\n zodSource: \"z.object({ unit: z.string(), value: z.string() })\",\n schema,\n representation: \"json-object\",\n coercion: stringAmountCoercion(schema),\n});\n","import { z } from \"zod\";\nimport { validatingCoercion } from \"../coercion.js\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\nimport {\n floatOnlyNumber,\n literalString,\n objectFields,\n} from \"../scalar-literal.js\";\n\nconst schema = z.object({ unit: z.string().optional(), value: z.number() });\n\nexport const amountScalar = defineCatalogScalar({\n name: \"Amount\",\n typescriptType: \"{ unit?: string, value?: number }\",\n zodSource: \"z.object({ unit: z.string().optional(), value: z.number() })\",\n schema,\n representation: \"json-object\",\n coercion: validatingCoercion(schema, (node) => {\n const fields = objectFields(node);\n const unit = fields.get(\"unit\");\n return {\n unit: unit === undefined ? undefined : literalString(unit, \"unit\"),\n value: floatOnlyNumber(fields.get(\"value\"), \"value\"),\n };\n }),\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const uploadScalar = defineCatalogScalar({\n name: \"Upload\",\n typescriptType: \"File\",\n zodSource: \"z.any()\",\n schema: z.any(),\n representation: \"opaque\",\n coercion: {\n parseValue: (value) => value,\n parseLiteral: () => {\n throw new TypeError(\"Upload literals are not supported.\");\n },\n serialize: (value) => value,\n },\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const jsonObjectScalar = defineCatalogScalar({\n name: \"JSONObject\",\n typescriptType: null,\n zodSource: null,\n schema: z.record(z.string(), z.unknown()),\n representation: \"json-object\",\n});\n","import { unknownScalar } from \"./declarations/unknown.js\";\nimport { dateTimeScalar } from \"./declarations/date-time.js\";\nimport { addressScalar } from \"./declarations/address.js\";\nimport { attachmentRefScalar } from \"./declarations/attachment-ref.js\";\nimport { amountTokensScalar } from \"./declarations/amount-tokens.js\";\nimport { ethereumAddressScalar } from \"./declarations/ethereum-address.js\";\nimport { emailAddressScalar } from \"./declarations/email-address.js\";\nimport { amountPercentageScalar } from \"./declarations/amount-percentage.js\";\nimport { dateScalar } from \"./declarations/date.js\";\nimport { urlScalar } from \"./declarations/url.js\";\nimport { amountMoneyScalar } from \"./declarations/amount-money.js\";\nimport { olabelScalar } from \"./declarations/olabel.js\";\nimport { currencyScalar } from \"./declarations/currency.js\";\nimport { phidScalar } from \"./declarations/phid.js\";\nimport { oidScalar } from \"./declarations/oid.js\";\nimport { amountFiatScalar } from \"./declarations/amount-fiat.js\";\nimport { amountCurrencyScalar } from \"./declarations/amount-currency.js\";\nimport { amountCryptoScalar } from \"./declarations/amount-crypto.js\";\nimport { amountScalar } from \"./declarations/amount.js\";\nimport { uploadScalar } from \"./declarations/upload.js\";\nimport { jsonObjectScalar } from \"./declarations/json-object.js\";\nimport type { DescribedScalarDefinition } from \"./types.js\";\n\nconst declarations = [\n unknownScalar,\n dateTimeScalar,\n addressScalar,\n attachmentRefScalar,\n amountTokensScalar,\n ethereumAddressScalar,\n emailAddressScalar,\n amountPercentageScalar,\n dateScalar,\n urlScalar,\n amountMoneyScalar,\n olabelScalar,\n currencyScalar,\n phidScalar,\n oidScalar,\n amountFiatScalar,\n amountCurrencyScalar,\n amountCryptoScalar,\n amountScalar,\n uploadScalar,\n jsonObjectScalar,\n] as const;\n\nexport type CatalogScalarDefinition = (typeof declarations)[number];\n\nexport const scalarCatalog: readonly DescribedScalarDefinition[] =\n Object.freeze([...declarations]);\n\nconst byName = new Map(\n scalarCatalog.map((definition) => [definition.name, definition]),\n);\n\nexport function getCatalogScalar(\n name: string,\n): DescribedScalarDefinition | undefined {\n return byName.get(name);\n}\n\ntype DocumentModelScalar = DescribedScalarDefinition & {\n readonly typescriptType: string;\n readonly zodSource: string;\n};\n\n// A model's SDL may use every catalog scalar codegen can type. JSONObject is\n// host-only, so it has neither a TypeScript type nor a zod source.\nexport const documentModelScalars: readonly DocumentModelScalar[] =\n Object.freeze(\n scalarCatalog.filter(\n (definition): definition is DocumentModelScalar =>\n definition.typescriptType !== null && definition.zodSource !== null,\n ),\n );\n","import type {\n DefinitionDiagnostic,\n DefinitionRef,\n} from \"@powerhousedao/shared/document-model\";\nimport {\n type DefinitionDiagnosticInput,\n DefinitionError,\n type DiagnosticCatalog,\n type DiagnosticCode,\n sortDefinitionDiagnostics,\n} from \"./diagnostics.js\";\n\nexport class DefinitionDiagnosticCollector<TCode extends DiagnosticCode> {\n readonly #catalog: DiagnosticCatalog<TCode>;\n readonly #definition: DefinitionRef | undefined;\n readonly #diagnostics: DefinitionDiagnostic[] = [];\n\n constructor(catalog: DiagnosticCatalog<TCode>, definition?: DefinitionRef) {\n this.#catalog = catalog;\n this.#definition = definition;\n }\n\n get diagnostics(): readonly DefinitionDiagnostic[] {\n return sortDefinitionDiagnostics(this.#diagnostics);\n }\n\n add(input: DefinitionDiagnosticInput<TCode>): void {\n this.#diagnostics.push(\n this.#catalog.create({\n ...(this.#definition !== undefined && { definition: this.#definition }),\n ...input,\n }),\n );\n }\n\n merge(diagnostics: readonly DefinitionDiagnostic[]): void {\n for (const diagnostic of diagnostics) {\n this.#diagnostics.push(\n this.#definition === undefined || diagnostic.definition !== undefined\n ? diagnostic\n : { ...diagnostic, definition: { ...this.#definition } },\n );\n }\n }\n\n capture<T>(attempt: () => T): T | undefined {\n try {\n return attempt();\n } catch (error) {\n if (!(error instanceof DefinitionError)) throw error;\n this.merge(error.diagnostics);\n return undefined;\n }\n }\n\n throwIfFailed(): void {\n if (!this.#diagnostics.some((entry) => entry.severity === \"error\")) return;\n throw new DefinitionError(\n this.#diagnostics as [DefinitionDiagnostic, ...DefinitionDiagnostic[]],\n );\n }\n}\n","import type { DefinitionPath } from \"@powerhousedao/shared/document-model\";\nimport { describeReceived } from \"./diagnostics.js\";\n\ntype DataLeaf = string | number | boolean | bigint | null | undefined;\n\nexport type DataValue =\n | DataLeaf\n | readonly DataValue[]\n | { readonly [key: string]: DataValue };\n\nexport type DataSnapshotRejection =\n | {\n readonly ok: false;\n readonly reason: \"not-record\";\n readonly path: DefinitionPath;\n readonly received: string;\n }\n | {\n readonly ok: false;\n readonly reason: \"not-array\";\n readonly path: DefinitionPath;\n readonly received: string;\n }\n | {\n readonly ok: false;\n readonly reason: \"custom-prototype\";\n readonly path: DefinitionPath;\n readonly expected: \"record\" | \"array\";\n readonly received: string;\n }\n | {\n readonly ok: false;\n readonly reason: \"symbol-key\";\n readonly path: DefinitionPath;\n readonly key: symbol;\n }\n | {\n readonly ok: false;\n readonly reason: \"unknown-key\";\n readonly path: DefinitionPath;\n readonly key: string;\n readonly allowedKeys: readonly string[];\n }\n | {\n readonly ok: false;\n readonly reason: \"accessor\";\n readonly path: DefinitionPath;\n readonly key: string | number;\n }\n | {\n readonly ok: false;\n readonly reason: \"non-enumerable\";\n readonly path: DefinitionPath;\n readonly key: string | number;\n }\n | {\n readonly ok: false;\n readonly reason: \"sparse\";\n readonly path: DefinitionPath;\n readonly key: number;\n }\n | {\n readonly ok: false;\n readonly reason: \"array-property\";\n readonly path: DefinitionPath;\n readonly key: string;\n }\n | {\n readonly ok: false;\n readonly reason: \"cycle\";\n readonly path: DefinitionPath;\n }\n | {\n readonly ok: false;\n readonly reason: \"not-data\";\n readonly path: DefinitionPath;\n readonly received: string;\n }\n | {\n readonly ok: false;\n readonly reason: \"inspection-failed\";\n readonly path: DefinitionPath;\n };\n\nexport type DataSnapshot<T> =\n | { readonly ok: true; readonly value: T }\n | DataSnapshotRejection;\n\nexport function rejectionReceived(rejection: DataSnapshotRejection): string {\n return \"received\" in rejection ? rejection.received : rejection.reason;\n}\n\nconst CANONICAL_INDEX = /^(?:0|[1-9][0-9]*)$/;\n\nexport function snapshotDataRecord(\n value: unknown,\n allowedKeys: readonly string[] | undefined,\n path: DefinitionPath,\n): DataSnapshot<{ readonly [key: string]: DataValue }> {\n return snapshotPlainObject(\n value,\n allowedKeys,\n path,\n snapshotDataValue,\n new Set(),\n );\n}\n\nexport function snapshotDataArray(\n value: unknown,\n path: DefinitionPath,\n): DataSnapshot<readonly DataValue[]> {\n return snapshotArrayValue(value, path, snapshotDataValue, new Set());\n}\n\nexport function snapshotArray(\n value: unknown,\n path: DefinitionPath,\n): DataSnapshot<readonly unknown[]> {\n return snapshotArrayValue<unknown>(\n value,\n path,\n (member) => ({ ok: true, value: member }),\n new Set(),\n );\n}\n\ntype MemberSnapshot<T> = (\n value: unknown,\n path: DefinitionPath,\n ancestors: Set<object>,\n) => DataSnapshot<T>;\n\nfunction snapshotArrayValue<T>(\n value: unknown,\n path: DefinitionPath,\n member: MemberSnapshot<T>,\n ancestors: Set<object>,\n): DataSnapshot<readonly T[]> {\n try {\n if (!Array.isArray(value)) {\n return {\n ok: false,\n reason: \"not-array\",\n path,\n received: describeReceived(value),\n };\n }\n } catch {\n return { ok: false, reason: \"inspection-failed\", path };\n }\n if (ancestors.has(value)) {\n return { ok: false, reason: \"cycle\", path };\n }\n ancestors.add(value);\n try {\n return snapshotArrayMembers(value, path, member, ancestors);\n } finally {\n ancestors.delete(value);\n }\n}\n\nfunction snapshotArrayMembers<T>(\n value: readonly unknown[],\n path: DefinitionPath,\n member: MemberSnapshot<T>,\n ancestors: Set<object>,\n): DataSnapshot<readonly T[]> {\n let prototype: unknown;\n let keys: readonly (string | symbol)[];\n let lengthDescriptor: PropertyDescriptor | undefined;\n try {\n prototype = Object.getPrototypeOf(value);\n keys = Reflect.ownKeys(value);\n lengthDescriptor = Object.getOwnPropertyDescriptor(value, \"length\");\n } catch {\n return { ok: false, reason: \"inspection-failed\", path };\n }\n if (prototype !== Array.prototype) {\n return {\n ok: false,\n reason: \"custom-prototype\",\n path,\n expected: \"array\",\n received: \"array of another prototype or realm\",\n };\n }\n const length: unknown = lengthDescriptor?.value;\n if (\n typeof length !== \"number\" ||\n !Number.isSafeInteger(length) ||\n length < 0\n ) {\n return { ok: false, reason: \"inspection-failed\", path };\n }\n for (const key of keys) {\n if (key === \"length\") continue;\n if (typeof key === \"symbol\") {\n return { ok: false, reason: \"symbol-key\", path, key };\n }\n if (!CANONICAL_INDEX.test(key) || Number(key) >= length) {\n return { ok: false, reason: \"array-property\", path: [...path, key], key };\n }\n }\n const elements: T[] = [];\n for (let index = 0; index < length; index += 1) {\n const elementPath = [...path, index];\n let descriptor: PropertyDescriptor | undefined;\n try {\n descriptor = Object.getOwnPropertyDescriptor(value, index);\n } catch {\n return { ok: false, reason: \"inspection-failed\", path: elementPath };\n }\n if (descriptor === undefined) {\n return { ok: false, reason: \"sparse\", path: elementPath, key: index };\n }\n const propertyValue = dataPropertyValue(descriptor, index, elementPath);\n if (!propertyValue.ok) return propertyValue;\n const element = member(propertyValue.value, elementPath, ancestors);\n if (!element.ok) return element;\n elements.push(element.value);\n }\n return { ok: true, value: Object.freeze(elements) };\n}\n\nexport function snapshotRecord(\n value: unknown,\n allowedKeys: readonly string[] | undefined,\n path: DefinitionPath,\n ignoredKeys: readonly string[] = [],\n): DataSnapshot<{ readonly [key: string]: unknown }> {\n return snapshotPlainObject<unknown>(\n value,\n allowedKeys,\n path,\n (member) => ({ ok: true, value: member }),\n new Set(),\n ignoredKeys,\n );\n}\n\nfunction snapshotPlainObject<T>(\n value: unknown,\n allowedKeys: readonly string[] | undefined,\n path: DefinitionPath,\n member: (\n value: unknown,\n path: DefinitionPath,\n ancestors: Set<object>,\n ) => DataSnapshot<T>,\n ancestors: Set<object>,\n ignoredKeys: readonly string[] = [],\n): DataSnapshot<{ readonly [key: string]: T }> {\n if (value === null || typeof value !== \"object\") {\n return {\n ok: false,\n reason: \"not-record\",\n path,\n received: describeReceived(value),\n };\n }\n if (ancestors.has(value)) {\n return { ok: false, reason: \"cycle\", path };\n }\n ancestors.add(value);\n try {\n return snapshotPlainObjectMembers(\n value,\n allowedKeys,\n path,\n member,\n ancestors,\n ignoredKeys,\n );\n } finally {\n ancestors.delete(value);\n }\n}\n\nfunction snapshotPlainObjectMembers<T>(\n value: object,\n allowedKeys: readonly string[] | undefined,\n path: DefinitionPath,\n member: (\n value: unknown,\n path: DefinitionPath,\n ancestors: Set<object>,\n ) => DataSnapshot<T>,\n ancestors: Set<object>,\n ignoredKeys: readonly string[],\n): DataSnapshot<{ readonly [key: string]: T }> {\n let isArray: boolean;\n let prototype: unknown;\n let keys: readonly (string | symbol)[];\n try {\n isArray = Array.isArray(value);\n prototype = Object.getPrototypeOf(value);\n keys = Reflect.ownKeys(value);\n } catch {\n return { ok: false, reason: \"inspection-failed\", path };\n }\n if (isArray) {\n return { ok: false, reason: \"not-record\", path, received: \"array\" };\n }\n if (prototype !== Object.prototype && prototype !== null) {\n return {\n ok: false,\n reason: \"custom-prototype\",\n path,\n expected: \"record\",\n received: \"object\",\n };\n }\n const entries: [string, T][] = [];\n for (const key of keys) {\n if (typeof key === \"symbol\") {\n return { ok: false, reason: \"symbol-key\", path, key };\n }\n if (ignoredKeys.includes(key)) continue;\n const memberPath = [...path, key];\n if (allowedKeys !== undefined && !allowedKeys.includes(key)) {\n return {\n ok: false,\n reason: \"unknown-key\",\n path: memberPath,\n key,\n allowedKeys,\n };\n }\n let descriptor: PropertyDescriptor | undefined;\n try {\n descriptor = Object.getOwnPropertyDescriptor(value, key);\n } catch {\n return { ok: false, reason: \"inspection-failed\", path: memberPath };\n }\n if (descriptor === undefined) {\n return { ok: false, reason: \"inspection-failed\", path: memberPath };\n }\n const propertyValue = dataPropertyValue(descriptor, key, memberPath);\n if (!propertyValue.ok) return propertyValue;\n const snapshot = member(propertyValue.value, memberPath, ancestors);\n if (!snapshot.ok) return snapshot;\n entries.push([key, snapshot.value]);\n }\n // `Object.fromEntries` defines own properties, so an own \"__proto__\" key stays\n // an own key instead of silently becoming the prototype as plain assignment would.\n return { ok: true, value: Object.freeze(Object.fromEntries(entries)) };\n}\n\nfunction dataPropertyValue(\n descriptor: PropertyDescriptor,\n key: string | number,\n path: DefinitionPath,\n): DataSnapshot<unknown> {\n if (!(\"value\" in descriptor)) {\n return { ok: false, reason: \"accessor\", path, key };\n }\n if (!descriptor.enumerable) {\n return { ok: false, reason: \"non-enumerable\", path, key };\n }\n const value: unknown = descriptor.value;\n return { ok: true, value };\n}\n\nfunction snapshotDataValue(\n value: unknown,\n path: DefinitionPath,\n ancestors: Set<object>,\n): DataSnapshot<DataValue> {\n switch (typeof value) {\n case \"string\":\n case \"number\":\n case \"boolean\":\n case \"bigint\":\n case \"undefined\":\n return { ok: true, value };\n case \"function\":\n return { ok: false, reason: \"not-data\", path, received: \"function\" };\n case \"symbol\":\n return { ok: false, reason: \"not-data\", path, received: \"symbol\" };\n case \"object\": {\n if (value === null) return { ok: true, value };\n let isArray: boolean;\n try {\n isArray = Array.isArray(value);\n } catch {\n return { ok: false, reason: \"inspection-failed\", path };\n }\n return isArray\n ? snapshotArrayValue(value, path, snapshotDataValue, ancestors)\n : snapshotPlainObject(\n value,\n undefined,\n path,\n snapshotDataValue,\n ancestors,\n );\n }\n }\n}\n","import { defineDiagnosticCatalog } from \"./diagnostics.js\";\n\nexport const kernelDiagnostics = defineDiagnosticCatalog({\n \"PH-DEF-OPTION-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"An option is malformed: wrong type, accessor, symbol key, non-plain object, an explicit undefined or non-JSON default, or an @equals pattern the generator cannot write\",\n },\n \"PH-DEF-COMPATIBILITY-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"A location-free GraphQL compatibility AST is malformed or disagrees with the stored definitions it accompanies\",\n },\n});\n","import { kernelDiagnostics } from \"./diagnostic-codes.js\";\nimport type {\n DefinitionDiagnostic,\n DefinitionPath,\n DefinitionRelatedLocation,\n DirectiveUseDefinition,\n GraphQLConstValueNode,\n GraphQLDirectiveNode,\n GraphQLEnumValueDefinitionNode,\n GraphQLFieldDefinitionNode,\n GraphQLInputValueDefinitionNode,\n GraphQLStringValueNode,\n GraphQLTypeNode,\n GraphQLTypeSystemDefinitionNode,\n GraphQLTypeSystemExtensionNode,\n JsonValue,\n LocationFreeGraphQLDocumentNode,\n NamedGraphQLTypeDefinition,\n SchemaFirstGraphQLDocumentCompatibility,\n} from \"@powerhousedao/shared/document-model\";\nimport { rejectionReceived, snapshotRecord } from \"./data-properties.js\";\nimport { describeReceived } from \"./diagnostics.js\";\nimport { equalsPatternProblem } from \"./equals-pattern.js\";\nimport {\n canonicalJson,\n compareCodeUnits,\n EMPTY_INPUT_FIELD_NAME,\n} from \"./primitives.js\";\nimport { printTypeReference } from \"./printer.js\";\n\nconst AST_KINDS = {\n object: \"ObjectTypeDefinition\",\n interface: \"InterfaceTypeDefinition\",\n enum: \"EnumTypeDefinition\",\n union: \"UnionTypeDefinition\",\n input: \"InputObjectTypeDefinition\",\n} as const satisfies Record<NamedGraphQLTypeDefinition[\"kind\"], string>;\n\ntype NamedDefinitionKind = (typeof AST_KINDS)[keyof typeof AST_KINDS];\n\ntype NamedDefinitionNode = Extract<\n GraphQLTypeSystemDefinitionNode,\n { readonly kind: NamedDefinitionKind }\n>;\n\ntype NamedAstDefinition = {\n readonly kind: NamedDefinitionKind;\n readonly name: { readonly value: string };\n readonly description?: GraphQLStringValueNode;\n readonly directives?: readonly GraphQLDirectiveNode[];\n readonly interfaces?: readonly {\n readonly name: { readonly value: string };\n }[];\n readonly fields?: readonly (\n | GraphQLFieldDefinitionNode\n | GraphQLInputValueDefinitionNode\n )[];\n readonly values?: readonly GraphQLEnumValueDefinitionNode[];\n readonly types?: readonly { readonly name: { readonly value: string } }[];\n};\n\nconst EXTENSION_TARGETS = {\n ObjectTypeExtension: \"ObjectTypeDefinition\",\n InterfaceTypeExtension: \"InterfaceTypeDefinition\",\n EnumTypeExtension: \"EnumTypeDefinition\",\n UnionTypeExtension: \"UnionTypeDefinition\",\n InputObjectTypeExtension: \"InputObjectTypeDefinition\",\n} as const satisfies Record<string, NamedDefinitionKind>;\n\ntype NamedExtensionNode = Extract<\n GraphQLTypeSystemExtensionNode,\n { readonly kind: keyof typeof EXTENSION_TARGETS }\n>;\n\nconst KIND_SPELLING: Record<\n NamedDefinitionKind | \"ScalarTypeDefinition\",\n { readonly noun: string; readonly keyword: string }\n> = {\n ScalarTypeDefinition: { noun: \"a scalar\", keyword: \"scalar\" },\n ObjectTypeDefinition: { noun: \"an object type\", keyword: \"type\" },\n InterfaceTypeDefinition: { noun: \"an interface\", keyword: \"interface\" },\n EnumTypeDefinition: { noun: \"an enum\", keyword: \"enum\" },\n UnionTypeDefinition: { noun: \"a union\", keyword: \"union\" },\n InputObjectTypeDefinition: { noun: \"an input\", keyword: \"input\" },\n};\n\nconst MEMBER_LISTS = [\"fields\", \"values\", \"interfaces\", \"types\"] as const;\n\ntype MemberList = (typeof MEMBER_LISTS)[number];\n\ntype Member = { readonly name: { readonly value: string } };\n\ntype EffectiveTypeDefinition = {\n readonly node: NamedAstDefinition;\n readonly index: number;\n readonly contributors: ReadonlyMap<`${MemberList}:${string}`, number>;\n};\n\ntype FoldedTypeDefinitions = {\n readonly types: ReadonlyMap<string, EffectiveTypeDefinition>;\n readonly redefinitions: readonly {\n readonly name: string;\n readonly index: number;\n }[];\n readonly diagnostics: readonly DefinitionDiagnostic[];\n};\n\ntype TypeUnderFold = {\n readonly base: Omit<NamedAstDefinition, \"kind\">;\n readonly kind: NamedDefinitionKind;\n readonly index: number;\n readonly contributors: Map<`${MemberList}:${string}`, number>;\n readonly lists: Partial<Record<MemberList, Member[]>>;\n readonly directives: GraphQLDirectiveNode[];\n};\n\nfunction isNamedDefinition(node: {\n readonly kind: string;\n}): node is NamedDefinitionNode {\n return Object.values(AST_KINDS).includes(node.kind as NamedDefinitionKind);\n}\n\nfunction isNamedExtension(node: {\n readonly kind: string;\n}): node is NamedExtensionNode {\n return Object.hasOwn(EXTENSION_TARGETS, node.kind);\n}\n\n/**\n * Folds every extension into the type it extends. A repeated definition or\n * member keeps its first occurrence and is reported; an extension-only type\n * starts from its first extension.\n */\nexport function foldTypeExtensions(\n definitions: LocationFreeGraphQLDocumentNode[\"definitions\"],\n path: DefinitionPath,\n): FoldedTypeDefinitions {\n const types = new Map<string, TypeUnderFold>();\n const redefinitions: { name: string; index: number }[] = [];\n const diagnostics: DefinitionDiagnostic[] = [];\n const memberPath = (index: number, list: MemberList, name: string) => [\n ...path,\n \"definitions\",\n index,\n list,\n name,\n ];\n const addMembers = (\n target: TypeUnderFold,\n node: Partial<Record<MemberList, readonly Member[]>>,\n index: number,\n ): void => {\n for (const list of MEMBER_LISTS) {\n const members = node[list];\n if (members === undefined) continue;\n for (const member of members) {\n const name = member.name.value;\n const key = `${list}:${name}` as const;\n const first = target.contributors.get(key);\n if (first !== undefined) {\n const coordinate = `${target.base.name.value}.${name}`;\n diagnostics.push(\n compatibilityDiagnostic(\n memberPath(index, list, name),\n `${coordinate} is defined more than once.`,\n {\n expected: \"one definition per member\",\n received: \"a second definition\",\n repair: `Remove the repeated ${name}; the host rejects a member defined twice.`,\n related: [\n {\n path: memberPath(first, list, name),\n message: `${coordinate} is first defined here.`,\n },\n ],\n },\n ),\n );\n continue;\n }\n target.contributors.set(key, index);\n target.lists[list]?.push(member);\n }\n }\n };\n const start = (\n node: Omit<NamedAstDefinition, \"kind\">,\n kind: NamedDefinitionKind,\n index: number,\n ): TypeUnderFold => {\n const folding: TypeUnderFold = {\n base: node,\n kind,\n index,\n contributors: new Map(),\n lists: Object.fromEntries(\n MEMBER_LISTS.filter((list) => node[list] !== undefined).map((list) => [\n list,\n [],\n ]),\n ),\n directives: [...(node.directives ?? [])],\n };\n addMembers(folding, node, index);\n return folding;\n };\n\n const scalars = new Set<string>();\n const wrongKind = (\n index: number,\n name: string,\n defined: keyof typeof KIND_SPELLING,\n extension: { readonly kind: string },\n extendedAs: keyof typeof KIND_SPELLING,\n ): void => {\n diagnostics.push(\n compatibilityDiagnostic(\n [...path, \"definitions\", index],\n `${name} is ${KIND_SPELLING[defined].noun}, so it cannot be extended as ${KIND_SPELLING[extendedAs].noun}.`,\n {\n expected: defined.replace(\"Definition\", \"Extension\"),\n received: extension.kind,\n repair: `Extend ${name} with \"extend ${KIND_SPELLING[defined].keyword}\", or remove the extension; the host rejects an extension of a different kind.`,\n },\n ),\n );\n };\n const foldScalarExtensions = (\n foldedTypes: ReadonlyMap<string, TypeUnderFold>,\n ): void => {\n definitions.forEach((node, index) => {\n if (node.kind !== \"ScalarTypeExtension\") return;\n const target = foldedTypes.get(node.name.value);\n if (target !== undefined) {\n wrongKind(\n index,\n node.name.value,\n target.kind,\n node,\n \"ScalarTypeDefinition\",\n );\n }\n });\n };\n\n definitions.forEach((node, index) => {\n if (node.kind === \"ScalarTypeDefinition\") {\n scalars.add(\n (node as GraphQLTypeSystemDefinitionNode & Member).name.value,\n );\n return;\n }\n if (!isNamedDefinition(node)) return;\n const name = node.name.value;\n if (types.has(name)) {\n redefinitions.push({ name, index });\n return;\n }\n types.set(name, start(node, node.kind, index));\n });\n\n definitions.forEach((node, index) => {\n if (!isNamedExtension(node)) return;\n const kind = EXTENSION_TARGETS[node.kind];\n const name = node.name.value;\n const target = types.get(name);\n if (target === undefined) {\n if (scalars.has(name)) {\n wrongKind(index, name, \"ScalarTypeDefinition\", node, kind);\n return;\n }\n types.set(name, start(node, kind, index));\n return;\n }\n if (target.kind !== kind) {\n wrongKind(index, name, target.kind, node, kind);\n return;\n }\n target.directives.push(...node.directives);\n addMembers(target, node, index);\n });\n\n foldScalarExtensions(types);\n\n return {\n types: new Map(\n [...types].map(\n ([name, { base, kind, index, contributors, lists, directives }]) => [\n name,\n {\n node: { ...base, kind, directives, ...lists } as NamedAstDefinition,\n index,\n contributors,\n },\n ],\n ),\n ),\n redefinitions,\n diagnostics,\n };\n}\n\nfunction compatibilityDiagnostic(\n path: DefinitionPath,\n message: string,\n detail: {\n readonly expected?: string;\n readonly received?: string;\n readonly repair?: string;\n readonly related?: readonly DefinitionRelatedLocation[];\n } = {},\n): DefinitionDiagnostic {\n return kernelDiagnostics.create({\n code: \"PH-DEF-COMPATIBILITY-INVALID\",\n path,\n message,\n ...(detail.expected !== undefined && { expected: detail.expected }),\n ...(detail.received !== undefined && { received: detail.received }),\n ...(detail.related !== undefined && { related: detail.related }),\n repair:\n detail.repair ??\n \"Regenerate the compatibility AST from the schema this declaration replaces, or change the descriptors to agree with it.\",\n });\n}\n\nconst ARRAY_INDEX = /^(?:0|[1-9][0-9]*)$/;\n\nexport function validateLocationFreeDocument(\n value: unknown,\n path: DefinitionPath,\n): readonly DefinitionDiagnostic[] {\n const diagnostics: DefinitionDiagnostic[] = [];\n const refuse = (at: DefinitionPath, message: string, received: string) =>\n diagnostics.push(\n compatibilityDiagnostic(at, message, {\n expected: \"JSON data\",\n received,\n repair:\n \"Keep only JSON data in the AST: strings, finite numbers, booleans, null, plain arrays and plain objects with data properties.\",\n }),\n );\n const ancestors = new Set<object>();\n const visitProperty = (\n owner: object,\n key: string | number,\n at: DefinitionPath,\n ): void => {\n const descriptor = Object.getOwnPropertyDescriptor(owner, key);\n if (descriptor === undefined) {\n refuse(at, \"A compatibility AST array must not have holes.\", \"hole\");\n } else if (!(\"value\" in descriptor)) {\n refuse(\n at,\n \"A compatibility AST must hold data properties, not accessors.\",\n \"accessor\",\n );\n } else {\n visit(descriptor.value, at);\n }\n };\n const visit = (node: unknown, at: DefinitionPath): void => {\n if (\n node === null ||\n typeof node === \"string\" ||\n typeof node === \"boolean\"\n ) {\n return;\n }\n if (typeof node === \"number\") {\n if (!Number.isFinite(node)) {\n refuse(at, \"A compatibility AST number must be finite.\", String(node));\n }\n return;\n }\n if (typeof node !== \"object\") {\n refuse(\n at,\n `A compatibility AST must contain JSON data only, received ${typeof node}.`,\n typeof node,\n );\n return;\n }\n if (ancestors.has(node)) {\n refuse(at, \"A compatibility AST must not contain a cycle.\", \"cycle\");\n return;\n }\n const prototype: unknown = Object.getPrototypeOf(node);\n const isArray = Array.isArray(node);\n if (\n isArray\n ? prototype !== Array.prototype\n : prototype !== Object.prototype && prototype !== null\n ) {\n refuse(\n at,\n \"A compatibility AST must hold plain arrays and plain objects only.\",\n describeReceived(node),\n );\n return;\n }\n ancestors.add(node);\n for (const key of Reflect.ownKeys(node)) {\n if (typeof key === \"symbol\") {\n refuse(at, \"A compatibility AST must not have symbol keys.\", \"symbol\");\n } else if (isArray) {\n if (key !== \"length\" && !ARRAY_INDEX.test(key)) {\n refuse(\n [...at, key],\n \"A compatibility AST array must hold only its items.\",\n key,\n );\n }\n } else if (key === \"loc\") {\n diagnostics.push(\n compatibilityDiagnostic(\n [...at, key],\n \"A compatibility AST must be location free.\",\n {\n expected: \"no loc property\",\n received: \"loc\",\n repair: \"Strip every loc property from the AST.\",\n },\n ),\n );\n } else {\n visitProperty(node, key, [...at, key]);\n }\n }\n if (isArray) {\n for (let index = 0; index < node.length; index += 1) {\n visitProperty(node, index, [...at, index]);\n }\n }\n ancestors.delete(node);\n };\n visit(value, path);\n return diagnostics;\n}\n\nfunction printAstType(node: GraphQLTypeNode): string {\n switch (node.kind) {\n case \"NamedType\":\n return node.name.value;\n case \"ListType\":\n return `[${printAstType(node.type)}]`;\n case \"NonNullType\":\n return `${printAstType(node.type)}!`;\n }\n}\n\nfunction astValue(node: GraphQLConstValueNode): JsonValue {\n switch (node.kind) {\n case \"IntValue\":\n case \"FloatValue\":\n return Number(node.value);\n case \"StringValue\":\n case \"EnumValue\":\n return node.value;\n case \"BooleanValue\":\n return node.value;\n case \"NullValue\":\n return null;\n case \"ListValue\":\n return node.values.map(astValue);\n case \"ObjectValue\":\n return Object.fromEntries(\n node.fields.map((field) => [field.name.value, astValue(field.value)]),\n );\n }\n}\n\nconst DEFAULT_DEPRECATION_REASON = \"No longer supported\";\n\nfunction astDeprecation(\n directives: readonly GraphQLDirectiveNode[] | undefined,\n): string | null {\n const directive = (directives ?? []).find(\n (candidate) => candidate.name.value === \"deprecated\",\n );\n if (directive === undefined) return null;\n const reason = directive.arguments.find(\n (argument) => argument.name.value === \"reason\",\n );\n if (reason === undefined) return DEFAULT_DEPRECATION_REASON;\n return reason.value.kind === \"StringValue\" ? reason.value.value : null;\n}\n\nfunction astEquals(\n directives: readonly GraphQLDirectiveNode[] | undefined,\n): string | null {\n const value = (directives ?? [])\n .find((directive) => directive.name.value === \"equals\")\n ?.arguments.find((argument) => argument.name.value === \"value\")?.value;\n return value !== undefined &&\n \"value\" in value &&\n typeof value.value === \"string\"\n ? value.value\n : null;\n}\n\nfunction definitionEquals(field: {\n readonly directives?: readonly DirectiveUseDefinition[];\n}): string | null {\n const value = field.directives\n ?.find((directive) => directive.name === \"equals\")\n ?.arguments.find((argument) => argument.name === \"value\")?.value;\n return typeof value === \"string\" ? value : null;\n}\n\nfunction printEquals(equals: string | null): string {\n return equals === null\n ? \"no @equals\"\n : `@equals(value: ${JSON.stringify(equals)})`;\n}\n\ntype FieldFingerprint = {\n readonly name: string;\n readonly type: string;\n readonly defaultValue: string | null;\n readonly description: string | null;\n readonly deprecated: string | null;\n readonly equals: string | null;\n};\n\ntype TypeFingerprint = {\n readonly kind: string;\n readonly name: string;\n readonly description: string | null;\n readonly implemented: readonly string[];\n readonly fields: readonly FieldFingerprint[];\n readonly members: readonly string[];\n};\n\nfunction descriptorFingerprint(\n definition: NamedGraphQLTypeDefinition,\n): TypeFingerprint {\n const fields =\n definition.kind === \"enum\"\n ? definition.values.map((value): FieldFingerprint => ({\n name: value.name,\n type: \"\",\n defaultValue: null,\n description: value.description,\n deprecated: value.deprecated,\n equals: null,\n }))\n : definition.kind === \"union\"\n ? []\n : definition.kind === \"input\" && definition.fields.length === 0\n ? [\n {\n name: EMPTY_INPUT_FIELD_NAME,\n type: \"Boolean\",\n defaultValue: null,\n description: null,\n deprecated: null,\n equals: null,\n },\n ]\n : definition.fields.map((field): FieldFingerprint => {\n const hasDefault = Object.hasOwn(field, \"defaultValue\");\n return {\n name: field.name,\n type: printTypeReference(field.type),\n defaultValue: hasDefault\n ? canonicalJson(\n (field as { readonly defaultValue: JsonValue })\n .defaultValue,\n )\n : null,\n description: field.description,\n deprecated: field.deprecated,\n equals: definitionEquals(field),\n };\n });\n return {\n kind: AST_KINDS[definition.kind],\n name: definition.name,\n description: definition.description,\n implemented:\n definition.kind === \"object\" || definition.kind === \"interface\"\n ? (definition.implements ?? [])\n : [],\n fields,\n members: definition.kind === \"union\" ? definition.members : [],\n };\n}\n\nfunction astFingerprint(node: NamedAstDefinition): TypeFingerprint {\n const fields =\n node.kind === AST_KINDS.enum\n ? (node.values ?? []).map((value): FieldFingerprint => ({\n name: value.name.value,\n type: \"\",\n defaultValue: null,\n description: value.description?.value ?? null,\n deprecated: astDeprecation(value.directives),\n equals: null,\n }))\n : (node.fields ?? []).map((field): FieldFingerprint => {\n const defaultValue = (field as GraphQLInputValueDefinitionNode)\n .defaultValue;\n return {\n name: field.name.value,\n type: printAstType(field.type),\n defaultValue:\n defaultValue === undefined\n ? null\n : canonicalJson(astValue(defaultValue)),\n description: field.description?.value ?? null,\n deprecated: astDeprecation(field.directives),\n equals: astEquals(field.directives),\n };\n });\n return {\n kind: node.kind,\n name: node.name.value,\n description: node.description?.value ?? null,\n implemented: (node.interfaces ?? []).map(\n (implemented) => implemented.name.value,\n ),\n fields,\n members: (node.types ?? []).map((member) => member.name.value),\n };\n}\n\ntype ExtensionSource = {\n readonly documentPath: DefinitionPath;\n readonly effective: EffectiveTypeDefinition;\n};\n\nfunction missingMemberRepair(\n kind: NamedDefinitionKind,\n typeName: string,\n member: string,\n): string {\n switch (kind) {\n case \"EnumTypeDefinition\":\n return `Add the value \"${member}\" to the definition of enum ${typeName}.`;\n case \"UnionTypeDefinition\":\n return `Add the member ${member} to the definition of union ${typeName}.`;\n default:\n return `Add a \"${member}\" field to the definition of ${typeName}.`;\n }\n}\n\nfunction compareFields(\n descriptor: TypeFingerprint,\n ast: TypeFingerprint,\n path: DefinitionPath,\n memberNoun: \"field\" | \"enum value\",\n source: ExtensionSource,\n): readonly DefinitionDiagnostic[] {\n const diagnostics: DefinitionDiagnostic[] = [];\n const astFields = new Map(ast.fields.map((field) => [field.name, field]));\n const list: MemberList = memberNoun === \"enum value\" ? \"values\" : \"fields\";\n for (const field of descriptor.fields) {\n const match = astFields.get(field.name);\n if (match === undefined) {\n diagnostics.push(\n compatibilityDiagnostic(\n [...path, field.name],\n `${descriptor.name}.${field.name} is declared by the descriptors and absent from the compatibility AST.`,\n {\n expected: `${memberNoun} ${field.name}`,\n received: \"absent\",\n },\n ),\n );\n continue;\n }\n astFields.delete(field.name);\n const contributor = source.effective.contributors.get(\n `${list}:${field.name}`,\n );\n const coordinate =\n contributor === undefined || contributor === source.effective.index\n ? [...path, field.name]\n : [\n ...source.documentPath,\n \"definitions\",\n contributor,\n list,\n field.name,\n ];\n if (field.type !== match.type) {\n diagnostics.push(\n compatibilityDiagnostic(\n [...coordinate, \"type\"],\n `${descriptor.name}.${field.name} has a different type in the compatibility AST.`,\n { expected: field.type, received: match.type },\n ),\n );\n }\n if (field.defaultValue !== match.defaultValue) {\n diagnostics.push(\n compatibilityDiagnostic(\n [...coordinate, \"defaultValue\"],\n `${descriptor.name}.${field.name} has a different default value in the compatibility AST.`,\n {\n expected: field.defaultValue ?? \"no default\",\n received: match.defaultValue ?? \"no default\",\n repair: `Remove the default from the compatibility AST, or declare a defaultValue the field's type accepts on the descriptor field ${descriptor.name}.${field.name}.`,\n },\n ),\n );\n }\n if (field.description !== match.description) {\n diagnostics.push(\n compatibilityDiagnostic(\n [...coordinate, \"description\"],\n `${descriptor.name}.${field.name} has a different description in the compatibility AST.`,\n {\n expected: field.description ?? \"no description\",\n received: match.description ?? \"no description\",\n },\n ),\n );\n }\n if (field.deprecated !== match.deprecated) {\n diagnostics.push(\n compatibilityDiagnostic(\n [...coordinate, \"deprecated\"],\n `${descriptor.name}.${field.name} has a different deprecation in the compatibility AST.`,\n {\n expected: field.deprecated ?? \"not deprecated\",\n received: match.deprecated ?? \"not deprecated\",\n },\n ),\n );\n }\n const astProblem =\n match.equals === null ? undefined : equalsPatternProblem(match.equals);\n if (match.equals !== null && astProblem !== undefined) {\n diagnostics.push(\n kernelDiagnostics.create({\n code: \"PH-DEF-OPTION-INVALID\",\n path: [...coordinate, \"equals\"],\n received: match.equals,\n ...astProblem,\n }),\n );\n } else if (field.equals !== match.equals) {\n diagnostics.push(\n compatibilityDiagnostic(\n [...coordinate, \"equals\"],\n `${descriptor.name}.${field.name} has a different @equals in the compatibility AST.`,\n {\n expected: printEquals(field.equals),\n received: printEquals(match.equals),\n repair:\n match.equals === null\n ? `Remove @equals from the definition of ${descriptor.name}.${field.name}, or add ${printEquals(field.equals)} to the field in the AST.`\n : `Give the definition of ${descriptor.name}.${field.name} ${printEquals(match.equals)}.`,\n },\n ),\n );\n }\n }\n for (const extra of astFields.keys()) {\n const received = `${memberNoun} ${extra}`;\n diagnostics.push(\n extensionMemberDiagnostic(\n descriptor.name,\n list,\n extra,\n received,\n source,\n ) ??\n compatibilityDiagnostic(\n [...path, extra],\n `${descriptor.name}.${extra} is in the compatibility AST and not in the descriptors.`,\n { expected: \"absent\", received },\n ),\n );\n }\n return diagnostics;\n}\n\nfunction extensionMemberDiagnostic(\n typeName: string,\n list: MemberList,\n member: string,\n received: string,\n { documentPath, effective }: ExtensionSource,\n): DefinitionDiagnostic | undefined {\n const index = effective.contributors.get(`${list}:${member}`);\n if (index === undefined || index === effective.index) return undefined;\n const keyword = KIND_SPELLING[effective.node.kind].keyword;\n return compatibilityDiagnostic(\n [...documentPath, \"definitions\", index, list, member],\n `${typeName}.${member} is added by \"extend ${keyword} ${typeName}\" and missing from the descriptors.`,\n {\n expected: \"absent\",\n received,\n repair: missingMemberRepair(effective.node.kind, typeName, member),\n },\n );\n}\n\nfunction refusedV1Member(record: {\n readonly [key: string]: unknown;\n}): { readonly member: string; readonly received: string } | undefined {\n if (record.kind !== \"graphql-ast-v1\") {\n return { member: \"kind\", received: spelledMember(record.kind) };\n }\n if (record.preserveDefinitionOrder !== true) {\n return {\n member: \"preserveDefinitionOrder\",\n received: spelledMember(record.preserveDefinitionOrder),\n };\n }\n return undefined;\n}\n\nfunction spelledMember(value: unknown): string {\n return typeof value === \"string\" || typeof value === \"boolean\"\n ? String(value)\n : describeReceived(value);\n}\n\nfunction sameMembers(\n left: readonly string[],\n right: readonly string[],\n): boolean {\n return (\n canonicalJson([...left].sort(compareCodeUnits)) ===\n canonicalJson([...right].sort(compareCodeUnits))\n );\n}\n\nfunction dataProperty(owner: object, key: string): unknown {\n const descriptor = Object.getOwnPropertyDescriptor(owner, key);\n return descriptor !== undefined && \"value\" in descriptor\n ? descriptor.value\n : undefined;\n}\n\nfunction rootOperationTypeNames(\n document: LocationFreeGraphQLDocumentNode,\n): ReadonlySet<string> {\n const names = new Set<string>([\"Query\", \"Mutation\", \"Subscription\"]);\n for (const node of document.definitions) {\n if (node.kind !== \"SchemaDefinition\" && node.kind !== \"SchemaExtension\") {\n continue;\n }\n for (const operationType of node.operationTypes) {\n names.add(operationType.type.name.value);\n }\n }\n return names;\n}\n\nexport function checkGraphQLDocumentAgreement(options: {\n readonly compatibility: SchemaFirstGraphQLDocumentCompatibility;\n readonly definitions: readonly NamedGraphQLTypeDefinition[];\n readonly path: DefinitionPath;\n}): readonly DefinitionDiagnostic[] {\n const { definitions, path } = options;\n const compatibility = snapshotRecord(options.compatibility, undefined, path);\n const refuse = (at: DefinitionPath, received: string) => [\n compatibilityDiagnostic(\n at,\n \"A GraphQL compatibility declaration must be a V1 location-free document with preserveDefinitionOrder.\",\n {\n expected: 'kind \"graphql-ast-v1\" with preserveDefinitionOrder: true',\n received,\n repair:\n 'Pass a location-free GraphQL document as { kind: \"graphql-ast-v1\", document, preserveDefinitionOrder: true }.',\n },\n ),\n ];\n if (!compatibility.ok) {\n return refuse(compatibility.path, rejectionReceived(compatibility));\n }\n const refused = refusedV1Member(compatibility.value);\n if (refused !== undefined) {\n return refuse([...path, refused.member], refused.received);\n }\n const document: unknown = compatibility.value.document;\n if (\n document === null ||\n typeof document !== \"object\" ||\n dataProperty(document, \"kind\") !== \"Document\" ||\n !Array.isArray(dataProperty(document, \"definitions\"))\n ) {\n return [\n compatibilityDiagnostic(\n [...path, \"document\"],\n \"A GraphQL compatibility document must be a location-free Document node.\",\n {\n expected: 'a { kind: \"Document\", definitions: [...] } node',\n received: describeReceived(document),\n },\n ),\n ];\n }\n const shape = validateLocationFreeDocument(document, [...path, \"document\"]);\n if (shape.length > 0) return shape;\n const validated = document as LocationFreeGraphQLDocumentNode;\n\n const documentPath = [...path, \"document\"];\n const folded = foldTypeExtensions(validated.definitions, documentPath);\n const diagnostics: DefinitionDiagnostic[] = [\n ...folded.redefinitions.map(({ name }) =>\n compatibilityDiagnostic(\n [...documentPath, name],\n `The compatibility AST defines ${name} twice.`,\n { expected: \"one definition per type name\", received: \"two\" },\n ),\n ),\n ...folded.diagnostics,\n ];\n\n const compared = new Set<string>();\n for (const definition of definitions) {\n if (compared.has(definition.name)) continue;\n compared.add(definition.name);\n const coordinate = [...path, \"document\", definition.name];\n const effective = folded.types.get(definition.name);\n if (effective === undefined) {\n diagnostics.push(\n compatibilityDiagnostic(\n coordinate,\n `${definition.name} is declared by the descriptors and absent from the compatibility AST.`,\n { expected: definition.name, received: \"absent\" },\n ),\n );\n continue;\n }\n const descriptor = descriptorFingerprint(definition);\n const ast = astFingerprint(effective.node);\n if (descriptor.kind !== ast.kind) {\n diagnostics.push(\n compatibilityDiagnostic(\n coordinate,\n `${definition.name} is a different kind of type in the compatibility AST.`,\n { expected: descriptor.kind, received: ast.kind },\n ),\n );\n continue;\n }\n if (descriptor.description !== ast.description) {\n diagnostics.push(\n compatibilityDiagnostic(\n [...coordinate, \"description\"],\n `${definition.name} has a different description in the compatibility AST.`,\n {\n expected: descriptor.description ?? \"no description\",\n received: ast.description ?? \"no description\",\n },\n ),\n );\n }\n if (!sameMembers(descriptor.implemented, ast.implemented)) {\n diagnostics.push(\n compatibilityDiagnostic(\n [...coordinate, \"implements\"],\n `${definition.name} implements different interfaces in the compatibility AST.`,\n {\n expected: descriptor.implemented.join(\" & \") || \"none\",\n received: ast.implemented.join(\" & \") || \"none\",\n },\n ),\n );\n }\n if (!sameMembers(descriptor.members, ast.members)) {\n diagnostics.push(\n compatibilityDiagnostic(\n [...coordinate, \"members\"],\n `${definition.name} has different union members in the compatibility AST.`,\n {\n expected: descriptor.members.join(\" | \") || \"none\",\n received: ast.members.join(\" | \") || \"none\",\n },\n ),\n );\n }\n diagnostics.push(\n ...compareFields(\n descriptor,\n ast,\n [...coordinate, definition.kind === \"enum\" ? \"values\" : \"fields\"],\n definition.kind === \"enum\" ? \"enum value\" : \"field\",\n { documentPath, effective },\n ),\n );\n }\n\n const rootTypes = rootOperationTypeNames(validated);\n for (const [name, { node }] of folded.types) {\n if (compared.has(name) || rootTypes.has(name)) continue;\n diagnostics.push(\n compatibilityDiagnostic(\n [...path, \"document\", name],\n `The compatibility AST declares ${name}, which no descriptor represents.`,\n {\n expected: \"a descriptor for every named type in the AST\",\n received: node.kind,\n repair: `Add a definition for ${name}, or remove it from the AST.`,\n },\n ),\n );\n }\n return diagnostics;\n}\n","import { kernelDiagnostics } from \"../kernel/diagnostic-codes.js\";\nimport { defineDiagnosticCatalog } from \"../kernel/diagnostics.js\";\n\nexport const dslDiagnostics = defineDiagnosticCatalog(\n {\n \"PH-DEF-FIELD-OPTION-UNSUPPORTED\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"A field use contains an option its builder or its position does not support\",\n },\n \"PH-DEF-TYPE-AS-FIELD\": {\n severity: \"error\",\n phase: \"definition\",\n meaning: \"A named type is used as a field without ph.ref\",\n },\n \"PH-DEF-NAME-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"An authored GraphQL type, field, or enum value name is lexically invalid or reserved\",\n },\n \"PH-DEF-FIELD-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"A field position holds a value that is neither a field use nor a named type\",\n },\n \"PH-DEF-REFERENCE-TARGET-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"A ph.ref target is not a named type: a field use, another reference, undefined, or an anonymous input\",\n },\n \"PH-DEF-ENUM-VALUES-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"An enum declares no values, a duplicate value, or a reserved value\",\n },\n \"PH-DEF-UNION-MEMBERS-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"A union declares no members, a duplicate member, or a member that is not a ph.object\",\n },\n \"PH-DEF-IMPLEMENTS-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"An object or an interface implements something that is not a ph.interface, or the same interface twice\",\n },\n \"PH-SCALAR-FACTORY-AS-FIELD\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"A scalar field-use factory is used as a field without being called\",\n },\n \"PH-SCALAR-INTERNAL\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"A field uses a catalog scalar that only the reactor host declares, such as JSONObject\",\n },\n \"PH-SCALAR-DEFINITION-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"ph.scalar received a value that is not a scalar definition of this release's format\",\n },\n },\n kernelDiagnostics,\n);\n\nexport type DslDiagnosticCode = keyof typeof dslDiagnostics.codes;\n","import { dslDiagnostics } from \"../dsl/diagnostic-codes.js\";\nimport { defineDiagnosticCatalog } from \"../kernel/diagnostics.js\";\n\nexport const compilerDiagnostics = defineDiagnosticCatalog(\n {\n \"PH-DM-DUPLICATE-ACTION\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"Two operations derive the same persisted action type, or an operation derives one the document runtime owns\",\n },\n \"PH-DM-DUPLICATE-NAME\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"Two declarations derive the same module, GraphQL type, or creator name\",\n },\n \"PH-DM-IDENTITY-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"An identity segment, compatibility ID, or derived UUID violates the V1 contract\",\n },\n \"PH-DM-DECLARATION-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"A model, module, operation, error, example, version, or family declaration member is absent, malformed, unsupported, or forged\",\n },\n \"PH-DM-DEFAULT-UNSUPPORTED\": {\n severity: \"error\",\n phase: \"definition\",\n meaning: \"A document state field declares a GraphQL default value\",\n },\n \"PH-DM-INTERFACE-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"An object or interface does not satisfy an implemented interface's fields or ancestor requirements\",\n },\n \"PH-DM-INPUT-CYCLE\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"An input type contains itself through singular non-null input fields, so no finite value satisfies it\",\n },\n \"PH-DM-TYPE-POSITION-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"An input type is referenced from an output position, or an output type from an input position\",\n },\n \"PH-DM-INITIAL-VALUE-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"A scope initial value cannot produce a stored JSON string, or its own state validator rejects it\",\n },\n \"PH-SCALAR-DUPLICATE-NAME\": {\n severity: \"error\",\n phase: \"definition\",\n meaning: \"Two different project scalars of one model claim one name\",\n },\n },\n dslDiagnostics,\n);\n\nexport type CompilerDiagnosticCode = keyof typeof compilerDiagnostics.codes;\n","import type {\n DefinitionDiagnostic,\n DefinitionPath,\n JsonValue,\n} from \"@powerhousedao/shared/document-model\";\nimport { documentModelScalars, scalarCatalog } from \"../../scalars/catalog.js\";\nimport { DefinitionDiagnosticCollector } from \"../kernel/diagnostic-collector.js\";\nimport {\n rejectionReceived,\n snapshotArray,\n snapshotRecord,\n} from \"../kernel/data-properties.js\";\nimport { describeReceived } from \"../kernel/diagnostics.js\";\nimport { validateLocationFreeDocument } from \"../kernel/graphql-ast.js\";\nimport { canonicalJson, isGraphQLName } from \"../kernel/primitives.js\";\nimport {\n type CompilerDiagnosticCode,\n compilerDiagnostics,\n} from \"./diagnostic-codes.js\";\n\ntype Node = { readonly [key: string]: unknown };\n\nconst BUILT_IN_SCALARS = [\"ID\", \"String\", \"Boolean\", \"Int\", \"Float\"] as const;\nconst CATALOG_SCALARS = documentModelScalars.map(({ name }) => name);\nconst MODEL_SCALARS: ReadonlySet<string> = new Set([\n ...BUILT_IN_SCALARS,\n ...CATALOG_SCALARS,\n]);\nconst HOST_ONLY_SCALARS: ReadonlySet<string> = new Set(\n scalarCatalog\n .map(({ name }) => name)\n .filter((name) => !MODEL_SCALARS.has(name)),\n);\nconst SCALAR_REPRESENTATIONS = [\n \"string\",\n \"number\",\n \"boolean\",\n \"json-object\",\n \"json\",\n \"opaque\",\n] as const;\n\nclass ShapeChecker {\n readonly collector =\n new DefinitionDiagnosticCollector<CompilerDiagnosticCode>(\n compilerDiagnostics,\n );\n\n packageScalars: ReadonlySet<string> = new Set();\n\n fail(\n path: DefinitionPath,\n message: string,\n expected: string,\n received: unknown,\n ): undefined {\n this.collector.add({\n code: \"PH-DM-DECLARATION-INVALID\",\n path,\n message,\n expected,\n received:\n typeof received === \"string\"\n ? received\n : typeof received === \"number\" || typeof received === \"boolean\"\n ? String(received)\n : describeReceived(received),\n repair:\n \"Produce the definition with materialize or a document-model/tooling adapter; a hand-edited wire definition is not accepted.\",\n });\n return undefined;\n }\n\n record(\n value: unknown,\n keys: readonly string[],\n path: DefinitionPath,\n ): Node | undefined {\n const snapshot = snapshotRecord(value, keys, path);\n if (snapshot.ok) return snapshot.value;\n return this.fail(\n snapshot.path,\n `This node is not a plain object with the V1 members (${snapshot.reason}).`,\n keys.join(\", \"),\n rejectionReceived(snapshot),\n );\n }\n\n array(value: unknown, path: DefinitionPath): readonly unknown[] | undefined {\n const snapshot = snapshotArray(value, path);\n if (snapshot.ok) return snapshot.value;\n return this.fail(\n snapshot.path,\n \"This node must be an array.\",\n \"an array\",\n rejectionReceived(snapshot),\n );\n }\n\n string(value: unknown, path: DefinitionPath): string | undefined {\n if (typeof value === \"string\") return value;\n return this.fail(path, \"This member must be a string.\", \"string\", value);\n }\n\n nullableString(value: unknown, path: DefinitionPath): void {\n if (value === null || typeof value === \"string\") return;\n this.fail(\n path,\n \"This member must be a string or null.\",\n \"string | null\",\n value,\n );\n }\n\n literal(\n value: unknown,\n expected: string | number | boolean,\n path: DefinitionPath,\n ): void {\n if (value === expected) return;\n this.fail(path, \"This member has a fixed value.\", String(expected), value);\n }\n\n oneOf<T extends string>(\n value: unknown,\n allowed: readonly T[],\n path: DefinitionPath,\n ): T | undefined {\n if ((allowed as readonly unknown[]).includes(value)) return value as T;\n return this.fail(\n path,\n \"This member is outside its closed set.\",\n allowed.join(\" | \"),\n value,\n );\n }\n\n json(value: unknown, path: DefinitionPath): JsonValue | undefined {\n try {\n canonicalJson(value);\n } catch (error) {\n return this.fail(\n path,\n `This member must be a JSON value: ${error instanceof Error ? error.message : String(error)}`,\n \"a JSON value\",\n value,\n );\n }\n return value as JsonValue;\n }\n\n graphQLName(value: unknown, path: DefinitionPath): string | undefined {\n if (isGraphQLName(value)) return value;\n return this.fail(\n path,\n \"This member must be a GraphQL name.\",\n \"a GraphQL name\",\n value,\n );\n }\n\n rejectHostOnlyScalar(value: unknown, path: DefinitionPath): boolean {\n if (typeof value !== \"string\" || !HOST_ONLY_SCALARS.has(value)) {\n return false;\n }\n this.collector.add({\n code: \"PH-SCALAR-INTERNAL\",\n definition: { kind: \"scalar\", key: value },\n path,\n message: `${value} is internal to the reactor host. A document model cannot use it.`,\n received: value,\n repair:\n \"Use ph.Unknown() for an unconstrained value, or ph.object(...) for a structured one.\",\n });\n return true;\n }\n}\n\nfunction typeReference(\n check: ShapeChecker,\n value: unknown,\n path: DefinitionPath,\n): void {\n const kind = (value as Node | null)?.kind;\n const node =\n kind === \"list\"\n ? check.record(value, [\"kind\", \"required\", \"item\"], path)\n : check.record(value, [\"kind\", \"name\", \"required\"], path);\n if (node === undefined) return;\n if (typeof node.required !== \"boolean\") {\n check.fail(\n [...path, \"required\"],\n \"A type reference records nullability.\",\n \"boolean\",\n node.required,\n );\n }\n if (kind === \"list\") {\n typeReference(check, node.item, [...path, \"item\"]);\n } else if (kind === \"scalar\") {\n if (check.rejectHostOnlyScalar(node.name, [...path, \"name\"])) return;\n if (\n typeof node.name !== \"string\" ||\n !(MODEL_SCALARS.has(node.name) || check.packageScalars.has(node.name))\n ) {\n check.fail(\n [...path, \"name\"],\n \"A scalar reference names a catalog scalar, a GraphQL built-in, or a package scalar the specification declares.\",\n [...MODEL_SCALARS, ...check.packageScalars].join(\" | \"),\n node.name,\n );\n }\n } else if (kind === \"named\") {\n check.graphQLName(node.name, [...path, \"name\"]);\n } else {\n check.fail(\n [...path, \"kind\"],\n \"A type reference has three kinds.\",\n \"scalar | named | list\",\n kind,\n );\n }\n}\n\nfunction directiveUses(\n check: ShapeChecker,\n value: unknown,\n path: DefinitionPath,\n): void {\n check.array(value, path)?.forEach((use, index) => {\n const node = check.record(use, [\"name\", \"arguments\"], [...path, index]);\n if (node === undefined) return;\n check.graphQLName(node.name, [...path, index, \"name\"]);\n const args = check.array(node.arguments, [...path, index, \"arguments\"]);\n args?.forEach((argument, argumentIndex) => {\n const at = [...path, index, \"arguments\", argumentIndex];\n const entry = check.record(argument, [\"name\", \"value\"], at);\n if (entry === undefined) return;\n check.graphQLName(entry.name, [...at, \"name\"]);\n check.json(entry.value, [...at, \"value\"]);\n });\n });\n}\n\nconst FIELD_KEYS = [\"key\", \"name\", \"description\", \"deprecated\", \"type\"];\n\nfunction field(\n check: ShapeChecker,\n value: unknown,\n path: DefinitionPath,\n input: boolean,\n): void {\n const node = check.record(\n value,\n [...FIELD_KEYS, \"directives\", input ? \"defaultValue\" : \"args\"],\n path,\n );\n if (node === undefined) return;\n check.string(node.key, [...path, \"key\"]);\n check.graphQLName(node.name, [...path, \"name\"]);\n check.nullableString(node.description, [...path, \"description\"]);\n check.nullableString(node.deprecated, [...path, \"deprecated\"]);\n typeReference(check, node.type, [...path, \"type\"]);\n if (node.directives !== undefined) {\n directiveUses(check, node.directives, [...path, \"directives\"]);\n }\n if (input) {\n if (Object.hasOwn(node, \"defaultValue\")) {\n check.json(node.defaultValue, [...path, \"defaultValue\"]);\n }\n } else if (node.args !== undefined) {\n check\n .array(node.args, [...path, \"args\"])\n ?.forEach((argument, index) =>\n field(check, argument, [...path, \"args\", index], true),\n );\n }\n}\n\nfunction fields(\n check: ShapeChecker,\n value: unknown,\n path: DefinitionPath,\n input: boolean,\n): void {\n check\n .array(value, path)\n ?.forEach((entry, index) => field(check, entry, [...path, index], input));\n}\n\nfunction enumValue(\n check: ShapeChecker,\n value: unknown,\n path: DefinitionPath,\n): void {\n const node = check.record(\n value,\n [\"name\", \"description\", \"deprecated\", \"directives\"],\n path,\n );\n if (node === undefined) return;\n check.graphQLName(node.name, [...path, \"name\"]);\n check.nullableString(node.description, [...path, \"description\"]);\n check.nullableString(node.deprecated, [...path, \"deprecated\"]);\n if (node.directives !== undefined) {\n directiveUses(check, node.directives, [...path, \"directives\"]);\n }\n}\n\nconst NAMED_TYPE_MEMBERS = {\n enum: \"values\",\n object: \"fields\",\n interface: \"fields\",\n input: \"fields\",\n union: \"members\",\n} as const;\n\nfunction namedType(\n check: ShapeChecker,\n value: unknown,\n path: DefinitionPath,\n): string | undefined {\n const kind = (value as Node | null)?.kind;\n if (typeof kind !== \"string\" || !Object.hasOwn(NAMED_TYPE_MEMBERS, kind)) {\n return check.fail(\n [...path, \"kind\"],\n \"A named type has five kinds.\",\n Object.keys(NAMED_TYPE_MEMBERS).join(\" | \"),\n kind,\n );\n }\n const typed = kind as keyof typeof NAMED_TYPE_MEMBERS;\n const member = NAMED_TYPE_MEMBERS[typed];\n const extra =\n typed === \"object\" || typed === \"interface\"\n ? [\"implements\"]\n : typed === \"input\"\n ? [\"unknownKeys\"]\n : [];\n const node = check.record(\n value,\n [\"kind\", \"name\", \"description\", ...extra, member],\n path,\n );\n if (node === undefined) return undefined;\n check.nullableString(node.description, [...path, \"description\"]);\n const members = check.array(node[member], [...path, member]);\n switch (typed) {\n case \"enum\":\n members?.forEach((entry, index) =>\n enumValue(check, entry, [...path, \"values\", index]),\n );\n break;\n case \"union\":\n members?.forEach((entry, index) =>\n check.graphQLName(entry, [...path, \"members\", index]),\n );\n break;\n case \"input\":\n check.oneOf(\n node.unknownKeys,\n [\"preserve\", \"reject\"],\n [...path, \"unknownKeys\"],\n );\n fields(check, node.fields, [...path, \"fields\"], true);\n break;\n default:\n if (node.implements !== undefined) {\n check\n .array(node.implements, [...path, \"implements\"])\n ?.forEach((entry, index) =>\n check.graphQLName(entry, [...path, \"implements\", index]),\n );\n }\n fields(check, node.fields, [...path, \"fields\"], false);\n }\n return check.graphQLName(node.name, [...path, \"name\"]);\n}\n\nfunction examples(\n check: ShapeChecker,\n value: unknown,\n path: DefinitionPath,\n keys: readonly string[],\n): void {\n check.array(value, path)?.forEach((entry, index) => {\n const node = check.record(entry, keys, [...path, index]);\n if (node === undefined) return;\n for (const key of keys) check.string(node[key], [...path, index, key]);\n });\n}\n\nfunction state(\n check: ShapeChecker,\n value: unknown,\n path: DefinitionPath,\n scope: \"global\" | \"local\",\n): void {\n const node = check.record(\n value,\n [\"root\", \"initialValue\", \"examples\", \"unknownKeys\", \"materialized\"],\n path,\n );\n if (node === undefined) return;\n if (node.root === null) {\n if (scope === \"global\") {\n check.fail(\n [...path, \"root\"],\n \"A global state always has a root.\",\n \"a named type reference\",\n null,\n );\n }\n if (\n check.json(node.initialValue, [...path, \"initialValue\"]) !== undefined\n ) {\n if (canonicalJson(node.initialValue) !== \"{}\") {\n check.fail(\n [...path, \"initialValue\"],\n \"An empty local state carries an exact empty object.\",\n \"{}\",\n node.initialValue,\n );\n }\n }\n } else {\n typeReference(check, node.root, [...path, \"root\"]);\n check.json(node.initialValue, [...path, \"initialValue\"]);\n }\n check.literal(node.unknownKeys, \"preserve\", [...path, \"unknownKeys\"]);\n examples(check, node.examples, [...path, \"examples\"], [\"id\", \"key\", \"value\"]);\n const materializedPath = [...path, \"materialized\"];\n const materialized = check.record(\n node.materialized,\n [\"schema\", \"initialValue\", \"examples\"],\n materializedPath,\n );\n if (materialized === undefined) return;\n const schema = check.string(materialized.schema, [\n ...materializedPath,\n \"schema\",\n ]);\n if (node.root === null && schema !== undefined && schema !== \"\") {\n check.fail(\n [...materializedPath, \"schema\"],\n \"An empty local state materializes an empty schema.\",\n '\"\"',\n schema,\n );\n }\n check.string(materialized.initialValue, [\n ...materializedPath,\n \"initialValue\",\n ]);\n examples(\n check,\n materialized.examples,\n [...materializedPath, \"examples\"],\n [\"id\", \"value\"],\n );\n}\n\nconst OPERATION_KEYS = [\n \"id\",\n \"key\",\n \"name\",\n \"description\",\n \"actionType\",\n \"creatorKey\",\n \"scope\",\n \"input\",\n \"errors\",\n \"examples\",\n \"template\",\n \"reducer\",\n];\nconst ERROR_KEYS = [\"id\", \"key\", \"code\", \"name\", \"description\", \"template\"];\n\nfunction operation(\n check: ShapeChecker,\n value: unknown,\n path: DefinitionPath,\n): void {\n const node = check.record(value, OPERATION_KEYS, path);\n if (node === undefined) return;\n for (const key of [\"id\", \"key\", \"actionType\", \"creatorKey\"]) {\n check.string(node[key], [...path, key]);\n }\n for (const key of [\"name\", \"description\", \"template\", \"reducer\"]) {\n check.nullableString(node[key], [...path, key]);\n }\n check.oneOf(node.scope, [\"global\", \"local\"], [...path, \"scope\"]);\n if (node.input !== null) {\n const kind = (node.input as Node | null)?.kind;\n if (kind !== \"input\") {\n check.fail(\n [...path, \"input\", \"kind\"],\n \"An operation input is an input type.\",\n \"input\",\n kind,\n );\n } else {\n namedType(check, node.input, [...path, \"input\"]);\n }\n }\n check.array(node.errors, [...path, \"errors\"])?.forEach((entry, index) => {\n const at = [...path, \"errors\", index];\n const error = check.record(entry, ERROR_KEYS, at);\n if (error === undefined) return;\n check.string(error.id, [...at, \"id\"]);\n check.string(error.key, [...at, \"key\"]);\n for (const key of [\"code\", \"name\", \"description\", \"template\"]) {\n check.nullableString(error[key], [...at, key]);\n }\n });\n examples(check, node.examples, [...path, \"examples\"], [\"id\", \"key\", \"value\"]);\n}\n\nfunction storedScalar(\n check: ShapeChecker,\n value: unknown,\n name: string,\n path: DefinitionPath,\n): void {\n const node = check.record(\n value,\n [\n \"kind\",\n \"formatVersion\",\n \"name\",\n \"representation\",\n \"description\",\n \"coercion\",\n \"coercionProfile\",\n ],\n path,\n );\n if (node === undefined) return;\n check.literal(node.kind, \"powerhouse.scalar\", [...path, \"kind\"]);\n check.literal(node.formatVersion, 1, [...path, \"formatVersion\"]);\n check.literal(node.name, name, [...path, \"name\"]);\n check.oneOf(node.representation, SCALAR_REPRESENTATIONS, [\n ...path,\n \"representation\",\n ]);\n check.string(node.description, [...path, \"description\"]);\n check.literal(node.coercionProfile, \"catalog-v1\", [\n ...path,\n \"coercionProfile\",\n ]);\n const coercion = check.record(\n node.coercion,\n [\"source\"],\n [...path, \"coercion\"],\n );\n if (coercion !== undefined) {\n check.oneOf(\n coercion.source,\n [\"derived\", \"explicit\"],\n [...path, \"coercion\", \"source\"],\n );\n }\n}\n\nfunction scalars(\n check: ShapeChecker,\n value: unknown,\n path: DefinitionPath,\n): ReadonlySet<string> {\n const declared = new Set<string>();\n check.array(value, path)?.forEach((entry, index) => {\n const at = [...path, index];\n const isPackage =\n typeof entry === \"object\" &&\n entry !== null &&\n Object.hasOwn(entry, \"definition\");\n const scalar = check.record(\n entry,\n [\"name\", \"implementation\", \"coercionProfile\", \"definition\"],\n at,\n );\n if (scalar === undefined) return;\n check.literal(scalar.coercionProfile, \"catalog-v1\", [\n ...at,\n \"coercionProfile\",\n ]);\n if (check.rejectHostOnlyScalar(scalar.name, [...at, \"name\"])) return;\n if (!isPackage) {\n const name = check.oneOf(scalar.name, CATALOG_SCALARS, [...at, \"name\"]);\n if (name !== undefined) {\n check.literal(scalar.implementation, `powerhouse.catalog#${name}`, [\n ...at,\n \"implementation\",\n ]);\n }\n return;\n }\n const name = check.graphQLName(scalar.name, [...at, \"name\"]);\n if (name === undefined) return;\n if (MODEL_SCALARS.has(name) || declared.has(name)) {\n check.fail(\n [...at, \"name\"],\n \"A package scalar has a name no catalog scalar, GraphQL built-in, or other package scalar uses.\",\n \"an unused GraphQL name\",\n name,\n );\n return;\n }\n check.literal(scalar.implementation, `package#${name}`, [\n ...at,\n \"implementation\",\n ]);\n storedScalar(check, scalar.definition, name, [...at, \"definition\"]);\n declared.add(name);\n });\n return declared;\n}\n\nfunction specification(\n check: ShapeChecker,\n value: unknown,\n path: DefinitionPath,\n): void {\n const node = check.record(\n value,\n [\n \"version\",\n \"scalars\",\n \"graphQLCompatibility\",\n \"types\",\n \"state\",\n \"modules\",\n \"changeLog\",\n ],\n path,\n );\n if (node === undefined) return;\n if (\n typeof node.version !== \"number\" ||\n !Number.isSafeInteger(node.version) ||\n node.version <= 0\n ) {\n check.fail(\n [...path, \"version\"],\n \"A specification version is a positive safe integer.\",\n \"a positive safe integer\",\n node.version,\n );\n }\n check.packageScalars = scalars(check, node.scalars, [...path, \"scalars\"]);\n\n if (node.graphQLCompatibility !== null) {\n const at = [...path, \"graphQLCompatibility\"];\n const compatibility = check.record(\n node.graphQLCompatibility,\n [\"kind\", \"document\", \"preserveDefinitionOrder\"],\n at,\n );\n if (compatibility !== undefined) {\n check.literal(compatibility.kind, \"graphql-ast-v1\", [...at, \"kind\"]);\n check.literal(compatibility.preserveDefinitionOrder, true, [\n ...at,\n \"preserveDefinitionOrder\",\n ]);\n check.collector.merge(\n validateLocationFreeDocument(compatibility.document, [\n ...at,\n \"document\",\n ]),\n );\n }\n }\n\n const declared = new Set<string>();\n check.array(node.types, [...path, \"types\"])?.forEach((entry, index) => {\n const name = namedType(check, entry, [...path, \"types\", index]);\n if (name === undefined) return;\n if (declared.has(name) || check.packageScalars.has(name)) {\n check.fail(\n [...path, \"types\", index, \"name\"],\n \"A named type is declared once per specification, and never under a package scalar's name.\",\n \"one definition per name\",\n name,\n );\n }\n declared.add(name);\n });\n\n const stateNode = check.record(\n node.state,\n [\"global\", \"local\"],\n [...path, \"state\"],\n );\n if (stateNode !== undefined) {\n for (const scope of [\"global\", \"local\"] as const) {\n state(check, stateNode[scope], [...path, \"state\", scope], scope);\n const root = (stateNode[scope] as Node | undefined)?.root as\n | Node\n | null\n | undefined;\n if (typeof root?.name === \"string\" && !declared.has(root.name)) {\n check.fail(\n [...path, \"state\", scope, \"root\", \"name\"],\n \"A state root is declared in this specification's types.\",\n [...declared].join(\" | \"),\n root.name,\n );\n }\n }\n }\n\n check.array(node.modules, [...path, \"modules\"])?.forEach((entry, index) => {\n const at = [...path, \"modules\", index];\n const module = check.record(\n entry,\n [\"id\", \"key\", \"name\", \"description\", \"operations\"],\n at,\n );\n if (module === undefined) return;\n check.string(module.id, [...at, \"id\"]);\n check.string(module.key, [...at, \"key\"]);\n check.string(module.name, [...at, \"name\"]);\n check.nullableString(module.description, [...at, \"description\"]);\n check\n .array(module.operations, [...at, \"operations\"])\n ?.forEach((candidate, operationIndex) =>\n operation(check, candidate, [...at, \"operations\", operationIndex]),\n );\n });\n\n check\n .array(node.changeLog, [...path, \"changeLog\"])\n ?.forEach((entry, index) =>\n check.string(entry, [...path, \"changeLog\", index]),\n );\n}\n\nexport function checkDocumentModelDefinitionShape(\n value: unknown,\n path: DefinitionPath = [],\n): readonly DefinitionDiagnostic[] {\n const check = new ShapeChecker();\n const node = check.record(\n value,\n [\"kind\", \"formatVersion\", \"compatibility\", \"model\", \"specifications\"],\n path,\n );\n if (node === undefined) return check.collector.diagnostics;\n check.literal(node.kind, \"powerhouse.document-model\", [...path, \"kind\"]);\n check.literal(node.formatVersion, 1, [...path, \"formatVersion\"]);\n\n const compatibilityPath = [...path, \"compatibility\"];\n const compatibility = check.record(\n node.compatibility,\n [\"identity\", \"scalarCoercion\", \"serialization\"],\n compatibilityPath,\n );\n if (compatibility !== undefined) {\n check.oneOf(\n compatibility.identity,\n [\"derived-v1\", \"explicit-schema-first\"],\n [...compatibilityPath, \"identity\"],\n );\n check.literal(compatibility.scalarCoercion, \"catalog-v1\", [\n ...compatibilityPath,\n \"scalarCoercion\",\n ]);\n check.oneOf(\n compatibility.serialization,\n [\"canonical-v1\", \"explicit-schema-first\"],\n [...compatibilityPath, \"serialization\"],\n );\n }\n\n const modelPath = [...path, \"model\"];\n const model = check.record(\n node.model,\n [\n \"documentType\",\n \"graphQLName\",\n \"name\",\n \"description\",\n \"extension\",\n \"author\",\n ],\n modelPath,\n );\n if (model !== undefined) {\n if (\n check.string(model.documentType, [...modelPath, \"documentType\"]) === \"\"\n ) {\n check.fail(\n [...modelPath, \"documentType\"],\n \"A document type is not empty.\",\n \"a document type\",\n '\"\"',\n );\n }\n check.graphQLName(model.graphQLName, [...modelPath, \"graphQLName\"]);\n for (const key of [\"name\", \"description\", \"extension\"]) {\n check.string(model[key], [...modelPath, key]);\n }\n const author = check.record(\n model.author,\n [\"name\", \"website\"],\n [...modelPath, \"author\"],\n );\n if (author !== undefined) {\n check.string(author.name, [...modelPath, \"author\", \"name\"]);\n check.nullableString(author.website, [...modelPath, \"author\", \"website\"]);\n }\n }\n\n const specifications = check.array(node.specifications, [\n ...path,\n \"specifications\",\n ]);\n if (specifications?.length === 0) {\n check.fail(\n [...path, \"specifications\"],\n \"A definition carries at least one specification.\",\n \"a nonempty specification history\",\n \"an empty array\",\n );\n }\n specifications?.forEach((entry, index) =>\n specification(check, entry, [...path, \"specifications\", index]),\n );\n return check.collector.diagnostics;\n}\n","import { compilerDiagnostics } from \"../compiler/diagnostic-codes.js\";\nimport { defineDiagnosticCatalog } from \"../kernel/diagnostics.js\";\n\nexport const modelDiagnostics = defineDiagnosticCatalog(\n {\n \"PH-DM-STATE-ROOT-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"A required state root is absent, is not an object, or has the wrong canonical name\",\n },\n \"PH-DM-SCOPE-UNSUPPORTED\": {\n severity: \"error\",\n phase: \"definition\",\n meaning: \"A definition requests a scope outside global or local\",\n },\n \"PH-AUTH-UNSUPPORTED\": {\n severity: \"error\",\n phase: \"authorization\",\n meaning: \"A document model declares authorization, which core v1 rejects\",\n },\n },\n compilerDiagnostics,\n);\n\nexport type ModelDiagnosticCode = keyof typeof modelDiagnostics.codes;\n","import { defineDiagnosticCatalog } from \"../kernel/diagnostics.js\";\nimport { modelDiagnostics } from \"../model/diagnostic-codes.js\";\n\nexport const toolingDiagnostics = defineDiagnosticCatalog(\n {\n \"PH-CONFIG-SOURCE-INVALID\": {\n severity: \"error\",\n phase: \"configuration\",\n meaning:\n \"The config file, a definition source entry, or an export pointer cannot select a module export\",\n },\n \"PH-CONFIG-SOURCE-OUTSIDE-PACKAGE\": {\n severity: \"error\",\n phase: \"configuration\",\n meaning:\n \"A definition source path, or the real path behind its symlinks, leaves the package root\",\n },\n \"PH-CONFIG-DUPLICATE-SOURCE\": {\n severity: \"error\",\n phase: \"configuration\",\n meaning: \"Two entries select the same module and export path\",\n },\n \"PH-CONFIG-VERSION-UNSUPPORTED\": {\n severity: \"error\",\n phase: \"configuration\",\n meaning:\n \"definitionSources declares a format version this release does not read\",\n },\n \"PH-IMPORT-FAILED\": {\n severity: \"error\",\n phase: \"import\",\n meaning:\n \"A selected module is missing, throws while it is evaluated, or the import adapter returned no namespace\",\n },\n \"PH-PKG-DEFINITION-UNRECOGNIZED\": {\n severity: \"error\",\n phase: \"package\",\n meaning:\n \"A selected export holds no materialized document model, family, or upgrade manifest\",\n },\n \"PH-PKG-DEFINITION-UNINSPECTABLE\": {\n severity: \"error\",\n phase: \"package\",\n meaning:\n \"A selected export hides its members behind an accessor or a Proxy\",\n },\n \"PH-PKG-LOGICAL-COLLISION\": {\n severity: \"error\",\n phase: \"package\",\n meaning:\n \"Two distinct values claim one document type and version, or one upgrade manifest document type\",\n },\n },\n modelDiagnostics,\n);\n\nexport type ToolingDiagnosticCode = keyof typeof toolingDiagnostics.codes;\n","import type {\n DefinitionPath,\n DefinitionSource,\n DocumentModelDefinition,\n DocumentModelPHState,\n UpgradeManifest,\n} from \"@powerhousedao/shared/document-model\";\nimport { definitionModuleMismatch } from \"../../compiler/module-definition.js\";\nimport { checkDocumentModelDefinitionShape } from \"../../compiler/wire-shape.js\";\nimport {\n rejectionReceived,\n snapshotArray,\n snapshotRecord,\n} from \"../../kernel/data-properties.js\";\nimport { DefinitionDiagnosticCollector } from \"../../kernel/diagnostic-collector.js\";\nimport { describeReceived } from \"../../kernel/diagnostics.js\";\nimport { canonicalDigest, canonicalJson } from \"../../kernel/primitives.js\";\nimport {\n type ToolingDiagnosticCode,\n toolingDiagnostics,\n} from \"../diagnostic-codes.js\";\nimport type {\n NormalizedDocumentModelArtifact,\n NormalizedDocumentModelResult,\n} from \"./types.js\";\n\ntype Collector = DefinitionDiagnosticCollector<ToolingDiagnosticCode>;\n\nconst MODULE_KEYS =\n \"version, reducer, actions, utils, documentModel, definition\";\nconst REPAIR =\n \"Export the module materialize returned, or family.at(version), without replacing its members.\";\n\nfunction sourceOf(\n source: DefinitionSource,\n exportPath: readonly string[],\n): DefinitionSource {\n const path = [...(source.exportPath ?? []), ...exportPath];\n return {\n specifier: source.specifier,\n ...(path.length > 0 && { exportPath: path }),\n };\n}\n\nfunction invalid(\n collector: Collector,\n path: DefinitionPath,\n message: string,\n expected: string,\n received: string,\n repair = REPAIR,\n): undefined {\n collector.add({\n code: \"PH-DM-DECLARATION-INVALID\",\n path,\n message,\n expected,\n received,\n repair,\n });\n return undefined;\n}\n\nfunction storedDocumentType(\n collector: Collector,\n value: unknown,\n path: DefinitionPath,\n): string | undefined {\n const documentModel = snapshotRecord(value, undefined, path);\n const global = documentModel.ok\n ? snapshotRecord(documentModel.value.global, undefined, [...path, \"global\"])\n : documentModel;\n if (!global.ok) {\n return invalid(\n collector,\n global.path,\n `A module keeps its stored model in documentModel.global as plain data, and it cannot be read (${global.reason}).`,\n \"documentModel.global as a plain record of data properties\",\n rejectionReceived(global),\n );\n }\n const id = global.value.id;\n if (typeof id !== \"string\" || id === \"\") {\n return invalid(\n collector,\n [...path, \"global\", \"id\"],\n \"A module has a stored model ID.\",\n \"a nonempty document type\",\n typeof id === \"string\" ? '\"\"' : describeReceived(id),\n \"Declare id in defineDocumentModel; the stored model ID is the document type every consumer registers.\",\n );\n }\n return id;\n}\n\nfunction artifact(\n collector: Collector,\n value: unknown,\n source: DefinitionSource,\n path: DefinitionPath,\n): NormalizedDocumentModelArtifact | undefined {\n const snapshot = snapshotRecord(value, undefined, path);\n if (!snapshot.ok) {\n return invalid(\n collector,\n snapshot.path,\n `This export is not a document-model module (${snapshot.reason}).`,\n MODULE_KEYS,\n rejectionReceived(snapshot),\n );\n }\n const module = snapshot.value;\n let usable = true;\n if (typeof module.reducer !== \"function\") {\n usable = false;\n invalid(\n collector,\n [...path, \"reducer\"],\n \"A module has a callable reducer.\",\n \"a reducer function\",\n describeReceived(module.reducer),\n );\n }\n const version = module.version;\n if (\n typeof version !== \"number\" ||\n !Number.isSafeInteger(version) ||\n version <= 0\n ) {\n usable = false;\n invalid(\n collector,\n [...path, \"version\"],\n \"A code-first module declares its registry version as a positive safe integer.\",\n \"a positive safe integer\",\n typeof version === \"number\" ? String(version) : describeReceived(version),\n );\n }\n const documentType = storedDocumentType(collector, module.documentModel, [\n ...path,\n \"documentModel\",\n ]);\n if (module.definition === undefined) {\n return invalid(\n collector,\n [...path, \"definition\"],\n \"This module carries no structured definition, so it was not made by materialize.\",\n \"the definition materialize attaches\",\n \"undefined\",\n \"Export the module materialize returned.\",\n );\n }\n const shape = checkDocumentModelDefinitionShape(module.definition, [\n ...path,\n \"definition\",\n ]);\n collector.merge(shape);\n if (\n !usable ||\n documentType === undefined ||\n shape.length > 0 ||\n typeof version !== \"number\"\n ) {\n return undefined;\n }\n const definition = module.definition as DocumentModelDefinition;\n\n const mismatch = definitionModuleMismatch(\n definition,\n { documentType, version },\n [...path, \"definition\"],\n );\n if (mismatch !== undefined) {\n collector.add(mismatch);\n return undefined;\n }\n return {\n kind: \"powerhouse.document-model-artifact\",\n source,\n documentType,\n version,\n definition,\n digest: canonicalDigest(definition),\n documentModel: module.documentModel as DocumentModelPHState,\n };\n}\n\nfunction familyManifest(\n collector: Collector,\n value: unknown,\n artifacts: readonly NormalizedDocumentModelArtifact[],\n path: DefinitionPath,\n): UpgradeManifest<readonly number[]> | null {\n const snapshot = snapshotRecord(value, undefined, path);\n const manifest = snapshot.ok ? snapshot.value : undefined;\n const versions = artifacts.map((entry) => entry.version);\n const supported = manifest?.supportedVersions;\n const declared =\n Array.isArray(supported) && supported.every(Number.isSafeInteger)\n ? canonicalJson(supported)\n : describeReceived(supported);\n if (\n manifest === undefined ||\n declared !== canonicalJson(versions) ||\n manifest.latestVersion !== versions.at(-1)\n ) {\n invalid(\n collector,\n snapshot.ok ? path : snapshot.path,\n \"A family's upgrade manifest covers exactly the versions its modules serve.\",\n canonicalJson(versions),\n snapshot.ok ? declared : rejectionReceived(snapshot),\n \"Export the family materialize returned, so its manifest and modules stay one declaration.\",\n );\n return null;\n }\n const documentTypes = new Set(artifacts.map((entry) => entry.documentType));\n if (\n documentTypes.size !== 1 ||\n !documentTypes.has(manifest.documentType as string)\n ) {\n invalid(\n collector,\n [...path, \"documentType\"],\n \"A family's upgrade manifest and its modules name one document type.\",\n [...documentTypes].join(\", \"),\n String(manifest.documentType),\n \"Compose one family per document type.\",\n );\n return null;\n }\n return value as UpgradeManifest<readonly number[]>;\n}\n\n/**\n * @experimental Normalizes one materialized code-first module, or a family\n * and its versions in order. A family reports every malformed member: a\n * valid sibling never makes a broken one pass.\n */\nexport function adaptCodeFirstDocumentModelSource(\n value: unknown,\n source: DefinitionSource,\n): NormalizedDocumentModelResult {\n const collector: Collector = new DefinitionDiagnosticCollector(\n toolingDiagnostics,\n );\n const family = snapshotRecord(value, undefined, []);\n const modules =\n family.ok && typeof family.value.at === \"function\"\n ? snapshotArray(family.value.modules, [\"modules\"])\n : undefined;\n if (family.ok && modules?.ok === true) {\n const artifacts = modules.value.flatMap((module, index) => {\n const entry = artifact(\n collector,\n module,\n sourceOf(source, [\"modules\", String(index)]),\n [\"modules\", index],\n );\n return entry === undefined ? [] : [entry];\n });\n const manifest =\n artifacts.length === modules.value.length\n ? familyManifest(collector, family.value.upgradeManifest, artifacts, [\n \"upgradeManifest\",\n ])\n : null;\n return {\n artifacts,\n upgradeManifest: manifest,\n diagnostics: collector.diagnostics,\n };\n }\n const single = artifact(collector, value, source, []);\n return {\n artifacts: single === undefined ? [] : [single],\n upgradeManifest: null,\n diagnostics: collector.diagnostics,\n };\n}\n","import {\n DEFAULT_AUTHORING_MODE,\n parseDefinitionSourcesConfig,\n} from \"@powerhousedao/shared/clis/definition-sources\";\nimport type {\n DefinitionCheckSkipReason,\n DefinitionDiagnostic,\n DefinitionPath,\n DefinitionSource,\n} from \"@powerhousedao/shared/document-model\";\nimport { existsSync, readFileSync, realpathSync } from \"node:fs\";\nimport { dirname, isAbsolute, posix, relative, resolve, sep } from \"node:path\";\nimport {\n compareDefinitionPaths,\n sortDefinitionDiagnostics,\n} from \"../kernel/diagnostics.js\";\nimport {\n canonicalDigest,\n compareCodeUnits,\n isNFC,\n} from \"../kernel/primitives.js\";\nimport type {\n DefinitionSourceOrigin,\n DefinitionSourceResolution,\n DefinitionSourceSelectionRequest,\n DefinitionSourceSet,\n} from \"./definition-source-types.js\";\nimport { toolingDiagnostics } from \"./diagnostic-codes.js\";\n\nexport type ResolvedDefinitionSource = {\n readonly source: DefinitionSource;\n\n readonly position: DefinitionPath;\n\n readonly moduleIdentity: string;\n};\n\nexport type InternalResolution = DefinitionSourceResolution & {\n readonly packageRootIdentity: string;\n readonly resolved: readonly ResolvedDefinitionSource[];\n};\n\nconst CONFIG_FILE_NAME = \"./powerhouse.config.json\";\n\nconst IDENTITY_SEPARATOR = String.fromCharCode(0);\n\nfunction render(value: unknown): string {\n if (typeof value === \"string\") return value;\n if (value === undefined) return \"undefined\";\n try {\n // `JSON.stringify` returns `undefined` for a function or a symbol.\n const json = JSON.stringify(value) as string | undefined;\n return json ?? typeof value;\n } catch {\n return typeof value;\n }\n}\n\nfunction sourceSet(\n mode: DefinitionSourceSet[\"mode\"],\n origin: DefinitionSourceOrigin,\n sources: readonly DefinitionSource[],\n): DefinitionSourceSet {\n const value = { mode, origin, sources };\n return { ...value, digest: canonicalDigest(value) };\n}\n\nexport function compareDefinitionSources(\n left: DefinitionSource,\n right: DefinitionSource,\n): number {\n const specifier = compareCodeUnits(left.specifier, right.specifier);\n if (specifier !== 0) return specifier;\n const leftPath = left.exportPath ?? [];\n const rightPath = right.exportPath ?? [];\n for (\n let index = 0;\n index < Math.min(leftPath.length, rightPath.length);\n index += 1\n ) {\n const segment = compareCodeUnits(leftPath[index], rightPath[index]);\n if (segment !== 0) return segment;\n }\n return leftPath.length - rightPath.length;\n}\n\nfunction isCanonicalText(value: string): boolean {\n for (const character of value) {\n const codePoint = character.codePointAt(0) ?? 0;\n if (codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f)) {\n return false;\n }\n }\n return isNFC(value);\n}\n\nexport function isWithin(root: string, path: string): boolean {\n const child = relative(root, path);\n return child !== \"..\" && !child.startsWith(`..${sep}`) && !isAbsolute(child);\n}\n\ntype SpecifierResult =\n | { readonly ok: true; readonly specifier: `./${string}` }\n | {\n readonly ok: false;\n readonly code:\n | \"PH-CONFIG-SOURCE-INVALID\"\n | \"PH-CONFIG-SOURCE-OUTSIDE-PACKAGE\";\n readonly message: string;\n };\n\nexport function normalizeSpecifier(value: string): SpecifierResult {\n if (\n !value.startsWith(\"./\") ||\n /[\\\\#?]/.test(value) ||\n !isCanonicalText(value)\n ) {\n return {\n ok: false,\n code: \"PH-CONFIG-SOURCE-INVALID\",\n message:\n \"A definition source is a POSIX package-relative path beginning with './'.\",\n };\n }\n const normalized = posix.normalize(value.slice(2));\n if (normalized === \".\" || normalized === \"./\") {\n return {\n ok: false,\n code: \"PH-CONFIG-SOURCE-INVALID\",\n message: \"A definition source names a module file, not the package root.\",\n };\n }\n if (normalized === \"..\" || normalized.startsWith(\"../\")) {\n return {\n ok: false,\n code: \"PH-CONFIG-SOURCE-OUTSIDE-PACKAGE\",\n message: \"The normalized definition source path leaves the package root.\",\n };\n }\n if (!/\\.(?:[cm]?[jt]s|[jt]sx)$/.test(value)) {\n return {\n ok: false,\n code: \"PH-CONFIG-SOURCE-INVALID\",\n message:\n \"A definition source names a JavaScript or TypeScript module file with its extension.\",\n };\n }\n return { ok: true, specifier: `./${normalized}` };\n}\n\n/**\n * Resolves symlinks as far as the path exists, so a source that is not\n * written yet is still judged against the real package root.\n */\nexport function realPathThroughExistingParent(path: string): string {\n let current = path;\n const suffix: string[] = [];\n while (!existsSync(current)) {\n const parent = dirname(current);\n if (parent === current) return path;\n suffix.unshift(relative(parent, current));\n current = parent;\n }\n return resolve(realpathSync.native(current), ...suffix);\n}\n\n/** Where a lexically contained module really lives, unless a symlink takes it out of the package. */\nexport function realModulePath(\n packageRoot: string,\n packageRootIdentity: string,\n specifier: `./${string}`,\n):\n | { readonly ok: true; readonly moduleIdentity: string }\n | { readonly ok: false; readonly reason: \"unresolvable\" | \"outside\" } {\n let moduleIdentity: string;\n try {\n moduleIdentity = realPathThroughExistingParent(\n resolve(packageRoot, ...specifier.slice(2).split(\"/\")),\n );\n } catch {\n return { ok: false, reason: \"unresolvable\" };\n }\n return isWithin(packageRootIdentity, moduleIdentity)\n ? { ok: true, moduleIdentity }\n : { ok: false, reason: \"outside\" };\n}\n\ntype EntryResult =\n | { readonly source: ResolvedDefinitionSource }\n | { readonly diagnostic: DefinitionDiagnostic };\n\nfunction invalidEntry(\n path: DefinitionPath,\n message: string,\n expected: string,\n received: string,\n repair: string,\n source?: DefinitionSource,\n): EntryResult {\n return {\n diagnostic: toolingDiagnostics.create({\n code: \"PH-CONFIG-SOURCE-INVALID\",\n ...(source !== undefined && { source }),\n path,\n message,\n expected,\n received,\n repair,\n }),\n };\n}\n\nfunction normalizeEntry(\n value: unknown,\n position: DefinitionPath,\n packageRoot: string,\n packageRootIdentity: string,\n): EntryResult {\n if (\n value === null ||\n typeof value !== \"object\" ||\n Object.getPrototypeOf(value) !== Object.prototype\n ) {\n return invalidEntry(\n position,\n \"A definition source entry must be a plain object.\",\n \"{ specifier, exportPath? }\",\n render(value),\n 'Replace this entry with { \"specifier\": \"./src/<module>.ts\" }.',\n );\n }\n const entry = value as Record<string, unknown>;\n const extra = Object.keys(entry)\n .filter((key) => key !== \"specifier\" && key !== \"exportPath\")\n .sort(compareCodeUnits);\n if (extra.length > 0) {\n return invalidEntry(\n position,\n \"A definition source entry carries unsupported properties.\",\n \"specifier and optional exportPath\",\n extra.join(\", \"),\n `Remove ${extra.join(\", \")} from this entry.`,\n );\n }\n const specifierPath = [...position, \"specifier\"];\n if (typeof entry.specifier !== \"string\") {\n return invalidEntry(\n specifierPath,\n \"A definition source specifier must be a string.\",\n \"a './' POSIX package-relative path\",\n render(entry.specifier),\n \"Set specifier to the package-relative TypeScript module path.\",\n );\n }\n const normalized = normalizeSpecifier(entry.specifier);\n if (!normalized.ok) {\n return {\n diagnostic: toolingDiagnostics.create({\n code: normalized.code,\n path: specifierPath,\n message: normalized.message,\n expected: \"a './' path contained by the selected package root\",\n received: entry.specifier,\n repair:\n \"Move the module inside the package and spell its path relative to the config file.\",\n }),\n };\n }\n const { specifier } = normalized;\n\n let exportPath: readonly string[] | undefined;\n if (entry.exportPath !== undefined) {\n const valid =\n Array.isArray(entry.exportPath) &&\n entry.exportPath.every(\n (segment) => typeof segment === \"string\" && isCanonicalText(segment),\n );\n if (!valid) {\n return invalidEntry(\n [...position, \"exportPath\"],\n \"An exportPath is an array of exact property keys in NFC, without control characters.\",\n \"an array of property-key strings\",\n render(entry.exportPath),\n \"Replace exportPath with the exported property keys, outermost first.\",\n { specifier },\n );\n }\n const segments = entry.exportPath as readonly string[];\n if (segments.length > 0) exportPath = [...segments];\n }\n\n const source: DefinitionSource =\n exportPath === undefined ? { specifier } : { specifier, exportPath };\n const real = realModulePath(packageRoot, packageRootIdentity, specifier);\n if (!real.ok && real.reason === \"unresolvable\") {\n return invalidEntry(\n specifierPath,\n \"The definition source path could not be resolved.\",\n \"a resolvable path inside the package root\",\n specifier,\n \"Fix the path, or the permissions of a directory on the way to it.\",\n source,\n );\n }\n if (!real.ok) {\n return {\n diagnostic: toolingDiagnostics.create({\n code: \"PH-CONFIG-SOURCE-OUTSIDE-PACKAGE\",\n source,\n path: specifierPath,\n message:\n \"The definition source resolves through a symlink that leaves the package root.\",\n expected: \"a real path contained by the package root\",\n received: specifier,\n repair:\n \"Replace the symlink with a module that really lives in this package.\",\n }),\n };\n }\n return { source: { source, position, moduleIdentity: real.moduleIdentity } };\n}\n\nfunction duplicateDiagnostics(\n sources: readonly ResolvedDefinitionSource[],\n): readonly DefinitionDiagnostic[] {\n const groups = new Map<string, ResolvedDefinitionSource[]>();\n for (const entry of sources) {\n const key = [\n entry.moduleIdentity,\n JSON.stringify(entry.source.exportPath ?? []),\n ].join(IDENTITY_SEPARATOR);\n groups.set(key, [...(groups.get(key) ?? []), entry]);\n }\n return [...groups.values()]\n .filter((group) => group.length > 1)\n .map((group) => {\n const [first, ...rest] = [...group].sort(\n (left, right) =>\n compareDefinitionSources(left.source, right.source) ||\n compareDefinitionPaths(left.position, right.position),\n );\n return toolingDiagnostics.create({\n code: \"PH-CONFIG-DUPLICATE-SOURCE\",\n source: first.source,\n path: first.position,\n message:\n \"Several entries select the same module and export path, so one of them can only repeat the other's definitions.\",\n expected: \"one entry per module and export path\",\n received: `${group.length} entries`,\n repair: \"Remove every duplicate entry except one.\",\n related: rest.map((entry) => ({\n source: entry.source,\n path: entry.position,\n message: \"This entry resolves to the same module and export path.\",\n })),\n });\n });\n}\n\ntype Roots = {\n readonly packageRoot: string;\n readonly packageRootIdentity: string;\n};\n\nfunction failed(\n roots: Roots,\n diagnostics: readonly DefinitionDiagnostic[],\n origin: DefinitionSourceOrigin = \"config\",\n sources: readonly DefinitionSource[] = [],\n): InternalResolution {\n return {\n ...roots,\n status: \"failed\",\n sourceSet: sourceSet(\"code-first\", origin, sources),\n diagnostics: sortDefinitionDiagnostics(diagnostics),\n resolved: [],\n };\n}\n\nfunction skipped(\n roots: Roots,\n skipReason: DefinitionCheckSkipReason,\n mode: DefinitionSourceSet[\"mode\"],\n): InternalResolution {\n return {\n ...roots,\n status: \"skipped\",\n skipReason,\n sourceSet: sourceSet(mode, \"config\", []),\n diagnostics: [],\n resolved: [],\n };\n}\n\ntype ConfigReadFailure =\n | \"missing\"\n | \"read-failed\"\n | \"parse-failed\"\n | \"not-an-object\";\n\nconst CONFIG_FAILURE_REPAIR: Record<ConfigReadFailure, string> = {\n missing:\n \"Create the config file, or point --config-file at the package's existing one.\",\n \"read-failed\": \"Fix the permissions of the selected config file.\",\n \"parse-failed\": \"Repair the JSON in the selected config file.\",\n \"not-an-object\": \"Make the config file a single JSON object.\",\n};\n\nexport function readConfigObject(\n configFile: string,\n):\n | { readonly ok: true; readonly value: Readonly<Record<string, unknown>> }\n | { readonly ok: false; readonly reason: ConfigReadFailure } {\n let text: string;\n try {\n text = readFileSync(configFile, \"utf8\");\n } catch (error) {\n const code = (error as { code?: unknown } | null)?.code;\n return {\n ok: false,\n reason:\n code === \"ENOENT\" || code === \"ENOTDIR\" ? \"missing\" : \"read-failed\",\n };\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return { ok: false, reason: \"parse-failed\" };\n }\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n return { ok: false, reason: \"not-an-object\" };\n }\n return { ok: true, value: parsed as Readonly<Record<string, unknown>> };\n}\n\nfunction selectionDiagnostic(\n narrowed: Exclude<\n ReturnType<typeof parseDefinitionSourcesConfig>,\n { ok: true } | { reason: \"missing\" }\n >,\n): DefinitionDiagnostic {\n if (narrowed.reason === \"unsupported-version\") {\n return toolingDiagnostics.create({\n code: \"PH-CONFIG-VERSION-UNSUPPORTED\",\n path: narrowed.path,\n message:\n \"The definitionSources format version is not one this release reads.\",\n expected: \"1\",\n received: render(narrowed.received),\n repair: \"Set definitionSources.formatVersion to 1, or upgrade ph.\",\n });\n }\n return toolingDiagnostics.create({\n code: \"PH-CONFIG-SOURCE-INVALID\",\n path: narrowed.path,\n message: \"The definitionSources selection is malformed.\",\n expected: narrowed.expected,\n received: render(narrowed.received),\n repair: `Set this member to ${narrowed.expected}.`,\n });\n}\n\n/** The selected config file, its directory, and that directory's real path when it exists. */\nexport function packageRoots(request: DefinitionSourceSelectionRequest): {\n readonly configFile: string;\n readonly packageRoot: string;\n readonly packageRootIdentity: string;\n} {\n const configFile = resolve(request.configFile ?? CONFIG_FILE_NAME);\n const packageRoot = dirname(configFile);\n try {\n const packageRootIdentity = realpathSync.native(packageRoot);\n return { configFile, packageRoot, packageRootIdentity };\n } catch {\n // Reading the config reports the missing directory.\n return { configFile, packageRoot, packageRootIdentity: packageRoot };\n }\n}\n\nexport function resolveDefinitionSources(\n request: DefinitionSourceSelectionRequest,\n): InternalResolution {\n const { configFile, ...roots } = packageRoots(request);\n const { packageRoot, packageRootIdentity } = roots;\n\n if (request.allowMissingConfig === true && !existsSync(configFile)) {\n return skipped(roots, \"definition-sources-absent\", DEFAULT_AUTHORING_MODE);\n }\n\n const config = readConfigObject(configFile);\n if (!config.ok) {\n return failed(roots, [\n toolingDiagnostics.create({\n code: \"PH-CONFIG-SOURCE-INVALID\",\n path: [\"configFile\"],\n message:\n \"The selected Powerhouse config file could not be read; its directory is the package root.\",\n expected: \"an existing config file holding one JSON object\",\n received: config.reason,\n repair: CONFIG_FAILURE_REPAIR[config.reason],\n }),\n ]);\n }\n\n const origin = \"config\";\n const narrowed = parseDefinitionSourcesConfig(config.value.definitionSources);\n if (!narrowed.ok) {\n return narrowed.reason === \"missing\"\n ? skipped(roots, \"definition-sources-absent\", DEFAULT_AUTHORING_MODE)\n : failed(roots, [selectionDiagnostic(narrowed)], origin);\n }\n if (narrowed.mode === \"schema-first\") {\n return skipped(roots, \"explicit-schema-first-mode\", \"schema-first\");\n }\n if (narrowed.entries.length === 0) {\n return skipped(roots, \"definition-sources-empty\", \"code-first\");\n }\n const entries = narrowed.entries;\n\n const normalized = entries.map((value, index) =>\n normalizeEntry(\n value,\n [\"definitionSources\", \"entries\", index],\n packageRoot,\n packageRootIdentity,\n ),\n );\n\n const resolved = normalized\n .flatMap((result) => (\"source\" in result ? [result.source] : []))\n .sort((left, right) => compareDefinitionSources(left.source, right.source));\n const sources = resolved.map((entry) => entry.source);\n const entryDiagnostics = normalized.flatMap((result) =>\n \"diagnostic\" in result ? [result.diagnostic] : [],\n );\n if (entryDiagnostics.length > 0) {\n return failed(roots, entryDiagnostics, origin, sources);\n }\n const duplicates = duplicateDiagnostics(resolved);\n if (duplicates.length > 0) {\n return failed(roots, duplicates, origin, sources);\n }\n return {\n ...roots,\n status: \"ready\",\n sourceSet: sourceSet(\"code-first\", origin, sources),\n diagnostics: [],\n resolved,\n };\n}\n\nexport function publicResolution(\n value: InternalResolution,\n): DefinitionSourceResolution {\n const common = {\n packageRoot: value.packageRoot,\n sourceSet: value.sourceSet,\n diagnostics: value.diagnostics,\n };\n return value.status === \"skipped\"\n ? { ...common, status: \"skipped\", skipReason: value.skipReason }\n : { ...common, status: value.status };\n}\n\n/**\n * @experimental The selection a command would load, resolved without\n * importing anything and without any machine-specific path but the root.\n */\nexport function resolveDefinitionSelection(\n request: DefinitionSourceSelectionRequest,\n): DefinitionSourceResolution {\n return publicResolution(resolveDefinitionSources(request));\n}\n","import type {\n DefinitionDiagnostic,\n DefinitionPath,\n DefinitionRef,\n DefinitionSource,\n} from \"@powerhousedao/shared/document-model\";\nimport { snapshotArray, snapshotRecord } from \"../kernel/data-properties.js\";\nimport {\n type ToolingDiagnosticCode,\n toolingDiagnostics,\n} from \"./diagnostic-codes.js\";\n\nexport function describeThrown(error: unknown): string {\n if (error === null) return \"null\";\n try {\n if (error instanceof Error) return `${error.name}: ${error.message}`;\n } catch {\n // A revoked Proxy or a throwing getter makes these reads throw.\n }\n return typeof error;\n}\n\n/** Reads an own data property without running a getter or a Proxy trap twice. */\nexport function readProperty(\n value: object,\n key: string,\n): { readonly ok: true; readonly value: unknown } | { readonly ok: false } {\n try {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor === undefined || !(\"value\" in descriptor)) {\n return { ok: false };\n }\n return { ok: true, value: descriptor.value as unknown };\n } catch {\n return { ok: false };\n }\n}\n\nconst DEFINITION_KINDS: readonly unknown[] = [\n \"document-model\",\n \"subgraph\",\n \"scalar\",\n \"package\",\n];\n\nfunction definitionRef(value: unknown): DefinitionRef | undefined {\n const snapshot = snapshotRecord(value, undefined, []);\n if (!snapshot.ok) return undefined;\n const { kind, key, version } = snapshot.value;\n if (\n typeof key !== \"string\" ||\n key === \"\" ||\n !DEFINITION_KINDS.includes(kind)\n ) {\n return undefined;\n }\n return {\n kind: kind as DefinitionRef[\"kind\"],\n key,\n ...(typeof version === \"number\" && { version }),\n };\n}\n\nfunction isPathSegment(segment: unknown): boolean {\n return (\n typeof segment === \"string\" ||\n (typeof segment === \"number\" && Number.isSafeInteger(segment))\n );\n}\n\nexport function structuredDiagnostics(\n value: unknown,\n source: DefinitionSource,\n): readonly DefinitionDiagnostic[] | undefined {\n if (\n value === null ||\n (typeof value !== \"object\" && typeof value !== \"function\")\n ) {\n return undefined;\n }\n const list = readProperty(value, \"diagnostics\");\n if (!list.ok) return undefined;\n const snapshot = snapshotArray(list.value, []);\n if (!snapshot.ok || snapshot.value.length === 0) return undefined;\n\n const rebuilt: DefinitionDiagnostic[] = [];\n for (const candidate of snapshot.value) {\n const entry = snapshotRecord(candidate, undefined, []);\n if (!entry.ok) return undefined;\n const { code, message, repair, expected, received } = entry.value;\n const path = snapshotArray(entry.value.path, []);\n if (\n typeof code !== \"string\" ||\n !Object.hasOwn(toolingDiagnostics.codes, code) ||\n typeof message !== \"string\" ||\n typeof repair !== \"string\" ||\n !path.ok ||\n !path.value.every(isPathSegment) ||\n (expected !== undefined && typeof expected !== \"string\") ||\n (received !== undefined && typeof received !== \"string\")\n ) {\n return undefined;\n }\n const definition = definitionRef(entry.value.definition);\n rebuilt.push(\n toolingDiagnostics.create({\n code: code as ToolingDiagnosticCode,\n source,\n ...(definition !== undefined && { definition }),\n path: path.value as DefinitionPath,\n message,\n ...(expected !== undefined && { expected }),\n ...(received !== undefined && { received }),\n repair,\n }),\n );\n }\n return rebuilt;\n}\n","import type {\n DefinitionDiagnostic,\n DefinitionPath,\n DefinitionSource,\n DocumentModelModule,\n Sha256Digest,\n UpgradeManifest,\n} from \"@powerhousedao/shared/document-model\";\nimport { existsSync } from \"node:fs\";\nimport { dirname, isAbsolute, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport {\n rejectionReceived,\n snapshotArray,\n snapshotRecord,\n} from \"../kernel/data-properties.js\";\nimport {\n compareDefinitionPaths,\n describeReceived,\n sortDefinitionDiagnostics,\n} from \"../kernel/diagnostics.js\";\nimport { compareCodeUnits } from \"../kernel/primitives.js\";\nimport {\n compareDefinitionSources,\n type InternalResolution,\n normalizeSpecifier,\n packageRoots,\n publicResolution,\n realModulePath,\n resolveDefinitionSources,\n} from \"./definition-source-resolution.js\";\nimport type {\n DefinitionSourceLoadRequest,\n DefinitionSourceResolution,\n DefinitionSourceSelectionRequest,\n LoadedDefinition,\n LoadedDefinitionSet,\n TypeScriptSourceImportInterface,\n} from \"./definition-source-types.js\";\nimport { toolingDiagnostics } from \"./diagnostic-codes.js\";\nimport {\n describeThrown,\n readProperty,\n structuredDiagnostics,\n} from \"./structured-diagnostics.js\";\n\ntype Manifest = UpgradeManifest<readonly number[]>;\n\ntype Collected = {\n readonly documentModels: LoadedDefinition<DocumentModelModule>[];\n readonly upgradeManifests: LoadedDefinition<Manifest>[];\n readonly diagnostics: DefinitionDiagnostic[];\n\n readonly visited: Map<object, number>;\n readonly claimed: Map<\n string,\n { readonly source: DefinitionSource; readonly path: DefinitionPath }\n >;\n};\n\ntype ImportedNamespace =\n | { readonly ok: true; readonly value: Readonly<Record<string, unknown>> }\n | {\n readonly ok: false;\n readonly diagnostics: (\n source: DefinitionSource,\n ) => readonly DefinitionDiagnostic[];\n };\n\nconst KEY_SEPARATOR = String.fromCharCode(0);\n\nfunction isSha256Digest(value: unknown): value is Sha256Digest {\n return typeof value === \"string\" && /^sha256:[0-9a-f]{64}$/.test(value);\n}\n\nfunction isVersionList(value: unknown): value is readonly number[] {\n return (\n Array.isArray(value) &&\n value.every(\n (version) => Number.isSafeInteger(version) && (version as number) > 0,\n )\n );\n}\n\nfunction isDocumentModelModule(record: Readonly<Record<string, unknown>>) {\n return (\n typeof record.reducer === \"function\" &&\n snapshotRecord(record.documentModel, undefined, []).ok\n );\n}\n\nfunction isUpgradeManifest(record: Readonly<Record<string, unknown>>) {\n return (\n typeof record.documentType === \"string\" &&\n Number.isSafeInteger(record.latestVersion) &&\n isVersionList(record.supportedVersions) &&\n snapshotRecord(record.upgrades, undefined, []).ok\n );\n}\n\nfunction familyMembers(\n record: Readonly<Record<string, unknown>>,\n): readonly unknown[] | undefined {\n if (typeof record.at !== \"function\" || record.upgradeManifest === undefined) {\n return undefined;\n }\n const modules = snapshotArray(record.modules, []);\n return modules.ok ? modules.value : undefined;\n}\n\nfunction documentTypeOf(module: unknown): string {\n const stored = snapshotRecord(\n (module as { documentModel?: unknown }).documentModel,\n undefined,\n [],\n );\n const global = stored.ok\n ? snapshotRecord(stored.value.global, undefined, [])\n : undefined;\n return global?.ok === true && typeof global.value.id === \"string\"\n ? global.value.id\n : \"\";\n}\n\nfunction extendSource(\n source: DefinitionSource,\n path: DefinitionPath,\n): DefinitionSource {\n const exportPath = [...(source.exportPath ?? []), ...path.map(String)];\n return {\n specifier: source.specifier,\n ...(exportPath.length > 0 && { exportPath }),\n };\n}\n\nfunction claim(\n collected: Collected,\n logicalKey: string,\n describe: string,\n source: DefinitionSource,\n path: DefinitionPath,\n): void {\n const existing = collected.claimed.get(logicalKey);\n if (existing === undefined) {\n collected.claimed.set(logicalKey, { source, path });\n return;\n }\n collected.diagnostics.push(\n toolingDiagnostics.create({\n code: \"PH-PKG-LOGICAL-COLLISION\",\n source,\n path,\n message: `Two different values both declare ${describe}, so a host registering this package would keep only one of them.`,\n expected: \"one value per logical definition\",\n received: describe,\n repair:\n \"Export one canonical value for this definition and remove the other source entry.\",\n related: [\n {\n source: existing.source,\n path: existing.path,\n message: \"The first value claiming it is here.\",\n },\n ],\n }),\n );\n}\n\nfunction collectDocumentModel(\n collected: Collected,\n value: object,\n source: DefinitionSource,\n path: DefinitionPath,\n): void {\n const module = value as DocumentModelModule;\n collected.documentModels.push({ source, path, value: module });\n const documentType = documentTypeOf(module);\n const version = (module as { version?: unknown }).version;\n\n if (documentType === \"\" || typeof version !== \"number\") return;\n claim(\n collected,\n [\"document-model\", documentType, String(version)].join(KEY_SEPARATOR),\n `document model ${documentType} version ${String(version)}`,\n source,\n path,\n );\n}\n\nfunction collectUpgradeManifest(\n collected: Collected,\n value: object,\n source: DefinitionSource,\n path: DefinitionPath,\n): void {\n const manifest = value as Manifest;\n collected.upgradeManifests.push({ source, path, value: manifest });\n claim(\n collected,\n [\"upgrade-manifest\", manifest.documentType].join(KEY_SEPARATOR),\n `the upgrade manifest of ${manifest.documentType}`,\n source,\n path,\n );\n}\n\nfunction visit(\n collected: Collected,\n value: unknown,\n source: DefinitionSource,\n path: DefinitionPath,\n): number {\n if (value === null || typeof value !== \"object\") return 0;\n const alias = collected.visited.get(value);\n if (alias !== undefined) return alias;\n\n collected.visited.set(value, 0);\n const found = walk(collected, value, source, path);\n collected.visited.set(value, found);\n return found;\n}\n\nfunction walk(\n collected: Collected,\n value: object,\n source: DefinitionSource,\n path: DefinitionPath,\n): number {\n const array = snapshotArray(value, path);\n if (array.ok) {\n return array.value.reduce<number>(\n (count, member, index) =>\n count + visit(collected, member, source, [...path, index]),\n 0,\n );\n }\n const plain = snapshotRecord(value, undefined, path);\n if (!plain.ok) {\n if (plain.reason !== \"accessor\" && plain.reason !== \"inspection-failed\") {\n return 0;\n }\n collected.diagnostics.push(\n toolingDiagnostics.create({\n code: \"PH-PKG-DEFINITION-UNINSPECTABLE\",\n source: extendSource(source, path),\n path,\n message: `This export could not be read safely (${plain.reason}).`,\n expected: \"a plain object, an array, or a materialized definition\",\n received: rejectionReceived(plain),\n repair:\n \"Export plain values: a getter or a Proxy hides what the loader reads.\",\n }),\n );\n return 0;\n }\n const record = plain.value;\n const members = familyMembers(record);\n if (members !== undefined) {\n const count = members.reduce<number>(\n (total, member, index) =>\n total + visit(collected, member, source, [...path, \"modules\", index]),\n 0,\n );\n return (\n count +\n visit(collected, record.upgradeManifest, source, [\n ...path,\n \"upgradeManifest\",\n ])\n );\n }\n if (isDocumentModelModule(record)) {\n collectDocumentModel(collected, value, extendSource(source, path), path);\n return 1;\n }\n if (isUpgradeManifest(record)) {\n collectUpgradeManifest(collected, value, extendSource(source, path), path);\n return 1;\n }\n return Object.keys(record)\n .sort(compareCodeUnits)\n .reduce<number>(\n (count, key) =>\n count + visit(collected, record[key], source, [...path, key]),\n 0,\n );\n}\n\nfunction checkManifestCoverage(collected: Collected): void {\n const versionsByType = new Map<string, number[]>();\n for (const entry of collected.documentModels) {\n const documentType = documentTypeOf(entry.value);\n const version = (entry.value as { version?: unknown }).version;\n if (documentType === \"\" || typeof version !== \"number\") continue;\n versionsByType.set(documentType, [\n ...(versionsByType.get(documentType) ?? []),\n version,\n ]);\n }\n const ascending = (left: number, right: number) => left - right;\n for (const manifest of collected.upgradeManifests) {\n const { documentType, supportedVersions, latestVersion, upgrades } =\n manifest.value;\n const definition = { kind: \"document-model\", key: documentType } as const;\n const loaded = [...(versionsByType.get(documentType) ?? [])].sort(\n ascending,\n );\n const declared = [...supportedVersions].sort(ascending);\n if (\n JSON.stringify(loaded) !== JSON.stringify(declared) ||\n latestVersion !== declared.at(-1)\n ) {\n collected.diagnostics.push(\n toolingDiagnostics.create({\n code: \"PH-DM-DECLARATION-INVALID\",\n source: manifest.source,\n definition,\n path: manifest.path,\n message:\n \"The upgrade manifest and the selected modules of this document type describe different version sets.\",\n expected: `supportedVersions ${JSON.stringify(loaded)} with latestVersion ${String(loaded.at(-1))}`,\n received: `supportedVersions ${JSON.stringify(declared)} with latestVersion ${String(latestVersion)}`,\n repair:\n \"Select the whole family that materialize returned, so its modules and its manifest stay one declaration.\",\n }),\n );\n continue;\n }\n const expected = declared.slice(1).map((version) => `v${version}`);\n const actual = Object.keys(upgrades).sort(compareCodeUnits);\n if (\n JSON.stringify(actual) !==\n JSON.stringify([...expected].sort(compareCodeUnits))\n ) {\n collected.diagnostics.push(\n toolingDiagnostics.create({\n code: \"PH-DM-DECLARATION-INVALID\",\n source: manifest.source,\n definition,\n path: [...manifest.path, \"upgrades\"],\n message:\n \"The upgrade manifest does not carry exactly one transition for each version after the first.\",\n expected: expected.join(\", \") || \"no transitions\",\n received: actual.join(\", \") || \"no transitions\",\n repair: \"Publish the manifest materialize returned, unmodified.\",\n }),\n );\n }\n }\n}\n\n/**\n * A native namespace carries a `Symbol.toStringTag` key and Vite's SSR\n * namespace exposes exports through getters; the data-property rules would\n * reject both without this flattening.\n */\nfunction namespaceSnapshot(value: unknown): Readonly<Record<string, unknown>> {\n if (\n value === null ||\n (typeof value !== \"object\" && typeof value !== \"function\")\n ) {\n throw new TypeError(\n `The import adapter returned ${describeReceived(value)} instead of a module namespace.`,\n );\n }\n return Object.freeze({ ...(value as Record<string, unknown>) });\n}\n\nfunction unresolvedBareImportOf(error: unknown): string | undefined {\n if (!(error instanceof Error)) return undefined;\n const match =\n /^Cannot find (?:package|module) '([^']+)' imported from '?(.+?)'?$/m.exec(\n error.message,\n );\n if (match === null) return undefined;\n const [, specifier, importer] = match;\n if (/^(?:[./\\\\]|[a-zA-Z][\\w+.-]*:)/.test(specifier)) return undefined;\n const name = specifier\n .split(\"/\")\n .slice(0, specifier.startsWith(\"@\") ? 2 : 1)\n .join(\"/\");\n const from = importer.startsWith(\"file:\")\n ? fileURLToPath(importer)\n : importer;\n if (!isAbsolute(from)) return undefined;\n for (let directory = dirname(from); ; directory = dirname(directory)) {\n if (existsSync(join(directory, \"node_modules\", name))) return undefined;\n if (dirname(directory) === directory) return name;\n }\n}\n\nfunction importDiagnostics(\n error: unknown,\n source: DefinitionSource,\n missing: boolean,\n): readonly DefinitionDiagnostic[] {\n if (missing) {\n return [\n toolingDiagnostics.create({\n code: \"PH-IMPORT-FAILED\",\n source,\n path: [],\n message: \"definitionSources lists a module that does not exist.\",\n expected: \"an existing module inside the package\",\n received: source.specifier,\n repair:\n \"Fix the specifier, or remove the entry from definitionSources.entries in powerhouse.config.json.\",\n }),\n ];\n }\n const structured = structuredDiagnostics(error, source);\n if (structured !== undefined) return structured;\n const unresolved = unresolvedBareImportOf(error);\n return [\n toolingDiagnostics.create({\n code: \"PH-IMPORT-FAILED\",\n source,\n path: [],\n message:\n unresolved === undefined\n ? \"This definition source could not be imported.\"\n : `This definition source could not resolve the import ${unresolved}.`,\n expected:\n unresolved === undefined\n ? \"an importable TypeScript module\"\n : `a project alias or installed dependency resolving ${unresolved}`,\n received: describeThrown(error),\n repair:\n unresolved === undefined\n ? \"Fix this module or one of its imports, then load it again.\"\n : `Check the project tsconfig paths and package dependencies for ${unresolved}. If it is an npm package, list it in package.json and install dependencies.`,\n }),\n ];\n}\n\ntype SelectedExport =\n | { readonly ok: true; readonly value: unknown }\n | { readonly ok: false; readonly diagnostic: DefinitionDiagnostic };\n\nfunction selectExport(\n source: DefinitionSource,\n namespace: Readonly<Record<string, unknown>>,\n): SelectedExport {\n let current: unknown = namespace;\n const exportPath = source.exportPath ?? [];\n for (const [index, key] of exportPath.entries()) {\n const read =\n current !== null &&\n (typeof current === \"object\" || typeof current === \"function\")\n ? readProperty(current, key)\n : undefined;\n if (read?.ok !== true) {\n return {\n ok: false,\n diagnostic: toolingDiagnostics.create({\n code: \"PH-CONFIG-SOURCE-INVALID\",\n source,\n path: [\"exportPath\", index],\n message:\n read === undefined\n ? `The export pointer reads \"${key}\" from a value that has no properties.`\n : `The configured export \"${key}\" is absent, or is not a plain readable property.`,\n expected: read === undefined ? \"an object or a namespace\" : key,\n received: read === undefined ? describeReceived(current) : \"missing\",\n repair:\n \"Point the export pointer at an exact exported property, spelled as it is exported.\",\n }),\n };\n }\n current = read.value;\n }\n return { ok: true, value: current };\n}\n\nfunction sortBySource<T>(\n entries: readonly LoadedDefinition<T>[],\n): readonly LoadedDefinition<T>[] {\n return [...entries].sort(\n (left, right) =>\n compareDefinitionSources(left.source, right.source) ||\n compareDefinitionPaths(left.path, right.path),\n );\n}\n\nfunction revisionDiagnostic(revision: unknown): DefinitionDiagnostic {\n return toolingDiagnostics.create({\n code: \"PH-CONFIG-SOURCE-INVALID\",\n path: [\"packageRevision\"],\n message:\n \"The package revision is not a SHA-256 identifier, so no import can be bound to it.\",\n expected: \"sha256: followed by 64 lowercase hexadecimal digits\",\n received:\n typeof revision === \"string\" ? revision : describeReceived(revision),\n repair: \"Pass a revision digest of the package's current files.\",\n });\n}\n\nfunction refusedModule(\n specifier: `./${string}`,\n code: \"PH-CONFIG-SOURCE-INVALID\" | \"PH-CONFIG-SOURCE-OUTSIDE-PACKAGE\",\n message: string,\n): { readonly ok: false; readonly diagnostic: DefinitionDiagnostic } {\n return {\n ok: false,\n diagnostic: toolingDiagnostics.create({\n code,\n source: { specifier },\n path: [],\n message,\n expected:\n \"a './' module path whose real path stays inside the package root\",\n received: specifier,\n repair:\n \"Keep the module inside the package, and do not reach it through a symlink that leaves the package.\",\n }),\n };\n}\n\ntype PackageModule = {\n readonly specifier: `./${string}`;\n readonly packageRootIdentity: string;\n readonly moduleIdentity: string;\n};\n\n/** The selected sources' containment rules, so a module outside the package is never imported. */\nfunction containedPackageModule(\n request: DefinitionSourceSelectionRequest & {\n readonly specifier: `./${string}`;\n },\n):\n | ({ readonly ok: true } & PackageModule)\n | { readonly ok: false; readonly diagnostic: DefinitionDiagnostic } {\n const { packageRoot, packageRootIdentity } = packageRoots(request);\n const normalized = normalizeSpecifier(request.specifier);\n if (!normalized.ok) {\n return refusedModule(\n request.specifier,\n normalized.code,\n normalized.message,\n );\n }\n const real = realModulePath(\n packageRoot,\n packageRootIdentity,\n normalized.specifier,\n );\n if (real.ok) {\n return {\n ok: true,\n specifier: normalized.specifier,\n packageRootIdentity,\n moduleIdentity: real.moduleIdentity,\n };\n }\n return real.reason === \"outside\"\n ? refusedModule(\n request.specifier,\n \"PH-CONFIG-SOURCE-OUTSIDE-PACKAGE\",\n \"The package module resolves through a symlink that leaves the package root.\",\n )\n : refusedModule(\n request.specifier,\n \"PH-CONFIG-SOURCE-INVALID\",\n \"The package module path could not be resolved.\",\n );\n}\n\nfunction empty(resolution: DefinitionSourceResolution): LoadedDefinitionSet {\n return { ...resolution, documentModels: [], upgradeManifests: [] };\n}\n\n/**\n * @experimental Imports the selected definition sources and finds the\n * materialized document models, families and upgrade manifests they export.\n * It folds aliases, reports two values that claim one `documentType@version`,\n * and returns everything sorted by source, so neither config order nor\n * import completion order changes a result. Validity belongs to the\n * adapters; registration belongs to the host.\n */\nexport class DefinitionSourceLoader {\n readonly #importer: TypeScriptSourceImportInterface;\n readonly #imports = new Map<\n string,\n Promise<Readonly<Record<string, unknown>>>\n >();\n #revision: Sha256Digest | undefined;\n\n constructor(importer: TypeScriptSourceImportInterface) {\n this.#importer = importer;\n }\n\n resolve(\n request: DefinitionSourceSelectionRequest,\n ): DefinitionSourceResolution {\n return publicResolution(resolveDefinitionSources(request));\n }\n\n async normalizeDefinitionSources(\n request: DefinitionSourceLoadRequest,\n ): Promise<LoadedDefinitionSet> {\n request.signal?.throwIfAborted();\n const resolution = resolveDefinitionSources(request);\n if (resolution.status !== \"ready\") {\n return empty(publicResolution(resolution));\n }\n if (!isSha256Digest(request.packageRevision)) {\n return empty({\n packageRoot: resolution.packageRoot,\n sourceSet: resolution.sourceSet,\n status: \"failed\",\n diagnostics: [revisionDiagnostic(request.packageRevision)],\n });\n }\n await this.#retainRevision(request.packageRevision);\n const namespaces = await this.#importModules(resolution, request);\n request.signal?.throwIfAborted();\n\n const collected: Collected = {\n documentModels: [],\n upgradeManifests: [],\n diagnostics: [],\n visited: new Map(),\n claimed: new Map(),\n };\n\n for (const entry of resolution.resolved) {\n const namespace = namespaces.get(entry.moduleIdentity);\n if (namespace === undefined) continue;\n if (!namespace.ok) {\n collected.diagnostics.push(...namespace.diagnostics(entry.source));\n continue;\n }\n const selected = selectExport(entry.source, namespace.value);\n if (!selected.ok) {\n collected.diagnostics.push(selected.diagnostic);\n continue;\n }\n if (visit(collected, selected.value, entry.source, []) === 0) {\n collected.diagnostics.push(\n toolingDiagnostics.create({\n code: \"PH-PKG-DEFINITION-UNRECOGNIZED\",\n source: entry.source,\n path: [],\n message:\n \"This source exports no materialized document model, so selecting it loads nothing.\",\n expected:\n \"a module or family materialize returned, or a collection holding them\",\n received: \"no recognized definition\",\n repair:\n \"Point this entry at the export that materialize(...) returned.\",\n }),\n );\n }\n }\n checkManifestCoverage(collected);\n\n const diagnostics = sortDefinitionDiagnostics(collected.diagnostics);\n return {\n packageRoot: resolution.packageRoot,\n sourceSet: resolution.sourceSet,\n status: diagnostics.some(({ severity }) => severity === \"error\")\n ? \"failed\"\n : \"ready\",\n diagnostics,\n documentModels: sortBySource(collected.documentModels),\n upgradeManifests: sortBySource(collected.upgradeManifests),\n };\n }\n\n /**\n * @experimental Imports one package module through the same importer and\n * package revision as the selected sources, so a module both reach is\n * evaluated once. A module outside the package root is refused as an\n * outside source is. Experimental: tooling uses it for the project scalars\n * module while code-first projects are introduced.\n */\n async importPackageModule(\n request: DefinitionSourceLoadRequest & {\n readonly specifier: `./${string}`;\n },\n ): Promise<\n | {\n readonly ok: true;\n readonly namespace: Readonly<Record<string, unknown>>;\n }\n | {\n readonly ok: false;\n readonly diagnostics: readonly DefinitionDiagnostic[];\n }\n > {\n request.signal?.throwIfAborted();\n if (!isSha256Digest(request.packageRevision)) {\n return {\n ok: false,\n diagnostics: [revisionDiagnostic(request.packageRevision)],\n };\n }\n const contained = containedPackageModule(request);\n if (!contained.ok)\n return { ok: false, diagnostics: [contained.diagnostic] };\n await this.#retainRevision(request.packageRevision);\n const imported = await this.#import(contained, request);\n return imported.ok\n ? { ok: true, namespace: imported.value }\n : {\n ok: false,\n diagnostics: imported.diagnostics({ specifier: request.specifier }),\n };\n }\n\n async dispose(): Promise<void> {\n const revision = this.#revision;\n this.#imports.clear();\n this.#revision = undefined;\n if (revision !== undefined) {\n await this.#importer.disposeRevision?.(revision);\n }\n }\n\n async #retainRevision(revision: Sha256Digest): Promise<void> {\n if (this.#revision === revision) return;\n const superseded = this.#revision;\n this.#imports.clear();\n this.#revision = revision;\n if (superseded !== undefined) {\n await this.#importer.disposeRevision?.(superseded);\n }\n }\n\n /** One evaluation per module and revision, whichever path asks first. */\n async #import(\n module: PackageModule,\n request: DefinitionSourceLoadRequest,\n ): Promise<ImportedNamespace> {\n const { moduleIdentity } = module;\n let namespace = this.#imports.get(moduleIdentity);\n if (namespace === undefined) {\n namespace = this.#importer.importModule({\n // Use the real root so symlink aliases cannot evaluate the module twice.\n packageRoot: module.packageRootIdentity,\n specifier: module.specifier,\n packageRevision: request.packageRevision,\n ...(request.signal !== undefined && { signal: request.signal }),\n });\n this.#imports.set(moduleIdentity, namespace);\n void namespace.catch(() => this.#imports.delete(moduleIdentity));\n }\n try {\n return { ok: true, value: namespaceSnapshot(await namespace) };\n } catch (error) {\n const missing = !existsSync(moduleIdentity);\n return {\n ok: false,\n diagnostics: (source) => importDiagnostics(error, source, missing),\n };\n }\n }\n\n async #importModules(\n resolution: InternalResolution,\n request: DefinitionSourceLoadRequest,\n ): Promise<Map<string, ImportedNamespace>> {\n const results = new Map<string, ImportedNamespace>();\n // Evaluate serially so aliases and their family share one module evaluation.\n for (const { moduleIdentity, source } of resolution.resolved) {\n if (results.has(moduleIdentity)) continue;\n const module = {\n specifier: source.specifier,\n packageRootIdentity: resolution.packageRootIdentity,\n moduleIdentity,\n };\n results.set(moduleIdentity, await this.#import(module, request));\n }\n return results;\n }\n}\n","import { compilerDiagnostics } from \"./diagnostic-codes.js\";\nimport type { DefinitionDiagnostic } from \"@powerhousedao/shared/document-model\";\nimport { camelCase, constantCase, pascalCase } from \"change-case\";\n\ntype Digit = \"0\" | \"1\" | \"2\" | \"3\" | \"4\" | \"5\" | \"6\" | \"7\" | \"8\" | \"9\";\n\ntype ActionTypeWords<\n TKey extends string,\n TPrevious extends string = \"\",\n TResult extends string = \"\",\n TSeparator extends string = \"\",\n> = TKey extends `${infer TFirst}${infer TRest}`\n ? TFirst extends \"_\"\n ? ActionTypeWords<TRest, \"\", TResult, TResult extends \"\" ? \"\" : \"_\">\n : ActionTypeWords<\n TRest,\n TFirst,\n `${TResult}${TSeparator extends \"_\"\n ? \"_\"\n : TFirst extends Lowercase<TFirst>\n ? \"\"\n : TPrevious extends \"\"\n ? \"\"\n : TPrevious extends Digit\n ? \"_\"\n : TPrevious extends Uppercase<TPrevious>\n ? TRest extends `${infer TNext}${string}`\n ? TNext extends Uppercase<TNext>\n ? \"\"\n : \"_\"\n : \"\"\n : \"_\"}${Uppercase<TFirst>}`\n >\n : TResult;\n\nexport type DocumentModelActionType<TKey extends string> = string extends TKey\n ? string\n : ActionTypeWords<TKey>;\n\nexport type DocumentModelNames = {\n readonly documentType: string;\n readonly graphQLName: string;\n readonly globalStateRootName: string;\n readonly localStateRootName: string;\n};\n\ntype DocumentModelModuleNames = {\n readonly storedName: string;\n readonly operationsInterfaceName: string;\n readonly actionNamespaceName: string;\n};\n\ntype DocumentModelOperationNames = {\n readonly storedName: string;\n readonly actionType: string;\n readonly inputTypeName: string;\n readonly creatorKey: string;\n readonly reducerMethod: string;\n};\n\ntype DocumentModelErrorNames = {\n readonly key: string;\n readonly storedName: string;\n readonly storedCode: string;\n};\n\nexport function deriveDocumentModelNames(\n model: { readonly id: string; readonly name: string },\n overrides: Partial<DocumentModelNames> = {},\n): DocumentModelNames {\n const graphQLName = overrides.graphQLName ?? pascalCase(model.name);\n return {\n documentType: overrides.documentType ?? model.id,\n graphQLName,\n globalStateRootName: overrides.globalStateRootName ?? `${graphQLName}State`,\n localStateRootName:\n overrides.localStateRootName ?? `${graphQLName}LocalState`,\n };\n}\n\nexport function deriveDocumentModelModuleNames(\n modelName: string,\n moduleKey: string,\n overrides: Partial<DocumentModelModuleNames> = {},\n): DocumentModelModuleNames {\n const modulePascal = pascalCase(moduleKey);\n return {\n storedName: overrides.storedName ?? modulePascal,\n operationsInterfaceName:\n overrides.operationsInterfaceName ??\n `${pascalCase(modelName)}${modulePascal}Operations`,\n actionNamespaceName:\n overrides.actionNamespaceName ??\n `${camelCase(modelName)}${modulePascal}Actions`,\n };\n}\n\nexport function deriveDocumentModelOperationNames(\n operationKey: string,\n overrides: Partial<DocumentModelOperationNames> = {},\n): DocumentModelOperationNames {\n const operationPascal = pascalCase(operationKey);\n const actionType = overrides.actionType ?? constantCase(operationKey);\n return {\n storedName: overrides.storedName ?? operationPascal,\n actionType,\n inputTypeName: overrides.inputTypeName ?? `${operationPascal}Input`,\n creatorKey: overrides.creatorKey ?? camelCase(constantCase(operationKey)),\n reducerMethod:\n overrides.reducerMethod ?? `${camelCase(operationKey)}Operation`,\n };\n}\n\n// Action types the base reducer or the reactor reduces before a model's own\n// reducer sees them, and RETRACT, which replay reads as a retraction. NOOP is\n// left out because the model's reducer still runs.\nexport const PLATFORM_ACTION_TYPES: ReadonlySet<string> = new Set([\n \"SET_NAME\",\n \"SET_PREFERRED_EDITOR\",\n \"UNDO\",\n \"REDO\",\n \"RETRACT\",\n \"CREATE_DOCUMENT\",\n \"DELETE_DOCUMENT\",\n \"UPGRADE_DOCUMENT\",\n \"ADD_RELATIONSHIP\",\n \"REMOVE_RELATIONSHIP\",\n \"UPDATE_RELATIONSHIP\",\n \"PURGE_DOCUMENT\",\n]);\n\nexport function deriveOperationErrorClassName(errorKey: string): string {\n return pascalCase(errorKey);\n}\n\nexport function deriveDocumentModelErrorNames(\n errorKey: string,\n authored: {\n readonly name?: string | null;\n readonly code?: string | null;\n } = {},\n): DocumentModelErrorNames {\n return {\n key: errorKey,\n storedName: authored.name ?? errorKey,\n storedCode: authored.code ?? errorKey,\n };\n}\n\nexport type DerivedOperationNames = {\n readonly key: string;\n readonly names: DocumentModelOperationNames;\n};\n\nexport type DerivedModuleNames = {\n readonly key: string;\n readonly names: DocumentModelModuleNames;\n readonly operations: readonly DerivedOperationNames[];\n};\n\ntype Claim = {\n readonly path: readonly string[];\n readonly label: string;\n};\n\ntype NameClaim = {\n readonly kind: string;\n readonly slot: string;\n readonly value: string;\n};\n\ntype Collision = {\n readonly first: Claim;\n readonly names: string[];\n actionType: boolean;\n};\n\nconst MODULE_NAME_KINDS = [\n \"storedName\",\n \"operationsInterfaceName\",\n \"actionNamespaceName\",\n] as const satisfies readonly (keyof DocumentModelModuleNames)[];\n\nconst OPERATION_NAME_KINDS = [\n \"actionType\",\n \"storedName\",\n \"inputTypeName\",\n \"creatorKey\",\n \"reducerMethod\",\n] as const satisfies readonly (keyof DocumentModelOperationNames)[];\n\nfunction nameSlot(\n owner: \"module\" | \"operation\",\n scope: string,\n kind: string,\n value: string,\n): string {\n return JSON.stringify([owner, scope, kind, value]);\n}\n\nfunction moduleNameClaims(\n names: DocumentModelModuleNames,\n): readonly NameClaim[] {\n return MODULE_NAME_KINDS.map((kind) => ({\n kind,\n slot: nameSlot(\"module\", \"model\", kind, names[kind]),\n value: names[kind],\n }));\n}\n\nfunction operationNameClaims(\n moduleKey: string,\n names: DocumentModelOperationNames,\n): readonly NameClaim[] {\n return OPERATION_NAME_KINDS.map((kind) => {\n const scope =\n kind === \"storedName\" || kind === \"reducerMethod\" ? moduleKey : \"model\";\n return {\n kind,\n slot: nameSlot(\"operation\", scope, kind, names[kind]),\n value: names[kind],\n };\n });\n}\n\nfunction claim(\n claims: Map<string, Claim>,\n claimant: Claim,\n nameClaims: readonly NameClaim[],\n): readonly Collision[] {\n const collisions = new Map<Claim, Collision>();\n for (const { kind, slot, value } of nameClaims) {\n const first = claims.get(slot);\n if (first === undefined) {\n claims.set(slot, claimant);\n continue;\n }\n const collision = collisions.get(first) ?? {\n first,\n names: [],\n actionType: false,\n };\n collision.names.push(`${kind} ${JSON.stringify(value)}`);\n if (kind === \"actionType\") collision.actionType = true;\n collisions.set(first, collision);\n }\n return [...collisions.values()];\n}\n\nfunction collisionDiagnostic(\n claimant: Claim,\n collision: Collision,\n): DefinitionDiagnostic {\n const list = collision.names.join(\", \");\n return compilerDiagnostics.create({\n code: collision.actionType\n ? \"PH-DM-DUPLICATE-ACTION\"\n : \"PH-DM-DUPLICATE-NAME\",\n path: claimant.path,\n message: `${claimant.label} derives ${list}, already derived by ${collision.first.label}.`,\n expected: `distinct derived names for ${claimant.label} and ${collision.first.label}`,\n received: list,\n repair: `Rename ${claimant.label} or ${collision.first.label} so their derived names differ.`,\n related: [\n {\n path: collision.first.path,\n message: `${collision.first.label} derives the same ${collision.names.length === 1 ? \"name\" : \"names\"}.`,\n },\n ],\n });\n}\n\nexport function checkDerivedNameCollisions(\n modules: readonly DerivedModuleNames[],\n): readonly DefinitionDiagnostic[] {\n const claims = new Map<string, Claim>();\n const diagnostics: DefinitionDiagnostic[] = [];\n for (const module of modules) {\n const moduleClaim: Claim = {\n path: [\"modules\", module.key],\n label: `module ${JSON.stringify(module.key)}`,\n };\n for (const collision of claim(\n claims,\n moduleClaim,\n moduleNameClaims(module.names),\n )) {\n diagnostics.push(collisionDiagnostic(moduleClaim, collision));\n }\n for (const operation of module.operations) {\n const operationClaim: Claim = {\n path: [\"modules\", module.key, \"operations\", operation.key],\n label: `operation ${JSON.stringify(`${module.key}.${operation.key}`)}`,\n };\n for (const collision of claim(\n claims,\n operationClaim,\n operationNameClaims(module.key, operation.names),\n )) {\n diagnostics.push(collisionDiagnostic(operationClaim, collision));\n }\n }\n }\n return diagnostics;\n}\n\n/** The symbol spellings codegen derives from a stored schema-first name. */\nexport function deriveDocumentModelSymbolNames(name: string) {\n return {\n typeName: pascalCase(name),\n memberName: camelCase(name),\n constantName: constantCase(name),\n };\n}\n","import { defineDiagnosticCatalog } from \"../../kernel/diagnostics.js\";\nimport { toolingDiagnostics } from \"../diagnostic-codes.js\";\n\nexport const checkDiagnostics = defineDiagnosticCatalog(\n {\n \"PH-DM-DUPLICATE-ERROR-CODE\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"Two errors of one operation persist the same error code, so a caller cannot tell them apart\",\n },\n \"PH-DM-ERROR-CLASS-CONFLICT\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"Two errors of one module generate the same error class with different codes\",\n },\n \"PH-PKG-SCALAR-CONFLICT\": {\n severity: \"error\",\n phase: \"package\",\n meaning:\n \"Two models of one package use different project scalars with one name, and a host declares each scalar once\",\n },\n \"PH-PKG-DEFINITION-UNREGISTERED\": {\n severity: \"error\",\n phase: \"package\",\n meaning:\n \"A code-first document model under the document models directory is reached by no definitionSources entry, so the package leaves it out\",\n },\n },\n toolingDiagnostics,\n);\n\nexport type CheckDiagnosticCode = keyof typeof checkDiagnostics.codes;\n","import type {\n DefinitionRef,\n DocumentModelSpecificationDefinition,\n} from \"@powerhousedao/shared/document-model\";\nimport type { NormalizedDocumentModelArtifact } from \"../adapters/types.js\";\n\n/**\n * The specification an artifact serves, and its index in the history. Every\n * member of a family carries the whole history, so a check that read every\n * specification of every artifact would report one defect once per member.\n */\nexport function servedSpecification(artifact: NormalizedDocumentModelArtifact):\n | {\n readonly specification: DocumentModelSpecificationDefinition;\n readonly index: number;\n }\n | undefined {\n const index = artifact.definition.specifications.findIndex(\n ({ version }) => version === artifact.version,\n );\n return index === -1\n ? undefined\n : { specification: artifact.definition.specifications[index], index };\n}\n\nexport function documentModelRef(\n artifact: NormalizedDocumentModelArtifact,\n): DefinitionRef {\n return {\n kind: \"document-model\",\n key: artifact.documentType,\n version: artifact.version,\n };\n}\n","import type {\n DefinitionDiagnostic,\n DefinitionPath,\n} from \"@powerhousedao/shared/document-model\";\nimport {\n deriveOperationErrorClassName,\n PLATFORM_ACTION_TYPES,\n} from \"../../../compiler/naming.js\";\nimport type { NormalizedDocumentModelArtifact } from \"../../adapters/types.js\";\nimport {\n type CheckDiagnosticCode,\n checkDiagnostics,\n} from \"../diagnostic-codes.js\";\nimport {\n documentModelRef,\n servedSpecification,\n} from \"../../report/served-specification.js\";\nimport type { DefinitionCheck } from \"../types.js\";\n\ntype Claim = { readonly path: DefinitionPath; readonly label: string };\n\n/** Codegen's rule: an empty or absent code falls back to the class name. */\nfunction effectiveErrorCode(code: string | null, className: string): string {\n return code?.trim() || className;\n}\n\n/**\n * The compiler refuses duplicate module keys, action types and creator keys,\n * an action type the document runtime owns, and an error class with two codes\n * in one module, before a code-first module exists, so for those this check fires only on a stored schema-first model.\n * Two errors of one operation sharing a code pass the compiler in both modes.\n */\nfunction duplicates(\n artifact: NormalizedDocumentModelArtifact,\n): readonly DefinitionDiagnostic[] {\n const served = servedSpecification(artifact);\n if (served === undefined) return [];\n const { specification, index } = served;\n const diagnostics: DefinitionDiagnostic[] = [];\n const report = (\n code: CheckDiagnosticCode,\n claimant: Claim,\n first: Claim,\n detail: {\n readonly message: string;\n readonly expected: string;\n readonly received: string;\n readonly repair: string;\n },\n ) =>\n diagnostics.push(\n checkDiagnostics.create({\n code,\n source: artifact.source,\n definition: documentModelRef(artifact),\n path: claimant.path,\n ...detail,\n related: [\n {\n source: artifact.source,\n path: first.path,\n message: `${first.label} claims it first.`,\n },\n ],\n }),\n );\n const shared = (\n code: CheckDiagnosticCode,\n claimant: Claim,\n first: Claim,\n [kind, value]: readonly [string, string],\n repair: string,\n ) =>\n report(code, claimant, first, {\n message: `${claimant.label} and ${first.label} share the ${kind} ${value}.`,\n expected: `one declaration per ${kind}`,\n received: value,\n repair,\n });\n\n const modules = new Map<string, Claim>();\n const actionTypes = new Map<string, Claim>();\n const operationKeys = new Map<string, Claim>();\n specification.modules.forEach((module, moduleIndex) => {\n const modulePath = [\"specifications\", index, \"modules\", moduleIndex];\n const moduleClaim = {\n path: modulePath,\n label: `module ${JSON.stringify(module.key)}`,\n };\n const firstModule = modules.get(module.key);\n if (firstModule === undefined) modules.set(module.key, moduleClaim);\n else {\n shared(\n \"PH-DM-DUPLICATE-NAME\",\n moduleClaim,\n firstModule,\n [\"key\", module.key],\n \"Rename one of the modules.\",\n );\n }\n const errorClasses = new Map<string, Claim & { readonly code: string }>();\n module.operations.forEach((operation, operationIndex) => {\n const operationPath = [...modulePath, \"operations\", operationIndex];\n const claim = {\n path: operationPath,\n label: `operation ${JSON.stringify(`${module.key}.${operation.key}`)}`,\n };\n if (PLATFORM_ACTION_TYPES.has(operation.actionType)) {\n diagnostics.push(\n checkDiagnostics.create({\n code: \"PH-DM-DUPLICATE-ACTION\",\n source: artifact.source,\n definition: documentModelRef(artifact),\n path: [...operationPath, \"key\"],\n message: `${claim.label} has action type ${operation.actionType}, which the document runtime reduces itself, so this operation's reducer would never run.`,\n expected: \"an action type the document runtime does not own\",\n received: operation.actionType,\n repair: \"Rename the operation.\",\n }),\n );\n }\n const firstAction = actionTypes.get(operation.actionType);\n const firstKey = operationKeys.get(operation.key);\n if (firstAction !== undefined) {\n shared(\n \"PH-DM-DUPLICATE-ACTION\",\n claim,\n firstAction,\n [\"action type\", operation.actionType],\n \"Rename one of the operations; a replayed history cannot tell which reducer wrote a shared action type.\",\n );\n } else if (firstKey !== undefined) {\n shared(\n \"PH-DM-DUPLICATE-NAME\",\n claim,\n firstKey,\n [\"creator key\", operation.key],\n \"Rename one of the operations; action creators share one namespace.\",\n );\n }\n actionTypes.set(operation.actionType, firstAction ?? claim);\n operationKeys.set(operation.key, firstKey ?? claim);\n\n const errorKeys = new Map<string, Claim>();\n const errorCodes = new Map<string, Claim>();\n operation.errors.forEach((error, errorIndex) => {\n const errorClaim = {\n path: [...operationPath, \"errors\", errorIndex],\n label: `error ${JSON.stringify(error.key)}`,\n };\n const className = deriveOperationErrorClassName(\n error.name ?? error.key,\n );\n const code = effectiveErrorCode(error.code, className);\n const sameKey = errorKeys.get(error.key);\n const sameCode = errorCodes.get(code);\n const sameClass = errorClasses.get(className);\n if (sameKey !== undefined) {\n shared(\n \"PH-DM-DUPLICATE-NAME\",\n errorClaim,\n sameKey,\n [\"key\", error.key],\n \"Rename one of the errors; each generates its own class.\",\n );\n } else if (sameCode !== undefined) {\n shared(\n \"PH-DM-DUPLICATE-ERROR-CODE\",\n errorClaim,\n sameCode,\n [\"code\", code],\n \"Give each error of the operation its own code, so a caller can tell them apart.\",\n );\n } else if (sameClass !== undefined && sameClass.code !== code) {\n report(\"PH-DM-ERROR-CLASS-CONFLICT\", errorClaim, sameClass, {\n message: `${errorClaim.label} of ${claim.label} gives the error class ${className} the code ${JSON.stringify(code)}, and ${sameClass.label} gives it ${JSON.stringify(sameClass.code)}.`,\n expected: sameClass.code,\n received: code,\n repair: `Give both ${className} errors the same code, or give one another name; a module generates one ${className} class.`,\n });\n }\n errorKeys.set(error.key, sameKey ?? errorClaim);\n errorCodes.set(code, sameCode ?? errorClaim);\n if (sameClass === undefined) {\n errorClasses.set(className, {\n ...errorClaim,\n label: `${errorClaim.label} of ${claim.label}`,\n code,\n });\n }\n });\n });\n });\n return diagnostics;\n}\n\nexport const duplicateIdentitiesCheck: DefinitionCheck = {\n name: \"duplicate-identities\",\n run: ({ artifacts }) => artifacts.flatMap(duplicates),\n};\n","import type { LocationFreeGraphQLDocumentNode } from \"@powerhousedao/shared/document-model\";\nimport type * as GraphQL from \"graphql\";\nimport type { validateSDL } from \"graphql/validation/validate.js\";\nimport { createRequire } from \"node:module\";\n\n/** graphql-js, plus the SDL validation its package index does not export. */\nexport type GraphQLModule = typeof GraphQL & {\n readonly validateSDL: typeof validateSDL;\n};\n\nlet graphql: GraphQLModule | undefined;\n\n/**\n * `graphql` is an optional peer: only tooling that reads SDL needs it, and a\n * package that imports document-model at runtime must not pay for it.\n */\nexport function loadGraphQL(): GraphQLModule {\n if (graphql !== undefined) return graphql;\n const require = createRequire(import.meta.url);\n let loaded: unknown;\n let validation: Partial<Pick<GraphQLModule, \"validateSDL\">>;\n try {\n loaded = require(\"graphql\");\n validation = require(\"graphql/validation/validate.js\") as typeof validation;\n } catch (error) {\n throw new Error(\n \"Reading GraphQL SDL needs the optional peer dependency graphql@^16. Install it in the package that runs this tool.\",\n { cause: error },\n );\n }\n if (\n loaded === null ||\n typeof loaded !== \"object\" ||\n typeof (loaded as Partial<GraphQLModule>).parse !== \"function\" ||\n typeof (loaded as Partial<GraphQLModule>).buildASTSchema !== \"function\" ||\n typeof validation.validateSDL !== \"function\"\n ) {\n throw new Error(\n \"The installed graphql package does not export parse, buildASTSchema and validateSDL; install graphql@^16.\",\n );\n }\n graphql = {\n ...(loaded as typeof GraphQL),\n validateSDL: validation.validateSDL,\n };\n return graphql;\n}\n\nfunction withoutLocations(node: unknown): unknown {\n if (Array.isArray(node)) return node.map(withoutLocations);\n if (node === null || typeof node !== \"object\") return node;\n return Object.fromEntries(\n Object.entries(node)\n .filter(([key, value]) => key !== \"loc\" && value !== undefined)\n .map(([key, value]) => [key, withoutLocations(value)]),\n );\n}\n\nexport const EMPTY_DOCUMENT: LocationFreeGraphQLDocumentNode = {\n kind: \"Document\",\n definitions: [],\n};\n\n/** Parses one stored SDL segment. A missing `graphql` peer throws; bad SDL does not. */\nexport function parseSchema(\n sdl: string,\n):\n | { readonly ok: true; readonly document: LocationFreeGraphQLDocumentNode }\n | { readonly ok: false; readonly message: string } {\n if (sdl.trim() === \"\") return { ok: true, document: EMPTY_DOCUMENT };\n const { parse } = loadGraphQL();\n try {\n return {\n ok: true,\n document: withoutLocations(\n parse(sdl, { noLocation: true }),\n ) as LocationFreeGraphQLDocumentNode,\n };\n } catch (error) {\n return {\n ok: false,\n message: error instanceof Error ? error.message : String(error),\n };\n }\n}\n","import type {\n DefinitionDiagnostic,\n DefinitionPath,\n DocumentModelSpecificationDefinition,\n} from \"@powerhousedao/shared/document-model\";\nimport type { DocumentNode, GraphQLError } from \"graphql\";\nimport { scalarCatalog } from \"../../../../scalars/catalog.js\";\nimport type { NormalizedDocumentModelArtifact } from \"../../adapters/types.js\";\nimport { type GraphQLModule, loadGraphQL } from \"../../graphql/parse-schema.js\";\nimport {\n type CheckDiagnosticCode,\n checkDiagnostics,\n} from \"../diagnostic-codes.js\";\nimport {\n documentModelRef,\n servedSpecification,\n} from \"../../report/served-specification.js\";\nimport type { DefinitionCheck } from \"../types.js\";\n\ntype Node = {\n readonly kind: string;\n readonly name?: { readonly value: string };\n readonly interfaces?: readonly {\n readonly name: { readonly value: string };\n }[];\n};\n\n/** The top-level node an error node sits in, and where a diagnostic points for it. */\ntype Owner = {\n readonly name: string | undefined;\n readonly implements: readonly string[];\n readonly path: DefinitionPath;\n};\n\ntype ErrorCode = {\n readonly code: CheckDiagnosticCode;\n readonly repair: string;\n};\n\n/** The first graphql-js message pattern that matches picks the code. */\nconst ERROR_CODES: readonly (ErrorCode & { readonly pattern: RegExp })[] = [\n {\n pattern:\n /^(?:Interface field |Object field \\S+ includes required argument |Type \\S+ (?:must only implement|cannot implement|can only implement|must implement) )/,\n code: \"PH-DM-INTERFACE-INVALID\",\n repair:\n \"Give the type every field, argument and ancestor interface its interfaces declare, with compatible types.\",\n },\n {\n pattern: / must be (?:Input|Output) Type but got: /,\n code: \"PH-DM-TYPE-POSITION-INVALID\",\n repair:\n \"Reference input types only from input fields and arguments, and output types only from output fields.\",\n },\n {\n pattern: / within itself through a series of non-null fields: /,\n code: \"PH-DM-INPUT-CYCLE\",\n repair: \"Make one input field on the cycle nullable or a list.\",\n },\n];\n\nconst OTHER_ERROR: ErrorCode = {\n code: \"PH-DEF-COMPATIBILITY-INVALID\",\n repair:\n \"Correct the stored schema so graphql-js builds it; codegen and hosts build the same schema.\",\n};\n\n/** A model's schema has no operations, so graphql-js has no Query root to require. */\nconst NO_QUERY_ROOT = \"Query root type must be provided.\";\n\n/**\n * The SDL rules graphql-js applies, minus the directive rules: a stored\n * schema carries directive uses such as `@equals` without declaring them,\n * and codegen and hosts read them as annotations.\n */\nfunction sdlRules(graphql: GraphQLModule) {\n return [\n graphql.LoneSchemaDefinitionRule,\n graphql.UniqueOperationTypesRule,\n graphql.UniqueTypeNamesRule,\n graphql.UniqueEnumValueNamesRule,\n graphql.UniqueFieldDefinitionNamesRule,\n graphql.UniqueArgumentDefinitionNamesRule,\n graphql.UniqueDirectiveNamesRule,\n graphql.KnownTypeNamesRule,\n graphql.PossibleTypeExtensionsRule,\n graphql.UniqueArgumentNamesRule,\n graphql.UniqueInputFieldNamesRule,\n ];\n}\n\nconst NAMED_DEFINITION =\n /^(?:Scalar|Object|Interface|InputObject|Enum|Union)TypeDefinition$/;\n\n/**\n * Hosts keep the first definition of a repeated type name and codegen merges\n * the repeats, so a repeat is not an error here. Catalog and project scalars\n * the document uses without declaring become stub declarations, and a type\n * the document only extends gets an empty base to extend.\n */\nfunction validationDocument(\n nodes: readonly Node[],\n specification: DocumentModelSpecificationDefinition,\n): DocumentNode {\n const defined = new Set<string>();\n const definitions: object[] = nodes.filter((node) => {\n if (!NAMED_DEFINITION.test(node.kind) || node.name === undefined) {\n return true;\n }\n if (defined.has(node.name.value)) return false;\n defined.add(node.name.value);\n return true;\n });\n const define = (kind: string, value: string) => {\n if (defined.has(value)) return;\n defined.add(value);\n definitions.push({\n kind,\n name: { kind: \"Name\", value },\n directives: [],\n interfaces: [],\n fields: [],\n values: [],\n types: [],\n });\n };\n for (const name of [\n ...scalarCatalog.map((scalar) => scalar.name),\n ...specification.scalars.map((scalar) => scalar.name),\n ]) {\n define(\"ScalarTypeDefinition\", name);\n }\n for (const node of nodes) {\n if (node.kind.endsWith(\"TypeExtension\") && node.name !== undefined) {\n define(node.kind.replace(/Extension$/, \"Definition\"), node.name.value);\n }\n }\n return { kind: \"Document\", definitions } as unknown as DocumentNode;\n}\n\n/**\n * Maps every object inside each top-level node to that node's owner. A\n * type's first definition points at its structured type; any other node\n * points at its place in the retained document.\n */\nfunction ownersByNode(\n nodes: readonly Node[],\n specification: DocumentModelSpecificationDefinition,\n index: number,\n): ReadonlyMap<object, Owner> {\n const typeIndex = new Map(\n specification.types.map((type, position) => [type.name, position]),\n );\n const firstDefinitions = new Set<string>();\n const owners = new Map<object, Owner>();\n nodes.forEach((node, nodeIndex) => {\n const name = node.name?.value;\n const position = name === undefined ? undefined : typeIndex.get(name);\n const first =\n name !== undefined &&\n NAMED_DEFINITION.test(node.kind) &&\n !firstDefinitions.has(name);\n if (first) firstDefinitions.add(name);\n const owner: Owner = {\n name,\n implements: (node.interfaces ?? []).map((entry) => entry.name.value),\n path:\n first && position !== undefined\n ? [\"specifications\", index, \"types\", position]\n : [\n \"specifications\",\n index,\n \"graphQLCompatibility\",\n \"document\",\n \"definitions\",\n nodeIndex,\n ],\n };\n const visit = (value: unknown): void => {\n if (value === null || typeof value !== \"object\") return;\n owners.set(value, owner);\n for (const child of Object.values(value)) visit(child);\n };\n visit(node);\n });\n return owners;\n}\n\n/**\n * The owner of an error's last node, except that an interface error belongs\n * to the type that implements another owner of the error, which graphql-js\n * may list before or after the interface's own nodes.\n */\nfunction ownerOf(\n error: GraphQLError,\n owners: ReadonlyMap<object, Owner>,\n): Owner | undefined {\n const candidates = (error.nodes ?? []).flatMap(\n (node) => owners.get(node) ?? [],\n );\n const names = new Set(candidates.map(({ name }) => name));\n return (\n candidates.findLast((owner) =>\n owner.implements.some((name) => names.has(name)),\n ) ?? candidates.at(-1)\n );\n}\n\nfunction checkArtifact(\n artifact: NormalizedDocumentModelArtifact,\n): readonly DefinitionDiagnostic[] {\n const served = servedSpecification(artifact);\n const retained = served?.specification.graphQLCompatibility;\n if (served === undefined || retained === undefined || retained === null) {\n return [];\n }\n const { specification, index } = served;\n const graphql = loadGraphQL();\n const nodes = retained.document.definitions as readonly Node[];\n const document = validationDocument(nodes, specification);\n let errors: readonly GraphQLError[] = graphql.validateSDL(\n document,\n undefined,\n sdlRules(graphql),\n );\n if (errors.length === 0) {\n errors = graphql\n .validateSchema(\n graphql.buildASTSchema(document, { assumeValidSDL: true }),\n )\n .filter(({ message }) => message !== NO_QUERY_ROOT);\n }\n const owners = ownersByNode(nodes, specification, index);\n return errors.map((error) => {\n const { code, repair } =\n ERROR_CODES.find(({ pattern }) => pattern.test(error.message)) ??\n OTHER_ERROR;\n return checkDiagnostics.create({\n code,\n source: artifact.source,\n definition: documentModelRef(artifact),\n path: ownerOf(error, owners)?.path ?? [\n \"specifications\",\n index,\n \"graphQLCompatibility\",\n ],\n message: error.message,\n repair,\n });\n });\n}\n\n/**\n * The compiler validates every type it declares. A retained GraphQL document\n * is the schema codegen and hosts build, so graphql-js validates it as they\n * would.\n */\nexport const graphqlSchemaCheck: DefinitionCheck = {\n name: \"graphql-schema\",\n run: ({ artifacts }) => artifacts.flatMap(checkArtifact),\n};\n","import type { DefinitionDiagnostic } from \"@powerhousedao/shared/document-model\";\nimport type { NormalizedDocumentModelArtifact } from \"../adapters/types.js\";\nimport type { DefinitionSourceSet } from \"../definition-source-types.js\";\nimport { toolingDiagnostics } from \"../diagnostic-codes.js\";\nimport { documentModelRef } from \"./served-specification.js\";\n\n/**\n * A host registers one module per `documentType@version`. The loader already\n * reports two selected sources that claim one, so a claimant is reported here\n * only when it or the anchor comes from outside the selection.\n */\nexport function logicalCollisionDiagnostics(\n sourceSet: DefinitionSourceSet,\n [anchor, ...claimants]: readonly NormalizedDocumentModelArtifact[],\n): readonly DefinitionDiagnostic[] {\n const selected = new Set(sourceSet.sources.map(({ specifier }) => specifier));\n const isSelected = (artifact: NormalizedDocumentModelArtifact) =>\n selected.has(artifact.source.specifier);\n const key = `${anchor.documentType}@${anchor.version}`;\n return claimants\n .filter((claimant) => !(isSelected(claimant) && isSelected(anchor)))\n .map((claimant) =>\n toolingDiagnostics.create({\n code: \"PH-PKG-LOGICAL-COLLISION\",\n source: claimant.source,\n definition: documentModelRef(claimant),\n path: [],\n message: `Two sources claim ${key}, and a host registers one module per document type and version.`,\n expected: `one source for ${key}`,\n received: `${anchor.source.specifier} and ${claimant.source.specifier}`,\n repair:\n \"Keep one of the two models, or give one of them another document type.\",\n related: [\n {\n source: anchor.source,\n path: [],\n message: `This source also claims ${key}.`,\n },\n ],\n }),\n );\n}\n","import type { NormalizedDocumentModelArtifact } from \"../../adapters/types.js\";\nimport { logicalCollisionDiagnostics } from \"../../report/logical-collisions.js\";\nimport type { DefinitionCheck } from \"../types.js\";\n\nexport const logicalCollisionsCheck: DefinitionCheck = {\n name: \"logical-collisions\",\n run: ({ sourceSet, artifacts }) => {\n const groups = new Map<string, NormalizedDocumentModelArtifact[]>();\n for (const artifact of artifacts) {\n const key = `${artifact.documentType}@${artifact.version}`;\n groups.set(key, [...(groups.get(key) ?? []), artifact]);\n }\n return [...groups.values()].flatMap((group) =>\n logicalCollisionDiagnostics(sourceSet, group),\n );\n },\n};\n","import type {\n DefinitionDiagnostic,\n DefinitionPath,\n DefinitionSource,\n Sha256Digest,\n} from \"@powerhousedao/shared/document-model\";\nimport { canonicalDigest } from \"../../../kernel/primitives.js\";\nimport { checkDiagnostics } from \"../diagnostic-codes.js\";\nimport { servedSpecification } from \"../../report/served-specification.js\";\nimport type { DefinitionCheck } from \"../types.js\";\n\ntype Use = {\n readonly digest: Sha256Digest;\n readonly source: DefinitionSource;\n readonly path: DefinitionPath;\n};\n\n/**\n * A host serves every model of a package and declares each scalar once, so\n * two package scalars that share a name but not a definition collide there.\n * The compiler sees one model at a time and cannot catch this.\n */\nexport const packageScalarNamesCheck: DefinitionCheck = {\n name: \"package-scalar-names\",\n run: ({ artifacts }) => {\n const first = new Map<string, Use>();\n const diagnostics: DefinitionDiagnostic[] = [];\n for (const artifact of artifacts) {\n const served = servedSpecification(artifact);\n if (served === undefined) continue;\n served.specification.scalars.forEach((scalar, scalarIndex) => {\n if (!(\"definition\" in scalar)) return;\n const use = {\n digest: canonicalDigest(scalar.definition),\n source: artifact.source,\n path: [\"specifications\", served.index, \"scalars\", scalarIndex],\n };\n const known = first.get(scalar.name);\n if (known === undefined) {\n first.set(scalar.name, use);\n return;\n }\n if (known.digest === use.digest) return;\n diagnostics.push(\n checkDiagnostics.create({\n code: \"PH-PKG-SCALAR-CONFLICT\",\n source: use.source,\n definition: { kind: \"scalar\", key: scalar.name },\n path: use.path,\n message: `Two different package scalars are named ${scalar.name}.`,\n expected: \"one definition per package scalar name\",\n received: scalar.name,\n repair: `Declare ${scalar.name} once with defineScalar in scalars/index.ts and import it everywhere it is used.`,\n related: [\n {\n source: known.source,\n path: known.path,\n message: `The other ${scalar.name} is used here.`,\n },\n ],\n }),\n );\n });\n }\n return diagnostics;\n },\n};\n","import type {\n InputTypeDefinition,\n NamedGraphQLTypeDefinition,\n TypeReferenceDefinition,\n} from \"@powerhousedao/shared/document-model\";\n\ntype SegmentOperation = {\n readonly key: string;\n readonly input: InputTypeDefinition | null;\n};\n\ntype StoredSegments = {\n readonly global: readonly NamedGraphQLTypeDefinition[];\n readonly local: readonly NamedGraphQLTypeDefinition[];\n readonly operations: ReadonlyMap<\n string,\n readonly NamedGraphQLTypeDefinition[]\n >;\n};\n\nfunction referencedNames(\n definition: NamedGraphQLTypeDefinition,\n): readonly string[] {\n const names: string[] = [];\n const visit = (reference: TypeReferenceDefinition): void => {\n if (reference.kind === \"list\") {\n visit(reference.item);\n return;\n }\n if (reference.kind === \"named\") names.push(reference.name);\n };\n switch (definition.kind) {\n case \"enum\":\n return names;\n case \"union\":\n return definition.members;\n case \"input\":\n definition.fields.forEach((field) => visit(field.type));\n return names;\n case \"object\":\n case \"interface\":\n names.push(...(definition.implements ?? []));\n for (const field of definition.fields) {\n field.args?.forEach((argument) => visit(argument.type));\n visit(field.type);\n }\n return names;\n }\n}\n\nfunction reachableFrom(\n rootName: string | null,\n index: ReadonlyMap<string, NamedGraphQLTypeDefinition>,\n): ReadonlySet<string> {\n const reached = new Set<string>();\n if (rootName === null) return reached;\n const queue = [rootName];\n while (queue.length > 0) {\n const name = queue.pop() as string;\n if (reached.has(name)) continue;\n const definition = index.get(name);\n if (definition === undefined) continue;\n reached.add(name);\n queue.push(...referencedNames(definition));\n }\n return reached;\n}\n\nexport function assignStoredSegments(input: {\n readonly types: readonly NamedGraphQLTypeDefinition[];\n readonly globalRoot: string;\n readonly localRoot: string | null;\n readonly operations: readonly SegmentOperation[];\n}): StoredSegments {\n const stateIndex = new Map(\n input.types.map((definition) => [definition.name, definition]),\n );\n const globalReach = reachableFrom(input.globalRoot, stateIndex);\n const localReach = reachableFrom(input.localRoot, stateIndex);\n\n const operationIndex = new Map(stateIndex);\n for (const operation of input.operations) {\n if (operation.input !== null) {\n operationIndex.set(operation.input.name, operation.input);\n }\n }\n\n const claimed = new Set<string>();\n const operations = new Map<string, readonly NamedGraphQLTypeDefinition[]>();\n for (const operation of input.operations) {\n if (operation.input === null) continue;\n claimed.add(operation.input.name);\n const reached = reachableFrom(operation.input.name, operationIndex);\n const supporting = input.types.filter(\n (definition) =>\n definition.kind === \"input\" &&\n reached.has(definition.name) &&\n !claimed.has(definition.name),\n );\n for (const definition of supporting) claimed.add(definition.name);\n operations.set(operation.key, [operation.input, ...supporting]);\n }\n\n const local = input.types.filter(\n (definition) =>\n definition.kind !== \"input\" &&\n localReach.has(definition.name) &&\n !globalReach.has(definition.name),\n );\n const localDeclared = new Set(local.map((definition) => definition.name));\n // An input no operation reaches stays global, because the host re-extracts\n // input definitions from the state schema (create-schema.ts).\n const global = input.types.filter(\n (definition) =>\n !localDeclared.has(definition.name) && !claimed.has(definition.name),\n );\n return { global, local, operations };\n}\n","import type {\n DirectiveUseDefinition,\n EnumValueDefinition,\n FieldDefinition,\n GraphQLConstValueNode,\n GraphQLDirectiveNode,\n GraphQLFieldDefinitionNode,\n GraphQLInputValueDefinitionNode,\n GraphQLStringValueNode,\n GraphQLTypeNode,\n InputFieldDefinition,\n JsonValue,\n LocationFreeGraphQLDocumentNode,\n NamedGraphQLTypeDefinition,\n TypeReferenceDefinition,\n} from \"@powerhousedao/shared/document-model\";\nimport { foldTypeExtensions } from \"../../kernel/graphql-ast.js\";\n\n/** graphql-js's reason for a bare `@deprecated`. */\nconst DEFAULT_DEPRECATION_REASON = \"No longer supported\";\n\nexport type GraphQLDefinitionNode =\n LocationFreeGraphQLDocumentNode[\"definitions\"][number];\n\ntype NamedDefinitionNode = Extract<\n GraphQLDefinitionNode,\n {\n readonly kind:\n | \"ObjectTypeDefinition\"\n | \"InterfaceTypeDefinition\"\n | \"InputObjectTypeDefinition\"\n | \"EnumTypeDefinition\"\n | \"UnionTypeDefinition\";\n }\n>;\n\nconst NAMED_TYPE_NODE =\n /^(?:Object|Interface|InputObject|Enum|Union)Type(?:Definition|Extension)$/;\n\nfunction description(node: GraphQLStringValueNode | undefined): string | null {\n return node === undefined ? null : node.value;\n}\n\nfunction constValue(node: GraphQLConstValueNode): JsonValue {\n switch (node.kind) {\n case \"IntValue\":\n case \"FloatValue\":\n return Number(node.value);\n case \"StringValue\":\n case \"EnumValue\":\n case \"BooleanValue\":\n return node.value;\n case \"NullValue\":\n return null;\n case \"ListValue\":\n return node.values.map(constValue);\n case \"ObjectValue\":\n return Object.fromEntries(\n node.fields.map((field) => [field.name.value, constValue(field.value)]),\n );\n }\n}\n\nfunction typeReference(\n node: GraphQLTypeNode,\n declared: ReadonlySet<string>,\n required = false,\n): TypeReferenceDefinition {\n switch (node.kind) {\n case \"NonNullType\":\n return typeReference(node.type, declared, true);\n case \"ListType\":\n return {\n kind: \"list\",\n required,\n item: typeReference(node.type, declared),\n };\n case \"NamedType\":\n return {\n kind: declared.has(node.name.value) ? \"named\" : \"scalar\",\n name: node.name.value,\n required,\n };\n }\n}\n\nfunction directives(nodes: readonly GraphQLDirectiveNode[]): {\n readonly deprecated: string | null;\n readonly uses?: readonly DirectiveUseDefinition[];\n} {\n const index = nodes.findIndex(\n (node) =>\n node.name.value === \"deprecated\" &&\n node.arguments.every(\n (argument) =>\n argument.name.value === \"reason\" &&\n argument.value.kind === \"StringValue\",\n ),\n );\n const reason = nodes[index]?.arguments[0]?.value as\n | GraphQLStringValueNode\n | undefined;\n const rest = nodes.filter((_, position) => position !== index);\n return {\n deprecated:\n index === -1 ? null : (reason?.value ?? DEFAULT_DEPRECATION_REASON),\n ...(rest.length > 0 && {\n uses: rest.map((node) => ({\n name: node.name.value,\n arguments: node.arguments.map((argument) => ({\n name: argument.name.value,\n value: constValue(argument.value),\n })),\n })),\n }),\n };\n}\n\nfunction inputField(\n node: GraphQLInputValueDefinitionNode,\n declared: ReadonlySet<string>,\n): InputFieldDefinition {\n const { deprecated, uses } = directives(node.directives);\n return {\n key: node.name.value,\n name: node.name.value,\n description: description(node.description),\n deprecated,\n type: typeReference(node.type, declared),\n ...(node.defaultValue !== undefined && {\n defaultValue: constValue(node.defaultValue),\n }),\n ...(uses !== undefined && { directives: uses }),\n };\n}\n\nfunction outputField(\n node: GraphQLFieldDefinitionNode,\n declared: ReadonlySet<string>,\n): FieldDefinition {\n const { deprecated, uses } = directives(node.directives);\n return {\n key: node.name.value,\n name: node.name.value,\n description: description(node.description),\n deprecated,\n ...(node.arguments.length > 0 && {\n args: node.arguments.map((argument) => inputField(argument, declared)),\n }),\n type: typeReference(node.type, declared),\n ...(uses !== undefined && { directives: uses }),\n };\n}\n\nfunction enumValue(\n node: Extract<\n GraphQLDefinitionNode,\n { kind: \"EnumTypeDefinition\" }\n >[\"values\"][number],\n): EnumValueDefinition {\n const { deprecated, uses } = directives(node.directives);\n return {\n name: node.name.value,\n description: description(node.description),\n deprecated,\n ...(uses !== undefined && { directives: uses }),\n };\n}\n\nfunction namedType(\n node: NamedDefinitionNode,\n declared: ReadonlySet<string>,\n): NamedGraphQLTypeDefinition {\n switch (node.kind) {\n case \"ObjectTypeDefinition\":\n case \"InterfaceTypeDefinition\":\n return {\n kind: node.kind === \"ObjectTypeDefinition\" ? \"object\" : \"interface\",\n name: node.name.value,\n description: description(node.description),\n ...(node.interfaces.length > 0 && {\n implements: node.interfaces.map((entry) => entry.name.value),\n }),\n fields: node.fields.map((field) => outputField(field, declared)),\n };\n case \"InputObjectTypeDefinition\":\n return {\n kind: \"input\",\n name: node.name.value,\n description: description(node.description),\n unknownKeys: \"preserve\",\n fields: node.fields.map((field) => inputField(field, declared)),\n };\n case \"EnumTypeDefinition\":\n return {\n kind: \"enum\",\n name: node.name.value,\n description: description(node.description),\n values: node.values.map(enumValue),\n };\n case \"UnionTypeDefinition\":\n return {\n kind: \"union\",\n name: node.name.value,\n description: description(node.description),\n members: node.types.map((member) => member.name.value),\n };\n }\n}\n\n/** Names of the object, interface, input, enum and union types the nodes define or extend. */\nexport function declaredTypeNames(\n definitions: readonly GraphQLDefinitionNode[],\n): ReadonlySet<string> {\n const declared = new Set<string>();\n for (const node of definitions) {\n if (NAMED_TYPE_NODE.test(node.kind) && \"name\" in node) {\n declared.add(node.name.value);\n }\n }\n return declared;\n}\n\n/**\n * Every object, interface, input, enum and union type the nodes define or\n * extend, with each extension folded into its type: defined types in\n * document order, then types the nodes only extend. A repeated definition or\n * member keeps its first occurrence; graphql-js validation reports the\n * repeat. A reference to a name in `declared` is a named type; any other\n * reference is a scalar.\n */\nexport function structuredTypes(\n definitions: readonly GraphQLDefinitionNode[],\n declared: ReadonlySet<string> = declaredTypeNames(definitions),\n): readonly NamedGraphQLTypeDefinition[] {\n // A folded node is its first definition or extension with the member\n // nodes of every extension appended, under the definition's kind.\n return [...foldTypeExtensions(definitions, []).types.values()].map(\n ({ node }) => namedType(node as unknown as NamedDefinitionNode, declared),\n );\n}\n\nfunction namedTypeName(node: GraphQLTypeNode): string {\n return node.kind === \"NamedType\" ? node.name.value : namedTypeName(node.type);\n}\n\n/**\n * The type name every field and field argument of the nodes refers to,\n * extensions included, in document order and with repeats.\n */\nexport function referencedTypeNames(\n definitions: readonly GraphQLDefinitionNode[],\n): readonly string[] {\n const names: string[] = [];\n for (const node of definitions) {\n if (!(\"fields\" in node)) continue;\n for (const field of node.fields) {\n names.push(namedTypeName(field.type));\n for (const argument of \"arguments\" in field ? field.arguments : []) {\n names.push(namedTypeName(argument.type));\n }\n }\n }\n return names;\n}\n","import type {\n DefinitionDiagnostic,\n DefinitionPath,\n} from \"@powerhousedao/shared/document-model\";\nimport {\n rejectionReceived,\n snapshotArray,\n snapshotRecord,\n} from \"../../kernel/data-properties.js\";\nimport { describeReceived } from \"../../kernel/diagnostics.js\";\nimport type { NormalizedDocumentModelArtifact } from \"../adapters/types.js\";\nimport { checkDiagnostics } from \"./diagnostic-codes.js\";\nimport { documentModelRef } from \"../report/served-specification.js\";\n\ntype Scope = \"global\" | \"local\";\n\n/** A stored SDL string, where it sits in the source, and what it describes. */\nexport type StoredSchemaSegment = {\n readonly path: DefinitionPath;\n readonly schema: string;\n readonly of:\n | { readonly scope: Scope }\n | { readonly module: number; readonly operation: number };\n};\n\n/** The stored strings of the specification an artifact serves. */\nexport type ServedStoredSpecification = {\n readonly path: DefinitionPath;\n readonly initialValues: Readonly<Record<Scope, string>>;\n /** In the order the stored model lists them: global, local, then operations. */\n readonly segments: readonly StoredSchemaSegment[];\n};\n\ntype StoredHistory = {\n readonly path: DefinitionPath;\n readonly versions: readonly number[];\n /** Undefined when the stored history has no specification for the served version. */\n readonly served: ServedStoredSpecification | undefined;\n};\n\nexport type StoredModelRead =\n | ({ readonly ok: true } & StoredHistory)\n | { readonly ok: false; readonly diagnostic: DefinitionDiagnostic };\n\ntype Read<T> =\n | { readonly ok: true; readonly value: T }\n | {\n readonly ok: false;\n readonly path: DefinitionPath;\n readonly expected: string;\n readonly received: string;\n };\n\nfunction record(\n value: unknown,\n path: DefinitionPath,\n): Read<{ readonly [key: string]: unknown }> {\n const snapshot = snapshotRecord(value, undefined, path);\n return snapshot.ok\n ? snapshot\n : {\n ok: false,\n path: snapshot.path,\n expected: \"a plain record\",\n received: rejectionReceived(snapshot),\n };\n}\n\nfunction array(value: unknown, path: DefinitionPath): Read<readonly unknown[]> {\n const snapshot = snapshotArray(value, path);\n return snapshot.ok\n ? snapshot\n : {\n ok: false,\n path: snapshot.path,\n expected: \"an array\",\n received: rejectionReceived(snapshot),\n };\n}\n\nfunction text(value: unknown, path: DefinitionPath): Read<string> {\n return typeof value === \"string\"\n ? { ok: true, value }\n : {\n ok: false,\n path,\n expected: \"a string\",\n received: describeReceived(value),\n };\n}\n\nfunction readServedStoredSpecification(\n value: unknown,\n path: DefinitionPath,\n): Read<ServedStoredSpecification> {\n const specification = record(value, path);\n if (!specification.ok) return specification;\n const state = record(specification.value.state, [...path, \"state\"]);\n if (!state.ok) return state;\n const initialValues: Partial<Record<Scope, string>> = {};\n const segments: StoredSchemaSegment[] = [];\n for (const scope of [\"global\", \"local\"] as const) {\n const at = [...path, \"state\", scope];\n const stored = record(state.value[scope], at);\n if (!stored.ok) return stored;\n const schema = text(stored.value.schema, [...at, \"schema\"]);\n if (!schema.ok) return schema;\n const initialValue = text(stored.value.initialValue, [\n ...at,\n \"initialValue\",\n ]);\n if (!initialValue.ok) return initialValue;\n initialValues[scope] = initialValue.value;\n segments.push({\n path: [...at, \"schema\"],\n schema: schema.value,\n of: { scope },\n });\n }\n const modules = array(specification.value.modules, [...path, \"modules\"]);\n if (!modules.ok) return modules;\n for (const [moduleIndex, entry] of modules.value.entries()) {\n const at = [...path, \"modules\", moduleIndex];\n const module = record(entry, at);\n if (!module.ok) return module;\n const operations = array(module.value.operations, [...at, \"operations\"]);\n if (!operations.ok) return operations;\n for (const [operationIndex, member] of operations.value.entries()) {\n const operationPath = [...at, \"operations\", operationIndex];\n const operation = record(member, operationPath);\n if (!operation.ok) return operation;\n if (operation.value.schema === null) continue;\n const schema = text(operation.value.schema, [...operationPath, \"schema\"]);\n if (!schema.ok) return schema;\n segments.push({\n path: [...operationPath, \"schema\"],\n schema: schema.value,\n of: { module: moduleIndex, operation: operationIndex },\n });\n }\n }\n return {\n ok: true,\n value: {\n path,\n initialValues: initialValues as Record<Scope, string>,\n segments,\n },\n };\n}\n\nfunction storedHistory(\n artifact: NormalizedDocumentModelArtifact,\n): Read<StoredHistory> {\n const documentModel = record(artifact.documentModel, [\"documentModel\"]);\n const global = documentModel.ok\n ? record(documentModel.value.global, [\"documentModel\", \"global\"])\n : documentModel;\n if (!global.ok) return global;\n const path = [\"documentModel\", \"global\", \"specifications\"];\n const specifications = array(global.value.specifications, path);\n if (!specifications.ok) return specifications;\n const versions: number[] = [];\n let served: unknown;\n let servedIndex = -1;\n for (const [index, entry] of specifications.value.entries()) {\n const specification = record(entry, [...path, index]);\n if (!specification.ok) return specification;\n const { version } = specification.value;\n if (typeof version !== \"number\") {\n return {\n ok: false,\n path: [...path, index, \"version\"],\n expected: \"a version number\",\n received: describeReceived(version),\n };\n }\n versions.push(version);\n if (version === artifact.version && servedIndex === -1) {\n served = entry;\n servedIndex = index;\n }\n }\n if (servedIndex === -1) {\n return { ok: true, value: { path, versions, served: undefined } };\n }\n const specification = readServedStoredSpecification(served, [\n ...path,\n servedIndex,\n ]);\n return specification.ok\n ? { ok: true, value: { path, versions, served: specification.value } }\n : specification;\n}\n\n/**\n * Reads the stored model an artifact serves without trusting its shape: a\n * module assembled by hand can carry anything there. Every check that reads\n * stored strings goes through this, so each reports one malformed member the\n * same way and the report keeps it once.\n */\nexport function readStoredModel(\n artifact: NormalizedDocumentModelArtifact,\n): StoredModelRead {\n const read = storedHistory(artifact);\n if (read.ok) return { ok: true, ...read.value };\n return {\n ok: false,\n diagnostic: checkDiagnostics.create({\n code: \"PH-DM-DECLARATION-INVALID\",\n source: artifact.source,\n definition: documentModelRef(artifact),\n path: read.path,\n message:\n \"The stored document model this source serves is malformed, so hosts and codegen cannot read it.\",\n expected: read.expected,\n received: read.received,\n repair:\n \"Export the module materialize returned, or save the model again from the document model editor; the stored model is not edited by hand.\",\n }),\n };\n}\n","import type {\n DefinitionDiagnostic,\n DefinitionPath,\n NamedGraphQLTypeDefinition,\n} from \"@powerhousedao/shared/document-model\";\nimport { assignStoredSegments } from \"../../../compiler/segments.js\";\nimport {\n canonicalJson,\n compareCodeUnits,\n EMPTY_INPUT_FIELD_NAME,\n} from \"../../../kernel/primitives.js\";\nimport type { NormalizedDocumentModelArtifact } from \"../../adapters/types.js\";\nimport {\n declaredTypeNames,\n type GraphQLDefinitionNode,\n structuredTypes,\n} from \"../../graphql/ast-to-structured.js\";\nimport { parseSchema } from \"../../graphql/parse-schema.js\";\nimport { checkDiagnostics } from \"../diagnostic-codes.js\";\nimport {\n documentModelRef,\n servedSpecification,\n} from \"../../report/served-specification.js\";\nimport { readStoredModel } from \"../stored-specification.js\";\nimport type { DefinitionCheck } from \"../types.js\";\n\ntype Segment = {\n readonly path: DefinitionPath;\n readonly stored: string;\n /** What the canonical printer puts in this segment. */\n readonly printed: readonly NamedGraphQLTypeDefinition[];\n};\n\ntype Report = (\n path: DefinitionPath,\n message: string,\n expected: string,\n received: string,\n) => void;\n\n/**\n * SDL cannot spell an input without fields, a field key apart from its name,\n * or a member order that means nothing, so those are not compared.\n */\nfunction comparable(type: NamedGraphQLTypeDefinition): string {\n if (type.kind === \"enum\") return canonicalJson(type);\n if (type.kind === \"union\") {\n return canonicalJson({\n ...type,\n members: [...type.members].sort(compareCodeUnits),\n });\n }\n const fields = type.fields.map((field) => {\n const { key: _key, ...rest } = field;\n return \"args\" in field && field.args !== undefined\n ? {\n ...rest,\n args: field.args.map(({ key: _argKey, ...arg }) => arg),\n }\n : rest;\n });\n const [only] = fields;\n const emptyMarker =\n type.kind === \"input\" &&\n fields.length === 1 &&\n only.name === EMPTY_INPUT_FIELD_NAME &&\n only.type.kind === \"scalar\" &&\n only.type.name === \"Boolean\" &&\n !only.type.required;\n return canonicalJson({\n ...type,\n ...(\"implements\" in type &&\n type.implements !== undefined && {\n implements: [...type.implements].sort(compareCodeUnits),\n }),\n fields: emptyMarker ? [] : fields,\n });\n}\n\nfunction differs(\n stored: NamedGraphQLTypeDefinition,\n declared: NamedGraphQLTypeDefinition,\n): boolean {\n return comparable(stored) !== comparable(declared);\n}\n\n/** The canonical printer owns each segment, so every segment holds exactly its printed types. */\nfunction compareCanonical(\n report: Report,\n segment: Segment,\n stored: readonly NamedGraphQLTypeDefinition[],\n): void {\n const expected = segment.printed.map(({ name }) => name);\n const received = stored.map(({ name }) => name);\n const missing = expected.find((name) => !received.includes(name));\n const surplus = received.find((name) => !expected.includes(name));\n if (missing !== undefined || surplus !== undefined) {\n report(\n segment.path,\n missing !== undefined\n ? `The stored schema segment does not declare ${missing}.`\n : `The stored schema segment declares ${surplus}, which the definition places elsewhere or not at all.`,\n expected.join(\", \"),\n received.join(\", \"),\n );\n return;\n }\n for (const declared of segment.printed) {\n const copy = stored.find(({ name }) => name === declared.name);\n if (copy === undefined || !differs(copy, declared)) continue;\n report(\n [...segment.path, declared.name],\n `The stored schema segment describes ${declared.name} differently than the definition.`,\n canonicalJson(declared),\n canonicalJson(copy),\n );\n }\n}\n\ntype ParsedSegment = {\n readonly segment: Segment;\n readonly definitions: readonly GraphQLDefinitionNode[];\n};\n\n/**\n * A schema-first model keeps its own split, and a segment may extend a type\n * another declares, so the union of segments is folded and compared.\n */\nfunction compareExplicit(\n report: Report,\n path: DefinitionPath,\n segments: readonly ParsedSegment[],\n declaration: ReadonlyMap<string, NamedGraphQLTypeDefinition>,\n): void {\n const types = structuredTypes(\n segments.flatMap(({ definitions }) => definitions),\n new Set(declaration.keys()),\n );\n const segmentOf = (name: string): DefinitionPath =>\n segments.find(({ definitions }) => declaredTypeNames(definitions).has(name))\n ?.segment.path ?? path;\n const seen = new Set<string>();\n for (const type of types) {\n seen.add(type.name);\n const declared = declaration.get(type.name);\n if (declared === undefined) {\n report(\n segmentOf(type.name),\n `The stored schema segment declares ${type.name}, which the definition does not describe.`,\n [...declaration.keys()].join(\", \"),\n type.name,\n );\n } else if (differs(type, declared)) {\n report(\n [...segmentOf(type.name), type.name],\n `The stored schema segment describes ${type.name} differently than the definition.`,\n canonicalJson(declared),\n canonicalJson(type),\n );\n }\n }\n for (const name of declaration.keys()) {\n if (seen.has(name)) continue;\n report(\n path,\n `No stored schema segment declares ${name}.`,\n name,\n [...seen].join(\", \"),\n );\n }\n}\n\nfunction checkArtifact(\n artifact: NormalizedDocumentModelArtifact,\n): readonly DefinitionDiagnostic[] {\n const served = servedSpecification(artifact);\n if (served === undefined) return [];\n const { specification, index } = served;\n const at: DefinitionPath = [\"specifications\", index];\n const diagnostics: DefinitionDiagnostic[] = [];\n const report: Report = (path, message, expected, received) =>\n diagnostics.push(\n checkDiagnostics.create({\n code: \"PH-DEF-COMPATIBILITY-INVALID\",\n source: artifact.source,\n definition: documentModelRef(artifact),\n path,\n message,\n expected,\n received,\n repair:\n \"Export the module materialize returned, or save the model again from the document model editor; a stored string that describes another structure is a definition error.\",\n }),\n );\n\n const operations = specification.modules.flatMap((module) =>\n module.operations.map((operation) => ({\n key: `${module.key}/${operation.key}`,\n input: operation.input,\n })),\n );\n const printed = assignStoredSegments({\n types: specification.types,\n globalRoot: specification.state.global.root.name,\n localRoot: specification.state.local.root?.name ?? null,\n operations,\n });\n const declaration = new Map<string, NamedGraphQLTypeDefinition>(\n [\n ...specification.types,\n ...operations.flatMap(({ input }) => (input === null ? [] : [input])),\n ].map((type) => [type.name, type]),\n );\n const stored = readStoredModel(artifact);\n if (!stored.ok) diagnostics.push(stored.diagnostic);\n const storedSpecification = stored.ok ? stored.served : undefined;\n const canonical =\n artifact.definition.compatibility.serialization === \"canonical-v1\";\n\n // The materializer writes every operation's segment; a schema-first\n // operation without an input may store none.\n const missing = new Map<string, string>();\n specification.modules.forEach((module, moduleIndex) =>\n module.operations.forEach((operation, operationIndex) => {\n if (canonical || operation.input !== null) {\n missing.set(\n `${moduleIndex}/${operationIndex}`,\n `${module.key}.${operation.key}`,\n );\n }\n }),\n );\n const segments: Segment[] = [];\n for (const { path, schema, of } of storedSpecification?.segments ?? []) {\n if (\"scope\" in of) {\n segments.push({ path, stored: schema, printed: printed[of.scope] });\n continue;\n }\n const module = specification.modules.at(of.module);\n const operation = module?.operations.at(of.operation);\n if (module === undefined || operation === undefined) {\n report(\n path,\n \"The stored schema segment belongs to an operation the definition does not declare.\",\n \"a segment of a declared operation\",\n schema,\n );\n continue;\n }\n missing.delete(`${of.module}/${of.operation}`);\n segments.push({\n path,\n stored: schema,\n printed:\n printed.operations.get(`${module.key}/${operation.key}`) ??\n (operation.input === null ? [] : [operation.input]),\n });\n }\n if (storedSpecification !== undefined) {\n for (const operation of missing.values()) {\n report(\n storedSpecification.path,\n `The stored model has no schema segment for operation ${operation}.`,\n `a schema segment for ${operation}`,\n \"absent\",\n );\n }\n }\n\n const parsed = segments.flatMap((segment): ParsedSegment[] => {\n const result = parseSchema(segment.stored);\n if (result.ok) {\n return [{ segment, definitions: result.document.definitions }];\n }\n report(\n segment.path,\n `The stored schema segment is not GraphQL SDL: ${result.message}`,\n \"GraphQL SDL\",\n segment.stored,\n );\n return [];\n });\n if (canonical) {\n const declared = new Set(declaration.keys());\n for (const { segment, definitions } of parsed) {\n compareCanonical(report, segment, structuredTypes(definitions, declared));\n }\n } else if (\n storedSpecification !== undefined &&\n parsed.length === segments.length\n ) {\n compareExplicit(report, storedSpecification.path, parsed, declaration);\n }\n\n for (const scope of [\"global\", \"local\"] as const) {\n const state = specification.state[scope];\n const text = state.materialized.initialValue;\n if (text.trim() === \"\") continue;\n let value: unknown;\n try {\n value = JSON.parse(text);\n } catch {\n value = undefined;\n }\n const received = value === undefined ? text : canonicalJson(value);\n if (received === canonicalJson(state.initialValue)) continue;\n report(\n [...at, \"state\", scope, \"initialValue\"],\n `The stored ${scope} initial value describes a different value than the definition.`,\n canonicalJson(state.initialValue),\n received,\n );\n }\n return diagnostics;\n}\n\n/**\n * Hosts and codegen read the stored SDL strings; the definition carries the\n * structure. Every segment is checked: for a canonical model the strings are\n * the printer's output, so a mismatch is a forged module or a compiler defect.\n */\nexport const retainedSerializationCheck: DefinitionCheck = {\n name: \"retained-serialization\",\n run: ({ artifacts }) => artifacts.flatMap(checkArtifact),\n};\n","import type { DefinitionDiagnostic } from \"@powerhousedao/shared/document-model\";\nimport { canonicalJson } from \"../../../kernel/primitives.js\";\nimport { checkDiagnostics } from \"../diagnostic-codes.js\";\nimport {\n documentModelRef,\n servedSpecification,\n} from \"../../report/served-specification.js\";\nimport { readStoredModel } from \"../stored-specification.js\";\nimport type { DefinitionCheck } from \"../types.js\";\n\n/**\n * Hosts read the stored model; consumers of the definition read the\n * structure. A module assembled by hand can make the two disagree.\n */\nexport const storedMaterializationCheck: DefinitionCheck = {\n name: \"stored-materialization\",\n run: ({ artifacts }) =>\n artifacts.flatMap((artifact): DefinitionDiagnostic[] => {\n const stored = readStoredModel(artifact);\n if (!stored.ok) return [stored.diagnostic];\n const storedVersions = canonicalJson(stored.versions);\n const declaredVersions = canonicalJson(\n artifact.definition.specifications.map(({ version }) => version),\n );\n const at = {\n source: artifact.source,\n definition: documentModelRef(artifact),\n };\n if (storedVersions !== declaredVersions) {\n return [\n checkDiagnostics.create({\n ...at,\n code: \"PH-DM-DECLARATION-INVALID\",\n path: stored.path,\n message:\n \"The stored specification history and the structured definition cover different versions.\",\n expected: declaredVersions,\n received: storedVersions,\n repair:\n \"Export the module materialize returned; do not assemble the stored model or its definition by hand.\",\n }),\n ];\n }\n const served = servedSpecification(artifact);\n if (served === undefined || stored.served === undefined) return [];\n const { path, initialValues } = stored.served;\n return ([\"global\", \"local\"] as const).flatMap((scope) => {\n const expected =\n served.specification.state[scope].materialized.initialValue;\n const received = initialValues[scope];\n if (received === expected) return [];\n return [\n checkDiagnostics.create({\n ...at,\n code: \"PH-DM-INITIAL-VALUE-INVALID\",\n path: [...path, \"state\", scope, \"initialValue\"],\n message: `The stored ${scope} initial value is not the one the definition materializes.`,\n expected,\n received,\n repair:\n \"Export the module materialize returned; a stored initial value is not an independent setting.\",\n }),\n ];\n });\n }),\n};\n","import { checkDiagnostics } from \"../diagnostic-codes.js\";\nimport type { DefinitionCheck } from \"../types.js\";\n\n/** Turns each declaration the project scan found unregistered into one diagnostic. */\nexport const unregisteredDefinitionsCheck: DefinitionCheck = {\n name: \"unregistered-definitions\",\n run: ({ unregistered }) =>\n unregistered.map(({ unit, specifier }) => {\n const entry = `{ \"specifier\": \"${specifier}\" }`;\n return checkDiagnostics.create({\n code: \"PH-PKG-DEFINITION-UNREGISTERED\",\n source: { specifier },\n path: [],\n message: `${unit} declares a code-first document model that no definitionSources entry reaches, so the package leaves it out.`,\n expected: `a definitionSources entry that reaches ${specifier}`,\n received: \"no entry\",\n repair: `Add ${entry} to definitionSources.entries in powerhouse.config.json. If definitionSources is absent or schema-first, set it to { \"formatVersion\": 1, \"mode\": \"code-first\", \"entries\": [${entry}] }; schema-first models keep generating from their stored files.`,\n });\n }),\n};\n","import type {\n DefinitionCheckProfile,\n DefinitionCheckReport,\n DefinitionCheckSkipReason,\n DefinitionDiagnostic,\n} from \"@powerhousedao/shared/document-model\";\nimport { compareDefinitionDiagnostics } from \"../../kernel/diagnostics.js\";\nimport { canonicalJson, compareCodeUnits } from \"../../kernel/primitives.js\";\nimport type { NormalizedDocumentModelArtifact } from \"../adapters/types.js\";\nimport type { DefinitionSourceSet } from \"../definition-source-types.js\";\n\nexport type DefinitionStatus = DefinitionCheckReport[\"status\"];\n\n/** These phases mean the tool could not read the package, not that a model is wrong. */\nconst FAILURE_PHASES: ReadonlySet<string> = new Set([\n \"configuration\",\n \"import\",\n]);\n\n/** Drops exact repeats and orders the rest independently of input order. */\nexport function sortedUniqueDiagnostics(\n diagnostics: readonly DefinitionDiagnostic[],\n): readonly DefinitionDiagnostic[] {\n const unique = new Map<string, DefinitionDiagnostic>();\n for (const diagnostic of diagnostics) {\n unique.set(canonicalJson(diagnostic), diagnostic);\n }\n return [...unique]\n .sort(\n ([leftKey, left], [rightKey, right]) =>\n compareDefinitionDiagnostics(left, right) ||\n compareCodeUnits(leftKey, rightKey),\n )\n .map(([, diagnostic]) => diagnostic);\n}\n\nexport function definitionStatus(input: {\n readonly skipReason?: DefinitionCheckSkipReason;\n readonly definitions: readonly unknown[];\n readonly diagnostics: readonly DefinitionDiagnostic[];\n}): DefinitionStatus {\n const errors = input.diagnostics.filter(\n ({ severity }) => severity === \"error\",\n );\n if (errors.some(({ phase }) => FAILURE_PHASES.has(phase))) return \"failed\";\n if (errors.length > 0) return \"invalid\";\n if (\n input.skipReason !== undefined &&\n input.definitions.length === 0 &&\n input.diagnostics.length === 0\n ) {\n return \"skipped\";\n }\n return \"ok\";\n}\n\nexport function compareArtifacts(\n left: NormalizedDocumentModelArtifact,\n right: NormalizedDocumentModelArtifact,\n): number {\n return (\n compareCodeUnits(left.documentType, right.documentType) ||\n left.version - right.version ||\n compareCodeUnits(left.source.specifier, right.source.specifier) ||\n compareCodeUnits(\n canonicalJson(left.source.exportPath ?? []),\n canonicalJson(right.source.exportPath ?? []),\n )\n );\n}\n\ntype InventoryEntry = DefinitionCheckReport[\"definitions\"][number];\n\n/** The artifact order, extended to every kind of inventory entry. */\nfunction compareInventoryEntries(\n left: InventoryEntry,\n right: InventoryEntry,\n): number {\n return (\n compareCodeUnits(left.key, right.key) ||\n (left.version ?? 0) - (right.version ?? 0) ||\n compareCodeUnits(left.source.specifier, right.source.specifier) ||\n compareCodeUnits(\n canonicalJson(left.source.exportPath ?? []),\n canonicalJson(right.source.exportPath ?? []),\n ) ||\n compareCodeUnits(left.kind, right.kind)\n );\n}\n\n/** Builds the stored check report. */\nexport function definitionCheckReport(input: {\n readonly profile: DefinitionCheckProfile;\n readonly sourceSet: DefinitionSourceSet;\n readonly skipReason?: DefinitionCheckSkipReason;\n readonly artifacts: readonly NormalizedDocumentModelArtifact[];\n /** Inventory entries besides the artifacts. */\n readonly definitions: readonly InventoryEntry[];\n readonly diagnostics: readonly DefinitionDiagnostic[];\n}): DefinitionCheckReport {\n const diagnostics = sortedUniqueDiagnostics(input.diagnostics);\n const definitions = [\n ...input.artifacts.map((artifact): InventoryEntry => ({\n kind: \"document-model\",\n key: artifact.documentType,\n version: artifact.version,\n digest: artifact.digest,\n source: artifact.source,\n })),\n ...input.definitions,\n ].sort(compareInventoryEntries);\n const status = definitionStatus({\n ...(input.skipReason !== undefined && { skipReason: input.skipReason }),\n definitions,\n diagnostics,\n });\n const errors = diagnostics.filter(\n ({ severity }) => severity === \"error\",\n ).length;\n const common = {\n kind: \"powerhouse.definition-check\",\n formatVersion: 1,\n profile: input.profile,\n sourceSet: input.sourceSet,\n definitions,\n diagnostics,\n summary: { errors, warnings: diagnostics.length - errors },\n } as const;\n if (status === \"skipped\") {\n // definitionStatus answers skipped only when a skip reason is present.\n return {\n ...common,\n status,\n skipReason: input.skipReason as DefinitionCheckSkipReason,\n };\n }\n return { ...common, status };\n}\n","import type {\n DefinitionCheckProfile,\n DefinitionCheckReport,\n DefinitionDiagnostic,\n DefinitionPath,\n DefinitionSource,\n} from \"@powerhousedao/shared/document-model\";\nimport type { DefinitionRelocation } from \"../adapters/producer.js\";\nimport { duplicateIdentitiesCheck } from \"./checks/duplicate-identities.js\";\nimport { graphqlSchemaCheck } from \"./checks/graphql-schema.js\";\nimport { logicalCollisionsCheck } from \"./checks/logical-collisions.js\";\nimport { packageScalarNamesCheck } from \"./checks/package-scalar-names.js\";\nimport { retainedSerializationCheck } from \"./checks/retained-serialization.js\";\nimport { storedMaterializationCheck } from \"./checks/stored-materialization.js\";\nimport { unregisteredDefinitionsCheck } from \"./checks/unregistered-definitions.js\";\nimport { definitionCheckReport } from \"../report/status.js\";\nimport type {\n DefinitionCheckInput,\n LoadedDefinitionProject,\n} from \"../report/types.js\";\nimport type { DefinitionCheck } from \"./types.js\";\n\n/**\n * @experimental The checks `ph model check` runs on document models. A later\n * layer, such as ph-cli's release profile, adds its own with\n * `[...documentModelChecks, ...theirs]`.\n */\nexport const documentModelChecks: readonly DefinitionCheck[] = Object.freeze([\n storedMaterializationCheck,\n duplicateIdentitiesCheck,\n packageScalarNamesCheck,\n logicalCollisionsCheck,\n graphqlSchemaCheck,\n retainedSerializationCheck,\n unregisteredDefinitionsCheck,\n]);\n\n/** Moves a check's normalized paths to where each source's author edits them. */\nfunction relocated(\n diagnostic: DefinitionDiagnostic,\n relocations: ReadonlyMap<string, DefinitionRelocation>,\n): DefinitionDiagnostic {\n const at = (source: DefinitionSource | undefined, path: DefinitionPath) =>\n (source === undefined ? undefined : relocations.get(source.specifier))?.(\n path,\n ) ?? path;\n return {\n ...diagnostic,\n path: at(diagnostic.source, diagnostic.path),\n ...(diagnostic.related !== undefined && {\n related: diagnostic.related.map((location) => ({\n ...location,\n path: at(location.source, location.path),\n })),\n }),\n };\n}\n\n/**\n * @experimental Runs every check over a loaded project and builds the stored\n * check report with the project's load diagnostics. `definitions` adds\n * inventory entries a caller checked itself; `profile` (default `edit`) names\n * the check list the caller ran. Experimental while code-first projects are\n * introduced.\n */\nexport async function checkProjectDefinitions<\n TInput extends DefinitionCheckInput = DefinitionCheckInput,\n>(\n project: LoadedDefinitionProject & TInput,\n options: {\n readonly checks?: readonly DefinitionCheck<TInput>[];\n readonly definitions?: DefinitionCheckReport[\"definitions\"];\n readonly profile?: DefinitionCheckProfile;\n } = {},\n): Promise<DefinitionCheckReport> {\n const relocations = project.relocations ?? new Map();\n const diagnostics = [...project.diagnostics];\n for (const check of options.checks ?? documentModelChecks) {\n for (const diagnostic of await check.run(project)) {\n diagnostics.push(relocated(diagnostic, relocations));\n }\n }\n return definitionCheckReport({\n profile: options.profile ?? \"edit\",\n sourceSet: project.sourceSet,\n ...(project.skipReason !== undefined && {\n skipReason: project.skipReason,\n }),\n artifacts: project.artifacts,\n definitions: options.definitions ?? [],\n diagnostics,\n });\n}\n","import { defineDiagnosticCatalog } from \"../../kernel/diagnostics.js\";\nimport { toolingDiagnostics } from \"../diagnostic-codes.js\";\n\nexport const releaseDiagnostics = defineDiagnosticCatalog(\n {\n \"PH-REL-HOST-SCALAR-UNBOUND\": {\n severity: \"error\",\n phase: \"package\",\n meaning:\n \"A model declares a package scalar the package registers no binding for, so a host serves it without validation\",\n },\n \"PH-REL-HOST-SCALAR-MISMATCH\": {\n severity: \"error\",\n phase: \"package\",\n meaning:\n \"A model declares a package scalar whose stored metadata differs from the binding the package registers\",\n },\n \"PH-REL-HOST-DEFINITION-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"A module's definition fails the wire shape, so a host serves the model from its stored SDL\",\n },\n \"PH-REL-HOST-DEFINITION-MISMATCH\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"A module's definition does not serve that module's document type or version, so a host serves the model from its stored SDL\",\n },\n \"PH-REL-HOST-VALIDATION-INCOMPLETE\": {\n severity: \"error\",\n // Not a defect of the package: the release check could not run, which\n // the report states as failed, not invalid.\n phase: \"import\",\n meaning:\n \"Host validation did not run, so the release check cannot tell whether a host serves the package as declared\",\n },\n },\n toolingDiagnostics,\n);\n","import type {\n DefinitionDiagnostic,\n DefinitionPath,\n DefinitionRelatedLocation,\n DefinitionSource,\n} from \"@powerhousedao/shared/document-model\";\nimport type { NormalizedDocumentModelArtifact } from \"../../adapters/types.js\";\nimport type { DefinitionCheck } from \"../../check/types.js\";\nimport {\n documentModelRef,\n servedSpecification,\n} from \"../../report/served-specification.js\";\nimport { releaseDiagnostics } from \"../diagnostic-codes.js\";\nimport type { HostValidationFindingData, ReleaseCheckInput } from \"../types.js\";\n\ntype Site = {\n readonly artifact: NormalizedDocumentModelArtifact;\n readonly path: DefinitionPath;\n};\n\n/**\n * Where an author edits what a finding names. A host finding names a document\n * type, not a version, so it points at every artifact of that type; a scalar\n * finding narrows that to the served specifications that declare the scalar.\n */\nfunction findingSites(\n artifacts: readonly NormalizedDocumentModelArtifact[],\n finding: HostValidationFindingData,\n): readonly Site[] {\n const ofType = artifacts.filter(\n ({ documentType }) => documentType === finding.documentType,\n );\n if (\"scalar\" in finding) {\n const declaring = ofType.flatMap((artifact): Site[] => {\n const served = servedSpecification(artifact);\n const index =\n served?.specification.scalars.findIndex(\n ({ name }) => name === finding.scalar,\n ) ?? -1;\n return served === undefined || index === -1\n ? []\n : [\n {\n artifact,\n path: [\"specifications\", served.index, \"scalars\", index],\n },\n ];\n });\n if (declaring.length > 0) return declaring;\n }\n return ofType.map((artifact) => ({ artifact, path: [] }));\n}\n\n/** The first site carries the diagnostic; the others are related locations. */\nfunction attribution(\n sites: readonly Site[],\n finding: HostValidationFindingData,\n alsoHere: string,\n): {\n readonly source?: DefinitionSource;\n readonly path: DefinitionPath;\n readonly related: readonly DefinitionRelatedLocation[];\n} {\n if (sites.length === 0) return { path: [], related: [] };\n const [first, ...others] = sites;\n return {\n source: first.artifact.source,\n path: first.path,\n related: others.map(({ artifact, path }) => ({\n source: artifact.source,\n path,\n message: alsoHere,\n })),\n };\n}\n\nfunction hostFindingDiagnostic(\n artifacts: readonly NormalizedDocumentModelArtifact[],\n finding: HostValidationFindingData,\n): DefinitionDiagnostic {\n const { documentType } = finding;\n const sites = findingSites(artifacts, finding);\n switch (finding.kind) {\n case \"scalar-unbound\": {\n const { source, path, related } = attribution(\n sites,\n finding,\n `This version also declares ${finding.scalar}.`,\n );\n return releaseDiagnostics.create({\n code: \"PH-REL-HOST-SCALAR-UNBOUND\",\n ...(source !== undefined && { source }),\n definition: { kind: \"scalar\", key: finding.scalar },\n path,\n message: `${documentType} declares package scalar ${finding.scalar}, but the package registers no binding for it, so a host serves ${finding.scalar} values without validating them.`,\n expected: `an export named ${finding.scalar} in the package's scalars entry`,\n received: \"no binding\",\n repair: `Export the defineScalar binding the model uses from scalars/index.ts under the name ${finding.scalar}.`,\n ...(related.length > 0 && { related }),\n });\n }\n case \"scalar-mismatch\": {\n const { source, path, related } = attribution(\n sites,\n finding,\n `This version also declares ${finding.scalar}.`,\n );\n return releaseDiagnostics.create({\n code: \"PH-REL-HOST-SCALAR-MISMATCH\",\n ...(source !== undefined && { source }),\n definition: { kind: \"scalar\", key: finding.scalar },\n path,\n message: `${documentType} declares package scalar ${finding.scalar} differently from the binding package ${finding.packageName} registers, and a host serves the registered binding.`,\n expected: finding.declared,\n received: finding.registered,\n repair: `Use the ${finding.scalar} binding that scalars/index.ts exports in the model, so the model and the package declare one ${finding.scalar}.`,\n ...(related.length > 0 && { related }),\n });\n }\n case \"definition-invalid\":\n case \"definition-mismatch\": {\n const { source, path, related } = attribution(\n sites,\n finding,\n `This version of ${documentType} carries the same definition.`,\n );\n const invalid = finding.kind === \"definition-invalid\";\n const repairs = [...new Set(finding.diagnostics.map((d) => d.repair))];\n return releaseDiagnostics.create({\n code: invalid\n ? \"PH-REL-HOST-DEFINITION-INVALID\"\n : \"PH-REL-HOST-DEFINITION-MISMATCH\",\n ...(source !== undefined && { source }),\n definition:\n sites.length === 0\n ? { kind: \"document-model\", key: documentType }\n : documentModelRef(sites[0].artifact),\n path,\n message: invalid\n ? `A host serves ${documentType} from its stored SDL, because the module's definition fails the wire shape.`\n : `A host serves ${documentType} from its stored SDL, because the module's definition declares another document type or version.`,\n repair:\n repairs.length > 0\n ? repairs.join(\" \")\n : \"Materialize the module and its definition from the same declaration, and export the module materialize returned.\",\n related: [\n ...related,\n ...finding.diagnostics.map(({ code, path, message }) => ({\n path,\n message: `${code}: ${message}`,\n })),\n ],\n });\n }\n }\n}\n\n/**\n * Maps the host's verdict on the package's models to diagnostics, so a\n * release check fails on what a host would refuse or serve differently.\n */\nexport const hostValidationCheck: DefinitionCheck<ReleaseCheckInput> = {\n name: \"host-validation\",\n run: ({ artifacts, release: { host } }) => [\n ...(host.completed\n ? []\n : [\n releaseDiagnostics.create({\n code: \"PH-REL-HOST-VALIDATION-INCOMPLETE\",\n path: [],\n message:\n \"Host validation did not run, so this check cannot tell whether a host serves the package's models as declared.\",\n received: host.reason,\n repair:\n \"Fix what stopped host validation, then run the release check again.\",\n }),\n ]),\n ...host.findings.map((finding) =>\n hostFindingDiagnostic(artifacts, finding),\n ),\n ],\n};\n","import type { DefinitionCheck } from \"../check/types.js\";\nimport { hostValidationCheck } from \"./checks/host-validation.js\";\nimport type { ReleaseCheckInput } from \"./types.js\";\n\n/**\n * @experimental The checks the release profile of `ph build --release` and\n * `ph model check --release` adds to `documentModelChecks`. They read the\n * release evidence a caller gathered.\n */\nexport const releaseChecks: readonly DefinitionCheck<ReleaseCheckInput>[] =\n Object.freeze([hostValidationCheck]);\n","import { defineDiagnosticCatalog } from \"../../kernel/diagnostics.js\";\nimport { toolingDiagnostics } from \"../diagnostic-codes.js\";\n\nexport const inspectDiagnostics = defineDiagnosticCatalog(\n {\n \"PH-INSPECT-SELECTION-UNKNOWN\": {\n severity: \"error\",\n // A mistyped selection is a usage error, not a defect of the package.\n phase: \"configuration\",\n meaning:\n \"The selected document type and version is not served by any model of the package\",\n },\n },\n toolingDiagnostics,\n);\n","import type {\n DefinitionDiagnostic,\n Sha256Digest,\n} from \"@powerhousedao/shared/document-model\";\nimport type { NormalizedDocumentModelArtifact } from \"../adapters/types.js\";\nimport { servedSpecification } from \"../report/served-specification.js\";\nimport {\n compareArtifacts,\n definitionStatus,\n sortedUniqueDiagnostics,\n} from \"../report/status.js\";\nimport { logicalCollisionDiagnostics } from \"../report/logical-collisions.js\";\nimport type { LoadedDefinitionProject } from \"../report/types.js\";\nimport { inspectDiagnostics } from \"./diagnostic-codes.js\";\nimport type {\n DefinitionInspectionReport,\n DefinitionInspectionSelection,\n DocumentModelFamilyInspection,\n DocumentModelInspection,\n} from \"./types.js\";\n\n/** Keeps the capped `expected` text from cutting a key in half. */\nconst MAX_LISTED = 20;\n\nfunction inspection(\n artifact: NormalizedDocumentModelArtifact,\n): DocumentModelInspection | undefined {\n const served = servedSpecification(artifact);\n if (served === undefined) return undefined;\n const { specification } = served;\n return {\n version: artifact.version,\n source: artifact.source,\n scopes: {\n global: specification.state.global.root.name,\n local: specification.state.local.root?.name ?? null,\n },\n modules: specification.modules.map((module) => ({\n key: module.key,\n name: module.name,\n operations: module.operations.map((operation) => ({\n key: operation.key,\n name: operation.name,\n actionType: operation.actionType,\n scope: operation.scope,\n input: operation.input?.name ?? null,\n errors: operation.errors.map(({ key, code }) => ({ key, code })),\n })),\n })),\n scalars: specification.scalars.map(({ name, implementation }) => ({\n name,\n implementation,\n })),\n types: specification.types.map(({ name }) => name),\n };\n}\n\n/** Artifacts that carry one definition, and so one digest, form one family. */\nfunction families(\n artifacts: readonly NormalizedDocumentModelArtifact[],\n): readonly DocumentModelFamilyInspection[] {\n const grouped = new Map<\n Sha256Digest,\n {\n readonly first: NormalizedDocumentModelArtifact;\n readonly versions: DocumentModelInspection[];\n }\n >();\n for (const artifact of artifacts) {\n const version = inspection(artifact);\n if (version === undefined) continue;\n const family = grouped.get(artifact.digest);\n if (family === undefined) {\n grouped.set(artifact.digest, { first: artifact, versions: [version] });\n } else {\n family.versions.push(version);\n }\n }\n return [...grouped.values()].map(({ first, versions }) => ({\n documentType: first.documentType,\n name: first.definition.model.name,\n extension: first.definition.model.extension,\n digest: first.digest,\n compatibility: first.definition.compatibility,\n versions,\n }));\n}\n\nfunction unknownSelection(\n selection: DefinitionInspectionSelection,\n artifacts: readonly NormalizedDocumentModelArtifact[],\n): DefinitionDiagnostic {\n const available = [\n ...new Set(\n artifacts.map(\n ({ documentType, version }) => `${documentType}@${version}`,\n ),\n ),\n ];\n const listed =\n available.length <= MAX_LISTED\n ? available.join(\", \")\n : `${available.slice(0, MAX_LISTED).join(\", \")}, and ${available.length - MAX_LISTED} more`;\n const selected = `${selection.documentType}@${selection.version}`;\n return inspectDiagnostics.create({\n code: \"PH-INSPECT-SELECTION-UNKNOWN\",\n path: [\"selection\"],\n message: `No model of this package serves ${selected}.`,\n expected: available.length === 0 ? \"a package with a model\" : listed,\n received: selected,\n repair:\n available.length === 0\n ? \"Add a document model to the package, or register its code-first source in definitionSources.\"\n : `Inspect one of: ${listed}.`,\n });\n}\n\n/**\n * @experimental Describes the loaded models without running checks. With a\n * selection it answers for that model only, and adds its full definition\n * when exactly one model serves it. Experimental while code-first projects\n * are introduced.\n */\nexport function inspectProjectDefinitions(\n project: LoadedDefinitionProject,\n options: { readonly selection?: DefinitionInspectionSelection } = {},\n): DefinitionInspectionReport {\n const artifacts = [...project.artifacts].sort(compareArtifacts);\n const { selection } = options;\n const selected =\n selection === undefined\n ? artifacts\n : artifacts.filter(\n ({ documentType, version }) =>\n documentType === selection.documentType &&\n version === selection.version,\n );\n const diagnostics = sortedUniqueDiagnostics([\n ...project.diagnostics,\n ...(selection === undefined\n ? []\n : selected.length === 0\n ? [unknownSelection(selection, artifacts)]\n : logicalCollisionDiagnostics(project.sourceSet, selected)),\n ]);\n return {\n kind: \"powerhouse.definition-inspection\",\n formatVersion: 1,\n status: definitionStatus({\n ...(project.skipReason !== undefined && {\n skipReason: project.skipReason,\n }),\n definitions: artifacts,\n diagnostics,\n }),\n sourceSet: project.sourceSet,\n families: families(selected),\n diagnostics,\n ...(selection !== undefined &&\n selected.length === 1 && { definition: selected[0].definition }),\n };\n}\n","import type {\n DefinitionDiagnostic,\n Sha256Digest,\n} from \"@powerhousedao/shared/document-model\";\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport {\n isScalarDefinition,\n type ScalarDefinition,\n} from \"../../../scalars/types.js\";\nimport { compareCodeUnits } from \"../../kernel/primitives.js\";\nimport type { DefinitionSourceLoader } from \"../definition-source-loader.js\";\n\n/** Where codegen reads a package's `defineScalar` exports from. */\nconst PROJECT_SCALARS_SPECIFIER = \"./scalars/index.ts\";\n\n/** The scalars `scalars/index.ts` exports, imported like the selected sources. */\nexport async function loadProjectScalars(request: {\n readonly loader: DefinitionSourceLoader;\n readonly packageRoot: string;\n readonly configFile: string;\n readonly packageRevision: Sha256Digest;\n readonly signal?: AbortSignal;\n}): Promise<{\n readonly definitions: readonly ScalarDefinition[];\n readonly diagnostics: readonly DefinitionDiagnostic[];\n}> {\n const { loader, packageRoot, configFile, packageRevision, signal } = request;\n if (!existsSync(join(packageRoot, \"scalars\", \"index.ts\"))) {\n return { definitions: [], diagnostics: [] };\n }\n const imported = await loader.importPackageModule({\n configFile,\n packageRevision,\n ...(signal !== undefined && { signal }),\n specifier: PROJECT_SCALARS_SPECIFIER,\n });\n if (!imported.ok) {\n return { definitions: [], diagnostics: imported.diagnostics };\n }\n // Codegen emits `import { <name> } from \"scalars\"`, so only an export bound\n // under the scalar's own name makes it available.\n const definitions = Object.entries(imported.namespace)\n .flatMap(([exportName, value]) =>\n isScalarDefinition(value) && value.name === exportName ? [value] : [],\n )\n .sort((left, right) => compareCodeUnits(left.name, right.name));\n return { definitions, diagnostics: [] };\n}\n","import type { StoredScalarDefinition } from \"@powerhousedao/shared/document-model\";\nimport type { ScalarDefinition } from \"./types.js\";\n\n/** The metadata a stored definition records for a `defineScalar` binding. */\nexport function storedScalarDefinition(\n definition: ScalarDefinition,\n): StoredScalarDefinition {\n return {\n kind: \"powerhouse.scalar\",\n formatVersion: 1,\n name: definition.name,\n representation: definition.representation ?? \"json\",\n description: definition.description ?? \"\",\n coercion: {\n source: definition.coercion === undefined ? \"derived\" : \"explicit\",\n },\n coercionProfile: \"catalog-v1\",\n };\n}\n","import type {\n DocumentScalarReferenceDefinition,\n InputTypeDefinition,\n NamedGraphQLTypeDefinition,\n PowerhouseScalarName,\n TypeReferenceDefinition,\n} from \"@powerhousedao/shared/document-model\";\nimport { documentModelScalars } from \"../../scalars/catalog.js\";\nimport type { ScalarDefinition } from \"../../scalars/types.js\";\nimport { storedScalarDefinition } from \"../../scalars/stored-definition.js\";\nimport { compareCodeUnits } from \"../kernel/primitives.js\";\n\nexport function scalarReferences(\n catalogScalars: ReadonlySet<string>,\n packageScalars: ReadonlyMap<string, ScalarDefinition>,\n): readonly DocumentScalarReferenceDefinition[] {\n const catalog = documentModelScalars\n .map(({ name }) => name as PowerhouseScalarName)\n .filter((name) => catalogScalars.has(name))\n .map(\n (name) =>\n ({\n name,\n implementation: `powerhouse.catalog#${name}`,\n coercionProfile: \"catalog-v1\",\n }) as DocumentScalarReferenceDefinition,\n );\n const declared = [...packageScalars]\n .sort(([left], [right]) => compareCodeUnits(left, right))\n .map(([name, definition]): DocumentScalarReferenceDefinition => ({\n name,\n implementation: `package#${name}`,\n coercionProfile: \"catalog-v1\",\n definition: storedScalarDefinition(definition),\n }));\n return [...catalog, ...declared];\n}\n\n// The host builds its schema from state SDL and drops scalar declarations from\n// operation SDL, so a scalar only local state or an operation input uses is\n// declared in the global segment too.\nexport function declareProjectScalars(\n segment: string,\n packageScalars: ReadonlyMap<string, ScalarDefinition>,\n): string {\n return [\n ...[...packageScalars.keys()]\n .sort(compareCodeUnits)\n .map((name) => `scalar ${name}`),\n segment,\n ].join(\"\\n\\n\");\n}\n\nfunction namedTypeOf(type: TypeReferenceDefinition): string {\n return type.kind === \"list\" ? namedTypeOf(type.item) : type.name;\n}\n\nexport function inputReachesProjectScalar(\n input: InputTypeDefinition,\n types: readonly NamedGraphQLTypeDefinition[],\n packageScalars: ReadonlyMap<string, ScalarDefinition>,\n): boolean {\n const visited = new Set<string>();\n const reaches = (candidate: InputTypeDefinition): boolean => {\n if (visited.has(candidate.name)) return false;\n visited.add(candidate.name);\n return candidate.fields.some((field) => {\n const name = namedTypeOf(field.type);\n if (packageScalars.has(name)) return true;\n const target = types.find((type) => type.name === name);\n return target?.kind === \"input\" && reaches(target);\n });\n };\n return reaches(input);\n}\n","import { DocumentModelGlobalStateSchema } from \"@powerhousedao/shared/document-model\";\nimport type {\n CompiledErrorDefinition,\n DefinitionExample,\n DefinitionPath,\n DefinitionSource,\n DocumentModelDefinition,\n DocumentModelGlobalState,\n DocumentModelModuleDefinition,\n DocumentModelOperationDefinition,\n DocumentModelPHState,\n DocumentModelSpecificationDefinition,\n DocumentSpecification,\n InputTypeDefinition,\n JsonValue,\n NamedGraphQLTypeDefinition,\n OperationSpecification,\n StateDefinition,\n} from \"@powerhousedao/shared/document-model\";\nimport { scalarCatalog } from \"../../../scalars/catalog.js\";\nimport type { ScalarDefinition } from \"../../../scalars/types.js\";\nimport { scalarReferences } from \"../../compiler/stored-scalar.js\";\nimport {\n deriveDocumentModelNames,\n deriveDocumentModelSymbolNames,\n} from \"../../compiler/naming.js\";\nimport { checkDocumentModelDefinitionShape } from \"../../compiler/wire-shape.js\";\nimport {\n rejectionReceived,\n snapshotRecord,\n snapshotDataRecord,\n} from \"../../kernel/data-properties.js\";\nimport { DefinitionDiagnosticCollector } from \"../../kernel/diagnostic-collector.js\";\nimport { describeReceived } from \"../../kernel/diagnostics.js\";\nimport {\n canonicalDigest,\n EMPTY_INPUT_FIELD_NAME,\n} from \"../../kernel/primitives.js\";\nimport type { NormalizedDocumentModelResult } from \"../adapters/types.js\";\nimport {\n type ToolingDiagnosticCode,\n toolingDiagnostics,\n} from \"../diagnostic-codes.js\";\nimport {\n declaredTypeNames,\n type GraphQLDefinitionNode,\n referencedTypeNames,\n structuredTypes,\n} from \"../graphql/ast-to-structured.js\";\nimport { parseSchema } from \"../graphql/parse-schema.js\";\n\ntype Collector = DefinitionDiagnosticCollector<ToolingDiagnosticCode>;\n\n/** @experimental Options for {@link adaptSchemaFirstDocumentModelModule}. */\nexport type SchemaFirstAdapterOptions = {\n readonly version?: number;\n\n readonly scalars?: readonly ScalarDefinition[];\n};\n\nconst EXAMPLE_KEY_PREFIX = \"schema-first-id:\";\n\nfunction producesRuntimeSymbol(name: unknown): name is string {\n if (typeof name !== \"string\" || name.trim() === \"\") return false;\n const { typeName, memberName, constantName } =\n deriveDocumentModelSymbolNames(name);\n return typeName !== \"\" && memberName !== \"\" && constantName !== \"\";\n}\n\nfunction blocked(\n collector: Collector,\n kind: \"module\" | \"operation\" | \"error\",\n value: unknown,\n path: DefinitionPath,\n): undefined {\n const received =\n typeof value === \"string\" ? JSON.stringify(value) : String(value);\n collector.add({\n code: \"PH-DM-DECLARATION-INVALID\",\n path,\n message: `The stored ${kind} name ${received} never produced a runtime symbol, so there is no generated ${kind} to describe.`,\n expected: \"a name with at least one letter or digit\",\n received,\n repair: `Name the ${kind} in the document model editor and generate again.`,\n });\n return undefined;\n}\n\nfunction examples(\n stored: readonly { readonly id: string; readonly value: string }[],\n): readonly DefinitionExample[] {\n return stored.map(({ id, value }) => ({\n id,\n key: `${EXAMPLE_KEY_PREFIX}${id}`,\n value,\n }));\n}\n\nfunction parseInitialValue(\n collector: Collector,\n stored: string,\n path: DefinitionPath,\n emptyIsObject: boolean,\n): JsonValue | undefined {\n if (emptyIsObject && stored.trim() === \"\") return {};\n let parsed: unknown;\n try {\n parsed = JSON.parse(stored);\n } catch {\n parsed = undefined;\n }\n if (parsed !== null && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n return parsed as JsonValue;\n }\n collector.add({\n code: \"PH-DM-INITIAL-VALUE-INVALID\",\n path,\n message:\n \"The stored initial value does not parse to a JSON object, so it cannot be the value its state root holds.\",\n expected: \"a JSON object, encoded once\",\n received: stored,\n repair: \"Store the scope's initial value as a JSON object.\",\n });\n return undefined;\n}\n\nfunction emptyInputProjection(input: InputTypeDefinition): InputTypeDefinition {\n const [only] = input.fields;\n const empty =\n input.fields.length === 1 &&\n only.name === EMPTY_INPUT_FIELD_NAME &&\n only.type.kind === \"scalar\" &&\n only.type.name === \"Boolean\" &&\n !only.type.required;\n return empty ? { ...input, fields: [] } : input;\n}\n\nfunction modelScalarReferences(\n definitions: readonly GraphQLDefinitionNode[],\n scalars: readonly ScalarDefinition[],\n): DocumentModelSpecificationDefinition[\"scalars\"] {\n const used = new Set(referencedTypeNames(definitions));\n return scalarReferences(\n used,\n new Map(\n scalars\n .filter(({ name }) => used.has(name))\n .map((definition) => [definition.name, definition]),\n ),\n );\n}\n\nfunction normalizeOperation(\n collector: Collector,\n operation: OperationSpecification,\n typesByName: ReadonlyMap<string, NamedGraphQLTypeDefinition>,\n path: DefinitionPath,\n): DocumentModelOperationDefinition | undefined {\n if (!producesRuntimeSymbol(operation.name)) {\n return blocked(collector, \"operation\", operation.name, [...path, \"name\"]);\n }\n if (operation.scope !== \"global\" && operation.scope !== \"local\") {\n collector.add({\n code: \"PH-DM-SCOPE-UNSUPPORTED\",\n path: [...path, \"scope\"],\n message: `Operation ${JSON.stringify(operation.name)} is stored in scope ${JSON.stringify(operation.scope)}, which a V1 definition cannot record.`,\n expected: \"global | local\",\n received: String(operation.scope),\n repair: \"Store the operation in the global or local scope.\",\n });\n return undefined;\n }\n const names = deriveDocumentModelSymbolNames(operation.name);\n const inputName = `${names.typeName}Input`;\n const hasSchema = operation.schema !== null && operation.schema.trim() !== \"\";\n const declared = hasSchema ? typesByName.get(inputName) : undefined;\n if (hasSchema && declared?.kind !== \"input\") {\n collector.add({\n code: \"PH-DM-DECLARATION-INVALID\",\n path: [...path, \"schema\"],\n message: `The stored schema of operation ${JSON.stringify(operation.name)} declares no input type ${inputName}, which codegen and the host read its input from.`,\n expected: `input ${inputName} { ... }`,\n received: declared === undefined ? \"absent\" : declared.kind,\n repair: `Declare input ${inputName} in the operation's schema.`,\n });\n return undefined;\n }\n const errors = operation.errors.map(\n (error, index): CompiledErrorDefinition | undefined =>\n producesRuntimeSymbol(error.name)\n ? {\n id: error.id,\n key: deriveDocumentModelSymbolNames(error.name).typeName,\n code: error.code,\n name: error.name,\n description: error.description,\n template: error.template,\n }\n : blocked(collector, \"error\", error.name, [\n ...path,\n \"errors\",\n index,\n \"name\",\n ]),\n );\n if (errors.includes(undefined)) return undefined;\n return {\n id: operation.id,\n key: names.memberName,\n name: operation.name,\n description: operation.description,\n actionType: names.constantName,\n creatorKey: names.memberName,\n scope: operation.scope,\n input: declared?.kind === \"input\" ? emptyInputProjection(declared) : null,\n errors: errors as readonly CompiledErrorDefinition[],\n examples: examples(operation.examples),\n template: operation.template,\n reducer: operation.reducer,\n };\n}\n\nfunction rootState(\n collector: Collector,\n stored: DocumentSpecification[\"state\"][\"global\"],\n root: string | null,\n path: DefinitionPath,\n scope: \"global\" | \"local\",\n): StateDefinition | undefined {\n const initialValue = parseInitialValue(\n collector,\n stored.initialValue,\n [...path, \"initialValue\"],\n scope === \"local\",\n );\n if (initialValue === undefined) return undefined;\n const materialized = {\n initialValue: stored.initialValue,\n examples: stored.examples.map(({ id, value }) => ({ id, value })),\n };\n return root === null\n ? {\n root: null,\n initialValue: {},\n examples: examples(stored.examples),\n unknownKeys: \"preserve\",\n materialized: { ...materialized, schema: \"\" },\n }\n : {\n root: { kind: \"named\", name: root, required: true },\n initialValue,\n examples: examples(stored.examples),\n unknownKeys: \"preserve\",\n materialized: { ...materialized, schema: stored.schema },\n };\n}\n\nconst BUILT_IN_SCALARS: ReadonlySet<string> = new Set([\n \"ID\",\n \"String\",\n \"Boolean\",\n \"Int\",\n \"Float\",\n]);\n\nconst CATALOG_SCALARS: ReadonlySet<string> = new Set(\n scalarCatalog.map(({ name }) => name),\n);\n\n/**\n * Codegen imports every scalar a stored schema declares or uses from\n * scalars/index.ts unless it is built in or in the catalog. A missing export\n * would otherwise surface later as an error that never names it.\n */\nfunction knownScalars(\n collector: Collector,\n segments: readonly {\n readonly path: DefinitionPath;\n readonly definitions: readonly GraphQLDefinitionNode[];\n }[],\n declared: ReadonlySet<string>,\n scalars: readonly ScalarDefinition[],\n): boolean {\n const project = new Set(scalars.map(({ name }) => name));\n const reported = new Set<string>();\n for (const segment of segments) {\n const names = [\n ...referencedTypeNames(segment.definitions)\n .filter((name) => !declared.has(name))\n .map((name) => ({ name, verb: \"uses\" })),\n ...segment.definitions.flatMap((node) =>\n node.kind === \"ScalarTypeDefinition\"\n ? [{ name: node.name.value, verb: \"declares\" }]\n : [],\n ),\n ];\n for (const { name, verb } of names) {\n if (\n BUILT_IN_SCALARS.has(name) ||\n CATALOG_SCALARS.has(name) ||\n project.has(name) ||\n reported.has(name)\n ) {\n continue;\n }\n reported.add(name);\n collector.add({\n code: \"PH-DM-DECLARATION-INVALID\",\n path: segment.path,\n message: `The stored schema ${verb} scalar ${name}, which is not a GraphQL built-in, a catalog scalar, or a project scalar exported from scalars/index.ts.`,\n expected: \"a scalar defined with defineScalar in scalars/index.ts\",\n received: name,\n repair: `Export ${name} from scalars/index.ts with defineScalar, or use a catalog scalar.`,\n });\n }\n }\n return reported.size === 0;\n}\n\n/** A specification's stored SDL strings, in the order its retained document concatenates them. */\nexport function storedSchemaSegments(\n specification: DocumentSpecification,\n path: DefinitionPath,\n): readonly { readonly schema: string; readonly path: DefinitionPath }[] {\n return [\n {\n schema: specification.state.global.schema,\n path: [...path, \"state\", \"global\", \"schema\"],\n },\n {\n schema: specification.state.local.schema,\n path: [...path, \"state\", \"local\", \"schema\"],\n },\n ...specification.modules.flatMap((module, moduleIndex) =>\n module.operations.map((operation, operationIndex) => ({\n schema: operation.schema ?? \"\",\n path: [\n ...path,\n \"modules\",\n moduleIndex,\n \"operations\",\n operationIndex,\n \"schema\",\n ],\n })),\n ),\n ];\n}\n\nfunction normalizeSpecification(\n collector: Collector,\n specification: DocumentSpecification,\n roots: { readonly global: string; readonly local: string },\n path: DefinitionPath,\n scalars: readonly ScalarDefinition[],\n): DocumentModelSpecificationDefinition | undefined {\n const segments = storedSchemaSegments(specification, path);\n const parsedSegments: {\n readonly path: DefinitionPath;\n readonly definitions: readonly GraphQLDefinitionNode[];\n }[] = [];\n for (const segment of segments) {\n const parsed = parseSchema(segment.schema);\n if (!parsed.ok) {\n collector.add({\n code: \"PH-DM-DECLARATION-INVALID\",\n path: segment.path,\n message: `The stored schema is not GraphQL SDL: ${parsed.message}`,\n expected: \"GraphQL SDL\",\n received: segment.schema,\n repair: \"Fix the schema in the document model editor.\",\n });\n return undefined;\n }\n parsedSegments.push({\n path: segment.path,\n definitions: parsed.document.definitions,\n });\n }\n const definitions = parsedSegments.flatMap((segment) => segment.definitions);\n const declared = declaredTypeNames(definitions);\n if (!knownScalars(collector, parsedSegments, declared, scalars)) {\n return undefined;\n }\n const allTypes = structuredTypes(definitions, declared);\n const typesByName: ReadonlyMap<string, NamedGraphQLTypeDefinition> = new Map(\n allTypes.map((type) => [type.name, type]),\n );\n\n const hasLocalRoot = specification.state.local.schema.trim() !== \"\";\n for (const scope of [\"global\", \"local\"] as const) {\n if (scope === \"local\" && !hasLocalRoot) continue;\n if (typesByName.get(roots[scope])?.kind !== \"object\") {\n collector.add({\n code: \"PH-DM-STATE-ROOT-INVALID\",\n path: [...path, \"state\", scope, \"schema\"],\n message: `The stored ${scope} state schema declares no object type named ${roots[scope]}.`,\n expected: `type ${roots[scope]} { ... }`,\n received: [...typesByName.keys()].join(\", \"),\n repair: `Name the ${scope} state root after the model; every consumer resolves it by that name.`,\n });\n return undefined;\n }\n }\n\n const modules: DocumentModelModuleDefinition[] = [];\n for (const [moduleIndex, module] of specification.modules.entries()) {\n const modulePath = [...path, \"modules\", moduleIndex];\n if (!producesRuntimeSymbol(module.name)) {\n return blocked(collector, \"module\", module.name, [...modulePath, \"name\"]);\n }\n const operations = module.operations.map((operation, operationIndex) =>\n normalizeOperation(collector, operation, typesByName, [\n ...modulePath,\n \"operations\",\n operationIndex,\n ]),\n );\n if (operations.includes(undefined)) return undefined;\n modules.push({\n id: module.id,\n key: deriveDocumentModelSymbolNames(module.name).memberName,\n name: module.name,\n description: module.description,\n operations: operations as readonly DocumentModelOperationDefinition[],\n });\n }\n\n const global = rootState(\n collector,\n specification.state.global,\n roots.global,\n [...path, \"state\", \"global\"],\n \"global\",\n );\n const local = rootState(\n collector,\n specification.state.local,\n hasLocalRoot ? roots.local : null,\n [...path, \"state\", \"local\"],\n \"local\",\n );\n if (global === undefined || global.root === null || local === undefined) {\n return undefined;\n }\n\n const inputs = new Set(\n modules.flatMap((module) =>\n module.operations.flatMap((operation) =>\n operation.input === null ? [] : [operation.input.name],\n ),\n ),\n );\n return {\n version: specification.version,\n scalars: modelScalarReferences(definitions, scalars),\n graphQLCompatibility: {\n kind: \"graphql-ast-v1\",\n document: { kind: \"Document\", definitions },\n preserveDefinitionOrder: true,\n },\n types: allTypes.filter((type) => !inputs.has(type.name)),\n state: { global, local },\n modules,\n changeLog: [...specification.changeLog],\n };\n}\n\ntype StoredModel = {\n readonly global: DocumentModelGlobalState;\n readonly documentModel: DocumentModelPHState;\n readonly version: number;\n};\n\nfunction storedModel(\n collector: Collector,\n value: unknown,\n options: SchemaFirstAdapterOptions,\n): StoredModel | undefined {\n const root = snapshotRecord(value, undefined, []);\n const module =\n root.ok && root.value.documentModel !== undefined ? root.value : undefined;\n const documentModel = module === undefined ? value : module.documentModel;\n const path = module === undefined ? [] : [\"documentModel\"];\n const state = snapshotRecord(documentModel, undefined, path);\n const global = state.ok\n ? snapshotDataRecord(state.value.global, undefined, [...path, \"global\"])\n : state;\n if (!global.ok) {\n collector.add({\n code: \"PH-DM-DECLARATION-INVALID\",\n path: global.path,\n message: `This export is neither a generated document-model module nor its stored state (${global.reason}).`,\n expected: \"a module with documentModel.global, or a DocumentModelPHState\",\n received: rejectionReceived(global),\n repair: \"Pass the module ph generate produced, or its documentModel.\",\n });\n return undefined;\n }\n const parsed = DocumentModelGlobalStateSchema().safeParse(global.value);\n if (!parsed.success) {\n for (const issue of parsed.error.issues) {\n collector.add({\n code: \"PH-DM-DECLARATION-INVALID\",\n path: [\n ...path,\n \"global\",\n ...issue.path.map((segment) =>\n typeof segment === \"symbol\" ? String(segment) : segment,\n ),\n ],\n message: issue.message,\n expected: \"a stored document model matching DocumentModelGlobalState\",\n received: \"a malformed stored model\",\n repair:\n \"Pass the module ph generate produced, or its stored documentModel.\",\n });\n }\n return undefined;\n }\n const declared: unknown = options.version ?? module?.version ?? 1;\n if (\n typeof declared !== \"number\" ||\n !Number.isSafeInteger(declared) ||\n declared <= 0\n ) {\n collector.add({\n code: \"PH-DM-DECLARATION-INVALID\",\n path: [\"version\"],\n message: \"A module's registry version is a positive safe integer.\",\n expected: \"a positive safe integer\",\n received:\n typeof declared === \"number\"\n ? String(declared)\n : describeReceived(declared),\n repair: \"Pass the version this module registers.\",\n });\n return undefined;\n }\n return {\n global: parsed.data,\n documentModel: documentModel as DocumentModelPHState,\n version: declared,\n };\n}\n\n/**\n * @experimental Normalizes one generated schema-first module, or one stored\n * `DocumentModelPHState`, into the V1 wire shape. A model it cannot\n * normalize is reported in `diagnostics`; the stored members it trusts are\n * the ones `ph generate` writes. Experimental: it exists so code-first and\n * schema-first models can be read through one shape while code-first\n * projects are introduced.\n */\nexport function adaptSchemaFirstDocumentModelModule(\n value: unknown,\n source: DefinitionSource,\n options: SchemaFirstAdapterOptions = {},\n): NormalizedDocumentModelResult {\n const probe: Collector = new DefinitionDiagnosticCollector(\n toolingDiagnostics,\n );\n const stored = storedModel(probe, value, options);\n if (stored === undefined) {\n return {\n artifacts: [],\n upgradeManifest: null,\n diagnostics: probe.diagnostics,\n };\n }\n const { global, version } = stored;\n const collector: Collector = new DefinitionDiagnosticCollector(\n toolingDiagnostics,\n { kind: \"document-model\", key: global.id, version },\n );\n const failed = (): NormalizedDocumentModelResult => ({\n artifacts: [],\n upgradeManifest: null,\n diagnostics: collector.diagnostics,\n });\n const names = deriveDocumentModelNames({ id: global.id, name: global.name });\n const specifications = global.specifications.map((specification, index) =>\n normalizeSpecification(\n collector,\n specification,\n { global: names.globalStateRootName, local: names.localStateRootName },\n [\"specifications\", index],\n options.scalars ?? [],\n ),\n );\n if (specifications.includes(undefined)) return failed();\n\n const definition: DocumentModelDefinition = {\n kind: \"powerhouse.document-model\",\n formatVersion: 1,\n compatibility: {\n identity: \"explicit-schema-first\",\n scalarCoercion: \"catalog-v1\",\n serialization: \"explicit-schema-first\",\n },\n model: {\n documentType: global.id,\n graphQLName: names.graphQLName,\n name: global.name,\n description: global.description,\n extension: global.extension,\n author: { name: global.author.name, website: global.author.website },\n },\n specifications: specifications as DocumentModelSpecificationDefinition[],\n };\n const shape = checkDocumentModelDefinitionShape(definition);\n collector.merge(shape);\n if (shape.length > 0) return failed();\n if (!definition.specifications.some((entry) => entry.version === version)) {\n collector.add({\n code: \"PH-DM-DECLARATION-INVALID\",\n path: [\"specifications\"],\n message: `The stored history carries no version ${version}, which is the version this module serves.`,\n expected: `a specification for version ${version}`,\n received: definition.specifications\n .map((entry) => String(entry.version))\n .join(\", \"),\n repair:\n \"Pass the version this module registers, or the module that serves a stored version.\",\n });\n return failed();\n }\n return {\n artifacts: [\n {\n kind: \"powerhouse.document-model-artifact\",\n source,\n documentType: global.id,\n version,\n definition,\n digest: canonicalDigest(definition),\n documentModel: stored.documentModel,\n },\n ],\n upgradeManifest: null,\n diagnostics: collector.diagnostics,\n };\n}\n","import type {\n DefinitionPath,\n DocumentSpecification,\n} from \"@powerhousedao/shared/document-model\";\nimport type { DefinitionRelocation } from \"../adapters/producer.js\";\nimport type { NormalizedDocumentModelArtifact } from \"../adapters/types.js\";\nimport { parseSchema } from \"../graphql/parse-schema.js\";\nimport { storedSchemaSegments } from \"./schema-first-document-model-module-adapter.js\";\n\ntype SegmentDeclarations = {\n /** The segment of each node of the retained document, in document order. */\n readonly nodes: readonly DefinitionPath[];\n /** The first segment that defines each type, else the first that extends it. */\n readonly types: ReadonlyMap<string, DefinitionPath>;\n};\n\nfunction segmentDeclarations(\n specification: DocumentSpecification,\n path: DefinitionPath,\n): SegmentDeclarations {\n const nodes: DefinitionPath[] = [];\n const defined = new Map<string, DefinitionPath>();\n const extended = new Map<string, DefinitionPath>();\n for (const segment of storedSchemaSegments(specification, path)) {\n // The adapter produced an artifact, so every segment parsed.\n const parsed = parseSchema(segment.schema);\n if (!parsed.ok) continue;\n for (const node of parsed.document.definitions) {\n nodes.push(segment.path);\n const name = \"name\" in node ? node.name.value : undefined;\n if (name === undefined) continue;\n const first = node.kind.endsWith(\"Extension\") ? extended : defined;\n if (!first.has(name)) first.set(name, segment.path);\n }\n }\n return { nodes, types: new Map([...extended, ...defined]) };\n}\n\n/**\n * A schema-first author edits the stored file, which is the served global\n * state, and declares types in its SDL segments rather than as structured\n * types. Served paths lose their `documentModel/global` prefix; a type, a\n * scalar or a retained document node points at the segment that declares it.\n * Every result is cut back to the deepest member the stored file has, so no\n * location names a normalized-only member or reaches inside an SDL string.\n */\nexport function storedModelRelocation(\n artifact: NormalizedDocumentModelArtifact,\n): DefinitionRelocation {\n const stored = artifact.documentModel.global.specifications;\n const declarations = new Map<number, SegmentDeclarations>();\n const declared = (index: number): SegmentDeclarations => {\n let found = declarations.get(index);\n if (found === undefined) {\n found = segmentDeclarations(stored[index], [\"specifications\", index]);\n declarations.set(index, found);\n }\n return found;\n };\n const relocate = (path: DefinitionPath): DefinitionPath => {\n if (path[0] === \"documentModel\" && path[1] === \"global\") {\n return path.slice(2);\n }\n const [root, index, member, ...rest] = path;\n if (\n root !== \"specifications\" ||\n typeof index !== \"number\" ||\n stored.at(index) === undefined\n ) {\n return path;\n }\n const specification: DefinitionPath = [\"specifications\", index];\n if (member === \"types\") {\n const name =\n typeof rest[0] === \"number\"\n ? artifact.definition.specifications.at(index)?.types.at(rest[0])\n ?.name\n : undefined;\n return (\n (name === undefined ? undefined : declared(index).types.get(name)) ??\n specification\n );\n }\n if (member === \"scalars\") {\n const name =\n typeof rest[0] === \"number\"\n ? artifact.definition.specifications.at(index)?.scalars.at(rest[0])\n ?.name\n : undefined;\n return (\n (name === undefined ? undefined : declared(index).types.get(name)) ??\n specification\n );\n }\n if (member === \"graphQLCompatibility\") {\n const [document, definitions, node] = rest;\n return (\n (document === \"document\" &&\n definitions === \"definitions\" &&\n typeof node === \"number\"\n ? declared(index).nodes.at(node)\n : undefined) ?? specification\n );\n }\n return path;\n };\n return (path) => storedPrefix(artifact.documentModel.global, relocate(path));\n}\n\nfunction storedPrefix(stored: unknown, path: DefinitionPath): DefinitionPath {\n let value = stored;\n let depth = 0;\n for (const segment of path) {\n if (typeof value !== \"object\" || value === null) break;\n if (!Object.hasOwn(value, segment)) break;\n value = (value as Readonly<Record<string | number, unknown>>)[segment];\n depth += 1;\n }\n return path.slice(0, depth);\n}\n","import {\n defaultBaseState,\n type DefinitionDiagnostic,\n type DefinitionSource,\n} from \"@powerhousedao/shared/document-model\";\nimport { readdirSync, readFileSync, realpathSync, statSync } from \"node:fs\";\nimport { join, relative, sep } from \"node:path\";\nimport type { ScalarDefinition } from \"../../../scalars/types.js\";\nimport { compareCodeUnits } from \"../../kernel/primitives.js\";\nimport type {\n DefinitionProducer,\n DefinitionRelocation,\n ProducedDefinitions,\n} from \"../adapters/producer.js\";\nimport { isWithin } from \"../definition-source-resolution.js\";\nimport { toolingDiagnostics } from \"../diagnostic-codes.js\";\nimport { describeThrown } from \"../structured-diagnostics.js\";\nimport { loadProjectScalars } from \"./project-scalars.js\";\nimport { adaptSchemaFirstDocumentModelModule } from \"./schema-first-document-model-module-adapter.js\";\nimport { storedModelRelocation } from \"./stored-locations.js\";\n\ntype StoredModelFiles = {\n readonly files: readonly string[];\n readonly diagnostics: readonly DefinitionDiagnostic[];\n};\n\nfunction unreadable(\n packageRoot: string,\n path: string,\n what: string,\n error: unknown,\n): DefinitionDiagnostic {\n return toolingDiagnostics.create({\n code: \"PH-IMPORT-FAILED\",\n source: { specifier: packageSpecifier(packageRoot, path) },\n path: [],\n message: `The ${what} could not be read, so the stored models in it are not checked.`,\n expected: `a readable ${what}`,\n received: describeThrown(error),\n repair: \"Fix the permissions of the path.\",\n });\n}\n\nfunction outsidePackage(specifier: `./${string}`): DefinitionDiagnostic {\n return toolingDiagnostics.create({\n code: \"PH-CONFIG-SOURCE-OUTSIDE-PACKAGE\",\n source: { specifier },\n path: [],\n message:\n \"The stored document model resolves through a symlink that leaves the package root, so it is not this package's model.\",\n expected: \"a real path contained by the package root\",\n received: specifier,\n repair:\n \"Replace the symlink with a model file that really lives in this package.\",\n });\n}\n\n/**\n * A missing models directory holds no models; any other read failure is\n * reported. A symlinked model directory or file counts when its real path\n * stays in the package.\n */\nfunction storedModelFiles(\n packageRoot: string,\n documentModelsDir: string,\n): StoredModelFiles {\n let names: string[];\n let packageRootIdentity: string;\n try {\n packageRootIdentity = realpathSync.native(packageRoot);\n names = readdirSync(documentModelsDir).sort(compareCodeUnits);\n } catch (error) {\n return {\n files: [],\n diagnostics:\n (error as NodeJS.ErrnoException).code === \"ENOENT\"\n ? []\n : [\n unreadable(\n packageRoot,\n documentModelsDir,\n \"document models directory\",\n error,\n ),\n ],\n };\n }\n const files: string[] = [];\n const diagnostics: DefinitionDiagnostic[] = [];\n for (const name of names) {\n const directory = join(documentModelsDir, name);\n const file = join(directory, `${name}.json`);\n let real: string;\n try {\n if (\n !statSync(directory, { throwIfNoEntry: false })?.isDirectory() ||\n !statSync(file, { throwIfNoEntry: false })?.isFile()\n ) {\n continue;\n }\n real = realpathSync.native(file);\n } catch (error) {\n diagnostics.push(\n unreadable(packageRoot, directory, \"document model directory\", error),\n );\n continue;\n }\n if (isWithin(packageRootIdentity, real)) files.push(file);\n else diagnostics.push(outsidePackage(packageSpecifier(packageRoot, file)));\n }\n return { files, diagnostics };\n}\n\nfunction packageSpecifier(packageRoot: string, file: string): `./${string}` {\n return `./${relative(packageRoot, file).split(sep).join(\"/\")}`;\n}\n\nfunction storedVersion(value: unknown): number | undefined {\n const specifications = (value as { specifications?: unknown } | null)\n ?.specifications;\n if (!Array.isArray(specifications)) return undefined;\n const version = (specifications.at(-1) as { version?: unknown } | undefined)\n ?.version;\n return typeof version === \"number\" ? version : undefined;\n}\n\nfunction adaptStoredModelFile(\n file: string,\n source: DefinitionSource,\n scalars: readonly ScalarDefinition[],\n): Omit<ProducedDefinitions, \"relocations\"> & {\n readonly relocation?: DefinitionRelocation;\n} {\n let text: string;\n try {\n text = readFileSync(file, \"utf8\");\n } catch (error) {\n return {\n artifacts: [],\n diagnostics: [\n toolingDiagnostics.create({\n code: \"PH-IMPORT-FAILED\",\n source,\n path: [],\n message: \"The stored document model file could not be read.\",\n expected: \"a readable JSON file\",\n received: describeThrown(error),\n repair: \"Fix the file's permissions.\",\n }),\n ],\n };\n }\n let stored: unknown;\n try {\n stored = JSON.parse(text);\n } catch (error) {\n return {\n artifacts: [],\n diagnostics: [\n toolingDiagnostics.create({\n code: \"PH-DM-DECLARATION-INVALID\",\n source,\n path: [],\n message: \"The stored document model is not JSON.\",\n expected: \"the JSON the document model editor saves\",\n received: describeThrown(error),\n repair:\n \"Repair the JSON, or save the model again from the document model editor.\",\n }),\n ],\n };\n }\n const version = storedVersion(stored);\n // Not createState: it fills absent members with defaults, which would hide\n // a malformed file.\n const result = adaptSchemaFirstDocumentModelModule(\n { ...defaultBaseState(), global: stored, local: {} },\n source,\n { scalars, ...(version !== undefined && { version }) },\n );\n const artifact = result.artifacts.at(0);\n return {\n // Every stored version is served, and each carries the whole history.\n artifacts:\n artifact === undefined\n ? []\n : artifact.definition.specifications.map((specification) => ({\n ...artifact,\n version: specification.version,\n })),\n ...(artifact !== undefined && {\n relocation: storedModelRelocation(artifact),\n }),\n // The adapter roots shape errors at the wrapping state's `global`, which\n // is the file itself.\n diagnostics: result.diagnostics.map((diagnostic) => ({\n ...diagnostic,\n source,\n path:\n diagnostic.path[0] === \"global\"\n ? diagnostic.path.slice(1)\n : diagnostic.path,\n })),\n };\n}\n\n/**\n * Normalizes every `<documentModelsDir>/<name>/<name>.json` a schema-first\n * package stores, with the project scalars `scalars/index.ts` exports. A\n * directory or file that cannot be read, or a file that cannot be adapted,\n * is a diagnostic.\n */\nexport const readStoredDocumentModels: DefinitionProducer = async (input) => {\n const { packageRoot, documentModelsDir } = input;\n if (documentModelsDir === undefined) {\n return { artifacts: [], diagnostics: [], relocations: new Map() };\n }\n const { files, diagnostics } = storedModelFiles(\n packageRoot,\n documentModelsDir,\n );\n if (files.length === 0) {\n return { artifacts: [], diagnostics, relocations: new Map() };\n }\n const scalars = await loadProjectScalars(input);\n const relocations = new Map<string, DefinitionRelocation>();\n const results = files.map((file) => {\n const specifier = packageSpecifier(packageRoot, file);\n const result = adaptStoredModelFile(\n file,\n { specifier },\n scalars.definitions,\n );\n if (result.relocation !== undefined) {\n relocations.set(specifier, result.relocation);\n }\n return result;\n });\n return {\n artifacts: results.flatMap((result) => result.artifacts),\n diagnostics: [\n ...diagnostics,\n ...scalars.diagnostics,\n ...results.flatMap((result) => result.diagnostics),\n ],\n relocations,\n };\n};\n","import type { DefinitionSource } from \"@powerhousedao/shared/document-model\";\nimport { readdirSync, readFileSync, realpathSync, statSync } from \"node:fs\";\nimport { join, relative, sep } from \"node:path\";\nimport { compareCodeUnits } from \"../../kernel/primitives.js\";\nimport type { UnregisteredDefinition } from \"../report/types.js\";\nimport { isWithin } from \"../definition-source-resolution.js\";\n\n/**\n * Finds `defineDocumentModel(Family)` calls under the document models\n * directory that no selected source reaches. Declarations are read from\n * source text, never run, so an unregistered model cannot fail the scan by\n * throwing. What a source reaches is the module graph its import evaluated.\n */\n\ntype Unit = UnregisteredDefinition & {\n /** Real paths. */\n readonly declaring: readonly string[];\n};\n\ntype Entry = {\n readonly name: string;\n /** As spelled under the models directory. */\n readonly path: string;\n readonly real: string;\n readonly isDirectory: boolean;\n};\n\nconst DECLARATION = {\n module: /^document-model(?:\\/|$)/,\n factory: \"defineDocumentModel(?:Family)?\",\n} as const;\n\nconst NAMED_IMPORT = /\\bimport\\s*\\{([^}]*)\\}\\s*from\\s*\"#(\\d+)\"/g;\n\nconst NAMESPACE_IMPORT = /\\bimport\\s*\\*\\s*as\\s+([\\w$]+)\\s*from\\s*\"#(\\d+)\"/g;\n\ntype Lexed = { readonly code: string; readonly strings: readonly string[] };\n\nfunction startsRegExp(code: string): boolean {\n const before = code.slice(-64).trimEnd();\n return (\n before === \"\" ||\n /[(,=:[!&|?{};+\\-*%<>~^}]$/.test(before) ||\n /(?:^|[^\\w$])(?:return|typeof|case|do|else|in|of|new|delete|void|throw|yield|await)$/.test(\n before,\n )\n );\n}\n\nfunction readCodeAndStrings(file: string): Lexed {\n let text: string;\n try {\n text = readFileSync(file, \"utf8\");\n } catch {\n return { code: \"\", strings: [] };\n }\n let code = \"\";\n const strings: string[] = [];\n const literal = (contents: string) => {\n code += `\"#${strings.length}\"`;\n strings.push(contents);\n };\n let braces = 0;\n const templates: number[] = [];\n let i = 0;\n const skipQuoted = (end: (index: number) => boolean) => {\n while (i < text.length && !end(i)) i += text[i] === \"\\\\\" ? 2 : 1;\n };\n while (i < text.length) {\n const char = text[i];\n if (char === \"/\" && text[i + 1] === \"/\") {\n i = text.indexOf(\"\\n\", i);\n if (i === -1) i = text.length;\n } else if (char === \"/\" && text[i + 1] === \"*\") {\n const end = text.indexOf(\"*/\", i + 2);\n i = end === -1 ? text.length : end + 2;\n code += \" \";\n } else if (char === \"/\" && startsRegExp(code)) {\n i += 1;\n let inClass = false;\n while (i < text.length && text[i] !== \"\\n\") {\n if (text[i] === \"\\\\\") i += 1;\n else if (text[i] === \"[\") inClass = true;\n else if (text[i] === \"]\") inClass = false;\n else if (text[i] === \"/\" && !inClass) break;\n i += 1;\n }\n i += 1;\n while (/[a-z]/.test(text[i] ?? \"\")) i += 1;\n code += \" \";\n } else if (char === '\"' || char === \"'\") {\n const start = (i += 1);\n skipQuoted((at) => text[at] === char || text[at] === \"\\n\");\n literal(text.slice(start, i));\n i += 1;\n } else if (char === \"`\" || (char === \"}\" && templates.at(-1) === braces)) {\n const whole = char === \"`\";\n if (!whole) templates.pop();\n const start = (i += 1);\n skipQuoted(\n (at) => text[at] === \"`\" || (text[at] === \"$\" && text[at + 1] === \"{\"),\n );\n const closed = text[i] === \"`\";\n literal(whole && closed ? text.slice(start, i) : \"\");\n if (closed) {\n i += 1;\n } else {\n templates.push(braces);\n i += 2;\n }\n } else {\n if (char === \"{\") braces += 1;\n if (char === \"}\") braces -= 1;\n code += char;\n i += 1;\n }\n }\n return { code, strings };\n}\n\n/** `type as e` imports a value named `type`. */\nfunction valueBindings(\n clause: string,\n): { readonly imported: string; readonly local: string }[] {\n return clause\n .split(\",\")\n .map((part) => part.trim())\n .filter((part) => part !== \"\" && !/^type\\s+(?!as\\b)/.test(part))\n .map((part) => {\n const [imported, local = imported] = part.split(/\\s+as\\s+/);\n return { imported, local };\n });\n}\n\nfunction isSourceFile(name: string): boolean {\n return /\\.m?tsx?$/.test(name) && !/\\.d\\.m?ts$/.test(name);\n}\n\nfunction isTestFile(name: string): boolean {\n return /\\.(?:test|spec)\\.m?tsx?$/.test(name);\n}\n\n/**\n * Sorted, with symlinks followed. An entry that cannot be read, or whose real\n * path leaves the package, is not the package's and is skipped.\n */\nfunction packageEntries(path: string, packageRootIdentity: string): Entry[] {\n let names: string[];\n try {\n names = readdirSync(path);\n } catch {\n return [];\n }\n return names\n .filter((name) => name !== \"node_modules\" && !name.startsWith(\".\"))\n .sort(compareCodeUnits)\n .flatMap((name) => {\n const child = join(path, name);\n try {\n const real = realpathSync.native(child);\n if (!isWithin(packageRootIdentity, real)) return [];\n const isDirectory = statSync(real).isDirectory();\n return [{ name, path: child, real, isDirectory }];\n } catch {\n return [];\n }\n });\n}\n\n/** `visited` holds real directories, so a symlink cycle ends. */\nfunction sourceFilesUnder(\n directory: Entry,\n packageRootIdentity: string,\n visited: Set<string>,\n): Entry[] {\n if (visited.has(directory.real)) return [];\n visited.add(directory.real);\n return packageEntries(directory.path, packageRootIdentity).flatMap(\n (entry) => {\n if (entry.isDirectory) {\n return entry.name === \"__tests__\"\n ? []\n : sourceFilesUnder(entry, packageRootIdentity, visited);\n }\n return isSourceFile(entry.name) && !isTestFile(entry.name) ? [entry] : [];\n },\n );\n}\n\nfunction declares(file: string): boolean {\n const { module, factory } = DECLARATION;\n const { code, strings } = readCodeAndStrings(file);\n const isFactory = new RegExp(`^${factory}$`);\n const callees = [\n ...[...code.matchAll(NAMED_IMPORT)]\n .filter(([, , index]) => module.test(strings[Number(index)]))\n .flatMap(([, clause]) =>\n valueBindings(clause)\n .filter(({ imported }) => isFactory.test(imported))\n .map(({ local }) => escapeRegExp(local)),\n ),\n ...[...code.matchAll(NAMESPACE_IMPORT)]\n .filter(([, , index]) => module.test(strings[Number(index)]))\n .map(\n ([, namespace]) => `${escapeRegExp(namespace)}\\\\s*\\\\.\\\\s*${factory}`,\n ),\n ];\n return callees.some((callee) =>\n new RegExp(`(?<![\\\\w$.])${callee}\\\\s*(?:<[^;()]*>\\\\s*)?\\\\(`).test(code),\n );\n}\n\nfunction escapeRegExp(name: string): string {\n return name.replaceAll(\"$\", \"\\\\$\");\n}\n\nfunction packagePath(root: string, path: string): `./${string}` {\n return `./${relative(root, path).split(sep).join(\"/\")}`;\n}\n\nfunction realPathOrSelf(path: string): string {\n try {\n return realpathSync.native(path);\n } catch {\n return path;\n }\n}\n\n/** The suggested specifier is the folder's `index.ts` when it declares, else the first declaring file. */\nfunction modelUnit(\n packageRoot: string,\n packageRootIdentity: string,\n directory: Entry,\n): Unit | undefined {\n const declaring = sourceFilesUnder(\n directory,\n packageRootIdentity,\n new Set(),\n ).filter(({ real }) => declares(real));\n const index = join(directory.path, \"index.ts\");\n const suggested =\n declaring.find(({ path }) => path === index) ?? declaring.at(0);\n if (suggested === undefined) return undefined;\n return {\n kind: \"document-model\",\n unit: `${packagePath(packageRoot, directory.path)}/`,\n specifier: packagePath(packageRoot, suggested.path),\n declaring: declaring.map(({ real }) => real),\n };\n}\n\n/**\n * Each `<documentModelsDir>/<name>/` whose sources declare a code-first model\n * that no selected source's import reached. A selected source that did not\n * import reaches files no one can name, so the scan then reports nothing.\n */\nexport function findUnregisteredDefinitions(request: {\n readonly packageRoot: string;\n /** Absolute, and already checked to stay inside the package root. */\n readonly documentModelsDir: string;\n readonly sources: readonly DefinitionSource[];\n /** Absolute paths of every module the import of `specifier` evaluated, its own included. */\n readonly importedFiles: (specifier: string) => readonly string[];\n}): readonly UnregisteredDefinition[] {\n const { packageRoot, documentModelsDir, sources, importedFiles } = request;\n const imported = sources.map(({ specifier }) => importedFiles(specifier));\n if (imported.some((files) => files.length === 0)) return [];\n const reached = new Set(imported.flat().map(realPathOrSelf));\n const packageRootIdentity = realPathOrSelf(packageRoot);\n return packageEntries(documentModelsDir, packageRootIdentity)\n .flatMap((entry) =>\n entry.isDirectory\n ? (modelUnit(packageRoot, packageRootIdentity, entry) ?? [])\n : [],\n )\n .filter((unit) => !unit.declaring.some((file) => reached.has(file)))\n .map(({ kind, unit, specifier }) => ({ kind, unit, specifier }));\n}\n","import type {\n DefinitionDiagnostic,\n Sha256Digest,\n} from \"@powerhousedao/shared/document-model\";\nimport { realpathSync, statSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { adaptCodeFirstDocumentModelSource } from \"../adapters/code-first-document-model-source-adapter.js\";\nimport type {\n DefinitionProducer,\n ProducedDefinitions,\n} from \"../adapters/producer.js\";\nimport { compareArtifacts, sortedUniqueDiagnostics } from \"../report/status.js\";\nimport type { LoadedDefinitionProject } from \"../report/types.js\";\nimport type { DefinitionSourceLoader } from \"../definition-source-loader.js\";\nimport {\n isWithin,\n readConfigObject,\n realPathThroughExistingParent,\n} from \"../definition-source-resolution.js\";\nimport { toolingDiagnostics } from \"../diagnostic-codes.js\";\nimport { readStoredDocumentModels } from \"../schema-first/stored-models.js\";\nimport { findUnregisteredDefinitions } from \"./unregistered-definitions.js\";\n\n/**\n * @experimental A package's document models, loaded once and read by both\n * `ph model check` and `ph model inspect`. Experimental while code-first\n * projects are introduced.\n */\nexport type ProjectDefinitions = LoadedDefinitionProject & {\n /** Absolute. No report carries it. */\n readonly packageRoot: string;\n};\n\nconst DEFAULT_DOCUMENT_MODELS_DIR = \"./document-models\";\n\n/** Code-first sources are authored in normalized coordinates, so they need no relocation. */\nconst adaptSelectedModules: DefinitionProducer = ({ loaded }) => {\n const results = loaded.documentModels.map(({ value, source }) => {\n const result = adaptCodeFirstDocumentModelSource(value, source);\n return {\n artifacts: result.artifacts,\n diagnostics: result.diagnostics.map((diagnostic) =>\n diagnostic.source === undefined\n ? { ...diagnostic, source }\n : diagnostic,\n ),\n };\n });\n return {\n artifacts: results.flatMap(({ artifacts }) => artifacts),\n diagnostics: results.flatMap(({ diagnostics }) => diagnostics),\n relocations: new Map(),\n };\n};\n\n/** The readers a project loads with unless a caller passes its own; the one place an authoring mode is named. */\nexport const defaultDefinitionProducers: readonly DefinitionProducer[] =\n Object.freeze([adaptSelectedModules, readStoredDocumentModels]);\n\n/** A path that cannot be inspected is left to the readers, which report it. */\nfunction namesNonDirectory(path: string): boolean {\n try {\n return statSync(path, { throwIfNoEntry: false })?.isDirectory() === false;\n } catch {\n return false;\n }\n}\n\n/** The configured models directory, or why it cannot be scanned. */\nfunction documentModelsDirectory(\n packageRoot: string,\n configFile: string,\n): {\n readonly path?: string;\n readonly diagnostics: readonly DefinitionDiagnostic[];\n} {\n const config = readConfigObject(resolve(configFile));\n // The loader already reported an unreadable config.\n if (!config.ok) return { diagnostics: [] };\n const configured =\n config.value.documentModelsDir ?? DEFAULT_DOCUMENT_MODELS_DIR;\n if (typeof configured !== \"string\" || configured.trim() === \"\") {\n return {\n diagnostics: [\n toolingDiagnostics.create({\n code: \"PH-CONFIG-SOURCE-INVALID\",\n path: [\"documentModelsDir\"],\n message: \"documentModelsDir is not a directory path.\",\n expected: \"a package-relative path such as ./document-models\",\n received: JSON.stringify(configured),\n repair:\n \"Set documentModelsDir to a package-relative directory, or remove it to use ./document-models.\",\n }),\n ],\n };\n }\n const path = resolve(packageRoot, configured);\n let inside = isWithin(packageRoot, path);\n try {\n inside &&= isWithin(\n realpathSync.native(packageRoot),\n realPathThroughExistingParent(path),\n );\n } catch {\n inside = false;\n }\n if (!inside) {\n return {\n diagnostics: [\n toolingDiagnostics.create({\n code: \"PH-CONFIG-SOURCE-OUTSIDE-PACKAGE\",\n path: [\"documentModelsDir\"],\n message:\n \"documentModelsDir leaves the package root, so its models are not this package's.\",\n expected: \"a directory inside the package\",\n received: configured,\n repair: \"Point documentModelsDir at a directory inside the package.\",\n }),\n ],\n };\n }\n if (namesNonDirectory(path)) {\n return {\n diagnostics: [\n toolingDiagnostics.create({\n code: \"PH-CONFIG-SOURCE-INVALID\",\n path: [\"documentModelsDir\"],\n message: \"documentModelsDir names a file, not a directory.\",\n expected: \"a package-relative directory such as ./document-models\",\n received: configured,\n repair:\n \"Point documentModelsDir at the directory that holds the models, or remove it to use ./document-models.\",\n }),\n ],\n };\n }\n return { path, diagnostics: [] };\n}\n\n/** Tool and Node messages can quote the machine path a package lives at. */\nfunction packageRelative(\n diagnostics: readonly DefinitionDiagnostic[],\n packageRoot: string,\n): readonly DefinitionDiagnostic[] {\n let real = packageRoot;\n try {\n real = realpathSync.native(packageRoot);\n } catch {\n // An unreadable root keeps its spelled path only.\n }\n const roots = [...new Set([packageRoot, real])]\n .sort((left, right) => right.length - left.length)\n .flatMap((root) => [pathToFileURL(root).href, root]);\n const rewrite = (text: string) =>\n roots.reduce((result, root) => result.replaceAll(root, \".\"), text);\n return diagnostics.map((diagnostic) => ({\n ...diagnostic,\n message: rewrite(diagnostic.message),\n repair: rewrite(diagnostic.repair),\n ...(diagnostic.expected !== undefined && {\n expected: rewrite(diagnostic.expected),\n }),\n ...(diagnostic.received !== undefined && {\n received: rewrite(diagnostic.received),\n }),\n ...(diagnostic.related !== undefined && {\n related: diagnostic.related.map((location) => ({\n ...location,\n message: rewrite(location.message),\n })),\n }),\n }));\n}\n\n/**\n * @experimental Loads the selected code-first sources and the package's stored\n * schema-first models, and scans for code-first declarations no source\n * reaches. Artifacts and diagnostics are sorted and package relative.\n * `producers` replaces the default readers. `importedFiles` names the\n * absolute paths of every module the loader's import of a selected\n * specifier evaluated, so reach follows whatever the importer resolved.\n * Experimental while code-first projects are introduced.\n */\nexport async function loadProjectDefinitions(request: {\n readonly loader: DefinitionSourceLoader;\n readonly configFile: string;\n readonly packageRevision: Sha256Digest;\n readonly signal?: AbortSignal;\n readonly producers?: readonly DefinitionProducer[];\n readonly importedFiles: (specifier: string) => readonly string[];\n}): Promise<ProjectDefinitions> {\n const {\n loader,\n producers = defaultDefinitionProducers,\n importedFiles,\n ...load\n } = request;\n const loaded = await loader.normalizeDefinitionSources(load);\n request.signal?.throwIfAborted();\n const { packageRoot } = loaded;\n const directory = documentModelsDirectory(packageRoot, request.configFile);\n const modelsDir = directory.path;\n const input = {\n ...load,\n loader,\n packageRoot,\n loaded,\n ...(modelsDir !== undefined && { documentModelsDir: modelsDir }),\n };\n const produced: ProducedDefinitions[] = [];\n for (const producer of producers) produced.push(await producer(input));\n request.signal?.throwIfAborted();\n const selectionKnown = !loaded.diagnostics.some(\n ({ phase, severity }) => phase === \"configuration\" && severity === \"error\",\n );\n return {\n packageRoot,\n sourceSet: loaded.sourceSet,\n ...(loaded.status === \"skipped\" && { skipReason: loaded.skipReason }),\n artifacts: produced\n .flatMap(({ artifacts }) => artifacts)\n .sort(compareArtifacts),\n relocations: new Map(\n produced.flatMap(({ relocations }) => [...relocations]),\n ),\n diagnostics: sortedUniqueDiagnostics(\n packageRelative(\n [\n ...loaded.diagnostics,\n ...directory.diagnostics,\n ...produced.flatMap(({ diagnostics }) => diagnostics),\n ],\n packageRoot,\n ),\n ),\n unregistered:\n selectionKnown && modelsDir !== undefined\n ? findUnregisteredDefinitions({\n packageRoot,\n documentModelsDir: modelsDir,\n sources: loaded.sourceSet.sources,\n importedFiles,\n })\n : [],\n };\n}\n"],"mappings":";;;;;;;;;AAKA,SAAS,YAAY,OAAe,OAAuB;CACzD,QAAS,UAAU,QAAU,SAAU,KAAK,WAAa;AAC3D;AAEA,MAAM,mBAAmB,IAAI,YAAY;CACvC;CAAY;CAAY;CAAY;CAAY;CAAY;CAC5D;CAAY;CAAY;CAAY;CAAY;CAAY;CAC5D;CAAY;CAAY;CAAY;CAAY;CAAY;CAC5D;CAAY;CAAY;CAAY;CAAY;CAAY;CAC5D;CAAY;CAAY;CAAY;CAAY;CAAY;CAC5D;CAAY;CAAY;CAAY;CAAY;CAAY;CAC5D;CAAY;CAAY;CAAY;CAAY;CAAY;CAC5D;CAAY;CAAY;CAAY;CAAY;CAAY;CAC5D;CAAY;CAAY;CAAY;CAAY;CAAY;CAC5D;CAAY;CAAY;CAAY;CAAY;CAAY;CAC5D;CAAY;CAAY;CAAY;AACtC,CAAC;AAED,SAAgB,OAAO,OAA6B;CAClD,MAAM,QAAQ,IAAI,YAAY,CAAC,CAAC,OAAO,KAAK;CAC5C,MAAM,eAAe,KAAK,MAAM,MAAM,SAAS,KAAK,EAAE,IAAI;CAC1D,MAAM,QAAQ,IAAI,WAAW,YAAY;CACzC,MAAM,IAAI,KAAK;CACf,MAAM,MAAM,UAAU;CACtB,MAAM,OAAO,IAAI,SAAS,MAAM,MAAM;CACtC,MAAM,YAAY,OAAO,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