@forgeax/engine-pack 0.1.21 → 0.1.24
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +167 -48
- package/dist/__tests__/inventory-schema.test.d.ts +2 -0
- package/dist/__tests__/inventory-schema.test.d.ts.map +1 -0
- package/dist/__tests__/material-cook-receipt-layer-plan.unit.test.d.ts +2 -0
- package/dist/__tests__/material-cook-receipt-layer-plan.unit.test.d.ts.map +1 -0
- package/dist/__tests__/pack-authoring-gateway.unit.test.d.ts +2 -0
- package/dist/__tests__/pack-authoring-gateway.unit.test.d.ts.map +1 -0
- package/dist/__tests__/pack-authoring.unit.test.d.ts +2 -0
- package/dist/__tests__/pack-authoring.unit.test.d.ts.map +1 -0
- package/dist/__tests__/pack-scanner.unit.test.d.ts +2 -0
- package/dist/__tests__/pack-scanner.unit.test.d.ts.map +1 -0
- package/dist/__tests__/scanner-blacklist.test.d.ts +2 -0
- package/dist/__tests__/scanner-blacklist.test.d.ts.map +1 -0
- package/dist/build.d.ts +9 -4
- package/dist/build.d.ts.map +1 -1
- package/dist/build.mjs +3449 -897
- package/dist/build.mjs.map +1 -1
- package/dist/builtin.mjs +37 -4
- package/dist/builtin.mjs.map +1 -1
- package/dist/catalog-builder.d.ts.map +1 -1
- package/dist/cli-asset.d.ts.map +1 -1
- package/dist/cli-asset.mjs +1361 -845
- package/dist/cli-asset.mjs.map +1 -1
- package/dist/deriveAssetName.d.ts +11 -7
- package/dist/deriveAssetName.d.ts.map +1 -1
- package/dist/evidence/material-cook.d.ts +11 -0
- package/dist/evidence/material-cook.d.ts.map +1 -1
- package/dist/evidence/source-inventory.d.ts.map +1 -1
- package/dist/guid.d.ts +15 -0
- package/dist/guid.d.ts.map +1 -1
- package/dist/guid.mjs +53 -5
- package/dist/guid.mjs.map +1 -1
- package/dist/index.d.ts +4 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.mjs +1297 -562
- package/dist/index.mjs.map +1 -1
- package/dist/inventory/binding.d.ts +6 -0
- package/dist/inventory/binding.d.ts.map +1 -0
- package/dist/inventory/declaration.d.ts +24 -0
- package/dist/inventory/declaration.d.ts.map +1 -0
- package/dist/inventory/index.d.ts +3 -0
- package/dist/inventory/index.d.ts.map +1 -0
- package/dist/inventory/sync.d.ts +5 -0
- package/dist/inventory/sync.d.ts.map +1 -0
- package/dist/material-cook.d.ts +1 -1
- package/dist/material-cook.d.ts.map +1 -1
- package/dist/material-cook.mjs +50 -3
- package/dist/material-cook.mjs.map +1 -1
- package/dist/name.mjs +4 -7
- package/dist/name.mjs.map +1 -1
- package/dist/pack-authoring-node.d.ts +26 -0
- package/dist/pack-authoring-node.d.ts.map +1 -0
- package/dist/pack-authoring-node.mjs +11089 -0
- package/dist/pack-authoring-node.mjs.map +1 -0
- package/dist/pack-authoring.d.ts +230 -0
- package/dist/pack-authoring.d.ts.map +1 -0
- package/dist/pack-authoring.mjs +1137 -0
- package/dist/pack-authoring.mjs.map +1 -0
- package/dist/package-finalizer.d.ts +2 -20
- package/dist/package-finalizer.d.ts.map +1 -1
- package/dist/resolve-asset-source.d.ts +1 -3
- package/dist/resolve-asset-source.d.ts.map +1 -1
- package/dist/resolve-asset-source.mjs +6 -81
- package/dist/resolve-asset-source.mjs.map +1 -1
- package/dist/runtime.mjs +77 -7
- package/dist/runtime.mjs.map +1 -1
- package/dist/scanner.d.ts +18 -7
- package/dist/scanner.d.ts.map +1 -1
- package/dist/scanner.mjs +1164 -687
- package/dist/scanner.mjs.map +1 -1
- package/dist/schema-compiled.d.ts.map +1 -1
- package/dist/schema.mjs +79 -7
- package/dist/schema.mjs.map +1 -1
- package/dist/scriptable-pack-node.d.ts +7 -31
- package/dist/scriptable-pack-node.d.ts.map +1 -1
- package/dist/scriptable-pack-node.mjs +572 -1019
- package/dist/scriptable-pack-node.mjs.map +1 -1
- package/dist/scriptable-pack-worker.mjs +29 -11
- package/dist/scriptable-pack-worker.mjs.map +1 -1
- package/dist/scriptable-pack.d.ts +20 -532
- package/dist/scriptable-pack.d.ts.map +1 -1
- package/dist/scriptable-pack.mjs +1038 -527
- package/dist/scriptable-pack.mjs.map +1 -1
- package/package.json +2 -7
- package/schema/meta.schema.json +1 -1
- package/schema/pack.schema.json +76 -6
- package/src/__tests__/guid-collision.unit.test.ts +18 -9
- package/src/__tests__/inventory-schema.test.ts +109 -0
- package/src/__tests__/material-cook-receipt-layer-plan.unit.test.ts +16 -0
- package/src/__tests__/material-cook-schema.unit.test.ts +62 -0
- package/src/__tests__/pack-authoring-gateway.unit.test.ts +249 -0
- package/src/__tests__/pack-authoring.unit.test.ts +266 -0
- package/src/__tests__/pack-scanner.unit.test.ts +123 -0
- package/src/__tests__/pack.unit.test.ts +1 -238
- package/src/__tests__/package-finalizer.contract.test.ts +55 -0
- package/src/__tests__/resolve-asset-source.test.ts +15 -98
- package/src/__tests__/scanner-blacklist.test.ts +55 -0
- package/src/__tests__/scanner-inventory.contract.test.ts +11 -14
- package/src/__tests__/scanner-inventory.test.ts +23 -10
- package/src/__tests__/scriptable-pack-cli.integration.test.ts +4 -9
- package/src/__tests__/topology.unit.test.ts +23 -0
- package/src/build.ts +28 -18
- package/src/catalog-builder.ts +60 -33
- package/src/cli-asset.ts +68 -83
- package/src/deriveAssetName.ts +14 -13
- package/src/evidence/material-cook.ts +79 -3
- package/src/evidence/source-inventory.ts +34 -21
- package/src/guid.ts +65 -4
- package/src/index.ts +15 -11
- package/src/inventory/binding.ts +25 -0
- package/src/inventory/declaration.ts +168 -0
- package/src/inventory/index.ts +18 -0
- package/src/inventory/sync.ts +22 -0
- package/src/material-cook.ts +1 -0
- package/src/pack-authoring-node.ts +1966 -0
- package/src/pack-authoring.ts +1478 -0
- package/src/package-finalizer.ts +2 -42
- package/src/resolve-asset-source.ts +4 -76
- package/src/scanner.ts +236 -56
- package/src/schema/material-cook.schema.json +4 -1
- package/src/schema-compiled.ts +2 -0
- package/src/scriptable-pack-node.ts +108 -719
- package/src/scriptable-pack-worker.ts +48 -16
- package/src/scriptable-pack.ts +28 -939
- package/dist/.tsbuildinfo +0 -1
- package/dist/__tests__/load-asset-config.test.d.ts +0 -2
- package/dist/__tests__/load-asset-config.test.d.ts.map +0 -1
- package/dist/__tests__/scriptable-pack.test-d.d.ts +0 -2
- package/dist/__tests__/scriptable-pack.test-d.d.ts.map +0 -1
- package/dist/__tests__/scriptable-pack.unit.test.d.ts +0 -2
- package/dist/__tests__/scriptable-pack.unit.test.d.ts.map +0 -1
- package/dist/config.d.ts +0 -6
- package/dist/config.d.ts.map +0 -1
- package/dist/config.mjs +0 -29
- package/dist/config.mjs.map +0 -1
- package/src/__tests__/load-asset-config.test.ts +0 -121
- package/src/__tests__/scriptable-pack.test-d.ts +0 -131
- package/src/__tests__/scriptable-pack.unit.test.ts +0 -789
- package/src/config.ts +0 -36
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts","../src/guid.ts","../src/scriptable-pack.ts","../src/evidence/source-inventory.ts","../src/scriptable-pack-node.ts"],"names":["resolve","dirname","readFile","createHash","executor","err","ok","relative","sep","actual"],"mappings":";;;;;;;;;;;;;;AA2BO,IAAM,SAAA,GAAN,cAAwB,KAAA,CAAM;AAAA,EAC1B,IAAA;AAAA,EACA,QAAA;AAAA,EACA,IAAA;AAAA,EACA,MAAA;AAAA,EAET,YAAY,IAAA,EAKT;AACD,IAAA,KAAA,CAAM,CAAA,WAAA,EAAc,KAAK,IAAI,CAAA,YAAA,EAAe,KAAK,QAAQ,CAAA,QAAA,EAAW,IAAA,CAAK,IAAI,CAAA,CAAE,CAAA;AAC/E,IAAA,IAAA,CAAK,IAAA,GAAO,WAAA;AACZ,IAAA,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA;AACjB,IAAA,IAAA,CAAK,WAAW,IAAA,CAAK,QAAA;AACrB,IAAA,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA;AACjB,IAAA,IAAA,CAAK,SAAS,IAAA,CAAK,MAAA;AAAA,EACrB;AACF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scriptable-pack-node.mjs","sourcesContent":["// errors.ts — PackError class (feat-20260513-guid-asset-package-system w15)\n//\n// Four-field surface: .code / .expected / .hint / .detail\n// Structurally parallel to AssetError / RhiError / RemoteError\n// (charter proposition 5 consistent abstraction).\n//\n// .detail is narrowed per .code via PackErrorDetail discriminated union\n// (requirements §6.2 AC-07; plan-strategy §D-5).\n\nimport type { PackErrorCode, PackErrorDetail } from '@forgeax/engine-types';\n\n/**\n * Structured error for the engine-pack disk scanner fail-fast chain.\n *\n * AI users consume via exhaustive switch on .code — no default case needed:\n * ```ts\n * switch (err.code) {\n * case 'pack-guid-collision':\n * console.error(err.detail.paths);\n * break;\n * case 'pack-cyclic-reference':\n * console.error(err.detail.cycle);\n * break;\n * // ...all 8 cases\n * }\n * ```\n */\nexport class PackError extends Error {\n readonly code: PackErrorCode;\n readonly expected: string;\n readonly hint: string;\n readonly detail: PackErrorDetail;\n\n constructor(args: {\n code: PackErrorCode;\n expected: string;\n hint: string;\n detail: PackErrorDetail;\n }) {\n super(`[PackError ${args.code}] expected: ${args.expected}; hint: ${args.hint}`);\n this.name = 'PackError';\n this.code = args.code;\n this.expected = args.expected;\n this.hint = args.hint;\n this.detail = args.detail;\n }\n}\n","import { uuidv7obj } from 'uuidv7';\nimport { PackError } from './errors.js';\n\n/**\n * 16-byte UUID branded ABI. Prevents assignment from plain Uint8Array or string.\n * Brand field mirrors the declaration in @forgeax/engine-types for cross-package\n * structural compatibility (both use __guidBrand: 'AssetGuid').\n */\nexport type AssetGuid = Uint8Array & { readonly __guidBrand: 'AssetGuid' };\n\n/** Minimal Result alias for this module (structurally compatible with ScanResult). */\nexport type GuidResult<T, E> =\n | { readonly ok: true; readonly value: T }\n | { readonly ok: false; readonly error: E };\n\nfunction brand(bytes: Uint8Array): AssetGuid {\n return bytes as AssetGuid;\n}\n\nconst HEX_BYTE = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n\nfunction bytesToDashForm(bytes: Uint8Array): string {\n const h = HEX_BYTE;\n // biome-ignore lint/style/noNonNullAssertion: length guaranteed 16\n return `${h[bytes[0]!]}${h[bytes[1]!]}${h[bytes[2]!]}${h[bytes[3]!]}-${h[bytes[4]!]}${h[bytes[5]!]}-${h[bytes[6]!]}${h[bytes[7]!]}-${h[bytes[8]!]}${h[bytes[9]!]}-${h[bytes[10]!]}${h[bytes[11]!]}${h[bytes[12]!]}${h[bytes[13]!]}${h[bytes[14]!]}${h[bytes[15]!]}`;\n}\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nexport function isValidAssetGuidString(value: unknown): value is string {\n return typeof value === 'string' && UUID_RE.test(value);\n}\n\nfunction dashFormToBytes(dashForm: string): Uint8Array {\n const hex = dashForm.replace(/-/g, '');\n const bytes = new Uint8Array(16);\n for (let i = 0; i < 16; i++) {\n bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);\n }\n return bytes;\n}\n\n/**\n * Utilities for the AssetGuid branded 16-byte UUID type.\n * Declare the type via `import type { AssetGuid } from '@forgeax/engine-pack/guid'`\n * or `import type { AssetGuid } from '@forgeax/engine-types'`.\n */\nexport const AssetGuid = {\n /**\n * Parse a 36-char RFC 4122 dash-form UUID string into an AssetGuid.\n * Returns Ok(AssetGuid) on success or Err(PackError) with code 'pack-guid-malformed' on failure.\n * Never throws for expected failures (requirements §4.2 / §14 / charter proposition 4).\n */\n parse(dashForm: string): GuidResult<AssetGuid, PackError> {\n if (!isValidAssetGuidString(dashForm)) {\n return {\n ok: false,\n error: new PackError({\n code: 'pack-guid-malformed',\n expected: '36-char RFC 4122 dash-form UUID',\n hint: 'use AssetGuid.random() or a UUIDv7 generator; all GUID fields must be 36-char RFC 4122 dash-form',\n detail: {\n raw: dashForm,\n reason: 'expected 36-char RFC 4122 dash-form UUID',\n },\n }),\n };\n }\n return { ok: true, value: brand(dashFormToBytes(dashForm)) };\n },\n\n /**\n * Format an AssetGuid as a 36-char RFC 4122 lowercase dash-form string.\n */\n format(guid: AssetGuid): string {\n return bytesToDashForm(guid);\n },\n\n /**\n * Test byte-by-byte equality between two AssetGuids.\n */\n equals(a: AssetGuid, b: AssetGuid): boolean {\n for (let i = 0; i < 16; i++) {\n if (a[i] !== b[i]) return false;\n }\n return true;\n },\n\n /**\n * Mint a new time-ordered UUIDv7 as an AssetGuid.\n * Works in both Node.js and browser environments.\n */\n random(): AssetGuid {\n const uuid = uuidv7obj();\n const bytes = new Uint8Array(16);\n bytes.set(uuid.bytes);\n return brand(bytes);\n },\n} as const;\n","import type { Asset, AssetGuid, AssetPublicationEnvelope, Result } from '@forgeax/engine-types';\nimport { err, ok } from '@forgeax/engine-types';\nimport { AssetGuid as AssetGuidCodec } from './guid.js';\n\n/** Closed ordinary kind vocabulary shared by authoring, producers, and loaders. */\nexport type ScriptablePackAssetKind = Asset['kind'];\n\n/** Complete ordinary Asset kind vocabulary exposed by ScriptablePack discovery. */\nexport const SCRIPTABLE_PACK_ASSET_KINDS = [\n 'mesh',\n 'material',\n 'scene',\n 'texture',\n 'equirect',\n 'sampler',\n 'font',\n 'render-pipeline',\n 'tileset',\n 'video',\n 'skeleton',\n 'skin',\n 'animation-clip',\n 'animation-graph',\n 'audio',\n 'particle-effect',\n] as const satisfies readonly ScriptablePackAssetKind[];\n\n/** Machine-readable producer/loader floor owned by engine-pack. */\nexport const SCRIPTABLE_PACK_CAPABILITY_MANIFEST = {\n assetKinds: SCRIPTABLE_PACK_ASSET_KINDS,\n durablePayload: true,\n refs: true,\n artifacts: true,\n hostCapabilities: ['audio-install', 'video-play', 'particle-execute'] as const,\n} as const;\n\nexport function isScriptablePackAssetKind(value: string): value is ScriptablePackAssetKind {\n return (SCRIPTABLE_PACK_ASSET_KINDS as readonly string[]).includes(value);\n}\n\nexport interface ScriptablePackAssetDeclaration<\n TKind extends ScriptablePackAssetKind = ScriptablePackAssetKind,\n> {\n readonly guid: AssetGuid;\n readonly kind: TKind;\n readonly name?: string;\n}\n\nexport type ScriptablePackAssetDeclarations = Readonly<\n Record<string, ScriptablePackAssetDeclaration>\n>;\n\nexport type ScriptablePackExternalAssets = Readonly<Record<string, AssetGuid>>;\n\n/**\n * Component-shaped input accepted by a ScriptablePack scene declaration.\n * Engine component tokens satisfy this shape; plain `{ type }` rows keep the\n * Pack contract independent of ECS and survive the isolated module worker.\n */\nexport interface ScriptablePackSceneComponentInput {\n readonly name: string;\n readonly fields: Readonly<Record<string, string | { readonly type: string }>>;\n}\n\n/** Neutral scene schema projection owned by the Pack definition. */\nexport interface ScriptablePackSceneComponent {\n readonly name: string;\n readonly fields: Readonly<Record<string, string>>;\n}\n\nfunction sceneComponentFieldType(value: unknown): string | undefined {\n if (typeof value === 'string') return value;\n if (isRecord(value) && typeof value.type === 'string') return value.type;\n return undefined;\n}\n\n/** Derive the frozen, ECS-neutral schema used by scene output producers. */\nexport function projectScriptablePackSceneComponents(\n components: readonly ScriptablePackSceneComponentInput[] | undefined,\n): readonly ScriptablePackSceneComponent[] {\n return (components ?? []).map((component) => ({\n name: component.name,\n fields: Object.fromEntries(\n Object.entries(component.fields).map(([fieldName, field]) => [\n fieldName,\n sceneComponentFieldType(field) as string,\n ]),\n ),\n }));\n}\n\n/** Pack-facing name for the shared Engine publication envelope. */\nexport type ScriptablePackPublicationEnvelope = AssetPublicationEnvelope;\n\n/** Structured domain failure permitted to cross the isolated build-time AssetReader seam. */\nexport interface ScriptablePackErrorProvenance {\n /** Published source generation observed by the reader, when available. */\n readonly generation?: number;\n /** Stable producer identity for the failed output, when available. */\n readonly sourceKey?: string;\n /** GUID associated with the failed read or output, when available. */\n readonly guid?: string;\n}\n\nexport interface ScriptablePackReadError {\n readonly code: string;\n readonly expected: string;\n readonly hint: string;\n readonly detail?: unknown;\n readonly provenance?: ScriptablePackErrorProvenance;\n}\n\nexport type ScriptablePackAssetFor<TDescriptor extends ScriptablePackAssetDeclaration> =\n TDescriptor extends { readonly kind: infer TKind extends ScriptablePackAssetKind }\n ? Extract<Asset, { readonly kind: TKind }>\n : never;\n\nexport type ScriptablePackOutputs<TAssets extends ScriptablePackAssetDeclarations> = {\n readonly [TKey in keyof TAssets]: TAssets[TKey] extends ScriptablePackAssetDeclaration\n ? ScriptablePackAssetFor<TAssets[TKey]>\n : never;\n};\n\nexport interface AssetReader {\n /** Load a declared GUID as a durable payload; this never mints a World handle. */\n readByGuid<TAsset extends Asset = Asset>(\n guid: AssetGuid,\n ): Promise<Result<TAsset, ScriptablePackReadError>>;\n}\n\nexport type ScriptablePackBuildResult<\n TAssets extends ScriptablePackAssetDeclarations,\n TError,\n> = Result<ScriptablePackOutputs<TAssets>, TError>;\n\nexport interface ScriptablePackDefinition<\n TAssets extends ScriptablePackAssetDeclarations = ScriptablePackAssetDeclarations,\n TExternal extends ScriptablePackExternalAssets = ScriptablePackExternalAssets,\n TError = ScriptablePackReadError,\n> {\n readonly schemaVersion: '1.0.0';\n readonly packageId: AssetGuid;\n readonly name?: string;\n readonly assets: TAssets;\n /** Component tokens/schema rows used by scene ref externalization. */\n readonly sceneComponents?: readonly ScriptablePackSceneComponentInput[];\n readonly externalAssets: TExternal;\n readonly build: (\n assetReader: AssetReader,\n ) =>\n | ScriptablePackBuildResult<TAssets, TError>\n | Promise<ScriptablePackBuildResult<TAssets, TError>>;\n}\n\nexport interface ScriptablePackSourceClosureEntry {\n readonly path: string;\n readonly digest: string;\n}\n\nexport interface ScriptablePackMetaJson {\n readonly schemaVersion: '1.0.0';\n readonly kind: 'external-asset-package';\n readonly packageId: string;\n readonly name?: string;\n readonly importer: 'pack-ts';\n readonly source: string;\n readonly importSettings: {\n readonly contractVersion: '1.0.0';\n readonly externalAssets: readonly {\n readonly alias: string;\n readonly guid: string;\n }[];\n };\n readonly subAssets: readonly {\n readonly guid: string;\n readonly sourceIndex: number;\n readonly sourceKey: string;\n readonly kind: ScriptablePackAssetKind;\n readonly name?: string;\n }[];\n}\n\nexport interface ScriptablePackOperationEnvelope {\n readonly requestId: string;\n readonly expectedRevision?: string;\n}\n\nexport type ScriptablePackGatewayOperation =\n | (ScriptablePackOperationEnvelope & {\n readonly kind: 'preflight';\n readonly sourcePath: string;\n })\n | (ScriptablePackOperationEnvelope & {\n readonly kind: 'create-scriptable-pack';\n readonly sourcePath: string;\n readonly name?: string;\n readonly initialOutput: {\n readonly sourceKey: string;\n readonly kind: ScriptablePackAssetKind;\n readonly name?: string;\n };\n })\n | (ScriptablePackOperationEnvelope & {\n readonly kind: 'add-output';\n readonly sourcePath: string;\n readonly sourceKey: string;\n readonly assetKind: ScriptablePackAssetKind;\n readonly name?: string;\n })\n | (ScriptablePackOperationEnvelope & {\n readonly kind: 'add-external-asset';\n readonly sourcePath: string;\n readonly alias: string;\n readonly guid: AssetGuid;\n })\n | (ScriptablePackOperationEnvelope & {\n readonly kind: 'rename-display';\n readonly sourcePath: string;\n readonly target:\n | { readonly kind: 'package' }\n | { readonly kind: 'output'; readonly sourceKey: string };\n readonly name: string;\n })\n | (ScriptablePackOperationEnvelope & {\n readonly kind: 'remove-output';\n readonly sourcePath: string;\n readonly sourceKey: string;\n /** Exact incoming reference identities acknowledged by the caller. */\n readonly confirmIncomingRefs?: readonly string[];\n })\n | (ScriptablePackOperationEnvelope & {\n readonly kind: 'clone-scriptable-pack';\n readonly sourcePath: string;\n readonly targetPath: string;\n })\n | (ScriptablePackOperationEnvelope & {\n readonly kind: 'inspect-meta';\n readonly sourcePath: string;\n })\n | (ScriptablePackOperationEnvelope & {\n readonly kind: 'rebuild' | 'cold-cook';\n readonly sourcePath: string;\n });\n\nexport interface ScriptablePackMutationCapabilities {\n readonly inspect: true;\n readonly rebuild: true;\n readonly coldCook: true;\n readonly create?: true;\n readonly addOutput?: true;\n readonly addExternalAsset?: true;\n readonly renameDisplay?: true;\n readonly removeOutput?: true;\n readonly clone?: true;\n readonly reason?: string;\n}\n\nexport interface ScriptablePackPreflight {\n readonly sourcePath: string;\n readonly revision: string;\n readonly meta: ScriptablePackMetaJson;\n readonly capabilities: ScriptablePackMutationCapabilities;\n readonly incomingRefs: readonly string[];\n}\n\nexport interface ScriptablePackGatewayMutation {\n readonly sourcePath: string;\n readonly revision: string;\n readonly meta: ScriptablePackMetaJson;\n}\n\nexport interface ScriptablePackAuthoringGateway {\n execute(\n operation: ScriptablePackGatewayOperation,\n ): Promise<Result<ScriptablePackGatewayMutation | ScriptablePackPreflight, ScriptablePackError>>;\n}\n\nexport type ScriptablePackAuthoringMutation =\n | (ScriptablePackOperationEnvelope & {\n readonly kind: 'create-scriptable-pack';\n readonly sourcePath: string;\n readonly packageId: AssetGuid;\n readonly name?: string;\n readonly initialOutput: {\n readonly sourceKey: string;\n readonly kind: ScriptablePackAssetKind;\n readonly guid: AssetGuid;\n readonly name?: string;\n };\n })\n | (ScriptablePackOperationEnvelope & {\n readonly kind: 'add-output';\n readonly sourcePath: string;\n readonly sourceKey: string;\n readonly assetKind: ScriptablePackAssetKind;\n readonly guid: AssetGuid;\n readonly name?: string;\n })\n | Extract<\n ScriptablePackGatewayOperation,\n { readonly kind: 'add-external-asset' | 'rename-display' | 'remove-output' }\n >\n | (ScriptablePackOperationEnvelope & {\n readonly kind: 'clone-scriptable-pack';\n readonly sourcePath: string;\n readonly targetPath: string;\n readonly packageId: AssetGuid;\n readonly outputGuids: Readonly<Record<string, AssetGuid>>;\n });\n\nexport interface ScriptablePackAuthoringPort {\n preflight(\n sourcePath: string,\n ): Promise<Result<Omit<ScriptablePackPreflight, 'sourcePath'>, ScriptablePackError>>;\n mutate(\n operation: ScriptablePackAuthoringMutation,\n ): Promise<\n Result<{ readonly sourcePath: string; readonly revision: string }, ScriptablePackError>\n >;\n inspect(\n sourcePath: string,\n ): Promise<\n Result<\n { readonly revision: string; readonly meta: ScriptablePackMetaJson },\n ScriptablePackError\n >\n >;\n rebuild(\n sourcePath: string,\n mode: 'rebuild' | 'cold-cook',\n ): Promise<\n Result<\n { readonly revision: string; readonly meta: ScriptablePackMetaJson },\n ScriptablePackError\n >\n >;\n}\n\n/** Keep GUID allocation and multi-identity operations in one auditable gateway transaction. */\nexport function createScriptablePackAuthoringGateway(\n port: ScriptablePackAuthoringPort,\n allocateGuid: () => AssetGuid = AssetGuidCodec.random,\n): ScriptablePackAuthoringGateway {\n const requests = new Map<\n string,\n {\n readonly fingerprint: string;\n readonly result: Promise<\n Result<ScriptablePackGatewayMutation | ScriptablePackPreflight, ScriptablePackError>\n >;\n }\n >();\n\n async function mutationResult(\n result: Awaited<ReturnType<ScriptablePackAuthoringPort['mutate']>>,\n ): Promise<Result<ScriptablePackGatewayMutation, ScriptablePackError>> {\n if (!result.ok) return result;\n const inspected = await port.inspect(result.value.sourcePath);\n if (!inspected.ok) return inspected;\n return ok({\n sourcePath: result.value.sourcePath,\n revision: inspected.value.revision,\n meta: inspected.value.meta,\n });\n }\n\n async function dispatch(\n operation: ScriptablePackGatewayOperation,\n ): Promise<Result<ScriptablePackGatewayMutation | ScriptablePackPreflight, ScriptablePackError>> {\n switch (operation.kind) {\n case 'preflight': {\n const preflight = await port.preflight(operation.sourcePath);\n return preflight.ok\n ? ok({ sourcePath: operation.sourcePath, ...preflight.value })\n : preflight;\n }\n case 'inspect-meta': {\n const inspected = await port.inspect(operation.sourcePath);\n return inspected.ok\n ? ok({ sourcePath: operation.sourcePath, ...inspected.value })\n : inspected;\n }\n case 'rebuild':\n case 'cold-cook': {\n const preflight = await port.preflight(operation.sourcePath);\n if (!preflight.ok) return preflight;\n if (\n operation.expectedRevision !== undefined &&\n operation.expectedRevision !== preflight.value.revision\n ) {\n return err({\n code: 'pack-source-revision-conflict',\n expected: operation.expectedRevision,\n actual: preflight.value.revision,\n hint: 'inspect the current source revision, then retry the build with a new requestId',\n retryable: true,\n recoveryActions: ['asset.preflight', 'mint-request-id'],\n detail: { requestId: operation.requestId, sourcePath: operation.sourcePath },\n });\n }\n const rebuilt = await port.rebuild(operation.sourcePath, operation.kind);\n return rebuilt.ok ? ok({ sourcePath: operation.sourcePath, ...rebuilt.value }) : rebuilt;\n }\n case 'create-scriptable-pack':\n return mutationResult(\n await port.mutate({\n ...operation,\n packageId: allocateGuid(),\n initialOutput: { ...operation.initialOutput, guid: allocateGuid() },\n }),\n );\n case 'add-output':\n return mutationResult(await port.mutate({ ...operation, guid: allocateGuid() }));\n case 'clone-scriptable-pack': {\n const inspected = await port.inspect(operation.sourcePath);\n if (!inspected.ok) return inspected;\n const outputGuids = Object.fromEntries(\n inspected.value.meta.subAssets.map((asset) => [asset.sourceKey, allocateGuid()]),\n );\n return mutationResult(\n await port.mutate({\n ...operation,\n packageId: allocateGuid(),\n outputGuids,\n }),\n );\n }\n case 'add-external-asset':\n case 'rename-display':\n case 'remove-output':\n return mutationResult(await port.mutate(operation));\n }\n }\n\n return {\n execute(operation) {\n if (operation.requestId.trim().length === 0) {\n return Promise.resolve(\n err({\n code: 'pack-source-operation-committed',\n expected: 'a non-empty caller-minted requestId',\n actual: operation.requestId,\n hint: 'mint a new requestId and retry the operation once',\n retryable: true,\n recoveryActions: ['mint-request-id'],\n detail: { requestId: operation.requestId, sourcePath: operation.sourcePath },\n }),\n );\n }\n const fingerprint = JSON.stringify(operation);\n const prior = requests.get(operation.requestId);\n if (prior !== undefined) {\n if (prior.fingerprint === fingerprint) return prior.result;\n return Promise.resolve(\n err({\n code: 'pack-source-operation-committed',\n expected: 'one immutable operation per requestId',\n actual: operation.kind,\n hint: 'read the original operation result or mint a new requestId',\n retryable: false,\n recoveryActions: ['read-operation-run', 'mint-request-id'],\n detail: { requestId: operation.requestId, sourcePath: operation.sourcePath },\n }),\n );\n }\n const result = dispatch(operation);\n requests.set(operation.requestId, { fingerprint, result });\n return result;\n },\n };\n}\n\nconst SCRIPTABLE_PACK_REQUEST_ID_SCHEMA = {\n type: 'string',\n minLength: 1,\n maxLength: 128,\n pattern: '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$',\n description: 'Caller-minted identity for one idempotent ScriptablePack operation.',\n} as const;\nconst SCRIPTABLE_PACK_SOURCE_PATH_SCHEMA = {\n type: 'string',\n minLength: 8,\n pattern: '^[^/].*\\\\.pack\\\\.ts$',\n description: 'Game-root-relative ScriptablePack source path.',\n} as const;\nconst SCRIPTABLE_PACK_OWNER_GUID_SCHEMA = {\n type: 'string',\n format: 'uuid',\n description: 'Catalog GUID used to resolve the producer-owned source subject.',\n} as const;\nconst SCRIPTABLE_PACK_REVISION_SCHEMA = {\n type: 'string',\n minLength: 64,\n maxLength: 64,\n pattern: '^[a-f0-9]{64}$',\n description: 'SHA-256 source revision returned by preflight.',\n} as const;\nconst SCRIPTABLE_PACK_SOURCE_KEY_SCHEMA = { type: 'string', minLength: 1 } as const;\nconst SCRIPTABLE_PACK_ASSET_KIND_SCHEMA = {\n enum: SCRIPTABLE_PACK_ASSET_KINDS,\n description: 'Ordinary Asset kind supported by the ScriptablePack producer/loader matrix.',\n} as const;\nconst SCRIPTABLE_PACK_NAME_SCHEMA = { type: 'string', minLength: 1 } as const;\n\nfunction scriptablePackArgsSchema(\n properties: Readonly<Record<string, unknown>>,\n required: readonly string[],\n options: { readonly subject?: boolean; readonly guidSubject?: boolean } = {},\n) {\n const subjectRequired = ['requestId', ...required];\n return {\n type: 'object',\n properties: {\n sourcePath: SCRIPTABLE_PACK_SOURCE_PATH_SCHEMA,\n ownerGuid: SCRIPTABLE_PACK_OWNER_GUID_SCHEMA,\n requestId: SCRIPTABLE_PACK_REQUEST_ID_SCHEMA,\n ...properties,\n },\n required: subjectRequired,\n ...(options.subject === false\n ? {}\n : {\n anyOf: [\n { required: [...subjectRequired, 'sourcePath'] },\n { required: [...subjectRequired, 'ownerGuid'] },\n ...(options.guidSubject === false ? [] : [{ required: [...subjectRequired, 'guid'] }]),\n ],\n }),\n additionalProperties: false,\n } as const;\n}\n\nexport const SOURCE_AUTHORING_OPERATION_DESCRIPTORS = [\n {\n id: 'asset-source.create',\n kind: 'create',\n domain: 'session',\n title: 'Create Asset Source',\n argsSchema: scriptablePackArgsSchema(\n {\n name: SCRIPTABLE_PACK_NAME_SCHEMA,\n initialOutput: {\n type: 'object',\n properties: {\n sourceKey: SCRIPTABLE_PACK_SOURCE_KEY_SCHEMA,\n kind: SCRIPTABLE_PACK_ASSET_KIND_SCHEMA,\n name: SCRIPTABLE_PACK_NAME_SCHEMA,\n },\n required: ['sourceKey', 'kind'],\n additionalProperties: false,\n },\n },\n ['sourcePath', 'initialOutput'],\n { subject: false },\n ),\n },\n {\n id: 'asset-source.add-output',\n kind: 'add-output',\n domain: 'session',\n title: 'Add Asset Source Output',\n argsSchema: scriptablePackArgsSchema(\n {\n sourceKey: SCRIPTABLE_PACK_SOURCE_KEY_SCHEMA,\n assetKind: SCRIPTABLE_PACK_ASSET_KIND_SCHEMA,\n name: SCRIPTABLE_PACK_NAME_SCHEMA,\n expectedRevision: SCRIPTABLE_PACK_REVISION_SCHEMA,\n },\n ['sourceKey', 'assetKind', 'expectedRevision'],\n ),\n },\n {\n id: 'asset-source.add-external-asset',\n kind: 'add-external-asset',\n domain: 'session',\n title: 'Add Asset Source External Asset',\n argsSchema: scriptablePackArgsSchema(\n {\n alias: SCRIPTABLE_PACK_SOURCE_KEY_SCHEMA,\n guid: { type: 'string', format: 'uuid' },\n expectedRevision: SCRIPTABLE_PACK_REVISION_SCHEMA,\n },\n ['alias', 'guid', 'expectedRevision'],\n { guidSubject: false },\n ),\n },\n {\n id: 'asset-source.rename',\n kind: 'rename',\n domain: 'session',\n title: 'Rename Asset Source Display Name',\n argsSchema: scriptablePackArgsSchema(\n {\n target: {\n oneOf: [\n {\n type: 'object',\n properties: { kind: { const: 'package' } },\n required: ['kind'],\n additionalProperties: false,\n },\n {\n type: 'object',\n properties: {\n kind: { const: 'output' },\n sourceKey: SCRIPTABLE_PACK_SOURCE_KEY_SCHEMA,\n },\n required: ['kind', 'sourceKey'],\n additionalProperties: false,\n },\n ],\n },\n name: SCRIPTABLE_PACK_NAME_SCHEMA,\n expectedRevision: SCRIPTABLE_PACK_REVISION_SCHEMA,\n },\n ['target', 'name', 'expectedRevision'],\n ),\n },\n {\n id: 'asset-source.remove-output',\n kind: 'remove-output',\n domain: 'session',\n title: 'Remove Asset Source Output',\n destructive: true,\n argsSchema: scriptablePackArgsSchema(\n {\n sourceKey: SCRIPTABLE_PACK_SOURCE_KEY_SCHEMA,\n confirmIncomingRefs: { type: 'array', items: { type: 'string' } },\n expectedRevision: SCRIPTABLE_PACK_REVISION_SCHEMA,\n },\n ['sourceKey', 'expectedRevision'],\n ),\n },\n {\n id: 'asset-source.clone',\n kind: 'clone',\n domain: 'session',\n title: 'Clone Asset Source',\n argsSchema: scriptablePackArgsSchema(\n {\n targetPath: SCRIPTABLE_PACK_SOURCE_PATH_SCHEMA,\n expectedRevision: SCRIPTABLE_PACK_REVISION_SCHEMA,\n },\n ['targetPath', 'expectedRevision'],\n ),\n },\n {\n id: 'asset-source.rebuild',\n kind: 'rebuild',\n domain: 'session',\n title: 'Rebuild Asset Source',\n argsSchema: scriptablePackArgsSchema({ expectedRevision: SCRIPTABLE_PACK_REVISION_SCHEMA }, [\n 'expectedRevision',\n ]),\n },\n {\n id: 'asset-source.cold-cook',\n kind: 'cold-cook',\n domain: 'session',\n title: 'Cold Cook Asset Source',\n argsSchema: scriptablePackArgsSchema({ expectedRevision: SCRIPTABLE_PACK_REVISION_SCHEMA }, [\n 'expectedRevision',\n ]),\n },\n] as const;\n\nexport type ScriptablePackError =\n | {\n readonly code: 'pack-source-load-failed';\n readonly expected: string;\n readonly hint: string;\n readonly detail: {\n readonly sourcePath: string;\n readonly reason: 'module-load' | 'timeout' | 'source-changed';\n readonly phase: 'module-load' | 'build';\n readonly diagnostic: string;\n readonly timeoutMs?: number;\n };\n }\n | {\n readonly code: 'pack-source-definition-invalid';\n readonly expected: string;\n readonly hint: string;\n readonly detail: {\n readonly sourcePath?: string;\n readonly propertyPath: string;\n readonly actual: string;\n };\n }\n | {\n readonly code: 'pack-source-output-invalid';\n readonly expected: string;\n readonly hint: string;\n readonly detail: {\n readonly missingGuids: readonly string[];\n readonly unexpectedSourceKeys: readonly string[];\n readonly kindMismatches: readonly {\n readonly sourceKey: string;\n readonly expected: string;\n readonly actual: string;\n }[];\n };\n }\n | {\n readonly code: 'pack-source-external-closure-mismatch';\n readonly expected: string;\n readonly hint: string;\n readonly detail: {\n readonly undeclaredReferencedGuids: readonly string[];\n readonly undeclaredReadGuids: readonly string[];\n readonly unusedDeclaredGuids: readonly string[];\n };\n }\n | {\n readonly code:\n | 'pack-source-path-invalid'\n | 'pack-source-revision-conflict'\n | 'pack-source-mutation-unsupported'\n | 'pack-source-reference-conflict'\n | 'pack-source-write-failed'\n | 'pack-source-build-cycle'\n | 'pack-source-publication-timeout'\n | 'pack-source-operation-committed';\n readonly expected: string;\n readonly actual?: string;\n readonly hint: string;\n readonly retryable: boolean;\n readonly recoveryActions: readonly string[];\n readonly detail: {\n readonly requestId?: string;\n readonly sourcePath?: string;\n readonly packageId?: string;\n readonly sourceKey?: string;\n readonly incomingRefs?: readonly string[];\n };\n };\n\nfunction actual(value: unknown): string {\n if (value === null) return 'null';\n if (Array.isArray(value)) return 'array';\n if (ArrayBuffer.isView(value)) return value.constructor.name;\n return typeof value;\n}\n\nfunction invalid(\n propertyPath: string,\n expected: string,\n value: unknown,\n sourcePath?: string,\n): Result<never, ScriptablePackError> {\n return err({\n code: 'pack-source-definition-invalid',\n expected,\n hint: 'repair the default exported ScriptablePack definition, then inspect Meta again',\n detail: {\n ...(sourcePath === undefined ? {} : { sourcePath }),\n propertyPath,\n actual: actual(value),\n },\n });\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction isAssetGuid(value: unknown): value is AssetGuid {\n return value instanceof Uint8Array && value.byteLength === 16;\n}\n\nfunction guidKey(guid: AssetGuid): string {\n return AssetGuidCodec.format(guid);\n}\n\nfunction freezeDefinition(\n definition: ScriptablePackDefinition,\n): Readonly<ScriptablePackDefinition> {\n const assets = Object.fromEntries(\n Object.entries(definition.assets).map(([sourceKey, descriptor]) => [\n sourceKey,\n Object.freeze({ ...descriptor, guid: descriptor.guid.slice() as AssetGuid }),\n ]),\n );\n const externalAssets = Object.fromEntries(\n Object.entries(definition.externalAssets).map(([alias, guid]) => [\n alias,\n guid.slice() as AssetGuid,\n ]),\n );\n const sceneComponents =\n definition.sceneComponents === undefined\n ? undefined\n : Object.freeze(\n projectScriptablePackSceneComponents(definition.sceneComponents).map((component) =>\n Object.freeze({\n ...component,\n fields: Object.freeze({ ...component.fields }),\n }),\n ),\n );\n return Object.freeze({\n ...definition,\n packageId: definition.packageId.slice() as AssetGuid,\n assets: Object.freeze(assets),\n externalAssets: Object.freeze(externalAssets),\n ...(sceneComponents === undefined ? {} : { sceneComponents }),\n });\n}\n\nexport function validateScriptablePackDefinition(\n value: unknown,\n sourcePath?: string,\n): Result<Readonly<ScriptablePackDefinition>, ScriptablePackError> {\n if (!isRecord(value))\n return invalid('$', 'a ScriptablePack definition object', value, sourcePath);\n if (value.schemaVersion !== '1.0.0') {\n return invalid('$.schemaVersion', \"the literal '1.0.0'\", value.schemaVersion, sourcePath);\n }\n if (!isAssetGuid(value.packageId)) {\n return invalid('$.packageId', 'a 16-byte AssetGuid', value.packageId, sourcePath);\n }\n if (value.name !== undefined && typeof value.name !== 'string') {\n return invalid('$.name', 'a string when present', value.name, sourcePath);\n }\n if (!isRecord(value.assets) || Object.keys(value.assets).length === 0) {\n return invalid(\n '$.assets',\n 'a non-empty sourceKey to descriptor object',\n value.assets,\n sourcePath,\n );\n }\n if (!isRecord(value.externalAssets)) {\n return invalid(\n '$.externalAssets',\n 'an alias to AssetGuid object',\n value.externalAssets,\n sourcePath,\n );\n }\n if (value.sceneComponents !== undefined) {\n if (!Array.isArray(value.sceneComponents)) {\n return invalid(\n '$.sceneComponents',\n 'an array of component tokens or neutral schema rows when present',\n value.sceneComponents,\n sourcePath,\n );\n }\n const componentNames = new Set<string>();\n for (const [componentIndex, component] of value.sceneComponents.entries()) {\n if (!isRecord(component)) {\n return invalid(\n `$.sceneComponents[${componentIndex}]`,\n 'a component token or neutral schema row',\n component,\n sourcePath,\n );\n }\n if (typeof component.name !== 'string' || component.name.trim().length === 0) {\n return invalid(\n `$.sceneComponents[${componentIndex}].name`,\n 'a non-empty component name',\n component.name,\n sourcePath,\n );\n }\n if (componentNames.has(component.name)) {\n return invalid(\n `$.sceneComponents[${componentIndex}].name`,\n 'component names to be unique within one ScriptablePack',\n component.name,\n sourcePath,\n );\n }\n componentNames.add(component.name);\n if (!isRecord(component.fields)) {\n return invalid(\n `$.sceneComponents[${componentIndex}].fields`,\n 'a field-name to schema-type object',\n component.fields,\n sourcePath,\n );\n }\n for (const [fieldName, field] of Object.entries(component.fields)) {\n const type = sceneComponentFieldType(field);\n if (fieldName.trim().length === 0 || type === undefined || type.trim().length === 0) {\n return invalid(\n `$.sceneComponents[${componentIndex}].fields`,\n 'field names with non-empty string schema types',\n field,\n sourcePath,\n );\n }\n }\n }\n }\n if (typeof value.build !== 'function') {\n return invalid('$.build', 'a build(assetReader) function', value.build, sourcePath);\n }\n\n const packageGuid = guidKey(value.packageId);\n const localGuids = new Set<string>();\n for (const [sourceKey, descriptor] of Object.entries(value.assets)) {\n if (sourceKey.trim().length === 0) {\n return invalid('$.assets', 'non-empty sourceKey object keys', sourceKey, sourcePath);\n }\n if (!isRecord(descriptor)) {\n return invalid(\n `$.assets[${JSON.stringify(sourceKey)}]`,\n 'an asset descriptor',\n descriptor,\n sourcePath,\n );\n }\n if (!isAssetGuid(descriptor.guid)) {\n return invalid(\n `$.assets[${JSON.stringify(sourceKey)}].guid`,\n 'a 16-byte AssetGuid',\n descriptor.guid,\n sourcePath,\n );\n }\n if (typeof descriptor.kind !== 'string' || !isScriptablePackAssetKind(descriptor.kind)) {\n return invalid(\n `$.assets[${JSON.stringify(sourceKey)}].kind`,\n 'one of SCRIPTABLE_PACK_ASSET_KINDS',\n descriptor.kind,\n sourcePath,\n );\n }\n if (descriptor.name !== undefined && typeof descriptor.name !== 'string') {\n return invalid(\n `$.assets[${JSON.stringify(sourceKey)}].name`,\n 'a string when present',\n descriptor.name,\n sourcePath,\n );\n }\n const guid = guidKey(descriptor.guid);\n if (guid === packageGuid || localGuids.has(guid)) {\n return invalid(\n `$.assets[${JSON.stringify(sourceKey)}].guid`,\n 'a GUID unique within the package and distinct from packageId',\n descriptor.guid,\n sourcePath,\n );\n }\n localGuids.add(guid);\n }\n\n const externalGuids = new Set<string>();\n for (const [alias, guidValue] of Object.entries(value.externalAssets)) {\n if (alias.trim().length === 0) {\n return invalid('$.externalAssets', 'non-empty alias object keys', alias, sourcePath);\n }\n if (!isAssetGuid(guidValue)) {\n return invalid(\n `$.externalAssets[${JSON.stringify(alias)}]`,\n 'a 16-byte AssetGuid',\n guidValue,\n sourcePath,\n );\n }\n const guid = guidKey(guidValue);\n if (guid === packageGuid || localGuids.has(guid) || externalGuids.has(guid)) {\n return invalid(\n `$.externalAssets[${JSON.stringify(alias)}]`,\n 'a unique foreign GUID not owned by this package',\n guidValue,\n sourcePath,\n );\n }\n externalGuids.add(guid);\n }\n\n return ok(freezeDefinition(value as unknown as ScriptablePackDefinition));\n}\n\nexport function projectScriptablePackMeta(\n definition: ScriptablePackDefinition,\n source: string,\n): ScriptablePackMetaJson {\n const subAssets = Object.entries(definition.assets)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([sourceKey, descriptor], sourceIndex) => ({\n guid: guidKey(descriptor.guid),\n sourceIndex,\n sourceKey,\n kind: descriptor.kind,\n ...(descriptor.name === undefined ? {} : { name: descriptor.name }),\n }));\n const externalAssets = Object.entries(definition.externalAssets)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([alias, guid]) => ({ alias, guid: guidKey(guid) }));\n return {\n schemaVersion: '1.0.0',\n kind: 'external-asset-package',\n packageId: guidKey(definition.packageId),\n ...(definition.name === undefined ? {} : { name: definition.name }),\n importer: 'pack-ts',\n source,\n importSettings: { contractVersion: '1.0.0', externalAssets },\n subAssets,\n };\n}\n","import { createHash } from 'node:crypto';\nimport { readdir, readFile } from 'node:fs/promises';\nimport { basename, dirname, join, relative, resolve, sep } from 'node:path';\nimport type { SourceDeclarationEvidence } from '@forgeax/engine-types';\nimport { SCANNER_BLACKLIST, scan } from '../scanner.js';\nimport { projectScriptablePackMeta } from '../scriptable-pack.js';\nimport { loadScriptablePack } from '../scriptable-pack-node.js';\n\n/** Project root and GUID used to locate an authoritative source declaration. */\nexport interface SourceInventoryRequest {\n readonly projectRoot: string;\n readonly guid: string;\n}\n\nexport interface ProducerSemanticIdentityInput {\n readonly producerRoot: string;\n readonly sourcePath: string;\n readonly sourceDigest: string;\n readonly schemaVersion: string;\n readonly importer: string;\n readonly codec: string;\n readonly settings: unknown;\n readonly producer: string;\n readonly profile: string;\n readonly declaredGuids?: readonly string[];\n}\n\nexport interface ProducerRelativeDdcIdentity {\n readonly logicalPath: string;\n readonly sourceDigest: string;\n readonly key: string;\n}\n\nfunction stableValue(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(stableValue);\n if (value !== null && typeof value === 'object') {\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([key, entry]) => [key, stableValue(entry)]),\n );\n }\n return value;\n}\n\nexport function producerRelativeLogicalPath(producerRoot: string, sourcePath: string): string {\n const root = resolve(producerRoot);\n const source = resolve(sourcePath);\n const path = relative(root, source);\n if (\n path.length === 0 ||\n path === '..' ||\n path.startsWith(`..${sep}`) ||\n resolve(root, path) !== source\n ) {\n throw new Error('producer source must be inside the injected producer root');\n }\n return path.split(sep).join('/');\n}\n\nexport function producerRelativeDdcKey(input: ProducerSemanticIdentityInput): string {\n const logicalPath = producerRelativeLogicalPath(input.producerRoot, input.sourcePath);\n const semantic = {\n schemaVersion: input.schemaVersion,\n logicalPath,\n sourceDigest: input.sourceDigest,\n importer: input.importer,\n codec: input.codec,\n settings: stableValue(input.settings),\n producer: input.producer,\n profile: input.profile,\n declaredGuids: [...(input.declaredGuids ?? [])].sort(),\n };\n return createHash('sha256').update(JSON.stringify(semantic)).digest('hex');\n}\n\nexport function producerRelativeDdcIdentity(\n input: ProducerSemanticIdentityInput,\n): ProducerRelativeDdcIdentity {\n return {\n logicalPath: producerRelativeLogicalPath(input.producerRoot, input.sourcePath),\n sourceDigest: input.sourceDigest,\n key: producerRelativeDdcKey(input),\n };\n}\n\nfunction fingerprint(meta: string, source: Uint8Array | undefined): string {\n const hash = createHash('sha256').update(meta);\n if (source !== undefined) hash.update(source);\n return hash.digest('base64');\n}\n\nfunction sourceFromMeta(\n metaPath: string,\n meta: {\n readonly source?: unknown;\n readonly inputFingerprint?: unknown;\n readonly importSettings?: unknown;\n readonly subAssets?: readonly { readonly guid?: unknown }[];\n },\n guid: string,\n raw: string,\n): SourceDeclarationEvidence | undefined {\n if (\n !meta.subAssets?.some(\n (asset) => typeof asset.guid === 'string' && asset.guid.toLowerCase() === guid.toLowerCase(),\n )\n ) {\n return undefined;\n }\n const source =\n typeof meta.source === 'string' ? meta.source : basename(metaPath).replace(/\\.meta\\.json$/, '');\n const sourcePath = resolve(dirname(metaPath), source);\n const inputFingerprint =\n typeof meta.inputFingerprint === 'string' ? meta.inputFingerprint : fingerprint(raw, undefined);\n return { origin: 'sourceMeta', sourcePath, inputFingerprint };\n}\n\nasync function collectDeclarationPaths(root: string): Promise<string[]> {\n const paths: string[] = [];\n async function visit(dir: string): Promise<void> {\n const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);\n for (const entry of entries) {\n const path = join(dir, entry.name);\n if (entry.isDirectory()) {\n if (!SCANNER_BLACKLIST.has(entry.name)) await visit(path);\n continue;\n }\n if (\n entry.isFile() &&\n (entry.name.endsWith('.meta.json') ||\n entry.name.endsWith('.pack.json') ||\n entry.name.endsWith('.pack.ts'))\n ) {\n paths.push(path);\n }\n }\n }\n await visit(root);\n return paths;\n}\n\n/** Read `.meta.json` or `.pack.json` source declarations without runtime imports. */\nexport async function readSourceInventory(\n request: SourceInventoryRequest,\n): Promise<SourceDeclarationEvidence | undefined> {\n const result = await scan([request.projectRoot]);\n const paths = result.ok ? result.value : await collectDeclarationPaths(request.projectRoot);\n const guid = request.guid.toLowerCase();\n let authored: SourceDeclarationEvidence | undefined;\n for (const path of paths) {\n if (path.endsWith('.pack.ts')) {\n const loaded = await loadScriptablePack(path, { metadataOnly: true });\n if (!loaded.ok) continue;\n const meta = projectScriptablePackMeta(loaded.value, path);\n if (meta.subAssets.some((asset) => asset.guid.toLowerCase() === guid)) {\n return { origin: 'sourceMeta', sourcePath: path };\n }\n continue;\n }\n const raw = await readFile(path, 'utf8').catch(() => undefined);\n if (raw === undefined) continue;\n let parsed: {\n readonly assets?: readonly { readonly guid?: unknown }[];\n readonly source?: unknown;\n readonly inputFingerprint?: unknown;\n readonly importSettings?: unknown;\n readonly subAssets?: readonly { readonly guid?: unknown }[];\n };\n try {\n parsed = JSON.parse(raw) as typeof parsed;\n } catch {\n continue;\n }\n if (path.endsWith('.pack.json')) {\n if (\n parsed.assets?.some(\n (asset) =>\n typeof asset.guid === 'string' &&\n (asset.guid === request.guid || asset.guid.toLowerCase() === guid),\n )\n ) {\n authored = { origin: 'authoredPack', sourcePath: path };\n }\n continue;\n }\n if (path.endsWith('.meta.json')) {\n const source = sourceFromMeta(path, parsed, request.guid, raw);\n if (source !== undefined) return source;\n }\n }\n return authored;\n}\n","import { createHash } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { mkdir, mkdtemp, readFile, realpath, rename, rm, stat, writeFile } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { dirname, extname, isAbsolute, relative, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { Worker } from 'node:worker_threads';\nimport type { AssetGuid, Result } from '@forgeax/engine-types';\nimport { AssetError, err, ImportError, ok } from '@forgeax/engine-types';\nimport ts from 'typescript';\nimport {\n type ProducerSemanticIdentityInput,\n producerRelativeDdcKey,\n} from './evidence/source-inventory.js';\nimport { AssetGuid as AssetGuidCodec } from './guid.js';\nimport {\n type AssetReader,\n projectScriptablePackMeta,\n type ScriptablePackAssetKind,\n type ScriptablePackAuthoringMutation,\n type ScriptablePackAuthoringPort,\n type ScriptablePackDefinition,\n type ScriptablePackError,\n type ScriptablePackReadError,\n type ScriptablePackSourceClosureEntry,\n validateScriptablePackDefinition,\n} from './scriptable-pack.js';\n\nconst IMPORT_META_RESOLVE_FLAG = '--experimental-import-meta-resolve';\n\nfunction scriptablePackWorkerExecArgv(): string[] {\n // import.meta.resolve(parentURL) is the canonical ESM resolver, but Node\n // keeps its parentURL overload behind this flag. Filter --input-type as\n // well: stdin/eval hosts may pass it through process.execArgv, and Node\n // rejects that option inside a file-backed worker.\n const inherited = process.execArgv.filter((arg) => !arg.startsWith('--input-type'));\n return inherited.includes(IMPORT_META_RESOLVE_FLAG)\n ? inherited\n : [...inherited, IMPORT_META_RESOLVE_FLAG];\n}\n\nexport interface ScriptablePackModuleExecutor {\n load(sourcePath: string): Promise<unknown>;\n dispose?(reason: 'complete' | 'timeout' | 'failure'): void | Promise<void>;\n}\n\nexport interface ScriptablePackModuleExecutorPool {\n acquire(): Promise<ScriptablePackModuleExecutor>;\n dispose(): Promise<void>;\n}\n\nexport interface ScriptablePackModuleExecutorPoolOptions {\n readonly maxWorkers?: number;\n readonly maxTasksPerWorker?: number;\n}\n\nexport function scriptablePackDdcKey(input: ProducerSemanticIdentityInput): string {\n return producerRelativeDdcKey(input);\n}\n\nexport interface OptionalBuildCache<T> {\n readonly read: () => Promise<T | null>;\n readonly coldCook: () => Promise<T>;\n}\n\n/** Build CAS is a performance hint; source cold cook remains the correctness path. */\nexport async function readOptionalBuildCache<T>(cache: OptionalBuildCache<T>): Promise<{\n readonly value: T;\n readonly fromCache: boolean;\n}> {\n try {\n const cached = await cache.read();\n if (cached !== null) return { value: cached, fromCache: true };\n } catch {\n // Cache deletion, read-only storage, and corrupt optional objects fail open.\n }\n return { value: await cache.coldCook(), fromCache: false };\n}\n\nexport interface LoadScriptablePackOptions {\n /** Maximum time allowed for module initialization in the isolated worker. */\n readonly timeoutMs?: number;\n /** Maximum time allowed for one definition.build(reader) in the isolated worker. */\n readonly buildTimeoutMs?: number;\n readonly executor?: ScriptablePackModuleExecutor;\n /** Release the isolated loader after identity projection when build will not be called. */\n readonly metadataOnly?: boolean;\n}\n\nasync function resolveRelativeImport(\n sourcePath: string,\n specifier: string,\n): Promise<string | undefined> {\n if (!specifier.startsWith('.')) return undefined;\n const raw = resolve(dirname(sourcePath), specifier);\n const candidates =\n extname(raw).length > 0\n ? [raw]\n : [\n raw,\n `${raw}.ts`,\n `${raw}.tsx`,\n `${raw}.mts`,\n `${raw}.js`,\n `${raw}.mjs`,\n `${raw}.json`,\n resolve(raw, 'index.ts'),\n ];\n for (const candidate of candidates) {\n try {\n if ((await stat(candidate)).isFile()) return candidate;\n } catch {\n // Continue through deterministic extension candidates.\n }\n }\n return undefined;\n}\n\n/** Capture one immutable ScriptablePack module closure for inventory and production. */\nexport async function inventoryScriptablePackSource(\n sourcePath: string,\n initialSourceText?: string,\n): Promise<readonly ScriptablePackSourceClosureEntry[]> {\n const root = await realpath(sourcePath);\n const pending = [root];\n const seen = new Set<string>();\n const entries: ScriptablePackSourceClosureEntry[] = [];\n while (pending.length > 0) {\n const path = pending.pop();\n if (path === undefined || seen.has(path)) continue;\n seen.add(path);\n const bytes =\n path === root && initialSourceText !== undefined\n ? new TextEncoder().encode(initialSourceText)\n : await readFile(path);\n entries.push({ path, digest: `sha256:${createHash('sha256').update(bytes).digest('hex')}` });\n const source = new TextDecoder().decode(bytes);\n for (const imported of ts.preProcessFile(source, true, true).importedFiles) {\n const resolved = await resolveRelativeImport(path, imported.fileName);\n if (resolved !== undefined) pending.push(await realpath(resolved));\n }\n }\n return entries.sort((left, right) => left.path.localeCompare(right.path));\n}\n\ninterface StructuredFailure {\n readonly name?: unknown;\n readonly code?: unknown;\n readonly expected?: unknown;\n readonly actual?: unknown;\n readonly hint?: unknown;\n readonly detail?: unknown;\n readonly message?: unknown;\n}\n\nfunction serializeFailure(value: unknown): StructuredFailure {\n if (value !== null && typeof value === 'object') {\n const failure = value as Record<string, unknown>;\n return {\n name: failure.name,\n code: failure.code,\n expected: failure.expected,\n actual: failure.actual,\n hint: failure.hint,\n detail: failure.detail,\n message: failure.message,\n };\n }\n return { message: String(value) };\n}\n\nfunction hydrateFailure(value: unknown): unknown {\n if (value === null || typeof value !== 'object') return value;\n const failure = value as StructuredFailure;\n if (\n failure.name === 'AssetError' &&\n typeof failure.code === 'string' &&\n typeof failure.expected === 'string' &&\n typeof failure.hint === 'string'\n ) {\n const args = {\n code: failure.code as ConstructorParameters<typeof AssetError>[0]['code'],\n expected: failure.expected,\n hint: failure.hint,\n };\n return failure.detail === undefined\n ? new AssetError(args)\n : new AssetError({\n ...args,\n detail: failure.detail as NonNullable<\n ConstructorParameters<typeof AssetError>[0]['detail']\n >,\n });\n }\n if (\n failure.name === 'ImportError' &&\n typeof failure.code === 'string' &&\n typeof failure.expected === 'string' &&\n typeof failure.hint === 'string' &&\n failure.detail !== undefined\n ) {\n return new ImportError({\n code: failure.code as ConstructorParameters<typeof ImportError>[0]['code'],\n expected: failure.expected,\n hint: failure.hint,\n detail: failure.detail as ConstructorParameters<typeof ImportError>[0]['detail'],\n ...(typeof failure.actual === 'string' ? { actual: failure.actual } : {}),\n });\n }\n if (typeof failure.message === 'string') {\n const error = new Error(failure.message);\n if (typeof failure.name === 'string') error.name = failure.name;\n return error;\n }\n return value;\n}\n\nclass WorkerScriptablePackExecutor implements ScriptablePackModuleExecutor {\n private worker: Worker | undefined;\n private compileRoot: string | undefined;\n private nextBuildId = 0;\n private disposal: Promise<void> | undefined;\n private build:\n | {\n readonly id: number;\n readonly reader: AssetReader;\n readonly resolve: (value: unknown) => void;\n readonly reject: (reason: unknown) => void;\n }\n | undefined;\n\n async load(sourcePath: string): Promise<unknown> {\n const workerUrl = scriptablePackWorkerUrl();\n const compileRoot = await mkdtemp(resolve(tmpdir(), 'forgeax-scriptable-pack-'));\n this.compileRoot = compileRoot;\n const worker = new Worker(workerUrl, {\n workerData: { sourcePath: resolve(sourcePath), compileRoot },\n execArgv: scriptablePackWorkerExecArgv(),\n resourceLimits: { maxOldGenerationSizeMb: 256, maxYoungGenerationSizeMb: 64 },\n });\n this.worker = worker;\n worker.on('message', (message: unknown) => this.onMessage(message));\n worker.unref();\n return new Promise((resolveLoad, rejectLoad) => {\n const onMessage = (message: unknown): void => {\n if (message === null || typeof message !== 'object') return;\n const value = message as Record<string, unknown>;\n if (value.kind === 'loaded') {\n // The scan keeps this executor alive for the later no-reopen build\n // route, but an idle source worker must not keep a Vite/Vitest host\n // process alive after its own work has settled.\n worker.unref();\n worker.off('message', onMessage);\n resolveLoad({\n default:\n value.definition === undefined\n ? undefined\n : {\n ...(value.definition as Record<string, unknown>),\n build: (reader: AssetReader) => this.runBuild(reader),\n },\n });\n } else if (value.kind === 'load-threw') {\n worker.off('message', onMessage);\n rejectLoad(hydrateFailure(value.error));\n }\n };\n worker.on('message', onMessage);\n worker.once('error', rejectLoad);\n worker.once('exit', (code) => {\n if (code !== 0) rejectLoad(new Error(`ScriptablePack worker exited with code ${code}`));\n });\n });\n }\n\n dispose(reason: 'complete' | 'timeout' | 'failure' = 'complete'): Promise<void> {\n if (this.disposal !== undefined) return this.disposal;\n const worker = this.worker;\n this.worker = undefined;\n const compileRoot = this.compileRoot;\n this.compileRoot = undefined;\n const active = this.build;\n this.build = undefined;\n if (active !== undefined) {\n active.reject(new Error(`ScriptablePack build disposed during ${reason}`));\n }\n this.disposal = (async () => {\n if (worker !== undefined) await worker.terminate();\n if (compileRoot !== undefined) await rm(compileRoot, { recursive: true, force: true });\n })();\n return this.disposal;\n }\n\n private runBuild(reader: AssetReader): Promise<unknown> {\n const worker = this.worker;\n if (worker === undefined) return Promise.reject(new Error('ScriptablePack worker is closed'));\n if (this.build !== undefined)\n return Promise.reject(new Error('ScriptablePack worker already has an active build'));\n const id = this.nextBuildId++;\n return new Promise((resolveBuild, rejectBuild) => {\n this.build = { id, reader, resolve: resolveBuild, reject: rejectBuild };\n worker.postMessage({ kind: 'build', buildId: id });\n });\n }\n\n private onMessage(message: unknown): void {\n if (message === null || typeof message !== 'object') return;\n const value = message as Record<string, unknown>;\n const active = this.build;\n if (active === undefined || value.buildId !== active.id) return;\n if (value.kind === 'asset-read' && typeof value.readId === 'number') {\n void active.reader\n .readByGuid(value.guid as AssetGuid)\n .then((result) =>\n this.worker?.postMessage({\n kind: 'asset-result',\n readId: value.readId,\n result:\n result.ok === true ? result : { ...result, error: serializeFailure(result.error) },\n }),\n )\n .catch((error: unknown) => {\n if (this.build?.id !== active.id) return;\n this.build = undefined;\n active.reject(error);\n void this.dispose('failure');\n });\n return;\n }\n this.build = undefined;\n if (value.kind === 'build-result') active.resolve(value.result);\n else if (value.kind === 'build-threw') active.reject(hydrateFailure(value.error));\n else this.build = active;\n }\n}\n\nfunction scriptablePackWorkerUrl(): URL {\n const bundledWorker = new URL('./scriptable-pack-worker.mjs', import.meta.url);\n return existsSync(fileURLToPath(bundledWorker))\n ? bundledWorker\n : new URL('../dist/scriptable-pack-worker.mjs', import.meta.url);\n}\n\nclass ReusableWorkerScriptablePackExecutor implements ScriptablePackModuleExecutor {\n private readonly worker: Worker;\n private readonly compileRootReady = mkdtemp(resolve(tmpdir(), 'forgeax-scriptable-pack-pool-'));\n private compileRoot: string | undefined;\n private nextLoadId = 0;\n private nextBuildId = 0;\n private pendingLoad:\n | {\n readonly id: number;\n readonly resolve: (value: unknown) => void;\n readonly reject: (reason: unknown) => void;\n }\n | undefined;\n private build:\n | {\n readonly id: number;\n readonly reader: AssetReader;\n readonly resolve: (value: unknown) => void;\n readonly reject: (reason: unknown) => void;\n }\n | undefined;\n private disposal: Promise<void> | undefined;\n private forceDispose = false;\n private failed = false;\n private taskCount = 0;\n private released = false;\n\n constructor(\n private readonly maxTasksPerWorker: number,\n private readonly release: (\n executor: ReusableWorkerScriptablePackExecutor,\n reusable: boolean,\n ) => void,\n ) {\n this.worker = new Worker(scriptablePackWorkerUrl(), {\n workerData: { mode: 'reusable' },\n execArgv: scriptablePackWorkerExecArgv(),\n resourceLimits: { maxOldGenerationSizeMb: 256, maxYoungGenerationSizeMb: 64 },\n });\n this.worker.on('message', (message: unknown) => this.onMessage(message));\n this.worker.on('error', (error: Error) => {\n this.failed = true;\n this.rejectActive(error);\n void this.dispose('failure');\n });\n this.worker.on('exit', (code) => {\n if (code === 0 || this.disposal !== undefined) return;\n this.failed = true;\n this.rejectActive(new Error(`ScriptablePack worker exited with code ${code}`));\n void this.dispose('failure');\n });\n // Listener registration can retain the worker's MessagePort in Node.\n // A reusable worker must not keep a completed Vite build alive while its\n // pool is draining; it still processes messages while the host is live.\n this.worker.unref();\n }\n\n async load(sourcePath: string): Promise<unknown> {\n const activeDisposal = this.disposal;\n if (activeDisposal !== undefined) {\n await activeDisposal;\n if (this.failed) {\n return Promise.reject(new Error('ScriptablePack executor is not leased'));\n }\n this.disposal = undefined;\n }\n this.released = false;\n if (this.pendingLoad !== undefined || this.build !== undefined) {\n return Promise.reject(new Error('ScriptablePack executor already has an active task'));\n }\n const compileRoot = this.compileRoot ?? (await this.compileRootReady);\n if (this.disposal !== undefined) {\n const disposal = this.disposal;\n await disposal;\n if (this.failed) {\n return Promise.reject(new Error('ScriptablePack executor is not leased'));\n }\n this.disposal = undefined;\n }\n const loadId = this.nextLoadId++;\n this.compileRoot = compileRoot;\n this.taskCount += 1;\n return new Promise((resolveLoad, rejectLoad) => {\n this.pendingLoad = { id: loadId, resolve: resolveLoad, reject: rejectLoad };\n try {\n this.worker.postMessage({\n kind: 'load',\n loadId,\n sourcePath: resolve(sourcePath),\n compileRoot,\n });\n } catch (error) {\n this.pendingLoad = undefined;\n rejectLoad(error);\n void this.dispose('failure');\n }\n });\n }\n\n dispose(reason: 'complete' | 'timeout' | 'failure' = 'complete'): Promise<void> {\n if (reason === 'failure') this.forceDispose = true;\n const activeDisposal = this.disposal;\n if (activeDisposal !== undefined) {\n return activeDisposal;\n }\n this.rejectActive(new Error(`ScriptablePack task disposed during ${reason}`));\n this.disposal = (async () => {\n const compileRoot = this.compileRoot ?? (await this.compileRootReady);\n const reusable =\n reason === 'complete' &&\n !this.failed &&\n !this.forceDispose &&\n this.taskCount < this.maxTasksPerWorker;\n this.forceDispose = false;\n if (!reusable) {\n this.compileRoot = undefined;\n await this.worker.terminate();\n await rm(compileRoot, { recursive: true, force: true });\n }\n this.released = true;\n this.disposal = undefined;\n this.release(this, reusable);\n })();\n return this.disposal;\n }\n\n private rejectActive(error: unknown): void {\n const loading = this.pendingLoad;\n this.pendingLoad = undefined;\n loading?.reject(error);\n const building = this.build;\n this.build = undefined;\n building?.reject(error);\n }\n\n private runBuild(reader: AssetReader): Promise<unknown> {\n if (this.released || this.disposal !== undefined) {\n return Promise.reject(new Error('ScriptablePack executor is not leased'));\n }\n if (this.build !== undefined) {\n return Promise.reject(new Error('ScriptablePack worker already has an active build'));\n }\n const id = this.nextBuildId++;\n return new Promise((resolveBuild, rejectBuild) => {\n this.build = { id, reader, resolve: resolveBuild, reject: rejectBuild };\n try {\n this.worker.postMessage({ kind: 'build', buildId: id });\n } catch (error) {\n this.build = undefined;\n rejectBuild(error);\n void this.dispose('failure');\n }\n });\n }\n\n private onMessage(message: unknown): void {\n if (message === null || typeof message !== 'object') return;\n const value = message as Record<string, unknown>;\n const loading = this.pendingLoad;\n if (loading !== undefined && value.kind === 'loaded' && value.loadId === loading.id) {\n this.pendingLoad = undefined;\n loading.resolve({\n default:\n value.definition === undefined\n ? undefined\n : {\n ...(value.definition as Record<string, unknown>),\n build: (reader: AssetReader) => this.runBuild(reader),\n },\n });\n return;\n }\n if (loading !== undefined && value.kind === 'load-threw' && value.loadId === loading.id) {\n this.pendingLoad = undefined;\n loading.reject(hydrateFailure(value.error));\n return;\n }\n const active = this.build;\n if (active === undefined || value.buildId !== active.id) return;\n if (value.kind === 'asset-read' && typeof value.readId === 'number') {\n void active.reader\n .readByGuid(value.guid as AssetGuid)\n .then((result) =>\n this.worker.postMessage({\n kind: 'asset-result',\n readId: value.readId,\n result:\n result.ok === true ? result : { ...result, error: serializeFailure(result.error) },\n }),\n )\n .catch((error: unknown) => {\n if (this.build?.id !== active.id) return;\n this.build = undefined;\n active.reject(error);\n void this.dispose('failure');\n });\n return;\n }\n this.build = undefined;\n if (value.kind === 'build-result') active.resolve(value.result);\n else if (value.kind === 'build-threw') active.reject(hydrateFailure(value.error));\n else this.build = active;\n }\n}\n\nclass DefaultScriptablePackModuleExecutorPool implements ScriptablePackModuleExecutorPool {\n private readonly maxWorkers: number;\n private readonly maxTasksPerWorker: number;\n private readonly idle: ReusableWorkerScriptablePackExecutor[] = [];\n private readonly waiters: {\n readonly resolve: (executor: ScriptablePackModuleExecutor) => void;\n readonly reject: (reason: unknown) => void;\n }[] = [];\n private readonly executors = new Set<ReusableWorkerScriptablePackExecutor>();\n private workerCount = 0;\n private closed = false;\n\n constructor(options: ScriptablePackModuleExecutorPoolOptions = {}) {\n this.maxWorkers = Math.max(1, Math.trunc(options.maxWorkers ?? 2));\n this.maxTasksPerWorker = Math.max(1, Math.trunc(options.maxTasksPerWorker ?? 32));\n }\n\n acquire(): Promise<ScriptablePackModuleExecutor> {\n if (this.closed) return Promise.reject(new Error('ScriptablePack executor pool is closed'));\n const executor = this.idle.pop();\n if (executor !== undefined) return Promise.resolve(executor);\n if (this.workerCount < this.maxWorkers) {\n this.workerCount += 1;\n return Promise.resolve(this.createExecutor());\n }\n return new Promise((resolveAcquire, rejectAcquire) =>\n this.waiters.push({ resolve: resolveAcquire, reject: rejectAcquire }),\n );\n }\n\n async dispose(): Promise<void> {\n if (this.closed) return;\n this.closed = true;\n const waiters = this.waiters.splice(0);\n for (const waiter of waiters) {\n waiter.reject(new Error('ScriptablePack executor pool is closed'));\n }\n this.idle.splice(0);\n await Promise.all([...this.executors].map((executor) => executor.dispose('failure')));\n }\n\n private createExecutor(): ReusableWorkerScriptablePackExecutor {\n const executor = new ReusableWorkerScriptablePackExecutor(\n this.maxTasksPerWorker,\n (executor, reusable) => {\n if (this.closed) {\n this.executors.delete(executor);\n if (!reusable) this.workerCount -= 1;\n return;\n }\n if (!reusable) {\n this.executors.delete(executor);\n this.workerCount -= 1;\n } else {\n this.idle.push(executor);\n }\n this.drain();\n },\n );\n this.executors.add(executor);\n return executor;\n }\n\n private drain(): void {\n if (this.closed) return;\n while (this.waiters.length > 0) {\n const idle = this.idle.pop();\n if (idle !== undefined) {\n this.waiters.shift()?.resolve(idle);\n continue;\n }\n if (this.workerCount >= this.maxWorkers) return;\n this.workerCount += 1;\n this.waiters.shift()?.resolve(this.createExecutor());\n }\n }\n}\n\nexport function createScriptablePackModuleExecutorPool(\n options: ScriptablePackModuleExecutorPoolOptions = {},\n): ScriptablePackModuleExecutorPool {\n return new DefaultScriptablePackModuleExecutorPool(options);\n}\n\nfunction loadFailure(\n sourcePath: string,\n reason: 'module-load' | 'timeout',\n phase: 'module-load' | 'build',\n diagnostic: string,\n timeoutMs?: number,\n): Result<never, ScriptablePackError> {\n return err({\n code: 'pack-source-load-failed',\n expected: 'a trusted synchronous module with a valid default ScriptablePack export',\n hint: 'repair the module load or initialization failure, then inspect Meta again',\n detail: {\n sourcePath,\n reason,\n phase,\n diagnostic,\n ...(timeoutMs === undefined ? {} : { timeoutMs }),\n },\n });\n}\n\nfunction buildTimeoutFailure(sourcePath: string, timeoutMs: number): ScriptablePackReadError {\n return {\n code: 'pack-source-load-failed',\n expected: 'a ScriptablePack build to settle within the configured build timeout',\n hint: 'repair the authored build, then retry through a fresh ScriptablePack generation',\n detail: {\n sourcePath,\n reason: 'timeout',\n phase: 'build',\n timeoutMs,\n diagnostic: `ScriptablePack build exceeded ${timeoutMs}ms`,\n },\n };\n}\n\nexport async function loadScriptablePack(\n sourcePath: string,\n options: LoadScriptablePackOptions = {},\n): Promise<Result<Readonly<ScriptablePackDefinition>, ScriptablePackError>> {\n // Module initialization includes transpiling the trusted TypeScript source\n // closure in a fresh Worker. A cold SDK workspace can legitimately exceed\n // the build execution budget before any authored build() code has run.\n const timeoutMs = options.timeoutMs ?? 15_000;\n const buildTimeoutMs = options.buildTimeoutMs ?? 5_000;\n const executor = options.executor ?? new WorkerScriptablePackExecutor();\n let disposeReason: 'complete' | 'timeout' | 'failure' | undefined;\n let timeout: ReturnType<typeof setTimeout> | undefined;\n try {\n const timeoutSignal = Symbol('scriptable-pack-module-timeout');\n const loaded = await Promise.race([\n executor.load(sourcePath),\n new Promise<typeof timeoutSignal>((resolve) => {\n timeout = setTimeout(() => resolve(timeoutSignal), timeoutMs);\n }),\n ]);\n if (loaded === timeoutSignal) {\n disposeReason = 'timeout';\n return loadFailure(\n sourcePath,\n 'timeout',\n 'module-load',\n `ScriptablePack module initialization exceeded ${timeoutMs}ms`,\n timeoutMs,\n );\n }\n const moduleValue =\n loaded !== null && typeof loaded === 'object' && 'default' in loaded\n ? (loaded as { readonly default: unknown }).default\n : undefined;\n const validated = validateScriptablePackDefinition(moduleValue, sourcePath);\n if (!validated.ok) {\n disposeReason = 'failure';\n return validated;\n }\n if (options.metadataOnly === true) {\n disposeReason = 'complete';\n return validated;\n }\n const definition = validated.value;\n type BuildOutcome = Awaited<ReturnType<ScriptablePackDefinition['build']>>;\n return ok({\n ...definition,\n build: async (reader: AssetReader): Promise<BuildOutcome> => {\n let buildTimedOut = false;\n let buildTimeout: ReturnType<typeof setTimeout> | undefined;\n const timeoutResult = err(buildTimeoutFailure(sourcePath, buildTimeoutMs));\n try {\n const built = await Promise.race([\n Promise.resolve(definition.build(reader)),\n new Promise<BuildOutcome>((resolve) => {\n buildTimeout = setTimeout(() => {\n buildTimedOut = true;\n resolve(timeoutResult as BuildOutcome);\n }, buildTimeoutMs);\n }),\n ]);\n if (buildTimedOut) {\n await executor.dispose?.('timeout');\n return built;\n }\n await executor.dispose?.('complete');\n return built;\n } catch (error) {\n await executor.dispose?.('failure');\n throw error;\n } finally {\n if (buildTimeout !== undefined) clearTimeout(buildTimeout);\n }\n },\n });\n } catch (error) {\n const diagnostic = error instanceof Error ? error.message : String(error);\n disposeReason = 'failure';\n return loadFailure(sourcePath, 'module-load', 'module-load', diagnostic);\n } finally {\n if (timeout !== undefined) clearTimeout(timeout);\n if (disposeReason !== undefined) await executor.dispose?.(disposeReason);\n }\n}\n\nconst CANONICAL_SCAFFOLD_MARKER = '// @forgeax-scriptable-pack canonical-v1';\nconst CANONICAL_MANIFEST_NAME = 'canonicalManifest';\nconst CANONICAL_MUTABLE_KINDS = new Set<ScriptablePackAssetKind>(['scene', 'mesh', 'material']);\n\ninterface CanonicalOutput {\n readonly guid: string;\n readonly kind: ScriptablePackAssetKind;\n readonly name?: string;\n}\n\ninterface CanonicalManifest {\n readonly schemaVersion: '1.0.0';\n readonly packageId: string;\n readonly name?: string;\n readonly assets: Readonly<Record<string, CanonicalOutput>>;\n readonly externalAssets: Readonly<Record<string, string>>;\n}\n\nexport interface FileSystemScriptablePackAuthoringOptions {\n /** All source and target paths are confined to this game root. */\n readonly gameRoot: string;\n readonly incomingRefs?: (sourcePath: string, sourceKey?: string) => Promise<readonly string[]>;\n readonly rebuild?: (\n sourcePath: string,\n mode: 'rebuild' | 'cold-cook',\n ) => Promise<Result<void, ScriptablePackError>>;\n}\n\nfunction authoringError(\n code:\n | 'pack-source-path-invalid'\n | 'pack-source-revision-conflict'\n | 'pack-source-mutation-unsupported'\n | 'pack-source-reference-conflict'\n | 'pack-source-write-failed',\n input: {\n readonly expected: string;\n readonly actual?: string;\n readonly hint: string;\n readonly retryable: boolean;\n readonly recoveryActions: readonly string[];\n readonly requestId?: string;\n readonly sourcePath?: string;\n readonly sourceKey?: string;\n readonly incomingRefs?: readonly string[];\n },\n): ScriptablePackError {\n return {\n code,\n expected: input.expected,\n ...(input.actual === undefined ? {} : { actual: input.actual }),\n hint: input.hint,\n retryable: input.retryable,\n recoveryActions: input.recoveryActions,\n detail: {\n ...(input.requestId === undefined ? {} : { requestId: input.requestId }),\n ...(input.sourcePath === undefined ? {} : { sourcePath: input.sourcePath }),\n ...(input.sourceKey === undefined ? {} : { sourceKey: input.sourceKey }),\n ...(input.incomingRefs === undefined ? {} : { incomingRefs: input.incomingRefs }),\n },\n };\n}\n\nfunction confinedSourcePath(\n gameRoot: string,\n sourcePath: string,\n): Result<{ readonly absolute: string; readonly relative: string }, ScriptablePackError> {\n const root = resolve(gameRoot);\n const absolute = resolve(root, sourcePath);\n const rel = relative(root, absolute);\n if (\n rel.length === 0 ||\n rel === '..' ||\n rel.startsWith(`..${sep}`) ||\n isAbsolute(sourcePath) ||\n !rel.endsWith('.pack.ts')\n ) {\n return err(\n authoringError('pack-source-path-invalid', {\n expected: 'a game-root-relative *.pack.ts path confined to the selected game',\n actual: sourcePath,\n hint: 'choose a relative ScriptablePack source path inside the selected game root',\n retryable: false,\n recoveryActions: ['choose-game-relative-source-path'],\n sourcePath,\n }),\n );\n }\n return ok({ absolute, relative: rel.split(sep).join('/') });\n}\n\nfunction revisionOf(source: string): string {\n return createHash('sha256').update(source).digest('hex');\n}\n\nfunction unwrapExpression(expression: ts.Expression): ts.Expression {\n if (\n ts.isAsExpression(expression) ||\n ts.isSatisfiesExpression(expression) ||\n ts.isParenthesizedExpression(expression)\n ) {\n return unwrapExpression(expression.expression);\n }\n return expression;\n}\n\nfunction literalValue(expression: ts.Expression): unknown {\n const value = unwrapExpression(expression);\n if (ts.isStringLiteral(value) || ts.isNoSubstitutionTemplateLiteral(value)) return value.text;\n if (value.kind === ts.SyntaxKind.TrueKeyword) return true;\n if (value.kind === ts.SyntaxKind.FalseKeyword) return false;\n if (value.kind === ts.SyntaxKind.NullKeyword) return null;\n if (ts.isNumericLiteral(value)) return Number(value.text);\n if (ts.isArrayLiteralExpression(value)) return value.elements.map(literalValue);\n if (ts.isObjectLiteralExpression(value)) {\n const result: Record<string, unknown> = {};\n for (const property of value.properties) {\n if (!ts.isPropertyAssignment(property))\n throw new TypeError('manifest properties must be data');\n const name = property.name;\n const key =\n ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)\n ? name.text\n : undefined;\n if (key === undefined) throw new TypeError('manifest property names must be static');\n result[key] = literalValue(property.initializer);\n }\n return result;\n }\n throw new TypeError('manifest values must be literal data');\n}\n\nfunction parseCanonicalManifest(source: string, sourcePath: string): CanonicalManifest | undefined {\n if (!source.startsWith(`${CANONICAL_SCAFFOLD_MARKER}\\n`)) return undefined;\n const file = ts.createSourceFile(\n sourcePath,\n source,\n ts.ScriptTarget.Latest,\n true,\n ts.ScriptKind.TS,\n );\n for (const statement of file.statements) {\n if (!ts.isVariableStatement(statement)) continue;\n for (const declaration of statement.declarationList.declarations) {\n if (\n ts.isIdentifier(declaration.name) &&\n declaration.name.text === CANONICAL_MANIFEST_NAME &&\n declaration.initializer !== undefined\n ) {\n const value = literalValue(declaration.initializer);\n if (value === null || typeof value !== 'object') return undefined;\n return value as CanonicalManifest;\n }\n }\n }\n return undefined;\n}\n\nfunction guidExpression(value: string): string {\n return `parseGuid(${JSON.stringify(value)})`;\n}\n\n/** Render the one source shape that the file authoring port may mutate structurally. */\nexport function renderCanonicalScriptablePack(manifest: CanonicalManifest): string {\n const data = JSON.stringify(manifest, null, 2);\n return `${CANONICAL_SCAFFOLD_MARKER}\nimport { AssetGuid } from '@forgeax/engine-pack/guid';\nimport { buildMeshAttributeMapForUvSets } from '@forgeax/engine-geometry';\nimport type { ScriptablePackDefinition } from '@forgeax/engine-pack/source';\nimport type { Asset, AssetGuid as AssetGuidType } from '@forgeax/engine-types';\nimport { ok } from '@forgeax/engine-types';\n\nconst ${CANONICAL_MANIFEST_NAME} = ${data} as const;\n\nfunction parseGuid(value: string): AssetGuidType {\n const parsed = AssetGuid.parse(value);\n if (!parsed.ok) throw parsed.error;\n return parsed.value;\n}\n\nfunction createOutput(kind: string): Asset {\n switch (kind) {\n case 'scene':\n return { kind: 'scene', entities: [], mounts: [] };\n case 'material':\n return { kind: 'material', values: {} };\n case 'mesh': {\n const vertices = new Float32Array([\n 0, 0.7, 0, 0, 0, 1, 0.5, 1, 0, 0, 0, 1,\n -0.7, -0.6, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1,\n 0.7, -0.6, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1,\n ]);\n return {\n kind: 'mesh',\n vertices,\n indices: new Uint16Array([0, 1, 2]),\n attributes: { ...buildMeshAttributeMapForUvSets(1), position: vertices },\n aabb: new Float32Array([-0.7, -0.6, 0, 0.7, 0.7, 0]),\n submeshes: [{ indexOffset: 0, indexCount: 3, vertexCount: 3, topology: 'triangle-list', materialSlot: 0 }],\n materialSlots: [{ slotName: 'Default' }],\n };\n }\n default:\n throw new Error(\\`canonical ScriptablePack output kind is not mutable: \\${kind}\\`);\n }\n}\n\nconst assets = Object.fromEntries(\n Object.entries(${CANONICAL_MANIFEST_NAME}.assets).map(([sourceKey, asset]) => [\n sourceKey,\n { ...asset, guid: parseGuid(asset.guid) },\n ]),\n);\nconst externalAssets = Object.fromEntries(\n Object.entries(${CANONICAL_MANIFEST_NAME}.externalAssets).map(([alias, guid]) => [alias, parseGuid(guid)]),\n);\n\nexport default {\n schemaVersion: '1.0.0',\n packageId: ${guidExpression(manifest.packageId)},\n ${manifest.name === undefined ? '' : `name: ${JSON.stringify(manifest.name)},\\n `}assets,\n externalAssets,\n build: () => ok(Object.fromEntries(Object.entries(assets).map(([sourceKey, asset]) => [sourceKey, createOutput(asset.kind)])) as Record<string, Asset>),\n} satisfies ScriptablePackDefinition;\n`;\n}\n\nfunction definitionFromCanonical(\n manifest: CanonicalManifest,\n): Result<ScriptablePackDefinition, ScriptablePackError> {\n const packageId = AssetGuidCodec.parse(manifest.packageId);\n if (!packageId.ok) return invalidCanonicalGuid('$.packageId', manifest.packageId);\n const assets: Record<string, { guid: AssetGuid; kind: ScriptablePackAssetKind; name?: string }> =\n {};\n for (const [sourceKey, output] of Object.entries(manifest.assets)) {\n const guid = AssetGuidCodec.parse(output.guid);\n if (!guid.ok)\n return invalidCanonicalGuid(`$.assets[${JSON.stringify(sourceKey)}].guid`, output.guid);\n assets[sourceKey] = {\n guid: guid.value,\n kind: output.kind,\n ...(output.name === undefined ? {} : { name: output.name }),\n };\n }\n const externalAssets: Record<string, AssetGuid> = {};\n for (const [alias, value] of Object.entries(manifest.externalAssets)) {\n const guid = AssetGuidCodec.parse(value);\n if (!guid.ok) return invalidCanonicalGuid(`$.externalAssets[${JSON.stringify(alias)}]`, value);\n externalAssets[alias] = guid.value;\n }\n return validateScriptablePackDefinition({\n schemaVersion: '1.0.0',\n packageId: packageId.value,\n ...(manifest.name === undefined ? {} : { name: manifest.name }),\n assets,\n externalAssets,\n build: () => ok({} as Record<string, never>),\n });\n}\n\nfunction invalidCanonicalGuid(\n propertyPath: string,\n actual: string,\n): Result<never, ScriptablePackError> {\n return err({\n code: 'pack-source-definition-invalid',\n expected: 'a canonical UUID string',\n hint: 'repair the canonical scaffold manifest GUID and inspect Meta again',\n detail: { propertyPath, actual },\n });\n}\n\nfunction invalidCanonicalSource(\n sourcePath: string,\n error: unknown,\n): Result<never, ScriptablePackError> {\n return err({\n code: 'pack-source-definition-invalid',\n expected: 'a literal canonical-v1 manifest with the required package/assets/external fields',\n hint: 'repair the canonical scaffold or open it as custom source without structured mutation',\n detail: {\n sourcePath,\n propertyPath: '$.canonicalManifest',\n actual: error instanceof Error ? error.message : String(error),\n },\n });\n}\n\nasync function atomicWrite(path: string, source: string): Promise<void> {\n await mkdir(dirname(path), { recursive: true });\n const temporary = `${path}.${process.pid}.${Date.now()}.tmp`;\n try {\n await writeFile(temporary, source, { encoding: 'utf8', flag: 'wx' });\n await rename(temporary, path);\n } catch (error) {\n await rm(temporary, { force: true });\n throw error;\n }\n}\n\nfunction sameStrings(left: readonly string[], right: readonly string[]): boolean {\n return [...left].sort().join('\\0') === [...right].sort().join('\\0');\n}\n\n/** Node filesystem adapter for the public ScriptablePack authoring gateway. */\nexport function createFileSystemScriptablePackAuthoringPort(\n options: FileSystemScriptablePackAuthoringOptions,\n): ScriptablePackAuthoringPort {\n const resolvePath = (sourcePath: string) => confinedSourcePath(options.gameRoot, sourcePath);\n\n async function readSource(sourcePath: string) {\n const path = resolvePath(sourcePath);\n if (!path.ok) return path;\n try {\n const source = await readFile(path.value.absolute, 'utf8');\n return ok({ ...path.value, source, revision: revisionOf(source) });\n } catch (error) {\n return err(\n authoringError('pack-source-write-failed', {\n expected: 'a readable ScriptablePack source file',\n actual: error instanceof Error ? error.message : String(error),\n hint: 'restore the source file or create it through the ScriptablePack gateway',\n retryable: true,\n recoveryActions: ['inspect-source-path', 'retry'],\n sourcePath,\n }),\n );\n }\n }\n\n async function inspect(sourcePath: string) {\n const read = await readSource(sourcePath);\n if (!read.ok) return read;\n let canonical: CanonicalManifest | undefined;\n try {\n canonical = parseCanonicalManifest(read.value.source, read.value.relative);\n } catch (error) {\n return invalidCanonicalSource(read.value.relative, error);\n }\n const loaded =\n canonical === undefined\n ? await loadScriptablePack(read.value.absolute, { metadataOnly: true })\n : definitionFromCanonical(canonical);\n if (!loaded.ok) return loaded;\n return ok({\n revision: read.value.revision,\n meta: projectScriptablePackMeta(loaded.value, read.value.relative),\n });\n }\n\n async function preflight(sourcePath: string) {\n const read = await readSource(sourcePath);\n if (!read.ok) return read;\n const inspected = await inspect(sourcePath);\n if (!inspected.ok) return inspected;\n let canonical: CanonicalManifest | undefined;\n try {\n canonical = parseCanonicalManifest(read.value.source, read.value.relative);\n } catch (error) {\n return invalidCanonicalSource(read.value.relative, error);\n }\n const incomingRefs = (await options.incomingRefs?.(read.value.relative)) ?? [];\n return ok({\n revision: inspected.value.revision,\n meta: inspected.value.meta,\n capabilities:\n canonical === undefined\n ? ({\n inspect: true,\n rebuild: true,\n coldCook: true,\n reason: 'structured mutation is available only for canonical-v1 scaffolds',\n } as const)\n : ({\n inspect: true,\n rebuild: true,\n coldCook: true,\n addOutput: true,\n addExternalAsset: true,\n renameDisplay: true,\n removeOutput: true,\n clone: true,\n } as const),\n incomingRefs,\n });\n }\n\n async function mutate(operation: ScriptablePackAuthoringMutation) {\n const targetPath =\n operation.kind === 'clone-scriptable-pack' ? operation.targetPath : operation.sourcePath;\n const target = resolvePath(targetPath);\n if (!target.ok) return target;\n\n let manifest: CanonicalManifest;\n let currentRevision: string | undefined;\n if (operation.kind === 'create-scriptable-pack') {\n if (!CANONICAL_MUTABLE_KINDS.has(operation.initialOutput.kind)) {\n return err(\n authoringError('pack-source-mutation-unsupported', {\n expected: 'a canonical scene, mesh, or material initial output',\n actual: operation.initialOutput.kind,\n hint: 'create one of the canonical output kinds, then hand-author advanced outputs',\n retryable: false,\n recoveryActions: ['choose-supported-output-kind'],\n requestId: operation.requestId,\n sourcePath: operation.sourcePath,\n }),\n );\n }\n try {\n await stat(target.value.absolute);\n return err(\n authoringError('pack-source-revision-conflict', {\n expected: 'an unused target source path',\n actual: 'source already exists',\n hint: 'inspect the existing source or choose a new path',\n retryable: false,\n recoveryActions: ['asset.preflight', 'choose-new-source-path'],\n requestId: operation.requestId,\n sourcePath: operation.sourcePath,\n }),\n );\n } catch {\n // Missing is the required create precondition.\n }\n manifest = {\n schemaVersion: '1.0.0',\n packageId: AssetGuidCodec.format(operation.packageId),\n ...(operation.name === undefined ? {} : { name: operation.name }),\n assets: {\n [operation.initialOutput.sourceKey]: {\n guid: AssetGuidCodec.format(operation.initialOutput.guid),\n kind: operation.initialOutput.kind,\n ...(operation.initialOutput.name === undefined\n ? {}\n : { name: operation.initialOutput.name }),\n },\n },\n externalAssets: {},\n };\n } else {\n const read = await readSource(operation.sourcePath);\n if (!read.ok) return read;\n currentRevision = read.value.revision;\n if (\n operation.expectedRevision !== undefined &&\n operation.expectedRevision !== currentRevision\n ) {\n return err(\n authoringError('pack-source-revision-conflict', {\n expected: operation.expectedRevision,\n actual: currentRevision,\n hint: 'inspect the current source revision, reconcile the edit, then retry with a new requestId',\n retryable: true,\n recoveryActions: ['asset.preflight', 'mint-request-id'],\n requestId: operation.requestId,\n sourcePath: operation.sourcePath,\n }),\n );\n }\n let parsed: CanonicalManifest | undefined;\n try {\n parsed = parseCanonicalManifest(read.value.source, read.value.relative);\n } catch (error) {\n return invalidCanonicalSource(read.value.relative, error);\n }\n if (parsed === undefined) {\n return err(\n authoringError('pack-source-mutation-unsupported', {\n expected: 'a canonical-v1 scaffold for structured source mutation',\n actual: 'custom ScriptablePack source',\n hint: 'clone into a canonical scaffold or edit custom source with a code editor',\n retryable: false,\n recoveryActions: ['clone-scriptable-pack', 'open-code-editor'],\n requestId: operation.requestId,\n sourcePath: operation.sourcePath,\n }),\n );\n }\n manifest = parsed;\n }\n\n if (operation.kind === 'clone-scriptable-pack') {\n try {\n await stat(target.value.absolute);\n return err(\n authoringError('pack-source-revision-conflict', {\n expected: 'an unused clone target source path',\n actual: 'source already exists',\n hint: 'inspect the existing target or choose a new path',\n retryable: false,\n recoveryActions: ['asset.preflight', 'choose-new-source-path'],\n requestId: operation.requestId,\n sourcePath: target.value.relative,\n }),\n );\n } catch {\n // Missing is the required clone precondition.\n }\n }\n\n if (operation.kind === 'add-output') {\n if (!CANONICAL_MUTABLE_KINDS.has(operation.assetKind)) {\n return err(\n authoringError('pack-source-mutation-unsupported', {\n expected: 'a canonical scene, mesh, or material output',\n actual: operation.assetKind,\n hint: 'hand-author advanced output kinds in the source module',\n retryable: false,\n recoveryActions: ['open-code-editor'],\n requestId: operation.requestId,\n sourcePath: operation.sourcePath,\n sourceKey: operation.sourceKey,\n }),\n );\n }\n manifest = {\n ...manifest,\n assets: {\n ...manifest.assets,\n [operation.sourceKey]: {\n guid: AssetGuidCodec.format(operation.guid),\n kind: operation.assetKind,\n ...(operation.name === undefined ? {} : { name: operation.name }),\n },\n },\n };\n } else if (operation.kind === 'add-external-asset') {\n manifest = {\n ...manifest,\n externalAssets: {\n ...manifest.externalAssets,\n [operation.alias]: AssetGuidCodec.format(operation.guid),\n },\n };\n } else if (operation.kind === 'rename-display') {\n if (operation.target.kind === 'package') manifest = { ...manifest, name: operation.name };\n else {\n const output = manifest.assets[operation.target.sourceKey];\n if (output === undefined)\n return err(\n authoringError('pack-source-mutation-unsupported', {\n expected: 'an existing sourceKey',\n actual: operation.target.sourceKey,\n hint: 'inspect Meta and choose a current output',\n retryable: true,\n recoveryActions: ['asset.preflight'],\n requestId: operation.requestId,\n sourcePath: operation.sourcePath,\n sourceKey: operation.target.sourceKey,\n }),\n );\n manifest = {\n ...manifest,\n assets: {\n ...manifest.assets,\n [operation.target.sourceKey]: { ...output, name: operation.name },\n },\n };\n }\n } else if (operation.kind === 'remove-output') {\n const incomingRefs =\n (await options.incomingRefs?.(operation.sourcePath, operation.sourceKey)) ?? [];\n if (\n incomingRefs.length > 0 &&\n !sameStrings(incomingRefs, operation.confirmIncomingRefs ?? [])\n ) {\n return err(\n authoringError('pack-source-reference-conflict', {\n expected: 'explicit acknowledgement of every current incoming reference',\n actual: `${incomingRefs.length} incoming references`,\n hint: 'inspect dependents, then confirm the exact incoming reference identities or cancel',\n retryable: true,\n recoveryActions: ['inspect-incoming-refs', 'confirm-remove-output'],\n requestId: operation.requestId,\n sourcePath: operation.sourcePath,\n sourceKey: operation.sourceKey,\n incomingRefs,\n }),\n );\n }\n const { [operation.sourceKey]: removed, ...assets } = manifest.assets;\n if (removed === undefined || Object.keys(assets).length === 0) {\n return err(\n authoringError('pack-source-mutation-unsupported', {\n expected: 'an existing output while retaining at least one package output',\n actual: operation.sourceKey,\n hint: 'keep one output or remove the entire source file through an explicit file operation',\n retryable: false,\n recoveryActions: ['asset.preflight'],\n requestId: operation.requestId,\n sourcePath: operation.sourcePath,\n sourceKey: operation.sourceKey,\n }),\n );\n }\n manifest = { ...manifest, assets };\n } else if (operation.kind === 'clone-scriptable-pack') {\n manifest = {\n ...manifest,\n packageId: AssetGuidCodec.format(operation.packageId),\n assets: Object.fromEntries(\n Object.entries(manifest.assets).map(([sourceKey, output]) => [\n sourceKey,\n {\n ...output,\n guid: AssetGuidCodec.format(operation.outputGuids[sourceKey] as AssetGuid),\n },\n ]),\n ),\n };\n }\n\n const source = renderCanonicalScriptablePack(manifest);\n try {\n await atomicWrite(target.value.absolute, source);\n return ok({ sourcePath: target.value.relative, revision: revisionOf(source) });\n } catch (error) {\n return err(\n authoringError('pack-source-write-failed', {\n expected: 'an atomic source-file replacement',\n actual: error instanceof Error ? error.message : String(error),\n hint: 'repair filesystem permissions or disk capacity, then retry with a new requestId',\n retryable: true,\n recoveryActions: ['inspect-filesystem', 'mint-request-id'],\n requestId: operation.requestId,\n sourcePath: target.value.relative,\n }),\n );\n }\n }\n\n return {\n preflight,\n mutate,\n inspect,\n async rebuild(sourcePath, mode) {\n const path = resolvePath(sourcePath);\n if (!path.ok) return path;\n const rebuilt = (await options.rebuild?.(path.value.relative, mode)) ?? ok(undefined);\n return rebuilt.ok ? inspect(path.value.relative) : rebuilt;\n },\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/guid.ts","../src/pack-authoring.ts","../src/evidence/source-inventory.ts","../src/scriptable-pack-node.ts"],"names":["resolve","dirname","readFile","createHash","failure","executor","err","ok"],"mappings":";;;;;;;;;;;;;;;AA2BO,IAAM,SAAA,GAAN,cAAwB,KAAA,CAAM;AAAA,EAC1B,IAAA;AAAA,EACA,QAAA;AAAA,EACA,IAAA;AAAA,EACA,MAAA;AAAA,EAET,YAAY,IAAA,EAKT;AACD,IAAA,KAAA,CAAM,CAAA,WAAA,EAAc,KAAK,IAAI,CAAA,YAAA,EAAe,KAAK,QAAQ,CAAA,QAAA,EAAW,IAAA,CAAK,IAAI,CAAA,CAAE,CAAA;AAC/E,IAAA,IAAA,CAAK,IAAA,GAAO,WAAA;AACZ,IAAA,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA;AACjB,IAAA,IAAA,CAAK,WAAW,IAAA,CAAK,QAAA;AACrB,IAAA,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA;AACjB,IAAA,IAAA,CAAK,SAAS,IAAA,CAAK,MAAA;AAAA,EACrB;AACF,CAAA;;;AC3BA,SAAS,MAAM,KAAA,EAA8B;AAC3C,EAAA,OAAO,KAAA;AACT;AAEA,IAAM,WAAW,KAAA,CAAM,IAA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;AACA,UAAA,IAAI,YAAA,KAAiB,KAAA,CAAA,EAAW,YAAA,CAAa,YAAY,CAAA;AAAA,QAC3D;AAAA,MACF;AAAA,KAC8B,CAAA;AAAA,EAClC,SAAS,KAAA,EAAO;AACd,IAAA,aAAA,GAAgB,SAAA;AAChB,IAAA,OAAOM,GAAAA;AAAA,MACL,yBAAA;AAAA,QACE,UAAA;AAAA,QACA,aAAA;AAAA,QACA,aAAA;AAAA,QACA,KAAA,YAAiB,KAAA,GAAQ,KAAA,CAAM,OAAA,GAAU,OAAO,KAAK;AAAA;AACvD,KACF;AAAA,EACF,CAAA,SAAE;AACA,IAAA,IAAI,OAAA,KAAY,MAAA,EAAW,YAAA,CAAa,OAAO,CAAA;AAC/C,IAAA,IAAI,aAAA,KAAkB,MAAA,EAAW,MAAM,QAAA,CAAS,UAAU,aAAa,CAAA;AAAA,EACzE;AACF","file":"scriptable-pack-node.mjs","sourcesContent":["// errors.ts — PackError class (feat-20260513-guid-asset-package-system w15)\n//\n// Four-field surface: .code / .expected / .hint / .detail\n// Structurally parallel to AssetError / RhiError / RemoteError\n// (charter proposition 5 consistent abstraction).\n//\n// .detail is narrowed per .code via PackErrorDetail discriminated union\n// (requirements §6.2 AC-07; plan-strategy §D-5).\n\nimport type { PackErrorCode, PackErrorDetail } from '@forgeax/engine-types';\n\n/**\n * Structured error for the engine-pack disk scanner fail-fast chain.\n *\n * AI users consume via exhaustive switch on .code — no default case needed:\n * ```ts\n * switch (err.code) {\n * case 'pack-guid-collision':\n * console.error(err.detail.paths);\n * break;\n * case 'pack-cyclic-reference':\n * console.error(err.detail.cycle);\n * break;\n * // ...all 8 cases\n * }\n * ```\n */\nexport class PackError extends Error {\n readonly code: PackErrorCode;\n readonly expected: string;\n readonly hint: string;\n readonly detail: PackErrorDetail;\n\n constructor(args: {\n code: PackErrorCode;\n expected: string;\n hint: string;\n detail: PackErrorDetail;\n }) {\n super(`[PackError ${args.code}] expected: ${args.expected}; hint: ${args.hint}`);\n this.name = 'PackError';\n this.code = args.code;\n this.expected = args.expected;\n this.hint = args.hint;\n this.detail = args.detail;\n }\n}\n","import { sha1 } from '@noble/hashes/legacy.js';\nimport { uuidv7obj } from 'uuidv7';\nimport { PackError } from './errors.js';\n\n/**\n * 16-byte UUID branded ABI. Prevents assignment from plain Uint8Array or string.\n * Brand field mirrors the declaration in @forgeax/engine-types for cross-package\n * structural compatibility (both use __guidBrand: 'AssetGuid').\n */\nexport type AssetGuid = Uint8Array & { readonly __guidBrand: 'AssetGuid' };\n\n/** Pack-level identity. It is intentionally not assignable to AssetGuid. */\nexport type PackageId = Uint8Array & { readonly __packageIdBrand: 'PackageId' };\n\n/** Minimal Result alias for this module (structurally compatible with ScanResult). */\nexport type GuidResult<T, E> =\n | { readonly ok: true; readonly value: T }\n | { readonly ok: false; readonly error: E };\n\nfunction brand(bytes: Uint8Array): AssetGuid {\n return bytes as AssetGuid;\n}\n\nconst HEX_BYTE = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n\nfunction bytesToDashForm(bytes: Uint8Array): string {\n const h = HEX_BYTE;\n // biome-ignore lint/style/noNonNullAssertion: length guaranteed 16\n return `${h[bytes[0]!]}${h[bytes[1]!]}${h[bytes[2]!]}${h[bytes[3]!]}-${h[bytes[4]!]}${h[bytes[5]!]}-${h[bytes[6]!]}${h[bytes[7]!]}-${h[bytes[8]!]}${h[bytes[9]!]}-${h[bytes[10]!]}${h[bytes[11]!]}${h[bytes[12]!]}${h[bytes[13]!]}${h[bytes[14]!]}${h[bytes[15]!]}`;\n}\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/** Stable author-owned output identity. Paths and payloads are not identity inputs. */\nexport const PACK_SOURCE_KEY_RE = /^[a-z0-9][a-z0-9._-]*(\\/[a-z0-9][a-z0-9._-]*)*$/;\n\nexport function isValidPackSourceKey(value: unknown): value is string {\n return typeof value === 'string' && PACK_SOURCE_KEY_RE.test(value);\n}\n\nexport function isValidAssetGuidString(value: unknown): value is string {\n return typeof value === 'string' && UUID_RE.test(value);\n}\n\nfunction dashFormToBytes(dashForm: string): Uint8Array {\n const hex = dashForm.replace(/-/g, '');\n const bytes = new Uint8Array(16);\n for (let i = 0; i < 16; i++) {\n bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);\n }\n return bytes;\n}\n\nfunction randomUuidBytes(): Uint8Array {\n const uuid = uuidv7obj();\n const bytes = new Uint8Array(16);\n bytes.set(uuid.bytes);\n return bytes;\n}\n\nfunction packageId(value: Uint8Array): PackageId {\n return value as PackageId;\n}\n\n/** Utilities for the pack-level UUID identity. */\nexport const PackageId = {\n parse(dashForm: string): GuidResult<PackageId, PackError> {\n const parsed = AssetGuid.parse(dashForm);\n return parsed.ok ? { ok: true, value: packageId(parsed.value) } : parsed;\n },\n format(value: PackageId): string {\n return bytesToDashForm(value);\n },\n random(): PackageId {\n return packageId(randomUuidBytes());\n },\n} as const;\n\nfunction derivedGuid(namespace: PackageId, sourceKey: string): AssetGuid {\n if (!(namespace instanceof Uint8Array) || namespace.byteLength !== 16) {\n throw new TypeError('AssetGuid.derive requires a 16-byte PackageId');\n }\n if (!isValidPackSourceKey(sourceKey)) {\n const error = new TypeError(\n `AssetGuid.derive received invalid sourceKey ${JSON.stringify(sourceKey)}`,\n ) as TypeError & { readonly code?: string };\n Object.defineProperty(error, 'code', { value: 'pack-source-key-invalid' });\n throw error;\n }\n const name = new TextEncoder().encode(sourceKey);\n const input = new Uint8Array(namespace.byteLength + name.byteLength);\n input.set(namespace, 0);\n input.set(name, namespace.byteLength);\n const digest = sha1(input);\n const result = digest.slice(0, 16);\n // RFC 4122 §4.1.1 / §4.1.3: UUID version 5, RFC variant.\n result[6] = ((result[6] ?? 0) & 0x0f) | 0x50;\n result[8] = ((result[8] ?? 0) & 0x3f) | 0x80;\n return brand(result);\n}\n\n/**\n * Utilities for the AssetGuid branded 16-byte UUID type.\n * Declare the type via `import type { AssetGuid } from '@forgeax/engine-pack/guid'`\n * or `import type { AssetGuid } from '@forgeax/engine-types'`.\n */\nexport const AssetGuid = {\n /**\n * Parse a 36-char RFC 4122 dash-form UUID string into an AssetGuid.\n * Returns Ok(AssetGuid) on success or Err(PackError) with code 'pack-guid-malformed' on failure.\n * Never throws for expected failures (requirements §4.2 / §14 / charter proposition 4).\n */\n parse(dashForm: string): GuidResult<AssetGuid, PackError> {\n if (!isValidAssetGuidString(dashForm)) {\n return {\n ok: false,\n error: new PackError({\n code: 'pack-guid-malformed',\n expected: '36-char RFC 4122 dash-form UUID',\n hint: 'use AssetGuid.random() or a UUIDv7 generator; all GUID fields must be 36-char RFC 4122 dash-form',\n detail: {\n raw: dashForm,\n reason: 'expected 36-char RFC 4122 dash-form UUID',\n },\n }),\n };\n }\n return { ok: true, value: brand(dashFormToBytes(dashForm)) };\n },\n\n /**\n * Format an AssetGuid as a 36-char RFC 4122 lowercase dash-form string.\n */\n format(guid: AssetGuid): string {\n return bytesToDashForm(guid);\n },\n\n /**\n * Test byte-by-byte equality between two AssetGuids.\n */\n equals(a: AssetGuid, b: AssetGuid): boolean {\n for (let i = 0; i < 16; i++) {\n if (a[i] !== b[i]) return false;\n }\n return true;\n },\n\n /**\n * Mint a new time-ordered UUIDv7 as an AssetGuid.\n * Works in both Node.js and browser environments.\n */\n random(): AssetGuid {\n return brand(randomUuidBytes());\n },\n\n /** Derive the stable UUIDv5 projection for one Pack subject and sourceKey. */\n derive(namespace: PackageId, sourceKey: string): AssetGuid {\n return derivedGuid(namespace, sourceKey);\n },\n} as const;\n","import type { Asset, AssetGuid, Result } from '@forgeax/engine-types';\nimport { err, ok } from '@forgeax/engine-types';\nimport {\n AssetGuid as AssetGuidCodec,\n isValidAssetGuidString,\n isValidPackSourceKey,\n PackageId,\n} from './guid.js';\nimport type { ScriptablePackSceneComponentInput } from './scriptable-pack.js';\n\n/** Values deliberately stay finite and serialisable at the authoring boundary. */\nexport type PackParameterScalar = boolean | number | string;\nexport type PackParameterValue = PackParameterScalar | readonly number[] | AssetGuid;\n\nexport type PackParameterType =\n | 'bool'\n | 'u32'\n | 'i32'\n | 'f32'\n | 'f64'\n | 'string'\n | 'enum'\n | 'vec2'\n | 'vec3'\n | 'vec4'\n | 'color'\n | 'asset-guid';\n\nexport const PACK_PARAMETER_TYPES = [\n 'bool',\n 'u32',\n 'i32',\n 'f32',\n 'f64',\n 'string',\n 'enum',\n 'vec2',\n 'vec3',\n 'vec4',\n 'color',\n 'asset-guid',\n] as const satisfies readonly PackParameterType[];\n\nexport interface PackParameterDefinition<\n TName extends string = string,\n TType extends PackParameterType = PackParameterType,\n TDefault extends PackParameterValue = PackParameterValue,\n> {\n readonly name: TName;\n readonly type: TType;\n readonly default: TDefault;\n readonly minimum?: number;\n readonly maximum?: number;\n /** Closed choices are required for `enum` and forbidden for other types. */\n readonly values?: readonly PackParameterScalar[];\n /** Optional authoring-only kind constraint for asset GUID parameters. */\n readonly kind?: Asset['kind'];\n}\n\nexport type PackParameterValueFor<T extends PackParameterType> = T extends 'bool'\n ? boolean\n : T extends 'u32' | 'i32' | 'f32' | 'f64'\n ? number\n : T extends 'string' | 'enum'\n ? string\n : T extends 'vec2'\n ? readonly [number, number]\n : T extends 'vec3'\n ? readonly [number, number, number]\n : T extends 'vec4' | 'color'\n ? readonly [number, number, number, number]\n : T extends 'asset-guid'\n ? AssetGuid\n : never;\n\nexport type PackParameterValues<TParameters extends readonly PackParameterDefinition[]> = Readonly<{\n [TParameter in TParameters[number] as TParameter['name']]: TParameter extends {\n readonly type: infer TType extends PackParameterType;\n }\n ? TType extends 'enum'\n ? TParameter extends { readonly values: readonly (infer TValue)[] }\n ? Extract<TValue, string>\n : string\n : PackParameterValueFor<TType>\n : never;\n}>;\n\nexport interface PackAuthoringError {\n readonly code: PackAuthoringErrorCode;\n readonly expected: string;\n readonly hint: string;\n readonly actual?: string;\n readonly detail: Readonly<Record<string, unknown>>;\n}\n\nexport type PackAuthoringErrorCode =\n | 'pack-package-id-invalid'\n | 'pack-package-id-collision'\n | 'pack-source-key-invalid'\n | 'pack-guid-collision'\n | 'pack-parent-not-found'\n | 'pack-parent-cycle'\n | 'pack-parent-has-no-parameters'\n | 'pack-parameter-invalid'\n | 'pack-content-dependency-stalled'\n | 'pack-output-reference-missing'\n | 'pack-output-reference-conflict'\n | 'pack-output-not-materialized'\n | 'asset-not-ready'\n | 'pack-source-revision-conflict'\n | 'pack-source-path-invalid'\n | 'pack-source-not-found'\n | 'pack-source-mutation-unsupported'\n | 'pack-source-write-failed';\n\nfunction authoringError(\n code: PackAuthoringErrorCode,\n expected: string,\n hint: string,\n detail: Readonly<Record<string, unknown>> = {},\n actual?: string,\n): PackAuthoringError {\n return {\n code,\n expected,\n hint,\n ...(actual === undefined ? {} : { actual }),\n detail,\n };\n}\n\nfunction failure<T = never>(error: PackAuthoringError): Result<T, PackAuthoringError> {\n return err(error);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction validateSceneComponents(\n value: unknown,\n): Result<readonly ScriptablePackSceneComponentInput[] | undefined, PackAuthoringError> {\n if (value === undefined) return ok(undefined);\n if (!Array.isArray(value)) {\n return failure(\n parameterFailure(\n '$.sceneComponents',\n 'an array of component schema records',\n value,\n 'sceneComponents is not an array',\n ),\n );\n }\n const components: ScriptablePackSceneComponentInput[] = [];\n const names = new Set<string>();\n for (const [componentIndex, candidate] of value.entries()) {\n if (!isRecord(candidate) || typeof candidate.name !== 'string' || !isRecord(candidate.fields)) {\n return failure(\n parameterFailure(\n `$.sceneComponents[${componentIndex}]`,\n 'a component record with name and fields',\n candidate,\n 'scene component schema is malformed',\n ),\n );\n }\n if (candidate.name.length === 0 || names.has(candidate.name)) {\n return failure(\n parameterFailure(\n `$.sceneComponents[${componentIndex}].name`,\n 'a non-empty unique component name',\n candidate.name,\n 'scene component names must be unique',\n ),\n );\n }\n names.add(candidate.name);\n const fields: Record<string, string | { readonly type: string }> = {};\n for (const [fieldName, field] of Object.entries(candidate.fields)) {\n if (\n (typeof field === 'string' && field.length === 0) ||\n (typeof field !== 'string' &&\n (!isRecord(field) || typeof field.type !== 'string' || field.type.length === 0))\n ) {\n return failure(\n parameterFailure(\n `$.sceneComponents[${componentIndex}].fields.${fieldName}`,\n 'a field type string or { type: string }',\n field,\n 'scene component field schema is malformed',\n ),\n );\n }\n fields[fieldName] = field as string | { readonly type: string };\n }\n components.push({ name: candidate.name, fields });\n }\n return ok(components);\n}\n\nfunction isPackageId(value: unknown): value is PackageId {\n return value instanceof Uint8Array && value.byteLength === 16;\n}\n\nfunction cloneValue<T>(value: T): T {\n if (value instanceof Uint8Array) return value.slice() as T;\n if (Array.isArray(value)) return value.map((item) => cloneValue(item)) as T;\n return value;\n}\n\nfunction sourceKeyFailure(sourceKey: unknown, propertyPath = '$.sourceKey'): PackAuthoringError {\n return authoringError(\n 'pack-source-key-invalid',\n 'a sourceKey matching ^[a-z0-9][a-z0-9._-]*(/[a-z0-9][a-z0-9._-]*)*$',\n 'use a stable lower-case semantic key; do not derive it from file paths or output order',\n { propertyPath, sourceKey },\n typeof sourceKey === 'string' ? sourceKey : undefined,\n );\n}\n\nfunction parameterFailure(\n propertyPath: string,\n expected: string,\n actual: unknown,\n reason: string,\n): PackAuthoringError {\n return authoringError(\n 'pack-parameter-invalid',\n expected,\n 'repair the parameter declaration or the instance values, then inspect and rebuild',\n { propertyPath, reason, actual: typeof actual === 'string' ? actual : JSON.stringify(actual) },\n );\n}\n\nfunction numericType(type: PackParameterType): boolean {\n return type === 'u32' || type === 'i32' || type === 'f32' || type === 'f64';\n}\n\nfunction vectorLength(type: PackParameterType): number | undefined {\n switch (type) {\n case 'vec2':\n return 2;\n case 'vec3':\n return 3;\n case 'vec4':\n case 'color':\n return 4;\n default:\n return undefined;\n }\n}\n\nfunction parameterValueError(\n parameter: PackParameterDefinition,\n value: unknown,\n propertyPath: string,\n): PackAuthoringError | undefined {\n const { type } = parameter;\n if (type === 'bool' && typeof value !== 'boolean') {\n return parameterFailure(propertyPath, 'a boolean', value, 'bool value has the wrong type');\n }\n if (numericType(type)) {\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n return parameterFailure(\n propertyPath,\n 'a finite number',\n value,\n 'numeric value is not finite',\n );\n }\n if ((type === 'u32' || type === 'i32') && !Number.isInteger(value)) {\n return parameterFailure(\n propertyPath,\n 'an integer',\n value,\n 'integer parameter received a fraction',\n );\n }\n if (type === 'u32' && (value < 0 || value > 0xffff_ffff)) {\n return parameterFailure(\n propertyPath,\n 'an unsigned 32-bit integer',\n value,\n 'u32 value is outside [0, 2^32 - 1]',\n );\n }\n if (type === 'i32' && (value < -0x8000_0000 || value > 0x7fff_ffff)) {\n return parameterFailure(\n propertyPath,\n 'a signed 32-bit integer',\n value,\n 'i32 value is outside [-2^31, 2^31 - 1]',\n );\n }\n if (type === 'f32' && !Number.isFinite(Math.fround(value))) {\n return parameterFailure(\n propertyPath,\n 'a finite IEEE-754 32-bit float',\n value,\n 'f32 value overflows binary32',\n );\n }\n if (parameter.minimum !== undefined && value < parameter.minimum) {\n return parameterFailure(\n propertyPath,\n `a number >= ${parameter.minimum}`,\n value,\n 'value is below minimum',\n );\n }\n if (parameter.maximum !== undefined && value > parameter.maximum) {\n return parameterFailure(\n propertyPath,\n `a number <= ${parameter.maximum}`,\n value,\n 'value is above maximum',\n );\n }\n return undefined;\n }\n if (type === 'string' && typeof value !== 'string') {\n return parameterFailure(propertyPath, 'a string', value, 'string parameter has the wrong type');\n }\n if (type === 'enum') {\n if (typeof value !== 'string') {\n return parameterFailure(\n propertyPath,\n 'one of the declared enum strings',\n value,\n 'enum value has the wrong type',\n );\n }\n if (parameter.values === undefined || !parameter.values.includes(value)) {\n return parameterFailure(\n propertyPath,\n 'one of the declared enum values',\n value,\n 'enum value is not declared',\n );\n }\n return undefined;\n }\n const length = vectorLength(type);\n if (length !== undefined) {\n if (\n !Array.isArray(value) ||\n value.length !== length ||\n value.some((component) => typeof component !== 'number' || !Number.isFinite(component))\n ) {\n return parameterFailure(\n propertyPath,\n `a finite numeric vector with ${length} components`,\n value,\n 'vector value has the wrong shape',\n );\n }\n if (type === 'color' && value.some((component) => component < 0 || component > 1)) {\n return parameterFailure(\n propertyPath,\n 'an RGBA color with components in [0, 1]',\n value,\n 'color component is outside [0, 1]',\n );\n }\n return undefined;\n }\n if (type === 'asset-guid') {\n const validString = typeof value === 'string' && isValidAssetGuidString(value);\n if (!(value instanceof Uint8Array && value.byteLength === 16) && !validString) {\n return parameterFailure(\n propertyPath,\n 'a 16-byte AssetGuid or UUID string',\n value,\n 'asset GUID value is malformed',\n );\n }\n return undefined;\n }\n return parameterFailure(\n propertyPath,\n 'a supported Pack parameter type',\n value,\n 'unknown parameter type',\n );\n}\n\nfunction normalizeParameterValue(\n parameter: PackParameterDefinition,\n value: unknown,\n propertyPath: string,\n): Result<PackParameterValue, PackAuthoringError> {\n const error = parameterValueError(parameter, value, propertyPath);\n if (error !== undefined) return failure(error);\n if (parameter.type === 'asset-guid' && typeof value === 'string') {\n const parsed = AssetGuidCodec.parse(value);\n if (!parsed.ok) {\n return failure(\n parameterFailure(\n propertyPath,\n 'a valid AssetGuid UUID string',\n value,\n 'asset GUID parser rejected the value',\n ),\n );\n }\n return ok(parsed.value);\n }\n return ok(cloneValue(value as PackParameterValue));\n}\n\nfunction validateParameterDefinitions(\n parameters: unknown,\n propertyPath = '$.parameters',\n): Result<readonly PackParameterDefinition[], PackAuthoringError> {\n if (!Array.isArray(parameters) || parameters.length === 0) {\n return failure(\n parameterFailure(\n propertyPath,\n 'a non-empty parameter descriptor array',\n parameters,\n 'parameters must be explicit and non-empty',\n ),\n );\n }\n const names = new Set<string>();\n const normalized: PackParameterDefinition[] = [];\n for (const [index, candidate] of parameters.entries()) {\n const path = `${propertyPath}[${index}]`;\n if (!isRecord(candidate))\n return failure(\n parameterFailure(\n path,\n 'a parameter descriptor object',\n candidate,\n 'descriptor is not an object',\n ),\n );\n const name = candidate.name;\n if (typeof name !== 'string' || !/^[A-Za-z][A-Za-z0-9_.-]*$/.test(name)) {\n return failure(\n parameterFailure(\n `${path}.name`,\n 'a unique identifier-like parameter name',\n name,\n 'parameter name is invalid',\n ),\n );\n }\n if (names.has(name))\n return failure(\n parameterFailure(\n `${path}.name`,\n 'a unique parameter name',\n name,\n 'parameter name is duplicated',\n ),\n );\n names.add(name);\n const unknown = Object.keys(candidate).find(\n (key) => !['name', 'type', 'default', 'minimum', 'maximum', 'values', 'kind'].includes(key),\n );\n if (unknown !== undefined) {\n return failure(\n parameterFailure(\n `${path}.${unknown}`,\n 'only name, type, default, minimum, maximum, values, and kind fields',\n candidate[unknown],\n 'parameter descriptors are a closed authoring schema',\n ),\n );\n }\n const type = candidate.type;\n if (typeof type !== 'string' || !(PACK_PARAMETER_TYPES as readonly string[]).includes(type)) {\n return failure(\n parameterFailure(\n `${path}.type`,\n PACK_PARAMETER_TYPES.join(' | '),\n type,\n 'parameter type is not supported',\n ),\n );\n }\n const typed = {\n ...candidate,\n name,\n type: type as PackParameterType,\n } as PackParameterDefinition;\n if (typed.values !== undefined) {\n if (\n typed.type !== 'enum' ||\n !Array.isArray(typed.values) ||\n typed.values.length === 0 ||\n typed.values.some((item) => typeof item !== 'string') ||\n new Set(typed.values).size !== typed.values.length\n ) {\n return failure(\n parameterFailure(\n `${path}.values`,\n 'unique non-empty strings for enum',\n typed.values,\n 'enum values are malformed',\n ),\n );\n }\n } else if (typed.type === 'enum') {\n return failure(\n parameterFailure(\n `${path}.values`,\n 'a non-empty enum choices array',\n typed.values,\n 'enum has no choices',\n ),\n );\n }\n if (\n typed.kind !== undefined &&\n (typed.type !== 'asset-guid' || typeof typed.kind !== 'string')\n ) {\n return failure(\n parameterFailure(\n `${path}.kind`,\n 'a kind constraint only on asset-guid parameters',\n typed.kind,\n 'kind is misplaced',\n ),\n );\n }\n for (const field of ['minimum', 'maximum'] as const) {\n const bound = typed[field];\n if (bound !== undefined && (typeof bound !== 'number' || !Number.isFinite(bound))) {\n return failure(\n parameterFailure(\n `${path}.${field}`,\n 'a finite numeric bound',\n bound,\n 'numeric bound is invalid',\n ),\n );\n }\n }\n if (!numericType(typed.type) && (typed.minimum !== undefined || typed.maximum !== undefined)) {\n return failure(\n parameterFailure(\n path,\n 'minimum/maximum only on numeric parameters',\n typed,\n 'numeric bounds are not meaningful for this parameter type',\n ),\n );\n }\n if (\n typed.minimum !== undefined &&\n typed.maximum !== undefined &&\n typed.minimum > typed.maximum\n ) {\n return failure(\n parameterFailure(path, 'minimum <= maximum', typed, 'numeric bounds are reversed'),\n );\n }\n const defaultResult = normalizeParameterValue(typed, typed.default, `${path}.default`);\n if (!defaultResult.ok) return defaultResult;\n normalized.push({\n ...typed,\n default: defaultResult.value,\n ...(typed.values === undefined ? {} : { values: Object.freeze([...typed.values]) }),\n });\n }\n return ok(Object.freeze(normalized));\n}\n\nexport interface PackBuildReadContext {\n readByGuid<TAsset extends Asset = Asset>(guid: AssetGuid): Promise<Result<TAsset, unknown>>;\n}\n\nexport interface PackBuildContextWithoutParameters extends PackBuildReadContext {\n readonly packageId: PackageId;\n}\n\nexport interface PackBuildContextWithParameters<\n TParameters extends readonly PackParameterDefinition[],\n> extends PackBuildReadContext {\n readonly packageId: PackageId;\n readonly values: PackParameterValues<TParameters>;\n}\n\nexport type PackBuildContext<TParameters extends readonly PackParameterDefinition[] | undefined> =\n TParameters extends readonly PackParameterDefinition[]\n ? PackBuildContextWithParameters<TParameters>\n : PackBuildContextWithoutParameters;\n\nexport type PackOutputMap = Readonly<Record<string, Asset>>;\nexport type PackBuildResult<TError = unknown> =\n | Result<PackOutputMap, TError>\n | Promise<Result<PackOutputMap, TError>>;\n\ninterface PackDefinitionBase {\n readonly schemaVersion: '2.0.0';\n readonly packageId: PackageId;\n readonly name?: string;\n /** Neutral component schemas used only to externalize SceneAsset refs at cook time. */\n readonly sceneComponents?: readonly ScriptablePackSceneComponentInput[];\n}\n\nexport type ScriptablePackDefinition<\n TParameters extends readonly PackParameterDefinition[] | undefined = undefined,\n> = PackDefinitionBase &\n (TParameters extends readonly PackParameterDefinition[]\n ? {\n readonly parameters: TParameters;\n readonly build: (context: PackBuildContextWithParameters<TParameters>) => PackBuildResult;\n }\n : {\n readonly build: (context: PackBuildContextWithoutParameters) => PackBuildResult;\n });\n\nexport type PackParameterList = readonly [PackParameterDefinition, ...PackParameterDefinition[]];\ntype NonEmptyParameters = PackParameterList;\ntype NoParameterPackInput = PackDefinitionBase & {\n readonly parameters?: never;\n readonly build: (context: PackBuildContextWithoutParameters) => PackBuildResult;\n};\ntype ScriptablePackDefinitionInput<TParameters extends NonEmptyParameters> = PackDefinitionBase & {\n readonly parameters: TParameters;\n readonly build: (context: PackBuildContextWithParameters<TParameters>) => PackBuildResult;\n};\n\n/** Convert a UUID literal into the distinct Pack-level identity brand. */\nexport function definePackageId(value: string | PackageId): PackageId {\n if (isPackageId(value)) return value.slice() as PackageId;\n const parsed = PackageId.parse(value);\n if (!parsed.ok) {\n const error = authoringError(\n 'pack-package-id-invalid',\n 'a 36-character RFC 4122 UUID packageId',\n 'use PackageId.random() or repair the packageId literal before loading the Pack',\n { value },\n value,\n );\n throw Object.assign(new TypeError(error.hint), error);\n }\n return parsed.value;\n}\n\nfunction cloneDefinition(\n definition: ScriptablePackDefinition<NonEmptyParameters> | ScriptablePackDefinition<undefined>,\n): ScriptablePackDefinition<NonEmptyParameters> | ScriptablePackDefinition<undefined> {\n const parameters =\n 'parameters' in definition\n ? Object.freeze(\n definition.parameters.map((parameter) =>\n Object.freeze({\n ...parameter,\n default: cloneValue(parameter.default),\n ...(parameter.values === undefined\n ? {}\n : { values: Object.freeze(parameter.values.map((value) => cloneValue(value))) }),\n }),\n ),\n )\n : undefined;\n const sceneComponents =\n definition.sceneComponents === undefined\n ? undefined\n : Object.freeze(\n definition.sceneComponents.map((component) =>\n Object.freeze({\n name: component.name,\n fields: Object.freeze({ ...component.fields }),\n }),\n ),\n );\n return Object.freeze({\n ...definition,\n packageId: definition.packageId.slice() as PackageId,\n ...(parameters === undefined ? {} : { parameters }),\n ...(sceneComponents === undefined ? {} : { sceneComponents }),\n }) as ScriptablePackDefinition<NonEmptyParameters> | ScriptablePackDefinition<undefined>;\n}\n\n/**\n * Define the only executable authoring shape. A missing `parameters` property\n * is meaningful: its build context has no `values` member.\n */\nexport function definePack(definition: NoParameterPackInput): ScriptablePackDefinition<undefined>;\nexport function definePack<const TParameters extends NonEmptyParameters>(\n definition: ScriptablePackDefinitionInput<TParameters>,\n): ScriptablePackDefinition<TParameters>;\nexport function definePack(\n definition: NoParameterPackInput | ScriptablePackDefinitionInput<NonEmptyParameters>,\n): ScriptablePackDefinition<NonEmptyParameters> | ScriptablePackDefinition<undefined> {\n const validated = validatePackDefinition(definition);\n if (!validated.ok) throw Object.assign(new TypeError(validated.error.hint), validated.error);\n return cloneDefinition(\n validated.value as\n | ScriptablePackDefinition<NonEmptyParameters>\n | ScriptablePackDefinition<undefined>,\n );\n}\n\n/** Union used only at orchestration boundaries that accept either source form. */\nexport type AnyScriptablePackDefinition =\n | ScriptablePackDefinition<PackParameterList>\n | ScriptablePackDefinition<undefined>;\n\nexport interface ScriptablePackSourceMeta {\n readonly schemaVersion: '2.0.0';\n readonly kind: 'scriptable-pack-source';\n readonly packageId: string;\n readonly source: string;\n readonly parameters?: readonly Readonly<Record<string, unknown>>[];\n}\n\n/** Ephemeral scan evidence; it intentionally contains no output GUID table. */\nexport function projectScriptablePackMeta(\n definition: AnyScriptablePackDefinition,\n sourcePath: string,\n): ScriptablePackSourceMeta {\n return {\n schemaVersion: '2.0.0',\n kind: 'scriptable-pack-source',\n packageId: PackageId.format(definition.packageId),\n source: sourcePath,\n ...('parameters' in definition\n ? {\n parameters: definition.parameters.map((parameter) => ({\n name: parameter.name,\n type: parameter.type,\n default: jsonParameterValue(parameter.default),\n ...(parameter.minimum === undefined ? {} : { minimum: parameter.minimum }),\n ...(parameter.maximum === undefined ? {} : { maximum: parameter.maximum }),\n ...(parameter.values === undefined ? {} : { values: parameter.values }),\n ...(parameter.kind === undefined ? {} : { kind: parameter.kind }),\n })),\n }\n : {}),\n };\n}\n\nfunction jsonParameterValue(value: PackParameterValue): unknown {\n return value instanceof Uint8Array ? AssetGuidCodec.format(value) : value;\n}\n\n/** Runtime validation used by the isolated module loader and source scanner. */\nexport function validatePackDefinition(\n value: unknown,\n sourcePath?: string,\n): Result<\n ScriptablePackDefinition<NonEmptyParameters> | ScriptablePackDefinition<undefined>,\n PackAuthoringError\n> {\n if (!isRecord(value))\n return failure(\n parameterFailure('$', 'a Pack definition object', value, 'definition is not an object'),\n );\n const unknown = Object.keys(value).find(\n (key) =>\n !['schemaVersion', 'packageId', 'name', 'parameters', 'sceneComponents', 'build'].includes(\n key,\n ),\n );\n if (unknown !== undefined) {\n return failure(\n parameterFailure(\n `$.${unknown}`,\n 'only schemaVersion, packageId, name, parameters, sceneComponents, and build fields',\n value[unknown],\n 'legacy static output declarations and external asset tables are not part of v2 authoring',\n ),\n );\n }\n if (value.schemaVersion !== '2.0.0') {\n return failure(\n parameterFailure(\n '$.schemaVersion',\n \"the literal '2.0.0'\",\n value.schemaVersion,\n 'authoring source schema is unsupported',\n ),\n );\n }\n if (!isPackageId(value.packageId)) {\n return failure(\n authoringError(\n 'pack-package-id-invalid',\n 'a 16-byte PackageId',\n 'use definePackageId() for the stable source identity',\n { sourcePath, propertyPath: '$.packageId' },\n typeof value.packageId === 'string' ? value.packageId : undefined,\n ),\n );\n }\n if (value.name !== undefined && typeof value.name !== 'string') {\n return failure(\n parameterFailure('$.name', 'a string when present', value.name, 'display name is malformed'),\n );\n }\n if (typeof value.build !== 'function') {\n return failure(\n parameterFailure('$.build', 'a build function', value.build, 'build is not callable'),\n );\n }\n const sceneComponents = validateSceneComponents(value.sceneComponents);\n if (!sceneComponents.ok) return sceneComponents;\n const hasParameters = Object.hasOwn(value, 'parameters');\n if (!hasParameters) {\n return ok(\n Object.freeze({\n schemaVersion: '2.0.0',\n packageId: value.packageId,\n ...(value.name === undefined ? {} : { name: value.name }),\n ...(sceneComponents.value === undefined ? {} : { sceneComponents: sceneComponents.value }),\n build: value.build,\n }) as ScriptablePackDefinition<undefined>,\n );\n }\n const parameters = validateParameterDefinitions(value.parameters);\n if (!parameters.ok) return parameters;\n return ok(\n Object.freeze({\n schemaVersion: '2.0.0',\n packageId: value.packageId,\n ...(value.name === undefined ? {} : { name: value.name }),\n ...(sceneComponents.value === undefined ? {} : { sceneComponents: sceneComponents.value }),\n parameters: parameters.value,\n build: value.build,\n }) as ScriptablePackDefinition<NonEmptyParameters>,\n );\n}\n\nexport function hasPackParameters(\n value: ScriptablePackDefinition | unknown,\n): value is ScriptablePackDefinition<NonEmptyParameters> {\n return isRecord(value) && Array.isArray(value.parameters) && value.parameters.length > 0;\n}\n\n/** Resolve defaults plus a sparse instance override with shallow replacement. */\nexport function resolvePackParameterValues(\n definition: ScriptablePackDefinition<NonEmptyParameters>,\n overrides: unknown = {},\n inheritedValues?: Readonly<Record<string, PackParameterValue>>,\n): Result<PackParameterValues<NonEmptyParameters>, PackAuthoringError> {\n if (!isRecord(overrides)) {\n return failure(\n parameterFailure(\n '$.values',\n 'an object of sparse parameter overrides',\n overrides,\n 'values is not an object',\n ),\n );\n }\n const descriptors = new Map(\n definition.parameters.map((parameter) => [parameter.name, parameter]),\n );\n for (const name of Object.keys(overrides)) {\n if (!descriptors.has(name)) {\n return failure(\n parameterFailure(\n `$.values.${name}`,\n 'a declared parameter name',\n name,\n 'instance contains an unknown parameter',\n ),\n );\n }\n }\n const values: Record<string, PackParameterValue> = {};\n for (const parameter of definition.parameters) {\n const raw = Object.hasOwn(overrides, parameter.name)\n ? overrides[parameter.name]\n : (inheritedValues?.[parameter.name] ?? parameter.default);\n const normalized = normalizeParameterValue(parameter, raw, `$.values.${parameter.name}`);\n if (!normalized.ok) return normalized;\n values[parameter.name] = normalized.value;\n }\n return ok(Object.freeze(values) as PackParameterValues<NonEmptyParameters>);\n}\n\nexport interface DirectPackJsonAsset {\n readonly kind: string;\n readonly payload: Readonly<Record<string, unknown>>;\n readonly refs: readonly string[];\n readonly name?: string;\n readonly artifacts?: Readonly<Record<string, Readonly<Record<string, unknown>>>>;\n}\n\nexport interface DirectPackJson {\n readonly schemaVersion: '3.0.0';\n readonly packageId: string;\n readonly assets: Readonly<Record<string, DirectPackJsonAsset>>;\n}\n\nexport interface PackInstanceJson {\n readonly schemaVersion: '3.0.0';\n readonly packageId: string;\n readonly parent: string;\n readonly values: Readonly<Record<string, unknown>>;\n}\n\nexport interface ParsedDirectPackJson {\n readonly format: 'direct';\n readonly schemaVersion: '3.0.0';\n readonly packageId: PackageId;\n readonly assets: Readonly<Record<string, DirectPackJsonAsset>>;\n}\n\nexport interface ParsedPackInstanceJson {\n readonly format: 'instance';\n readonly schemaVersion: '3.0.0';\n readonly packageId: PackageId;\n readonly parent: PackageId;\n readonly values: Readonly<Record<string, unknown>>;\n}\n\nexport type ParsedPackJson = ParsedDirectPackJson | ParsedPackInstanceJson;\n\nfunction jsonError(\n propertyPath: string,\n expected: string,\n actual: unknown,\n reason: string,\n): Result<never, PackAuthoringError> {\n return failure(\n authoringError(\n 'pack-parameter-invalid',\n expected,\n 'repair the v3 pack.json authoring data, then rerun scan or rebuild',\n {\n propertyPath,\n reason,\n actual: typeof actual === 'string' ? actual : JSON.stringify(actual),\n },\n ),\n );\n}\n\nfunction parsePackageId(\n value: unknown,\n propertyPath: string,\n): Result<PackageId, PackAuthoringError> {\n if (typeof value !== 'string') {\n return failure(\n authoringError(\n 'pack-package-id-invalid',\n 'a UUID string',\n 'repair packageId in the authoring file',\n { propertyPath, value },\n ),\n );\n }\n const parsed = PackageId.parse(value);\n if (!parsed.ok) {\n return failure(\n authoringError(\n 'pack-package-id-invalid',\n 'a 36-character RFC 4122 UUID',\n 'repair packageId or use the authoring gateway to mint one',\n { propertyPath, value },\n value,\n ),\n );\n }\n return ok(parsed.value);\n}\n\nfunction parsePackJsonAsset(\n value: unknown,\n sourceKey: string,\n): Result<DirectPackJsonAsset, PackAuthoringError> {\n if (!isRecord(value))\n return jsonError(\n `$.assets.${sourceKey}`,\n 'an asset entry object',\n value,\n 'asset entry is not an object',\n );\n const allowed = new Set(['kind', 'payload', 'refs', 'name', 'artifacts']);\n const unknown = Object.keys(value).find((key) => !allowed.has(key));\n if (unknown !== undefined)\n return jsonError(\n `$.assets.${sourceKey}.${unknown}`,\n 'no GUID or extra authoring field',\n value[unknown],\n 'direct v3 entries derive identity from their object key',\n );\n if (typeof value.kind !== 'string' || value.kind.length === 0)\n return jsonError(\n `$.assets.${sourceKey}.kind`,\n 'a non-empty asset kind',\n value.kind,\n 'asset kind is missing',\n );\n if (!isRecord(value.payload))\n return jsonError(\n `$.assets.${sourceKey}.payload`,\n 'a JSON object payload',\n value.payload,\n 'payload must be a plain object',\n );\n if (\n !Array.isArray(value.refs) ||\n value.refs.some((ref) => typeof ref !== 'string' || !isValidAssetGuidString(ref))\n ) {\n return jsonError(\n `$.assets.${sourceKey}.refs`,\n 'an array of UUID references',\n value.refs,\n 'references must already be real AssetGuids',\n );\n }\n if (value.name !== undefined && (typeof value.name !== 'string' || value.name.length === 0))\n return jsonError(\n `$.assets.${sourceKey}.name`,\n 'a non-empty display name when present',\n value.name,\n 'asset name is malformed',\n );\n if (value.artifacts !== undefined && !isRecord(value.artifacts))\n return jsonError(\n `$.assets.${sourceKey}.artifacts`,\n 'an artifact descriptor object when present',\n value.artifacts,\n 'artifacts are not an object',\n );\n const base: DirectPackJsonAsset = {\n kind: value.kind,\n payload: value.payload,\n refs: Object.freeze([...value.refs]) as readonly string[],\n ...(value.name === undefined ? {} : { name: value.name }),\n };\n if (value.artifacts === undefined) return ok(base);\n const withArtifacts: DirectPackJsonAsset = {\n ...base,\n artifacts: value.artifacts as NonNullable<DirectPackJsonAsset['artifacts']>,\n };\n return ok(withArtifacts);\n}\n\n/** Parse the two mutually exclusive v3 pack.json branches. */\nexport function parsePackSourceJson(value: unknown): Result<ParsedPackJson, PackAuthoringError> {\n if (!isRecord(value))\n return jsonError('$', 'a v3 pack.json object', value, 'document is not an object');\n if (value.schemaVersion !== '3.0.0')\n return jsonError(\n '$.schemaVersion',\n \"the literal '3.0.0'\",\n value.schemaVersion,\n 'document schema is not v3',\n );\n const unknown = Object.keys(value).find(\n (key) => !['schemaVersion', 'packageId', 'assets', 'parent', 'values'].includes(key),\n );\n if (unknown !== undefined)\n return jsonError(\n `$.${unknown}`,\n 'no extra top-level authoring fields',\n value[unknown],\n 'keep the v3 document to packageId+assets or packageId+parent+values',\n );\n const packageResult = parsePackageId(value.packageId, '$.packageId');\n if (!packageResult.ok) return packageResult;\n const hasAssets = Object.hasOwn(value, 'assets');\n const hasParent = Object.hasOwn(value, 'parent');\n const hasValues = Object.hasOwn(value, 'values');\n if (hasAssets && (hasParent || hasValues))\n return jsonError(\n '$',\n 'assets or parent+values, never both',\n value,\n 'direct and instance branches are mutually exclusive',\n );\n if (hasAssets) {\n if (!isRecord(value.assets))\n return jsonError(\n '$.assets',\n 'a sourceKey to asset object',\n value.assets,\n 'direct assets are not an object',\n );\n const assets: Record<string, DirectPackJsonAsset> = {};\n for (const [sourceKey, entry] of Object.entries(value.assets)) {\n if (!isValidPackSourceKey(sourceKey))\n return failure(sourceKeyFailure(sourceKey, `$.assets.${sourceKey}`));\n const parsed = parsePackJsonAsset(entry, sourceKey);\n if (!parsed.ok) return parsed;\n assets[sourceKey] = parsed.value;\n }\n return ok({\n format: 'direct',\n schemaVersion: '3.0.0',\n packageId: packageResult.value,\n assets: Object.freeze(assets),\n });\n }\n if (!hasParent || !hasValues || hasAssets)\n return jsonError(\n '$',\n 'parent and values for an instance document',\n value,\n 'instance branch is incomplete',\n );\n const parentResult = parsePackageId(value.parent, '$.parent');\n if (!parentResult.ok) return parentResult;\n if (!isRecord(value.values))\n return jsonError(\n '$.values',\n 'a sparse parameter object',\n value.values,\n 'instance values are not an object',\n );\n return ok({\n format: 'instance',\n schemaVersion: '3.0.0',\n packageId: packageResult.value,\n parent: parentResult.value,\n values: Object.freeze({ ...value.values }),\n });\n}\n\nexport interface DirectPackAssetProjection extends DirectPackJsonAsset {\n readonly guid: string;\n readonly sourceKey: string;\n}\n\nexport interface DirectPackProjection {\n readonly packageId: string;\n readonly assets: readonly DirectPackAssetProjection[];\n}\n\n/** Add the computed GUIDs needed by the ordinary Pack v2 publication path. */\nexport function projectDirectPackJson(\n value: ParsedDirectPackJson | DirectPackJson,\n): Result<DirectPackProjection, PackAuthoringError> {\n const parsed = 'format' in value ? ok(value) : parsePackSourceJson(value);\n if (!parsed.ok) return parsed;\n if (parsed.value.format !== 'direct') {\n return failure(\n authoringError(\n 'pack-parameter-invalid',\n 'a direct v3 pack.json',\n 'projectDirectPackJson accepts the direct branch only',\n { observed: parsed.value.format },\n ),\n );\n }\n const assets: DirectPackAssetProjection[] = [];\n for (const [sourceKey, entry] of Object.entries(parsed.value.assets).sort(([left], [right]) =>\n left.localeCompare(right),\n )) {\n assets.push({\n ...entry,\n guid: AssetGuidCodec.format(AssetGuidCodec.derive(parsed.value.packageId, sourceKey)),\n sourceKey,\n });\n }\n return ok({ packageId: PackageId.format(parsed.value.packageId), assets: Object.freeze(assets) });\n}\n\nexport interface PackParameterRootSubject {\n readonly format: 'source';\n readonly packageId: PackageId;\n readonly parameters: readonly PackParameterDefinition[];\n}\n\nexport interface PackParameterInstanceSubject {\n readonly format: 'instance';\n readonly packageId: PackageId;\n readonly parent: PackageId;\n readonly values: Readonly<Record<string, unknown>>;\n}\n\nexport interface PackDirectSubject {\n readonly format: 'direct';\n readonly packageId: PackageId;\n}\n\nexport type PackParameterInheritanceSubject =\n | PackParameterRootSubject\n | PackParameterInstanceSubject\n | PackDirectSubject;\n\nexport interface ResolvedPackParameterInheritance {\n readonly packageId: PackageId;\n readonly rootPackageId: PackageId;\n readonly values: Readonly<Record<string, PackParameterValue>>;\n readonly parentChain: readonly string[];\n readonly parameters: readonly PackParameterDefinition[];\n}\n\nexport type PackParameterSubjectReader = (\n packageId: PackageId,\n) =>\n | PackParameterInheritanceSubject\n | undefined\n | Promise<PackParameterInheritanceSubject | undefined>;\n\nfunction subjectId(subject: PackParameterInheritanceSubject): string {\n return PackageId.format(subject.packageId).toLowerCase();\n}\n\n/** Resolve one finite parent chain. Every instance keeps its own packageId. */\nexport async function resolvePackParameterInheritance(\n subject: PackParameterInheritanceSubject,\n readParent: PackParameterSubjectReader,\n): Promise<Result<ResolvedPackParameterInheritance, PackAuthoringError>> {\n const visited = new Set<string>();\n\n async function visit(\n current: PackParameterInheritanceSubject,\n path: readonly string[],\n ): Promise<Result<ResolvedPackParameterInheritance, PackAuthoringError>> {\n const currentId = subjectId(current);\n if (visited.has(currentId) || path.includes(currentId)) {\n return failure(\n authoringError(\n 'pack-parent-cycle',\n 'a finite acyclic Pack parent chain',\n 'inspect parentChain and repair the first repeated packageId',\n { packageId: currentId, parentChain: [...path, currentId] },\n ),\n );\n }\n visited.add(currentId);\n const nextPath = [...path, currentId];\n if (current.format === 'direct') {\n return failure(\n authoringError(\n 'pack-parent-has-no-parameters',\n 'a ScriptablePack source with parameters as the parent',\n 'direct packs cannot be instance parents; point the instance at a ScriptablePack source with parameters',\n { packageId: currentId },\n ),\n );\n }\n if (current.format === 'source') {\n const descriptors = validateParameterDefinitions(current.parameters, '$.parameters');\n if (!descriptors.ok) return descriptors;\n if (descriptors.value.length === 0) {\n return failure(\n authoringError(\n 'pack-parent-has-no-parameters',\n 'the parent source to declare a non-empty parameter list',\n 'use clone for an independent zero-parameter Pack instead of creating an empty instance',\n { packageId: currentId },\n ),\n );\n }\n const definition = {\n schemaVersion: '2.0.0',\n packageId: current.packageId,\n parameters: descriptors.value as NonEmptyParameters,\n build: () => ok({}),\n } as ScriptablePackDefinition<NonEmptyParameters>;\n const values = resolvePackParameterValues(definition);\n if (!values.ok) return values;\n return ok({\n packageId: current.packageId,\n rootPackageId: current.packageId,\n values: values.value,\n parentChain: [],\n parameters: descriptors.value,\n });\n }\n const parent = await readParent(current.parent);\n if (parent === undefined) {\n return failure(\n authoringError(\n 'pack-parent-not-found',\n 'the parent packageId to resolve in the source index',\n 'inspect the parent locator or recreate the instance from a live ScriptablePack with parameters',\n { packageId: currentId, parent: PackageId.format(current.parent) },\n ),\n );\n }\n if (\n PackageId.format(parent.packageId).toLowerCase() !==\n PackageId.format(current.parent).toLowerCase()\n ) {\n return failure(\n authoringError(\n 'pack-parent-not-found',\n 'the parent reader to return the requested packageId',\n 'repair the Source Index locator and retry inheritance resolution',\n {\n packageId: currentId,\n requestedParent: PackageId.format(current.parent),\n observedParent: PackageId.format(parent.packageId),\n },\n ),\n );\n }\n const resolvedParent = await visit(parent, nextPath);\n if (!resolvedParent.ok) return resolvedParent;\n const descriptors = resolvedParent.value.parameters;\n const definition = {\n schemaVersion: '2.0.0',\n packageId: resolvedParent.value.rootPackageId,\n parameters: descriptors as NonEmptyParameters,\n build: () => ok({}),\n } as ScriptablePackDefinition<NonEmptyParameters>;\n const values = resolvePackParameterValues(\n definition,\n current.values,\n resolvedParent.value.values,\n );\n if (!values.ok) return values;\n return ok({\n packageId: current.packageId,\n rootPackageId: resolvedParent.value.rootPackageId,\n values: values.value,\n parentChain: [PackageId.format(current.parent), ...resolvedParent.value.parentChain],\n parameters: descriptors,\n });\n }\n\n return visit(subject, []);\n}\n\nexport const resolvePackInheritance = resolvePackParameterInheritance;\n\nexport const PACK_AUTHORING_OPERATION_IDS = [\n 'asset.list',\n 'asset.inspect',\n 'asset.resolve',\n 'asset.verify',\n 'asset-source.create',\n 'asset-source.clone',\n 'asset-source.create-instance',\n 'asset-source.apply-values',\n 'asset-source.rebuild',\n 'asset-source.cold-cook',\n] as const;\n\nexport type PackAuthoringOperationId = (typeof PACK_AUTHORING_OPERATION_IDS)[number];\n\nexport interface PackAuthoringOperation {\n readonly requestId: string;\n readonly expectedRevision?: string;\n readonly operation: PackAuthoringOperationId;\n readonly subject?: string;\n readonly sourcePath?: string;\n readonly targetPath?: string;\n readonly packageId?: string;\n /** Parent package identity used by asset-source.create-instance. */\n readonly parentPackageId?: string;\n /** JSON-facing alias accepted by adapters at the operation boundary. */\n readonly parent?: string;\n readonly sourceKey?: string;\n readonly values?: Readonly<Record<string, unknown>>;\n /** `pack.ts` or `pack.json`; omitted defaults to the target extension. */\n readonly format?: 'pack.ts' | 'pack.json';\n /** Direct v3 entries for asset-source.create. */\n readonly initialAssets?: Readonly<Record<string, DirectPackJsonAsset>>;\n /** Explicit non-empty parameter declarations for a generated pack.ts scaffold. */\n readonly parameters?: readonly Readonly<Record<string, unknown>>[];\n /** Required proof level for asset.resolve. */\n readonly require?: 'identity' | 'present' | 'ready';\n}\n\nexport type PackAuthoringResolutionStatus = 'identity' | 'present' | 'ready';\n\nexport interface PackAuthoringOperationResult {\n readonly operation: PackAuthoringOperationId;\n readonly requestId: string;\n readonly sourcePath?: string;\n readonly targetPath?: string;\n readonly revision?: string;\n readonly packageId?: string;\n readonly parentPackageId?: string;\n readonly sourceKey?: string;\n readonly guid?: string;\n readonly format?: 'pack.ts' | 'pack.json' | 'direct' | 'instance';\n readonly status?: PackAuthoringResolutionStatus;\n readonly kind?: string;\n readonly parameters?: readonly Readonly<Record<string, unknown>>[];\n readonly values?: Readonly<Record<string, unknown>>;\n readonly effectiveValues?: Readonly<Record<string, unknown>>;\n readonly parentChain?: readonly string[];\n readonly assets?: readonly Readonly<Record<string, unknown>>[];\n readonly sources?: readonly Readonly<Record<string, unknown>>[];\n readonly capabilities?: readonly PackAuthoringOperationId[];\n readonly snapshot?: {\n readonly sourceCount: number;\n readonly assetCount: number;\n };\n}\n\nexport interface PackAuthoringGatewayPort<TResult = unknown> {\n execute(operation: PackAuthoringOperation): Promise<Result<TResult, PackAuthoringError>>;\n}\n\n/** One idempotent gateway wrapper shared by Editor and CLI adapters. */\nexport function createPackAuthoringGateway<TResult = unknown>(\n port: PackAuthoringGatewayPort<TResult>,\n): PackAuthoringGatewayPort<TResult> {\n const requests = new Map<\n string,\n { fingerprint: string; result: Promise<Result<TResult, PackAuthoringError>> }\n >();\n return {\n execute(operation) {\n if (typeof operation.requestId !== 'string' || operation.requestId.trim().length === 0) {\n return Promise.resolve(\n failure(\n authoringError(\n 'pack-source-revision-conflict',\n 'a non-empty caller-minted requestId',\n 'mint a new requestId and retry',\n { requestId: operation.requestId },\n ),\n ),\n );\n }\n let fingerprint: string;\n try {\n fingerprint = JSON.stringify(operation);\n } catch (cause) {\n return Promise.resolve(\n failure(\n authoringError(\n 'pack-parameter-invalid',\n 'a JSON-serialisable authoring operation',\n 'remove non-serialisable operation fields and retry with a new requestId',\n {\n requestId: operation.requestId,\n cause: cause instanceof Error ? cause.message : String(cause),\n },\n ),\n ),\n );\n }\n const previous = requests.get(operation.requestId);\n if (previous !== undefined) {\n if (previous.fingerprint === fingerprint) return previous.result;\n return Promise.resolve(\n failure(\n authoringError(\n 'pack-source-revision-conflict',\n 'one immutable operation per requestId',\n 'read the original result or mint a new requestId',\n { requestId: operation.requestId },\n ),\n ),\n );\n }\n const result = Promise.resolve()\n .then(() => port.execute(operation))\n .catch(\n (cause): Result<TResult, PackAuthoringError> =>\n failure(\n authoringError(\n 'pack-parameter-invalid',\n 'the Pack authoring port to return a structured Result',\n 'repair the gateway port failure, then retry with a new requestId',\n {\n requestId: operation.requestId,\n cause: cause instanceof Error ? cause.message : String(cause),\n },\n ),\n ),\n );\n requests.set(operation.requestId, { fingerprint, result });\n return result;\n },\n };\n}\n\nexport const PACK_AUTHORING_OPERATION_DESCRIPTORS = PACK_AUTHORING_OPERATION_IDS.map((id) => ({\n id,\n domain: id.startsWith('asset-source.') ? 'session' : 'asset',\n readOnly: id.startsWith('asset.'),\n requiresRevision: !id.startsWith('asset.') && id !== 'asset-source.create',\n})) as readonly {\n id: PackAuthoringOperationId;\n domain: 'asset' | 'session';\n readOnly: boolean;\n requiresRevision: boolean;\n}[];\n","import { createHash } from 'node:crypto';\nimport { readdir, readFile } from 'node:fs/promises';\nimport { basename, dirname, join, relative, resolve, sep } from 'node:path';\nimport type { SourceDeclarationEvidence } from '@forgeax/engine-types';\nimport { parsePackSourceJson, projectDirectPackJson } from '../pack-authoring.js';\nimport { SCANNER_BLACKLIST, scan } from '../scanner.js';\n\n/** Project root and GUID used to locate an authoritative source declaration. */\nexport interface SourceInventoryRequest {\n readonly projectRoot: string;\n readonly guid: string;\n}\n\nexport interface ProducerSemanticIdentityInput {\n readonly producerRoot: string;\n readonly sourcePath: string;\n readonly sourceDigest: string;\n readonly schemaVersion: string;\n readonly importer: string;\n readonly codec: string;\n readonly settings: unknown;\n readonly producer: string;\n readonly profile: string;\n readonly declaredGuids?: readonly string[];\n}\n\nexport interface ProducerRelativeDdcIdentity {\n readonly logicalPath: string;\n readonly sourceDigest: string;\n readonly key: string;\n}\n\nfunction stableValue(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(stableValue);\n if (value !== null && typeof value === 'object') {\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([key, entry]) => [key, stableValue(entry)]),\n );\n }\n return value;\n}\n\nexport function producerRelativeLogicalPath(producerRoot: string, sourcePath: string): string {\n const root = resolve(producerRoot);\n const source = resolve(sourcePath);\n const path = relative(root, source);\n if (\n path.length === 0 ||\n path === '..' ||\n path.startsWith(`..${sep}`) ||\n resolve(root, path) !== source\n ) {\n throw new Error('producer source must be inside the injected producer root');\n }\n return path.split(sep).join('/');\n}\n\nexport function producerRelativeDdcKey(input: ProducerSemanticIdentityInput): string {\n const logicalPath = producerRelativeLogicalPath(input.producerRoot, input.sourcePath);\n const semantic = {\n schemaVersion: input.schemaVersion,\n logicalPath,\n sourceDigest: input.sourceDigest,\n importer: input.importer,\n codec: input.codec,\n settings: stableValue(input.settings),\n producer: input.producer,\n profile: input.profile,\n declaredGuids: [...(input.declaredGuids ?? [])].sort(),\n };\n return createHash('sha256').update(JSON.stringify(semantic)).digest('hex');\n}\n\nexport function producerRelativeDdcIdentity(\n input: ProducerSemanticIdentityInput,\n): ProducerRelativeDdcIdentity {\n return {\n logicalPath: producerRelativeLogicalPath(input.producerRoot, input.sourcePath),\n sourceDigest: input.sourceDigest,\n key: producerRelativeDdcKey(input),\n };\n}\n\nfunction fingerprint(meta: string, source: Uint8Array | undefined): string {\n const hash = createHash('sha256').update(meta);\n if (source !== undefined) hash.update(source);\n return hash.digest('base64');\n}\n\nfunction sourceFromMeta(\n metaPath: string,\n meta: {\n readonly source?: unknown;\n readonly inputFingerprint?: unknown;\n readonly importSettings?: unknown;\n readonly subAssets?: readonly { readonly guid?: unknown }[];\n },\n guid: string,\n raw: string,\n): SourceDeclarationEvidence | undefined {\n if (\n !meta.subAssets?.some(\n (asset) => typeof asset.guid === 'string' && asset.guid.toLowerCase() === guid.toLowerCase(),\n )\n ) {\n return undefined;\n }\n const source =\n typeof meta.source === 'string' ? meta.source : basename(metaPath).replace(/\\.meta\\.json$/, '');\n const sourcePath = resolve(dirname(metaPath), source);\n const inputFingerprint =\n typeof meta.inputFingerprint === 'string' ? meta.inputFingerprint : fingerprint(raw, undefined);\n return { origin: 'sourceMeta', sourcePath, inputFingerprint };\n}\n\nasync function collectDeclarationPaths(root: string): Promise<string[]> {\n const paths: string[] = [];\n async function visit(dir: string): Promise<void> {\n const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);\n for (const entry of entries) {\n const path = join(dir, entry.name);\n if (entry.isDirectory()) {\n if (!SCANNER_BLACKLIST.has(entry.name)) await visit(path);\n continue;\n }\n if (\n entry.isFile() &&\n (entry.name.endsWith('.meta.json') ||\n entry.name.endsWith('.pack.json') ||\n entry.name.endsWith('.pack.ts'))\n ) {\n paths.push(path);\n }\n }\n }\n await visit(root);\n return paths;\n}\n\n/** Read `.meta.json` or `.pack.json` source declarations without runtime imports. */\nexport async function readSourceInventory(\n request: SourceInventoryRequest,\n): Promise<SourceDeclarationEvidence | undefined> {\n const result = await scan([request.projectRoot]);\n const paths = result.ok ? result.value : await collectDeclarationPaths(request.projectRoot);\n const guid = request.guid.toLowerCase();\n let authored: SourceDeclarationEvidence | undefined;\n for (const path of paths) {\n if (path.endsWith('.pack.ts')) {\n // ScriptablePack source identity is a build result, not a declaration\n // table. The source index therefore records the source only after the\n // producer publishes its materialized Pack output.\n continue;\n }\n const raw = await readFile(path, 'utf8').catch(() => undefined);\n if (raw === undefined) continue;\n let parsed: Record<string, unknown>;\n try {\n const value: unknown = JSON.parse(raw);\n if (value === null || typeof value !== 'object' || Array.isArray(value)) continue;\n parsed = value as Record<string, unknown>;\n } catch {\n continue;\n }\n if (path.endsWith('.pack.json')) {\n if (parsed.schemaVersion === '3.0.0') {\n const direct = parsePackSourceJson(parsed);\n if (direct.ok && direct.value.format === 'direct') {\n const projected = projectDirectPackJson(direct.value);\n if (\n projected.ok &&\n projected.value.assets.some((asset) => asset.guid.toLowerCase() === guid)\n ) {\n authored = { origin: 'authoredPack', sourcePath: path };\n }\n }\n } else if (\n Array.isArray(parsed.assets) &&\n parsed.assets.some(\n (asset) =>\n asset !== null &&\n typeof asset === 'object' &&\n !Array.isArray(asset) &&\n typeof (asset as { readonly guid?: unknown }).guid === 'string' &&\n ((asset as { readonly guid: string }).guid === request.guid ||\n (asset as { readonly guid: string }).guid.toLowerCase() === guid),\n )\n ) {\n authored = { origin: 'authoredPack', sourcePath: path };\n }\n continue;\n }\n if (path.endsWith('.meta.json')) {\n const source = sourceFromMeta(\n path,\n parsed as Parameters<typeof sourceFromMeta>[1],\n request.guid,\n raw,\n );\n if (source !== undefined) return source;\n }\n }\n return authored;\n}\n","import { createHash } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { mkdtemp, readFile, realpath, rm, stat } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { dirname, extname, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { Worker } from 'node:worker_threads';\nimport type { AssetGuid, Result } from '@forgeax/engine-types';\nimport { AssetError, err, ImportError, ok } from '@forgeax/engine-types';\nimport ts from 'typescript';\nimport {\n type ProducerSemanticIdentityInput,\n producerRelativeDdcKey,\n} from './evidence/source-inventory.js';\nimport {\n type AnyScriptablePackDefinition,\n type PackAuthoringError,\n type PackBuildContextWithoutParameters,\n type PackBuildResult,\n validatePackDefinition,\n} from './pack-authoring.js';\nimport type { AssetReader, ScriptablePackSourceClosureEntry } from './scriptable-pack.js';\n\nconst IMPORT_META_RESOLVE_FLAG = '--experimental-import-meta-resolve';\n\nfunction scriptablePackWorkerExecArgv(): string[] {\n // import.meta.resolve(parentURL) is the canonical ESM resolver, but Node\n // keeps its parentURL overload behind this flag. Filter --input-type as\n // well: stdin/eval hosts may pass it through process.execArgv, and Node\n // rejects that option inside a file-backed worker.\n const inherited = process.execArgv.filter((arg) => !arg.startsWith('--input-type'));\n return inherited.includes(IMPORT_META_RESOLVE_FLAG)\n ? inherited\n : [...inherited, IMPORT_META_RESOLVE_FLAG];\n}\n\nexport interface ScriptablePackModuleExecutor {\n load(sourcePath: string): Promise<unknown>;\n dispose?(reason: 'complete' | 'timeout' | 'failure'): void | Promise<void>;\n}\n\ninterface SerializedScriptablePackBuildContext {\n readonly packageId: readonly number[];\n readonly values?: Readonly<Record<string, unknown>>;\n}\n\ninterface WorkerBackedScriptablePackExecutor {\n readonly supportsPackParameters: true;\n}\n\nexport interface ScriptablePackModuleExecutorPool {\n acquire(): Promise<ScriptablePackModuleExecutor>;\n dispose(): Promise<void>;\n}\n\nexport interface ScriptablePackModuleExecutorPoolOptions {\n readonly maxWorkers?: number;\n readonly maxTasksPerWorker?: number;\n}\n\nexport function scriptablePackDdcKey(input: ProducerSemanticIdentityInput): string {\n return producerRelativeDdcKey(input);\n}\n\nexport interface OptionalBuildCache<T> {\n readonly read: () => Promise<T | null>;\n readonly coldCook: () => Promise<T>;\n}\n\n/** Build CAS is a performance hint; source cold cook remains the correctness path. */\nexport async function readOptionalBuildCache<T>(cache: OptionalBuildCache<T>): Promise<{\n readonly value: T;\n readonly fromCache: boolean;\n}> {\n try {\n const cached = await cache.read();\n if (cached !== null) return { value: cached, fromCache: true };\n } catch {\n // Cache deletion, read-only storage, and corrupt optional objects fail open.\n }\n return { value: await cache.coldCook(), fromCache: false };\n}\n\nasync function resolveRelativeImport(\n sourcePath: string,\n specifier: string,\n): Promise<string | undefined> {\n if (!specifier.startsWith('.')) return undefined;\n const raw = resolve(dirname(sourcePath), specifier);\n const candidates =\n extname(raw).length > 0\n ? [raw]\n : [\n raw,\n `${raw}.ts`,\n `${raw}.tsx`,\n `${raw}.mts`,\n `${raw}.js`,\n `${raw}.mjs`,\n `${raw}.json`,\n resolve(raw, 'index.ts'),\n ];\n for (const candidate of candidates) {\n try {\n if ((await stat(candidate)).isFile()) return candidate;\n } catch {\n // Continue through deterministic extension candidates.\n }\n }\n return undefined;\n}\n\n/** Capture one immutable ScriptablePack module closure for inventory and production. */\nexport async function inventoryScriptablePackSource(\n sourcePath: string,\n initialSourceText?: string,\n): Promise<readonly ScriptablePackSourceClosureEntry[]> {\n const root = await realpath(sourcePath);\n const pending = [root];\n const seen = new Set<string>();\n const entries: ScriptablePackSourceClosureEntry[] = [];\n while (pending.length > 0) {\n const path = pending.pop();\n if (path === undefined || seen.has(path)) continue;\n seen.add(path);\n const bytes =\n path === root && initialSourceText !== undefined\n ? new TextEncoder().encode(initialSourceText)\n : await readFile(path);\n entries.push({ path, digest: `sha256:${createHash('sha256').update(bytes).digest('hex')}` });\n const source = new TextDecoder().decode(bytes);\n for (const imported of ts.preProcessFile(source, true, true).importedFiles) {\n const resolved = await resolveRelativeImport(path, imported.fileName);\n if (resolved !== undefined) pending.push(await realpath(resolved));\n }\n }\n return entries.sort((left, right) => left.path.localeCompare(right.path));\n}\n\ninterface StructuredFailure {\n readonly name?: unknown;\n readonly code?: unknown;\n readonly expected?: unknown;\n readonly actual?: unknown;\n readonly hint?: unknown;\n readonly detail?: unknown;\n readonly message?: unknown;\n}\n\nfunction serializeFailure(value: unknown): StructuredFailure {\n if (value !== null && typeof value === 'object') {\n const failure = value as Record<string, unknown>;\n return {\n name: failure.name,\n code: failure.code,\n expected: failure.expected,\n actual: failure.actual,\n hint: failure.hint,\n detail: failure.detail,\n message: failure.message,\n };\n }\n return { message: String(value) };\n}\n\nfunction hydrateFailure(value: unknown): unknown {\n if (value === null || typeof value !== 'object') return value;\n const failure = value as StructuredFailure;\n if (\n failure.name === 'AssetError' &&\n typeof failure.code === 'string' &&\n typeof failure.expected === 'string' &&\n typeof failure.hint === 'string'\n ) {\n const args = {\n code: failure.code as ConstructorParameters<typeof AssetError>[0]['code'],\n expected: failure.expected,\n hint: failure.hint,\n };\n return failure.detail === undefined\n ? new AssetError(args)\n : new AssetError({\n ...args,\n detail: failure.detail as NonNullable<\n ConstructorParameters<typeof AssetError>[0]['detail']\n >,\n });\n }\n if (\n failure.name === 'ImportError' &&\n typeof failure.code === 'string' &&\n typeof failure.expected === 'string' &&\n typeof failure.hint === 'string' &&\n failure.detail !== undefined\n ) {\n return new ImportError({\n code: failure.code as ConstructorParameters<typeof ImportError>[0]['code'],\n expected: failure.expected,\n hint: failure.hint,\n detail: failure.detail as ConstructorParameters<typeof ImportError>[0]['detail'],\n ...(typeof failure.actual === 'string' ? { actual: failure.actual } : {}),\n });\n }\n if (typeof failure.message === 'string') {\n const error = new Error(failure.message);\n if (typeof failure.name === 'string') error.name = failure.name;\n return error;\n }\n return value;\n}\n\nclass WorkerScriptablePackExecutor\n implements ScriptablePackModuleExecutor, WorkerBackedScriptablePackExecutor\n{\n readonly supportsPackParameters = true as const;\n private worker: Worker | undefined;\n private compileRoot: string | undefined;\n private nextBuildId = 0;\n private disposal: Promise<void> | undefined;\n private build:\n | {\n readonly id: number;\n readonly reader: AssetReader;\n readonly resolve: (value: unknown) => void;\n readonly reject: (reason: unknown) => void;\n }\n | undefined;\n\n async load(sourcePath: string): Promise<unknown> {\n const workerUrl = scriptablePackWorkerUrl();\n const compileRoot = await mkdtemp(resolve(tmpdir(), 'forgeax-scriptable-pack-'));\n this.compileRoot = compileRoot;\n const worker = new Worker(workerUrl, {\n workerData: { sourcePath: resolve(sourcePath), compileRoot },\n execArgv: scriptablePackWorkerExecArgv(),\n resourceLimits: { maxOldGenerationSizeMb: 256, maxYoungGenerationSizeMb: 64 },\n });\n this.worker = worker;\n worker.on('message', (message: unknown) => this.onMessage(message));\n worker.unref();\n return new Promise((resolveLoad, rejectLoad) => {\n const onMessage = (message: unknown): void => {\n if (message === null || typeof message !== 'object') return;\n const value = message as Record<string, unknown>;\n if (value.kind === 'loaded') {\n // The scan keeps this executor alive for the later no-reopen build\n // route, but an idle source worker must not keep a Vite/Vitest host\n // process alive after its own work has settled.\n worker.unref();\n worker.off('message', onMessage);\n resolveLoad({\n default:\n value.definition === undefined\n ? undefined\n : {\n ...(value.definition as Record<string, unknown>),\n build: (\n readByGuid: AssetReader['readByGuid'],\n context?: SerializedScriptablePackBuildContext,\n ) => this.runBuild({ readByGuid }, context),\n },\n });\n } else if (value.kind === 'load-threw') {\n worker.off('message', onMessage);\n rejectLoad(hydrateFailure(value.error));\n }\n };\n worker.on('message', onMessage);\n worker.once('error', rejectLoad);\n worker.once('exit', (code) => {\n if (code !== 0) rejectLoad(new Error(`ScriptablePack worker exited with code ${code}`));\n });\n });\n }\n\n dispose(reason: 'complete' | 'timeout' | 'failure' = 'complete'): Promise<void> {\n if (this.disposal !== undefined) return this.disposal;\n const worker = this.worker;\n this.worker = undefined;\n const compileRoot = this.compileRoot;\n this.compileRoot = undefined;\n const active = this.build;\n this.build = undefined;\n if (active !== undefined) {\n active.reject(new Error(`ScriptablePack build disposed during ${reason}`));\n }\n this.disposal = (async () => {\n if (worker !== undefined) await worker.terminate();\n if (compileRoot !== undefined) await rm(compileRoot, { recursive: true, force: true });\n })();\n return this.disposal;\n }\n\n private runBuild(\n reader: AssetReader,\n context?: SerializedScriptablePackBuildContext,\n ): Promise<unknown> {\n const worker = this.worker;\n if (worker === undefined) return Promise.reject(new Error('ScriptablePack worker is closed'));\n if (this.build !== undefined)\n return Promise.reject(new Error('ScriptablePack worker already has an active build'));\n const id = this.nextBuildId++;\n return new Promise((resolveBuild, rejectBuild) => {\n this.build = { id, reader, resolve: resolveBuild, reject: rejectBuild };\n worker.postMessage({ kind: 'build', buildId: id, context });\n });\n }\n\n private onMessage(message: unknown): void {\n if (message === null || typeof message !== 'object') return;\n const value = message as Record<string, unknown>;\n const active = this.build;\n if (active === undefined || value.buildId !== active.id) return;\n if (value.kind === 'asset-read' && typeof value.readId === 'number') {\n void active.reader\n .readByGuid(value.guid as AssetGuid)\n .then((result) =>\n this.worker?.postMessage({\n kind: 'asset-result',\n readId: value.readId,\n result:\n result.ok === true ? result : { ...result, error: serializeFailure(result.error) },\n }),\n )\n .catch((error: unknown) => {\n if (this.build?.id !== active.id) return;\n this.build = undefined;\n active.reject(error);\n void this.dispose('failure');\n });\n return;\n }\n this.build = undefined;\n if (value.kind === 'build-result') active.resolve(value.result);\n else if (value.kind === 'build-threw') active.reject(hydrateFailure(value.error));\n else this.build = active;\n }\n}\n\nfunction scriptablePackWorkerUrl(): URL {\n const bundledWorker = new URL('./scriptable-pack-worker.mjs', import.meta.url);\n return existsSync(fileURLToPath(bundledWorker))\n ? bundledWorker\n : new URL('../dist/scriptable-pack-worker.mjs', import.meta.url);\n}\n\nclass ReusableWorkerScriptablePackExecutor\n implements ScriptablePackModuleExecutor, WorkerBackedScriptablePackExecutor\n{\n readonly supportsPackParameters = true as const;\n private readonly worker: Worker;\n private readonly compileRootReady = mkdtemp(resolve(tmpdir(), 'forgeax-scriptable-pack-pool-'));\n private compileRoot: string | undefined;\n private nextLoadId = 0;\n private nextBuildId = 0;\n private pendingLoad:\n | {\n readonly id: number;\n readonly resolve: (value: unknown) => void;\n readonly reject: (reason: unknown) => void;\n }\n | undefined;\n private build:\n | {\n readonly id: number;\n readonly reader: AssetReader;\n readonly resolve: (value: unknown) => void;\n readonly reject: (reason: unknown) => void;\n }\n | undefined;\n private disposal: Promise<void> | undefined;\n private forceDispose = false;\n private failed = false;\n private taskCount = 0;\n private released = false;\n\n constructor(\n private readonly maxTasksPerWorker: number,\n private readonly release: (\n executor: ReusableWorkerScriptablePackExecutor,\n reusable: boolean,\n ) => void,\n ) {\n this.worker = new Worker(scriptablePackWorkerUrl(), {\n workerData: { mode: 'reusable' },\n execArgv: scriptablePackWorkerExecArgv(),\n resourceLimits: { maxOldGenerationSizeMb: 256, maxYoungGenerationSizeMb: 64 },\n });\n this.worker.on('message', (message: unknown) => this.onMessage(message));\n this.worker.on('error', (error: Error) => {\n this.failed = true;\n this.rejectActive(error);\n void this.dispose('failure');\n });\n this.worker.on('exit', (code) => {\n if (code === 0 || this.disposal !== undefined) return;\n this.failed = true;\n this.rejectActive(new Error(`ScriptablePack worker exited with code ${code}`));\n void this.dispose('failure');\n });\n // Listener registration can retain the worker's MessagePort in Node.\n // A reusable worker must not keep a completed Vite build alive while its\n // pool is draining; it still processes messages while the host is live.\n this.worker.unref();\n }\n\n async load(sourcePath: string): Promise<unknown> {\n const activeDisposal = this.disposal;\n if (activeDisposal !== undefined) {\n await activeDisposal;\n if (this.failed) {\n return Promise.reject(new Error('ScriptablePack executor is not leased'));\n }\n this.disposal = undefined;\n }\n this.released = false;\n if (this.pendingLoad !== undefined || this.build !== undefined) {\n return Promise.reject(new Error('ScriptablePack executor already has an active task'));\n }\n const compileRoot = this.compileRoot ?? (await this.compileRootReady);\n if (this.disposal !== undefined) {\n const disposal = this.disposal;\n await disposal;\n if (this.failed) {\n return Promise.reject(new Error('ScriptablePack executor is not leased'));\n }\n this.disposal = undefined;\n }\n const loadId = this.nextLoadId++;\n this.compileRoot = compileRoot;\n this.taskCount += 1;\n return new Promise((resolveLoad, rejectLoad) => {\n this.pendingLoad = { id: loadId, resolve: resolveLoad, reject: rejectLoad };\n try {\n this.worker.postMessage({\n kind: 'load',\n loadId,\n sourcePath: resolve(sourcePath),\n compileRoot,\n });\n } catch (error) {\n this.pendingLoad = undefined;\n rejectLoad(error);\n void this.dispose('failure');\n }\n });\n }\n\n dispose(reason: 'complete' | 'timeout' | 'failure' = 'complete'): Promise<void> {\n if (reason === 'failure') this.forceDispose = true;\n const activeDisposal = this.disposal;\n if (activeDisposal !== undefined) {\n return activeDisposal;\n }\n this.rejectActive(new Error(`ScriptablePack task disposed during ${reason}`));\n this.disposal = (async () => {\n const compileRoot = this.compileRoot ?? (await this.compileRootReady);\n const reusable =\n reason === 'complete' &&\n !this.failed &&\n !this.forceDispose &&\n this.taskCount < this.maxTasksPerWorker;\n this.forceDispose = false;\n if (!reusable) {\n this.compileRoot = undefined;\n await this.worker.terminate();\n await rm(compileRoot, { recursive: true, force: true });\n }\n this.released = true;\n this.disposal = undefined;\n this.release(this, reusable);\n })();\n return this.disposal;\n }\n\n private rejectActive(error: unknown): void {\n const loading = this.pendingLoad;\n this.pendingLoad = undefined;\n loading?.reject(error);\n const building = this.build;\n this.build = undefined;\n building?.reject(error);\n }\n\n private runBuild(\n reader: AssetReader,\n context?: SerializedScriptablePackBuildContext,\n ): Promise<unknown> {\n if (this.released || this.disposal !== undefined) {\n return Promise.reject(new Error('ScriptablePack executor is not leased'));\n }\n if (this.build !== undefined) {\n return Promise.reject(new Error('ScriptablePack worker already has an active build'));\n }\n const id = this.nextBuildId++;\n return new Promise((resolveBuild, rejectBuild) => {\n this.build = { id, reader, resolve: resolveBuild, reject: rejectBuild };\n try {\n this.worker.postMessage({ kind: 'build', buildId: id, context });\n } catch (error) {\n this.build = undefined;\n rejectBuild(error);\n void this.dispose('failure');\n }\n });\n }\n\n private onMessage(message: unknown): void {\n if (message === null || typeof message !== 'object') return;\n const value = message as Record<string, unknown>;\n const loading = this.pendingLoad;\n if (loading !== undefined && value.kind === 'loaded' && value.loadId === loading.id) {\n this.pendingLoad = undefined;\n loading.resolve({\n default:\n value.definition === undefined\n ? undefined\n : {\n ...(value.definition as Record<string, unknown>),\n build: (\n readByGuid: AssetReader['readByGuid'],\n context?: SerializedScriptablePackBuildContext,\n ) => this.runBuild({ readByGuid }, context),\n },\n });\n return;\n }\n if (loading !== undefined && value.kind === 'load-threw' && value.loadId === loading.id) {\n this.pendingLoad = undefined;\n loading.reject(hydrateFailure(value.error));\n return;\n }\n const active = this.build;\n if (active === undefined || value.buildId !== active.id) return;\n if (value.kind === 'asset-read' && typeof value.readId === 'number') {\n void active.reader\n .readByGuid(value.guid as AssetGuid)\n .then((result) =>\n this.worker.postMessage({\n kind: 'asset-result',\n readId: value.readId,\n result:\n result.ok === true ? result : { ...result, error: serializeFailure(result.error) },\n }),\n )\n .catch((error: unknown) => {\n if (this.build?.id !== active.id) return;\n this.build = undefined;\n active.reject(error);\n void this.dispose('failure');\n });\n return;\n }\n this.build = undefined;\n if (value.kind === 'build-result') active.resolve(value.result);\n else if (value.kind === 'build-threw') active.reject(hydrateFailure(value.error));\n else this.build = active;\n }\n}\n\nclass DefaultScriptablePackModuleExecutorPool implements ScriptablePackModuleExecutorPool {\n private readonly maxWorkers: number;\n private readonly maxTasksPerWorker: number;\n private readonly idle: ReusableWorkerScriptablePackExecutor[] = [];\n private readonly waiters: {\n readonly resolve: (executor: ScriptablePackModuleExecutor) => void;\n readonly reject: (reason: unknown) => void;\n }[] = [];\n private readonly executors = new Set<ReusableWorkerScriptablePackExecutor>();\n private workerCount = 0;\n private closed = false;\n\n constructor(options: ScriptablePackModuleExecutorPoolOptions = {}) {\n this.maxWorkers = Math.max(1, Math.trunc(options.maxWorkers ?? 2));\n this.maxTasksPerWorker = Math.max(1, Math.trunc(options.maxTasksPerWorker ?? 32));\n }\n\n acquire(): Promise<ScriptablePackModuleExecutor> {\n if (this.closed) return Promise.reject(new Error('ScriptablePack executor pool is closed'));\n const executor = this.idle.pop();\n if (executor !== undefined) return Promise.resolve(executor);\n if (this.workerCount < this.maxWorkers) {\n this.workerCount += 1;\n return Promise.resolve(this.createExecutor());\n }\n return new Promise((resolveAcquire, rejectAcquire) =>\n this.waiters.push({ resolve: resolveAcquire, reject: rejectAcquire }),\n );\n }\n\n async dispose(): Promise<void> {\n if (this.closed) return;\n this.closed = true;\n const waiters = this.waiters.splice(0);\n for (const waiter of waiters) {\n waiter.reject(new Error('ScriptablePack executor pool is closed'));\n }\n this.idle.splice(0);\n await Promise.all([...this.executors].map((executor) => executor.dispose('failure')));\n }\n\n private createExecutor(): ReusableWorkerScriptablePackExecutor {\n const executor = new ReusableWorkerScriptablePackExecutor(\n this.maxTasksPerWorker,\n (executor, reusable) => {\n if (this.closed) {\n this.executors.delete(executor);\n if (!reusable) this.workerCount -= 1;\n return;\n }\n if (!reusable) {\n this.executors.delete(executor);\n this.workerCount -= 1;\n } else {\n this.idle.push(executor);\n }\n this.drain();\n },\n );\n this.executors.add(executor);\n return executor;\n }\n\n private drain(): void {\n if (this.closed) return;\n while (this.waiters.length > 0) {\n const idle = this.idle.pop();\n if (idle !== undefined) {\n this.waiters.shift()?.resolve(idle);\n continue;\n }\n if (this.workerCount >= this.maxWorkers) return;\n this.workerCount += 1;\n this.waiters.shift()?.resolve(this.createExecutor());\n }\n }\n}\n\nexport function createScriptablePackModuleExecutorPool(\n options: ScriptablePackModuleExecutorPoolOptions = {},\n): ScriptablePackModuleExecutorPool {\n return new DefaultScriptablePackModuleExecutorPool(options);\n}\n\nexport interface LoadScriptablePackOptions {\n readonly timeoutMs?: number;\n readonly buildTimeoutMs?: number;\n readonly executor?: ScriptablePackModuleExecutor;\n readonly metadataOnly?: boolean;\n}\n\nfunction scriptablePackLoadFailure(\n sourcePath: string,\n reason: 'module-load' | 'timeout',\n phase: 'module-load' | 'build',\n diagnostic: string,\n timeoutMs?: number,\n): PackAuthoringError {\n return {\n code: 'pack-parameter-invalid',\n expected: 'a trusted Pack v2 authoring module with a valid default export',\n hint: 'repair the source module or its build timeout, then inspect the Pack again',\n detail: {\n sourcePath,\n reason,\n phase,\n diagnostic,\n ...(timeoutMs === undefined ? {} : { timeoutMs }),\n },\n };\n}\n\n/** Load a ScriptablePack source contract in an isolated module executor. */\nexport async function loadScriptablePack(\n sourcePath: string,\n options: LoadScriptablePackOptions = {},\n): Promise<Result<Readonly<AnyScriptablePackDefinition>, PackAuthoringError>> {\n const timeoutMs = options.timeoutMs ?? 15_000;\n const buildTimeoutMs = options.buildTimeoutMs ?? 5_000;\n const executor = options.executor ?? new WorkerScriptablePackExecutor();\n let disposeReason: 'complete' | 'timeout' | 'failure' | undefined;\n let timeout: ReturnType<typeof setTimeout> | undefined;\n try {\n const timeoutSignal = Symbol('scriptable-pack-module-timeout');\n const loaded = await Promise.race([\n executor.load(sourcePath),\n new Promise<typeof timeoutSignal>((resolve) => {\n timeout = setTimeout(() => resolve(timeoutSignal), timeoutMs);\n }),\n ]);\n if (loaded === timeoutSignal) {\n disposeReason = 'timeout';\n return err(\n scriptablePackLoadFailure(\n sourcePath,\n 'timeout',\n 'module-load',\n `Pack module initialization exceeded ${timeoutMs}ms`,\n timeoutMs,\n ),\n );\n }\n const moduleValue =\n loaded !== null && typeof loaded === 'object' && 'default' in loaded\n ? (loaded as { readonly default: unknown }).default\n : undefined;\n const validated = validatePackDefinition(moduleValue, sourcePath);\n if (!validated.ok) {\n disposeReason = 'failure';\n return validated;\n }\n if (options.metadataOnly === true) {\n disposeReason = 'complete';\n return ok(validated.value);\n }\n const definition = validated.value;\n const build = definition.build as unknown as (\n first: unknown,\n context?: SerializedScriptablePackBuildContext,\n ) => PackBuildResult;\n return ok({\n ...definition,\n build: async (\n context: PackBuildContextWithoutParameters,\n ): Promise<Awaited<PackBuildResult>> => {\n let buildTimedOut = false;\n let buildTimeout: ReturnType<typeof setTimeout> | undefined;\n const timeoutResult = err(\n scriptablePackLoadFailure(\n sourcePath,\n 'timeout',\n 'build',\n `ScriptablePack build exceeded ${buildTimeoutMs}ms`,\n buildTimeoutMs,\n ),\n );\n try {\n const invocation =\n 'supportsPackParameters' in executor &&\n (executor as Partial<WorkerBackedScriptablePackExecutor>).supportsPackParameters ===\n true\n ? build(context.readByGuid, {\n packageId: [...context.packageId],\n ...('values' in context && context.values !== undefined\n ? { values: context.values as Readonly<Record<string, unknown>> }\n : {}),\n })\n : definition.build(context as never);\n const built = await Promise.race([\n Promise.resolve(invocation),\n new Promise<Awaited<PackBuildResult>>((resolve) => {\n buildTimeout = setTimeout(() => {\n buildTimedOut = true;\n resolve(timeoutResult as Awaited<PackBuildResult>);\n }, buildTimeoutMs);\n }),\n ]);\n if (buildTimedOut) {\n await executor.dispose?.('timeout');\n return built;\n }\n await executor.dispose?.('complete');\n return built;\n } catch (error) {\n await executor.dispose?.('failure');\n throw error;\n } finally {\n if (buildTimeout !== undefined) clearTimeout(buildTimeout);\n }\n },\n } as AnyScriptablePackDefinition);\n } catch (error) {\n disposeReason = 'failure';\n return err(\n scriptablePackLoadFailure(\n sourcePath,\n 'module-load',\n 'module-load',\n error instanceof Error ? error.message : String(error),\n ),\n );\n } finally {\n if (timeout !== undefined) clearTimeout(timeout);\n if (disposeReason !== undefined) await executor.dispose?.(disposeReason);\n }\n}\n"]}
|