@forgeax/engine-app 0.1.7 → 0.1.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/ecs-import.ts","../src/internal/browser-remote-bridge.ts","../src/browser-frame-signal.ts","../src/animation-asset-lookup.ts","../src/errors.ts","../src/execution/bootstrap-entry.ts","../src/execution/types.ts","../src/execution/capabilities.ts","../src/execution/schema.ts","../src/execution/report.ts","../src/execution/control.ts","../src/execution/selector.ts","../src/execution/bootstrap-url.ts","../src/internal/error-fanout.ts","../src/types.ts","../src/execution/engine-worker.ts","../src/execution/measurement.ts","../src/execution/protocol.ts","../src/execution/host-controller.ts","../src/renderer-plugin.ts","../src/internal/assets-world-plugin.ts","../src/internal/assembled-engine-profile.ts","../src/internal/component-introspection.ts","../src/internal/frame-loop.ts","../src/internal/input-attach.ts","../src/input-map-plugin.ts","../src/input-plugin.ts","../../render/src/record/render-context.ts","../src/internal/debug-draw.ts","../src/internal/main-engine-profile.ts","../src/internal/remote-serve-flag.ts","../src/internal/remote-server-plugin.ts","../src/internal/rhi-capture.ts","../src/internal/rhi-debug-flag.ts","../src/create-app.ts","../src/fallback-camera.ts","../src/game-context.ts","../src/load-game-errors.ts","../src/load-game.ts","../src/internal/browser-rhi-debug-runtime.ts","../src/tool-preview/recipe.ts","../src/tool-preview/bootstrap.ts","../src/tool-preview/evidence.ts","../src/tool-preview/framing.ts"],"names":["isRecord","Update","err","performance","ok","attachBrowserInputBackend","makeAppError","RhiError","Camera","attachRecorder"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,SAASA,UAAS,KAAA,EAAkD;AAClE,EAAA,OAAO,KAAA,KAAU,IAAA,IAAQ,OAAO,KAAA,KAAU,QAAA;AAC5C;AAEO,SAAS,uBAAuB,KAAA,EAAiC;AACtE,EAAA,IAAI,CAACA,SAAAA,CAAS,KAAK,CAAA,SAAU,EAAC;AAC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/engine-app/internal/ecs-import — host-owned capability projection.\n//\n// The remote transport deliberately has no engine-package vocabulary. Hosts\n// that expose ECS to eval inject this narrow projection at the transport seam,\n// keeping the ECS wire surface and its dependency ownership in one place.\n\nconst ECS_MODULE_SPECIFIER = '@forgeax/engine-ecs';\n\nexport const ECS_PUBLIC_SYMBOLS = Object.freeze([\n 'World',\n 'Entity',\n 'Update',\n 'FixedUpdate',\n 'Time',\n 'FixedTime',\n] as const);\n\nexport type EcsPublicSymbol = (typeof ECS_PUBLIC_SYMBOLS)[number];\nexport type EcsPublicModule = Readonly<Partial<Record<EcsPublicSymbol, unknown>>>;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object';\n}\n\nexport function projectEcsPublicModule(value: unknown): EcsPublicModule {\n if (!isRecord(value)) return {};\n const projected: Record<string, unknown> = {};\n for (const symbol of ECS_PUBLIC_SYMBOLS) {\n if (symbol in value) projected[symbol] = value[symbol];\n }\n return projected;\n}\n\nexport function createEcsImportModule(\n importModule: (specifier: string) => Promise<unknown>,\n): (specifier: string) => Promise<unknown> {\n return async (specifier: string): Promise<unknown> => {\n const moduleValue = await importModule(specifier);\n return specifier === ECS_MODULE_SPECIFIER ? projectEcsPublicModule(moduleValue) : moduleValue;\n };\n}\n","// @forgeax/engine-app/internal/browser-remote-bridge — DEV-only page-side bridge\n// that makes a live BROWSER engine drivable over a loopback relay.\n//\n// WHY: @forgeax/engine-remote's only external transport is a Node WebSocket\n// server (packages/remote/src/server.ts). A browser page cannot bind a listening\n// socket, so createApp's startServer attempt throws on ws's browser shim and\n// app.remote stays undefined — the running engine is unreachable in a real\n// `pnpm --filter <app> dev` browser. But a page CAN dial OUT. So we open a\n// WebSocket CLIENT to the loopback relay\n// (skills/forgeax-engine-cli/scripts/remote-bridge-server.mjs) and run\n// @forgeax/engine-remote/execute (the ws-free eval core) in the page realm\n// against the live world/renderer/assets/rhiCapture. A CLI POSTs to the relay;\n// the relay forwards to us; we eval and reply. This is the engine-side mirror of\n// the editor's ViewportComponent DEV bridge.\n//\n// This module is reached only via a DEV-gated dynamic import from create-app.ts,\n// so production (import.meta.env.DEV === false) never bundles it (tree-shake /\n// zero-injection). It carries NO static top-level @forgeax/engine-remote\n// dependency — the eval core is pulled by a further dynamic import, keeping\n// @forgeax/engine-app free of a runtime dep on @forgeax/engine-remote (same\n// discipline as the createApp startServer path). The import is deliberately\n// left visible to Vite: the SDK host aliases the focused package to its exact\n// installed path, while @vite-ignore would make a browser resolve the bare\n// specifier from the consumer document root and yield a 500.\n\nimport { Update, type World } from '@forgeax/engine-ecs';\nimport { createEcsImportModule } from './ecs-import';\n\ntype ExecuteResult = { ok: true; value: unknown } | { ok: false; error: unknown };\n\ntype ExecuteModule = {\n executeScript: (\n script: string,\n ctx: {\n world: unknown;\n renderer: unknown;\n assets: unknown;\n rhiCapture?: unknown;\n profiler?: unknown;\n execution?: unknown;\n importModule?: (specifier: string) => Promise<unknown>;\n },\n ) => Promise<ExecuteResult>;\n};\n\ntype ComponentLike = { readonly name: string };\n\n/**\n * Project component exports onto the tokens already stored by this World.\n *\n * WHY: Vite may evaluate a workspace package once through the host package's\n * dist graph and once through a source graph. Component ids are process-local,\n * so equal `{ name, schema }` objects are not interchangeable with World\n * access. The bridge is the one place that can reconcile the public module\n * recipe with the live World's archetype SSOT.\n */\nfunction canonicalRuntimeModule(moduleValue: unknown, world: World): unknown {\n if (moduleValue === null || typeof moduleValue !== 'object') return moduleValue;\n const componentsByName = new Map<string, ComponentLike>();\n for (const [name, component] of world.components.entries()) {\n if (!componentsByName.has(name)) componentsByName.set(name, component);\n }\n const projected: Record<string, unknown> = { ...(moduleValue as Record<string, unknown>) };\n for (const [key, value] of Object.entries(projected)) {\n if (value === null || typeof value !== 'object' || !('name' in value)) continue;\n const canonical = componentsByName.get((value as ComponentLike).name);\n if (canonical !== undefined) projected[key] = canonical;\n }\n return projected;\n}\n\nexport interface BrowserRemoteBridgeDeps {\n readonly world: World;\n readonly renderer: unknown;\n readonly assets: unknown;\n /** The host's already-loaded runtime namespace; preserves component-token identity. */\n readonly runtimeModule: unknown;\n readonly rhiCapture?: unknown;\n /** The host's explicit CPU profiler capability, when opted in. */\n readonly profiler?: unknown;\n readonly execution?: unknown;\n /** Relay port. */\n readonly port: string;\n}\n\n/** Serialize a RemoteError-shaped object (or any thrown value) into a JSON-safe\n * {code, expected, hint, detail?} envelope. AI users branch on error.code by\n * property access, so the four structured fields must survive the wire. */\nfunction serializeError(error: unknown): Record<string, unknown> {\n if (error !== null && typeof error === 'object') {\n const e = error as {\n code?: unknown;\n expected?: unknown;\n hint?: unknown;\n detail?: unknown;\n message?: unknown;\n };\n const out: Record<string, unknown> = {\n code: typeof e.code === 'string' ? e.code : 'script-runtime-error',\n };\n if (typeof e.expected === 'string') out.expected = e.expected;\n if (typeof e.hint === 'string') out.hint = e.hint;\n if (e.detail !== undefined) out.detail = e.detail;\n if (out.hint === undefined && typeof e.message === 'string') out.hint = e.message;\n return out;\n }\n return { code: 'script-runtime-error', hint: String(error) };\n}\n\n/**\n * Install the DEV-only browser remote bridge. Idempotent per call site; the\n * caller gates on import.meta.env.DEV so this never runs in production.\n *\n * Returns a teardown function that stops reconnection and closes the socket —\n * the caller wires it to import.meta.hot.dispose so a vite HMR of the host app\n * does not stack duplicate bridges.\n */\nexport async function installBrowserRemoteBridge(\n deps: BrowserRemoteBridgeDeps,\n): Promise<() => void> {\n const { world, renderer, assets, rhiCapture, profiler, execution, port } = deps;\n\n // The ws-free eval core. Dynamic import keeps @forgeax/engine-app free of a\n // static @forgeax/engine-remote dependency while allowing the consumer's\n // Vite config to resolve the focused package through its SDK alias.\n const mod = (await import('@forgeax/engine-remote/execute')) as ExecuteModule;\n const executeScript = mod.executeScript;\n const importModule = createEcsImportModule((specifier: string): Promise<unknown> => {\n // The host app and the bridge must share the same component-token objects.\n // Vite can otherwise serve `/@id/@forgeax/engine-runtime` as a second\n // module graph entry, so `world.get(entity, Transform)` sees a different\n // Component id even though the token has the same name and schema.\n if (specifier === '@forgeax/engine-runtime')\n return Promise.resolve(canonicalRuntimeModule(deps.runtimeModule, world));\n const browserSpecifier = specifier.startsWith('@') ? `/@id/${specifier}` : specifier;\n return import(/* @vite-ignore */ browserSpecifier).then((moduleValue) =>\n canonicalRuntimeModule(moduleValue, world),\n );\n });\n\n let ws: WebSocket | null = null;\n let backoff = 1000;\n let stopped = false;\n\n // Frame-start eval queue: a WebSocket `message` fires at an arbitrary phase of\n // the rAF tick, so running eval inline would land world writes at an\n // unpredictable phase. Enqueue instead and drain from Update system (frame\n // start) so every bridge write passes through this frame's systems.\n const evalQueue: Array<{ id: number; code: string }> = [];\n\n const drainEvalQueue = (): void => {\n if (evalQueue.length === 0) return;\n // Snapshot + clear so an eval that enqueues runs next frame, not in an\n // unbounded same-frame loop.\n const jobs = evalQueue.splice(0, evalQueue.length);\n for (const job of jobs) {\n const reply = (payload: unknown): void => {\n // Reply on the CURRENT socket (it may have reconnected since enqueue).\n // The relay keys replies by request id, so the live socket resolves it.\n try {\n ws?.send(JSON.stringify({ type: 'result', id: job.id, payload }));\n } catch {\n /* socket gone; relay times the request out */\n }\n };\n void (async () => {\n let res: ExecuteResult;\n try {\n res = await executeScript(job.code, {\n world,\n renderer,\n assets,\n rhiCapture,\n profiler: profiler,\n execution,\n importModule,\n });\n } catch (e) {\n reply({\n ok: false,\n error: { code: 'BRIDGE_EVAL_THREW', hint: String((e as Error)?.message ?? e) },\n });\n return;\n }\n const envelope = res.ok\n ? { ok: true as const, value: res.value }\n : { ok: false as const, error: serializeError(res.error) };\n // JSON-guard: non-serializable values (opaque engine handles, cycles)\n // degrade to a marker so one bad field never wedges the channel.\n try {\n JSON.stringify(envelope);\n reply(envelope);\n } catch {\n reply({ ok: true, value: '[unserializable value — inspect in the live window]' });\n }\n })();\n }\n };\n world\n .addSystem(Update, {\n name: 'browser-remote-bridge-drain-eval-queue',\n queries: [],\n fn: drainEvalQueue,\n })\n .unwrap();\n\n const connect = (): void => {\n if (stopped) return;\n try {\n ws = new WebSocket(`ws://127.0.0.1:${port}/bridge`);\n } catch {\n return;\n }\n ws.addEventListener('open', () => {\n backoff = 1000;\n });\n ws.addEventListener('message', (ev: MessageEvent) => {\n let msg: { type?: string; id?: number; code?: string };\n try {\n msg = JSON.parse(typeof ev.data === 'string' ? ev.data : '');\n } catch {\n return;\n }\n if (msg?.type !== 'eval' || typeof msg.id !== 'number' || typeof msg.code !== 'string')\n return;\n evalQueue.push({ id: msg.id, code: msg.code });\n });\n const retry = (): void => {\n ws = null;\n if (stopped) return;\n setTimeout(connect, backoff);\n backoff = Math.min(backoff * 2, 15000);\n };\n ws.addEventListener('close', retry);\n ws.addEventListener('error', () => {\n try {\n ws?.close();\n } catch {\n /* */\n }\n });\n };\n connect();\n\n const teardown = (): void => {\n if (stopped) return;\n stopped = true;\n world.removeSystem(Update, 'browser-remote-bridge-drain-eval-queue');\n const s = ws;\n ws = null;\n if (s) {\n try {\n s.onclose = null;\n s.close();\n } catch {\n /* */\n }\n }\n };\n\n // Self-register HMR teardown so a vite HMR of the host app does not stack\n // duplicate bridges. Kept here (not in create-app.ts) so create-app.ts carries\n // no import.meta.hot reference — the rhi-debug guard gate requires every\n // import.meta.hot there to sit inside the FORGEAX_ENGINE_RHI_DEBUG block.\n const hot = (import.meta as { hot?: { dispose(cb: () => void): void } }).hot;\n if (hot) hot.dispose(teardown);\n\n return teardown;\n}\n","/**\n * Browser-visible render progress owned by the App frame loop.\n *\n * The Renderer already emits `frame-submitted` after its sole queue-submit\n * boundary. This adapter projects that event onto the document without\n * exposing a renderer handle or creating a second readiness registry. DevKit\n * capture waits on the same projection, then verifies compositor pixels.\n */\n\nexport const FORGEAX_FRAME_SUBMITTED_DATASET = 'forgeaxFrameSubmitted';\nexport const FORGEAX_FRAME_SUBMITTED_EVENT = 'forgeax:frame-submitted';\n\nexport interface BrowserFrameSubmitted {\n readonly frameId: number;\n readonly deviceGeneration: number;\n}\n\nexport function resetBrowserFrameSubmitted(canvas: HTMLCanvasElement): void {\n const documentElement = canvas.ownerDocument?.documentElement;\n if (documentElement !== undefined) {\n delete documentElement.dataset[FORGEAX_FRAME_SUBMITTED_DATASET];\n }\n}\n\nexport function publishBrowserFrameSubmitted(\n canvas: HTMLCanvasElement,\n event: BrowserFrameSubmitted,\n): void {\n const documentElement = canvas.ownerDocument?.documentElement;\n if (documentElement !== undefined) {\n documentElement.dataset[FORGEAX_FRAME_SUBMITTED_DATASET] = String(event.frameId);\n }\n // Native/Web test canvases may be structural objects without DOM event\n // methods. The dataset projection above remains optional as well, so the\n // signal must stay a no-op outside a browser host instead of poisoning the\n // frame loop with a listener exception.\n if (typeof CustomEvent === 'function' && typeof canvas.dispatchEvent === 'function') {\n canvas.dispatchEvent(\n new CustomEvent(FORGEAX_FRAME_SUBMITTED_EVENT, {\n detail: Object.freeze({ ...event }),\n }),\n );\n }\n}\n","import type { AnimationPayloadLookup } from '@forgeax/engine-animation';\nimport type { AnimationClip } from '@forgeax/engine-types';\n\nexport interface AnimationPayloadSource {\n lookup<T = unknown>(guid: string): T | undefined;\n}\n\n/** Bridge the renderer-owned GUID catalogue into the animation plugin. */\nexport function createAnimationPayloadLookup(\n source: AnimationPayloadSource | undefined,\n): AnimationPayloadLookup {\n return (guid) => source?.lookup<AnimationClip>(guid);\n}\n","// @forgeax/engine-app -- AppError + closed AppErrorCode union (12 members) +\n// APP_ERROR_HINTS / APP_EXPECTED + discriminated AppErrorDetail per code.\n//\n// Shape:\n// - AppErrorCode = closed union 12 members (charter P4 closed-union\n// exhaustive switch needs no default fallback; tsc strict mode guards\n// completeness; AGENTS.md \"Errors are structured\" + AC-07).\n// Members:\n// - 'app-not-started'\n// - 'app-already-running'\n// - 'app-canvas-detached'\n// - 'app-system-update-failed'\n// - 'app-pointer-lock-failed'\n// Plan-strategy D-3 lock: device-lost stays on RhiErrorCode (18-member\n// union); the AppError surface does NOT add a seventh 'app-device-lost'\n// member. Host onError listener receives RhiError({code:'device-lost'})\n// verbatim through the fan-out.\n//\n// - AppError class = 4-field surface (.code / .expected / .hint /\n// .detail) byte-for-byte parallel to RhiError (packages/rhi/src/errors.ts).\n// The class extends Error so debug surfaces (stack, name) work in host\n// environments; AI users walk .code / .detail by property access (charter\n// P3 explicit failure: never parse the message string).\n//\n// - AppError is exposed as a discriminated union (variant per code) so AI\n// users get .detail narrowing for free after `if (err.code === '...')`:\n//\n// if (err.code === 'app-canvas-detached') {\n// console.warn('reattach canvas', err.detail.canvasId);\n// }\n//\n// Constructor accepts a generic args object and infers the variant from\n// the literal `code` argument; `detail` must satisfy the per-code\n// payload (`AppErrorDetailFor<C>`). Callers therefore cannot supply\n// non-canonical fields like `{ state: 'running' }` on the\n// 'app-already-running' arm.\n//\n// - APP_ERROR_HINTS / APP_EXPECTED are 12-key Records keyed by AppErrorCode;\n// one private policy owner supplies both projections. The focused policy-owner\n// proof asserts that every code has the exact expected and hint strings.\n//\n// Related: requirements AC-07 / AC-04 / AC-09; plan-strategy section 2 D-3\n// (6-member lock) + D-4 ('app-system-update-failed' detail = { cause,\n// systemName? }) + D-6 (dual-layer instanceof + switch consumption form);\n// research section 2.7 (AppErrorCode lands in AGENTS.md Error model table\n// alongside RhiErrorCode et al.); charter P3 (explicit failure) + P4\n// (closed-union exhaustive switch).\n\nimport type { RhiError } from '@forgeax/engine-rhi/errors';\nimport type { ExecutionCapabilityName, ExecutionTier } from './execution/types';\n\n/**\n * Closed AppErrorCode union (12 members).\n *\n * | code | trigger |\n * |:--|:--|\n * | `'app-not-started'` | `stop()` / `pause()` / `resume()` invoked while the rAF loop is in the terminal `'idle'` or `'stopped'` state (post-device-lost terminal sink). The handle has no live frame to interrupt; AI users either call `start()` first or accept that this handle is dead and rebuild via `createApp({...})`. |\n * | `'app-already-running'` | second `start()` invocation against an already-running handle; the call is a no-op state-machine-wise (state preserved). |\n * | `'app-canvas-detached'` | `createApp(canvas)` thin wrapper found `canvas.isConnected === false` at entry. Detail carries optional `canvasId` so the host can surface the offending canvas in a multi-canvas page (D-2 minor). |\n * | `'app-system-update-failed'` | World update, renderer draw, or a frame-loop callback failed; the original failure value is forwarded on `detail.cause`. `detail.systemName` is optional when the call site can name the failing owner. |\n * | `'app-pointer-lock-failed'` | `attachInputAuto`'s `onLockError` callback received a lock failure from the input backend. `detail.path` carries `'w3c'` (W3C `requestPointerLock` rejection) or `'provider'` (host-injected `lockProvider.requestLock` throw/reject). `detail.cause` carries the original rejection value verbatim. The host recovers by remaining in unlocked state; the next trusted click will retry the lock request. |\n *\n * Plan-strategy D-4 locked the count at 6; device-lost rides RhiErrorCode.\n */\nexport type AppErrorCode = keyof typeof appErrorPolicy;\n\n/**\n * Detail variant for the `'app-canvas-detached'` arm.\n *\n * `canvasId` carries an optional identifier the host can surface to AI\n * users when multiple canvases live on the page (e.g. preview vs live\n * canvas). `undefined` when the host did not assign an id.\n */\nexport interface AppDetailCanvasDetached {\n readonly canvasId?: string | undefined;\n}\n\n/**\n * Detail variant for the `'app-system-update-failed'` arm (plan-strategy D-4).\n *\n * `cause` carries the original thrown value verbatim so AI users can\n * `cause instanceof EcsError` / `cause instanceof RhiError` narrow without\n * losing structure. `systemName` is populated when the call site can name\n * the offending system (input-attach cleanup path forwards\n * `FRAME_START_SCAN_SYSTEM_NAME`).\n */\nexport interface AppDetailSystemUpdateFailed {\n readonly cause: unknown;\n readonly systemName?: string | undefined;\n}\n\n/**\n * Detail variant for the `'app-pointer-lock-failed'` arm (plan-strategy D-4).\n *\n * `path` discriminates between W3C `requestPointerLock` rejections (`'w3c'`)\n * and host-injected `lockProvider.requestLock` throw/reject (`'provider'`).\n * `cause` carries the original rejection value verbatim so AI users can\n * narrow further (e.g. `cause instanceof DOMException` for W3C timeout\n * rejections).\n */\nexport interface AppDetailPointerLockFailed {\n readonly path: 'w3c' | 'provider';\n readonly cause: unknown;\n}\n\n/** Why a host-requested deterministic frame could not run. */\nexport interface AppDetailFrameStepInvalid {\n readonly state: 'idle' | 'running' | 'paused' | 'stopped';\n readonly deltaSeconds: number;\n readonly reason: 'state' | 'delta';\n}\n\nexport interface AppDetailExecutionTierUnavailable {\n readonly requestedTier: ExecutionTier;\n readonly missingCapabilities: readonly ExecutionCapabilityName[];\n readonly sharedEvidencePassed: boolean;\n}\n\nexport interface AppDetailExecutionBootstrapFailed {\n readonly phase: 'import' | 'export' | 'prepare' | 'bootstrap' | 'data';\n readonly moduleUrl: string;\n readonly cause: unknown;\n}\n\n/** Original startup failure thrown by a Cordis plugin fiber. */\nexport interface AppDetailPluginActivationFailed {\n readonly cause: unknown;\n}\n\nexport interface AppDetailExecutionDeadlineExceeded {\n readonly phase: 'startup' | 'handshake' | 'frame';\n readonly timeoutMs: number;\n}\n\nexport interface AppDetailExecutionKernelFailed {\n readonly kernelName: string;\n readonly worldIdentity: string;\n readonly cause: unknown;\n readonly partialWrite: true;\n readonly retryable: false;\n}\n\nexport interface AppDetailExecutionStaleWorld {\n readonly expectedIdentity: string;\n readonly receivedIdentity: string;\n readonly messageKind: string;\n}\n\nexport interface AppDetailExecutionRebuildFailed {\n readonly worldIdentity: string | null;\n readonly cause: unknown;\n}\n\n/**\n * Empty-detail shape for the 2 codes that carry no payload\n * (`'app-not-started'`, `'app-already-running'`).\n *\n * Modelled as `Readonly<Record<string, never>>` so literal builders use\n * `{}` while still narrowing under tsc strict (no extra property allowed).\n */\nexport type AppDetailEmpty = Readonly<Record<string, never>>;\n\n/**\n * Conditional resolver from `AppErrorCode` to its detail payload type.\n *\n * Used by the constructor signature so `new AppError({ code: 'X', ... })`\n * narrows the `detail` parameter to the variant payload at compile time.\n */\nexport type AppErrorDetailFor<C extends AppErrorCode> = C extends 'app-canvas-detached'\n ? AppDetailCanvasDetached\n : C extends 'app-frame-step-invalid'\n ? AppDetailFrameStepInvalid\n : C extends 'app-system-update-failed'\n ? AppDetailSystemUpdateFailed\n : C extends 'app-pointer-lock-failed'\n ? AppDetailPointerLockFailed\n : C extends 'app-plugin-activation-failed'\n ? AppDetailPluginActivationFailed\n : C extends 'app-execution-tier-unavailable'\n ? AppDetailExecutionTierUnavailable\n : C extends 'app-execution-bootstrap-failed'\n ? AppDetailExecutionBootstrapFailed\n : C extends 'app-execution-deadline-exceeded'\n ? AppDetailExecutionDeadlineExceeded\n : C extends 'app-execution-kernel-failed'\n ? AppDetailExecutionKernelFailed\n : C extends 'app-execution-stale-world'\n ? AppDetailExecutionStaleWorld\n : C extends 'app-execution-rebuild-failed'\n ? AppDetailExecutionRebuildFailed\n : AppDetailEmpty;\n\n/**\n * Tagged union of `.detail` payloads carried by structured AppError.\n *\n * Each variant maps to its `AppErrorCode` arm via `AppErrorDetailFor<C>`;\n * the variants are unique by structural fields (`AppDetailCanvasDetached`\n * has `canvasId`, `AppDetailSystemUpdateFailed` has `cause`, the empty\n * shape has neither).\n */\nexport type AppErrorDetail = AppErrorDetailFor<AppErrorCode>;\n\n/**\n * Render a one-line summary of `detail.cause` for embedding in\n * `AppError.message`. `cause` is structurally typed (`unknown`) because\n * upstream may throw any value; callers downstream still get the verbatim\n * value via `err.detail.cause` — this helper exists so tools that only see\n * `err.message` (`console.error(err)`, raw stringification) still surface\n * the root cause without consumers manually expanding `detail`.\n *\n * Closed precedence:\n * 1. Structured engine errors (RhiError / EcsError / RenderGraphError /\n * AssetError / ShaderError / ...) carry `.code` + `.message`; render\n * `<Name> <code>: <message>`.\n * 2. Plain `Error`: render `<name>: <message>`.\n * 3. Anything else: `String(cause)` (covers thrown strings, numbers, null).\n *\n * Newlines are replaced with `' / '` so the final AppError message stays a\n * single line (callers already split on `\\n` in stack traces, so a multiline\n * message would corrupt their parsing).\n */\nfunction summarizeCause(cause: unknown): string {\n if (cause === null || cause === undefined) return String(cause);\n if (typeof cause !== 'object') return String(cause);\n const r = cause as { name?: unknown; message?: unknown; code?: unknown };\n const name = typeof r.name === 'string' && r.name.length > 0 ? r.name : 'Error';\n const code = typeof r.code === 'string' && r.code.length > 0 ? r.code : '';\n const message = typeof r.message === 'string' ? r.message : '';\n const head = code !== '' ? `${name} ${code}` : name;\n const body = message !== '' ? `: ${message}` : '';\n return `${head}${body}`.replace(/\\s*\\n+\\s*/g, ' / ');\n}\n\nclass AppErrorClass extends Error {\n readonly code: AppErrorCode;\n readonly expected: string;\n readonly hint: string;\n readonly detail: AppErrorDetail;\n\n constructor(args: {\n code: AppErrorCode;\n expected: string;\n hint: string;\n detail: AppErrorDetail;\n }) {\n // Surface `detail.cause` directly inside `.message` for the\n // `'app-system-update-failed'` arm. Without this, a generic\n // `console.error(err)` shows only the wrapper expected/hint and\n // hides the actual EcsError / RhiError / host-system Error that\n // tripped the frame loop. The verbatim `cause` value remains on\n // `err.detail.cause` for two-level-narrow consumers (charter P3).\n let causeSuffix = '';\n if (args.code === 'app-system-update-failed') {\n const d = args.detail as AppDetailSystemUpdateFailed;\n const sys =\n typeof d.systemName === 'string' && d.systemName.length > 0\n ? ` (system=${d.systemName})`\n : '';\n causeSuffix = `; cause: ${summarizeCause(d.cause)}${sys}`;\n } else if (args.code === 'app-pointer-lock-failed') {\n const d = args.detail as AppDetailPointerLockFailed;\n causeSuffix = `; path: ${d.path}; cause: ${summarizeCause(d.cause)}`;\n } else if (args.code === 'app-plugin-activation-failed') {\n const d = args.detail as AppDetailPluginActivationFailed;\n causeSuffix = `; cause: ${summarizeCause(d.cause)}`;\n } else if (args.code === 'app-execution-bootstrap-failed') {\n const d = args.detail as AppDetailExecutionBootstrapFailed;\n causeSuffix = `; phase: ${d.phase}; cause: ${summarizeCause(d.cause)}`;\n } else if (args.code === 'app-execution-kernel-failed') {\n const d = args.detail as AppDetailExecutionKernelFailed;\n causeSuffix = `; kernel: ${d.kernelName}; cause: ${summarizeCause(d.cause)}`;\n } else if (args.code === 'app-execution-rebuild-failed') {\n const d = args.detail as AppDetailExecutionRebuildFailed;\n causeSuffix = `; cause: ${summarizeCause(d.cause)}`;\n }\n super(`[AppError ${args.code}] expected: ${args.expected}; hint: ${args.hint}${causeSuffix}`);\n this.name = 'AppError';\n this.code = args.code;\n this.expected = args.expected;\n this.hint = args.hint;\n this.detail = args.detail;\n }\n}\n\n/**\n * Variant intersection: an `AppErrorClass` instance whose `code` literal\n * narrows to `C` and whose `detail` narrows to `AppErrorDetailFor<C>`. The\n * shape lets `if (err.code === 'X')` simultaneously narrow `err.detail` to\n * the per-code payload (charter P3 + AC-07 discriminated union).\n */\ntype AppErrorVariant<C extends AppErrorCode> = AppErrorClass & {\n readonly code: C;\n readonly detail: AppErrorDetailFor<C>;\n};\n\n/**\n * Public AppError type — discriminated union of the policy variants.\n *\n * AI-user form (charter P3 explicit failure):\n *\n * ```ts\n * function recover(err: AppError): string {\n * switch (err.code) {\n * case 'app-not-started': return 'call start() first';\n * case 'app-already-running': return 'state preserved; ignore';\n * case 'app-canvas-detached': return `reattach ${err.detail.canvasId ?? 'canvas'}`;\n * case 'app-system-update-failed':\n * return err.detail.cause instanceof Error ? err.detail.cause.message : 'unknown';\n * case 'app-pointer-lock-failed':\n * return `lock failed (${err.detail.path}): ${err.detail.cause}`;\n * }\n * }\n * ```\n */\nexport type AppError = {\n [C in AppErrorCode]: AppErrorVariant<C>;\n}[AppErrorCode];\n\ninterface AppErrorConstructor {\n new <C extends AppErrorCode>(args: {\n code: C;\n expected: string;\n hint: string;\n detail: AppErrorDetailFor<C>;\n }): AppErrorVariant<C>;\n readonly prototype: AppErrorClass;\n}\n\n/**\n * AppError constructor — `new AppError({ code, expected, hint, detail })`.\n *\n * The generic `C` is inferred from the literal `code` argument, which\n * narrows `detail` to the per-code payload (`AppErrorDetailFor<C>`) and\n * narrows the return type to the corresponding `AppErrorVariant<C>` so the\n * call site walks the discriminated union without manual cast.\n *\n * The constructor delegates to the `AppErrorClass` runtime; the typed-cast\n * here is the ergonomic affordance for AI users (TS class declarations\n * cannot directly express `<C> ... AppErrorVariant<C>` polymorphism).\n */\nexport const AppError: AppErrorConstructor = AppErrorClass as unknown as AppErrorConstructor;\n\n/**\n * `expected` table — the engine-side invariant that was violated when each\n * code surfaces. AI users read this as the L2 detail (charter F2 priority\n * text); `.hint` carries the recovery action.\n *\n * 12 keys; the focused policy-owner proof locks the exact key set and values.\n * locks the count and non-emptiness of every entry.\n */\ntype AppErrorPolicy = { readonly expected: string; readonly hint: string };\n\nconst appErrorPolicy = {\n 'app-not-started': {\n expected:\n 'state must be \"running\" or \"paused\" to accept stop/pause/resume; \"idle\" / \"stopped\" terminal sinks reject',\n hint: 'check getState() before calling stop/pause/resume; rebuild the handle via createApp({...}) when the previous one terminated on device-lost',\n },\n 'app-already-running': {\n expected:\n 'state must be \"idle\" or \"paused\" to start; \"running\" handles ignore subsequent start() calls',\n hint: 'call stop() first or audit start() call sites; the second start() is a no-op so state is preserved',\n },\n 'app-canvas-detached': {\n expected: 'canvas.isConnected === true at createApp(canvas) entry',\n hint: 'append the canvas to the document tree before calling createApp(canvas), or use the assemble entry createApp({ renderer, world }) when the host already manages canvas lifetime',\n },\n 'app-frame-step-invalid': {\n expected:\n 'stepFrame(deltaSeconds) runs only while the App is paused and deltaSeconds is finite and non-negative',\n hint: 'pause the App before deterministic stepping and pass an explicit finite delta; resume after the bounded step sequence completes',\n },\n 'app-system-update-failed': {\n expected:\n 'world.update(world), renderer.draw(world), and frame-loop callbacks complete without failure',\n hint: 'inspect detail.cause for the original thrown value (EcsError / RhiError / host system bug); detail.systemName names the offending system when the call site can supply it',\n },\n 'app-pointer-lock-failed': {\n expected:\n 'pointer-lock request (W3C requestPointerLock or host lockProvider.requestLock) to succeed; failure signals the browser rejected the lock or the host provider threw',\n hint: 'remain in unlocked state; the next trusted click will automatically retry the lock request. inspect detail.path (\"w3c\" or \"provider\") and detail.cause to determine the root cause',\n },\n 'app-plugin-activation-failed': {\n expected: 'every requested Cordis plugin fiber reaches a stable active or pending state',\n hint: 'inspect detail.cause and the plugin fiber effects; repair the failing activation before creating the App again',\n },\n 'app-execution-tier-unavailable': {\n expected:\n 'the explicitly requested execution tier has every required observed capability and the shipped shared evidence gate',\n hint: 'inspect detail.missingCapabilities and detail.sharedEvidencePassed; use tier=\"auto\" only when an observed fallback is acceptable',\n },\n 'app-execution-bootstrap-failed': {\n expected:\n 'the bootstrap URL imports a module whose default export completes as an ExecutionBootstrapEntry in the selected Engine Realm',\n hint: 'inspect detail.phase, moduleUrl and cause; export one default ExecutionBootstrapEntry that creates only realm-local engine state',\n },\n 'app-execution-deadline-exceeded': {\n expected:\n 'the execution startup, handshake or frame completes within its configured bounded deadline',\n hint: 'inspect detail.phase and timeoutMs; the timed-out Worker has been terminated, so fix startup or frame work before creating a new App',\n },\n 'app-execution-kernel-failed': {\n expected:\n 'a shared kernel completes every dispatched shard without leaving a possibly partial World write',\n hint: 'do not retry or draw the poisoned World; inspect detail.kernelName and cause, then call app.execution.rebuild()',\n },\n 'app-execution-stale-world': {\n expected:\n 'every execution message targets the currently active World identity before it can write',\n hint: 'discard the late message and keep the current World; inspect expectedIdentity, receivedIdentity and messageKind',\n },\n 'app-execution-rebuild-failed': {\n expected:\n 'explicit rebuild disposes the poisoned World and bootstraps a fresh World identity in the surviving Engine Realm',\n hint: 'inspect detail.cause; this App remains stopped, so fix the bootstrap failure or create a new App explicitly',\n },\n} satisfies Record<string, AppErrorPolicy>;\n\nexport const APP_EXPECTED: Readonly<Record<AppErrorCode, string>> = Object.fromEntries(\n Object.entries(appErrorPolicy).map(([code, policy]) => [code, policy.expected]),\n) as Readonly<Record<AppErrorCode, string>>;\n\nexport const APP_ERROR_HINTS: Readonly<Record<AppErrorCode, string>> = Object.fromEntries(\n Object.entries(appErrorPolicy).map(([code, policy]) => [code, policy.hint]),\n) as Readonly<Record<AppErrorCode, string>>;\n\n/**\n * Type guard for narrowing `CanvasAppError`-compatible mixed signals to AppError.\n *\n * The fan-out signature is `(err: CanvasAppError) => void`; AI users\n * who want to handle only the AppError leg call `if (isAppError(err)) ...`\n * before walking `.code`. Reverse-compatible with `instanceof AppError`\n * (the class is exposed); the function form is provided as the\n * canonical idiom in JSDoc / README so AI users do not need to reason\n * about cross-realm `instanceof` quirks.\n *\n * The parameter accepts the complete App/RHI boundary union so callers can\n * narrow the error without casts.\n */\nexport function isAppError(err: AppError | RhiError): err is AppError {\n return err instanceof AppErrorClass;\n}\n","import type { Plugin } from '@forgeax/engine-plugin';\nimport type { RenderFeature } from '@forgeax/engine-render';\nimport { err, ok, type Result } from '@forgeax/engine-types';\nimport { APP_ERROR_HINTS, APP_EXPECTED, AppError, type AppError as AppErrorType } from '../errors';\nimport type { ExecutionBootstrapValue } from './types';\n\n/** Realm-local engine assembly returned by an execution bootstrap module. */\nexport interface PreparedExecutionBootstrap {\n /** Render features constructed in the realm that will own the Renderer. */\n readonly features?: readonly RenderFeature<unknown>[];\n /** Plugins constructed in the realm that will own the World. */\n readonly plugins?: readonly Plugin[];\n}\n\n/** Realm-local Host bridge available to execution bootstrap plugins. */\nexport interface ExecutionBootstrapHost {\n readonly port?: MessagePort;\n setPointerLockAllowed(allowed: boolean): void;\n}\n\ndeclare module '@forgeax/engine-plugin' {\n interface EngineContextServices {\n executionBootstrapHost: ExecutionBootstrapHost;\n }\n}\n\n/** Bind the optional Host transport to the same Fiber that owns bootstrap plugins. */\nexport function executionBootstrapHostPlugin(host: ExecutionBootstrapHost): Plugin {\n return {\n name: 'execution-bootstrap-host',\n provide: 'executionBootstrapHost',\n apply(ctx) {\n ctx.provide('executionBootstrapHost', host);\n if (host.port !== undefined) {\n ctx.effect(() => () => host.port?.close(), 'execution/bootstrap-port');\n }\n },\n };\n}\n\n/** Default export contract for `ExecutionOptions.bootstrap`. */\nexport type ExecutionBootstrapEntry = (\n data: ExecutionBootstrapValue | undefined,\n) => PreparedExecutionBootstrap | Promise<PreparedExecutionBootstrap>;\n\nfunction bootstrapError(\n phase: 'import' | 'export' | 'prepare' | 'bootstrap' | 'data',\n moduleUrl: string,\n cause: unknown,\n): AppErrorType {\n return new AppError({\n code: 'app-execution-bootstrap-failed',\n expected: APP_EXPECTED['app-execution-bootstrap-failed'],\n hint: APP_ERROR_HINTS['app-execution-bootstrap-failed'],\n detail: { phase, moduleUrl, cause },\n });\n}\n\nexport function validateExecutionBootstrapData(\n data: ExecutionBootstrapValue | undefined,\n moduleUrl: string,\n): Result<void, AppErrorType> {\n if (data === undefined) return ok(undefined);\n try {\n structuredClone(data);\n return ok(undefined);\n } catch (cause) {\n return err(bootstrapError('data', moduleUrl, cause));\n }\n}\n\nexport async function loadBootstrapEntry(\n moduleUrl: string,\n): Promise<Result<ExecutionBootstrapEntry, AppErrorType>> {\n let loaded: unknown;\n try {\n loaded = await import(/* @vite-ignore */ moduleUrl);\n } catch (cause) {\n return err(bootstrapError('import', moduleUrl, cause));\n }\n const entry = (loaded as { default?: unknown }).default;\n if (typeof entry !== 'function') {\n return err(\n bootstrapError(\n 'export',\n moduleUrl,\n new TypeError('default export is not an ExecutionBootstrapEntry function'),\n ),\n );\n }\n return ok(entry as ExecutionBootstrapEntry);\n}\n\nexport async function prepareBootstrapEntry(\n moduleUrl: string,\n data: ExecutionBootstrapValue | undefined,\n): Promise<Result<PreparedExecutionBootstrap, AppErrorType>> {\n const valid = validateExecutionBootstrapData(data, moduleUrl);\n if (!valid.ok) return valid;\n const loaded = await loadBootstrapEntry(moduleUrl);\n if (!loaded.ok) return loaded;\n try {\n const prepared = await loaded.value(data);\n if (\n typeof prepared !== 'object' ||\n prepared === null ||\n (prepared.features !== undefined && !Array.isArray(prepared.features)) ||\n (prepared.plugins !== undefined && !Array.isArray(prepared.plugins))\n ) {\n return err(\n bootstrapError(\n 'prepare',\n moduleUrl,\n new TypeError('execution bootstrap must return an object with feature and plugin arrays'),\n ),\n );\n }\n return ok(prepared);\n } catch (cause) {\n return err(bootstrapError('prepare', moduleUrl, cause));\n }\n}\n","import type { WorldExecutionHealth } from '@forgeax/engine-ecs/shared';\nimport type { Result, RuntimeAssetBinding } from '@forgeax/engine-types';\nimport type { AppError } from '../errors';\n\nexport const EXECUTION_TIERS = ['main-serial', 'engine-worker', 'shared'] as const;\nexport type ExecutionTier = (typeof EXECUTION_TIERS)[number];\n\nexport const EXECUTION_REQUESTED_TIERS = ['auto', ...EXECUTION_TIERS] as const;\nexport type ExecutionRequestedTier = (typeof EXECUTION_REQUESTED_TIERS)[number];\n\nexport const EXECUTION_CAPABILITY_NAMES = [\n 'worker',\n 'offscreenCanvas',\n 'workerAnimationFrame',\n 'workerWebGpu',\n 'crossOriginIsolated',\n 'sharedArrayBuffer',\n 'atomicsWait',\n] as const;\nexport type ExecutionCapabilityName = (typeof EXECUTION_CAPABILITY_NAMES)[number];\n\nexport interface ExecutionCapabilityFact {\n readonly available: boolean;\n readonly reason: string;\n}\n\nexport type ExecutionCapabilities = Readonly<\n Record<ExecutionCapabilityName, ExecutionCapabilityFact>\n>;\n\nexport type ExecutionSelectionReason =\n | 'explicit-request'\n | 'auto-shared'\n | 'auto-engine-worker'\n | 'auto-main-serial';\n\nexport interface ExecutionSelection {\n readonly requestedTier: ExecutionRequestedTier;\n readonly actualTier: ExecutionTier;\n readonly selectionReason: ExecutionSelectionReason;\n readonly missingCapabilities: readonly ExecutionCapabilityName[];\n readonly sharedEvidencePassed: boolean;\n}\n\nexport type ExecutionEngineHealth = 'idle' | 'starting' | 'running' | 'stopped' | 'faulted';\nexport type ExecutionWorldHealth = WorldExecutionHealth;\n\nexport type KernelDispatchReason =\n | 'no-eligible-kernel'\n | 'zero-work'\n | 'small-span'\n | 'forced-inline'\n | 'shared'\n | 'poisoned';\n\nexport interface ExecutionMeasurement {\n readonly samples: number;\n readonly p50: number;\n readonly p95: number;\n readonly p99: number;\n readonly jitter: number;\n}\n\nexport interface ExecutionFault {\n readonly source: 'bootstrap' | 'handshake' | 'runtime' | 'kernel' | 'world' | 'rebuild';\n readonly code: string;\n readonly expected: string;\n readonly hint: string;\n readonly detail: unknown;\n readonly partialWrite: boolean;\n readonly retryable: boolean;\n}\n\nexport interface ExecutionAudioReport {\n readonly owner: 'host';\n readonly contextState: 'running' | 'suspended' | 'closed';\n readonly activeSourceCount: number;\n readonly lastError: {\n readonly code: string;\n readonly expected: string;\n readonly hint: string;\n readonly detail: unknown;\n } | null;\n}\n\n/**\n * Serializable asset-catalog configuration copied into the selected Engine\n * realm. The URL is resolved by that realm, so a Worker never closes over a\n * Host-side CatalogSource or Registry instance.\n */\nexport interface ExecutionAssetCatalog {\n readonly url: string;\n readonly expectedScope?: Pick<RuntimeAssetBinding, 'scopeId' | 'generation'>;\n}\n\nexport interface ExecutionReport {\n readonly schemaVersion: 1;\n readonly requestedTier: ExecutionRequestedTier;\n readonly actualTier: ExecutionTier | null;\n readonly selectionReason: ExecutionSelectionReason | null;\n readonly sharedEvidencePassed: boolean;\n readonly capabilities: ExecutionCapabilities;\n readonly engine: {\n readonly realm: 'host' | 'worker';\n readonly health: ExecutionEngineHealth;\n };\n readonly world: {\n readonly identity: string | null;\n readonly health: ExecutionWorldHealth;\n readonly partialWrite: boolean;\n readonly retryable: boolean;\n };\n readonly kernelDispatch: {\n readonly eligible: boolean;\n readonly usedShared: boolean;\n readonly reason: KernelDispatchReason;\n readonly dispatched: number;\n readonly completed: number;\n };\n readonly performance: {\n readonly hostFrameMs: ExecutionMeasurement | null;\n readonly engineUpdateMs: ExecutionMeasurement | null;\n readonly kernelWaitMs: ExecutionMeasurement | null;\n readonly hostAudioMs: ExecutionMeasurement | null;\n };\n readonly audio: ExecutionAudioReport;\n readonly fault: ExecutionFault | null;\n}\n\nexport interface ExecutionOptions {\n readonly tier?: ExecutionRequestedTier;\n /** Absolute or import.meta.url-relative URL of an ExecutionBootstrapEntry module. */\n readonly bootstrap: string | URL;\n /** Structured-cloneable input supplied identically to main and Worker realms. */\n readonly bootstrapData?: ExecutionBootstrapValue;\n /**\n * Realm side of an optional typed host/game channel. The engine transfers it\n * to a Worker when needed and otherwise preserves the same port contract.\n */\n readonly bootstrapPort?: MessagePort;\n /**\n * Serializable CatalogSource configuration constructed inside the selected\n * execution realm. This is the asset delivery seam for Worker execution;\n * `CreateAppOptions.assetCatalog` remains realm-bound and is rejected when\n * execution is requested.\n */\n readonly assetCatalog?: ExecutionAssetCatalog;\n readonly startupTimeoutMs?: number;\n readonly frameTimeoutMs?: number;\n}\n\nexport type ExecutionBootstrapValue =\n | null\n | boolean\n | number\n | string\n | readonly ExecutionBootstrapValue[]\n | { readonly [key: string]: ExecutionBootstrapValue };\n\nexport interface ExecutionControl {\n report(): ExecutionReport;\n rebuild(): Promise<Result<ExecutionReport, AppError>>;\n}\n","import {\n EXECUTION_CAPABILITY_NAMES,\n type ExecutionCapabilities,\n type ExecutionCapabilityName,\n} from './types';\n\nexport function unavailableExecutionCapabilities(reason: string): ExecutionCapabilities {\n return Object.fromEntries(\n EXECUTION_CAPABILITY_NAMES.map((name) => [name, { available: false, reason }]),\n ) as unknown as ExecutionCapabilities;\n}\n\nexport function missingExecutionCapabilities(\n capabilities: ExecutionCapabilities,\n required: readonly ExecutionCapabilityName[],\n): readonly ExecutionCapabilityName[] {\n return required.filter((name) => !capabilities[name].available);\n}\n\ninterface WorkerProbeResult {\n readonly workerAnimationFrame: boolean;\n readonly workerWebGpu: boolean;\n readonly atomicsWait: boolean;\n}\n\nfunction probeWorker(timeoutMs: number): Promise<WorkerProbeResult> {\n return new Promise((resolve) => {\n const source = `postMessage({workerAnimationFrame:typeof requestAnimationFrame==='function',workerWebGpu:typeof navigator==='object'&&navigator.gpu!==undefined,atomicsWait:typeof Atomics==='object'&&typeof Atomics.wait==='function'})`;\n const url = URL.createObjectURL(new Blob([source], { type: 'text/javascript' }));\n const worker = new Worker(url);\n const finish = (result: WorkerProbeResult): void => {\n worker.terminate();\n URL.revokeObjectURL(url);\n resolve(result);\n };\n const timeout = setTimeout(\n () => finish({ workerAnimationFrame: false, workerWebGpu: false, atomicsWait: false }),\n timeoutMs,\n );\n worker.onmessage = (event: MessageEvent<WorkerProbeResult>) => {\n clearTimeout(timeout);\n finish(event.data);\n };\n worker.onerror = () => {\n clearTimeout(timeout);\n finish({ workerAnimationFrame: false, workerWebGpu: false, atomicsWait: false });\n };\n });\n}\n\nexport async function probeExecutionCapabilities(\n canvas: HTMLCanvasElement,\n timeoutMs = 2_000,\n): Promise<ExecutionCapabilities> {\n const workerAvailable = typeof Worker === 'function';\n const offscreenAvailable = typeof canvas.transferControlToOffscreen === 'function';\n const isolated = globalThis.crossOriginIsolated === true;\n const sabAvailable = typeof SharedArrayBuffer === 'function';\n const worker = workerAvailable\n ? await probeWorker(timeoutMs)\n : { workerAnimationFrame: false, workerWebGpu: false, atomicsWait: false };\n return {\n worker: {\n available: workerAvailable,\n reason: workerAvailable ? 'Worker constructor observed' : 'Worker constructor unavailable',\n },\n offscreenCanvas: {\n available: offscreenAvailable,\n reason: offscreenAvailable\n ? 'canvas transferControlToOffscreen observed'\n : 'canvas cannot transfer to OffscreenCanvas',\n },\n workerAnimationFrame: {\n available: worker.workerAnimationFrame,\n reason: worker.workerAnimationFrame\n ? 'requestAnimationFrame observed in DedicatedWorker'\n : 'requestAnimationFrame unavailable in DedicatedWorker',\n },\n workerWebGpu: {\n available: worker.workerWebGpu,\n reason: worker.workerWebGpu\n ? 'navigator.gpu observed in DedicatedWorker'\n : 'navigator.gpu unavailable in DedicatedWorker',\n },\n crossOriginIsolated: {\n available: isolated,\n reason: isolated ? 'crossOriginIsolated is true' : 'crossOriginIsolated is false',\n },\n sharedArrayBuffer: {\n available: sabAvailable,\n reason: sabAvailable\n ? 'SharedArrayBuffer constructor observed'\n : 'SharedArrayBuffer constructor unavailable',\n },\n atomicsWait: {\n available: worker.atomicsWait,\n reason: worker.atomicsWait\n ? 'Atomics.wait observed in DedicatedWorker'\n : 'Atomics.wait unavailable in DedicatedWorker',\n },\n };\n}\n","import {\n EXECUTION_CAPABILITY_NAMES,\n EXECUTION_REQUESTED_TIERS,\n EXECUTION_TIERS,\n type ExecutionReport,\n} from './types';\n\nexport const EXECUTION_REPORT_SCHEMA_VERSION = 1 as const;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction hasExactKeys(value: Record<string, unknown>, keys: readonly string[]): boolean {\n const actual = Object.keys(value);\n return actual.length === keys.length && keys.every((key) => key in value);\n}\n\nfunction isMeasurement(value: unknown): boolean {\n if (!isRecord(value) || !hasExactKeys(value, ['samples', 'p50', 'p95', 'p99', 'jitter'])) {\n return false;\n }\n return (\n Number.isInteger(value.samples) &&\n (value.samples as number) > 0 &&\n ['p50', 'p95', 'p99', 'jitter'].every(\n (key) => typeof value[key] === 'number' && Number.isFinite(value[key]) && value[key] >= 0,\n )\n );\n}\n\nexport function isExecutionReport(value: unknown): value is ExecutionReport {\n if (!isRecord(value)) return false;\n if (\n !hasExactKeys(value, [\n 'schemaVersion',\n 'requestedTier',\n 'actualTier',\n 'selectionReason',\n 'sharedEvidencePassed',\n 'capabilities',\n 'engine',\n 'world',\n 'kernelDispatch',\n 'performance',\n 'audio',\n 'fault',\n ])\n ) {\n return false;\n }\n const report = value as unknown as Partial<ExecutionReport>;\n if (report.schemaVersion !== EXECUTION_REPORT_SCHEMA_VERSION) return false;\n if (!EXECUTION_REQUESTED_TIERS.includes(report.requestedTier as never)) return false;\n if (report.actualTier !== null && !EXECUTION_TIERS.includes(report.actualTier as never)) {\n return false;\n }\n if (typeof report.sharedEvidencePassed !== 'boolean' || report.capabilities === undefined) {\n return false;\n }\n if (\n !EXECUTION_CAPABILITY_NAMES.every((name) => {\n const fact = report.capabilities?.[name];\n return typeof fact?.available === 'boolean' && typeof fact.reason === 'string';\n })\n )\n return false;\n const engine = report.engine;\n const world = report.world;\n const dispatch = report.kernelDispatch;\n const performance = report.performance;\n const audio = report.audio;\n if (!isRecord(engine) || !hasExactKeys(engine, ['realm', 'health'])) return false;\n if (!['host', 'worker'].includes(engine.realm as string)) return false;\n if (!['idle', 'starting', 'running', 'stopped', 'faulted'].includes(engine.health as string)) {\n return false;\n }\n if (\n !isRecord(world) ||\n !hasExactKeys(world, ['identity', 'health', 'partialWrite', 'retryable'])\n ) {\n return false;\n }\n if (world.identity !== null && typeof world.identity !== 'string') return false;\n if (!['healthy', 'poisoned'].includes(world.health as string)) return false;\n if (typeof world.partialWrite !== 'boolean' || typeof world.retryable !== 'boolean') return false;\n if (\n !isRecord(dispatch) ||\n !hasExactKeys(dispatch, ['eligible', 'usedShared', 'reason', 'dispatched', 'completed'])\n ) {\n return false;\n }\n if (typeof dispatch.eligible !== 'boolean' || typeof dispatch.usedShared !== 'boolean')\n return false;\n if (\n ![\n 'no-eligible-kernel',\n 'zero-work',\n 'small-span',\n 'forced-inline',\n 'shared',\n 'poisoned',\n ].includes(dispatch.reason as string)\n )\n return false;\n if (!Number.isInteger(dispatch.dispatched) || !Number.isInteger(dispatch.completed)) return false;\n if (\n !isRecord(performance) ||\n !hasExactKeys(performance, ['hostFrameMs', 'engineUpdateMs', 'kernelWaitMs', 'hostAudioMs'])\n )\n return false;\n for (const key of ['hostFrameMs', 'engineUpdateMs', 'kernelWaitMs', 'hostAudioMs'] as const) {\n const measurement = performance[key];\n if (measurement !== null && !isMeasurement(measurement)) return false;\n }\n if (\n !isRecord(audio) ||\n !hasExactKeys(audio, ['owner', 'contextState', 'activeSourceCount', 'lastError'])\n )\n return false;\n if (audio.owner !== 'host') return false;\n if (!['running', 'suspended', 'closed'].includes(audio.contextState as string)) return false;\n if (!Number.isInteger(audio.activeSourceCount) || (audio.activeSourceCount as number) < 0)\n return false;\n if (audio.lastError !== null) {\n if (!isRecord(audio.lastError)) return false;\n if (!hasExactKeys(audio.lastError, ['code', 'expected', 'hint', 'detail'])) return false;\n if (\n typeof audio.lastError.code !== 'string' ||\n typeof audio.lastError.expected !== 'string' ||\n typeof audio.lastError.hint !== 'string'\n )\n return false;\n }\n if (report.fault !== null) {\n if (!isRecord(report.fault)) return false;\n if (\n !hasExactKeys(report.fault, [\n 'source',\n 'code',\n 'expected',\n 'hint',\n 'detail',\n 'partialWrite',\n 'retryable',\n ])\n )\n return false;\n if (\n !['bootstrap', 'handshake', 'runtime', 'kernel', 'world', 'rebuild'].includes(\n report.fault.source as string,\n )\n )\n return false;\n if (\n typeof report.fault.code !== 'string' ||\n typeof report.fault.expected !== 'string' ||\n typeof report.fault.hint !== 'string'\n )\n return false;\n if (\n typeof report.fault.partialWrite !== 'boolean' ||\n typeof report.fault.retryable !== 'boolean'\n )\n return false;\n }\n return true;\n}\n","import type { AudioState } from '@forgeax/engine-audio';\nimport { EXECUTION_REPORT_SCHEMA_VERSION } from './schema';\nimport type {\n ExecutionCapabilities,\n ExecutionReport,\n ExecutionRequestedTier,\n ExecutionSelection,\n} from './types';\n\nexport function executionAudioReport(state?: AudioState): ExecutionReport['audio'] {\n const error = state?.lastError ?? null;\n return {\n owner: 'host',\n contextState: state?.contextState ?? 'suspended',\n activeSourceCount: state?.activeSourceCount ?? 0,\n lastError:\n error === null\n ? null\n : {\n code: error.code,\n expected: error.expected,\n hint: error.hint,\n detail: error.detail,\n },\n };\n}\n\nexport function createExecutionReport(\n requestedTier: ExecutionRequestedTier,\n capabilities: ExecutionCapabilities,\n selection?: ExecutionSelection,\n): ExecutionReport {\n return {\n schemaVersion: EXECUTION_REPORT_SCHEMA_VERSION,\n requestedTier,\n actualTier: selection?.actualTier ?? null,\n selectionReason: selection?.selectionReason ?? null,\n sharedEvidencePassed: selection?.sharedEvidencePassed ?? false,\n capabilities,\n engine: {\n realm: selection?.actualTier === 'main-serial' ? 'host' : 'worker',\n health: 'idle',\n },\n world: {\n identity: null,\n health: 'healthy',\n partialWrite: false,\n retryable: true,\n },\n kernelDispatch: {\n eligible: false,\n usedShared: false,\n reason: 'no-eligible-kernel',\n dispatched: 0,\n completed: 0,\n },\n performance: {\n hostFrameMs: null,\n engineUpdateMs: null,\n kernelWaitMs: null,\n hostAudioMs: null,\n },\n audio: executionAudioReport(),\n fault: null,\n };\n}\n","import type { AudioState } from '@forgeax/engine-audio';\nimport { err } from '@forgeax/engine-types';\nimport { APP_ERROR_HINTS, APP_EXPECTED, AppError } from '../errors';\nimport { executionAudioReport } from './report';\nimport type { ExecutionControl, ExecutionEngineHealth, ExecutionReport } from './types';\n\nexport function cloneExecutionReport(report: ExecutionReport): ExecutionReport {\n return structuredClone(report);\n}\n\nexport interface LocalExecutionControl extends ExecutionControl {\n setEngineHealth(health: ExecutionEngineHealth): void;\n}\n\nexport interface LocalExecutionReportProviders {\n readonly audio?: () => AudioState;\n readonly world?: () => ExecutionReport['world'];\n}\n\nexport function createLocalExecutionControl(\n initial: ExecutionReport,\n providers: LocalExecutionReportProviders = {},\n): LocalExecutionControl {\n let current = cloneExecutionReport(initial);\n return {\n setEngineHealth: (health) => {\n current = { ...current, engine: { ...current.engine, health } };\n },\n report: () =>\n cloneExecutionReport({\n ...current,\n world: providers.world?.() ?? current.world,\n audio: executionAudioReport(providers.audio?.()),\n }),\n rebuild: async () =>\n err(\n new AppError({\n code: 'app-execution-rebuild-failed',\n expected: APP_EXPECTED['app-execution-rebuild-failed'],\n hint: APP_ERROR_HINTS['app-execution-rebuild-failed'],\n detail: {\n worldIdentity: current.world.identity,\n cause: new Error('This local assembly has no bootstrap module.'),\n },\n }),\n ),\n };\n}\n","import { err, ok, type Result } from '@forgeax/engine-types';\nimport { APP_ERROR_HINTS, APP_EXPECTED, AppError, type AppError as AppErrorType } from '../errors';\nimport { missingExecutionCapabilities } from './capabilities';\nimport type {\n ExecutionCapabilities,\n ExecutionCapabilityName,\n ExecutionRequestedTier,\n ExecutionSelection,\n ExecutionTier,\n} from './types';\n\nconst ENGINE_WORKER_CAPABILITIES = [\n 'worker',\n 'offscreenCanvas',\n 'workerWebGpu',\n] as const satisfies readonly ExecutionCapabilityName[];\nconst SHARED_CAPABILITIES = [\n ...ENGINE_WORKER_CAPABILITIES,\n 'crossOriginIsolated',\n 'sharedArrayBuffer',\n 'atomicsWait',\n] as const satisfies readonly ExecutionCapabilityName[];\n\nexport interface ExecutionSelectionInput {\n readonly requestedTier: ExecutionRequestedTier;\n readonly capabilities: ExecutionCapabilities;\n readonly sharedEvidencePassed: boolean;\n}\n\nfunction requiredCapabilities(tier: ExecutionTier): readonly ExecutionCapabilityName[] {\n if (tier === 'main-serial') return [];\n if (tier === 'engine-worker') return ENGINE_WORKER_CAPABILITIES;\n return SHARED_CAPABILITIES;\n}\n\nfunction missingFor(\n tier: ExecutionTier,\n capabilities: ExecutionCapabilities,\n): readonly ExecutionCapabilityName[] {\n return missingExecutionCapabilities(capabilities, requiredCapabilities(tier));\n}\n\nexport function selectExecutionTier(\n input: ExecutionSelectionInput,\n): Result<ExecutionSelection, AppErrorType> {\n if (input.requestedTier !== 'auto') {\n const missing = missingFor(input.requestedTier, input.capabilities);\n if (missing.length > 0 || (input.requestedTier === 'shared' && !input.sharedEvidencePassed)) {\n return err(\n new AppError({\n code: 'app-execution-tier-unavailable',\n expected: APP_EXPECTED['app-execution-tier-unavailable'],\n hint: APP_ERROR_HINTS['app-execution-tier-unavailable'],\n detail: {\n requestedTier: input.requestedTier,\n missingCapabilities: missing,\n sharedEvidencePassed: input.sharedEvidencePassed,\n },\n }),\n );\n }\n return ok({\n requestedTier: input.requestedTier,\n actualTier: input.requestedTier,\n selectionReason: 'explicit-request',\n missingCapabilities: [],\n sharedEvidencePassed: input.sharedEvidencePassed,\n });\n }\n\n const sharedMissing = missingFor('shared', input.capabilities);\n if (sharedMissing.length === 0 && input.sharedEvidencePassed) {\n return ok({\n requestedTier: 'auto',\n actualTier: 'shared',\n selectionReason: 'auto-shared',\n missingCapabilities: [],\n sharedEvidencePassed: true,\n });\n }\n const workerMissing = missingFor('engine-worker', input.capabilities);\n if (workerMissing.length === 0) {\n return ok({\n requestedTier: 'auto',\n actualTier: 'engine-worker',\n selectionReason: 'auto-engine-worker',\n missingCapabilities: sharedMissing,\n sharedEvidencePassed: input.sharedEvidencePassed,\n });\n }\n return ok({\n requestedTier: 'auto',\n actualTier: 'main-serial',\n selectionReason: 'auto-main-serial',\n missingCapabilities: workerMissing,\n sharedEvidencePassed: input.sharedEvidencePassed,\n });\n}\n","import { err, ok, type Result } from '@forgeax/engine-types';\nimport { APP_ERROR_HINTS, APP_EXPECTED, AppError, type AppError as AppErrorType } from '../errors';\n\n/** Normalize a bootstrap module before any realm probing or worker startup. */\nexport function normalizeExecutionBootstrapUrl(\n bootstrap: string | URL,\n): Result<string, AppErrorType> {\n const moduleUrl = typeof bootstrap === 'string' ? bootstrap : bootstrap.href;\n try {\n return ok(new URL(bootstrap, globalThis.location?.href).href);\n } catch (cause) {\n return err(\n new AppError({\n code: 'app-execution-bootstrap-failed',\n expected: APP_EXPECTED['app-execution-bootstrap-failed'],\n hint: APP_ERROR_HINTS['app-execution-bootstrap-failed'],\n detail: {\n phase: 'prepare',\n moduleUrl,\n cause: cause instanceof TypeError ? cause : new TypeError(String(cause)),\n },\n }),\n );\n }\n}\n","// @forgeax/engine-app -- error fan-out registry + console.error fallback (M4 / w11).\n//\n// Public surface (consumed only by createApp + frame-loop -- this module\n// lives under `internal/` and is not re-exported from the package barrel):\n//\n// const fan = new ErrorFanoutRegistry({ silenceUnhandledErrors: false });\n// const off = fan.add(cb); // add listener; returns idempotent unsubscribe\n// off(); // remove listener (safe to call twice)\n// fan.fire(err); // fan out to all listeners; if none AND\n// // silenceUnhandledErrors !== true, call\n// // console.error(err)\n//\n// Wiring (per plan-strategy D-9 + research section 7.3\n// createRenderer.ts:532-566 LostListenerRegistry side-evidence):\n//\n// - Listener set is a Set so duplicate add() is idempotent (set semantics).\n// - fire() iterates over a snapshot so a listener that calls .add()/.remove()\n// mid-fire does not perturb the iteration.\n// - When the listener set is empty AND silenceUnhandledErrors !== true,\n// console.error(err) is invoked once with the structured error object as\n// the single argument. Tests pin reference equality via mock.calls[0][0]\n// so the AI-user contract (.code / .expected / .hint structure preserved)\n// is observable in browser devtools.\n// - late-attach replay is deliberately NOT implemented. rAF errors are\n// frame-time stream (each tick generates a fresh event); a replay\n// semantic would surface stale state to a freshly registered listener.\n// This is a deliberate divergence from runtime/createRenderer.ts:337-345\n// LostListenerRegistry which DOES replay (because device.lost is a\n// one-shot lifecycle event); see plan-strategy D-9 for the divergence\n// rationale.\n//\n// Architecture principle SSOT: the listener set + the silence flag are the\n// only state owned by this module; createApp passes the silence flag in via\n// constructor options and never reads it again, so the SSOT is the Registry\n// instance state.\n\nimport type { AppDispatchError } from '../types';\n\n/**\n * Listener callback for app-shell error fan-out.\n *\n * The narrow union (`AppDispatchError` = AppError | RhiError | RuntimeError)\n * deliberately excludes raw `Error` (charter P3 explicit failure: AI users\n * walk `.code` not message strings). `RuntimeError` is included so a\n * runtime-layer error fanned out by `Renderer.onError` (e.g.\n * `'equirect-projection-failed'`) reaches host App listeners verbatim\n * (feat-20260531-skybox-env-background F-1). `EngineEnvironmentError` does not\n * appear here because construction-time failure flows through\n * `Promise<Result<App, ...>>` of `createApp(canvas)` before the App handle\n * exists; once an App handle is alive, only frame-time errors (this union)\n * reach onError.\n */\nexport type ErrorFanoutListener = (err: AppDispatchError) => void;\n\n/**\n * Constructor options for ErrorFanoutRegistry. Mirrors the\n * `silenceUnhandledErrors` field on CreateAppOptions / AppAssembleArgs;\n * createApp threads the field down into the registry verbatim.\n */\nexport interface ErrorFanoutOptions {\n readonly silenceUnhandledErrors?: boolean;\n}\n\n/**\n * ErrorFanoutRegistry shares its shape with the LostListenerRegistry\n * implementation in `packages/runtime/src/createRenderer.ts:532-566` per\n * plan-strategy D-9 -- listener set + fan-out fire + idempotent unsubscribe.\n * The two divergences from the runtime registry are intentional:\n *\n * 1. Late-attach replay is NOT implemented -- rAF errors are a frame-time\n * stream (each tick produces fresh state) so replay semantics are\n * meaningless and would mislead newly registered listeners.\n * 2. `console.error(err)` fallback fires when the listener set is empty\n * and `silenceUnhandledErrors !== true` -- a charter P3 tribute that\n * makes \"unhandled\" errors loud rather than silent.\n */\nexport class ErrorFanoutRegistry {\n private readonly listeners: Set<ErrorFanoutListener> = new Set();\n private readonly silenceUnhandledErrors: boolean;\n\n constructor(opts: ErrorFanoutOptions = {}) {\n this.silenceUnhandledErrors = opts.silenceUnhandledErrors === true;\n }\n\n /**\n * Register a listener. Returns an unsubscribe function. Calling\n * unsubscribe more than once is a safe no-op (Set.delete returns\n * false on the second call but does not throw). Re-registering the\n * same listener function is a no-op (Set semantics).\n */\n add(cb: ErrorFanoutListener): () => void {\n this.listeners.add(cb);\n return () => {\n this.listeners.delete(cb);\n };\n }\n\n /**\n * Iterate over a snapshot of the listener set so a listener that\n * mutates the set mid-fire does not perturb the iteration. When the\n * set is empty AND silenceUnhandledErrors !== true, call\n * console.error(err) so the unhandled error is visible in devtools\n * (charter P3 explicit failure: silent drop is a footgun).\n */\n fire(err: AppDispatchError): void {\n if (this.listeners.size === 0) {\n if (!this.silenceUnhandledErrors) {\n // eslint-disable-next-line no-console -- charter P3 fallback\n console.error(err);\n }\n return;\n }\n const snapshot = Array.from(this.listeners);\n for (const cb of snapshot) {\n cb(err);\n }\n }\n\n /**\n * Number of currently registered listeners. Reserved for diagnostics +\n * test fixtures (e.g. asserting cleanup paths reach the registry); not\n * part of the public app-shell surface.\n *\n * @internal\n */\n _size(): number {\n return this.listeners.size;\n }\n}\n","// @forgeax/engine-app -- shared types for createApp double-SSOT entry.\n//\n// AI users: see packages/app/src/index.ts for the public surface and\n// packages/app/src/create-app.ts for the runtime implementation.\n//\n// M1 (this milestone) ships the skeleton: interfaces are final-shape, but\n// start / stop / pause / resume / onError on the returned App are stubs\n// that return Result.ok(undefined) and a no-op unsubscribe. The rAF main\n// loop, dt clamp, error fan-out, and input attach internals land in\n// later milestones (M2..M5 per plan-strategy section 7).\n\nimport type { AssetRegistry } from '@forgeax/engine-assets-runtime';\nimport type { AudioBackend } from '@forgeax/engine-audio';\nimport type { DebugDraw } from '@forgeax/engine-debug-draw';\nimport type { TimePolicy, World } from '@forgeax/engine-ecs';\nimport type {\n ActionConfig,\n InputBackend,\n PointerLockProvider,\n VirtualJoystickConfig,\n} from '@forgeax/engine-input';\nimport type { PhysicsWorld, PhysicsWorld2D } from '@forgeax/engine-physics';\nimport type { Context, Plugin } from '@forgeax/engine-plugin';\nimport type { Profiler } from '@forgeax/engine-profiler';\nimport type { RenderError, Renderer, RenderFeature, RenderProfile } from '@forgeax/engine-render';\nimport type { RhiBackendInstrumentation } from '@forgeax/engine-render/internal/construct-renderer';\nimport type { RhiError, RhiInstance } from '@forgeax/engine-rhi';\nimport type { EngineEnvironmentError } from '@forgeax/engine-runtime';\nimport type { ImportTransport, Result } from '@forgeax/engine-types';\n\nimport type { AppError, AppErrorCode } from './errors';\nimport type { ExecutionControl, ExecutionOptions } from './execution';\nimport type { RhiCapture } from './internal/rhi-capture';\n\n// Re-export AppError + AppErrorCode (the canonical SSOT lives in\n// `./errors`). Pre-M5 (M1..M4) referenced these as type-only declarations\n// inside this file; M5 collapses to the single SSOT in `./errors.ts` per\n// plan-strategy section 7 + research section 2.7.\nexport type { AppError, AppErrorCode };\n\n/**\n * Structured error union surfaced through the App `onError` fan-out + the\n * assemble-form construction Result. Derived from the `Renderer.onError`\n * channel contract `RendererError` (feat-20260704-runtime-tier1-decomposition\n * M2 / w14 / D-4) so a runtime-layer error fanned out by the renderer (e.g.\n * `'equirect-projection-failed'`) reaches host App listeners verbatim, plus the\n * App-layer `AppError`. `RendererError` = `RhiError | RenderError |\n * AssetRuntimeError | SkinError | PostProcessError`, so this equals the\n * pre-decomposition `AppError | RhiError | RuntimeError | PostProcessError`\n * exactly (RuntimeError was RenderError | AssetRuntimeError | SkinError). AI\n * users `switch (err.code)` over the union: the disjoint `AppErrorCode` /\n * `RhiErrorCode` / per-cluster `*ErrorCode` / `PostProcessErrorCode` literal\n * sets let TS narrow each arm to the concrete class.\n */\nexport type AppDispatchError = AppError | RenderError;\n\n/**\n * Per-frame draw description pulled from the host each frame\n * (feat-20260709-editor-world-partition-editorworld-super-composite / M2 / D-3).\n *\n * - `worlds` — the exact world list to render this frame, in draw order.\n * - `cameraOwner` — index into `worlds` whose cameras drive the frame.\n * - `resourceOwner`— index into `worlds` whose singleton render resources\n * (skylight / skybox / postProcessParams) drive the frame.\n *\n * The two owners are independent (M1 owner-split): an editor can render a scene\n * world's geometry through an editor world's camera while sourcing lighting from\n * a third. `cameraOwner === resourceOwner` is the single-owner degenerate case.\n *\n * @see {@link DrawSource}\n */\nexport interface DrawSourceResult {\n readonly worlds: readonly World[];\n readonly cameraOwner: number;\n readonly resourceOwner: number;\n}\n\n/**\n * Stable frame-loop phase vocabulary for opt-in performance diagnostics.\n *\n * Local and Worker execution record these phases through the same optional\n * Profiler capability. When omitted, the frame loop keeps its normal path and\n * does not allocate capture records.\n */\nexport const APP_PHASE_CATALOG = [\n 'frame-total',\n 'draw-source',\n 'world-update-primary',\n 'world-update-injected',\n 'renderer-draw',\n 'host-frame',\n 'engine-update',\n 'kernel-wait',\n 'host-audio',\n] as const;\n\n/**\n * Optional per-frame draw-source injection seam\n * (feat-20260709-editor-world-partition-editorworld-super-composite / M2 / D-3).\n *\n * The frame-loop invokes this callback once per frame (a \"pull\"). It lets a host\n * (e.g. the editor) decide, each frame, WHICH worlds to render and which owner\n * indices to use — without the engine knowing anything about editor world\n * partitioning.\n *\n * - Returns `undefined` → the frame-loop degrades to the single-world path,\n * byte-identical to `renderer.draw([world], { cameraOwner: 0, resourceOwner: 0 })` where `world` is\n * the App's own world (the single-world AI-user default). A host that wires\n * the seam but has nothing multi-world to inject this frame returns\n * `undefined`.\n * - Returns a {@link DrawSourceResult} → the frame-loop runs `world.update(1 / 60).unwrap()`\n * on EVERY returned world (so transform propagation writes each world's\n * derived `Transform.world` mat4 before extract reads it — no stale matrix),\n * then calls `renderer.draw(worlds, { cameraOwner, resourceOwner })`.\n *\n * When omitted entirely, the App never consults a seam and always renders its\n * own single world (legacy behaviour unchanged).\n */\nexport type DrawSource = () => DrawSourceResult | undefined;\n\n/**\n * Options for the assemble-form entry createApp({ renderer, world, ... }).\n *\n * Field semantics (final shape -- runtime use lands in M2..M5):\n * - renderer: caller-owned Renderer (host already invoked createRenderer).\n * - world: caller-owned World (host already invoked new World()).\n * - input: InputBackend handle the host-side attached. When omitted the\n * assemble entry skips input attach (caller manages input).\n * - silenceUnhandledErrors: when true, suppresses the console.error\n * fallback inside the error fan-out (M4).\n */\nexport interface AppAssembleArgs {\n readonly renderer: Renderer;\n /** Host-owned asset catalogue paired with the renderer construction. */\n readonly assets?: AssetRegistry;\n readonly world: World;\n /** Unified plugin list (M1 feat-20260623-plugin-system-unify-build-world-protocol). */\n readonly plugins?: readonly Plugin[];\n readonly silenceUnhandledErrors?: boolean;\n /**\n * Per-frame draw-source injection seam (M2 / D-3). When supplied, the\n * frame-loop pulls it each frame to decide which worlds to render + which\n * owner indices to use; when omitted the App renders its own single world\n * (legacy behaviour). See {@link DrawSource}.\n */\n readonly drawSource?: DrawSource;\n /** Explicit profiler capability shared by the host and renderer. */\n readonly profiler?: Profiler;\n}\n\n/** Effective physical canvas size transported to an Engine Worker frame. */\nexport interface CanvasDrawingBufferSize {\n readonly width: number;\n readonly height: number;\n}\n\n/**\n * Options for the canvas-form thin wrapper createApp(canvas, opts?, bundler?).\n *\n * feat-20260608-create-app-param-surface-trim / M2 / D-3: self-describing\n * surface -- no longer `extends RendererOptions`. The 7 app-only fields\n * (input / audio / physics / silenceUnhandledErrors) plus the RHI escape-hatch\n * field (rhi) are\n * listed inline, so IDE autocomplete shows AI users a clean surface\n * without inheriting now-disallowed slots like clearColor (M1, on Camera)\n * and shaderManifestUrl (M2, on BundlerOptions / 3rd arg). The escape\n * hatches stay discoverable for the RHI debugging path (charter P1 -- not\n * default noise, but reachable when the AI user scrolls the type).\n */\nexport interface CreateAppOptions {\n /** Opt into realm-local engine execution. Omission preserves the existing local assembly path. */\n readonly execution?: ExecutionOptions;\n /** Host-owned UI root whose events do not enter gameplay input. */\n readonly uiRoot?: Node;\n /** Producer-owned render features forwarded to the renderer unchanged. */\n readonly features?: readonly RenderFeature<unknown>[];\n /** Standard profile forwarded to the single renderer-owned pipeline. */\n readonly standardProfile?: RenderProfile;\n /** Unified plugin list (M1 feat-20260623-plugin-system-unify-build-world-protocol). */\n readonly plugins?: readonly Plugin[];\n /**\n * A host-owned input backend for this canvas. When supplied, createApp inserts\n * it into the World instead of attaching a second browser listener set. The\n * host retains its lifecycle; this app only consumes snapshots from the view.\n */\n readonly input?: InputBackend;\n /**\n * World-owned time policy supplied to the canvas-form World constructor.\n * Assemble-form callers retain their pre-existing World policy.\n */\n readonly time?: TimePolicy;\n /**\n * When true, suppresses the console.error fallback inside the error\n * fan-out for hosts that prefer total silence (M4 default: false).\n */\n readonly silenceUnhandledErrors?: boolean;\n /**\n * RHI escape hatch -- forwarded verbatim to createRenderer. Same semantics\n * as `RendererOptions.rhi` (the createRenderer third-party-RHI-instance\n * injection point). Use only for testing / pinning a specific backend /\n * advanced AI users that ship their own RhiInstance shim.\n */\n readonly rhi?: RhiInstance | undefined;\n /** Optional host-owned RHI lifecycle instrumentation, such as recording. */\n readonly rhiInstrumentation?: RhiBackendInstrumentation;\n /**\n * Neutral PointerLock gate forwarded verbatim to the canvas-form input\n * attach (attachInputAuto → attachBrowserInputBackend). When it returns\n * false, a canvas click does NOT capture the cursor. Absent => always-lock\n * (standalone game behaviour). The engine never learns WHY locking is\n * (dis)allowed — the host owns that decision (e.g. an editor viewport that\n * only allows lock in its play·game quadrant). Ignored by the assemble form\n * (host-managed input owns its own lock policy).\n */\n readonly pointerLockAllowed?: () => boolean;\n /**\n * Virtual joystick configs forwarded verbatim to the canvas-form input\n * attach (attachInputAuto -> attachBrowserInputBackend). Each config derives\n * a normalized 2D axis readable via `snap.virtualAxis(name)`. Absent => no\n * virtual joysticks. Ignored by the assemble form (host-managed input wires\n * its own backend). Mirrors `pointerLockAllowed`: the canvas-form entry must\n * expose every backend option the standard recipe needs, or the config path\n * dead-ends before reaching the backend that already supports it.\n */\n readonly virtualJoysticks?: readonly VirtualJoystickConfig[];\n /**\n * Action mapping configuration (M1: action semantic abstraction layer).\n *\n * Declares named actions (e.g. 'jump', 'moveRight') bound to raw input sources\n * (key, mouseButton, gamepadButton, gamepadAxis). The engine derives per-frame\n * action states via `deriveActionStates()` and exposes them via\n * `snap.action(name).isPressed()`. Duplicate action names follow last-wins\n * semantics (D-8).\n *\n * This is canvas-form only. Assemble-form hosts insert the\n * `INPUT_MAP_KEY` Resource directly.\n */\n readonly inputMap?: readonly ActionConfig[] | undefined;\n /**\n * M2: pointer-lock provider injected by the host (e.g. editor play-runtime).\n * Forwarded verbatim through InputAttachOptions to BrowserInputBackendOptions.\n * When absent, the backend falls back to the W3C requestPointerLock() path.\n * Type SSOT is @forgeax/engine-input's PointerLockProvider.\n * Ignored by the assemble form (host-managed input owns its own lock policy).\n */\n readonly lockProvider?: PointerLockProvider;\n /**\n * Per-frame draw-source injection seam (M2 / D-3). When supplied, the\n * frame-loop pulls it each frame to decide which worlds to render + which\n * owner indices to use; when omitted the canvas-form App renders its own\n * single world (legacy behaviour unchanged). See {@link DrawSource}.\n */\n readonly drawSource?: DrawSource;\n /** Explicit profiler capability shared by the host and renderer. */\n readonly profiler?: Profiler;\n}\n\n/**\n * Bundler-layer injection for the canvas-form createApp(canvas, opts, bundler?)\n * and createRenderer(canvas, opts, bundler?).\n *\n * feat-20260608-create-app-param-surface-trim / M2 / D-3: this is the SSOT\n * for build-tool emit knowledge that the engine consumes at runtime.\n * Aggregates two host-injected channels:\n *\n * - importTransport: dev-only ImportTransport that the engine threads to\n * the AssetRegistry third ctor slot so a DDC miss can lazy-import.\n * Absent => shipped form (DDC miss fails fast with `asset-not-imported`).\n *\n * - shaderManifestUrl: the path the host's vite-plugin-shader emit step\n * wrote `manifest.json` to. Absent (or `BundlerOptions` itself omitted)\n * => createRenderer falls back to '/shaders/manifest.json'\n * (createRenderer.ts D-2 q5-A) so the LO 1.1 zero-config takeoff path\n * keeps working without any explicit injection.\n *\n * Both fields are optional so `BundlerOptions = {}` is a valid call shape.\n * M3 collapses the typical demo callsite to `forgeaxBundlerAdapter()` (a\n * factory exported by `virtual:forgeax/bundler`), which returns an object\n * with this same structural shape -- type compatibility is enforced by\n * TypeScript structural typing (D-4: vite-plugin-shader does NOT import\n * `@forgeax/engine-app`, so this interface is the consumer-side SSOT).\n */\nexport interface BundlerOptions {\n /**\n * Dev-only ImportTransport forwarded verbatim to createRenderer (and thence\n * to the AssetRegistry third ctor slot). Absent => shipped form (a DDC miss\n * fails fast with `asset-not-imported`).\n *\n * The `| undefined` widening is necessary because exactOptionalPropertyTypes\n * is enabled at the workspace level (tsconfig.base.json); it lets tests\n * (and demos that gate on a build-mode flag) write `{ importTransport:\n * undefined }` without a TS2379 error.\n */\n readonly importTransport?: ImportTransport | undefined;\n /**\n * vite-plugin-shader emit URL (the path the build wrote `manifest.json`\n * to). Absent => createRenderer falls back to '/shaders/manifest.json'.\n * Tests can inject via a `data:application/json,...` URL to bypass fetch.\n *\n * The `| undefined` widening lets tests opt into the zero-entry mode by\n * writing `{ shaderManifestUrl: undefined }` (the createRenderer body\n * checks `'shaderManifestUrl' in bundler` to distinguish \"absent\" from\n * \"explicitly undefined\"; see D-2 q5-A in plan-strategy).\n */\n readonly shaderManifestUrl?: string | undefined;\n}\n\n/**\n * App handle returned by createApp(...). Host owns the lifecycle and\n * interacts with the rAF loop through start / stop / pause / resume +\n * the structured error fan-out via onError.\n *\n * M1 skeleton: start / stop / pause / resume return Result.ok(undefined)\n * synchronously and onError returns a no-op unsubscribe. The 4-state\n * machine + idempotent transitions land in M2 (plan-strategy section 7).\n */\nexport interface App {\n /** Caller-owned Renderer (reference equality with the assemble input). */\n readonly renderer: Renderer;\n /** Host-owned asset catalogue paired with this renderer lease. */\n readonly assets?: AssetRegistry;\n /** Caller-owned World (reference equality with the assemble input). */\n readonly world: World;\n /** Host-side lifecycle and immutable diagnostics for the selected execution tier. */\n readonly execution: ExecutionControl;\n /**\n * Pause frame submission and relinquish the renderer presentation surface\n * without replacing World, Renderer, AssetRegistry, plugins, or history.\n */\n releaseSurfacePreserveWorld(): Promise<Result<void, RhiError | RenderError>>;\n /** Restore the same surface and resume only when release paused a running App. */\n restoreSurface(): Promise<Result<void, RhiError | RenderError>>;\n /** Native Cordis realm that owns this App's capability fibers and effects. */\n readonly pluginContext: Context;\n /** InputBackend handle when input attach is enabled; undefined otherwise. */\n readonly input?: InputBackend;\n /** AudioBackend handle when audio attach is enabled; undefined otherwise. */\n readonly audio?: AudioBackend;\n /**\n * PhysicsWorld handle when physicsPlugin is loaded; undefined\n * otherwise. physicsPlugin.build awaits the WASM import -- createApp\n * resolves ONLY after the WASM module is loaded, so this field is\n * populated immediately when createApp returns (AC-06: no timing gap).\n */\n readonly physics?: PhysicsWorld | PhysicsWorld2D | undefined;\n /**\n * Immediate-mode debug-draw overlay instance (feat-20260615 debug-draw M5).\n *\n * Created automatically during createApp (canvas form). AI users call\n * `app.debugDraw.line(a, b, RED)` in any system and the overlay renders\n * at frame-end via the render-graph's debug-overlay pass. Shape calls are\n * immediate-mode — vertices accumulate per-frame and are flushed at the\n * tonemap suffix; stale data from frame N-1 is never visible in frame N.\n *\n * Undefined when debug-draw is not wired (assemble-form createApp with\n * no explicit debugDraw creation — the auto-attach is canvas-form only).\n */\n readonly debugDraw?: DebugDraw | undefined;\n /**\n * Begin rAF scheduling. Idempotent guard lands in M2:\n * - first call: Result.ok(undefined)\n * - second call (already running): Result.err({ code: 'app-already-running' })\n * M1 stub returns Result.ok(undefined) unconditionally.\n */\n start(): Result<void, AppError>;\n /**\n * Stop rAF scheduling. State-machine semantics land in M2:\n * - 'idle' / 'stopped' state: Result.err({ code: 'app-not-started' })\n * - 'running' / 'paused' state: Result.ok(undefined)\n * M1 stub returns Result.ok(undefined) unconditionally.\n */\n stop(): Result<void, AppError>;\n /** Tear down plugins, host resources, and renderer ownership. */\n dispose(): Promise<Result<void, AppError>>;\n /**\n * Pause rAF scheduling. Idempotent in 'paused' state. M1 stub returns\n * Result.ok(undefined) unconditionally; full state machine in M2.\n */\n pause(): Result<void, AppError>;\n /**\n * Resume rAF scheduling from paused state. M1 stub returns\n * Result.ok(undefined) unconditionally; full state machine in M2.\n */\n resume(): Result<void, AppError>;\n /**\n * Advance one complete update/draw frame through the App-owned frame authority.\n * The App must be paused; deterministic tools supply the explicit delta.\n */\n stepFrame(deltaSeconds: number): Result<void, AppDispatchError>;\n /**\n * Subscribe to structured errors fan-out from the rAF loop. Returns an\n * unsubscribe handle. The callback signature deliberately excludes raw\n * Error (charter P3 -- AI users walk .code, not message strings).\n *\n * M1 stub: registers nothing and returns a no-op unsubscribe; full\n * fan-out registry lands in M4 (plan-strategy section 7).\n */\n onError(cb: (err: AppDispatchError) => void): () => void;\n /**\n * Replace the per-frame world routing pull. `undefined` restores the\n * single-world path; an injected result updates every returned secondary\n * World before drawing it with the declared owners. This changes routing,\n * not scheduling or time ownership.\n */\n setDrawSource(drawSource: DrawSource | undefined): void;\n /**\n * Most recent dispatched error retained for host self-inspection without\n * requiring an onError listener up front.\n */\n readonly lastError?: AppDispatchError | undefined;\n /** Optional single-frame RHI capture capability owned by the App host. */\n readonly rhiCapture?: RhiCapture;\n /**\n * Handle for the remote eval server started by createApp (dev mode).\n *\n * `undefined` in production builds and headless/dawn-node without explicit\n * opt-in. When present, the host can read `app.remote.port` for WS connection\n * details or call `await app.remote.close()` to tear down the server\n * (feat-20260629-inspector-two-layer-model M4 / w20).\n *\n * Typed as {@link RemoteHandle} from `@forgeax/engine-types` — a neutral\n * package with no dependency on `@forgeax/engine-remote`.\n */\n readonly remote?: import('@forgeax/engine-types').RemoteHandle | undefined;\n}\n\n/** Host control returned by the unified execution path. Engine-owned objects remain realm-local. */\nexport type ExecutionApp = Pick<\n App,\n 'execution' | 'input' | 'audio' | 'start' | 'stop' | 'pause' | 'resume' | 'onError' | 'lastError'\n>;\n\n/**\n * Error union returned by the assemble-form entry. The canvas-form thin\n * wrapper widens this with EngineEnvironmentError (createRenderer\n * construction-time failure path -- plan-strategy D-5 / requirements AC-01).\n *\n * Cordis activation failures are projected into AppError at this boundary.\n */\nexport type AssembleAppError = AppError | RhiError;\n\n/**\n * Error union returned by the canvas-form thin wrapper. Extends\n * AssembleAppError with EngineEnvironmentError to surface\n * createRenderer construction-time failures unchanged (preserves\n * .detail.webgpuError per requirements section 6.1).\n *\n * The canvas form adds renderer construction failures.\n */\nexport type CanvasAppError = AssembleAppError | EngineEnvironmentError;\n","import { err, ok, type Result } from '@forgeax/engine-types';\nimport { APP_ERROR_HINTS, APP_EXPECTED, AppError, type AppError as AppErrorType } from '../errors';\nimport { validateExecutionBootstrapData } from './bootstrap-entry';\nimport type {\n EngineToHostMessage,\n ExecutionFaultMessage,\n ExecutionInitMessage,\n ExecutionReadyMessage,\n HostToEngineMessage,\n} from './protocol';\n\nexport interface EngineWorkerSession {\n readonly worker: Worker;\n readonly ready: ExecutionReadyMessage;\n post(message: HostToEngineMessage, transfer?: Transferable[]): void;\n listen(listener: (message: EngineToHostMessage) => void): () => void;\n dispose(): void;\n}\n\nexport interface StartEngineWorkerOptions {\n readonly canvas: HTMLCanvasElement;\n readonly bootstrapUrl: string;\n readonly bootstrapData?: import('./types').ExecutionBootstrapValue;\n readonly bootstrapPort?: MessagePort;\n readonly assetCatalog?: import('./types').ExecutionAssetCatalog;\n readonly shaderManifestUrl?: string;\n readonly time?: import('@forgeax/engine-ecs').TimePolicy;\n readonly timeoutMs: number;\n readonly tier: import('./types').ExecutionTier;\n readonly workerFactory?: () => Worker;\n}\n\nfunction deadlineError(timeoutMs: number): AppErrorType {\n return new AppError({\n code: 'app-execution-deadline-exceeded',\n expected: APP_EXPECTED['app-execution-deadline-exceeded'],\n hint: APP_ERROR_HINTS['app-execution-deadline-exceeded'],\n detail: { phase: 'handshake', timeoutMs },\n });\n}\n\nfunction startupFault(message: ExecutionFaultMessage, moduleUrl: string): AppErrorType {\n return new AppError({\n code: 'app-execution-bootstrap-failed',\n expected: APP_EXPECTED['app-execution-bootstrap-failed'],\n hint: APP_ERROR_HINTS['app-execution-bootstrap-failed'],\n detail: { phase: 'bootstrap', moduleUrl, cause: message.detail },\n });\n}\n\nexport async function startEngineWorker(\n options: StartEngineWorkerOptions,\n): Promise<Result<EngineWorkerSession, AppErrorType>> {\n const validData = validateExecutionBootstrapData(options.bootstrapData, options.bootstrapUrl);\n if (!validData.ok) return validData;\n const worker =\n options.workerFactory?.() ??\n new Worker(new URL('./engine-worker-runtime.mjs', import.meta.url), {\n type: 'module',\n name: 'forgeax-engine',\n });\n const listeners = new Set<(message: EngineToHostMessage) => void>();\n let settled = false;\n let resolveReady: (result: Result<ExecutionReadyMessage, AppErrorType>) => void = () => {};\n const readyPromise = new Promise<Result<ExecutionReadyMessage, AppErrorType>>((resolve) => {\n resolveReady = resolve;\n });\n const timeout = setTimeout(() => {\n if (settled) return;\n settled = true;\n worker.terminate();\n resolveReady(err(deadlineError(options.timeoutMs)));\n }, options.timeoutMs);\n worker.onmessage = (event: MessageEvent<EngineToHostMessage>) => {\n const message = event.data;\n if (!settled && message.kind === 'ready') {\n settled = true;\n clearTimeout(timeout);\n resolveReady(ok(message));\n } else if (!settled && message.kind === 'fault') {\n settled = true;\n clearTimeout(timeout);\n worker.terminate();\n resolveReady(err(startupFault(message, options.bootstrapUrl)));\n }\n for (const listener of listeners) listener(message);\n };\n worker.onerror = (event) => {\n if (settled) {\n const crash: ExecutionFaultMessage = {\n kind: 'fault',\n worldIdentity: null,\n source: 'runtime',\n code: 'worker-crashed',\n expected: 'Engine Worker remains alive while the App is running',\n hint: 'inspect the Worker error and create a new App; transferred canvas ownership is terminal',\n detail: { message: event.message },\n partialWrite: false,\n retryable: false,\n };\n for (const listener of listeners) listener(crash);\n return;\n }\n settled = true;\n clearTimeout(timeout);\n worker.terminate();\n resolveReady(\n err(\n startupFault(\n {\n kind: 'fault',\n worldIdentity: null,\n source: 'bootstrap',\n code: 'worker-error',\n expected: 'Engine Worker module loads',\n hint: 'inspect the Worker module graph',\n detail: { message: event.message },\n partialWrite: false,\n retryable: false,\n },\n options.bootstrapUrl,\n ),\n ),\n );\n };\n\n const offscreen = options.canvas.transferControlToOffscreen();\n const init: ExecutionInitMessage = {\n kind: 'init',\n canvas: offscreen,\n bootstrapUrl: options.bootstrapUrl,\n ...(options.bootstrapData === undefined ? {} : { bootstrapData: options.bootstrapData }),\n ...(options.bootstrapPort === undefined ? {} : { bootstrapPort: options.bootstrapPort }),\n ...(options.assetCatalog === undefined ? {} : { assetCatalog: options.assetCatalog }),\n ...(options.shaderManifestUrl !== undefined\n ? { shaderManifestUrl: options.shaderManifestUrl }\n : {}),\n ...(options.time !== undefined ? { time: options.time } : {}),\n tier: options.tier,\n };\n worker.postMessage(init, [\n offscreen,\n ...(options.bootstrapPort === undefined ? [] : [options.bootstrapPort]),\n ]);\n const ready = await readyPromise;\n if (!ready.ok) return ready;\n return ok({\n worker,\n ready: ready.value,\n post(message, transfer = []): void {\n worker.postMessage(message, transfer);\n },\n listen(listener): () => void {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n dispose(): void {\n worker.postMessage({ kind: 'dispose' } satisfies HostToEngineMessage);\n worker.terminate();\n listeners.clear();\n },\n });\n}\n","import type { ExecutionMeasurement } from './types';\n\nfunction percentile(sorted: readonly number[], fraction: number): number {\n const index = Math.min(sorted.length - 1, Math.max(0, Math.ceil(sorted.length * fraction) - 1));\n return sorted[index] ?? 0;\n}\n\nexport interface MeasurementSeries {\n add(value: number): ExecutionMeasurement;\n clear(): void;\n}\n\nexport function createMeasurementSeries(capacity = 240): MeasurementSeries {\n const values: number[] = [];\n let samples = 0;\n return {\n add(value): ExecutionMeasurement {\n samples += 1;\n values.push(value);\n if (values.length > capacity) values.shift();\n const sorted = [...values].sort((a, b) => a - b);\n let jitter = 0;\n for (let index = 1; index < values.length; index += 1) {\n jitter += Math.abs((values[index] ?? 0) - (values[index - 1] ?? 0));\n }\n return {\n samples,\n p50: percentile(sorted, 0.5),\n p95: percentile(sorted, 0.95),\n p99: percentile(sorted, 0.99),\n jitter: values.length < 2 ? 0 : jitter / (values.length - 1),\n };\n },\n clear(): void {\n values.length = 0;\n samples = 0;\n },\n };\n}\n","import type { AudioIntent } from '@forgeax/engine-audio';\nimport type { InputBackendSample } from '@forgeax/engine-input';\nimport type { CanvasDrawingBufferSize } from '../types';\nimport type { ExecutionAssetCatalog } from './types';\n\nexport interface ExecutionFrameMessage {\n readonly kind: 'frame';\n readonly worldIdentity: string;\n readonly frameId: number;\n readonly deltaSeconds: number;\n readonly inputSample: InputBackendSample;\n readonly canvasWidth: number;\n readonly canvasHeight: number;\n}\n\nexport interface ExecutionFrameCompletion {\n readonly kind: 'frame-complete';\n readonly worldIdentity: string;\n readonly frameId: number;\n readonly engineUpdateMs: number;\n readonly kernelWaitMs: number;\n readonly audioIntents?: readonly AudioIntent[];\n readonly kernelDispatch?: {\n readonly eligible: boolean;\n readonly usedShared: boolean;\n readonly reason: import('./types').KernelDispatchReason;\n readonly dispatched: number;\n readonly completed: number;\n };\n}\n\nexport type FrameCompletionDisposition = 'accepted' | 'duplicate' | 'stale-world' | 'late';\n\nexport class FrameCreditLedger {\n private nextFrameId = 1;\n private inFlight: number | null = null;\n private completed = 0;\n\n constructor(readonly worldIdentity: string) {}\n\n issue(\n deltaSeconds: number,\n sampleInput: () => InputBackendSample,\n canvasSize: CanvasDrawingBufferSize = { width: 0, height: 0 },\n ): ExecutionFrameMessage | undefined {\n if (this.inFlight !== null) return undefined;\n const frameId = this.nextFrameId;\n this.nextFrameId += 1;\n this.inFlight = frameId;\n return {\n kind: 'frame',\n worldIdentity: this.worldIdentity,\n frameId,\n deltaSeconds,\n inputSample: sampleInput(),\n canvasWidth: canvasSize.width,\n canvasHeight: canvasSize.height,\n };\n }\n\n complete(message: ExecutionFrameCompletion): FrameCompletionDisposition {\n if (message.worldIdentity !== this.worldIdentity) return 'stale-world';\n if (message.frameId <= this.completed) return 'duplicate';\n if (message.frameId !== this.inFlight) return 'late';\n this.completed = message.frameId;\n this.inFlight = null;\n return 'accepted';\n }\n\n get hasCreditInFlight(): boolean {\n return this.inFlight !== null;\n }\n}\n\nexport interface ExecutionInitMessage {\n readonly kind: 'init';\n readonly canvas: OffscreenCanvas;\n readonly bootstrapUrl: string;\n readonly bootstrapData?: import('./types').ExecutionBootstrapValue;\n readonly bootstrapPort?: MessagePort;\n /** Realm-serializable asset catalog configuration. */\n readonly assetCatalog?: ExecutionAssetCatalog;\n readonly shaderManifestUrl?: string;\n readonly time?: import('@forgeax/engine-ecs').TimePolicy;\n readonly tier: import('./types').ExecutionTier;\n}\n\nexport interface ExecutionHostControlMessage {\n readonly kind: 'host-control';\n readonly command: 'set-pointer-lock-allowed';\n readonly allowed: boolean;\n}\n\nexport interface ExecutionReadyMessage {\n readonly kind: 'ready';\n readonly worldIdentity: string;\n readonly realm: 'worker';\n readonly workerWebGpu: boolean;\n}\n\nexport interface ExecutionFaultMessage {\n readonly kind: 'fault';\n readonly worldIdentity: string | null;\n readonly source: 'bootstrap' | 'handshake' | 'runtime' | 'kernel' | 'world' | 'rebuild';\n readonly code: string;\n readonly expected: string;\n readonly hint: string;\n readonly detail: unknown;\n readonly partialWrite: boolean;\n readonly retryable: boolean;\n}\n\nexport interface ExecutionRebuildMessage {\n readonly kind: 'rebuild';\n readonly worldIdentity: string;\n}\n\nexport interface ExecutionRebuiltMessage {\n readonly kind: 'rebuilt';\n readonly previousWorldIdentity: string;\n readonly worldIdentity: string;\n}\n\nexport type HostToEngineMessage =\n | ExecutionInitMessage\n | ExecutionFrameMessage\n | ExecutionRebuildMessage\n | { readonly kind: 'dispose' };\nexport type EngineToHostMessage =\n | ExecutionReadyMessage\n | ExecutionFrameCompletion\n | ExecutionFaultMessage\n | ExecutionRebuiltMessage\n | ExecutionHostControlMessage;\n","import { createHostAudioConsumer } from '@forgeax/engine-audio-webaudio';\nimport { attachBrowserInputBackend, type InputBackend } from '@forgeax/engine-input';\nimport { err, ok, type Result } from '@forgeax/engine-types';\nimport { APP_ERROR_HINTS, APP_EXPECTED, AppError, type AppError as AppErrorType } from '../errors';\nimport { ErrorFanoutRegistry } from '../internal/error-fanout';\nimport type { BundlerOptions, CanvasDrawingBufferSize } from '../types';\nimport {\n APP_PHASE_CATALOG,\n type AppDispatchError,\n type CreateAppOptions,\n type ExecutionApp,\n} from '../types';\nimport { normalizeExecutionBootstrapUrl } from './bootstrap-url';\nimport { cloneExecutionReport } from './control';\nimport { type EngineWorkerSession, startEngineWorker } from './engine-worker';\nimport { createMeasurementSeries } from './measurement';\nimport {\n type EngineToHostMessage,\n type ExecutionFaultMessage,\n FrameCreditLedger,\n} from './protocol';\nimport { createExecutionReport, executionAudioReport } from './report';\nimport type {\n ExecutionCapabilities,\n ExecutionControl,\n ExecutionReport,\n ExecutionSelection,\n} from './types';\n\nexport interface CreateWorkerExecutionAppOptions {\n readonly canvas: HTMLCanvasElement;\n readonly appOptions: CreateAppOptions;\n /** Host-owned resize policy applied before each frame sent to the worker. */\n readonly syncCanvas?: () => CanvasDrawingBufferSize;\n readonly bundler?: BundlerOptions;\n readonly capabilities: ExecutionCapabilities;\n readonly selection: ExecutionSelection;\n}\n\nfunction lifecycleError(code: 'app-not-started' | 'app-already-running'): AppErrorType {\n return new AppError({\n code,\n expected: APP_EXPECTED[code],\n hint: APP_ERROR_HINTS[code],\n detail: {},\n });\n}\n\nfunction runtimeError(message: ExecutionFaultMessage): AppErrorType {\n if (message.code === 'shared-kernel-failed' && message.worldIdentity !== null) {\n return new AppError({\n code: 'app-execution-kernel-failed',\n expected: APP_EXPECTED['app-execution-kernel-failed'],\n hint: APP_ERROR_HINTS['app-execution-kernel-failed'],\n detail: {\n kernelName: (message.detail as { kernelName?: string })?.kernelName ?? 'unknown',\n worldIdentity: message.worldIdentity,\n cause: message.detail,\n partialWrite: true,\n retryable: false,\n },\n });\n }\n return new AppError({\n code: 'app-system-update-failed',\n expected: APP_EXPECTED['app-system-update-failed'],\n hint: APP_ERROR_HINTS['app-system-update-failed'],\n detail: { cause: message.detail },\n });\n}\n\nexport async function createWorkerExecutionApp(\n options: CreateWorkerExecutionAppOptions,\n): Promise<Result<ExecutionApp, AppErrorType>> {\n const executionOptions = options.appOptions.execution;\n if (executionOptions === undefined) throw new Error('execution options are required');\n const normalizedBootstrap = normalizeExecutionBootstrapUrl(executionOptions.bootstrap);\n if (!normalizedBootstrap.ok) return normalizedBootstrap;\n const bootstrapUrl = normalizedBootstrap.value;\n const startupTimeoutMs = executionOptions.startupTimeoutMs ?? 10_000;\n const frameTimeoutMs = executionOptions.frameTimeoutMs ?? 2_000;\n const syncCanvas = options.syncCanvas;\n const started = await startEngineWorker({\n canvas: options.canvas,\n bootstrapUrl,\n ...(executionOptions.bootstrapData === undefined\n ? {}\n : { bootstrapData: executionOptions.bootstrapData }),\n ...(executionOptions.bootstrapPort === undefined\n ? {}\n : { bootstrapPort: executionOptions.bootstrapPort }),\n ...(executionOptions.assetCatalog === undefined\n ? {}\n : { assetCatalog: executionOptions.assetCatalog }),\n ...(options.bundler?.shaderManifestUrl !== undefined\n ? { shaderManifestUrl: options.bundler.shaderManifestUrl }\n : {}),\n ...(options.appOptions.time !== undefined ? { time: options.appOptions.time } : {}),\n timeoutMs: startupTimeoutMs,\n tier: options.selection.actualTier,\n });\n if (!started.ok) return started;\n\n const session: EngineWorkerSession = started.value;\n const profiler = options.appOptions.profiler;\n const phaseCatalogRegistration = profiler?.registerPhaseCatalog('app', APP_PHASE_CATALOG);\n let releasePhaseCatalog =\n phaseCatalogRegistration?.ok === true ? phaseCatalogRegistration.value : undefined;\n const fanout = new ErrorFanoutRegistry(\n options.appOptions.silenceUnhandledErrors === undefined\n ? {}\n : { silenceUnhandledErrors: options.appOptions.silenceUnhandledErrors },\n );\n const inputHandle =\n options.appOptions.input === undefined\n ? attachBrowserInputBackend(options.canvas, {\n ...(options.appOptions.uiRoot !== undefined ? { uiRoot: options.appOptions.uiRoot } : {}),\n ...(options.appOptions.pointerLockAllowed !== undefined\n ? { pointerLockAllowed: options.appOptions.pointerLockAllowed }\n : {}),\n ...(options.appOptions.virtualJoysticks !== undefined\n ? { virtualJoysticks: options.appOptions.virtualJoysticks }\n : {}),\n ...(options.appOptions.lockProvider !== undefined\n ? { lockProvider: options.appOptions.lockProvider }\n : {}),\n onLockError: (detail) =>\n fanout.fire(\n new AppError({\n code: 'app-pointer-lock-failed',\n expected: APP_EXPECTED['app-pointer-lock-failed'],\n hint: APP_ERROR_HINTS['app-pointer-lock-failed'],\n detail,\n }),\n ),\n })\n : undefined;\n const input: InputBackend = options.appOptions.input ??\n inputHandle?.backend ?? {\n sample: () => ({\n downKeys: new Set(),\n upKeys: new Set(),\n buttons: [false, false, false],\n movementX: 0,\n movementY: 0,\n wheelDelta: 0,\n focused: true,\n pointerLocked: false,\n }),\n detach: () => {},\n };\n\n let report: ExecutionReport = {\n ...createExecutionReport(\n executionOptions.tier ?? 'auto',\n options.capabilities,\n options.selection,\n ),\n engine: { realm: 'worker', health: 'idle' },\n world: {\n identity: session.ready.worldIdentity,\n health: 'healthy',\n partialWrite: false,\n retryable: true,\n },\n };\n let state: 'idle' | 'running' | 'paused' | 'stopped' | 'faulted' = 'idle';\n let ledger = new FrameCreditLedger(session.ready.worldIdentity);\n let rafId = 0;\n let lastTimestamp = 0;\n let frameDeadline: ReturnType<typeof setTimeout> | undefined;\n let lastError: AppDispatchError | undefined;\n let rebuildResolve: ((result: Result<ExecutionReport, AppErrorType>) => void) | undefined;\n let rebuildInFlight: Promise<Result<ExecutionReport, AppErrorType>> | undefined;\n const hostFrameMeasurements = createMeasurementSeries();\n const engineMeasurements = createMeasurementSeries();\n const kernelMeasurements = createMeasurementSeries();\n const audioMeasurements = createMeasurementSeries();\n let audio = createHostAudioConsumer();\n let frameSentAt = 0;\n let profilerCaptureId: string | undefined;\n let profilerFrameId = 0;\n let frameProfile = profiler?.activeSession();\n let profileFrameOpen = false;\n let hostFrameOpen = false;\n\n const setEngineHealth = (health: ExecutionReport['engine']['health']): void => {\n report = { ...report, engine: { ...report.engine, health } };\n };\n\n const finishProfile = (): void => {\n if (hostFrameOpen) frameProfile?.endPhase();\n if (profileFrameOpen) frameProfile?.endFrame();\n frameProfile = undefined;\n profileFrameOpen = false;\n hostFrameOpen = false;\n try {\n profiler?.activeSession()?.finish();\n } catch {}\n releasePhaseCatalog?.();\n releasePhaseCatalog = undefined;\n };\n\n const terminalFault = (message: ExecutionFaultMessage): void => {\n if (frameDeadline !== undefined) {\n clearTimeout(frameDeadline);\n frameDeadline = undefined;\n }\n const error = runtimeError(message);\n lastError = error;\n state = message.partialWrite ? 'faulted' : 'stopped';\n report = {\n ...report,\n engine: { ...report.engine, health: 'faulted' },\n world: {\n identity: message.worldIdentity,\n health: message.partialWrite ? 'poisoned' : report.world.health,\n partialWrite: message.partialWrite,\n retryable: message.retryable,\n },\n kernelDispatch: {\n ...report.kernelDispatch,\n reason: message.partialWrite ? 'poisoned' : report.kernelDispatch.reason,\n },\n fault: {\n source: message.source,\n code: message.code,\n expected: message.expected,\n hint: message.hint,\n detail: message.detail,\n partialWrite: message.partialWrite,\n retryable: message.retryable,\n },\n };\n fanout.fire(error);\n if (!message.partialWrite) {\n audio.dispose();\n session.dispose();\n }\n finishProfile();\n };\n\n const scheduleFrame = (): void => {\n rafId = requestAnimationFrame((timestamp) => {\n if (state !== 'running') return;\n const deltaSeconds =\n lastTimestamp === 0 ? 0 : Math.max(0, (timestamp - lastTimestamp) / 1_000);\n lastTimestamp = timestamp;\n const canvasSize =\n syncCanvas?.() ??\n ({\n width: options.canvas.width,\n height: options.canvas.height,\n } satisfies CanvasDrawingBufferSize);\n const frame = ledger.issue(deltaSeconds, () => input.sample(), canvasSize);\n if (frame === undefined) return;\n frameProfile = profiler?.activeSession();\n if (frameProfile !== undefined && profilerCaptureId !== frameProfile.captureId) {\n profilerCaptureId = frameProfile.captureId;\n profilerFrameId = 0;\n }\n profileFrameOpen = frameProfile?.beginFrame(++profilerFrameId).ok ?? false;\n hostFrameOpen = profileFrameOpen\n ? (frameProfile?.beginPhase('app', 'host-frame').ok ?? false)\n : false;\n session.post(frame);\n frameSentAt = performance.now();\n frameDeadline = setTimeout(() => {\n if (state !== 'running') return;\n terminalFault({\n kind: 'fault',\n worldIdentity: report.world.identity,\n source: 'runtime',\n code: 'app-execution-deadline-exceeded',\n expected: APP_EXPECTED['app-execution-deadline-exceeded'],\n hint: APP_ERROR_HINTS['app-execution-deadline-exceeded'],\n detail: { phase: 'frame', timeoutMs: frameTimeoutMs },\n partialWrite: false,\n retryable: false,\n });\n }, frameTimeoutMs);\n });\n };\n\n session.listen((message: EngineToHostMessage) => {\n if (message.kind === 'frame-complete') {\n if (ledger.complete(message) !== 'accepted') return;\n if (frameDeadline !== undefined) clearTimeout(frameDeadline);\n if (hostFrameOpen) frameProfile?.endPhase();\n if (profileFrameOpen) {\n frameProfile?.recordSkip({\n source: 'app',\n phase: 'engine-update',\n reason: `worker-report:${message.engineUpdateMs.toFixed(3)}ms`,\n });\n frameProfile?.recordSkip({\n source: 'app',\n phase: 'kernel-wait',\n reason: `worker-report:${message.kernelWaitMs.toFixed(3)}ms`,\n });\n }\n const audioStarted = performance.now();\n const audioProfileOpen = profileFrameOpen\n ? (frameProfile?.beginPhase('app', 'host-audio').ok ?? false)\n : false;\n for (const intent of message.audioIntents ?? []) audio.consume(intent);\n if (audioProfileOpen) frameProfile?.endPhase();\n const audioMs = performance.now() - audioStarted;\n report = {\n ...report,\n performance: {\n ...report.performance,\n hostFrameMs: hostFrameMeasurements.add(performance.now() - frameSentAt),\n engineUpdateMs: engineMeasurements.add(message.engineUpdateMs),\n kernelWaitMs: kernelMeasurements.add(message.kernelWaitMs),\n hostAudioMs: audioMeasurements.add(audioMs),\n },\n };\n if (message.kernelDispatch !== undefined) {\n report = { ...report, kernelDispatch: message.kernelDispatch };\n }\n if (profileFrameOpen) frameProfile?.endFrame();\n frameProfile = undefined;\n profileFrameOpen = false;\n hostFrameOpen = false;\n if (state === 'running') scheduleFrame();\n } else if (message.kind === 'fault') {\n terminalFault(message);\n } else if (message.kind === 'rebuilt') {\n audio.dispose();\n audio = createHostAudioConsumer();\n ledger = new FrameCreditLedger(message.worldIdentity);\n hostFrameMeasurements.clear();\n engineMeasurements.clear();\n kernelMeasurements.clear();\n audioMeasurements.clear();\n state = 'idle';\n report = {\n ...report,\n engine: { ...report.engine, health: 'idle' },\n world: {\n identity: message.worldIdentity,\n health: 'healthy',\n partialWrite: false,\n retryable: true,\n },\n kernelDispatch: {\n eligible: false,\n usedShared: false,\n reason: 'no-eligible-kernel',\n dispatched: 0,\n completed: 0,\n },\n fault: null,\n performance: {\n hostFrameMs: null,\n engineUpdateMs: null,\n kernelWaitMs: null,\n hostAudioMs: null,\n },\n };\n rebuildResolve?.(ok(cloneExecutionReport(report)));\n rebuildResolve = undefined;\n rebuildInFlight = undefined;\n } else if (message.kind === 'host-control') {\n if (message.command === 'set-pointer-lock-allowed') {\n input.setPointerLockAllowed?.(message.allowed);\n }\n }\n });\n\n const execution: ExecutionControl = {\n report: () =>\n cloneExecutionReport({\n ...report,\n audio: executionAudioReport(audio.state()),\n }),\n rebuild: () => {\n if (rebuildInFlight !== undefined) return rebuildInFlight;\n if (state !== 'faulted' || report.world.identity === null) {\n return Promise.resolve(\n err(\n new AppError({\n code: 'app-execution-rebuild-failed',\n expected: APP_EXPECTED['app-execution-rebuild-failed'],\n hint: APP_ERROR_HINTS['app-execution-rebuild-failed'],\n detail: {\n worldIdentity: report.world.identity,\n cause: new Error('World is not in a rebuildable poisoned state.'),\n },\n }),\n ),\n );\n }\n rebuildInFlight = new Promise((resolve) => {\n rebuildResolve = resolve;\n session.post({ kind: 'rebuild', worldIdentity: report.world.identity as string });\n setTimeout(() => {\n if (rebuildResolve !== resolve) return;\n rebuildResolve = undefined;\n rebuildInFlight = undefined;\n resolve(\n err(\n new AppError({\n code: 'app-execution-deadline-exceeded',\n expected: APP_EXPECTED['app-execution-deadline-exceeded'],\n hint: APP_ERROR_HINTS['app-execution-deadline-exceeded'],\n detail: { phase: 'handshake', timeoutMs: startupTimeoutMs },\n }),\n ),\n );\n }, startupTimeoutMs);\n });\n return rebuildInFlight;\n },\n };\n\n const app: ExecutionApp = {\n execution,\n input,\n start: () => {\n if (state === 'running') return err(lifecycleError('app-already-running'));\n if (state === 'stopped' || state === 'faulted') return err(lifecycleError('app-not-started'));\n state = 'running';\n setEngineHealth('running');\n lastTimestamp = 0;\n scheduleFrame();\n return ok(undefined);\n },\n stop: () => {\n if (state !== 'running' && state !== 'paused') return err(lifecycleError('app-not-started'));\n if (state === 'running') cancelAnimationFrame(rafId);\n state = 'stopped';\n inputHandle?.();\n audio.dispose();\n session.dispose();\n setEngineHealth('stopped');\n finishProfile();\n return ok(undefined);\n },\n pause: () => {\n if (state !== 'running') return err(lifecycleError('app-not-started'));\n state = 'paused';\n cancelAnimationFrame(rafId);\n return ok(undefined);\n },\n resume: () => {\n if (state !== 'paused') return err(lifecycleError('app-not-started'));\n state = 'running';\n lastTimestamp = 0;\n scheduleFrame();\n return ok(undefined);\n },\n onError: (listener) => fanout.add(listener),\n get lastError() {\n return lastError;\n },\n };\n return ok(app);\n}\n","import type { Plugin } from '@forgeax/engine-plugin';\nimport type { RenderError, Renderer, RenderFeature, RenderResult } from '@forgeax/engine-render';\nimport type { RendererFeatureAssemblyHost } from '@forgeax/engine-render/internal/construct-renderer';\n\nexport interface RenderFeatureHost {\n installFeature(\n feature: RenderFeature<unknown>,\n ): Promise<RenderResult<RenderFeatureLease, RenderError>>;\n}\n\nexport interface RenderFeatureLease {\n release(): Promise<RenderResult<void, RenderError>>;\n}\n\nexport function createRenderFeatureHost(host: RendererFeatureAssemblyHost): RenderFeatureHost {\n return {\n async installFeature(feature) {\n const installed = await host.installRenderFeature(feature);\n if (!installed.ok) return installed;\n let released = false;\n return {\n ok: true,\n value: {\n release: async () => {\n if (released) return { ok: true, value: undefined };\n released = true;\n return host.uninstallRenderFeature(feature);\n },\n },\n };\n },\n };\n}\n\ndeclare module '@forgeax/engine-plugin' {\n interface EngineContextServices {\n renderer?: Renderer;\n renderFeatureHost?: RenderFeatureHost;\n }\n}\n\n/** Provide the renderer without transferring its host-owned lifetime. */\nexport function rendererPlugin(renderer: Renderer): Plugin {\n return {\n name: 'renderer',\n provide: 'renderer',\n apply(ctx) {\n ctx.provide('renderer', renderer);\n },\n };\n}\n\n/** Provide an App/Worker-owned Renderer and release it after dependent Fibers. */\nexport function ownedRendererPlugin(renderer: Renderer): Plugin {\n return {\n name: 'renderer',\n provide: 'renderer',\n apply(ctx) {\n ctx.provide('renderer', renderer);\n ctx.effect(() => () => renderer.dispose(), 'render/renderer');\n },\n };\n}\n\n/** Provide the App-owned late RenderFeature assembly capability. */\nexport function renderFeatureHostPlugin(host: RenderFeatureHost): Plugin {\n return {\n name: 'render-feature-host',\n provide: 'renderFeatureHost',\n apply(ctx) {\n ctx.provide('renderFeatureHost', host);\n },\n };\n}\n\n/** Install a producer feature under the same Cordis Fiber that owns the caller. */\nexport function renderFeaturePlugin(feature: RenderFeature<unknown>): Plugin {\n return {\n name: `render-feature:${feature.identity}`,\n inject: ['renderFeatureHost'],\n async apply(ctx) {\n if (ctx.renderFeatureHost === undefined) {\n throw new Error('render-feature host capability is unavailable in this App realm');\n }\n const installed = await ctx.renderFeatureHost.installFeature(feature);\n if (!installed.ok) throw installed.error;\n ctx.effect(\n () => async () => {\n const removed = await installed.value.release();\n if (!removed.ok) throw removed.error;\n },\n `render-feature/${feature.identity}`,\n );\n },\n };\n}\n","import type { AssetRegistry } from '@forgeax/engine-assets-runtime';\nimport type { Plugin } from '@forgeax/engine-plugin';\n\nconst ASSET_REGISTRY_RESOURCE_KEY = 'AssetRegistry' as const;\n\n/** Project the Renderer-owned AssetRegistry as a declared dependent service. */\nexport function rendererAssetsPlugin(assets: AssetRegistry | undefined): Plugin {\n return {\n name: 'renderer-assets',\n inject: ['renderer'],\n provide: 'assets',\n apply(ctx) {\n if (assets !== undefined) ctx.provide('assets', assets);\n },\n };\n}\n\n/** Project the realm AssetRegistry into legacy World resource lookup reversibly. */\nexport function assetsWorldPlugin(): Plugin {\n return {\n name: 'assets-world',\n inject: ['world', 'assets'],\n apply(ctx) {\n if (ctx.assets === undefined) return;\n ctx.effect(() => {\n ctx.world.insertResource(ASSET_REGISTRY_RESOURCE_KEY, ctx.assets);\n return () => {\n ctx.world.removeResource(ASSET_REGISTRY_RESOURCE_KEY);\n };\n }, 'assets/world-resource');\n },\n };\n}\n","import type { Plugin } from '@forgeax/engine-plugin';\nimport { rendererPlugin } from '../renderer-plugin';\nimport { assetsWorldPlugin, rendererAssetsPlugin } from './assets-world-plugin';\nimport type { EngineProfileBase } from './engine-profile-common';\n\n/** Assemble-form roots plus explicitly selected host capabilities. */\nexport function assembledEngineProfile(options: EngineProfileBase): Plugin[] {\n return [\n rendererPlugin(options.renderer),\n rendererAssetsPlugin(options.assets),\n assetsWorldPlugin(),\n ...(options.extensions ?? []),\n ];\n}\n","import { type Component, componentDefinition, type FieldReflection } from '@forgeax/engine-ecs';\nimport { componentSchema } from '@forgeax/engine-ecs/internal';\n\nexport type JsonValue =\n | null\n | boolean\n | number\n | string\n | readonly JsonValue[]\n | { readonly [key: string]: JsonValue };\n\nexport interface ComponentIntrospectionField {\n readonly type: string;\n readonly default?: JsonValue;\n readonly shape?: string;\n readonly transient?: boolean;\n readonly arrayMeta?: {\n readonly elementType: string;\n readonly length?: number;\n };\n readonly labels?: Readonly<Record<string, number>>;\n}\n\nexport interface ComponentIntrospectionDescriptor {\n readonly name: string;\n readonly schema: Readonly<Record<string, string>>;\n readonly fields: Readonly<Record<string, ComponentIntrospectionField>>;\n readonly meta: Readonly<Record<string, JsonValue>>;\n}\n\nfunction projectJson(value: unknown, seen: Set<object>): JsonValue | undefined {\n if (value === null) return null;\n if (typeof value === 'boolean' || typeof value === 'string') return value;\n if (typeof value === 'number') return Number.isFinite(value) ? value : undefined;\n if (typeof value !== 'object') return undefined;\n if (seen.has(value)) return undefined;\n seen.add(value);\n\n if (ArrayBuffer.isView(value)) {\n const values = Array.from(value as unknown as ArrayLike<unknown>);\n const projected = values.map((entry) => projectJson(entry, seen));\n seen.delete(value);\n return projected.every((entry) => entry !== undefined) ? (projected as JsonValue[]) : undefined;\n }\n if (Array.isArray(value)) {\n const projected = value.map((entry) => projectJson(entry, seen));\n seen.delete(value);\n return projected.every((entry) => entry !== undefined) ? (projected as JsonValue[]) : undefined;\n }\n\n const object: Record<string, JsonValue> = {};\n for (const [key, entry] of Object.entries(value)) {\n const projected = projectJson(entry, seen);\n if (projected !== undefined) object[key] = projected;\n }\n seen.delete(value);\n return object;\n}\n\nfunction isJsonRecord(\n value: JsonValue | undefined,\n): value is { readonly [key: string]: JsonValue } {\n return (\n value !== undefined && value !== null && typeof value === 'object' && !Array.isArray(value)\n );\n}\n\nfunction projectMeta(meta: Readonly<Record<string, unknown>>): Readonly<Record<string, JsonValue>> {\n const projected = projectJson(meta, new Set<object>());\n return isJsonRecord(projected) ? projected : {};\n}\n\nfunction projectField(reflection: FieldReflection): ComponentIntrospectionField {\n const field: ComponentIntrospectionField = { type: reflection.type };\n const defaultValue = projectJson(reflection.default, new Set<object>());\n if (defaultValue !== undefined) Object.assign(field, { default: defaultValue });\n if (reflection.shape !== undefined) Object.assign(field, { shape: reflection.shape });\n if (reflection.transient !== undefined) Object.assign(field, { transient: reflection.transient });\n if (reflection.arrayMeta !== undefined) {\n Object.assign(field, {\n arrayMeta: {\n elementType: reflection.arrayMeta.elementType,\n ...(reflection.arrayMeta.length !== undefined\n ? { length: reflection.arrayMeta.length }\n : {}),\n },\n });\n }\n if (reflection.labels !== undefined) Object.assign(field, { labels: { ...reflection.labels } });\n return Object.freeze(field);\n}\n\nfunction projectComponent(component: Component): ComponentIntrospectionDescriptor {\n const definition = componentDefinition(component);\n const fields: Record<string, ComponentIntrospectionField> = {};\n for (const [name, reflection] of Object.entries(definition.fields)) {\n fields[name] = projectField(reflection);\n }\n return Object.freeze({\n name: component.name,\n schema: Object.freeze({ ...componentSchema(component) }),\n fields: Object.freeze(fields),\n meta: Object.freeze(projectMeta(definition.policy.meta)),\n });\n}\n\n/** Project one World-local component catalog into transport-safe data. */\nexport function projectComponentIntrospection(\n components: ReadonlyMap<string, Component>,\n): readonly ComponentIntrospectionDescriptor[] {\n return Object.freeze(\n [...components.values()]\n .sort((left, right) => left.name.localeCompare(right.name))\n .map(projectComponent),\n );\n}\n","import type { World } from '@forgeax/engine-ecs';\nimport type { ProfileFrameToken, Profiler, RecorderSession } from '@forgeax/engine-profiler';\nimport type { RenderError, Renderer, RenderWorldLease } from '@forgeax/engine-render';\nimport { err, ok, type Result } from '@forgeax/engine-types';\n\nimport type { AppErrorCode, AppErrorDetailFor } from '../errors';\nimport { AppError } from '../errors';\nimport { APP_PHASE_CATALOG } from '../types';\n\nexport type FrameState = 'idle' | 'running' | 'paused' | 'stopped';\n\nexport interface FrameLoopOptions {\n readonly world: World;\n readonly renderer: Renderer;\n readonly onError?: (e: AppError | RenderError) => void;\n /** Optional dev-only RHI recorder hook; called once after each frame draw. */\n readonly debugRhi?: { onFrameEnd(): void };\n readonly now?: () => number;\n readonly raf?: (cb: (t: number) => void) => number;\n readonly caf?: (id: number) => void;\n readonly profiler?: Profiler;\n readonly drawSource?: () =>\n | { worlds: readonly World[]; cameraOwner: number; resourceOwner: number }\n | undefined;\n}\n\nexport interface FrameLoopHandle {\n start(): Result<void, AppError>;\n stop(): Result<void, AppError>;\n pause(): Result<void, AppError>;\n resume(): Result<void, AppError>;\n /** Run one complete update/draw frame through this loop while paused. */\n stepFrame(deltaSeconds: number): Result<void, AppError | RenderError>;\n /** Replace the per-frame world routing pull without replacing the loop. */\n setDrawSource(drawSource: FrameLoopOptions['drawSource']): void;\n getState(): FrameState;\n setStopped(): void;\n}\n\nfunction beginFrame(session: RecorderSession | undefined, frameId: number): boolean {\n if (session === undefined) return false;\n try {\n return session.beginFrame(frameId).ok;\n } catch {\n return false;\n }\n}\n\nfunction beginPhase(session: RecorderSession | undefined, phase: string): boolean {\n if (session === undefined) return false;\n try {\n return session.beginPhase('app', phase).ok;\n } catch {\n return false;\n }\n}\n\nfunction endPhase(session: RecorderSession | undefined): void {\n if (session === undefined) return;\n try {\n session.endPhase();\n } catch {\n // Profiler failures never alter the host loop.\n }\n}\n\nfunction endFrame(session: RecorderSession | undefined): void {\n if (session === undefined) return;\n try {\n session.endFrame();\n } catch {\n // Profiler failures never alter the host loop.\n }\n}\n\nfunction finishProfilerCapture(profiler: Profiler | undefined): void {\n const session = profiler?.activeSession();\n if (session === undefined) return;\n try {\n session.finish();\n } catch {\n // Profiler failures never alter the host stop transition.\n }\n}\n\nfunction makeAppError<C extends AppErrorCode>(\n code: C,\n expected: string,\n hint: string,\n detail: AppErrorDetailFor<C>,\n): AppError {\n return new AppError({ code, expected, hint, detail }) as AppError;\n}\n\nfunction makeWorldUpdateError(cause: unknown): AppError {\n return makeAppError(\n 'app-system-update-failed',\n 'world.update(deltaSeconds) completes successfully',\n 'check detail.cause for the original structured ECS error',\n { cause },\n );\n}\n\nfunction fireWorldUpdateResult(\n result: ReturnType<World['update']>,\n fireError: ((e: AppError | RenderError) => void) | undefined,\n): boolean {\n if (!result.ok && fireError !== undefined) {\n fireError(makeWorldUpdateError(result.error));\n }\n return result.ok;\n}\n\nfunction updateInjectedWorlds(\n worlds: readonly World[],\n ownWorld: World,\n deltaSeconds: number,\n fireError: ((e: AppError | RenderError) => void) | undefined,\n attachedWorlds: ReadonlySet<World>,\n updatedWorlds: Set<World>,\n): void {\n for (const injectedWorld of worlds) {\n if (\n injectedWorld === ownWorld ||\n updatedWorlds.has(injectedWorld) ||\n !attachedWorlds.has(injectedWorld)\n ) {\n continue;\n }\n try {\n if (fireWorldUpdateResult(injectedWorld.update(deltaSeconds), fireError)) {\n updatedWorlds.add(injectedWorld);\n }\n } catch (cause: unknown) {\n if (fireError !== undefined) fireError(makeWorldUpdateError(cause));\n }\n }\n}\n\nfunction resolveNow(opts: FrameLoopOptions): () => number {\n if (opts.now !== undefined) return opts.now;\n return () => {\n const perf = (globalThis as { performance?: { now?: () => number } }).performance;\n const fn = perf?.now;\n return typeof fn === 'function' ? fn.call(perf) : Date.now();\n };\n}\n\nfunction resolveRaf(opts: FrameLoopOptions): (cb: (t: number) => void) => number {\n if (opts.raf !== undefined) return opts.raf;\n const g = globalThis as { requestAnimationFrame?: (cb: (t: number) => void) => number };\n return typeof g.requestAnimationFrame === 'function'\n ? g.requestAnimationFrame.bind(globalThis)\n : () => 0;\n}\n\nfunction resolveCaf(opts: FrameLoopOptions): (id: number) => void {\n if (opts.caf !== undefined) return opts.caf;\n const g = globalThis as { cancelAnimationFrame?: (id: number) => void };\n return typeof g.cancelAnimationFrame === 'function'\n ? g.cancelAnimationFrame.bind(globalThis)\n : () => {};\n}\n\nexport function createFrameLoop(opts: FrameLoopOptions): FrameLoopHandle {\n const { world, renderer } = opts;\n const phaseCatalogRegistration = opts.profiler?.registerPhaseCatalog('app', APP_PHASE_CATALOG);\n let releasePhaseCatalog =\n phaseCatalogRegistration?.ok === true ? phaseCatalogRegistration.value : undefined;\n let drawSource = opts.drawSource;\n const now = resolveNow(opts);\n const raf = resolveRaf(opts);\n const caf = resolveCaf(opts);\n\n let state: FrameState = 'idle';\n let lastTimestamp = 0;\n let pendingFrameId = 0;\n let profilerFrameId = 0;\n let profilerCaptureId: string | undefined;\n const leases = new Map<World, RenderWorldLease>();\n\n function attachPrimary(fireError: (e: AppError | RenderError) => void): void {\n if (leases.has(world)) return;\n try {\n const result = renderer.attach(world);\n if (result.ok) leases.set(world, result.value);\n else fireError(result.error);\n } catch (cause: unknown) {\n fireError(makeWorldUpdateError(cause));\n }\n }\n\n function syncInjectedAttachments(\n worlds: readonly World[] | undefined,\n fireError?: (e: AppError | RenderError) => void,\n ): ReadonlySet<World> | undefined {\n if (worlds === undefined) {\n for (const [attached, lease] of leases) {\n if (attached !== world) {\n lease.dispose();\n leases.delete(attached);\n }\n }\n return undefined;\n }\n\n const next = new Set<World>();\n for (const candidate of worlds) {\n if (candidate === world || next.has(candidate)) continue;\n if (leases.has(candidate)) {\n next.add(candidate);\n continue;\n }\n try {\n const result = renderer.attach(candidate);\n if (result.ok) {\n leases.set(candidate, result.value);\n next.add(candidate);\n } else fireError?.(result.error);\n } catch (cause: unknown) {\n fireError?.(makeWorldUpdateError(cause));\n }\n }\n for (const [attached, lease] of leases) {\n if (attached !== world && !next.has(attached)) {\n lease.dispose();\n leases.delete(attached);\n }\n }\n return next;\n }\n\n function releaseInjectedAttachments(): void {\n syncInjectedAttachments(undefined);\n }\n\n function releaseAttachments(): void {\n releaseInjectedAttachments();\n const lease = leases.get(world);\n if (lease !== undefined) {\n lease.dispose();\n leases.delete(world);\n }\n }\n\n function runProfiledPhase<T>(\n session: RecorderSession | undefined,\n phase: string,\n action: () => T,\n ): T {\n const opened = beginPhase(session, phase);\n try {\n return action();\n } finally {\n if (opened) endPhase(session);\n }\n }\n\n function runFrame(deltaSeconds: number): Result<void, AppError | RenderError> {\n const session = opts.profiler?.activeSession();\n let profileFrame: ProfileFrameToken | undefined;\n let frameError: AppError | RenderError | undefined;\n let primaryUpdated = false;\n const reportError = (error: AppError | RenderError): void => {\n frameError ??= error;\n opts.onError?.(error);\n };\n if (session !== undefined) {\n if (profilerCaptureId !== session.captureId) {\n profilerCaptureId = session.captureId;\n profilerFrameId = 0;\n }\n const frameId = ++profilerFrameId;\n if (beginFrame(session, frameId)) {\n profileFrame = { captureId: session.captureId, frameId };\n }\n }\n\n runProfiledPhase(session, 'frame-total', () => {\n attachPrimary(reportError);\n\n runProfiledPhase(session, 'world-update-primary', () => {\n try {\n if (fireWorldUpdateResult(world.update(deltaSeconds), reportError)) {\n primaryUpdated = true;\n }\n } catch (cause: unknown) {\n reportError(makeWorldUpdateError(cause));\n }\n });\n\n let injected:\n | { worlds: readonly World[]; cameraOwner: number; resourceOwner: number }\n | undefined;\n runProfiledPhase(session, 'draw-source', () => {\n if (drawSource === undefined) return;\n try {\n injected = drawSource();\n } catch (cause: unknown) {\n reportError(makeWorldUpdateError(cause));\n }\n });\n\n const attachedInjectedWorlds = syncInjectedAttachments(injected?.worlds, reportError);\n const updatedWorlds = injected === undefined ? undefined : new Set<World>();\n if (updatedWorlds !== undefined && primaryUpdated && leases.has(world)) {\n updatedWorlds.add(world);\n }\n\n runProfiledPhase(session, 'world-update-injected', () => {\n if (\n injected !== undefined &&\n attachedInjectedWorlds !== undefined &&\n updatedWorlds !== undefined\n ) {\n updateInjectedWorlds(\n injected.worlds,\n world,\n deltaSeconds,\n reportError,\n attachedInjectedWorlds,\n updatedWorlds,\n );\n }\n });\n\n runProfiledPhase(session, 'renderer-draw', () => {\n try {\n let drawResult: ReturnType<Renderer['draw']>;\n if (injected === undefined) {\n const primaryLease = leases.get(world);\n if (!primaryUpdated || primaryLease === undefined) return;\n drawResult = renderer.draw({\n leases: [primaryLease],\n camera: { lease: primaryLease },\n environment: { lease: primaryLease },\n ...(profileFrame === undefined ? {} : { profileFrame }),\n });\n } else {\n if (updatedWorlds === undefined) return;\n const readyEntries = injected.worlds\n .filter((candidate) => updatedWorlds.has(candidate))\n .map((candidate) => ({ candidate, lease: leases.get(candidate) }))\n .filter(\n (entry): entry is { candidate: World; lease: RenderWorldLease } =>\n entry.lease !== undefined,\n );\n const readyLeases = readyEntries.map((entry) => entry.lease);\n const cameraWorld = injected.worlds[injected.cameraOwner];\n const environmentWorld = injected.worlds[injected.resourceOwner];\n if (cameraWorld === undefined || environmentWorld === undefined) return;\n const cameraLease = leases.get(cameraWorld);\n const environmentLease = leases.get(environmentWorld);\n if (\n readyLeases.length === 0 ||\n cameraLease === undefined ||\n environmentLease === undefined\n )\n return;\n drawResult = renderer.draw({\n leases: readyLeases,\n camera: { lease: cameraLease },\n environment: { lease: environmentLease },\n ...(profileFrame === undefined ? {} : { profileFrame }),\n });\n }\n if (drawResult !== undefined) {\n const result = drawResult as { ok: boolean; error?: RenderError };\n if (!result.ok && result.error !== undefined) {\n reportError(result.error);\n }\n }\n } catch (cause: unknown) {\n reportError(makeWorldUpdateError(cause));\n }\n });\n });\n endFrame(session);\n try {\n opts.debugRhi?.onFrameEnd();\n } catch {\n // Debug capture is an observational bridge. A recorder failure must not\n // change the App frame result or make the host loop stop.\n }\n return frameError === undefined ? ok(undefined) : err(frameError);\n }\n\n function tick(): void {\n if (state !== 'running') return;\n\n // Device loss is a renderer-owned degraded interval, not an application\n // stop. Keep the rAF heartbeat alive while the host performs the explicit\n // Renderer.recover() rebuild, but freeze simulation so recovery does not\n // advance the World against frames that cannot be submitted. The next\n // tick observes `alive` and resumes the normal update/draw sequence.\n const timestamp = now();\n const deltaSeconds = (timestamp - lastTimestamp) / 1000;\n lastTimestamp = timestamp;\n runFrame(deltaSeconds);\n pendingFrameId = raf(tick);\n }\n\n function releaseProfiler(): void {\n finishProfilerCapture(opts.profiler);\n releasePhaseCatalog?.();\n releasePhaseCatalog = undefined;\n }\n\n return {\n setDrawSource(nextDrawSource): void {\n if (drawSource !== nextDrawSource) syncInjectedAttachments(undefined);\n drawSource = nextDrawSource;\n },\n stepFrame(deltaSeconds): Result<void, AppError | RenderError> {\n const reason =\n state !== 'paused'\n ? 'state'\n : !Number.isFinite(deltaSeconds) || deltaSeconds < 0\n ? 'delta'\n : undefined;\n if (reason !== undefined) {\n return err(\n makeAppError(\n 'app-frame-step-invalid',\n 'state is \"paused\" and deltaSeconds is finite and non-negative',\n 'pause the App and pass a finite non-negative delta before retrying',\n { state, deltaSeconds, reason },\n ),\n );\n }\n return runFrame(deltaSeconds);\n },\n start(): Result<void, AppError> {\n if (state === 'running') {\n return err(\n makeAppError(\n 'app-already-running',\n 'state must be \"idle\" or \"paused\" to start',\n 'call stop() first or check getState() before retrying',\n {},\n ),\n );\n }\n if (state === 'stopped') {\n return err(\n makeAppError(\n 'app-not-started',\n 'frame-loop is in terminal \"stopped\" state',\n 'create a new App via createApp({...}); the existing handle is dead',\n {},\n ),\n );\n }\n lastTimestamp = now();\n state = 'running';\n pendingFrameId = raf(tick);\n return ok(undefined);\n },\n\n stop(): Result<void, AppError> {\n if (state === 'idle') {\n return err(\n makeAppError(\n 'app-not-started',\n 'state must be \"running\" to stop',\n 'check getState() before calling stop(); idle handles cannot stop',\n {},\n ),\n );\n }\n if (state === 'stopped') {\n return err(\n makeAppError(\n 'app-not-started',\n 'frame-loop is in terminal \"stopped\" state',\n 'discard this handle and create a new App',\n {},\n ),\n );\n }\n caf(pendingFrameId);\n pendingFrameId = 0;\n state = 'stopped';\n releaseAttachments();\n releaseProfiler();\n return ok(undefined);\n },\n\n pause(): Result<void, AppError> {\n if (state === 'paused') return ok(undefined);\n if (state !== 'running') {\n return err(\n makeAppError(\n 'app-not-started',\n 'state must be \"running\" or \"paused\" to pause',\n 'call start() first; idle handles cannot pause',\n {},\n ),\n );\n }\n caf(pendingFrameId);\n pendingFrameId = 0;\n state = 'paused';\n return ok(undefined);\n },\n\n resume(): Result<void, AppError> {\n if (state === 'idle' || state === 'stopped') {\n return err(\n makeAppError(\n 'app-not-started',\n 'state must be \"paused\" to resume',\n 'call start() first to leave idle; resume() expects an active handle',\n {},\n ),\n );\n }\n if (state === 'running') return ok(undefined);\n lastTimestamp = now();\n state = 'running';\n pendingFrameId = raf(tick);\n return ok(undefined);\n },\n\n getState(): FrameState {\n return state;\n },\n\n setStopped(): void {\n if (pendingFrameId !== 0) {\n caf(pendingFrameId);\n pendingFrameId = 0;\n }\n releaseAttachments();\n releaseProfiler();\n state = 'stopped';\n },\n };\n}\n","import {\n attachBrowserInputBackend,\n type BrowserInputBackendOptions,\n type InputBackend,\n type PointerLockProvider,\n type VirtualJoystickConfig,\n} from '@forgeax/engine-input';\n\nimport { APP_ERROR_HINTS, APP_EXPECTED, AppError } from '../errors';\n\n/**\n * Handle returned by attachInputAuto. Captures the backend (exposed via\n * App.input), the detach callable, and a cleanup() funnel that the\n * frame-loop / app-stop / device-lost paths share (R-4).\n */\nexport interface InputAttachHandle {\n readonly backend: InputBackend;\n cleanup(): void;\n /**\n * M2: install the error dispatch callback for onLockError events.\n * Must be called by createApp after the ErrorFanoutRegistry is created\n * (the dispatch function is created after attachInputAuto returns).\n * Idempotent — subsequent calls replace the previous callback.\n */\n setOnErrorDispatch(fn: (err: AppError) => void): void;\n}\n\n/**\n * Acquire a browser input backend. This Host helper owns only DOM listeners;\n * the Cordis input plugin owns every World resource and system contribution.\n */\n/**\n * Options forwarded to attachBrowserInputBackend at attach time. Currently only\n * the neutral PointerLock gate (host decides whether a canvas click captures the\n * cursor); the backend stays host-opaque. Optional so existing call sites are\n * unchanged.\n */\nexport interface InputAttachOptions {\n /** Host-owned UI root used to route Shadow DOM events away from gameplay. */\n readonly uiRoot?: Node;\n readonly pointerLockAllowed?: () => boolean;\n /** M3: virtual joystick configurations passed through to browser backend. */\n readonly virtualJoysticks?: readonly VirtualJoystickConfig[];\n /**\n * M2: pointer-lock provider injected by the host (e.g. editor play-runtime).\n * Forwarded to BrowserInputBackendOptions.lockProvider. When absent, the\n * backend falls back to the W3C requestPointerLock() path.\n * Type SSOT is @forgeax/engine-input's PointerLockProvider.\n */\n readonly lockProvider?: PointerLockProvider;\n}\n\nexport function attachInputAuto(\n canvas: HTMLCanvasElement,\n options: InputAttachOptions = {},\n): InputAttachHandle {\n // Mutable slot for error dispatch. The dispatch function is created by\n // createApp AFTER the ErrorFanoutRegistry is set up, so we need an\n // indirection: the backend's onLockError callback fires synchronously\n // inside the click handler, but the fan-out is ready by then because\n // createApp wires it before calling app.start().\n let onLockErrorDispatch: ((err: AppError) => void) | undefined;\n\n const backendOpts: BrowserInputBackendOptions = {\n ...(options.uiRoot ? { uiRoot: options.uiRoot } : {}),\n ...(options.pointerLockAllowed ? { pointerLockAllowed: options.pointerLockAllowed } : {}),\n ...(options.virtualJoysticks ? { virtualJoysticks: options.virtualJoysticks } : {}),\n ...(options.lockProvider ? { lockProvider: options.lockProvider } : {}),\n onLockError: (detail: { path: 'w3c' | 'provider'; cause: unknown }) => {\n // D-4: wrap the backend's onLockError signal into a structured AppError\n // and fan-out through createApp's onError channel. The dispatch function\n // is installed by setOnErrorDispatch after createApp creates the\n // ErrorFanoutRegistry. If no dispatch is set yet (e.g. during unit tests\n // that don't call setOnErrorDispatch), the error is silently dropped.\n if (onLockErrorDispatch) {\n const err = new AppError({\n code: 'app-pointer-lock-failed',\n expected: APP_EXPECTED['app-pointer-lock-failed'],\n hint: APP_ERROR_HINTS['app-pointer-lock-failed'],\n detail,\n });\n onLockErrorDispatch(err);\n }\n },\n };\n const detach = attachBrowserInputBackend(canvas, backendOpts);\n const backend = detach.backend;\n\n let cleanedUp = false;\n\n return {\n backend,\n setOnErrorDispatch(fn: (err: AppError) => void): void {\n onLockErrorDispatch = fn;\n },\n cleanup(): void {\n if (cleanedUp) {\n return;\n }\n cleanedUp = true;\n detach();\n },\n };\n}\n","import { type ActionConfig, INPUT_MAP_KEY } from '@forgeax/engine-input';\nimport type { Plugin } from '@forgeax/engine-plugin';\n\n/** Install the canvas-form action map as an App-owned World contribution. */\nexport function inputMapPlugin(configs: readonly ActionConfig[]): Plugin {\n const deduped = new Map<string, ActionConfig>();\n for (const config of configs) {\n if (config.action.length > 0) deduped.set(config.action, config);\n }\n const inputMap = Object.freeze([...deduped.values()]);\n return {\n name: 'input-map',\n inject: ['world'],\n apply(ctx) {\n ctx.effect(() => {\n ctx.world.insertResource(INPUT_MAP_KEY, inputMap);\n return () => ctx.world.removeResource(INPUT_MAP_KEY);\n }, 'input/action-map');\n },\n };\n}\n","import { Update } from '@forgeax/engine-ecs';\nimport { INPUT_BACKEND_KEY, InputFrameStartScan, InputSet } from '@forgeax/engine-input';\nimport type { Plugin } from '@forgeax/engine-plugin';\n\n/** Project one Host-owned input provider into reversible World contributions. */\nexport function inputPlugin(): Plugin {\n return {\n name: 'input',\n inject: ['world', 'input'],\n apply(ctx) {\n const world = ctx.world;\n const input = ctx.input;\n if (input === undefined) throw new Error('Cordis activated input without its provider');\n ctx.effect(() => {\n world.insertResource(INPUT_BACKEND_KEY, input);\n return () => {\n world.removeResource(INPUT_BACKEND_KEY);\n };\n }, 'input/resource');\n ctx.effect(() => {\n world.addSystems(Update, InputSet, [InputFrameStartScan]).unwrap();\n return () => world.removeSystem(Update, InputFrameStartScan.name);\n }, 'input/frame-start-scan');\n },\n };\n}\n","import type { AssetRegistry, DynamicTextureStore } from '@forgeax/engine-assets-runtime';\nimport type { World } from '@forgeax/engine-ecs';\nimport type { VertexLayoutProjection } from '@forgeax/engine-geometry';\nimport type { Profiler } from '@forgeax/engine-profiler';\nimport type {\n BindGroup,\n BindGroupLayout,\n Buffer,\n ComputePipeline,\n PipelineLayout,\n Result,\n RhiCanvasContext,\n RhiDevice,\n RhiError,\n RenderPipeline as RhiRenderPipeline,\n Sampler,\n Texture,\n TextureFormat,\n TextureView,\n} from '@forgeax/engine-rhi';\nimport type { MaterialRuntimeArtifact } from '@forgeax/engine-shader';\nimport type {\n MaterialRenderState,\n ParamSchemaEntry,\n PassKind,\n PrimitiveTopology,\n VertexAttributeMap,\n} from '@forgeax/engine-types';\nimport type { MaterialRenderProjection } from '../assembly/material/assembly';\nimport type { DeviceScope } from '../device/device-scope';\nimport type { MeshGpuHandles } from '../device/gpu-residency';\nimport type { EngineMetrics } from '../engine-metrics';\nimport type { RenderFeatureHost } from '../features/host';\nimport {\n GPU_TEXTURE_USAGE_COPY_SRC,\n GPU_TEXTURE_USAGE_RENDER_ATTACHMENT,\n GPU_TEXTURE_USAGE_TEXTURE_BINDING,\n} from '../gpu-texture-usage';\nimport type { SkylightFallback } from '../ibl/skylight-bind-group';\nimport type { HealthListenerRegistry, RhiErrorListenerRegistry } from '../lifecycle';\nimport type { StandardProfile } from '../pipeline/standard-profile';\nimport type { PipelineBuilderShaderModuleFactory } from '../pipeline-builder';\nimport type { PointsLinesInspection } from '../points-lines/inspection';\nimport type { PointsLinesRecordPlan } from '../points-lines/record';\n\nexport interface PointsLinesRecordSubmission {\n readonly plan: PointsLinesRecordPlan;\n readonly vertexBuffer: Buffer;\n readonly indexBuffer: Buffer;\n readonly layoutProjection: VertexLayoutProjection;\n}\n\nimport type {\n RenderDebugOverlay,\n RenderPipelineContext,\n RenderRecordPhase,\n} from '../render-contract';\nimport type {\n DispatchEntry,\n MaterialSnapshot,\n SkyboxSnapshot,\n SkylightSnapshot,\n} from '../render-system-extract';\nimport type { SkinPaletteAllocator } from '../systems/skin-palette-allocator';\nimport type {\n BindGroupCounts,\n DispatchCounts,\n MaterialBgAssemblyCacheEntry,\n RenderFrameState,\n ValidatedRenderable,\n} from './frame-snapshot';\nimport type { FoldDispatchPlan } from './mesh-ssbo';\n\nexport interface RenderSystemRuntime {\n readonly device: RhiDevice;\n readonly deviceScope: DeviceScope;\n readonly errorRegistry: RhiErrorListenerRegistry;\n readonly debugOverlay?: RenderDebugOverlay | undefined;\n readonly healthRegistry: HealthListenerRegistry;\n readonly getMaterialProjection?: (materialGuid: string) => MaterialRenderProjection | undefined;\n readonly getMaterialArtifact?: (specializationKey: string) => MaterialRuntimeArtifact | undefined;\n readonly getMaterialShaderPipeline?: (\n materialShaderId: string,\n isHdr: boolean,\n renderState?: MaterialRenderState,\n topology?: PrimitiveTopology,\n indexFormat?: 'uint16' | 'uint32',\n variantSet?: string,\n passKind?: PassKind,\n meshAttributes?: VertexAttributeMap,\n sampleCount?: number,\n colorFormatOverride?: GPUTextureFormat,\n shaderUvSetCount?: number,\n depthFormatOverride?: GPUTextureFormat | null,\n vertexLayout?: string,\n vertexLayoutProjection?: VertexLayoutProjection,\n ) => RhiRenderPipeline | null;\n readonly getMaterialShaderBindingContract?: (\n materialShaderId: string,\n ) => 'group-0' | 'group-0-resource' | 'view-only' | 'view-and-scene-depth' | 'render-material';\n readonly getParamSchema?: (materialShaderId: string) => readonly ParamSchemaEntry[] | undefined;\n readonly getMaterialBindGroupLayout?: (materialShaderId: string) => BindGroupLayout | undefined;\n readonly metrics: EngineMetrics;\n readonly lookupPostProcess?: (\n id: string,\n ) => import('../fullscreen-post-process-pass').PostProcessShaderEntry | undefined;\n readonly getPostProcessParamsBuffer?: (id: string) => Buffer | undefined;\n readonly getPostProcessPipeline?: (\n id: string,\n bgl: BindGroupLayout,\n colorFormat: GPUTextureFormat,\n ) => RhiRenderPipeline | null;\n readonly dynamicTextureStore?: DynamicTextureStore | undefined;\n}\n\n/** Renderer-owned bridge from retained Points/Lines facts into main geometry. */\nexport interface PointsLinesRecordOwner {\n prepare(entry: ValidatedRenderable, clustered: boolean): PointsLinesRecordSubmission | undefined;\n beginFrame(): void;\n resetForDeviceLoss(): void;\n inspections(): readonly PointsLinesInspection[];\n}\n\nexport interface PerPassResources {\n depthTexture: Texture | null;\n depthTextureView: TextureView | null;\n depthTextureWidth: number;\n depthTextureHeight: number;\n configured: boolean;\n hdrColorTexture: Texture | null;\n hdrColorView: TextureView | null;\n hdrDepthTexture: Texture | null;\n hdrDepthView: TextureView | null;\n hdrTextureWidth: number;\n hdrTextureHeight: number;\n hdrDepthSampleCount: number;\n readonly fxaaPipeline: RhiRenderPipeline | null;\n readonly fxaaBindGroupLayout: BindGroupLayout | null;\n readonly fxaaSampler: Sampler | null;\n msaaColorTexture: Texture | null;\n msaaColorView: TextureView | null;\n msaaSpriteColorTexture: Texture | null;\n msaaSpriteColorView: TextureView | null;\n msaaDepthTexture: Texture | null;\n msaaDepthView: TextureView | null;\n msaaTextureWidth: number;\n msaaTextureHeight: number;\n hdrColorMsaaTexture: Texture | null;\n hdrColorMsaaView: TextureView | null;\n readonly skyboxPipeline: RhiRenderPipeline | null;\n readonly skyboxPipelineMsaa: RhiRenderPipeline | null;\n readonly skyboxBindGroupLayout: BindGroupLayout | null;\n readonly skyboxSampler: Sampler | null;\n readonly skyboxRotationBuffer: Buffer | null;\n readonly bloomBrightPipeline: RhiRenderPipeline | null;\n readonly bloomBlurHPipeline: RhiRenderPipeline | null;\n readonly bloomBlurVPipeline: RhiRenderPipeline | null;\n readonly bloomCompositePipeline: RhiRenderPipeline | null;\n readonly bloomBrightBindGroupLayout: BindGroupLayout | null;\n readonly bloomBlurBindGroupLayout: BindGroupLayout | null;\n readonly bloomCompositeBindGroupLayout: BindGroupLayout | null;\n readonly bloomSampler: Sampler | null;\n readonly bloomBrightParamsBuffer: Buffer | null;\n readonly bloomBlurHParamsBuffer: Buffer | null;\n readonly bloomBlurVParamsBuffer: Buffer | null;\n readonly bloomCompositeParamsBuffer: Buffer | null;\n bloomBrightTexture: Texture | null;\n bloomBrightView: TextureView | null;\n bloomBrightWidth: number;\n bloomBrightHeight: number;\n bloomBlurHTexture: Texture | null;\n bloomBlurHView: TextureView | null;\n bloomBlurHWidth: number;\n bloomBlurHHeight: number;\n bloomBlurVTexture: Texture | null;\n bloomBlurVView: TextureView | null;\n bloomBlurVWidth: number;\n bloomBlurVHeight: number;\n ssaoCalcPipeline: RhiRenderPipeline | null;\n ssaoBlurPipeline: RhiRenderPipeline | null;\n ssaoBgl: BindGroupLayout | null;\n ssaoFilteringSampler: Sampler | null;\n ssaoDepthSampler: Sampler | null;\n ssaoFallbackRawView: TextureView | null;\n shadowTexture: Texture | null;\n shadowMapSize: number;\n shadowCascadeCount: number;\n shadowSampler: Sampler | null;\n shadowLightSpaceMatrix: Float32Array | null;\n shadowCsmLightViewProj: Float32Array | null;\n shadowCsmSelection: {\n readonly viewMatrix: Float32Array;\n readonly splitPlanes: Float32Array;\n } | null;\n}\n\nexport interface PipelineState {\n readonly meshes: ReadonlyMap<number, MeshGpuHandles>;\n readonly format: TextureFormat;\n readonly colorAttachmentFormat: TextureFormat;\n readonly viewBindGroupLayout: BindGroupLayout;\n readonly materialBindGroupLayout: BindGroupLayout;\n readonly meshBindGroupLayout: BindGroupLayout;\n readonly viewUniformBuffer: Buffer;\n readonly pointsLinesViewBuffer?: Buffer;\n readonly shadowCasterCascadeBuffer: Buffer;\n readonly materialUniformBuffer: { readonly buffer: Buffer; readonly sizeInBytes: number };\n readonly meshStorageBuffer: { readonly buffer: Buffer; readonly sizeInBytes: number };\n readonly pointLightsBuffer: Buffer;\n readonly spotLightsBuffer: Buffer;\n readonly instancesBindGroupLayout: BindGroupLayout;\n readonly identityInstanceBuffer: Buffer;\n readonly defaultSampler: Sampler;\n readonly nearestSampler: Sampler;\n readonly fallbackTextureView: TextureView;\n readonly unlitPipeline: RhiRenderPipeline | null;\n readonly standardPipeline: RhiRenderPipeline | null;\n readonly unlitPipelineMsaa: RhiRenderPipeline | null;\n readonly unlitPipelineHdrMsaa: RhiRenderPipeline | null;\n readonly pbrPipelineLayout: PipelineLayout | null;\n readonly hdrpPbrPipelineLayout: PipelineLayout | null;\n readonly hdrpClusterMembershipPipeline: ComputePipeline | null;\n readonly hdrpClusterMembershipBindGroupLayout: BindGroupLayout | null;\n readonly pbrSkinPipelineLayout: PipelineLayout | null;\n readonly pbrSkinMeshBindGroupLayout: BindGroupLayout | null;\n readonly skinPaletteAllocator: SkinPaletteAllocator | null;\n readonly defaultWhiteTextureView: TextureView;\n readonly defaultNormalTextureView: TextureView;\n readonly unlitPipelineHdr: RhiRenderPipeline | null;\n readonly shadowFallbackTextureView: TextureView;\n readonly shadowAtlasFallbackTextureView: TextureView;\n readonly shadowParamsBuffer: Buffer;\n readonly skylightFallback: SkylightFallback | null;\n readonly perPassResources: PerPassResources;\n}\n\nexport interface RenderSystemInternals extends RenderSystemRuntime {\n readonly canvas: HTMLCanvasElement | OffscreenCanvas;\n readonly standardProfile?: StandardProfile | undefined;\n readonly standardPipeline: RenderFrameState['activePipeline'];\n readonly featureHost?: RenderFeatureHost | undefined;\n readonly shaderModuleFactory?: PipelineBuilderShaderModuleFactory;\n readonly profiler?: Profiler | undefined;\n readonly context: RhiCanvasContext | null;\n readonly getPipelineState: () => PipelineState | null;\n readonly assets: AssetRegistry;\n readonly gpuStore: import('../device/gpu-residency').GpuResidencyCache;\n readonly growMeshSsbo?:\n | ((neededSlots: number) =>\n | { readonly ok: true }\n | {\n readonly ok: false;\n readonly code: 'mesh-ssbo-ceiling-reached' | 'mesh-ssbo-capacity-exceeded';\n readonly degradedToSlotCount: number;\n })\n | undefined;\n readonly meshSsboState?: { readonly slotCount: number } | undefined;\n readonly buildPostProcessPipeline?:\n | ((\n entry: import('../fullscreen-post-process-pass').PostProcessShaderEntry,\n bgl: BindGroupLayout,\n colorFormat: GPUTextureFormat,\n label: string,\n ) => RhiRenderPipeline | null)\n | undefined;\n}\n\nexport interface _StandardForwardSceneView {\n readonly assets: AssetRegistry;\n readonly store: import('../device/gpu-residency').GpuResidencyCache;\n readonly pipelineState: PipelineState;\n readonly runtime: RenderSystemRuntime;\n readonly validated: readonly ValidatedRenderable[];\n readonly validatedOrdered: readonly ValidatedRenderable[];\n readonly viewBindGroup: BindGroup | null;\n readonly meshBindGroup: BindGroup | null;\n readonly frameState: RenderFrameState;\n readonly dispatchCounts: DispatchCounts;\n readonly bindGroupCounts: BindGroupCounts;\n readonly skylight: SkylightSnapshot | undefined;\n readonly skylightCount: number;\n readonly skybox: SkyboxSnapshot | undefined;\n readonly profilePhase?: <T>(phase: RenderRecordPhase, action: () => T) => T;\n readonly directionalShadowCacheReuse: boolean;\n readonly world: World;\n readonly gpuDrivenEntityKeys: ReadonlySet<number>;\n readonly tonemapActive: boolean;\n readonly geometryColorView: TextureView | null;\n readonly geometryDepthView: TextureView | null;\n readonly geometryDepthKey: string | null;\n readonly skyboxActive: boolean;\n readonly splitLdrSprite: boolean;\n readonly ldrSpritePassView: TextureView | null;\n readonly transparentColorFormat?: GPUTextureFormat;\n readonly dispatch: readonly DispatchEntry[];\n readonly hdrpClusterBindGroup: BindGroup | null;\n readonly hdrpClusterMembershipBindGroup: BindGroup | null;\n readonly foldDispatchPlan: FoldDispatchPlan | null;\n readonly materialSlotIndices: readonly (readonly number[])[];\n readonly materialSlots: readonly MaterialSnapshot[];\n readonly materialSlotOwners: readonly number[];\n readonly materialSlotCount: number;\n readonly pointsLines: PointsLinesRecordOwner | undefined;\n readonly materialBgAssemblyCache: Map<string, MaterialBgAssemblyCacheEntry>;\n materialUboPayloadCache?: {\n readonly materialSlots: readonly MaterialSnapshot[];\n readonly materialSlotCount: number;\n readonly payload: Uint8Array;\n };\n hdrpSsaoBlurredView?: TextureView;\n}\n\nexport type _InternalRenderPipelineContext = RenderPipelineContext & _StandardForwardSceneView;\n\nexport type RecordProfileRunner = <T>(phase: RenderRecordPhase, action: () => T) => T;\n\nexport const STANDARD_PBR_UBO_SIZE = 304;\nexport const MATERIAL_PER_ENTITY_STRIDE = 512;\n\nexport type SwapChainFormatPair = {\n readonly storage: GPUTextureFormat;\n readonly view: GPUTextureFormat;\n readonly fallbackReason?: 'preferred-canvas-format-missing';\n};\n\nexport type SurfaceBackendKind = 'webgpu' | 'wgpu-native' | 'wgpu-webgl2' | 'null';\n\nexport function resolveSurfaceFormatPair(\n backendKind: SurfaceBackendKind,\n storage: GPUTextureFormat,\n view: GPUTextureFormat,\n): SwapChainFormatPair {\n return backendKind === 'wgpu-webgl2' ? { storage: view, view } : { storage, view };\n}\n\nexport function configureSurface(\n context: RhiCanvasContext,\n device: RhiDevice,\n format: TextureFormat,\n colorAttachmentFormat: TextureFormat,\n): Result<void, RhiError> {\n const backendKind = device.caps?.backendKind ?? 'webgpu';\n const isWebGl2 = backendKind === 'wgpu-webgl2';\n const surfaceFormats = resolveSurfaceFormatPair(\n backendKind,\n format as GPUTextureFormat,\n colorAttachmentFormat as GPUTextureFormat,\n );\n const supportsTextureBinding = device.caps?.storageBuffer ?? true;\n return context.configure({\n device,\n format: surfaceFormats.storage,\n alphaMode: isWebGl2 ? 'opaque' : 'premultiplied',\n usage:\n GPU_TEXTURE_USAGE_RENDER_ATTACHMENT |\n (supportsTextureBinding ? GPU_TEXTURE_USAGE_TEXTURE_BINDING : 0) |\n (isWebGl2 ? 0 : GPU_TEXTURE_USAGE_COPY_SRC),\n ...(!isWebGl2 ? { viewFormats: [surfaceFormats.view] } : {}),\n });\n}\n\nexport function selectSwapChainFormat(storageBufferCapable: boolean): SwapChainFormatPair {\n if (!storageBufferCapable) return { storage: 'rgba8unorm', view: 'rgba8unorm-srgb' };\n const nav = (\n globalThis as { navigator?: { gpu?: { getPreferredCanvasFormat?: () => GPUTextureFormat } } }\n ).navigator;\n const gpu = nav?.gpu;\n const getPreferred = gpu?.getPreferredCanvasFormat;\n if (gpu !== undefined && typeof getPreferred === 'function') {\n const storage = getPreferred.call(gpu);\n const view =\n storage === 'rgba8unorm'\n ? 'rgba8unorm-srgb'\n : storage === 'bgra8unorm'\n ? 'bgra8unorm-srgb'\n : storage;\n return { storage, view };\n }\n return {\n storage: 'rgba8unorm',\n view: 'rgba8unorm-srgb',\n fallbackReason: 'preferred-canvas-format-missing',\n };\n}\n","import type { DebugDraw } from '@forgeax/engine-debug-draw';\nimport { createDebugDraw } from '@forgeax/engine-debug-draw';\nimport type { RendererHostAssembly } from '@forgeax/engine-render/internal/construct-renderer';\nimport type { TextureFormat } from '@forgeax/engine-rhi';\nimport { selectSwapChainFormat } from '../../../render/src/record/render-context';\n\nexport type RendererDebugDrawHost = Pick<\n RendererHostAssembly['debugDrawHost'],\n 'initialization' | 'device' | '_internal_createShaderModule' | '_internal_setRenderOverlay'\n>;\n\n/** Create the App-owned debug overlay after the renderer has initialized. */\nexport async function createDebugDrawOnReady(\n context: RendererDebugDrawHost,\n format?: TextureFormat,\n): Promise<DebugDraw> {\n const ready = await context.initialization;\n if (!ready.ok) throw ready.error;\n\n const resolvedFormat =\n format ??\n (selectSwapChainFormat(context.device.caps.storageBuffer).view as unknown as TextureFormat);\n const result = await createDebugDraw({\n device: context.device,\n queue: context.device.queue,\n createShaderModule: context._internal_createShaderModule,\n format: resolvedFormat,\n });\n if (!result.ok) throw result.error;\n context._internal_setRenderOverlay(result.value);\n return result.value;\n}\n\n/** Release the App-owned debug overlay and clear its Render capability. */\nexport function releaseDebugDraw(context: RendererDebugDrawHost, debugDraw: DebugDraw): void {\n context._internal_setRenderOverlay(undefined);\n debugDraw.destroy();\n}\n","import {\n type AnimationPayloadLookup,\n animationPayloadsPlugin,\n animationRuntimePlugin,\n} from '@forgeax/engine-animation';\nimport type { DebugDraw } from '@forgeax/engine-debug-draw';\nimport {\n type ActionConfig,\n type InputBackend,\n inputBackendPlugin,\n ownedInputBackendPlugin,\n} from '@forgeax/engine-input';\nimport type { Plugin } from '@forgeax/engine-plugin';\nimport { renderComponentsPlugin } from '@forgeax/engine-render';\nimport { scenePlugin } from '@forgeax/engine-scene';\nimport { statePlugin } from '@forgeax/engine-state';\nimport { inputMapPlugin } from '../input-map-plugin';\nimport { inputPlugin } from '../input-plugin';\nimport {\n ownedRendererPlugin,\n type RenderFeatureHost,\n renderFeatureHostPlugin,\n} from '../renderer-plugin';\nimport { assetsWorldPlugin, rendererAssetsPlugin } from './assets-world-plugin';\nimport { createDebugDrawOnReady, type RendererDebugDrawHost, releaseDebugDraw } from './debug-draw';\nimport type { EngineProfileBase } from './engine-profile-common';\n\nexport interface MainEngineProfileOptions extends EngineProfileBase {\n readonly rendererDebugDrawHost?: RendererDebugDrawHost;\n readonly rendererFeatureHost?: RenderFeatureHost;\n readonly animationPayloads: AnimationPayloadLookup;\n readonly onDebugDrawReady?: (debugDraw: DebugDraw) => void;\n readonly input?: InputBackend;\n readonly inputDispose?: () => void;\n readonly inputMap?: readonly ActionConfig[];\n}\n\nfunction debugDrawPlugin(\n context: RendererDebugDrawHost,\n onReady: (debugDraw: DebugDraw) => void,\n): Plugin {\n return {\n name: 'debug-draw',\n async apply(ctx) {\n try {\n const debugDraw = await createDebugDrawOnReady(context);\n onReady(debugDraw);\n ctx.effect(() => () => releaseDebugDraw(context, debugDraw), 'render/debug-draw');\n } catch {\n // DebugDraw is optional; renderer error reporting owns creation failures.\n }\n },\n };\n}\n\n/** Static browser-main selection; dependency order remains owned by inject/provide. */\nexport function mainEngineProfile(options: MainEngineProfileOptions): Plugin[] {\n return [\n ownedRendererPlugin(options.renderer),\n renderComponentsPlugin(),\n ...(options.rendererFeatureHost === undefined\n ? []\n : [renderFeatureHostPlugin(options.rendererFeatureHost)]),\n rendererAssetsPlugin(options.assets),\n assetsWorldPlugin(),\n ...(options.input === undefined\n ? []\n : [\n options.inputDispose === undefined\n ? inputBackendPlugin(options.input)\n : ownedInputBackendPlugin(options.input, options.inputDispose),\n ]),\n scenePlugin(),\n animationPayloadsPlugin(options.animationPayloads),\n animationRuntimePlugin(),\n statePlugin(),\n ...(options.onDebugDrawReady === undefined || options.rendererDebugDrawHost === undefined\n ? []\n : [debugDrawPlugin(options.rendererDebugDrawHost, options.onDebugDrawReady)]),\n ...(options.input === undefined ? [] : [inputPlugin()]),\n ...(options.inputMap === undefined ? [] : [inputMapPlugin(options.inputMap)]),\n ...(options.extensions ?? []),\n ];\n}\n","// @forgeax/engine-app/internal/remote-serve-flag -- FORGEAX_ENGINE_REMOTE_SERVE\n// dual-source resolution (plan-strategy secondary D-7).\n//\n// The remote eval server is auto-started in dev mode (vite's import.meta.env.DEV)\n// and production builds skip it. Headless/dawn-node can opt in via the\n// FORGEAX_ENGINE_REMOTE_SERVE=1 env var.\n//\n// Dual sources (mirrors rhi-debug-flag.ts pattern):\n// browser (vite): import.meta.env.DEV is statically replaced by vite\n// (true in dev server, false in production build).\n// dawn-node : import.meta may be undefined; fallback to\n// globalThis.process.env.FORGEAX_ENGINE_REMOTE_SERVE === '1'.\n//\n// The SSOT precedence: import.meta.env.DEV wins when available;\n// process.env is the headless opt-in path.\n\n/** Minimal structural view of an env bag carrying the serve flag. */\ninterface RemoteServeEnv {\n readonly FORGEAX_ENGINE_REMOTE_SERVE?: string | undefined;\n}\n\n/**\n * Resolve whether the remote eval server should be started.\n *\n * Returns `true` when:\n * - vite dev mode (import.meta.env.DEV === true), OR\n * - headless/dawn-node with FORGEAX_ENGINE_REMOTE_SERVE=1 opt-in\n *\n * Returns `false` in production builds and headless without explicit opt-in.\n *\n * @param isDev flag from import.meta.env.DEV (undefined when import.meta absent)\n * @param processEnv globalThis.process?.env when present, else undefined\n */\nexport function resolveRemoteServeFlag(\n isDev: boolean | undefined,\n processEnv: RemoteServeEnv | undefined,\n): boolean {\n if (isDev === true) return true;\n if (processEnv?.FORGEAX_ENGINE_REMOTE_SERVE === '1') return true;\n return false;\n}\n","import type { Plugin } from '@forgeax/engine-plugin';\n\nexport interface RemoteServerHandle {\n readonly port: number;\n close(): Promise<void>;\n}\n\n/** Own a Node remote server with the App Fiber while App still exposes its handle. */\nexport function remoteServerPlugin(handle: RemoteServerHandle): Plugin {\n return {\n name: 'remote-server',\n apply(ctx) {\n ctx.effect(() => async () => handle.close(), 'remote/server');\n },\n };\n}\n","import type { RhiBackendInstrumentation } from '@forgeax/engine-render/internal/construct-renderer';\nimport { RhiError } from '@forgeax/engine-rhi';\nimport type {\n CaptureFrameOptions,\n EncodedTape,\n RecorderAttachment,\n RhiDebugError,\n} from '@forgeax/engine-rhi-debug';\nimport { createRhiDebugError } from '@forgeax/engine-rhi-debug';\nimport { err, ok, type Result } from '@forgeax/engine-types';\nimport type { FrameLoopHandle } from './frame-loop';\n\nexport interface RhiTapeArtifactRef {\n readonly kind: 'rhi-tape';\n readonly digest: string;\n readonly bytes: Uint8Array;\n}\n\nexport interface RhiCapture {\n captureFrame(options?: CaptureFrameOptions): Promise<Result<RhiTapeArtifactRef, RhiDebugError>>;\n}\n\ntype CaptureResult = Result<EncodedTape, RhiDebugError>;\ntype CaptureFrameDriver = Pick<FrameLoopHandle, 'getState' | 'pause' | 'resume' | 'stepFrame'>;\n\nconst captureDrivers = new WeakMap<RhiCapture, CaptureFrameDriver>();\n\nexport function createRhiCapture(attachment: RecorderAttachment): RhiCapture {\n let activeCapture: Promise<Result<RhiTapeArtifactRef, RhiDebugError>> | undefined;\n const capture: RhiCapture = {\n captureFrame(options) {\n const driver = captureDrivers.get(capture);\n if (driver === undefined) return captureAttachment(attachment, options);\n if (activeCapture !== undefined) {\n return Promise.resolve(\n err(\n createRhiDebugError('capture-busy', {\n stage: 'capture',\n cause: 'another App capture transaction is active',\n }),\n ),\n );\n }\n const request = captureWithAppFrame(attachment, driver, options);\n activeCapture = request;\n void request.then(\n () => {\n if (activeCapture === request) activeCapture = undefined;\n },\n () => {\n if (activeCapture === request) activeCapture = undefined;\n },\n );\n return request;\n },\n };\n return capture;\n}\n\n/** Bind the App-owned frame authority to its host capture capability. */\nexport function bindRhiCaptureFrameDriver(capture: RhiCapture, driver: CaptureFrameDriver): void {\n captureDrivers.set(capture, driver);\n}\n\nasync function captureAttachment(\n attachment: RecorderAttachment,\n options: CaptureFrameOptions | undefined,\n): Promise<Result<RhiTapeArtifactRef, RhiDebugError>> {\n const result = await attachment.captureFrame(options);\n if (!result.ok) return result;\n return ok(toArtifact(result.value));\n}\n\nasync function captureWithAppFrame(\n attachment: RecorderAttachment,\n driver: CaptureFrameDriver,\n options: CaptureFrameOptions | undefined,\n): Promise<Result<RhiTapeArtifactRef, RhiDebugError>> {\n const state = driver.getState();\n if (state !== 'running' && state !== 'paused') {\n return err(\n createRhiDebugError('capture-unavailable', {\n stage: 'capture',\n cause: `App capture requires a running or paused frame loop, received '${state}'`,\n }),\n );\n }\n if (options?.signal?.aborted) return captureAttachment(attachment, options);\n\n const resumeAfter = state === 'running';\n if (resumeAfter) {\n const paused = driver.pause();\n if (!paused.ok) {\n return err(\n createRhiDebugError('capture-unavailable', {\n stage: 'capture',\n cause: `App capture could not pause the frame loop: ${describeFailure(paused.error)}`,\n }),\n );\n }\n }\n\n const controller = new AbortController();\n const abortFromUser = (): void => controller.abort();\n options?.signal?.addEventListener('abort', abortFromUser, { once: true });\n let captureResult: Promise<CaptureResult>;\n try {\n captureResult = attachment.captureFrame({\n ...(options ?? {}),\n signal: controller.signal,\n });\n } catch (cause: unknown) {\n options?.signal?.removeEventListener('abort', abortFromUser);\n if (resumeAfter && driver.getState() === 'paused') driver.resume();\n return err(\n createRhiDebugError('capture-unavailable', {\n stage: 'capture',\n cause: `App capture could not arm the recorder: ${describeFailure(cause)}`,\n }),\n );\n }\n\n let result: CaptureResult | undefined;\n let transactionError: RhiDebugError | undefined;\n try {\n const snapshot = await attachment.frameBoundary();\n if (!snapshot.ok) {\n result = await captureResult;\n } else if (options?.signal?.aborted) {\n controller.abort();\n result = await captureResult;\n } else {\n const stepped = driver.stepFrame(0);\n if (!stepped.ok) {\n transactionError = createRhiDebugError('capture-unavailable', {\n stage: 'capture',\n cause: `App capture frame failed: ${describeFailure(stepped.error)}`,\n });\n controller.abort();\n result = await captureResult;\n } else {\n result = await captureResult;\n }\n }\n } catch (cause: unknown) {\n transactionError = createRhiDebugError('capture-unavailable', {\n stage: 'capture',\n cause: `App capture transaction failed: ${describeFailure(cause)}`,\n });\n controller.abort();\n result = await captureResult;\n } finally {\n options?.signal?.removeEventListener('abort', abortFromUser);\n if (resumeAfter && driver.getState() === 'paused') {\n const resumed = driver.resume();\n if (!resumed.ok && transactionError === undefined) {\n transactionError = createRhiDebugError('capture-unavailable', {\n stage: 'capture',\n cause: `App capture could not resume the frame loop: ${describeFailure(resumed.error)}`,\n });\n }\n }\n }\n\n if (transactionError !== undefined) return err(transactionError);\n if (result === undefined) result = await captureResult;\n if (!result.ok) return result;\n return ok(toArtifact(result.value));\n}\n\nfunction describeFailure(cause: unknown): string {\n if (typeof cause === 'string') return cause;\n if (cause instanceof Error) return cause.message;\n if (typeof cause === 'object' && cause !== null && 'hint' in cause) {\n const hint = (cause as { hint?: unknown }).hint;\n if (typeof hint === 'string') return hint;\n }\n return String(cause);\n}\n\nexport function createRhiInstrumentation(\n attachment: RecorderAttachment,\n): RhiBackendInstrumentation {\n return {\n resolveSurfaceDevice(device) {\n const resolved = attachment.backend.unwrapDeviceForSurface(device);\n if (resolved.ok) return resolved;\n return err(\n new RhiError({\n code: 'rhi-not-available',\n expected: 'the recorder can resolve the wrapped surface device',\n hint: resolved.error.hint,\n }),\n );\n },\n onFrameBoundary() {\n void attachment.frameBoundary();\n },\n onDeviceLost() {\n attachment.deviceLost();\n },\n };\n}\n\nfunction toArtifact(encoded: EncodedTape): RhiTapeArtifactRef {\n return {\n kind: 'rhi-tape',\n digest: encoded.digest,\n bytes: encoded.bytes,\n };\n}\n","// @forgeax/engine-app/internal/rhi-debug-flag -- FORGEAX_ENGINE_RHI_DEBUG\n// three-segment dual-source resolution (plan-strategy D-4).\n//\n// The canvas form reads the flag from two independent sources with a precise\n// precedence + short-circuit shape so the same build serves both deployment\n// targets:\n//\n// browser (vite): `import.meta.env.FORGEAX_ENGINE_RHI_DEBUG` is statically\n// replaced by the vite-plugin-rhi-debug `define` hook.\n// dawn-node : `import.meta` may be undefined and there is no vite define,\n// so the flag arrives through `globalThis.process.env`.\n//\n// Extracting the resolution into this pure helper lets it be unit-tested across\n// the three scenarios (browser '1' / dawn-node process.env / unset) without a\n// real bundler or runtime. The call site keeps the literal `typeof import.meta\n// !== 'undefined'` prefix (C5) -- modelled here by passing `undefined` for the\n// `importMetaEnv` argument when `import.meta` is absent.\n\n/** Minimal structural view of an env bag carrying the flag. */\ninterface RhiDebugEnv {\n readonly FORGEAX_ENGINE_RHI_DEBUG?: string | undefined;\n}\n\n/**\n * Resolve the raw FORGEAX_ENGINE_RHI_DEBUG flag from the two sources.\n *\n * Precedence: `import.meta.env` wins; `globalThis.process.env` is the fallback.\n * Returns the raw string (or undefined); the caller compares `=== '1'`.\n *\n * @param importMetaEnv `import.meta.env` when `import.meta` is defined,\n * else `undefined` (models the `typeof import.meta !== 'undefined'` prefix\n * short-circuiting to a falsy first operand).\n * @param processEnv `globalThis.process?.env` when present, else `undefined`.\n */\nexport function resolveRhiDebugFlag(\n importMetaEnv: RhiDebugEnv | undefined,\n processEnv: RhiDebugEnv | undefined,\n): string | undefined {\n return importMetaEnv?.FORGEAX_ENGINE_RHI_DEBUG ?? processEnv?.FORGEAX_ENGINE_RHI_DEBUG;\n}\n","// @forgeax/engine-app -- createApp double-SSOT entry (M3 wiring).\n//\n// This file ships the final-shape signatures for both overload routes\n// (canvas thin wrapper + assemble form per plan-strategy D-5):\n//\n// - createApp({ renderer, world, ... }) -- assemble form: returns an\n// App with the supplied renderer / world wired through; the M2 rAF\n// frame-loop + state machine + dt clamp drive start / stop / pause /\n// resume. M3 lands listener-registry-backed onError + input-attach\n// plumbing: when the host passes a pre-built InputBackend through\n// args.input, the assemble form treats it as host-managed (no auto\n// attach, no auto cleanup -- the host owns the lifetime).\n//\n// - createApp(canvas, opts?) -- canvas form (M3 partial):\n// calls createRenderer(canvas, opts?), constructs a new World, and\n// (when opts.input !== false) wires the auto input-attach helper so\n// world.getResource('InputSnapshot') is populated each frame.\n// Falls through to the assemble form for the rest of the wiring.\n// Full canvas form (canvas-detached check, EngineEnvironmentError\n// catch, console.error fallback) lands in M4 (plan-strategy section 7).\n//\n// 'tagName' in arg dispatch (per plan-strategy D-5): HTMLCanvasElement\n// inherits .tagName from HTMLElement, so the property test cleanly\n// separates the canvas argument from the AppAssembleArgs plain object.\n\nimport type { AssetRegistry } from '@forgeax/engine-assets-runtime';\nimport type { AudioBackend } from '@forgeax/engine-audio';\nimport type { DebugDraw } from '@forgeax/engine-debug-draw';\nimport { createWorldContext, Update, World } from '@forgeax/engine-ecs';\nimport type { InputBackend } from '@forgeax/engine-input';\nimport type { Context, Plugin } from '@forgeax/engine-plugin';\nimport type { RenderError } from '@forgeax/engine-render';\nimport { CAMERA_PROJECTION_PERSPECTIVE, Camera, type Renderer } from '@forgeax/engine-render';\nimport type { RendererHostAssembly } from '@forgeax/engine-render/internal/construct-renderer';\nimport { RhiError } from '@forgeax/engine-rhi';\nimport {\n attachRecorder,\n type CaptureFrameOptions,\n type RecorderAttachment,\n} from '@forgeax/engine-rhi-debug';\nimport * as engineRuntimeModule from '@forgeax/engine-runtime';\nimport { EngineEnvironmentError } from '@forgeax/engine-runtime';\nimport {\n constructRuntimeRendererHost,\n loadRhiPack,\n} from '@forgeax/engine-runtime/internal/renderer-host';\nimport { err, ok, type Result } from '@forgeax/engine-types';\n\nimport { createAnimationPayloadLookup } from './animation-asset-lookup';\nimport { publishBrowserFrameSubmitted, resetBrowserFrameSubmitted } from './browser-frame-signal';\nimport type { AppErrorCode, AppErrorDetailFor } from './errors';\nimport { APP_ERROR_HINTS, APP_EXPECTED, AppError } from './errors';\nimport {\n createExecutionReport,\n type ExecutionControl,\n executionBootstrapHostPlugin,\n type PreparedExecutionBootstrap,\n prepareBootstrapEntry,\n probeExecutionCapabilities,\n selectExecutionTier,\n unavailableExecutionCapabilities,\n} from './execution';\nimport { normalizeExecutionBootstrapUrl } from './execution/bootstrap-url';\nimport { createLocalExecutionControl } from './execution/control';\nimport { createWorkerExecutionApp } from './execution/host-controller';\nimport { assembledEngineProfile } from './internal/assembled-engine-profile';\nimport { projectComponentIntrospection } from './internal/component-introspection';\nimport { ErrorFanoutRegistry } from './internal/error-fanout';\nimport { createFrameLoop } from './internal/frame-loop';\nimport { attachInputAuto } from './internal/input-attach';\nimport { mainEngineProfile } from './internal/main-engine-profile';\nimport { resolveRemoteServeFlag } from './internal/remote-serve-flag';\nimport { remoteServerPlugin } from './internal/remote-server-plugin';\nimport {\n bindRhiCaptureFrameDriver,\n createRhiCapture,\n createRhiInstrumentation,\n type RhiCapture,\n} from './internal/rhi-capture';\nimport { resolveRhiDebugFlag } from './internal/rhi-debug-flag';\nimport { createRenderFeatureHost, type RenderFeatureHost } from './renderer-plugin';\nimport type {\n App,\n AppAssembleArgs,\n AppDispatchError,\n AssembleAppError,\n BundlerOptions,\n CanvasAppError,\n CreateAppOptions,\n ExecutionApp,\n} from './types';\n\nfunction makeAppError<C extends AppErrorCode>(\n code: C,\n expected: string,\n hint: string,\n detail: AppErrorDetailFor<C>,\n): AppError {\n return new AppError({ code, expected, hint, detail }) as AppError;\n}\n\nfunction canvasAspectPlugin(canvas: HTMLCanvasElement): Plugin {\n return {\n name: 'canvas-aspect',\n inject: ['world'],\n apply(ctx) {\n ctx.effect(() => {\n const system = {\n name: 'app-sync-camera-aspect',\n queries: [],\n fn: () => {\n syncCanvasDrawingBuffer(canvas);\n syncCameraAspect(ctx.world, canvas.width, canvas.height);\n },\n };\n ctx.world.addSystem(Update, system).unwrap();\n return () => ctx.world.removeSystem(Update, system.name).unwrap();\n }, 'app/canvas-aspect');\n },\n };\n}\n\nfunction rhiDebugHostPlugin(dispose: () => void): Plugin {\n return {\n name: 'rhi-debug-host',\n apply(ctx) {\n ctx.effect(() => dispose, 'rhi-debug/host');\n },\n };\n}\n\n/**\n * createApp(canvas, opts?, bundler?) -- canvas thin wrapper SSOT (per\n * plan-strategy D-5). Resolves with Result.ok(app) on success; failure routes\n * through AppError | RhiError | EngineEnvironmentError per requirements AC-01.\n *\n * feat-20260608-create-app-param-surface-trim / M2 / D-3: the third arg is\n * `BundlerOptions` (importTransport + shaderManifestUrl) -- the SSOT for\n * host-injected build-tool emit knowledge. M3 demos collapse the third-arg\n * literal to `forgeaxBundlerAdapter()` exported by `virtual:forgeax/bundler`.\n *\n * M3 ships the path needed by AC-05 (auto input acquisition plus an ECS scan\n * plugin). M4 finalises the canvas-detached guard +\n * EngineEnvironmentError try/catch + onError default fallback.\n *\n * The host-engine contract defines the boundary between host (DOM, canvas, UI)\n * and engine (renderer, world, frame loop). Only the `createApp(canvas)` path\n * auto-wires the aspect-sync sidecar; the assemble form and bare\n * `createRenderer` path do not.\n *\n * @see {@link https://github.com/Ubpa/forgeax-engine/blob/main/docs/how-to/2026-06-18-host-engine-contract.md | Host-engine contract SSOT}\n */\nexport function createApp(\n canvas: HTMLCanvasElement,\n opts: CreateAppOptions & { readonly execution: NonNullable<CreateAppOptions['execution']> },\n bundler?: BundlerOptions,\n): Promise<Result<ExecutionApp, CanvasAppError>>;\nexport function createApp(\n canvas: HTMLCanvasElement,\n opts?: CreateAppOptions,\n bundler?: BundlerOptions,\n): Promise<Result<App, CanvasAppError>>;\n\n/**\n * Create the browser host for the single RenderScene -> FrameReceipt path.\n * `createApp({ renderer, world, input?, schedule?, ... })` is the assemble form\n * SSOT (per plan-strategy D-5). Host already owns renderer / world; the\n * returned App holds them by reference equality (per AC-02).\n *\n * M3 wires the rAF frame-loop + listener-registry-backed onError. When\n * args.input is supplied, the assemble form treats it as host-managed:\n * it is exposed verbatim as app.input, and the host is responsible for\n * detaching it (no auto-cleanup on stop). The canvas form is the entry\n * that engages the auto-attach helper (input-attach.ts).\n */\nexport function createApp(args: AppAssembleArgs): Promise<Result<App, AssembleAppError>>;\n\nexport function createApp(\n arg: HTMLCanvasElement | AppAssembleArgs,\n opts?: CreateAppOptions,\n bundler?: BundlerOptions,\n): Promise<Result<App | ExecutionApp, CanvasAppError>> {\n if ('tagName' in arg) {\n return createAppFromCanvas(arg, opts, bundler);\n }\n return createAppFromAssemble(arg);\n}\n\nasync function createAppFromCanvas(\n canvas: HTMLCanvasElement,\n opts: CreateAppOptions | undefined,\n // feat-20260608-create-app-param-surface-trim / M2 / D-3: BundlerOptions is\n // the host-injection SSOT (importTransport + shaderManifestUrl). Forwarded\n // verbatim to createRenderer's third arg, so the engine reads\n // shaderManifestUrl in its ShaderRegistry fallback (D-2 q5-A) and threads\n // importTransport to AssetRegistry (AC-05 / R-4: keeps build-tool\n // injection out of RendererOptions / CreateAppOptions).\n bundler: BundlerOptions | undefined,\n): Promise<Result<App | ExecutionApp, CanvasAppError>> {\n // M4: 4-step thin wrapper per plan-strategy D-5.\n //\n // Step 1: canvas-detached fail-fast guard (AC-08). isConnected returns\n // false when the canvas is not in the document tree, including freshly\n // document.createElement('canvas') without appendChild. Returning\n // Result.err here short-circuits before createRenderer fires off any\n // async adapter / device / shader work that would only fail later.\n if (!canvas.isConnected) {\n return err(\n makeAppError(\n 'app-canvas-detached',\n 'canvas.isConnected === true at createApp(canvas) entry',\n 'append the canvas to the document tree before calling createApp; or use the assemble entry createApp({ renderer, world }) when the host already manages canvas lifetime',\n {},\n ),\n );\n }\n\n // The DOM canvas starts with a 300x150 drawing buffer even when CSS lays it\n // out at a different size. Set the physical buffer before the renderer\n // configures its swap chain; the same helper runs before each frame so a CSS\n // resize remains visible to both rendering and camera policy.\n syncCanvasDrawingBuffer(canvas);\n\n let executionBootstrapUrl: string | undefined;\n if (opts?.execution !== undefined) {\n const normalizedBootstrap = normalizeExecutionBootstrapUrl(opts.execution.bootstrap);\n if (!normalizedBootstrap.ok) return err(normalizedBootstrap.error);\n executionBootstrapUrl = normalizedBootstrap.value;\n const realmBoundOption = [\n ['features', opts.features],\n ['plugins', opts.plugins],\n ['rhi', opts.rhi],\n ['rhiInstrumentation', opts.rhiInstrumentation],\n ['drawSource', opts.drawSource],\n ['bundler.importTransport', bundler?.importTransport],\n ].find(([, value]) => value !== undefined)?.[0];\n if (realmBoundOption !== undefined) {\n return err(\n makeAppError(\n 'app-execution-bootstrap-failed',\n APP_EXPECTED['app-execution-bootstrap-failed'],\n APP_ERROR_HINTS['app-execution-bootstrap-failed'],\n {\n phase: 'prepare',\n moduleUrl: executionBootstrapUrl,\n cause: new TypeError(\n `${realmBoundOption} must be constructed by the execution bootstrap module`,\n ),\n },\n ),\n );\n }\n }\n\n let executionContext:\n | {\n readonly capabilities: import('./execution').ExecutionCapabilities;\n readonly selection: import('./execution').ExecutionSelection;\n }\n | undefined;\n let preparedExecutionBootstrap: PreparedExecutionBootstrap | undefined;\n if (opts?.execution !== undefined) {\n const capabilities = await probeExecutionCapabilities(canvas);\n const selected = selectExecutionTier({\n requestedTier: opts.execution.tier ?? 'auto',\n capabilities,\n sharedEvidencePassed: true,\n });\n if (!selected.ok) return err(selected.error);\n executionContext = { capabilities, selection: selected.value };\n if (selected.value.actualTier !== 'main-serial') {\n return createWorkerExecutionApp({\n canvas,\n appOptions: opts,\n syncCanvas: () => measureCanvasDrawingBuffer(canvas),\n ...(bundler !== undefined ? { bundler } : {}),\n capabilities,\n selection: selected.value,\n });\n }\n if (executionBootstrapUrl === undefined) {\n throw new Error('execution bootstrap URL was not normalized');\n }\n const prepared = await prepareBootstrapEntry(\n executionBootstrapUrl,\n opts.execution.bootstrapData,\n );\n if (!prepared.ok) return err(prepared.error);\n preparedExecutionBootstrap = prepared.value;\n }\n\n // Step 2: createRenderer try/catch -> Result.err(EngineEnvironmentError)\n // (AC-01 / research section 2.2). createRenderer throws at\n // createRenderer.ts:400 / :429 (rhi pack load failure /\n // all WebGPU channels unavailable); we forward the original\n // EngineEnvironmentError instance verbatim to preserve the\n // .detail.webgpuError surface. RhiError instances raised mid-\n // construction are also forwarded -- the AppError | RhiError leg of\n // the union covers them. Any other unexpected throw is also\n // forwarded to keep the contract honest (AI users walk the union\n // discriminant rather than parse error.message strings).\n // feat-20260608 / M2 / D-3: CreateAppOptions stops `extends RendererOptions`,\n // so the RHI escape hatch (rhi) is\n // forwarded explicitly. Build a RendererOptions object out of just those\n // fields when present; an empty {} keeps createRenderer on its default path.\n const rendererOpts: import('@forgeax/engine-render').RendererOptions = {};\n if (opts?.rhi !== undefined) {\n Object.assign(rendererOpts, { rhi: opts.rhi });\n }\n if (opts?.profiler !== undefined) {\n Object.assign(rendererOpts, { profiler: opts.profiler });\n }\n const rendererFeatures = preparedExecutionBootstrap?.features ?? opts?.features;\n if (rendererFeatures !== undefined) {\n Object.assign(rendererOpts, { features: rendererFeatures });\n }\n if (opts?.standardProfile !== undefined) {\n Object.assign(rendererOpts, { standardProfile: opts.standardProfile });\n }\n if (opts?.rhiInstrumentation !== undefined) {\n Object.assign(rendererOpts, { rhiInstrumentation: opts.rhiInstrumentation });\n }\n\n // FORGEAX_ENGINE_RHI_DEBUG=1 attaches the recorder at the Runtime backend\n // seam. Render remains the owner of device/surface lifecycle; App only owns\n // the optional capture capability and its frame transaction.\n let rhiAttachment: RecorderAttachment | undefined;\n let rhiCapture: RhiCapture | undefined;\n let rhiDebugGlobal:\n | { captureFrame(options?: CaptureFrameOptions): ReturnType<RhiCapture['captureFrame']> }\n | undefined;\n const cleanupRhiDebugHost = (): void => {\n const host = globalThis as { __forgeax?: typeof rhiDebugGlobal };\n if (host.__forgeax === rhiDebugGlobal) delete host.__forgeax;\n rhiDebugGlobal = undefined;\n const attachment = rhiAttachment;\n rhiAttachment = undefined;\n if (attachment !== undefined) void attachment.dispose();\n };\n // Read FORGEAX_ENGINE_RHI_DEBUG from two sources (plan-strategy D-4):\n // - browser: import.meta.env, statically replaced by the\n // vite-plugin-rhi-debug `define` hook. The `typeof import.meta !==\n // 'undefined'` prefix short-circuits under dawn-node, where import.meta\n // itself can be undefined (C5).\n // - dawn-node: globalThis.process.env (no vite define on the native path).\n // resolveRhiDebugFlag (internal/rhi-debug-flag) is the SSOT for the `??`\n // precedence; the source bags are computed inline here so the\n // typeof-import.meta prefix stays at the call site. Keeps this file\n // @types/node-free (engine-app ships ESM into both browser + dawn-node;\n // same pattern as runtime/src/render-system-record.ts:isMeshSsboDevMode).\n // Keep the Vite define key in a direct property expression. Wrapping\n // `import.meta` in a structural cast hides the token from Vite's define\n // pass, so production builds retain the debug-only dynamic chunks even when\n // the Preview host explicitly sets the flag to `0`. Optional chaining keeps\n // the package safe on the Dawn/Node path where `import.meta.env` is absent.\n const importMetaEnv =\n typeof import.meta !== 'undefined'\n ? { FORGEAX_ENGINE_RHI_DEBUG: import.meta.env?.FORGEAX_ENGINE_RHI_DEBUG }\n : undefined;\n // A browser production build must be able to erase the entire recorder\n // branch. The `undefined` arm preserves Dawn/Node's process.env fallback;\n // Vite replaces the direct property with `\"0\"` or `\"1\"`, making this outer\n // guard a literal false/true before Rollup sees the debug-only imports.\n const browserBuildRhiDebugFlag =\n typeof import.meta !== 'undefined' ? import.meta.env?.FORGEAX_ENGINE_RHI_DEBUG : undefined;\n const processEnv = (globalThis as { process?: { env?: { FORGEAX_ENGINE_RHI_DEBUG?: string } } })\n .process?.env;\n const rhiDebugFlag = resolveRhiDebugFlag(importMetaEnv, processEnv);\n const nav: { gpu?: unknown } | undefined =\n typeof globalThis !== 'undefined'\n ? (globalThis as { navigator?: { gpu?: unknown } }).navigator\n : undefined;\n const hasWebGPU = nav !== undefined && 'gpu' in nav && nav.gpu !== undefined;\n if (\n (browserBuildRhiDebugFlag === undefined || browserBuildRhiDebugFlag === '1') &&\n rhiDebugFlag === '1'\n ) {\n const realBackend = (hasWebGPU\n ? await import('@forgeax/engine-rhi-webgpu')\n : await import('@forgeax/engine-rhi-wgpu')) as unknown as Record<string, unknown>;\n if (!hasWebGPU && 'ensureReady' in realBackend) {\n await (realBackend.ensureReady as () => Promise<unknown>)();\n }\n const pack = loadRhiPack(realBackend);\n if (pack.createShaderModule === undefined) {\n throw new Error('RHI-debug requires a backend createShaderModule capability');\n }\n const attached = attachRecorder({\n rhi: pack.rhi,\n createShaderModule: pack.createShaderModule,\n });\n if (!attached.ok) throw new Error(attached.error.hint);\n rhiAttachment = attached.value;\n rhiCapture = createRhiCapture(attached.value);\n const capture = rhiCapture;\n rhiDebugGlobal = { captureFrame: (options) => capture.captureFrame(options) };\n Object.assign(rendererOpts, {\n rhi: attached.value.backend.rhi,\n rhiInstrumentation: createRhiInstrumentation(attached.value),\n });\n (globalThis as { __forgeax?: typeof rhiDebugGlobal }).__forgeax = rhiDebugGlobal;\n }\n\n let renderer: Renderer;\n let rendererDebugDrawHost: RendererHostAssembly['debugDrawHost'];\n let rendererFeatureHost: RenderFeatureHost;\n let assets: AssetRegistry;\n try {\n const constructed = await constructRuntimeRendererHost(canvas, rendererOpts, bundler);\n if (!constructed.ok) throw constructed.error;\n renderer = constructed.value.renderer;\n rendererDebugDrawHost = constructed.value.debugDrawHost;\n rendererFeatureHost = createRenderFeatureHost(constructed.value.featureHost);\n assets = constructed.value.assets;\n } catch (e: unknown) {\n cleanupRhiDebugHost();\n if (e instanceof EngineEnvironmentError) return err(e);\n const detail = e instanceof Error ? e : new Error(String(e));\n return err(\n new EngineEnvironmentError('renderer construction failed', {\n webgpuError: detail,\n }),\n );\n }\n\n // Step 2.4 decision: resolve whether the remote eval server should start\n // (feat-20260629-inspector-two-layer-model M4 / w20). Dual-source gating\n // mirrors the rhi-debug-flag pattern. The actual startServer call is\n // deferred to after World creation (Step 3) because the server needs\n // a live World reference.\n const shouldStartRemote = resolveRemoteServeFlag(\n typeof import.meta !== 'undefined'\n ? (import.meta as { env?: { DEV?: boolean } }).env?.DEV\n : undefined,\n (globalThis as { process?: { env?: { FORGEAX_ENGINE_REMOTE_SERVE?: string } } }).process?.env,\n );\n\n let debugDraw: DebugDraw | undefined;\n\n // Step 3: new World() -- the canvas form owns world lifetime, in\n // contrast to the assemble form where the host owns it.\n const world = new World(opts?.time !== undefined ? { time: opts.time } : {});\n // Step 3.1 (M2 plugin-system-unify / D-4): app-layer side effects that the\n // plugins consume via pre-injected world resources.\n //\n // Animation keeps durable clip GUIDs in graph payloads. The canvas default\n // plugin receives the renderer-owned GUID catalogue as a lookup bridge; it\n // still projects payloads into this World through the animation owner.\n // transform + animation system registration lives in the plugins (default set).\n\n // A normal canvas app owns its browser acquisition. An embedding host that\n // shares this physical canvas with another world supplies its routed view via\n // opts.input; createApp then consumes that one boundary instead of attaching a\n // second listener set. The host owns the supplied backend's lifetime.\n const inputHandle =\n opts?.input === undefined\n ? attachInputAuto(canvas, {\n ...(opts?.uiRoot ? { uiRoot: opts.uiRoot } : {}),\n ...(opts?.pointerLockAllowed ? { pointerLockAllowed: opts.pointerLockAllowed } : {}),\n ...(opts?.virtualJoysticks ? { virtualJoysticks: opts.virtualJoysticks } : {}),\n ...(opts?.lockProvider ? { lockProvider: opts.lockProvider } : {}),\n })\n : undefined;\n const inputBackend = opts?.input ?? inputHandle?.backend;\n const userPlugins =\n preparedExecutionBootstrap === undefined\n ? (opts?.plugins ?? [])\n : [\n executionBootstrapHostPlugin({\n ...(opts?.execution?.bootstrapPort === undefined\n ? {}\n : { port: opts.execution.bootstrapPort }),\n setPointerLockAllowed: (allowed) => inputBackend?.setPointerLockAllowed?.(allowed),\n }),\n ...(preparedExecutionBootstrap.plugins ?? []),\n ];\n let pluginContext: Context;\n try {\n pluginContext = await createWorldContext(\n world,\n mainEngineProfile({\n renderer,\n rendererDebugDrawHost,\n rendererFeatureHost,\n assets,\n animationPayloads: createAnimationPayloadLookup(assets),\n ...(inputBackend === undefined ? {} : { input: inputBackend }),\n ...(inputHandle === undefined ? {} : { inputDispose: inputHandle.cleanup }),\n ...(opts?.inputMap === undefined ? {} : { inputMap: opts.inputMap }),\n onDebugDrawReady: (value) => {\n debugDraw = value;\n },\n extensions: [\n rhiDebugHostPlugin(cleanupRhiDebugHost),\n ...userPlugins,\n canvasAspectPlugin(canvas),\n ],\n }),\n );\n } catch (cause) {\n cleanupRhiDebugHost();\n return err(\n makeAppError(\n 'app-plugin-activation-failed',\n APP_EXPECTED['app-plugin-activation-failed'],\n APP_ERROR_HINTS['app-plugin-activation-failed'],\n { cause },\n ),\n );\n }\n const audioBackend = pluginContext.audio;\n\n const executionControl = createLocalExecutionControl(\n executionContext === undefined\n ? {\n ...createExecutionReport('main-serial', unavailableExecutionCapabilities('not required')),\n actualTier: 'main-serial',\n selectionReason: 'explicit-request',\n sharedEvidencePassed: true,\n engine: { realm: 'host', health: 'idle' },\n world: {\n identity: world.identity,\n health: world.execution.health,\n partialWrite: false,\n retryable: true,\n },\n }\n : {\n ...createExecutionReport(\n opts?.execution?.tier ?? 'auto',\n executionContext.capabilities,\n executionContext.selection,\n ),\n engine: { realm: 'host', health: 'idle' },\n world: {\n identity: world.identity,\n health: world.execution.health,\n partialWrite: false,\n retryable: true,\n },\n },\n {\n ...(audioBackend === undefined ? {} : { audio: () => audioBackend.getState() }),\n world: () => ({\n identity: world.identity,\n health: world.execution.health,\n partialWrite: world.execution.fault?.partialWrite ?? false,\n retryable: world.execution.fault?.retryable ?? true,\n }),\n },\n );\n\n // Step 3.3: Remote eval server auto-start (deferred from Step 2.4 so\n // World is available). Dynamic import keeps @forgeax/engine-app free\n // of static dep on @forgeax/engine-remote. Component reflection crosses\n // this boundary as JSON-safe host data; app does not own any component.\n const remoteHandle = shouldStartRemote\n ? await startRemoteServer(world, renderer, assets, rhiCapture, opts?.profiler, executionControl)\n : undefined;\n if (remoteHandle !== undefined) await pluginContext.plugin(remoteServerPlugin(remoteHandle));\n\n const buildArgs: BuildAppArgs = {\n renderer,\n assets,\n world,\n pluginContext,\n executionControl,\n onFrameSubmitted: (event) => publishBrowserFrameSubmitted(canvas, event),\n ...(inputBackend !== undefined ? { inputBackend } : {}),\n ...(inputHandle === undefined\n ? {}\n : {\n wireOnLockErrorDispatch: (dispatch: (err: AppError) => void) => {\n inputHandle.setOnErrorDispatch(dispatch);\n },\n }),\n };\n if (audioBackend !== undefined) {\n Object.assign(buildArgs, {\n audioBackend,\n });\n }\n if (opts?.silenceUnhandledErrors !== undefined) {\n Object.assign(buildArgs, { silenceUnhandledErrors: opts.silenceUnhandledErrors });\n }\n // M2 / D-3: canvas form forwards the host-supplied draw-source pull.\n if (opts?.drawSource !== undefined) {\n Object.assign(buildArgs, { drawSource: opts.drawSource });\n }\n if (opts?.profiler !== undefined) {\n Object.assign(buildArgs, { profiler: opts.profiler });\n }\n if (rhiCapture !== undefined) {\n Object.assign(buildArgs, { rhiCapture });\n }\n if (debugDraw !== undefined) {\n Object.assign(buildArgs, { debugDraw });\n }\n if (remoteHandle !== undefined) {\n Object.assign(buildArgs, { remoteHandle });\n }\n\n // The aspect-sync sidecar belongs to the canvas path because it owns the DOM\n // canvas. It runs as an Update system so it shares World scheduling semantics.\n resetBrowserFrameSubmitted(canvas);\n const built = await buildApp(buildArgs);\n if (!built.ok) {\n await pluginContext.fiber.dispose();\n return built;\n }\n if (built.ok) {\n // DEV-only browser remote bridge (remote-live). A browser cannot host the\n // Node WS server that @forgeax/engine-remote/server needs, so the running\n // engine would be unreachable from a CLI in a real dev browser. Instead the\n // page dials OUT to a loopback relay and runs the ws-free eval core against\n // the live world/renderer/assets/rhiCapture.\n //\n // OPT-IN via VITE_FORGEAX_ENGINE_BRIDGE=1 (set by scripts/dev-live.mjs), NOT\n // on-by-default: a page that dials a relay which is not running makes the\n // BROWSER itself log \"WebSocket connection failed\" to the console — noise a\n // JS catch cannot suppress — which trips every zero-console-error browser\n // smoke (collectathon / hello-*). So a plain `pnpm --filter <app> dev` (and\n // CI) stays silent; only dev-live.mjs, which also launches the relay, turns\n // it on. Production DCE's the whole block (import.meta.env.DEV === false).\n // Additive: the Node startServer path above and app.remote are untouched.\n if (\n typeof import.meta !== 'undefined' &&\n (import.meta as { env?: { DEV?: boolean; VITE_FORGEAX_ENGINE_BRIDGE?: string } }).env?.DEV ===\n true &&\n (import.meta as { env?: { VITE_FORGEAX_ENGINE_BRIDGE?: string } }).env\n ?.VITE_FORGEAX_ENGINE_BRIDGE === '1'\n ) {\n const bridgePort =\n (import.meta as { env?: { VITE_FORGEAX_ENGINE_BRIDGE_PORT?: string } }).env\n ?.VITE_FORGEAX_ENGINE_BRIDGE_PORT ?? '5733';\n await pluginContext.plugin({\n name: 'browser-remote-bridge',\n inject: ['world', 'renderer', 'assets'],\n async apply(ctx) {\n if (ctx.renderer === undefined || ctx.assets === undefined) {\n throw new Error('browser remote bridge requires renderer and assets services');\n }\n try {\n const bridge = await import('./internal/browser-remote-bridge');\n const teardown = await bridge.installBrowserRemoteBridge({\n world: ctx.world,\n renderer: ctx.renderer,\n assets: ctx.assets,\n runtimeModule: engineRuntimeModule,\n ...(rhiCapture !== undefined ? { rhiCapture } : {}),\n ...(opts?.profiler !== undefined ? { profiler: opts.profiler } : {}),\n execution: built.value.execution,\n port: bridgePort,\n });\n ctx.effect(() => teardown, 'remote/browser-bridge');\n } catch {\n // The optional live bridge does not make App creation fail.\n }\n },\n });\n }\n }\n return built;\n}\n\n/**\n * Synchronize a DOM canvas drawing buffer with its CSS size and device pixel\n * ratio. Detached or zero-sized hosts are left untouched so a hidden canvas\n * cannot be converted into a 1x1 render target accidentally.\n */\nexport function syncCanvasDrawingBuffer(\n canvas: Pick<HTMLCanvasElement, 'clientWidth' | 'clientHeight' | 'width' | 'height'> & {\n readonly style?: Pick<CSSStyleDeclaration, 'width' | 'height'>;\n },\n): void {\n if (\n !Number.isFinite(canvas.clientWidth) ||\n !Number.isFinite(canvas.clientHeight) ||\n canvas.clientWidth <= 0 ||\n canvas.clientHeight <= 0\n )\n return;\n // An intrinsic canvas with no CSS dimensions already has an explicit\n // drawing-buffer contract. `clientWidth` mirrors `width` for this shape;\n // multiplying it by DPR would change the caller's requested pixel size and\n // can feed that new width back as the next layout measurement. CSS-sized\n // canvases take the DPR path below (including stylesheet-sized canvases\n // whose layout width differs from the initial intrinsic width).\n const hasExplicitCssSize =\n (canvas.style?.width ?? '') !== '' || (canvas.style?.height ?? '') !== '';\n if (\n !hasExplicitCssSize &&\n canvas.clientWidth === canvas.width &&\n canvas.clientHeight === canvas.height\n ) {\n return;\n }\n const dpr = Math.max(1, globalThis.devicePixelRatio || 1);\n const previous = syncedCanvasSizes.get(canvas);\n const drawingBufferIsTheLayoutMeasurement =\n previous !== undefined &&\n canvas.width === previous.drawingWidth &&\n canvas.height === previous.drawingHeight &&\n canvas.clientWidth === previous.drawingWidth &&\n canvas.clientHeight === previous.drawingHeight;\n const cssWidth = drawingBufferIsTheLayoutMeasurement ? previous.cssWidth : canvas.clientWidth;\n const cssHeight = drawingBufferIsTheLayoutMeasurement ? previous.cssHeight : canvas.clientHeight;\n const width = Math.max(1, Math.round(cssWidth * dpr));\n const height = Math.max(1, Math.round(cssHeight * dpr));\n if (canvas.width !== width) canvas.width = width;\n if (canvas.height !== height) canvas.height = height;\n syncedCanvasSizes.set(canvas, {\n cssWidth,\n cssHeight,\n drawingWidth: width,\n drawingHeight: height,\n });\n}\n\n/** Measure a CSS-sized canvas without mutating its drawing buffer. */\nexport function measureCanvasDrawingBuffer(\n canvas: Pick<HTMLCanvasElement, 'clientWidth' | 'clientHeight' | 'width' | 'height'> & {\n readonly style?: Pick<CSSStyleDeclaration, 'width' | 'height'>;\n },\n maxCanvasPixelRatio?: number,\n): { readonly width: number; readonly height: number } {\n if (\n !Number.isFinite(canvas.clientWidth) ||\n !Number.isFinite(canvas.clientHeight) ||\n canvas.clientWidth <= 0 ||\n canvas.clientHeight <= 0\n ) {\n return { width: canvas.width, height: canvas.height };\n }\n const hasExplicitCssSize =\n (canvas.style?.width ?? '') !== '' || (canvas.style?.height ?? '') !== '';\n if (\n !hasExplicitCssSize &&\n canvas.clientWidth === canvas.width &&\n canvas.clientHeight === canvas.height\n ) {\n return { width: canvas.width, height: canvas.height };\n }\n const devicePixelRatio = Math.max(1, globalThis.devicePixelRatio || 1);\n const dpr =\n maxCanvasPixelRatio === undefined ||\n !Number.isFinite(maxCanvasPixelRatio) ||\n maxCanvasPixelRatio <= 0\n ? devicePixelRatio\n : Math.min(devicePixelRatio, maxCanvasPixelRatio);\n const previous = syncedCanvasSizes.get(canvas);\n const drawingBufferIsTheLayoutMeasurement =\n previous !== undefined &&\n canvas.width === previous.drawingWidth &&\n canvas.height === previous.drawingHeight &&\n canvas.clientWidth === previous.drawingWidth &&\n canvas.clientHeight === previous.drawingHeight;\n const cssWidth = drawingBufferIsTheLayoutMeasurement ? previous.cssWidth : canvas.clientWidth;\n const cssHeight = drawingBufferIsTheLayoutMeasurement ? previous.cssHeight : canvas.clientHeight;\n return {\n width: Math.max(1, Math.round(cssWidth * dpr)),\n height: Math.max(1, Math.round(cssHeight * dpr)),\n };\n}\n\nconst syncedCanvasSizes = new WeakMap<\n object,\n {\n readonly cssWidth: number;\n readonly cssHeight: number;\n readonly drawingWidth: number;\n readonly drawingHeight: number;\n }\n>();\n\n/**\n * Per-frame aspect-sync body for the createApp(canvas) path (feat-20260617\n * M3 / w13). Walks every Camera entity and, for perspective cameras with\n * `autoAspect === true`, writes `canvasW / canvasH` into `Camera.aspect`.\n *\n * Read discipline (D-5 / research Finding 2): `autoAspect` is read through\n * `world.get` (the readRow path narrows the bool column to a JS boolean).\n * The query bundle is used only to enumerate the entity handles -- reading\n * the bool column off the bundle would return a raw 0/1 number, so a\n * `!== 0` test is always true (the\n * bool-field-compared-with-not-equal-zero-always-true trap).\n *\n * Best-effort + side-effect-isolated:\n * - canvas size 0 (detached / display:none) -> skip entirely so `aspect`\n * never becomes NaN / 0.\n * - orthographic cameras and `autoAspect === false` cameras are left\n * untouched.\n *\n * @see {@link https://github.com/Ubpa/forgeax-engine/blob/main/docs/how-to/2026-06-18-host-engine-contract.md | Host-engine contract SSOT}\n */\nexport function syncCameraAspect(world: World, canvasW: number, canvasH: number): void {\n // Guard against detached / zero-sized canvases: a 0 width or height would\n // write NaN (0 / 0) or 0 into aspect and corrupt the projection matrix.\n if (canvasW <= 0 || canvasH <= 0) return;\n const aspect = canvasW / canvasH;\n\n const query = world.query({ with: [Camera] }).unwrap();\n for (const row of query) {\n const entity = row.entity;\n const r = world.get(entity, Camera);\n if (!r.ok) continue;\n // world.get narrows the bool column to a real boolean (D-5); the\n // perspective discriminator is the numeric column value.\n if (r.value.autoAspect !== true) continue;\n if (r.value.projection !== CAMERA_PROJECTION_PERSPECTIVE) continue;\n world.set(entity, Camera, { aspect });\n }\n}\n\nasync function startRemoteServer(\n world: World,\n renderer: Renderer,\n assets: AssetRegistry | undefined,\n rhiCapture: RhiCapture | undefined,\n profiler: import('@forgeax/engine-profiler').Profiler | undefined,\n execution: ExecutionControl,\n): Promise<{ readonly port: number; close(): Promise<void> } | undefined> {\n try {\n const remoteServerMod = (await import(\n /* @vite-ignore */ '@forgeax/engine-remote/server'\n )) as unknown as {\n startServer: (opts: {\n port: number;\n host?: string;\n world: unknown;\n renderer?: unknown;\n assets?: unknown;\n rhiCapture?: unknown;\n introspection?: readonly unknown[];\n profiler?: unknown;\n execution?: unknown;\n }) => Promise<{\n ok: boolean;\n value?: { port: number; close(): Promise<void> };\n }>;\n };\n const serverResult = await remoteServerMod.startServer({\n port: 0,\n host: '127.0.0.1',\n world,\n renderer,\n assets,\n introspection: projectComponentIntrospection(world.components.entries()),\n ...(rhiCapture !== undefined ? { rhiCapture } : {}),\n ...(profiler !== undefined ? { profiler } : {}),\n execution,\n });\n if (serverResult.ok && serverResult.value !== undefined) {\n return { port: serverResult.value.port, close: serverResult.value.close };\n }\n } catch (_error) {\n // Dynamic import or server start failed; the app continues without remote.\n }\n return undefined;\n}\n\nasync function createAppFromAssemble(\n args: AppAssembleArgs,\n): Promise<Result<App, AssembleAppError>> {\n let pluginContext: Context;\n try {\n pluginContext = await createWorldContext(\n args.world,\n assembledEngineProfile({\n renderer: args.renderer,\n ...(args.assets === undefined ? {} : { assets: args.assets }),\n extensions: args.plugins ?? [],\n }),\n );\n } catch (cause) {\n return err(\n makeAppError(\n 'app-plugin-activation-failed',\n APP_EXPECTED['app-plugin-activation-failed'],\n APP_ERROR_HINTS['app-plugin-activation-failed'],\n { cause },\n ),\n );\n }\n\n const shouldStartRemote = resolveRemoteServeFlag(\n undefined,\n (globalThis as { process?: { env?: { FORGEAX_ENGINE_REMOTE_SERVE?: string } } }).process?.env,\n );\n const assembledAudioBackend = pluginContext.audio;\n const executionControl = createLocalExecutionControl(\n {\n ...createExecutionReport('main-serial', unavailableExecutionCapabilities('not required')),\n actualTier: 'main-serial',\n selectionReason: 'explicit-request',\n sharedEvidencePassed: true,\n engine: { realm: 'host', health: 'idle' },\n world: {\n identity: args.world.identity,\n health: args.world.execution.health,\n partialWrite: false,\n retryable: true,\n },\n },\n {\n ...(assembledAudioBackend === undefined\n ? {}\n : { audio: () => assembledAudioBackend.getState() }),\n world: () => ({\n identity: args.world.identity,\n health: args.world.execution.health,\n partialWrite: args.world.execution.fault?.partialWrite ?? false,\n retryable: args.world.execution.fault?.retryable ?? true,\n }),\n },\n );\n const remoteHandle = shouldStartRemote\n ? await startRemoteServer(\n args.world,\n args.renderer,\n args.assets,\n undefined,\n args.profiler,\n executionControl,\n )\n : undefined;\n if (remoteHandle !== undefined) await pluginContext.plugin(remoteServerPlugin(remoteHandle));\n\n const buildArgs: BuildAppArgs = {\n renderer: args.renderer,\n world: args.world,\n pluginContext,\n executionControl,\n ...(remoteHandle !== undefined ? { remoteHandle } : {}),\n };\n\n const assembledInputBackend = pluginContext.input;\n if (assembledInputBackend !== undefined) {\n Object.assign(buildArgs, {\n inputBackend: assembledInputBackend,\n });\n }\n if (assembledAudioBackend !== undefined) {\n Object.assign(buildArgs, {\n audioBackend: assembledAudioBackend,\n });\n }\n if (args.silenceUnhandledErrors !== undefined) {\n Object.assign(buildArgs, { silenceUnhandledErrors: args.silenceUnhandledErrors });\n }\n // M2 / D-3: assemble form forwards the host-supplied draw-source pull.\n if (args.drawSource !== undefined) {\n Object.assign(buildArgs, { drawSource: args.drawSource });\n }\n if (args.profiler !== undefined) {\n Object.assign(buildArgs, { profiler: args.profiler });\n }\n const built = await buildApp(buildArgs);\n if (!built.ok) await pluginContext.fiber.dispose();\n return built;\n}\n\ninterface BuildAppArgs {\n readonly renderer: Renderer;\n readonly assets?: AssetRegistry;\n readonly world: World;\n readonly pluginContext: Context;\n readonly inputBackend?: InputBackend;\n /**\n * M2 D-4: callback that buildApp calls after creating the ErrorFanoutRegistry\n * dispatch function. The input handle's onLockError callback needs the dispatch\n * function to fan out 'app-pointer-lock-failed' errors, but the dispatch function\n * is created inside buildApp (after the input handle is already constructed).\n * This callback bridges the gap.\n */\n readonly wireOnLockErrorDispatch?: (dispatch: (err: AppError) => void) => void;\n readonly audioBackend?: AudioBackend;\n readonly silenceUnhandledErrors?: boolean;\n /** Optional App-owned RHI capture capability. */\n readonly rhiCapture?: RhiCapture;\n /** feat-20260615 debug-draw M5: DebugDraw instance created by createDebugDrawOnReady. */\n readonly debugDraw?: DebugDraw;\n /** feat-20260629 M4 / w20: remote eval server handle from createAppFromCanvas. */\n readonly remoteHandle?: { readonly port: number; close(): Promise<void> };\n /**\n * feat-20260709-editor-world-partition-editorworld-super-composite / M2 / D-3:\n * per-frame draw-source pull forwarded verbatim into the frame-loop. Absent =>\n * the allocation-free primary-World path. Both createApp forms (canvas + assemble) forward\n * it from their respective options object.\n */\n readonly drawSource?: () =>\n | {\n worlds: readonly import('@forgeax/engine-ecs').World[];\n cameraOwner: number;\n resourceOwner: number;\n }\n | undefined;\n readonly profiler?: import('@forgeax/engine-profiler').Profiler;\n readonly executionControl?: import('./execution/control').LocalExecutionControl;\n /** Canvas-form projection of the Renderer frame-submitted event. */\n readonly onFrameSubmitted?: (event: {\n readonly frameId: number;\n readonly deviceGeneration: number;\n }) => void;\n}\n\n/**\n * Internal builder shared by both overloads. Wires the frame-loop +\n * listener-registry onError and returns the App handle. Effectful ownership\n * has already moved into pluginContext before this boundary runs.\n */\nasync function buildApp(args: BuildAppArgs): Promise<Result<App, AppError | RhiError>> {\n const {\n renderer,\n world,\n pluginContext,\n inputBackend,\n audioBackend,\n silenceUnhandledErrors,\n rhiCapture,\n debugDraw,\n remoteHandle,\n profiler,\n } = args;\n\n // Physics is a Context service; the App exposes the active provider without\n // storing a second mutable slot.\n function readPhysicsWorld():\n | import('@forgeax/engine-physics').PhysicsWorld\n | import('@forgeax/engine-physics').PhysicsWorld2D\n | undefined {\n return pluginContext.physics;\n }\n // M4 (w11): listener registry replaces the M3 inline Set so console.error\n // fallback + duplicate-add no-op + unsubscribe handle behaviour matches\n // packages/runtime/src/createRenderer.ts:532-566 LostListenerRegistry\n // (plan-strategy D-9). silenceUnhandledErrors threads through verbatim.\n const fanout = new ErrorFanoutRegistry(\n silenceUnhandledErrors !== undefined ? { silenceUnhandledErrors } : {},\n );\n let lastError: AppDispatchError | undefined;\n const execution =\n args.executionControl ??\n createLocalExecutionControl(\n {\n ...createExecutionReport('main-serial', unavailableExecutionCapabilities('not required')),\n actualTier: 'main-serial',\n selectionReason: 'explicit-request',\n sharedEvidencePassed: true,\n engine: { realm: 'host', health: 'idle' },\n world: {\n identity: world.identity,\n health: world.execution.health,\n partialWrite: world.execution.fault?.partialWrite ?? false,\n retryable: world.execution.fault?.retryable ?? true,\n },\n },\n {\n ...(audioBackend === undefined ? {} : { audio: () => audioBackend.getState() }),\n world: () => ({\n identity: world.identity,\n health: world.execution.health,\n partialWrite: world.execution.fault?.partialWrite ?? false,\n retryable: world.execution.fault?.retryable ?? true,\n }),\n },\n );\n\n function dispatch(e: AppDispatchError): void {\n lastError = e;\n fanout.fire(e);\n }\n\n // M2 D-4: wire the input handle's onLockError callback to the error fan-out.\n // The dispatch function is created here; the input handle was created earlier\n // in createAppFromCanvas and passed to buildApp with a wireOnLockErrorDispatch\n // callback that calls setOnErrorDispatch on the handle.\n if (args.wireOnLockErrorDispatch) {\n args.wireOnLockErrorDispatch(dispatch);\n }\n\n const loopOpts: Parameters<typeof createFrameLoop>[0] = {\n world,\n renderer,\n onError: dispatch,\n };\n // M2 / D-3: forward the optional draw-source pull into the frame-loop. Absent\n // => the loop keeps the allocation-free primary-World draw path.\n if (args.drawSource !== undefined) {\n Object.assign(loopOpts, { drawSource: args.drawSource });\n }\n if (profiler !== undefined) {\n Object.assign(loopOpts, { profiler });\n }\n const loop = createFrameLoop(loopOpts);\n if (rhiCapture !== undefined) {\n bindRhiCaptureFrameDriver(rhiCapture, {\n getState: () => loop.getState(),\n pause: () => {\n const result = loop.pause();\n if (result.ok) execution.setEngineHealth('idle');\n return result;\n },\n resume: () => {\n const result = loop.resume();\n if (result.ok) execution.setEngineHealth('running');\n return result;\n },\n stepFrame: (deltaSeconds) => loop.stepFrame(deltaSeconds),\n });\n }\n // M4 (w13) device-lost internal subscription. R-1 timing contract:\n // app.start() arms the rAF handle BEFORE this listener subscribes, so\n // a synchronous late-attach replay of a persisted device-lost event\n // (LostListenerRegistry replay -- runtime/src/renderer.ts:337-345)\n // hits a frame-loop with a real rAF handle to cancel (M2 setStopped\n // tolerates pendingFrameId === 0 as a no-op so even pre-rAF replays\n // do not NPE). The subscription remains active across pause / resume;\n // unsubscribe runs only on stop / disposal (charter P3:\n // device-lost is a terminal lifecycle signal, not a transient blip).\n let rendererUnsubscribe: (() => void) | undefined;\n let resumeAfterSurfaceRestore = false;\n\n function subscribeRendererErrors(): void {\n if (rendererUnsubscribe !== undefined) {\n return;\n }\n rendererUnsubscribe = renderer.subscribe((event) => {\n if (event.kind === 'frame-submitted') {\n args.onFrameSubmitted?.(event);\n return;\n }\n if (event.kind !== 'error') return;\n const e: RenderError = event.error;\n dispatch(e);\n });\n }\n\n function unsubscribeRendererErrors(): void {\n if (rendererUnsubscribe !== undefined) {\n rendererUnsubscribe();\n rendererUnsubscribe = undefined;\n }\n }\n\n const stub: App = {\n renderer,\n ...(args.assets === undefined ? {} : { assets: args.assets }),\n world,\n execution,\n async releaseSurfacePreserveWorld(): Promise<Result<void, RhiError | RenderError>> {\n if (loop.getState() === 'running') {\n const paused = loop.pause();\n if (!paused.ok) {\n return err(\n new RhiError({\n code: 'rhi-not-available',\n expected: 'running App pauses before releasing its presentation surface',\n hint: paused.error.hint,\n }),\n );\n }\n resumeAfterSurfaceRestore = true;\n execution.setEngineHealth('idle');\n }\n // A surface handoff can be requested by an Update system while the\n // current frame is still in progress. Let that frame reach renderer.draw\n // before unconfiguring the surface; pause() only cancels the next rAF.\n await Promise.resolve();\n const released = renderer.releaseSurface();\n if (!released.ok && resumeAfterSurfaceRestore) {\n loop.resume();\n resumeAfterSurfaceRestore = false;\n execution.setEngineHealth('running');\n }\n return released.ok ? ok(undefined) : err(released.error);\n },\n async restoreSurface(): Promise<Result<void, RhiError | RenderError>> {\n const restored = renderer.restoreSurface();\n if (!restored.ok) return err(restored.error);\n if (resumeAfterSurfaceRestore) {\n const resumed = loop.resume();\n if (!resumed.ok) {\n return err(\n new RhiError({\n code: 'rhi-not-available',\n expected: 'paused App resumes after restoring its presentation surface',\n hint: resumed.error.hint,\n }),\n );\n }\n resumeAfterSurfaceRestore = false;\n execution.setEngineHealth('running');\n }\n return ok(undefined);\n },\n pluginContext,\n ...(inputBackend !== undefined ? { input: inputBackend } : {}),\n ...(audioBackend !== undefined ? { audio: audioBackend } : {}),\n get physics():\n | import('@forgeax/engine-physics').PhysicsWorld\n | import('@forgeax/engine-physics').PhysicsWorld2D\n | undefined {\n return readPhysicsWorld();\n },\n start(): Result<void, AppError> {\n // R-1: arm the rAF handle FIRST (loop.start schedules raf(tick))\n // and only THEN subscribe to renderer events. If the renderer\n // late-attach replays a persisted device-lost event during the\n // subscribe call, the loop is already armed and can retain the error.\n const r = loop.start();\n if (r.ok) {\n execution.setEngineHealth('running');\n subscribeRendererErrors();\n }\n return r;\n },\n stop(): Result<void, AppError> {\n const r = loop.stop();\n if (r.ok) execution.setEngineHealth('stopped');\n unsubscribeRendererErrors();\n return r;\n },\n async dispose(): Promise<Result<void, AppError>> {\n const state = loop.getState();\n if (state === 'running' || state === 'paused') loop.stop();\n else if (state !== 'stopped') loop.setStopped();\n await pluginContext.fiber.dispose();\n unsubscribeRendererErrors();\n execution.setEngineHealth('stopped');\n return ok(undefined);\n },\n pause(): Result<void, AppError> {\n const r = loop.pause();\n if (r.ok) execution.setEngineHealth('idle');\n return r;\n },\n resume(): Result<void, AppError> {\n const r = loop.resume();\n if (r.ok) execution.setEngineHealth('running');\n return r;\n },\n stepFrame(deltaSeconds): Result<void, AppDispatchError> {\n return loop.stepFrame(deltaSeconds);\n },\n onError(cb: (e: AppDispatchError) => void): () => void {\n return fanout.add(cb);\n },\n setDrawSource(drawSource): void {\n loop.setDrawSource(drawSource);\n },\n /**\n * Most recent dispatched error retained for host self-inspection.\n */\n get lastError(): AppDispatchError | undefined {\n return lastError;\n },\n ...(rhiCapture !== undefined ? { rhiCapture } : {}),\n ...(debugDraw !== undefined ? { debugDraw } : {}),\n ...(remoteHandle !== undefined ? { remote: remoteHandle } : {}),\n };\n\n return ok(stub);\n}\n","import type { World } from '@forgeax/engine-ecs';\nimport { Camera, perspective } from '@forgeax/engine-render';\nimport { Transform } from '@forgeax/engine-scene';\n\n/**\n * Ensure the neutral camera used only by hosts that have no game bootstrap.\n * An authored scene camera wins; a resolved game owns its camera policy and\n * must not call this helper.\n */\nexport function ensureFallbackCamera(\n world: World,\n aspect = 1,\n): ReturnType<World['spawn']> | undefined {\n const cameras = world.query({ with: [Camera] }).unwrap();\n if (!cameras[Symbol.iterator]().next().done) return undefined;\n return world.spawn(\n { component: Transform, data: { pos: [0, 0.6, 5] } },\n { component: Camera, data: perspective({ fov: Math.PI / 3, aspect, far: 1000 }) },\n );\n}\n","// @forgeax/engine-app -- Host service for asset-resident game plugins.\n//\n// App, Preview, and Devkit provide one realm-local GameHost service. Project\n// code default-exports a native Cordis plugin that injects this service and\n// owns all non-ECS teardown through Fiber effects.\n\nimport type { AssetRegistry } from '@forgeax/engine-assets-runtime';\nimport type { EntityHandle } from '@forgeax/engine-ecs';\nimport type { Plugin } from '@forgeax/engine-plugin';\nimport type { Renderer } from '@forgeax/engine-render';\nimport type { SceneAsset } from '@forgeax/engine-types';\n\nimport type { App } from './types';\n\n/** JSON-shaped data a game may intentionally project through a host bridge. */\nexport type GameProjectionValue =\n | null\n | boolean\n | number\n | string\n | GameProjectionValue[]\n | { [key: string]: GameProjectionValue };\n\n/** Lightweight, host-agnostic argument schema for a game-owned action. */\nexport interface GameActionArgsSchema {\n readonly type?: 'string' | 'number' | 'boolean' | 'object' | 'array';\n readonly properties?: Record<string, GameActionArgsSchema>;\n readonly required?: string[];\n readonly enum?: GameProjectionValue[];\n readonly items?: GameActionArgsSchema;\n readonly nullable?: boolean;\n readonly description?: string;\n}\n\n/**\n * A Play-only capability owned by game code. The host may discover and invoke it,\n * but never supplies its gameplay semantics or reaches into the game World.\n */\nexport interface GameActionDef {\n readonly id: string;\n readonly title: string;\n readonly description?: string;\n readonly argsSchema?: GameActionArgsSchema;\n /** Return an optional JSON-shaped result for inspection clients. */\n readonly run: (\n args: GameProjectionValue,\n ) => GameProjectionValue | void | Promise<GameProjectionValue | void>;\n}\n\n/** A named, serializable Play-only read projection owned by game code. */\nexport interface GameReadDef {\n readonly id: string;\n readonly title: string;\n readonly description?: string;\n readonly read: () => GameProjectionValue | Promise<GameProjectionValue>;\n}\n\n/**\n * Host-provided registration sink for one Play run. Games receive this only while\n * bootstrapping the fresh transient world; registrations are discarded when the run is disposed.\n */\nexport interface GameProjectionRegistrar {\n registerAction(def: GameActionDef): () => void;\n registerRead(def: GameReadDef): () => void;\n}\n\n/** Realm-local Host capability injected into an asset-resident game plugin. */\nexport interface GameHost {\n /** Presentation canvas owned by this Host realm. */\n readonly canvas: HTMLCanvasElement;\n /** The WebGPU Renderer (optional — some hosts may not expose it). */\n readonly renderer?: Renderer;\n /** The AssetRegistry owned by the Renderer. */\n readonly assets: AssetRegistry;\n /** The App handle for lifecycle introspection. */\n readonly app: App;\n /** Synthetic root entity of the host-instantiated defaultScene. Carries the\n * SceneInstance component. Absent when the game has no defaultScene. */\n readonly defaultSceneRoot?: EntityHandle;\n /** The loaded SceneAsset payload for the defaultScene. Contains the\n * author-side entity list with Name components. Absent when the game has\n * no defaultScene. */\n readonly defaultScene?: SceneAsset;\n /**\n * Controlled UI container for this run. Games must mount their DOM UI here\n * (`(ctx.uiRoot ?? document.body).appendChild(el)`) instead of appending\n * directly to `document.body`. In the embedded editor viewport the host\n * removes this whole container when the run is disposed. Absent means game\n * code falls back to `document.body`.\n */\n readonly uiRoot?: HTMLElement;\n /**\n * M2 D-3: command-set pointer-lock gate. The game template calls this\n * when the view mode changes (e.g. `setPointerLockAllowed(mode === 'fps')`\n * to allow lock in FPS, disallow in top-down). The host wires this to\n * App.input.setPointerLockAllowed?.() which delegates to the input backend.\n * Absent → the host does not support pointer-lock gating (e.g. a host\n * that only runs top-down games).\n */\n readonly setPointerLockAllowed?: (allowed: boolean) => void;\n /**\n * Optional Play-only projection seam. A game registers its own action and read\n * capabilities here; the host may only discover/invoke/read those closures. It\n * is deliberately absent outside a host that can clear registrations on disposal.\n */\n readonly gameProjection?: GameProjectionRegistrar;\n}\n\n/**\n * Provide the Host boundary to a native Cordis game plugin.\n */\nexport function gameHostPlugin(host: GameHost): Plugin {\n return {\n name: 'game-host',\n provide: 'gameHost',\n apply(ctx) {\n ctx.provide('gameHost', host);\n },\n };\n}\n\ndeclare module '@forgeax/engine-plugin' {\n interface EngineContextServices {\n gameHost?: GameHost;\n }\n}\n","// @forgeax/engine-app -- LoadGameError class + 3-code closed union +\n// LOAD_GAME_ERROR_HINTS / LOAD_GAME_EXPECTED tables.\n//\n// Isomorphic to AppError in errors.ts: class extends Error + 4-field\n// surface (.code / .expected / .hint / .detail) + discriminated detail\n// per code; the co-located policy-owner proof locks the derived views.\n//\n// Shape:\n// - LoadGameErrorCode = closed union 3 members (charter P4 closed-union\n// exhaustive switch needs no default fallback; tsc strict mode guards\n// completeness; AGENTS.md \"Errors are structured\").\n// Members:\n// - 'module-not-found'\n// - 'invalid-format'\n// - 'import-failed'\n//\n// - LoadGameError class = 4-field surface (.code / .expected / .hint /\n// .detail) byte-for-byte parallel to AppError. AI users walk .code /\n// .detail by property access (charter P3 explicit failure: never parse\n// the message string).\n//\n// - LoadGameError is exposed as a discriminated union (variant per code)\n// so AI users get .detail narrowing for free after\n// `if (err.code === '...')`:\n//\n// if (err.code === 'module-not-found') {\n// console.warn('game not found:', err.detail.slug);\n// }\n//\n// - LOAD_GAME_ERROR_HINTS / LOAD_GAME_EXPECTED are 3-key Records keyed\n// by LoadGameErrorCode; the private policy owner below is the single\n// source for both projections.\n//\n// Related: requirements AC-08 (LoadGameError structured error 3 codes +\n// hint + detail); plan-strategy D-3 (reuse codebase structured error\n// pattern); charter P3 (explicit failure).\n\n/**\n * Closed LoadGameErrorCode union (3 members).\n *\n * | code | trigger |\n * |:--|:--|\n * | `'module-not-found'` | resolver throws an error distinguishable as module-not-found (e.g. \"Cannot find module\"). Detail carries `slug` so AI users can surface which game path failed. |\n * | `'invalid-format'` | resolver returns a module without a valid native Cordis default export. Detail carries `exportKeys` so AI users can inspect the module shape. |\n * | `'import-failed'` | resolver throws a generic Error (network error, build error, etc.) not distinguishable as module-not-found. Detail carries the original `cause` Error so AI users can chain narrow. |\n *\n * Plan-strategy D-3 locks the count at 3.\n */\nexport type LoadGameErrorCode = keyof typeof loadGameErrorPolicy;\n\n/**\n * Detail variant for the `'module-not-found'` arm.\n *\n * `slug` carries the game identifier that the resolver failed to locate\n * so AI users can surface exactly which game could not be loaded.\n */\nexport interface LoadGameDetailModuleNotFound {\n readonly slug: string;\n}\n\n/**\n * Detail variant for the `'invalid-format'` arm.\n *\n * `exportKeys` carries the keys of the module object returned by the\n * resolver. AI users inspect these to understand why the native default\n * plugin export was rejected.\n */\nexport interface LoadGameDetailInvalidFormat {\n readonly exportKeys: string[];\n}\n\n/**\n * Detail variant for the `'import-failed'` arm.\n *\n * `cause` carries the original thrown value verbatim so AI users can\n * chain narrow (e.g. `cause instanceof TypeError` for network errors)\n * without losing structure.\n */\nexport interface LoadGameDetailImportFailed {\n readonly cause: unknown;\n}\n\n/**\n * Conditional resolver from `LoadGameErrorCode` to its detail payload type.\n */\nexport type LoadGameErrorDetailFor<C extends LoadGameErrorCode> = C extends 'module-not-found'\n ? LoadGameDetailModuleNotFound\n : C extends 'invalid-format'\n ? LoadGameDetailInvalidFormat\n : LoadGameDetailImportFailed;\n\n/**\n * Tagged union of `.detail` payloads carried by structured LoadGameError.\n */\nexport type LoadGameErrorDetail = LoadGameErrorDetailFor<LoadGameErrorCode>;\n\nclass LoadGameErrorClass extends Error {\n readonly code: LoadGameErrorCode;\n readonly expected: string;\n readonly hint: string;\n readonly detail: LoadGameErrorDetail;\n\n constructor(args: {\n code: LoadGameErrorCode;\n expected: string;\n hint: string;\n detail: LoadGameErrorDetail;\n }) {\n super(`[LoadGameError ${args.code}] expected: ${args.expected}; hint: ${args.hint}`);\n this.name = 'LoadGameError';\n this.code = args.code;\n this.expected = args.expected;\n this.hint = args.hint;\n this.detail = args.detail;\n }\n}\n\n/**\n * Variant intersection: a `LoadGameErrorClass` instance whose `code` literal\n * narrows to `C` and whose `detail` narrows to `LoadGameErrorDetailFor<C>`.\n */\ntype LoadGameErrorVariant<C extends LoadGameErrorCode> = LoadGameErrorClass & {\n readonly code: C;\n readonly detail: LoadGameErrorDetailFor<C>;\n};\n\n/**\n * Public LoadGameError type -- discriminated union of the 3 variants.\n *\n * AI-user form (charter P3 explicit failure):\n *\n * ```ts\n * function recover(err: LoadGameError): string {\n * switch (err.code) {\n * case 'module-not-found': return `game not found: ${err.detail.slug}`;\n * case 'invalid-format': return `bad shape, exports: ${err.detail.exportKeys.join(', ')}`;\n * case 'import-failed': return err.detail.cause instanceof Error ? err.detail.cause.message : 'unknown';\n * }\n * }\n * ```\n */\nexport type LoadGameError = {\n [C in LoadGameErrorCode]: LoadGameErrorVariant<C>;\n}[LoadGameErrorCode];\n\ninterface LoadGameErrorConstructor {\n new <C extends LoadGameErrorCode>(args: {\n code: C;\n expected: string;\n hint: string;\n detail: LoadGameErrorDetailFor<C>;\n }): LoadGameErrorVariant<C>;\n readonly prototype: LoadGameErrorClass;\n}\n\n/**\n * LoadGameError constructor -- `new LoadGameError({ code, expected, hint, detail })`.\n */\nexport const LoadGameError: LoadGameErrorConstructor =\n LoadGameErrorClass as unknown as LoadGameErrorConstructor;\n\n/**\n * `expected` table -- the engine-side invariant that was violated when each\n * code surfaces. AI users read this as the L2 detail (charter F2 priority\n * text); `.hint` carries the recovery action.\n *\n * 3 keys; the policy-owner proof locks the exact count, order, and values.\n */\ntype LoadGameErrorPolicy = { readonly expected: string; readonly hint: string };\n\nconst loadGameErrorPolicy = {\n 'module-not-found': {\n expected:\n 'resolver should return a module with a native Cordis default export for the given slug',\n hint: 'verify the game slug matches an existing template directory; check the resolver import path for typos',\n },\n 'invalid-format': {\n expected: 'resolved module must default-export a Cordis function, class, or object plugin',\n hint: 'default-export one plugin and let the Host mount it into App.pluginContext',\n },\n 'import-failed': {\n expected:\n 'resolver should complete without throwing; import path, network, and build errors are forwarded here',\n hint: 'inspect detail.cause for the original error (network failure, build error, dynamic import timeout, etc.)',\n },\n} satisfies Record<string, LoadGameErrorPolicy>;\n\nexport const LOAD_GAME_EXPECTED: Readonly<Record<LoadGameErrorCode, string>> = Object.fromEntries(\n Object.entries(loadGameErrorPolicy).map(([code, policy]) => [code, policy.expected]),\n) as Readonly<Record<LoadGameErrorCode, string>>;\n\n/**\n * `hint` table -- actionable recovery guidance per code (charter P3).\n *\n * 3 keys; the policy-owner proof locks the exact count, order, and values.\n */\nexport const LOAD_GAME_ERROR_HINTS: Readonly<Record<LoadGameErrorCode, string>> =\n Object.fromEntries(\n Object.entries(loadGameErrorPolicy).map(([code, policy]) => [code, policy.hint]),\n ) as Readonly<Record<LoadGameErrorCode, string>>;\n\n/**\n * Type guard for narrowing unknown errors to LoadGameError.\n *\n * AI users who catch mixed error types can call `if (isLoadGameError(e))`\n * before walking `.code`. Uses instanceof against the internal class\n * (the public constructor delegates to LoadGameErrorClass).\n */\nexport function isLoadGameError(err: unknown): err is LoadGameError {\n return err instanceof LoadGameErrorClass;\n}\n","// @forgeax/engine-app -- loadGame(slug, resolver) -> Result<Plugin, LoadGameError>\n//\n// Pure-function load helper that validates a dynamically-imported game\n// template module. The resolver is an injection point so loadGame is\n// independent of Vite / bundler specifics.\n//\n// Shape:\n// 1. Call resolver(slug). If resolver throws, distinguish module-not-found\n// (slug in detail) from import-failed (cause in detail).\n// 2. Validate the module's `default` export as a Cordis plugin.\n// 3. On success, return that plugin without creating a parallel entry lifecycle.\n//\n// Constraints from upstream:\n// - requirements D-3: loadGame does NOT depend on Vite specifics\n// - requirements boundary-case table: module-not-found -> slug in detail;\n// invalid-format -> exportKeys; import-failed -> cause\n// - plan-strategy D-3: LoadGameError reuses codebase structured error pattern\n//\n// Charter awareness:\n// - P3 explicit failure: all 3 error paths return structured Result.err\n// - F1 context-limited: the function is one screen (no hidden state)\n\nimport type { Plugin } from '@forgeax/engine-plugin';\nimport { err, ok, type Result } from '@forgeax/engine-types';\n\nimport { LOAD_GAME_ERROR_HINTS, LOAD_GAME_EXPECTED, LoadGameError } from './load-game-errors';\n\n/**\n * The shape of a module that the resolver returns.\n */\ninterface GameEntryModule {\n readonly default?: unknown;\n readonly [key: string]: unknown;\n}\n\n/**\n * Resolver function signature: receives a slug (the game identifier),\n * returns a Promise that resolves to a module object.\n *\n * The host (apps/preview/) injects this as a dynamic import proxy,\n * e.g. `(slug) => import(\\`../../templates/\\${slug}/src/main.ts\\`)`.\n * loadGame does not hardcode any import path.\n */\nexport type GamePluginResolver = (slug: string) => Promise<GameEntryModule>;\n\nfunction isPlugin(value: unknown): value is Plugin {\n return (\n typeof value === 'function' ||\n (typeof value === 'object' &&\n value !== null &&\n 'apply' in value &&\n typeof value.apply === 'function')\n );\n}\n\n/**\n * Load and validate a game template module.\n *\n * Returns `Result.ok<Plugin>` when the resolver returns a module\n * whose default export is a native Cordis plugin. Returns `Result.err<LoadGameError>`\n * with one of 3 error codes on failure.\n *\n * @param slug - The game identifier (e.g. 'game-default'). Passed\n * through to the resolver and carried in the 'module-not-found' detail.\n * @param resolver - Async function that imports/fetches the game module.\n * The host owns all path resolution logic.\n */\nexport async function loadGame(\n slug: string,\n resolver: GamePluginResolver,\n): Promise<Result<Plugin, LoadGameError>> {\n let module: GameEntryModule;\n try {\n module = await resolver(slug);\n } catch (thrown: unknown) {\n // Distinguish module-not-found from generic import failure.\n // The heuristic: if the thrown error contains the slug in its message,\n // treat it as module-not-found (the resolver signaled the specific\n // module was not found, e.g. Vite \"Failed to load module\" with the\n // slug path in the message). Otherwise treat it as import-failed\n // (generic network error, eval error, etc.).\n if (thrown instanceof Error && thrown.message.includes(slug)) {\n return err(\n new LoadGameError({\n code: 'module-not-found',\n expected: LOAD_GAME_EXPECTED['module-not-found'],\n hint: LOAD_GAME_ERROR_HINTS['module-not-found'],\n detail: { slug },\n }),\n );\n }\n return err(\n new LoadGameError({\n code: 'import-failed',\n expected: LOAD_GAME_EXPECTED['import-failed'],\n hint: LOAD_GAME_ERROR_HINTS['import-failed'],\n detail: { cause: thrown },\n }),\n );\n }\n\n if (!isPlugin(module.default)) {\n const exportKeys = Object.keys(module);\n return err(\n new LoadGameError({\n code: 'invalid-format',\n expected: LOAD_GAME_EXPECTED['invalid-format'],\n hint: LOAD_GAME_ERROR_HINTS['invalid-format'],\n detail: { exportKeys },\n }),\n );\n }\n\n return ok(module.default);\n}\n","import type { Renderer } from '@forgeax/engine-render';\nimport type { RhiDevice, RhiInstance } from '@forgeax/engine-rhi';\nimport type {\n CreateShaderModuleFn,\n RecordableBackend,\n RecorderAttachment,\n} from '@forgeax/engine-rhi-debug';\nimport { attachRecorder } from '@forgeax/engine-rhi-debug';\nimport { createRhiInstrumentation } from './rhi-capture';\n\nexport interface BrowserRhiDebugRuntime {\n readonly rhi: RhiInstance;\n readonly attachment: RecorderAttachment;\n readonly createReplayDevice: () => Promise<\n import('@forgeax/engine-types').Result<RhiDevice, unknown>\n >;\n readonly createShaderModule: CreateShaderModuleFn;\n readonly rhiInstrumentation: import('@forgeax/engine-render/internal/construct-renderer').RhiBackendInstrumentation;\n attachRenderer(renderer: Renderer): () => void;\n}\n\ninterface BackendModule extends RecordableBackend {\n readonly ensureReady?: () => Promise<unknown>;\n}\n\nfunction hasWebGpu(): boolean {\n const nav = (globalThis as { navigator?: { gpu?: unknown } }).navigator;\n return nav?.gpu !== undefined;\n}\n\nasync function loadBackend(): Promise<BackendModule> {\n const backend = (hasWebGpu()\n ? await import('@forgeax/engine-rhi-webgpu')\n : await import('@forgeax/engine-rhi-wgpu')) as unknown as BackendModule;\n if (!hasWebGpu()) await backend.ensureReady?.();\n return backend;\n}\n\n/**\n * Assemble the browser preview's recorder at the Runtime seam. The preview\n * host owns the attachment and consumes only the encoded tape; it does not\n * reach into recorder state or reintroduce the removed DebugRhi facade.\n */\nexport async function createBrowserRhiDebugRuntime(): Promise<BrowserRhiDebugRuntime> {\n const backend = await loadBackend();\n const attached = attachRecorder(backend);\n if (!attached.ok) throw new Error(attached.error.hint);\n const attachment = attached.value;\n return {\n rhi: attachment.backend.rhi,\n attachment,\n createShaderModule: backend.createShaderModule,\n rhiInstrumentation: createRhiInstrumentation(attachment),\n createReplayDevice: async () => {\n const adapter = await backend.rhi.requestAdapter();\n if (!adapter.ok) return adapter;\n return adapter.value.requestDevice();\n },\n attachRenderer(_renderer: Renderer): () => void {\n // Frame boundaries and device loss are connected by the typed\n // rhiInstrumentation passed to createApp. This hook remains a no-op so\n // the Preview host keeps an explicit lifecycle slot without subscribing\n // a second boundary callback.\n return () => {};\n },\n };\n}\n","import { isSerializableValue, type JsonValue } from '@forgeax/engine-tool-runtime';\n\nexport type ToolPreviewPresentation = 'hidden' | 'visible';\n\nexport interface ToolPreviewAction {\n readonly frame: number;\n readonly name: string;\n readonly value?: JsonValue;\n}\n\nexport interface ToolPreviewRecipe {\n readonly backend: 'webgpu';\n readonly presentation: ToolPreviewPresentation;\n readonly viewport: { readonly width: number; readonly height: number };\n readonly actions: readonly ToolPreviewAction[];\n readonly deltaSeconds: number;\n readonly frames: number;\n}\n\nexport interface ToolPreviewRecipeOptions {\n readonly backend?: 'webgpu' | 'rhi-null' | string;\n readonly presentation?: ToolPreviewPresentation;\n readonly viewport?: { readonly width: number; readonly height: number };\n readonly actions?: readonly ToolPreviewAction[];\n readonly deltaSeconds?: number;\n readonly frames?: number;\n}\n\nexport type ToolPreviewTraceEvent =\n | 'canvas-created'\n | 'rhi-debug-armed'\n | 'renderer-created'\n | 'world-updated'\n | 'draw-submitted'\n | 'validation-complete';\n\nexport interface ToolPreviewTrace {\n readonly events: readonly ToolPreviewTraceEvent[];\n readonly backend: 'webgpu' | string;\n readonly adapter: string;\n readonly presentation: ToolPreviewPresentation;\n}\n\nexport type ToolPreviewTraceValidation =\n | { readonly ok: true; readonly value: ToolPreviewTrace }\n | {\n readonly ok: false;\n readonly error: {\n readonly code: 'tool-preview-invalid-trace';\n readonly expected: string;\n readonly hint: string;\n readonly detail: { readonly missing: string; readonly index: number };\n };\n };\n\nexport function createToolPreviewRecipe(options: ToolPreviewRecipeOptions): ToolPreviewRecipe {\n if (options.backend !== undefined && options.backend !== 'webgpu') {\n throw new TypeError('tool preview requires the real WebGPU backend');\n }\n const viewport = options.viewport ?? { width: 640, height: 360 };\n if (\n !Number.isSafeInteger(viewport.width) ||\n !Number.isSafeInteger(viewport.height) ||\n viewport.width <= 0 ||\n viewport.height <= 0\n ) {\n throw new TypeError('tool preview viewport must contain positive safe integers');\n }\n const deltaSeconds = options.deltaSeconds ?? 1 / 60;\n const frames = options.frames ?? 1;\n if (!Number.isFinite(deltaSeconds) || deltaSeconds < 0) {\n throw new TypeError('tool preview deltaSeconds must be finite and non-negative');\n }\n if (!Number.isSafeInteger(frames) || frames <= 0) {\n throw new TypeError('tool preview frames must be a positive safe integer');\n }\n const actions = (options.actions ?? []).map((action) => ({ ...action }));\n for (const action of actions) {\n if (\n !Number.isSafeInteger(action.frame) ||\n action.frame < 0 ||\n action.frame >= frames ||\n action.name.length === 0 ||\n (action.value !== undefined && !isSerializableValue(action.value))\n ) {\n throw new TypeError('tool preview actions require a valid frame, name, and JSON value');\n }\n }\n return {\n backend: 'webgpu',\n presentation: options.presentation ?? 'hidden',\n viewport: { width: viewport.width, height: viewport.height },\n actions,\n deltaSeconds,\n frames,\n };\n}\n\nconst REQUIRED_EVENTS: readonly ToolPreviewTraceEvent[] = [\n 'canvas-created',\n 'rhi-debug-armed',\n 'renderer-created',\n 'world-updated',\n 'draw-submitted',\n 'validation-complete',\n];\n\nexport function validateToolPreviewTrace(trace: ToolPreviewTrace): ToolPreviewTraceValidation {\n if (trace.backend !== 'webgpu') {\n return {\n ok: false,\n error: {\n code: 'tool-preview-invalid-trace',\n expected: 'trace.backend === \"webgpu\"',\n hint: 'run the same recipe with a real WebGPU adapter; RHI-null is not a preview backend',\n detail: { missing: 'webgpu-backend', index: -1 },\n },\n };\n }\n let last = -1;\n for (const event of REQUIRED_EVENTS) {\n const index = trace.events.indexOf(event);\n if (index <= last) {\n return {\n ok: false,\n error: {\n code: 'tool-preview-invalid-trace',\n expected: `event '${event}' occurs after the previous recipe phase`,\n hint: 'arm RHI-debug before Renderer construction and retain update/draw/validation evidence',\n detail: { missing: event, index },\n },\n };\n }\n last = index;\n }\n return { ok: true, value: trace };\n}\n","import { createProfiler } from '@forgeax/engine-profiler';\nimport {\n buildTapeIndex,\n decodeTape,\n decodeToRgba8,\n openReplay,\n type V7Tape,\n} from '@forgeax/engine-rhi-debug';\nimport {\n type ArtifactRef,\n createPreviewArtifactManifest,\n type PreviewArtifactManifest,\n type SnapshotRef,\n type ToolTiming,\n} from '@forgeax/engine-tool-runtime';\nimport { err, ok, type Result } from '@forgeax/engine-types';\nimport { createApp } from '../create-app';\nimport { createBrowserRhiDebugRuntime } from '../internal/browser-rhi-debug-runtime';\nimport type { App, BundlerOptions, CreateAppOptions } from '../types';\nimport {\n createToolPreviewRecipe,\n type ToolPreviewAction,\n type ToolPreviewRecipe,\n type ToolPreviewTrace,\n} from './recipe';\n\nexport type ToolPreviewResourceKind = 'material' | 'mesh' | 'texture' | 'vfx';\n\nexport interface ToolPreviewResourceRequest {\n readonly kind: ToolPreviewResourceKind;\n readonly guid: string;\n readonly size?: number;\n}\n\nexport interface ToolPreviewResourceFacts {\n readonly kind: ToolPreviewResourceKind;\n readonly guid: string;\n readonly asset: unknown;\n readonly digest?: string;\n readonly ownerFacts?: Readonly<Record<string, string | number | boolean>>;\n readonly observation?: Readonly<Record<string, string | number | boolean | readonly number[]>>;\n}\n\nexport interface ToolPreviewHostOptions {\n readonly runId?: string;\n readonly recipe: ToolPreviewRecipe;\n readonly snapshot: SnapshotRef;\n readonly canvas?: HTMLCanvasElement;\n readonly root?: Document | HTMLElement;\n readonly app?: Omit<CreateAppOptions, 'rhi'>;\n readonly bundler?: BundlerOptions;\n readonly resource?: ToolPreviewResourceRequest;\n readonly prepare?: (\n app: App,\n ) => void | ToolPreviewResourceFacts | Promise<void | ToolPreviewResourceFacts>;\n /** Refresh producer-owned resource facts after the bounded real frame run. */\n readonly collectResourceFacts?: (\n app: App,\n current: ToolPreviewResourceFacts | undefined,\n ) => void | ToolPreviewResourceFacts | Promise<void | ToolPreviewResourceFacts>;\n /** Dispose producer-owned preview attachments before the App. */\n readonly onDispose?: (app: App) => void | Promise<void>;\n readonly executeAction?: (action: ToolPreviewAction, app: App) => boolean | Promise<boolean>;\n}\n\nexport interface ToolPreviewHostError {\n readonly code: 'tool-preview-capability-unavailable' | 'tool-preview-bootstrap-failed';\n readonly expected: string;\n readonly hint: string;\n readonly detail: { readonly phase: string; readonly cause?: unknown };\n}\n\nexport interface ToolPreviewHost {\n readonly app: App;\n readonly recipe: ToolPreviewRecipe;\n readonly trace: ToolPreviewTrace;\n capture(): Promise<Result<ToolPreviewCaptureResult, ToolPreviewHostError>>;\n run(): Promise<Result<ToolPreviewRunResult, ToolPreviewHostError>>;\n dispose(): Promise<Result<void, ToolPreviewHostError>>;\n}\n\nexport interface ToolPreviewCaptureResult {\n readonly recipe: ToolPreviewRecipe;\n readonly snapshot: SnapshotRef;\n readonly trace: ToolPreviewTrace;\n readonly captureId: string;\n readonly actionTrace: readonly ToolPreviewAction[];\n readonly tape: {\n readonly runId: string;\n readonly jsonUri: string;\n readonly blobUri: string;\n readonly byteLength: number;\n };\n readonly profile: { readonly captureId: string; readonly uri: string };\n readonly capturePng: { readonly uri: string; readonly width: number; readonly height: number };\n readonly executeDurationMs: number;\n readonly captureDurationMs: number;\n readonly browserJsHeapBytes?: number;\n readonly appErrors: readonly unknown[];\n readonly resource?: ToolPreviewResourceFacts;\n}\n\nexport interface ToolPreviewRunResult {\n readonly trace: ToolPreviewTrace;\n readonly captureId: string;\n readonly drawCalls: number;\n readonly committedDrawIndex: number;\n readonly nonBlackPixels: number;\n readonly actionTrace: readonly ToolPreviewAction[];\n readonly tape: {\n readonly runId: string;\n readonly jsonUri: string;\n readonly blobUri: string;\n readonly byteLength: number;\n };\n readonly profile: { readonly captureId: string; readonly uri: string };\n readonly capturePng: { readonly uri: string; readonly width: number; readonly height: number };\n readonly png: { readonly uri: string; readonly width: number; readonly height: number };\n readonly manifest: PreviewArtifactManifest;\n readonly artifacts: readonly ArtifactRef[];\n readonly operationTiming: ToolTiming;\n readonly resource?: ToolPreviewResourceFacts;\n}\n\nfunction layoutCanvas(canvas: HTMLCanvasElement, recipe: ToolPreviewRecipe): void {\n canvas.width = recipe.viewport.width;\n canvas.height = recipe.viewport.height;\n canvas.style.position = 'fixed';\n canvas.style.inset = '0';\n canvas.style.width = `${recipe.viewport.width}px`;\n canvas.style.height = `${recipe.viewport.height}px`;\n canvas.style.opacity = '1';\n canvas.style.visibility = 'visible';\n canvas.style.pointerEvents = 'auto';\n}\n\nfunction appendCanvas(canvas: HTMLCanvasElement, root: Document | HTMLElement | undefined): void {\n if (canvas.isConnected) return;\n const parent =\n typeof Document !== 'undefined' && root instanceof Document\n ? root.body\n : (root ?? (typeof document === 'undefined' ? undefined : document.body));\n parent?.appendChild(canvas);\n}\n\nfunction removeOwnedCanvas(canvas: HTMLCanvasElement, owned: boolean): void {\n if (owned && canvas.isConnected) canvas.remove();\n}\n\nfunction bytesToDataUri(bytes: Uint8Array, mediaType: string): string {\n let binary = '';\n for (let offset = 0; offset < bytes.length; offset += 0x2000) {\n binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x2000));\n }\n return `data:${mediaType};base64,${btoa(binary)}`;\n}\n\nasync function sha256(bytes: Uint8Array): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', new Uint8Array(bytes).buffer as ArrayBuffer);\n return `sha256:${[...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, '0')).join('')}`;\n}\n\nfunction dataUriBytes(uri: string): Uint8Array {\n const encoded = uri.slice(uri.indexOf(',') + 1);\n const binary = atob(encoded);\n return Uint8Array.from(binary, (char) => char.charCodeAt(0));\n}\n\nfunction generateRunId(): string {\n return `preview-${crypto.randomUUID()}`;\n}\n\nfunction countDrawCalls(tape: V7Tape): number {\n return buildTapeIndex(tape).works.filter((work) => isRenderDraw(work.kind)).length;\n}\n\nfunction lastRenderDrawIndex(tape: V7Tape): number {\n const works = buildTapeIndex(tape).works;\n return works.reduce((last, work) => (isRenderDraw(work.kind) ? work.workIndex : last), -1);\n}\n\nfunction isRenderDraw(kind: ReturnType<typeof buildTapeIndex>['works'][number]['kind']): boolean {\n return (\n kind === 'draw' ||\n kind === 'drawIndexed' ||\n kind === 'drawIndirect' ||\n kind === 'drawIndexedIndirect'\n );\n}\n\nfunction resourceSubjectDigest(resource: ToolPreviewResourceFacts | undefined): string | undefined {\n if (resource === undefined) return undefined;\n const asset =\n typeof resource.asset === 'object' && resource.asset !== null\n ? (resource.asset as Record<string, unknown>)\n : undefined;\n const candidates = [\n resource.observation?.subjectDigest,\n resource.digest,\n asset?.digest,\n asset?.programFingerprint,\n ];\n return candidates.find((value): value is string => typeof value === 'string' && value.length > 0);\n}\n\nexport async function replayToolPreviewCapture(\n capture: ToolPreviewCaptureResult,\n): Promise<Result<ToolPreviewRunResult, ToolPreviewHostError>> {\n const analyzeStartedAtMs = performance.now();\n const tapeBytes = dataUriBytes(capture.tape.jsonUri);\n const parsed = decodeTape(tapeBytes);\n if (!parsed.ok) {\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'the finalized tape to deserialize for fresh-device replay',\n hint: parsed.error.hint,\n detail: { phase: 'tape-parse', cause: parsed.error },\n });\n }\n const subjectDigest = resourceSubjectDigest(capture.resource);\n if (capture.resource !== undefined && subjectDigest === undefined) {\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'the resource owner to publish a subject identity before evidence publication',\n hint: 'repair AssetRegistry owner facts or post-frame observation; recipe and trace are not subject identity',\n detail: { phase: 'resource-identity' },\n });\n }\n let runtime: Awaited<ReturnType<typeof createBrowserRhiDebugRuntime>>;\n try {\n runtime = await createBrowserRhiDebugRuntime();\n } catch (cause) {\n return err({\n code: 'tool-preview-capability-unavailable',\n expected: 'a fresh browser WebGPU runtime for offline replay',\n hint: 'Run replay in an isolated browser process; do not reuse the capture device.',\n detail: { phase: 'replay-runtime', cause },\n });\n }\n const replayDevice = await runtime.createReplayDevice();\n if (!replayDevice.ok) {\n return err({\n code: 'tool-preview-capability-unavailable',\n expected: 'a fresh WebGPU device for offline replay',\n hint: 'the capture device cannot be reused as a substitute for fresh-device replay',\n detail: { phase: 'replay-device', cause: replayDevice.error },\n });\n }\n const replayResult = await openReplay(parsed.value, {\n device: replayDevice.value,\n createShaderModule: runtime.createShaderModule,\n });\n if (!replayResult.ok) {\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'the self-contained tape to replay on a fresh WebGPU device',\n hint: replayResult.error.hint,\n detail: { phase: 'replay-create', cause: replayResult.error },\n });\n }\n const replay = replayResult.value;\n const drawCalls = countDrawCalls(parsed.value);\n if (drawCalls === 0) {\n await replay.dispose();\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'the preview recipe to submit at least one render draw',\n hint: 'seed a visible mesh and camera before capturing the preview frame',\n detail: { phase: 'replay-draws', cause: { appErrors: capture.appErrors } },\n });\n }\n const committedDrawIndex = lastRenderDrawIndex(parsed.value);\n if (committedDrawIndex < 0) {\n await replay.dispose();\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'the preview tape to contain a render draw after compute work',\n hint: 'seed a visible render output after simulation dispatches before capturing the preview frame',\n detail: { phase: 'replay-draws', cause: { appErrors: capture.appErrors } },\n });\n }\n const committed = await replay.inspectWork(committedDrawIndex, ['pixels']);\n if (!committed.ok || committed.value.attachment === undefined) {\n await replay.dispose();\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'the fresh replay session to expose a color attachment for the final render work',\n hint: committed.ok\n ? 'the tape contains no readable color attachment for PNG evidence'\n : committed.error.hint,\n detail: { phase: 'replay-inspect', cause: committed.ok ? undefined : committed.error },\n });\n }\n const attachment = committed.value.attachment;\n const width = attachment.width ?? 0;\n const height = attachment.height ?? 0;\n const rgba =\n attachment.format === undefined\n ? undefined\n : decodeToRgba8(attachment.bytes, attachment.format, width, height);\n if (rgba === null || rgba === undefined || width <= 0 || height <= 0) {\n await replay.dispose();\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'the replayed color attachment to have a supported display format',\n hint: 'move PNG encoding to the producer-owned preview shell for unsupported formats',\n detail: { phase: 'png-readback', cause: { format: attachment.format, width, height } },\n });\n }\n const outputCanvas = document.createElement('canvas');\n outputCanvas.width = width;\n outputCanvas.height = height;\n const outputContext = outputCanvas.getContext('2d');\n if (outputContext === null) {\n await replay.dispose();\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'the browser to provide a 2D canvas context for replay PNG encoding',\n hint: 'enable the browser canvas 2D context before running the preview host',\n detail: { phase: 'png-encode' },\n });\n }\n outputContext.putImageData(new ImageData(rgba, width, height), 0, 0);\n await replay.dispose();\n const pixels = outputContext.getImageData(0, 0, width, height).data;\n let nonBlackPixels = 0;\n if (pixels !== undefined) {\n for (let offset = 0; offset < pixels.length; offset += 4) {\n if ((pixels[offset] ?? 0) + (pixels[offset + 1] ?? 0) + (pixels[offset + 2] ?? 0) > 0) {\n nonBlackPixels += 1;\n }\n }\n }\n if (nonBlackPixels === 0) {\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'the replayed PNG to contain non-black pixels',\n hint: 'inspect the RHI tape and renderer draw submission before accepting the preview',\n detail: { phase: 'png-non-black' },\n });\n }\n const analyzeDurationMs = performance.now() - analyzeStartedAtMs;\n const finalizeStartedAtMs = performance.now();\n const pngUri = outputCanvas.toDataURL('image/png');\n const pngBytes = dataUriBytes(pngUri);\n if (\n !capture.capturePng.uri.startsWith('data:image/png') ||\n capture.capturePng.width <= 0 ||\n capture.capturePng.height <= 0\n ) {\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'the capture browser to provide a PNG before fresh replay',\n hint: 'capture the rendered canvas before closing the capture carrier; do not reuse the replay PNG',\n detail: { phase: 'capture-png' },\n });\n }\n const capturePngBytes = dataUriBytes(capture.capturePng.uri);\n if (capturePngBytes.byteLength === 0) {\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'the capture PNG to contain encoded bytes',\n hint: 'repair the capture carrier readback before publishing evidence',\n detail: { phase: 'capture-png' },\n });\n }\n const profileBytes = dataUriBytes(capture.profile.uri);\n const tapeDigest = await sha256(tapeBytes);\n const capturePngDigest = await sha256(capturePngBytes);\n const pngDigest = await sha256(pngBytes);\n const profileDigest = await sha256(profileBytes);\n const presentationDigest = await sha256(new TextEncoder().encode(capture.trace.presentation));\n const manifest = createPreviewArtifactManifest({\n schemaVersion: '2.0.0',\n identity: {\n runId: capture.tape.runId,\n snapshotDigest: capture.snapshot.digest,\n subjectDigest: subjectDigest ?? capture.snapshot.digest,\n presentationDigest,\n frameId: 0,\n captureId: capture.captureId,\n },\n artifacts: [\n {\n owner: 'rhi-debug',\n kind: 'rhi-tape',\n role: 'rhi-tape',\n uri: capture.tape.jsonUri,\n digest: tapeDigest,\n byteLength: tapeBytes.byteLength,\n mediaType: 'application/json',\n derivedFrom: [],\n },\n {\n owner: 'visual',\n kind: 'png',\n role: 'capture',\n uri: capture.capturePng.uri,\n digest: capturePngDigest,\n byteLength: capturePngBytes.byteLength,\n mediaType: 'image/png',\n derivedFrom: [tapeDigest],\n },\n {\n owner: 'rhi-debug-replay',\n kind: 'png',\n role: 'fresh-replay',\n uri: pngUri,\n digest: pngDigest,\n byteLength: pngBytes.byteLength,\n mediaType: 'image/png',\n derivedFrom: [tapeDigest, capturePngDigest],\n },\n {\n owner: 'profiler',\n kind: 'profile-capture',\n role: 'profile-capture',\n uri: capture.profile.uri,\n digest: profileDigest,\n byteLength: profileBytes.byteLength,\n mediaType: 'application/json',\n derivedFrom: [],\n },\n ],\n });\n const finalizeDurationMs = performance.now() - finalizeStartedAtMs;\n const durationMs =\n capture.executeDurationMs + capture.captureDurationMs + analyzeDurationMs + finalizeDurationMs;\n const memory = (\n performance as Performance & {\n readonly memory?: { readonly usedJSHeapSize?: number };\n }\n ).memory?.usedJSHeapSize;\n const browserJsHeapBytes =\n typeof memory === 'number' && Number.isFinite(memory) && memory >= 0\n ? Math.max(Math.round(memory), capture.browserJsHeapBytes ?? 0)\n : capture.browserJsHeapBytes;\n return ok({\n trace: capture.trace,\n captureId: capture.captureId,\n drawCalls,\n committedDrawIndex,\n nonBlackPixels,\n actionTrace: capture.actionTrace,\n tape: capture.tape,\n profile: capture.profile,\n capturePng: capture.capturePng,\n png: { uri: pngUri, width: outputCanvas.width, height: outputCanvas.height },\n manifest,\n artifacts: manifest.artifacts.flatMap((artifact) => {\n if (\n artifact.kind !== 'rhi-tape' &&\n artifact.kind !== 'png' &&\n artifact.kind !== 'profile-capture'\n ) {\n return [];\n }\n return [\n {\n kind: artifact.kind,\n digest: artifact.digest,\n uri: artifact.uri,\n sizeBytes: artifact.byteLength,\n },\n ];\n }),\n operationTiming: {\n startedAtMs: 0,\n endedAtMs: durationMs,\n durationMs,\n phases: {\n lookup: { status: 'not-applicable' },\n lease: { status: 'not-applicable' },\n transport: { status: 'not-applicable' },\n execute: {\n status: 'observed',\n durationMs: capture.executeDurationMs,\n workUnits: capture.recipe.frames,\n },\n capture: { status: 'observed', durationMs: capture.captureDurationMs },\n finalize: { status: 'observed', durationMs: finalizeDurationMs },\n analyze: { status: 'observed', durationMs: analyzeDurationMs },\n },\n unattributedMs: 0,\n resources: {\n 'node-rss': { status: 'not-applicable' },\n 'browser-js-heap':\n browserJsHeapBytes === undefined\n ? { status: 'unavailable', reason: 'performance.memory is not exposed' }\n : {\n status: 'observed',\n bytes: browserJsHeapBytes,\n source: 'maximum performance.memory.usedJSHeapSize across capture and replay',\n },\n 'artifact-bytes': {\n status: 'observed',\n bytes:\n tapeBytes.byteLength +\n dataUriBytes(capture.capturePng.uri).byteLength +\n pngBytes.byteLength +\n profileBytes.byteLength,\n source: 'browser-produced artifact payloads',\n },\n 'gpu-memory': {\n status: 'unavailable',\n reason: 'WebGPU does not expose portable allocation totals',\n },\n },\n },\n ...(capture.resource === undefined ? {} : { resource: capture.resource }),\n });\n}\n\nexport async function createToolPreviewHost(\n options: ToolPreviewHostOptions,\n): Promise<Result<ToolPreviewHost, ToolPreviewHostError>> {\n const recipe = createToolPreviewRecipe(options.recipe);\n const runId = options.runId ?? generateRunId();\n const doc = options.root ?? (typeof document === 'undefined' ? undefined : document);\n if (options.canvas === undefined && doc === undefined) {\n return err({\n code: 'tool-preview-capability-unavailable',\n expected: 'a DOM document or caller-owned HTMLCanvasElement',\n hint: 'run the browser host or provide an attached canvas; headless does not mean RHI-null',\n detail: { phase: 'canvas' },\n });\n }\n const canvas =\n options.canvas ??\n (typeof Document !== 'undefined' && doc instanceof Document\n ? doc.createElement('canvas')\n : undefined);\n const ownsCanvas = options.canvas === undefined;\n if (canvas === undefined) {\n return err({\n code: 'tool-preview-capability-unavailable',\n expected: 'root document can create an HTMLCanvasElement',\n hint: 'provide a document root or an existing canvas',\n detail: { phase: 'canvas' },\n });\n }\n layoutCanvas(canvas, recipe);\n appendCanvas(canvas, options.root);\n if (!canvas.isConnected) {\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'preview canvas is connected before App creation',\n hint: 'attach the canvas to the document or pass a connected caller-owned canvas',\n detail: { phase: 'canvas' },\n });\n }\n\n let runtime: Awaited<ReturnType<typeof createBrowserRhiDebugRuntime>>;\n try {\n runtime = await createBrowserRhiDebugRuntime();\n } catch (cause) {\n removeOwnedCanvas(canvas, ownsCanvas);\n return err({\n code: 'tool-preview-capability-unavailable',\n expected: 'a real WebGPU adapter and device',\n hint: 'install or enable WebGPU; do not replace this route with RHI-null',\n detail: { phase: 'rhi-debug', cause },\n });\n }\n const profiler = createProfiler();\n const appResult = await createApp(\n canvas,\n {\n ...(options.app ?? {}),\n rhi: runtime.rhi,\n rhiInstrumentation: runtime.rhiInstrumentation,\n profiler,\n },\n options.bundler,\n );\n if (!appResult.ok) {\n await runtime.attachment.dispose();\n removeOwnedCanvas(canvas, ownsCanvas);\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'createApp constructs a real WebGPU Renderer',\n hint: 'inspect the structured App/RHI error; the preview must not fall back to RHI-null',\n detail: { phase: 'renderer', cause: appResult.error },\n });\n }\n const app = appResult.value;\n const appErrors: unknown[] = [];\n const unsubscribeAppErrors = app.onError((error) => appErrors.push(error));\n let resourceFacts: ToolPreviewResourceFacts | undefined;\n try {\n const prepared = await options.prepare?.(app);\n if (prepared !== undefined) resourceFacts = prepared;\n } catch (cause) {\n unsubscribeAppErrors();\n await app.dispose();\n await runtime.attachment.dispose();\n removeOwnedCanvas(canvas, ownsCanvas);\n const bootstrapFailure =\n options.resource === undefined\n ? {\n expected: 'the project bootstrap to prepare the preview World',\n hint: 'Repair the project Entry, assets, or scene before retrying the same recipe.',\n phase: 'project-bootstrap',\n }\n : {\n expected: 'the resource preview bootstrap to prepare the preview World',\n hint: 'Repair the resource owner, cooked payload, or preview environment before retrying the same recipe.',\n phase: 'resource-bootstrap',\n };\n return err({\n code: 'tool-preview-bootstrap-failed',\n ...bootstrapFailure,\n detail: { phase: bootstrapFailure.phase, cause },\n });\n }\n const attached = app.renderer.attach(app.world);\n if (!attached.ok) {\n unsubscribeAppErrors();\n await app.dispose();\n await runtime.attachment.dispose();\n removeOwnedCanvas(canvas, ownsCanvas);\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'the preview World to attach to the real Renderer before stepping',\n hint: attached.error.hint,\n detail: { phase: 'world-attach', cause: attached.error },\n });\n }\n const profileSession = profiler.startCapture({ frameLimit: recipe.frames, eventLimit: 1024 });\n if (!profileSession.ok) {\n await app.dispose();\n await runtime.attachment.dispose();\n removeOwnedCanvas(canvas, ownsCanvas);\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'the App profiler to start a bounded capture',\n hint: profileSession.error.hint,\n detail: { phase: 'profiler', cause: profileSession.error },\n });\n }\n const detach = runtime.attachRenderer(app.renderer);\n const trace: ToolPreviewTrace = {\n events: ['canvas-created', 'rhi-debug-armed', 'renderer-created'],\n backend: 'webgpu',\n adapter: 'webgpu-adapter',\n presentation: recipe.presentation,\n };\n let disposed = false;\n const capturePreview = async (): Promise<\n Result<ToolPreviewCaptureResult, ToolPreviewHostError>\n > => {\n if (disposed) {\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'preview host remains alive until capture completes',\n hint: 'create a new preview host after dispose',\n detail: { phase: 'capture' },\n });\n }\n const started = app.start();\n if (!started.ok)\n return err({\n ...started.error,\n code: 'tool-preview-bootstrap-failed',\n detail: { phase: 'start', cause: started.error },\n });\n const paused = app.pause();\n if (!paused.ok)\n return err({\n ...paused.error,\n code: 'tool-preview-bootstrap-failed',\n detail: { phase: 'pause', cause: paused.error },\n });\n const executeStartedAtMs = performance.now();\n const actionTrace: ToolPreviewAction[] = [];\n const encodedCapture = runtime.attachment.captureFrame();\n for (let frame = 0; frame < recipe.frames; frame += 1) {\n for (const action of recipe.actions.filter((candidate) => candidate.frame === frame)) {\n let accepted = false;\n try {\n accepted = (await options.executeAction?.(action, app)) === true;\n } catch (cause) {\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: `project action '${action.name}' to execute at frame ${frame}`,\n hint: 'Repair the project-owned preview action handler and rerun the same recipe.',\n detail: { phase: 'action', cause },\n });\n }\n if (!accepted) {\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: `project action '${action.name}' to have a registered handler`,\n hint: 'Register the action in the project plugin or remove it from the recipe.',\n detail: { phase: 'action', cause: { frame, name: action.name } },\n });\n }\n actionTrace.push(action);\n }\n const stepped = app.stepFrame(recipe.deltaSeconds);\n if (!stepped.ok)\n return err({\n ...stepped.error,\n code: 'tool-preview-bootstrap-failed',\n detail: { phase: 'frame', cause: stepped.error },\n });\n // Render features may start an asynchronous shader/module bake on their\n // first prepare pass. Yield once between bounded frames so the bake can\n // settle before the next retry; a synchronous tight loop would capture\n // only the feature's intentional `next-frame` pending state.\n await new Promise<void>((resolve) => setTimeout(resolve, 0));\n }\n // RecorderAttachment captures one complete frame. The first boundary\n // snapshots live resources and the following boundary finalizes it;\n // explicit boundaries keep stepFrame() deterministic for preview hosts.\n await runtime.attachment.frameBoundary();\n await new Promise<void>((resolve) => setTimeout(resolve, 0));\n await runtime.attachment.frameBoundary();\n if (options.collectResourceFacts !== undefined) {\n try {\n const collected = await options.collectResourceFacts(app, resourceFacts);\n if (collected !== undefined) resourceFacts = collected;\n } catch (cause) {\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'the resource owner to publish post-frame preview facts',\n hint: 'Repair the producer-owned preview observation and retry the same recipe.',\n detail: { phase: 'resource-observation', cause },\n });\n }\n }\n const executeDurationMs = performance.now() - executeStartedAtMs;\n const finalTrace: ToolPreviewTrace = {\n ...trace,\n events: [...trace.events, 'world-updated', 'draw-submitted', 'validation-complete'],\n };\n const captureStartedAtMs = performance.now();\n const profile = profileSession.value.finish();\n if (!profile.ok) {\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'the bounded App profiler to finish with ProfileCapture',\n hint: profile.error.hint,\n detail: { phase: 'profiler-finish', cause: profile.error },\n });\n }\n const tape = await encodedCapture;\n if (!tape.ok)\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'RHI-debug produces a self-contained tape',\n hint: tape.error.hint,\n detail: { phase: 'rhi-finalize', cause: tape.error },\n });\n const captureDurationMs = performance.now() - captureStartedAtMs;\n const tapeBytes = tape.value.bytes;\n const profileBytes = new TextEncoder().encode(JSON.stringify(profile.value));\n const capturePng = {\n uri: canvas.toDataURL('image/png'),\n width: canvas.width,\n height: canvas.height,\n };\n const memory = (\n performance as Performance & {\n readonly memory?: { readonly usedJSHeapSize?: number };\n }\n ).memory?.usedJSHeapSize;\n return ok({\n recipe,\n snapshot: options.snapshot,\n trace: finalTrace,\n captureId: profile.value.captureId,\n actionTrace,\n tape: {\n runId,\n jsonUri: bytesToDataUri(tapeBytes, 'application/octet-stream'),\n blobUri: bytesToDataUri(new Uint8Array(), 'application/octet-stream'),\n byteLength: tapeBytes.byteLength,\n },\n profile: {\n captureId: profile.value.captureId,\n uri: bytesToDataUri(profileBytes, 'application/json'),\n },\n capturePng,\n executeDurationMs,\n captureDurationMs,\n ...(typeof memory === 'number' && Number.isFinite(memory) && memory >= 0\n ? { browserJsHeapBytes: Math.round(memory) }\n : {}),\n appErrors,\n ...(resourceFacts === undefined ? {} : { resource: resourceFacts }),\n });\n };\n return ok({\n app,\n recipe,\n trace,\n capture: capturePreview,\n async run() {\n const capture = await capturePreview();\n if (!capture.ok) return capture;\n return replayToolPreviewCapture(capture.value);\n },\n async dispose() {\n if (disposed) return ok(undefined);\n disposed = true;\n detach();\n unsubscribeAppErrors();\n let disposeError: unknown;\n try {\n await options.onDispose?.(app);\n } catch (cause) {\n disposeError = cause;\n }\n const result = await app.dispose();\n removeOwnedCanvas(canvas, ownsCanvas);\n if (disposeError !== undefined) {\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'producer-owned preview attachments to dispose before the App',\n hint: 'Repair the preview owner lifecycle and retry the same operation.',\n detail: { phase: 'producer-dispose', cause: disposeError },\n });\n }\n return result.ok\n ? ok(undefined)\n : err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'preview app disposes cleanly',\n hint: result.error.hint,\n detail: { phase: 'dispose', cause: result.error },\n });\n },\n });\n}\n","import {\n type ArtifactRef,\n createArtifactRef,\n type PreviewArtifactManifest,\n type PreviewArtifactRole,\n type SnapshotRef,\n snapshotStaleError,\n type ToolRuntimeError,\n validatePreviewArtifactManifest,\n} from '@forgeax/engine-tool-runtime';\nimport { err, ok, type Result } from '@forgeax/engine-types';\nimport type { ToolPreviewTrace } from './recipe';\n\nexport interface ToolPreviewEvidence {\n readonly trace: ToolPreviewTrace;\n readonly artifacts: readonly ArtifactRef[];\n readonly manifest?: PreviewArtifactManifest;\n}\n\nexport function joinToolPreviewEvidence(input: {\n readonly trace: ToolPreviewTrace;\n readonly manifest: PreviewArtifactManifest;\n readonly required: readonly PreviewArtifactRole[];\n}): Result<ToolPreviewEvidence, ToolRuntimeError> {\n const validated = validatePreviewArtifactManifest(input.manifest, input.required);\n if (!validated.ok) return err(validated.error);\n const artifacts = input.manifest.artifacts.map((artifact) =>\n createArtifactRef({\n kind:\n artifact.kind === 'report' || artifact.kind === 'contact-sheet'\n ? 'tool-result'\n : artifact.kind,\n digest: artifact.digest,\n uri: artifact.uri,\n mediaType: artifact.mediaType,\n sizeBytes: artifact.byteLength,\n }),\n );\n return ok({ trace: input.trace, artifacts, manifest: input.manifest });\n}\n\nexport function createToolPreviewEvidence(\n trace: ToolPreviewTrace,\n artifacts: readonly ArtifactRef[],\n): ToolPreviewEvidence {\n return { trace, artifacts: [...artifacts] };\n}\n\nexport function joinResourcePreviewEvidence(input: {\n readonly snapshot: SnapshotRef;\n readonly manifest: PreviewArtifactManifest;\n readonly requiredRoles: readonly PreviewArtifactRole[];\n}): Result<PreviewArtifactManifest, ToolRuntimeError> {\n if (input.manifest.identity.snapshotDigest !== input.snapshot.digest) {\n return err(snapshotStaleError(input.snapshot.digest, input.manifest.identity.snapshotDigest));\n }\n const validated = validatePreviewArtifactManifest(input.manifest, input.requiredRoles);\n return validated.ok ? ok(validated.value) : err(validated.error);\n}\n","export interface ToolPreviewCameraFrame {\n readonly center: readonly [number, number, number];\n readonly radius: number;\n readonly distance: number;\n readonly near: number;\n readonly far: number;\n}\n\nexport function fitToolPreviewCameraToAabb(\n aabb: readonly [number, number, number, number, number, number],\n options: { readonly aspect: number; readonly fov: number; readonly padding?: number },\n): ToolPreviewCameraFrame {\n const [minX, minY, minZ, maxX, maxY, maxZ] = aabb;\n if (\n ![minX, minY, minZ, maxX, maxY, maxZ].every(Number.isFinite) ||\n minX > maxX ||\n minY > maxY ||\n minZ > maxZ ||\n !Number.isFinite(options.aspect) ||\n options.aspect <= 0 ||\n !Number.isFinite(options.fov) ||\n options.fov <= 0 ||\n options.fov >= Math.PI\n ) {\n throw new TypeError('tool preview camera framing requires a finite AABB, aspect, and FOV');\n }\n const center: readonly [number, number, number] = [\n (minX + maxX) / 2,\n (minY + maxY) / 2,\n (minZ + maxZ) / 2,\n ];\n const radius = Math.max(\n Math.hypot((maxX - minX) / 2, (maxY - minY) / 2, (maxZ - minZ) / 2),\n 0.001,\n );\n const verticalHalfFov = options.fov / 2;\n const horizontalHalfFov = Math.atan(Math.tan(verticalHalfFov) * options.aspect);\n const limitingHalfFov = Math.min(verticalHalfFov, horizontalHalfFov);\n const padding = options.padding ?? 1.15;\n if (!Number.isFinite(padding) || padding < 1) {\n throw new TypeError('tool preview camera framing padding must be finite and at least one');\n }\n const distance = (radius / Math.sin(limitingHalfFov)) * padding;\n const depthMargin = radius * (padding - 1);\n return {\n center,\n radius,\n distance,\n near: Math.max(0.001, distance - radius - depthMargin),\n far: distance + radius + depthMargin,\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/internal/ecs-import.ts","../src/internal/browser-remote-bridge.ts","../src/browser-frame-signal.ts","../src/animation-asset-lookup.ts","../src/errors.ts","../src/execution/bootstrap-entry.ts","../src/execution/types.ts","../src/execution/capabilities.ts","../src/execution/schema.ts","../src/execution/report.ts","../src/execution/control.ts","../src/execution/selector.ts","../src/execution/bootstrap-url.ts","../src/internal/error-fanout.ts","../src/types.ts","../src/execution/engine-worker.ts","../src/execution/measurement.ts","../src/execution/protocol.ts","../src/execution/host-controller.ts","../src/renderer-plugin.ts","../src/internal/assets-world-plugin.ts","../src/internal/assembled-engine-profile.ts","../src/internal/component-introspection.ts","../src/internal/frame-loop.ts","../src/internal/input-attach.ts","../src/input-map-plugin.ts","../src/input-plugin.ts","../../render/src/record/render-context.ts","../src/internal/debug-draw.ts","../src/internal/main-engine-profile.ts","../src/internal/remote-serve-flag.ts","../src/internal/remote-server-plugin.ts","../src/internal/rhi-capture.ts","../src/internal/rhi-debug-flag.ts","../src/create-app.ts","../src/fallback-camera.ts","../src/game-context.ts","../src/load-game-errors.ts","../src/load-game.ts","../src/internal/browser-rhi-debug-runtime.ts","../src/tool-preview/recipe.ts","../src/tool-preview/bootstrap.ts","../src/tool-preview/evidence.ts","../src/tool-preview/framing.ts"],"names":["isRecord","Update","err","performance","ok","attachBrowserInputBackend","RhiError","makeAppError","Camera","attachRecorder"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,SAASA,UAAS,KAAA,EAAkD;AAClE,EAAA,OAAO,KAAA,KAAU,IAAA,IAAQ,OAAO,KAAA,KAAU,QAAA;AAC5C;AAEO,SAAS,uBAAuB,KAAA,EAAiC;AACtE,EAAA,IAAI,CAACA,SAAAA,CAAS,KAAK,CAAA,SAAU,EAAC;AAC9B,EAAA,MAAM,YAAqC,EAAC;AAC5C,EAAA,KAAA,MAAW,UAAU,kBAAA,EAAoB;AACvC,IAAA,IAAI,UAAU,KAAA,EAAO,SAAA,CAAU,MAAM,CAAA,GAAI,MAAM,MAAM,CAAA;AAAA,EACvD;AACA,EAAA,OAAO,SAAA;AACT;AAEO,SAAS,sBACd,YAAA,EACyC;AACzC,EAAA,OAAO,OAAO,SAAA,KAAwC;AACpD,IAAA,MAAM,WAAA,GAAc,MAAM,YAAA,CAAa,SAAS,CAAA;AAChD,IAAA,OAAO,SAAA,KAAc,oBAAA,GAAuB,sBAAA,CAAuB,WAAW,CAAA,GAAI,WAAA;AAAA,EACpF,CAAA;AACF;AAxCA,IAMM,oBAAA,EAEO,kBAAA;AARb,IAAA,eAAA,GAAA,KAAA,CAAA;AAAA,EAAA,4BAAA,GAAA;AAMA,IAAM,oBAAA,GAAuB,qBAAA;AAEtB,IAAM,kBAAA,GAAqB,OA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W,CAAA;AAAA,IACrD,GAAA,EAAK,WAAW,MAAA,GAAS;AAAA,GAC3B;AACF","file":"index.mjs","sourcesContent":["// @forgeax/engine-app/internal/ecs-import — host-owned capability projection.\n//\n// The remote transport deliberately has no engine-package vocabulary. Hosts\n// that expose ECS to eval inject this narrow projection at the transport seam,\n// keeping the ECS wire surface and its dependency ownership in one place.\n\nconst ECS_MODULE_SPECIFIER = '@forgeax/engine-ecs';\n\nexport const ECS_PUBLIC_SYMBOLS = Object.freeze([\n 'World',\n 'Entity',\n 'Update',\n 'FixedUpdate',\n 'Time',\n 'FixedTime',\n] as const);\n\nexport type EcsPublicSymbol = (typeof ECS_PUBLIC_SYMBOLS)[number];\nexport type EcsPublicModule = Readonly<Partial<Record<EcsPublicSymbol, unknown>>>;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object';\n}\n\nexport function projectEcsPublicModule(value: unknown): EcsPublicModule {\n if (!isRecord(value)) return {};\n const projected: Record<string, unknown> = {};\n for (const symbol of ECS_PUBLIC_SYMBOLS) {\n if (symbol in value) projected[symbol] = value[symbol];\n }\n return projected;\n}\n\nexport function createEcsImportModule(\n importModule: (specifier: string) => Promise<unknown>,\n): (specifier: string) => Promise<unknown> {\n return async (specifier: string): Promise<unknown> => {\n const moduleValue = await importModule(specifier);\n return specifier === ECS_MODULE_SPECIFIER ? projectEcsPublicModule(moduleValue) : moduleValue;\n };\n}\n","// @forgeax/engine-app/internal/browser-remote-bridge — DEV-only page-side bridge\n// that makes a live BROWSER engine drivable over a loopback relay.\n//\n// WHY: @forgeax/engine-remote's only external transport is a Node WebSocket\n// server (packages/remote/src/server.ts). A browser page cannot bind a listening\n// socket, so createApp's startServer attempt throws on ws's browser shim and\n// app.remote stays undefined — the running engine is unreachable in a real\n// `pnpm --filter <app> dev` browser. But a page CAN dial OUT. So we open a\n// WebSocket CLIENT to the loopback relay\n// (skills/forgeax-engine-cli/scripts/remote-bridge-server.mjs) and run\n// @forgeax/engine-remote/execute (the ws-free eval core) in the page realm\n// against the live world/renderer/assets/rhiCapture. A CLI POSTs to the relay;\n// the relay forwards to us; we eval and reply. This is the engine-side mirror of\n// the editor's ViewportComponent DEV bridge.\n//\n// This module is reached only via a DEV-gated dynamic import from create-app.ts,\n// so production (import.meta.env.DEV === false) never bundles it (tree-shake /\n// zero-injection). It carries NO static top-level @forgeax/engine-remote\n// dependency — the eval core is pulled by a further dynamic import, keeping\n// @forgeax/engine-app free of a runtime dep on @forgeax/engine-remote (same\n// discipline as the createApp startServer path). The import is deliberately\n// left visible to Vite: the SDK host aliases the focused package to its exact\n// installed path, while @vite-ignore would make a browser resolve the bare\n// specifier from the consumer document root and yield a 500.\n\nimport { Update, type World } from '@forgeax/engine-ecs';\nimport { createEcsImportModule } from './ecs-import';\n\ntype ExecuteResult = { ok: true; value: unknown } | { ok: false; error: unknown };\n\ntype ExecuteModule = {\n executeScript: (\n script: string,\n ctx: {\n world: unknown;\n renderer: unknown;\n assets: unknown;\n rhiCapture?: unknown;\n profiler?: unknown;\n execution?: unknown;\n importModule?: (specifier: string) => Promise<unknown>;\n },\n ) => Promise<ExecuteResult>;\n};\n\ntype ComponentLike = { readonly name: string };\n\n/**\n * Project component exports onto the tokens already stored by this World.\n *\n * WHY: Vite may evaluate a workspace package once through the host package's\n * dist graph and once through a source graph. Component ids are process-local,\n * so equal `{ name, schema }` objects are not interchangeable with World\n * access. The bridge is the one place that can reconcile the public module\n * recipe with the live World's archetype SSOT.\n */\nfunction canonicalRuntimeModule(moduleValue: unknown, world: World): unknown {\n if (moduleValue === null || typeof moduleValue !== 'object') return moduleValue;\n const componentsByName = new Map<string, ComponentLike>();\n for (const [name, component] of world.components.entries()) {\n if (!componentsByName.has(name)) componentsByName.set(name, component);\n }\n const projected: Record<string, unknown> = { ...(moduleValue as Record<string, unknown>) };\n for (const [key, value] of Object.entries(projected)) {\n if (value === null || typeof value !== 'object' || !('name' in value)) continue;\n const canonical = componentsByName.get((value as ComponentLike).name);\n if (canonical !== undefined) projected[key] = canonical;\n }\n return projected;\n}\n\nexport interface BrowserRemoteBridgeDeps {\n readonly world: World;\n readonly renderer: unknown;\n readonly assets: unknown;\n /** The host's already-loaded runtime namespace; preserves component-token identity. */\n readonly runtimeModule: unknown;\n readonly rhiCapture?: unknown;\n /** The host's explicit CPU profiler capability, when opted in. */\n readonly profiler?: unknown;\n readonly execution?: unknown;\n /** Relay port. */\n readonly port: string;\n}\n\n/** Serialize a RemoteError-shaped object (or any thrown value) into a JSON-safe\n * {code, expected, hint, detail?} envelope. AI users branch on error.code by\n * property access, so the four structured fields must survive the wire. */\nfunction serializeError(error: unknown): Record<string, unknown> {\n if (error !== null && typeof error === 'object') {\n const e = error as {\n code?: unknown;\n expected?: unknown;\n hint?: unknown;\n detail?: unknown;\n message?: unknown;\n };\n const out: Record<string, unknown> = {\n code: typeof e.code === 'string' ? e.code : 'script-runtime-error',\n };\n if (typeof e.expected === 'string') out.expected = e.expected;\n if (typeof e.hint === 'string') out.hint = e.hint;\n if (e.detail !== undefined) out.detail = e.detail;\n if (out.hint === undefined && typeof e.message === 'string') out.hint = e.message;\n return out;\n }\n return { code: 'script-runtime-error', hint: String(error) };\n}\n\n/**\n * Install the DEV-only browser remote bridge. Idempotent per call site; the\n * caller gates on import.meta.env.DEV so this never runs in production.\n *\n * Returns a teardown function that stops reconnection and closes the socket —\n * the caller wires it to import.meta.hot.dispose so a vite HMR of the host app\n * does not stack duplicate bridges.\n */\nexport async function installBrowserRemoteBridge(\n deps: BrowserRemoteBridgeDeps,\n): Promise<() => void> {\n const { world, renderer, assets, rhiCapture, profiler, execution, port } = deps;\n\n // The ws-free eval core. Dynamic import keeps @forgeax/engine-app free of a\n // static @forgeax/engine-remote dependency while allowing the consumer's\n // Vite config to resolve the focused package through its SDK alias.\n const mod = (await import('@forgeax/engine-remote/execute')) as ExecuteModule;\n const executeScript = mod.executeScript;\n const importModule = createEcsImportModule((specifier: string): Promise<unknown> => {\n // The host app and the bridge must share the same component-token objects.\n // Vite can otherwise serve `/@id/@forgeax/engine-runtime` as a second\n // module graph entry, so `world.get(entity, Transform)` sees a different\n // Component id even though the token has the same name and schema.\n if (specifier === '@forgeax/engine-runtime')\n return Promise.resolve(canonicalRuntimeModule(deps.runtimeModule, world));\n const browserSpecifier = specifier.startsWith('@') ? `/@id/${specifier}` : specifier;\n return import(/* @vite-ignore */ browserSpecifier).then((moduleValue) =>\n canonicalRuntimeModule(moduleValue, world),\n );\n });\n\n let ws: WebSocket | null = null;\n let backoff = 1000;\n let stopped = false;\n\n // Frame-start eval queue: a WebSocket `message` fires at an arbitrary phase of\n // the rAF tick, so running eval inline would land world writes at an\n // unpredictable phase. Enqueue instead and drain from Update system (frame\n // start) so every bridge write passes through this frame's systems.\n const evalQueue: Array<{ id: number; code: string }> = [];\n\n const drainEvalQueue = (): void => {\n if (evalQueue.length === 0) return;\n // Snapshot + clear so an eval that enqueues runs next frame, not in an\n // unbounded same-frame loop.\n const jobs = evalQueue.splice(0, evalQueue.length);\n for (const job of jobs) {\n const reply = (payload: unknown): void => {\n // Reply on the CURRENT socket (it may have reconnected since enqueue).\n // The relay keys replies by request id, so the live socket resolves it.\n try {\n ws?.send(JSON.stringify({ type: 'result', id: job.id, payload }));\n } catch {\n /* socket gone; relay times the request out */\n }\n };\n void (async () => {\n let res: ExecuteResult;\n try {\n res = await executeScript(job.code, {\n world,\n renderer,\n assets,\n rhiCapture,\n profiler: profiler,\n execution,\n importModule,\n });\n } catch (e) {\n reply({\n ok: false,\n error: { code: 'BRIDGE_EVAL_THREW', hint: String((e as Error)?.message ?? e) },\n });\n return;\n }\n const envelope = res.ok\n ? { ok: true as const, value: res.value }\n : { ok: false as const, error: serializeError(res.error) };\n // JSON-guard: non-serializable values (opaque engine handles, cycles)\n // degrade to a marker so one bad field never wedges the channel.\n try {\n JSON.stringify(envelope);\n reply(envelope);\n } catch {\n reply({ ok: true, value: '[unserializable value — inspect in the live window]' });\n }\n })();\n }\n };\n world\n .addSystem(Update, {\n name: 'browser-remote-bridge-drain-eval-queue',\n queries: [],\n fn: drainEvalQueue,\n })\n .unwrap();\n\n const connect = (): void => {\n if (stopped) return;\n try {\n ws = new WebSocket(`ws://127.0.0.1:${port}/bridge`);\n } catch {\n return;\n }\n ws.addEventListener('open', () => {\n backoff = 1000;\n });\n ws.addEventListener('message', (ev: MessageEvent) => {\n let msg: { type?: string; id?: number; code?: string };\n try {\n msg = JSON.parse(typeof ev.data === 'string' ? ev.data : '');\n } catch {\n return;\n }\n if (msg?.type !== 'eval' || typeof msg.id !== 'number' || typeof msg.code !== 'string')\n return;\n evalQueue.push({ id: msg.id, code: msg.code });\n });\n const retry = (): void => {\n ws = null;\n if (stopped) return;\n setTimeout(connect, backoff);\n backoff = Math.min(backoff * 2, 15000);\n };\n ws.addEventListener('close', retry);\n ws.addEventListener('error', () => {\n try {\n ws?.close();\n } catch {\n /* */\n }\n });\n };\n connect();\n\n const teardown = (): void => {\n if (stopped) return;\n stopped = true;\n world.removeSystem(Update, 'browser-remote-bridge-drain-eval-queue');\n const s = ws;\n ws = null;\n if (s) {\n try {\n s.onclose = null;\n s.close();\n } catch {\n /* */\n }\n }\n };\n\n // Self-register HMR teardown so a vite HMR of the host app does not stack\n // duplicate bridges. Kept here (not in create-app.ts) so create-app.ts carries\n // no import.meta.hot reference — the rhi-debug guard gate requires every\n // import.meta.hot there to sit inside the FORGEAX_ENGINE_RHI_DEBUG block.\n const hot = (import.meta as { hot?: { dispose(cb: () => void): void } }).hot;\n if (hot) hot.dispose(teardown);\n\n return teardown;\n}\n","/**\n * Browser-visible render progress owned by the App frame loop.\n *\n * The Renderer already emits `frame-submitted` after its sole queue-submit\n * boundary. This adapter projects that event onto the document without\n * exposing a renderer handle or creating a second readiness registry. DevKit\n * capture waits on the same projection, then verifies compositor pixels.\n */\n\nexport const FORGEAX_FRAME_SUBMITTED_DATASET = 'forgeaxFrameSubmitted';\nexport const FORGEAX_FRAME_SUBMITTED_EVENT = 'forgeax:frame-submitted';\n\nexport interface BrowserFrameSubmitted {\n readonly frameId: number;\n readonly deviceGeneration: number;\n}\n\nexport function resetBrowserFrameSubmitted(canvas: HTMLCanvasElement): void {\n const documentElement = canvas.ownerDocument?.documentElement;\n if (documentElement !== undefined) {\n delete documentElement.dataset[FORGEAX_FRAME_SUBMITTED_DATASET];\n }\n}\n\nexport function publishBrowserFrameSubmitted(\n canvas: HTMLCanvasElement,\n event: BrowserFrameSubmitted,\n): void {\n const documentElement = canvas.ownerDocument?.documentElement;\n if (documentElement !== undefined) {\n documentElement.dataset[FORGEAX_FRAME_SUBMITTED_DATASET] = String(event.frameId);\n }\n // Dawn-node smoke canvases intentionally expose only the drawing-buffer\n // surface; they are not DOM EventTargets. Keep the document projection\n // above useful for those hosts, while dispatching the browser event only\n // when the host actually provides the optional EventTarget capability.\n if (typeof CustomEvent === 'function' && typeof canvas.dispatchEvent === 'function') {\n canvas.dispatchEvent(\n new CustomEvent(FORGEAX_FRAME_SUBMITTED_EVENT, {\n detail: Object.freeze({ ...event }),\n }),\n );\n }\n}\n","import type { AnimationPayloadLookup } from '@forgeax/engine-animation';\nimport type { AnimationClip } from '@forgeax/engine-types';\n\nexport interface AnimationPayloadSource {\n lookup<T = unknown>(guid: string): T | undefined;\n}\n\n/** Bridge the renderer-owned GUID catalogue into the animation plugin. */\nexport function createAnimationPayloadLookup(\n source: AnimationPayloadSource | undefined,\n): AnimationPayloadLookup {\n return (guid) => source?.lookup<AnimationClip>(guid);\n}\n","// @forgeax/engine-app -- AppError + closed AppErrorCode union (12 members) +\n// APP_ERROR_HINTS / APP_EXPECTED + discriminated AppErrorDetail per code.\n//\n// Shape:\n// - AppErrorCode = closed union 12 members (charter P4 closed-union\n// exhaustive switch needs no default fallback; tsc strict mode guards\n// completeness; AGENTS.md \"Errors are structured\" + AC-07).\n// Members:\n// - 'app-not-started'\n// - 'app-already-running'\n// - 'app-canvas-detached'\n// - 'app-system-update-failed'\n// - 'app-pointer-lock-failed'\n// Plan-strategy D-3 lock: device-lost stays on RhiErrorCode (18-member\n// union); the AppError surface does NOT add a seventh 'app-device-lost'\n// member. Host onError listener receives RhiError({code:'device-lost'})\n// verbatim through the fan-out.\n//\n// - AppError class = 4-field surface (.code / .expected / .hint /\n// .detail) byte-for-byte parallel to RhiError (packages/rhi/src/errors.ts).\n// The class extends Error so debug surfaces (stack, name) work in host\n// environments; AI users walk .code / .detail by property access (charter\n// P3 explicit failure: never parse the message string).\n//\n// - AppError is exposed as a discriminated union (variant per code) so AI\n// users get .detail narrowing for free after `if (err.code === '...')`:\n//\n// if (err.code === 'app-canvas-detached') {\n// console.warn('reattach canvas', err.detail.canvasId);\n// }\n//\n// Constructor accepts a generic args object and infers the variant from\n// the literal `code` argument; `detail` must satisfy the per-code\n// payload (`AppErrorDetailFor<C>`). Callers therefore cannot supply\n// non-canonical fields like `{ state: 'running' }` on the\n// 'app-already-running' arm.\n//\n// - APP_ERROR_HINTS / APP_EXPECTED are 12-key Records keyed by AppErrorCode;\n// one private policy owner supplies both projections. The focused policy-owner\n// proof asserts that every code has the exact expected and hint strings.\n//\n// Related: requirements AC-07 / AC-04 / AC-09; plan-strategy section 2 D-3\n// (6-member lock) + D-4 ('app-system-update-failed' detail = { cause,\n// systemName? }) + D-6 (dual-layer instanceof + switch consumption form);\n// research section 2.7 (AppErrorCode lands in AGENTS.md Error model table\n// alongside RhiErrorCode et al.); charter P3 (explicit failure) + P4\n// (closed-union exhaustive switch).\n\nimport type { RhiError } from '@forgeax/engine-rhi/errors';\nimport type { ExecutionCapabilityName, ExecutionTier } from './execution/types';\n\n/**\n * Closed AppErrorCode union (12 members).\n *\n * | code | trigger |\n * |:--|:--|\n * | `'app-not-started'` | `stop()` / `pause()` / `resume()` invoked while the rAF loop is in the terminal `'idle'` or `'stopped'` state (post-device-lost terminal sink). The handle has no live frame to interrupt; AI users either call `start()` first or accept that this handle is dead and rebuild via `createApp({...})`. |\n * | `'app-already-running'` | second `start()` invocation against an already-running handle; the call is a no-op state-machine-wise (state preserved). |\n * | `'app-canvas-detached'` | `createApp(canvas)` thin wrapper found `canvas.isConnected === false` at entry. Detail carries optional `canvasId` so the host can surface the offending canvas in a multi-canvas page (D-2 minor). |\n * | `'app-system-update-failed'` | World update, renderer draw, or a frame-loop callback failed; the original failure value is forwarded on `detail.cause`. `detail.systemName` is optional when the call site can name the failing owner. |\n * | `'app-pointer-lock-failed'` | `attachInputAuto`'s `onLockError` callback received a lock failure from the input backend. `detail.path` carries `'w3c'` (W3C `requestPointerLock` rejection) or `'provider'` (host-injected `lockProvider.requestLock` throw/reject). `detail.cause` carries the original rejection value verbatim. The host recovers by remaining in unlocked state; the next trusted click will retry the lock request. |\n *\n * Plan-strategy D-4 locked the count at 6; device-lost rides RhiErrorCode.\n */\nexport type AppErrorCode = keyof typeof appErrorPolicy;\n\n/**\n * Detail variant for the `'app-canvas-detached'` arm.\n *\n * `canvasId` carries an optional identifier the host can surface to AI\n * users when multiple canvases live on the page (e.g. preview vs live\n * canvas). `undefined` when the host did not assign an id.\n */\nexport interface AppDetailCanvasDetached {\n readonly canvasId?: string | undefined;\n}\n\n/**\n * Detail variant for the `'app-system-update-failed'` arm (plan-strategy D-4).\n *\n * `cause` carries the original thrown value verbatim so AI users can\n * `cause instanceof EcsError` / `cause instanceof RhiError` narrow without\n * losing structure. `systemName` is populated when the call site can name\n * the offending system (input-attach cleanup path forwards\n * `FRAME_START_SCAN_SYSTEM_NAME`).\n */\nexport interface AppDetailSystemUpdateFailed {\n readonly cause: unknown;\n readonly systemName?: string | undefined;\n}\n\n/**\n * Detail variant for the `'app-pointer-lock-failed'` arm (plan-strategy D-4).\n *\n * `path` discriminates between W3C `requestPointerLock` rejections (`'w3c'`)\n * and host-injected `lockProvider.requestLock` throw/reject (`'provider'`).\n * `cause` carries the original rejection value verbatim so AI users can\n * narrow further (e.g. `cause instanceof DOMException` for W3C timeout\n * rejections).\n */\nexport interface AppDetailPointerLockFailed {\n readonly path: 'w3c' | 'provider';\n readonly cause: unknown;\n}\n\n/** Why a host-requested deterministic frame could not run. */\nexport interface AppDetailFrameStepInvalid {\n readonly state: 'idle' | 'running' | 'paused' | 'stopped';\n readonly deltaSeconds: number;\n readonly reason: 'state' | 'delta';\n}\n\nexport interface AppDetailExecutionTierUnavailable {\n readonly requestedTier: ExecutionTier;\n readonly missingCapabilities: readonly ExecutionCapabilityName[];\n readonly sharedEvidencePassed: boolean;\n}\n\nexport interface AppDetailExecutionBootstrapFailed {\n readonly phase: 'import' | 'export' | 'prepare' | 'bootstrap' | 'data';\n readonly moduleUrl: string;\n readonly cause: unknown;\n}\n\n/** Original startup failure thrown by a Cordis plugin fiber. */\nexport interface AppDetailPluginActivationFailed {\n readonly cause: unknown;\n}\n\nexport interface AppDetailExecutionDeadlineExceeded {\n readonly phase: 'startup' | 'handshake' | 'frame';\n readonly timeoutMs: number;\n}\n\nexport interface AppDetailExecutionKernelFailed {\n readonly kernelName: string;\n readonly worldIdentity: string;\n readonly cause: unknown;\n readonly partialWrite: true;\n readonly retryable: false;\n}\n\nexport interface AppDetailExecutionStaleWorld {\n readonly expectedIdentity: string;\n readonly receivedIdentity: string;\n readonly messageKind: string;\n}\n\nexport interface AppDetailExecutionRebuildFailed {\n readonly worldIdentity: string | null;\n readonly cause: unknown;\n}\n\n/**\n * Empty-detail shape for the 2 codes that carry no payload\n * (`'app-not-started'`, `'app-already-running'`).\n *\n * Modelled as `Readonly<Record<string, never>>` so literal builders use\n * `{}` while still narrowing under tsc strict (no extra property allowed).\n */\nexport type AppDetailEmpty = Readonly<Record<string, never>>;\n\n/**\n * Conditional resolver from `AppErrorCode` to its detail payload type.\n *\n * Used by the constructor signature so `new AppError({ code: 'X', ... })`\n * narrows the `detail` parameter to the variant payload at compile time.\n */\nexport type AppErrorDetailFor<C extends AppErrorCode> = C extends 'app-canvas-detached'\n ? AppDetailCanvasDetached\n : C extends 'app-frame-step-invalid'\n ? AppDetailFrameStepInvalid\n : C extends 'app-system-update-failed'\n ? AppDetailSystemUpdateFailed\n : C extends 'app-pointer-lock-failed'\n ? AppDetailPointerLockFailed\n : C extends 'app-plugin-activation-failed'\n ? AppDetailPluginActivationFailed\n : C extends 'app-execution-tier-unavailable'\n ? AppDetailExecutionTierUnavailable\n : C extends 'app-execution-bootstrap-failed'\n ? AppDetailExecutionBootstrapFailed\n : C extends 'app-execution-deadline-exceeded'\n ? AppDetailExecutionDeadlineExceeded\n : C extends 'app-execution-kernel-failed'\n ? AppDetailExecutionKernelFailed\n : C extends 'app-execution-stale-world'\n ? AppDetailExecutionStaleWorld\n : C extends 'app-execution-rebuild-failed'\n ? AppDetailExecutionRebuildFailed\n : AppDetailEmpty;\n\n/**\n * Tagged union of `.detail` payloads carried by structured AppError.\n *\n * Each variant maps to its `AppErrorCode` arm via `AppErrorDetailFor<C>`;\n * the variants are unique by structural fields (`AppDetailCanvasDetached`\n * has `canvasId`, `AppDetailSystemUpdateFailed` has `cause`, the empty\n * shape has neither).\n */\nexport type AppErrorDetail = AppErrorDetailFor<AppErrorCode>;\n\n/**\n * Render a one-line summary of `detail.cause` for embedding in\n * `AppError.message`. `cause` is structurally typed (`unknown`) because\n * upstream may throw any value; callers downstream still get the verbatim\n * value via `err.detail.cause` — this helper exists so tools that only see\n * `err.message` (`console.error(err)`, raw stringification) still surface\n * the root cause without consumers manually expanding `detail`.\n *\n * Closed precedence:\n * 1. Structured engine errors (RhiError / EcsError / RenderGraphError /\n * AssetError / ShaderError / ...) carry `.code` + `.message`; render\n * `<Name> <code>: <message>`.\n * 2. Plain `Error`: render `<name>: <message>`.\n * 3. Anything else: `String(cause)` (covers thrown strings, numbers, null).\n *\n * Newlines are replaced with `' / '` so the final AppError message stays a\n * single line (callers already split on `\\n` in stack traces, so a multiline\n * message would corrupt their parsing).\n */\nfunction summarizeCause(cause: unknown): string {\n if (cause === null || cause === undefined) return String(cause);\n if (typeof cause !== 'object') return String(cause);\n const r = cause as { name?: unknown; message?: unknown; code?: unknown };\n const name = typeof r.name === 'string' && r.name.length > 0 ? r.name : 'Error';\n const code = typeof r.code === 'string' && r.code.length > 0 ? r.code : '';\n const message = typeof r.message === 'string' ? r.message : '';\n const head = code !== '' ? `${name} ${code}` : name;\n const body = message !== '' ? `: ${message}` : '';\n return `${head}${body}`.replace(/\\s*\\n+\\s*/g, ' / ');\n}\n\nclass AppErrorClass extends Error {\n readonly code: AppErrorCode;\n readonly expected: string;\n readonly hint: string;\n readonly detail: AppErrorDetail;\n\n constructor(args: {\n code: AppErrorCode;\n expected: string;\n hint: string;\n detail: AppErrorDetail;\n }) {\n // Surface `detail.cause` directly inside `.message` for the\n // `'app-system-update-failed'` arm. Without this, a generic\n // `console.error(err)` shows only the wrapper expected/hint and\n // hides the actual EcsError / RhiError / host-system Error that\n // tripped the frame loop. The verbatim `cause` value remains on\n // `err.detail.cause` for two-level-narrow consumers (charter P3).\n let causeSuffix = '';\n if (args.code === 'app-system-update-failed') {\n const d = args.detail as AppDetailSystemUpdateFailed;\n const sys =\n typeof d.systemName === 'string' && d.systemName.length > 0\n ? ` (system=${d.systemName})`\n : '';\n causeSuffix = `; cause: ${summarizeCause(d.cause)}${sys}`;\n } else if (args.code === 'app-pointer-lock-failed') {\n const d = args.detail as AppDetailPointerLockFailed;\n causeSuffix = `; path: ${d.path}; cause: ${summarizeCause(d.cause)}`;\n } else if (args.code === 'app-plugin-activation-failed') {\n const d = args.detail as AppDetailPluginActivationFailed;\n causeSuffix = `; cause: ${summarizeCause(d.cause)}`;\n } else if (args.code === 'app-execution-bootstrap-failed') {\n const d = args.detail as AppDetailExecutionBootstrapFailed;\n causeSuffix = `; phase: ${d.phase}; cause: ${summarizeCause(d.cause)}`;\n } else if (args.code === 'app-execution-kernel-failed') {\n const d = args.detail as AppDetailExecutionKernelFailed;\n causeSuffix = `; kernel: ${d.kernelName}; cause: ${summarizeCause(d.cause)}`;\n } else if (args.code === 'app-execution-rebuild-failed') {\n const d = args.detail as AppDetailExecutionRebuildFailed;\n causeSuffix = `; cause: ${summarizeCause(d.cause)}`;\n }\n super(`[AppError ${args.code}] expected: ${args.expected}; hint: ${args.hint}${causeSuffix}`);\n this.name = 'AppError';\n this.code = args.code;\n this.expected = args.expected;\n this.hint = args.hint;\n this.detail = args.detail;\n }\n}\n\n/**\n * Variant intersection: an `AppErrorClass` instance whose `code` literal\n * narrows to `C` and whose `detail` narrows to `AppErrorDetailFor<C>`. The\n * shape lets `if (err.code === 'X')` simultaneously narrow `err.detail` to\n * the per-code payload (charter P3 + AC-07 discriminated union).\n */\ntype AppErrorVariant<C extends AppErrorCode> = AppErrorClass & {\n readonly code: C;\n readonly detail: AppErrorDetailFor<C>;\n};\n\n/**\n * Public AppError type — discriminated union of the policy variants.\n *\n * AI-user form (charter P3 explicit failure):\n *\n * ```ts\n * function recover(err: AppError): string {\n * switch (err.code) {\n * case 'app-not-started': return 'call start() first';\n * case 'app-already-running': return 'state preserved; ignore';\n * case 'app-canvas-detached': return `reattach ${err.detail.canvasId ?? 'canvas'}`;\n * case 'app-system-update-failed':\n * return err.detail.cause instanceof Error ? err.detail.cause.message : 'unknown';\n * case 'app-pointer-lock-failed':\n * return `lock failed (${err.detail.path}): ${err.detail.cause}`;\n * }\n * }\n * ```\n */\nexport type AppError = {\n [C in AppErrorCode]: AppErrorVariant<C>;\n}[AppErrorCode];\n\ninterface AppErrorConstructor {\n new <C extends AppErrorCode>(args: {\n code: C;\n expected: string;\n hint: string;\n detail: AppErrorDetailFor<C>;\n }): AppErrorVariant<C>;\n readonly prototype: AppErrorClass;\n}\n\n/**\n * AppError constructor — `new AppError({ code, expected, hint, detail })`.\n *\n * The generic `C` is inferred from the literal `code` argument, which\n * narrows `detail` to the per-code payload (`AppErrorDetailFor<C>`) and\n * narrows the return type to the corresponding `AppErrorVariant<C>` so the\n * call site walks the discriminated union without manual cast.\n *\n * The constructor delegates to the `AppErrorClass` runtime; the typed-cast\n * here is the ergonomic affordance for AI users (TS class declarations\n * cannot directly express `<C> ... AppErrorVariant<C>` polymorphism).\n */\nexport const AppError: AppErrorConstructor = AppErrorClass as unknown as AppErrorConstructor;\n\n/**\n * `expected` table — the engine-side invariant that was violated when each\n * code surfaces. AI users read this as the L2 detail (charter F2 priority\n * text); `.hint` carries the recovery action.\n *\n * 12 keys; the focused policy-owner proof locks the exact key set and values.\n * locks the count and non-emptiness of every entry.\n */\ntype AppErrorPolicy = { readonly expected: string; readonly hint: string };\n\nconst appErrorPolicy = {\n 'app-not-started': {\n expected:\n 'state must be \"running\" or \"paused\" to accept stop/pause/resume; \"idle\" / \"stopped\" terminal sinks reject',\n hint: 'check getState() before calling stop/pause/resume; rebuild the handle via createApp({...}) when the previous one terminated on device-lost',\n },\n 'app-already-running': {\n expected:\n 'state must be \"idle\" or \"paused\" to start; \"running\" handles ignore subsequent start() calls',\n hint: 'call stop() first or audit start() call sites; the second start() is a no-op so state is preserved',\n },\n 'app-canvas-detached': {\n expected: 'canvas.isConnected === true at createApp(canvas) entry',\n hint: 'append the canvas to the document tree before calling createApp(canvas), or use the assemble entry createApp({ renderer, world }) when the host already manages canvas lifetime',\n },\n 'app-frame-step-invalid': {\n expected:\n 'stepFrame(deltaSeconds) runs only while the App is paused and deltaSeconds is finite and non-negative',\n hint: 'pause the App before deterministic stepping and pass an explicit finite delta; resume after the bounded step sequence completes',\n },\n 'app-system-update-failed': {\n expected:\n 'world.update(world), renderer.draw(world), and frame-loop callbacks complete without failure',\n hint: 'inspect detail.cause for the original thrown value (EcsError / RhiError / host system bug); detail.systemName names the offending system when the call site can supply it',\n },\n 'app-pointer-lock-failed': {\n expected:\n 'pointer-lock request (W3C requestPointerLock or host lockProvider.requestLock) to succeed; failure signals the browser rejected the lock or the host provider threw',\n hint: 'remain in unlocked state; the next trusted click will automatically retry the lock request. inspect detail.path (\"w3c\" or \"provider\") and detail.cause to determine the root cause',\n },\n 'app-plugin-activation-failed': {\n expected: 'every requested Cordis plugin fiber reaches a stable active or pending state',\n hint: 'inspect detail.cause and the plugin fiber effects; repair the failing activation before creating the App again',\n },\n 'app-execution-tier-unavailable': {\n expected:\n 'the explicitly requested execution tier has every required observed capability and the shipped shared evidence gate',\n hint: 'inspect detail.missingCapabilities and detail.sharedEvidencePassed; use tier=\"auto\" only when an observed fallback is acceptable',\n },\n 'app-execution-bootstrap-failed': {\n expected:\n 'the bootstrap URL imports a module whose default export completes as an ExecutionBootstrapEntry in the selected Engine Realm',\n hint: 'inspect detail.phase, moduleUrl and cause; export one default ExecutionBootstrapEntry that creates only realm-local engine state',\n },\n 'app-execution-deadline-exceeded': {\n expected:\n 'the execution startup, handshake or frame completes within its configured bounded deadline',\n hint: 'inspect detail.phase and timeoutMs; the timed-out Worker has been terminated, so fix startup or frame work before creating a new App',\n },\n 'app-execution-kernel-failed': {\n expected:\n 'a shared kernel completes every dispatched shard without leaving a possibly partial World write',\n hint: 'do not retry or draw the poisoned World; inspect detail.kernelName and cause, then call app.execution.rebuild()',\n },\n 'app-execution-stale-world': {\n expected:\n 'every execution message targets the currently active World identity before it can write',\n hint: 'discard the late message and keep the current World; inspect expectedIdentity, receivedIdentity and messageKind',\n },\n 'app-execution-rebuild-failed': {\n expected:\n 'explicit rebuild disposes the poisoned World and bootstraps a fresh World identity in the surviving Engine Realm',\n hint: 'inspect detail.cause; this App remains stopped, so fix the bootstrap failure or create a new App explicitly',\n },\n} satisfies Record<string, AppErrorPolicy>;\n\nexport const APP_EXPECTED: Readonly<Record<AppErrorCode, string>> = Object.fromEntries(\n Object.entries(appErrorPolicy).map(([code, policy]) => [code, policy.expected]),\n) as Readonly<Record<AppErrorCode, string>>;\n\nexport const APP_ERROR_HINTS: Readonly<Record<AppErrorCode, string>> = Object.fromEntries(\n Object.entries(appErrorPolicy).map(([code, policy]) => [code, policy.hint]),\n) as Readonly<Record<AppErrorCode, string>>;\n\n/**\n * Type guard for narrowing `CanvasAppError`-compatible mixed signals to AppError.\n *\n * The fan-out signature is `(err: CanvasAppError) => void`; AI users\n * who want to handle only the AppError leg call `if (isAppError(err)) ...`\n * before walking `.code`. Reverse-compatible with `instanceof AppError`\n * (the class is exposed); the function form is provided as the\n * canonical idiom in JSDoc / README so AI users do not need to reason\n * about cross-realm `instanceof` quirks.\n *\n * The parameter accepts the complete App/RHI boundary union so callers can\n * narrow the error without casts.\n */\nexport function isAppError(err: AppError | RhiError): err is AppError {\n return err instanceof AppErrorClass;\n}\n","import type { Plugin } from '@forgeax/engine-plugin';\nimport type { RenderFeature } from '@forgeax/engine-render';\nimport { err, ok, type Result } from '@forgeax/engine-types';\nimport { APP_ERROR_HINTS, APP_EXPECTED, AppError, type AppError as AppErrorType } from '../errors';\nimport type { ExecutionBootstrapValue } from './types';\n\n/** Realm-local engine assembly returned by an execution bootstrap module. */\nexport interface PreparedExecutionBootstrap {\n /** Render features constructed in the realm that will own the Renderer. */\n readonly features?: readonly RenderFeature<unknown>[];\n /** Plugins constructed in the realm that will own the World. */\n readonly plugins?: readonly Plugin[];\n}\n\n/** Realm-local Host bridge available to execution bootstrap plugins. */\nexport interface ExecutionBootstrapHost {\n readonly port?: MessagePort;\n setPointerLockAllowed(allowed: boolean): void;\n}\n\ndeclare module '@forgeax/engine-plugin' {\n interface EngineContextServices {\n executionBootstrapHost: ExecutionBootstrapHost;\n }\n}\n\n/** Bind the optional Host transport to the same Fiber that owns bootstrap plugins. */\nexport function executionBootstrapHostPlugin(host: ExecutionBootstrapHost): Plugin {\n return {\n name: 'execution-bootstrap-host',\n provide: 'executionBootstrapHost',\n apply(ctx) {\n ctx.provide('executionBootstrapHost', host);\n if (host.port !== undefined) {\n ctx.effect(() => () => host.port?.close(), 'execution/bootstrap-port');\n }\n },\n };\n}\n\n/** Default export contract for `ExecutionOptions.bootstrap`. */\nexport type ExecutionBootstrapEntry = (\n data: ExecutionBootstrapValue | undefined,\n) => PreparedExecutionBootstrap | Promise<PreparedExecutionBootstrap>;\n\nfunction bootstrapError(\n phase: 'import' | 'export' | 'prepare' | 'bootstrap' | 'data',\n moduleUrl: string,\n cause: unknown,\n): AppErrorType {\n return new AppError({\n code: 'app-execution-bootstrap-failed',\n expected: APP_EXPECTED['app-execution-bootstrap-failed'],\n hint: APP_ERROR_HINTS['app-execution-bootstrap-failed'],\n detail: { phase, moduleUrl, cause },\n });\n}\n\nexport function validateExecutionBootstrapData(\n data: ExecutionBootstrapValue | undefined,\n moduleUrl: string,\n): Result<void, AppErrorType> {\n if (data === undefined) return ok(undefined);\n try {\n structuredClone(data);\n return ok(undefined);\n } catch (cause) {\n return err(bootstrapError('data', moduleUrl, cause));\n }\n}\n\nexport async function loadBootstrapEntry(\n moduleUrl: string,\n): Promise<Result<ExecutionBootstrapEntry, AppErrorType>> {\n let loaded: unknown;\n try {\n loaded = await import(/* @vite-ignore */ moduleUrl);\n } catch (cause) {\n return err(bootstrapError('import', moduleUrl, cause));\n }\n const entry = (loaded as { default?: unknown }).default;\n if (typeof entry !== 'function') {\n return err(\n bootstrapError(\n 'export',\n moduleUrl,\n new TypeError('default export is not an ExecutionBootstrapEntry function'),\n ),\n );\n }\n return ok(entry as ExecutionBootstrapEntry);\n}\n\nexport async function prepareBootstrapEntry(\n moduleUrl: string,\n data: ExecutionBootstrapValue | undefined,\n): Promise<Result<PreparedExecutionBootstrap, AppErrorType>> {\n const valid = validateExecutionBootstrapData(data, moduleUrl);\n if (!valid.ok) return valid;\n const loaded = await loadBootstrapEntry(moduleUrl);\n if (!loaded.ok) return loaded;\n try {\n const prepared = await loaded.value(data);\n if (\n typeof prepared !== 'object' ||\n prepared === null ||\n (prepared.features !== undefined && !Array.isArray(prepared.features)) ||\n (prepared.plugins !== undefined && !Array.isArray(prepared.plugins))\n ) {\n return err(\n bootstrapError(\n 'prepare',\n moduleUrl,\n new TypeError('execution bootstrap must return an object with feature and plugin arrays'),\n ),\n );\n }\n return ok(prepared);\n } catch (cause) {\n return err(bootstrapError('prepare', moduleUrl, cause));\n }\n}\n","import type { WorldExecutionHealth } from '@forgeax/engine-ecs/shared';\nimport type { Result, RuntimeAssetBinding } from '@forgeax/engine-types';\nimport type { AppError } from '../errors';\n\nexport const EXECUTION_TIERS = ['main-serial', 'engine-worker', 'shared'] as const;\nexport type ExecutionTier = (typeof EXECUTION_TIERS)[number];\n\nexport const EXECUTION_REQUESTED_TIERS = ['auto', ...EXECUTION_TIERS] as const;\nexport type ExecutionRequestedTier = (typeof EXECUTION_REQUESTED_TIERS)[number];\n\nexport const EXECUTION_CAPABILITY_NAMES = [\n 'worker',\n 'offscreenCanvas',\n 'workerAnimationFrame',\n 'workerWebGpu',\n 'crossOriginIsolated',\n 'sharedArrayBuffer',\n 'atomicsWait',\n] as const;\nexport type ExecutionCapabilityName = (typeof EXECUTION_CAPABILITY_NAMES)[number];\n\nexport interface ExecutionCapabilityFact {\n readonly available: boolean;\n readonly reason: string;\n}\n\nexport type ExecutionCapabilities = Readonly<\n Record<ExecutionCapabilityName, ExecutionCapabilityFact>\n>;\n\nexport type ExecutionSelectionReason =\n | 'explicit-request'\n | 'auto-shared'\n | 'auto-engine-worker'\n | 'auto-main-serial';\n\nexport interface ExecutionSelection {\n readonly requestedTier: ExecutionRequestedTier;\n readonly actualTier: ExecutionTier;\n readonly selectionReason: ExecutionSelectionReason;\n readonly missingCapabilities: readonly ExecutionCapabilityName[];\n readonly sharedEvidencePassed: boolean;\n}\n\nexport type ExecutionEngineHealth = 'idle' | 'starting' | 'running' | 'stopped' | 'faulted';\nexport type ExecutionWorldHealth = WorldExecutionHealth;\n\nexport type KernelDispatchReason =\n | 'no-eligible-kernel'\n | 'zero-work'\n | 'small-span'\n | 'forced-inline'\n | 'shared'\n | 'poisoned';\n\nexport interface ExecutionMeasurement {\n readonly samples: number;\n readonly p50: number;\n readonly p95: number;\n readonly p99: number;\n readonly jitter: number;\n}\n\nexport interface ExecutionFault {\n readonly source: 'bootstrap' | 'handshake' | 'runtime' | 'kernel' | 'world' | 'rebuild';\n readonly code: string;\n readonly expected: string;\n readonly hint: string;\n readonly detail: unknown;\n readonly partialWrite: boolean;\n readonly retryable: boolean;\n}\n\nexport interface ExecutionAudioReport {\n readonly owner: 'host';\n readonly contextState: 'running' | 'suspended' | 'closed';\n readonly activeSourceCount: number;\n readonly lastError: {\n readonly code: string;\n readonly expected: string;\n readonly hint: string;\n readonly detail: unknown;\n } | null;\n}\n\n/**\n * Serializable asset-catalog configuration copied into the selected Engine\n * realm. The URL is resolved by that realm, so a Worker never closes over a\n * Host-side CatalogSource or Registry instance.\n */\nexport interface ExecutionAssetCatalog {\n readonly url: string;\n readonly expectedScope?: Pick<RuntimeAssetBinding, 'scopeId' | 'generation'>;\n}\n\nexport interface ExecutionReport {\n readonly schemaVersion: 1;\n readonly requestedTier: ExecutionRequestedTier;\n readonly actualTier: ExecutionTier | null;\n readonly selectionReason: ExecutionSelectionReason | null;\n readonly sharedEvidencePassed: boolean;\n readonly capabilities: ExecutionCapabilities;\n readonly engine: {\n readonly realm: 'host' | 'worker';\n readonly health: ExecutionEngineHealth;\n };\n readonly world: {\n readonly identity: string | null;\n readonly health: ExecutionWorldHealth;\n readonly partialWrite: boolean;\n readonly retryable: boolean;\n };\n readonly kernelDispatch: {\n readonly eligible: boolean;\n readonly usedShared: boolean;\n readonly reason: KernelDispatchReason;\n readonly dispatched: number;\n readonly completed: number;\n };\n readonly performance: {\n readonly hostFrameMs: ExecutionMeasurement | null;\n readonly engineUpdateMs: ExecutionMeasurement | null;\n readonly kernelWaitMs: ExecutionMeasurement | null;\n readonly hostAudioMs: ExecutionMeasurement | null;\n };\n readonly audio: ExecutionAudioReport;\n readonly fault: ExecutionFault | null;\n}\n\nexport interface ExecutionOptions {\n readonly tier?: ExecutionRequestedTier;\n /** Absolute or import.meta.url-relative URL of an ExecutionBootstrapEntry module. */\n readonly bootstrap: string | URL;\n /** Structured-cloneable input supplied identically to main and Worker realms. */\n readonly bootstrapData?: ExecutionBootstrapValue;\n /**\n * Realm side of an optional typed host/game channel. The engine transfers it\n * to a Worker when needed and otherwise preserves the same port contract.\n */\n readonly bootstrapPort?: MessagePort;\n /**\n * Serializable CatalogSource configuration constructed inside the selected\n * execution realm. This is the asset delivery seam for Worker execution;\n * `CreateAppOptions.assetCatalog` remains realm-bound and is rejected when\n * execution is requested.\n */\n readonly assetCatalog?: ExecutionAssetCatalog;\n readonly startupTimeoutMs?: number;\n readonly frameTimeoutMs?: number;\n}\n\nexport type ExecutionBootstrapValue =\n | null\n | boolean\n | number\n | string\n | readonly ExecutionBootstrapValue[]\n | { readonly [key: string]: ExecutionBootstrapValue };\n\nexport interface ExecutionControl {\n report(): ExecutionReport;\n rebuild(): Promise<Result<ExecutionReport, AppError>>;\n}\n","import {\n EXECUTION_CAPABILITY_NAMES,\n type ExecutionCapabilities,\n type ExecutionCapabilityName,\n} from './types';\n\nexport function unavailableExecutionCapabilities(reason: string): ExecutionCapabilities {\n return Object.fromEntries(\n EXECUTION_CAPABILITY_NAMES.map((name) => [name, { available: false, reason }]),\n ) as unknown as ExecutionCapabilities;\n}\n\nexport function missingExecutionCapabilities(\n capabilities: ExecutionCapabilities,\n required: readonly ExecutionCapabilityName[],\n): readonly ExecutionCapabilityName[] {\n return required.filter((name) => !capabilities[name].available);\n}\n\ninterface WorkerProbeResult {\n readonly workerAnimationFrame: boolean;\n readonly workerWebGpu: boolean;\n readonly atomicsWait: boolean;\n}\n\nfunction probeWorker(timeoutMs: number): Promise<WorkerProbeResult> {\n return new Promise((resolve) => {\n const source = `postMessage({workerAnimationFrame:typeof requestAnimationFrame==='function',workerWebGpu:typeof navigator==='object'&&navigator.gpu!==undefined,atomicsWait:typeof Atomics==='object'&&typeof Atomics.wait==='function'})`;\n const url = URL.createObjectURL(new Blob([source], { type: 'text/javascript' }));\n const worker = new Worker(url);\n const finish = (result: WorkerProbeResult): void => {\n worker.terminate();\n URL.revokeObjectURL(url);\n resolve(result);\n };\n const timeout = setTimeout(\n () => finish({ workerAnimationFrame: false, workerWebGpu: false, atomicsWait: false }),\n timeoutMs,\n );\n worker.onmessage = (event: MessageEvent<WorkerProbeResult>) => {\n clearTimeout(timeout);\n finish(event.data);\n };\n worker.onerror = () => {\n clearTimeout(timeout);\n finish({ workerAnimationFrame: false, workerWebGpu: false, atomicsWait: false });\n };\n });\n}\n\nexport async function probeExecutionCapabilities(\n canvas: HTMLCanvasElement,\n timeoutMs = 2_000,\n): Promise<ExecutionCapabilities> {\n const workerAvailable = typeof Worker === 'function';\n const offscreenAvailable = typeof canvas.transferControlToOffscreen === 'function';\n const isolated = globalThis.crossOriginIsolated === true;\n const sabAvailable = typeof SharedArrayBuffer === 'function';\n const worker = workerAvailable\n ? await probeWorker(timeoutMs)\n : { workerAnimationFrame: false, workerWebGpu: false, atomicsWait: false };\n return {\n worker: {\n available: workerAvailable,\n reason: workerAvailable ? 'Worker constructor observed' : 'Worker constructor unavailable',\n },\n offscreenCanvas: {\n available: offscreenAvailable,\n reason: offscreenAvailable\n ? 'canvas transferControlToOffscreen observed'\n : 'canvas cannot transfer to OffscreenCanvas',\n },\n workerAnimationFrame: {\n available: worker.workerAnimationFrame,\n reason: worker.workerAnimationFrame\n ? 'requestAnimationFrame observed in DedicatedWorker'\n : 'requestAnimationFrame unavailable in DedicatedWorker',\n },\n workerWebGpu: {\n available: worker.workerWebGpu,\n reason: worker.workerWebGpu\n ? 'navigator.gpu observed in DedicatedWorker'\n : 'navigator.gpu unavailable in DedicatedWorker',\n },\n crossOriginIsolated: {\n available: isolated,\n reason: isolated ? 'crossOriginIsolated is true' : 'crossOriginIsolated is false',\n },\n sharedArrayBuffer: {\n available: sabAvailable,\n reason: sabAvailable\n ? 'SharedArrayBuffer constructor observed'\n : 'SharedArrayBuffer constructor unavailable',\n },\n atomicsWait: {\n available: worker.atomicsWait,\n reason: worker.atomicsWait\n ? 'Atomics.wait observed in DedicatedWorker'\n : 'Atomics.wait unavailable in DedicatedWorker',\n },\n };\n}\n","import {\n EXECUTION_CAPABILITY_NAMES,\n EXECUTION_REQUESTED_TIERS,\n EXECUTION_TIERS,\n type ExecutionReport,\n} from './types';\n\nexport const EXECUTION_REPORT_SCHEMA_VERSION = 1 as const;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction hasExactKeys(value: Record<string, unknown>, keys: readonly string[]): boolean {\n const actual = Object.keys(value);\n return actual.length === keys.length && keys.every((key) => key in value);\n}\n\nfunction isMeasurement(value: unknown): boolean {\n if (!isRecord(value) || !hasExactKeys(value, ['samples', 'p50', 'p95', 'p99', 'jitter'])) {\n return false;\n }\n return (\n Number.isInteger(value.samples) &&\n (value.samples as number) > 0 &&\n ['p50', 'p95', 'p99', 'jitter'].every(\n (key) => typeof value[key] === 'number' && Number.isFinite(value[key]) && value[key] >= 0,\n )\n );\n}\n\nexport function isExecutionReport(value: unknown): value is ExecutionReport {\n if (!isRecord(value)) return false;\n if (\n !hasExactKeys(value, [\n 'schemaVersion',\n 'requestedTier',\n 'actualTier',\n 'selectionReason',\n 'sharedEvidencePassed',\n 'capabilities',\n 'engine',\n 'world',\n 'kernelDispatch',\n 'performance',\n 'audio',\n 'fault',\n ])\n ) {\n return false;\n }\n const report = value as unknown as Partial<ExecutionReport>;\n if (report.schemaVersion !== EXECUTION_REPORT_SCHEMA_VERSION) return false;\n if (!EXECUTION_REQUESTED_TIERS.includes(report.requestedTier as never)) return false;\n if (report.actualTier !== null && !EXECUTION_TIERS.includes(report.actualTier as never)) {\n return false;\n }\n if (typeof report.sharedEvidencePassed !== 'boolean' || report.capabilities === undefined) {\n return false;\n }\n if (\n !EXECUTION_CAPABILITY_NAMES.every((name) => {\n const fact = report.capabilities?.[name];\n return typeof fact?.available === 'boolean' && typeof fact.reason === 'string';\n })\n )\n return false;\n const engine = report.engine;\n const world = report.world;\n const dispatch = report.kernelDispatch;\n const performance = report.performance;\n const audio = report.audio;\n if (!isRecord(engine) || !hasExactKeys(engine, ['realm', 'health'])) return false;\n if (!['host', 'worker'].includes(engine.realm as string)) return false;\n if (!['idle', 'starting', 'running', 'stopped', 'faulted'].includes(engine.health as string)) {\n return false;\n }\n if (\n !isRecord(world) ||\n !hasExactKeys(world, ['identity', 'health', 'partialWrite', 'retryable'])\n ) {\n return false;\n }\n if (world.identity !== null && typeof world.identity !== 'string') return false;\n if (!['healthy', 'poisoned'].includes(world.health as string)) return false;\n if (typeof world.partialWrite !== 'boolean' || typeof world.retryable !== 'boolean') return false;\n if (\n !isRecord(dispatch) ||\n !hasExactKeys(dispatch, ['eligible', 'usedShared', 'reason', 'dispatched', 'completed'])\n ) {\n return false;\n }\n if (typeof dispatch.eligible !== 'boolean' || typeof dispatch.usedShared !== 'boolean')\n return false;\n if (\n ![\n 'no-eligible-kernel',\n 'zero-work',\n 'small-span',\n 'forced-inline',\n 'shared',\n 'poisoned',\n ].includes(dispatch.reason as string)\n )\n return false;\n if (!Number.isInteger(dispatch.dispatched) || !Number.isInteger(dispatch.completed)) return false;\n if (\n !isRecord(performance) ||\n !hasExactKeys(performance, ['hostFrameMs', 'engineUpdateMs', 'kernelWaitMs', 'hostAudioMs'])\n )\n return false;\n for (const key of ['hostFrameMs', 'engineUpdateMs', 'kernelWaitMs', 'hostAudioMs'] as const) {\n const measurement = performance[key];\n if (measurement !== null && !isMeasurement(measurement)) return false;\n }\n if (\n !isRecord(audio) ||\n !hasExactKeys(audio, ['owner', 'contextState', 'activeSourceCount', 'lastError'])\n )\n return false;\n if (audio.owner !== 'host') return false;\n if (!['running', 'suspended', 'closed'].includes(audio.contextState as string)) return false;\n if (!Number.isInteger(audio.activeSourceCount) || (audio.activeSourceCount as number) < 0)\n return false;\n if (audio.lastError !== null) {\n if (!isRecord(audio.lastError)) return false;\n if (!hasExactKeys(audio.lastError, ['code', 'expected', 'hint', 'detail'])) return false;\n if (\n typeof audio.lastError.code !== 'string' ||\n typeof audio.lastError.expected !== 'string' ||\n typeof audio.lastError.hint !== 'string'\n )\n return false;\n }\n if (report.fault !== null) {\n if (!isRecord(report.fault)) return false;\n if (\n !hasExactKeys(report.fault, [\n 'source',\n 'code',\n 'expected',\n 'hint',\n 'detail',\n 'partialWrite',\n 'retryable',\n ])\n )\n return false;\n if (\n !['bootstrap', 'handshake', 'runtime', 'kernel', 'world', 'rebuild'].includes(\n report.fault.source as string,\n )\n )\n return false;\n if (\n typeof report.fault.code !== 'string' ||\n typeof report.fault.expected !== 'string' ||\n typeof report.fault.hint !== 'string'\n )\n return false;\n if (\n typeof report.fault.partialWrite !== 'boolean' ||\n typeof report.fault.retryable !== 'boolean'\n )\n return false;\n }\n return true;\n}\n","import type { AudioState } from '@forgeax/engine-audio';\nimport { EXECUTION_REPORT_SCHEMA_VERSION } from './schema';\nimport type {\n ExecutionCapabilities,\n ExecutionReport,\n ExecutionRequestedTier,\n ExecutionSelection,\n} from './types';\n\nexport function executionAudioReport(state?: AudioState): ExecutionReport['audio'] {\n const error = state?.lastError ?? null;\n return {\n owner: 'host',\n contextState: state?.contextState ?? 'suspended',\n activeSourceCount: state?.activeSourceCount ?? 0,\n lastError:\n error === null\n ? null\n : {\n code: error.code,\n expected: error.expected,\n hint: error.hint,\n detail: error.detail,\n },\n };\n}\n\nexport function createExecutionReport(\n requestedTier: ExecutionRequestedTier,\n capabilities: ExecutionCapabilities,\n selection?: ExecutionSelection,\n): ExecutionReport {\n return {\n schemaVersion: EXECUTION_REPORT_SCHEMA_VERSION,\n requestedTier,\n actualTier: selection?.actualTier ?? null,\n selectionReason: selection?.selectionReason ?? null,\n sharedEvidencePassed: selection?.sharedEvidencePassed ?? false,\n capabilities,\n engine: {\n realm: selection?.actualTier === 'main-serial' ? 'host' : 'worker',\n health: 'idle',\n },\n world: {\n identity: null,\n health: 'healthy',\n partialWrite: false,\n retryable: true,\n },\n kernelDispatch: {\n eligible: false,\n usedShared: false,\n reason: 'no-eligible-kernel',\n dispatched: 0,\n completed: 0,\n },\n performance: {\n hostFrameMs: null,\n engineUpdateMs: null,\n kernelWaitMs: null,\n hostAudioMs: null,\n },\n audio: executionAudioReport(),\n fault: null,\n };\n}\n","import type { AudioState } from '@forgeax/engine-audio';\nimport { err } from '@forgeax/engine-types';\nimport { APP_ERROR_HINTS, APP_EXPECTED, AppError } from '../errors';\nimport { executionAudioReport } from './report';\nimport type { ExecutionControl, ExecutionEngineHealth, ExecutionReport } from './types';\n\nexport function cloneExecutionReport(report: ExecutionReport): ExecutionReport {\n return structuredClone(report);\n}\n\nexport interface LocalExecutionControl extends ExecutionControl {\n setEngineHealth(health: ExecutionEngineHealth): void;\n}\n\nexport interface LocalExecutionReportProviders {\n readonly audio?: () => AudioState;\n readonly world?: () => ExecutionReport['world'];\n}\n\nexport function createLocalExecutionControl(\n initial: ExecutionReport,\n providers: LocalExecutionReportProviders = {},\n): LocalExecutionControl {\n let current = cloneExecutionReport(initial);\n return {\n setEngineHealth: (health) => {\n current = { ...current, engine: { ...current.engine, health } };\n },\n report: () =>\n cloneExecutionReport({\n ...current,\n world: providers.world?.() ?? current.world,\n audio: executionAudioReport(providers.audio?.()),\n }),\n rebuild: async () =>\n err(\n new AppError({\n code: 'app-execution-rebuild-failed',\n expected: APP_EXPECTED['app-execution-rebuild-failed'],\n hint: APP_ERROR_HINTS['app-execution-rebuild-failed'],\n detail: {\n worldIdentity: current.world.identity,\n cause: new Error('This local assembly has no bootstrap module.'),\n },\n }),\n ),\n };\n}\n","import { err, ok, type Result } from '@forgeax/engine-types';\nimport { APP_ERROR_HINTS, APP_EXPECTED, AppError, type AppError as AppErrorType } from '../errors';\nimport { missingExecutionCapabilities } from './capabilities';\nimport type {\n ExecutionCapabilities,\n ExecutionCapabilityName,\n ExecutionRequestedTier,\n ExecutionSelection,\n ExecutionTier,\n} from './types';\n\nconst ENGINE_WORKER_CAPABILITIES = [\n 'worker',\n 'offscreenCanvas',\n 'workerWebGpu',\n] as const satisfies readonly ExecutionCapabilityName[];\nconst SHARED_CAPABILITIES = [\n ...ENGINE_WORKER_CAPABILITIES,\n 'crossOriginIsolated',\n 'sharedArrayBuffer',\n 'atomicsWait',\n] as const satisfies readonly ExecutionCapabilityName[];\n\nexport interface ExecutionSelectionInput {\n readonly requestedTier: ExecutionRequestedTier;\n readonly capabilities: ExecutionCapabilities;\n readonly sharedEvidencePassed: boolean;\n}\n\nfunction requiredCapabilities(tier: ExecutionTier): readonly ExecutionCapabilityName[] {\n if (tier === 'main-serial') return [];\n if (tier === 'engine-worker') return ENGINE_WORKER_CAPABILITIES;\n return SHARED_CAPABILITIES;\n}\n\nfunction missingFor(\n tier: ExecutionTier,\n capabilities: ExecutionCapabilities,\n): readonly ExecutionCapabilityName[] {\n return missingExecutionCapabilities(capabilities, requiredCapabilities(tier));\n}\n\nexport function selectExecutionTier(\n input: ExecutionSelectionInput,\n): Result<ExecutionSelection, AppErrorType> {\n if (input.requestedTier !== 'auto') {\n const missing = missingFor(input.requestedTier, input.capabilities);\n if (missing.length > 0 || (input.requestedTier === 'shared' && !input.sharedEvidencePassed)) {\n return err(\n new AppError({\n code: 'app-execution-tier-unavailable',\n expected: APP_EXPECTED['app-execution-tier-unavailable'],\n hint: APP_ERROR_HINTS['app-execution-tier-unavailable'],\n detail: {\n requestedTier: input.requestedTier,\n missingCapabilities: missing,\n sharedEvidencePassed: input.sharedEvidencePassed,\n },\n }),\n );\n }\n return ok({\n requestedTier: input.requestedTier,\n actualTier: input.requestedTier,\n selectionReason: 'explicit-request',\n missingCapabilities: [],\n sharedEvidencePassed: input.sharedEvidencePassed,\n });\n }\n\n const sharedMissing = missingFor('shared', input.capabilities);\n if (sharedMissing.length === 0 && input.sharedEvidencePassed) {\n return ok({\n requestedTier: 'auto',\n actualTier: 'shared',\n selectionReason: 'auto-shared',\n missingCapabilities: [],\n sharedEvidencePassed: true,\n });\n }\n const workerMissing = missingFor('engine-worker', input.capabilities);\n if (workerMissing.length === 0) {\n return ok({\n requestedTier: 'auto',\n actualTier: 'engine-worker',\n selectionReason: 'auto-engine-worker',\n missingCapabilities: sharedMissing,\n sharedEvidencePassed: input.sharedEvidencePassed,\n });\n }\n return ok({\n requestedTier: 'auto',\n actualTier: 'main-serial',\n selectionReason: 'auto-main-serial',\n missingCapabilities: workerMissing,\n sharedEvidencePassed: input.sharedEvidencePassed,\n });\n}\n","import { err, ok, type Result } from '@forgeax/engine-types';\nimport { APP_ERROR_HINTS, APP_EXPECTED, AppError, type AppError as AppErrorType } from '../errors';\n\n/** Normalize a bootstrap module before any realm probing or worker startup. */\nexport function normalizeExecutionBootstrapUrl(\n bootstrap: string | URL,\n): Result<string, AppErrorType> {\n const moduleUrl = typeof bootstrap === 'string' ? bootstrap : bootstrap.href;\n try {\n return ok(new URL(bootstrap, globalThis.location?.href).href);\n } catch (cause) {\n return err(\n new AppError({\n code: 'app-execution-bootstrap-failed',\n expected: APP_EXPECTED['app-execution-bootstrap-failed'],\n hint: APP_ERROR_HINTS['app-execution-bootstrap-failed'],\n detail: {\n phase: 'prepare',\n moduleUrl,\n cause: cause instanceof TypeError ? cause : new TypeError(String(cause)),\n },\n }),\n );\n }\n}\n","// @forgeax/engine-app -- error fan-out registry + console.error fallback (M4 / w11).\n//\n// Public surface (consumed only by createApp + frame-loop -- this module\n// lives under `internal/` and is not re-exported from the package barrel):\n//\n// const fan = new ErrorFanoutRegistry({ silenceUnhandledErrors: false });\n// const off = fan.add(cb); // add listener; returns idempotent unsubscribe\n// off(); // remove listener (safe to call twice)\n// fan.fire(err); // fan out to all listeners; if none AND\n// // silenceUnhandledErrors !== true, call\n// // console.error(err)\n//\n// Wiring (per plan-strategy D-9 + research section 7.3\n// createRenderer.ts:532-566 LostListenerRegistry side-evidence):\n//\n// - Listener set is a Set so duplicate add() is idempotent (set semantics).\n// - fire() iterates over a snapshot so a listener that calls .add()/.remove()\n// mid-fire does not perturb the iteration.\n// - When the listener set is empty AND silenceUnhandledErrors !== true,\n// console.error(err) is invoked once with the structured error object as\n// the single argument. Tests pin reference equality via mock.calls[0][0]\n// so the AI-user contract (.code / .expected / .hint structure preserved)\n// is observable in browser devtools.\n// - late-attach replay is deliberately NOT implemented. rAF errors are\n// frame-time stream (each tick generates a fresh event); a replay\n// semantic would surface stale state to a freshly registered listener.\n// This is a deliberate divergence from runtime/createRenderer.ts:337-345\n// LostListenerRegistry which DOES replay (because device.lost is a\n// one-shot lifecycle event); see plan-strategy D-9 for the divergence\n// rationale.\n//\n// Architecture principle SSOT: the listener set + the silence flag are the\n// only state owned by this module; createApp passes the silence flag in via\n// constructor options and never reads it again, so the SSOT is the Registry\n// instance state.\n\nimport type { AppDispatchError } from '../types';\n\n/**\n * Listener callback for app-shell error fan-out.\n *\n * The narrow union (`AppDispatchError` = AppError | RhiError | RuntimeError)\n * deliberately excludes raw `Error` (charter P3 explicit failure: AI users\n * walk `.code` not message strings). `RuntimeError` is included so a\n * runtime-layer error fanned out by `Renderer.onError` (e.g.\n * `'equirect-projection-failed'`) reaches host App listeners verbatim\n * (feat-20260531-skybox-env-background F-1). `EngineEnvironmentError` does not\n * appear here because construction-time failure flows through\n * `Promise<Result<App, ...>>` of `createApp(canvas)` before the App handle\n * exists; once an App handle is alive, only frame-time errors (this union)\n * reach onError.\n */\nexport type ErrorFanoutListener = (err: AppDispatchError) => void;\n\n/**\n * Constructor options for ErrorFanoutRegistry. Mirrors the\n * `silenceUnhandledErrors` field on CreateAppOptions / AppAssembleArgs;\n * createApp threads the field down into the registry verbatim.\n */\nexport interface ErrorFanoutOptions {\n readonly silenceUnhandledErrors?: boolean;\n}\n\n/**\n * ErrorFanoutRegistry shares its shape with the LostListenerRegistry\n * implementation in `packages/runtime/src/createRenderer.ts:532-566` per\n * plan-strategy D-9 -- listener set + fan-out fire + idempotent unsubscribe.\n * The two divergences from the runtime registry are intentional:\n *\n * 1. Late-attach replay is NOT implemented -- rAF errors are a frame-time\n * stream (each tick produces fresh state) so replay semantics are\n * meaningless and would mislead newly registered listeners.\n * 2. `console.error(err)` fallback fires when the listener set is empty\n * and `silenceUnhandledErrors !== true` -- a charter P3 tribute that\n * makes \"unhandled\" errors loud rather than silent.\n */\nexport class ErrorFanoutRegistry {\n private readonly listeners: Set<ErrorFanoutListener> = new Set();\n private readonly silenceUnhandledErrors: boolean;\n\n constructor(opts: ErrorFanoutOptions = {}) {\n this.silenceUnhandledErrors = opts.silenceUnhandledErrors === true;\n }\n\n /**\n * Register a listener. Returns an unsubscribe function. Calling\n * unsubscribe more than once is a safe no-op (Set.delete returns\n * false on the second call but does not throw). Re-registering the\n * same listener function is a no-op (Set semantics).\n */\n add(cb: ErrorFanoutListener): () => void {\n this.listeners.add(cb);\n return () => {\n this.listeners.delete(cb);\n };\n }\n\n /**\n * Iterate over a snapshot of the listener set so a listener that\n * mutates the set mid-fire does not perturb the iteration. When the\n * set is empty AND silenceUnhandledErrors !== true, call\n * console.error(err) so the unhandled error is visible in devtools\n * (charter P3 explicit failure: silent drop is a footgun).\n */\n fire(err: AppDispatchError): void {\n if (this.listeners.size === 0) {\n if (!this.silenceUnhandledErrors) {\n // eslint-disable-next-line no-console -- charter P3 fallback\n console.error(err);\n }\n return;\n }\n const snapshot = Array.from(this.listeners);\n for (const cb of snapshot) {\n cb(err);\n }\n }\n\n /**\n * Number of currently registered listeners. Reserved for diagnostics +\n * test fixtures (e.g. asserting cleanup paths reach the registry); not\n * part of the public app-shell surface.\n *\n * @internal\n */\n _size(): number {\n return this.listeners.size;\n }\n}\n","// @forgeax/engine-app -- shared types for createApp double-SSOT entry.\n//\n// AI users: see packages/app/src/index.ts for the public surface and\n// packages/app/src/create-app.ts for the runtime implementation.\n//\n// M1 (this milestone) ships the skeleton: interfaces are final-shape, but\n// start / stop / pause / resume / onError on the returned App are stubs\n// that return Result.ok(undefined) and a no-op unsubscribe. The rAF main\n// loop, dt clamp, error fan-out, and input attach internals land in\n// later milestones (M2..M5 per plan-strategy section 7).\n\nimport type { AssetRegistry } from '@forgeax/engine-assets-runtime';\nimport type { AudioBackend } from '@forgeax/engine-audio';\nimport type { DebugDraw } from '@forgeax/engine-debug-draw';\nimport type { TimePolicy, World } from '@forgeax/engine-ecs';\nimport type {\n ActionConfig,\n InputBackend,\n PointerLockProvider,\n VirtualJoystickConfig,\n} from '@forgeax/engine-input';\nimport type { PhysicsWorld, PhysicsWorld2D } from '@forgeax/engine-physics';\nimport type { Context, Plugin } from '@forgeax/engine-plugin';\nimport type { Profiler } from '@forgeax/engine-profiler';\nimport type { RenderError, Renderer, RenderFeature, RenderProfile } from '@forgeax/engine-render';\nimport type { RhiBackendInstrumentation } from '@forgeax/engine-render/internal/construct-renderer';\nimport type { RhiError, RhiInstance } from '@forgeax/engine-rhi';\nimport type { EngineEnvironmentError } from '@forgeax/engine-runtime';\nimport type { ImportTransport, Result } from '@forgeax/engine-types';\n\nimport type { AppError, AppErrorCode } from './errors';\nimport type { ExecutionControl, ExecutionOptions } from './execution';\nimport type { RhiCapture } from './internal/rhi-capture';\n\n// Re-export AppError + AppErrorCode (the canonical SSOT lives in\n// `./errors`). Pre-M5 (M1..M4) referenced these as type-only declarations\n// inside this file; M5 collapses to the single SSOT in `./errors.ts` per\n// plan-strategy section 7 + research section 2.7.\nexport type { AppError, AppErrorCode };\n\n/**\n * Structured error union surfaced through the App `onError` fan-out + the\n * assemble-form construction Result. Derived from the `Renderer.onError`\n * channel contract `RendererError` (feat-20260704-runtime-tier1-decomposition\n * M2 / w14 / D-4) so a runtime-layer error fanned out by the renderer (e.g.\n * `'equirect-projection-failed'`) reaches host App listeners verbatim, plus the\n * App-layer `AppError`. `RendererError` = `RhiError | RenderError |\n * AssetRuntimeError | SkinError | PostProcessError`, so this equals the\n * pre-decomposition `AppError | RhiError | RuntimeError | PostProcessError`\n * exactly (RuntimeError was RenderError | AssetRuntimeError | SkinError). AI\n * users `switch (err.code)` over the union: the disjoint `AppErrorCode` /\n * `RhiErrorCode` / per-cluster `*ErrorCode` / `PostProcessErrorCode` literal\n * sets let TS narrow each arm to the concrete class.\n */\nexport type AppDispatchError = AppError | RenderError;\n\n/**\n * Per-frame draw description pulled from the host each frame\n * (feat-20260709-editor-world-partition-editorworld-super-composite / M2 / D-3).\n *\n * - `worlds` — the exact world list to render this frame, in draw order.\n * - `cameraOwner` — index into `worlds` whose cameras drive the frame.\n * - `resourceOwner`— index into `worlds` whose singleton render resources\n * (skylight / skybox / postProcessParams) drive the frame.\n *\n * The two owners are independent (M1 owner-split): an editor can render a scene\n * world's geometry through an editor world's camera while sourcing lighting from\n * a third. `cameraOwner === resourceOwner` is the single-owner degenerate case.\n *\n * @see {@link DrawSource}\n */\nexport interface DrawSourceResult {\n readonly worlds: readonly World[];\n readonly cameraOwner: number;\n readonly resourceOwner: number;\n}\n\n/**\n * Stable frame-loop phase vocabulary for opt-in performance diagnostics.\n *\n * Local and Worker execution record these phases through the same optional\n * Profiler capability. When omitted, the frame loop keeps its normal path and\n * does not allocate capture records.\n */\nexport const APP_PHASE_CATALOG = [\n 'frame-total',\n 'draw-source',\n 'world-update-primary',\n 'world-update-injected',\n 'renderer-draw',\n 'host-frame',\n 'engine-update',\n 'kernel-wait',\n 'host-audio',\n] as const;\n\n/**\n * Optional per-frame draw-source injection seam\n * (feat-20260709-editor-world-partition-editorworld-super-composite / M2 / D-3).\n *\n * The frame-loop invokes this callback once per frame (a \"pull\"). It lets a host\n * (e.g. the editor) decide, each frame, WHICH worlds to render and which owner\n * indices to use — without the engine knowing anything about editor world\n * partitioning.\n *\n * - Returns `undefined` → the frame-loop degrades to the single-world path,\n * byte-identical to `renderer.draw([world], { cameraOwner: 0, resourceOwner: 0 })` where `world` is\n * the App's own world (the single-world AI-user default). A host that wires\n * the seam but has nothing multi-world to inject this frame returns\n * `undefined`.\n * - Returns a {@link DrawSourceResult} → the frame-loop runs `world.update(1 / 60).unwrap()`\n * on EVERY returned world (so transform propagation writes each world's\n * derived `Transform.world` mat4 before extract reads it — no stale matrix),\n * then calls `renderer.draw(worlds, { cameraOwner, resourceOwner })`.\n *\n * When omitted entirely, the App never consults a seam and always renders its\n * own single world (legacy behaviour unchanged).\n */\nexport type DrawSource = () => DrawSourceResult | undefined;\n\n/**\n * Options for the assemble-form entry createApp({ renderer, world, ... }).\n *\n * Field semantics (final shape -- runtime use lands in M2..M5):\n * - renderer: caller-owned Renderer (host already invoked createRenderer).\n * - world: caller-owned World (host already invoked new World()).\n * - input: InputBackend handle the host-side attached. When omitted the\n * assemble entry skips input attach (caller manages input).\n * - silenceUnhandledErrors: when true, suppresses the console.error\n * fallback inside the error fan-out (M4).\n */\nexport interface AppAssembleArgs {\n readonly renderer: Renderer;\n /** Host-owned asset catalogue paired with the renderer construction. */\n readonly assets?: AssetRegistry;\n readonly world: World;\n /** Unified plugin list (M1 feat-20260623-plugin-system-unify-build-world-protocol). */\n readonly plugins?: readonly Plugin[];\n readonly silenceUnhandledErrors?: boolean;\n /**\n * Per-frame draw-source injection seam (M2 / D-3). When supplied, the\n * frame-loop pulls it each frame to decide which worlds to render + which\n * owner indices to use; when omitted the App renders its own single world\n * (legacy behaviour). See {@link DrawSource}.\n */\n readonly drawSource?: DrawSource;\n /** Explicit profiler capability shared by the host and renderer. */\n readonly profiler?: Profiler;\n}\n\n/** Effective physical canvas size transported to an Engine Worker frame. */\nexport interface CanvasDrawingBufferSize {\n readonly width: number;\n readonly height: number;\n}\n\n/**\n * Options for the canvas-form thin wrapper createApp(canvas, opts?, bundler?).\n *\n * feat-20260608-create-app-param-surface-trim / M2 / D-3: self-describing\n * surface -- no longer `extends RendererOptions`. The 7 app-only fields\n * (input / audio / physics / silenceUnhandledErrors) plus the RHI escape-hatch\n * field (rhi) are\n * listed inline, so IDE autocomplete shows AI users a clean surface\n * without inheriting now-disallowed slots like clearColor (M1, on Camera)\n * and shaderManifestUrl (M2, on BundlerOptions / 3rd arg). The escape\n * hatches stay discoverable for the RHI debugging path (charter P1 -- not\n * default noise, but reachable when the AI user scrolls the type).\n */\nexport interface CreateAppOptions {\n /** Opt into realm-local engine execution. Omission preserves the existing local assembly path. */\n readonly execution?: ExecutionOptions;\n /** Host-owned UI root whose events do not enter gameplay input. */\n readonly uiRoot?: Node;\n /** Producer-owned render features forwarded to the renderer unchanged. */\n readonly features?: readonly RenderFeature<unknown>[];\n /** Standard profile forwarded to the single renderer-owned pipeline. */\n readonly standardProfile?: RenderProfile;\n /** Unified plugin list (M1 feat-20260623-plugin-system-unify-build-world-protocol). */\n readonly plugins?: readonly Plugin[];\n /**\n * A host-owned input backend for this canvas. When supplied, createApp inserts\n * it into the World instead of attaching a second browser listener set. The\n * host retains its lifecycle; this app only consumes snapshots from the view.\n */\n readonly input?: InputBackend;\n /**\n * World-owned time policy supplied to the canvas-form World constructor.\n * Assemble-form callers retain their pre-existing World policy.\n */\n readonly time?: TimePolicy;\n /**\n * When true, suppresses the console.error fallback inside the error\n * fan-out for hosts that prefer total silence (M4 default: false).\n */\n readonly silenceUnhandledErrors?: boolean;\n /**\n * RHI escape hatch -- forwarded verbatim to createRenderer. Same semantics\n * as `RendererOptions.rhi` (the createRenderer third-party-RHI-instance\n * injection point). Use only for testing / pinning a specific backend /\n * advanced AI users that ship their own RhiInstance shim.\n */\n readonly rhi?: RhiInstance | undefined;\n /** Optional host-owned RHI lifecycle instrumentation, such as recording. */\n readonly rhiInstrumentation?: RhiBackendInstrumentation;\n /**\n * Neutral PointerLock gate forwarded verbatim to the canvas-form input\n * attach (attachInputAuto → attachBrowserInputBackend). When it returns\n * false, a canvas click does NOT capture the cursor. Absent => always-lock\n * (standalone game behaviour). The engine never learns WHY locking is\n * (dis)allowed — the host owns that decision (e.g. an editor viewport that\n * only allows lock in its play·game quadrant). Ignored by the assemble form\n * (host-managed input owns its own lock policy).\n */\n readonly pointerLockAllowed?: () => boolean;\n /**\n * Virtual joystick configs forwarded verbatim to the canvas-form input\n * attach (attachInputAuto -> attachBrowserInputBackend). Each config derives\n * a normalized 2D axis readable via `snap.virtualAxis(name)`. Absent => no\n * virtual joysticks. Ignored by the assemble form (host-managed input wires\n * its own backend). Mirrors `pointerLockAllowed`: the canvas-form entry must\n * expose every backend option the standard recipe needs, or the config path\n * dead-ends before reaching the backend that already supports it.\n */\n readonly virtualJoysticks?: readonly VirtualJoystickConfig[];\n /**\n * Action mapping configuration (M1: action semantic abstraction layer).\n *\n * Declares named actions (e.g. 'jump', 'moveRight') bound to raw input sources\n * (key, mouseButton, gamepadButton, gamepadAxis). The engine derives per-frame\n * action states via `deriveActionStates()` and exposes them via\n * `snap.action(name).isPressed()`. Duplicate action names follow last-wins\n * semantics (D-8).\n *\n * This is canvas-form only. Assemble-form hosts insert the\n * `INPUT_MAP_KEY` Resource directly.\n */\n readonly inputMap?: readonly ActionConfig[] | undefined;\n /**\n * M2: pointer-lock provider injected by the host (e.g. editor play-runtime).\n * Forwarded verbatim through InputAttachOptions to BrowserInputBackendOptions.\n * When absent, the backend falls back to the W3C requestPointerLock() path.\n * Type SSOT is @forgeax/engine-input's PointerLockProvider.\n * Ignored by the assemble form (host-managed input owns its own lock policy).\n */\n readonly lockProvider?: PointerLockProvider;\n /**\n * Per-frame draw-source injection seam (M2 / D-3). When supplied, the\n * frame-loop pulls it each frame to decide which worlds to render + which\n * owner indices to use; when omitted the canvas-form App renders its own\n * single world (legacy behaviour unchanged). See {@link DrawSource}.\n */\n readonly drawSource?: DrawSource;\n /** Explicit profiler capability shared by the host and renderer. */\n readonly profiler?: Profiler;\n}\n\n/**\n * Bundler-layer injection for the canvas-form createApp(canvas, opts, bundler?)\n * and createRenderer(canvas, opts, bundler?).\n *\n * feat-20260608-create-app-param-surface-trim / M2 / D-3: this is the SSOT\n * for build-tool emit knowledge that the engine consumes at runtime.\n * Aggregates two host-injected channels:\n *\n * - importTransport: dev-only ImportTransport that the engine threads to\n * the AssetRegistry third ctor slot so a DDC miss can lazy-import.\n * Absent => shipped form (DDC miss fails fast with `asset-not-imported`).\n *\n * - shaderManifestUrl: the path the host's vite-plugin-shader emit step\n * wrote `manifest.json` to. Absent (or `BundlerOptions` itself omitted)\n * => createRenderer falls back to '/shaders/manifest.json'\n * (createRenderer.ts D-2 q5-A) so the LO 1.1 zero-config takeoff path\n * keeps working without any explicit injection.\n *\n * Both fields are optional so `BundlerOptions = {}` is a valid call shape.\n * M3 collapses the typical demo callsite to `forgeaxBundlerAdapter()` (a\n * factory exported by `virtual:forgeax/bundler`), which returns an object\n * with this same structural shape -- type compatibility is enforced by\n * TypeScript structural typing (D-4: vite-plugin-shader does NOT import\n * `@forgeax/engine-app`, so this interface is the consumer-side SSOT).\n */\nexport interface BundlerOptions {\n /**\n * Dev-only ImportTransport forwarded verbatim to createRenderer (and thence\n * to the AssetRegistry third ctor slot). Absent => shipped form (a DDC miss\n * fails fast with `asset-not-imported`).\n *\n * The `| undefined` widening is necessary because exactOptionalPropertyTypes\n * is enabled at the workspace level (tsconfig.base.json); it lets tests\n * (and demos that gate on a build-mode flag) write `{ importTransport:\n * undefined }` without a TS2379 error.\n */\n readonly importTransport?: ImportTransport | undefined;\n /**\n * vite-plugin-shader emit URL (the path the build wrote `manifest.json`\n * to). Absent => createRenderer falls back to '/shaders/manifest.json'.\n * Tests can inject via a `data:application/json,...` URL to bypass fetch.\n *\n * The `| undefined` widening lets tests opt into the zero-entry mode by\n * writing `{ shaderManifestUrl: undefined }` (the createRenderer body\n * checks `'shaderManifestUrl' in bundler` to distinguish \"absent\" from\n * \"explicitly undefined\"; see D-2 q5-A in plan-strategy).\n */\n readonly shaderManifestUrl?: string | undefined;\n}\n\n/**\n * App handle returned by createApp(...). Host owns the lifecycle and\n * interacts with the rAF loop through start / stop / pause / resume +\n * the structured error fan-out via onError.\n *\n * M1 skeleton: start / stop / pause / resume return Result.ok(undefined)\n * synchronously and onError returns a no-op unsubscribe. The 4-state\n * machine + idempotent transitions land in M2 (plan-strategy section 7).\n */\nexport interface App {\n /** Caller-owned Renderer (reference equality with the assemble input). */\n readonly renderer: Renderer;\n /** Host-owned asset catalogue paired with this renderer lease. */\n readonly assets?: AssetRegistry;\n /** Caller-owned World (reference equality with the assemble input). */\n readonly world: World;\n /** Host-side lifecycle and immutable diagnostics for the selected execution tier. */\n readonly execution: ExecutionControl;\n /**\n * Pause frame submission and relinquish the renderer presentation surface\n * without replacing World, Renderer, AssetRegistry, plugins, or history.\n */\n releaseSurfacePreserveWorld(): Promise<Result<void, RhiError | RenderError>>;\n /** Restore the same surface and resume only when release paused a running App. */\n restoreSurface(): Promise<Result<void, RhiError | RenderError>>;\n /** Native Cordis realm that owns this App's capability fibers and effects. */\n readonly pluginContext: Context;\n /** InputBackend handle when input attach is enabled; undefined otherwise. */\n readonly input?: InputBackend;\n /** AudioBackend handle when audio attach is enabled; undefined otherwise. */\n readonly audio?: AudioBackend;\n /**\n * PhysicsWorld handle when physicsPlugin is loaded; undefined\n * otherwise. physicsPlugin.build awaits the WASM import -- createApp\n * resolves ONLY after the WASM module is loaded, so this field is\n * populated immediately when createApp returns (AC-06: no timing gap).\n */\n readonly physics?: PhysicsWorld | PhysicsWorld2D | undefined;\n /**\n * Immediate-mode debug-draw overlay instance (feat-20260615 debug-draw M5).\n *\n * Created automatically during createApp (canvas form). AI users call\n * `app.debugDraw.line(a, b, RED)` in any system and the overlay renders\n * at frame-end via the render-graph's debug-overlay pass. Shape calls are\n * immediate-mode — vertices accumulate per-frame and are flushed at the\n * tonemap suffix; stale data from frame N-1 is never visible in frame N.\n *\n * Undefined when debug-draw is not wired (assemble-form createApp with\n * no explicit debugDraw creation — the auto-attach is canvas-form only).\n */\n readonly debugDraw?: DebugDraw | undefined;\n /**\n * Begin rAF scheduling. Idempotent guard lands in M2:\n * - first call: Result.ok(undefined)\n * - second call (already running): Result.err({ code: 'app-already-running' })\n * M1 stub returns Result.ok(undefined) unconditionally.\n */\n start(): Result<void, AppError>;\n /**\n * Stop rAF scheduling. State-machine semantics land in M2:\n * - 'idle' / 'stopped' state: Result.err({ code: 'app-not-started' })\n * - 'running' / 'paused' state: Result.ok(undefined)\n * M1 stub returns Result.ok(undefined) unconditionally.\n */\n stop(): Result<void, AppError>;\n /** Tear down plugins, host resources, and renderer ownership. */\n dispose(): Promise<Result<void, AppError>>;\n /**\n * Pause rAF scheduling. Idempotent in 'paused' state. M1 stub returns\n * Result.ok(undefined) unconditionally; full state machine in M2.\n */\n pause(): Result<void, AppError>;\n /**\n * Resume rAF scheduling from paused state. M1 stub returns\n * Result.ok(undefined) unconditionally; full state machine in M2.\n */\n resume(): Result<void, AppError>;\n /**\n * Advance one complete update/draw frame through the App-owned frame authority.\n * The App must be paused; deterministic tools supply the explicit delta.\n */\n stepFrame(deltaSeconds: number): Result<void, AppDispatchError>;\n /**\n * Subscribe to structured errors fan-out from the rAF loop. Returns an\n * unsubscribe handle. The callback signature deliberately excludes raw\n * Error (charter P3 -- AI users walk .code, not message strings).\n *\n * M1 stub: registers nothing and returns a no-op unsubscribe; full\n * fan-out registry lands in M4 (plan-strategy section 7).\n */\n onError(cb: (err: AppDispatchError) => void): () => void;\n /**\n * Replace the per-frame world routing pull. `undefined` restores the\n * single-world path; an injected result updates every returned secondary\n * World before drawing it with the declared owners. This changes routing,\n * not scheduling or time ownership.\n */\n setDrawSource(drawSource: DrawSource | undefined): void;\n /**\n * Most recent dispatched error retained for host self-inspection without\n * requiring an onError listener up front.\n */\n readonly lastError?: AppDispatchError | undefined;\n /** Optional single-frame RHI capture capability owned by the App host. */\n readonly rhiCapture?: RhiCapture;\n /**\n * Handle for the remote eval server started by createApp (dev mode).\n *\n * `undefined` in production builds and headless/dawn-node without explicit\n * opt-in. When present, the host can read `app.remote.port` for WS connection\n * details or call `await app.remote.close()` to tear down the server\n * (feat-20260629-inspector-two-layer-model M4 / w20).\n *\n * Typed as {@link RemoteHandle} from `@forgeax/engine-types` — a neutral\n * package with no dependency on `@forgeax/engine-remote`.\n */\n readonly remote?: import('@forgeax/engine-types').RemoteHandle | undefined;\n}\n\n/** Host control returned by the unified execution path. Engine-owned objects remain realm-local. */\nexport type ExecutionApp = Pick<\n App,\n 'execution' | 'input' | 'audio' | 'start' | 'stop' | 'pause' | 'resume' | 'onError' | 'lastError'\n>;\n\n/**\n * Error union returned by the assemble-form entry. The canvas-form thin\n * wrapper widens this with EngineEnvironmentError (createRenderer\n * construction-time failure path -- plan-strategy D-5 / requirements AC-01).\n *\n * Cordis activation failures are projected into AppError at this boundary.\n */\nexport type AssembleAppError = AppError | RhiError;\n\n/**\n * Error union returned by the canvas-form thin wrapper. Extends\n * AssembleAppError with EngineEnvironmentError to surface\n * createRenderer construction-time failures unchanged (preserves\n * .detail.webgpuError per requirements section 6.1).\n *\n * The canvas form adds renderer construction failures.\n */\nexport type CanvasAppError = AssembleAppError | EngineEnvironmentError;\n","import { err, ok, type Result } from '@forgeax/engine-types';\nimport { APP_ERROR_HINTS, APP_EXPECTED, AppError, type AppError as AppErrorType } from '../errors';\nimport { validateExecutionBootstrapData } from './bootstrap-entry';\nimport type {\n EngineToHostMessage,\n ExecutionFaultMessage,\n ExecutionInitMessage,\n ExecutionReadyMessage,\n HostToEngineMessage,\n} from './protocol';\n\nexport interface EngineWorkerSession {\n readonly worker: Worker;\n readonly ready: ExecutionReadyMessage;\n post(message: HostToEngineMessage, transfer?: Transferable[]): void;\n listen(listener: (message: EngineToHostMessage) => void): () => void;\n dispose(): void;\n}\n\nexport interface StartEngineWorkerOptions {\n readonly canvas: HTMLCanvasElement;\n readonly bootstrapUrl: string;\n readonly bootstrapData?: import('./types').ExecutionBootstrapValue;\n readonly bootstrapPort?: MessagePort;\n readonly assetCatalog?: import('./types').ExecutionAssetCatalog;\n readonly shaderManifestUrl?: string;\n readonly time?: import('@forgeax/engine-ecs').TimePolicy;\n readonly timeoutMs: number;\n readonly tier: import('./types').ExecutionTier;\n readonly workerFactory?: () => Worker;\n}\n\nfunction deadlineError(timeoutMs: number): AppErrorType {\n return new AppError({\n code: 'app-execution-deadline-exceeded',\n expected: APP_EXPECTED['app-execution-deadline-exceeded'],\n hint: APP_ERROR_HINTS['app-execution-deadline-exceeded'],\n detail: { phase: 'handshake', timeoutMs },\n });\n}\n\nfunction startupFault(message: ExecutionFaultMessage, moduleUrl: string): AppErrorType {\n return new AppError({\n code: 'app-execution-bootstrap-failed',\n expected: APP_EXPECTED['app-execution-bootstrap-failed'],\n hint: APP_ERROR_HINTS['app-execution-bootstrap-failed'],\n detail: { phase: 'bootstrap', moduleUrl, cause: message.detail },\n });\n}\n\nexport async function startEngineWorker(\n options: StartEngineWorkerOptions,\n): Promise<Result<EngineWorkerSession, AppErrorType>> {\n const validData = validateExecutionBootstrapData(options.bootstrapData, options.bootstrapUrl);\n if (!validData.ok) return validData;\n const worker =\n options.workerFactory?.() ??\n new Worker(new URL('./engine-worker-runtime.mjs', import.meta.url), {\n type: 'module',\n name: 'forgeax-engine',\n });\n const listeners = new Set<(message: EngineToHostMessage) => void>();\n let settled = false;\n let resolveReady: (result: Result<ExecutionReadyMessage, AppErrorType>) => void = () => {};\n const readyPromise = new Promise<Result<ExecutionReadyMessage, AppErrorType>>((resolve) => {\n resolveReady = resolve;\n });\n const timeout = setTimeout(() => {\n if (settled) return;\n settled = true;\n worker.terminate();\n resolveReady(err(deadlineError(options.timeoutMs)));\n }, options.timeoutMs);\n worker.onmessage = (event: MessageEvent<EngineToHostMessage>) => {\n const message = event.data;\n if (!settled && message.kind === 'ready') {\n settled = true;\n clearTimeout(timeout);\n resolveReady(ok(message));\n } else if (!settled && message.kind === 'fault') {\n settled = true;\n clearTimeout(timeout);\n worker.terminate();\n resolveReady(err(startupFault(message, options.bootstrapUrl)));\n }\n for (const listener of listeners) listener(message);\n };\n worker.onerror = (event) => {\n if (settled) {\n const crash: ExecutionFaultMessage = {\n kind: 'fault',\n worldIdentity: null,\n source: 'runtime',\n code: 'worker-crashed',\n expected: 'Engine Worker remains alive while the App is running',\n hint: 'inspect the Worker error and create a new App; transferred canvas ownership is terminal',\n detail: { message: event.message },\n partialWrite: false,\n retryable: false,\n };\n for (const listener of listeners) listener(crash);\n return;\n }\n settled = true;\n clearTimeout(timeout);\n worker.terminate();\n resolveReady(\n err(\n startupFault(\n {\n kind: 'fault',\n worldIdentity: null,\n source: 'bootstrap',\n code: 'worker-error',\n expected: 'Engine Worker module loads',\n hint: 'inspect the Worker module graph',\n detail: { message: event.message },\n partialWrite: false,\n retryable: false,\n },\n options.bootstrapUrl,\n ),\n ),\n );\n };\n\n const offscreen = options.canvas.transferControlToOffscreen();\n const init: ExecutionInitMessage = {\n kind: 'init',\n canvas: offscreen,\n bootstrapUrl: options.bootstrapUrl,\n ...(options.bootstrapData === undefined ? {} : { bootstrapData: options.bootstrapData }),\n ...(options.bootstrapPort === undefined ? {} : { bootstrapPort: options.bootstrapPort }),\n ...(options.assetCatalog === undefined ? {} : { assetCatalog: options.assetCatalog }),\n ...(options.shaderManifestUrl !== undefined\n ? { shaderManifestUrl: options.shaderManifestUrl }\n : {}),\n ...(options.time !== undefined ? { time: options.time } : {}),\n tier: options.tier,\n };\n worker.postMessage(init, [\n offscreen,\n ...(options.bootstrapPort === undefined ? [] : [options.bootstrapPort]),\n ]);\n const ready = await readyPromise;\n if (!ready.ok) return ready;\n return ok({\n worker,\n ready: ready.value,\n post(message, transfer = []): void {\n worker.postMessage(message, transfer);\n },\n listen(listener): () => void {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n dispose(): void {\n worker.postMessage({ kind: 'dispose' } satisfies HostToEngineMessage);\n worker.terminate();\n listeners.clear();\n },\n });\n}\n","import type { ExecutionMeasurement } from './types';\n\nfunction percentile(sorted: readonly number[], fraction: number): number {\n const index = Math.min(sorted.length - 1, Math.max(0, Math.ceil(sorted.length * fraction) - 1));\n return sorted[index] ?? 0;\n}\n\nexport interface MeasurementSeries {\n add(value: number): ExecutionMeasurement;\n clear(): void;\n}\n\nexport function createMeasurementSeries(capacity = 240): MeasurementSeries {\n const values: number[] = [];\n let samples = 0;\n return {\n add(value): ExecutionMeasurement {\n samples += 1;\n values.push(value);\n if (values.length > capacity) values.shift();\n const sorted = [...values].sort((a, b) => a - b);\n let jitter = 0;\n for (let index = 1; index < values.length; index += 1) {\n jitter += Math.abs((values[index] ?? 0) - (values[index - 1] ?? 0));\n }\n return {\n samples,\n p50: percentile(sorted, 0.5),\n p95: percentile(sorted, 0.95),\n p99: percentile(sorted, 0.99),\n jitter: values.length < 2 ? 0 : jitter / (values.length - 1),\n };\n },\n clear(): void {\n values.length = 0;\n samples = 0;\n },\n };\n}\n","import type { AudioIntent } from '@forgeax/engine-audio';\nimport type { InputBackendSample } from '@forgeax/engine-input';\nimport type { CanvasDrawingBufferSize } from '../types';\nimport type { ExecutionAssetCatalog } from './types';\n\nexport interface ExecutionFrameMessage {\n readonly kind: 'frame';\n readonly worldIdentity: string;\n readonly frameId: number;\n readonly deltaSeconds: number;\n readonly inputSample: InputBackendSample;\n readonly canvasWidth: number;\n readonly canvasHeight: number;\n}\n\nexport interface ExecutionFrameCompletion {\n readonly kind: 'frame-complete';\n readonly worldIdentity: string;\n readonly frameId: number;\n readonly engineUpdateMs: number;\n readonly kernelWaitMs: number;\n readonly audioIntents?: readonly AudioIntent[];\n readonly kernelDispatch?: {\n readonly eligible: boolean;\n readonly usedShared: boolean;\n readonly reason: import('./types').KernelDispatchReason;\n readonly dispatched: number;\n readonly completed: number;\n };\n}\n\nexport type FrameCompletionDisposition = 'accepted' | 'duplicate' | 'stale-world' | 'late';\n\nexport class FrameCreditLedger {\n private nextFrameId = 1;\n private inFlight: number | null = null;\n private completed = 0;\n\n constructor(readonly worldIdentity: string) {}\n\n issue(\n deltaSeconds: number,\n sampleInput: () => InputBackendSample,\n canvasSize: CanvasDrawingBufferSize = { width: 0, height: 0 },\n ): ExecutionFrameMessage | undefined {\n if (this.inFlight !== null) return undefined;\n const frameId = this.nextFrameId;\n this.nextFrameId += 1;\n this.inFlight = frameId;\n return {\n kind: 'frame',\n worldIdentity: this.worldIdentity,\n frameId,\n deltaSeconds,\n inputSample: sampleInput(),\n canvasWidth: canvasSize.width,\n canvasHeight: canvasSize.height,\n };\n }\n\n complete(message: ExecutionFrameCompletion): FrameCompletionDisposition {\n if (message.worldIdentity !== this.worldIdentity) return 'stale-world';\n if (message.frameId <= this.completed) return 'duplicate';\n if (message.frameId !== this.inFlight) return 'late';\n this.completed = message.frameId;\n this.inFlight = null;\n return 'accepted';\n }\n\n get hasCreditInFlight(): boolean {\n return this.inFlight !== null;\n }\n}\n\nexport interface ExecutionInitMessage {\n readonly kind: 'init';\n readonly canvas: OffscreenCanvas;\n readonly bootstrapUrl: string;\n readonly bootstrapData?: import('./types').ExecutionBootstrapValue;\n readonly bootstrapPort?: MessagePort;\n /** Realm-serializable asset catalog configuration. */\n readonly assetCatalog?: ExecutionAssetCatalog;\n readonly shaderManifestUrl?: string;\n readonly time?: import('@forgeax/engine-ecs').TimePolicy;\n readonly tier: import('./types').ExecutionTier;\n}\n\nexport interface ExecutionHostControlMessage {\n readonly kind: 'host-control';\n readonly command: 'set-pointer-lock-allowed';\n readonly allowed: boolean;\n}\n\nexport interface ExecutionReadyMessage {\n readonly kind: 'ready';\n readonly worldIdentity: string;\n readonly realm: 'worker';\n readonly workerWebGpu: boolean;\n}\n\nexport interface ExecutionFaultMessage {\n readonly kind: 'fault';\n readonly worldIdentity: string | null;\n readonly source: 'bootstrap' | 'handshake' | 'runtime' | 'kernel' | 'world' | 'rebuild';\n readonly code: string;\n readonly expected: string;\n readonly hint: string;\n readonly detail: unknown;\n readonly partialWrite: boolean;\n readonly retryable: boolean;\n}\n\nexport interface ExecutionRebuildMessage {\n readonly kind: 'rebuild';\n readonly worldIdentity: string;\n}\n\nexport interface ExecutionRebuiltMessage {\n readonly kind: 'rebuilt';\n readonly previousWorldIdentity: string;\n readonly worldIdentity: string;\n}\n\nexport type HostToEngineMessage =\n | ExecutionInitMessage\n | ExecutionFrameMessage\n | ExecutionRebuildMessage\n | { readonly kind: 'dispose' };\nexport type EngineToHostMessage =\n | ExecutionReadyMessage\n | ExecutionFrameCompletion\n | ExecutionFaultMessage\n | ExecutionRebuiltMessage\n | ExecutionHostControlMessage;\n","import { createHostAudioConsumer } from '@forgeax/engine-audio-webaudio';\nimport { attachBrowserInputBackend, type InputBackend } from '@forgeax/engine-input';\nimport { err, ok, type Result } from '@forgeax/engine-types';\nimport { APP_ERROR_HINTS, APP_EXPECTED, AppError, type AppError as AppErrorType } from '../errors';\nimport { ErrorFanoutRegistry } from '../internal/error-fanout';\nimport type { BundlerOptions, CanvasDrawingBufferSize } from '../types';\nimport {\n APP_PHASE_CATALOG,\n type AppDispatchError,\n type CreateAppOptions,\n type ExecutionApp,\n} from '../types';\nimport { normalizeExecutionBootstrapUrl } from './bootstrap-url';\nimport { cloneExecutionReport } from './control';\nimport { type EngineWorkerSession, startEngineWorker } from './engine-worker';\nimport { createMeasurementSeries } from './measurement';\nimport {\n type EngineToHostMessage,\n type ExecutionFaultMessage,\n FrameCreditLedger,\n} from './protocol';\nimport { createExecutionReport, executionAudioReport } from './report';\nimport type {\n ExecutionCapabilities,\n ExecutionControl,\n ExecutionReport,\n ExecutionSelection,\n} from './types';\n\nexport interface CreateWorkerExecutionAppOptions {\n readonly canvas: HTMLCanvasElement;\n readonly appOptions: CreateAppOptions;\n /** Host-owned resize policy applied before each frame sent to the worker. */\n readonly syncCanvas?: () => CanvasDrawingBufferSize;\n readonly bundler?: BundlerOptions;\n readonly capabilities: ExecutionCapabilities;\n readonly selection: ExecutionSelection;\n}\n\nfunction lifecycleError(code: 'app-not-started' | 'app-already-running'): AppErrorType {\n return new AppError({\n code,\n expected: APP_EXPECTED[code],\n hint: APP_ERROR_HINTS[code],\n detail: {},\n });\n}\n\nfunction runtimeError(message: ExecutionFaultMessage): AppErrorType {\n if (message.code === 'shared-kernel-failed' && message.worldIdentity !== null) {\n return new AppError({\n code: 'app-execution-kernel-failed',\n expected: APP_EXPECTED['app-execution-kernel-failed'],\n hint: APP_ERROR_HINTS['app-execution-kernel-failed'],\n detail: {\n kernelName: (message.detail as { kernelName?: string })?.kernelName ?? 'unknown',\n worldIdentity: message.worldIdentity,\n cause: message.detail,\n partialWrite: true,\n retryable: false,\n },\n });\n }\n return new AppError({\n code: 'app-system-update-failed',\n expected: APP_EXPECTED['app-system-update-failed'],\n hint: APP_ERROR_HINTS['app-system-update-failed'],\n detail: { cause: message.detail },\n });\n}\n\nexport async function createWorkerExecutionApp(\n options: CreateWorkerExecutionAppOptions,\n): Promise<Result<ExecutionApp, AppErrorType>> {\n const executionOptions = options.appOptions.execution;\n if (executionOptions === undefined) throw new Error('execution options are required');\n const normalizedBootstrap = normalizeExecutionBootstrapUrl(executionOptions.bootstrap);\n if (!normalizedBootstrap.ok) return normalizedBootstrap;\n const bootstrapUrl = normalizedBootstrap.value;\n const startupTimeoutMs = executionOptions.startupTimeoutMs ?? 10_000;\n const frameTimeoutMs = executionOptions.frameTimeoutMs ?? 2_000;\n const syncCanvas = options.syncCanvas;\n const started = await startEngineWorker({\n canvas: options.canvas,\n bootstrapUrl,\n ...(executionOptions.bootstrapData === undefined\n ? {}\n : { bootstrapData: executionOptions.bootstrapData }),\n ...(executionOptions.bootstrapPort === undefined\n ? {}\n : { bootstrapPort: executionOptions.bootstrapPort }),\n ...(executionOptions.assetCatalog === undefined\n ? {}\n : { assetCatalog: executionOptions.assetCatalog }),\n ...(options.bundler?.shaderManifestUrl !== undefined\n ? { shaderManifestUrl: options.bundler.shaderManifestUrl }\n : {}),\n ...(options.appOptions.time !== undefined ? { time: options.appOptions.time } : {}),\n timeoutMs: startupTimeoutMs,\n tier: options.selection.actualTier,\n });\n if (!started.ok) return started;\n\n const session: EngineWorkerSession = started.value;\n const profiler = options.appOptions.profiler;\n const phaseCatalogRegistration = profiler?.registerPhaseCatalog('app', APP_PHASE_CATALOG);\n let releasePhaseCatalog =\n phaseCatalogRegistration?.ok === true ? phaseCatalogRegistration.value : undefined;\n const fanout = new ErrorFanoutRegistry(\n options.appOptions.silenceUnhandledErrors === undefined\n ? {}\n : { silenceUnhandledErrors: options.appOptions.silenceUnhandledErrors },\n );\n const inputHandle =\n options.appOptions.input === undefined\n ? attachBrowserInputBackend(options.canvas, {\n ...(options.appOptions.uiRoot !== undefined ? { uiRoot: options.appOptions.uiRoot } : {}),\n ...(options.appOptions.pointerLockAllowed !== undefined\n ? { pointerLockAllowed: options.appOptions.pointerLockAllowed }\n : {}),\n ...(options.appOptions.virtualJoysticks !== undefined\n ? { virtualJoysticks: options.appOptions.virtualJoysticks }\n : {}),\n ...(options.appOptions.lockProvider !== undefined\n ? { lockProvider: options.appOptions.lockProvider }\n : {}),\n onLockError: (detail) =>\n fanout.fire(\n new AppError({\n code: 'app-pointer-lock-failed',\n expected: APP_EXPECTED['app-pointer-lock-failed'],\n hint: APP_ERROR_HINTS['app-pointer-lock-failed'],\n detail,\n }),\n ),\n })\n : undefined;\n const input: InputBackend = options.appOptions.input ??\n inputHandle?.backend ?? {\n sample: () => ({\n downKeys: new Set(),\n upKeys: new Set(),\n buttons: [false, false, false],\n movementX: 0,\n movementY: 0,\n wheelDelta: 0,\n focused: true,\n pointerLocked: false,\n }),\n detach: () => {},\n };\n\n let report: ExecutionReport = {\n ...createExecutionReport(\n executionOptions.tier ?? 'auto',\n options.capabilities,\n options.selection,\n ),\n engine: { realm: 'worker', health: 'idle' },\n world: {\n identity: session.ready.worldIdentity,\n health: 'healthy',\n partialWrite: false,\n retryable: true,\n },\n };\n let state: 'idle' | 'running' | 'paused' | 'stopped' | 'faulted' = 'idle';\n let ledger = new FrameCreditLedger(session.ready.worldIdentity);\n let rafId = 0;\n let lastTimestamp = 0;\n let frameDeadline: ReturnType<typeof setTimeout> | undefined;\n let lastError: AppDispatchError | undefined;\n let rebuildResolve: ((result: Result<ExecutionReport, AppErrorType>) => void) | undefined;\n let rebuildInFlight: Promise<Result<ExecutionReport, AppErrorType>> | undefined;\n const hostFrameMeasurements = createMeasurementSeries();\n const engineMeasurements = createMeasurementSeries();\n const kernelMeasurements = createMeasurementSeries();\n const audioMeasurements = createMeasurementSeries();\n let audio = createHostAudioConsumer();\n let frameSentAt = 0;\n let profilerCaptureId: string | undefined;\n let profilerFrameId = 0;\n let frameProfile = profiler?.activeSession();\n let profileFrameOpen = false;\n let hostFrameOpen = false;\n\n const setEngineHealth = (health: ExecutionReport['engine']['health']): void => {\n report = { ...report, engine: { ...report.engine, health } };\n };\n\n const finishProfile = (): void => {\n if (hostFrameOpen) frameProfile?.endPhase();\n if (profileFrameOpen) frameProfile?.endFrame();\n frameProfile = undefined;\n profileFrameOpen = false;\n hostFrameOpen = false;\n try {\n profiler?.activeSession()?.finish();\n } catch {}\n releasePhaseCatalog?.();\n releasePhaseCatalog = undefined;\n };\n\n const terminalFault = (message: ExecutionFaultMessage): void => {\n if (frameDeadline !== undefined) {\n clearTimeout(frameDeadline);\n frameDeadline = undefined;\n }\n const error = runtimeError(message);\n lastError = error;\n state = message.partialWrite ? 'faulted' : 'stopped';\n report = {\n ...report,\n engine: { ...report.engine, health: 'faulted' },\n world: {\n identity: message.worldIdentity,\n health: message.partialWrite ? 'poisoned' : report.world.health,\n partialWrite: message.partialWrite,\n retryable: message.retryable,\n },\n kernelDispatch: {\n ...report.kernelDispatch,\n reason: message.partialWrite ? 'poisoned' : report.kernelDispatch.reason,\n },\n fault: {\n source: message.source,\n code: message.code,\n expected: message.expected,\n hint: message.hint,\n detail: message.detail,\n partialWrite: message.partialWrite,\n retryable: message.retryable,\n },\n };\n fanout.fire(error);\n if (!message.partialWrite) {\n audio.dispose();\n session.dispose();\n }\n finishProfile();\n };\n\n const scheduleFrame = (): void => {\n rafId = requestAnimationFrame((timestamp) => {\n if (state !== 'running') return;\n const deltaSeconds =\n lastTimestamp === 0 ? 0 : Math.max(0, (timestamp - lastTimestamp) / 1_000);\n lastTimestamp = timestamp;\n const canvasSize =\n syncCanvas?.() ??\n ({\n width: options.canvas.width,\n height: options.canvas.height,\n } satisfies CanvasDrawingBufferSize);\n const frame = ledger.issue(deltaSeconds, () => input.sample(), canvasSize);\n if (frame === undefined) return;\n frameProfile = profiler?.activeSession();\n if (frameProfile !== undefined && profilerCaptureId !== frameProfile.captureId) {\n profilerCaptureId = frameProfile.captureId;\n profilerFrameId = 0;\n }\n profileFrameOpen = frameProfile?.beginFrame(++profilerFrameId).ok ?? false;\n hostFrameOpen = profileFrameOpen\n ? (frameProfile?.beginPhase('app', 'host-frame').ok ?? false)\n : false;\n session.post(frame);\n frameSentAt = performance.now();\n frameDeadline = setTimeout(() => {\n if (state !== 'running') return;\n terminalFault({\n kind: 'fault',\n worldIdentity: report.world.identity,\n source: 'runtime',\n code: 'app-execution-deadline-exceeded',\n expected: APP_EXPECTED['app-execution-deadline-exceeded'],\n hint: APP_ERROR_HINTS['app-execution-deadline-exceeded'],\n detail: { phase: 'frame', timeoutMs: frameTimeoutMs },\n partialWrite: false,\n retryable: false,\n });\n }, frameTimeoutMs);\n });\n };\n\n session.listen((message: EngineToHostMessage) => {\n if (message.kind === 'frame-complete') {\n if (ledger.complete(message) !== 'accepted') return;\n if (frameDeadline !== undefined) clearTimeout(frameDeadline);\n if (hostFrameOpen) frameProfile?.endPhase();\n if (profileFrameOpen) {\n frameProfile?.recordSkip({\n source: 'app',\n phase: 'engine-update',\n reason: `worker-report:${message.engineUpdateMs.toFixed(3)}ms`,\n });\n frameProfile?.recordSkip({\n source: 'app',\n phase: 'kernel-wait',\n reason: `worker-report:${message.kernelWaitMs.toFixed(3)}ms`,\n });\n }\n const audioStarted = performance.now();\n const audioProfileOpen = profileFrameOpen\n ? (frameProfile?.beginPhase('app', 'host-audio').ok ?? false)\n : false;\n for (const intent of message.audioIntents ?? []) audio.consume(intent);\n if (audioProfileOpen) frameProfile?.endPhase();\n const audioMs = performance.now() - audioStarted;\n report = {\n ...report,\n performance: {\n ...report.performance,\n hostFrameMs: hostFrameMeasurements.add(performance.now() - frameSentAt),\n engineUpdateMs: engineMeasurements.add(message.engineUpdateMs),\n kernelWaitMs: kernelMeasurements.add(message.kernelWaitMs),\n hostAudioMs: audioMeasurements.add(audioMs),\n },\n };\n if (message.kernelDispatch !== undefined) {\n report = { ...report, kernelDispatch: message.kernelDispatch };\n }\n if (profileFrameOpen) frameProfile?.endFrame();\n frameProfile = undefined;\n profileFrameOpen = false;\n hostFrameOpen = false;\n if (state === 'running') scheduleFrame();\n } else if (message.kind === 'fault') {\n terminalFault(message);\n } else if (message.kind === 'rebuilt') {\n audio.dispose();\n audio = createHostAudioConsumer();\n ledger = new FrameCreditLedger(message.worldIdentity);\n hostFrameMeasurements.clear();\n engineMeasurements.clear();\n kernelMeasurements.clear();\n audioMeasurements.clear();\n state = 'idle';\n report = {\n ...report,\n engine: { ...report.engine, health: 'idle' },\n world: {\n identity: message.worldIdentity,\n health: 'healthy',\n partialWrite: false,\n retryable: true,\n },\n kernelDispatch: {\n eligible: false,\n usedShared: false,\n reason: 'no-eligible-kernel',\n dispatched: 0,\n completed: 0,\n },\n fault: null,\n performance: {\n hostFrameMs: null,\n engineUpdateMs: null,\n kernelWaitMs: null,\n hostAudioMs: null,\n },\n };\n rebuildResolve?.(ok(cloneExecutionReport(report)));\n rebuildResolve = undefined;\n rebuildInFlight = undefined;\n } else if (message.kind === 'host-control') {\n if (message.command === 'set-pointer-lock-allowed') {\n input.setPointerLockAllowed?.(message.allowed);\n }\n }\n });\n\n const execution: ExecutionControl = {\n report: () =>\n cloneExecutionReport({\n ...report,\n audio: executionAudioReport(audio.state()),\n }),\n rebuild: () => {\n if (rebuildInFlight !== undefined) return rebuildInFlight;\n if (state !== 'faulted' || report.world.identity === null) {\n return Promise.resolve(\n err(\n new AppError({\n code: 'app-execution-rebuild-failed',\n expected: APP_EXPECTED['app-execution-rebuild-failed'],\n hint: APP_ERROR_HINTS['app-execution-rebuild-failed'],\n detail: {\n worldIdentity: report.world.identity,\n cause: new Error('World is not in a rebuildable poisoned state.'),\n },\n }),\n ),\n );\n }\n rebuildInFlight = new Promise((resolve) => {\n rebuildResolve = resolve;\n session.post({ kind: 'rebuild', worldIdentity: report.world.identity as string });\n setTimeout(() => {\n if (rebuildResolve !== resolve) return;\n rebuildResolve = undefined;\n rebuildInFlight = undefined;\n resolve(\n err(\n new AppError({\n code: 'app-execution-deadline-exceeded',\n expected: APP_EXPECTED['app-execution-deadline-exceeded'],\n hint: APP_ERROR_HINTS['app-execution-deadline-exceeded'],\n detail: { phase: 'handshake', timeoutMs: startupTimeoutMs },\n }),\n ),\n );\n }, startupTimeoutMs);\n });\n return rebuildInFlight;\n },\n };\n\n const app: ExecutionApp = {\n execution,\n input,\n start: () => {\n if (state === 'running') return err(lifecycleError('app-already-running'));\n if (state === 'stopped' || state === 'faulted') return err(lifecycleError('app-not-started'));\n state = 'running';\n setEngineHealth('running');\n lastTimestamp = 0;\n scheduleFrame();\n return ok(undefined);\n },\n stop: () => {\n if (state !== 'running' && state !== 'paused') return err(lifecycleError('app-not-started'));\n if (state === 'running') cancelAnimationFrame(rafId);\n state = 'stopped';\n inputHandle?.();\n audio.dispose();\n session.dispose();\n setEngineHealth('stopped');\n finishProfile();\n return ok(undefined);\n },\n pause: () => {\n if (state !== 'running') return err(lifecycleError('app-not-started'));\n state = 'paused';\n cancelAnimationFrame(rafId);\n return ok(undefined);\n },\n resume: () => {\n if (state !== 'paused') return err(lifecycleError('app-not-started'));\n state = 'running';\n lastTimestamp = 0;\n scheduleFrame();\n return ok(undefined);\n },\n onError: (listener) => fanout.add(listener),\n get lastError() {\n return lastError;\n },\n };\n return ok(app);\n}\n","import type { Plugin } from '@forgeax/engine-plugin';\nimport type { RenderError, Renderer, RenderFeature, RenderResult } from '@forgeax/engine-render';\nimport type { RendererFeatureAssemblyHost } from '@forgeax/engine-render/internal/construct-renderer';\n\nexport interface RenderFeatureHost {\n installFeature(\n feature: RenderFeature<unknown>,\n ): Promise<RenderResult<RenderFeatureLease, RenderError>>;\n}\n\nexport interface RenderFeatureLease {\n release(): Promise<RenderResult<void, RenderError>>;\n}\n\nexport function createRenderFeatureHost(host: RendererFeatureAssemblyHost): RenderFeatureHost {\n return {\n async installFeature(feature) {\n const installed = await host.installRenderFeature(feature);\n if (!installed.ok) return installed;\n let released = false;\n return {\n ok: true,\n value: {\n release: async () => {\n if (released) return { ok: true, value: undefined };\n released = true;\n return host.uninstallRenderFeature(feature);\n },\n },\n };\n },\n };\n}\n\ndeclare module '@forgeax/engine-plugin' {\n interface EngineContextServices {\n renderer?: Renderer;\n renderFeatureHost?: RenderFeatureHost;\n }\n}\n\n/** Provide the renderer without transferring its host-owned lifetime. */\nexport function rendererPlugin(renderer: Renderer): Plugin {\n return {\n name: 'renderer',\n provide: 'renderer',\n apply(ctx) {\n ctx.provide('renderer', renderer);\n },\n };\n}\n\n/** Provide an App/Worker-owned Renderer and release it after dependent Fibers. */\nexport function ownedRendererPlugin(renderer: Renderer): Plugin {\n return {\n name: 'renderer',\n provide: 'renderer',\n apply(ctx) {\n ctx.provide('renderer', renderer);\n ctx.effect(() => () => renderer.dispose(), 'render/renderer');\n },\n };\n}\n\n/** Provide the App-owned late RenderFeature assembly capability. */\nexport function renderFeatureHostPlugin(host: RenderFeatureHost): Plugin {\n return {\n name: 'render-feature-host',\n provide: 'renderFeatureHost',\n apply(ctx) {\n ctx.provide('renderFeatureHost', host);\n },\n };\n}\n\n/** Install a producer feature under the same Cordis Fiber that owns the caller. */\nexport function renderFeaturePlugin(feature: RenderFeature<unknown>): Plugin {\n return {\n name: `render-feature:${feature.identity}`,\n inject: ['renderFeatureHost'],\n async apply(ctx) {\n if (ctx.renderFeatureHost === undefined) {\n throw new Error('render-feature host capability is unavailable in this App realm');\n }\n const installed = await ctx.renderFeatureHost.installFeature(feature);\n if (!installed.ok) throw installed.error;\n ctx.effect(\n () => async () => {\n const removed = await installed.value.release();\n if (!removed.ok) throw removed.error;\n },\n `render-feature/${feature.identity}`,\n );\n },\n };\n}\n","import type { AssetRegistry } from '@forgeax/engine-assets-runtime';\nimport type { Plugin } from '@forgeax/engine-plugin';\n\nconst ASSET_REGISTRY_RESOURCE_KEY = 'AssetRegistry' as const;\n\n/** Project the Renderer-owned AssetRegistry as a declared dependent service. */\nexport function rendererAssetsPlugin(assets: AssetRegistry | undefined): Plugin {\n return {\n name: 'renderer-assets',\n inject: ['renderer'],\n provide: 'assets',\n apply(ctx) {\n if (assets !== undefined) ctx.provide('assets', assets);\n },\n };\n}\n\n/** Project the realm AssetRegistry into legacy World resource lookup reversibly. */\nexport function assetsWorldPlugin(): Plugin {\n return {\n name: 'assets-world',\n inject: ['world', 'assets'],\n apply(ctx) {\n if (ctx.assets === undefined) return;\n ctx.effect(() => {\n ctx.world.insertResource(ASSET_REGISTRY_RESOURCE_KEY, ctx.assets);\n return () => {\n ctx.world.removeResource(ASSET_REGISTRY_RESOURCE_KEY);\n };\n }, 'assets/world-resource');\n },\n };\n}\n","import type { Plugin } from '@forgeax/engine-plugin';\nimport { rendererPlugin } from '../renderer-plugin';\nimport { assetsWorldPlugin, rendererAssetsPlugin } from './assets-world-plugin';\nimport type { EngineProfileBase } from './engine-profile-common';\n\n/** Assemble-form roots plus explicitly selected host capabilities. */\nexport function assembledEngineProfile(options: EngineProfileBase): Plugin[] {\n return [\n rendererPlugin(options.renderer),\n rendererAssetsPlugin(options.assets),\n assetsWorldPlugin(),\n ...(options.extensions ?? []),\n ];\n}\n","import { type Component, componentDefinition, type FieldReflection } from '@forgeax/engine-ecs';\nimport { componentSchema } from '@forgeax/engine-ecs/internal';\n\nexport type JsonValue =\n | null\n | boolean\n | number\n | string\n | readonly JsonValue[]\n | { readonly [key: string]: JsonValue };\n\nexport interface ComponentIntrospectionField {\n readonly type: string;\n readonly default?: JsonValue;\n readonly shape?: string;\n readonly transient?: boolean;\n readonly arrayMeta?: {\n readonly elementType: string;\n readonly length?: number;\n };\n readonly labels?: Readonly<Record<string, number>>;\n}\n\nexport interface ComponentIntrospectionDescriptor {\n readonly name: string;\n readonly schema: Readonly<Record<string, string>>;\n readonly fields: Readonly<Record<string, ComponentIntrospectionField>>;\n readonly meta: Readonly<Record<string, JsonValue>>;\n}\n\nfunction projectJson(value: unknown, seen: Set<object>): JsonValue | undefined {\n if (value === null) return null;\n if (typeof value === 'boolean' || typeof value === 'string') return value;\n if (typeof value === 'number') return Number.isFinite(value) ? value : undefined;\n if (typeof value !== 'object') return undefined;\n if (seen.has(value)) return undefined;\n seen.add(value);\n\n if (ArrayBuffer.isView(value)) {\n const values = Array.from(value as unknown as ArrayLike<unknown>);\n const projected = values.map((entry) => projectJson(entry, seen));\n seen.delete(value);\n return projected.every((entry) => entry !== undefined) ? (projected as JsonValue[]) : undefined;\n }\n if (Array.isArray(value)) {\n const projected = value.map((entry) => projectJson(entry, seen));\n seen.delete(value);\n return projected.every((entry) => entry !== undefined) ? (projected as JsonValue[]) : undefined;\n }\n\n const object: Record<string, JsonValue> = {};\n for (const [key, entry] of Object.entries(value)) {\n const projected = projectJson(entry, seen);\n if (projected !== undefined) object[key] = projected;\n }\n seen.delete(value);\n return object;\n}\n\nfunction isJsonRecord(\n value: JsonValue | undefined,\n): value is { readonly [key: string]: JsonValue } {\n return (\n value !== undefined && value !== null && typeof value === 'object' && !Array.isArray(value)\n );\n}\n\nfunction projectMeta(meta: Readonly<Record<string, unknown>>): Readonly<Record<string, JsonValue>> {\n const projected = projectJson(meta, new Set<object>());\n return isJsonRecord(projected) ? projected : {};\n}\n\nfunction projectField(reflection: FieldReflection): ComponentIntrospectionField {\n const field: ComponentIntrospectionField = { type: reflection.type };\n const defaultValue = projectJson(reflection.default, new Set<object>());\n if (defaultValue !== undefined) Object.assign(field, { default: defaultValue });\n if (reflection.shape !== undefined) Object.assign(field, { shape: reflection.shape });\n if (reflection.transient !== undefined) Object.assign(field, { transient: reflection.transient });\n if (reflection.arrayMeta !== undefined) {\n Object.assign(field, {\n arrayMeta: {\n elementType: reflection.arrayMeta.elementType,\n ...(reflection.arrayMeta.length !== undefined\n ? { length: reflection.arrayMeta.length }\n : {}),\n },\n });\n }\n if (reflection.labels !== undefined) Object.assign(field, { labels: { ...reflection.labels } });\n return Object.freeze(field);\n}\n\nfunction projectComponent(component: Component): ComponentIntrospectionDescriptor {\n const definition = componentDefinition(component);\n const fields: Record<string, ComponentIntrospectionField> = {};\n for (const [name, reflection] of Object.entries(definition.fields)) {\n fields[name] = projectField(reflection);\n }\n return Object.freeze({\n name: component.name,\n schema: Object.freeze({ ...componentSchema(component) }),\n fields: Object.freeze(fields),\n meta: Object.freeze(projectMeta(definition.policy.meta)),\n });\n}\n\n/** Project one World-local component catalog into transport-safe data. */\nexport function projectComponentIntrospection(\n components: ReadonlyMap<string, Component>,\n): readonly ComponentIntrospectionDescriptor[] {\n return Object.freeze(\n [...components.values()]\n .sort((left, right) => left.name.localeCompare(right.name))\n .map(projectComponent),\n );\n}\n","import type { World } from '@forgeax/engine-ecs';\nimport type { ProfileFrameToken, Profiler, RecorderSession } from '@forgeax/engine-profiler';\nimport type { RenderError, Renderer, RenderWorldLease } from '@forgeax/engine-render';\nimport { err, ok, type Result } from '@forgeax/engine-types';\n\nimport type { AppErrorCode, AppErrorDetailFor } from '../errors';\nimport { AppError } from '../errors';\nimport { APP_PHASE_CATALOG } from '../types';\n\nexport type FrameState = 'idle' | 'running' | 'paused' | 'stopped';\n\nexport interface FrameLoopOptions {\n readonly world: World;\n readonly renderer: Renderer;\n readonly onError?: (e: AppError | RenderError) => void;\n /** Optional dev-only RHI recorder hook; called once after each frame draw. */\n readonly debugRhi?: { onFrameEnd(): void };\n readonly now?: () => number;\n readonly raf?: (cb: (t: number) => void) => number;\n readonly caf?: (id: number) => void;\n readonly profiler?: Profiler;\n readonly drawSource?: () =>\n | { worlds: readonly World[]; cameraOwner: number; resourceOwner: number }\n | undefined;\n}\n\nexport interface FrameLoopHandle {\n start(): Result<void, AppError>;\n stop(): Result<void, AppError>;\n pause(): Result<void, AppError>;\n resume(): Result<void, AppError>;\n /** Run one complete update/draw frame through this loop while paused. */\n stepFrame(deltaSeconds: number): Result<void, AppError | RenderError>;\n /** Replace the per-frame world routing pull without replacing the loop. */\n setDrawSource(drawSource: FrameLoopOptions['drawSource']): void;\n getState(): FrameState;\n setStopped(): void;\n}\n\nfunction beginFrame(session: RecorderSession | undefined, frameId: number): boolean {\n if (session === undefined) return false;\n try {\n return session.beginFrame(frameId).ok;\n } catch {\n return false;\n }\n}\n\nfunction beginPhase(session: RecorderSession | undefined, phase: string): boolean {\n if (session === undefined) return false;\n try {\n return session.beginPhase('app', phase).ok;\n } catch {\n return false;\n }\n}\n\nfunction endPhase(session: RecorderSession | undefined): void {\n if (session === undefined) return;\n try {\n session.endPhase();\n } catch {\n // Profiler failures never alter the host loop.\n }\n}\n\nfunction endFrame(session: RecorderSession | undefined): void {\n if (session === undefined) return;\n try {\n session.endFrame();\n } catch {\n // Profiler failures never alter the host loop.\n }\n}\n\nfunction finishProfilerCapture(profiler: Profiler | undefined): void {\n const session = profiler?.activeSession();\n if (session === undefined) return;\n try {\n session.finish();\n } catch {\n // Profiler failures never alter the host stop transition.\n }\n}\n\nfunction makeAppError<C extends AppErrorCode>(\n code: C,\n expected: string,\n hint: string,\n detail: AppErrorDetailFor<C>,\n): AppError {\n return new AppError({ code, expected, hint, detail }) as AppError;\n}\n\nfunction makeWorldUpdateError(cause: unknown): AppError {\n return makeAppError(\n 'app-system-update-failed',\n 'world.update(deltaSeconds) completes successfully',\n 'check detail.cause for the original structured ECS error',\n { cause },\n );\n}\n\nfunction fireWorldUpdateResult(\n result: ReturnType<World['update']>,\n fireError: ((e: AppError | RenderError) => void) | undefined,\n): boolean {\n if (!result.ok && fireError !== undefined) {\n fireError(makeWorldUpdateError(result.error));\n }\n return result.ok;\n}\n\nfunction updateInjectedWorlds(\n worlds: readonly World[],\n ownWorld: World,\n deltaSeconds: number,\n fireError: ((e: AppError | RenderError) => void) | undefined,\n attachedWorlds: ReadonlySet<World>,\n updatedWorlds: Set<World>,\n): void {\n for (const injectedWorld of worlds) {\n if (\n injectedWorld === ownWorld ||\n updatedWorlds.has(injectedWorld) ||\n !attachedWorlds.has(injectedWorld)\n ) {\n continue;\n }\n try {\n if (fireWorldUpdateResult(injectedWorld.update(deltaSeconds), fireError)) {\n updatedWorlds.add(injectedWorld);\n }\n } catch (cause: unknown) {\n if (fireError !== undefined) fireError(makeWorldUpdateError(cause));\n }\n }\n}\n\nfunction resolveNow(opts: FrameLoopOptions): () => number {\n if (opts.now !== undefined) return opts.now;\n return () => {\n const perf = (globalThis as { performance?: { now?: () => number } }).performance;\n const fn = perf?.now;\n return typeof fn === 'function' ? fn.call(perf) : Date.now();\n };\n}\n\nfunction resolveRaf(opts: FrameLoopOptions): (cb: (t: number) => void) => number {\n if (opts.raf !== undefined) return opts.raf;\n const g = globalThis as { requestAnimationFrame?: (cb: (t: number) => void) => number };\n return typeof g.requestAnimationFrame === 'function'\n ? g.requestAnimationFrame.bind(globalThis)\n : () => 0;\n}\n\nfunction resolveCaf(opts: FrameLoopOptions): (id: number) => void {\n if (opts.caf !== undefined) return opts.caf;\n const g = globalThis as { cancelAnimationFrame?: (id: number) => void };\n return typeof g.cancelAnimationFrame === 'function'\n ? g.cancelAnimationFrame.bind(globalThis)\n : () => {};\n}\n\nexport function createFrameLoop(opts: FrameLoopOptions): FrameLoopHandle {\n const { world, renderer } = opts;\n const phaseCatalogRegistration = opts.profiler?.registerPhaseCatalog('app', APP_PHASE_CATALOG);\n let releasePhaseCatalog =\n phaseCatalogRegistration?.ok === true ? phaseCatalogRegistration.value : undefined;\n let drawSource = opts.drawSource;\n const now = resolveNow(opts);\n const raf = resolveRaf(opts);\n const caf = resolveCaf(opts);\n\n let state: FrameState = 'idle';\n let lastTimestamp = 0;\n let pendingFrameId = 0;\n let profilerFrameId = 0;\n let profilerCaptureId: string | undefined;\n const leases = new Map<World, RenderWorldLease>();\n\n function attachPrimary(fireError: (e: AppError | RenderError) => void): void {\n if (leases.has(world)) return;\n try {\n const result = renderer.attach(world);\n if (result.ok) leases.set(world, result.value);\n else fireError(result.error);\n } catch (cause: unknown) {\n fireError(makeWorldUpdateError(cause));\n }\n }\n\n function syncInjectedAttachments(\n worlds: readonly World[] | undefined,\n fireError?: (e: AppError | RenderError) => void,\n ): ReadonlySet<World> | undefined {\n if (worlds === undefined) {\n for (const [attached, lease] of leases) {\n if (attached !== world) {\n lease.dispose();\n leases.delete(attached);\n }\n }\n return undefined;\n }\n\n const next = new Set<World>();\n for (const candidate of worlds) {\n if (candidate === world || next.has(candidate)) continue;\n if (leases.has(candidate)) {\n next.add(candidate);\n continue;\n }\n try {\n const result = renderer.attach(candidate);\n if (result.ok) {\n leases.set(candidate, result.value);\n next.add(candidate);\n } else fireError?.(result.error);\n } catch (cause: unknown) {\n fireError?.(makeWorldUpdateError(cause));\n }\n }\n for (const [attached, lease] of leases) {\n if (attached !== world && !next.has(attached)) {\n lease.dispose();\n leases.delete(attached);\n }\n }\n return next;\n }\n\n function releaseInjectedAttachments(): void {\n syncInjectedAttachments(undefined);\n }\n\n function releaseAttachments(): void {\n releaseInjectedAttachments();\n const lease = leases.get(world);\n if (lease !== undefined) {\n lease.dispose();\n leases.delete(world);\n }\n }\n\n function runProfiledPhase<T>(\n session: RecorderSession | undefined,\n phase: string,\n action: () => T,\n ): T {\n const opened = beginPhase(session, phase);\n try {\n return action();\n } finally {\n if (opened) endPhase(session);\n }\n }\n\n function runFrame(deltaSeconds: number): Result<void, AppError | RenderError> {\n const session = opts.profiler?.activeSession();\n let profileFrame: ProfileFrameToken | undefined;\n let frameError: AppError | RenderError | undefined;\n let primaryUpdated = false;\n const reportError = (error: AppError | RenderError): void => {\n frameError ??= error;\n opts.onError?.(error);\n };\n if (session !== undefined) {\n if (profilerCaptureId !== session.captureId) {\n profilerCaptureId = session.captureId;\n profilerFrameId = 0;\n }\n const frameId = ++profilerFrameId;\n if (beginFrame(session, frameId)) {\n profileFrame = { captureId: session.captureId, frameId };\n }\n }\n\n runProfiledPhase(session, 'frame-total', () => {\n attachPrimary(reportError);\n\n runProfiledPhase(session, 'world-update-primary', () => {\n try {\n if (fireWorldUpdateResult(world.update(deltaSeconds), reportError)) {\n primaryUpdated = true;\n }\n } catch (cause: unknown) {\n reportError(makeWorldUpdateError(cause));\n }\n });\n\n let injected:\n | { worlds: readonly World[]; cameraOwner: number; resourceOwner: number }\n | undefined;\n runProfiledPhase(session, 'draw-source', () => {\n if (drawSource === undefined) return;\n try {\n injected = drawSource();\n } catch (cause: unknown) {\n reportError(makeWorldUpdateError(cause));\n }\n });\n\n const attachedInjectedWorlds = syncInjectedAttachments(injected?.worlds, reportError);\n const updatedWorlds = injected === undefined ? undefined : new Set<World>();\n if (updatedWorlds !== undefined && primaryUpdated && leases.has(world)) {\n updatedWorlds.add(world);\n }\n\n runProfiledPhase(session, 'world-update-injected', () => {\n if (\n injected !== undefined &&\n attachedInjectedWorlds !== undefined &&\n updatedWorlds !== undefined\n ) {\n updateInjectedWorlds(\n injected.worlds,\n world,\n deltaSeconds,\n reportError,\n attachedInjectedWorlds,\n updatedWorlds,\n );\n }\n });\n\n runProfiledPhase(session, 'renderer-draw', () => {\n try {\n let drawResult: ReturnType<Renderer['draw']>;\n if (injected === undefined) {\n const primaryLease = leases.get(world);\n if (!primaryUpdated || primaryLease === undefined) return;\n drawResult = renderer.draw({\n leases: [primaryLease],\n camera: { lease: primaryLease },\n environment: { lease: primaryLease },\n ...(profileFrame === undefined ? {} : { profileFrame }),\n });\n } else {\n if (updatedWorlds === undefined) return;\n const readyEntries = injected.worlds\n .filter((candidate) => updatedWorlds.has(candidate))\n .map((candidate) => ({ candidate, lease: leases.get(candidate) }))\n .filter(\n (entry): entry is { candidate: World; lease: RenderWorldLease } =>\n entry.lease !== undefined,\n );\n const readyLeases = readyEntries.map((entry) => entry.lease);\n const cameraWorld = injected.worlds[injected.cameraOwner];\n const environmentWorld = injected.worlds[injected.resourceOwner];\n if (cameraWorld === undefined || environmentWorld === undefined) return;\n const cameraLease = leases.get(cameraWorld);\n const environmentLease = leases.get(environmentWorld);\n if (\n readyLeases.length === 0 ||\n cameraLease === undefined ||\n environmentLease === undefined\n )\n return;\n drawResult = renderer.draw({\n leases: readyLeases,\n camera: { lease: cameraLease },\n environment: { lease: environmentLease },\n ...(profileFrame === undefined ? {} : { profileFrame }),\n });\n }\n if (drawResult !== undefined) {\n const result = drawResult as { ok: boolean; error?: RenderError };\n if (!result.ok && result.error !== undefined) {\n reportError(result.error);\n }\n }\n } catch (cause: unknown) {\n reportError(makeWorldUpdateError(cause));\n }\n });\n });\n endFrame(session);\n try {\n opts.debugRhi?.onFrameEnd();\n } catch {\n // Debug capture is an observational bridge. A recorder failure must not\n // change the App frame result or make the host loop stop.\n }\n return frameError === undefined ? ok(undefined) : err(frameError);\n }\n\n function tick(): void {\n if (state !== 'running') return;\n\n // Device loss is a renderer-owned degraded interval, not an application\n // stop. Keep the rAF heartbeat alive while the host performs the explicit\n // Renderer.recover() rebuild, but freeze simulation so recovery does not\n // advance the World against frames that cannot be submitted. The next\n // tick observes `alive` and resumes the normal update/draw sequence.\n const timestamp = now();\n const deltaSeconds = (timestamp - lastTimestamp) / 1000;\n lastTimestamp = timestamp;\n runFrame(deltaSeconds);\n pendingFrameId = raf(tick);\n }\n\n function releaseProfiler(): void {\n finishProfilerCapture(opts.profiler);\n releasePhaseCatalog?.();\n releasePhaseCatalog = undefined;\n }\n\n return {\n setDrawSource(nextDrawSource): void {\n if (drawSource !== nextDrawSource) syncInjectedAttachments(undefined);\n drawSource = nextDrawSource;\n },\n stepFrame(deltaSeconds): Result<void, AppError | RenderError> {\n const reason =\n state !== 'paused'\n ? 'state'\n : !Number.isFinite(deltaSeconds) || deltaSeconds < 0\n ? 'delta'\n : undefined;\n if (reason !== undefined) {\n return err(\n makeAppError(\n 'app-frame-step-invalid',\n 'state is \"paused\" and deltaSeconds is finite and non-negative',\n 'pause the App and pass a finite non-negative delta before retrying',\n { state, deltaSeconds, reason },\n ),\n );\n }\n return runFrame(deltaSeconds);\n },\n start(): Result<void, AppError> {\n if (state === 'running') {\n return err(\n makeAppError(\n 'app-already-running',\n 'state must be \"idle\" or \"paused\" to start',\n 'call stop() first or check getState() before retrying',\n {},\n ),\n );\n }\n if (state === 'stopped') {\n return err(\n makeAppError(\n 'app-not-started',\n 'frame-loop is in terminal \"stopped\" state',\n 'create a new App via createApp({...}); the existing handle is dead',\n {},\n ),\n );\n }\n lastTimestamp = now();\n state = 'running';\n pendingFrameId = raf(tick);\n return ok(undefined);\n },\n\n stop(): Result<void, AppError> {\n if (state === 'idle') {\n return err(\n makeAppError(\n 'app-not-started',\n 'state must be \"running\" to stop',\n 'check getState() before calling stop(); idle handles cannot stop',\n {},\n ),\n );\n }\n if (state === 'stopped') {\n return err(\n makeAppError(\n 'app-not-started',\n 'frame-loop is in terminal \"stopped\" state',\n 'discard this handle and create a new App',\n {},\n ),\n );\n }\n caf(pendingFrameId);\n pendingFrameId = 0;\n state = 'stopped';\n releaseAttachments();\n releaseProfiler();\n return ok(undefined);\n },\n\n pause(): Result<void, AppError> {\n if (state === 'paused') return ok(undefined);\n if (state !== 'running') {\n return err(\n makeAppError(\n 'app-not-started',\n 'state must be \"running\" or \"paused\" to pause',\n 'call start() first; idle handles cannot pause',\n {},\n ),\n );\n }\n caf(pendingFrameId);\n pendingFrameId = 0;\n state = 'paused';\n return ok(undefined);\n },\n\n resume(): Result<void, AppError> {\n if (state === 'idle' || state === 'stopped') {\n return err(\n makeAppError(\n 'app-not-started',\n 'state must be \"paused\" to resume',\n 'call start() first to leave idle; resume() expects an active handle',\n {},\n ),\n );\n }\n if (state === 'running') return ok(undefined);\n lastTimestamp = now();\n state = 'running';\n pendingFrameId = raf(tick);\n return ok(undefined);\n },\n\n getState(): FrameState {\n return state;\n },\n\n setStopped(): void {\n if (pendingFrameId !== 0) {\n caf(pendingFrameId);\n pendingFrameId = 0;\n }\n releaseAttachments();\n releaseProfiler();\n state = 'stopped';\n },\n };\n}\n","import {\n attachBrowserInputBackend,\n type BrowserInputBackendOptions,\n type InputBackend,\n type PointerLockProvider,\n type VirtualJoystickConfig,\n} from '@forgeax/engine-input';\n\nimport { APP_ERROR_HINTS, APP_EXPECTED, AppError } from '../errors';\n\n/**\n * Handle returned by attachInputAuto. Captures the backend (exposed via\n * App.input), the detach callable, and a cleanup() funnel that the\n * frame-loop / app-stop / device-lost paths share (R-4).\n */\nexport interface InputAttachHandle {\n readonly backend: InputBackend;\n cleanup(): void;\n /**\n * M2: install the error dispatch callback for onLockError events.\n * Must be called by createApp after the ErrorFanoutRegistry is created\n * (the dispatch function is created after attachInputAuto returns).\n * Idempotent — subsequent calls replace the previous callback.\n */\n setOnErrorDispatch(fn: (err: AppError) => void): void;\n}\n\n/**\n * Acquire a browser input backend. This Host helper owns only DOM listeners;\n * the Cordis input plugin owns every World resource and system contribution.\n */\n/**\n * Options forwarded to attachBrowserInputBackend at attach time. Currently only\n * the neutral PointerLock gate (host decides whether a canvas click captures the\n * cursor); the backend stays host-opaque. Optional so existing call sites are\n * unchanged.\n */\nexport interface InputAttachOptions {\n /** Host-owned UI root used to route Shadow DOM events away from gameplay. */\n readonly uiRoot?: Node;\n readonly pointerLockAllowed?: () => boolean;\n /** M3: virtual joystick configurations passed through to browser backend. */\n readonly virtualJoysticks?: readonly VirtualJoystickConfig[];\n /**\n * M2: pointer-lock provider injected by the host (e.g. editor play-runtime).\n * Forwarded to BrowserInputBackendOptions.lockProvider. When absent, the\n * backend falls back to the W3C requestPointerLock() path.\n * Type SSOT is @forgeax/engine-input's PointerLockProvider.\n */\n readonly lockProvider?: PointerLockProvider;\n}\n\nexport function attachInputAuto(\n canvas: HTMLCanvasElement,\n options: InputAttachOptions = {},\n): InputAttachHandle {\n // Mutable slot for error dispatch. The dispatch function is created by\n // createApp AFTER the ErrorFanoutRegistry is set up, so we need an\n // indirection: the backend's onLockError callback fires synchronously\n // inside the click handler, but the fan-out is ready by then because\n // createApp wires it before calling app.start().\n let onLockErrorDispatch: ((err: AppError) => void) | undefined;\n\n const backendOpts: BrowserInputBackendOptions = {\n ...(options.uiRoot ? { uiRoot: options.uiRoot } : {}),\n ...(options.pointerLockAllowed ? { pointerLockAllowed: options.pointerLockAllowed } : {}),\n ...(options.virtualJoysticks ? { virtualJoysticks: options.virtualJoysticks } : {}),\n ...(options.lockProvider ? { lockProvider: options.lockProvider } : {}),\n onLockError: (detail: { path: 'w3c' | 'provider'; cause: unknown }) => {\n // D-4: wrap the backend's onLockError signal into a structured AppError\n // and fan-out through createApp's onError channel. The dispatch function\n // is installed by setOnErrorDispatch after createApp creates the\n // ErrorFanoutRegistry. If no dispatch is set yet (e.g. during unit tests\n // that don't call setOnErrorDispatch), the error is silently dropped.\n if (onLockErrorDispatch) {\n const err = new AppError({\n code: 'app-pointer-lock-failed',\n expected: APP_EXPECTED['app-pointer-lock-failed'],\n hint: APP_ERROR_HINTS['app-pointer-lock-failed'],\n detail,\n });\n onLockErrorDispatch(err);\n }\n },\n };\n const detach = attachBrowserInputBackend(canvas, backendOpts);\n const backend = detach.backend;\n\n let cleanedUp = false;\n\n return {\n backend,\n setOnErrorDispatch(fn: (err: AppError) => void): void {\n onLockErrorDispatch = fn;\n },\n cleanup(): void {\n if (cleanedUp) {\n return;\n }\n cleanedUp = true;\n detach();\n },\n };\n}\n","import { type ActionConfig, INPUT_MAP_KEY } from '@forgeax/engine-input';\nimport type { Plugin } from '@forgeax/engine-plugin';\n\n/** Install the canvas-form action map as an App-owned World contribution. */\nexport function inputMapPlugin(configs: readonly ActionConfig[]): Plugin {\n const deduped = new Map<string, ActionConfig>();\n for (const config of configs) {\n if (config.action.length > 0) deduped.set(config.action, config);\n }\n const inputMap = Object.freeze([...deduped.values()]);\n return {\n name: 'input-map',\n inject: ['world'],\n apply(ctx) {\n ctx.effect(() => {\n ctx.world.insertResource(INPUT_MAP_KEY, inputMap);\n return () => ctx.world.removeResource(INPUT_MAP_KEY);\n }, 'input/action-map');\n },\n };\n}\n","import { Update } from '@forgeax/engine-ecs';\nimport { INPUT_BACKEND_KEY, InputFrameStartScan, InputSet } from '@forgeax/engine-input';\nimport type { Plugin } from '@forgeax/engine-plugin';\n\n/** Project one Host-owned input provider into reversible World contributions. */\nexport function inputPlugin(): Plugin {\n return {\n name: 'input',\n inject: ['world', 'input'],\n apply(ctx) {\n const world = ctx.world;\n const input = ctx.input;\n if (input === undefined) throw new Error('Cordis activated input without its provider');\n ctx.effect(() => {\n world.insertResource(INPUT_BACKEND_KEY, input);\n return () => {\n world.removeResource(INPUT_BACKEND_KEY);\n };\n }, 'input/resource');\n ctx.effect(() => {\n world.addSystems(Update, InputSet, [InputFrameStartScan]).unwrap();\n return () => world.removeSystem(Update, InputFrameStartScan.name);\n }, 'input/frame-start-scan');\n },\n };\n}\n","import type { AssetRegistry, DynamicTextureStore } from '@forgeax/engine-assets-runtime';\nimport type { World } from '@forgeax/engine-ecs';\nimport type { VertexLayoutProjection } from '@forgeax/engine-geometry';\nimport type { Profiler } from '@forgeax/engine-profiler';\nimport type { CompiledRenderGraphInfo } from '@forgeax/engine-render-graph';\nimport type {\n BindGroup,\n BindGroupLayout,\n Buffer,\n ComputePipeline,\n PipelineLayout,\n Result,\n RhiCanvasContext,\n RhiDevice,\n RenderPipeline as RhiRenderPipeline,\n Sampler,\n Texture,\n TextureFormat,\n TextureView,\n} from '@forgeax/engine-rhi';\nimport { err, ok, RhiError } from '@forgeax/engine-rhi';\nimport type { MaterialRuntimeArtifact } from '@forgeax/engine-shader';\nimport type {\n MaterialRenderState,\n ParamSchemaEntry,\n PassKind,\n PrimitiveTopology,\n VertexAttributeMap,\n} from '@forgeax/engine-types';\nimport type { MaterialRenderProjection } from '../assembly/material/assembly';\nimport type { DeviceScope } from '../device/device-scope';\nimport type { MeshGpuHandles } from '../device/gpu-residency';\nimport type { EngineMetrics } from '../engine-metrics';\nimport type { RenderFeatureHost } from '../features/host';\nimport type { RenderFeatureShaderModuleMode } from '../features/types';\nimport {\n GPU_TEXTURE_USAGE_COPY_SRC,\n GPU_TEXTURE_USAGE_RENDER_ATTACHMENT,\n GPU_TEXTURE_USAGE_TEXTURE_BINDING,\n} from '../gpu-texture-usage';\nimport type { SkylightFallback } from '../ibl/skylight-bind-group';\nimport type { BloomInspection } from '../inspection-types';\nimport type { HealthListenerRegistry, RhiErrorListenerRegistry } from '../lifecycle';\nimport type { StandardProfile } from '../pipeline/standard-profile';\nimport type { PipelineBuilderShaderModuleFactory } from '../pipeline-builder';\nimport type { PointsLinesInspection } from '../points-lines/inspection';\nimport type { PointsLinesRecordPlan } from '../points-lines/record';\n\nexport interface PointsLinesRecordSubmission {\n readonly plan: PointsLinesRecordPlan;\n readonly vertexBuffer: Buffer;\n readonly indexBuffer: Buffer;\n readonly layoutProjection: VertexLayoutProjection;\n}\n\nimport type {\n RenderDebugOverlay,\n RenderPipelineContext,\n RenderRecordPhase,\n VolumetricFogShaderSources,\n} from '../render-contract';\nimport type {\n DispatchEntry,\n MaterialSnapshot,\n SkyboxSnapshot,\n SkylightSnapshot,\n} from '../render-system-extract';\nimport type { SkinPaletteAllocator } from '../systems/skin-palette-allocator';\nimport type {\n BindGroupCounts,\n BloomFrameReceipts,\n DispatchCounts,\n MaterialBgAssemblyCacheEntry,\n RenderFrameState,\n ValidatedRenderable,\n} from './frame-snapshot';\nimport type { FoldDispatchPlan } from './mesh-ssbo';\n\nexport interface RenderSystemRuntime {\n readonly device: RhiDevice;\n readonly deviceScope: DeviceScope;\n readonly errorRegistry: RhiErrorListenerRegistry;\n readonly debugOverlay?: RenderDebugOverlay | undefined;\n readonly healthRegistry: HealthListenerRegistry;\n readonly getMaterialProjection?: (materialGuid: string) => MaterialRenderProjection | undefined;\n readonly getMaterialArtifact?: (specializationKey: string) => MaterialRuntimeArtifact | undefined;\n readonly getMaterialShaderPipeline?: (\n materialShaderId: string,\n isHdr: boolean,\n renderState?: MaterialRenderState,\n topology?: PrimitiveTopology,\n indexFormat?: 'uint16' | 'uint32',\n variantSet?: string,\n passKind?: PassKind,\n meshAttributes?: VertexAttributeMap,\n sampleCount?: number,\n colorFormatOverride?: GPUTextureFormat,\n shaderUvSetCount?: number,\n depthFormatOverride?: GPUTextureFormat | null,\n vertexLayout?: string,\n vertexLayoutProjection?: VertexLayoutProjection,\n shaderModuleMode?: RenderFeatureShaderModuleMode,\n layoutKindOverride?: 'pbr' | 'pbr-skin',\n ) => RhiRenderPipeline | null;\n readonly getMaterialShaderBindingContract?: (\n materialShaderId: string,\n ) => 'group-0' | 'group-0-resource' | 'view-only' | 'view-and-scene-depth' | 'render-material';\n readonly getParamSchema?: (materialShaderId: string) => readonly ParamSchemaEntry[] | undefined;\n readonly getMaterialBindGroupLayout?: (materialShaderId: string) => BindGroupLayout | undefined;\n readonly metrics: EngineMetrics;\n readonly lookupPostProcess?: (\n id: string,\n ) => import('../fullscreen-post-process-pass').PostProcessShaderEntry | undefined;\n readonly getPostProcessParamsBuffer?: (id: string) => Buffer | undefined;\n readonly getPostProcessPipeline?: (\n id: string,\n bgl: BindGroupLayout,\n colorFormat: GPUTextureFormat,\n ) => RhiRenderPipeline | null;\n readonly clearPostProcessPipelineCache?: (id: string) => void;\n readonly invalidateShaderModule?: (label: string) => void;\n readonly dynamicTextureStore?: DynamicTextureStore | undefined;\n}\n\n/** Renderer-owned bridge from retained Points/Lines facts into main geometry. */\nexport interface PointsLinesRecordOwner {\n prepare(entry: ValidatedRenderable, clustered: boolean): PointsLinesRecordSubmission | undefined;\n beginFrame(): void;\n resetForDeviceLoss(): void;\n inspections(): readonly PointsLinesInspection[];\n}\n\nexport interface PerPassResources {\n depthTexture: Texture | null;\n depthTextureView: TextureView | null;\n depthTextureWidth: number;\n depthTextureHeight: number;\n configured: boolean;\n hdrColorTexture: Texture | null;\n hdrColorView: TextureView | null;\n hdrDepthTexture: Texture | null;\n hdrDepthView: TextureView | null;\n hdrTextureWidth: number;\n hdrTextureHeight: number;\n hdrDepthSampleCount: number;\n readonly fxaaPipeline: RhiRenderPipeline | null;\n readonly fxaaBindGroupLayout: BindGroupLayout | null;\n readonly fxaaSampler: Sampler | null;\n msaaColorTexture: Texture | null;\n msaaColorView: TextureView | null;\n msaaSpriteColorTexture: Texture | null;\n msaaSpriteColorView: TextureView | null;\n msaaDepthTexture: Texture | null;\n msaaDepthView: TextureView | null;\n msaaTextureWidth: number;\n msaaTextureHeight: number;\n hdrColorMsaaTexture: Texture | null;\n hdrColorMsaaView: TextureView | null;\n readonly skyboxPipeline: RhiRenderPipeline | null;\n readonly skyboxPipelineMsaa: RhiRenderPipeline | null;\n readonly skyboxBindGroupLayout: BindGroupLayout | null;\n readonly skyboxSampler: Sampler | null;\n readonly skyboxRotationBuffer: Buffer | null;\n bloomBrightPipeline: RhiRenderPipeline | null;\n bloomBlurHPipeline: RhiRenderPipeline | null;\n bloomBlurVPipeline: RhiRenderPipeline | null;\n bloomCompositePipeline: RhiRenderPipeline | null;\n bloomBrightBindGroupLayout: BindGroupLayout | null;\n bloomBlurBindGroupLayout: BindGroupLayout | null;\n bloomCompositeBindGroupLayout: BindGroupLayout | null;\n bloomSampler: Sampler | null;\n bloomBrightParamsBuffer: Buffer | null;\n bloomBlurHParamsBuffer: Buffer | null;\n bloomBlurVParamsBuffer: Buffer | null;\n bloomCompositeParamsBuffer: Buffer | null;\n ensureBloomResources?: () => void;\n getBloomResources?: () => BloomPersistentBundle | null;\n commitBloomResources?: () => void;\n commitBloomFrameReceipts?: (receipts: BloomFrameReceipts) => void;\n discardBloomResources?: () => void;\n retireBloomResources?: (completion: Promise<unknown>) => void;\n /** Drain candidate, active, and fence-retiring Bloom generations. */\n drainBloomResources?: () => void;\n inspectBloomResources?: (graph?: CompiledRenderGraphInfo) => BloomInspection;\n bloomBrightTexture: Texture | null;\n bloomBrightView: TextureView | null;\n bloomBrightWidth: number;\n bloomBrightHeight: number;\n bloomBlurHTexture: Texture | null;\n bloomBlurHView: TextureView | null;\n bloomBlurHWidth: number;\n bloomBlurHHeight: number;\n bloomBlurVTexture: Texture | null;\n bloomBlurVView: TextureView | null;\n bloomBlurVWidth: number;\n bloomBlurVHeight: number;\n ssaoCalcPipeline: RhiRenderPipeline | null;\n ssaoBlurPipeline: RhiRenderPipeline | null;\n ssaoBgl: BindGroupLayout | null;\n ssaoFilteringSampler: Sampler | null;\n ssaoDepthSampler: Sampler | null;\n ssaoFallbackRawView: TextureView | null;\n shadowTexture: Texture | null;\n shadowMapSize: number;\n shadowCascadeCount: number;\n shadowSampler: Sampler | null;\n shadowLightSpaceMatrix: Float32Array | null;\n shadowCsmLightViewProj: Float32Array | null;\n shadowCsmSelection: {\n readonly viewMatrix: Float32Array;\n readonly splitPlanes: Float32Array;\n } | null;\n}\n\n/** Renderer-private Bloom bundle selected for one record transaction. */\nexport interface BloomPersistentBundle {\n readonly scope: DeviceScope;\n readonly generation: number;\n readonly bloomBrightPipeline: RhiRenderPipeline | null;\n readonly bloomBlurHPipeline: RhiRenderPipeline | null;\n readonly bloomBlurVPipeline: RhiRenderPipeline | null;\n readonly bloomCompositePipeline: RhiRenderPipeline | null;\n readonly bloomBrightBindGroupLayout: BindGroupLayout | null;\n readonly bloomBlurBindGroupLayout: BindGroupLayout | null;\n readonly bloomCompositeBindGroupLayout: BindGroupLayout | null;\n readonly bloomSampler: Sampler | null;\n readonly bloomBrightParamsBuffer: Buffer | null;\n readonly bloomBlurHParamsBuffer: Buffer | null;\n readonly bloomBlurVParamsBuffer: Buffer | null;\n readonly bloomCompositeParamsBuffer: Buffer | null;\n}\n\nexport interface PipelineState {\n readonly meshes: ReadonlyMap<number, MeshGpuHandles>;\n readonly format: TextureFormat;\n readonly colorAttachmentFormat: TextureFormat;\n /** Surface route committed by configureSurface for inspection provenance. */\n readonly surfaceProfile?: 'dual-view' | 'raw-only';\n readonly viewBindGroupLayout: BindGroupLayout;\n /** Device capability gate for the optional SpotLight projector binding. */\n readonly projectorAvailable?: boolean;\n readonly materialBindGroupLayout: BindGroupLayout;\n readonly meshBindGroupLayout: BindGroupLayout;\n readonly viewUniformBuffer: Buffer;\n readonly pointsLinesViewBuffer?: Buffer;\n readonly shadowCasterCascadeBuffer: Buffer;\n readonly materialUniformBuffer: { readonly buffer: Buffer; readonly sizeInBytes: number };\n readonly meshStorageBuffer: { readonly buffer: Buffer; readonly sizeInBytes: number };\n readonly pointLightsBuffer: Buffer;\n readonly spotLightsBuffer: Buffer;\n readonly instancesBindGroupLayout: BindGroupLayout;\n readonly identityInstanceBuffer: Buffer;\n readonly defaultSampler: Sampler;\n readonly nearestSampler: Sampler;\n readonly fallbackTextureView: TextureView;\n readonly unlitPipeline: RhiRenderPipeline | null;\n readonly standardPipeline: RhiRenderPipeline | null;\n readonly unlitPipelineMsaa: RhiRenderPipeline | null;\n readonly unlitPipelineHdrMsaa: RhiRenderPipeline | null;\n readonly pbrPipelineLayout: PipelineLayout | null;\n readonly hdrpPbrPipelineLayout: PipelineLayout | null;\n readonly hdrpClusterMembershipPipeline: ComputePipeline | null;\n readonly hdrpClusterMembershipBindGroupLayout: BindGroupLayout | null;\n readonly pbrSkinPipelineLayout: PipelineLayout | null;\n readonly pbrSkinMeshBindGroupLayout: BindGroupLayout | null;\n readonly skinPaletteAllocator: SkinPaletteAllocator | null;\n readonly defaultWhiteTextureView: TextureView;\n readonly defaultNormalTextureView: TextureView;\n readonly unlitPipelineHdr: RhiRenderPipeline | null;\n readonly shadowFallbackTextureView: TextureView;\n readonly shadowAtlasFallbackTextureView: TextureView;\n readonly shadowParamsBuffer: Buffer;\n readonly skylightFallback: SkylightFallback | null;\n readonly perPassResources: PerPassResources;\n}\n\nexport interface RenderSystemInternals extends RenderSystemRuntime {\n readonly canvas: HTMLCanvasElement | OffscreenCanvas;\n readonly standardProfile?: StandardProfile | undefined;\n readonly standardPipeline: RenderFrameState['activePipeline'];\n readonly featureHost?: RenderFeatureHost | undefined;\n readonly shaderModuleFactory?: PipelineBuilderShaderModuleFactory;\n /** Optional handle-first factory for feature-owned generated shader programs. */\n readonly immediateShaderModuleFactory?: PipelineBuilderShaderModuleFactory;\n readonly profiler?: Profiler | undefined;\n readonly context: RhiCanvasContext | null;\n readonly getPipelineState: () => PipelineState | null;\n readonly assets: AssetRegistry;\n readonly gpuStore: import('../device/gpu-residency').GpuResidencyCache;\n readonly growMeshSsbo?:\n | ((neededSlots: number) =>\n | { readonly ok: true }\n | {\n readonly ok: false;\n readonly code: 'mesh-ssbo-ceiling-reached' | 'mesh-ssbo-capacity-exceeded';\n readonly degradedToSlotCount: number;\n })\n | undefined;\n readonly meshSsboState?: { readonly slotCount: number } | undefined;\n readonly buildPostProcessPipeline?:\n | ((\n entry: import('../fullscreen-post-process-pass').PostProcessShaderEntry,\n bgl: BindGroupLayout,\n colorFormat: GPUTextureFormat,\n label: string,\n ) => RhiRenderPipeline | null)\n | undefined;\n /** Composed renderer utility sources installed atomically at build-ready. */\n volumetricFogShaders?: VolumetricFogShaderSources | undefined;\n}\n\nexport interface _StandardForwardSceneView {\n readonly assets: AssetRegistry;\n readonly store: import('../device/gpu-residency').GpuResidencyCache;\n readonly pipelineState: PipelineState;\n readonly bloomResources?: BloomPersistentBundle | null;\n readonly runtime: RenderSystemRuntime;\n readonly validated: readonly ValidatedRenderable[];\n readonly validatedOrdered: readonly ValidatedRenderable[];\n readonly viewBindGroup: BindGroup | null;\n readonly meshBindGroup: BindGroup | null;\n readonly frameState: RenderFrameState;\n readonly dispatchCounts: DispatchCounts;\n readonly bindGroupCounts: BindGroupCounts;\n readonly skylight: SkylightSnapshot | undefined;\n readonly skylightCount: number;\n readonly skybox: SkyboxSnapshot | undefined;\n readonly profilePhase?: <T>(phase: RenderRecordPhase, action: () => T) => T;\n readonly directionalShadowCacheReuse: boolean;\n readonly world: World;\n readonly gpuDrivenEntityKeys: ReadonlySet<number>;\n readonly tonemapActive: boolean;\n readonly geometryColorView: TextureView | null;\n readonly geometryDepthView: TextureView | null;\n readonly geometryDepthKey: string | null;\n readonly skyboxActive: boolean;\n readonly splitLdrSprite: boolean;\n readonly ldrSpritePassView: TextureView | null;\n readonly transparentColorFormat?: GPUTextureFormat;\n readonly dispatch: readonly DispatchEntry[];\n readonly hdrpClusterBindGroup: BindGroup | null;\n readonly hdrpClusterMembershipBindGroup: BindGroup | null;\n readonly foldDispatchPlan: FoldDispatchPlan | null;\n readonly materialSlotIndices: readonly (readonly number[])[];\n readonly materialSlots: readonly MaterialSnapshot[];\n readonly materialSlotOwners: readonly number[];\n readonly materialSlotCount: number;\n readonly pointsLines: PointsLinesRecordOwner | undefined;\n readonly materialBgAssemblyCache: Map<string, MaterialBgAssemblyCacheEntry>;\n materialUboPayloadCache?: {\n readonly materialSlots: readonly MaterialSnapshot[];\n readonly materialSlotCount: number;\n readonly payload: Uint8Array;\n };\n hdrpSsaoBlurredView?: TextureView;\n}\n\nexport type _InternalRenderPipelineContext = RenderPipelineContext & _StandardForwardSceneView;\n\nexport type RecordProfileRunner = <T>(phase: RenderRecordPhase, action: () => T) => T;\n\nexport const STANDARD_PBR_UBO_SIZE = 384;\nexport const MATERIAL_PER_ENTITY_STRIDE = 512;\n\nexport type SwapChainFormatPair = {\n readonly storage: GPUTextureFormat;\n readonly view: GPUTextureFormat;\n readonly fallbackReason?: 'preferred-canvas-format-missing';\n};\n\n/** Internal closed projection of the concrete surface route. */\nexport type SurfaceProfile =\n | {\n readonly kind: 'dual-view';\n readonly storageFormat: GPUTextureFormat;\n readonly viewFormat: GPUTextureFormat;\n readonly viewFormats: readonly [GPUTextureFormat];\n readonly hasDisplayEndpoint: true;\n }\n | {\n readonly kind: 'raw-only';\n readonly storageFormat: GPUTextureFormat;\n readonly viewFormat: GPUTextureFormat;\n readonly viewFormats: readonly [];\n readonly hasDisplayEndpoint: false;\n };\n\nexport interface SurfaceCapabilityFacts {\n /** Concrete wgpu downlevel `SURFACE_VIEW_FORMATS` flag. */\n readonly surfaceViewFormats: boolean;\n readonly rawAttachment: boolean;\n readonly floatRenderAttachment: boolean;\n}\n\nexport function resolveSurfaceProfile(\n storageFormat: GPUTextureFormat,\n viewFormat: GPUTextureFormat,\n facts: SurfaceCapabilityFacts,\n): Result<SurfaceProfile, RhiError> {\n if (facts.surfaceViewFormats) {\n return ok({\n kind: 'dual-view',\n storageFormat,\n viewFormat,\n viewFormats: [viewFormat],\n hasDisplayEndpoint: true,\n });\n }\n if (!facts.rawAttachment || !facts.floatRenderAttachment) {\n return err(\n new RhiError({\n code: 'webgpu-runtime-error',\n expected: 'raw surface attachment and rgba16float render attachment capabilities',\n hint: 'surface profile cannot establish a raw-only linear output route',\n detail: {\n error: {\n code: 'surface-raw-endpoint-failed',\n message: 'raw-only surface capabilities are incomplete',\n },\n },\n }),\n );\n }\n return ok({\n kind: 'raw-only',\n storageFormat,\n viewFormat: storageFormat,\n viewFormats: [],\n hasDisplayEndpoint: false,\n });\n}\n\nexport type SurfaceBackendKind = 'webgpu' | 'wgpu-native' | 'wgpu-webgl2' | 'null';\n\nexport function resolveSurfaceFormatPair(\n _backendKind: SurfaceBackendKind,\n storage: GPUTextureFormat,\n view: GPUTextureFormat,\n): SwapChainFormatPair {\n return { storage, view };\n}\n\nfunction surfaceCapabilityFacts(\n device: RhiDevice,\n storageFormat: GPUTextureFormat,\n): SurfaceCapabilityFacts {\n const internal = device as unknown as { readonly surfaceViewFormats?: boolean };\n return {\n surfaceViewFormats: internal.surfaceViewFormats ?? device.caps?.backendKind !== 'wgpu-webgl2',\n rawAttachment: storageFormat === 'rgba8unorm' || storageFormat === 'bgra8unorm',\n floatRenderAttachment: device.caps?.rgba16floatRenderable ?? true,\n };\n}\n\nexport function configureSurface(\n context: RhiCanvasContext,\n device: RhiDevice,\n format: TextureFormat,\n colorAttachmentFormat: TextureFormat,\n): Result<void, RhiError> {\n const backendKind = device.caps?.backendKind ?? 'webgpu';\n const isWebGl2 = backendKind === 'wgpu-webgl2';\n const surfaceFormats = resolveSurfaceFormatPair(\n backendKind,\n format as GPUTextureFormat,\n colorAttachmentFormat as GPUTextureFormat,\n );\n const profile = resolveSurfaceProfile(\n surfaceFormats.storage,\n surfaceFormats.view,\n surfaceCapabilityFacts(device, surfaceFormats.storage),\n );\n if (!profile.ok) return profile;\n // WebGL2 surface pixels are proven by the compositor fixture, so it has no\n // surface consumer for optional TEXTURE_BINDING/COPY_SRC usage. The concrete\n // wgpu surface derives supported usages from SurfaceCapabilities and rejects\n // unsupported requests; this path requests only the guaranteed attachment\n // usage. Raw-only deliberately has no alternate view.\n const supportsTextureBinding =\n backendKind !== 'wgpu-webgl2' && (device.caps?.storageBuffer ?? true);\n const configured = context.configure({\n device,\n format: surfaceFormats.storage,\n alphaMode: isWebGl2 ? 'opaque' : 'premultiplied',\n usage:\n GPU_TEXTURE_USAGE_RENDER_ATTACHMENT |\n (supportsTextureBinding ? GPU_TEXTURE_USAGE_TEXTURE_BINDING : 0) |\n (isWebGl2 ? 0 : GPU_TEXTURE_USAGE_COPY_SRC),\n viewFormats: [...profile.value.viewFormats],\n });\n if (!configured.ok) return configured;\n if (\n isWebGl2 &&\n (context.presentationProof === undefined ||\n !context.presentationProof.descriptor ||\n !context.presentationProof.acquisition ||\n !context.presentationProof.validation ||\n typeof context.presentationProof.surfaceIdentity !== 'string' ||\n context.presentationProof.surfaceIdentity.length === 0 ||\n context.presentationProof.requested === undefined ||\n context.presentationProof.validated === undefined ||\n JSON.stringify(context.presentationProof.requested) !==\n JSON.stringify(context.presentationProof.validated))\n ) {\n return err(\n new RhiError({\n code: 'webgpu-runtime-error',\n expected: 'WebGL2 surface storage has descriptor, acquisition, and validation proof',\n hint: 'run the concrete presentation probe and retain the last-known-good graph when proof is absent',\n detail: {\n error: {\n code: 'surface-raw-endpoint-failed',\n message: 'surface storage raw endpoint proof is incomplete',\n },\n },\n }),\n );\n }\n return ok(undefined);\n}\n\nexport function selectSwapChainFormat(\n storageBufferCapable: boolean,\n surfaceViewFormats = true,\n): SwapChainFormatPair {\n if (!storageBufferCapable) {\n return {\n storage: 'rgba8unorm',\n view: surfaceViewFormats ? 'rgba8unorm-srgb' : 'rgba8unorm',\n };\n }\n const nav = (\n globalThis as { navigator?: { gpu?: { getPreferredCanvasFormat?: () => GPUTextureFormat } } }\n ).navigator;\n const gpu = nav?.gpu;\n const getPreferred = gpu?.getPreferredCanvasFormat;\n if (gpu !== undefined && typeof getPreferred === 'function') {\n const storage = getPreferred.call(gpu);\n const view =\n storage === 'rgba8unorm'\n ? 'rgba8unorm-srgb'\n : storage === 'bgra8unorm'\n ? 'bgra8unorm-srgb'\n : storage;\n return {\n storage,\n view: surfaceViewFormats ? view : storage,\n };\n }\n return {\n storage: 'rgba8unorm',\n view: surfaceViewFormats ? 'rgba8unorm-srgb' : 'rgba8unorm',\n fallbackReason: 'preferred-canvas-format-missing',\n };\n}\n","import type { DebugDraw } from '@forgeax/engine-debug-draw';\nimport { createDebugDraw } from '@forgeax/engine-debug-draw';\nimport type { RendererHostAssembly } from '@forgeax/engine-render/internal/construct-renderer';\nimport type { TextureFormat } from '@forgeax/engine-rhi';\nimport { selectSwapChainFormat } from '../../../render/src/record/render-context';\n\nexport type RendererDebugDrawHost = Pick<\n RendererHostAssembly['debugDrawHost'],\n 'initialization' | 'device' | '_internal_createShaderModule' | '_internal_setRenderOverlay'\n>;\n\n/** Create the App-owned debug overlay after the renderer has initialized. */\nexport async function createDebugDrawOnReady(\n context: RendererDebugDrawHost,\n format?: TextureFormat,\n): Promise<DebugDraw> {\n const ready = await context.initialization;\n if (!ready.ok) throw ready.error;\n\n const resolvedFormat =\n format ??\n (selectSwapChainFormat(context.device.caps.storageBuffer).view as unknown as TextureFormat);\n const result = await createDebugDraw({\n device: context.device,\n queue: context.device.queue,\n createShaderModule: context._internal_createShaderModule,\n format: resolvedFormat,\n });\n if (!result.ok) throw result.error;\n context._internal_setRenderOverlay(result.value);\n return result.value;\n}\n\n/** Release the App-owned debug overlay and clear its Render capability. */\nexport function releaseDebugDraw(context: RendererDebugDrawHost, debugDraw: DebugDraw): void {\n context._internal_setRenderOverlay(undefined);\n debugDraw.destroy();\n}\n","import {\n type AnimationPayloadLookup,\n animationPayloadsPlugin,\n animationRuntimePlugin,\n} from '@forgeax/engine-animation';\nimport type { DebugDraw } from '@forgeax/engine-debug-draw';\nimport {\n type ActionConfig,\n type InputBackend,\n inputBackendPlugin,\n ownedInputBackendPlugin,\n} from '@forgeax/engine-input';\nimport type { Plugin } from '@forgeax/engine-plugin';\nimport { renderComponentsPlugin } from '@forgeax/engine-render';\nimport { scenePlugin } from '@forgeax/engine-scene';\nimport { statePlugin } from '@forgeax/engine-state';\nimport { inputMapPlugin } from '../input-map-plugin';\nimport { inputPlugin } from '../input-plugin';\nimport {\n ownedRendererPlugin,\n type RenderFeatureHost,\n renderFeatureHostPlugin,\n} from '../renderer-plugin';\nimport { assetsWorldPlugin, rendererAssetsPlugin } from './assets-world-plugin';\nimport { createDebugDrawOnReady, type RendererDebugDrawHost, releaseDebugDraw } from './debug-draw';\nimport type { EngineProfileBase } from './engine-profile-common';\n\nexport interface MainEngineProfileOptions extends EngineProfileBase {\n readonly rendererDebugDrawHost?: RendererDebugDrawHost;\n readonly rendererFeatureHost?: RenderFeatureHost;\n readonly animationPayloads: AnimationPayloadLookup;\n readonly onDebugDrawReady?: (debugDraw: DebugDraw) => void;\n readonly input?: InputBackend;\n readonly inputDispose?: () => void;\n readonly inputMap?: readonly ActionConfig[];\n}\n\nfunction debugDrawPlugin(\n context: RendererDebugDrawHost,\n onReady: (debugDraw: DebugDraw) => void,\n): Plugin {\n return {\n name: 'debug-draw',\n async apply(ctx) {\n try {\n const debugDraw = await createDebugDrawOnReady(context);\n onReady(debugDraw);\n ctx.effect(() => () => releaseDebugDraw(context, debugDraw), 'render/debug-draw');\n } catch {\n // DebugDraw is optional; renderer error reporting owns creation failures.\n }\n },\n };\n}\n\n/** Static browser-main selection; dependency order remains owned by inject/provide. */\nexport function mainEngineProfile(options: MainEngineProfileOptions): Plugin[] {\n return [\n ownedRendererPlugin(options.renderer),\n renderComponentsPlugin(),\n ...(options.rendererFeatureHost === undefined\n ? []\n : [renderFeatureHostPlugin(options.rendererFeatureHost)]),\n rendererAssetsPlugin(options.assets),\n assetsWorldPlugin(),\n ...(options.input === undefined\n ? []\n : [\n options.inputDispose === undefined\n ? inputBackendPlugin(options.input)\n : ownedInputBackendPlugin(options.input, options.inputDispose),\n ]),\n scenePlugin(),\n animationPayloadsPlugin(options.animationPayloads),\n animationRuntimePlugin(),\n statePlugin(),\n ...(options.onDebugDrawReady === undefined || options.rendererDebugDrawHost === undefined\n ? []\n : [debugDrawPlugin(options.rendererDebugDrawHost, options.onDebugDrawReady)]),\n ...(options.input === undefined ? [] : [inputPlugin()]),\n ...(options.inputMap === undefined ? [] : [inputMapPlugin(options.inputMap)]),\n ...(options.extensions ?? []),\n ];\n}\n","// @forgeax/engine-app/internal/remote-serve-flag -- FORGEAX_ENGINE_REMOTE_SERVE\n// dual-source resolution (plan-strategy secondary D-7).\n//\n// The remote eval server is auto-started in dev mode (vite's import.meta.env.DEV)\n// and production builds skip it. Headless/dawn-node can opt in via the\n// FORGEAX_ENGINE_REMOTE_SERVE=1 env var.\n//\n// Dual sources (mirrors rhi-debug-flag.ts pattern):\n// browser (vite): import.meta.env.DEV is statically replaced by vite\n// (true in dev server, false in production build).\n// dawn-node : import.meta may be undefined; fallback to\n// globalThis.process.env.FORGEAX_ENGINE_REMOTE_SERVE === '1'.\n//\n// The SSOT precedence: import.meta.env.DEV wins when available;\n// process.env is the headless opt-in path.\n\n/** Minimal structural view of an env bag carrying the serve flag. */\ninterface RemoteServeEnv {\n readonly FORGEAX_ENGINE_REMOTE_SERVE?: string | undefined;\n}\n\n/**\n * Resolve whether the remote eval server should be started.\n *\n * Returns `true` when:\n * - vite dev mode (import.meta.env.DEV === true), OR\n * - headless/dawn-node with FORGEAX_ENGINE_REMOTE_SERVE=1 opt-in\n *\n * Returns `false` in production builds and headless without explicit opt-in.\n *\n * @param isDev flag from import.meta.env.DEV (undefined when import.meta absent)\n * @param processEnv globalThis.process?.env when present, else undefined\n */\nexport function resolveRemoteServeFlag(\n isDev: boolean | undefined,\n processEnv: RemoteServeEnv | undefined,\n): boolean {\n if (isDev === true) return true;\n if (processEnv?.FORGEAX_ENGINE_REMOTE_SERVE === '1') return true;\n return false;\n}\n","import type { Plugin } from '@forgeax/engine-plugin';\n\nexport interface RemoteServerHandle {\n readonly port: number;\n close(): Promise<void>;\n}\n\n/** Own a Node remote server with the App Fiber while App still exposes its handle. */\nexport function remoteServerPlugin(handle: RemoteServerHandle): Plugin {\n return {\n name: 'remote-server',\n apply(ctx) {\n ctx.effect(() => async () => handle.close(), 'remote/server');\n },\n };\n}\n","import type { RhiBackendInstrumentation } from '@forgeax/engine-render/internal/construct-renderer';\nimport { RhiError } from '@forgeax/engine-rhi';\nimport type {\n CaptureFrameOptions,\n EncodedTape,\n RecorderAttachment,\n RhiDebugError,\n} from '@forgeax/engine-rhi-debug';\nimport { createRhiDebugError } from '@forgeax/engine-rhi-debug';\nimport { err, ok, type Result } from '@forgeax/engine-types';\nimport type { FrameLoopHandle } from './frame-loop';\n\nexport interface RhiTapeArtifactRef {\n readonly kind: 'rhi-tape';\n readonly digest: string;\n readonly bytes: Uint8Array;\n}\n\nexport interface RhiCapture {\n captureFrame(options?: CaptureFrameOptions): Promise<Result<RhiTapeArtifactRef, RhiDebugError>>;\n}\n\ntype CaptureResult = Result<EncodedTape, RhiDebugError>;\ntype CaptureFrameDriver = Pick<FrameLoopHandle, 'getState' | 'pause' | 'resume' | 'stepFrame'>;\n\nconst captureDrivers = new WeakMap<RhiCapture, CaptureFrameDriver>();\n\nexport function createRhiCapture(attachment: RecorderAttachment): RhiCapture {\n let activeCapture: Promise<Result<RhiTapeArtifactRef, RhiDebugError>> | undefined;\n const capture: RhiCapture = {\n captureFrame(options) {\n const driver = captureDrivers.get(capture);\n if (driver === undefined) return captureAttachment(attachment, options);\n if (activeCapture !== undefined) {\n return Promise.resolve(\n err(\n createRhiDebugError('capture-busy', {\n stage: 'capture',\n cause: 'another App capture transaction is active',\n }),\n ),\n );\n }\n const request = captureWithAppFrame(attachment, driver, options);\n activeCapture = request;\n void request.then(\n () => {\n if (activeCapture === request) activeCapture = undefined;\n },\n () => {\n if (activeCapture === request) activeCapture = undefined;\n },\n );\n return request;\n },\n };\n return capture;\n}\n\n/** Bind the App-owned frame authority to its host capture capability. */\nexport function bindRhiCaptureFrameDriver(capture: RhiCapture, driver: CaptureFrameDriver): void {\n captureDrivers.set(capture, driver);\n}\n\nasync function captureAttachment(\n attachment: RecorderAttachment,\n options: CaptureFrameOptions | undefined,\n): Promise<Result<RhiTapeArtifactRef, RhiDebugError>> {\n const result = await attachment.captureFrame(options);\n if (!result.ok) return result;\n return ok(toArtifact(result.value));\n}\n\nasync function captureWithAppFrame(\n attachment: RecorderAttachment,\n driver: CaptureFrameDriver,\n options: CaptureFrameOptions | undefined,\n): Promise<Result<RhiTapeArtifactRef, RhiDebugError>> {\n const state = driver.getState();\n if (state !== 'running' && state !== 'paused') {\n return err(\n createRhiDebugError('capture-unavailable', {\n stage: 'capture',\n cause: `App capture requires a running or paused frame loop, received '${state}'`,\n }),\n );\n }\n if (options?.signal?.aborted) return captureAttachment(attachment, options);\n\n const resumeAfter = state === 'running';\n if (resumeAfter) {\n const paused = driver.pause();\n if (!paused.ok) {\n return err(\n createRhiDebugError('capture-unavailable', {\n stage: 'capture',\n cause: `App capture could not pause the frame loop: ${describeFailure(paused.error)}`,\n }),\n );\n }\n }\n\n const controller = new AbortController();\n const abortFromUser = (): void => controller.abort();\n options?.signal?.addEventListener('abort', abortFromUser, { once: true });\n let captureResult: Promise<CaptureResult>;\n try {\n captureResult = attachment.captureFrame({\n ...(options ?? {}),\n signal: controller.signal,\n });\n } catch (cause: unknown) {\n options?.signal?.removeEventListener('abort', abortFromUser);\n if (resumeAfter && driver.getState() === 'paused') driver.resume();\n return err(\n createRhiDebugError('capture-unavailable', {\n stage: 'capture',\n cause: `App capture could not arm the recorder: ${describeFailure(cause)}`,\n }),\n );\n }\n\n let result: CaptureResult | undefined;\n let transactionError: RhiDebugError | undefined;\n try {\n const snapshot = await attachment.frameBoundary();\n if (!snapshot.ok) {\n result = await captureResult;\n } else if (options?.signal?.aborted) {\n controller.abort();\n result = await captureResult;\n } else {\n const stepped = driver.stepFrame(0);\n if (!stepped.ok) {\n transactionError = createRhiDebugError('capture-unavailable', {\n stage: 'capture',\n cause: `App capture frame failed: ${describeFailure(stepped.error)}`,\n });\n controller.abort();\n result = await captureResult;\n } else {\n result = await captureResult;\n }\n }\n } catch (cause: unknown) {\n transactionError = createRhiDebugError('capture-unavailable', {\n stage: 'capture',\n cause: `App capture transaction failed: ${describeFailure(cause)}`,\n });\n controller.abort();\n result = await captureResult;\n } finally {\n options?.signal?.removeEventListener('abort', abortFromUser);\n if (resumeAfter && driver.getState() === 'paused') {\n const resumed = driver.resume();\n if (!resumed.ok && transactionError === undefined) {\n transactionError = createRhiDebugError('capture-unavailable', {\n stage: 'capture',\n cause: `App capture could not resume the frame loop: ${describeFailure(resumed.error)}`,\n });\n }\n }\n }\n\n if (transactionError !== undefined) return err(transactionError);\n if (result === undefined) result = await captureResult;\n if (!result.ok) return result;\n return ok(toArtifact(result.value));\n}\n\nfunction describeFailure(cause: unknown): string {\n if (typeof cause === 'string') return cause;\n if (cause instanceof Error) return cause.message;\n if (typeof cause === 'object' && cause !== null && 'hint' in cause) {\n const hint = (cause as { hint?: unknown }).hint;\n if (typeof hint === 'string') return hint;\n }\n return String(cause);\n}\n\nexport function createRhiInstrumentation(\n attachment: RecorderAttachment,\n): RhiBackendInstrumentation {\n return {\n resolveSurfaceDevice(device) {\n const resolved = attachment.backend.unwrapDeviceForSurface(device);\n if (resolved.ok) return resolved;\n return err(\n new RhiError({\n code: 'rhi-not-available',\n expected: 'the recorder can resolve the wrapped surface device',\n hint: resolved.error.hint,\n }),\n );\n },\n onFrameBoundary() {\n void attachment.frameBoundary();\n },\n onDeviceLost() {\n attachment.deviceLost();\n },\n };\n}\n\nfunction toArtifact(encoded: EncodedTape): RhiTapeArtifactRef {\n return {\n kind: 'rhi-tape',\n digest: encoded.digest,\n bytes: encoded.bytes,\n };\n}\n","// @forgeax/engine-app/internal/rhi-debug-flag -- FORGEAX_ENGINE_RHI_DEBUG\n// three-segment dual-source resolution (plan-strategy D-4).\n//\n// The canvas form reads the flag from two independent sources with a precise\n// precedence + short-circuit shape so the same build serves both deployment\n// targets:\n//\n// browser (vite): `import.meta.env.FORGEAX_ENGINE_RHI_DEBUG` is statically\n// replaced by the vite-plugin-rhi-debug `define` hook.\n// dawn-node : `import.meta` may be undefined and there is no vite define,\n// so the flag arrives through `globalThis.process.env`.\n//\n// Extracting the resolution into this pure helper lets it be unit-tested across\n// the three scenarios (browser '1' / dawn-node process.env / unset) without a\n// real bundler or runtime. The call site keeps the literal `typeof import.meta\n// !== 'undefined'` prefix (C5) -- modelled here by passing `undefined` for the\n// `importMetaEnv` argument when `import.meta` is absent.\n\n/** Minimal structural view of an env bag carrying the flag. */\ninterface RhiDebugEnv {\n readonly FORGEAX_ENGINE_RHI_DEBUG?: string | undefined;\n}\n\n/**\n * Resolve the raw FORGEAX_ENGINE_RHI_DEBUG flag from the two sources.\n *\n * Precedence: `import.meta.env` wins; `globalThis.process.env` is the fallback.\n * Returns the raw string (or undefined); the caller compares `=== '1'`.\n *\n * @param importMetaEnv `import.meta.env` when `import.meta` is defined,\n * else `undefined` (models the `typeof import.meta !== 'undefined'` prefix\n * short-circuiting to a falsy first operand).\n * @param processEnv `globalThis.process?.env` when present, else `undefined`.\n */\nexport function resolveRhiDebugFlag(\n importMetaEnv: RhiDebugEnv | undefined,\n processEnv: RhiDebugEnv | undefined,\n): string | undefined {\n return importMetaEnv?.FORGEAX_ENGINE_RHI_DEBUG ?? processEnv?.FORGEAX_ENGINE_RHI_DEBUG;\n}\n","// @forgeax/engine-app -- createApp double-SSOT entry (M3 wiring).\n//\n// This file ships the final-shape signatures for both overload routes\n// (canvas thin wrapper + assemble form per plan-strategy D-5):\n//\n// - createApp({ renderer, world, ... }) -- assemble form: returns an\n// App with the supplied renderer / world wired through; the M2 rAF\n// frame-loop + state machine + dt clamp drive start / stop / pause /\n// resume. M3 lands listener-registry-backed onError + input-attach\n// plumbing: when the host passes a pre-built InputBackend through\n// args.input, the assemble form treats it as host-managed (no auto\n// attach, no auto cleanup -- the host owns the lifetime).\n//\n// - createApp(canvas, opts?) -- canvas form (M3 partial):\n// calls createRenderer(canvas, opts?), constructs a new World, and\n// (when opts.input !== false) wires the auto input-attach helper so\n// world.getResource('InputSnapshot') is populated each frame.\n// Falls through to the assemble form for the rest of the wiring.\n// Full canvas form (canvas-detached check, EngineEnvironmentError\n// catch, console.error fallback) lands in M4 (plan-strategy section 7).\n//\n// 'tagName' in arg dispatch (per plan-strategy D-5): HTMLCanvasElement\n// inherits .tagName from HTMLElement, so the property test cleanly\n// separates the canvas argument from the AppAssembleArgs plain object.\n\nimport type { AssetRegistry } from '@forgeax/engine-assets-runtime';\nimport type { AudioBackend } from '@forgeax/engine-audio';\nimport type { DebugDraw } from '@forgeax/engine-debug-draw';\nimport { createWorldContext, Update, World } from '@forgeax/engine-ecs';\nimport type { InputBackend } from '@forgeax/engine-input';\nimport type { Context, Plugin } from '@forgeax/engine-plugin';\nimport type { RenderError } from '@forgeax/engine-render';\nimport { CAMERA_PROJECTION_PERSPECTIVE, Camera, type Renderer } from '@forgeax/engine-render';\nimport type { RendererHostAssembly } from '@forgeax/engine-render/internal/construct-renderer';\nimport { RhiError } from '@forgeax/engine-rhi';\nimport {\n attachRecorder,\n type CaptureFrameOptions,\n type RecorderAttachment,\n} from '@forgeax/engine-rhi-debug';\nimport * as engineRuntimeModule from '@forgeax/engine-runtime';\nimport { EngineEnvironmentError } from '@forgeax/engine-runtime';\nimport {\n constructRuntimeRendererHost,\n loadRhiPack,\n} from '@forgeax/engine-runtime/internal/renderer-host';\nimport { err, ok, type Result } from '@forgeax/engine-types';\n\nimport { createAnimationPayloadLookup } from './animation-asset-lookup';\nimport { publishBrowserFrameSubmitted, resetBrowserFrameSubmitted } from './browser-frame-signal';\nimport type { AppErrorCode, AppErrorDetailFor } from './errors';\nimport { APP_ERROR_HINTS, APP_EXPECTED, AppError } from './errors';\nimport {\n createExecutionReport,\n type ExecutionControl,\n executionBootstrapHostPlugin,\n type PreparedExecutionBootstrap,\n prepareBootstrapEntry,\n probeExecutionCapabilities,\n selectExecutionTier,\n unavailableExecutionCapabilities,\n} from './execution';\nimport { normalizeExecutionBootstrapUrl } from './execution/bootstrap-url';\nimport { createLocalExecutionControl } from './execution/control';\nimport { createWorkerExecutionApp } from './execution/host-controller';\nimport { assembledEngineProfile } from './internal/assembled-engine-profile';\nimport { projectComponentIntrospection } from './internal/component-introspection';\nimport { ErrorFanoutRegistry } from './internal/error-fanout';\nimport { createFrameLoop } from './internal/frame-loop';\nimport { attachInputAuto } from './internal/input-attach';\nimport { mainEngineProfile } from './internal/main-engine-profile';\nimport { resolveRemoteServeFlag } from './internal/remote-serve-flag';\nimport { remoteServerPlugin } from './internal/remote-server-plugin';\nimport {\n bindRhiCaptureFrameDriver,\n createRhiCapture,\n createRhiInstrumentation,\n type RhiCapture,\n} from './internal/rhi-capture';\nimport { resolveRhiDebugFlag } from './internal/rhi-debug-flag';\nimport { createRenderFeatureHost, type RenderFeatureHost } from './renderer-plugin';\nimport type {\n App,\n AppAssembleArgs,\n AppDispatchError,\n AssembleAppError,\n BundlerOptions,\n CanvasAppError,\n CreateAppOptions,\n ExecutionApp,\n} from './types';\n\nfunction makeAppError<C extends AppErrorCode>(\n code: C,\n expected: string,\n hint: string,\n detail: AppErrorDetailFor<C>,\n): AppError {\n return new AppError({ code, expected, hint, detail }) as AppError;\n}\n\nfunction canvasAspectPlugin(canvas: HTMLCanvasElement): Plugin {\n return {\n name: 'canvas-aspect',\n inject: ['world'],\n apply(ctx) {\n ctx.effect(() => {\n const system = {\n name: 'app-sync-camera-aspect',\n queries: [],\n fn: () => {\n syncCanvasDrawingBuffer(canvas);\n syncCameraAspect(ctx.world, canvas.width, canvas.height);\n },\n };\n ctx.world.addSystem(Update, system).unwrap();\n return () => ctx.world.removeSystem(Update, system.name).unwrap();\n }, 'app/canvas-aspect');\n },\n };\n}\n\nfunction rhiDebugHostPlugin(dispose: () => void): Plugin {\n return {\n name: 'rhi-debug-host',\n apply(ctx) {\n ctx.effect(() => dispose, 'rhi-debug/host');\n },\n };\n}\n\n/**\n * createApp(canvas, opts?, bundler?) -- canvas thin wrapper SSOT (per\n * plan-strategy D-5). Resolves with Result.ok(app) on success; failure routes\n * through AppError | RhiError | EngineEnvironmentError per requirements AC-01.\n *\n * feat-20260608-create-app-param-surface-trim / M2 / D-3: the third arg is\n * `BundlerOptions` (importTransport + shaderManifestUrl) -- the SSOT for\n * host-injected build-tool emit knowledge. M3 demos collapse the third-arg\n * literal to `forgeaxBundlerAdapter()` exported by `virtual:forgeax/bundler`.\n *\n * M3 ships the path needed by AC-05 (auto input acquisition plus an ECS scan\n * plugin). M4 finalises the canvas-detached guard +\n * EngineEnvironmentError try/catch + onError default fallback.\n *\n * The host-engine contract defines the boundary between host (DOM, canvas, UI)\n * and engine (renderer, world, frame loop). Only the `createApp(canvas)` path\n * auto-wires the aspect-sync sidecar; the assemble form and bare\n * `createRenderer` path do not.\n *\n * @see {@link https://github.com/Ubpa/forgeax-engine/blob/main/docs/how-to/2026-06-18-host-engine-contract.md | Host-engine contract SSOT}\n */\nexport function createApp(\n canvas: HTMLCanvasElement,\n opts: CreateAppOptions & { readonly execution: NonNullable<CreateAppOptions['execution']> },\n bundler?: BundlerOptions,\n): Promise<Result<ExecutionApp, CanvasAppError>>;\nexport function createApp(\n canvas: HTMLCanvasElement,\n opts?: CreateAppOptions,\n bundler?: BundlerOptions,\n): Promise<Result<App, CanvasAppError>>;\n\n/**\n * Create the browser host for the single RenderScene -> FrameReceipt path.\n * `createApp({ renderer, world, input?, schedule?, ... })` is the assemble form\n * SSOT (per plan-strategy D-5). Host already owns renderer / world; the\n * returned App holds them by reference equality (per AC-02).\n *\n * M3 wires the rAF frame-loop + listener-registry-backed onError. When\n * args.input is supplied, the assemble form treats it as host-managed:\n * it is exposed verbatim as app.input, and the host is responsible for\n * detaching it (no auto-cleanup on stop). The canvas form is the entry\n * that engages the auto-attach helper (input-attach.ts).\n */\nexport function createApp(args: AppAssembleArgs): Promise<Result<App, AssembleAppError>>;\n\nexport function createApp(\n arg: HTMLCanvasElement | AppAssembleArgs,\n opts?: CreateAppOptions,\n bundler?: BundlerOptions,\n): Promise<Result<App | ExecutionApp, CanvasAppError>> {\n if ('tagName' in arg) {\n return createAppFromCanvas(arg, opts, bundler);\n }\n return createAppFromAssemble(arg);\n}\n\nasync function createAppFromCanvas(\n canvas: HTMLCanvasElement,\n opts: CreateAppOptions | undefined,\n // feat-20260608-create-app-param-surface-trim / M2 / D-3: BundlerOptions is\n // the host-injection SSOT (importTransport + shaderManifestUrl). Forwarded\n // verbatim to createRenderer's third arg, so the engine reads\n // shaderManifestUrl in its ShaderRegistry fallback (D-2 q5-A) and threads\n // importTransport to AssetRegistry (AC-05 / R-4: keeps build-tool\n // injection out of RendererOptions / CreateAppOptions).\n bundler: BundlerOptions | undefined,\n): Promise<Result<App | ExecutionApp, CanvasAppError>> {\n // M4: 4-step thin wrapper per plan-strategy D-5.\n //\n // Step 1: canvas-detached fail-fast guard (AC-08). isConnected returns\n // false when the canvas is not in the document tree, including freshly\n // document.createElement('canvas') without appendChild. Returning\n // Result.err here short-circuits before createRenderer fires off any\n // async adapter / device / shader work that would only fail later.\n if (!canvas.isConnected) {\n return err(\n makeAppError(\n 'app-canvas-detached',\n 'canvas.isConnected === true at createApp(canvas) entry',\n 'append the canvas to the document tree before calling createApp; or use the assemble entry createApp({ renderer, world }) when the host already manages canvas lifetime',\n {},\n ),\n );\n }\n\n // The DOM canvas starts with a 300x150 drawing buffer even when CSS lays it\n // out at a different size. Set the physical buffer before the renderer\n // configures its swap chain; the same helper runs before each frame so a CSS\n // resize remains visible to both rendering and camera policy.\n syncCanvasDrawingBuffer(canvas);\n\n let executionBootstrapUrl: string | undefined;\n if (opts?.execution !== undefined) {\n const normalizedBootstrap = normalizeExecutionBootstrapUrl(opts.execution.bootstrap);\n if (!normalizedBootstrap.ok) return err(normalizedBootstrap.error);\n executionBootstrapUrl = normalizedBootstrap.value;\n const realmBoundOption = [\n ['features', opts.features],\n ['plugins', opts.plugins],\n ['rhi', opts.rhi],\n ['rhiInstrumentation', opts.rhiInstrumentation],\n ['drawSource', opts.drawSource],\n ['bundler.importTransport', bundler?.importTransport],\n ].find(([, value]) => value !== undefined)?.[0];\n if (realmBoundOption !== undefined) {\n return err(\n makeAppError(\n 'app-execution-bootstrap-failed',\n APP_EXPECTED['app-execution-bootstrap-failed'],\n APP_ERROR_HINTS['app-execution-bootstrap-failed'],\n {\n phase: 'prepare',\n moduleUrl: executionBootstrapUrl,\n cause: new TypeError(\n `${realmBoundOption} must be constructed by the execution bootstrap module`,\n ),\n },\n ),\n );\n }\n }\n\n let executionContext:\n | {\n readonly capabilities: import('./execution').ExecutionCapabilities;\n readonly selection: import('./execution').ExecutionSelection;\n }\n | undefined;\n let preparedExecutionBootstrap: PreparedExecutionBootstrap | undefined;\n if (opts?.execution !== undefined) {\n const capabilities = await probeExecutionCapabilities(canvas);\n const selected = selectExecutionTier({\n requestedTier: opts.execution.tier ?? 'auto',\n capabilities,\n sharedEvidencePassed: true,\n });\n if (!selected.ok) return err(selected.error);\n executionContext = { capabilities, selection: selected.value };\n if (selected.value.actualTier !== 'main-serial') {\n return createWorkerExecutionApp({\n canvas,\n appOptions: opts,\n syncCanvas: () => measureCanvasDrawingBuffer(canvas),\n ...(bundler !== undefined ? { bundler } : {}),\n capabilities,\n selection: selected.value,\n });\n }\n if (executionBootstrapUrl === undefined) {\n throw new Error('execution bootstrap URL was not normalized');\n }\n const prepared = await prepareBootstrapEntry(\n executionBootstrapUrl,\n opts.execution.bootstrapData,\n );\n if (!prepared.ok) return err(prepared.error);\n preparedExecutionBootstrap = prepared.value;\n }\n\n // Step 2: createRenderer try/catch -> Result.err(EngineEnvironmentError)\n // (AC-01 / research section 2.2). createRenderer throws at\n // createRenderer.ts:400 / :429 (rhi pack load failure /\n // all WebGPU channels unavailable); we forward the original\n // EngineEnvironmentError instance verbatim to preserve the\n // .detail.webgpuError surface. RhiError instances raised mid-\n // construction are also forwarded -- the AppError | RhiError leg of\n // the union covers them. Any other unexpected throw is also\n // forwarded to keep the contract honest (AI users walk the union\n // discriminant rather than parse error.message strings).\n // feat-20260608 / M2 / D-3: CreateAppOptions stops `extends RendererOptions`,\n // so the RHI escape hatch (rhi) is\n // forwarded explicitly. Build a RendererOptions object out of just those\n // fields when present; an empty {} keeps createRenderer on its default path.\n const rendererOpts: import('@forgeax/engine-render').RendererOptions = {};\n if (opts?.rhi !== undefined) {\n Object.assign(rendererOpts, { rhi: opts.rhi });\n }\n if (opts?.profiler !== undefined) {\n Object.assign(rendererOpts, { profiler: opts.profiler });\n }\n const rendererFeatures = preparedExecutionBootstrap?.features ?? opts?.features;\n if (rendererFeatures !== undefined) {\n Object.assign(rendererOpts, { features: rendererFeatures });\n }\n if (opts?.standardProfile !== undefined) {\n Object.assign(rendererOpts, { standardProfile: opts.standardProfile });\n }\n if (opts?.rhiInstrumentation !== undefined) {\n Object.assign(rendererOpts, { rhiInstrumentation: opts.rhiInstrumentation });\n }\n\n // FORGEAX_ENGINE_RHI_DEBUG=1 attaches the recorder at the Runtime backend\n // seam. Render remains the owner of device/surface lifecycle; App only owns\n // the optional capture capability and its frame transaction.\n let rhiAttachment: RecorderAttachment | undefined;\n let rhiCapture: RhiCapture | undefined;\n let rhiDebugGlobal:\n | { captureFrame(options?: CaptureFrameOptions): ReturnType<RhiCapture['captureFrame']> }\n | undefined;\n const cleanupRhiDebugHost = (): void => {\n const host = globalThis as { __forgeax?: typeof rhiDebugGlobal };\n if (host.__forgeax === rhiDebugGlobal) delete host.__forgeax;\n rhiDebugGlobal = undefined;\n const attachment = rhiAttachment;\n rhiAttachment = undefined;\n if (attachment !== undefined) void attachment.dispose();\n };\n // Read FORGEAX_ENGINE_RHI_DEBUG from two sources (plan-strategy D-4):\n // - browser: import.meta.env, statically replaced by the\n // vite-plugin-rhi-debug `define` hook. The `typeof import.meta !==\n // 'undefined'` prefix short-circuits under dawn-node, where import.meta\n // itself can be undefined (C5).\n // - dawn-node: globalThis.process.env (no vite define on the native path).\n // resolveRhiDebugFlag (internal/rhi-debug-flag) is the SSOT for the `??`\n // precedence; the source bags are computed inline here so the\n // typeof-import.meta prefix stays at the call site. Keeps this file\n // @types/node-free (engine-app ships ESM into both browser + dawn-node;\n // same pattern as runtime/src/render-system-record.ts:isMeshSsboDevMode).\n // Keep the Vite define key in a direct property expression. Wrapping\n // `import.meta` in a structural cast hides the token from Vite's define\n // pass, so production builds retain the debug-only dynamic chunks even when\n // the Preview host explicitly sets the flag to `0`. Optional chaining keeps\n // the package safe on the Dawn/Node path where `import.meta.env` is absent.\n const importMetaEnv =\n typeof import.meta !== 'undefined'\n ? { FORGEAX_ENGINE_RHI_DEBUG: import.meta.env?.FORGEAX_ENGINE_RHI_DEBUG }\n : undefined;\n // A browser production build must be able to erase the entire recorder\n // branch. The `undefined` arm preserves Dawn/Node's process.env fallback;\n // Vite replaces the direct property with `\"0\"` or `\"1\"`, making this outer\n // guard a literal false/true before Rollup sees the debug-only imports.\n const browserBuildRhiDebugFlag =\n typeof import.meta !== 'undefined' ? import.meta.env?.FORGEAX_ENGINE_RHI_DEBUG : undefined;\n const processEnv = (globalThis as { process?: { env?: { FORGEAX_ENGINE_RHI_DEBUG?: string } } })\n .process?.env;\n const rhiDebugFlag = resolveRhiDebugFlag(importMetaEnv, processEnv);\n const nav: { gpu?: unknown } | undefined =\n typeof globalThis !== 'undefined'\n ? (globalThis as { navigator?: { gpu?: unknown } }).navigator\n : undefined;\n const hasWebGPU = nav !== undefined && 'gpu' in nav && nav.gpu !== undefined;\n if (\n (browserBuildRhiDebugFlag === undefined || browserBuildRhiDebugFlag === '1') &&\n rhiDebugFlag === '1'\n ) {\n const realBackend = (hasWebGPU\n ? await import('@forgeax/engine-rhi-webgpu')\n : await import('@forgeax/engine-rhi-wgpu')) as unknown as Record<string, unknown>;\n if (!hasWebGPU && 'ensureReady' in realBackend) {\n await (realBackend.ensureReady as () => Promise<unknown>)();\n }\n const pack = loadRhiPack(realBackend);\n if (pack.createShaderModule === undefined) {\n throw new Error('RHI-debug requires a backend createShaderModule capability');\n }\n const attached = attachRecorder({\n rhi: pack.rhi,\n createShaderModule: pack.createShaderModule,\n });\n if (!attached.ok) throw new Error(attached.error.hint);\n rhiAttachment = attached.value;\n rhiCapture = createRhiCapture(attached.value);\n const capture = rhiCapture;\n rhiDebugGlobal = { captureFrame: (options) => capture.captureFrame(options) };\n Object.assign(rendererOpts, {\n rhi: attached.value.backend.rhi,\n rhiInstrumentation: createRhiInstrumentation(attached.value),\n });\n (globalThis as { __forgeax?: typeof rhiDebugGlobal }).__forgeax = rhiDebugGlobal;\n }\n\n let renderer: Renderer;\n let rendererDebugDrawHost: RendererHostAssembly['debugDrawHost'];\n let rendererFeatureHost: RenderFeatureHost;\n let assets: AssetRegistry;\n try {\n const constructed = await constructRuntimeRendererHost(canvas, rendererOpts, bundler);\n if (!constructed.ok) throw constructed.error;\n renderer = constructed.value.renderer;\n rendererDebugDrawHost = constructed.value.debugDrawHost;\n rendererFeatureHost = createRenderFeatureHost(constructed.value.featureHost);\n assets = constructed.value.assets;\n } catch (e: unknown) {\n cleanupRhiDebugHost();\n if (e instanceof EngineEnvironmentError) return err(e);\n const detail = e instanceof Error ? e : new Error(String(e));\n return err(\n new EngineEnvironmentError('renderer construction failed', {\n webgpuError: detail,\n }),\n );\n }\n\n // Step 2.4 decision: resolve whether the remote eval server should start\n // (feat-20260629-inspector-two-layer-model M4 / w20). Dual-source gating\n // mirrors the rhi-debug-flag pattern. The actual startServer call is\n // deferred to after World creation (Step 3) because the server needs\n // a live World reference.\n const shouldStartRemote = resolveRemoteServeFlag(\n typeof import.meta !== 'undefined'\n ? (import.meta as { env?: { DEV?: boolean } }).env?.DEV\n : undefined,\n (globalThis as { process?: { env?: { FORGEAX_ENGINE_REMOTE_SERVE?: string } } }).process?.env,\n );\n\n let debugDraw: DebugDraw | undefined;\n\n // Step 3: new World() -- the canvas form owns world lifetime, in\n // contrast to the assemble form where the host owns it.\n const world = new World(opts?.time !== undefined ? { time: opts.time } : {});\n // Step 3.1 (M2 plugin-system-unify / D-4): app-layer side effects that the\n // plugins consume via pre-injected world resources.\n //\n // Animation keeps durable clip GUIDs in graph payloads. The canvas default\n // plugin receives the renderer-owned GUID catalogue as a lookup bridge; it\n // still projects payloads into this World through the animation owner.\n // transform + animation system registration lives in the plugins (default set).\n\n // A normal canvas app owns its browser acquisition. An embedding host that\n // shares this physical canvas with another world supplies its routed view via\n // opts.input; createApp then consumes that one boundary instead of attaching a\n // second listener set. The host owns the supplied backend's lifetime.\n const inputHandle =\n opts?.input === undefined\n ? attachInputAuto(canvas, {\n ...(opts?.uiRoot ? { uiRoot: opts.uiRoot } : {}),\n ...(opts?.pointerLockAllowed ? { pointerLockAllowed: opts.pointerLockAllowed } : {}),\n ...(opts?.virtualJoysticks ? { virtualJoysticks: opts.virtualJoysticks } : {}),\n ...(opts?.lockProvider ? { lockProvider: opts.lockProvider } : {}),\n })\n : undefined;\n const inputBackend = opts?.input ?? inputHandle?.backend;\n const userPlugins =\n preparedExecutionBootstrap === undefined\n ? (opts?.plugins ?? [])\n : [\n executionBootstrapHostPlugin({\n ...(opts?.execution?.bootstrapPort === undefined\n ? {}\n : { port: opts.execution.bootstrapPort }),\n setPointerLockAllowed: (allowed) => inputBackend?.setPointerLockAllowed?.(allowed),\n }),\n ...(preparedExecutionBootstrap.plugins ?? []),\n ];\n let pluginContext: Context;\n try {\n pluginContext = await createWorldContext(\n world,\n mainEngineProfile({\n renderer,\n rendererDebugDrawHost,\n rendererFeatureHost,\n assets,\n animationPayloads: createAnimationPayloadLookup(assets),\n ...(inputBackend === undefined ? {} : { input: inputBackend }),\n ...(inputHandle === undefined ? {} : { inputDispose: inputHandle.cleanup }),\n ...(opts?.inputMap === undefined ? {} : { inputMap: opts.inputMap }),\n onDebugDrawReady: (value) => {\n debugDraw = value;\n },\n extensions: [\n rhiDebugHostPlugin(cleanupRhiDebugHost),\n ...userPlugins,\n canvasAspectPlugin(canvas),\n ],\n }),\n );\n } catch (cause) {\n cleanupRhiDebugHost();\n return err(\n makeAppError(\n 'app-plugin-activation-failed',\n APP_EXPECTED['app-plugin-activation-failed'],\n APP_ERROR_HINTS['app-plugin-activation-failed'],\n { cause },\n ),\n );\n }\n const audioBackend = pluginContext.audio;\n\n const executionControl = createLocalExecutionControl(\n executionContext === undefined\n ? {\n ...createExecutionReport('main-serial', unavailableExecutionCapabilities('not required')),\n actualTier: 'main-serial',\n selectionReason: 'explicit-request',\n sharedEvidencePassed: true,\n engine: { realm: 'host', health: 'idle' },\n world: {\n identity: world.identity,\n health: world.execution.health,\n partialWrite: false,\n retryable: true,\n },\n }\n : {\n ...createExecutionReport(\n opts?.execution?.tier ?? 'auto',\n executionContext.capabilities,\n executionContext.selection,\n ),\n engine: { realm: 'host', health: 'idle' },\n world: {\n identity: world.identity,\n health: world.execution.health,\n partialWrite: false,\n retryable: true,\n },\n },\n {\n ...(audioBackend === undefined ? {} : { audio: () => audioBackend.getState() }),\n world: () => ({\n identity: world.identity,\n health: world.execution.health,\n partialWrite: world.execution.fault?.partialWrite ?? false,\n retryable: world.execution.fault?.retryable ?? true,\n }),\n },\n );\n\n // Step 3.3: Remote eval server auto-start (deferred from Step 2.4 so\n // World is available). Dynamic import keeps @forgeax/engine-app free\n // of static dep on @forgeax/engine-remote. Component reflection crosses\n // this boundary as JSON-safe host data; app does not own any component.\n const remoteHandle = shouldStartRemote\n ? await startRemoteServer(world, renderer, assets, rhiCapture, opts?.profiler, executionControl)\n : undefined;\n if (remoteHandle !== undefined) await pluginContext.plugin(remoteServerPlugin(remoteHandle));\n\n const buildArgs: BuildAppArgs = {\n renderer,\n assets,\n world,\n pluginContext,\n executionControl,\n onFrameSubmitted: (event) => publishBrowserFrameSubmitted(canvas, event),\n ...(inputBackend !== undefined ? { inputBackend } : {}),\n ...(inputHandle === undefined\n ? {}\n : {\n wireOnLockErrorDispatch: (dispatch: (err: AppError) => void) => {\n inputHandle.setOnErrorDispatch(dispatch);\n },\n }),\n };\n if (audioBackend !== undefined) {\n Object.assign(buildArgs, {\n audioBackend,\n });\n }\n if (opts?.silenceUnhandledErrors !== undefined) {\n Object.assign(buildArgs, { silenceUnhandledErrors: opts.silenceUnhandledErrors });\n }\n // M2 / D-3: canvas form forwards the host-supplied draw-source pull.\n if (opts?.drawSource !== undefined) {\n Object.assign(buildArgs, { drawSource: opts.drawSource });\n }\n if (opts?.profiler !== undefined) {\n Object.assign(buildArgs, { profiler: opts.profiler });\n }\n if (rhiCapture !== undefined) {\n Object.assign(buildArgs, { rhiCapture });\n }\n if (debugDraw !== undefined) {\n Object.assign(buildArgs, { debugDraw });\n }\n if (remoteHandle !== undefined) {\n Object.assign(buildArgs, { remoteHandle });\n }\n\n // The aspect-sync sidecar belongs to the canvas path because it owns the DOM\n // canvas. It runs as an Update system so it shares World scheduling semantics.\n resetBrowserFrameSubmitted(canvas);\n const built = await buildApp(buildArgs);\n if (!built.ok) {\n await pluginContext.fiber.dispose();\n return built;\n }\n if (built.ok) {\n // DEV-only browser remote bridge (remote-live). A browser cannot host the\n // Node WS server that @forgeax/engine-remote/server needs, so the running\n // engine would be unreachable from a CLI in a real dev browser. Instead the\n // page dials OUT to a loopback relay and runs the ws-free eval core against\n // the live world/renderer/assets/rhiCapture.\n //\n // OPT-IN via VITE_FORGEAX_ENGINE_BRIDGE=1 (set by scripts/dev-live.mjs), NOT\n // on-by-default: a page that dials a relay which is not running makes the\n // BROWSER itself log \"WebSocket connection failed\" to the console — noise a\n // JS catch cannot suppress — which trips every zero-console-error browser\n // smoke (collectathon / hello-*). So a plain `pnpm --filter <app> dev` (and\n // CI) stays silent; only dev-live.mjs, which also launches the relay, turns\n // it on. Production DCE's the whole block (import.meta.env.DEV === false).\n // Additive: the Node startServer path above and app.remote are untouched.\n if (\n typeof import.meta !== 'undefined' &&\n (import.meta as { env?: { DEV?: boolean; VITE_FORGEAX_ENGINE_BRIDGE?: string } }).env?.DEV ===\n true &&\n (import.meta as { env?: { VITE_FORGEAX_ENGINE_BRIDGE?: string } }).env\n ?.VITE_FORGEAX_ENGINE_BRIDGE === '1'\n ) {\n const bridgePort =\n (import.meta as { env?: { VITE_FORGEAX_ENGINE_BRIDGE_PORT?: string } }).env\n ?.VITE_FORGEAX_ENGINE_BRIDGE_PORT ?? '5733';\n await pluginContext.plugin({\n name: 'browser-remote-bridge',\n inject: ['world', 'renderer', 'assets'],\n async apply(ctx) {\n if (ctx.renderer === undefined || ctx.assets === undefined) {\n throw new Error('browser remote bridge requires renderer and assets services');\n }\n try {\n const bridge = await import('./internal/browser-remote-bridge');\n const teardown = await bridge.installBrowserRemoteBridge({\n world: ctx.world,\n renderer: ctx.renderer,\n assets: ctx.assets,\n runtimeModule: engineRuntimeModule,\n ...(rhiCapture !== undefined ? { rhiCapture } : {}),\n ...(opts?.profiler !== undefined ? { profiler: opts.profiler } : {}),\n execution: built.value.execution,\n port: bridgePort,\n });\n ctx.effect(() => teardown, 'remote/browser-bridge');\n } catch {\n // The optional live bridge does not make App creation fail.\n }\n },\n });\n }\n }\n return built;\n}\n\n/**\n * Synchronize a DOM canvas drawing buffer with its CSS size and device pixel\n * ratio. Detached or zero-sized hosts are left untouched so a hidden canvas\n * cannot be converted into a 1x1 render target accidentally.\n */\nexport function syncCanvasDrawingBuffer(\n canvas: Pick<HTMLCanvasElement, 'clientWidth' | 'clientHeight' | 'width' | 'height'> & {\n readonly style?: Pick<CSSStyleDeclaration, 'width' | 'height'>;\n },\n): void {\n if (\n !Number.isFinite(canvas.clientWidth) ||\n !Number.isFinite(canvas.clientHeight) ||\n canvas.clientWidth <= 0 ||\n canvas.clientHeight <= 0\n )\n return;\n // An intrinsic canvas with no CSS dimensions already has an explicit\n // drawing-buffer contract. `clientWidth` mirrors `width` for this shape;\n // multiplying it by DPR would change the caller's requested pixel size and\n // can feed that new width back as the next layout measurement. CSS-sized\n // canvases take the DPR path below (including stylesheet-sized canvases\n // whose layout width differs from the initial intrinsic width).\n const hasExplicitCssSize =\n (canvas.style?.width ?? '') !== '' || (canvas.style?.height ?? '') !== '';\n if (\n !hasExplicitCssSize &&\n canvas.clientWidth === canvas.width &&\n canvas.clientHeight === canvas.height\n ) {\n return;\n }\n const dpr = Math.max(1, globalThis.devicePixelRatio || 1);\n const previous = syncedCanvasSizes.get(canvas);\n const drawingBufferIsTheLayoutMeasurement =\n previous !== undefined &&\n canvas.width === previous.drawingWidth &&\n canvas.height === previous.drawingHeight &&\n canvas.clientWidth === previous.drawingWidth &&\n canvas.clientHeight === previous.drawingHeight;\n const cssWidth = drawingBufferIsTheLayoutMeasurement ? previous.cssWidth : canvas.clientWidth;\n const cssHeight = drawingBufferIsTheLayoutMeasurement ? previous.cssHeight : canvas.clientHeight;\n const width = Math.max(1, Math.round(cssWidth * dpr));\n const height = Math.max(1, Math.round(cssHeight * dpr));\n if (canvas.width !== width) canvas.width = width;\n if (canvas.height !== height) canvas.height = height;\n syncedCanvasSizes.set(canvas, {\n cssWidth,\n cssHeight,\n drawingWidth: width,\n drawingHeight: height,\n });\n}\n\n/** Measure a CSS-sized canvas without mutating its drawing buffer. */\nexport function measureCanvasDrawingBuffer(\n canvas: Pick<HTMLCanvasElement, 'clientWidth' | 'clientHeight' | 'width' | 'height'> & {\n readonly style?: Pick<CSSStyleDeclaration, 'width' | 'height'>;\n },\n maxCanvasPixelRatio?: number,\n): { readonly width: number; readonly height: number } {\n if (\n !Number.isFinite(canvas.clientWidth) ||\n !Number.isFinite(canvas.clientHeight) ||\n canvas.clientWidth <= 0 ||\n canvas.clientHeight <= 0\n ) {\n return { width: canvas.width, height: canvas.height };\n }\n const hasExplicitCssSize =\n (canvas.style?.width ?? '') !== '' || (canvas.style?.height ?? '') !== '';\n if (\n !hasExplicitCssSize &&\n canvas.clientWidth === canvas.width &&\n canvas.clientHeight === canvas.height\n ) {\n return { width: canvas.width, height: canvas.height };\n }\n const devicePixelRatio = Math.max(1, globalThis.devicePixelRatio || 1);\n const dpr =\n maxCanvasPixelRatio === undefined ||\n !Number.isFinite(maxCanvasPixelRatio) ||\n maxCanvasPixelRatio <= 0\n ? devicePixelRatio\n : Math.min(devicePixelRatio, maxCanvasPixelRatio);\n const previous = syncedCanvasSizes.get(canvas);\n const drawingBufferIsTheLayoutMeasurement =\n previous !== undefined &&\n canvas.width === previous.drawingWidth &&\n canvas.height === previous.drawingHeight &&\n canvas.clientWidth === previous.drawingWidth &&\n canvas.clientHeight === previous.drawingHeight;\n const cssWidth = drawingBufferIsTheLayoutMeasurement ? previous.cssWidth : canvas.clientWidth;\n const cssHeight = drawingBufferIsTheLayoutMeasurement ? previous.cssHeight : canvas.clientHeight;\n return {\n width: Math.max(1, Math.round(cssWidth * dpr)),\n height: Math.max(1, Math.round(cssHeight * dpr)),\n };\n}\n\nconst syncedCanvasSizes = new WeakMap<\n object,\n {\n readonly cssWidth: number;\n readonly cssHeight: number;\n readonly drawingWidth: number;\n readonly drawingHeight: number;\n }\n>();\n\n/**\n * Per-frame aspect-sync body for the createApp(canvas) path (feat-20260617\n * M3 / w13). Walks every Camera entity and, for perspective cameras with\n * `autoAspect === true`, writes `canvasW / canvasH` into `Camera.aspect`.\n *\n * Read discipline (D-5 / research Finding 2): `autoAspect` is read through\n * `world.get` (the readRow path narrows the bool column to a JS boolean).\n * The query bundle is used only to enumerate the entity handles -- reading\n * the bool column off the bundle would return a raw 0/1 number, so a\n * `!== 0` test is always true (the\n * bool-field-compared-with-not-equal-zero-always-true trap).\n *\n * Best-effort + side-effect-isolated:\n * - canvas size 0 (detached / display:none) -> skip entirely so `aspect`\n * never becomes NaN / 0.\n * - orthographic cameras and `autoAspect === false` cameras are left\n * untouched.\n *\n * @see {@link https://github.com/Ubpa/forgeax-engine/blob/main/docs/how-to/2026-06-18-host-engine-contract.md | Host-engine contract SSOT}\n */\nexport function syncCameraAspect(world: World, canvasW: number, canvasH: number): void {\n // Guard against detached / zero-sized canvases: a 0 width or height would\n // write NaN (0 / 0) or 0 into aspect and corrupt the projection matrix.\n if (canvasW <= 0 || canvasH <= 0) return;\n const aspect = canvasW / canvasH;\n\n const query = world.query({ with: [Camera] }).unwrap();\n for (const row of query) {\n const entity = row.entity;\n const r = world.get(entity, Camera);\n if (!r.ok) continue;\n // world.get narrows the bool column to a real boolean (D-5); the\n // perspective discriminator is the numeric column value.\n if (r.value.autoAspect !== true) continue;\n if (r.value.projection !== CAMERA_PROJECTION_PERSPECTIVE) continue;\n if (r.value.aspect === Math.fround(aspect)) continue;\n world.set(entity, Camera, { aspect });\n }\n}\n\nasync function startRemoteServer(\n world: World,\n renderer: Renderer,\n assets: AssetRegistry | undefined,\n rhiCapture: RhiCapture | undefined,\n profiler: import('@forgeax/engine-profiler').Profiler | undefined,\n execution: ExecutionControl,\n): Promise<{ readonly port: number; close(): Promise<void> } | undefined> {\n try {\n const remoteServerMod = (await import(\n /* @vite-ignore */ '@forgeax/engine-remote/server'\n )) as unknown as {\n startServer: (opts: {\n port: number;\n host?: string;\n world: unknown;\n renderer?: unknown;\n assets?: unknown;\n rhiCapture?: unknown;\n introspection?: readonly unknown[];\n profiler?: unknown;\n execution?: unknown;\n }) => Promise<{\n ok: boolean;\n value?: { port: number; close(): Promise<void> };\n }>;\n };\n const serverResult = await remoteServerMod.startServer({\n port: 0,\n host: '127.0.0.1',\n world,\n renderer,\n assets,\n introspection: projectComponentIntrospection(world.components.entries()),\n ...(rhiCapture !== undefined ? { rhiCapture } : {}),\n ...(profiler !== undefined ? { profiler } : {}),\n execution,\n });\n if (serverResult.ok && serverResult.value !== undefined) {\n return { port: serverResult.value.port, close: serverResult.value.close };\n }\n } catch (_error) {\n // Dynamic import or server start failed; the app continues without remote.\n }\n return undefined;\n}\n\nasync function createAppFromAssemble(\n args: AppAssembleArgs,\n): Promise<Result<App, AssembleAppError>> {\n let pluginContext: Context;\n try {\n pluginContext = await createWorldContext(\n args.world,\n assembledEngineProfile({\n renderer: args.renderer,\n ...(args.assets === undefined ? {} : { assets: args.assets }),\n extensions: args.plugins ?? [],\n }),\n );\n } catch (cause) {\n return err(\n makeAppError(\n 'app-plugin-activation-failed',\n APP_EXPECTED['app-plugin-activation-failed'],\n APP_ERROR_HINTS['app-plugin-activation-failed'],\n { cause },\n ),\n );\n }\n\n const shouldStartRemote = resolveRemoteServeFlag(\n undefined,\n (globalThis as { process?: { env?: { FORGEAX_ENGINE_REMOTE_SERVE?: string } } }).process?.env,\n );\n const assembledAudioBackend = pluginContext.audio;\n const executionControl = createLocalExecutionControl(\n {\n ...createExecutionReport('main-serial', unavailableExecutionCapabilities('not required')),\n actualTier: 'main-serial',\n selectionReason: 'explicit-request',\n sharedEvidencePassed: true,\n engine: { realm: 'host', health: 'idle' },\n world: {\n identity: args.world.identity,\n health: args.world.execution.health,\n partialWrite: false,\n retryable: true,\n },\n },\n {\n ...(assembledAudioBackend === undefined\n ? {}\n : { audio: () => assembledAudioBackend.getState() }),\n world: () => ({\n identity: args.world.identity,\n health: args.world.execution.health,\n partialWrite: args.world.execution.fault?.partialWrite ?? false,\n retryable: args.world.execution.fault?.retryable ?? true,\n }),\n },\n );\n const remoteHandle = shouldStartRemote\n ? await startRemoteServer(\n args.world,\n args.renderer,\n args.assets,\n undefined,\n args.profiler,\n executionControl,\n )\n : undefined;\n if (remoteHandle !== undefined) await pluginContext.plugin(remoteServerPlugin(remoteHandle));\n\n const buildArgs: BuildAppArgs = {\n renderer: args.renderer,\n world: args.world,\n pluginContext,\n executionControl,\n ...(remoteHandle !== undefined ? { remoteHandle } : {}),\n };\n\n const assembledInputBackend = pluginContext.input;\n if (assembledInputBackend !== undefined) {\n Object.assign(buildArgs, {\n inputBackend: assembledInputBackend,\n });\n }\n if (assembledAudioBackend !== undefined) {\n Object.assign(buildArgs, {\n audioBackend: assembledAudioBackend,\n });\n }\n if (args.silenceUnhandledErrors !== undefined) {\n Object.assign(buildArgs, { silenceUnhandledErrors: args.silenceUnhandledErrors });\n }\n // M2 / D-3: assemble form forwards the host-supplied draw-source pull.\n if (args.drawSource !== undefined) {\n Object.assign(buildArgs, { drawSource: args.drawSource });\n }\n if (args.profiler !== undefined) {\n Object.assign(buildArgs, { profiler: args.profiler });\n }\n const built = await buildApp(buildArgs);\n if (!built.ok) await pluginContext.fiber.dispose();\n return built;\n}\n\ninterface BuildAppArgs {\n readonly renderer: Renderer;\n readonly assets?: AssetRegistry;\n readonly world: World;\n readonly pluginContext: Context;\n readonly inputBackend?: InputBackend;\n /**\n * M2 D-4: callback that buildApp calls after creating the ErrorFanoutRegistry\n * dispatch function. The input handle's onLockError callback needs the dispatch\n * function to fan out 'app-pointer-lock-failed' errors, but the dispatch function\n * is created inside buildApp (after the input handle is already constructed).\n * This callback bridges the gap.\n */\n readonly wireOnLockErrorDispatch?: (dispatch: (err: AppError) => void) => void;\n readonly audioBackend?: AudioBackend;\n readonly silenceUnhandledErrors?: boolean;\n /** Optional App-owned RHI capture capability. */\n readonly rhiCapture?: RhiCapture;\n /** feat-20260615 debug-draw M5: DebugDraw instance created by createDebugDrawOnReady. */\n readonly debugDraw?: DebugDraw;\n /** feat-20260629 M4 / w20: remote eval server handle from createAppFromCanvas. */\n readonly remoteHandle?: { readonly port: number; close(): Promise<void> };\n /**\n * feat-20260709-editor-world-partition-editorworld-super-composite / M2 / D-3:\n * per-frame draw-source pull forwarded verbatim into the frame-loop. Absent =>\n * the allocation-free primary-World path. Both createApp forms (canvas + assemble) forward\n * it from their respective options object.\n */\n readonly drawSource?: () =>\n | {\n worlds: readonly import('@forgeax/engine-ecs').World[];\n cameraOwner: number;\n resourceOwner: number;\n }\n | undefined;\n readonly profiler?: import('@forgeax/engine-profiler').Profiler;\n readonly executionControl?: import('./execution/control').LocalExecutionControl;\n /** Canvas-form projection of the Renderer frame-submitted event. */\n readonly onFrameSubmitted?: (event: {\n readonly frameId: number;\n readonly deviceGeneration: number;\n }) => void;\n}\n\n/**\n * Internal builder shared by both overloads. Wires the frame-loop +\n * listener-registry onError and returns the App handle. Effectful ownership\n * has already moved into pluginContext before this boundary runs.\n */\nasync function buildApp(args: BuildAppArgs): Promise<Result<App, AppError | RhiError>> {\n const {\n renderer,\n world,\n pluginContext,\n inputBackend,\n audioBackend,\n silenceUnhandledErrors,\n rhiCapture,\n debugDraw,\n remoteHandle,\n profiler,\n } = args;\n\n // Physics is a Context service; the App exposes the active provider without\n // storing a second mutable slot.\n function readPhysicsWorld():\n | import('@forgeax/engine-physics').PhysicsWorld\n | import('@forgeax/engine-physics').PhysicsWorld2D\n | undefined {\n return pluginContext.physics;\n }\n // M4 (w11): listener registry replaces the M3 inline Set so console.error\n // fallback + duplicate-add no-op + unsubscribe handle behaviour matches\n // packages/runtime/src/createRenderer.ts:532-566 LostListenerRegistry\n // (plan-strategy D-9). silenceUnhandledErrors threads through verbatim.\n const fanout = new ErrorFanoutRegistry(\n silenceUnhandledErrors !== undefined ? { silenceUnhandledErrors } : {},\n );\n let lastError: AppDispatchError | undefined;\n const execution =\n args.executionControl ??\n createLocalExecutionControl(\n {\n ...createExecutionReport('main-serial', unavailableExecutionCapabilities('not required')),\n actualTier: 'main-serial',\n selectionReason: 'explicit-request',\n sharedEvidencePassed: true,\n engine: { realm: 'host', health: 'idle' },\n world: {\n identity: world.identity,\n health: world.execution.health,\n partialWrite: world.execution.fault?.partialWrite ?? false,\n retryable: world.execution.fault?.retryable ?? true,\n },\n },\n {\n ...(audioBackend === undefined ? {} : { audio: () => audioBackend.getState() }),\n world: () => ({\n identity: world.identity,\n health: world.execution.health,\n partialWrite: world.execution.fault?.partialWrite ?? false,\n retryable: world.execution.fault?.retryable ?? true,\n }),\n },\n );\n\n function dispatch(e: AppDispatchError): void {\n lastError = e;\n fanout.fire(e);\n }\n\n // M2 D-4: wire the input handle's onLockError callback to the error fan-out.\n // The dispatch function is created here; the input handle was created earlier\n // in createAppFromCanvas and passed to buildApp with a wireOnLockErrorDispatch\n // callback that calls setOnErrorDispatch on the handle.\n if (args.wireOnLockErrorDispatch) {\n args.wireOnLockErrorDispatch(dispatch);\n }\n\n const loopOpts: Parameters<typeof createFrameLoop>[0] = {\n world,\n renderer,\n onError: dispatch,\n };\n // M2 / D-3: forward the optional draw-source pull into the frame-loop. Absent\n // => the loop keeps the allocation-free primary-World draw path.\n if (args.drawSource !== undefined) {\n Object.assign(loopOpts, { drawSource: args.drawSource });\n }\n if (profiler !== undefined) {\n Object.assign(loopOpts, { profiler });\n }\n const loop = createFrameLoop(loopOpts);\n if (rhiCapture !== undefined) {\n bindRhiCaptureFrameDriver(rhiCapture, {\n getState: () => loop.getState(),\n pause: () => {\n const result = loop.pause();\n if (result.ok) execution.setEngineHealth('idle');\n return result;\n },\n resume: () => {\n const result = loop.resume();\n if (result.ok) execution.setEngineHealth('running');\n return result;\n },\n stepFrame: (deltaSeconds) => loop.stepFrame(deltaSeconds),\n });\n }\n // M4 (w13) device-lost internal subscription. R-1 timing contract:\n // app.start() arms the rAF handle BEFORE this listener subscribes, so\n // a synchronous late-attach replay of a persisted device-lost event\n // (LostListenerRegistry replay -- runtime/src/renderer.ts:337-345)\n // hits a frame-loop with a real rAF handle to cancel (M2 setStopped\n // tolerates pendingFrameId === 0 as a no-op so even pre-rAF replays\n // do not NPE). The subscription remains active across pause / resume;\n // unsubscribe runs only on stop / disposal (charter P3:\n // device-lost is a terminal lifecycle signal, not a transient blip).\n let rendererUnsubscribe: (() => void) | undefined;\n let resumeAfterSurfaceRestore = false;\n\n function subscribeRendererErrors(): void {\n if (rendererUnsubscribe !== undefined) {\n return;\n }\n rendererUnsubscribe = renderer.subscribe((event) => {\n if (event.kind === 'frame-submitted') {\n args.onFrameSubmitted?.(event);\n return;\n }\n if (event.kind !== 'error') return;\n const e: RenderError = event.error;\n dispatch(e);\n });\n }\n\n function unsubscribeRendererErrors(): void {\n if (rendererUnsubscribe !== undefined) {\n rendererUnsubscribe();\n rendererUnsubscribe = undefined;\n }\n }\n\n const stub: App = {\n renderer,\n ...(args.assets === undefined ? {} : { assets: args.assets }),\n world,\n execution,\n async releaseSurfacePreserveWorld(): Promise<Result<void, RhiError | RenderError>> {\n if (loop.getState() === 'running') {\n const paused = loop.pause();\n if (!paused.ok) {\n return err(\n new RhiError({\n code: 'rhi-not-available',\n expected: 'running App pauses before releasing its presentation surface',\n hint: paused.error.hint,\n }),\n );\n }\n resumeAfterSurfaceRestore = true;\n execution.setEngineHealth('idle');\n }\n // A surface handoff can be requested by an Update system while the\n // current frame is still in progress. Let that frame reach renderer.draw\n // before unconfiguring the surface; pause() only cancels the next rAF.\n await Promise.resolve();\n const released = renderer.releaseSurface();\n if (!released.ok && resumeAfterSurfaceRestore) {\n loop.resume();\n resumeAfterSurfaceRestore = false;\n execution.setEngineHealth('running');\n }\n return released.ok ? ok(undefined) : err(released.error);\n },\n async restoreSurface(): Promise<Result<void, RhiError | RenderError>> {\n const restored = renderer.restoreSurface();\n if (!restored.ok) return err(restored.error);\n if (resumeAfterSurfaceRestore) {\n const resumed = loop.resume();\n if (!resumed.ok) {\n return err(\n new RhiError({\n code: 'rhi-not-available',\n expected: 'paused App resumes after restoring its presentation surface',\n hint: resumed.error.hint,\n }),\n );\n }\n resumeAfterSurfaceRestore = false;\n execution.setEngineHealth('running');\n }\n return ok(undefined);\n },\n pluginContext,\n ...(inputBackend !== undefined ? { input: inputBackend } : {}),\n ...(audioBackend !== undefined ? { audio: audioBackend } : {}),\n get physics():\n | import('@forgeax/engine-physics').PhysicsWorld\n | import('@forgeax/engine-physics').PhysicsWorld2D\n | undefined {\n return readPhysicsWorld();\n },\n start(): Result<void, AppError> {\n // R-1: arm the rAF handle FIRST (loop.start schedules raf(tick))\n // and only THEN subscribe to renderer events. If the renderer\n // late-attach replays a persisted device-lost event during the\n // subscribe call, the loop is already armed and can retain the error.\n const r = loop.start();\n if (r.ok) {\n execution.setEngineHealth('running');\n subscribeRendererErrors();\n }\n return r;\n },\n stop(): Result<void, AppError> {\n const r = loop.stop();\n if (r.ok) execution.setEngineHealth('stopped');\n unsubscribeRendererErrors();\n return r;\n },\n async dispose(): Promise<Result<void, AppError>> {\n const state = loop.getState();\n if (state === 'running' || state === 'paused') loop.stop();\n else if (state !== 'stopped') loop.setStopped();\n await pluginContext.fiber.dispose();\n unsubscribeRendererErrors();\n execution.setEngineHealth('stopped');\n return ok(undefined);\n },\n pause(): Result<void, AppError> {\n const r = loop.pause();\n if (r.ok) execution.setEngineHealth('idle');\n return r;\n },\n resume(): Result<void, AppError> {\n const r = loop.resume();\n if (r.ok) execution.setEngineHealth('running');\n return r;\n },\n stepFrame(deltaSeconds): Result<void, AppDispatchError> {\n return loop.stepFrame(deltaSeconds);\n },\n onError(cb: (e: AppDispatchError) => void): () => void {\n return fanout.add(cb);\n },\n setDrawSource(drawSource): void {\n loop.setDrawSource(drawSource);\n },\n /**\n * Most recent dispatched error retained for host self-inspection.\n */\n get lastError(): AppDispatchError | undefined {\n return lastError;\n },\n ...(rhiCapture !== undefined ? { rhiCapture } : {}),\n ...(debugDraw !== undefined ? { debugDraw } : {}),\n ...(remoteHandle !== undefined ? { remote: remoteHandle } : {}),\n };\n\n return ok(stub);\n}\n","import type { World } from '@forgeax/engine-ecs';\nimport { Camera, perspective } from '@forgeax/engine-render';\nimport { Transform } from '@forgeax/engine-scene';\n\n/**\n * Ensure the neutral camera used only by hosts that have no game bootstrap.\n * An authored scene camera wins; a resolved game owns its camera policy and\n * must not call this helper.\n */\nexport function ensureFallbackCamera(\n world: World,\n aspect = 1,\n): ReturnType<World['spawn']> | undefined {\n const cameras = world.query({ with: [Camera] }).unwrap();\n if (!cameras[Symbol.iterator]().next().done) return undefined;\n return world.spawn(\n { component: Transform, data: { pos: [0, 0.6, 5] } },\n { component: Camera, data: perspective({ fov: Math.PI / 3, aspect, far: 1000 }) },\n );\n}\n","// @forgeax/engine-app -- Host service for asset-resident game plugins.\n//\n// App, Preview, and Devkit provide one realm-local GameHost service. Project\n// code default-exports a native Cordis plugin that injects this service and\n// owns all non-ECS teardown through Fiber effects.\n\nimport type { AssetRegistry } from '@forgeax/engine-assets-runtime';\nimport type { EntityHandle } from '@forgeax/engine-ecs';\nimport type { Plugin } from '@forgeax/engine-plugin';\nimport type { Renderer } from '@forgeax/engine-render';\nimport type { SceneAsset } from '@forgeax/engine-types';\n\nimport type { App } from './types';\n\n/** JSON-shaped data a game may intentionally project through a host bridge. */\nexport type GameProjectionValue =\n | null\n | boolean\n | number\n | string\n | GameProjectionValue[]\n | { [key: string]: GameProjectionValue };\n\n/** Lightweight, host-agnostic argument schema for a game-owned action. */\nexport interface GameActionArgsSchema {\n readonly type?: 'string' | 'number' | 'boolean' | 'object' | 'array';\n readonly properties?: Record<string, GameActionArgsSchema>;\n readonly required?: string[];\n readonly enum?: GameProjectionValue[];\n readonly items?: GameActionArgsSchema;\n readonly nullable?: boolean;\n readonly description?: string;\n}\n\n/**\n * A Play-only capability owned by game code. The host may discover and invoke it,\n * but never supplies its gameplay semantics or reaches into the game World.\n */\nexport interface GameActionDef {\n readonly id: string;\n readonly title: string;\n readonly description?: string;\n readonly argsSchema?: GameActionArgsSchema;\n /** Return an optional JSON-shaped result for inspection clients. */\n readonly run: (\n args: GameProjectionValue,\n ) => GameProjectionValue | void | Promise<GameProjectionValue | void>;\n}\n\n/** A named, serializable Play-only read projection owned by game code. */\nexport interface GameReadDef {\n readonly id: string;\n readonly title: string;\n readonly description?: string;\n readonly read: () => GameProjectionValue | Promise<GameProjectionValue>;\n}\n\n/**\n * Host-provided registration sink for one Play run. Games receive this only while\n * bootstrapping the fresh transient world; registrations are discarded when the run is disposed.\n */\nexport interface GameProjectionRegistrar {\n registerAction(def: GameActionDef): () => void;\n registerRead(def: GameReadDef): () => void;\n}\n\n/** Realm-local Host capability injected into an asset-resident game plugin. */\nexport interface GameHost {\n /** Presentation canvas owned by this Host realm. */\n readonly canvas: HTMLCanvasElement;\n /** The WebGPU Renderer (optional — some hosts may not expose it). */\n readonly renderer?: Renderer;\n /** The AssetRegistry owned by the Renderer. */\n readonly assets: AssetRegistry;\n /** The App handle for lifecycle introspection. */\n readonly app: App;\n /** Synthetic root entity of the host-instantiated defaultScene. Carries the\n * SceneInstance component. Absent when the game has no defaultScene. */\n readonly defaultSceneRoot?: EntityHandle;\n /** The loaded SceneAsset payload for the defaultScene. Contains the\n * author-side entity list with Name components. Absent when the game has\n * no defaultScene. */\n readonly defaultScene?: SceneAsset;\n /**\n * Controlled UI container for this run. Games must mount their DOM UI here\n * (`(ctx.uiRoot ?? document.body).appendChild(el)`) instead of appending\n * directly to `document.body`. In the embedded editor viewport the host\n * removes this whole container when the run is disposed. Absent means game\n * code falls back to `document.body`.\n */\n readonly uiRoot?: HTMLElement;\n /**\n * M2 D-3: command-set pointer-lock gate. The game template calls this\n * when the view mode changes (e.g. `setPointerLockAllowed(mode === 'fps')`\n * to allow lock in FPS, disallow in top-down). The host wires this to\n * App.input.setPointerLockAllowed?.() which delegates to the input backend.\n * Absent → the host does not support pointer-lock gating (e.g. a host\n * that only runs top-down games).\n */\n readonly setPointerLockAllowed?: (allowed: boolean) => void;\n /**\n * Optional Play-only projection seam. A game registers its own action and read\n * capabilities here; the host may only discover/invoke/read those closures. It\n * is deliberately absent outside a host that can clear registrations on disposal.\n */\n readonly gameProjection?: GameProjectionRegistrar;\n}\n\n/**\n * Provide the Host boundary to a native Cordis game plugin.\n */\nexport function gameHostPlugin(host: GameHost): Plugin {\n return {\n name: 'game-host',\n provide: 'gameHost',\n apply(ctx) {\n ctx.provide('gameHost', host);\n },\n };\n}\n\ndeclare module '@forgeax/engine-plugin' {\n interface EngineContextServices {\n gameHost?: GameHost;\n }\n}\n","// @forgeax/engine-app -- LoadGameError class + 3-code closed union +\n// LOAD_GAME_ERROR_HINTS / LOAD_GAME_EXPECTED tables.\n//\n// Isomorphic to AppError in errors.ts: class extends Error + 4-field\n// surface (.code / .expected / .hint / .detail) + discriminated detail\n// per code; the co-located policy-owner proof locks the derived views.\n//\n// Shape:\n// - LoadGameErrorCode = closed union 3 members (charter P4 closed-union\n// exhaustive switch needs no default fallback; tsc strict mode guards\n// completeness; AGENTS.md \"Errors are structured\").\n// Members:\n// - 'module-not-found'\n// - 'invalid-format'\n// - 'import-failed'\n//\n// - LoadGameError class = 4-field surface (.code / .expected / .hint /\n// .detail) byte-for-byte parallel to AppError. AI users walk .code /\n// .detail by property access (charter P3 explicit failure: never parse\n// the message string).\n//\n// - LoadGameError is exposed as a discriminated union (variant per code)\n// so AI users get .detail narrowing for free after\n// `if (err.code === '...')`:\n//\n// if (err.code === 'module-not-found') {\n// console.warn('game not found:', err.detail.slug);\n// }\n//\n// - LOAD_GAME_ERROR_HINTS / LOAD_GAME_EXPECTED are 3-key Records keyed\n// by LoadGameErrorCode; the private policy owner below is the single\n// source for both projections.\n//\n// Related: requirements AC-08 (LoadGameError structured error 3 codes +\n// hint + detail); plan-strategy D-3 (reuse codebase structured error\n// pattern); charter P3 (explicit failure).\n\n/**\n * Closed LoadGameErrorCode union (3 members).\n *\n * | code | trigger |\n * |:--|:--|\n * | `'module-not-found'` | resolver throws an error distinguishable as module-not-found (e.g. \"Cannot find module\"). Detail carries `slug` so AI users can surface which game path failed. |\n * | `'invalid-format'` | resolver returns a module without a valid native Cordis default export. Detail carries `exportKeys` so AI users can inspect the module shape. |\n * | `'import-failed'` | resolver throws a generic Error (network error, build error, etc.) not distinguishable as module-not-found. Detail carries the original `cause` Error so AI users can chain narrow. |\n *\n * Plan-strategy D-3 locks the count at 3.\n */\nexport type LoadGameErrorCode = keyof typeof loadGameErrorPolicy;\n\n/**\n * Detail variant for the `'module-not-found'` arm.\n *\n * `slug` carries the game identifier that the resolver failed to locate\n * so AI users can surface exactly which game could not be loaded.\n */\nexport interface LoadGameDetailModuleNotFound {\n readonly slug: string;\n}\n\n/**\n * Detail variant for the `'invalid-format'` arm.\n *\n * `exportKeys` carries the keys of the module object returned by the\n * resolver. AI users inspect these to understand why the native default\n * plugin export was rejected.\n */\nexport interface LoadGameDetailInvalidFormat {\n readonly exportKeys: string[];\n}\n\n/**\n * Detail variant for the `'import-failed'` arm.\n *\n * `cause` carries the original thrown value verbatim so AI users can\n * chain narrow (e.g. `cause instanceof TypeError` for network errors)\n * without losing structure.\n */\nexport interface LoadGameDetailImportFailed {\n readonly cause: unknown;\n}\n\n/**\n * Conditional resolver from `LoadGameErrorCode` to its detail payload type.\n */\nexport type LoadGameErrorDetailFor<C extends LoadGameErrorCode> = C extends 'module-not-found'\n ? LoadGameDetailModuleNotFound\n : C extends 'invalid-format'\n ? LoadGameDetailInvalidFormat\n : LoadGameDetailImportFailed;\n\n/**\n * Tagged union of `.detail` payloads carried by structured LoadGameError.\n */\nexport type LoadGameErrorDetail = LoadGameErrorDetailFor<LoadGameErrorCode>;\n\nclass LoadGameErrorClass extends Error {\n readonly code: LoadGameErrorCode;\n readonly expected: string;\n readonly hint: string;\n readonly detail: LoadGameErrorDetail;\n\n constructor(args: {\n code: LoadGameErrorCode;\n expected: string;\n hint: string;\n detail: LoadGameErrorDetail;\n }) {\n super(`[LoadGameError ${args.code}] expected: ${args.expected}; hint: ${args.hint}`);\n this.name = 'LoadGameError';\n this.code = args.code;\n this.expected = args.expected;\n this.hint = args.hint;\n this.detail = args.detail;\n }\n}\n\n/**\n * Variant intersection: a `LoadGameErrorClass` instance whose `code` literal\n * narrows to `C` and whose `detail` narrows to `LoadGameErrorDetailFor<C>`.\n */\ntype LoadGameErrorVariant<C extends LoadGameErrorCode> = LoadGameErrorClass & {\n readonly code: C;\n readonly detail: LoadGameErrorDetailFor<C>;\n};\n\n/**\n * Public LoadGameError type -- discriminated union of the 3 variants.\n *\n * AI-user form (charter P3 explicit failure):\n *\n * ```ts\n * function recover(err: LoadGameError): string {\n * switch (err.code) {\n * case 'module-not-found': return `game not found: ${err.detail.slug}`;\n * case 'invalid-format': return `bad shape, exports: ${err.detail.exportKeys.join(', ')}`;\n * case 'import-failed': return err.detail.cause instanceof Error ? err.detail.cause.message : 'unknown';\n * }\n * }\n * ```\n */\nexport type LoadGameError = {\n [C in LoadGameErrorCode]: LoadGameErrorVariant<C>;\n}[LoadGameErrorCode];\n\ninterface LoadGameErrorConstructor {\n new <C extends LoadGameErrorCode>(args: {\n code: C;\n expected: string;\n hint: string;\n detail: LoadGameErrorDetailFor<C>;\n }): LoadGameErrorVariant<C>;\n readonly prototype: LoadGameErrorClass;\n}\n\n/**\n * LoadGameError constructor -- `new LoadGameError({ code, expected, hint, detail })`.\n */\nexport const LoadGameError: LoadGameErrorConstructor =\n LoadGameErrorClass as unknown as LoadGameErrorConstructor;\n\n/**\n * `expected` table -- the engine-side invariant that was violated when each\n * code surfaces. AI users read this as the L2 detail (charter F2 priority\n * text); `.hint` carries the recovery action.\n *\n * 3 keys; the policy-owner proof locks the exact count, order, and values.\n */\ntype LoadGameErrorPolicy = { readonly expected: string; readonly hint: string };\n\nconst loadGameErrorPolicy = {\n 'module-not-found': {\n expected:\n 'resolver should return a module with a native Cordis default export for the given slug',\n hint: 'verify the game slug matches an existing template directory; check the resolver import path for typos',\n },\n 'invalid-format': {\n expected: 'resolved module must default-export a Cordis function, class, or object plugin',\n hint: 'default-export one plugin and let the Host mount it into App.pluginContext',\n },\n 'import-failed': {\n expected:\n 'resolver should complete without throwing; import path, network, and build errors are forwarded here',\n hint: 'inspect detail.cause for the original error (network failure, build error, dynamic import timeout, etc.)',\n },\n} satisfies Record<string, LoadGameErrorPolicy>;\n\nexport const LOAD_GAME_EXPECTED: Readonly<Record<LoadGameErrorCode, string>> = Object.fromEntries(\n Object.entries(loadGameErrorPolicy).map(([code, policy]) => [code, policy.expected]),\n) as Readonly<Record<LoadGameErrorCode, string>>;\n\n/**\n * `hint` table -- actionable recovery guidance per code (charter P3).\n *\n * 3 keys; the policy-owner proof locks the exact count, order, and values.\n */\nexport const LOAD_GAME_ERROR_HINTS: Readonly<Record<LoadGameErrorCode, string>> =\n Object.fromEntries(\n Object.entries(loadGameErrorPolicy).map(([code, policy]) => [code, policy.hint]),\n ) as Readonly<Record<LoadGameErrorCode, string>>;\n\n/**\n * Type guard for narrowing unknown errors to LoadGameError.\n *\n * AI users who catch mixed error types can call `if (isLoadGameError(e))`\n * before walking `.code`. Uses instanceof against the internal class\n * (the public constructor delegates to LoadGameErrorClass).\n */\nexport function isLoadGameError(err: unknown): err is LoadGameError {\n return err instanceof LoadGameErrorClass;\n}\n","// @forgeax/engine-app -- loadGame(slug, resolver) -> Result<Plugin, LoadGameError>\n//\n// Pure-function load helper that validates a dynamically-imported game\n// template module. The resolver is an injection point so loadGame is\n// independent of Vite / bundler specifics.\n//\n// Shape:\n// 1. Call resolver(slug). If resolver throws, distinguish module-not-found\n// (slug in detail) from import-failed (cause in detail).\n// 2. Validate the module's `default` export as a Cordis plugin.\n// 3. On success, return that plugin without creating a parallel entry lifecycle.\n//\n// Constraints from upstream:\n// - requirements D-3: loadGame does NOT depend on Vite specifics\n// - requirements boundary-case table: module-not-found -> slug in detail;\n// invalid-format -> exportKeys; import-failed -> cause\n// - plan-strategy D-3: LoadGameError reuses codebase structured error pattern\n//\n// Charter awareness:\n// - P3 explicit failure: all 3 error paths return structured Result.err\n// - F1 context-limited: the function is one screen (no hidden state)\n\nimport type { Plugin } from '@forgeax/engine-plugin';\nimport { err, ok, type Result } from '@forgeax/engine-types';\n\nimport { LOAD_GAME_ERROR_HINTS, LOAD_GAME_EXPECTED, LoadGameError } from './load-game-errors';\n\n/**\n * The shape of a module that the resolver returns.\n */\ninterface GameEntryModule {\n readonly default?: unknown;\n readonly [key: string]: unknown;\n}\n\n/**\n * Resolver function signature: receives a slug (the game identifier),\n * returns a Promise that resolves to a module object.\n *\n * The host (apps/preview/) injects this as a dynamic import proxy,\n * e.g. `(slug) => import(\\`../../templates/\\${slug}/src/main.ts\\`)`.\n * loadGame does not hardcode any import path.\n */\nexport type GamePluginResolver = (slug: string) => Promise<GameEntryModule>;\n\nfunction isPlugin(value: unknown): value is Plugin {\n return (\n typeof value === 'function' ||\n (typeof value === 'object' &&\n value !== null &&\n 'apply' in value &&\n typeof value.apply === 'function')\n );\n}\n\n/**\n * Load and validate a game template module.\n *\n * Returns `Result.ok<Plugin>` when the resolver returns a module\n * whose default export is a native Cordis plugin. Returns `Result.err<LoadGameError>`\n * with one of 3 error codes on failure.\n *\n * @param slug - The game identifier (e.g. 'game-default'). Passed\n * through to the resolver and carried in the 'module-not-found' detail.\n * @param resolver - Async function that imports/fetches the game module.\n * The host owns all path resolution logic.\n */\nexport async function loadGame(\n slug: string,\n resolver: GamePluginResolver,\n): Promise<Result<Plugin, LoadGameError>> {\n let module: GameEntryModule;\n try {\n module = await resolver(slug);\n } catch (thrown: unknown) {\n // Distinguish module-not-found from generic import failure.\n // The heuristic: if the thrown error contains the slug in its message,\n // treat it as module-not-found (the resolver signaled the specific\n // module was not found, e.g. Vite \"Failed to load module\" with the\n // slug path in the message). Otherwise treat it as import-failed\n // (generic network error, eval error, etc.).\n if (thrown instanceof Error && thrown.message.includes(slug)) {\n return err(\n new LoadGameError({\n code: 'module-not-found',\n expected: LOAD_GAME_EXPECTED['module-not-found'],\n hint: LOAD_GAME_ERROR_HINTS['module-not-found'],\n detail: { slug },\n }),\n );\n }\n return err(\n new LoadGameError({\n code: 'import-failed',\n expected: LOAD_GAME_EXPECTED['import-failed'],\n hint: LOAD_GAME_ERROR_HINTS['import-failed'],\n detail: { cause: thrown },\n }),\n );\n }\n\n if (!isPlugin(module.default)) {\n const exportKeys = Object.keys(module);\n return err(\n new LoadGameError({\n code: 'invalid-format',\n expected: LOAD_GAME_EXPECTED['invalid-format'],\n hint: LOAD_GAME_ERROR_HINTS['invalid-format'],\n detail: { exportKeys },\n }),\n );\n }\n\n return ok(module.default);\n}\n","import type { Renderer } from '@forgeax/engine-render';\nimport type { RhiDevice, RhiInstance } from '@forgeax/engine-rhi';\nimport type {\n CreateShaderModuleFn,\n RecordableBackend,\n RecorderAttachment,\n V7Tape,\n} from '@forgeax/engine-rhi-debug';\nimport { attachRecorder, replayDeviceRequest } from '@forgeax/engine-rhi-debug';\nimport { createRhiInstrumentation } from './rhi-capture';\n\nexport interface BrowserRhiDebugRuntime {\n readonly rhi: RhiInstance;\n readonly attachment: RecorderAttachment;\n readonly createReplayDevice: (\n tape: V7Tape,\n ) => Promise<import('@forgeax/engine-types').Result<RhiDevice, unknown>>;\n readonly createShaderModule: CreateShaderModuleFn;\n readonly rhiInstrumentation: import('@forgeax/engine-render/internal/construct-renderer').RhiBackendInstrumentation;\n attachRenderer(renderer: Renderer): () => void;\n}\n\ninterface BackendModule extends RecordableBackend {\n readonly ensureReady?: () => Promise<unknown>;\n}\n\nfunction hasWebGpu(): boolean {\n const nav = (globalThis as { navigator?: { gpu?: unknown } }).navigator;\n return nav?.gpu !== undefined;\n}\n\nasync function loadBackend(): Promise<BackendModule> {\n const backend = (hasWebGpu()\n ? await import('@forgeax/engine-rhi-webgpu')\n : await import('@forgeax/engine-rhi-wgpu')) as unknown as BackendModule;\n if (!hasWebGpu()) await backend.ensureReady?.();\n return backend;\n}\n\n/**\n * Assemble the browser preview's recorder at the Runtime seam. The preview\n * host owns the attachment and consumes only the encoded tape; it does not\n * reach into recorder state or reintroduce the removed DebugRhi facade.\n */\nexport async function createBrowserRhiDebugRuntime(): Promise<BrowserRhiDebugRuntime> {\n const backend = await loadBackend();\n const attached = attachRecorder(backend);\n if (!attached.ok) throw new Error(attached.error.hint);\n const attachment = attached.value;\n return {\n rhi: attachment.backend.rhi,\n attachment,\n createShaderModule: backend.createShaderModule,\n rhiInstrumentation: createRhiInstrumentation(attachment),\n createReplayDevice: async (tape) => {\n const adapter = await backend.rhi.requestAdapter();\n if (!adapter.ok) return adapter;\n return adapter.value.requestDevice(\n replayDeviceRequest(tape, adapter.value.features, adapter.value.limits),\n );\n },\n attachRenderer(_renderer: Renderer): () => void {\n // Frame boundaries and device loss are connected by the typed\n // rhiInstrumentation passed to createApp. This hook remains a no-op so\n // the Preview host keeps an explicit lifecycle slot without subscribing\n // a second boundary callback.\n return () => {};\n },\n };\n}\n","import { isSerializableValue, type JsonValue } from '@forgeax/engine-tool-runtime';\n\nexport type ToolPreviewPresentation = 'hidden' | 'visible';\n\nexport interface ToolPreviewAction {\n readonly frame: number;\n readonly name: string;\n readonly value?: JsonValue;\n}\n\nexport interface ToolPreviewRecipe {\n readonly backend: 'webgpu';\n readonly presentation: ToolPreviewPresentation;\n readonly viewport: { readonly width: number; readonly height: number };\n readonly actions: readonly ToolPreviewAction[];\n readonly deltaSeconds: number;\n readonly frames: number;\n}\n\nexport interface ToolPreviewRecipeOptions {\n readonly backend?: 'webgpu' | 'rhi-null' | string;\n readonly presentation?: ToolPreviewPresentation;\n readonly viewport?: { readonly width: number; readonly height: number };\n readonly actions?: readonly ToolPreviewAction[];\n readonly deltaSeconds?: number;\n readonly frames?: number;\n}\n\nexport type ToolPreviewTraceEvent =\n | 'canvas-created'\n | 'rhi-debug-armed'\n | 'renderer-created'\n | 'world-updated'\n | 'draw-submitted'\n | 'validation-complete';\n\nexport interface ToolPreviewTrace {\n readonly events: readonly ToolPreviewTraceEvent[];\n readonly backend: 'webgpu' | string;\n readonly adapter: string;\n readonly presentation: ToolPreviewPresentation;\n}\n\nexport type ToolPreviewTraceValidation =\n | { readonly ok: true; readonly value: ToolPreviewTrace }\n | {\n readonly ok: false;\n readonly error: {\n readonly code: 'tool-preview-invalid-trace';\n readonly expected: string;\n readonly hint: string;\n readonly detail: { readonly missing: string; readonly index: number };\n };\n };\n\nexport function createToolPreviewRecipe(options: ToolPreviewRecipeOptions): ToolPreviewRecipe {\n if (options.backend !== undefined && options.backend !== 'webgpu') {\n throw new TypeError('tool preview requires the real WebGPU backend');\n }\n const viewport = options.viewport ?? { width: 640, height: 360 };\n if (\n !Number.isSafeInteger(viewport.width) ||\n !Number.isSafeInteger(viewport.height) ||\n viewport.width <= 0 ||\n viewport.height <= 0\n ) {\n throw new TypeError('tool preview viewport must contain positive safe integers');\n }\n const deltaSeconds = options.deltaSeconds ?? 1 / 60;\n const frames = options.frames ?? 1;\n if (!Number.isFinite(deltaSeconds) || deltaSeconds < 0) {\n throw new TypeError('tool preview deltaSeconds must be finite and non-negative');\n }\n if (!Number.isSafeInteger(frames) || frames <= 0) {\n throw new TypeError('tool preview frames must be a positive safe integer');\n }\n const actions = (options.actions ?? []).map((action) => ({ ...action }));\n for (const action of actions) {\n if (\n !Number.isSafeInteger(action.frame) ||\n action.frame < 0 ||\n action.frame >= frames ||\n action.name.length === 0 ||\n (action.value !== undefined && !isSerializableValue(action.value))\n ) {\n throw new TypeError('tool preview actions require a valid frame, name, and JSON value');\n }\n }\n return {\n backend: 'webgpu',\n presentation: options.presentation ?? 'hidden',\n viewport: { width: viewport.width, height: viewport.height },\n actions,\n deltaSeconds,\n frames,\n };\n}\n\nconst REQUIRED_EVENTS: readonly ToolPreviewTraceEvent[] = [\n 'canvas-created',\n 'rhi-debug-armed',\n 'renderer-created',\n 'world-updated',\n 'draw-submitted',\n 'validation-complete',\n];\n\nexport function validateToolPreviewTrace(trace: ToolPreviewTrace): ToolPreviewTraceValidation {\n if (trace.backend !== 'webgpu') {\n return {\n ok: false,\n error: {\n code: 'tool-preview-invalid-trace',\n expected: 'trace.backend === \"webgpu\"',\n hint: 'run the same recipe with a real WebGPU adapter; RHI-null is not a preview backend',\n detail: { missing: 'webgpu-backend', index: -1 },\n },\n };\n }\n let last = -1;\n for (const event of REQUIRED_EVENTS) {\n const index = trace.events.indexOf(event);\n if (index <= last) {\n return {\n ok: false,\n error: {\n code: 'tool-preview-invalid-trace',\n expected: `event '${event}' occurs after the previous recipe phase`,\n hint: 'arm RHI-debug before Renderer construction and retain update/draw/validation evidence',\n detail: { missing: event, index },\n },\n };\n }\n last = index;\n }\n return { ok: true, value: trace };\n}\n","import { createProfiler } from '@forgeax/engine-profiler';\nimport {\n buildTapeIndex,\n decodeTape,\n decodeToRgba8,\n openReplay,\n type V7Tape,\n} from '@forgeax/engine-rhi-debug';\nimport {\n type ArtifactRef,\n createPreviewArtifactManifest,\n type PreviewArtifactManifest,\n type SnapshotRef,\n type ToolTiming,\n} from '@forgeax/engine-tool-runtime';\nimport { err, ok, type Result } from '@forgeax/engine-types';\nimport { createApp } from '../create-app';\nimport { createBrowserRhiDebugRuntime } from '../internal/browser-rhi-debug-runtime';\nimport type { App, BundlerOptions, CreateAppOptions } from '../types';\nimport {\n createToolPreviewRecipe,\n type ToolPreviewAction,\n type ToolPreviewRecipe,\n type ToolPreviewTrace,\n} from './recipe';\n\nexport type ToolPreviewResourceKind = 'material' | 'mesh' | 'texture' | 'vfx';\n\nexport interface ToolPreviewResourceRequest {\n readonly kind: ToolPreviewResourceKind;\n readonly guid: string;\n readonly size?: number;\n}\n\nexport interface ToolPreviewResourceFacts {\n readonly kind: ToolPreviewResourceKind;\n readonly guid: string;\n readonly asset: unknown;\n readonly digest?: string;\n readonly ownerFacts?: Readonly<Record<string, string | number | boolean>>;\n readonly observation?: Readonly<Record<string, string | number | boolean | readonly number[]>>;\n}\n\nexport interface ToolPreviewHostOptions {\n readonly runId?: string;\n readonly recipe: ToolPreviewRecipe;\n readonly snapshot: SnapshotRef;\n readonly canvas?: HTMLCanvasElement;\n readonly root?: Document | HTMLElement;\n readonly app?: Omit<CreateAppOptions, 'rhi'>;\n readonly bundler?: BundlerOptions;\n readonly resource?: ToolPreviewResourceRequest;\n readonly prepare?: (\n app: App,\n ) => void | ToolPreviewResourceFacts | Promise<void | ToolPreviewResourceFacts>;\n /** Refresh producer-owned resource facts after the bounded real frame run. */\n readonly collectResourceFacts?: (\n app: App,\n current: ToolPreviewResourceFacts | undefined,\n ) => void | ToolPreviewResourceFacts | Promise<void | ToolPreviewResourceFacts>;\n /** Dispose producer-owned preview attachments before the App. */\n readonly onDispose?: (app: App) => void | Promise<void>;\n readonly executeAction?: (action: ToolPreviewAction, app: App) => boolean | Promise<boolean>;\n}\n\nexport interface ToolPreviewHostError {\n readonly code: 'tool-preview-capability-unavailable' | 'tool-preview-bootstrap-failed';\n readonly expected: string;\n readonly hint: string;\n readonly detail: { readonly phase: string; readonly cause?: unknown };\n}\n\nexport interface ToolPreviewHost {\n readonly app: App;\n readonly recipe: ToolPreviewRecipe;\n readonly trace: ToolPreviewTrace;\n capture(): Promise<Result<ToolPreviewCaptureResult, ToolPreviewHostError>>;\n run(): Promise<Result<ToolPreviewRunResult, ToolPreviewHostError>>;\n dispose(): Promise<Result<void, ToolPreviewHostError>>;\n}\n\nexport interface ToolPreviewCaptureResult {\n readonly recipe: ToolPreviewRecipe;\n readonly snapshot: SnapshotRef;\n readonly trace: ToolPreviewTrace;\n readonly captureId: string;\n readonly actionTrace: readonly ToolPreviewAction[];\n readonly tape: {\n readonly runId: string;\n readonly jsonUri: string;\n readonly blobUri: string;\n readonly byteLength: number;\n };\n readonly profile: { readonly captureId: string; readonly uri: string };\n readonly capturePng: { readonly uri: string; readonly width: number; readonly height: number };\n readonly executeDurationMs: number;\n readonly captureDurationMs: number;\n readonly browserJsHeapBytes?: number;\n readonly appErrors: readonly unknown[];\n readonly resource?: ToolPreviewResourceFacts;\n}\n\nexport interface ToolPreviewRunResult {\n readonly trace: ToolPreviewTrace;\n readonly captureId: string;\n readonly drawCalls: number;\n readonly committedDrawIndex: number;\n readonly nonBlackPixels: number;\n readonly actionTrace: readonly ToolPreviewAction[];\n readonly tape: {\n readonly runId: string;\n readonly jsonUri: string;\n readonly blobUri: string;\n readonly byteLength: number;\n };\n readonly profile: { readonly captureId: string; readonly uri: string };\n readonly capturePng: { readonly uri: string; readonly width: number; readonly height: number };\n readonly png: { readonly uri: string; readonly width: number; readonly height: number };\n readonly manifest: PreviewArtifactManifest;\n readonly artifacts: readonly ArtifactRef[];\n readonly operationTiming: ToolTiming;\n readonly resource?: ToolPreviewResourceFacts;\n}\n\nfunction layoutCanvas(canvas: HTMLCanvasElement, recipe: ToolPreviewRecipe): void {\n canvas.width = recipe.viewport.width;\n canvas.height = recipe.viewport.height;\n canvas.style.position = 'fixed';\n canvas.style.inset = '0';\n canvas.style.width = `${recipe.viewport.width}px`;\n canvas.style.height = `${recipe.viewport.height}px`;\n canvas.style.opacity = '1';\n canvas.style.visibility = 'visible';\n canvas.style.pointerEvents = 'auto';\n}\n\nfunction appendCanvas(canvas: HTMLCanvasElement, root: Document | HTMLElement | undefined): void {\n if (canvas.isConnected) return;\n const parent =\n typeof Document !== 'undefined' && root instanceof Document\n ? root.body\n : (root ?? (typeof document === 'undefined' ? undefined : document.body));\n parent?.appendChild(canvas);\n}\n\nfunction removeOwnedCanvas(canvas: HTMLCanvasElement, owned: boolean): void {\n if (owned && canvas.isConnected) canvas.remove();\n}\n\nfunction bytesToDataUri(bytes: Uint8Array, mediaType: string): string {\n let binary = '';\n for (let offset = 0; offset < bytes.length; offset += 0x2000) {\n binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x2000));\n }\n return `data:${mediaType};base64,${btoa(binary)}`;\n}\n\nasync function sha256(bytes: Uint8Array): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', new Uint8Array(bytes).buffer as ArrayBuffer);\n return `sha256:${[...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, '0')).join('')}`;\n}\n\nfunction dataUriBytes(uri: string): Uint8Array {\n const encoded = uri.slice(uri.indexOf(',') + 1);\n const binary = atob(encoded);\n return Uint8Array.from(binary, (char) => char.charCodeAt(0));\n}\n\nfunction generateRunId(): string {\n return `preview-${crypto.randomUUID()}`;\n}\n\nfunction countDrawCalls(tape: V7Tape): number {\n return buildTapeIndex(tape).works.filter((work) => isRenderDraw(work.kind)).length;\n}\n\nfunction lastRenderDrawIndex(tape: V7Tape): number {\n const works = buildTapeIndex(tape).works;\n return works.reduce((last, work) => (isRenderDraw(work.kind) ? work.workIndex : last), -1);\n}\n\nfunction isRenderDraw(kind: ReturnType<typeof buildTapeIndex>['works'][number]['kind']): boolean {\n return (\n kind === 'draw' ||\n kind === 'drawIndexed' ||\n kind === 'drawIndirect' ||\n kind === 'drawIndexedIndirect'\n );\n}\n\nfunction resourceSubjectDigest(resource: ToolPreviewResourceFacts | undefined): string | undefined {\n if (resource === undefined) return undefined;\n const asset =\n typeof resource.asset === 'object' && resource.asset !== null\n ? (resource.asset as Record<string, unknown>)\n : undefined;\n const candidates = [\n resource.observation?.subjectDigest,\n resource.digest,\n asset?.digest,\n asset?.programFingerprint,\n ];\n return candidates.find((value): value is string => typeof value === 'string' && value.length > 0);\n}\n\nfunction resourceSubjectDrawn(resource: ToolPreviewResourceFacts, drawCalls: number): boolean {\n if (resource.kind === 'texture') return drawCalls > 0;\n if (resource.kind === 'material' || resource.kind === 'mesh') return drawCalls > 2;\n return resource.observation !== undefined;\n}\n\nexport async function replayToolPreviewCapture(\n capture: ToolPreviewCaptureResult,\n): Promise<Result<ToolPreviewRunResult, ToolPreviewHostError>> {\n const analyzeStartedAtMs = performance.now();\n const tapeBytes = dataUriBytes(capture.tape.jsonUri);\n const parsed = decodeTape(tapeBytes);\n if (!parsed.ok) {\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'the finalized tape to deserialize for fresh-device replay',\n hint: parsed.error.hint,\n detail: { phase: 'tape-parse', cause: parsed.error },\n });\n }\n const drawCalls = countDrawCalls(parsed.value);\n const resource =\n capture.resource !== undefined &&\n capture.resource.observation === undefined &&\n capture.resource.ownerFacts !== undefined &&\n resourceSubjectDrawn(capture.resource, drawCalls)\n ? { ...capture.resource, observation: capture.resource.ownerFacts }\n : capture.resource;\n const subjectDigest = resourceSubjectDigest(resource);\n if (resource !== undefined && subjectDigest === undefined) {\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'the resource owner to publish a subject identity before evidence publication',\n hint: 'repair AssetRegistry owner facts or post-frame observation; recipe and trace are not subject identity',\n detail: {\n phase: 'resource-identity',\n cause: {\n kind: resource.kind,\n drawCalls,\n ownerFactsPublished: resource.ownerFacts !== undefined,\n observationPublished: resource.observation !== undefined,\n },\n },\n });\n }\n let runtime: Awaited<ReturnType<typeof createBrowserRhiDebugRuntime>>;\n try {\n runtime = await createBrowserRhiDebugRuntime();\n } catch (cause) {\n return err({\n code: 'tool-preview-capability-unavailable',\n expected: 'a fresh browser WebGPU runtime for offline replay',\n hint: 'Run replay in an isolated browser process; do not reuse the capture device.',\n detail: { phase: 'replay-runtime', cause },\n });\n }\n const replayDevice = await runtime.createReplayDevice(parsed.value);\n if (!replayDevice.ok) {\n return err({\n code: 'tool-preview-capability-unavailable',\n expected: 'a fresh WebGPU device for offline replay',\n hint: 'the capture device cannot be reused as a substitute for fresh-device replay',\n detail: { phase: 'replay-device', cause: replayDevice.error },\n });\n }\n const replayResult = await openReplay(parsed.value, {\n device: replayDevice.value,\n createShaderModule: runtime.createShaderModule,\n });\n if (!replayResult.ok) {\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'the self-contained tape to replay on a fresh WebGPU device',\n hint: replayResult.error.hint,\n detail: { phase: 'replay-create', cause: replayResult.error },\n });\n }\n const replay = replayResult.value;\n if (drawCalls === 0) {\n await replay.dispose();\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'the preview recipe to submit at least one render draw',\n hint: 'seed a visible mesh and camera before capturing the preview frame',\n detail: { phase: 'replay-draws', cause: { appErrors: capture.appErrors } },\n });\n }\n const committedDrawIndex = lastRenderDrawIndex(parsed.value);\n if (committedDrawIndex < 0) {\n await replay.dispose();\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'the preview tape to contain a render draw after compute work',\n hint: 'seed a visible render output after simulation dispatches before capturing the preview frame',\n detail: { phase: 'replay-draws', cause: { appErrors: capture.appErrors } },\n });\n }\n const committed = await replay.inspectWork(committedDrawIndex, ['pixels']);\n if (!committed.ok || committed.value.attachment === undefined) {\n await replay.dispose();\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'the fresh replay session to expose a color attachment for the final render work',\n hint: committed.ok\n ? 'the tape contains no readable color attachment for PNG evidence'\n : committed.error.hint,\n detail: { phase: 'replay-inspect', cause: committed.ok ? undefined : committed.error },\n });\n }\n const attachment = committed.value.attachment;\n const width = attachment.width ?? 0;\n const height = attachment.height ?? 0;\n const rgba =\n attachment.format === undefined\n ? undefined\n : decodeToRgba8(attachment.bytes, attachment.format, width, height);\n if (rgba === null || rgba === undefined || width <= 0 || height <= 0) {\n await replay.dispose();\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'the replayed color attachment to have a supported display format',\n hint: 'move PNG encoding to the producer-owned preview shell for unsupported formats',\n detail: { phase: 'png-readback', cause: { format: attachment.format, width, height } },\n });\n }\n const outputCanvas = document.createElement('canvas');\n outputCanvas.width = width;\n outputCanvas.height = height;\n const outputContext = outputCanvas.getContext('2d');\n if (outputContext === null) {\n await replay.dispose();\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'the browser to provide a 2D canvas context for replay PNG encoding',\n hint: 'enable the browser canvas 2D context before running the preview host',\n detail: { phase: 'png-encode' },\n });\n }\n outputContext.putImageData(new ImageData(rgba, width, height), 0, 0);\n await replay.dispose();\n const pixels = outputContext.getImageData(0, 0, width, height).data;\n let nonBlackPixels = 0;\n if (pixels !== undefined) {\n for (let offset = 0; offset < pixels.length; offset += 4) {\n if ((pixels[offset] ?? 0) + (pixels[offset + 1] ?? 0) + (pixels[offset + 2] ?? 0) > 0) {\n nonBlackPixels += 1;\n }\n }\n }\n if (nonBlackPixels === 0) {\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'the replayed PNG to contain non-black pixels',\n hint: 'inspect the RHI tape and renderer draw submission before accepting the preview',\n detail: { phase: 'png-non-black' },\n });\n }\n const analyzeDurationMs = performance.now() - analyzeStartedAtMs;\n const finalizeStartedAtMs = performance.now();\n const pngUri = outputCanvas.toDataURL('image/png');\n const pngBytes = dataUriBytes(pngUri);\n if (\n !capture.capturePng.uri.startsWith('data:image/png') ||\n capture.capturePng.width <= 0 ||\n capture.capturePng.height <= 0\n ) {\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'the capture browser to provide a PNG before fresh replay',\n hint: 'capture the rendered canvas before closing the capture carrier; do not reuse the replay PNG',\n detail: { phase: 'capture-png' },\n });\n }\n const capturePngBytes = dataUriBytes(capture.capturePng.uri);\n if (capturePngBytes.byteLength === 0) {\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'the capture PNG to contain encoded bytes',\n hint: 'repair the capture carrier readback before publishing evidence',\n detail: { phase: 'capture-png' },\n });\n }\n const profileBytes = dataUriBytes(capture.profile.uri);\n const tapeDigest = await sha256(tapeBytes);\n const capturePngDigest = await sha256(capturePngBytes);\n const pngDigest = await sha256(pngBytes);\n const profileDigest = await sha256(profileBytes);\n const presentationDigest = await sha256(new TextEncoder().encode(capture.trace.presentation));\n const manifest = createPreviewArtifactManifest({\n schemaVersion: '2.0.0',\n identity: {\n runId: capture.tape.runId,\n snapshotDigest: capture.snapshot.digest,\n subjectDigest: subjectDigest ?? capture.snapshot.digest,\n presentationDigest,\n frameId: 0,\n captureId: capture.captureId,\n },\n artifacts: [\n {\n owner: 'rhi-debug',\n kind: 'rhi-tape',\n role: 'rhi-tape',\n uri: capture.tape.jsonUri,\n digest: tapeDigest,\n byteLength: tapeBytes.byteLength,\n mediaType: 'application/json',\n derivedFrom: [],\n },\n {\n owner: 'visual',\n kind: 'png',\n role: 'capture',\n uri: capture.capturePng.uri,\n digest: capturePngDigest,\n byteLength: capturePngBytes.byteLength,\n mediaType: 'image/png',\n derivedFrom: [tapeDigest],\n },\n {\n owner: 'rhi-debug-replay',\n kind: 'png',\n role: 'fresh-replay',\n uri: pngUri,\n digest: pngDigest,\n byteLength: pngBytes.byteLength,\n mediaType: 'image/png',\n derivedFrom: [tapeDigest, capturePngDigest],\n },\n {\n owner: 'profiler',\n kind: 'profile-capture',\n role: 'profile-capture',\n uri: capture.profile.uri,\n digest: profileDigest,\n byteLength: profileBytes.byteLength,\n mediaType: 'application/json',\n derivedFrom: [],\n },\n ],\n });\n const finalizeDurationMs = performance.now() - finalizeStartedAtMs;\n const durationMs =\n capture.executeDurationMs + capture.captureDurationMs + analyzeDurationMs + finalizeDurationMs;\n const memory = (\n performance as Performance & {\n readonly memory?: { readonly usedJSHeapSize?: number };\n }\n ).memory?.usedJSHeapSize;\n const browserJsHeapBytes =\n typeof memory === 'number' && Number.isFinite(memory) && memory >= 0\n ? Math.max(Math.round(memory), capture.browserJsHeapBytes ?? 0)\n : capture.browserJsHeapBytes;\n return ok({\n trace: capture.trace,\n captureId: capture.captureId,\n drawCalls,\n committedDrawIndex,\n nonBlackPixels,\n actionTrace: capture.actionTrace,\n tape: capture.tape,\n profile: capture.profile,\n capturePng: capture.capturePng,\n png: { uri: pngUri, width: outputCanvas.width, height: outputCanvas.height },\n manifest,\n artifacts: manifest.artifacts.flatMap((artifact) => {\n if (\n artifact.kind !== 'rhi-tape' &&\n artifact.kind !== 'png' &&\n artifact.kind !== 'profile-capture'\n ) {\n return [];\n }\n return [\n {\n kind: artifact.kind,\n digest: artifact.digest,\n uri: artifact.uri,\n sizeBytes: artifact.byteLength,\n },\n ];\n }),\n operationTiming: {\n startedAtMs: 0,\n endedAtMs: durationMs,\n durationMs,\n phases: {\n lookup: { status: 'not-applicable' },\n lease: { status: 'not-applicable' },\n transport: { status: 'not-applicable' },\n execute: {\n status: 'observed',\n durationMs: capture.executeDurationMs,\n workUnits: capture.recipe.frames,\n },\n capture: { status: 'observed', durationMs: capture.captureDurationMs },\n finalize: { status: 'observed', durationMs: finalizeDurationMs },\n analyze: { status: 'observed', durationMs: analyzeDurationMs },\n },\n unattributedMs: 0,\n resources: {\n 'node-rss': { status: 'not-applicable' },\n 'browser-js-heap':\n browserJsHeapBytes === undefined\n ? { status: 'unavailable', reason: 'performance.memory is not exposed' }\n : {\n status: 'observed',\n bytes: browserJsHeapBytes,\n source: 'maximum performance.memory.usedJSHeapSize across capture and replay',\n },\n 'artifact-bytes': {\n status: 'observed',\n bytes:\n tapeBytes.byteLength +\n dataUriBytes(capture.capturePng.uri).byteLength +\n pngBytes.byteLength +\n profileBytes.byteLength,\n source: 'browser-produced artifact payloads',\n },\n 'gpu-memory': {\n status: 'unavailable',\n reason: 'WebGPU does not expose portable allocation totals',\n },\n },\n },\n ...(resource === undefined ? {} : { resource }),\n });\n}\n\nexport async function createToolPreviewHost(\n options: ToolPreviewHostOptions,\n): Promise<Result<ToolPreviewHost, ToolPreviewHostError>> {\n const recipe = createToolPreviewRecipe(options.recipe);\n const runId = options.runId ?? generateRunId();\n const doc = options.root ?? (typeof document === 'undefined' ? undefined : document);\n if (options.canvas === undefined && doc === undefined) {\n return err({\n code: 'tool-preview-capability-unavailable',\n expected: 'a DOM document or caller-owned HTMLCanvasElement',\n hint: 'run the browser host or provide an attached canvas; headless does not mean RHI-null',\n detail: { phase: 'canvas' },\n });\n }\n const canvas =\n options.canvas ??\n (typeof Document !== 'undefined' && doc instanceof Document\n ? doc.createElement('canvas')\n : undefined);\n const ownsCanvas = options.canvas === undefined;\n if (canvas === undefined) {\n return err({\n code: 'tool-preview-capability-unavailable',\n expected: 'root document can create an HTMLCanvasElement',\n hint: 'provide a document root or an existing canvas',\n detail: { phase: 'canvas' },\n });\n }\n layoutCanvas(canvas, recipe);\n appendCanvas(canvas, options.root);\n if (!canvas.isConnected) {\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'preview canvas is connected before App creation',\n hint: 'attach the canvas to the document or pass a connected caller-owned canvas',\n detail: { phase: 'canvas' },\n });\n }\n\n let runtime: Awaited<ReturnType<typeof createBrowserRhiDebugRuntime>>;\n try {\n runtime = await createBrowserRhiDebugRuntime();\n } catch (cause) {\n removeOwnedCanvas(canvas, ownsCanvas);\n return err({\n code: 'tool-preview-capability-unavailable',\n expected: 'a real WebGPU adapter and device',\n hint: 'install or enable WebGPU; do not replace this route with RHI-null',\n detail: { phase: 'rhi-debug', cause },\n });\n }\n const profiler = createProfiler();\n const appResult = await createApp(\n canvas,\n {\n ...(options.app ?? {}),\n rhi: runtime.rhi,\n rhiInstrumentation: runtime.rhiInstrumentation,\n profiler,\n },\n options.bundler,\n );\n if (!appResult.ok) {\n await runtime.attachment.dispose();\n removeOwnedCanvas(canvas, ownsCanvas);\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'createApp constructs a real WebGPU Renderer',\n hint: 'inspect the structured App/RHI error; the preview must not fall back to RHI-null',\n detail: { phase: 'renderer', cause: appResult.error },\n });\n }\n const app = appResult.value;\n const appErrors: unknown[] = [];\n const unsubscribeAppErrors = app.onError((error) => appErrors.push(error));\n let resourceFacts: ToolPreviewResourceFacts | undefined;\n try {\n const prepared = await options.prepare?.(app);\n if (prepared !== undefined) resourceFacts = prepared;\n } catch (cause) {\n unsubscribeAppErrors();\n await app.dispose();\n await runtime.attachment.dispose();\n removeOwnedCanvas(canvas, ownsCanvas);\n const bootstrapFailure =\n options.resource === undefined\n ? {\n expected: 'the project bootstrap to prepare the preview World',\n hint: 'Repair the project Entry, assets, or scene before retrying the same recipe.',\n phase: 'project-bootstrap',\n }\n : {\n expected: 'the resource preview bootstrap to prepare the preview World',\n hint: 'Repair the resource owner, cooked payload, or preview environment before retrying the same recipe.',\n phase: 'resource-bootstrap',\n };\n return err({\n code: 'tool-preview-bootstrap-failed',\n ...bootstrapFailure,\n detail: { phase: bootstrapFailure.phase, cause },\n });\n }\n const attached = app.renderer.attach(app.world);\n if (!attached.ok) {\n unsubscribeAppErrors();\n await app.dispose();\n await runtime.attachment.dispose();\n removeOwnedCanvas(canvas, ownsCanvas);\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'the preview World to attach to the real Renderer before stepping',\n hint: attached.error.hint,\n detail: { phase: 'world-attach', cause: attached.error },\n });\n }\n const profileSession = profiler.startCapture({ frameLimit: recipe.frames, eventLimit: 1024 });\n if (!profileSession.ok) {\n await app.dispose();\n await runtime.attachment.dispose();\n removeOwnedCanvas(canvas, ownsCanvas);\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'the App profiler to start a bounded capture',\n hint: profileSession.error.hint,\n detail: { phase: 'profiler', cause: profileSession.error },\n });\n }\n const detach = runtime.attachRenderer(app.renderer);\n const trace: ToolPreviewTrace = {\n events: ['canvas-created', 'rhi-debug-armed', 'renderer-created'],\n backend: 'webgpu',\n adapter: 'webgpu-adapter',\n presentation: recipe.presentation,\n };\n let disposed = false;\n const capturePreview = async (): Promise<\n Result<ToolPreviewCaptureResult, ToolPreviewHostError>\n > => {\n if (disposed) {\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'preview host remains alive until capture completes',\n hint: 'create a new preview host after dispose',\n detail: { phase: 'capture' },\n });\n }\n const started = app.start();\n if (!started.ok)\n return err({\n ...started.error,\n code: 'tool-preview-bootstrap-failed',\n detail: { phase: 'start', cause: started.error },\n });\n const paused = app.pause();\n if (!paused.ok)\n return err({\n ...paused.error,\n code: 'tool-preview-bootstrap-failed',\n detail: { phase: 'pause', cause: paused.error },\n });\n const executeStartedAtMs = performance.now();\n const actionTrace: ToolPreviewAction[] = [];\n let encodedCapture: ReturnType<typeof runtime.attachment.captureFrame> | undefined;\n for (let frame = 0; frame < recipe.frames; frame += 1) {\n for (const action of recipe.actions.filter((candidate) => candidate.frame === frame)) {\n let accepted = false;\n try {\n accepted = (await options.executeAction?.(action, app)) === true;\n } catch (cause) {\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: `project action '${action.name}' to execute at frame ${frame}`,\n hint: 'Repair the project-owned preview action handler and rerun the same recipe.',\n detail: { phase: 'action', cause },\n });\n }\n if (!accepted) {\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: `project action '${action.name}' to have a registered handler`,\n hint: 'Register the action in the project plugin or remove it from the recipe.',\n detail: { phase: 'action', cause: { frame, name: action.name } },\n });\n }\n actionTrace.push(action);\n }\n if (frame === recipe.frames - 1) {\n encodedCapture = runtime.attachment.captureFrame();\n const snapshot = await runtime.attachment.frameBoundary();\n if (!snapshot.ok)\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'RHI-debug snapshots live resources before the captured frame',\n hint: snapshot.error.hint,\n detail: { phase: 'rhi-snapshot', cause: snapshot.error },\n });\n }\n const stepped = app.stepFrame(recipe.deltaSeconds);\n if (!stepped.ok)\n return err({\n ...stepped.error,\n code: 'tool-preview-bootstrap-failed',\n detail: { phase: 'frame', cause: stepped.error },\n });\n // Render features may start an asynchronous shader/module bake on their\n // first prepare pass. Yield once between bounded frames so the bake can\n // settle before the next retry; a synchronous tight loop would capture\n // only the feature's intentional `next-frame` pending state.\n await new Promise<void>((resolve) => setTimeout(resolve, 0));\n }\n const finalized = await runtime.attachment.frameBoundary();\n if (!finalized.ok)\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'RHI-debug finalizes the captured frame',\n hint: finalized.error.hint,\n detail: { phase: 'rhi-finalize', cause: finalized.error },\n });\n if (options.collectResourceFacts !== undefined) {\n try {\n const collected = await options.collectResourceFacts(app, resourceFacts);\n if (collected !== undefined) resourceFacts = collected;\n } catch (cause) {\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'the resource owner to publish post-frame preview facts',\n hint: 'Repair the producer-owned preview observation and retry the same recipe.',\n detail: { phase: 'resource-observation', cause },\n });\n }\n }\n const executeDurationMs = performance.now() - executeStartedAtMs;\n const finalTrace: ToolPreviewTrace = {\n ...trace,\n events: [...trace.events, 'world-updated', 'draw-submitted', 'validation-complete'],\n };\n const captureStartedAtMs = performance.now();\n const profile = profileSession.value.finish();\n if (!profile.ok) {\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'the bounded App profiler to finish with ProfileCapture',\n hint: profile.error.hint,\n detail: { phase: 'profiler-finish', cause: profile.error },\n });\n }\n if (encodedCapture === undefined) {\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'a positive-frame recipe to arm one captured frame',\n hint: 'validate the recipe before running the preview host',\n detail: { phase: 'rhi-capture' },\n });\n }\n const tape = await encodedCapture;\n if (!tape.ok)\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'RHI-debug produces a self-contained tape',\n hint: tape.error.hint,\n detail: { phase: 'rhi-finalize', cause: tape.error },\n });\n const captureDurationMs = performance.now() - captureStartedAtMs;\n const tapeBytes = tape.value.bytes;\n const profileBytes = new TextEncoder().encode(JSON.stringify(profile.value));\n const capturePng = {\n uri: canvas.toDataURL('image/png'),\n width: canvas.width,\n height: canvas.height,\n };\n const memory = (\n performance as Performance & {\n readonly memory?: { readonly usedJSHeapSize?: number };\n }\n ).memory?.usedJSHeapSize;\n return ok({\n recipe,\n snapshot: options.snapshot,\n trace: finalTrace,\n captureId: profile.value.captureId,\n actionTrace,\n tape: {\n runId,\n jsonUri: bytesToDataUri(tapeBytes, 'application/octet-stream'),\n blobUri: bytesToDataUri(new Uint8Array(), 'application/octet-stream'),\n byteLength: tapeBytes.byteLength,\n },\n profile: {\n captureId: profile.value.captureId,\n uri: bytesToDataUri(profileBytes, 'application/json'),\n },\n capturePng,\n executeDurationMs,\n captureDurationMs,\n ...(typeof memory === 'number' && Number.isFinite(memory) && memory >= 0\n ? { browserJsHeapBytes: Math.round(memory) }\n : {}),\n appErrors,\n ...(resourceFacts === undefined ? {} : { resource: resourceFacts }),\n });\n };\n return ok({\n app,\n recipe,\n trace,\n capture: capturePreview,\n async run() {\n const capture = await capturePreview();\n if (!capture.ok) return capture;\n return replayToolPreviewCapture(capture.value);\n },\n async dispose() {\n if (disposed) return ok(undefined);\n disposed = true;\n detach();\n unsubscribeAppErrors();\n let disposeError: unknown;\n try {\n await options.onDispose?.(app);\n } catch (cause) {\n disposeError = cause;\n }\n const result = await app.dispose();\n removeOwnedCanvas(canvas, ownsCanvas);\n if (disposeError !== undefined) {\n return err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'producer-owned preview attachments to dispose before the App',\n hint: 'Repair the preview owner lifecycle and retry the same operation.',\n detail: { phase: 'producer-dispose', cause: disposeError },\n });\n }\n return result.ok\n ? ok(undefined)\n : err({\n code: 'tool-preview-bootstrap-failed',\n expected: 'preview app disposes cleanly',\n hint: result.error.hint,\n detail: { phase: 'dispose', cause: result.error },\n });\n },\n });\n}\n","import {\n type ArtifactRef,\n createArtifactRef,\n type PreviewArtifactManifest,\n type PreviewArtifactRole,\n type SnapshotRef,\n snapshotStaleError,\n type ToolRuntimeError,\n validatePreviewArtifactManifest,\n} from '@forgeax/engine-tool-runtime';\nimport { err, ok, type Result } from '@forgeax/engine-types';\nimport type { ToolPreviewTrace } from './recipe';\n\nexport interface ToolPreviewEvidence {\n readonly trace: ToolPreviewTrace;\n readonly artifacts: readonly ArtifactRef[];\n readonly manifest?: PreviewArtifactManifest;\n}\n\nexport function joinToolPreviewEvidence(input: {\n readonly trace: ToolPreviewTrace;\n readonly manifest: PreviewArtifactManifest;\n readonly required: readonly PreviewArtifactRole[];\n}): Result<ToolPreviewEvidence, ToolRuntimeError> {\n const validated = validatePreviewArtifactManifest(input.manifest, input.required);\n if (!validated.ok) return err(validated.error);\n const artifacts = input.manifest.artifacts.map((artifact) =>\n createArtifactRef({\n kind:\n artifact.kind === 'report' || artifact.kind === 'contact-sheet'\n ? 'tool-result'\n : artifact.kind,\n digest: artifact.digest,\n uri: artifact.uri,\n mediaType: artifact.mediaType,\n sizeBytes: artifact.byteLength,\n }),\n );\n return ok({ trace: input.trace, artifacts, manifest: input.manifest });\n}\n\nexport function createToolPreviewEvidence(\n trace: ToolPreviewTrace,\n artifacts: readonly ArtifactRef[],\n): ToolPreviewEvidence {\n return { trace, artifacts: [...artifacts] };\n}\n\nexport function joinResourcePreviewEvidence(input: {\n readonly snapshot: SnapshotRef;\n readonly manifest: PreviewArtifactManifest;\n readonly requiredRoles: readonly PreviewArtifactRole[];\n}): Result<PreviewArtifactManifest, ToolRuntimeError> {\n if (input.manifest.identity.snapshotDigest !== input.snapshot.digest) {\n return err(snapshotStaleError(input.snapshot.digest, input.manifest.identity.snapshotDigest));\n }\n const validated = validatePreviewArtifactManifest(input.manifest, input.requiredRoles);\n return validated.ok ? ok(validated.value) : err(validated.error);\n}\n","export interface ToolPreviewCameraFrame {\n readonly center: readonly [number, number, number];\n readonly radius: number;\n readonly distance: number;\n readonly near: number;\n readonly far: number;\n}\n\nexport function fitToolPreviewCameraToAabb(\n aabb: readonly [number, number, number, number, number, number],\n options: { readonly aspect: number; readonly fov: number; readonly padding?: number },\n): ToolPreviewCameraFrame {\n const [minX, minY, minZ, maxX, maxY, maxZ] = aabb;\n if (\n ![minX, minY, minZ, maxX, maxY, maxZ].every(Number.isFinite) ||\n minX > maxX ||\n minY > maxY ||\n minZ > maxZ ||\n !Number.isFinite(options.aspect) ||\n options.aspect <= 0 ||\n !Number.isFinite(options.fov) ||\n options.fov <= 0 ||\n options.fov >= Math.PI\n ) {\n throw new TypeError('tool preview camera framing requires a finite AABB, aspect, and FOV');\n }\n const center: readonly [number, number, number] = [\n (minX + maxX) / 2,\n (minY + maxY) / 2,\n (minZ + maxZ) / 2,\n ];\n const radius = Math.max(\n Math.hypot((maxX - minX) / 2, (maxY - minY) / 2, (maxZ - minZ) / 2),\n 0.001,\n );\n const verticalHalfFov = options.fov / 2;\n const horizontalHalfFov = Math.atan(Math.tan(verticalHalfFov) * options.aspect);\n const limitingHalfFov = Math.min(verticalHalfFov, horizontalHalfFov);\n const padding = options.padding ?? 1.15;\n if (!Number.isFinite(padding) || padding < 1) {\n throw new TypeError('tool preview camera framing padding must be finite and at least one');\n }\n const distance = (radius / Math.sin(limitingHalfFov)) * padding;\n const depthMargin = radius * (padding - 1);\n return {\n center,\n radius,\n distance,\n near: Math.max(0.001, distance - radius - depthMargin),\n far: distance + radius + depthMargin,\n };\n}\n"]}