@ignifx/editor-host 0.10.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/error-codes.d.ts +3 -3
- package/dist/error-codes.js +3 -3
- package/dist/error-codes.js.map +1 -1
- package/dist/index.d.ts +262 -15
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1727 -741
- package/dist/index.js.map +1 -1
- package/dist/vite.d.ts +8 -3
- package/dist/vite.d.ts.map +1 -1
- package/dist/vite.js +305 -7
- package/dist/vite.js.map +1 -1
- package/package.json +10 -6
- package/skills/editor-host/SKILL.md +49 -16
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["CLICK_SLOP_PX"],"sources":["../src/protocol/rpc.ts","../src/protocol/connect.ts","../src/protocol/handshake.ts","../src/protocol/heartbeat.ts","../src/protocol/play.ts","../src/protocol/scene-file.ts","../src/protocol/scene-ops.ts","../src/protocol/scene.ts","../src/protocol/version.ts","../src/channel.ts","../src/app-reports.ts","../src/lite/gizmos.ts","../src/scene/asset-reload.ts","../src/scene/defaults.ts","../src/play-stats.ts","../src/scene/document.ts","../src/scene/editor-camera.ts","../src/scene/view-2d.ts","../src/scene/editor-camera-2d.ts","../src/scene/ops.ts","../src/scene/schemas.ts","../src/scene/screenshot.ts","../src/scene/settings.ts","../src/scene/view-math.ts","../src/scene/scene-host.ts","../src/host.ts","../src/play-controls.ts"],"sourcesContent":["// A copy of `packages/editor-protocol/src/rpc.ts` from `astrum-forge/ignifx-editor` (protocol 0.3).\n// Below this comment it is byte-identical to that file, but for the link rule in `./index.ts`.\n/**\n * JSON-RPC 2.0 envelopes (https://www.jsonrpc.org/specification) shared by every editor channel:\n * editor↔host and editor↔play over a `MessagePort`.\n */\n\n/**\n * The value of every envelope's `jsonrpc` field.\n *\n * @public\n */\nexport const JSON_RPC_VERSION = \"2.0\";\n\n/**\n * A request id, chosen by the sender and echoed in the response.\n *\n * @public\n */\nexport type RpcId = string | number;\n\n/**\n * The error codes a peer may send. The first five are JSON-RPC's own; the rest use the range\n * JSON-RPC reserves for implementations (-32000 to -32099).\n *\n * @remarks\n * `as const` object plus derived union rather than an `enum` (engine coding standards §5.2, §5.3).\n *\n * @public\n */\nexport const RpcErrorCode = {\n /** The message was not valid JSON. */\n parseError: -32_700,\n /** The message was JSON but not a valid request. */\n invalidRequest: -32_600,\n /** No handler exists for the method. */\n methodNotFound: -32_601,\n /** The method exists but its `params` are wrong. */\n invalidParams: -32_602,\n /** The handler failed. */\n internalError: -32_603,\n /** The peers' protocol versions are incompatible (see `protocolVersionIsCompatible`). */\n incompatibleProtocol: -32_000,\n /**\n * The peer cannot answer this method yet: it has not finished its handshake, or (a scene host)\n * its app has not started.\n */\n notReady: -32_001,\n /** A scene method that needs an open scene was called while none is open (`SceneMethod`). */\n noScene: -32_002,\n} as const;\n\n/**\n * The union of the codes in `RpcErrorCode`.\n *\n * @public\n */\nexport type RpcErrorCode = (typeof RpcErrorCode)[keyof typeof RpcErrorCode];\n\n/**\n * The `error` member of a failed response.\n *\n * @public\n */\nexport interface RpcError {\n /** What kind of failure it was. */\n readonly code: RpcErrorCode;\n /** A short, human-readable description. */\n readonly message: string;\n /** Extra detail for debugging; its shape depends on the method. */\n readonly data?: unknown;\n}\n\n/**\n * A call that expects a response with the same `id`.\n *\n * @typeParam M - The method name.\n * @typeParam P - The parameters; omitted when the method takes none.\n *\n * @public\n */\nexport interface RpcRequest<M extends string = string, P = unknown> {\n /** Always `\"2.0\"`. */\n readonly jsonrpc: typeof JSON_RPC_VERSION;\n /** Matches the response to this request. */\n readonly id: RpcId;\n /** The method to call. */\n readonly method: M;\n /** The method's arguments, an object or an array in JSON. */\n readonly params?: P;\n}\n\n/**\n * A one-way message: like a request, but with no `id` and no response.\n *\n * @typeParam M - The method name.\n * @typeParam P - The parameters; omitted when the method takes none.\n *\n * @public\n */\nexport interface RpcNotification<M extends string = string, P = unknown> {\n /** Always `\"2.0\"`. */\n readonly jsonrpc: typeof JSON_RPC_VERSION;\n /** The event or method being signalled. */\n readonly method: M;\n /** The message's arguments, an object or an array in JSON. */\n readonly params?: P;\n}\n\n/**\n * The answer to a request that succeeded.\n *\n * @typeParam R - The result.\n *\n * @public\n */\nexport interface RpcSuccessResponse<R = unknown> {\n /** Always `\"2.0\"`. */\n readonly jsonrpc: typeof JSON_RPC_VERSION;\n /** The `id` of the request being answered. */\n readonly id: RpcId;\n /** What the method returned. */\n readonly result: R;\n}\n\n/**\n * The answer to a request that failed.\n *\n * @public\n */\nexport interface RpcErrorResponse {\n /** Always `\"2.0\"`. */\n readonly jsonrpc: typeof JSON_RPC_VERSION;\n /** The `id` of the request being answered, or `null` when it could not be read. */\n readonly id: RpcId | null;\n /** Why the request failed. */\n readonly error: RpcError;\n}\n\n/**\n * The answer to a request: a result or an error, never both.\n *\n * @typeParam R - The result on success.\n *\n * @public\n */\nexport type RpcResponse<R = unknown> = RpcSuccessResponse<R> | RpcErrorResponse;\n\n/**\n * Any message that can travel on an editor channel.\n *\n * @public\n */\nexport type RpcMessage = RpcRequest | RpcNotification | RpcResponse;\n\n/**\n * Narrows to a plain object without an `as` assertion. Shared by this package's guards; not\n * re-exported from the barrel.\n *\n * @param value - The value to test.\n * @returns True when the value is a non-null, non-array object.\n *\n * @internal\n */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Tells whether a JSON value is a valid request or notification id.\n *\n * @param value - The value to test.\n * @returns True for a string or a finite number.\n */\nfunction isRpcId(value: unknown): value is RpcId {\n return typeof value === \"string\" || (typeof value === \"number\" && Number.isFinite(value));\n}\n\n/**\n * Tells whether a JSON value is a valid `error` member with a known code.\n *\n * @param value - The value to test.\n * @returns True when its `code` is one of `RpcErrorCode` and its `message` is a string.\n */\nfunction isRpcError(value: unknown): value is RpcError {\n return (\n isRecord(value) &&\n Object.values(RpcErrorCode).some((code) => code === value[\"code\"]) &&\n typeof value[\"message\"] === \"string\"\n );\n}\n\n/**\n * Checks the envelope of a received message: a request, a notification, or a response. It does not\n * check a method's `params` or `result`; that is the handler's job.\n *\n * @param value - A value parsed from JSON or received through `postMessage`.\n * @returns True when `value` is a well-formed JSON-RPC 2.0 message with a known error code, if any.\n *\n * @public\n */\nexport function isRpcMessage(value: unknown): value is RpcMessage {\n if (!isRecord(value) || value[\"jsonrpc\"] !== JSON_RPC_VERSION) {\n return false;\n }\n if (\"method\" in value) {\n // JSON-RPC allows `params` to be absent, an object or an array, but never `null` or a scalar.\n const params = value[\"params\"];\n const hasValidParams = !(\"params\" in value) || (typeof params === \"object\" && params !== null);\n const hasValidId = !(\"id\" in value) || isRpcId(value[\"id\"]);\n return typeof value[\"method\"] === \"string\" && hasValidParams && hasValidId;\n }\n const hasResult = \"result\" in value;\n const hasError = \"error\" in value;\n if (hasResult === hasError) {\n return false;\n }\n if (hasResult) {\n return isRpcId(value[\"id\"]);\n }\n return (value[\"id\"] === null || isRpcId(value[\"id\"])) && isRpcError(value[\"error\"]);\n}\n","// A copy of `packages/editor-protocol/src/connect.ts` from `astrum-forge/ignifx-editor` (protocol 0.3).\n// Below this comment it is byte-identical to that file, but for the link rule in `./index.ts`.\n/**\n * The window message that hands a view its `MessagePort`. It is the only message that travels\n * outside the port: everything after it is JSON-RPC on the port (`rpc.ts`, `handshake.ts`).\n */\nimport { isRecord } from \"./rpc.js\";\n\n/**\n * The `type` of the window message that hands a host its `MessagePort`.\n *\n * @remarks\n * The editor posts `{ type: EDITOR_CONNECT_MESSAGE_TYPE }` to the view's window, targeted at the\n * view's origin, with the port as the one transferred object. It posts a fresh one after every load\n * of the view: a port that has been transferred once cannot be sent again, and the newest port\n * replaces the previous one. The host ignores the message unless `event.origin` is the editor's\n * origin, the data is this shape, and exactly one port is attached.\n *\n * @example\n * ```ts\n * const channel = new MessageChannel();\n * frame.contentWindow?.postMessage({ type: EDITOR_CONNECT_MESSAGE_TYPE }, \"http://127.0.0.1:5173\", [channel.port2]);\n * ```\n *\n * @public\n */\nexport const EDITOR_CONNECT_MESSAGE_TYPE = \"ignifx-editor/connect\";\n\n/**\n * The window message that hands a host its `MessagePort`; the port travels as its one transferred\n * object, not inside the data.\n *\n * @public\n */\nexport interface EditorConnectMessage {\n /** Always {@link EDITOR_CONNECT_MESSAGE_TYPE}. */\n readonly type: typeof EDITOR_CONNECT_MESSAGE_TYPE;\n}\n\n/**\n * Tells whether a window message's data is the connect message. It checks the data only; the\n * caller still checks `event.origin` and that `event.ports` holds exactly one port.\n *\n * @param value - The `data` of a received `MessageEvent`.\n * @returns True when `value` is an object whose `type` is {@link EDITOR_CONNECT_MESSAGE_TYPE}.\n *\n * @public\n */\nexport function isEditorConnectMessage(value: unknown): value is EditorConnectMessage {\n return isRecord(value) && value[\"type\"] === EDITOR_CONNECT_MESSAGE_TYPE;\n}\n","// A copy of `packages/editor-protocol/src/handshake.ts` from `astrum-forge/ignifx-editor` (protocol 0.3).\n// Below this comment it is byte-identical to that file, but for the link rule in `./index.ts`.\n/**\n * The handshake the editor runs with each host it embeds: the scene view (`@ignifx/editor-host`)\n * and the play view (`virtual:ignifx/editor`). Plan §3.3.\n *\n * The editor sends `hello`; the host answers with its `ready` result, or with an\n * `RpcErrorCode.incompatibleProtocol` error when `protocolVersionIsCompatible` refuses the\n * pair. Either side may send `ping` at any time after that. The editor posts a fresh port for every\n * load of a view (`connect.ts`), so the handshake runs again after every reload.\n */\nimport { isRecord } from \"./rpc.js\";\nimport type { RpcRequest, RpcSuccessResponse } from \"./rpc.js\";\nimport type { ProtocolVersion } from \"./version.js\";\n\n/**\n * The method names of the handshake.\n *\n * @remarks\n * `as const` object plus derived union rather than an `enum` (engine coding standards §5.2, §5.3).\n *\n * @public\n */\nexport const HandshakeMethod = {\n /** Editor → host: the first message on a new channel. */\n hello: \"hello\",\n /** Either direction: a liveness check, answered with `\"pong\"`. */\n ping: \"ping\",\n} as const;\n\n/**\n * The union of the names in `HandshakeMethod`.\n *\n * @public\n */\nexport type HandshakeMethod = (typeof HandshakeMethod)[keyof typeof HandshakeMethod];\n\n/**\n * Which kind of view a host runs.\n *\n * @public\n */\nexport const HostKind = {\n /** The scene view: an edit-mode app that applies document ops and draws gizmos. */\n scene: \"scene\",\n /** The play view: the project's own page, running the game. */\n play: \"play\",\n} as const;\n\n/**\n * The union of the kinds in `HostKind`.\n *\n * @public\n */\nexport type HostKind = (typeof HostKind)[keyof typeof HostKind];\n\n/**\n * The optional features a host lists in its `ready` result.\n *\n * @remarks\n * The play controls send `[\"heartbeat\", \"playControls\"]`. The scene host sends `\"heartbeat\"` and\n * whichever of `\"gizmos\"`, `\"screenshot\"`, `\"viewMode2d\"` and `\"pick2d\"` it supports; every\n * `SceneMethod` not tied to one of them is required of a 0.3 scene host.\n *\n * @public\n */\nexport const HostCapability = {\n /** The host sends `heartbeat` notifications after `ready` (see `HostNotification`). */\n heartbeat: \"heartbeat\",\n /** The host answers the methods in `PlayMethod`. */\n playControls: \"playControls\",\n /**\n * The scene host draws gizmos on the primary selection, answers `setGizmo`, and sends\n * `transformDragging` and `transformDragged`.\n */\n gizmos: \"gizmos\",\n /** The scene host answers `screenshot`. */\n screenshot: \"screenshot\",\n /** The scene host accepts `setViewMode` with `\"2d\"`: a 2D editor camera and planar gizmos. */\n viewMode2d: \"viewMode2d\",\n /**\n * The scene host picks sprites in 2D view mode (`app.twoD.pickAt` from `@ignifx/2d`); without it,\n * `pick` and view clicks in 2D mode resolve through the 3D picker only.\n */\n pick2d: \"pick2d\",\n /**\n * The host relays the app's reports: `log` lines with the first `Error` each carries, a\n * `hostError` with `AppErrorData` (entity, component, phase, stack) for every `app.onError`\n * report, and `hotReloaded` with each error's stack. The scene view sends them as scene\n * notifications, the play view as play notifications. Additive in 0.3.\n */\n logRelay: \"logRelay\",\n /**\n * After a script's hot reload changes a field's default, the scene host gives the field its new\n * default wherever the document leaves it out: on each document component whose record omits the\n * field, and on the members of each prefab instance (rebuilt from the prefab, with the instance's\n * overrides). A value the document sets is kept. An editor need not reopen the scene for changed\n * defaults. Additive in 0.3.\n */\n hotReloadDefaults: \"hotReloadDefaults\",\n} as const;\n\n/**\n * The union of the names in `HostCapability`.\n *\n * @public\n */\nexport type HostCapability = (typeof HostCapability)[keyof typeof HostCapability];\n\n/**\n * What the editor says about itself in `hello`.\n *\n * @public\n */\nexport interface HelloParams {\n /** The editor's own version, for example `\"0.1.0\"`. */\n readonly editorVersion: string;\n /** The protocol version the editor speaks. */\n readonly protocol: ProtocolVersion;\n}\n\n/**\n * Editor → host: the first request on a new channel.\n *\n * @public\n */\nexport interface HelloRequest extends RpcRequest<typeof HandshakeMethod.hello, HelloParams> {\n /** What the editor says about itself. */\n readonly params: HelloParams;\n}\n\n/**\n * What a host says about itself in answer to `hello`.\n *\n * @public\n */\nexport interface ReadyResult {\n /** The version of `@ignifx/core` the project runs, for example `\"0.9.0\"`. */\n readonly engineVersion: string;\n /** The protocol version the host speaks. */\n readonly protocol: ProtocolVersion;\n /**\n * Optional features the host supports, named by `HostCapability`. Names are added as the\n * protocol grows; a peer ignores names it does not know.\n */\n readonly capabilities: readonly string[];\n /** Which view the host runs. */\n readonly hostKind: HostKind;\n}\n\n/**\n * Host → editor: the successful answer to {@link HelloRequest}.\n *\n * @public\n */\nexport type ReadyResponse = RpcSuccessResponse<ReadyResult>;\n\n/**\n * Either direction: a liveness check. It takes no parameters.\n *\n * @public\n */\nexport type PingRequest = RpcRequest<typeof HandshakeMethod.ping, never>;\n\n/**\n * The answer to {@link PingRequest}.\n *\n * @public\n */\nexport type PongResponse = RpcSuccessResponse<\"pong\">;\n\n/**\n * The `data` of the `RpcErrorCode.incompatibleProtocol` error a host answers `hello` with when\n * the protocol versions differ.\n *\n * @public\n */\nexport interface IncompatibleProtocolData {\n /** The protocol version the host speaks. */\n readonly host: ProtocolVersion;\n /** The version of `@ignifx/core` the project runs. */\n readonly engineVersion: string;\n}\n\n/**\n * Tells whether a value is a protocol version: two non-negative integers.\n *\n * @param value - The value to test.\n * @returns True for `{ major, minor }` with non-negative safe integers.\n *\n * @public\n */\nexport function isProtocolVersion(value: unknown): value is ProtocolVersion {\n if (!isRecord(value)) {\n return false;\n }\n const { major, minor } = value;\n return (\n typeof major === \"number\" &&\n typeof minor === \"number\" &&\n Number.isSafeInteger(major) &&\n Number.isSafeInteger(minor) &&\n major >= 0 &&\n minor >= 0\n );\n}\n\n/**\n * Checks the `result` of a `hello` answer.\n *\n * @param value - The received `result`.\n * @returns True when it has a string `engineVersion`, a protocol version, an array of capability\n * strings, and a known `hostKind`.\n *\n * @public\n */\nexport function isReadyResult(value: unknown): value is ReadyResult {\n if (!isRecord(value)) {\n return false;\n }\n const { capabilities, hostKind } = value;\n return (\n typeof value[\"engineVersion\"] === \"string\" &&\n isProtocolVersion(value[\"protocol\"]) &&\n Array.isArray(capabilities) &&\n capabilities.every((name: unknown) => typeof name === \"string\") &&\n Object.values(HostKind).some((kind) => kind === hostKind)\n );\n}\n\n/**\n * Checks the `data` of an `incompatibleProtocol` answer to `hello`.\n *\n * @param value - The received `error.data`.\n * @returns True when it names the host's protocol version and the engine version.\n *\n * @public\n */\nexport function isIncompatibleProtocolData(value: unknown): value is IncompatibleProtocolData {\n return isRecord(value) && isProtocolVersion(value[\"host\"]) && typeof value[\"engineVersion\"] === \"string\";\n}\n","// A copy of `packages/editor-protocol/src/heartbeat.ts` from `astrum-forge/ignifx-editor` (protocol 0.3).\n// Below this comment it is byte-identical to that file, but for the link rule in `./index.ts`.\n/**\n * The heartbeat: how the editor tells a live view from a crashed or hung one. Chromium reports\n * nothing for a dead sub-frame, so silence is the only signal.\n */\nimport type { RpcNotification } from \"./rpc.js\";\n\n/**\n * The notifications a host sends on its own.\n *\n * @remarks\n * `as const` object plus derived union rather than an `enum` (engine coding standards §5.2, §5.3).\n *\n * @public\n */\nexport const HostNotification = {\n /** Host → editor, every {@link DEFAULT_HEARTBEAT_INTERVAL_MS} by default after `ready`: the view is alive. */\n heartbeat: \"heartbeat\",\n} as const;\n\n/**\n * The union of the names in `HostNotification`.\n *\n * @public\n */\nexport type HostNotification = (typeof HostNotification)[keyof typeof HostNotification];\n\n/**\n * The milliseconds between heartbeats when the host is not configured otherwise: one second, so a\n * dead view is noticed within a few.\n *\n * @remarks\n * A host starts its heartbeat after it has answered a compatible `hello` with `ready`, sends it on\n * the current port only, and stops it when that port is replaced or closed. A host that lists\n * `HostCapability.heartbeat` in `ready` sends it, and the editor treats a missing heartbeat as a\n * dead view.\n *\n * @public\n */\nexport const DEFAULT_HEARTBEAT_INTERVAL_MS = 1000;\n\n/**\n * Host → editor: the view is alive. It carries no parameters, so `params` is absent on the wire:\n * `{\"jsonrpc\":\"2.0\",\"method\":\"heartbeat\"}`.\n *\n * @public\n */\nexport type HeartbeatNotification = RpcNotification<typeof HostNotification.heartbeat, never>;\n","// A copy of `packages/editor-protocol/src/play.ts` from `astrum-forge/ignifx-editor` (protocol 0.3).\n// Below this comment it is byte-identical to that file, but for the link rule in `./index.ts`.\n/**\n * The play view's controls: the methods the editor calls on the project's own game page after the\n * handshake, through `attachEditorPlayControls(app)` from `virtual:ignifx/editor`. Plan §3.6.\n */\nimport { isRecord } from \"./rpc.js\";\nimport type { RpcNotification, RpcRequest, RpcSuccessResponse } from \"./rpc.js\";\n\n/**\n * The methods the play view answers after `ready`. `play`, `pause`, `step` and `stop` answer with a\n * {@link PlayState}; `playState` answers with a {@link PlayStateReport}; `playStats` answers with\n * {@link PlayStats}.\n *\n * @remarks\n * A host that answers them lists `HostCapability.playControls` in `ready`. Sent before `ready`, they\n * fail with `RpcErrorCode.notReady`; sent to a host without them, with `RpcErrorCode.methodNotFound`.\n * `playState` and `playStats` are additive 0.3 methods: a host from before one answers it with\n * `RpcErrorCode.methodNotFound`.\n *\n * @public\n */\nexport const PlayMethod = {\n /** Clears `app.time.paused` and starts the frame loop if it is stopped. */\n play: \"play\",\n /** Sets `app.time.paused`; scripts marked `updateWhenPaused` keep running. */\n pause: \"pause\",\n /** Stops the frame loop, then advances exactly one frame with `app.step()` and leaves the game paused. */\n step: \"step\",\n /** Stops the frame loop with `app.stop()`. The editor reloads the view to reset the game. */\n stop: \"stop\",\n /** Reads the game's state without changing it. Takes no parameters. */\n playState: \"playState\",\n /**\n * Reads the game's frame rate, frame time, entity count and frame count without changing\n * anything. Takes no parameters. The editor polls it; no notification carries it.\n */\n playStats: \"playStats\",\n} as const;\n\n/**\n * The union of the names in `PlayMethod`.\n *\n * @public\n */\nexport type PlayMethod = (typeof PlayMethod)[keyof typeof PlayMethod];\n\n/**\n * The parameters of the `step` method.\n *\n * @public\n */\nexport interface StepParams {\n /**\n * The frame delta in seconds, a positive finite number. Defaults to `app.time.fixedDeltaTime`;\n * any other value fails with `RpcErrorCode.invalidParams`.\n */\n readonly deltaSeconds?: number;\n}\n\n/**\n * Editor → play view: one of the `PlayMethod`s. Only `step` takes parameters.\n *\n * @public\n */\nexport type PlayRequest =\n | RpcRequest<typeof PlayMethod.play, never>\n | RpcRequest<typeof PlayMethod.pause, never>\n | RpcRequest<typeof PlayMethod.step, StepParams>\n | RpcRequest<typeof PlayMethod.stop, never>\n | RpcRequest<typeof PlayMethod.playState, never>\n | RpcRequest<typeof PlayMethod.playStats, never>;\n\n/**\n * What the play view reports after every `PlayMethod`.\n *\n * @public\n */\nexport interface PlayState {\n /** Whether the frame loop runs (`app.isRunning`). */\n readonly isRunning: boolean;\n /** Whether game time is paused (`app.time.paused`). */\n readonly isPaused: boolean;\n /** How many frames have started (`app.time.frameCount`). */\n readonly frameCount: number;\n}\n\n/**\n * Play view → editor: the answer to `play`, `pause`, `step` or `stop`.\n *\n * @public\n */\nexport type PlayResponse = RpcSuccessResponse<PlayState>;\n\n/**\n * The notifications the play view sends after `ready`.\n *\n * @remarks\n * Additive in 0.3: a host from before them sends none, and answers `playState` with\n * `RpcErrorCode.methodNotFound`. `log`, `hostError` and `hotReloaded` came later still: only a host\n * that lists `HostCapability.logRelay` in `ready` sends them.\n *\n * @public\n */\nexport const PlayNotification = {\n /**\n * After the game's {@link PlayStateReport.state} changed. A change a `PlayMethod` makes is sent\n * right after that method's answer; one the game makes itself, such as setting\n * `app.time.paused`, within one heartbeat interval.\n */\n playStateChanged: \"playStateChanged\",\n /**\n * One line from the game's logger, with the same `LogParams` as the scene view's `log`. Sent by a\n * host that lists `HostCapability.logRelay`; lines logged before the handshake are kept (the\n * newest few hundred) and sent right after `ready`.\n */\n log: \"log\",\n /**\n * An error the game's app reported through `app.onError`: the same `HostErrorParams` as the scene\n * view's `hostError`, with `AppErrorData` as its `data`. Sent by a host that lists\n * `HostCapability.logRelay`, kept before the handshake as `log` is.\n */\n hostError: \"hostError\",\n /**\n * After every `app.hotReload` operation in the game: the same `HotReloadedParams` as the scene\n * view's `hotReloaded`. Sent by a host that lists `HostCapability.logRelay`.\n */\n hotReloaded: \"hotReloaded\",\n} as const;\n\n/**\n * The union of the names in `PlayNotification`.\n *\n * @public\n */\nexport type PlayNotification = (typeof PlayNotification)[keyof typeof PlayNotification];\n\n/**\n * Whether the game plays, is paused, or is stopped, as {@link PlayStateReport.state} reports it.\n *\n * @public\n */\nexport const PlayPhase = {\n /** The frame loop runs (`app.isRunning`) and game time is not paused. */\n playing: \"playing\",\n /**\n * Game time is paused (`app.time.paused`): after `pause`, or after `step`, which leaves the frame\n * loop stopped on the stepped frame.\n */\n paused: \"paused\",\n /** The frame loop does not run: before the game starts it, or after `stop`. */\n stopped: \"stopped\",\n} as const;\n\n/**\n * The union of the names in `PlayPhase`.\n *\n * @public\n */\nexport type PlayPhase = (typeof PlayPhase)[keyof typeof PlayPhase];\n\n/**\n * The game's state as `playState` answers it and `playStateChanged` reports it.\n *\n * @public\n */\nexport interface PlayStateReport {\n /** Whether the game plays, is paused, or is stopped. */\n readonly state: PlayPhase;\n /** How many frames have started (`app.time.frameCount`). */\n readonly frameCount: number;\n /** Scaled seconds of game time since the app started running frames (`app.time.time`). */\n readonly time: number;\n}\n\n/**\n * Play view → editor: the answer to `playState`.\n *\n * @public\n */\nexport type PlayStateResponse = RpcSuccessResponse<PlayStateReport>;\n\n/**\n * The game's performance as `playStats` answers it.\n *\n * @public\n */\nexport interface PlayStats {\n /**\n * Frames per second: `1000 / frameTimeMs`, or `0` when `frameTimeMs` is `0`. Rendered frames\n * count whether or not game time is paused.\n */\n readonly fps: number;\n /**\n * The mean wall-clock time between the frames of the last second, in milliseconds, from the\n * frame history in `app.diagnostics` (each frame's `rawDeltaMs`); `0` while the frame loop does\n * not run (stopped, or stepped and paused on a frame) or before its first frame.\n */\n readonly frameTimeMs: number;\n /** How many entities the game's world holds, in every scene instance, persistent ones included. */\n readonly entityCount: number;\n /** How many frames have started (`app.time.frameCount`). */\n readonly frameCount: number;\n}\n\n/**\n * Play view → editor: the answer to `playStats`.\n *\n * @public\n */\nexport type PlayStatsResponse = RpcSuccessResponse<PlayStats>;\n\n/**\n * Play view → editor: the game's state changed.\n *\n * @public\n */\nexport interface PlayStateChangedNotification extends RpcNotification<\n typeof PlayNotification.playStateChanged,\n PlayStateReport\n> {\n /** The game's state after the change. */\n readonly params: PlayStateReport;\n}\n\n/**\n * Checks the `result` of a play method's response.\n *\n * @param value - The received `result`.\n * @returns True when `value` has boolean `isRunning` and `isPaused` and a non-negative integer\n * `frameCount`.\n *\n * @public\n */\nexport function isPlayState(value: unknown): value is PlayState {\n if (!isRecord(value)) {\n return false;\n }\n const frameCount = value[\"frameCount\"];\n return (\n typeof value[\"isRunning\"] === \"boolean\" &&\n typeof value[\"isPaused\"] === \"boolean\" &&\n typeof frameCount === \"number\" &&\n Number.isSafeInteger(frameCount) &&\n frameCount >= 0\n );\n}\n\n/**\n * Checks the `result` of `playState` and the `params` of `playStateChanged`.\n *\n * @param value - The received value.\n * @returns True when `value` has a `state` that is a `PlayPhase`, a non-negative integer\n * `frameCount`, and a non-negative finite `time`.\n *\n * @public\n */\nexport function isPlayStateReport(value: unknown): value is PlayStateReport {\n if (!isRecord(value)) {\n return false;\n }\n const state = value[\"state\"];\n const frameCount = value[\"frameCount\"];\n const time = value[\"time\"];\n return (\n typeof state === \"string\" &&\n Object.values<string>(PlayPhase).includes(state) &&\n typeof frameCount === \"number\" &&\n Number.isSafeInteger(frameCount) &&\n frameCount >= 0 &&\n typeof time === \"number\" &&\n Number.isFinite(time) &&\n time >= 0\n );\n}\n\n/**\n * Checks the `result` of `playStats`.\n *\n * @param value - The received `result`.\n * @returns True when `value` has non-negative finite `fps` and `frameTimeMs` and non-negative\n * integer `entityCount` and `frameCount`.\n *\n * @public\n */\nexport function isPlayStats(value: unknown): value is PlayStats {\n if (!isRecord(value)) {\n return false;\n }\n const fps = value[\"fps\"];\n const frameTimeMs = value[\"frameTimeMs\"];\n const entityCount = value[\"entityCount\"];\n const frameCount = value[\"frameCount\"];\n return (\n typeof fps === \"number\" &&\n Number.isFinite(fps) &&\n fps >= 0 &&\n typeof frameTimeMs === \"number\" &&\n Number.isFinite(frameTimeMs) &&\n frameTimeMs >= 0 &&\n typeof entityCount === \"number\" &&\n Number.isSafeInteger(entityCount) &&\n entityCount >= 0 &&\n typeof frameCount === \"number\" &&\n Number.isSafeInteger(frameCount) &&\n frameCount >= 0\n );\n}\n","// A copy of `packages/editor-protocol/src/scene-file.ts` from `astrum-forge/ignifx-editor` (protocol 0.3).\n// Below this comment it is byte-identical to that file, but for the link rule in `./index.ts`.\n/**\n * The engine's scene file format as it travels on the wire: the same object `@ignifx/core`'s\n * `serializeScene` builds and `stringifySceneFile` writes\n * (`docs/architecture/06-serialization-and-scene-format.md` §2 in the engine repository).\n *\n * @remarks\n * This package has no dependencies, so it restates the engine's types instead of importing them.\n * Every type here has the engine type's name, fields and literal strings, and the package's tests\n * check that each pair is assignable both ways against the pinned `@ignifx/core`. The guards check\n * the structure a peer relies on, not every rule of the format: the host still validates an opened\n * file with the engine's `validateSceneFile`.\n */\nimport { isRecord } from \"./rpc.js\";\n\n/**\n * Any JSON value. The engine's `JsonValue`.\n *\n * @public\n */\nexport type JsonValue = string | number | boolean | null | JsonArray | JsonObject;\n\n/**\n * A JSON array. The engine's `JsonArray`.\n *\n * @public\n */\nexport type JsonArray = readonly JsonValue[];\n\n/**\n * A JSON object. The engine's `JsonObject`.\n *\n * @public\n */\nexport type JsonObject = { readonly [key: string]: JsonValue };\n\n/**\n * A serialized asset reference: `{ \"$asset\": \"<address>\", \"type\"?: \"<type>\" }`. The engine's\n * `SceneFileAssetRef`.\n *\n * @public\n */\nexport interface SceneFileAssetRef {\n /** The address the asset is registered under. */\n readonly $asset: string;\n /** The asset type name, written only when the address extension does not identify it. */\n readonly type?: string;\n}\n\n/**\n * An entity's local transform. The engine's `SceneFileTransform`.\n *\n * @public\n */\nexport interface SceneFileTransform {\n /** Local position, `[x, y, z]`, in metres. */\n readonly position: readonly [number, number, number];\n /** Local rotation quaternion, `[x, y, z, w]`. */\n readonly rotation: readonly [number, number, number, number];\n /** Local scale, `[x, y, z]`. */\n readonly scale: readonly [number, number, number];\n}\n\n/**\n * One component of one entity. The engine's `SceneFileComponent`.\n *\n * @public\n */\nexport interface SceneFileComponent {\n /** ULID, unique within the file. */\n readonly uid: string;\n /** The component class's registered `typeId`. */\n readonly type: string;\n /** Omitted when `true`, the default. */\n readonly enabled?: boolean;\n /** Written only when the class's `schemaVersion` differs from `1`. */\n readonly schemaVersion?: number;\n /** Values in the component schema's declaration order. */\n readonly props?: JsonObject;\n}\n\n/**\n * One override patch applied to an instanced scene. The engine's `SceneFileOverride`.\n *\n * @public\n */\nexport interface SceneFileOverride {\n /** `\"replace\"` (the default) patches a value, `\"remove\"` deletes a component, `\"add\"` appends one. */\n readonly op?: \"replace\" | \"remove\" | \"add\";\n /** The path into the instanced file, in the engine's override path grammar. */\n readonly path: string;\n /** The new value, for `\"replace\"` and `\"add\"`. */\n readonly value?: JsonValue;\n}\n\n/**\n * The `instance` entry that makes an entity the root of an instanced scene (a prefab instance).\n * The engine's `SceneFileInstance`.\n *\n * @public\n */\nexport interface SceneFileInstance {\n /** The scene asset to instance. */\n readonly scene: SceneFileAssetRef;\n /** The content hash of that asset at save time. */\n readonly hash?: string;\n /** The patches applied to the instanced entities, in order. */\n readonly overrides?: readonly SceneFileOverride[];\n}\n\n/**\n * One entity of a scene file. The engine's `SceneFileEntity`.\n *\n * @public\n */\nexport interface SceneFileEntity {\n /** ULID, unique within the file. */\n readonly uid: string;\n /** The display name. */\n readonly name: string;\n /** The parent's uid, or `null` for a root. */\n readonly parent: string | null;\n /** Omitted when `true`, the default. */\n readonly active?: boolean;\n /** Omitted when `false`, the default. */\n readonly static?: boolean;\n /** The layer name, omitted when `\"Default\"`. */\n readonly layer?: string;\n /** The tags, omitted when empty. */\n readonly tags?: readonly string[];\n /** Always present. */\n readonly transform: SceneFileTransform;\n /** Present only on instance roots. */\n readonly instance?: SceneFileInstance;\n /** The entity's own components; on an instance root, the ones added on top of the instance. */\n readonly components?: readonly SceneFileComponent[];\n}\n\n/**\n * A whole scene or prefab file. The engine's `SceneFile`.\n *\n * @public\n */\nexport interface SceneFile {\n /** Always `\"ignifx.scene\"`. */\n readonly format: string;\n /** `1` for every file the engine writes before 1.0. */\n readonly formatVersion: number;\n /** The `@ignifx/core` version that wrote the file; informational. */\n readonly engineVersion?: string;\n /** The scene's name. */\n readonly name: string;\n /** Scene-level values interpreted by systems. */\n readonly settings?: JsonObject;\n /** Every entity, in tree order: parents before children, siblings in order. */\n readonly entities: readonly SceneFileEntity[];\n}\n\n/** How deep a JSON value may nest before {@link isJsonValue} refuses it, as a guard against cycles. */\nconst MAX_JSON_DEPTH = 256;\n\n/**\n * Tells whether a value is JSON: `null`, a boolean, a string, a finite number, or an array or\n * plain object of JSON values, nested at most 256 levels deep.\n *\n * @param value - The value to test.\n * @returns True for a JSON value.\n *\n * @public\n */\nexport function isJsonValue(value: unknown): value is JsonValue {\n return isJsonValueAt(value, 0);\n}\n\n/**\n * {@link isJsonValue} at a nesting depth.\n *\n * @param value - The value to test.\n * @param depth - How deep the value sits.\n * @returns True for a JSON value no deeper than the limit.\n */\nfunction isJsonValueAt(value: unknown, depth: number): value is JsonValue {\n if (depth > MAX_JSON_DEPTH) {\n return false;\n }\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") {\n return true;\n }\n if (typeof value === \"number\") {\n return Number.isFinite(value);\n }\n if (Array.isArray(value)) {\n return value.every((item: unknown) => isJsonValueAt(item, depth + 1));\n }\n if (!isRecord(value)) {\n return false;\n }\n const prototype: unknown = Object.getPrototypeOf(value);\n return (\n (prototype === Object.prototype || prototype === null) &&\n Object.values(value).every((item) => isJsonValueAt(item, depth + 1))\n );\n}\n\n/**\n * Tells whether a value is a JSON object.\n *\n * @param value - The value to test.\n * @returns True for a plain object of JSON values.\n *\n * @public\n */\nexport function isJsonObject(value: unknown): value is JsonObject {\n return isRecord(value) && isJsonValue(value);\n}\n\n/**\n * Tells whether a value is a uid: a non-empty string, as the scene format's `uid` definition\n * requires. Whether it is a ULID is not the wire's concern.\n *\n * @param value - The value to test.\n * @returns True for a non-empty string.\n *\n * @internal\n */\nexport function isUidString(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0;\n}\n\n/**\n * Tells whether a value is a finite number.\n *\n * @param value - The value to test.\n * @returns True for a finite number.\n *\n * @internal\n */\nexport function isFiniteNumber(value: unknown): value is number {\n return typeof value === \"number\" && Number.isFinite(value);\n}\n\n/**\n * Tells whether a value is an array of finite numbers of one length.\n *\n * @param value - The value to test.\n * @param length - The required length.\n * @returns True for `length` finite numbers.\n *\n * @internal\n */\nexport function isNumberTuple(value: unknown, length: number): boolean {\n return Array.isArray(value) && value.length === length && value.every((item: unknown) => isFiniteNumber(item));\n}\n\n/**\n * Tells whether a value is an array whose every item passes a test.\n *\n * @param value - The value to test.\n * @param item - The test for one item.\n * @returns True for an array of passing items.\n *\n * @internal\n */\nexport function isArrayOf<T>(value: unknown, item: (entry: unknown) => entry is T): value is readonly T[] {\n return Array.isArray(value) && value.every((entry: unknown) => item(entry));\n}\n\n/**\n * Tells whether an optional field of a record is absent or passes a test.\n *\n * @param record - The record.\n * @param key - The field.\n * @param test - The test for a present value.\n * @returns True when the field is absent (or `undefined`) or passes.\n *\n * @internal\n */\nexport function optionalField(\n record: Record<string, unknown>,\n key: string,\n test: (value: unknown) => boolean,\n): boolean {\n const value = record[key];\n return value === undefined || test(value);\n}\n\n/**\n * Tells whether a value is a string.\n *\n * @param value - The value to test.\n * @returns True for a string.\n *\n * @internal\n */\nexport function isString(value: unknown): value is string {\n return typeof value === \"string\";\n}\n\n/**\n * Tells whether a value is a boolean.\n *\n * @param value - The value to test.\n * @returns True for a boolean.\n *\n * @internal\n */\nexport function isBoolean(value: unknown): value is boolean {\n return typeof value === \"boolean\";\n}\n\n/**\n * Checks an asset reference.\n *\n * @param value - The value to test.\n * @returns True for `{ $asset: string, type?: string }`.\n *\n * @public\n */\nexport function isSceneFileAssetRef(value: unknown): value is SceneFileAssetRef {\n return isRecord(value) && isString(value[\"$asset\"]) && optionalField(value, \"type\", isString);\n}\n\n/**\n * Checks a local transform.\n *\n * @param value - The value to test.\n * @returns True for three, four and three finite numbers in `position`, `rotation` and `scale`.\n *\n * @public\n */\nexport function isSceneFileTransform(value: unknown): value is SceneFileTransform {\n return (\n isRecord(value) &&\n isNumberTuple(value[\"position\"], 3) &&\n isNumberTuple(value[\"rotation\"], 4) &&\n isNumberTuple(value[\"scale\"], 3)\n );\n}\n\n/**\n * Checks a component record.\n *\n * @param value - The value to test.\n * @returns True for a record with a uid, a type and well-typed optional fields.\n *\n * @public\n */\nexport function isSceneFileComponent(value: unknown): value is SceneFileComponent {\n return (\n isRecord(value) &&\n isUidString(value[\"uid\"]) &&\n isString(value[\"type\"]) &&\n optionalField(value, \"enabled\", isBoolean) &&\n optionalField(value, \"schemaVersion\", (version) => Number.isSafeInteger(version)) &&\n optionalField(value, \"props\", isJsonObject)\n );\n}\n\n/**\n * Tells whether a value is an override's `op`.\n *\n * @param value - The value to test.\n * @returns True for `\"replace\"`, `\"remove\"` or `\"add\"`.\n *\n * @internal\n */\nexport function isOverrideOp(value: unknown): value is \"replace\" | \"remove\" | \"add\" {\n return value === \"replace\" || value === \"remove\" || value === \"add\";\n}\n\n/**\n * Checks an override patch.\n *\n * @param value - The value to test.\n * @returns True for `{ op?, path, value? }` with a known `op` and a JSON `value`.\n *\n * @public\n */\nexport function isSceneFileOverride(value: unknown): value is SceneFileOverride {\n return (\n isRecord(value) &&\n isString(value[\"path\"]) &&\n optionalField(value, \"op\", isOverrideOp) &&\n optionalField(value, \"value\", (patch) => isJsonValue(patch))\n );\n}\n\n/**\n * Checks an `instance` entry.\n *\n * @param value - The value to test.\n * @returns True for `{ scene, hash?, overrides? }`.\n *\n * @public\n */\nexport function isSceneFileInstance(value: unknown): value is SceneFileInstance {\n return (\n isRecord(value) &&\n isSceneFileAssetRef(value[\"scene\"]) &&\n optionalField(value, \"hash\", isString) &&\n optionalField(value, \"overrides\", (overrides) => isArrayOf(overrides, isSceneFileOverride))\n );\n}\n\n/**\n * Checks an entity record.\n *\n * @param value - The value to test.\n * @returns True for a record with a uid, a name, a parent, a transform and well-typed optional\n * fields.\n *\n * @public\n */\nexport function isSceneFileEntity(value: unknown): value is SceneFileEntity {\n if (!isRecord(value)) {\n return false;\n }\n const parent = value[\"parent\"];\n return (\n isUidString(value[\"uid\"]) &&\n isString(value[\"name\"]) &&\n (parent === null || isUidString(parent)) &&\n optionalField(value, \"active\", isBoolean) &&\n optionalField(value, \"static\", isBoolean) &&\n optionalField(value, \"layer\", isString) &&\n optionalField(value, \"tags\", (tags) => isArrayOf(tags, isString)) &&\n isSceneFileTransform(value[\"transform\"]) &&\n optionalField(value, \"instance\", isSceneFileInstance) &&\n optionalField(value, \"components\", (components) => isArrayOf(components, isSceneFileComponent))\n );\n}\n\n/**\n * Checks a whole scene file's structure.\n *\n * @param value - The value to test.\n * @returns True for a file object whose header fields and entity records have the right types.\n *\n * @public\n */\nexport function isSceneFile(value: unknown): value is SceneFile {\n return (\n isRecord(value) &&\n isString(value[\"format\"]) &&\n Number.isSafeInteger(value[\"formatVersion\"]) &&\n optionalField(value, \"engineVersion\", isString) &&\n isString(value[\"name\"]) &&\n optionalField(value, \"settings\", isJsonObject) &&\n isArrayOf(value[\"entities\"], isSceneFileEntity)\n );\n}\n","// A copy of `packages/editor-protocol/src/scene-ops.ts` from `astrum-forge/ignifx-editor` (protocol 0.3).\n// Below this comment it is byte-identical to that file, but for the link rule in `./index.ts`.\n/**\n * The scene op vocabulary on the wire: the thirteen ops of plan §3.4, exactly as\n * `@ignifx/editor-core` defines them (`packages/editor-core/src/ops.ts`), so a command the editor\n * applied to its document is sent to the host unchanged and MCP's `apply_ops` accepts the same JSON.\n *\n * @remarks\n * The types are restated here because this package has no dependencies. Every op, field name and\n * literal string is editor-core's; the package's tests check that editor-core's `SceneOp` and this\n * one are assignable both ways. Whether an op makes sense for a document (does the entity exist, is\n * the index in range) is not the wire's question: editor-core answers it before the op is sent, and\n * the host answers it again when it applies the op to the live world.\n */\nimport { isRecord } from \"./rpc.js\";\nimport {\n isArrayOf,\n isBoolean,\n isJsonValue,\n isOverrideOp,\n isSceneFileEntity,\n isSceneFileComponent,\n isSceneFileInstance,\n isSceneFileOverride,\n isSceneFileTransform,\n isString,\n isUidString,\n optionalField,\n} from \"./scene-file.js\";\nimport type {\n JsonValue,\n SceneFileComponent,\n SceneFileEntity,\n SceneFileInstance,\n SceneFileOverride,\n SceneFileTransform,\n} from \"./scene-file.js\";\n\n/**\n * The `op` discriminant of every scene op.\n *\n * @remarks\n * `as const` object plus derived union rather than an `enum` (engine coding standards §5.2, §5.3).\n *\n * @public\n */\nexport const SceneOpKind = {\n /** Creates an entity, optionally with a subtree. */\n createEntity: \"createEntity\",\n /** Destroys an entity and its subtree. */\n destroyEntity: \"destroyEntity\",\n /** Moves an entity under another parent, keeping its local transform. */\n reparent: \"reparent\",\n /** Moves an entity among its siblings. */\n reorder: \"reorder\",\n /** Sets `name`, `active`, `static`, `layer` or `tags`. */\n setEntityField: \"setEntityField\",\n /** Sets an entity's local transform. */\n setTransform: \"setTransform\",\n /** Adds a component. */\n addComponent: \"addComponent\",\n /** Removes a component. */\n removeComponent: \"removeComponent\",\n /** Sets or removes a value inside a component's `props`. */\n setProp: \"setProp\",\n /** Sets or removes a value inside the scene's `settings`. */\n setSceneSetting: \"setSceneSetting\",\n /** Creates an instance root (a prefab instance). */\n instantiate: \"instantiate\",\n /** Sets an override on an instance root. */\n setOverride: \"setOverride\",\n /** Removes an override from an instance root. */\n removeOverride: \"removeOverride\",\n} as const;\n\n/**\n * The union of the names in `SceneOpKind`.\n *\n * @public\n */\nexport type SceneOpKind = (typeof SceneOpKind)[keyof typeof SceneOpKind];\n\n/**\n * The entity properties {@link SetEntityFieldOp} writes, and their value types.\n *\n * @public\n */\nexport interface EntityFieldValues {\n /** The display name. */\n readonly name: string;\n /** `false` deactivates the entity and its subtree. */\n readonly active: boolean;\n /** The static flag. */\n readonly static: boolean;\n /** The layer name; `\"Default\"` is the default. */\n readonly layer: string;\n /** The tags; stored deduplicated and sorted, as the serializer writes them. */\n readonly tags: readonly string[];\n}\n\n/**\n * The name of an entity property {@link SetEntityFieldOp} writes.\n *\n * @public\n */\nexport type EntityField = keyof EntityFieldValues;\n\n/**\n * A path into a JSON object: object keys as strings, array indices as whole numbers.\n *\n * @public\n */\nexport type JsonPath = readonly (string | number)[];\n\n/**\n * Creates an entity, optionally with a whole subtree below it. `entity.parent` places it; `index`\n * is its place among the parent's children (default: last); `descendants` are further records,\n * parents first.\n *\n * @public\n */\nexport interface CreateEntityOp {\n /** The discriminant. */\n readonly op: \"createEntity\";\n /** The new entity's record, including its components and, for an instance root, its `instance`. */\n readonly entity: SceneFileEntity;\n /** The entity's index among its siblings; defaults to the end. */\n readonly index?: number;\n /** The rest of the subtree, parents first. */\n readonly descendants?: readonly SceneFileEntity[];\n}\n\n/**\n * Destroys an entity and its whole subtree.\n *\n * @public\n */\nexport interface DestroyEntityOp {\n /** The discriminant. */\n readonly op: \"destroyEntity\";\n /** The entity's uid. */\n readonly entity: string;\n}\n\n/**\n * Moves an entity under another parent, keeping its local transform.\n *\n * @public\n */\nexport interface ReparentOp {\n /** The discriminant. */\n readonly op: \"reparent\";\n /** The entity's uid. */\n readonly entity: string;\n /** The new parent's uid, or `null` to make the entity a root. */\n readonly parent: string | null;\n /** The entity's index among its new siblings; defaults to the end. */\n readonly index?: number;\n}\n\n/**\n * Moves an entity among its siblings; `index` is its place after the move.\n *\n * @public\n */\nexport interface ReorderOp {\n /** The discriminant. */\n readonly op: \"reorder\";\n /** The entity's uid. */\n readonly entity: string;\n /** The new index among its siblings. */\n readonly index: number;\n}\n\n/**\n * Sets one entity property.\n *\n * @public\n */\nexport type SetEntityFieldOp = {\n readonly [F in EntityField]: {\n /** The discriminant. */\n readonly op: \"setEntityField\";\n /** The entity's uid. */\n readonly entity: string;\n /** Which property. */\n readonly field: F;\n /** The new value. */\n readonly value: EntityFieldValues[F];\n };\n}[EntityField];\n\n/**\n * Sets an entity's local transform. `before` is informational and ignored when applying.\n *\n * @public\n */\nexport interface SetTransformOp {\n /** The discriminant. */\n readonly op: \"setTransform\";\n /** The entity's uid. */\n readonly entity: string;\n /** The new local transform. */\n readonly after: SceneFileTransform;\n /** The local transform the emitter saw before the change; ignored when applying. */\n readonly before?: SceneFileTransform;\n}\n\n/**\n * Adds a component to an entity.\n *\n * @public\n */\nexport interface AddComponentOp {\n /** The discriminant. */\n readonly op: \"addComponent\";\n /** The entity's uid. */\n readonly entity: string;\n /** The component's record; its uid must be new to the document. */\n readonly component: SceneFileComponent;\n /** The component's index on the entity; defaults to the end. */\n readonly index?: number;\n}\n\n/**\n * Removes a component.\n *\n * @public\n */\nexport interface RemoveComponentOp {\n /** The discriminant. */\n readonly op: \"removeComponent\";\n /** The component's uid. */\n readonly component: string;\n}\n\n/**\n * Sets, or removes, a value inside a component's `props`. `path[0]` is the field name; an absent\n * `value` removes the key; the empty path addresses `props` itself.\n *\n * @public\n */\nexport interface SetPropOp {\n /** The discriminant. */\n readonly op: \"setProp\";\n /** The component's uid. */\n readonly component: string;\n /** The path into `props`. */\n readonly path: JsonPath;\n /** The new value; absent removes the key. */\n readonly value?: JsonValue;\n}\n\n/**\n * Sets, or removes, a value inside the scene's `settings`, with {@link SetPropOp}'s path rules.\n *\n * @public\n */\nexport interface SetSceneSettingOp {\n /** The discriminant. */\n readonly op: \"setSceneSetting\";\n /** The path into `settings`; `path[0]` is the setting's key. */\n readonly path: JsonPath;\n /** The new value; absent removes the key. */\n readonly value?: JsonValue;\n}\n\n/**\n * Creates an instance root: an entity carrying an `instance` entry.\n *\n * @public\n */\nexport interface InstantiateOp {\n /** The discriminant. */\n readonly op: \"instantiate\";\n /** The new entity's uid. */\n readonly entity: string;\n /** Its name; usually the prefab root's name. */\n readonly name: string;\n /** Its parent's uid, or `null` for a root. */\n readonly parent: string | null;\n /** Its index among its siblings; defaults to the end. */\n readonly index?: number;\n /** Its local transform. */\n readonly transform: SceneFileTransform;\n /** The instance entry: the scene asset, its hash, and any overrides. */\n readonly instance: SceneFileInstance;\n}\n\n/**\n * Sets an override on an instance root's entry, replacing the override with the same identity or\n * inserting a new one at `index` (default: last).\n *\n * @public\n */\nexport interface SetOverrideOp {\n /** The discriminant. */\n readonly op: \"setOverride\";\n /** The instance root's uid. */\n readonly entity: string;\n /** The override. */\n readonly override: SceneFileOverride;\n /** Where a new override goes; defaults to the end. */\n readonly index?: number;\n}\n\n/**\n * Removes an override from an instance root's entry.\n *\n * @public\n */\nexport interface RemoveOverrideOp {\n /** The discriminant. */\n readonly op: \"removeOverride\";\n /** The instance root's uid. */\n readonly entity: string;\n /** The override's path. */\n readonly path: string;\n /** The override's `op`; defaults to what the path implies. */\n readonly overrideOp?: \"replace\" | \"remove\" | \"add\";\n /** For a component `add`, the uid of the component it adds. */\n readonly added?: string;\n}\n\n/**\n * One scene op: the closed vocabulary of plan §3.4, identical to `@ignifx/editor-core`'s `SceneOp`.\n *\n * @public\n */\nexport type SceneOp =\n | CreateEntityOp\n | DestroyEntityOp\n | ReparentOp\n | ReorderOp\n | SetEntityFieldOp\n | SetTransformOp\n | AddComponentOp\n | RemoveComponentOp\n | SetPropOp\n | SetSceneSettingOp\n | InstantiateOp\n | SetOverrideOp\n | RemoveOverrideOp;\n\n/**\n * Tells whether a value is an insertion index: a non-negative safe integer. Whether it is in range\n * is the applier's question.\n *\n * @param value - The value to test.\n * @returns True for a non-negative safe integer.\n */\nfunction isIndex(value: unknown): boolean {\n return Number.isSafeInteger(value) && Number(value) >= 0;\n}\n\n/**\n * Tells whether a value is a JSON path.\n *\n * @param value - The value to test.\n * @returns True for an array of strings and non-negative safe integers.\n */\nfunction isJsonPath(value: unknown): value is JsonPath {\n return isArrayOf(value, (step): step is string | number => isString(step) || isIndex(step));\n}\n\n/**\n * Tells whether a value is a parent: a uid or `null`.\n *\n * @param value - The value to test.\n * @returns True for `null` or a uid.\n */\nfunction isParent(value: unknown): value is string | null {\n return value === null || isUidString(value);\n}\n\n/** The value test for each field {@link SetEntityFieldOp} writes. */\nconst ENTITY_FIELD_TESTS: Readonly<Record<EntityField, (value: unknown) => boolean>> = {\n name: isString,\n active: isBoolean,\n static: isBoolean,\n layer: isString,\n tags: (value) => isArrayOf(value, isString),\n};\n\n/** The structural test of each op's fields beyond `op`. */\nconst OP_TESTS: Readonly<Record<SceneOpKind, (op: Record<string, unknown>) => boolean>> = {\n createEntity: (op) =>\n isSceneFileEntity(op[\"entity\"]) &&\n optionalField(op, \"index\", isIndex) &&\n optionalField(op, \"descendants\", (descendants) => isArrayOf(descendants, isSceneFileEntity)),\n destroyEntity: (op) => isUidString(op[\"entity\"]),\n reparent: (op) => isUidString(op[\"entity\"]) && isParent(op[\"parent\"]) && optionalField(op, \"index\", isIndex),\n reorder: (op) => isUidString(op[\"entity\"]) && isIndex(op[\"index\"]),\n setEntityField: (op) => {\n const field = op[\"field\"];\n const test = Object.entries(ENTITY_FIELD_TESTS).find(([name]) => name === field)?.[1];\n return isUidString(op[\"entity\"]) && test !== undefined && test(op[\"value\"]);\n },\n setTransform: (op) =>\n isUidString(op[\"entity\"]) && isSceneFileTransform(op[\"after\"]) && optionalField(op, \"before\", isSceneFileTransform),\n addComponent: (op) =>\n isUidString(op[\"entity\"]) && isSceneFileComponent(op[\"component\"]) && optionalField(op, \"index\", isIndex),\n removeComponent: (op) => isUidString(op[\"component\"]),\n setProp: (op) =>\n isUidString(op[\"component\"]) && isJsonPath(op[\"path\"]) && optionalField(op, \"value\", (value) => isJsonValue(value)),\n setSceneSetting: (op) => isJsonPath(op[\"path\"]) && optionalField(op, \"value\", (value) => isJsonValue(value)),\n instantiate: (op) =>\n isUidString(op[\"entity\"]) &&\n isString(op[\"name\"]) &&\n isParent(op[\"parent\"]) &&\n optionalField(op, \"index\", isIndex) &&\n isSceneFileTransform(op[\"transform\"]) &&\n isSceneFileInstance(op[\"instance\"]),\n setOverride: (op) =>\n isUidString(op[\"entity\"]) && isSceneFileOverride(op[\"override\"]) && optionalField(op, \"index\", isIndex),\n removeOverride: (op) =>\n isUidString(op[\"entity\"]) &&\n isString(op[\"path\"]) &&\n optionalField(op, \"overrideOp\", isOverrideOp) &&\n optionalField(op, \"added\", isUidString),\n};\n\n/**\n * Checks the structure of one scene op: a known `op` and fields of the right types.\n *\n * @remarks\n * It answers \"is this an op of the vocabulary\", not \"does it apply\": uids are checked to be\n * non-empty strings, indices to be non-negative integers, values to be JSON, and records to have the\n * scene format's shape. Unknown extra fields are ignored. A `setProp` or `setSceneSetting` value may\n * be any JSON; that the empty path receives an object is the applier's check.\n *\n * @param value - A received op.\n * @returns True when `value` is a structurally valid {@link SceneOp}.\n *\n * @example\n * ```ts\n * isSceneOp({ op: \"setEntityField\", entity: \"01J9Z6M7E5S3A0V2Q4R8T1Y6WX\", field: \"name\", value: \"Player\" }); // true\n * isSceneOp({ op: \"setEntityField\", entity: \"01J9Z6M7E5S3A0V2Q4R8T1Y6WX\", field: \"name\", value: 3 }); // false\n * ```\n *\n * @public\n */\nexport function isSceneOp(value: unknown): value is SceneOp {\n if (!isRecord(value)) {\n return false;\n }\n const kind = value[\"op\"];\n const test = Object.entries(OP_TESTS).find(([name]) => name === kind)?.[1];\n return test !== undefined && test(value);\n}\n","// A copy of `packages/editor-protocol/src/scene.ts` from `astrum-forge/ignifx-editor` (protocol 0.3).\n// Below this comment it is byte-identical to that file, but for the link rule in `./index.ts`.\n/**\n * Protocol 0.3: the scene document transport between the editor and the scene view\n * (`@ignifx/editor-host`). Plan §3.4, §3.5, §3.7.\n *\n * The editor holds the scene document (`@ignifx/editor-core`) and the host mirrors it into a live\n * world: the editor opens the scene with the whole file, then sends every command's ops as it\n * applies them. The host reports what the user does in the view (a pick click, a gizmo drag) as\n * notifications, which the editor turns into commands of its own; the host never edits the document.\n * `docs/protocol.md`, \"0.3: scene documents\", gives the sequences and what the host must do per\n * method.\n */\nimport { isRecord } from \"./rpc.js\";\nimport {\n isArrayOf,\n isBoolean,\n isFiniteNumber,\n isJsonObject,\n isJsonValue,\n isNumberTuple,\n isSceneFile,\n isSceneFileEntity,\n isSceneFileTransform,\n isString,\n isUidString,\n optionalField,\n} from \"./scene-file.js\";\nimport { isSceneOp } from \"./scene-ops.js\";\nimport type { RpcNotification, RpcRequest, RpcSuccessResponse } from \"./rpc.js\";\nimport type { JsonObject, JsonValue, SceneFile, SceneFileEntity, SceneFileTransform } from \"./scene-file.js\";\nimport type { SceneOp } from \"./scene-ops.js\";\n\n/**\n * Editor → scene host: the methods of protocol 0.3, answered after `ready`.\n *\n * @remarks\n * `as const` object plus derived union rather than an `enum` (engine coding standards §5.2, §5.3).\n *\n * The host handles these requests one at a time, in the order they arrive: a request starts only\n * after the previous one has been answered, so `applyOps` sent right after `openScene` sees the new\n * scene. Until the host's app has started, every one of them fails with `RpcErrorCode.notReady`;\n * the host's first `schemasChanged` is the editor's cue that they are accepted. A method that needs\n * an open scene fails with `RpcErrorCode.noScene` while none is open. A method whose capability the\n * host does not list in `ready` fails with `RpcErrorCode.methodNotFound`.\n *\n * @public\n */\nexport const SceneMethod = {\n /** Opens a scene from the editor's document, replacing any open scene. Answers {@link OpenSceneResult}. */\n openScene: \"openScene\",\n /** Unloads the open scene, if any. Answers `null`. */\n closeScene: \"closeScene\",\n /** Applies one command's ops to the open scene, in order. Answers {@link ApplyOpsResult}. */\n applyOps: \"applyOps\",\n /** Serializes entities of the open scene as the live world has them. Answers {@link ReadBackResult}. */\n readBack: \"readBack\",\n /** Sets the selection the view outlines and attaches the gizmo to. Answers {@link EntitySelection}. */\n select: \"select\",\n /** Sets the gizmo's mode, space and snapping. Needs `HostCapability.gizmos`. Answers `null`. */\n setGizmo: \"setGizmo\",\n /** Moves the editor camera to frame entities. Answers `null`. */\n frame: \"frame\",\n /** Asks which entity is under a point of the view, without selecting it. Answers {@link PickResult}. */\n pick: \"pick\",\n /** Captures the view as an image. Needs `HostCapability.screenshot`. Answers {@link ScreenshotResult}. */\n screenshot: \"screenshot\",\n /** Describes every registered component's schema. Answers {@link SchemaSet}. */\n getSchemas: \"getSchemas\",\n /**\n * Describes the project's settings sections and the values the app resolved for them. Answers\n * {@link SettingsSet}. A host from before it answers `RpcErrorCode.methodNotFound`.\n */\n describeSettings: \"describeSettings\",\n /** Switches the view between the 3D and the 2D editor camera. Answers `null`. */\n setViewMode: \"setViewMode\",\n} as const;\n\n/**\n * The union of the names in `SceneMethod`.\n *\n * @public\n */\nexport type SceneMethod = (typeof SceneMethod)[keyof typeof SceneMethod];\n\n/**\n * Scene host → editor: the notifications of protocol 0.3. None has an answer.\n *\n * @remarks\n * There is no `reloadScripts` method: script hot reload is Vite's. When a script changes, Vite\n * replaces the module in the host page, `acceptHotReload(app)` hands the new classes to\n * `app.hotReload.apply`, and the host reports the outcome with `hotReloaded` and `schemasChanged`.\n * A change that Vite cannot hot-replace reloads the host page, which the editor sees as a new load:\n * a new port, a new handshake, and `openScene` again.\n *\n * @public\n */\nexport const SceneNotification = {\n /** After the answer to every successful `openScene`: what was opened. */\n sceneOpened: \"sceneOpened\",\n /** Once the app has started (after `ready`), and after every hot reload: the component schemas. */\n schemasChanged: \"schemasChanged\",\n /** After every `app.hotReload` operation: its report. */\n hotReloaded: \"hotReloaded\",\n /** After a click in the view changed the selection: the new selection. */\n selectionChanged: \"selectionChanged\",\n /** During a gizmo drag, at most every {@link TRANSFORM_DRAGGING_INTERVAL_MS}: for display only. */\n transformDragging: \"transformDragging\",\n /** Once per gizmo gesture, at pointer-up: the editor turns it into a `setTransform` command. */\n transformDragged: \"transformDragged\",\n /** A failure that answers no request: an error the app reported, a failed hot reload. */\n hostError: \"hostError\",\n /** One line from the app's logger, for the editor's Console. */\n log: \"log\",\n /**\n * After the host reloaded an asset that changed on disk, in place: its address, its type, and\n * the document's instance roots rebuilt from it. A host from before it sends nothing.\n */\n assetReloaded: \"assetReloaded\",\n} as const;\n\n/**\n * The union of the names in `SceneNotification`.\n *\n * @public\n */\nexport type SceneNotification = (typeof SceneNotification)[keyof typeof SceneNotification];\n\n/**\n * The fewest milliseconds between two `transformDragging` notifications for the same gesture: at\n * most 20 a second, which S0.2 measured as smooth enough for an inspector to follow a drag.\n *\n * @public\n */\nexport const TRANSFORM_DRAGGING_INTERVAL_MS = 50;\n\n/**\n * The largest width and height, in pixels, of a `screenshot`. A request for more fails with\n * `invalidParams`; a request without a size gets the view's own size scaled down to fit. It keeps\n * an image well under what an MCP client accepts inline (plan §3.11).\n *\n * @public\n */\nexport const SCREENSHOT_MAX_SIZE = 2048;\n\n/**\n * A world-space point, `[x, y, z]`, in metres.\n *\n * @public\n */\nexport type Vec3 = readonly [number, number, number];\n\n/**\n * One recoverable problem the engine reported while building or serializing a scene: the engine's\n * `SceneLoadIssue` and `SerializeIssue`.\n *\n * @public\n */\nexport interface SceneIssue {\n /** The engine's diagnostic code, for example `\"IGX-0602\"`. */\n readonly code: string;\n /** The engine's actionable sentence. */\n readonly message: string;\n}\n\n/**\n * One structural problem in a scene file: the engine's `SceneFileIssue`, from `validateSceneFile`.\n *\n * @public\n */\nexport interface SceneFileIssue {\n /** Where the problem is, for example `\"entities/3/transform\"`. */\n readonly path: string;\n /** An actionable description. */\n readonly message: string;\n}\n\n/**\n * The parameters of `openScene`.\n *\n * @public\n */\nexport interface OpenSceneParams {\n /**\n * The whole scene file, as the editor's document holds it: the engine's `SceneFile` object, not\n * its text. It may differ from the file on disk (unsaved edits), so it is the only source the\n * host builds from.\n */\n readonly file: SceneFile;\n /**\n * The asset address the document is saved at, for example `\"scenes/level01.scene.json\"`, or\n * `null` for a document that has never been saved. The host names the scene's asset with it and\n * never loads the file from it.\n */\n readonly address: string | null;\n}\n\n/**\n * The answer to `openScene`, once every entity is built.\n *\n * @public\n */\nexport interface OpenSceneResult {\n /** How many entities the host built, including those expanded from instanced scenes. */\n readonly entityCount: number;\n /** Every recoverable problem the build reported, in order (`SceneBuildResult.issues`). */\n readonly warnings: readonly SceneIssue[];\n /**\n * The editor camera the scene is made for, as the host's engine sees it: `\"2d\"` when the project\n * draws sprites only (`twoD.mode: \"sprite\"`) or the scene's cameras are all `Camera2D`, else\n * `\"3d\"`. The host does not switch to it; the editor sends `setViewMode`. Absent from a host from\n * before it.\n */\n readonly viewMode?: ViewMode;\n}\n\n/**\n * The `data` of the `invalidParams` error `openScene` answers when `validateSceneFile` refuses the\n * file.\n *\n * @public\n */\nexport interface InvalidSceneFileData {\n /** What `validateSceneFile` reported. */\n readonly issues: readonly SceneFileIssue[];\n}\n\n/**\n * The parameters of `applyOps`: one command, as the editor applied it to its document.\n *\n * @public\n */\nexport interface ApplyOpsParams {\n /** The ops, in the order they apply. Undo sends the inverse ops; redo sends the ops again. */\n readonly ops: readonly SceneOp[];\n /** The command's label, for example `\"Move Player\"`, for the host's log. */\n readonly commandName: string;\n /** The editor's id for this command, unique on the channel, for correlating logs and failures. */\n readonly commandId: string;\n}\n\n/**\n * Why the host could not apply one op.\n *\n * @remarks\n * The first ten are `@ignifx/editor-core`'s `OpErrorCode`s, with its meanings, for a world that\n * disagrees with the document the op was checked against. The last two are the host's own.\n *\n * @public\n */\nexport const ApplyOpFailureCode = {\n /** Not an op of the vocabulary. */\n invalidOp: \"invalidOp\",\n /** The target entity uid is not in the open scene. */\n unknownEntity: \"unknownEntity\",\n /** The target component uid is not in the open scene. */\n unknownComponent: \"unknownComponent\",\n /** A new entity or component reuses a uid. */\n duplicateUid: \"duplicateUid\",\n /** A parent outside the scene, or a move under its own subtree. */\n invalidParent: \"invalidParent\",\n /** An index outside the list it positions in. */\n invalidIndex: \"invalidIndex\",\n /** A value of the wrong shape for its field. */\n invalidValue: \"invalidValue\",\n /** A JSON path or override path that does not resolve. */\n invalidPath: \"invalidPath\",\n /** An override op on an entity without an `instance` entry. */\n notAnInstance: \"notAnInstance\",\n /** No override with that identity. */\n unknownOverride: \"unknownOverride\",\n /** The host cannot apply this op to a live world yet; the editor reopens the scene instead. */\n unsupportedOp: \"unsupportedOp\",\n /** The engine threw while applying the op; `diagnostic` carries its `IGX-` code when it had one. */\n engineError: \"engineError\",\n} as const;\n\n/**\n * The union of the codes in `ApplyOpFailureCode`.\n *\n * @public\n */\nexport type ApplyOpFailureCode = (typeof ApplyOpFailureCode)[keyof typeof ApplyOpFailureCode];\n\n/**\n * One op the host could not apply.\n *\n * @public\n */\nexport interface ApplyOpFailure {\n /** The op's index in `ApplyOpsParams.ops`. */\n readonly index: number;\n /** Why it failed. */\n readonly code: ApplyOpFailureCode;\n /** An actionable sentence. */\n readonly message: string;\n /** The engine's diagnostic code, for example `\"IGX-0307\"`, when the engine reported one. */\n readonly diagnostic?: string;\n}\n\n/**\n * The answer to `applyOps`.\n *\n * @remarks\n * The host applies the ops in order and does not stop at a failure, so `applied + failures.length`\n * is the number of ops sent. Any failure means the live world no longer mirrors the document; the\n * editor then sends `openScene` with the whole document again.\n *\n * @public\n */\nexport interface ApplyOpsResult {\n /** How many ops were applied. */\n readonly applied: number;\n /** The ops that were not, in order. */\n readonly failures: readonly ApplyOpFailure[];\n}\n\n/**\n * The parameters of `readBack`.\n *\n * @public\n */\nexport interface ReadBackParams {\n /** The entities to serialize; absent for every entity of the open scene. */\n readonly entities?: readonly string[];\n}\n\n/**\n * The answer to `readBack`: the open scene's entities as `serializeScene` writes them from the live\n * world, which is what the document should hold when the mirror is exact.\n *\n * @public\n */\nexport interface ReadBackResult {\n /** The entity records, in tree order, as `serializeScene` writes them. */\n readonly entities: readonly SceneFileEntity[];\n /** The requested uids that name no entity of the open scene, in request order. */\n readonly missing: readonly string[];\n /** The scene's `settings`, or `null` when it has none. */\n readonly settings: JsonObject | null;\n /** What the serializer reported (`SerializeIssue`), in order. */\n readonly issues: readonly SceneIssue[];\n}\n\n/**\n * A selection: the parameters and the answer of `select`, and the parameters of `selectionChanged`.\n *\n * @public\n */\nexport interface EntitySelection {\n /** The selected entities' uids. The last one is the primary selection, which the gizmo follows. */\n readonly entities: readonly string[];\n}\n\n/**\n * What the gizmo does.\n *\n * @public\n */\nexport const GizmoMode = {\n /** Move along axes and planes. */\n translate: \"translate\",\n /** Rotate around axes. */\n rotate: \"rotate\",\n /** Scale along axes and uniformly. */\n scale: \"scale\",\n /** No gizmo; the selection is only outlined. */\n none: \"none\",\n} as const;\n\n/**\n * The union of the modes in `GizmoMode`.\n *\n * @public\n */\nexport type GizmoMode = (typeof GizmoMode)[keyof typeof GizmoMode];\n\n/**\n * The gizmo modes a drag can happen in: every `GizmoMode` but `none`.\n *\n * @public\n */\nexport type GizmoDragMode = Exclude<GizmoMode, typeof GizmoMode.none>;\n\n/**\n * Which axes the gizmo follows.\n *\n * @public\n */\nexport const GizmoSpace = {\n /** The entity's own axes. */\n local: \"local\",\n /** The world's axes. */\n world: \"world\",\n} as const;\n\n/**\n * The union of the spaces in `GizmoSpace`.\n *\n * @public\n */\nexport type GizmoSpace = (typeof GizmoSpace)[keyof typeof GizmoSpace];\n\n/**\n * The gizmo's snapping increments. `0` turns snapping off for that mode.\n *\n * @public\n */\nexport interface GizmoSnap {\n /** The translation step, in metres. */\n readonly translate: number;\n /** The rotation step, in degrees. */\n readonly rotate: number;\n /** The scale step, as a factor added per step (`0.1` snaps scale to tenths). */\n readonly scale: number;\n}\n\n/**\n * The parameters of `setGizmo`.\n *\n * @public\n */\nexport interface SetGizmoParams {\n /** What the gizmo does. */\n readonly mode: GizmoMode;\n /** Which axes it follows. */\n readonly space: GizmoSpace;\n /** The snapping increments, or `null` for no snapping. */\n readonly snap: GizmoSnap | null;\n}\n\n/**\n * The parameters of `frame`.\n *\n * @public\n */\nexport interface FrameParams {\n /** The entities to fit in the view, or `\"all\"` for the whole open scene. */\n readonly entities: readonly string[] | \"all\";\n}\n\n/**\n * The unit of a `pick` point (S0.2 §6.1).\n *\n * @public\n */\nexport const PickUnit = {\n /** CSS pixels from the view's top-left corner: a DOM event's `offsetX` and `offsetY`. */\n css: \"css\",\n /** The canvas's backing-store pixels: CSS pixels times `canvas.width / canvas.clientWidth`. */\n backing: \"backing\",\n} as const;\n\n/**\n * The union of the units in `PickUnit`.\n *\n * @public\n */\nexport type PickUnit = (typeof PickUnit)[keyof typeof PickUnit];\n\n/**\n * The parameters of `pick`.\n *\n * @public\n */\nexport interface PickParams {\n /** The point's x, from the view's left edge, in `unit`. */\n readonly x: number;\n /** The point's y, from the view's top edge, in `unit`. */\n readonly y: number;\n /** The unit of `x` and `y`; the host converts it to whatever its engine's picker takes. */\n readonly unit: PickUnit;\n}\n\n/**\n * A world-space ray from the view's camera through a point of the view.\n *\n * @public\n */\nexport interface PickRay {\n /** Where the ray starts, in metres: the point under the cursor on the camera's near plane. */\n readonly origin: Vec3;\n /** Which way it points: a unit vector. */\n readonly direction: Vec3;\n}\n\n/**\n * The answer to `pick`.\n *\n * @public\n */\nexport interface PickResult {\n /** The scene entity hit, or `null` for a miss. A hit inside an instanced scene names its instance root. */\n readonly entity: string | null;\n /** The world-space hit point, or `null` for a miss or when the picker does not report one. */\n readonly point: Vec3 | null;\n /** How far along the camera ray the hit is, in metres, or `null` for a miss or a 2D pick. */\n readonly distance: number | null;\n /**\n * The ray the view's camera casts through the point, hit or miss, so that an editor can place\n * something where nothing was hit (a 3D editor intersects it with its ground plane, `y = 0`).\n * Absent when the host builds no ray (a headless view, a point outside the canvas) and from a host\n * from before it.\n */\n readonly ray?: PickRay;\n /**\n * Where `ray` meets the 2D world plane `z = 0`, as `[x, y, 0]`: in a 2D scene, the world point\n * under the cursor. Absent when `ray` is, and when the ray runs parallel to the plane or meets it\n * behind its origin.\n */\n readonly plane?: Vec3;\n}\n\n/**\n * The image formats of a `screenshot`.\n *\n * @public\n */\nexport const ScreenshotFormat = {\n /** Lossless, `image/png`. */\n png: \"png\",\n /** Lossy, `image/jpeg`. */\n jpeg: \"jpeg\",\n} as const;\n\n/**\n * The union of the formats in `ScreenshotFormat`.\n *\n * @public\n */\nexport type ScreenshotFormat = (typeof ScreenshotFormat)[keyof typeof ScreenshotFormat];\n\n/**\n * The parameters of `screenshot`.\n *\n * @public\n */\nexport interface ScreenshotParams {\n /** The image width in pixels, 1 to {@link SCREENSHOT_MAX_SIZE}; absent to follow the view. */\n readonly width?: number;\n /** The image height in pixels, 1 to {@link SCREENSHOT_MAX_SIZE}; absent to follow the view. */\n readonly height?: number;\n /** The image format. */\n readonly format: ScreenshotFormat;\n /** The JPEG quality, from 0 to 1; the host's default (0.9) when absent. Ignored for PNG. */\n readonly quality?: number;\n}\n\n/**\n * The answer to `screenshot`.\n *\n * @public\n */\nexport interface ScreenshotResult {\n /** The image as a `data:image/png;base64,…` or `data:image/jpeg;base64,…` URL. */\n readonly dataUrl: string;\n /** The image width in pixels. */\n readonly width: number;\n /** The image height in pixels. */\n readonly height: number;\n}\n\n/**\n * One field of a component schema: the engine's `SchemaFieldDescription`.\n *\n * @public\n */\nexport interface SchemaFieldDescription {\n /** The field kind, for example `\"f32\"` or `\"asset\"`; an editor shows a kind it does not know as JSON. */\n readonly kind: string;\n /** The field's default value, encoded as JSON. */\n readonly default?: JsonValue;\n /** The field's tooltip. */\n readonly description?: string;\n /**\n * The increment of the inspector's drag and spinner controls (`FieldOptions.step`), present only\n * when the field declares one; in degrees for a `quat` field, which an inspector edits as Euler\n * angles.\n */\n readonly step?: number;\n /** `FieldOptions.hidden`: the inspector leaves the field out; it is still saved. */\n readonly hidden?: boolean;\n /** `FieldOptions.readonly`: the inspector shows the field but does not let it be edited. */\n readonly readonly?: boolean;\n /** `FieldOptions.group`: the inspector group the field folds into. */\n readonly group?: string;\n /**\n * An `asset` field's asset type name (`asset(TextureAsset)` → `\"texture\"`), the `type` an asset\n * reference to it carries; absent when the asset token names no type.\n */\n readonly assetType?: string;\n /**\n * A `componentRef` field's accepted component, as its `typeId`, or `null` when the class it was\n * declared with carries no `typeId`; present on every `componentRef` field a 0.3 host describes\n * with core's `describeRegisteredSchemas`.\n */\n readonly componentType?: string | null;\n}\n\n/**\n * One component schema: the engine's `SchemaDescription`, plus the JSON Schema of its `props`.\n *\n * @public\n */\nexport interface SchemaDescription {\n /** The human-readable name. */\n readonly title: string;\n /** `\"components\"` for a component; a file format's name for the engine's file-format entries. */\n readonly format: string;\n /** A one-line summary. */\n readonly description?: string;\n /** Every declared field, in declaration order. */\n readonly fields: Readonly<Record<string, SchemaFieldDescription>>;\n /**\n * Whether an entity may hold more than one of the component (the class's `static allowMultiple`,\n * `true` when it declares nothing); absent on file-format entries and from a host from before\n * core's `describeRegisteredSchemas`, where an editor assumes `true`.\n */\n readonly allowMultiple?: boolean;\n /**\n * Who registered the component: the extension's `name` (the npm package name, for example\n * `@ignifx/3d`), or, for a class the game registered itself, its type id's namespace (`game` for\n * `game/Health`); absent on file-format entries and from a host from before\n * `describeRegisteredSchemas`.\n */\n readonly package?: string;\n /**\n * `true` for the one component every entity carries itself, `ignifx/Transform`: it is never in a\n * scene file's `components` list, an editor neither adds nor removes it, and its fields are the\n * entity record's `transform` block, edited whole with the `setTransform` op rather than prop by\n * prop. Absent on every other entry. A host from before the engine described the transform (engine\n * ask E4) sends no such member.\n */\n readonly builtIn?: boolean;\n /**\n * The JSON Schema of the component's `props` (the engine's `toJsonSchema(schema)`), which adds\n * each field's `minimum`, `maximum`, `enum` and nested shapes; absent for file-format entries.\n */\n readonly propsSchema?: JsonObject;\n}\n\n/**\n * Every schema the host's app knows: the answer to `getSchemas` and the parameters of\n * `schemasChanged`.\n *\n * @public\n */\nexport interface SchemaSet {\n /** The descriptions, keyed by component `typeId` (file formats by `ignifx/<format>-file`). */\n readonly schemas: Readonly<Record<string, SchemaDescription>>;\n}\n\n/**\n * The project's settings as the host's app has them: the answer to `describeSettings`.\n *\n * @public\n */\nexport interface SettingsSet {\n /**\n * Every settings section the app registered (core's and each extension's), keyed by section name,\n * in registration order: the engine's `describeSettings(app)`. Each has `format: \"settings\"`, the\n * registering extension as `package`, field defaults in the settings form (a vector is\n * `{ x, y, z }` and a colour `{ r, g, b, a }`, not the scene file's arrays), and as `propsSchema`\n * the JSON Schema of the section as `ignifx.settings.json` may write it (its entry in the engine's\n * `settingsJsonSchema(app)`).\n */\n readonly sections: Readonly<Record<string, SchemaDescription>>;\n /**\n * The values the app resolved for each section, keyed by section name, in the same settings form:\n * the project's settings over the section's defaults. A value JSON cannot carry (a function, a\n * non-finite number) is left out.\n */\n readonly values: Readonly<Record<string, JsonObject>>;\n}\n\n/**\n * The editor cameras the view can use.\n *\n * @public\n */\nexport const ViewMode = {\n /** The 3D editor camera, gizmos and grid. */\n threeD: \"3d\",\n /** The 2D editor camera, planar gizmos and pixel grid. Needs `HostCapability.viewMode2d`. */\n twoD: \"2d\",\n} as const;\n\n/**\n * The union of the modes in `ViewMode`.\n *\n * @public\n */\nexport type ViewMode = (typeof ViewMode)[keyof typeof ViewMode];\n\n/**\n * The parameters of `setViewMode`.\n *\n * @public\n */\nexport interface SetViewModeParams {\n /** The editor camera to use. */\n readonly mode: ViewMode;\n}\n\n/**\n * The parameters of `sceneOpened`.\n *\n * @public\n */\nexport interface SceneOpenedParams {\n /** The address `openScene` was given. */\n readonly address: string | null;\n /** The file's `name`. */\n readonly name: string;\n /** As in {@link OpenSceneResult}. */\n readonly entityCount: number;\n /** As in {@link OpenSceneResult}. */\n readonly warnings: readonly SceneIssue[];\n /** As in {@link OpenSceneResult}. */\n readonly viewMode?: ViewMode;\n}\n\n/**\n * One error a hot reload ran into.\n *\n * @public\n */\nexport interface HotReloadError {\n /** The error's message (`String(error)` when it is not an `Error`). */\n readonly message: string;\n /** Its `IGX-` code when it is an `IgnifxError`, else `null`. */\n readonly code: string | null;\n /** Its `stack`, or `null` when it has none. Additive in 0.3: a host from before it leaves it out. */\n readonly stack?: string | null;\n}\n\n/**\n * What one hot reload did: the engine's `HotReloadReport`, with its errors made JSON.\n *\n * @public\n */\nexport interface HotReloadReport {\n /** Which operation: a prototype swap, a recreate of instances, or a scene rebuild. */\n readonly kind: \"patch\" | \"recreate\" | \"scene\";\n /** The `typeId`s reloaded, in the order applied. */\n readonly typeIds: readonly string[];\n /** How many live component instances were swapped or re-created, or entities rebuilt. */\n readonly instances: number;\n /** How long it took, in milliseconds. */\n readonly durationMs: number;\n /** Everything that threw on the way. */\n readonly errors: readonly HotReloadError[];\n}\n\n/**\n * The parameters of `hotReloaded`.\n *\n * @public\n */\nexport interface HotReloadedParams {\n /** The report `app.hotReload.onApplied` emitted. */\n readonly report: HotReloadReport;\n}\n\n/**\n * The parameters of `assetReloaded`.\n *\n * @remarks\n * The host reloads an asset in place when the dev server reports it changed on disk and the scene\n * view's app has it loaded: a scene or prefab (`\"scene\"`), whose document instances it rebuilds from\n * the new file with their uids, transforms and overrides, and a model, mesh, material, sprite atlas\n * or shader, which the renderers pick up on their next frame. Any other type, such as a texture, is\n * left as it was loaded and sends nothing. The open document's own file is never reloaded.\n *\n * @public\n */\nexport interface AssetReloadedParams {\n /** The asset's address, relative to the asset root. */\n readonly address: string;\n /** Its asset type, as the manifest records it: `\"scene\"` for a scene or a prefab. */\n readonly type: string;\n /**\n * The uids of the document's instance roots rebuilt from the new file, in document order: those\n * that instance it, directly or through another scene. Empty for any other type.\n */\n readonly entities: readonly string[];\n}\n\n/**\n * The parameters of `transformDragging`.\n *\n * @public\n */\nexport interface TransformDraggingParams {\n /** The dragged entity's uid. */\n readonly entity: string;\n /** The gizmo mode of the drag. */\n readonly mode: GizmoDragMode;\n /** Its local transform now, rounded as the engine writes numbers. */\n readonly after: SceneFileTransform;\n}\n\n/**\n * The parameters of `transformDragged`: the shape of a `setTransform` op plus the drag's mode.\n *\n * @public\n */\nexport interface TransformDraggedParams {\n /** The dragged entity's uid. */\n readonly entity: string;\n /** The gizmo mode of the drag, for the command's name. */\n readonly mode: GizmoDragMode;\n /** Its local transform when the drag started. */\n readonly before: SceneFileTransform;\n /** Its local transform at pointer-up. */\n readonly after: SceneFileTransform;\n}\n\n/**\n * The parameters of `hostError`.\n *\n * @public\n */\nexport interface HostErrorParams {\n /** The engine's `IGX-` code, or `null` when the error had none. */\n readonly code: string | null;\n /** An actionable sentence. */\n readonly message: string;\n /** Extra detail as JSON, when there is any. */\n readonly data?: JsonValue;\n}\n\n/**\n * The `data` of a `hostError` the host sends for an error the app reported through `app.onError`:\n * where it was caught. The host's `message` and `code` are the thrown error's.\n *\n * @remarks\n * `source`, `phase` and `entity` are in every 0.3 host; the other fields are additive in 0.3, sent by\n * a host that lists `HostCapability.logRelay`.\n *\n * @public\n */\nexport interface AppErrorData {\n /** Which boundary caught it: the engine's `ErrorReport.source`, such as `\"lifecycle\"`. */\n readonly source: string;\n /** The phase that was running, as the engine's `Phase` value, or `null` outside a phase. */\n readonly phase: number | null;\n /** That phase's name in the engine's `Phase`, such as `\"Update\"`, or `null`. */\n readonly phaseName?: string | null;\n /** The uid of the entity involved, or `null`. */\n readonly entity: string | null;\n /** The name of the entity involved, or `null`. */\n readonly entityName?: string | null;\n /** The `typeId` of the component involved (its class name when it has none), or `null`. */\n readonly component?: string | null;\n /** The thrown error's `stack`, or `null` when it has none. */\n readonly stack?: string | null;\n}\n\n/**\n * A log line's severity: the engine's `LogLevel`.\n *\n * @public\n */\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\n/**\n * An `Error` a log line carried among its extras, made JSON.\n *\n * @public\n */\nexport interface LoggedError {\n /** The error's message. */\n readonly message: string;\n /** Its `IGX-` code when it is an `IgnifxError`, else `null`. */\n readonly code: string | null;\n /** Its `stack`, or `null` when it has none. */\n readonly stack: string | null;\n}\n\n/**\n * The parameters of `log`: the engine's `LogRecord` without its `data`, which is not JSON, but for\n * the first `Error` in it.\n *\n * @public\n */\nexport interface LogParams {\n /** The severity. */\n readonly level: LogLevel;\n /** The logger's dotted scope, or `null` for the root logger. */\n readonly scope: string | null;\n /** The message. */\n readonly message: string;\n /** The logger clock's reading, in milliseconds. */\n readonly timeMs: number;\n /**\n * The first `Error` among the record's extras, such as the one the app's default `onError` handler\n * logs. Additive in 0.3: a host from before it leaves it out.\n */\n readonly error?: LoggedError;\n}\n\n/**\n * A request whose `params` are required.\n *\n * @typeParam M - The method name.\n * @typeParam P - The parameters.\n *\n * @public\n */\nexport interface RpcRequestWithParams<M extends string, P> extends RpcRequest<M, P> {\n /** The method's parameters. */\n readonly params: P;\n}\n\n/**\n * A notification whose `params` are required.\n *\n * @typeParam M - The method name.\n * @typeParam P - The parameters.\n *\n * @public\n */\nexport interface RpcNotificationWithParams<M extends string, P> extends RpcNotification<M, P> {\n /** The notification's parameters. */\n readonly params: P;\n}\n\n/**\n * Editor → scene host: one of the `SceneMethod`s. `closeScene`, `getSchemas` and `describeSettings`\n * take no parameters.\n *\n * @public\n */\nexport type SceneRequest =\n | RpcRequestWithParams<typeof SceneMethod.openScene, OpenSceneParams>\n | RpcRequest<typeof SceneMethod.closeScene, never>\n | RpcRequestWithParams<typeof SceneMethod.applyOps, ApplyOpsParams>\n | RpcRequestWithParams<typeof SceneMethod.readBack, ReadBackParams>\n | RpcRequestWithParams<typeof SceneMethod.select, EntitySelection>\n | RpcRequestWithParams<typeof SceneMethod.setGizmo, SetGizmoParams>\n | RpcRequestWithParams<typeof SceneMethod.frame, FrameParams>\n | RpcRequestWithParams<typeof SceneMethod.pick, PickParams>\n | RpcRequestWithParams<typeof SceneMethod.screenshot, ScreenshotParams>\n | RpcRequest<typeof SceneMethod.getSchemas, never>\n | RpcRequest<typeof SceneMethod.describeSettings, never>\n | RpcRequestWithParams<typeof SceneMethod.setViewMode, SetViewModeParams>;\n\n/**\n * The success answer of the `SceneMethod`s that return nothing: `closeScene`, `setGizmo`, `frame`\n * and `setViewMode`.\n *\n * @public\n */\nexport type NullResponse = RpcSuccessResponse<null>;\n\n/**\n * The success answer to `openScene`.\n *\n * @public\n */\nexport type OpenSceneResponse = RpcSuccessResponse<OpenSceneResult>;\n\n/**\n * The success answer to `applyOps`.\n *\n * @public\n */\nexport type ApplyOpsResponse = RpcSuccessResponse<ApplyOpsResult>;\n\n/**\n * The success answer to `readBack`.\n *\n * @public\n */\nexport type ReadBackResponse = RpcSuccessResponse<ReadBackResult>;\n\n/**\n * The success answer to `select`.\n *\n * @public\n */\nexport type SelectResponse = RpcSuccessResponse<EntitySelection>;\n\n/**\n * The success answer to `pick`.\n *\n * @public\n */\nexport type PickResponse = RpcSuccessResponse<PickResult>;\n\n/**\n * The success answer to `screenshot`.\n *\n * @public\n */\nexport type ScreenshotResponse = RpcSuccessResponse<ScreenshotResult>;\n\n/**\n * The success answer to `getSchemas`.\n *\n * @public\n */\nexport type GetSchemasResponse = RpcSuccessResponse<SchemaSet>;\n\n/**\n * The success answer to `describeSettings`.\n *\n * @public\n */\nexport type DescribeSettingsResponse = RpcSuccessResponse<SettingsSet>;\n\n/**\n * Scene host → editor: one of the `SceneNotification`s.\n *\n * @public\n */\nexport type SceneHostNotification =\n | RpcNotificationWithParams<typeof SceneNotification.sceneOpened, SceneOpenedParams>\n | RpcNotificationWithParams<typeof SceneNotification.schemasChanged, SchemaSet>\n | RpcNotificationWithParams<typeof SceneNotification.hotReloaded, HotReloadedParams>\n | RpcNotificationWithParams<typeof SceneNotification.selectionChanged, EntitySelection>\n | RpcNotificationWithParams<typeof SceneNotification.transformDragging, TransformDraggingParams>\n | RpcNotificationWithParams<typeof SceneNotification.transformDragged, TransformDraggedParams>\n | RpcNotificationWithParams<typeof SceneNotification.hostError, HostErrorParams>\n | RpcNotificationWithParams<typeof SceneNotification.log, LogParams>\n | RpcNotificationWithParams<typeof SceneNotification.assetReloaded, AssetReloadedParams>;\n\n// ---------------------------------------------------------------------------------------------\n// Guards\n// ---------------------------------------------------------------------------------------------\n\n/**\n * Tells whether a value is one of an `as const` object's values.\n *\n * @param names - The object.\n * @param value - The value to test.\n * @returns True when `value` is one of the object's values.\n */\nfunction isOneOf(names: Readonly<Record<string, string>>, value: unknown): boolean {\n return typeof value === \"string\" && Object.values(names).includes(value);\n}\n\n/**\n * Tells whether a value is a count: a non-negative safe integer.\n *\n * @param value - The value to test.\n * @returns True for a non-negative safe integer.\n */\nfunction isCount(value: unknown): value is number {\n return Number.isSafeInteger(value) && Number(value) >= 0;\n}\n\n/**\n * Tells whether a value is a non-negative finite number.\n *\n * @param value - The value to test.\n * @returns True for a finite number at least 0.\n */\nfunction isNonNegative(value: unknown): value is number {\n return isFiniteNumber(value) && value >= 0;\n}\n\n/**\n * Tells whether a value is a list of uids.\n *\n * @param value - The value to test.\n * @returns True for an array of non-empty strings.\n */\nfunction isUidList(value: unknown): value is readonly string[] {\n return isArrayOf(value, isUidString);\n}\n\n/**\n * Tells whether a value is a string or `null`.\n *\n * @param value - The value to test.\n * @returns True for a string or `null`.\n */\nfunction isStringOrNull(value: unknown): value is string | null {\n return value === null || isString(value);\n}\n\n/**\n * Checks one engine issue.\n *\n * @param value - The value to test.\n * @returns True for `{ code: string, message: string }`.\n *\n * @public\n */\nexport function isSceneIssue(value: unknown): value is SceneIssue {\n return isRecord(value) && isString(value[\"code\"]) && isString(value[\"message\"]);\n}\n\n/**\n * Checks the parameters of `openScene`.\n *\n * @param value - The received `params`.\n * @returns True for a structurally valid scene file and a string or `null` address.\n *\n * @public\n */\nexport function isOpenSceneParams(value: unknown): value is OpenSceneParams {\n return isRecord(value) && isSceneFile(value[\"file\"]) && isStringOrNull(value[\"address\"]);\n}\n\n/**\n * Checks the result of `openScene`.\n *\n * @param value - The received `result`.\n * @returns True for a count, a list of issues, and an optional view mode.\n *\n * @public\n */\nexport function isOpenSceneResult(value: unknown): value is OpenSceneResult {\n return (\n isRecord(value) &&\n isCount(value[\"entityCount\"]) &&\n isArrayOf(value[\"warnings\"], isSceneIssue) &&\n optionalField(value, \"viewMode\", (mode) => isOneOf(ViewMode, mode))\n );\n}\n\n/**\n * Checks the `data` of the `invalidParams` error `openScene` answers for a file\n * `validateSceneFile` refuses.\n *\n * @param value - The received `error.data`.\n * @returns True for `{ issues: [{ path, message }] }`.\n *\n * @public\n */\nexport function isInvalidSceneFileData(value: unknown): value is InvalidSceneFileData {\n return (\n isRecord(value) &&\n isArrayOf(\n value[\"issues\"],\n (issue): issue is SceneFileIssue => isRecord(issue) && isString(issue[\"path\"]) && isString(issue[\"message\"]),\n )\n );\n}\n\n/**\n * Checks the parameters of `applyOps`.\n *\n * @param value - The received `params`.\n * @returns True when every op passes {@link isSceneOp} and the command has a name and an id.\n *\n * @public\n */\nexport function isApplyOpsParams(value: unknown): value is ApplyOpsParams {\n return (\n isRecord(value) &&\n isArrayOf(value[\"ops\"], isSceneOp) &&\n isString(value[\"commandName\"]) &&\n isUidString(value[\"commandId\"])\n );\n}\n\n/**\n * Checks one failure in the result of `applyOps`.\n *\n * @param value - The value to test.\n * @returns True for `{ index, code, message, diagnostic? }` with a known code.\n */\nfunction isApplyOpFailure(value: unknown): value is ApplyOpFailure {\n return (\n isRecord(value) &&\n isCount(value[\"index\"]) &&\n isOneOf(ApplyOpFailureCode, value[\"code\"]) &&\n isString(value[\"message\"]) &&\n optionalField(value, \"diagnostic\", isString)\n );\n}\n\n/**\n * Checks the result of `applyOps`.\n *\n * @param value - The received `result`.\n * @returns True for a count of applied ops and a list of failures with known codes.\n *\n * @public\n */\nexport function isApplyOpsResult(value: unknown): value is ApplyOpsResult {\n return isRecord(value) && isCount(value[\"applied\"]) && isArrayOf(value[\"failures\"], isApplyOpFailure);\n}\n\n/**\n * Checks the parameters of `readBack`.\n *\n * @param value - The received `params`.\n * @returns True for an object with an optional list of uids.\n *\n * @public\n */\nexport function isReadBackParams(value: unknown): value is ReadBackParams {\n return isRecord(value) && optionalField(value, \"entities\", isUidList);\n}\n\n/**\n * Checks the result of `readBack`.\n *\n * @param value - The received `result`.\n * @returns True for entity records, missing uids, settings or `null`, and issues.\n *\n * @public\n */\nexport function isReadBackResult(value: unknown): value is ReadBackResult {\n const settings = isRecord(value) ? value[\"settings\"] : undefined;\n return (\n isRecord(value) &&\n isArrayOf(value[\"entities\"], isSceneFileEntity) &&\n isUidList(value[\"missing\"]) &&\n (settings === null || isJsonObject(settings)) &&\n isArrayOf(value[\"issues\"], isSceneIssue)\n );\n}\n\n/**\n * Checks a selection: the parameters and result of `select` and the parameters of\n * `selectionChanged`.\n *\n * @param value - The received `params` or `result`.\n * @returns True for `{ entities: uid[] }`.\n *\n * @public\n */\nexport function isEntitySelection(value: unknown): value is EntitySelection {\n return isRecord(value) && isUidList(value[\"entities\"]);\n}\n\n/**\n * Checks the parameters of `setGizmo`.\n *\n * @param value - The received `params`.\n * @returns True for a known mode and space and a snap of three non-negative numbers, or `null`.\n *\n * @public\n */\nexport function isSetGizmoParams(value: unknown): value is SetGizmoParams {\n if (!isRecord(value)) {\n return false;\n }\n const snap = value[\"snap\"];\n return (\n isOneOf(GizmoMode, value[\"mode\"]) &&\n isOneOf(GizmoSpace, value[\"space\"]) &&\n (snap === null ||\n (isRecord(snap) &&\n isNonNegative(snap[\"translate\"]) &&\n isNonNegative(snap[\"rotate\"]) &&\n isNonNegative(snap[\"scale\"])))\n );\n}\n\n/**\n * Checks the parameters of `frame`.\n *\n * @param value - The received `params`.\n * @returns True for a list of uids or `\"all\"`.\n *\n * @public\n */\nexport function isFrameParams(value: unknown): value is FrameParams {\n return isRecord(value) && (value[\"entities\"] === \"all\" || isUidList(value[\"entities\"]));\n}\n\n/**\n * Checks the parameters of `pick`.\n *\n * @param value - The received `params`.\n * @returns True for finite `x` and `y` and a known unit.\n *\n * @public\n */\nexport function isPickParams(value: unknown): value is PickParams {\n return (\n isRecord(value) && isFiniteNumber(value[\"x\"]) && isFiniteNumber(value[\"y\"]) && isOneOf(PickUnit, value[\"unit\"])\n );\n}\n\n/**\n * Checks a pick ray.\n *\n * @param value - The value to test.\n * @returns True for `{ origin, direction }`, each three finite numbers.\n */\nfunction isPickRay(value: unknown): value is PickRay {\n return isRecord(value) && isNumberTuple(value[\"origin\"], 3) && isNumberTuple(value[\"direction\"], 3);\n}\n\n/**\n * Checks the result of `pick`.\n *\n * @param value - The received `result`.\n * @returns True for a uid or `null`, a point or `null`, a non-negative distance or `null`, an\n * optional ray and an optional plane point.\n *\n * @public\n */\nexport function isPickResult(value: unknown): value is PickResult {\n if (!isRecord(value)) {\n return false;\n }\n const { entity, point, distance } = value;\n return (\n (entity === null || isUidString(entity)) &&\n (point === null || isNumberTuple(point, 3)) &&\n (distance === null || isNonNegative(distance)) &&\n optionalField(value, \"ray\", isPickRay) &&\n optionalField(value, \"plane\", (plane) => isNumberTuple(plane, 3))\n );\n}\n\n/**\n * Tells whether a value is a screenshot side: a whole number from 1 to {@link SCREENSHOT_MAX_SIZE}.\n *\n * @param value - The value to test.\n * @returns True for an integer in range.\n */\nfunction isScreenshotSide(value: unknown): boolean {\n return Number.isSafeInteger(value) && Number(value) >= 1 && Number(value) <= SCREENSHOT_MAX_SIZE;\n}\n\n/**\n * Checks the parameters of `screenshot`.\n *\n * @param value - The received `params`.\n * @returns True for a known format, sizes in range when given, and a quality from 0 to 1 when given.\n *\n * @public\n */\nexport function isScreenshotParams(value: unknown): value is ScreenshotParams {\n return (\n isRecord(value) &&\n isOneOf(ScreenshotFormat, value[\"format\"]) &&\n optionalField(value, \"width\", isScreenshotSide) &&\n optionalField(value, \"height\", isScreenshotSide) &&\n optionalField(value, \"quality\", (quality) => isNonNegative(quality) && quality <= 1)\n );\n}\n\n/**\n * Checks the result of `screenshot`.\n *\n * @param value - The received `result`.\n * @returns True for a PNG or JPEG data URL and sizes in range.\n *\n * @public\n */\nexport function isScreenshotResult(value: unknown): value is ScreenshotResult {\n return (\n isRecord(value) &&\n isString(value[\"dataUrl\"]) &&\n /^data:image\\/(?:png|jpeg);base64,/u.test(value[\"dataUrl\"]) &&\n isScreenshotSide(value[\"width\"]) &&\n isScreenshotSide(value[\"height\"])\n );\n}\n\n/**\n * Checks one field description.\n *\n * @param value - The value to test.\n * @returns True for `{ kind, default?, description?, step?, hidden?, readonly?, group?, assetType?,\n * componentType? }`, ignoring members it does not declare.\n */\nfunction isSchemaFieldDescription(value: unknown): value is SchemaFieldDescription {\n return (\n isRecord(value) &&\n isString(value[\"kind\"]) &&\n optionalField(value, \"default\", (fallback) => isJsonValue(fallback)) &&\n optionalField(value, \"description\", isString) &&\n optionalField(value, \"step\", (step) => isFiniteNumber(step) && step > 0) &&\n optionalField(value, \"hidden\", isBoolean) &&\n optionalField(value, \"readonly\", isBoolean) &&\n optionalField(value, \"group\", isString) &&\n optionalField(value, \"assetType\", isString) &&\n optionalField(value, \"componentType\", (type) => type === null || isString(type))\n );\n}\n\n/**\n * Checks one schema description.\n *\n * @param value - The value to test.\n * @returns True for `{ title, format, description?, fields, allowMultiple?, package?, builtIn?,\n * propsSchema? }`, ignoring members it does not declare.\n */\nfunction isSchemaDescription(value: unknown): value is SchemaDescription {\n return (\n isRecord(value) &&\n isString(value[\"title\"]) &&\n isString(value[\"format\"]) &&\n optionalField(value, \"description\", isString) &&\n isRecord(value[\"fields\"]) &&\n Object.values(value[\"fields\"]).every((field) => isSchemaFieldDescription(field)) &&\n optionalField(value, \"allowMultiple\", isBoolean) &&\n optionalField(value, \"package\", isString) &&\n optionalField(value, \"builtIn\", isBoolean) &&\n optionalField(value, \"propsSchema\", isJsonObject)\n );\n}\n\n/**\n * Checks the result of `getSchemas` and the parameters of `schemasChanged`.\n *\n * @param value - The received `result` or `params`.\n * @returns True for `{ schemas }` whose every entry is a schema description.\n *\n * @public\n */\nexport function isSchemaSet(value: unknown): value is SchemaSet {\n const schemas = isRecord(value) ? value[\"schemas\"] : undefined;\n return isRecord(schemas) && Object.values(schemas).every((schema) => isSchemaDescription(schema));\n}\n\n/**\n * Checks the result of `describeSettings`.\n *\n * @param value - The received `result`.\n * @returns True for `{ sections, values }`: every section a schema description, every value an\n * object.\n *\n * @public\n */\nexport function isSettingsSet(value: unknown): value is SettingsSet {\n if (!isRecord(value)) {\n return false;\n }\n const { sections, values } = value;\n return (\n isRecord(sections) &&\n Object.values(sections).every((section) => isSchemaDescription(section)) &&\n isRecord(values) &&\n Object.values(values).every((section) => isJsonObject(section))\n );\n}\n\n/**\n * Checks the parameters of `setViewMode`.\n *\n * @param value - The received `params`.\n * @returns True for `{ mode: \"3d\" | \"2d\" }`.\n *\n * @public\n */\nexport function isSetViewModeParams(value: unknown): value is SetViewModeParams {\n return isRecord(value) && isOneOf(ViewMode, value[\"mode\"]);\n}\n\n/**\n * Checks the parameters of `sceneOpened`.\n *\n * @param value - The received `params`.\n * @returns True for an address or `null`, a name, a count, issues, and an optional view mode.\n *\n * @public\n */\nexport function isSceneOpenedParams(value: unknown): value is SceneOpenedParams {\n return (\n isRecord(value) &&\n isStringOrNull(value[\"address\"]) &&\n isString(value[\"name\"]) &&\n isOpenSceneResult({ entityCount: value[\"entityCount\"], warnings: value[\"warnings\"], viewMode: value[\"viewMode\"] })\n );\n}\n\n/** The `kind`s of a hot-reload report. */\nconst HOT_RELOAD_KINDS: Readonly<Record<string, string>> = { patch: \"patch\", recreate: \"recreate\", scene: \"scene\" };\n\n/**\n * Checks the parameters of `hotReloaded`.\n *\n * @param value - The received `params`.\n * @returns True for `{ report }` with a known kind, type ids, counts and JSON errors.\n *\n * @public\n */\nexport function isHotReloadedParams(value: unknown): value is HotReloadedParams {\n const report = isRecord(value) ? value[\"report\"] : undefined;\n return (\n isRecord(report) &&\n isOneOf(HOT_RELOAD_KINDS, report[\"kind\"]) &&\n isArrayOf(report[\"typeIds\"], isString) &&\n isCount(report[\"instances\"]) &&\n isNonNegative(report[\"durationMs\"]) &&\n isArrayOf(\n report[\"errors\"],\n (error): error is HotReloadError =>\n isRecord(error) &&\n isString(error[\"message\"]) &&\n isStringOrNull(error[\"code\"]) &&\n optionalField(error, \"stack\", isStringOrNull),\n )\n );\n}\n\n/**\n * Checks the parameters of `assetReloaded`.\n *\n * @param value - The received `params`.\n * @returns True for `{ address, type, entities }` with a non-empty address and type.\n *\n * @public\n */\nexport function isAssetReloadedParams(value: unknown): value is AssetReloadedParams {\n return (\n isRecord(value) &&\n isString(value[\"address\"]) &&\n value[\"address\"] !== \"\" &&\n isString(value[\"type\"]) &&\n value[\"type\"] !== \"\" &&\n isUidList(value[\"entities\"])\n );\n}\n\n/** The modes a drag can happen in. */\nconst DRAG_MODES: Readonly<Record<string, string>> = {\n translate: GizmoMode.translate,\n rotate: GizmoMode.rotate,\n scale: GizmoMode.scale,\n};\n\n/**\n * Checks the parameters of `transformDragging`.\n *\n * @param value - The received `params`.\n * @returns True for an entity, a drag mode and a transform.\n *\n * @public\n */\nexport function isTransformDraggingParams(value: unknown): value is TransformDraggingParams {\n return (\n isRecord(value) &&\n isUidString(value[\"entity\"]) &&\n isOneOf(DRAG_MODES, value[\"mode\"]) &&\n isSceneFileTransform(value[\"after\"])\n );\n}\n\n/**\n * Checks the parameters of `transformDragged`.\n *\n * @param value - The received `params`.\n * @returns True for an entity, a drag mode and two transforms.\n *\n * @public\n */\nexport function isTransformDraggedParams(value: unknown): value is TransformDraggedParams {\n return isTransformDraggingParams(value) && \"before\" in value && isSceneFileTransform(value.before);\n}\n\n/**\n * Checks the parameters of `hostError`.\n *\n * @param value - The received `params`.\n * @returns True for a code or `null`, a message and optional JSON data.\n *\n * @public\n */\nexport function isHostErrorParams(value: unknown): value is HostErrorParams {\n return (\n isRecord(value) &&\n isStringOrNull(value[\"code\"]) &&\n isString(value[\"message\"]) &&\n optionalField(value, \"data\", (data) => isJsonValue(data))\n );\n}\n\n/**\n * Checks the `data` of a `hostError` for an error the app reported.\n *\n * @param value - The received `data`.\n * @returns True for a boundary name, a phase or `null`, an entity uid or `null`, and, when present,\n * a phase name, an entity name, a component and a stack, each a string or `null`.\n *\n * @public\n */\nexport function isAppErrorData(value: unknown): value is AppErrorData {\n return (\n isRecord(value) &&\n isString(value[\"source\"]) &&\n (value[\"phase\"] === null || isCount(value[\"phase\"])) &&\n (value[\"entity\"] === null || isUidString(value[\"entity\"])) &&\n optionalField(value, \"phaseName\", isStringOrNull) &&\n optionalField(value, \"entityName\", isStringOrNull) &&\n optionalField(value, \"component\", isStringOrNull) &&\n optionalField(value, \"stack\", isStringOrNull)\n );\n}\n\n/** The severities of a log line. */\nconst LOG_LEVELS: Readonly<Record<string, string>> = { debug: \"debug\", info: \"info\", warn: \"warn\", error: \"error\" };\n\n/**\n * Checks the parameters of `log`.\n *\n * @param value - The received `params`.\n * @returns True for a known level, a scope or `null`, a message and a finite time.\n *\n * @public\n */\nexport function isLogParams(value: unknown): value is LogParams {\n return (\n isRecord(value) &&\n isOneOf(LOG_LEVELS, value[\"level\"]) &&\n isStringOrNull(value[\"scope\"]) &&\n isString(value[\"message\"]) &&\n isFiniteNumber(value[\"timeMs\"]) &&\n optionalField(\n value,\n \"error\",\n (error) =>\n isRecord(error) &&\n isString(error[\"message\"]) &&\n isStringOrNull(error[\"code\"]) &&\n isStringOrNull(error[\"stack\"]),\n )\n );\n}\n","// A copy of `packages/editor-protocol/src/version.ts` from `astrum-forge/ignifx-editor` (protocol 0.3).\n// Below this comment it is byte-identical to that file, but for the link rule in `./index.ts`.\n/**\n * The protocol's own version, separate from the editor's and the engine's package versions.\n */\n\n/**\n * A protocol version. `major` changes when a message changes incompatibly; `minor` when messages\n * or fields are added in a way an older peer can ignore. Before 1.0 the minor plays the role of the\n * major (ADR-E008), so every 0.x minor is its own incompatible line.\n *\n * @public\n */\nexport interface ProtocolVersion {\n /** Incremented for incompatible changes. Peers must agree on it. */\n readonly major: number;\n /** Incremented for additions. From 1.0 peers may differ in it; before 1.0 they must agree on it too. */\n readonly minor: number;\n}\n\n/**\n * The protocol version this package describes. The editor sends it in `hello` and the host in\n * `ready`.\n *\n * @public\n */\nexport const PROTOCOL_VERSION: ProtocolVersion = { major: 0, minor: 3 };\n\n/**\n * Tells whether two peers can talk.\n *\n * @remarks\n * The rule is ADR-E008's: the protocol follows SemVer, and until 1.0 its minor plays the role of the\n * major, as the engine's minors do. So from 1.0 two peers are compatible when their majors are\n * equal and the minors are free to differ; before 1.0 the major and the minor must both be equal.\n * The check is symmetric. Which versions the editor accepts beyond it (ADR-E008 has the editor\n * support the current protocol line and the previous one) is the editor's decision, not this\n * function's.\n *\n * @example\n * ```ts\n * protocolVersionIsCompatible({ major: 0, minor: 3 }, { major: 0, minor: 2 }); // false\n * protocolVersionIsCompatible({ major: 1, minor: 0 }, { major: 1, minor: 4 }); // true\n * ```\n *\n * @param a - One peer's protocol version.\n * @param b - The other peer's protocol version.\n * @returns `true` when the versions are on the same compatible line.\n *\n * @public\n */\nexport function protocolVersionIsCompatible(a: ProtocolVersion, b: ProtocolVersion): boolean {\n if (a.major !== b.major) {\n return false;\n }\n return a.major !== 0 || a.minor === b.minor;\n}\n","/**\n * The host half of an editor channel: accepts the `MessagePort` the editor posts to the view's\n * window, runs the `hello`/`ready` handshake, answers requests, and sends heartbeats. The scene\n * host and the play controls each open one.\n */\n\nimport { IgnifxError } from \"@ignifx/core\";\nimport { EditorHostErrorCode, isEditorOrigin } from \"./error-codes.js\";\nimport {\n DEFAULT_HEARTBEAT_INTERVAL_MS,\n HandshakeMethod,\n HostNotification,\n isEditorConnectMessage,\n isRpcMessage,\n JSON_RPC_VERSION,\n PROTOCOL_VERSION,\n protocolVersionIsCompatible,\n RpcErrorCode,\n} from \"./protocol/index.js\";\nimport { isRecord } from \"./protocol/rpc.js\";\nimport type { HelloParams, ReadyResult, RpcErrorResponse, RpcId, RpcSuccessResponse } from \"./protocol/index.js\";\n\n/**\n * Where a host listens for the editor's connect message: the view's `window` in a browser, or any\n * `EventTarget` that dispatches `MessageEvent`s, which is how a headless test stands in for one.\n * Events that are not `MessageEvent`s are ignored.\n *\n * @beta\n */\nexport interface EditorMessageTarget {\n /**\n * Subscribes to window messages.\n *\n * @param type - Always `\"message\"`.\n * @param listener - Receives each message.\n */\n addEventListener(type: \"message\", listener: (event: Event) => void): void;\n /**\n * Unsubscribes a listener added with `addEventListener`.\n *\n * @param type - Always `\"message\"`.\n * @param listener - The listener to remove.\n */\n removeEventListener(type: \"message\", listener: (event: Event) => void): void;\n}\n\n/** A request handler. It may be asynchronous; whatever it throws becomes an `internalError` reply. */\nexport type RequestHandler = (params: unknown) => unknown;\n\n/**\n * A handler's answer that has work to do once the answer is on the port, such as a notification\n * the protocol orders after it (`sceneOpened` after the answer to `openScene`).\n */\nexport class Reply {\n /** The method's result. */\n readonly result: unknown;\n\n /** Runs right after the answer has been sent on the port that asked. */\n readonly after: () => void;\n\n /**\n * Creates the reply.\n *\n * @param result - The method's result.\n * @param after - What to run once the answer is sent.\n */\n constructor(result: unknown, after: () => void) {\n this.result = result;\n this.after = after;\n }\n}\n\n/** A handler's way of answering with a protocol error of its choice rather than `internalError`. */\nexport class RpcFailure extends Error {\n /** The JSON-RPC error code. */\n readonly code: RpcErrorCode;\n\n /** The error's `data`, when it has any. */\n readonly data: unknown;\n\n /**\n * Creates the failure.\n *\n * @param code - The error code.\n * @param message - What went wrong.\n * @param data - Extra detail, as JSON.\n */\n constructor(code: RpcErrorCode, message: string, data?: unknown) {\n super(message);\n this.name = \"RpcFailure\";\n this.code = code;\n this.data = data;\n }\n}\n\n/** A handler's way of refusing its parameters with `invalidParams` rather than `internalError`. */\nexport class InvalidParamsError extends RpcFailure {\n /**\n * Creates the refusal.\n *\n * @param message - What is wrong with the parameters.\n * @param data - Extra detail, as JSON.\n */\n constructor(message: string, data?: unknown) {\n super(RpcErrorCode.invalidParams, message, data);\n this.name = \"InvalidParamsError\";\n }\n}\n\n/** What {@link openChannel} needs. */\nexport interface ChannelOptions {\n /** Where the connect message arrives. */\n readonly target: EditorMessageTarget;\n /** The only origin a port is accepted from. */\n readonly editorOrigin: string;\n /** The `ready` result, sent in answer to a compatible `hello`. */\n readonly ready: ReadyResult;\n /** Methods answered after the handshake, by name. */\n readonly methods: ReadonlyMap<string, RequestHandler>;\n /** Milliseconds between heartbeats. */\n readonly heartbeatIntervalMs: number;\n /** Called each time a port's `hello` has been answered with `ready`, after the answer is sent. */\n readonly onReady?: () => void;\n /**\n * A port that arrived before the channel opened (see {@link connectPortOf}), served at once as\n * though it had just been posted. Its queued messages are read only from then on.\n */\n readonly port?: MessagePort | null;\n}\n\n/** An open channel. */\nexport interface Channel {\n /** Whether a port has been accepted and not replaced or closed. */\n readonly isConnected: boolean;\n /** Whether the current port has completed the handshake. */\n readonly isReady: boolean;\n /**\n * Sends a notification on the current port, once it has completed the handshake; otherwise drops\n * it, since the editor re-sends what a new port needs.\n *\n * @param method - The notification's name.\n * @param params - Its parameters, if any.\n */\n notify(method: string, params?: unknown): void;\n /** Removes the window listener, stops the heartbeat, and closes the port. Idempotent. */\n dispose(): void;\n}\n\n/** A request's answer, and what to run once it is on the port. */\ninterface Answer {\n /** The response envelope. */\n readonly response: RpcSuccessResponse | RpcErrorResponse;\n /** Runs right after the response is sent, or `null`. */\n readonly after: (() => void) | null;\n}\n\n/**\n * Checks the parameters of `hello`.\n *\n * @param value - The received `params`.\n * @returns True when they carry an editor version and an integer protocol version.\n */\nfunction isHelloParams(value: unknown): value is HelloParams {\n if (!isRecord(value) || typeof value[\"editorVersion\"] !== \"string\") {\n return false;\n }\n const protocol = value[\"protocol\"];\n return isRecord(protocol) && Number.isInteger(protocol[\"major\"]) && Number.isInteger(protocol[\"minor\"]);\n}\n\n/**\n * Builds a success response.\n *\n * @param id - The request id.\n * @param result - The result.\n * @returns The envelope.\n */\nfunction success(id: RpcId, result: unknown): RpcSuccessResponse {\n return { jsonrpc: JSON_RPC_VERSION, id, result };\n}\n\n/**\n * Builds an error response.\n *\n * @param id - The request id, or `null` when it could not be read.\n * @param code - The error code.\n * @param message - A short description.\n * @param data - Extra detail, if any.\n * @returns The envelope.\n */\nfunction failure(id: RpcId | null, code: RpcErrorCode, message: string, data?: unknown): RpcErrorResponse {\n const error = data === undefined ? { code, message } : { code, message, data };\n return { jsonrpc: JSON_RPC_VERSION, id, error };\n}\n\n/**\n * Posts one message on a port.\n *\n * @param port - The port the editor handed over.\n * @param message - The envelope to send.\n */\nfunction send(port: MessagePort, message: unknown): void {\n // A `MessagePort` has exactly one peer, so it takes no target origin; the rule is for windows.\n // oxlint-disable-next-line unicorn/require-post-message-target-origin -- see above.\n port.postMessage(message);\n}\n\n/**\n * Checks the options every host shares and throws the documented error for a bad one.\n *\n * @param editorOrigin - The origin the editor is served from.\n * @param heartbeatIntervalMs - The heartbeat period, if given.\n * @returns The heartbeat period with its default applied.\n * @throws IgnifxError `IGX-1801` for an origin that is not `scheme://host[:port]`, `IGX-1803` for a\n * period that is not a positive finite number.\n */\nexport function checkChannelOptions(editorOrigin: string, heartbeatIntervalMs: number | undefined): number {\n if (!isEditorOrigin(editorOrigin)) {\n throw new IgnifxError(\n EditorHostErrorCode.invalidEditorOrigin,\n `\"${editorOrigin}\" is not an origin the editor can be served from.`,\n { hint: 'Pass the editor\\'s origin exactly as the browser reports it, for example \"ignifx://app\".' },\n );\n }\n const interval = heartbeatIntervalMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS;\n if (!Number.isFinite(interval) || interval <= 0) {\n throw new IgnifxError(\n EditorHostErrorCode.invalidOption,\n `heartbeatIntervalMs must be a positive number of milliseconds; got ${String(interval)}.`,\n { context: { option: \"heartbeatIntervalMs\" } },\n );\n }\n return interval;\n}\n\n/**\n * Picks the window a host listens on.\n *\n * @param target - The target the caller passed, if any.\n * @returns That target, or the page's `window`.\n * @throws IgnifxError `IGX-1802` when there is neither, as in Node.\n */\nexport function resolveMessageTarget(target: EditorMessageTarget | undefined): EditorMessageTarget {\n if (target !== undefined) {\n return target;\n }\n if (typeof window === \"undefined\") {\n throw new IgnifxError(\n EditorHostErrorCode.noMessageTarget,\n \"The editor host needs a window to receive the editor's port, and this environment has none.\",\n { hint: \"Pass messageTarget, for example an EventTarget a test dispatches MessageEvents on.\" },\n );\n }\n return window;\n}\n\n/**\n * Reads the port out of a window message, if it is the editor's connect message.\n *\n * @remarks\n * Anyone can post to a window; only the editor's own origin may hand a host a port. The message\n * must come from exactly `editorOrigin`, carry the connect message's data, and transfer exactly\n * one port.\n *\n * @param event - A window message.\n * @param editorOrigin - The only origin a port is accepted from.\n * @returns The port, or `null` when the message is anything else.\n */\nexport function connectPortOf(event: Event, editorOrigin: string): MessagePort | null {\n if (!(event instanceof MessageEvent) || event.origin !== editorOrigin) {\n return null;\n }\n const port = event.ports[0];\n if (!isEditorConnectMessage(event.data) || event.ports.length !== 1 || port === undefined) {\n return null;\n }\n return port;\n}\n\n/**\n * Opens a channel: listens for the editor's connect message and serves whichever port arrived last.\n *\n * @remarks\n * Call it before the host's first `await`. The editor posts the port on the view's `load` event,\n * which can fire while `createApp` is still running, and a message nobody listens for is lost.\n *\n * @param options - The target, origin, handshake answer, methods, and heartbeat period.\n * @returns The channel; dispose it with the host.\n */\nexport function openChannel(options: ChannelOptions): Channel {\n const { target, editorOrigin, ready, methods, heartbeatIntervalMs, onReady } = options;\n let port: MessagePort | null = null;\n let portListener: ((event: MessageEvent) => void) | null = null;\n let isReady = false;\n let heartbeat: ReturnType<typeof setInterval> | null = null;\n let isDisposed = false;\n // Requests are answered one at a time, in arrival order (protocol 0.3): an `applyOps` sent right\n // after an `openScene` must see the scene that request opens.\n let queue: Promise<void> = Promise.resolve();\n\n const stopHeartbeat = (): void => {\n if (heartbeat !== null) {\n clearInterval(heartbeat);\n heartbeat = null;\n }\n };\n\n const closePort = (): void => {\n stopHeartbeat();\n isReady = false;\n if (port !== null && portListener !== null) {\n port.removeEventListener(\"message\", portListener);\n port.close();\n }\n port = null;\n portListener = null;\n };\n\n const handshake = (id: RpcId, params: unknown): RpcSuccessResponse | RpcErrorResponse => {\n if (!isHelloParams(params)) {\n return failure(id, RpcErrorCode.invalidParams, \"hello needs { editorVersion, protocol: { major, minor } }.\");\n }\n if (!protocolVersionIsCompatible(params.protocol, PROTOCOL_VERSION)) {\n return failure(\n id,\n RpcErrorCode.incompatibleProtocol,\n `The editor speaks protocol ${String(params.protocol.major)}.${String(params.protocol.minor)} and this ` +\n `host speaks ${String(PROTOCOL_VERSION.major)}.${String(PROTOCOL_VERSION.minor)}. Update the editor, ` +\n \"or the project's @ignifx packages, so the protocol versions match.\",\n { host: PROTOCOL_VERSION, engineVersion: ready.engineVersion },\n );\n }\n isReady = true;\n return success(id, ready);\n };\n\n const answer = async (id: RpcId, method: string, params: unknown): Promise<Answer> => {\n if (method === HandshakeMethod.hello) {\n return { response: handshake(id, params), after: null };\n }\n if (method === HandshakeMethod.ping) {\n return { response: success(id, \"pong\"), after: null };\n }\n const handler = methods.get(method);\n if (handler === undefined) {\n return {\n response: failure(id, RpcErrorCode.methodNotFound, `This host has no method \"${method}\".`),\n after: null,\n };\n }\n if (!isReady) {\n return { response: failure(id, RpcErrorCode.notReady, `Send hello before \"${method}\".`), after: null };\n }\n try {\n const value: unknown = await handler(params);\n return value instanceof Reply\n ? { response: success(id, value.result), after: value.after }\n : { response: success(id, value), after: null };\n } catch (error) {\n if (error instanceof RpcFailure) {\n return { response: failure(id, error.code, error.message, error.data), after: null };\n }\n const message = error instanceof Error ? error.message : String(error);\n const code = error instanceof IgnifxError ? error.code : null;\n return { response: failure(id, RpcErrorCode.internalError, message, { code }), after: null };\n }\n };\n\n const startHeartbeat = (current: MessagePort): void => {\n if (heartbeat !== null) {\n return;\n }\n const notification = { jsonrpc: JSON_RPC_VERSION, method: HostNotification.heartbeat };\n heartbeat = setInterval(() => {\n send(current, notification);\n }, heartbeatIntervalMs);\n };\n\n const onPortMessage = async (current: MessagePort, data: unknown): Promise<void> => {\n if (!isRpcMessage(data)) {\n send(current, failure(null, RpcErrorCode.invalidRequest, \"Not a JSON-RPC 2.0 message.\"));\n return;\n }\n // Responses and notifications from the editor need no answer, and none is defined yet.\n if (!(\"method\" in data) || !(\"id\" in data)) {\n return;\n }\n const { id, method, params } = data;\n const reply = async (): Promise<void> => {\n const wasReady = isReady;\n const { response, after } = await answer(id, method, params);\n // A reload or a reconnect may have replaced the port while an asynchronous method ran.\n if (current !== port) {\n return;\n }\n send(current, response);\n after?.();\n if (isReady) {\n startHeartbeat(current);\n if (!wasReady && method === HandshakeMethod.hello) {\n onReady?.();\n }\n }\n };\n // `ping` jumps the queue, so a long `openScene` does not look like a hung view.\n if (method === HandshakeMethod.ping) {\n await reply();\n return;\n }\n const next = queue.then(reply);\n // `reply` turns every failure into an answer; the guard keeps one bug from stalling the queue.\n queue = next.catch(() => undefined);\n await next;\n };\n\n const accept = (next: MessagePort): void => {\n closePort();\n const listener = (event: MessageEvent): void => {\n // Detached on purpose: replies go out on the port, and `answer` turns every failure into one.\n void onPortMessage(next, event.data);\n };\n port = next;\n portListener = listener;\n next.addEventListener(\"message\", listener);\n next.start();\n };\n\n const onWindowMessage = (event: Event): void => {\n const next = connectPortOf(event, editorOrigin);\n if (next !== null) {\n accept(next);\n }\n };\n\n target.addEventListener(\"message\", onWindowMessage);\n if (options.port !== undefined && options.port !== null) {\n accept(options.port);\n }\n\n return {\n get isConnected(): boolean {\n return port !== null;\n },\n get isReady(): boolean {\n return port !== null && isReady;\n },\n notify(method: string, params?: unknown): void {\n if (port !== null && isReady) {\n send(\n port,\n params === undefined ? { jsonrpc: JSON_RPC_VERSION, method } : { jsonrpc: JSON_RPC_VERSION, method, params },\n );\n }\n },\n dispose(): void {\n if (isDisposed) {\n return;\n }\n isDisposed = true;\n target.removeEventListener(\"message\", onWindowMessage);\n closePort();\n },\n };\n}\n","/**\n * The app's reports as the editor's Console reads them: log lines, `app.onError` reports and hot\n * reloads, made JSON. The scene view and the play view relay the same shapes.\n */\n\nimport { isIgnifxError, Phase } from \"@ignifx/core\";\nimport type { AppErrorData, HostErrorParams, HotReloadedParams, LoggedError, LogParams } from \"./protocol/index.js\";\nimport type { App, Component, ErrorReport, HotReloadReport, LogRecord } from \"@ignifx/core\";\n\n/**\n * Names one of the engine's phases.\n *\n * @param phase - The phase's value.\n * @returns Its name in `Phase`, such as `\"Update\"`, or `null` for a value `Phase` does not have.\n */\nfunction phaseName(phase: number): string | null {\n return Object.entries(Phase).find(([, value]) => value === phase)?.[0] ?? null;\n}\n\n/**\n * Reads a thrown value's message.\n *\n * @param error - Whatever was thrown.\n * @returns Its message, or the value as a string when it is not an `Error`.\n */\nexport function messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/**\n * Reads a thrown value's stack.\n *\n * @param error - Whatever was thrown.\n * @returns Its `stack` when it is an `Error` with one, else `null`.\n */\nfunction stackOf(error: unknown): string | null {\n return error instanceof Error && typeof error.stack === \"string\" && error.stack !== \"\" ? error.stack : null;\n}\n\n/**\n * Reads a thrown value's `IGX-` code.\n *\n * @param error - Whatever was thrown.\n * @returns The code of an `IgnifxError`, else `null`.\n */\nfunction codeOf(error: unknown): string | null {\n return isIgnifxError(error) ? error.code : null;\n}\n\n/**\n * Names a component for the editor: its `typeId`, else its class name.\n *\n * @param component - The component.\n * @returns The name.\n */\nfunction componentName(component: Component): string {\n const typeId: unknown = Reflect.get(component.constructor, \"typeId\");\n return typeof typeId === \"string\" && typeId !== \"\" ? typeId : component.constructor.name;\n}\n\n/**\n * Builds the parameters of `log` from one record.\n *\n * @param record - The record the app's logger wrote.\n * @returns The level, scope, message and time, and the first `Error` among the extras.\n */\nexport function logParamsOf(record: LogRecord): LogParams {\n const params: LogParams = {\n level: record.level,\n scope: record.scope,\n message: record.message,\n timeMs: record.timeMs,\n };\n const error = record.data.find((value): value is Error => value instanceof Error);\n if (error === undefined) {\n return params;\n }\n const logged: LoggedError = { message: error.message, code: codeOf(error), stack: stackOf(error) };\n return { ...params, error: logged };\n}\n\n/**\n * Builds the parameters of `hostError` from one `app.onError` report.\n *\n * @param report - The report.\n * @returns The thrown error's code and message, and where it was caught.\n */\nexport function hostErrorParamsOf(report: ErrorReport): HostErrorParams {\n const data: AppErrorData = {\n source: report.source,\n phase: report.phase,\n phaseName: report.phase === null ? null : phaseName(report.phase),\n entity: report.entity?.uid ?? null,\n entityName: report.entity?.name ?? null,\n component: report.component === null ? null : componentName(report.component),\n stack: stackOf(report.error),\n };\n return { code: codeOf(report.error), message: messageOf(report.error), data: { ...data } };\n}\n\n/**\n * Builds the parameters of `hotReloaded` from one report.\n *\n * @param report - What `app.hotReload` did.\n * @returns The report, with its errors made JSON.\n */\nexport function hotReloadedParamsOf(report: HotReloadReport): HotReloadedParams {\n return {\n report: {\n kind: report.kind,\n typeIds: report.typeIds,\n instances: report.instances,\n durationMs: report.durationMs,\n errors: report.errors.map((error) => ({ message: messageOf(error), code: codeOf(error), stack: stackOf(error) })),\n },\n };\n}\n\n/** Where {@link relayAppReports} sends each report. */\nexport interface AppReportSink {\n /** Called with each log line. */\n readonly log: (params: LogParams) => void;\n /** Called with each `app.onError` report. */\n readonly error: (params: HostErrorParams) => void;\n /** Called with each hot reload. */\n readonly hotReloaded: (report: HotReloadReport) => void;\n}\n\n/**\n * Follows an app's log lines, error reports and hot reloads.\n *\n * @param app - The app.\n * @param sink - Where each one goes.\n * @returns A function that stops following.\n */\nexport function relayAppReports(app: App, sink: AppReportSink): () => void {\n const cleanups = [\n app.log.addSink({\n write: (record): void => {\n sink.log(logParamsOf(record));\n },\n }),\n app.onError.connect((report) => {\n sink.error(hostErrorParamsOf(report));\n }),\n app.hotReload.onApplied.connect((report) => {\n sink.hotReloaded(report);\n }),\n ];\n return (): void => {\n for (const cleanup of cleanups) {\n cleanup();\n }\n };\n}\n","/**\n * The scene view's overlay: Babylon Lite's position, rotation and scale gizmos and the selection\n * outline, in core's render overlay over the app's frame. Picking is `app.renderer.pickAsync`'s.\n *\n * This is the only module of the editor host that imports Lite (`CONSTITUTION.md` §3.4). The rest\n * of the host reaches it through {@link createEditorView}, which takes and returns ignifx objects\n * and plain data. Every Lite claim here was read from the pinned `@babylonjs/lite` 1.34\n * `index.d.ts`; the behaviours are the ones spike S0.2 measured (editor repository,\n * `docs/research/spikes/s0.2-gizmos-and-cameras.md`).\n */\n\nimport {\n addToScene,\n attachPositionGizmoToNode,\n attachRotationGizmoToNode,\n attachScaleGizmoToNode,\n createLines,\n createPositionGizmo,\n createRotationGizmo,\n createScaleGizmo,\n isGizmoDragging,\n isGizmoInteracting,\n isGizmoPickPending,\n onBeforeRender,\n setPositionGizmoLocalCoordinates,\n setRotationGizmoLocalCoordinates,\n setScaleGizmoLocalCoordinates,\n} from \"@babylonjs/lite\";\nimport type { Mesh, PointerDrag, SceneContext, SceneNode, Vec3 } from \"@babylonjs/lite\";\nimport type { AppLiteHandles, Entity, RenderOverlay } from \"@ignifx/core\";\n\n/** What a gizmo drag does. */\nexport type ViewGizmoMode = \"translate\" | \"rotate\" | \"scale\";\n\n/** Which handle of the gizmo is dragged. */\nexport type ViewGizmoAxis = \"x\" | \"y\" | \"z\" | \"uniform\";\n\n/** One sub-gizmo's drag. */\nexport interface ViewDrag {\n /** The gizmo's mode. */\n readonly mode: ViewGizmoMode;\n /** The handle. */\n readonly axis: ViewGizmoAxis;\n}\n\n/** Where Lite's gizmo dispatcher is with the current pointer gesture, for the editor camera. */\nexport interface ViewPointerState {\n /** A handle is hovered or dragged: a press there belongs to the gizmo. */\n readonly interacting: boolean;\n /** A gizmo drag is active. */\n readonly dragging: boolean;\n /** The dispatcher is still picking under the last press. */\n readonly pickPending: boolean;\n}\n\n/** An axis-aligned box in world space, in metres. */\nexport interface WorldBounds {\n /** The low corner. */\n readonly min: { readonly x: number; readonly y: number; readonly z: number };\n /** The high corner. */\n readonly max: { readonly x: number; readonly y: number; readonly z: number };\n}\n\n/** The overlay of one scene view. */\nexport interface EditorView {\n /**\n * Sets what the gizmo does; `null` hides every gizmo.\n *\n * @param mode - The mode, or `null` for none.\n */\n setMode(mode: ViewGizmoMode | null): void;\n /**\n * Sets whether the gizmo follows the entity's own axes.\n *\n * @param local - `true` for local axes, `false` for world axes.\n */\n setLocal(local: boolean): void;\n /**\n * Attaches the gizmo to an entity, or detaches it.\n *\n * @param entity - The primary selection, or `null`.\n */\n attach(entity: Entity | null): void;\n /**\n * Outlines entities with a line box over each one's world bounds.\n *\n * @param entities - The selection.\n */\n outline(entities: readonly Entity[]): void;\n /**\n * Shows or hides the gizmo and the outline, for a capture without them.\n *\n * @param visible - Whether they draw.\n */\n setVisible(visible: boolean): void;\n /**\n * Subscribes to every handle's drag start, move and end.\n *\n * @param listener - Receives the phase and the drag.\n */\n onDrag(listener: (phase: \"start\" | \"move\" | \"end\", drag: ViewDrag) => void): void;\n /**\n * Reads the gizmo dispatcher's state for the current pointer gesture.\n *\n * @returns The state.\n */\n pointerState(): ViewPointerState;\n /**\n * The world bounds of the meshes under an entity, glTF models included.\n *\n * @param entity - The entity.\n * @returns The box, or `null` when nothing under it is drawn.\n */\n worldBounds(entity: Entity): WorldBounds | null;\n /** Disposes the overlay and everything in it. */\n dispose(): void;\n}\n\n/** The three axes of a gizmo. */\nconst AXES: readonly (\"x\" | \"y\" | \"z\")[] = [\"x\", \"y\", \"z\"];\n\n/** The outline's colour: the editor's selection orange. */\nconst OUTLINE_COLOR = { r: 1, g: 0.6, b: 0.1, a: 1 };\n\n/** A unit cube's corners, centred on the origin. */\nconst CORNERS: readonly Vec3[] = [\n { x: -0.5, y: -0.5, z: -0.5 },\n { x: 0.5, y: -0.5, z: -0.5 },\n { x: 0.5, y: -0.5, z: 0.5 },\n { x: -0.5, y: -0.5, z: 0.5 },\n { x: -0.5, y: 0.5, z: -0.5 },\n { x: 0.5, y: 0.5, z: -0.5 },\n { x: 0.5, y: 0.5, z: 0.5 },\n { x: -0.5, y: 0.5, z: 0.5 },\n];\n\n/** One polyline over all twelve edges of a cube (three are walked twice), as corner indices. */\nconst OUTLINE_PATH: readonly number[] = [0, 1, 2, 3, 0, 4, 5, 1, 5, 6, 2, 6, 7, 3, 7, 4];\n\n/** The smallest outline side, so a flat or empty box stays visible. */\nconst MIN_OUTLINE_SIDE = 1e-3;\n\n/**\n * Builds the overlay of one scene view.\n *\n * @remarks\n * The gizmos and the outline live in core's render overlay (`app.renderer.openOverlay()`, ADR-0031),\n * whose Lite scenes have the shape Lite's gizmo constructors take as a utility layer. Core draws it\n * over the finished frame at every MSAA setting; Lite's own utility layer blacks out the scene or\n * draws nothing in an ignifx app (S0.2 §3.2).\n *\n * A detached Lite gizmo keeps drawing at its last pose, so a hidden sub-gizmo is collapsed to zero\n * scale; Lite restores the scale when it is attached again (S0.2 §3.3). The outline is a line box,\n * because Lite's bounding-box gizmo drags whatever is pressed inside it (S0.2 §7).\n *\n * @param handles - The app's Lite engine and render scene (`app.lite`).\n * @param overlay - An open render overlay of the same app, which the view now owns.\n * @param canvas - The canvas the gizmo dispatcher listens on.\n * @returns The view.\n */\nexport function createEditorView(\n handles: AppLiteHandles,\n overlay: RenderOverlay,\n canvas: HTMLCanvasElement,\n): EditorView {\n const { engine, scene } = handles;\n const layer = overlay.lite;\n const position = createPositionGizmo(engine, layer);\n const rotation = createRotationGizmo(engine, layer);\n const scale = createScaleGizmo(engine, layer);\n const listeners: ((phase: \"start\" | \"move\" | \"end\", drag: ViewDrag) => void)[] = [];\n const outlines: Mesh[] = [];\n let outlined: readonly Entity[] = [];\n let mode: ViewGizmoMode | null = \"translate\";\n let target: SceneNode | null = null;\n let visible = true;\n\n const wire = (drag: PointerDrag, info: ViewDrag): void => {\n const emit = (phase: \"start\" | \"move\" | \"end\"): void => {\n for (const listener of listeners) {\n listener(phase, info);\n }\n };\n drag.onDragStart.add(() => {\n emit(\"start\");\n });\n drag.onDrag.add(() => {\n emit(\"move\");\n });\n drag.onDragEnd.add(() => {\n emit(\"end\");\n });\n };\n for (const axis of AXES) {\n wire(position[`${axis}Gizmo`].drag, { mode: \"translate\", axis });\n wire(rotation[`${axis}Gizmo`].drag, { mode: \"rotate\", axis });\n wire(scale[`${axis}Gizmo`].drag, { mode: \"scale\", axis });\n }\n wire(scale.uniformScaleGizmo.drag, { mode: \"scale\", axis: \"uniform\" });\n\n const roots: Readonly<Record<ViewGizmoMode, readonly SceneNode[]>> = {\n translate: AXES.map((axis) => position[`${axis}Gizmo`].root),\n rotate: AXES.map((axis) => rotation[`${axis}Gizmo`].root),\n scale: [...AXES.map((axis) => scale[`${axis}Gizmo`].root), scale.uniformScaleGizmo.root],\n };\n\n const applyAttachment = (): void => {\n const shown = visible ? mode : null;\n attachPositionGizmoToNode(position, shown === \"translate\" ? target : null);\n attachRotationGizmoToNode(rotation, shown === \"rotate\" ? target : null);\n attachScaleGizmoToNode(scale, shown === \"scale\" ? target : null);\n for (const which of [\"translate\", \"rotate\", \"scale\"] as const) {\n if (which !== shown || target === null) {\n for (const root of roots[which]) {\n root.scaling.set(0, 0, 0);\n }\n }\n }\n };\n applyAttachment();\n\n const outlineMesh = (index: number): Mesh => {\n const existing = outlines[index];\n if (existing !== undefined) {\n return existing;\n }\n const mesh = createLines(engine, {\n name: \"ignifx-editor-outline\",\n points: OUTLINE_PATH.map((corner) => CORNERS[corner] ?? { x: 0, y: 0, z: 0 }),\n color: OUTLINE_COLOR,\n });\n mesh.pickable = false;\n mesh.visible = false;\n addToScene(layer.scene, mesh);\n outlines.push(mesh);\n return mesh;\n };\n\n onBeforeRender(layer.scene, () => {\n for (const [index, mesh] of outlines.entries()) {\n const entity = visible ? outlined[index] : undefined;\n const bounds =\n entity === undefined || entity.isDestroyed ? null : computeWorldBounds(entity.transform.lite, scene);\n if (bounds === null) {\n mesh.visible = false;\n continue;\n }\n mesh.visible = true;\n mesh.position.set(\n (bounds.min.x + bounds.max.x) / 2,\n (bounds.min.y + bounds.max.y) / 2,\n (bounds.min.z + bounds.max.z) / 2,\n );\n mesh.scaling.set(\n Math.max(MIN_OUTLINE_SIDE, bounds.max.x - bounds.min.x),\n Math.max(MIN_OUTLINE_SIDE, bounds.max.y - bounds.min.y),\n Math.max(MIN_OUTLINE_SIDE, bounds.max.z - bounds.min.z),\n );\n }\n });\n\n return {\n setMode(next: ViewGizmoMode | null): void {\n mode = next;\n applyAttachment();\n },\n setLocal(local: boolean): void {\n setPositionGizmoLocalCoordinates(position, local);\n setRotationGizmoLocalCoordinates(rotation, local);\n setScaleGizmoLocalCoordinates(scale, local);\n },\n attach(entity: Entity | null): void {\n target = entity === null ? null : entity.transform.lite;\n applyAttachment();\n },\n outline(entities: readonly Entity[]): void {\n outlined = [...entities];\n for (let index = 0; index < entities.length; index += 1) {\n outlineMesh(index);\n }\n for (const mesh of outlines.slice(entities.length)) {\n mesh.visible = false;\n }\n },\n setVisible(next: boolean): void {\n visible = next;\n applyAttachment();\n if (!next) {\n for (const mesh of outlines) {\n mesh.visible = false;\n }\n }\n },\n onDrag(listener): void {\n listeners.push(listener);\n },\n pointerState(): ViewPointerState {\n return {\n interacting: isGizmoInteracting(canvas),\n dragging: isGizmoDragging(canvas),\n pickPending: isGizmoPickPending(canvas),\n };\n },\n worldBounds(entity: Entity): WorldBounds | null {\n return computeWorldBounds(entity.transform.lite, scene);\n },\n dispose(): void {\n listeners.length = 0;\n overlay.dispose();\n },\n };\n}\n\n/**\n * A node's parent. Lite types it as a bare world-matrix provider, so it is followed by identity only.\n *\n * @param node - The node.\n * @returns The parent, or `null` at a root.\n */\nfunction parentNode(node: object): object | null {\n const parent: unknown = Reflect.get(node, \"parent\");\n return typeof parent === \"object\" && parent !== null ? parent : null;\n}\n\n/**\n * The world bounds of every visible mesh whose parent chain reaches a node.\n *\n * @remarks\n * Walking `node.children` is not enough: a `Model` parents its cloned glTF root with a bare\n * `parent` assignment, which leaves the entity node's `children` empty (S0.2 §6.1). So the scene's\n * meshes are scanned and kept when their parent chain reaches the node, as Lite's own bounding-box\n * gizmo does.\n *\n * @param root - The entity's node.\n * @param scene - The render scene.\n * @returns The box, or `null` when nothing under the node is drawn.\n */\nfunction computeWorldBounds(root: SceneNode, scene: SceneContext): WorldBounds | null {\n const min = { x: Number.POSITIVE_INFINITY, y: Number.POSITIVE_INFINITY, z: Number.POSITIVE_INFINITY };\n const max = { x: Number.NEGATIVE_INFINITY, y: Number.NEGATIVE_INFINITY, z: Number.NEGATIVE_INFINITY };\n const isUnder = (node: object): boolean => {\n for (let current: object | null = node; current !== null; current = parentNode(current)) {\n if (current === root) {\n return true;\n }\n }\n return false;\n };\n for (const mesh of scene.meshes) {\n const low = mesh.boundMin;\n const high = mesh.boundMax;\n if (low === undefined || high === undefined || mesh.visible === false || !isUnder(mesh)) {\n continue;\n }\n const m = mesh.worldMatrix;\n for (let corner = 0; corner < 8; corner += 1) {\n const x = (corner & 1) === 0 ? low[0] : high[0];\n const y = (corner & 2) === 0 ? low[1] : high[1];\n const z = (corner & 4) === 0 ? low[2] : high[2];\n const wx = (m[0] ?? 0) * x + (m[4] ?? 0) * y + (m[8] ?? 0) * z + (m[12] ?? 0);\n const wy = (m[1] ?? 0) * x + (m[5] ?? 0) * y + (m[9] ?? 0) * z + (m[13] ?? 0);\n const wz = (m[2] ?? 0) * x + (m[6] ?? 0) * y + (m[10] ?? 0) * z + (m[14] ?? 0);\n min.x = Math.min(min.x, wx);\n min.y = Math.min(min.y, wy);\n min.z = Math.min(min.z, wz);\n max.x = Math.max(max.x, wx);\n max.y = Math.max(max.y, wy);\n max.z = Math.max(max.z, wz);\n }\n }\n return Number.isFinite(min.x) ? { min, max } : null;\n}\n","/**\n * Asset hot reload in the scene view (engine ask E23): which changed assets the host reloads in\n * place, how it waits for the new value, and which of the document's instance roots a changed scene\n * or prefab rebuilds (`docs/architecture/17-editor-host.md` §6.1).\n */\n\nimport type { DocumentIndex } from \"./document.js\";\nimport type { App, AssetHandle } from \"@ignifx/core\";\n\n/**\n * A change on disk to one asset, as `@ignifx/vite-plugin`'s `ignifx:asset-changed` event reports\n * it; the event's payload is accepted as it is.\n *\n * @beta\n */\nexport interface EditorAssetChange {\n /** The asset's address, relative to the asset root. */\n readonly address: string;\n /** What happened to the file. */\n readonly kind: \"added\" | \"changed\" | \"removed\";\n}\n\n/** The asset type of a scene or prefab file. */\nexport const SCENE_ASSET_TYPE = \"scene\";\n\n/**\n * The asset types the host reloads in place. A scene or prefab rebuilds the document's instances\n * of it; the renderers read a model, mesh, material and sprite atlas from their handle every frame,\n * and a shader's materials rebuild on its `onReplaced`. A texture is left out: the materials and\n * atlases built from it keep the texture they were given, which the reload would unload.\n */\nexport const IN_PLACE_ASSET_TYPES: readonly string[] = [\n SCENE_ASSET_TYPE,\n \"model\",\n \"mesh\",\n \"material\",\n \"spriteatlas\",\n \"shader\",\n];\n\n/** A pending wait for a reload, which the host settles with `false` when it is disposed. */\nexport interface PendingReload {\n /** Resolves with `true` once the new value is delivered, `false` when the reload failed. */\n readonly replaced: Promise<boolean>;\n /** Stops waiting and resolves {@link PendingReload.replaced} with `false`. */\n cancel(): void;\n}\n\n/**\n * Starts waiting for a handle's next replacement. The assets service reports a failed reload only\n * through `app.onError`, without the address, so any asset failure while waiting ends the wait.\n *\n * @param app - The scene view's app.\n * @param handle - The handle about to be reloaded.\n * @returns The wait.\n */\nexport function waitForReplacement(app: App, handle: AssetHandle): PendingReload {\n let settle: ((replaced: boolean) => void) | null = null;\n const replaced = new Promise<boolean>((resolve) => {\n settle = resolve;\n });\n const disconnects: (() => void)[] = [];\n const finish = (value: boolean): void => {\n for (const disconnect of disconnects.splice(0)) {\n disconnect();\n }\n settle?.(value);\n };\n disconnects.push(\n handle.onReplaced.connect((): void => {\n finish(true);\n }),\n app.onError.connect((report): void => {\n if (report.source === \"asset\") {\n finish(false);\n }\n }),\n );\n return {\n replaced,\n cancel: (): void => {\n finish(false);\n },\n };\n}\n\n/**\n * Collects the addresses a scene asset instances, directly or through the scenes it instances.\n *\n * @param app - The scene view's app.\n * @param address - The scene's address.\n * @param into - The addresses found so far; also guards against a cycle.\n * @returns `into`, with `address` and every scene it pulls in added.\n */\nfunction sceneClosure(app: App, address: string, into: Set<string>): Set<string> {\n if (into.has(address)) {\n return into;\n }\n into.add(address);\n const handle = app.assets.get(address);\n if (handle === null || handle.state !== \"loaded\" || handle.type !== SCENE_ASSET_TYPE) {\n return into;\n }\n const dependencies: unknown = Reflect.get(Object(handle.value), \"dependencies\");\n if (Array.isArray(dependencies)) {\n for (const dependency of dependencies) {\n const nested: unknown = Reflect.get(Object(dependency), \"address\");\n if (typeof nested === \"string\") {\n sceneClosure(app, nested, into);\n }\n }\n }\n return into;\n}\n\n/**\n * The document's instance roots built from a scene, directly or through another scene they\n * instance, in document order. A root inside another root of the list is left out: rebuilding the\n * outer one rebuilds it.\n *\n * @param app - The scene view's app.\n * @param index - The open document's index.\n * @param address - The changed scene's address.\n * @returns The roots' uids.\n */\nexport function instancesOf(app: App, index: DocumentIndex, address: string): readonly string[] {\n const affected = new Set<string>();\n for (const record of index.file.entities) {\n const scene = record.instance?.scene.$asset;\n if (scene !== undefined && sceneClosure(app, scene, new Set()).has(address)) {\n affected.add(record.uid);\n }\n }\n return outermostRoots(index, affected);\n}\n\n/**\n * The document entities of a set that have no ancestor in the set, in the set's order: rebuilding\n * an instance root rebuilds every instance root under it.\n *\n * @param index - The open document's index.\n * @param roots - The uids.\n * @returns The outermost ones.\n */\nexport function outermostRoots(index: DocumentIndex, roots: ReadonlySet<string>): readonly string[] {\n return [...roots].filter((uid) => {\n for (let parent = index.records.get(uid)?.parent ?? null; parent !== null;) {\n if (roots.has(parent)) {\n return false;\n }\n parent = index.records.get(parent)?.parent ?? null;\n }\n return true;\n });\n}\n","/**\n * Defaults that a script's hot reload changes (engine ask E25): which fields of which component\n * types took a new default, and the live world brought in line with the document for them. A field\n * a document component's record leaves out takes the new default; a field it sets keeps its value;\n * a prefab instance whose members hold such a field is rebuilt from its prefab, with its overrides\n * (`docs/architecture/17-editor-host.md` §6.1).\n */\n\nimport { encodeProps } from \"@ignifx/core\";\nimport type { DocumentIndex, DocumentMirror } from \"./document.js\";\nimport type { App, Component, ComponentType, Entity, ReferenceEncoder } from \"@ignifx/core\";\n\n/** The fields whose default changed, by component type id. */\nexport type ChangedDefaults = ReadonlyMap<string, readonly string[]>;\n\n/** Each field's default as JSON text, by field name. */\ntype FieldDefaults = ReadonlyMap<string, string>;\n\n/** Defaults hold no reference to anything in a file. */\nconst NO_REFERENCES: ReferenceEncoder = {\n entityUid: (): null => null,\n componentUid: (): null => null,\n};\n\n/**\n * Reads a component type's field defaults as the file format writes them; `transient` fields,\n * which no file holds, are left out.\n *\n * @param app - The scene view's app.\n * @param type - The registered type.\n * @returns The defaults, or `null` for a type without a schema.\n */\nfunction defaultsOf(app: App, type: ComponentType): FieldDefaults | null {\n const schema = app.world.registry.describe(type).schema;\n if (schema === null) {\n return null;\n }\n const encoded = encodeProps(schema, {}, NO_REFERENCES);\n return new Map(Object.entries(encoded).map(([name, value]) => [name, JSON.stringify(value)]));\n}\n\n/** The field defaults of every registered type, as the host last saw them. */\nexport class DefaultsTracker {\n readonly #app: App;\n\n readonly #known = new Map<string, FieldDefaults | null>();\n\n /**\n * Reads the defaults of every type registered now.\n *\n * @param app - The scene view's app, started.\n */\n constructor(app: App) {\n this.#app = app;\n for (const [typeId, type] of app.world.registry.registrations()) {\n this.#known.set(typeId, defaultsOf(app, type));\n }\n }\n\n /**\n * Compares the defaults of reloaded types with the ones seen before, and keeps the new ones.\n *\n * @param typeIds - The type ids a hot reload replaced; any other id is ignored.\n * @returns The fields whose default changed or which are new, by type id. A type seen for the\n * first time has no change: no document component was built from it.\n */\n changed(typeIds: readonly string[]): ChangedDefaults {\n const changed = new Map<string, readonly string[]>();\n const registry = this.#app.world.registry;\n for (const typeId of typeIds) {\n const type = registry.get(typeId);\n if (type === null) {\n continue;\n }\n const next = defaultsOf(this.#app, type);\n const previous = this.#known.get(typeId);\n this.#known.set(typeId, next);\n if (previous === undefined || next === null) {\n continue;\n }\n const fields = [...next].filter(([name, value]) => previous?.get(name) !== value).map(([name]) => name);\n if (fields.length > 0) {\n changed.set(typeId, fields);\n }\n }\n return changed;\n }\n}\n\n/**\n * The type id of a live component.\n *\n * @param app - The scene view's app.\n * @param component - The component.\n * @returns Its registered type id, or `null`.\n */\nfunction typeIdOf(app: App, component: Component): string | null {\n return app.world.registry.describe(component.constructor).typeId;\n}\n\n/**\n * Gives every document component the new default of each changed field its record leaves out. A\n * component the mirror has no record of is left alone.\n *\n * @param app - The scene view's app.\n * @param mirror - The open document.\n * @param index - Its index.\n * @param changed - The changed fields, by type id.\n */\nexport function applyDefaults(app: App, mirror: DocumentMirror, index: DocumentIndex, changed: ChangedDefaults): void {\n for (const [uid, component] of index.components) {\n const fields = changed.get(typeIdOf(app, component) ?? \"\");\n const set = mirror.propsSetBy(uid);\n const schema = app.world.registry.describe(component.constructor).schema;\n if (fields === undefined || set === null || schema === null) {\n continue;\n }\n for (const name of fields) {\n const field = Object.hasOwn(schema, name) ? schema[name] : undefined;\n if (field !== undefined && !set.has(name)) {\n Reflect.set(component, name, field.createDefault());\n }\n }\n }\n}\n\n/**\n * The document's instance roots whose members (not the document's own components) include a\n * component of a changed type, in document order.\n *\n * @param app - The scene view's app.\n * @param index - The open document's index.\n * @param changed - The changed fields, by type id.\n * @returns The roots' uids.\n */\nexport function instancesHolding(app: App, index: DocumentIndex, changed: ChangedDefaults): ReadonlySet<string> {\n const roots = new Set<string>();\n for (const record of index.file.entities) {\n const root = index.entities.get(record.uid);\n if (record.instance === undefined || root === undefined) {\n continue;\n }\n const pending: Entity[] = [root];\n for (let entity = pending.pop(); entity !== undefined; entity = pending.pop()) {\n const holds = entity.components.some(\n (component) => !index.components.has(component.uid) && changed.has(typeIdOf(app, component) ?? \"\"),\n );\n if (holds) {\n roots.add(record.uid);\n break;\n }\n pending.push(...entity.children);\n }\n }\n return roots;\n}\n","/**\n * `playStats`: the game's frame rate and frame time from the frame history `app.diagnostics` keeps,\n * and the number of entities its world holds (`docs/architecture/17-editor-host.md` §5).\n */\n\nimport { createFrameSample } from \"@ignifx/core\";\nimport type { PlayStats } from \"./protocol/index.js\";\nimport type { App, Entity, FrameSample, SceneInstance } from \"@ignifx/core\";\n\n/** How much of the frame history the rate is averaged over, in milliseconds of rendered frames. */\nexport const PLAY_STATS_WINDOW_MS = 1000;\n\n/** Milliseconds in one second. */\nconst MILLISECONDS_PER_SECOND = 1000;\n\n/**\n * Counts the entities of a scene instance, members of instanced scenes included.\n *\n * @param scene - The instance.\n * @returns How many entities it holds, destroyed ones left out.\n */\nexport function countEntities(scene: SceneInstance): number {\n let count = 0;\n const pending: Entity[] = [...scene.roots];\n for (let entity = pending.pop(); entity !== undefined; entity = pending.pop()) {\n if (!entity.isDestroyed) {\n count += 1;\n pending.push(...entity.children);\n }\n }\n return count;\n}\n\n/**\n * Rounds a rate for the wire: two decimals are more than the stats strip shows.\n *\n * @param value - The value.\n * @returns It, to the nearest hundredth.\n */\nfunction hundredths(value: number): number {\n return Math.round(value * 100) / 100;\n}\n\n/** Reads a game's stats, with the one frame sample it reads the history into. */\nexport class PlayStatsReader {\n readonly #app: App;\n\n readonly #sample: FrameSample = createFrameSample();\n\n /**\n * Binds a reader to the game's app.\n *\n * @param app - The game's app.\n */\n constructor(app: App) {\n this.#app = app;\n }\n\n /**\n * Reads the stats now.\n *\n * @returns The mean frame time and rate over the newest second of the frame history (both `0`\n * while the frame loop does not run), the world's entity count, and `app.time.frameCount`.\n */\n read(): PlayStats {\n const app = this.#app;\n const diagnostics = app.diagnostics;\n let frames = 0;\n let elapsedMs = 0;\n // A stopped or stepped game has no loop: its history is the past, not a rate.\n if (app.isRunning) {\n for (let offset = 0; offset < diagnostics.historyLength && elapsedMs < PLAY_STATS_WINDOW_MS; offset += 1) {\n elapsedMs += diagnostics.readFrame(offset, this.#sample).rawDeltaMs;\n frames += 1;\n }\n }\n const frameTimeMs = frames > 0 && elapsedMs > 0 ? elapsedMs / frames : 0;\n let entityCount = 0;\n for (const scene of app.world.scenes) {\n entityCount += countEntities(scene);\n }\n return {\n fps: frameTimeMs > 0 ? hundredths(MILLISECONDS_PER_SECOND / frameTimeMs) : 0,\n frameTimeMs: hundredths(frameTimeMs),\n entityCount,\n frameCount: app.time.frameCount,\n };\n }\n}\n","/**\n * The open scene document's live mirror: the scene instance the editor's file is built into, the\n * scene settings the host keeps for it, and the lookups every scene method shares. Only the\n * document's own entities and components are reachable through it: an instanced scene's members and\n * the editor's objects never are (protocol 0.3, \"Document uids only\").\n */\n\nimport { decodeProps, serializeScene } from \"@ignifx/core\";\nimport { countEntities } from \"../play-stats.js\";\nimport type { OpenSceneResult, ReadBackParams, ReadBackResult, SceneIssue } from \"../protocol/index.js\";\nimport type {\n App,\n AssetHandle,\n Component,\n Entity,\n JsonObject,\n JsonValue,\n ReferenceDecoder,\n SceneFile,\n SceneFileComponent,\n SceneFileEntity,\n SceneFileOverride,\n SceneInstance,\n UidRemap,\n} from \"@ignifx/core\";\n\n/** Where a document that was never saved is published in the asset cache. */\nexport const UNSAVED_SCENE_ADDRESS = \"memory:scene/unsaved\";\n\n/** The document as the live world holds it now, written by `serializeScene`. */\nexport interface DocumentIndex {\n /** The serialized document, with `engineVersion` omitted. */\n readonly file: SceneFile;\n /** What the serializer reported. */\n readonly issues: readonly SceneIssue[];\n /** Each document entity, by uid. */\n readonly entities: ReadonlyMap<string, Entity>;\n /** Each document entity's record, by uid. */\n readonly records: ReadonlyMap<string, SceneFileEntity>;\n /** Each document component, by uid. */\n readonly components: ReadonlyMap<string, Component>;\n}\n\n/**\n * Copies a JSON value, so the host's settings never share an object with the editor's message.\n *\n * @param value - The value.\n * @returns A deep copy.\n */\nexport function copyJson<T extends JsonValue>(value: T): T {\n return structuredClone(value);\n}\n\n/**\n * Assigns a component's props decoded from JSON, the way the scene loader does: every schema field\n * the JSON leaves out takes its default.\n *\n * @param component - The component.\n * @param props - The `props` object.\n * @param references - How references resolve.\n * @returns The decoding problems, as `{ code, message }`.\n */\nexport function assignProps(component: Component, props: JsonObject, references: ReferenceDecoder): SceneIssue[] {\n const schema = component.world.registry.describe(component.constructor).schema;\n if (schema === null) {\n return [];\n }\n const decoded = decodeProps(schema, props, references);\n const values = new Map<string, unknown>(Object.entries(decoded.value));\n for (const name of Object.keys(schema)) {\n Reflect.set(component, name, values.get(name));\n }\n return decoded.issues.map((issue) => ({\n code: issue.code,\n message: `${component.uid}.${issue.path}: ${issue.message}`,\n }));\n}\n\n/** The live mirror of the editor's open scene document. */\nexport class DocumentMirror {\n readonly #app: App;\n\n #scene: SceneInstance | null = null;\n\n #address: string | null = null;\n\n #name = \"\";\n\n #settings: JsonObject | null = null;\n\n #index: DocumentIndex | null = null;\n\n /**\n * The fields each document component's record sets, by component uid: the keys of its `props` as\n * the file and the ops since have written them. A field left out takes the schema's default.\n */\n readonly #explicit = new Map<string, Set<string>>();\n\n /**\n * Each instance root's override list as the document holds it, by root uid. The serializer\n * recomputes overrides by diffing the live members with their scene, which after a hot reload\n * that changed a default reads every stale member value as an override.\n */\n readonly #overrides = new Map<string, readonly SceneFileOverride[]>();\n\n /** Assets loaded for ops, held until the document closes. */\n readonly #handles: AssetHandle[] = [];\n\n /**\n * Creates the mirror for one app.\n *\n * @param app - The scene view's app.\n */\n constructor(app: App) {\n this.#app = app;\n }\n\n /**\n * The open document's scene instance.\n *\n * @returns The instance, or `null` while no document is open.\n */\n get scene(): SceneInstance | null {\n return this.#scene;\n }\n\n /**\n * The address the open document was given, or `null` for one never saved.\n *\n * @returns The address.\n */\n get address(): string | null {\n return this.#address;\n }\n\n /**\n * The open document's file name.\n *\n * @returns The name, or `\"\"` while no document is open.\n */\n get name(): string {\n return this.#name;\n }\n\n /**\n * The document's `settings`, as the host keeps them. `readBack` writes these, because ops edit\n * them; systems that read scene settings read them once, when a scene opens.\n *\n * @returns The settings, or `null` when the document has none.\n */\n get settings(): JsonObject | null {\n return this.#settings;\n }\n\n // The accessor pair is documented on the getter only (API Extractor's `ae-setter-with-docs`).\n // eslint-disable-next-line jsdoc/require-jsdoc -- see the comment above\n set settings(value: JsonObject | null) {\n this.#settings = value;\n this.#index = null;\n }\n\n /**\n * Replaces the open document with a file: unloads the previous one, then builds this one into a\n * new scene instance with the file's uids, loading its assets.\n *\n * @param file - The document's file, already validated.\n * @param address - Where it is saved, or `null`.\n * @returns The entity count and the build's warnings.\n * @throws Whatever `world.loadSceneFile` throws; no document is open afterwards.\n */\n async open(file: SceneFile, address: string | null): Promise<OpenSceneResult> {\n await this.close();\n const warnings: SceneIssue[] = [];\n const scene = await this.#app.world.loadSceneFile(file, {\n address: address ?? UNSAVED_SCENE_ADDRESS,\n onIssue: (issue) => {\n warnings.push({ code: issue.code, message: issue.message });\n },\n });\n this.#scene = scene;\n this.#address = address;\n this.#name = file.name;\n this.#settings = file.settings === undefined ? null : copyJson(file.settings);\n this.recordComponents(file.entities.flatMap((record) => record.components ?? []));\n this.recordInstances(file.entities);\n return { entityCount: countEntities(scene), warnings };\n }\n\n /** Unloads the open document, if any, and releases the assets its ops loaded. */\n async close(): Promise<void> {\n const scene = this.#scene;\n this.#scene = null;\n this.#address = null;\n this.#name = \"\";\n this.#settings = null;\n this.#index = null;\n this.#explicit.clear();\n this.#overrides.clear();\n if (scene !== null) {\n await this.#app.world.unloadScene(scene);\n }\n for (const handle of this.#handles.splice(0)) {\n handle.release();\n }\n }\n\n /**\n * Keeps asset handles alive until the document closes.\n *\n * @param handles - Handles loaded for an op, each with one holder the mirror now owns.\n */\n retain(handles: readonly AssetHandle[]): void {\n this.#handles.push(...handles);\n }\n\n /**\n * Records which fields document components' records set, replacing what was known of each uid.\n *\n * @param components - The component records, as a file or an op carries them.\n */\n recordComponents(components: readonly SceneFileComponent[]): void {\n for (const component of components) {\n this.recordProps(component.uid, Object.keys(component.props ?? {}));\n }\n }\n\n /**\n * Records the whole set of fields a component's record sets.\n *\n * @param uid - The component's uid.\n * @param fields - The fields.\n */\n recordProps(uid: string, fields: Iterable<string>): void {\n this.#explicit.set(uid, new Set(fields));\n }\n\n /**\n * Records that a component's record now sets a field, or leaves it out.\n *\n * @param uid - The component's uid.\n * @param field - The field.\n * @param isSet - Whether the record sets it.\n */\n recordProp(uid: string, field: string, isSet: boolean): void {\n let fields = this.#explicit.get(uid);\n if (fields === undefined) {\n fields = new Set();\n this.#explicit.set(uid, fields);\n }\n if (isSet) {\n fields.add(field);\n } else {\n fields.delete(field);\n }\n }\n\n /**\n * The fields a document component's record sets.\n *\n * @param uid - The component's uid.\n * @returns The field names, or `null` when the mirror has no record of the component.\n */\n propsSetBy(uid: string): ReadonlySet<string> | null {\n return this.#explicit.get(uid) ?? null;\n }\n\n /**\n * Records the override lists of the instance roots among some entity records.\n *\n * @param records - The records, as a file or an op carries them.\n */\n recordInstances(records: readonly SceneFileEntity[]): void {\n for (const record of records) {\n if (record.instance !== undefined) {\n this.recordOverrides(record.uid, record.instance.overrides ?? []);\n }\n }\n }\n\n /**\n * Records an instance root's override list.\n *\n * @param uid - The root's uid.\n * @param overrides - The list.\n */\n recordOverrides(uid: string, overrides: readonly SceneFileOverride[]): void {\n // A copy, so the list never shares an object with the editor's message.\n this.#overrides.set(uid, structuredClone(overrides));\n }\n\n /**\n * An instance root's override list as the document holds it.\n *\n * @param uid - The root's uid.\n * @returns The list, or `null` when the mirror has no record of the root.\n */\n overridesOf(uid: string): readonly SceneFileOverride[] | null {\n return this.#overrides.get(uid) ?? null;\n }\n\n /** Forgets the cached index; call it after anything changed the document's structure. */\n invalidate(): void {\n this.#index = null;\n }\n\n /**\n * The document as the live world holds it, serialized once and cached until the next change.\n *\n * @returns The index, or `null` while no document is open.\n */\n index(): DocumentIndex | null {\n const scene = this.#scene;\n if (scene === null) {\n return null;\n }\n this.#index ??= this.#buildIndex(scene);\n return this.#index;\n }\n\n /**\n * Serializes the requested entities as the live world has them (protocol `readBack`).\n *\n * @param params - The uids to read, or none for all.\n * @returns The records in file order, the uids not found, the settings, and the serializer's issues.\n */\n readBack(params: ReadBackParams): ReadBackResult | null {\n const index = this.index();\n if (index === null) {\n return null;\n }\n const requested = params.entities;\n const wanted = requested === undefined ? null : new Set(requested);\n return {\n entities: index.file.entities.filter((record) => wanted === null || wanted.has(record.uid)),\n missing: requested === undefined ? [] : [...new Set(requested)].filter((uid) => !index.records.has(uid)),\n settings: index.file.settings ?? null,\n issues: index.issues,\n };\n }\n\n /**\n * The nearest document entity at or above an entity: itself, or the instance root it was\n * expanded from (protocol 0.3, \"Document uids only\").\n *\n * @param entity - Any entity.\n * @returns The document entity, or `null` when the entity is not in the document.\n */\n documentEntityOf(entity: Entity | null): Entity | null {\n const index = this.index();\n if (index === null || entity === null || entity.scene !== this.#scene) {\n return null;\n }\n for (let current: Entity | null = entity; current !== null; current = current.parent) {\n if (index.entities.get(current.uid) === current) {\n return current;\n }\n }\n return null;\n }\n\n /**\n * How references in props resolve: document uids first, then the uids of a subtree just built,\n * and assets already loaded in the app's cache.\n *\n * @param built - The uid table of a subtree an op just built, if any.\n * @returns The decoder.\n */\n decoder(built?: UidRemap): ReferenceDecoder {\n const index = this.index();\n const assets = this.#app.assets;\n return {\n entity: (uid: string): Entity | null => index?.entities.get(uid) ?? built?.entity(uid) ?? null,\n component: (uid: string): Component | null => index?.components.get(uid) ?? built?.component(uid) ?? null,\n asset: (address: string, type: string | null): AssetHandle | null => {\n const handle = assets.get(address);\n return handle !== null && handle.state === \"loaded\" && (type === null || handle.type === type) ? handle : null;\n },\n };\n }\n\n /**\n * Serializes the document and indexes its entities and components.\n *\n * @param scene - The document's scene instance.\n * @returns The index.\n */\n #buildIndex(scene: SceneInstance): DocumentIndex {\n const issues: SceneIssue[] = [];\n const file = serializeScene(scene, {\n engineVersion: null,\n settings: this.#settings,\n onIssue: (issue) => {\n issues.push({ code: issue.code, message: issue.message });\n },\n });\n const world = this.#app.world;\n const entities = new Map<string, Entity>();\n const records = new Map<string, SceneFileEntity>();\n const components = new Map<string, Component>();\n for (const record of file.entities) {\n const entity = world.getEntity(record.uid);\n if (entity === null) {\n continue;\n }\n entities.set(record.uid, entity);\n records.set(record.uid, record);\n const uids = new Set((record.components ?? []).map((component) => component.uid));\n for (const component of entity.components) {\n if (uids.has(component.uid) && !component.isDestroyed) {\n components.set(component.uid, component);\n }\n }\n }\n return { file, issues, entities, records, components };\n }\n}\n","/**\n * The scene view's 3D editor camera: an ordinary script on an entity of the host's persistent\n * `editor` scene, beside a `Camera` whose priority outranks every camera of the document.\n */\n\nimport { clamp, degToRad, Script } from \"@ignifx/core\";\nimport type { ScriptCallbacks } from \"@ignifx/core\";\n\n/** What the camera asks the gizmo dispatcher before it takes a pointer gesture. */\nexport interface PointerClaims {\n /**\n * Reads the dispatcher's state for the current gesture.\n *\n * @returns Whether a handle is hovered or dragged, and whether a press is still being picked.\n */\n pointerState(): { readonly interacting: boolean; readonly dragging: boolean; readonly pickPending: boolean };\n}\n\n/** A sphere to fit in the view, in world space. */\nexport interface FrameTarget {\n /** Its centre. */\n readonly center: { readonly x: number; readonly y: number; readonly z: number };\n /** Its radius, in metres. */\n readonly radius: number;\n}\n\n/** A click on the view: where, and with which modifier keys. */\nexport interface ViewClick {\n /** The CSS pixel x, from the canvas's left edge. */\n readonly x: number;\n /** The CSS pixel y, from the canvas's top edge. */\n readonly y: number;\n /** Shift, Ctrl or Cmd was held: the click toggles rather than replaces. */\n readonly toggle: boolean;\n}\n\n/**\n * Captures a pointer on the canvas. The pointer may already be gone (released before the listener\n * ran, or an event no device produced), which `setPointerCapture` reports by throwing; the gesture\n * then simply runs uncaptured.\n *\n * @param canvas - The canvas, or `null`.\n * @param pointerId - The pointer.\n * @param capture - `true` to capture, `false` to release.\n */\nexport function setCapture(canvas: HTMLCanvasElement | null, pointerId: number, capture: boolean): void {\n if (canvas === null) {\n return;\n }\n try {\n if (capture) {\n canvas.setPointerCapture(pointerId);\n } else if (canvas.hasPointerCapture(pointerId)) {\n canvas.releasePointerCapture(pointerId);\n }\n } catch {\n // An inactive pointer cannot be captured; nothing else depends on the capture.\n }\n}\n\n/** The camera's vertical field of view, in degrees. */\nexport const EDITOR_CAMERA_FOV = 50;\n\n/** The steepest the camera looks up or down, in degrees. */\nconst MAX_PITCH = 89;\n\n/** How far a press may move, in CSS pixels, and still be a click. */\nconst CLICK_SLOP_PX = 4;\n\n/** The gesture the current pointer press drives. */\ntype Gesture = \"none\" | \"orbit\" | \"fly\" | \"pan\";\n\n/**\n * Orbits, flies and pans around a focus point on DOM pointer events, and frames what it is asked to.\n *\n * @remarks\n * Left drag orbits, middle drag pans, right drag looks around while W, A, S, D, Q and E fly (Shift\n * for speed), the wheel dollies, and a left click is reported to `onClick`. The camera listens in\n * the bubble phase, after Lite's gizmo dispatcher has seen the press in the capture phase, and it\n * yields to the gizmo by the three rules Lite documents for its own controls (S0.2 §4.2): no orbit\n * starts on a hovered handle, a move is held while the press is still being picked, and an orbit\n * stops once a gizmo drag begins.\n */\nexport class EditorCamera extends Script implements ScriptCallbacks {\n /** The type id; the host leaves it out of the schemas it reports. */\n static typeId = \"ignifx-editor/EditorCamera\";\n\n /** The scene view runs in edit mode, where only these scripts get callbacks. */\n static runInEditMode = true;\n\n /** The point the camera orbits and looks at. */\n focus = { x: 0, y: 1, z: 0 };\n\n /** The heading, in degrees; 0 looks along +Z. */\n yaw = 30;\n\n /** The tilt, in degrees; positive looks down. */\n pitch = 25;\n\n /** How far the eye is from the focus, in metres. */\n distance = 12;\n\n /** Whether the camera answers the view's input; the host clears it while the view is in 2D mode. */\n active = true;\n\n /** The gizmo dispatcher, once the view has one. */\n claims: PointerClaims | null = null;\n\n /** Receives each click on the view. */\n onClick: ((click: ViewClick) => void) | null = null;\n\n #canvas: HTMLCanvasElement | null = null;\n\n #gesture: Gesture = \"none\";\n\n #pointer = -1;\n\n #lastX = 0;\n\n #lastY = 0;\n\n #downX = 0;\n\n #downY = 0;\n\n #moved = false;\n\n #gizmoTookGesture = false;\n\n readonly #keys = new Set<string>();\n\n readonly #onPointerDown = (event: PointerEvent): void => {\n if (!this.active || this.#pointer !== -1) {\n return;\n }\n this.#downX = event.offsetX;\n this.#downY = event.offsetY;\n this.#lastX = event.clientX;\n this.#lastY = event.clientY;\n this.#moved = false;\n this.#gizmoTookGesture = false;\n if (event.button === 0) {\n this.#gizmoTookGesture = this.claims?.pointerState().interacting === true;\n this.#gesture = this.#gizmoTookGesture ? \"none\" : \"orbit\";\n } else if (event.button === 1) {\n this.#gesture = \"pan\";\n event.preventDefault();\n } else if (event.button === 2) {\n this.#gesture = \"fly\";\n } else {\n return;\n }\n this.#pointer = event.pointerId;\n setCapture(this.#canvas, event.pointerId, true);\n };\n\n readonly #onPointerMove = (event: PointerEvent): void => {\n if (event.pointerId !== this.#pointer) {\n return;\n }\n const dx = event.clientX - this.#lastX;\n const dy = event.clientY - this.#lastY;\n this.#lastX = event.clientX;\n this.#lastY = event.clientY;\n if (Math.hypot(event.offsetX - this.#downX, event.offsetY - this.#downY) > CLICK_SLOP_PX) {\n this.#moved = true;\n }\n if (this.#gesture === \"orbit\") {\n const state = this.claims?.pointerState();\n if (state?.dragging === true) {\n this.#gizmoTookGesture = true;\n this.#gesture = \"none\";\n return;\n }\n if (state?.pickPending !== true) {\n this.yaw += dx * 0.3;\n this.pitch = clamp(this.pitch + dy * 0.3, -MAX_PITCH, MAX_PITCH);\n }\n } else if (this.#gesture === \"fly\") {\n const eye = this.#eye();\n this.yaw += dx * 0.2;\n this.pitch = clamp(this.pitch + dy * 0.2, -MAX_PITCH, MAX_PITCH);\n const direction = this.#direction();\n this.focus = {\n x: eye.x + direction.x * this.distance,\n y: eye.y + direction.y * this.distance,\n z: eye.z + direction.z * this.distance,\n };\n } else if (this.#gesture === \"pan\") {\n const scale = (this.distance * 0.0016 * (this.#canvas?.clientHeight ?? 800)) / 800;\n const right = this.#right();\n const up = this.#up();\n this.focus = {\n x: this.focus.x + (-dx * right.x + dy * up.x) * scale,\n y: this.focus.y + (-dx * right.y + dy * up.y) * scale,\n z: this.focus.z + (-dx * right.z + dy * up.z) * scale,\n };\n }\n this.apply();\n };\n\n readonly #onPointerUp = (event: PointerEvent): void => {\n if (event.pointerId !== this.#pointer) {\n return;\n }\n setCapture(this.#canvas, event.pointerId, false);\n this.#pointer = -1;\n this.#gesture = \"none\";\n this.#keys.clear();\n if (\n event.button === 0 &&\n !this.#moved &&\n !this.#gizmoTookGesture &&\n this.claims?.pointerState().dragging !== true\n ) {\n this.onClick?.({\n x: event.offsetX,\n y: event.offsetY,\n toggle: event.shiftKey || event.ctrlKey || event.metaKey,\n });\n }\n };\n\n readonly #onWheel = (event: WheelEvent): void => {\n if (!this.active) {\n return;\n }\n event.preventDefault();\n this.distance = clamp(this.distance * Math.exp(event.deltaY * 0.0015), 0.2, 5000);\n this.apply();\n };\n\n readonly #onContextMenu = (event: Event): void => {\n event.preventDefault();\n };\n\n readonly #onKeyDown = (event: KeyboardEvent): void => {\n this.#keys.add(event.code);\n };\n\n readonly #onKeyUp = (event: KeyboardEvent): void => {\n this.#keys.delete(event.code);\n };\n\n /**\n * Starts listening to a canvas's pointer, wheel and key events.\n *\n * @param canvas - The scene view's canvas.\n */\n bind(canvas: HTMLCanvasElement): void {\n this.#canvas = canvas;\n canvas.addEventListener(\"pointerdown\", this.#onPointerDown);\n canvas.addEventListener(\"pointermove\", this.#onPointerMove);\n canvas.addEventListener(\"pointerup\", this.#onPointerUp);\n canvas.addEventListener(\"pointercancel\", this.#onPointerUp);\n canvas.addEventListener(\"wheel\", this.#onWheel, { passive: false });\n canvas.addEventListener(\"contextmenu\", this.#onContextMenu);\n canvas.ownerDocument.addEventListener(\"keydown\", this.#onKeyDown);\n canvas.ownerDocument.addEventListener(\"keyup\", this.#onKeyUp);\n }\n\n /** Stops listening. */\n onDestroy(): void {\n const canvas = this.#canvas;\n if (canvas === null) {\n return;\n }\n canvas.removeEventListener(\"pointerdown\", this.#onPointerDown);\n canvas.removeEventListener(\"pointermove\", this.#onPointerMove);\n canvas.removeEventListener(\"pointerup\", this.#onPointerUp);\n canvas.removeEventListener(\"pointercancel\", this.#onPointerUp);\n canvas.removeEventListener(\"wheel\", this.#onWheel);\n canvas.removeEventListener(\"contextmenu\", this.#onContextMenu);\n canvas.ownerDocument.removeEventListener(\"keydown\", this.#onKeyDown);\n canvas.ownerDocument.removeEventListener(\"keyup\", this.#onKeyUp);\n this.#canvas = null;\n }\n\n /**\n * Fits a sphere in the view: the focus moves to its centre and the distance fits its radius in\n * the field of view, with a margin.\n *\n * @param target - The sphere.\n */\n frame(target: FrameTarget): void {\n this.focus = { x: target.center.x, y: target.center.y, z: target.center.z };\n this.distance = Math.max(0.5, (Math.max(target.radius, 0.25) / Math.sin(degToRad(EDITOR_CAMERA_FOV / 2))) * 1.2);\n this.apply();\n }\n\n /**\n * Flies while the right button is held and a movement key is down.\n *\n * @param deltaTime - The frame's unscaled delta, in seconds.\n */\n update(deltaTime: number): void {\n if (!this.active || this.#gesture !== \"fly\" || this.#keys.size === 0) {\n return;\n }\n const speed = 5 * (this.#keys.has(\"ShiftLeft\") || this.#keys.has(\"ShiftRight\") ? 4 : 1) * deltaTime;\n const direction = this.#direction();\n const right = this.#right();\n const along = (this.#keys.has(\"KeyW\") ? speed : 0) - (this.#keys.has(\"KeyS\") ? speed : 0);\n const across = (this.#keys.has(\"KeyD\") ? speed : 0) - (this.#keys.has(\"KeyA\") ? speed : 0);\n const rise = (this.#keys.has(\"KeyE\") ? speed : 0) - (this.#keys.has(\"KeyQ\") ? speed : 0);\n this.focus = {\n x: this.focus.x + direction.x * along + right.x * across,\n y: this.focus.y + direction.y * along + right.y * across + rise,\n z: this.focus.z + direction.z * along + right.z * across,\n };\n this.apply();\n }\n\n /** Places the camera's entity at the eye, looking at the focus. */\n apply(): void {\n const eye = this.#eye();\n this.transform.localPosition.set(eye.x, eye.y, eye.z);\n this.transform.lookAt(this.focus);\n }\n\n /**\n * The unit view direction; yaw 0 looks along +Z, positive pitch looks down.\n *\n * @returns The direction.\n */\n #direction(): { x: number; y: number; z: number } {\n const yaw = degToRad(this.yaw);\n const pitch = degToRad(this.pitch);\n return { x: Math.cos(pitch) * Math.sin(yaw), y: -Math.sin(pitch), z: Math.cos(pitch) * Math.cos(yaw) };\n }\n\n /**\n * The view's right vector, level with the ground.\n *\n * @returns The vector.\n */\n #right(): { x: number; y: number; z: number } {\n const yaw = degToRad(this.yaw);\n return { x: Math.cos(yaw), y: 0, z: -Math.sin(yaw) };\n }\n\n /**\n * The view's up vector.\n *\n * @returns The vector.\n */\n #up(): { x: number; y: number; z: number } {\n const d = this.#direction();\n const r = this.#right();\n return { x: d.y * r.z - d.z * r.y, y: d.z * r.x - d.x * r.z, z: d.x * r.y - d.y * r.x };\n }\n\n /**\n * The eye position.\n *\n * @returns The point `distance` behind the focus along the view direction.\n */\n #eye(): { x: number; y: number; z: number } {\n const d = this.#direction();\n return {\n x: this.focus.x - d.x * this.distance,\n y: this.focus.y - d.y * this.distance,\n z: this.focus.z - d.z * this.distance,\n };\n }\n}\n","/**\n * The scene view's 2D side: the 2D editor camera's arithmetic, and the parts of `@ignifx/2d` the\n * host reads. The host does not import `@ignifx/2d` (it is not a dependency of this package): it\n * reaches `app.twoD` and the 2D component classes by their names, through the project's own copy,\n * the way `@ignifx/physics-2d` finds a `Tilemap` by its type id (`11-2d-toolkit.md` §2.5).\n */\n\nimport { Camera } from \"@ignifx/core\";\nimport { ViewMode } from \"../protocol/index.js\";\nimport type { App, Component, ComponentType, ConcreteComponentType, Entity, SceneInstance } from \"@ignifx/core\";\n\n/** The type id of `@ignifx/2d`'s `Camera2D`. */\nexport const CAMERA_2D_TYPE = \"ignifx/Camera2D\";\n\n/** The type id of `@ignifx/2d`'s `SpriteRenderer`. */\nexport const SPRITE_RENDERER_TYPE = \"ignifx/SpriteRenderer\";\n\n/** The type id of `@ignifx/2d`'s `Tilemap`. */\nexport const TILEMAP_TYPE = \"ignifx/Tilemap\";\n\n/** `@ignifx/2d`'s default pixels per unit, used when the project has no 2D toolkit. */\nexport const DEFAULT_PIXELS_PER_UNIT = 100;\n\n/**\n * The wheel's zoom steps, in screen pixels per layer pixel (`Camera2D.zoom`): with a pixels-per-unit\n * equal to the art's, a source pixel spans a whole number of screen pixels from 1 up (S0.2 §5).\n */\nexport const ZOOM_STEPS: readonly number[] = [0.125, 0.25, 0.5, 1, 2, 3, 4, 6, 8, 12, 16, 24, 32];\n\n/** The farthest out a frame may zoom. */\nconst MIN_ZOOM = 1 / 64;\n\n/** The farthest in a frame may zoom. */\nconst MAX_ZOOM = 64;\n\n/** How much room a frame leaves around what it fits, as a factor of its size. */\nconst FRAME_MARGIN = 1.2;\n\n/** The smallest extent a frame fits, in metres, so a point or a sliver does not zoom in forever. */\nconst MIN_FRAME_EXTENT = 0.5;\n\n/** An axis-aligned rectangle of the 2D world, in metres, +Y up. */\nexport interface Box2D {\n /** The left edge. */\n readonly minX: number;\n /** The bottom edge. */\n readonly minY: number;\n /** The right edge. */\n readonly maxX: number;\n /** The top edge. */\n readonly maxY: number;\n}\n\n/** What the 2D editor camera shows. */\nexport interface View2D {\n /** The world x at the view's centre, in metres. */\n readonly centerX: number;\n /** The world y at the view's centre, in metres. */\n readonly centerY: number;\n /** Screen pixels per layer pixel, as `Camera2D.zoom`. */\n readonly zoom: number;\n /** Layer pixels per metre. */\n readonly pixelsPerUnit: number;\n /** The view's backing-store width, in pixels. */\n readonly widthPx: number;\n /** The view's backing-store height, in pixels. */\n readonly heightPx: number;\n}\n\n/**\n * The next zoom step in or out from a zoom, which need not be a step itself.\n *\n * @param zoom - The current zoom.\n * @param direction - `1` to zoom in, `-1` to zoom out.\n * @returns The nearest step beyond `zoom` that way, or the last step when there is none.\n */\nexport function stepZoom(zoom: number, direction: 1 | -1): number {\n if (direction > 0) {\n return ZOOM_STEPS.find((step) => step > zoom * 1.0001) ?? ZOOM_STEPS.at(-1) ?? zoom;\n }\n return ZOOM_STEPS.findLast((step) => step < zoom * 0.9999) ?? ZOOM_STEPS[0] ?? zoom;\n}\n\n/**\n * The half-height a camera shows at a zoom: the inverse of `Camera2D`'s\n * `zoom = heightPx / (2 · size · PPU)`.\n *\n * @param zoom - Screen pixels per layer pixel.\n * @param heightPx - The view's backing-store height.\n * @param pixelsPerUnit - Layer pixels per metre.\n * @returns The half-height, in metres.\n */\nexport function orthographicSizeFor(zoom: number, heightPx: number, pixelsPerUnit: number): number {\n return heightPx / (2 * zoom * pixelsPerUnit);\n}\n\n/**\n * The zoom at which a camera shows a half-height: `Camera2D`'s own rule.\n *\n * @param orthographicSize - The half-height, in metres.\n * @param heightPx - The view's backing-store height.\n * @param pixelsPerUnit - Layer pixels per metre.\n * @returns The zoom.\n */\nexport function zoomForSize(orthographicSize: number, heightPx: number, pixelsPerUnit: number): number {\n return heightPx / (2 * orthographicSize * pixelsPerUnit);\n}\n\n/**\n * The world point under a backing-store pixel of the view.\n *\n * @param view - The view.\n * @param x - The pixel x, from the left edge.\n * @param y - The pixel y, from the top edge.\n * @returns The point, in metres, +Y up.\n */\nexport function screenToWorld2D(view: View2D, x: number, y: number): { readonly x: number; readonly y: number } {\n const scale = view.zoom * view.pixelsPerUnit;\n return {\n x: view.centerX + (x - view.widthPx / 2) / scale,\n y: view.centerY - (y - view.heightPx / 2) / scale,\n };\n}\n\n/**\n * Where the view's centre goes when it zooms about a pixel, so the world point under that pixel\n * stays under it.\n *\n * @param view - The view before the zoom.\n * @param x - The pixel x.\n * @param y - The pixel y.\n * @param zoom - The new zoom.\n * @returns The new centre.\n */\nexport function zoomAbout(\n view: View2D,\n x: number,\n y: number,\n zoom: number,\n): { readonly centerX: number; readonly centerY: number } {\n const anchor = screenToWorld2D(view, x, y);\n const scale = zoom * view.pixelsPerUnit;\n return {\n centerX: anchor.x - (x - view.widthPx / 2) / scale,\n centerY: anchor.y + (y - view.heightPx / 2) / scale,\n };\n}\n\n/**\n * The centre and zoom that fit a rectangle in the view, with a margin.\n *\n * @param box - The rectangle.\n * @param widthPx - The view's backing-store width.\n * @param heightPx - The view's backing-store height.\n * @param pixelsPerUnit - Layer pixels per metre.\n * @returns The centre and the zoom.\n */\nexport function fitView(\n box: Box2D,\n widthPx: number,\n heightPx: number,\n pixelsPerUnit: number,\n): { readonly centerX: number; readonly centerY: number; readonly zoom: number } {\n const width = Math.max(box.maxX - box.minX, MIN_FRAME_EXTENT) * FRAME_MARGIN * pixelsPerUnit;\n const height = Math.max(box.maxY - box.minY, MIN_FRAME_EXTENT) * FRAME_MARGIN * pixelsPerUnit;\n const zoom = Math.min(widthPx / width, heightPx / height);\n return {\n centerX: (box.minX + box.maxX) / 2,\n centerY: (box.minY + box.maxY) / 2,\n zoom: Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, Number.isFinite(zoom) && zoom > 0 ? zoom : 1)),\n };\n}\n\n/**\n * Grows a rectangle to take in another.\n *\n * @param box - The rectangle so far, or `null`.\n * @param other - The one to take in.\n * @returns Their union.\n */\nfunction union(box: Box2D | null, other: Box2D): Box2D {\n return box === null\n ? other\n : {\n minX: Math.min(box.minX, other.minX),\n minY: Math.min(box.minY, other.minY),\n maxX: Math.max(box.maxX, other.maxX),\n maxY: Math.max(box.maxY, other.maxY),\n };\n}\n\n// -------------------------------------------------------------------------------------------\n// `@ignifx/2d`, by data\n// -------------------------------------------------------------------------------------------\n\n/** What the host reads of a `TwoDPick`. */\nexport interface TwoDPickLike {\n /** The entity carrying the sprite hit. */\n readonly entity: Entity;\n}\n\n/** What the host passes to `app.twoD.pickAt`, as `@ignifx/2d`'s `TwoDPickOptions`. */\nexport interface TwoDPickOptionsLike {\n /** Restricts the pick to the sprites of the entities this accepts. */\n readonly filter?: (entity: Entity) => boolean;\n /** Whether sprites the game marks `pickable: false` count too. */\n readonly includeUnpickable?: boolean;\n}\n\n/** What the host uses of `app.twoD`, `@ignifx/2d`'s `TwoDService`. */\nexport interface TwoDServiceLike {\n /** `\"sprite\"`, where sprites are the whole frame, or `\"mixed\"`. */\n readonly mode: string;\n /** Layer pixels per metre. */\n readonly pixelsPerUnit: number;\n /**\n * Picks the topmost sprite under a backing-store pixel.\n *\n * @param xPx - The pixel x.\n * @param yPx - The pixel y.\n * @param options - Which sprites count.\n * @returns The hit, or `null`.\n */\n pickAt(xPx: number, yPx: number, options?: TwoDPickOptionsLike): TwoDPickLike | null;\n}\n\n/** What the host reads and writes of a `Camera2D`. */\nexport interface Camera2DLike extends Component {\n /** The half-height it shows, in metres. */\n orthographicSize: number;\n /** Highest enabled wins. */\n priority: number;\n /** Whether zoom and position snap to whole pixels. */\n pixelPerfect: boolean;\n}\n\n/** What the host reads of a `SpriteRenderer`. */\ninterface SpriteLike extends Component {\n /** The world rectangle of the unrotated quad, as the last frame's sync measured it. */\n readonly bounds: {\n readonly min: { readonly x: number; readonly y: number };\n readonly max: { readonly x: number; readonly y: number };\n };\n}\n\n/** What the host reads of a `Tilemap`. */\ninterface TilemapLike extends Component {\n /** Metres per cell; `0` before the map has loaded. */\n readonly cellSize: number;\n /** How many layers the map has. */\n readonly layerCount: number;\n /**\n * A layer's size, in cells.\n *\n * @param layer - The layer's index.\n * @returns The size.\n */\n layerSize(layer: number): { readonly x: number; readonly y: number };\n}\n\n/**\n * The app's 2D service, when the project registers `@ignifx/2d`.\n *\n * @param app - The app.\n * @returns `app.twoD`, or `null`.\n */\nexport function twoDServiceOf(app: App): TwoDServiceLike | null {\n const service: unknown = Reflect.get(app, \"twoD\");\n if (typeof service !== \"object\" || service === null) {\n return null;\n }\n const pickAt: unknown = Reflect.get(service, \"pickAt\");\n const mode: unknown = Reflect.get(service, \"mode\");\n const pixelsPerUnit: unknown = Reflect.get(service, \"pixelsPerUnit\");\n if (typeof pickAt !== \"function\" || typeof mode !== \"string\" || typeof pixelsPerUnit !== \"number\") {\n return null;\n }\n return {\n mode,\n pixelsPerUnit,\n pickAt: (xPx, yPx, options): TwoDPickLike | null => {\n const hit: unknown = Reflect.apply(pickAt, service, [xPx, yPx, options]);\n const entity: unknown = typeof hit === \"object\" && hit !== null ? Reflect.get(hit, \"entity\") : null;\n return isEntity(entity) ? { entity } : null;\n },\n };\n}\n\n/**\n * Tells whether a value is an entity of some world.\n *\n * @param value - The value.\n * @returns True for an object with a uid, a scene and a transform.\n */\nfunction isEntity(value: unknown): value is Entity {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof Reflect.get(value, \"uid\") === \"string\" &&\n typeof Reflect.get(value, \"transform\") === \"object\"\n );\n}\n\n/**\n * Tells whether a component type can be constructed, which `addComponent` needs.\n *\n * @param type - The type.\n * @returns True for a class.\n */\nfunction isConcrete(type: ComponentType): type is ConcreteComponentType {\n return typeof type === \"function\";\n}\n\n/**\n * A registered component class, by type id.\n *\n * @param app - The app.\n * @param typeId - The type id.\n * @returns The class, or `null` when the project does not register it.\n */\nexport function componentTypeOf(app: App, typeId: string): ConcreteComponentType | null {\n const type = app.world.registry.get(typeId);\n return type !== null && isConcrete(type) ? type : null;\n}\n\n/**\n * Tells whether a component is a `Camera2D`.\n *\n * @param component - The component.\n * @returns True when it has the fields the host drives.\n */\nexport function isCamera2DLike(component: Component | null): component is Camera2DLike {\n return (\n component !== null &&\n typeof Reflect.get(component, \"orthographicSize\") === \"number\" &&\n typeof Reflect.get(component, \"priority\") === \"number\" &&\n typeof Reflect.get(component, \"pixelPerfect\") === \"boolean\"\n );\n}\n\n/**\n * Tells whether a component is a `SpriteRenderer`.\n *\n * @param component - The component.\n * @returns True when it reports world bounds.\n */\nfunction isSpriteLike(component: Component): component is SpriteLike {\n const bounds: unknown = Reflect.get(component, \"bounds\");\n return typeof bounds === \"object\" && bounds !== null && \"min\" in bounds && \"max\" in bounds;\n}\n\n/**\n * Tells whether a component is a `Tilemap`.\n *\n * @param component - The component.\n * @returns True when it reports its cell size and layer sizes.\n */\nfunction isTilemapLike(component: Component): component is TilemapLike {\n return (\n typeof Reflect.get(component, \"cellSize\") === \"number\" &&\n typeof Reflect.get(component, \"layerCount\") === \"number\" &&\n typeof Reflect.get(component, \"layerSize\") === \"function\"\n );\n}\n\n/**\n * The 2D world rectangle entities cover: each sprite's quad and each tilemap's extent under them,\n * plus every entity's position, so an entity with nothing drawn, or a sprite not yet synced, still\n * counts.\n *\n * @param app - The app whose registry names the 2D classes.\n * @param entities - The entities.\n * @returns The rectangle, or `null` for none.\n */\nexport function boundsOf2D(app: App, entities: readonly Entity[]): Box2D | null {\n const sprite = componentTypeOf(app, SPRITE_RENDERER_TYPE);\n const tilemap = componentTypeOf(app, TILEMAP_TYPE);\n let box: Box2D | null = null;\n for (const entity of entities) {\n const position = entity.transform.position;\n box = union(box, { minX: position.x, minY: position.y, maxX: position.x, maxY: position.y });\n for (const component of sprite === null ? [] : entity.getComponentsInChildren(sprite, true)) {\n if (isSpriteLike(component)) {\n const { min, max } = component.bounds;\n // An unsynced sprite reports an empty box at the origin; its position already counts.\n if (max.x > min.x && max.y > min.y) {\n box = union(box, { minX: min.x, minY: min.y, maxX: max.x, maxY: max.y });\n }\n }\n }\n for (const component of tilemap === null ? [] : entity.getComponentsInChildren(tilemap, true)) {\n const extent = isTilemapLike(component) ? tilemapBox(component) : null;\n if (extent !== null) {\n box = union(box, extent);\n }\n }\n }\n return box;\n}\n\n/**\n * A tilemap's world rectangle: from its entity's origin, its widest and tallest layer in cells.\n *\n * @param map - The tilemap.\n * @returns The rectangle, or `null` before the map has loaded.\n */\nfunction tilemapBox(map: TilemapLike): Box2D | null {\n let columns = 0;\n let rows = 0;\n for (let layer = 0; layer < map.layerCount; layer += 1) {\n const size = map.layerSize(layer);\n columns = Math.max(columns, size.x);\n rows = Math.max(rows, size.y);\n }\n if (map.cellSize <= 0 || columns === 0 || rows === 0) {\n return null;\n }\n const origin = map.entity.transform.position;\n return {\n minX: origin.x,\n minY: origin.y,\n maxX: origin.x + columns * map.cellSize,\n maxY: origin.y + rows * map.cellSize,\n };\n}\n\n/**\n * The highest-priority enabled `Camera2D` of a scene instance: the camera the level is played through.\n *\n * @param app - The app.\n * @param scene - The document's scene instance.\n * @returns The camera, or `null`.\n */\nexport function levelCamera2D(app: App, scene: SceneInstance | null): Camera2DLike | null {\n const type = componentTypeOf(app, CAMERA_2D_TYPE);\n if (type === null || scene === null) {\n return null;\n }\n let best: Camera2DLike | null = null;\n for (const camera of app.world.components(type)) {\n if (isCamera2DLike(camera) && camera.entity.scene === scene && camera.isEnabledInHierarchy) {\n if (best === null || camera.priority > best.priority) {\n best = camera;\n }\n }\n }\n return best;\n}\n\n/**\n * The editor camera a scene is made for: 2D when the project draws sprites only\n * (`twoD.mode: \"sprite\"`, which skips the 3D pass), or when the scene's cameras are all `Camera2D`\n * and it has at least one; 3D otherwise, and always without `@ignifx/2d`.\n *\n * @param app - The app, after the scene opened (a scene file can override `twoD.mode`).\n * @param scene - The document's scene instance.\n * @returns The mode.\n */\nexport function sceneViewMode(app: App, scene: SceneInstance | null): ViewMode {\n const twoD = twoDServiceOf(app);\n if (twoD === null) {\n return ViewMode.threeD;\n }\n if (twoD.mode === \"sprite\") {\n return ViewMode.twoD;\n }\n const camera2D = componentTypeOf(app, CAMERA_2D_TYPE);\n const inScene = (component: Component): boolean => component.entity.scene === scene;\n const has2D = camera2D !== null && app.world.components(camera2D).some(inScene);\n const has3D = app.world.components(Camera).some(inScene);\n return has2D && !has3D ? ViewMode.twoD : ViewMode.threeD;\n}\n","/**\n * The scene view's 2D editor camera (S0.2 §5): a script on the editor camera's entity that, while\n * the view is in 2D mode, drives an editor-owned `Camera2D` that outranks the level's, and turns\n * the 3D editor camera into a matching orthographic camera looking down +Z at the 2D plane, so\n * the gizmo overlay and the 3D picker see what the sprites show. The level's own `Camera2D` is\n * never touched.\n */\n\nimport { Script } from \"@ignifx/core\";\nimport { setCapture } from \"./editor-camera.js\";\nimport {\n DEFAULT_PIXELS_PER_UNIT,\n fitView,\n orthographicSizeFor,\n screenToWorld2D,\n stepZoom,\n zoomAbout,\n} from \"./view-2d.js\";\nimport type { PointerClaims, ViewClick } from \"./editor-camera.js\";\nimport type { Box2D, Camera2DLike, View2D } from \"./view-2d.js\";\nimport type { Camera, ScriptCallbacks } from \"@ignifx/core\";\n\n/** How far in front of the 2D plane the orthographic eye sits, in metres (it looks along +Z). */\nexport const EYE_DISTANCE_2D = 500;\n\n/** How far a press may move, in CSS pixels, and still be a click. */\nconst CLICK_SLOP_PX = 4;\n\n/** How much wheel travel, in pixels, makes one zoom step; a mouse notch is about 100. */\nconst WHEEL_STEP_PX = 50;\n\n/** The gesture the current pointer press drives. */\ntype Gesture2D = \"none\" | \"click\" | \"pan\";\n\n/**\n * Pans and zooms the 2D view on DOM pointer events, and frames what it is asked to.\n *\n * @remarks\n * Middle drag, right drag, and left drag with Space held pan; the wheel zooms in pixel steps about\n * the cursor; a left click is reported to `onClick`. A press on a gizmo handle is left to the\n * gizmo, by the same rule as the 3D camera (S0.2 §4.2). It does nothing until\n * {@link EditorCamera2D.activate}.\n */\nexport class EditorCamera2D extends Script implements ScriptCallbacks {\n /** The type id; the host leaves it out of the schemas it reports. */\n static typeId = \"ignifx-editor/EditorCamera2D\";\n\n /** The scene view runs in edit mode, where only these scripts get callbacks. */\n static runInEditMode = true;\n\n /** The world x at the view's centre, in metres. */\n centerX = 0;\n\n /** The world y at the view's centre, in metres. */\n centerY = 0;\n\n /** Screen pixels per layer pixel, as `Camera2D.zoom`. */\n zoom = 1;\n\n /**\n * Reads the layer pixels per metre: the project's `twoD.pixelsPerUnit`.\n *\n * @returns The pixels per unit.\n */\n pixelsPerUnit: () => number = () => DEFAULT_PIXELS_PER_UNIT;\n\n /** The gizmo dispatcher, once the view has one. */\n claims: PointerClaims | null = null;\n\n /** Receives each click on the view. */\n onClick: ((click: ViewClick) => void) | null = null;\n\n #active = false;\n\n #eye: Camera | null = null;\n\n #camera2D: Camera2DLike | null = null;\n\n #canvas: HTMLCanvasElement | null = null;\n\n #gesture: Gesture2D = \"none\";\n\n #pointer = -1;\n\n #lastX = 0;\n\n #lastY = 0;\n\n #downX = 0;\n\n #downY = 0;\n\n #moved = false;\n\n #space = false;\n\n #wheel = 0;\n\n /** Whether the entity holds the 2D pose since the last {@link EditorCamera2D.activate}. */\n #posed = false;\n\n readonly #onPointerDown = (event: PointerEvent): void => {\n if (!this.#active || this.#pointer !== -1) {\n return;\n }\n this.#downX = event.offsetX;\n this.#downY = event.offsetY;\n this.#lastX = event.clientX;\n this.#lastY = event.clientY;\n this.#moved = false;\n if (event.button === 0) {\n this.#gesture = this.#space ? \"pan\" : this.claims?.pointerState().interacting === true ? \"none\" : \"click\";\n } else if (event.button === 1 || event.button === 2) {\n this.#gesture = \"pan\";\n event.preventDefault();\n } else {\n return;\n }\n this.#pointer = event.pointerId;\n setCapture(this.#canvas, event.pointerId, true);\n };\n\n readonly #onPointerMove = (event: PointerEvent): void => {\n if (event.pointerId !== this.#pointer) {\n return;\n }\n const dx = event.clientX - this.#lastX;\n const dy = event.clientY - this.#lastY;\n this.#lastX = event.clientX;\n this.#lastY = event.clientY;\n if (Math.hypot(event.offsetX - this.#downX, event.offsetY - this.#downY) > CLICK_SLOP_PX) {\n this.#moved = true;\n }\n if (this.#gesture === \"pan\") {\n const metresPerCssPixel = this.#backingRatio() / (this.zoom * this.pixelsPerUnit());\n this.centerX -= dx * metresPerCssPixel;\n this.centerY += dy * metresPerCssPixel;\n this.apply();\n }\n };\n\n readonly #onPointerUp = (event: PointerEvent): void => {\n if (event.pointerId !== this.#pointer) {\n return;\n }\n setCapture(this.#canvas, event.pointerId, false);\n this.#pointer = -1;\n const gesture = this.#gesture;\n this.#gesture = \"none\";\n if (event.button === 0 && gesture === \"click\" && !this.#moved && this.claims?.pointerState().dragging !== true) {\n this.onClick?.({\n x: event.offsetX,\n y: event.offsetY,\n toggle: event.shiftKey || event.ctrlKey || event.metaKey,\n });\n }\n };\n\n readonly #onWheel = (event: WheelEvent): void => {\n if (!this.#active) {\n return;\n }\n event.preventDefault();\n this.#wheel += event.deltaY;\n if (Math.abs(this.#wheel) < WHEEL_STEP_PX) {\n return;\n }\n const direction = this.#wheel < 0 ? 1 : -1;\n this.#wheel = 0;\n const ratio = this.#backingRatio();\n this.zoomTo(stepZoom(this.zoom, direction), event.offsetX * ratio, event.offsetY * ratio);\n };\n\n readonly #onKeyDown = (event: KeyboardEvent): void => {\n if (event.code === \"Space\") {\n this.#space = true;\n }\n };\n\n readonly #onKeyUp = (event: KeyboardEvent): void => {\n if (event.code === \"Space\") {\n this.#space = false;\n }\n };\n\n /**\n * Gives the camera the components it drives: the 3D editor camera, and the editor's own\n * `Camera2D` when the project has `@ignifx/2d`.\n *\n * @param eye - The 3D editor camera, on this script's entity.\n * @param camera2D - The editor's `Camera2D`, on this script's entity, or `null`.\n */\n attach(eye: Camera, camera2D: Camera2DLike | null): void {\n this.#eye = eye;\n this.#camera2D = camera2D;\n }\n\n /**\n * Whether the view is in 2D mode.\n *\n * @returns True between {@link EditorCamera2D.activate} and {@link EditorCamera2D.deactivate}.\n */\n get active(): boolean {\n return this.#active;\n }\n\n /** Enters 2D mode: enables the editor's `Camera2D` and makes the 3D editor camera orthographic. */\n activate(): void {\n this.#active = true;\n // The 3D camera left the entity turned; the next apply writes the pose whatever it is.\n this.#posed = false;\n if (this.#camera2D !== null) {\n this.#camera2D.enabled = true;\n }\n if (this.#eye !== null) {\n this.#eye.projection = \"orthographic\";\n }\n this.apply();\n }\n\n /** Leaves 2D mode: the level's cameras draw the sprites again, and the 3D camera is perspective. */\n deactivate(): void {\n this.#active = false;\n this.#pointer = -1;\n this.#gesture = \"none\";\n if (this.#camera2D !== null) {\n this.#camera2D.enabled = false;\n }\n if (this.#eye !== null) {\n this.#eye.projection = \"perspective\";\n }\n }\n\n /**\n * Starts listening to a canvas's pointer, wheel and Space key events.\n *\n * @param canvas - The scene view's canvas.\n */\n bind(canvas: HTMLCanvasElement): void {\n this.#canvas = canvas;\n canvas.addEventListener(\"pointerdown\", this.#onPointerDown);\n canvas.addEventListener(\"pointermove\", this.#onPointerMove);\n canvas.addEventListener(\"pointerup\", this.#onPointerUp);\n canvas.addEventListener(\"pointercancel\", this.#onPointerUp);\n canvas.addEventListener(\"wheel\", this.#onWheel, { passive: false });\n canvas.ownerDocument.addEventListener(\"keydown\", this.#onKeyDown);\n canvas.ownerDocument.addEventListener(\"keyup\", this.#onKeyUp);\n }\n\n /** Stops listening. */\n onDestroy(): void {\n const canvas = this.#canvas;\n if (canvas === null) {\n return;\n }\n canvas.removeEventListener(\"pointerdown\", this.#onPointerDown);\n canvas.removeEventListener(\"pointermove\", this.#onPointerMove);\n canvas.removeEventListener(\"pointerup\", this.#onPointerUp);\n canvas.removeEventListener(\"pointercancel\", this.#onPointerUp);\n canvas.removeEventListener(\"wheel\", this.#onWheel);\n canvas.ownerDocument.removeEventListener(\"keydown\", this.#onKeyDown);\n canvas.ownerDocument.removeEventListener(\"keyup\", this.#onKeyUp);\n this.#canvas = null;\n }\n\n /**\n * What the view shows now.\n *\n * @returns The centre, zoom, pixels per unit and backing-store size.\n */\n view(): View2D {\n return {\n centerX: this.centerX,\n centerY: this.centerY,\n zoom: this.zoom,\n pixelsPerUnit: this.pixelsPerUnit(),\n widthPx: Math.max(1, this.#canvas?.width ?? 1),\n heightPx: Math.max(1, this.#canvas?.height ?? 1),\n };\n }\n\n /**\n * The world point under a backing-store pixel.\n *\n * @param x - The pixel x.\n * @param y - The pixel y.\n * @returns The point, in metres, +Y up.\n */\n screenToWorld(x: number, y: number): { readonly x: number; readonly y: number } {\n return screenToWorld2D(this.view(), x, y);\n }\n\n /**\n * Shows a world rectangle: centred, at the zoom that fits it with a margin.\n *\n * @param box - The rectangle, in metres.\n */\n frame(box: Box2D): void {\n const view = this.view();\n const fit = fitView(box, view.widthPx, view.heightPx, view.pixelsPerUnit);\n this.centerX = fit.centerX;\n this.centerY = fit.centerY;\n this.zoom = fit.zoom;\n this.apply();\n }\n\n /**\n * Changes the zoom about a backing-store pixel, keeping the world point under it in place.\n *\n * @param zoom - The new zoom.\n * @param x - The pixel x.\n * @param y - The pixel y.\n */\n zoomTo(zoom: number, x: number, y: number): void {\n const centre = zoomAbout(this.view(), x, y, zoom);\n this.centerX = centre.centerX;\n this.centerY = centre.centerY;\n this.zoom = zoom;\n this.apply();\n }\n\n /** Keeps the shown size in step with the canvas, which can be resized at any time. */\n update(): void {\n if (this.#active) {\n this.apply();\n }\n }\n\n /**\n * Writes the view onto the entity and the two cameras: the entity sits on the view's centre,\n * {@link EYE_DISTANCE_2D} in front of the plane, looking along +Z with +Y up, so its x and y are\n * the `Camera2D`'s centre and its orthographic half-height is the `Camera2D`'s.\n */\n apply(): void {\n if (!this.#active) {\n return;\n }\n const view = this.view();\n const size = orthographicSizeFor(view.zoom, view.heightPx, view.pixelsPerUnit);\n const position = this.transform.localPosition;\n // Called every frame; an unchanged pose is not rewritten, so the transform stays clean.\n if (!this.#posed || position.x !== this.centerX || position.y !== this.centerY) {\n position.set(this.centerX, this.centerY, -EYE_DISTANCE_2D);\n this.transform.lookAt({ x: this.centerX, y: this.centerY, z: 0 });\n this.#posed = true;\n }\n if (this.#eye !== null && this.#eye.orthographicSize !== size) {\n this.#eye.orthographicSize = size;\n }\n if (this.#camera2D !== null && this.#camera2D.orthographicSize !== size) {\n this.#camera2D.orthographicSize = size;\n }\n }\n\n /**\n * The canvas's backing pixels per CSS pixel.\n *\n * @returns `canvas.width / canvas.clientWidth`, or 1 without a laid-out canvas.\n */\n #backingRatio(): number {\n const canvas = this.#canvas;\n return canvas === null || canvas.clientWidth <= 0 ? 1 : canvas.width / canvas.clientWidth;\n }\n}\n","/**\n * `applyOps`: the thirteen scene ops of protocol 0.3, applied to the open document's live world.\n *\n * Each op changes the world the way the editor's `applyOp` changes the document, so that a mirror\n * that started exact stays exact: `readBack` then returns the document's own records. An op that\n * the world disagrees with fails with one of editor-core's codes; the host does not roll back,\n * because the editor reopens the scene after any failure.\n */\n\nimport {\n addComponentFromRecord,\n createSceneAsset,\n decodeValue,\n encodeValue,\n instantiateScene,\n isIgnifxError,\n loadSceneDependencies,\n parseOverridePath,\n SCENE_FILE_FORMAT,\n SCENE_FORMAT_VERSION,\n} from \"@ignifx/core\";\nimport { ApplyOpFailureCode } from \"../protocol/index.js\";\nimport { assignProps, copyJson } from \"./document.js\";\nimport type { DocumentIndex, DocumentMirror } from \"./document.js\";\nimport type {\n AddComponentOp,\n ApplyOpFailure,\n ApplyOpsParams,\n ApplyOpsResult,\n CreateEntityOp,\n InstantiateOp,\n JsonPath,\n RemoveOverrideOp,\n ReparentOp,\n SceneOp,\n SetEntityFieldOp,\n SetOverrideOp,\n SetPropOp,\n SetSceneSettingOp,\n SetTransformOp,\n} from \"../protocol/index.js\";\nimport type {\n App,\n Component,\n Entity,\n FieldDefinition,\n JsonObject,\n JsonValue,\n ReferenceEncoder,\n SceneFile,\n SceneFileComponent,\n SceneFileEntity,\n SceneFileInstance,\n SceneFileOverride,\n} from \"@ignifx/core\";\n\n/** The address the subtrees ops build are named by, in the engine's diagnostics. */\nconst SUBTREE_ADDRESS = \"memory:scene/editor-op\";\n\n/** Why one op failed, as `applyOps` reports it. */\nexport class OpFailure extends Error {\n /** The failure code. */\n readonly code: ApplyOpFailureCode;\n\n /** The engine's diagnostic code, when there is one. */\n readonly diagnostic: string | null;\n\n /**\n * Creates the failure.\n *\n * @param code - The failure code.\n * @param message - An actionable sentence.\n * @param diagnostic - The engine's `IGX-` code, if any.\n */\n constructor(code: ApplyOpFailureCode, message: string, diagnostic: string | null = null) {\n super(message);\n this.name = \"OpFailure\";\n this.code = code;\n this.diagnostic = diagnostic;\n }\n}\n\n/** What applying ops needs: the app and the open document. */\ninterface OpContext {\n /** The scene view's app. */\n readonly app: App;\n /** The open document. */\n readonly mirror: DocumentMirror;\n}\n\n/**\n * Applies one command's ops in order, never stopping at a failure.\n *\n * @param app - The scene view's app.\n * @param mirror - The open document.\n * @param params - The ops and the command they belong to.\n * @returns How many applied, and the failures in order.\n */\nexport async function applyOps(app: App, mirror: DocumentMirror, params: ApplyOpsParams): Promise<ApplyOpsResult> {\n const context: OpContext = { app, mirror };\n const failures: ApplyOpFailure[] = [];\n let applied = 0;\n for (const [index, op] of params.ops.entries()) {\n try {\n // Ops apply in order, each against the world the previous one left.\n // oxlint-disable-next-line no-await-in-loop -- see above\n await applyOp(context, op);\n applied += 1;\n } catch (error) {\n const failure = toFailure(index, error);\n failures.push(failure);\n app.log.warn(\n `applyOps ${params.commandId} (${params.commandName}): op ${String(index)} (${op.op}) failed: ${failure.code}: ${failure.message}`,\n );\n } finally {\n mirror.invalidate();\n }\n }\n return { applied, failures };\n}\n\n/**\n * Turns whatever an op threw into its failure record.\n *\n * @param index - The op's index.\n * @param error - What it threw.\n * @returns The failure.\n */\nfunction toFailure(index: number, error: unknown): ApplyOpFailure {\n if (error instanceof OpFailure) {\n return {\n index,\n code: error.code,\n message: error.message,\n ...(error.diagnostic === null ? {} : { diagnostic: error.diagnostic }),\n };\n }\n const message = error instanceof Error ? error.message : String(error);\n return {\n index,\n code: ApplyOpFailureCode.engineError,\n message,\n ...(isIgnifxError(error) ? { diagnostic: error.code } : {}),\n };\n}\n\n/**\n * Applies one op.\n *\n * @param context - The app and the document.\n * @param op - The op.\n */\nasync function applyOp(context: OpContext, op: SceneOp): Promise<void> {\n switch (op.op) {\n case \"createEntity\": {\n await createEntity(context, op);\n return;\n }\n case \"destroyEntity\": {\n requireEntity(context, op.entity).destroyImmediate();\n return;\n }\n case \"reparent\": {\n reparent(context, op);\n return;\n }\n case \"reorder\": {\n const entity = requireEntity(context, op.entity);\n placeAmongSiblings(context, entity, op.index);\n return;\n }\n case \"setEntityField\": {\n setEntityField(context, op);\n return;\n }\n case \"setTransform\": {\n setTransform(requireEntity(context, op.entity), op);\n return;\n }\n case \"addComponent\": {\n await addComponent(context, op);\n return;\n }\n case \"removeComponent\": {\n const component = requireComponent(context, op.component);\n component.entity.removeComponent(component);\n return;\n }\n case \"setProp\": {\n await setProp(context, op);\n return;\n }\n case \"setSceneSetting\": {\n setSceneSetting(context, op);\n return;\n }\n case \"instantiate\": {\n await instantiate(context, op);\n return;\n }\n case \"setOverride\": {\n await setOverride(context, op);\n return;\n }\n case \"removeOverride\": {\n await removeOverride(context, op);\n return;\n }\n default: {\n throw new OpFailure(ApplyOpFailureCode.invalidOp, \"Not an op of the scene op vocabulary.\");\n }\n }\n}\n\n// ---------------------------------------------------------------------------------------------\n// Lookups\n// ---------------------------------------------------------------------------------------------\n\n/**\n * The document's index; the scene methods only call `applyOps` with a document open.\n *\n * @param context - The app and the document.\n * @returns The index.\n */\nfunction indexOf(context: OpContext): DocumentIndex {\n const index = context.mirror.index();\n if (index === null) {\n throw new OpFailure(ApplyOpFailureCode.unknownEntity, \"No scene is open.\");\n }\n return index;\n}\n\n/**\n * A document entity by uid.\n *\n * @param context - The app and the document.\n * @param uid - The uid.\n * @returns The entity.\n */\nfunction requireEntity(context: OpContext, uid: string): Entity {\n const entity = indexOf(context).entities.get(uid);\n if (entity === undefined || entity.isDestroyed) {\n throw new OpFailure(ApplyOpFailureCode.unknownEntity, `No entity ${uid} is in the open scene.`);\n }\n return entity;\n}\n\n/**\n * A document component by uid.\n *\n * @param context - The app and the document.\n * @param uid - The uid.\n * @returns The component.\n */\nfunction requireComponent(context: OpContext, uid: string): Component {\n const component = indexOf(context).components.get(uid);\n if (component === undefined || component.isDestroyed) {\n throw new OpFailure(ApplyOpFailureCode.unknownComponent, `No component ${uid} is in the open scene.`);\n }\n return component;\n}\n\n/**\n * A parent named by an op: a document entity, or `null` for the scene's roots.\n *\n * @param context - The app and the document.\n * @param uid - The parent's uid, or `null`.\n * @returns The parent entity, or `null`.\n */\nfunction requireParent(context: OpContext, uid: string | null): Entity | null {\n if (uid === null) {\n return null;\n }\n const parent = indexOf(context).entities.get(uid);\n if (parent === undefined || parent.isDestroyed) {\n throw new OpFailure(ApplyOpFailureCode.invalidParent, `The parent ${uid} is not in the open scene.`);\n }\n return parent;\n}\n\n/**\n * The document entities among a parent's children, or among the scene's roots.\n *\n * @param context - The app and the document.\n * @param parent - The parent, or `null` for the roots.\n * @param except - An entity to leave out, the one being moved.\n * @returns The document siblings, in order.\n */\nfunction documentSiblings(context: OpContext, parent: Entity | null, except: Entity | null): Entity[] {\n const index = indexOf(context);\n const siblings = parent === null ? (context.mirror.scene?.roots ?? []) : parent.children;\n return siblings.filter((sibling) => sibling !== except && index.entities.get(sibling.uid) === sibling);\n}\n\n/**\n * Checks an insertion index against the document siblings it positions among.\n *\n * @param index - The index, or `undefined` for the end.\n * @param count - How many document siblings there are, the moved entity left out.\n * @returns The index to use.\n */\nfunction checkIndex(index: number | undefined, count: number): number {\n if (index === undefined) {\n return count;\n }\n if (index > count) {\n throw new OpFailure(\n ApplyOpFailureCode.invalidIndex,\n `Index ${String(index)} is past the end of a list of ${String(count)}.`,\n );\n }\n return index;\n}\n\n/**\n * Moves an entity to an index among its document siblings. Members of an instanced scene under the\n * same parent keep their places; the document does not list them.\n *\n * @param context - The app and the document.\n * @param entity - The entity, already under its final parent.\n * @param index - Its index among the document siblings, or `undefined` for the end.\n */\nfunction placeAmongSiblings(context: OpContext, entity: Entity, index: number | undefined): void {\n const others = documentSiblings(context, entity.parent, entity);\n const at = checkIndex(index, others.length);\n const all = (entity.parent === null ? (context.mirror.scene?.roots ?? []) : entity.parent.children).filter(\n (sibling) => sibling !== entity,\n );\n const before = others[at];\n const last = others.at(-1);\n const target = before === undefined ? (last === undefined ? all.length : all.indexOf(last) + 1) : all.indexOf(before);\n entity.setSiblingIndex(target);\n}\n\n// ---------------------------------------------------------------------------------------------\n// Structure\n// ---------------------------------------------------------------------------------------------\n\n/**\n * Checks that every component type a set of records names is registered, before anything is built.\n *\n * @param context - The app and the document.\n * @param components - The component records.\n */\nfunction requireTypes(context: OpContext, components: readonly SceneFileComponent[]): void {\n for (const component of components) {\n if (context.app.world.registry.get(component.type) === null) {\n throw new OpFailure(\n ApplyOpFailureCode.engineError,\n `The component type \"${component.type}\" is not registered; register it with app.registerComponents or check its typeId.`,\n \"IGX-0307\",\n );\n }\n }\n}\n\n/**\n * Checks that new entity and component uids are free in the world and in the document.\n *\n * @param context - The app and the document.\n * @param records - The new entity records.\n */\nfunction requireFreeUids(context: OpContext, records: readonly SceneFileEntity[]): void {\n const index = indexOf(context);\n const seen = new Set<string>();\n const claim = (uid: string, taken: boolean): void => {\n if (taken || seen.has(uid)) {\n throw new OpFailure(ApplyOpFailureCode.duplicateUid, `The uid ${uid} is already in use.`);\n }\n seen.add(uid);\n };\n for (const record of records) {\n claim(record.uid, context.app.world.getEntity(record.uid) !== null);\n for (const component of record.components ?? []) {\n claim(component.uid, index.components.has(component.uid));\n }\n }\n}\n\n/**\n * Tells whether JSON holds an entity or component reference anywhere.\n *\n * @param value - The JSON.\n * @returns True when a `$entity` or `$component` object is in it.\n */\nfunction hasReferences(value: JsonValue | undefined): boolean {\n const array = asJsonArray(value);\n if (array !== null) {\n return array.some((item) => hasReferences(item));\n }\n const object = asJsonObject(value);\n return (\n object !== null &&\n (\"$entity\" in object || \"$component\" in object || Object.values(object).some((item) => hasReferences(item)))\n );\n}\n\n/**\n * Builds a subtree from entity records under a live parent, with the records' uids, loading the\n * assets they reference first; then resolves references to the rest of the document, which a\n * subtree built on its own cannot see.\n *\n * @param context - The app and the document.\n * @param records - The subtree's records, parents first; the first is its root.\n * @param parent - The live parent, or `null` for a root of the scene.\n * @param index - The root's index among its document siblings, or `undefined` for the end.\n * @returns The subtree's root.\n */\nasync function buildSubtree(\n context: OpContext,\n records: readonly SceneFileEntity[],\n parent: Entity | null,\n index: number | undefined,\n): Promise<Entity> {\n const [top, ...rest] = records;\n const scene = context.mirror.scene;\n if (top === undefined || scene === null) {\n throw new OpFailure(ApplyOpFailureCode.invalidOp, \"There is nothing to build.\");\n }\n const file: SceneFile = {\n format: SCENE_FILE_FORMAT,\n formatVersion: SCENE_FORMAT_VERSION,\n name: top.name,\n entities: [{ ...top, parent: null }, ...rest],\n };\n const dependencies = await loadSceneDependencies(context.app.assets, file);\n context.mirror.retain(dependencies);\n const asset = await createSceneAsset(SUBTREE_ADDRESS, file, dependencies);\n const built = instantiateScene(context.app.world, asset, { scene, ...(parent === null ? {} : { parent }) });\n context.mirror.invalidate();\n const references = context.mirror.decoder(built.remap);\n for (const record of file.entities) {\n for (const component of record.components ?? []) {\n const live = built.remap.component(component.uid);\n if (live !== null && hasReferences(component.props)) {\n assignProps(live, component.props ?? {}, references);\n }\n }\n }\n const root = built.roots[0] ?? built.remap.entity(top.uid);\n if (root === null) {\n throw new OpFailure(ApplyOpFailureCode.engineError, `The engine built no entity for ${top.uid}.`);\n }\n placeAmongSiblings(context, root, index);\n return root;\n}\n\n/**\n * Applies `createEntity`: the entity and its descendants, with their uids and components.\n *\n * @param context - The app and the document.\n * @param op - The op.\n */\nasync function createEntity(context: OpContext, op: CreateEntityOp): Promise<void> {\n const records = [op.entity, ...(op.descendants ?? [])];\n const parent = requireParent(context, op.entity.parent);\n checkIndex(op.index, documentSiblings(context, parent, null).length);\n requireFreeUids(context, records);\n const inside = new Set([op.entity.uid]);\n for (const record of op.descendants ?? []) {\n if (record.parent === null || !inside.has(record.parent)) {\n throw new OpFailure(\n ApplyOpFailureCode.invalidParent,\n `${record.uid} must be the child of an entity created before it in the same op.`,\n );\n }\n inside.add(record.uid);\n }\n const components = records.flatMap((record) => record.components ?? []);\n requireTypes(context, components);\n await buildSubtree(context, records, parent, op.index);\n context.mirror.recordComponents(components);\n context.mirror.recordInstances(records);\n}\n\n/**\n * Applies `reparent`: the new parent, keeping the local transform, at an index.\n *\n * @param context - The app and the document.\n * @param op - The op.\n */\nfunction reparent(context: OpContext, op: ReparentOp): void {\n const entity = requireEntity(context, op.entity);\n const parent = requireParent(context, op.parent);\n if (parent !== null && (parent === entity || parent.isDescendantOf(entity))) {\n throw new OpFailure(ApplyOpFailureCode.invalidParent, `${entity.name} cannot move under its own subtree.`);\n }\n checkIndex(op.index, documentSiblings(context, parent, entity).length);\n entity.setParent(parent, { worldPositionStays: false });\n placeAmongSiblings(context, entity, op.index);\n}\n\n/**\n * Applies `setEntityField`.\n *\n * @param context - The app and the document.\n * @param op - The op.\n */\nfunction setEntityField(context: OpContext, op: SetEntityFieldOp): void {\n const entity = requireEntity(context, op.entity);\n switch (op.field) {\n case \"name\": {\n entity.name = op.value;\n return;\n }\n case \"active\": {\n entity.active = op.value;\n return;\n }\n case \"static\": {\n entity.isStatic = op.value;\n return;\n }\n case \"layer\": {\n const layer = context.app.world.layers.indexOf(op.value);\n if (layer < 0) {\n throw new OpFailure(\n ApplyOpFailureCode.invalidValue,\n `\"${op.value}\" is not a layer of this project.`,\n \"IGX-0303\",\n );\n }\n entity.layer = layer;\n return;\n }\n case \"tags\": {\n entity.tags.clear();\n for (const tag of op.value) {\n entity.tags.add(tag);\n }\n return;\n }\n default: {\n throw new OpFailure(ApplyOpFailureCode.invalidOp, \"Not an entity field.\");\n }\n }\n}\n\n/**\n * Applies `setTransform`: the local position, rotation and scale. `before` is ignored.\n *\n * @param entity - The entity.\n * @param op - The op.\n */\nfunction setTransform(entity: Entity, op: SetTransformOp): void {\n const { position, rotation, scale } = op.after;\n const transform = entity.transform;\n transform.localPosition.set(position[0], position[1], position[2]);\n transform.localRotation.set(rotation[0], rotation[1], rotation[2], rotation[3]);\n transform.localScale.set(scale[0], scale[1], scale[2]);\n}\n\n/**\n * The number of components an entity lists in the document.\n *\n * @param context - The app and the document.\n * @param entity - The entity.\n * @returns The length of its record's `components`.\n */\nfunction documentComponentCount(context: OpContext, entity: Entity): number {\n return indexOf(context).records.get(entity.uid)?.components?.length ?? 0;\n}\n\n/**\n * Loads the assets a value references, and keeps them for the document.\n *\n * @param context - The app and the document.\n * @param props - The JSON that may name assets.\n */\nasync function loadAssets(context: OpContext, props: JsonValue | undefined): Promise<void> {\n if (props === undefined) {\n return;\n }\n // The scene loader's own walk, over a one-entity file that carries the value as props.\n const file: SceneFile = {\n format: SCENE_FILE_FORMAT,\n formatVersion: SCENE_FORMAT_VERSION,\n name: \"props\",\n entities: [\n {\n uid: \"props\",\n name: \"props\",\n parent: null,\n transform: { position: [0, 0, 0], rotation: [0, 0, 0, 1], scale: [1, 1, 1] },\n components: [{ uid: \"props\", type: \"props\", props: { value: props } }],\n },\n ],\n };\n context.mirror.retain(await loadSceneDependencies(context.app.assets, file));\n}\n\n/**\n * Applies `addComponent`: the registered type, with its uid, `enabled` and decoded props, at an index.\n *\n * @param context - The app and the document.\n * @param op - The op.\n */\nasync function addComponent(context: OpContext, op: AddComponentOp): Promise<void> {\n const entity = requireEntity(context, op.entity);\n if (indexOf(context).components.has(op.component.uid)) {\n throw new OpFailure(ApplyOpFailureCode.duplicateUid, `The uid ${op.component.uid} is already in use.`);\n }\n checkIndex(op.index, documentComponentCount(context, entity));\n requireTypes(context, [op.component]);\n await loadAssets(context, op.component.props);\n const { issues } = addComponentFromRecord(entity, op.component, {\n ...(op.index === undefined ? {} : { index: op.index }),\n references: context.mirror.decoder(),\n });\n context.mirror.recordComponents([op.component]);\n const first = issues[0];\n if (first !== undefined) {\n throw new OpFailure(ApplyOpFailureCode.invalidValue, first.message, first.code);\n }\n}\n\n/**\n * Applies `instantiate`: an instance root, built from its scene asset.\n *\n * @param context - The app and the document.\n * @param op - The op.\n */\nasync function instantiate(context: OpContext, op: InstantiateOp): Promise<void> {\n const parent = requireParent(context, op.parent);\n checkIndex(op.index, documentSiblings(context, parent, null).length);\n const record: SceneFileEntity = {\n uid: op.entity,\n name: op.name,\n parent: op.parent,\n transform: op.transform,\n instance: op.instance,\n };\n requireFreeUids(context, [record]);\n await buildSubtree(context, [record], parent, op.index);\n context.mirror.recordInstances([record]);\n}\n\n// ---------------------------------------------------------------------------------------------\n// Props and settings\n// ---------------------------------------------------------------------------------------------\n\n/**\n * The uid of a referenced entity or component.\n *\n * @param target - The field's value.\n * @returns Its uid, or `null` for anything without one.\n */\nfunction uidOf(target: unknown): string | null {\n const uid: unknown = typeof target === \"object\" && target !== null ? Reflect.get(target, \"uid\") : null;\n return typeof uid === \"string\" ? uid : null;\n}\n\n/**\n * Reads a schema field's current value as JSON, references written as the uids they point at.\n *\n * @param field - The field.\n * @param value - The live value.\n * @returns The JSON.\n */\nfunction encodeLive(field: FieldDefinition<unknown>, value: unknown): JsonValue {\n const references: ReferenceEncoder = { entityUid: uidOf, componentUid: uidOf };\n return encodeValue(field, value, references);\n}\n\n/**\n * Narrows JSON to an object. `Array.isArray` does not remove a readonly array from the union, so the\n * discrimination lives here once.\n *\n * @param value - The JSON.\n * @returns The object, or `null` for anything else.\n */\nfunction asJsonObject(value: JsonValue | undefined): JsonObject | null {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return null;\n }\n // The guard above leaves exactly `JsonObject` of the `JsonValue` union.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return value as JsonObject;\n}\n\n/**\n * Narrows JSON to an array.\n *\n * @param value - The JSON.\n * @returns The array, or `null`.\n */\nfunction asJsonArray(value: JsonValue | undefined): readonly JsonValue[] | null {\n return Array.isArray(value) ? value : null;\n}\n\n/**\n * Returns JSON with the value at a path set, or removed, leaving the input unchanged.\n *\n * @param container - The JSON the path starts in.\n * @param path - The steps, at least one: object keys and array indices.\n * @param value - The new value, or `undefined` to remove the key or the array item.\n * @returns The new JSON.\n */\nfunction withValueAt(container: JsonValue, path: JsonPath, value: JsonValue | undefined): JsonValue {\n const [step, ...rest] = path;\n const array = asJsonArray(container);\n if (array !== null && typeof step === \"number\" && step <= array.length) {\n const copy = [...array];\n if (rest.length > 0) {\n const next = copy[step];\n if (next === undefined) {\n throw invalidPath(path);\n }\n copy[step] = withValueAt(next, rest, value);\n } else if (value === undefined) {\n copy.splice(step, 1);\n } else {\n copy[step] = value;\n }\n return copy;\n }\n const object = asJsonObject(container);\n if (object !== null && typeof step === \"string\") {\n if (rest.length > 0) {\n const next = object[step];\n if (next === undefined) {\n throw invalidPath(path);\n }\n return { ...object, [step]: withValueAt(next, rest, value) };\n }\n const others = Object.entries(object).filter(([key]) => key !== step);\n return Object.fromEntries(value === undefined ? others : [...others, [step, value]]);\n }\n throw invalidPath(path);\n}\n\n/**\n * The failure for a path that does not resolve.\n *\n * @param path - The path.\n * @returns The failure.\n */\nfunction invalidPath(path: JsonPath): OpFailure {\n return new OpFailure(ApplyOpFailureCode.invalidPath, `The path ${JSON.stringify(path)} does not resolve.`);\n}\n\n/**\n * Applies `setProp`: the value at a path of a component's props, decoded with the field's schema\n * and assigned, the way the inspector writes a field.\n *\n * @param context - The app and the document.\n * @param op - The op.\n */\nasync function setProp(context: OpContext, op: SetPropOp): Promise<void> {\n const component = requireComponent(context, op.component);\n const schema = context.app.world.registry.describe(component.constructor).schema;\n if (schema === null) {\n throw new OpFailure(ApplyOpFailureCode.invalidPath, `${op.component} has no props.`);\n }\n await loadAssets(context, op.value);\n const references = context.mirror.decoder();\n const [name, ...rest] = op.path;\n if (name === undefined) {\n const props = op.value === undefined ? {} : asJsonObject(op.value);\n if (props === null) {\n throw new OpFailure(ApplyOpFailureCode.invalidValue, \"props must be an object.\");\n }\n rejectIssues(assignProps(component, props, references));\n context.mirror.recordProps(op.component, Object.keys(props));\n return;\n }\n const field = typeof name === \"string\" && Object.hasOwn(schema, name) ? schema[name] : undefined;\n if (typeof name !== \"string\" || field === undefined) {\n throw new OpFailure(ApplyOpFailureCode.invalidPath, `${String(name)} is not a field of ${op.component}.`);\n }\n if (rest.length === 0 && op.value === undefined) {\n Reflect.set(component, name, field.createDefault());\n context.mirror.recordProp(op.component, name, false);\n return;\n }\n const json =\n rest.length > 0 ? withValueAt(encodeLive(field, Reflect.get(component, name)), rest, op.value) : op.value;\n const decoded = decodeValue(field, json ?? null, references);\n rejectIssues(\n decoded.issues.map((issue) => ({\n code: issue.code,\n message: `${op.component}.${name}${issue.path === \"\" ? \"\" : `.${issue.path}`}: ${issue.message}`,\n })),\n );\n Reflect.set(component, name, decoded.value);\n context.mirror.recordProp(op.component, name, true);\n}\n\n/**\n * Fails the op on the first decoding problem: the value the field got is not the document's.\n *\n * @param issues - The problems.\n */\nfunction rejectIssues(issues: readonly { readonly code: string; readonly message: string }[]): void {\n const first = issues[0];\n if (first !== undefined) {\n throw new OpFailure(ApplyOpFailureCode.invalidValue, first.message, first.code);\n }\n}\n\n/**\n * Applies `setSceneSetting`: the value at a path of the scene's settings.\n *\n * @param context - The app and the document.\n * @param op - The op.\n */\nfunction setSceneSetting(context: OpContext, op: SetSceneSettingOp): void {\n const mirror = context.mirror;\n const next = op.path.length === 0 ? (op.value ?? null) : withValueAt(mirror.settings ?? {}, op.path, op.value);\n const settings = next === null ? null : asJsonObject(next);\n if (next !== null && settings === null) {\n throw new OpFailure(ApplyOpFailureCode.invalidValue, \"settings must be an object.\");\n }\n mirror.settings = settings === null ? null : copyJson(settings);\n}\n\n// ---------------------------------------------------------------------------------------------\n// Overrides\n// ---------------------------------------------------------------------------------------------\n\n/** The op of an override. */\ntype OverrideOp = \"replace\" | \"remove\" | \"add\";\n\n/**\n * The kind an override path parses to.\n *\n * @param path - The path.\n * @returns The kind, or `null` when the engine's grammar refuses it.\n */\nfunction overrideKind(path: string): string | null {\n try {\n return parseOverridePath(path).kind;\n } catch {\n return null;\n }\n}\n\n/**\n * The op an override path implies when none is given, as editor-core reads it.\n *\n * @param path - The path.\n * @returns `\"add\"` for a component list, `\"remove\"` for a whole component, else `\"replace\"`.\n */\nfunction impliedOp(path: string): OverrideOp {\n const kind = overrideKind(path);\n return kind === \"componentList\" ? \"add\" : kind === \"component\" ? \"remove\" : \"replace\";\n}\n\n/**\n * The uid of the component an `add` override adds.\n *\n * @param override - The override.\n * @returns The uid, or `null`.\n */\nfunction addedUid(override: SceneFileOverride): string | null {\n const uid = asJsonObject(override.value)?.[\"uid\"];\n return (override.op ?? \"replace\") === \"add\" && typeof uid === \"string\" ? uid : null;\n}\n\n/**\n * Finds an override by editor-core's identity: its path and op, and for a component `add` the\n * added uid.\n *\n * @param overrides - The list.\n * @param path - The path.\n * @param op - The op.\n * @param added - The added uid, for a component `add`.\n * @returns The index, or `-1`.\n */\nfunction findOverride(\n overrides: readonly SceneFileOverride[],\n path: string,\n op: OverrideOp,\n added: string | null,\n): number {\n return overrides.findIndex(\n (candidate) =>\n candidate.path === path &&\n (candidate.op ?? \"replace\") === op &&\n (overrideKind(path) !== \"componentList\" || addedUid(candidate) === added),\n );\n}\n\n/**\n * Rebuilds an instance root's subtree with an edited override list: the live world has no way to\n * re-apply one override, so the root and its document children are serialized, destroyed and built\n * again from the instanced scene with the new list. References from the rest of the document into\n * the rebuilt subtree are resolved again.\n *\n * @param context - The app and the document.\n * @param uid - The instance root.\n * @param edit - Returns the new override list from the current one.\n * @param documentOverrides - Whether the root and the instance roots under it are rebuilt with the\n * override lists the document holds rather than the ones the serializer recomputes from the live\n * members, which a hot reload that changed a default has left stale.\n */\nasync function rebuildInstance(\n context: OpContext,\n uid: string,\n edit: (overrides: readonly SceneFileOverride[]) => readonly SceneFileOverride[],\n documentOverrides = false,\n): Promise<void> {\n const index = indexOf(context);\n const root = requireEntity(context, uid);\n const mirror = context.mirror;\n const withDocumentOverrides = (record: SceneFileEntity): SceneFileEntity => {\n const listed = documentOverrides && record.instance !== undefined ? mirror.overridesOf(record.uid) : null;\n if (listed === null || record.instance === undefined) {\n return record;\n }\n const { scene, hash } = record.instance;\n const instance: SceneFileInstance = {\n scene,\n ...(hash === undefined ? {} : { hash }),\n ...(listed.length === 0 ? {} : { overrides: listed }),\n };\n return { ...record, instance };\n };\n const found = index.records.get(uid);\n const record = found === undefined ? undefined : withDocumentOverrides(found);\n const instance = record?.instance;\n if (record === undefined || instance === undefined) {\n throw new OpFailure(ApplyOpFailureCode.notAnInstance, `${root.name} (${uid}) has no instance entry.`);\n }\n const overrides = edit(instance.overrides ?? []);\n const top: SceneFileEntity = {\n ...record,\n instance: {\n scene: instance.scene,\n ...(instance.hash === undefined ? {} : { hash: instance.hash }),\n ...(overrides.length === 0 ? {} : { overrides }),\n },\n };\n const inside = new Set([uid]);\n const records: SceneFileEntity[] = [top];\n for (const candidate of index.file.entities) {\n if (candidate.parent !== null && inside.has(candidate.parent)) {\n inside.add(candidate.uid);\n records.push(withDocumentOverrides(candidate));\n }\n }\n const insideComponents = new Set(\n records.flatMap((entry_) => (entry_.components ?? []).map((component) => component.uid)),\n );\n const parent = root.parent;\n const at = documentSiblings(context, parent, null).indexOf(root);\n root.destroyImmediate();\n context.mirror.invalidate();\n await buildSubtree(context, records, parent, at);\n mirror.recordInstances(records);\n const references = context.mirror.decoder();\n const rebuilt = indexOf(context);\n for (const outside of index.file.entities) {\n if (inside.has(outside.uid)) {\n continue;\n }\n for (const component of outside.components ?? []) {\n const live = rebuilt.components.get(component.uid);\n if (live !== undefined && pointsInto(component.props, inside, insideComponents)) {\n assignProps(live, component.props ?? {}, references);\n }\n }\n }\n}\n\n/**\n * Rebuilds one instance root from its scene asset's current value, keeping its uid, its record\n * (transform, overrides, components) and its document children, as `setOverride` does: what the\n * host does after a hot reload replaced the scene the root instances, or changed a default its\n * members leave out.\n *\n * @param app - The scene view's app.\n * @param mirror - The open document.\n * @param uid - The instance root.\n * @param documentOverrides - Whether to rebuild with the override lists the document holds rather\n * than the ones the live members read as; `true` after a hot reload changed a default.\n * @throws OpFailure when the uid names no document entity or one without an instance entry.\n */\nexport async function reloadInstance(\n app: App,\n mirror: DocumentMirror,\n uid: string,\n documentOverrides = false,\n): Promise<void> {\n try {\n await rebuildInstance({ app, mirror }, uid, (overrides) => overrides, documentOverrides);\n } finally {\n mirror.invalidate();\n }\n}\n\n/**\n * Tells whether JSON references an entity or component of a set.\n *\n * @param value - The JSON.\n * @param entities - The entity uids.\n * @param components - The component uids.\n * @returns True when a `$entity` or `$component` names one of them.\n */\nfunction pointsInto(\n value: JsonValue | undefined,\n entities: ReadonlySet<string>,\n components: ReadonlySet<string>,\n): boolean {\n const array = asJsonArray(value);\n if (array !== null) {\n return array.some((item) => pointsInto(item, entities, components));\n }\n const object = asJsonObject(value);\n if (object === null) {\n return false;\n }\n const entity = object[\"$entity\"];\n const component = object[\"$component\"];\n return (\n (typeof entity === \"string\" && entities.has(entity)) ||\n (typeof component === \"string\" && components.has(component)) ||\n Object.values(object).some((item) => pointsInto(item, entities, components))\n );\n}\n\n/**\n * Applies `setOverride`: replaces the override with the same identity, or inserts it.\n *\n * @param context - The app and the document.\n * @param op - The op.\n */\nasync function setOverride(context: OpContext, op: SetOverrideOp): Promise<void> {\n const override = op.override;\n if (overrideKind(override.path) === null) {\n throw new OpFailure(\n ApplyOpFailureCode.invalidPath,\n `\"${override.path}\" is not an override path the engine can apply.`,\n \"IGX-0609\",\n );\n }\n await loadAssets(context, override.value);\n await rebuildInstance(context, op.entity, (overrides) => {\n const next = [...overrides];\n const existing = findOverride(next, override.path, override.op ?? \"replace\", addedUid(override));\n if (existing >= 0) {\n if (op.index !== undefined && op.index !== existing) {\n throw new OpFailure(\n ApplyOpFailureCode.invalidIndex,\n `The override already exists at index ${String(existing)}.`,\n );\n }\n next[existing] = override;\n return next;\n }\n next.splice(checkIndex(op.index, next.length), 0, override);\n return next;\n });\n}\n\n/**\n * Applies `removeOverride`.\n *\n * @param context - The app and the document.\n * @param op - The op.\n */\nasync function removeOverride(context: OpContext, op: RemoveOverrideOp): Promise<void> {\n await rebuildInstance(context, op.entity, (overrides) => {\n const next = [...overrides];\n const at = findOverride(next, op.path, op.overrideOp ?? impliedOp(op.path), op.added ?? null);\n if (at < 0) {\n throw new OpFailure(ApplyOpFailureCode.unknownOverride, `The instance has no override at \"${op.path}\".`);\n }\n next.splice(at, 1);\n return next;\n });\n}\n","/**\n * `getSchemas` and `schemasChanged`: every registered component's schema, as the inspector reads\n * it, plus core's file-format entries.\n */\n\nimport { describeRegisteredSchemas, describeSchemas, toJsonSchema, Transform, transformSchema } from \"@ignifx/core\";\nimport type { SchemaDescription, SchemaSet } from \"../protocol/index.js\";\nimport type { App } from \"@ignifx/core\";\n\n/** The `format` core's component entries carry; file formats carry their own name instead. */\nconst COMPONENTS_FORMAT = \"components\";\n\n/**\n * Describes every component class the app's registry holds (engine, extensions and the project's\n * scripts) with core's `describeRegisteredSchemas`, plus the JSON Schema of its `props` and core's\n * file-format entries.\n *\n * @remarks\n * Each field carries its inspector options (`step`, `hidden`, `readonly`, `group`, an asset's\n * `assetType`, a `componentRef`'s `componentType`), and each component its `allowMultiple` and the\n * `package` that registered it, all optional members of protocol 0.3. A component core describes\n * keeps core's title and summary; any other is titled from its type id. The host's own classes are left out: they are not the\n * document's. `ignifx/Transform` is described with core's `transformSchema()` and carries\n * `builtIn`: its fields are each entity's `transform` block, edited with `setTransform`, and it is\n * never added or removed.\n *\n * The set is read from the live registry each time, so a hot reload that adds a field or a script\n * shows in the next `schemasChanged`.\n *\n * @param app - The scene view's app.\n * @param hidden - Type ids to leave out.\n * @returns The set, keyed by type id.\n */\nexport function schemaSet(app: App, hidden: ReadonlySet<string>): SchemaSet {\n const core = describeSchemas();\n const registry = app.world.registry;\n const described = describeRegisteredSchemas(registry, core);\n const schemas: Record<string, SchemaDescription> = {};\n for (const [typeId, type] of registry.registrations()) {\n const description = described[typeId];\n if (hidden.has(typeId) || description === undefined) {\n continue;\n }\n const schema = type === Transform ? transformSchema() : (registry.describe(type).schema ?? {});\n schemas[typeId] = { ...description, propsSchema: toJsonSchema(schema) };\n }\n for (const [id, description] of Object.entries(core)) {\n if (description.format !== COMPONENTS_FORMAT) {\n schemas[id] = description;\n }\n }\n return { schemas };\n}\n","/**\n * `screenshot`'s image encoding: a captured frame scaled to the requested size and written as a\n * PNG or JPEG data URL. It needs a browser's `OffscreenCanvas`, as the capture needs a GPU.\n */\n\nimport type { PixelSize } from \"./view-math.js\";\nimport type { ScreenshotFormat } from \"../protocol/index.js\";\nimport type { RenderCapture } from \"@ignifx/core\";\n\n/** Bytes encoded per `String.fromCharCode` call, to stay under engines' argument limits. */\nconst BASE64_CHUNK = 0x8000;\n\n/**\n * Encodes bytes as base64.\n *\n * @param bytes - The bytes.\n * @returns The base64 text.\n */\nfunction toBase64(bytes: Uint8Array): string {\n let binary = \"\";\n for (let start = 0; start < bytes.length; start += BASE64_CHUNK) {\n binary += String.fromCharCode(...bytes.subarray(start, start + BASE64_CHUNK));\n }\n return btoa(binary);\n}\n\n/**\n * Scales a captured frame to a size and encodes it as a data URL.\n *\n * @param capture - The frame, RGBA8 with the top row first.\n * @param size - The image size.\n * @param format - `\"png\"` or `\"jpeg\"`.\n * @param quality - The JPEG quality, from 0 to 1; ignored for PNG.\n * @returns A `data:image/png;base64,…` or `data:image/jpeg;base64,…` URL.\n * @throws Error when the browser has no 2D canvas context.\n */\nexport async function encodeCapture(\n capture: RenderCapture,\n size: PixelSize,\n format: ScreenshotFormat,\n quality: number,\n): Promise<string> {\n const source = new OffscreenCanvas(capture.width, capture.height);\n const sourceContext = source.getContext(\"2d\");\n const target = new OffscreenCanvas(size.width, size.height);\n const targetContext = target.getContext(\"2d\");\n if (sourceContext === null || targetContext === null) {\n throw new Error(\"This browser has no 2D canvas to encode the screenshot with.\");\n }\n sourceContext.putImageData(new ImageData(new Uint8ClampedArray(capture.data), capture.width, capture.height), 0, 0);\n targetContext.imageSmoothingQuality = \"high\";\n targetContext.drawImage(source, 0, 0, size.width, size.height);\n const type = format === \"png\" ? \"image/png\" : \"image/jpeg\";\n const blob = await target.convertToBlob(format === \"png\" ? { type } : { type, quality });\n return `data:${type};base64,${toBase64(new Uint8Array(await blob.arrayBuffer()))}`;\n}\n","/**\n * `describeSettings`: the project's settings sections, as the editor's settings panel reads them,\n * and the values the app resolved for them.\n */\n\nimport { describeSettings, settingsJsonSchema } from \"@ignifx/core\";\nimport type { JsonObject, JsonValue, SchemaDescription, SettingsSet } from \"../protocol/index.js\";\nimport type { App } from \"@ignifx/core\";\n\n/**\n * Copies a value made of JSON data, leaving out what JSON cannot carry.\n *\n * @param value - The value.\n * @returns The copy, or `undefined` for a function, `undefined`, a symbol, a bigint or a\n * non-finite number.\n */\nfunction jsonCopy(value: unknown): JsonValue | undefined {\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") {\n return value;\n }\n if (typeof value === \"number\") {\n return Number.isFinite(value) ? value : undefined;\n }\n if (Array.isArray(value)) {\n return value.map((item: unknown) => jsonCopy(item) ?? null);\n }\n if (typeof value === \"object\") {\n return jsonObjectCopy(value);\n }\n return undefined;\n}\n\n/**\n * Copies an object's own enumerable members with {@link jsonCopy}.\n *\n * @param value - The object.\n * @returns The copy.\n */\nfunction jsonObjectCopy(value: object): JsonObject {\n const copy: Record<string, JsonValue> = {};\n for (const [key, member] of Object.entries(value)) {\n const converted = jsonCopy(member);\n if (converted !== undefined) {\n copy[key] = converted;\n }\n }\n return copy;\n}\n\n/**\n * Tells whether a JSON value is an object.\n *\n * @param value - The value.\n * @returns True for an object that is not an array.\n */\nfunction isObject(value: JsonValue | undefined): value is JsonObject {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Describes every settings section the app registered with core's `describeSettings`, each with\n * its JSON Schema from `settingsJsonSchema` as `propsSchema`, and copies the value the app resolved\n * for each section.\n *\n * @remarks\n * Settings are held in the settings form (`{ x, y, z }` for a vector), which is plain data, so a\n * section's value is copied member by member; a member JSON cannot carry is left out. The answer is\n * read from the app each time and sent only on request.\n *\n * @param app - The scene view's app.\n * @returns The sections and their values, keyed by section name in registration order.\n */\nexport function settingsSet(app: App): SettingsSet {\n const described = describeSettings(app);\n const properties = settingsJsonSchema(app)[\"properties\"];\n const sections: Record<string, SchemaDescription> = {};\n const values: Record<string, JsonObject> = {};\n for (const [name, description] of Object.entries(described)) {\n const propsSchema = isObject(properties) ? properties[name] : undefined;\n sections[name] = isObject(propsSchema) ? { ...description, propsSchema } : description;\n const value: unknown = app.settings.section(name);\n values[name] = typeof value === \"object\" && value !== null ? jsonObjectCopy(value) : {};\n }\n return { sections, values };\n}\n","/**\n * The arithmetic of the scene view's methods that needs no GPU: the `pick` unit rule, the ray and\n * plane point a `pick` answers with, the `screenshot` size rule, the transform the drag\n * notifications carry, and gizmo snapping. Each is a pure function, so the headless tests check it\n * directly.\n */\n\nimport { canonicalizeNumber } from \"@ignifx/core\";\nimport { PickUnit, SCREENSHOT_MAX_SIZE } from \"../protocol/index.js\";\nimport type { GizmoSnap, PickParams, PickRay, ScreenshotParams, SceneFileTransform, Vec3 } from \"../protocol/index.js\";\nimport type { Entity, MutableQuat, MutableVec3, Ray } from \"@ignifx/core\";\n\n/** An image or frame size, in pixels. */\nexport interface PixelSize {\n /** The width. */\n readonly width: number;\n /** The height. */\n readonly height: number;\n}\n\n/** The sizes of the view's canvas that the unit rule needs. */\nexport interface ViewSurface {\n /** The backing-store width, `canvas.width`. */\n readonly width: number;\n /** The backing-store height, `canvas.height`. */\n readonly height: number;\n /** The CSS width, `canvas.clientWidth`. */\n readonly clientWidth: number;\n /** The CSS height, `canvas.clientHeight`. */\n readonly clientHeight: number;\n}\n\n/**\n * Reads a render surface's sizes. An `OffscreenCanvas` has no CSS size, so its CSS pixels are its\n * backing pixels.\n *\n * @param surface - The canvas.\n * @returns The sizes.\n */\nexport function viewSurfaceOf(surface: HTMLCanvasElement | OffscreenCanvas): ViewSurface {\n const clientWidth: unknown = Reflect.get(surface, \"clientWidth\");\n const clientHeight: unknown = Reflect.get(surface, \"clientHeight\");\n return {\n width: surface.width,\n height: surface.height,\n clientWidth: typeof clientWidth === \"number\" && clientWidth > 0 ? clientWidth : surface.width,\n clientHeight: typeof clientHeight === \"number\" && clientHeight > 0 ? clientHeight : surface.height,\n };\n}\n\n/**\n * Converts a `pick` point to the backing-store pixels `app.renderer.pickAsync` takes (protocol 0.3,\n * \"The pick unit rule\"; engine ask E3). This is the host's one conversion: the renderer converts\n * on to the CSS pixels Lite's picker wants.\n *\n * @param params - The point and its unit.\n * @param surface - The canvas's sizes.\n * @returns The point in backing-store pixels, or `null` when it is outside the canvas (a miss).\n */\nexport function toBackingPixels(\n params: PickParams,\n surface: ViewSurface,\n): { readonly x: number; readonly y: number } | null {\n const x = params.unit === PickUnit.backing ? params.x : (params.x * surface.width) / surface.clientWidth;\n const y = params.unit === PickUnit.backing ? params.y : (params.y * surface.height) / surface.clientHeight;\n if (x < 0 || y < 0 || x >= surface.width || y >= surface.height) {\n return null;\n }\n return { x, y };\n}\n\n/** The members a `pick` answer gains from the camera ray. */\nexport interface PickRayMembers {\n /** The ray, rounded to the file format's precision. */\n readonly ray: PickRay;\n /** Where the ray meets `z = 0`, or absent when it runs parallel to the plane or meets it behind its origin. */\n readonly plane?: Vec3;\n}\n\n/**\n * Turns a camera ray into a `pick` answer's `ray` and `plane` members (protocol 0.3, additive): the\n * ray as it is, and the point where it meets the 2D world plane `z = 0`. The plane point is\n * computed before rounding, and its `z` is exactly `0`.\n *\n * @param ray - The world-space ray, from `Camera.screenToRay`, with a unit direction.\n * @returns The members, every number rounded with `canonicalizeNumber`.\n */\nexport function pickRayMembers(ray: Ray): PickRayMembers {\n const c = canonicalizeNumber;\n const { origin, direction } = ray;\n const members: PickRayMembers = {\n ray: {\n origin: [c(origin.x), c(origin.y), c(origin.z)],\n direction: [c(direction.x), c(direction.y), c(direction.z)],\n },\n };\n // A ray parallel to the plane never meets it; one whose `t` is negative meets it behind the camera.\n const t = direction.z === 0 ? Number.NaN : -origin.z / direction.z;\n if (!Number.isFinite(t) || t < 0) {\n return members;\n }\n return { ...members, plane: [c(origin.x + direction.x * t), c(origin.y + direction.y * t), 0] };\n}\n\n/**\n * Rounds an image side and keeps it from 1 to {@link SCREENSHOT_MAX_SIZE}.\n *\n * @param side - The side, in pixels.\n * @returns The whole side in range.\n */\nfunction clampSide(side: number): number {\n return Math.min(SCREENSHOT_MAX_SIZE, Math.max(1, Math.round(side)));\n}\n\n/**\n * The size of a `screenshot`: the request's, or the view's backing size scaled down, keeping its\n * aspect, to fit {@link SCREENSHOT_MAX_SIZE}; with one side given the other follows the aspect.\n *\n * @param params - The request; its sizes are already checked to be 1 to 2048.\n * @param view - The captured frame's size.\n * @returns The image size, each side at least 1 and at most 2048.\n */\nexport function screenshotSize(params: ScreenshotParams, view: PixelSize): PixelSize {\n const aspect = view.height > 0 ? view.width / view.height : 1;\n const { width, height } = params;\n if (width !== undefined && height !== undefined) {\n return { width, height };\n }\n if (width !== undefined) {\n return { width, height: clampSide(width / aspect) };\n }\n if (height !== undefined) {\n return { width: clampSide(height * aspect), height };\n }\n const fit = Math.min(1, SCREENSHOT_MAX_SIZE / Math.max(view.width, view.height, 1));\n return { width: clampSide(view.width * fit), height: clampSide(view.height * fit) };\n}\n\n/**\n * Reads an entity's local transform as the scene file writes it, numbers canonicalized.\n *\n * @param entity - The entity.\n * @returns The transform.\n */\nexport function readLocalTransform(entity: Entity): SceneFileTransform {\n const { localPosition: p, localRotation: r, localScale: s } = entity.transform;\n const c = canonicalizeNumber;\n return {\n position: [c(p.x), c(p.y), c(p.z)],\n rotation: [c(r.x), c(r.y), c(r.z), c(r.w)],\n scale: [c(s.x), c(s.y), c(s.z)],\n };\n}\n\n/**\n * Tells whether two transforms are equal number for number.\n *\n * @param a - One transform.\n * @param b - The other.\n * @returns True when every channel matches.\n */\nexport function sameTransform(a: SceneFileTransform, b: SceneFileTransform): boolean {\n return JSON.stringify(a) === JSON.stringify(b);\n}\n\n/**\n * Rounds a value to a step; a step of 0 leaves it alone.\n *\n * @param value - The value.\n * @param step - The step.\n * @returns The snapped value.\n */\nfunction snapTo(value: number, step: number): number {\n return step > 0 ? Math.round(value / step) * step : value;\n}\n\n/** A vector or quaternion's channels, as a snapping state holds them. */\ntype Channels = number[];\n\n/**\n * Snaps a gizmo drag after Lite has applied each move (S0.2 §3.4, post-correction). The raw, unsnapped\n * value is kept apart from the node, so the snapped steps do not accumulate rounding.\n */\nexport class DragSnapper {\n readonly #mode: \"translate\" | \"rotate\" | \"scale\";\n\n readonly #snap: GizmoSnap;\n\n readonly #start: Channels;\n\n #raw: Channels;\n\n #written: Channels;\n\n /**\n * Starts snapping one drag.\n *\n * @param mode - The drag's mode.\n * @param snap - The snapping steps.\n * @param entity - The dragged entity, at drag start.\n */\n constructor(mode: \"translate\" | \"rotate\" | \"scale\", snap: GizmoSnap, entity: Entity) {\n this.#mode = mode;\n this.#snap = snap;\n this.#start = this.#read(entity);\n this.#raw = [...this.#start];\n this.#written = [...this.#start];\n }\n\n /**\n * Folds the move Lite just wrote into the raw value and writes the snapped value back.\n *\n * @param entity - The dragged entity.\n */\n apply(entity: Entity): void {\n const now = this.#read(entity);\n if (this.#mode === \"rotate\") {\n this.#applyRotation(entity, now);\n return;\n }\n const step = this.#mode === \"translate\" ? this.#snap.translate : this.#snap.scale;\n if (step <= 0) {\n return;\n }\n this.#raw = this.#raw.map((value, index) => value + (now[index] ?? 0) - (this.#written[index] ?? 0));\n const snapped = this.#raw.map(\n (value, index) => (this.#start[index] ?? 0) + snapTo(value - (this.#start[index] ?? 0), step),\n );\n const target: MutableVec3 =\n this.#mode === \"translate\" ? entity.transform.localPosition : entity.transform.localScale;\n target.set(snapped[0] ?? 0, snapped[1] ?? 0, snapped[2] ?? 0);\n this.#written = snapped;\n }\n\n /**\n * Snaps a rotation drag: a ring turns about one axis, so the turn since drag start is one angle,\n * which is rounded to the step.\n *\n * @param entity - The dragged entity.\n * @param now - Its rotation now, as Lite wrote it.\n */\n #applyRotation(entity: Entity, now: Channels): void {\n const step = this.#snap.rotate;\n if (step <= 0) {\n return;\n }\n // raw = (now · written⁻¹) · raw, then the turn since start = raw · start⁻¹.\n this.#raw = multiply(multiply(now, conjugate(this.#written)), this.#raw);\n const turn = multiply(this.#raw, conjugate(this.#start));\n const sine = Math.hypot(turn[0] ?? 0, turn[1] ?? 0, turn[2] ?? 0);\n if (sine < 1e-9) {\n return;\n }\n const angle = 2 * Math.atan2(sine, turn[3] ?? 1);\n const snapped = (snapTo((angle * 180) / Math.PI, step) * Math.PI) / 180;\n const half = snapped / 2;\n const scale = Math.sin(half) / sine;\n const snappedTurn = [(turn[0] ?? 0) * scale, (turn[1] ?? 0) * scale, (turn[2] ?? 0) * scale, Math.cos(half)];\n const result = multiply(snappedTurn, this.#start);\n const rotation: MutableQuat = entity.transform.localRotation;\n rotation.set(result[0] ?? 0, result[1] ?? 0, result[2] ?? 0, result[3] ?? 1);\n this.#written = result;\n }\n\n /**\n * Reads the channels this drag moves.\n *\n * @param entity - The entity.\n * @returns Position, scale, or the rotation quaternion.\n */\n #read(entity: Entity): Channels {\n const t = entity.transform;\n if (this.#mode === \"rotate\") {\n return [t.localRotation.x, t.localRotation.y, t.localRotation.z, t.localRotation.w];\n }\n const v = this.#mode === \"translate\" ? t.localPosition : t.localScale;\n return [v.x, v.y, v.z];\n }\n}\n\n/**\n * Multiplies two quaternions, `a · b`.\n *\n * @param a - The left operand, `[x, y, z, w]`.\n * @param b - The right operand.\n * @returns The product.\n */\nfunction multiply(a: Channels, b: Channels): Channels {\n const [ax = 0, ay = 0, az = 0, aw = 1] = a;\n const [bx = 0, by = 0, bz = 0, bw = 1] = b;\n return [\n aw * bx + ax * bw + ay * bz - az * by,\n aw * by - ax * bz + ay * bw + az * bx,\n aw * bz + ax * by - ay * bx + az * bw,\n aw * bw - ax * bx - ay * by - az * bz,\n ];\n}\n\n/**\n * A unit quaternion's inverse.\n *\n * @param q - The quaternion.\n * @returns Its conjugate.\n */\nfunction conjugate(q: Channels): Channels {\n return [-(q[0] ?? 0), -(q[1] ?? 0), -(q[2] ?? 0), q[3] ?? 1];\n}\n","/**\n * The scene methods and notifications of protocol 0.3: what the scene view's host does with the\n * editor's document (`docs/architecture/17-editor-host.md` §6).\n */\n\nimport { Camera, canonicalizeNumber, createRay, isIgnifxError, validateSceneFile } from \"@ignifx/core\";\nimport { hotReloadedParamsOf, messageOf, relayAppReports } from \"../app-reports.js\";\nimport { InvalidParamsError, Reply, RpcFailure } from \"../channel.js\";\nimport { createEditorView } from \"../lite/gizmos.js\";\nimport {\n GizmoMode,\n GizmoSpace,\n HostCapability,\n isApplyOpsParams,\n isEntitySelection,\n isFrameParams,\n isOpenSceneParams,\n isPickParams,\n isReadBackParams,\n isScreenshotParams,\n isSetGizmoParams,\n isSetViewModeParams,\n PickUnit,\n RpcErrorCode,\n SCREENSHOT_MAX_SIZE,\n SceneMethod,\n SceneNotification,\n TRANSFORM_DRAGGING_INTERVAL_MS,\n ViewMode,\n} from \"../protocol/index.js\";\nimport {\n IN_PLACE_ASSET_TYPES,\n instancesOf,\n outermostRoots,\n SCENE_ASSET_TYPE,\n waitForReplacement,\n} from \"./asset-reload.js\";\nimport { applyDefaults, DefaultsTracker, instancesHolding } from \"./defaults.js\";\nimport { DocumentMirror } from \"./document.js\";\nimport { EditorCamera2D, EYE_DISTANCE_2D } from \"./editor-camera-2d.js\";\nimport { EDITOR_CAMERA_FOV, EditorCamera } from \"./editor-camera.js\";\nimport { applyOps, reloadInstance } from \"./ops.js\";\nimport { schemaSet } from \"./schemas.js\";\nimport { encodeCapture } from \"./screenshot.js\";\nimport { settingsSet } from \"./settings.js\";\nimport {\n boundsOf2D,\n CAMERA_2D_TYPE,\n componentTypeOf,\n DEFAULT_PIXELS_PER_UNIT,\n isCamera2DLike,\n levelCamera2D,\n sceneViewMode,\n twoDServiceOf,\n zoomForSize,\n} from \"./view-2d.js\";\nimport {\n DragSnapper,\n pickRayMembers,\n readLocalTransform,\n sameTransform,\n screenshotSize,\n toBackingPixels,\n viewSurfaceOf,\n} from \"./view-math.js\";\nimport type { RequestHandler } from \"../channel.js\";\nimport type { EditorAssetChange, PendingReload } from \"./asset-reload.js\";\nimport type { ChangedDefaults } from \"./defaults.js\";\nimport type { ViewClick } from \"./editor-camera.js\";\nimport type { PickRayMembers } from \"./view-math.js\";\nimport type { EditorView, ViewDrag, WorldBounds } from \"../lite/gizmos.js\";\nimport type {\n AssetReloadedParams,\n GizmoDragMode,\n GizmoSnap,\n HostErrorParams,\n PickParams,\n PickResult,\n SceneFileTransform,\n SchemaSet,\n ScreenshotResult,\n SettingsSet,\n} from \"../protocol/index.js\";\nimport type { App, Entity, HotReloadReport, RenderSurface, SceneInstance } from \"@ignifx/core\";\n\n/** The name of the host's persistent scene instance for its own objects. */\nexport const EDITOR_SCENE_NAME = \"editor\";\n\n/** The editor camera's priority: above any camera a document can hold. */\nconst EDITOR_CAMERA_PRIORITY = 1_000_000;\n\n/** What the scene host needs from the host that owns it. */\nexport interface SceneHostOptions {\n /** The capabilities the host announces in `ready`; the methods follow them. */\n readonly capabilities: readonly string[];\n /**\n * Sends a notification on the current port, or drops it when no editor is ready.\n *\n * @param method - The notification.\n * @param params - Its parameters.\n */\n readonly notify: (method: string, params: unknown) => void;\n}\n\n/** A point of the view, in backing-store pixels. */\ninterface BackingPoint {\n /** From the left edge. */\n readonly x: number;\n /** From the top edge. */\n readonly y: number;\n}\n\n/** The gizmo's settings, as `setGizmo` last set them. */\ninterface GizmoSettings {\n /** What it does. */\n readonly mode: GizmoMode;\n /** Which axes it follows. */\n readonly space: GizmoSpace;\n /** The snapping steps, or `null`. */\n readonly snap: GizmoSnap | null;\n}\n\n/** One gizmo drag in progress. */\ninterface DragState {\n /** The dragged entity. */\n readonly entity: Entity;\n /** The drag's mode. */\n readonly mode: GizmoDragMode;\n /** The local transform at drag start. */\n readonly before: SceneFileTransform;\n /** The snapping, or `null`. */\n readonly snapper: DragSnapper | null;\n /** When the last `transformDragging` went out, in milliseconds. */\n lastSentMs: number;\n}\n\n/**\n * Runs the scene methods against one app, and sends the notifications the app causes.\n *\n * @remarks\n * The host builds it before the app exists, so the channel can answer `hello` at once; every scene\n * method answers `notReady` until {@link SceneHost.start} has run (protocol 0.3, \"Not before the\n * app has started\").\n */\nexport class SceneHost {\n /** The scene methods, by name, for the channel. */\n readonly methods: ReadonlyMap<string, RequestHandler>;\n\n readonly #notify: (method: string, params: unknown) => void;\n\n #app: App | null = null;\n\n #mirror: DocumentMirror | null = null;\n\n #editorScene: SceneInstance | null = null;\n\n #camera: EditorCamera | null = null;\n\n #camera2D: EditorCamera2D | null = null;\n\n /** The editor camera the view uses, as `setViewMode` last set it. */\n #viewMode: ViewMode = ViewMode.threeD;\n\n /** The document the 2D camera was last placed on (see `#documentKey`), or `undefined` for none. */\n #placed2D: string | null | undefined = undefined;\n\n /** Whether the host lists `viewMode2d`. */\n readonly #hasViewMode2D: boolean;\n\n #eye: Camera | null = null;\n\n #canvas: RenderSurface | null = null;\n\n #view: EditorView | null = null;\n\n #selection: readonly string[] = [];\n\n #gizmo: GizmoSettings = { mode: GizmoMode.translate, space: GizmoSpace.world, snap: null };\n\n #drag: DragState | null = null;\n\n #started = false;\n\n /** The field defaults seen at start and after each hot reload, from {@link SceneHost.start} on. */\n #defaults: DefaultsTracker | null = null;\n\n readonly #cleanups: (() => void)[] = [];\n\n /** The reloads waiting for their new value; disposing the host cancels them. */\n readonly #reloads = new Set<PendingReload>();\n\n /** The tail of the work that touches the document, run one task at a time. */\n #queue: Promise<unknown> = Promise.resolve();\n\n /**\n * Creates the methods; none answers until the app has started.\n *\n * @param options - The capabilities and the notification sink.\n */\n constructor(options: SceneHostOptions) {\n this.#notify = options.notify;\n const has = (capability: string): boolean => options.capabilities.includes(capability);\n this.#hasViewMode2D = has(HostCapability.viewMode2d);\n const methods = new Map<string, RequestHandler>([\n [SceneMethod.openScene, async (params) => this.#openScene(params)],\n [SceneMethod.closeScene, async () => this.#closeScene()],\n [SceneMethod.applyOps, async (params) => this.#applyOps(params)],\n [SceneMethod.readBack, (params) => this.#readBack(params)],\n [SceneMethod.select, (params) => this.#select(params)],\n [SceneMethod.frame, (params) => this.#frame(params)],\n [SceneMethod.pick, async (params) => this.#pick(params)],\n [SceneMethod.getSchemas, () => this.#getSchemas()],\n [SceneMethod.describeSettings, () => this.#describeSettings()],\n [SceneMethod.setViewMode, (params) => this.#setViewMode(params)],\n ]);\n if (has(HostCapability.gizmos)) {\n methods.set(SceneMethod.setGizmo, (params) => this.#setGizmo(params));\n }\n if (has(HostCapability.screenshot)) {\n methods.set(SceneMethod.screenshot, async (params) => this.#screenshot(params));\n }\n // The channel answers one request at a time; an asset reload's rebuild queues with them.\n this.methods = new Map(\n [...methods].map(([name, handler]) => [name, async (params: unknown) => this.#serial(() => handler(params))]),\n );\n }\n\n /**\n * The persistent scene instance that holds the host's own objects, such as the editor camera.\n *\n * @returns The instance, or `null` before {@link SceneHost.prepare}.\n */\n get editorScene(): SceneInstance | null {\n return this.#editorScene;\n }\n\n /**\n * Prepares the app before it starts: the persistent `editor` scene with the editor camera, and\n * the log, error and hot-reload relays.\n *\n * @param app - The scene view's app, created and not yet started.\n */\n prepare(app: App): void {\n this.#app = app;\n this.#mirror = new DocumentMirror(app);\n const scene = app.world.createScene(EDITOR_SCENE_NAME, { persistent: true });\n this.#editorScene = scene;\n app.registerComponents([EditorCamera, EditorCamera2D]);\n const eye = app.world.createEntity(\"Editor Camera\", { scene });\n this.#eye = eye.addComponent(Camera, {\n fov: EDITOR_CAMERA_FOV,\n near: 0.05,\n far: 5000,\n priority: EDITOR_CAMERA_PRIORITY,\n });\n const camera = eye.addComponent(EditorCamera);\n camera.apply();\n this.#camera = camera;\n // The 2D toolkit's camera, found by its type id: highest priority wins, so while it is enabled\n // the sprites draw through it and the level's own `Camera2D` is left as the file has it.\n const camera2DType = componentTypeOf(app, CAMERA_2D_TYPE);\n const camera2D = camera2DType === null ? null : eye.addComponent(camera2DType);\n if (isCamera2DLike(camera2D)) {\n camera2D.priority = EDITOR_CAMERA_PRIORITY;\n camera2D.pixelPerfect = false;\n camera2D.enabled = false;\n }\n const twoD = eye.addComponent(EditorCamera2D);\n twoD.attach(this.#eye, isCamera2DLike(camera2D) ? camera2D : null);\n twoD.pixelsPerUnit = (): number => twoDServiceOf(app)?.pixelsPerUnit ?? DEFAULT_PIXELS_PER_UNIT;\n this.#camera2D = twoD;\n this.#cleanups.push(\n relayAppReports(app, {\n log: (params): void => {\n this.#notify(SceneNotification.log, params);\n },\n error: (params): void => {\n this.#notify(SceneNotification.hostError, params);\n },\n hotReloaded: (report): void => {\n this.#hotReloaded(report);\n },\n }),\n );\n }\n\n /**\n * Finishes setting up once the app has started: the gizmos and the outline on a canvas, the\n * camera's controls, and the first `schemasChanged`.\n *\n * @param canvas - The view's canvas, or `null` for a headless host.\n * @throws Whatever opening the render overlay throws.\n */\n async start(canvas: RenderSurface | null): Promise<void> {\n const app = this.#requireApp();\n this.#canvas = canvas;\n if (canvas !== null && !app.isHeadless && this.methods.has(SceneMethod.setGizmo) && isDomCanvas(canvas)) {\n const view = createEditorView(app.lite, await app.renderer.openOverlay(), canvas);\n view.onDrag((phase, drag) => {\n this.#onDrag(phase, drag);\n });\n this.#view = view;\n this.#applyGizmo();\n const onClick = (click: ViewClick): void => {\n void this.#onClick(click);\n };\n for (const camera of [this.#camera, this.#camera2D]) {\n if (camera !== null) {\n camera.claims = view;\n camera.onClick = onClick;\n camera.bind(canvas);\n }\n }\n }\n this.#defaults = new DefaultsTracker(app);\n this.#started = true;\n this.sendSchemas();\n }\n\n /** Sends `schemasChanged` once the app has started; the channel calls it after each `ready`. */\n sendSchemas(): void {\n if (this.#started) {\n this.#notify(SceneNotification.schemasChanged, this.#schemas());\n }\n }\n\n /**\n * Reloads an asset that changed on disk, in place, when the app has it loaded and its type is one\n * the renderers follow: a scene or prefab, whose instances in the open document are rebuilt from\n * the new file with their uids, transforms and overrides, or a model, mesh, material, sprite atlas\n * or shader. Sends `assetReloaded` once the new value is in. The open document's own file, a\n * removed file and any other type are left alone.\n *\n * @param change - The address and what happened to it.\n * @returns Whether the asset was reloaded; `false` also when the reload failed, which the app\n * reports as an error.\n */\n async assetChanged(change: EditorAssetChange): Promise<boolean> {\n const app = this.#app;\n const mirror = this.#mirror;\n const { address } = change;\n if (app === null || mirror === null || !this.#started || change.kind === \"removed\") {\n return false;\n }\n const handle = app.assets.get(address);\n if (\n handle === null ||\n handle.state !== \"loaded\" ||\n !IN_PLACE_ASSET_TYPES.includes(handle.type) ||\n (mirror.scene !== null && address === mirror.address)\n ) {\n return false;\n }\n const pending = waitForReplacement(app, handle);\n this.#reloads.add(pending);\n app.assets.reload(address);\n const replaced = await pending.replaced;\n this.#reloads.delete(pending);\n if (!replaced) {\n return false;\n }\n return this.#serial(async () => {\n const index = handle.type === SCENE_ASSET_TYPE ? mirror.index() : null;\n const roots = index === null ? [] : instancesOf(app, index, address);\n const entities = await this.#rebuildInstances(app, mirror, roots, address, { address }, false);\n this.#setSelection(this.#selection);\n const params: AssetReloadedParams = { address, type: handle.type, entities };\n this.#notify(SceneNotification.assetReloaded, params);\n return true;\n });\n }\n\n /**\n * Rebuilds instance roots from their scenes, one after the other; a root that fails is a\n * `hostError`.\n *\n * @param app - The scene view's app.\n * @param mirror - The open document.\n * @param roots - The roots' uids, none inside another.\n * @param cause - What the rebuild follows, for the error's message.\n * @param data - What the error's `data` carries besides the root's uid.\n * @param documentOverrides - Whether to rebuild with the document's override lists.\n * @returns The roots rebuilt.\n */\n async #rebuildInstances(\n app: App,\n mirror: DocumentMirror,\n roots: readonly string[],\n cause: string,\n data: Readonly<Record<string, string | readonly string[]>>,\n documentOverrides: boolean,\n ): Promise<string[]> {\n const rebuilt: string[] = [];\n for (const uid of roots) {\n try {\n // Each rebuild reads the document the previous one left.\n // oxlint-disable-next-line no-await-in-loop -- see above\n await reloadInstance(app, mirror, uid, documentOverrides);\n rebuilt.push(uid);\n } catch (error) {\n const params: HostErrorParams = {\n code: isIgnifxError(error) ? error.code : null,\n message: `Rebuilding ${uid} from ${cause}: ${messageOf(error)}`,\n data: { ...data, entity: uid },\n };\n this.#notify(SceneNotification.hostError, params);\n }\n }\n return rebuilt;\n }\n\n /**\n * Gives the open document the defaults a hot reload changed, where it leaves them out (engine ask\n * E25): each document component's omitted fields take the new default, then each prefab instance\n * whose members hold a changed type is rebuilt from its prefab with its overrides.\n *\n * @param changed - The changed fields, by type id.\n */\n async #followDefaults(changed: ChangedDefaults): Promise<void> {\n const app = this.#app;\n const mirror = this.#mirror;\n const index = mirror?.index() ?? null;\n if (app === null || mirror === null || index === null) {\n return;\n }\n applyDefaults(app, mirror, index, changed);\n mirror.invalidate();\n const rebuilt = mirror.index();\n const roots = rebuilt === null ? [] : outermostRoots(rebuilt, instancesHolding(app, rebuilt, changed));\n if (roots.length > 0) {\n const typeIds = [...changed.keys()];\n const cause = `the new defaults of ${typeIds.join(\", \")}`;\n await this.#rebuildInstances(app, mirror, roots, cause, { typeIds }, true);\n this.#setSelection(this.#selection);\n }\n }\n\n /** Removes the relays and the overlay; the host disposes the app. */\n dispose(): void {\n for (const pending of this.#reloads) {\n pending.cancel();\n }\n for (const cleanup of this.#cleanups.splice(0)) {\n cleanup();\n }\n this.#view?.dispose();\n this.#view = null;\n }\n\n // -------------------------------------------------------------------------------------------\n // Methods\n // -------------------------------------------------------------------------------------------\n\n /**\n * `openScene`: replaces the open document with the editor's file.\n *\n * @param params - `{ file, address }`.\n * @returns The entity count and warnings, then `sceneOpened`.\n */\n async #openScene(params: unknown): Promise<Reply> {\n const mirror = this.#requireMirror(SceneMethod.openScene);\n this.#setSelection([]);\n const file: unknown = typeof params === \"object\" && params !== null ? Reflect.get(params, \"file\") : undefined;\n const issues = file === undefined ? [] : validateSceneFile(file);\n if (issues.length > 0) {\n await mirror.close();\n const list = issues.map((issue) => `${issue.path}: ${issue.message}`).join(\"; \");\n throw new InvalidParamsError(`The scene file is not valid: ${list}`, { issues });\n }\n if (!isOpenSceneParams(params)) {\n throw new InvalidParamsError(\"openScene takes { file: SceneFile, address: string | null }.\");\n }\n const opened = await mirror.open(params.file, params.address);\n const viewMode = sceneViewMode(this.#requireApp(), mirror.scene);\n const result = { entityCount: opened.entityCount, warnings: opened.warnings, viewMode };\n if (this.#viewMode === ViewMode.twoD && this.#placed2D !== this.#documentKey()) {\n this.#place2D();\n }\n return new Reply(result, () => {\n this.#notify(SceneNotification.sceneOpened, {\n address: params.address,\n name: mirror.name,\n entityCount: result.entityCount,\n warnings: result.warnings,\n viewMode,\n });\n });\n }\n\n /**\n * `closeScene`: unloads the open document, if any.\n *\n * @returns `null`.\n */\n async #closeScene(): Promise<null> {\n const mirror = this.#requireMirror(SceneMethod.closeScene);\n this.#setSelection([]);\n await mirror.close();\n return null;\n }\n\n /**\n * `applyOps`: one command's ops, in order.\n *\n * @param params - `{ ops, commandName, commandId }`.\n * @returns How many applied, and the failures.\n */\n async #applyOps(params: unknown): Promise<unknown> {\n const mirror = this.#requireMirror(SceneMethod.applyOps);\n if (!isApplyOpsParams(params)) {\n throw new InvalidParamsError(\"applyOps takes { ops: SceneOp[], commandName, commandId }.\");\n }\n this.#requireOpen(SceneMethod.applyOps);\n const result = await applyOps(this.#requireApp(), mirror, params);\n this.#setSelection(this.#selection);\n return result;\n }\n\n /**\n * `readBack`: the open document as the live world has it.\n *\n * @param params - `{ entities? }`.\n * @returns The records, the missing uids, the settings, and the serializer's issues.\n */\n #readBack(params: unknown): unknown {\n const mirror = this.#requireMirror(SceneMethod.readBack);\n if (!isReadBackParams(params)) {\n throw new InvalidParamsError(\"readBack takes { entities?: uid[] }.\");\n }\n this.#requireOpen(SceneMethod.readBack);\n return mirror.readBack(params);\n }\n\n /**\n * `select`: the selection the view outlines and the gizmo follows.\n *\n * @param params - `{ entities }`.\n * @returns The selection kept: the document's uids, in order, without duplicates.\n */\n #select(params: unknown): unknown {\n const mirror = this.#requireMirror(SceneMethod.select);\n if (!isEntitySelection(params)) {\n throw new InvalidParamsError(\"select takes { entities: uid[] }.\");\n }\n const index = mirror.index();\n const kept = [...new Set(params.entities)].filter((uid) => index?.entities.has(uid) === true);\n this.#setSelection(kept);\n return { entities: kept };\n }\n\n /**\n * `setGizmo`: the gizmo's mode, axes and snapping.\n *\n * @param params - `{ mode, space, snap }`.\n * @returns `null`.\n */\n #setGizmo(params: unknown): null {\n this.#requireMirror(SceneMethod.setGizmo);\n if (!isSetGizmoParams(params)) {\n throw new InvalidParamsError(\n 'setGizmo takes { mode, space: \"local\" | \"world\", snap: { translate, rotate, scale } | null }.',\n );\n }\n this.#gizmo = { mode: params.mode, space: params.space, snap: params.snap };\n this.#applyGizmo();\n return null;\n }\n\n /**\n * `frame`: fits entities in the editor camera's view.\n *\n * @param params - `{ entities: uid[] | \"all\" }`.\n * @returns `null`.\n */\n #frame(params: unknown): null {\n const mirror = this.#requireMirror(SceneMethod.frame);\n if (!isFrameParams(params)) {\n throw new InvalidParamsError('frame takes { entities: uid[] | \"all\" }.');\n }\n this.#requireOpen(SceneMethod.frame);\n const index = mirror.index();\n const entities =\n params.entities === \"all\"\n ? [...(mirror.scene?.roots ?? [])]\n : params.entities.flatMap((uid) => {\n const entity = index?.entities.get(uid);\n return entity === undefined ? [] : [entity];\n });\n if (this.#viewMode === ViewMode.twoD) {\n const box = boundsOf2D(this.#requireApp(), entities);\n if (box !== null) {\n this.#camera2D?.frame(box);\n }\n return null;\n }\n const bounds = this.#boundsOf(entities);\n if (bounds !== null) {\n const center = {\n x: (bounds.min.x + bounds.max.x) / 2,\n y: (bounds.min.y + bounds.max.y) / 2,\n z: (bounds.min.z + bounds.max.z) / 2,\n };\n const radius = Math.hypot(bounds.max.x - center.x, bounds.max.y - center.y, bounds.max.z - center.z);\n this.#camera?.frame({ center, radius });\n }\n return null;\n }\n\n /**\n * `pick`: which document entity is under a point of the view. Changes nothing.\n *\n * @param params - `{ x, y, unit }`.\n * @returns The entity, the world point, and the distance, or a miss.\n */\n async #pick(params: unknown): Promise<PickResult> {\n this.#requireMirror(SceneMethod.pick);\n if (!isPickParams(params)) {\n throw new InvalidParamsError('pick takes { x, y, unit: \"css\" | \"backing\" }.');\n }\n return this.#pickAt(params);\n }\n\n /**\n * `screenshot`: the view as an image, without the gizmo and the outline.\n *\n * @param params - `{ width?, height?, format, quality? }`.\n * @returns The data URL and its size.\n */\n async #screenshot(params: unknown): Promise<ScreenshotResult> {\n const app = this.#requireApp();\n this.#requireMirror(SceneMethod.screenshot);\n if (typeof params === \"object\" && params !== null) {\n for (const side of [\"width\", \"height\"]) {\n const value: unknown = Reflect.get(params, side);\n if (\n value !== undefined &&\n (!Number.isSafeInteger(value) || Number(value) < 1 || Number(value) > SCREENSHOT_MAX_SIZE)\n ) {\n throw new InvalidParamsError(\n `screenshot takes a width and height from 1 to ${String(SCREENSHOT_MAX_SIZE)} pixels.`,\n );\n }\n }\n }\n if (!isScreenshotParams(params)) {\n throw new InvalidParamsError('screenshot takes { width?, height?, format: \"png\" | \"jpeg\", quality? }.');\n }\n this.#view?.setVisible(false);\n try {\n const capture = await app.renderer.captureScreenshot();\n const size = screenshotSize(params, capture);\n const dataUrl = await encodeCapture(capture, size, params.format, params.quality ?? 0.9);\n return { dataUrl, width: size.width, height: size.height };\n } finally {\n this.#view?.setVisible(true);\n }\n }\n\n /**\n * `getSchemas`: every registered component's schema.\n *\n * @returns The set.\n */\n #getSchemas(): SchemaSet {\n this.#requireMirror(SceneMethod.getSchemas);\n return this.#schemas();\n }\n\n /**\n * `describeSettings`: the project's settings sections and their resolved values. Sent only on\n * request.\n *\n * @returns The set.\n */\n #describeSettings(): SettingsSet {\n this.#requireMirror(SceneMethod.describeSettings);\n return settingsSet(this.#requireApp());\n }\n\n /**\n * `setViewMode`: switches the view between the 3D editor camera and the 2D one. The first switch\n * to 2D on a document starts where the level's own `Camera2D` looks, or frames the document.\n *\n * @param params - `{ mode }`.\n * @returns `null`.\n */\n #setViewMode(params: unknown): null {\n this.#requireMirror(SceneMethod.setViewMode);\n if (!isSetViewModeParams(params)) {\n throw new InvalidParamsError('setViewMode takes { mode: \"3d\" | \"2d\" }.');\n }\n if (params.mode === ViewMode.twoD && (!this.#hasViewMode2D || this.#camera2D === null)) {\n throw new InvalidParamsError(\"This scene view has no 2D view mode; it does not list the viewMode2d capability.\");\n }\n if (params.mode === this.#viewMode) {\n return null;\n }\n this.#viewMode = params.mode;\n const camera = this.#camera;\n const camera2D = this.#camera2D;\n if (params.mode === ViewMode.twoD) {\n if (camera !== null) {\n camera.active = false;\n }\n camera2D?.activate();\n if (this.#placed2D !== this.#documentKey()) {\n this.#place2D();\n }\n } else {\n camera2D?.deactivate();\n if (camera !== null) {\n camera.active = true;\n camera.apply();\n }\n }\n return null;\n }\n\n /**\n * Names the open document for the 2D camera's placement: its address, or `undefined` when none is\n * open. A reopen of the same address (the editor resends `openScene` after a failed op) keeps\n * the view where the user left it.\n *\n * @returns The key.\n */\n #documentKey(): string | null | undefined {\n const mirror = this.#mirror;\n return mirror === null || mirror.scene === null ? undefined : mirror.address;\n }\n\n /**\n * Places the 2D editor camera on the open document: where the level's own `Camera2D` looks, at\n * the half-height it shows, or, without one, around the whole document.\n */\n #place2D(): void {\n const camera2D = this.#camera2D;\n const mirror = this.#mirror;\n if (camera2D === null || mirror === null) {\n return;\n }\n const app = this.#requireApp();\n const scene = mirror.scene;\n this.#placed2D = this.#documentKey();\n const level = levelCamera2D(app, scene);\n if (level !== null) {\n const view = camera2D.view();\n const position = level.entity.transform.position;\n camera2D.centerX = position.x;\n camera2D.centerY = position.y;\n camera2D.zoom = zoomForSize(level.orthographicSize, view.heightPx, view.pixelsPerUnit);\n camera2D.apply();\n return;\n }\n const box = boundsOf2D(app, [...(scene?.roots ?? [])]);\n if (box !== null) {\n camera2D.frame(box);\n }\n }\n\n // -------------------------------------------------------------------------------------------\n // Selection, picking and the gizmo\n // -------------------------------------------------------------------------------------------\n\n /**\n * Sets the selection and updates the outline and the gizmo. Uids that no longer name a document\n * entity are dropped.\n *\n * @param uids - The selection, primary last.\n */\n #setSelection(uids: readonly string[]): void {\n const index = this.#mirror?.index() ?? null;\n const entities: Entity[] = [];\n const kept: string[] = [];\n for (const uid of uids) {\n const entity = index?.entities.get(uid);\n if (entity !== undefined && !entity.isDestroyed) {\n entities.push(entity);\n kept.push(uid);\n }\n }\n this.#selection = kept;\n this.#view?.outline(entities);\n this.#applyGizmo();\n }\n\n /** Attaches the gizmo to the primary selection in the current mode and space. */\n #applyGizmo(): void {\n const view = this.#view;\n if (view === null) {\n return;\n }\n const { mode, space } = this.#gizmo;\n view.setMode(mode === GizmoMode.none ? null : mode);\n view.setLocal(space === GizmoSpace.local);\n const primary = this.#selection.at(-1);\n view.attach(primary === undefined ? null : (this.#mirror?.index()?.entities.get(primary) ?? null));\n }\n\n /**\n * Picks the document's scene at a point of the view: in 3D mode with `app.renderer.pickAsync`,\n * which resolves a glTF model through its nearest entity node, and in 2D mode with\n * `app.twoD.pickAt` first. The hit resolves to its document entity. Hit or miss, the answer\n * carries the editor camera's ray through the point and where it meets `z = 0`.\n *\n * @param params - The point and its unit; it is converted to backing-store pixels once.\n * @returns The pick result; a point outside the canvas, or a headless view, misses without a ray.\n */\n async #pickAt(params: PickParams): Promise<PickResult> {\n const scene = this.#mirror?.scene ?? null;\n const canvas = this.#canvas;\n const at = canvas === null ? null : toBackingPixels(params, viewSurfaceOf(canvas));\n if (at === null) {\n return { entity: null, point: null, distance: null };\n }\n const camera2D = this.#camera2D;\n if (this.#viewMode === ViewMode.twoD && camera2D !== null) {\n return this.#pick2D(at, camera2D, scene);\n }\n const ray = this.#eye?.screenToRay(at.x, at.y) ?? null;\n const cast = ray === null ? {} : pickRayMembers(ray);\n if (scene === null) {\n return { entity: null, point: null, distance: null, ...cast };\n }\n return this.#pick3D(at, scene, cast);\n }\n\n /**\n * Picks in 2D mode: the topmost sprite of the document under the point with `app.twoD.pickAt`,\n * unpickable sprites included, answered with the world point on `z = 0` and no distance. Without\n * a sprite hit, a `\"mixed\"` project (or one without `@ignifx/2d`) goes on to the 3D picker through\n * the orthographic eye. The ray is the eye's, straight down +Z, built from the 2D camera's own\n * arithmetic so it never lags a frame behind a pan.\n *\n * @param at - The point, in backing-store pixels.\n * @param camera2D - The 2D editor camera.\n * @param scene - The document's scene instance, or `null`.\n * @returns The pick result.\n */\n async #pick2D(at: BackingPoint, camera2D: EditorCamera2D, scene: SceneInstance | null): Promise<PickResult> {\n const world = camera2D.screenToWorld(at.x, at.y);\n const ray = createRay();\n ray.origin.x = world.x;\n ray.origin.y = world.y;\n ray.origin.z = -EYE_DISTANCE_2D + (this.#eye?.near ?? 0);\n ray.direction.x = 0;\n ray.direction.y = 0;\n ray.direction.z = 1;\n const cast = pickRayMembers(ray);\n if (scene === null) {\n return { entity: null, point: null, distance: null, ...cast };\n }\n const twoD = twoDServiceOf(this.#requireApp());\n const hit = twoD?.pickAt(at.x, at.y, { includeUnpickable: true, filter: (entity) => entity.scene === scene });\n const entity = this.#mirror?.documentEntityOf(hit?.entity ?? null) ?? null;\n if (entity !== null) {\n const c = canonicalizeNumber;\n return { entity: entity.uid, point: [c(world.x), c(world.y), 0], distance: null, ...cast };\n }\n if (twoD !== null && twoD.mode === \"sprite\") {\n return { entity: null, point: null, distance: null, ...cast };\n }\n return this.#pick3D(at, scene, cast);\n }\n\n /**\n * Picks the document's meshes with `app.renderer.pickAsync`.\n *\n * @param at - The point, in backing-store pixels.\n * @param scene - The document's scene instance.\n * @param cast - The answer's `ray` and `plane`.\n * @returns The pick result.\n */\n async #pick3D(at: BackingPoint, scene: SceneInstance, cast: Partial<PickRayMembers>): Promise<PickResult> {\n const app = this.#requireApp();\n const hit = await app.renderer.pickAsync(at.x, at.y, { filter: (entity) => entity.scene === scene });\n const entity = this.#mirror?.documentEntityOf(hit?.entity ?? null) ?? null;\n if (hit === null || entity === null) {\n return { entity: null, point: null, distance: null, ...cast };\n }\n const c = canonicalizeNumber;\n const point = hit.point;\n return {\n entity: entity.uid,\n point: point === null ? null : [c(point[0]), c(point[1]), c(point[2])],\n distance: c(hit.distance),\n ...cast,\n };\n }\n\n /**\n * A click in the view: a plain click selects what it hits or clears the selection, a click with\n * Shift, Ctrl or Cmd toggles what it hits. A changed selection is applied and sent.\n *\n * @param click - Where, and whether it toggles.\n */\n async #onClick(click: ViewClick): Promise<void> {\n const { entity } = await this.#pickAt({ x: click.x, y: click.y, unit: PickUnit.css });\n const current = this.#selection;\n let next: readonly string[];\n if (click.toggle) {\n next =\n entity === null\n ? current\n : current.includes(entity)\n ? current.filter((uid) => uid !== entity)\n : [...current, entity];\n } else {\n next = entity === null ? [] : [entity];\n }\n if (next.length === current.length && next.every((uid, index) => uid === current[index])) {\n return;\n }\n this.#setSelection(next);\n this.#notify(SceneNotification.selectionChanged, { entities: this.#selection });\n }\n\n /**\n * Turns a gizmo drag into `transformDragging` (at most every 50 ms) and `transformDragged`.\n *\n * @param phase - Which part of the gesture.\n * @param drag - The handle.\n */\n #onDrag(phase: \"start\" | \"move\" | \"end\", drag: ViewDrag): void {\n if (phase === \"start\") {\n const uid = this.#selection.at(-1);\n const entity = uid === undefined ? undefined : this.#mirror?.index()?.entities.get(uid);\n if (entity === undefined) {\n this.#drag = null;\n return;\n }\n const snap = this.#gizmo.snap;\n this.#drag = {\n entity,\n mode: drag.mode,\n before: readLocalTransform(entity),\n snapper: snap === null ? null : new DragSnapper(drag.mode, snap, entity),\n lastSentMs: Number.NEGATIVE_INFINITY,\n };\n return;\n }\n const state = this.#drag;\n if (state === null) {\n return;\n }\n if (phase === \"move\") {\n state.snapper?.apply(state.entity);\n const now = performance.now();\n if (now - state.lastSentMs >= TRANSFORM_DRAGGING_INTERVAL_MS) {\n state.lastSentMs = now;\n this.#notify(SceneNotification.transformDragging, {\n entity: state.entity.uid,\n mode: state.mode,\n after: readLocalTransform(state.entity),\n });\n }\n return;\n }\n this.#drag = null;\n const after = readLocalTransform(state.entity);\n if (!sameTransform(state.before, after)) {\n this.#notify(SceneNotification.transformDragged, {\n entity: state.entity.uid,\n mode: state.mode,\n before: state.before,\n after,\n });\n }\n }\n\n /**\n * The world bounds of entities: their meshes' when the view can measure them, else their\n * positions, so a headless host still frames something.\n *\n * @param entities - The entities.\n * @returns The union box, or `null` for none.\n */\n #boundsOf(entities: readonly Entity[]): WorldBounds | null {\n let min = { x: Number.POSITIVE_INFINITY, y: Number.POSITIVE_INFINITY, z: Number.POSITIVE_INFINITY };\n let max = { x: Number.NEGATIVE_INFINITY, y: Number.NEGATIVE_INFINITY, z: Number.NEGATIVE_INFINITY };\n for (const entity of entities) {\n const p = entity.transform.position;\n const box = this.#view?.worldBounds(entity) ?? { min: p, max: p };\n min = { x: Math.min(min.x, box.min.x), y: Math.min(min.y, box.min.y), z: Math.min(min.z, box.min.z) };\n max = { x: Math.max(max.x, box.max.x), y: Math.max(max.y, box.max.y), z: Math.max(max.z, box.max.z) };\n }\n return Number.isFinite(min.x) ? { min, max } : null;\n }\n\n // -------------------------------------------------------------------------------------------\n // Notifications and guards\n // -------------------------------------------------------------------------------------------\n\n /**\n * Sends `hotReloaded`, then `schemasChanged`.\n *\n * @param report - What `app.hotReload` did.\n */\n #hotReloaded(report: HotReloadReport): void {\n // A \"recreate\" reload replaces component instances, which the document index holds.\n this.#mirror?.invalidate();\n const changed = this.#defaults?.changed(report.typeIds) ?? new Map<string, readonly string[]>();\n if (changed.size > 0) {\n // Queued with the requests, so a request the editor sends after `schemasChanged` sees it done.\n void this.#serial(async () => this.#followDefaults(changed));\n }\n const params = hotReloadedParamsOf(report);\n this.#notify(SceneNotification.hotReloaded, params);\n this.sendSchemas();\n }\n\n /**\n * Runs work that touches the document after everything queued before it.\n *\n * @param task - The work.\n * @returns What the task returns.\n */\n async #serial<T>(task: () => T | Promise<T>): Promise<T> {\n const run = this.#queue.then(task);\n this.#queue = run.catch(() => undefined);\n return run;\n }\n\n /**\n * The schemas, the host's own classes left out.\n *\n * @returns The set.\n */\n #schemas(): SchemaSet {\n return schemaSet(this.#requireApp(), new Set([EditorCamera.typeId, EditorCamera2D.typeId]));\n }\n\n /**\n * The app, once {@link SceneHost.prepare} has run.\n *\n * @returns The app.\n */\n #requireApp(): App {\n const app = this.#app;\n if (app === null) {\n throw new RpcFailure(RpcErrorCode.notReady, \"The scene view is still starting.\");\n }\n return app;\n }\n\n /**\n * The document mirror, once the app has started; otherwise the method answers `notReady`.\n *\n * @param method - The method being answered, for the message.\n * @returns The mirror.\n */\n #requireMirror(method: string): DocumentMirror {\n const mirror = this.#mirror;\n if (!this.#started || mirror === null) {\n throw new RpcFailure(\n RpcErrorCode.notReady,\n `The scene view is still starting; wait for schemasChanged before \"${method}\".`,\n );\n }\n return mirror;\n }\n\n /**\n * Refuses a method that needs an open document while none is open.\n *\n * @param method - The method being answered, for the message.\n */\n #requireOpen(method: string): void {\n if ((this.#mirror?.scene ?? null) === null) {\n throw new RpcFailure(RpcErrorCode.noScene, `No scene is open; send \"openScene\" before \"${method}\".`);\n }\n }\n}\n\n/**\n * Tells whether a render surface is a DOM canvas, which pointer events and Lite's gizmo dispatcher need.\n *\n * @param surface - The surface.\n * @returns True for an `HTMLCanvasElement`.\n */\nfunction isDomCanvas(surface: RenderSurface): surface is HTMLCanvasElement {\n return typeof HTMLCanvasElement !== \"undefined\" && surface instanceof HTMLCanvasElement;\n}\n","/**\n * The scene view's host: the app the editor looks at, built from the project's own `@ignifx/core`,\n * and the channel the editor drives it through.\n */\n\nimport { createApp, VERSION } from \"@ignifx/core\";\nimport { checkChannelOptions, openChannel, resolveMessageTarget } from \"./channel.js\";\nimport { HostCapability, HostKind, PROTOCOL_VERSION } from \"./protocol/index.js\";\nimport { SceneHost } from \"./scene/scene-host.js\";\nimport type { Channel, EditorMessageTarget } from \"./channel.js\";\nimport type { EditorAssetChange } from \"./scene/asset-reload.js\";\nimport type {\n App,\n AssetsCreateOptions,\n ConcreteComponentType,\n CreateAppOptions,\n Extension,\n RenderSurface,\n SceneInstance,\n SettingsInput,\n} from \"@ignifx/core\";\n\n/**\n * Options accepted by {@link startEditorHost}. The app options are the ones the project's `main.ts`\n * passes to `createApp`; the editor host's Vite plugin generates the call that supplies them.\n *\n * @beta\n */\nexport interface EditorHostOptions {\n /**\n * The origin the editor is served from, for example `\"ignifx://app\"`. A port posted from any\n * other origin is ignored.\n */\n readonly editorOrigin: string;\n /** Which view this host runs. Only `\"scene\"` exists in this release. Defaults to `\"scene\"`. */\n readonly hostKind?: typeof HostKind.scene;\n /** The canvas to render into. Without one the app is headless. */\n readonly canvas?: RenderSurface;\n /** Run on Babylon Lite's null engine. Defaults to `true` when there is no `canvas`. */\n readonly headless?: boolean;\n /**\n * Build the app in edit mode (`createApp({ editMode })`, ADR-0028), so the scene view shows the\n * scene without playing it: only scripts whose class sets `static runInEditMode = true` get\n * callbacks, and physics and other game-clock systems hold or skip. Defaults to `true`; pass\n * `false` to run the scene view as a game.\n */\n readonly editMode?: boolean;\n /** The project's extensions, in the order its `main.ts` registers them. */\n readonly extensions?: readonly Extension[];\n /** The project's component classes, registered with `app.registerComponents`. */\n readonly scripts?: readonly ConcreteComponentType[];\n /** Project settings, as `ignifx.config.ts` supplies them (`import.meta.env.IGNIFX_CONFIG`). */\n readonly settings?: SettingsInput;\n /** The asset manifest and `fetch`, as the project's `main.ts` passes them. */\n readonly assets?: AssetsCreateOptions;\n /** A scene address to load before the app starts, through the normal loader. Defaults to none. */\n readonly bootScene?: string | null;\n /**\n * The project's `@ignifx/core` version, reported in `ready`. Used only while core's own\n * `VERSION` is the unstamped `\"0.0.0\"`; the Vite plugin reads it from the project's installed\n * `@ignifx/core/package.json`.\n */\n readonly engineVersion?: string;\n /** Milliseconds between heartbeats once the editor has said `hello`. Defaults to `1000`. */\n readonly heartbeatIntervalMs?: number;\n /** Where the editor's connect message arrives. Defaults to the page's `window`. */\n readonly messageTarget?: EditorMessageTarget;\n}\n\n/**\n * A running scene-view host. The host owns its app: disposing the host disposes the app.\n *\n * @beta\n */\nexport interface EditorHost {\n /** The app the scene view shows. */\n readonly app: App;\n /** The instance of `bootScene`, or `null` when none was given. */\n readonly bootScene: SceneInstance | null;\n /**\n * The persistent scene instance named `editor` that holds the host's own objects, such as the\n * editor camera. It survives every scene the editor opens and is never part of the document.\n */\n readonly editorScene: SceneInstance;\n /** The engine version the host reports in `ready`. */\n readonly engineVersion: string;\n /** Whether the editor has handed the host a port that is still open. */\n readonly isConnected: boolean;\n /**\n * Reloads an asset that changed on disk, in place, through `app.assets.reload`. The generated\n * scene-view module calls it on every `ignifx:asset-changed` event.\n *\n * @remarks\n * Only an asset the app has loaded is reloaded, and only one of the types the renderers follow:\n * a scene or prefab, whose instances in the open document are then rebuilt from the new file with\n * their uids, transforms and overrides, or a model, mesh, material, sprite atlas or shader, which\n * the renderers pick up on their next frame. A texture, a removed file and the open document's\n * own file are left alone. Once the new value is in, the host sends `assetReloaded` with the\n * address, the type and the rebuilt instance roots, so the editor can compare its document with\n * the view instead of reloading it.\n *\n * @param change - The address and what happened to it.\n * @returns Whether the asset was reloaded; `false` when it was left alone or the reload failed,\n * which the app reports as an error (`hostError`).\n */\n assetChanged(change: EditorAssetChange): Promise<boolean>;\n /** Stops the heartbeat, closes the port, and disposes the app. Idempotent. */\n dispose(): void;\n /** Same as {@link EditorHost.dispose}, for `using`. */\n [Symbol.dispose](): void;\n}\n\n/** What core's `VERSION` reads when core runs from source; its build stamps the real number. */\nconst UNSTAMPED_VERSION = \"0.0.0\";\n\n/**\n * Chooses the engine version a host reports.\n *\n * @param fallback - The version the Vite plugin read from the project, if any.\n * @param coreVersion - Core's `VERSION`; a parameter only so tests can give an unstamped one.\n * @returns Core's `VERSION` when it is stamped, else the fallback, else `VERSION`.\n */\nexport function resolveEngineVersion(fallback: string | undefined, coreVersion: string = VERSION): string {\n if (coreVersion !== UNSTAMPED_VERSION) {\n return coreVersion;\n }\n return fallback ?? coreVersion;\n}\n\n/**\n * Starts the scene view's host: listens for the editor's port, creates the app from the project's\n * own `@ignifx/core` (in edit mode unless `editMode` is `false`), registers the project's scripts,\n * loads `bootScene` if one is given, starts the app, and serves the editor protocol's scene methods\n * (protocol 0.3, `docs/architecture/17-editor-host.md` §6).\n *\n * @remarks\n * The host answers `hello` with `ready` and `ping` with `\"pong\"` as soon as a port arrives, even\n * while the app is still being created; the scene methods answer `notReady` until the app has\n * started, and the host's first `schemasChanged` says they are accepted. It accepts a new port\n * whenever the editor sends one, closing the previous port.\n *\n * With a `canvas` the host draws Babylon Lite's gizmos and a selection outline in core's render\n * overlay (`app.renderer.openOverlay()`), answers `screenshot`, and has a 2D view mode\n * (`setViewMode`), which shows the sprites through an editor-owned `Camera2D` and picks them with\n * `app.twoD.pickAt` when the project registers `@ignifx/2d`. A headless host serves every method\n * that needs no GPU.\n *\n * @param options - The editor's origin and the project's app options.\n * @returns The running host, once the app has started.\n * @throws IgnifxError `IGX-1801` for a malformed `editorOrigin`, `IGX-1802` with no window and no\n * `messageTarget`, `IGX-1803` for a bad `heartbeatIntervalMs`. Whatever `createApp`, the scene\n * load, or `start` throws is rethrown after the channel is closed.\n *\n * @example\n * ```ts\n * import { startEditorHost } from \"@ignifx/editor-host\";\n *\n * const host = await startEditorHost({ editorOrigin: \"ignifx://app\", canvas, extensions: [], scripts });\n * ```\n *\n * @beta\n */\nexport async function startEditorHost(options: EditorHostOptions): Promise<EditorHost> {\n const heartbeatIntervalMs = checkChannelOptions(options.editorOrigin, options.heartbeatIntervalMs);\n const engineVersion = resolveEngineVersion(options.engineVersion);\n const capabilities = hasGpuView(options)\n ? [\n HostCapability.heartbeat,\n HostCapability.gizmos,\n HostCapability.screenshot,\n HostCapability.viewMode2d,\n HostCapability.pick2d,\n HostCapability.logRelay,\n HostCapability.hotReloadDefaults,\n ]\n : [HostCapability.heartbeat, HostCapability.logRelay, HostCapability.hotReloadDefaults];\n let channel: Channel | null = null;\n const scene = new SceneHost({\n capabilities,\n notify: (method, params) => {\n channel?.notify(method, params);\n },\n });\n // The channel opens before the first `await`, so a port posted while the app is created is kept.\n const opened = openChannel({\n target: resolveMessageTarget(options.messageTarget),\n editorOrigin: options.editorOrigin,\n ready: {\n engineVersion,\n protocol: PROTOCOL_VERSION,\n capabilities,\n hostKind: options.hostKind ?? HostKind.scene,\n },\n methods: scene.methods,\n heartbeatIntervalMs,\n onReady: () => {\n scene.sendSchemas();\n },\n });\n channel = opened;\n\n let app: App | null = null;\n let bootScene: SceneInstance | null = null;\n try {\n app = await createApp(appOptions(options));\n app.registerComponents(options.scripts ?? []);\n scene.prepare(app);\n // Loaded before `start()`, so the load settles without frames being pumped.\n if (options.bootScene !== undefined && options.bootScene !== null) {\n bootScene = await app.world.loadScene(options.bootScene);\n }\n await app.start();\n await scene.start(options.canvas ?? null);\n } catch (error) {\n scene.dispose();\n opened.dispose();\n app?.dispose();\n throw error;\n }\n\n const started = app;\n const editorScene = scene.editorScene ?? started.world.activeScene;\n const dispose = (): void => {\n scene.dispose();\n opened.dispose();\n started.dispose();\n };\n return {\n app: started,\n bootScene,\n editorScene,\n engineVersion,\n get isConnected(): boolean {\n return opened.isConnected;\n },\n assetChanged: async (change: EditorAssetChange): Promise<boolean> => scene.assetChanged(change),\n dispose,\n [Symbol.dispose]: dispose,\n };\n}\n\n/**\n * Tells whether a host renders: it has a canvas and is not forced headless.\n *\n * @param options - The host options.\n * @returns True when the view draws gizmos and can be captured.\n */\nfunction hasGpuView(options: EditorHostOptions): boolean {\n return options.canvas !== undefined && options.headless !== true;\n}\n\n/**\n * Picks the `createApp` options out of the host options, leaving out the ones that were not given.\n *\n * @param options - The host options.\n * @returns The app options.\n */\nfunction appOptions(options: EditorHostOptions): CreateAppOptions {\n return {\n editMode: options.editMode ?? true,\n ...(options.canvas === undefined ? {} : { canvas: options.canvas }),\n ...(options.headless === undefined ? {} : { headless: options.headless }),\n ...(options.extensions === undefined ? {} : { extensions: options.extensions }),\n ...(options.settings === undefined ? {} : { settings: options.settings }),\n ...(options.assets === undefined ? {} : { assets: options.assets }),\n };\n}\n","/**\n * The play view's controls: the project's own game page, reached by the editor through the app the\n * game's `main.ts` hands to `attachEditorPlayControls(app)` from `virtual:ignifx/editor`.\n */\n\nimport { hotReloadedParamsOf, relayAppReports } from \"./app-reports.js\";\nimport {\n checkChannelOptions,\n connectPortOf,\n InvalidParamsError,\n openChannel,\n Reply,\n resolveMessageTarget,\n} from \"./channel.js\";\nimport { resolveEngineVersion } from \"./host.js\";\nimport { PlayStatsReader } from \"./play-stats.js\";\nimport {\n HostCapability,\n HostKind,\n PlayMethod,\n PlayNotification,\n PlayPhase,\n PROTOCOL_VERSION,\n} from \"./protocol/index.js\";\nimport type { EditorMessageTarget, RequestHandler } from \"./channel.js\";\nimport type { PlayState, PlayStateReport, PlayStats } from \"./protocol/index.js\";\nimport type { App } from \"@ignifx/core\";\n\n/**\n * Options accepted by {@link startEditorPlayControls}.\n *\n * @beta\n */\nexport interface EditorPlayControlsOptions {\n /** The origin the editor is served from; a port posted from any other origin is ignored. */\n readonly editorOrigin: string;\n /** The project's `@ignifx/core` version, reported in `ready` while core's `VERSION` is unstamped. */\n readonly engineVersion?: string;\n /** Milliseconds between heartbeats once the editor has said `hello`. Defaults to `1000`. */\n readonly heartbeatIntervalMs?: number;\n /** Where the editor's connect message arrives. Defaults to the page's `window`. */\n readonly messageTarget?: EditorMessageTarget;\n}\n\n/**\n * The play view's side of an editor channel. The game keeps its app; the controls only drive it.\n *\n * @beta\n */\nexport interface EditorPlayControls {\n /** Whether the editor has handed the page a port that is still open. */\n readonly isConnected: boolean;\n /** Stops the heartbeat and closes the port. The app is left as it is. Idempotent. */\n dispose(): void;\n /** Same as {@link EditorPlayControls.dispose}, for `using`. */\n [Symbol.dispose](): void;\n}\n\n/**\n * A play view whose page listens for the editor's port before the game's app exists, so the\n * editor's first connect message is kept rather than lost.\n *\n * @beta\n */\nexport interface EditorPlayConnector {\n /** Whether a port has arrived and waits for {@link EditorPlayConnector.attach}. */\n readonly hasPendingPort: boolean;\n /**\n * Starts the play controls for the game's app on the port that has arrived, if any, and from\n * then on on every new one. Only the first call takes the waiting port; a later call, or one after\n * `dispose`, opens controls that wait for the editor's next port.\n *\n * @param app - The game's app. The controls never dispose it.\n * @returns The controls.\n */\n attach(app: App): EditorPlayControls;\n /** Stops listening, closes a waiting port, and disposes the controls it attached. Idempotent. */\n dispose(): void;\n /** Same as {@link EditorPlayConnector.dispose}, for `using`. */\n [Symbol.dispose](): void;\n}\n\n/**\n * How many reports the play view keeps while no editor has said `hello`; older ones are dropped.\n */\nconst EARLY_REPORT_LIMIT = 256;\n\n/** One report waiting for the handshake. */\ninterface EarlyReport {\n /** The notification's method. */\n readonly method: string;\n /** Its parameters. */\n readonly params: unknown;\n}\n\n/**\n * Sends the game's log lines, error reports and hot reloads to the editor, keeping the newest\n * {@link EARLY_REPORT_LIMIT} while no handshake has completed and sending them once one has.\n *\n * @param app - The game's app.\n * @param channel - The channel, read when a report arrives.\n * @returns A function that sends what was kept, for the handshake, and one that stops following.\n */\nfunction relayPlayReports(\n app: App,\n channel: () => { readonly isReady: boolean; notify(method: string, params?: unknown): void },\n): { readonly flush: () => void; readonly dispose: () => void } {\n const early: EarlyReport[] = [];\n const send = (method: string, params: unknown): void => {\n const current = channel();\n if (current.isReady) {\n current.notify(method, params);\n return;\n }\n early.push({ method, params });\n if (early.length > EARLY_REPORT_LIMIT) {\n early.shift();\n }\n };\n const dispose = relayAppReports(app, {\n log: (params): void => {\n send(PlayNotification.log, params);\n },\n error: (params): void => {\n send(PlayNotification.hostError, params);\n },\n hotReloaded: (report): void => {\n send(PlayNotification.hotReloaded, hotReloadedParamsOf(report));\n },\n });\n const flush = (): void => {\n const current = channel();\n for (const report of early.splice(0)) {\n current.notify(report.method, report.params);\n }\n };\n return { flush, dispose };\n}\n\n/**\n * Reads the game's state for a reply.\n *\n * @param app - The game's app.\n * @returns The state `play`, `pause`, `step` and `stop` answer with.\n */\nfunction playState(app: App): PlayState {\n return { isRunning: app.isRunning, isPaused: app.time.paused, frameCount: app.time.frameCount };\n}\n\n/**\n * Tells whether the game plays, is paused, or is stopped.\n *\n * @param app - The game's app.\n * @param isStopped - Whether the last control that stopped the loop was `stop`.\n * @returns The phase.\n */\nfunction playPhase(app: App, isStopped: boolean): PlayPhase {\n if (app.isRunning) {\n return app.time.paused ? PlayPhase.paused : PlayPhase.playing;\n }\n // A stepped game has no loop but sits paused on its frame; a stopped one is stopped, paused or not.\n return app.time.paused && !isStopped ? PlayPhase.paused : PlayPhase.stopped;\n}\n\n/**\n * Reads the frame delta of a `step` request.\n *\n * @param app - The game's app, whose fixed step is the default.\n * @param params - The received `params`.\n * @returns The delta in seconds.\n * @throws InvalidParamsError when `deltaSeconds` is present and not a positive finite number.\n */\nfunction stepDelta(app: App, params: unknown): number {\n if (typeof params !== \"object\" || params === null || !(\"deltaSeconds\" in params)) {\n return app.time.fixedDeltaTime;\n }\n const delta = params.deltaSeconds;\n if (typeof delta !== \"number\" || !Number.isFinite(delta) || delta <= 0) {\n throw new InvalidParamsError(\"step needs deltaSeconds to be a positive number of seconds.\");\n }\n return delta;\n}\n\n/**\n * Builds the play methods for one app.\n *\n * @param app - The game's app.\n * @param tracker - Reads the game's phase and reports its changes.\n * @returns The handlers, by method name.\n */\nfunction playMethods(app: App, tracker: PhaseTracker): ReadonlyMap<string, RequestHandler> {\n // Every control answers first, then reports the change it made, in that order on the port.\n const answer = (): Reply => new Reply(playState(app), tracker.report);\n const stats = new PlayStatsReader(app);\n return new Map<string, RequestHandler>([\n [\n PlayMethod.play,\n async (): Promise<Reply> => {\n tracker.isStopped = false;\n app.time.paused = false;\n await app.start();\n return answer();\n },\n ],\n [\n PlayMethod.pause,\n (): Reply => {\n app.time.paused = true;\n return answer();\n },\n ],\n [\n PlayMethod.step,\n (params): Reply => {\n const delta = stepDelta(app, params);\n // `app.step()` refuses to run beside the render loop, so stepping stops it first.\n app.stop();\n tracker.isStopped = false;\n app.time.paused = false;\n app.step(delta);\n app.time.paused = true;\n return answer();\n },\n ],\n [\n PlayMethod.stop,\n (): Reply => {\n app.stop();\n tracker.isStopped = true;\n return answer();\n },\n ],\n [PlayMethod.playState, (): PlayStateReport => tracker.read()],\n [PlayMethod.playStats, (): PlayStats => stats.read()],\n ]);\n}\n\n/** Reads the game's phase and sends `playStateChanged` when it differs from the last one sent. */\ninterface PhaseTracker {\n /** Whether the last control that stopped the loop was `stop` rather than `step`. */\n isStopped: boolean;\n /** Reads the game's state as `playState` answers it. */\n readonly read: () => PlayStateReport;\n /** Sends `playStateChanged` when the phase changed since the editor last saw it. */\n readonly report: () => void;\n /** Takes the current phase as the one the editor knows, after a handshake. */\n readonly reset: () => void;\n}\n\n/**\n * The options every play view checks before it opens a channel.\n *\n * @param options - The options as given.\n * @returns The heartbeat period and the message target.\n */\nfunction checkPlayOptions(options: EditorPlayControlsOptions): {\n heartbeatIntervalMs: number;\n target: EditorMessageTarget;\n} {\n const heartbeatIntervalMs = checkChannelOptions(options.editorOrigin, options.heartbeatIntervalMs);\n return { heartbeatIntervalMs, target: resolveMessageTarget(options.messageTarget) };\n}\n\n/**\n * Opens the play controls' channel.\n *\n * @param app - The game's app.\n * @param options - The editor's origin and the reporting options.\n * @param target - Where the connect message arrives.\n * @param heartbeatIntervalMs - The heartbeat period, which is also how often a change the game\n * makes itself is looked for.\n * @param port - A port that arrived before the app existed, or `null`.\n * @returns The controls.\n */\nfunction openPlayControls(\n app: App,\n options: EditorPlayControlsOptions,\n target: EditorMessageTarget,\n heartbeatIntervalMs: number,\n port: MessagePort | null,\n): EditorPlayControls {\n let lastPhase: PlayPhase | null = null;\n const tracker: PhaseTracker = {\n isStopped: false,\n read: (): PlayStateReport => ({\n state: playPhase(app, tracker.isStopped),\n frameCount: app.time.frameCount,\n time: app.time.time,\n }),\n report: (): void => {\n if (!channel.isReady) {\n return;\n }\n const report = tracker.read();\n if (report.state !== lastPhase) {\n lastPhase = report.state;\n channel.notify(PlayNotification.playStateChanged, report);\n }\n },\n reset: (): void => {\n lastPhase = playPhase(app, tracker.isStopped);\n },\n };\n const channel = openChannel({\n target,\n editorOrigin: options.editorOrigin,\n ready: {\n engineVersion: resolveEngineVersion(options.engineVersion),\n protocol: PROTOCOL_VERSION,\n capabilities: [HostCapability.heartbeat, HostCapability.playControls, HostCapability.logRelay],\n hostKind: HostKind.play,\n },\n methods: playMethods(app, tracker),\n heartbeatIntervalMs,\n onReady: (): void => {\n tracker.reset();\n reports.flush();\n },\n port,\n });\n const reports = relayPlayReports(app, () => channel);\n // The game can pause, stop or start itself; nothing in core announces it, so the controls look.\n const watch = setInterval(tracker.report, heartbeatIntervalMs);\n const dispose = (): void => {\n clearInterval(watch);\n reports.dispose();\n channel.dispose();\n };\n return {\n get isConnected(): boolean {\n return channel.isConnected;\n },\n dispose,\n [Symbol.dispose]: dispose,\n };\n}\n\n/**\n * Lets the editor drive a running game: answers the handshake with `hostKind: \"play\"`, then `play`,\n * `pause`, `step`, `stop`, `playState` and `playStats`, and sends `playStateChanged` when the game's phase\n * changes, and `log`, `hostError` and `hotReloaded` for the game's log lines, `app.onError` reports\n * and hot reloads (the newest 256 from before the handshake right after it).\n *\n * @remarks\n * A game does not call this directly. It calls `attachEditorPlayControls(app)` from\n * `virtual:ignifx/editor`, which the editor host's Vite plugin serves: in `vite dev` that module\n * calls this function, and in a production build it is an empty function, so no editor code ships.\n *\n * @param app - The game's app. The controls never dispose it.\n * @param options - The editor's origin and the reporting options.\n * @returns The controls; dispose them to stop listening.\n * @throws IgnifxError `IGX-1801` for a malformed `editorOrigin`, `IGX-1802` with no window and no\n * `messageTarget`, `IGX-1803` for a bad `heartbeatIntervalMs`.\n *\n * @example\n * ```ts\n * const controls = startEditorPlayControls(app, { editorOrigin: \"ignifx://app\" });\n * controls.dispose();\n * ```\n *\n * @beta\n */\nexport function startEditorPlayControls(app: App, options: EditorPlayControlsOptions): EditorPlayControls {\n const { heartbeatIntervalMs, target } = checkPlayOptions(options);\n return openPlayControls(app, options, target, heartbeatIntervalMs, null);\n}\n\n/**\n * Listens for the editor's connect message before the game's app exists, and keeps the newest port\n * until {@link EditorPlayConnector.attach} hands it the app.\n *\n * @remarks\n * The editor posts its port on the play view's `load` event, which can fire while the game's\n * `main.ts` still awaits `createApp`. `virtual:ignifx/editor` calls this when the module is\n * evaluated, which is before `main.ts` runs, and `attachEditorPlayControls(app)` calls `attach`, so\n * the handshake runs on the port the editor sent first. A port is accepted only from exactly\n * `editorOrigin`; a newer one replaces and closes the one waiting. Nothing is read from the port\n * before `attach`: the editor's `hello` waits in it.\n *\n * @param options - The editor's origin and the reporting options.\n * @returns The connector; dispose it to stop listening.\n * @throws IgnifxError `IGX-1801` for a malformed `editorOrigin`, `IGX-1802` with no window and no\n * `messageTarget`, `IGX-1803` for a bad `heartbeatIntervalMs`.\n *\n * @example\n * ```ts\n * const connector = listenForEditorPlayControls({ editorOrigin: \"ignifx://app\" });\n * const app = await createApp({ headless: true });\n * const controls = connector.attach(app);\n * connector.dispose();\n * ```\n *\n * @beta\n */\nexport function listenForEditorPlayControls(options: EditorPlayControlsOptions): EditorPlayConnector {\n const { heartbeatIntervalMs, target } = checkPlayOptions(options);\n const attached: EditorPlayControls[] = [];\n let pending: MessagePort | null = null;\n let isListening = true;\n let isDisposed = false;\n\n const onWindowMessage = (event: Event): void => {\n const port = connectPortOf(event, options.editorOrigin);\n if (port !== null) {\n pending?.close();\n pending = port;\n }\n };\n const stopListening = (): void => {\n if (isListening) {\n isListening = false;\n target.removeEventListener(\"message\", onWindowMessage);\n }\n };\n target.addEventListener(\"message\", onWindowMessage);\n\n const dispose = (): void => {\n if (isDisposed) {\n return;\n }\n isDisposed = true;\n stopListening();\n pending?.close();\n pending = null;\n for (const controls of attached.splice(0)) {\n controls.dispose();\n }\n };\n return {\n get hasPendingPort(): boolean {\n return pending !== null;\n },\n attach(app: App): EditorPlayControls {\n // The channel's own listener replaces this one in the same turn, so no message falls between.\n stopListening();\n const port = pending;\n pending = null;\n const controls = openPlayControls(app, options, target, heartbeatIntervalMs, port);\n if (!isDisposed) {\n attached.push(controls);\n }\n return controls;\n },\n dispose,\n [Symbol.dispose]: dispose,\n };\n}\n"],"mappings":";;;;;;;;;;;;;AAYA,MAAa,mBAAmB;;;;;;;;;;AAkBhC,MAAa,eAAe;;CAE1B,YAAY;;CAEZ,gBAAgB;;CAEhB,gBAAgB;;CAEhB,eAAe;;CAEf,eAAe;;CAEf,sBAAsB;;;;;CAKtB,UAAU;;CAEV,SAAS;AACX;;;;;;;;;;AAkHA,SAAgB,SAAS,OAAkD;CACzE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;;;;;;;AAQA,SAAS,QAAQ,OAAgC;CAC/C,OAAO,OAAO,UAAU,YAAa,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK;AACzF;;;;;;;AAQA,SAAS,WAAW,OAAmC;CACrD,OACE,SAAS,KAAK,KACd,OAAO,OAAO,YAAY,CAAC,CAAC,MAAM,SAAS,SAAS,MAAM,OAAO,KACjE,OAAO,MAAM,eAAe;AAEhC;;;;;;;;;;AAWA,SAAgB,aAAa,OAAqC;CAChE,IAAI,CAAC,SAAS,KAAK,KAAK,MAAM,eAAA,OAC5B,OAAO;CAET,IAAI,YAAY,OAAO;EAErB,MAAM,SAAS,MAAM;EACrB,MAAM,iBAAiB,EAAE,YAAY,UAAW,OAAO,WAAW,YAAY,WAAW;EACzF,MAAM,aAAa,EAAE,QAAQ,UAAU,QAAQ,MAAM,KAAK;EAC1D,OAAO,OAAO,MAAM,cAAc,YAAY,kBAAkB;CAClE;CACA,MAAM,YAAY,YAAY;CAE9B,IAAI,cADa,WAAW,OAE1B,OAAO;CAET,IAAI,WACF,OAAO,QAAQ,MAAM,KAAK;CAE5B,QAAQ,MAAM,UAAU,QAAQ,QAAQ,MAAM,KAAK,MAAM,WAAW,MA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D;CACnG,MAAM,EAAE,qBAAqB,WAAW,iBAAiB,OAAO;CAChE,MAAM,WAAiC,CAAC;CACxC,IAAI,UAA8B;CAClC,IAAI,cAAc;CAClB,IAAI,aAAa;CAEjB,MAAM,mBAAmB,UAAuB;EAC9C,MAAM,OAAO,cAAc,OAAO,QAAQ,YAAY;EACtD,IAAI,SAAS,MAAM;GACjB,SAAS,MAAM;GACf,UAAU;EACZ;CACF;CACA,MAAM,sBAA4B;EAChC,IAAI,aAAa;GACf,cAAc;GACd,OAAO,oBAAoB,WAAW,eAAe;EACvD;CACF;CACA,OAAO,iBAAiB,WAAW,eAAe;CAElD,MAAM,gBAAsB;EAC1B,IAAI,YACF;EAEF,aAAa;EACb,cAAc;EACd,SAAS,MAAM;EACf,UAAU;EACV,KAAK,MAAM,YAAY,SAAS,OAAO,CAAC,GACtC,SAAS,QAAQ;CAErB;CACA,OAAO;EACL,IAAI,iBAA0B;GAC5B,OAAO,YAAY;EACrB;EACA,OAAO,KAA8B;GAEnC,cAAc;GACd,MAAM,OAAO;GACb,UAAU;GACV,MAAM,WAAW,iBAAiB,KAAK,SAAS,QAAQ,qBAAqB,IAAI;GACjF,IAAI,CAAC,YACH,SAAS,KAAK,QAAQ;GAExB,OAAO;EACT;EACA;GACC,OAAO,UAAU;CACpB;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["SCENE_ASSET_TYPE","CLICK_SLOP_PX"],"sources":["../src/protocol/rpc.ts","../src/protocol/connect.ts","../src/protocol/handshake.ts","../src/protocol/heartbeat.ts","../src/protocol/play.ts","../src/protocol/scene-file.ts","../src/protocol/scene-ops.ts","../src/protocol/scene.ts","../src/protocol/version.ts","../src/channel.ts","../src/app-reports.ts","../src/lite/gizmos.ts","../src/scene/asset-reload.ts","../src/scene/collider-outlines.ts","../src/play-stats.ts","../src/scene/document.ts","../src/scene/defaults.ts","../src/scene/editor-camera.ts","../src/scene/view-2d.ts","../src/scene/editor-camera-2d.ts","../src/scene/view-math.ts","../src/scene/gizmo-drag.ts","../src/scene/json.ts","../src/scene/held-references.ts","../src/scene/ops.ts","../src/scene/sample-animation.ts","../src/scene/schemas.ts","../src/scene/screenshot.ts","../src/scene/settings.ts","../src/scene/scene-host.ts","../src/host.ts","../src/play-controls.ts"],"sourcesContent":["// A copy of `packages/editor-protocol/src/rpc.ts` from `astrum-forge/ignifx-editor` (protocol 0.3).\n// Below this comment it is byte-identical to that file, but for the link rule in `./index.ts`.\n/**\n * JSON-RPC 2.0 envelopes (https://www.jsonrpc.org/specification) shared by every editor channel:\n * editor↔host and editor↔play over a `MessagePort`.\n */\n\n/**\n * The value of every envelope's `jsonrpc` field.\n *\n * @public\n */\nexport const JSON_RPC_VERSION = \"2.0\";\n\n/**\n * A request id, chosen by the sender and echoed in the response.\n *\n * @public\n */\nexport type RpcId = string | number;\n\n/**\n * The error codes a peer may send. The first five are JSON-RPC's own; the rest use the range\n * JSON-RPC reserves for implementations (-32000 to -32099).\n *\n * @remarks\n * `as const` object plus derived union rather than an `enum` (engine coding standards §5.2, §5.3).\n *\n * @public\n */\nexport const RpcErrorCode = {\n /** The message was not valid JSON. */\n parseError: -32_700,\n /** The message was JSON but not a valid request. */\n invalidRequest: -32_600,\n /** No handler exists for the method. */\n methodNotFound: -32_601,\n /** The method exists but its `params` are wrong. */\n invalidParams: -32_602,\n /** The handler failed. */\n internalError: -32_603,\n /** The peers' protocol versions are incompatible (see `protocolVersionIsCompatible`). */\n incompatibleProtocol: -32_000,\n /**\n * The peer cannot answer this method yet: it has not finished its handshake, or (a scene host)\n * its app has not started.\n */\n notReady: -32_001,\n /** A scene method that needs an open scene was called while none is open (`SceneMethod`). */\n noScene: -32_002,\n} as const;\n\n/**\n * The union of the codes in `RpcErrorCode`.\n *\n * @public\n */\nexport type RpcErrorCode = (typeof RpcErrorCode)[keyof typeof RpcErrorCode];\n\n/**\n * The `error` member of a failed response.\n *\n * @public\n */\nexport interface RpcError {\n /** What kind of failure it was. */\n readonly code: RpcErrorCode;\n /** A short, human-readable description. */\n readonly message: string;\n /** Extra detail for debugging; its shape depends on the method. */\n readonly data?: unknown;\n}\n\n/**\n * A call that expects a response with the same `id`.\n *\n * @typeParam M - The method name.\n * @typeParam P - The parameters; omitted when the method takes none.\n *\n * @public\n */\nexport interface RpcRequest<M extends string = string, P = unknown> {\n /** Always `\"2.0\"`. */\n readonly jsonrpc: typeof JSON_RPC_VERSION;\n /** Matches the response to this request. */\n readonly id: RpcId;\n /** The method to call. */\n readonly method: M;\n /** The method's arguments, an object or an array in JSON. */\n readonly params?: P;\n}\n\n/**\n * A one-way message: like a request, but with no `id` and no response.\n *\n * @typeParam M - The method name.\n * @typeParam P - The parameters; omitted when the method takes none.\n *\n * @public\n */\nexport interface RpcNotification<M extends string = string, P = unknown> {\n /** Always `\"2.0\"`. */\n readonly jsonrpc: typeof JSON_RPC_VERSION;\n /** The event or method being signalled. */\n readonly method: M;\n /** The message's arguments, an object or an array in JSON. */\n readonly params?: P;\n}\n\n/**\n * The answer to a request that succeeded.\n *\n * @typeParam R - The result.\n *\n * @public\n */\nexport interface RpcSuccessResponse<R = unknown> {\n /** Always `\"2.0\"`. */\n readonly jsonrpc: typeof JSON_RPC_VERSION;\n /** The `id` of the request being answered. */\n readonly id: RpcId;\n /** What the method returned. */\n readonly result: R;\n}\n\n/**\n * The answer to a request that failed.\n *\n * @public\n */\nexport interface RpcErrorResponse {\n /** Always `\"2.0\"`. */\n readonly jsonrpc: typeof JSON_RPC_VERSION;\n /** The `id` of the request being answered, or `null` when it could not be read. */\n readonly id: RpcId | null;\n /** Why the request failed. */\n readonly error: RpcError;\n}\n\n/**\n * The answer to a request: a result or an error, never both.\n *\n * @typeParam R - The result on success.\n *\n * @public\n */\nexport type RpcResponse<R = unknown> = RpcSuccessResponse<R> | RpcErrorResponse;\n\n/**\n * Any message that can travel on an editor channel.\n *\n * @public\n */\nexport type RpcMessage = RpcRequest | RpcNotification | RpcResponse;\n\n/**\n * Narrows to a plain object without an `as` assertion. Shared by this package's guards; not\n * re-exported from the barrel.\n *\n * @param value - The value to test.\n * @returns True when the value is a non-null, non-array object.\n *\n * @internal\n */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Tells whether a JSON value is a valid request or notification id.\n *\n * @param value - The value to test.\n * @returns True for a string or a finite number.\n */\nfunction isRpcId(value: unknown): value is RpcId {\n return typeof value === \"string\" || (typeof value === \"number\" && Number.isFinite(value));\n}\n\n/**\n * Tells whether a JSON value is a valid `error` member with a known code.\n *\n * @param value - The value to test.\n * @returns True when its `code` is one of `RpcErrorCode` and its `message` is a string.\n */\nfunction isRpcError(value: unknown): value is RpcError {\n return (\n isRecord(value) &&\n Object.values(RpcErrorCode).some((code) => code === value[\"code\"]) &&\n typeof value[\"message\"] === \"string\"\n );\n}\n\n/**\n * Checks the envelope of a received message: a request, a notification, or a response. It does not\n * check a method's `params` or `result`; that is the handler's job.\n *\n * @param value - A value parsed from JSON or received through `postMessage`.\n * @returns True when `value` is a well-formed JSON-RPC 2.0 message with a known error code, if any.\n *\n * @public\n */\nexport function isRpcMessage(value: unknown): value is RpcMessage {\n if (!isRecord(value) || value[\"jsonrpc\"] !== JSON_RPC_VERSION) {\n return false;\n }\n if (\"method\" in value) {\n // JSON-RPC allows `params` to be absent, an object or an array, but never `null` or a scalar.\n const params = value[\"params\"];\n const hasValidParams = !(\"params\" in value) || (typeof params === \"object\" && params !== null);\n const hasValidId = !(\"id\" in value) || isRpcId(value[\"id\"]);\n return typeof value[\"method\"] === \"string\" && hasValidParams && hasValidId;\n }\n const hasResult = \"result\" in value;\n const hasError = \"error\" in value;\n if (hasResult === hasError) {\n return false;\n }\n if (hasResult) {\n return isRpcId(value[\"id\"]);\n }\n return (value[\"id\"] === null || isRpcId(value[\"id\"])) && isRpcError(value[\"error\"]);\n}\n","// A copy of `packages/editor-protocol/src/connect.ts` from `astrum-forge/ignifx-editor` (protocol 0.3).\n// Below this comment it is byte-identical to that file, but for the link rule in `./index.ts`.\n/**\n * The window message that hands a view its `MessagePort`. It is the only message that travels\n * outside the port: everything after it is JSON-RPC on the port (`rpc.ts`, `handshake.ts`).\n */\nimport { isRecord } from \"./rpc.js\";\n\n/**\n * The `type` of the window message that hands a host its `MessagePort`.\n *\n * @remarks\n * The editor posts `{ type: EDITOR_CONNECT_MESSAGE_TYPE }` to the view's window, targeted at the\n * view's origin, with the port as the one transferred object. It posts a fresh one after every load\n * of the view: a port that has been transferred once cannot be sent again, and the newest port\n * replaces the previous one. The host ignores the message unless `event.origin` is the editor's\n * origin, the data is this shape, and exactly one port is attached.\n *\n * @example\n * ```ts\n * const channel = new MessageChannel();\n * frame.contentWindow?.postMessage({ type: EDITOR_CONNECT_MESSAGE_TYPE }, \"http://127.0.0.1:5173\", [channel.port2]);\n * ```\n *\n * @public\n */\nexport const EDITOR_CONNECT_MESSAGE_TYPE = \"ignifx-editor/connect\";\n\n/**\n * The window message that hands a host its `MessagePort`; the port travels as its one transferred\n * object, not inside the data.\n *\n * @public\n */\nexport interface EditorConnectMessage {\n /** Always {@link EDITOR_CONNECT_MESSAGE_TYPE}. */\n readonly type: typeof EDITOR_CONNECT_MESSAGE_TYPE;\n}\n\n/**\n * Tells whether a window message's data is the connect message. It checks the data only; the\n * caller still checks `event.origin` and that `event.ports` holds exactly one port.\n *\n * @param value - The `data` of a received `MessageEvent`.\n * @returns True when `value` is an object whose `type` is {@link EDITOR_CONNECT_MESSAGE_TYPE}.\n *\n * @public\n */\nexport function isEditorConnectMessage(value: unknown): value is EditorConnectMessage {\n return isRecord(value) && value[\"type\"] === EDITOR_CONNECT_MESSAGE_TYPE;\n}\n","// A copy of `packages/editor-protocol/src/handshake.ts` from `astrum-forge/ignifx-editor` (protocol 0.3).\n// Below this comment it is byte-identical to that file, but for the link rule in `./index.ts`.\n/**\n * The handshake the editor runs with each host it embeds: the scene view (`@ignifx/editor-host`)\n * and the play view (`virtual:ignifx/editor`). Plan §3.3.\n *\n * The editor sends `hello`; the host answers with its `ready` result, or with an\n * `RpcErrorCode.incompatibleProtocol` error when `protocolVersionIsCompatible` refuses the\n * pair. Either side may send `ping` at any time after that. The editor posts a fresh port for every\n * load of a view (`connect.ts`), so the handshake runs again after every reload.\n */\nimport { isRecord } from \"./rpc.js\";\nimport type { RpcRequest, RpcSuccessResponse } from \"./rpc.js\";\nimport type { ProtocolVersion } from \"./version.js\";\n\n/**\n * The method names of the handshake.\n *\n * @remarks\n * `as const` object plus derived union rather than an `enum` (engine coding standards §5.2, §5.3).\n *\n * @public\n */\nexport const HandshakeMethod = {\n /** Editor → host: the first message on a new channel. */\n hello: \"hello\",\n /** Either direction: a liveness check, answered with `\"pong\"`. */\n ping: \"ping\",\n} as const;\n\n/**\n * The union of the names in `HandshakeMethod`.\n *\n * @public\n */\nexport type HandshakeMethod = (typeof HandshakeMethod)[keyof typeof HandshakeMethod];\n\n/**\n * Which kind of view a host runs.\n *\n * @public\n */\nexport const HostKind = {\n /** The scene view: an edit-mode app that applies document ops and draws gizmos. */\n scene: \"scene\",\n /** The play view: the project's own page, running the game. */\n play: \"play\",\n} as const;\n\n/**\n * The union of the kinds in `HostKind`.\n *\n * @public\n */\nexport type HostKind = (typeof HostKind)[keyof typeof HostKind];\n\n/**\n * The optional features a host lists in its `ready` result.\n *\n * @remarks\n * The play controls send `[\"heartbeat\", \"playControls\"]`. The scene host sends `\"heartbeat\"` and\n * whichever of `\"gizmos\"`, `\"screenshot\"`, `\"viewMode2d\"` and `\"pick2d\"` it supports; every\n * `SceneMethod` not tied to one of them is required of a 0.3 scene host.\n *\n * @public\n */\nexport const HostCapability = {\n /** The host sends `heartbeat` notifications after `ready` (see `HostNotification`). */\n heartbeat: \"heartbeat\",\n /** The host answers the methods in `PlayMethod`. */\n playControls: \"playControls\",\n /**\n * The scene host draws gizmos on the primary selection, answers `setGizmo`, and sends\n * `transformDragging` and `transformDragged`.\n */\n gizmos: \"gizmos\",\n /** The scene host answers `screenshot`. */\n screenshot: \"screenshot\",\n /** The scene host accepts `setViewMode` with `\"2d\"`: a 2D editor camera and planar gizmos. */\n viewMode2d: \"viewMode2d\",\n /**\n * The scene host picks sprites in 2D view mode (`app.twoD.pickAt` from `@ignifx/2d`); without it,\n * `pick` and view clicks in 2D mode resolve through the 3D picker only.\n */\n pick2d: \"pick2d\",\n /**\n * The host relays the app's reports: `log` lines with the first `Error` each carries, a\n * `hostError` with `AppErrorData` (entity, component, phase, stack) for every `app.onError`\n * report, and `hotReloaded` with each error's stack. The scene view sends them as scene\n * notifications, the play view as play notifications. Additive in 0.3.\n */\n logRelay: \"logRelay\",\n /**\n * After a script's hot reload changes a field's default, the scene host gives the field its new\n * default wherever the document leaves it out: on each document component whose record omits the\n * field, and on the members of each prefab instance (rebuilt from the prefab, with the instance's\n * overrides). A value the document sets is kept. An editor need not reopen the scene for changed\n * defaults. Additive in 0.3.\n */\n hotReloadDefaults: \"hotReloadDefaults\",\n} as const;\n\n/**\n * The union of the names in `HostCapability`.\n *\n * @public\n */\nexport type HostCapability = (typeof HostCapability)[keyof typeof HostCapability];\n\n/**\n * The longest string, in UTF-16 code units, the editor accepts from a host in `ready` (the engine\n * version, each capability name) and in the reports `log`, `hostError` (with `AppErrorData`) and\n * `hotReloaded` (messages, codes, scopes, stacks, type ids). A message holding a longer one fails\n * its guard and is dropped whole. It is far above what the Console keeps (which clips a message or\n * a stack it shows), so it only stops a runaway report from crossing the editor's processes. The\n * host does not clip to it.\n *\n * @public\n */\nexport const HOST_TEXT_MAX_LENGTH = 1_048_576;\n\n/**\n * The longest list the editor accepts from a host in `ready` (the capabilities) and in a\n * `hotReloaded` report (the type ids, the errors). A message holding a longer one fails its guard\n * and is dropped whole.\n *\n * @public\n */\nexport const HOST_LIST_MAX_LENGTH = 4096;\n\n/**\n * Tells whether a value is a string no longer than {@link HOST_TEXT_MAX_LENGTH}.\n *\n * @param value - The value to test.\n * @returns True for such a string.\n *\n * @internal\n */\nexport function isHostText(value: unknown): value is string {\n return typeof value === \"string\" && value.length <= HOST_TEXT_MAX_LENGTH;\n}\n\n/**\n * Tells whether a value is `null` or a string no longer than {@link HOST_TEXT_MAX_LENGTH}.\n *\n * @param value - The value to test.\n * @returns True for `null` or such a string.\n *\n * @internal\n */\nexport function isHostTextOrNull(value: unknown): value is string | null {\n return value === null || isHostText(value);\n}\n\n/**\n * Tells whether a value is a list of at most {@link HOST_LIST_MAX_LENGTH} passing items.\n *\n * @param value - The value to test.\n * @param item - The test for one item.\n * @returns True for such a list.\n *\n * @internal\n */\nexport function isHostList<T>(value: unknown, item: (entry: unknown) => entry is T): value is readonly T[] {\n return Array.isArray(value) && value.length <= HOST_LIST_MAX_LENGTH && value.every((entry: unknown) => item(entry));\n}\n\n/**\n * What the editor says about itself in `hello`.\n *\n * @public\n */\nexport interface HelloParams {\n /** The editor's own version, for example `\"0.1.0\"`. */\n readonly editorVersion: string;\n /** The protocol version the editor speaks. */\n readonly protocol: ProtocolVersion;\n}\n\n/**\n * Editor → host: the first request on a new channel.\n *\n * @public\n */\nexport interface HelloRequest extends RpcRequest<typeof HandshakeMethod.hello, HelloParams> {\n /** What the editor says about itself. */\n readonly params: HelloParams;\n}\n\n/**\n * What a host says about itself in answer to `hello`.\n *\n * @public\n */\nexport interface ReadyResult {\n /** The version of `@ignifx/core` the project runs, for example `\"0.9.0\"`. */\n readonly engineVersion: string;\n /** The protocol version the host speaks. */\n readonly protocol: ProtocolVersion;\n /**\n * Optional features the host supports, named by `HostCapability`. Names are added as the\n * protocol grows; a peer ignores names it does not know.\n */\n readonly capabilities: readonly string[];\n /** Which view the host runs. */\n readonly hostKind: HostKind;\n}\n\n/**\n * Host → editor: the successful answer to {@link HelloRequest}.\n *\n * @public\n */\nexport type ReadyResponse = RpcSuccessResponse<ReadyResult>;\n\n/**\n * Either direction: a liveness check. It takes no parameters.\n *\n * @public\n */\nexport type PingRequest = RpcRequest<typeof HandshakeMethod.ping, never>;\n\n/**\n * The answer to {@link PingRequest}.\n *\n * @public\n */\nexport type PongResponse = RpcSuccessResponse<\"pong\">;\n\n/**\n * The `data` of the `RpcErrorCode.incompatibleProtocol` error a host answers `hello` with when\n * the protocol versions differ.\n *\n * @public\n */\nexport interface IncompatibleProtocolData {\n /** The protocol version the host speaks. */\n readonly host: ProtocolVersion;\n /** The version of `@ignifx/core` the project runs. */\n readonly engineVersion: string;\n}\n\n/**\n * Tells whether a value is a protocol version: two non-negative integers.\n *\n * @param value - The value to test.\n * @returns True for `{ major, minor }` with non-negative safe integers.\n *\n * @public\n */\nexport function isProtocolVersion(value: unknown): value is ProtocolVersion {\n if (!isRecord(value)) {\n return false;\n }\n const { major, minor } = value;\n return (\n typeof major === \"number\" &&\n typeof minor === \"number\" &&\n Number.isSafeInteger(major) &&\n Number.isSafeInteger(minor) &&\n major >= 0 &&\n minor >= 0\n );\n}\n\n/**\n * Checks the `result` of a `hello` answer.\n *\n * @param value - The received `result`.\n * @returns True when it has a string `engineVersion`, a protocol version, an array of capability\n * strings, and a known `hostKind`; the strings and the list within {@link HOST_TEXT_MAX_LENGTH}\n * and {@link HOST_LIST_MAX_LENGTH}.\n *\n * @public\n */\nexport function isReadyResult(value: unknown): value is ReadyResult {\n if (!isRecord(value)) {\n return false;\n }\n const { capabilities, hostKind } = value;\n return (\n isHostText(value[\"engineVersion\"]) &&\n isProtocolVersion(value[\"protocol\"]) &&\n isHostList(capabilities, isHostText) &&\n Object.values(HostKind).some((kind) => kind === hostKind)\n );\n}\n\n/**\n * Checks the `data` of an `incompatibleProtocol` answer to `hello`.\n *\n * @param value - The received `error.data`.\n * @returns True when it names the host's protocol version and the engine version.\n *\n * @public\n */\nexport function isIncompatibleProtocolData(value: unknown): value is IncompatibleProtocolData {\n return isRecord(value) && isProtocolVersion(value[\"host\"]) && typeof value[\"engineVersion\"] === \"string\";\n}\n","// A copy of `packages/editor-protocol/src/heartbeat.ts` from `astrum-forge/ignifx-editor` (protocol 0.3).\n// Below this comment it is byte-identical to that file, but for the link rule in `./index.ts`.\n/**\n * The heartbeat: how the editor tells a live view from a crashed or hung one. Chromium reports\n * nothing for a dead sub-frame, so silence is the only signal.\n */\nimport type { RpcNotification } from \"./rpc.js\";\n\n/**\n * The notifications a host sends on its own.\n *\n * @remarks\n * `as const` object plus derived union rather than an `enum` (engine coding standards §5.2, §5.3).\n *\n * @public\n */\nexport const HostNotification = {\n /** Host → editor, every {@link DEFAULT_HEARTBEAT_INTERVAL_MS} by default after `ready`: the view is alive. */\n heartbeat: \"heartbeat\",\n} as const;\n\n/**\n * The union of the names in `HostNotification`.\n *\n * @public\n */\nexport type HostNotification = (typeof HostNotification)[keyof typeof HostNotification];\n\n/**\n * The milliseconds between heartbeats when the host is not configured otherwise: one second, so a\n * dead view is noticed within a few.\n *\n * @remarks\n * A host starts its heartbeat after it has answered a compatible `hello` with `ready`, sends it on\n * the current port only, and stops it when that port is replaced or closed. A host that lists\n * `HostCapability.heartbeat` in `ready` sends it, and the editor treats a missing heartbeat as a\n * dead view.\n *\n * @public\n */\nexport const DEFAULT_HEARTBEAT_INTERVAL_MS = 1000;\n\n/**\n * Host → editor: the view is alive. It carries no parameters, so `params` is absent on the wire:\n * `{\"jsonrpc\":\"2.0\",\"method\":\"heartbeat\"}`.\n *\n * @public\n */\nexport type HeartbeatNotification = RpcNotification<typeof HostNotification.heartbeat, never>;\n","// A copy of `packages/editor-protocol/src/play.ts` from `astrum-forge/ignifx-editor` (protocol 0.3).\n// Below this comment it is byte-identical to that file, but for the link rule in `./index.ts`.\n/**\n * The play view's controls: the methods the editor calls on the project's own game page after the\n * handshake, through `attachEditorPlayControls(app)` from `virtual:ignifx/editor`. Plan §3.6.\n */\nimport { isRecord } from \"./rpc.js\";\nimport type { RpcNotification, RpcRequest, RpcSuccessResponse } from \"./rpc.js\";\n\n/**\n * The methods the play view answers after `ready`. `play`, `pause`, `step` and `stop` answer with a\n * {@link PlayState}; `playState` answers with a {@link PlayStateReport}; `playStats` answers with\n * {@link PlayStats}.\n *\n * @remarks\n * A host that answers them lists `HostCapability.playControls` in `ready`. Sent before `ready`, they\n * fail with `RpcErrorCode.notReady`; sent to a host without them, with `RpcErrorCode.methodNotFound`.\n * `playState` and `playStats` are additive 0.3 methods: a host from before one answers it with\n * `RpcErrorCode.methodNotFound`.\n *\n * @public\n */\nexport const PlayMethod = {\n /** Clears `app.time.paused` and starts the frame loop if it is stopped. */\n play: \"play\",\n /** Sets `app.time.paused`; scripts marked `updateWhenPaused` keep running. */\n pause: \"pause\",\n /** Stops the frame loop, then advances exactly one frame with `app.step()` and leaves the game paused. */\n step: \"step\",\n /** Stops the frame loop with `app.stop()`. The editor reloads the view to reset the game. */\n stop: \"stop\",\n /** Reads the game's state without changing it. Takes no parameters. */\n playState: \"playState\",\n /**\n * Reads the game's frame rate, frame time, entity count and frame count without changing\n * anything. Takes no parameters. The editor polls it; no notification carries it.\n */\n playStats: \"playStats\",\n} as const;\n\n/**\n * The union of the names in `PlayMethod`.\n *\n * @public\n */\nexport type PlayMethod = (typeof PlayMethod)[keyof typeof PlayMethod];\n\n/**\n * The parameters of the `step` method.\n *\n * @public\n */\nexport interface StepParams {\n /**\n * The frame delta in seconds, a positive finite number. Defaults to `app.time.fixedDeltaTime`;\n * any other value fails with `RpcErrorCode.invalidParams`.\n */\n readonly deltaSeconds?: number;\n}\n\n/**\n * Editor → play view: one of the `PlayMethod`s. Only `step` takes parameters.\n *\n * @public\n */\nexport type PlayRequest =\n | RpcRequest<typeof PlayMethod.play, never>\n | RpcRequest<typeof PlayMethod.pause, never>\n | RpcRequest<typeof PlayMethod.step, StepParams>\n | RpcRequest<typeof PlayMethod.stop, never>\n | RpcRequest<typeof PlayMethod.playState, never>\n | RpcRequest<typeof PlayMethod.playStats, never>;\n\n/**\n * What the play view reports after every `PlayMethod`.\n *\n * @public\n */\nexport interface PlayState {\n /** Whether the frame loop runs (`app.isRunning`). */\n readonly isRunning: boolean;\n /** Whether game time is paused (`app.time.paused`). */\n readonly isPaused: boolean;\n /** How many frames have started (`app.time.frameCount`). */\n readonly frameCount: number;\n}\n\n/**\n * Play view → editor: the answer to `play`, `pause`, `step` or `stop`.\n *\n * @public\n */\nexport type PlayResponse = RpcSuccessResponse<PlayState>;\n\n/**\n * The notifications the play view sends after `ready`.\n *\n * @remarks\n * Additive in 0.3: a host from before them sends none, and answers `playState` with\n * `RpcErrorCode.methodNotFound`. `log`, `hostError` and `hotReloaded` came later still: only a host\n * that lists `HostCapability.logRelay` in `ready` sends them.\n *\n * @public\n */\nexport const PlayNotification = {\n /**\n * After the game's {@link PlayStateReport.state} changed. A change a `PlayMethod` makes is sent\n * right after that method's answer; one the game makes itself, such as setting\n * `app.time.paused`, within one heartbeat interval.\n */\n playStateChanged: \"playStateChanged\",\n /**\n * One line from the game's logger, with the same `LogParams` as the scene view's `log`. Sent by a\n * host that lists `HostCapability.logRelay`; lines logged before the handshake are kept (the\n * newest few hundred) and sent right after `ready`.\n */\n log: \"log\",\n /**\n * An error the game's app reported through `app.onError`: the same `HostErrorParams` as the scene\n * view's `hostError`, with `AppErrorData` as its `data`. Sent by a host that lists\n * `HostCapability.logRelay`, kept before the handshake as `log` is.\n */\n hostError: \"hostError\",\n /**\n * After every `app.hotReload` operation in the game: the same `HotReloadedParams` as the scene\n * view's `hotReloaded`. Sent by a host that lists `HostCapability.logRelay`.\n */\n hotReloaded: \"hotReloaded\",\n} as const;\n\n/**\n * The union of the names in `PlayNotification`.\n *\n * @public\n */\nexport type PlayNotification = (typeof PlayNotification)[keyof typeof PlayNotification];\n\n/**\n * Whether the game plays, is paused, or is stopped, as {@link PlayStateReport.state} reports it.\n *\n * @public\n */\nexport const PlayPhase = {\n /** The frame loop runs (`app.isRunning`) and game time is not paused. */\n playing: \"playing\",\n /**\n * Game time is paused (`app.time.paused`): after `pause`, or after `step`, which leaves the frame\n * loop stopped on the stepped frame.\n */\n paused: \"paused\",\n /** The frame loop does not run: before the game starts it, or after `stop`. */\n stopped: \"stopped\",\n} as const;\n\n/**\n * The union of the names in `PlayPhase`.\n *\n * @public\n */\nexport type PlayPhase = (typeof PlayPhase)[keyof typeof PlayPhase];\n\n/**\n * The game's state as `playState` answers it and `playStateChanged` reports it.\n *\n * @public\n */\nexport interface PlayStateReport {\n /** Whether the game plays, is paused, or is stopped. */\n readonly state: PlayPhase;\n /** How many frames have started (`app.time.frameCount`). */\n readonly frameCount: number;\n /** Scaled seconds of game time since the app started running frames (`app.time.time`). */\n readonly time: number;\n}\n\n/**\n * Play view → editor: the answer to `playState`.\n *\n * @public\n */\nexport type PlayStateResponse = RpcSuccessResponse<PlayStateReport>;\n\n/**\n * The game's performance as `playStats` answers it.\n *\n * @public\n */\nexport interface PlayStats {\n /**\n * Frames per second: `1000 / frameTimeMs`, or `0` when `frameTimeMs` is `0`. Rendered frames\n * count whether or not game time is paused.\n */\n readonly fps: number;\n /**\n * The mean wall-clock time between the frames of the last second, in milliseconds, from the\n * frame history in `app.diagnostics` (each frame's `rawDeltaMs`); `0` while the frame loop does\n * not run (stopped, or stepped and paused on a frame) or before its first frame.\n */\n readonly frameTimeMs: number;\n /** How many entities the game's world holds, in every scene instance, persistent ones included. */\n readonly entityCount: number;\n /** How many frames have started (`app.time.frameCount`). */\n readonly frameCount: number;\n}\n\n/**\n * Play view → editor: the answer to `playStats`.\n *\n * @public\n */\nexport type PlayStatsResponse = RpcSuccessResponse<PlayStats>;\n\n/**\n * Play view → editor: the game's state changed.\n *\n * @public\n */\nexport interface PlayStateChangedNotification extends RpcNotification<\n typeof PlayNotification.playStateChanged,\n PlayStateReport\n> {\n /** The game's state after the change. */\n readonly params: PlayStateReport;\n}\n\n/**\n * Checks the `result` of a play method's response.\n *\n * @param value - The received `result`.\n * @returns True when `value` has boolean `isRunning` and `isPaused` and a non-negative integer\n * `frameCount`.\n *\n * @public\n */\nexport function isPlayState(value: unknown): value is PlayState {\n if (!isRecord(value)) {\n return false;\n }\n const frameCount = value[\"frameCount\"];\n return (\n typeof value[\"isRunning\"] === \"boolean\" &&\n typeof value[\"isPaused\"] === \"boolean\" &&\n typeof frameCount === \"number\" &&\n Number.isSafeInteger(frameCount) &&\n frameCount >= 0\n );\n}\n\n/**\n * Checks the `result` of `playState` and the `params` of `playStateChanged`.\n *\n * @param value - The received value.\n * @returns True when `value` has a `state` that is a `PlayPhase`, a non-negative integer\n * `frameCount`, and a non-negative finite `time`.\n *\n * @public\n */\nexport function isPlayStateReport(value: unknown): value is PlayStateReport {\n if (!isRecord(value)) {\n return false;\n }\n const state = value[\"state\"];\n const frameCount = value[\"frameCount\"];\n const time = value[\"time\"];\n return (\n typeof state === \"string\" &&\n Object.values<string>(PlayPhase).includes(state) &&\n typeof frameCount === \"number\" &&\n Number.isSafeInteger(frameCount) &&\n frameCount >= 0 &&\n typeof time === \"number\" &&\n Number.isFinite(time) &&\n time >= 0\n );\n}\n\n/**\n * Checks the `result` of `playStats`.\n *\n * @param value - The received `result`.\n * @returns True when `value` has non-negative finite `fps` and `frameTimeMs` and non-negative\n * integer `entityCount` and `frameCount`.\n *\n * @public\n */\nexport function isPlayStats(value: unknown): value is PlayStats {\n if (!isRecord(value)) {\n return false;\n }\n const fps = value[\"fps\"];\n const frameTimeMs = value[\"frameTimeMs\"];\n const entityCount = value[\"entityCount\"];\n const frameCount = value[\"frameCount\"];\n return (\n typeof fps === \"number\" &&\n Number.isFinite(fps) &&\n fps >= 0 &&\n typeof frameTimeMs === \"number\" &&\n Number.isFinite(frameTimeMs) &&\n frameTimeMs >= 0 &&\n typeof entityCount === \"number\" &&\n Number.isSafeInteger(entityCount) &&\n entityCount >= 0 &&\n typeof frameCount === \"number\" &&\n Number.isSafeInteger(frameCount) &&\n frameCount >= 0\n );\n}\n","// A copy of `packages/editor-protocol/src/scene-file.ts` from `astrum-forge/ignifx-editor` (protocol 0.3).\n// Below this comment it is byte-identical to that file, but for the link rule in `./index.ts`.\n/**\n * The engine's scene file format as it travels on the wire: the same object `@ignifx/core`'s\n * `serializeScene` builds and `stringifySceneFile` writes\n * (`docs/architecture/06-serialization-and-scene-format.md` §2 in the engine repository).\n *\n * @remarks\n * This package has no dependencies, so it restates the engine's types instead of importing them.\n * Every type here has the engine type's name, fields and literal strings, and the package's tests\n * check that each pair is assignable both ways against the pinned `@ignifx/core`. The guards check\n * the structure a peer relies on, not every rule of the format: the host still validates an opened\n * file with the engine's `validateSceneFile`.\n */\nimport { isRecord } from \"./rpc.js\";\n\n/**\n * Any JSON value. The engine's `JsonValue`.\n *\n * @public\n */\nexport type JsonValue = string | number | boolean | null | JsonArray | JsonObject;\n\n/**\n * A JSON array. The engine's `JsonArray`.\n *\n * @public\n */\nexport type JsonArray = readonly JsonValue[];\n\n/**\n * A JSON object. The engine's `JsonObject`.\n *\n * @public\n */\nexport type JsonObject = { readonly [key: string]: JsonValue };\n\n/**\n * A serialized asset reference: `{ \"$asset\": \"<address>\", \"type\"?: \"<type>\" }`. The engine's\n * `SceneFileAssetRef`.\n *\n * @public\n */\nexport interface SceneFileAssetRef {\n /** The address the asset is registered under. */\n readonly $asset: string;\n /** The asset type name, written only when the address extension does not identify it. */\n readonly type?: string;\n}\n\n/**\n * An entity's local transform. The engine's `SceneFileTransform`.\n *\n * @public\n */\nexport interface SceneFileTransform {\n /** Local position, `[x, y, z]`, in metres. */\n readonly position: readonly [number, number, number];\n /** Local rotation quaternion, `[x, y, z, w]`. */\n readonly rotation: readonly [number, number, number, number];\n /** Local scale, `[x, y, z]`. */\n readonly scale: readonly [number, number, number];\n}\n\n/**\n * One component of one entity. The engine's `SceneFileComponent`.\n *\n * @public\n */\nexport interface SceneFileComponent {\n /** ULID, unique within the file. */\n readonly uid: string;\n /** The component class's registered `typeId`. */\n readonly type: string;\n /** Omitted when `true`, the default. */\n readonly enabled?: boolean;\n /** Written only when the class's `schemaVersion` differs from `1`. */\n readonly schemaVersion?: number;\n /** Values in the component schema's declaration order. */\n readonly props?: JsonObject;\n}\n\n/**\n * One override patch applied to an instanced scene. The engine's `SceneFileOverride`.\n *\n * @public\n */\nexport interface SceneFileOverride {\n /** `\"replace\"` (the default) patches a value, `\"remove\"` deletes a component, `\"add\"` appends one. */\n readonly op?: \"replace\" | \"remove\" | \"add\";\n /** The path into the instanced file, in the engine's override path grammar. */\n readonly path: string;\n /** The new value, for `\"replace\"` and `\"add\"`. */\n readonly value?: JsonValue;\n}\n\n/**\n * The `instance` entry that makes an entity the root of an instanced scene (a prefab instance).\n * The engine's `SceneFileInstance`.\n *\n * @public\n */\nexport interface SceneFileInstance {\n /** The scene asset to instance. */\n readonly scene: SceneFileAssetRef;\n /** The content hash of that asset at save time. */\n readonly hash?: string;\n /** The patches applied to the instanced entities, in order. */\n readonly overrides?: readonly SceneFileOverride[];\n}\n\n/**\n * One entity of a scene file. The engine's `SceneFileEntity`.\n *\n * @public\n */\nexport interface SceneFileEntity {\n /** ULID, unique within the file. */\n readonly uid: string;\n /** The display name. */\n readonly name: string;\n /** The parent's uid, or `null` for a root. */\n readonly parent: string | null;\n /** Omitted when `true`, the default. */\n readonly active?: boolean;\n /** Omitted when `false`, the default. */\n readonly static?: boolean;\n /** The layer name, omitted when `\"Default\"`. */\n readonly layer?: string;\n /** The tags, omitted when empty. */\n readonly tags?: readonly string[];\n /** Always present. */\n readonly transform: SceneFileTransform;\n /** Present only on instance roots. */\n readonly instance?: SceneFileInstance;\n /** The entity's own components; on an instance root, the ones added on top of the instance. */\n readonly components?: readonly SceneFileComponent[];\n}\n\n/**\n * A whole scene or prefab file. The engine's `SceneFile`.\n *\n * @public\n */\nexport interface SceneFile {\n /** Always `\"ignifx.scene\"`. */\n readonly format: string;\n /** `1` for every file the engine writes before 1.0. */\n readonly formatVersion: number;\n /** The `@ignifx/core` version that wrote the file; informational. */\n readonly engineVersion?: string;\n /** The scene's name. */\n readonly name: string;\n /** Scene-level values interpreted by systems. */\n readonly settings?: JsonObject;\n /** Every entity, in tree order: parents before children, siblings in order. */\n readonly entities: readonly SceneFileEntity[];\n}\n\n/** How deep a JSON value may nest before {@link isJsonValue} refuses it, as a guard against cycles. */\nconst MAX_JSON_DEPTH = 256;\n\n/**\n * Tells whether a value is JSON: `null`, a boolean, a string, a finite number, or an array or\n * plain object of JSON values, nested at most 256 levels deep.\n *\n * @param value - The value to test.\n * @returns True for a JSON value.\n *\n * @public\n */\nexport function isJsonValue(value: unknown): value is JsonValue {\n return isJsonValueAt(value, 0);\n}\n\n/**\n * {@link isJsonValue} at a nesting depth.\n *\n * @param value - The value to test.\n * @param depth - How deep the value sits.\n * @returns True for a JSON value no deeper than the limit.\n */\nfunction isJsonValueAt(value: unknown, depth: number): value is JsonValue {\n if (depth > MAX_JSON_DEPTH) {\n return false;\n }\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") {\n return true;\n }\n if (typeof value === \"number\") {\n return Number.isFinite(value);\n }\n if (Array.isArray(value)) {\n return value.every((item: unknown) => isJsonValueAt(item, depth + 1));\n }\n if (!isRecord(value)) {\n return false;\n }\n const prototype: unknown = Object.getPrototypeOf(value);\n return (\n (prototype === Object.prototype || prototype === null) &&\n Object.values(value).every((item) => isJsonValueAt(item, depth + 1))\n );\n}\n\n/**\n * Tells whether a value is a JSON object.\n *\n * @param value - The value to test.\n * @returns True for a plain object of JSON values.\n *\n * @public\n */\nexport function isJsonObject(value: unknown): value is JsonObject {\n return isRecord(value) && isJsonValue(value);\n}\n\n/**\n * Tells whether a value is a uid: a non-empty string, as the scene format's `uid` definition\n * requires. Whether it is a ULID is not the wire's concern.\n *\n * @param value - The value to test.\n * @returns True for a non-empty string.\n *\n * @internal\n */\nexport function isUidString(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0;\n}\n\n/**\n * Tells whether a value is a finite number.\n *\n * @param value - The value to test.\n * @returns True for a finite number.\n *\n * @internal\n */\nexport function isFiniteNumber(value: unknown): value is number {\n return typeof value === \"number\" && Number.isFinite(value);\n}\n\n/**\n * Tells whether a value is an array of finite numbers of one length.\n *\n * @param value - The value to test.\n * @param length - The required length.\n * @returns True for `length` finite numbers.\n *\n * @internal\n */\nexport function isNumberTuple(value: unknown, length: number): boolean {\n return Array.isArray(value) && value.length === length && value.every((item: unknown) => isFiniteNumber(item));\n}\n\n/**\n * Tells whether a value is an array whose every item passes a test.\n *\n * @param value - The value to test.\n * @param item - The test for one item.\n * @returns True for an array of passing items.\n *\n * @internal\n */\nexport function isArrayOf<T>(value: unknown, item: (entry: unknown) => entry is T): value is readonly T[] {\n return Array.isArray(value) && value.every((entry: unknown) => item(entry));\n}\n\n/**\n * Tells whether an optional field of a record is absent or passes a test.\n *\n * @param record - The record.\n * @param key - The field.\n * @param test - The test for a present value.\n * @returns True when the field is absent (or `undefined`) or passes.\n *\n * @internal\n */\nexport function optionalField(\n record: Record<string, unknown>,\n key: string,\n test: (value: unknown) => boolean,\n): boolean {\n const value = record[key];\n return value === undefined || test(value);\n}\n\n/**\n * Tells whether a value is a string.\n *\n * @param value - The value to test.\n * @returns True for a string.\n *\n * @internal\n */\nexport function isString(value: unknown): value is string {\n return typeof value === \"string\";\n}\n\n/**\n * Tells whether a value is a boolean.\n *\n * @param value - The value to test.\n * @returns True for a boolean.\n *\n * @internal\n */\nexport function isBoolean(value: unknown): value is boolean {\n return typeof value === \"boolean\";\n}\n\n/**\n * Checks an asset reference.\n *\n * @param value - The value to test.\n * @returns True for `{ $asset: string, type?: string }`.\n *\n * @public\n */\nexport function isSceneFileAssetRef(value: unknown): value is SceneFileAssetRef {\n return isRecord(value) && isString(value[\"$asset\"]) && optionalField(value, \"type\", isString);\n}\n\n/**\n * Checks a local transform.\n *\n * @param value - The value to test.\n * @returns True for three, four and three finite numbers in `position`, `rotation` and `scale`.\n *\n * @public\n */\nexport function isSceneFileTransform(value: unknown): value is SceneFileTransform {\n return (\n isRecord(value) &&\n isNumberTuple(value[\"position\"], 3) &&\n isNumberTuple(value[\"rotation\"], 4) &&\n isNumberTuple(value[\"scale\"], 3)\n );\n}\n\n/**\n * Checks a component record.\n *\n * @param value - The value to test.\n * @returns True for a record with a uid, a type and well-typed optional fields.\n *\n * @public\n */\nexport function isSceneFileComponent(value: unknown): value is SceneFileComponent {\n return (\n isRecord(value) &&\n isUidString(value[\"uid\"]) &&\n isString(value[\"type\"]) &&\n optionalField(value, \"enabled\", isBoolean) &&\n optionalField(value, \"schemaVersion\", (version) => Number.isSafeInteger(version)) &&\n optionalField(value, \"props\", isJsonObject)\n );\n}\n\n/**\n * Tells whether a value is an override's `op`.\n *\n * @param value - The value to test.\n * @returns True for `\"replace\"`, `\"remove\"` or `\"add\"`.\n *\n * @internal\n */\nexport function isOverrideOp(value: unknown): value is \"replace\" | \"remove\" | \"add\" {\n return value === \"replace\" || value === \"remove\" || value === \"add\";\n}\n\n/**\n * Checks an override patch.\n *\n * @param value - The value to test.\n * @returns True for `{ op?, path, value? }` with a known `op` and a JSON `value`.\n *\n * @public\n */\nexport function isSceneFileOverride(value: unknown): value is SceneFileOverride {\n return (\n isRecord(value) &&\n isString(value[\"path\"]) &&\n optionalField(value, \"op\", isOverrideOp) &&\n optionalField(value, \"value\", (patch) => isJsonValue(patch))\n );\n}\n\n/**\n * Checks an `instance` entry.\n *\n * @param value - The value to test.\n * @returns True for `{ scene, hash?, overrides? }`.\n *\n * @public\n */\nexport function isSceneFileInstance(value: unknown): value is SceneFileInstance {\n return (\n isRecord(value) &&\n isSceneFileAssetRef(value[\"scene\"]) &&\n optionalField(value, \"hash\", isString) &&\n optionalField(value, \"overrides\", (overrides) => isArrayOf(overrides, isSceneFileOverride))\n );\n}\n\n/**\n * Checks an entity record.\n *\n * @param value - The value to test.\n * @returns True for a record with a uid, a name, a parent, a transform and well-typed optional\n * fields.\n *\n * @public\n */\nexport function isSceneFileEntity(value: unknown): value is SceneFileEntity {\n if (!isRecord(value)) {\n return false;\n }\n const parent = value[\"parent\"];\n return (\n isUidString(value[\"uid\"]) &&\n isString(value[\"name\"]) &&\n (parent === null || isUidString(parent)) &&\n optionalField(value, \"active\", isBoolean) &&\n optionalField(value, \"static\", isBoolean) &&\n optionalField(value, \"layer\", isString) &&\n optionalField(value, \"tags\", (tags) => isArrayOf(tags, isString)) &&\n isSceneFileTransform(value[\"transform\"]) &&\n optionalField(value, \"instance\", isSceneFileInstance) &&\n optionalField(value, \"components\", (components) => isArrayOf(components, isSceneFileComponent))\n );\n}\n\n/**\n * Checks a whole scene file's structure.\n *\n * @param value - The value to test.\n * @returns True for a file object whose header fields and entity records have the right types.\n *\n * @public\n */\nexport function isSceneFile(value: unknown): value is SceneFile {\n return (\n isRecord(value) &&\n isString(value[\"format\"]) &&\n Number.isSafeInteger(value[\"formatVersion\"]) &&\n optionalField(value, \"engineVersion\", isString) &&\n isString(value[\"name\"]) &&\n optionalField(value, \"settings\", isJsonObject) &&\n isArrayOf(value[\"entities\"], isSceneFileEntity)\n );\n}\n","// A copy of `packages/editor-protocol/src/scene-ops.ts` from `astrum-forge/ignifx-editor` (protocol 0.3).\n// Below this comment it is byte-identical to that file, but for the link rule in `./index.ts`.\n/**\n * The scene op vocabulary on the wire: the thirteen ops of plan §3.4, exactly as\n * `@ignifx/editor-core` defines them (`packages/editor-core/src/ops.ts`), so a command the editor\n * applied to its document is sent to the host unchanged and MCP's `apply_ops` accepts the same JSON.\n *\n * @remarks\n * The types are restated here because this package has no dependencies. Every op, field name and\n * literal string is editor-core's; the package's tests check that editor-core's `SceneOp` and this\n * one are assignable both ways. Whether an op makes sense for a document (does the entity exist, is\n * the index in range) is not the wire's question: editor-core answers it before the op is sent, and\n * the host answers it again when it applies the op to the live world.\n */\nimport { isRecord } from \"./rpc.js\";\nimport {\n isArrayOf,\n isBoolean,\n isJsonValue,\n isOverrideOp,\n isSceneFileEntity,\n isSceneFileComponent,\n isSceneFileInstance,\n isSceneFileOverride,\n isSceneFileTransform,\n isString,\n isUidString,\n optionalField,\n} from \"./scene-file.js\";\nimport type {\n JsonValue,\n SceneFileComponent,\n SceneFileEntity,\n SceneFileInstance,\n SceneFileOverride,\n SceneFileTransform,\n} from \"./scene-file.js\";\n\n/**\n * The `op` discriminant of every scene op.\n *\n * @remarks\n * `as const` object plus derived union rather than an `enum` (engine coding standards §5.2, §5.3).\n *\n * @public\n */\nexport const SceneOpKind = {\n /** Creates an entity, optionally with a subtree. */\n createEntity: \"createEntity\",\n /** Destroys an entity and its subtree. */\n destroyEntity: \"destroyEntity\",\n /** Moves an entity under another parent, keeping its local transform. */\n reparent: \"reparent\",\n /** Moves an entity among its siblings. */\n reorder: \"reorder\",\n /** Sets `name`, `active`, `static`, `layer` or `tags`. */\n setEntityField: \"setEntityField\",\n /** Sets an entity's local transform. */\n setTransform: \"setTransform\",\n /** Adds a component. */\n addComponent: \"addComponent\",\n /** Removes a component. */\n removeComponent: \"removeComponent\",\n /** Sets or removes a value inside a component's `props`. */\n setProp: \"setProp\",\n /** Sets or removes a value inside the scene's `settings`. */\n setSceneSetting: \"setSceneSetting\",\n /** Creates an instance root (a prefab instance). */\n instantiate: \"instantiate\",\n /** Sets an override on an instance root. */\n setOverride: \"setOverride\",\n /** Removes an override from an instance root. */\n removeOverride: \"removeOverride\",\n} as const;\n\n/**\n * The union of the names in `SceneOpKind`.\n *\n * @public\n */\nexport type SceneOpKind = (typeof SceneOpKind)[keyof typeof SceneOpKind];\n\n/**\n * The entity properties {@link SetEntityFieldOp} writes, and their value types.\n *\n * @public\n */\nexport interface EntityFieldValues {\n /** The display name. */\n readonly name: string;\n /** `false` deactivates the entity and its subtree. */\n readonly active: boolean;\n /** The static flag. */\n readonly static: boolean;\n /** The layer name; `\"Default\"` is the default. */\n readonly layer: string;\n /** The tags; stored deduplicated and sorted, as the serializer writes them. */\n readonly tags: readonly string[];\n}\n\n/**\n * The name of an entity property {@link SetEntityFieldOp} writes.\n *\n * @public\n */\nexport type EntityField = keyof EntityFieldValues;\n\n/**\n * A path into a JSON object: object keys as strings, array indices as whole numbers.\n *\n * @public\n */\nexport type JsonPath = readonly (string | number)[];\n\n/**\n * Creates an entity, optionally with a whole subtree below it. `entity.parent` places it; `index`\n * is its place among the parent's children (default: last); `descendants` are further records,\n * parents first.\n *\n * @public\n */\nexport interface CreateEntityOp {\n /** The discriminant. */\n readonly op: \"createEntity\";\n /** The new entity's record, including its components and, for an instance root, its `instance`. */\n readonly entity: SceneFileEntity;\n /** The entity's index among its siblings; defaults to the end. */\n readonly index?: number;\n /** The rest of the subtree, parents first. */\n readonly descendants?: readonly SceneFileEntity[];\n}\n\n/**\n * Destroys an entity and its whole subtree.\n *\n * @public\n */\nexport interface DestroyEntityOp {\n /** The discriminant. */\n readonly op: \"destroyEntity\";\n /** The entity's uid. */\n readonly entity: string;\n}\n\n/**\n * Moves an entity under another parent, keeping its local transform.\n *\n * @public\n */\nexport interface ReparentOp {\n /** The discriminant. */\n readonly op: \"reparent\";\n /** The entity's uid. */\n readonly entity: string;\n /** The new parent's uid, or `null` to make the entity a root. */\n readonly parent: string | null;\n /** The entity's index among its new siblings; defaults to the end. */\n readonly index?: number;\n}\n\n/**\n * Moves an entity among its siblings; `index` is its place after the move.\n *\n * @public\n */\nexport interface ReorderOp {\n /** The discriminant. */\n readonly op: \"reorder\";\n /** The entity's uid. */\n readonly entity: string;\n /** The new index among its siblings. */\n readonly index: number;\n}\n\n/**\n * Sets one entity property.\n *\n * @public\n */\nexport type SetEntityFieldOp = {\n readonly [F in EntityField]: {\n /** The discriminant. */\n readonly op: \"setEntityField\";\n /** The entity's uid. */\n readonly entity: string;\n /** Which property. */\n readonly field: F;\n /** The new value. */\n readonly value: EntityFieldValues[F];\n };\n}[EntityField];\n\n/**\n * Sets an entity's local transform. `before` is informational and ignored when applying.\n *\n * @public\n */\nexport interface SetTransformOp {\n /** The discriminant. */\n readonly op: \"setTransform\";\n /** The entity's uid. */\n readonly entity: string;\n /** The new local transform. */\n readonly after: SceneFileTransform;\n /** The local transform the emitter saw before the change; ignored when applying. */\n readonly before?: SceneFileTransform;\n}\n\n/**\n * Adds a component to an entity.\n *\n * @public\n */\nexport interface AddComponentOp {\n /** The discriminant. */\n readonly op: \"addComponent\";\n /** The entity's uid. */\n readonly entity: string;\n /** The component's record; its uid must be new to the document. */\n readonly component: SceneFileComponent;\n /** The component's index on the entity; defaults to the end. */\n readonly index?: number;\n}\n\n/**\n * Removes a component.\n *\n * @public\n */\nexport interface RemoveComponentOp {\n /** The discriminant. */\n readonly op: \"removeComponent\";\n /** The component's uid. */\n readonly component: string;\n}\n\n/**\n * Sets, or removes, a value inside a component's `props`. `path[0]` is the field name; an absent\n * `value` removes the key; the empty path addresses `props` itself.\n *\n * @public\n */\nexport interface SetPropOp {\n /** The discriminant. */\n readonly op: \"setProp\";\n /** The component's uid. */\n readonly component: string;\n /** The path into `props`. */\n readonly path: JsonPath;\n /** The new value; absent removes the key. */\n readonly value?: JsonValue;\n}\n\n/**\n * Sets, or removes, a value inside the scene's `settings`, with {@link SetPropOp}'s path rules.\n *\n * @public\n */\nexport interface SetSceneSettingOp {\n /** The discriminant. */\n readonly op: \"setSceneSetting\";\n /** The path into `settings`; `path[0]` is the setting's key. */\n readonly path: JsonPath;\n /** The new value; absent removes the key. */\n readonly value?: JsonValue;\n}\n\n/**\n * Creates an instance root: an entity carrying an `instance` entry.\n *\n * @public\n */\nexport interface InstantiateOp {\n /** The discriminant. */\n readonly op: \"instantiate\";\n /** The new entity's uid. */\n readonly entity: string;\n /** Its name; usually the prefab root's name. */\n readonly name: string;\n /** Its parent's uid, or `null` for a root. */\n readonly parent: string | null;\n /** Its index among its siblings; defaults to the end. */\n readonly index?: number;\n /** Its local transform. */\n readonly transform: SceneFileTransform;\n /** The instance entry: the scene asset, its hash, and any overrides. */\n readonly instance: SceneFileInstance;\n}\n\n/**\n * Sets an override on an instance root's entry, replacing the override with the same identity or\n * inserting a new one at `index` (default: last).\n *\n * @public\n */\nexport interface SetOverrideOp {\n /** The discriminant. */\n readonly op: \"setOverride\";\n /** The instance root's uid. */\n readonly entity: string;\n /** The override. */\n readonly override: SceneFileOverride;\n /** Where a new override goes; defaults to the end. */\n readonly index?: number;\n}\n\n/**\n * Removes an override from an instance root's entry.\n *\n * @public\n */\nexport interface RemoveOverrideOp {\n /** The discriminant. */\n readonly op: \"removeOverride\";\n /** The instance root's uid. */\n readonly entity: string;\n /** The override's path. */\n readonly path: string;\n /** The override's `op`; defaults to what the path implies. */\n readonly overrideOp?: \"replace\" | \"remove\" | \"add\";\n /** For a component `add`, the uid of the component it adds. */\n readonly added?: string;\n}\n\n/**\n * One scene op: the closed vocabulary of plan §3.4, identical to `@ignifx/editor-core`'s `SceneOp`.\n *\n * @public\n */\nexport type SceneOp =\n | CreateEntityOp\n | DestroyEntityOp\n | ReparentOp\n | ReorderOp\n | SetEntityFieldOp\n | SetTransformOp\n | AddComponentOp\n | RemoveComponentOp\n | SetPropOp\n | SetSceneSettingOp\n | InstantiateOp\n | SetOverrideOp\n | RemoveOverrideOp;\n\n/**\n * Tells whether a value is an insertion index: a non-negative safe integer. Whether it is in range\n * is the applier's question.\n *\n * @param value - The value to test.\n * @returns True for a non-negative safe integer.\n */\nfunction isIndex(value: unknown): boolean {\n return Number.isSafeInteger(value) && Number(value) >= 0;\n}\n\n/**\n * Tells whether a value is a JSON path.\n *\n * @param value - The value to test.\n * @returns True for an array of strings and non-negative safe integers.\n */\nfunction isJsonPath(value: unknown): value is JsonPath {\n return isArrayOf(value, (step): step is string | number => isString(step) || isIndex(step));\n}\n\n/**\n * Tells whether a value is a parent: a uid or `null`.\n *\n * @param value - The value to test.\n * @returns True for `null` or a uid.\n */\nfunction isParent(value: unknown): value is string | null {\n return value === null || isUidString(value);\n}\n\n/** The value test for each field {@link SetEntityFieldOp} writes. */\nconst ENTITY_FIELD_TESTS: Readonly<Record<EntityField, (value: unknown) => boolean>> = {\n name: isString,\n active: isBoolean,\n static: isBoolean,\n layer: isString,\n tags: (value) => isArrayOf(value, isString),\n};\n\n/** The structural test of each op's fields beyond `op`. */\nconst OP_TESTS: Readonly<Record<SceneOpKind, (op: Record<string, unknown>) => boolean>> = {\n createEntity: (op) =>\n isSceneFileEntity(op[\"entity\"]) &&\n optionalField(op, \"index\", isIndex) &&\n optionalField(op, \"descendants\", (descendants) => isArrayOf(descendants, isSceneFileEntity)),\n destroyEntity: (op) => isUidString(op[\"entity\"]),\n reparent: (op) => isUidString(op[\"entity\"]) && isParent(op[\"parent\"]) && optionalField(op, \"index\", isIndex),\n reorder: (op) => isUidString(op[\"entity\"]) && isIndex(op[\"index\"]),\n setEntityField: (op) => {\n const field = op[\"field\"];\n const test = Object.entries(ENTITY_FIELD_TESTS).find(([name]) => name === field)?.[1];\n return isUidString(op[\"entity\"]) && test !== undefined && test(op[\"value\"]);\n },\n setTransform: (op) =>\n isUidString(op[\"entity\"]) && isSceneFileTransform(op[\"after\"]) && optionalField(op, \"before\", isSceneFileTransform),\n addComponent: (op) =>\n isUidString(op[\"entity\"]) && isSceneFileComponent(op[\"component\"]) && optionalField(op, \"index\", isIndex),\n removeComponent: (op) => isUidString(op[\"component\"]),\n setProp: (op) =>\n isUidString(op[\"component\"]) && isJsonPath(op[\"path\"]) && optionalField(op, \"value\", (value) => isJsonValue(value)),\n setSceneSetting: (op) => isJsonPath(op[\"path\"]) && optionalField(op, \"value\", (value) => isJsonValue(value)),\n instantiate: (op) =>\n isUidString(op[\"entity\"]) &&\n isString(op[\"name\"]) &&\n isParent(op[\"parent\"]) &&\n optionalField(op, \"index\", isIndex) &&\n isSceneFileTransform(op[\"transform\"]) &&\n isSceneFileInstance(op[\"instance\"]),\n setOverride: (op) =>\n isUidString(op[\"entity\"]) && isSceneFileOverride(op[\"override\"]) && optionalField(op, \"index\", isIndex),\n removeOverride: (op) =>\n isUidString(op[\"entity\"]) &&\n isString(op[\"path\"]) &&\n optionalField(op, \"overrideOp\", isOverrideOp) &&\n optionalField(op, \"added\", isUidString),\n};\n\n/**\n * Checks the structure of one scene op: a known `op` and fields of the right types.\n *\n * @remarks\n * It answers \"is this an op of the vocabulary\", not \"does it apply\": uids are checked to be\n * non-empty strings, indices to be non-negative integers, values to be JSON, and records to have the\n * scene format's shape. Unknown extra fields are ignored. A `setProp` or `setSceneSetting` value may\n * be any JSON; that the empty path receives an object is the applier's check.\n *\n * @param value - A received op.\n * @returns True when `value` is a structurally valid {@link SceneOp}.\n *\n * @example\n * ```ts\n * isSceneOp({ op: \"setEntityField\", entity: \"01J9Z6M7E5S3A0V2Q4R8T1Y6WX\", field: \"name\", value: \"Player\" }); // true\n * isSceneOp({ op: \"setEntityField\", entity: \"01J9Z6M7E5S3A0V2Q4R8T1Y6WX\", field: \"name\", value: 3 }); // false\n * ```\n *\n * @public\n */\nexport function isSceneOp(value: unknown): value is SceneOp {\n if (!isRecord(value)) {\n return false;\n }\n const kind = value[\"op\"];\n const test = Object.entries(OP_TESTS).find(([name]) => name === kind)?.[1];\n return test !== undefined && test(value);\n}\n","// A copy of `packages/editor-protocol/src/scene.ts` from `astrum-forge/ignifx-editor` (protocol 0.3).\n// Below this comment it is byte-identical to that file, but for the link rule in `./index.ts`.\n/**\n * Protocol 0.3: the scene document transport between the editor and the scene view\n * (`@ignifx/editor-host`). Plan §3.4, §3.5, §3.7.\n *\n * The editor holds the scene document (`@ignifx/editor-core`) and the host mirrors it into a live\n * world: the editor opens the scene with the whole file, then sends every command's ops as it\n * applies them. The host reports what the user does in the view (a pick click, a gizmo drag) as\n * notifications, which the editor turns into commands of its own; the host never edits the document.\n * `docs/protocol.md`, \"0.3: scene documents\", gives the sequences and what the host must do per\n * method.\n */\nimport { isHostList, isHostText, isHostTextOrNull } from \"./handshake.js\";\nimport { isRecord } from \"./rpc.js\";\nimport {\n isArrayOf,\n isBoolean,\n isFiniteNumber,\n isJsonObject,\n isJsonValue,\n isNumberTuple,\n isSceneFile,\n isSceneFileEntity,\n isSceneFileTransform,\n isString,\n isUidString,\n optionalField,\n} from \"./scene-file.js\";\nimport { isSceneOp } from \"./scene-ops.js\";\nimport type { RpcNotification, RpcRequest, RpcSuccessResponse } from \"./rpc.js\";\nimport type { JsonObject, JsonValue, SceneFile, SceneFileEntity, SceneFileTransform } from \"./scene-file.js\";\nimport type { SceneOp } from \"./scene-ops.js\";\n\n/**\n * Editor → scene host: the methods of protocol 0.3, answered after `ready`.\n *\n * @remarks\n * `as const` object plus derived union rather than an `enum` (engine coding standards §5.2, §5.3).\n *\n * The host handles these requests one at a time, in the order they arrive: a request starts only\n * after the previous one has been answered, so `applyOps` sent right after `openScene` sees the new\n * scene. Until the host's app has started, every one of them fails with `RpcErrorCode.notReady`;\n * the host's first `schemasChanged` is the editor's cue that they are accepted. A method that needs\n * an open scene fails with `RpcErrorCode.noScene` while none is open. A method whose capability the\n * host does not list in `ready` fails with `RpcErrorCode.methodNotFound`.\n *\n * @public\n */\nexport const SceneMethod = {\n /** Opens a scene from the editor's document, replacing any open scene. Answers {@link OpenSceneResult}. */\n openScene: \"openScene\",\n /** Unloads the open scene, if any. Answers `null`. */\n closeScene: \"closeScene\",\n /** Applies one command's ops to the open scene, in order. Answers {@link ApplyOpsResult}. */\n applyOps: \"applyOps\",\n /** Serializes entities of the open scene as the live world has them. Answers {@link ReadBackResult}. */\n readBack: \"readBack\",\n /** Sets the selection the view outlines and attaches the gizmo to. Answers {@link EntitySelection}. */\n select: \"select\",\n /** Sets the gizmo's mode, space and snapping. Needs `HostCapability.gizmos`. Answers `null`. */\n setGizmo: \"setGizmo\",\n /** Moves the editor camera to frame entities. Answers `null`. */\n frame: \"frame\",\n /** Asks which entity is under a point of the view, without selecting it. Answers {@link PickResult}. */\n pick: \"pick\",\n /** Captures the view as an image. Needs `HostCapability.screenshot`. Answers {@link ScreenshotResult}. */\n screenshot: \"screenshot\",\n /** Describes every registered component's schema. Answers {@link SchemaSet}. */\n getSchemas: \"getSchemas\",\n /**\n * Describes the project's settings sections and the values the app resolved for them. Answers\n * {@link SettingsSet}. A host from before it answers `RpcErrorCode.methodNotFound`.\n */\n describeSettings: \"describeSettings\",\n /** Switches the view between the 3D and the 2D editor camera. Answers `null`. */\n setViewMode: \"setViewMode\",\n /**\n * Turns the editor's \"animate materials\" toggle on or off: whether the shader clock runs in the\n * scene view. Answers `null`. The host starts with it on, after every load. A host from before it\n * answers `RpcErrorCode.methodNotFound`. Additive in 0.3.\n */\n setAnimateMaterials: \"setAnimateMaterials\",\n /**\n * Outlines the colliders of entities of the open scene, as world-space line segments, for the\n * editor's collider gizmos. Answers {@link ColliderOutlineSet}. A host from before it answers\n * `RpcErrorCode.methodNotFound`. Additive in 0.3.\n */\n getColliderOutlines: \"getColliderOutlines\",\n /**\n * Poses an entity's `Animator` at one point of one state without playing it (engine ADR-0028,\n * amendment 2026-10-20). Answers {@link SampleAnimationResult}. A host from before it answers\n * `RpcErrorCode.methodNotFound`. Additive in 0.3.\n */\n sampleAnimation: \"sampleAnimation\",\n} as const;\n\n/**\n * The union of the names in `SceneMethod`.\n *\n * @public\n */\nexport type SceneMethod = (typeof SceneMethod)[keyof typeof SceneMethod];\n\n/**\n * Scene host → editor: the notifications of protocol 0.3. None has an answer.\n *\n * @remarks\n * There is no `reloadScripts` method: script hot reload is Vite's. When a script changes, Vite\n * replaces the module in the host page, `acceptHotReload(app)` hands the new classes to\n * `app.hotReload.apply`, and the host reports the outcome with `hotReloaded` and `schemasChanged`.\n * A change that Vite cannot hot-replace reloads the host page, which the editor sees as a new load:\n * a new port, a new handshake, and `openScene` again.\n *\n * @public\n */\nexport const SceneNotification = {\n /** After the answer to every successful `openScene`: what was opened. */\n sceneOpened: \"sceneOpened\",\n /** Once the app has started (after `ready`), and after every hot reload: the component schemas. */\n schemasChanged: \"schemasChanged\",\n /** After every `app.hotReload` operation: its report. */\n hotReloaded: \"hotReloaded\",\n /** After a click in the view changed the selection: the new selection. */\n selectionChanged: \"selectionChanged\",\n /** During a gizmo drag, at most every {@link TRANSFORM_DRAGGING_INTERVAL_MS}: for display only. */\n transformDragging: \"transformDragging\",\n /** Once per gizmo gesture, at pointer-up: the editor turns it into a `setTransform` command. */\n transformDragged: \"transformDragged\",\n /** A failure that answers no request: an error the app reported, a failed hot reload. */\n hostError: \"hostError\",\n /** One line from the app's logger, for the editor's Console. */\n log: \"log\",\n /**\n * After the host reloaded an asset that changed on disk, in place: its address, its type, and\n * the document's instance roots rebuilt from it. A host from before it sends nothing.\n */\n assetReloaded: \"assetReloaded\",\n} as const;\n\n/**\n * The union of the names in `SceneNotification`.\n *\n * @public\n */\nexport type SceneNotification = (typeof SceneNotification)[keyof typeof SceneNotification];\n\n/**\n * The fewest milliseconds between two `transformDragging` notifications for the same gesture: at\n * most 20 a second, which S0.2 measured as smooth enough for an inspector to follow a drag.\n *\n * @public\n */\nexport const TRANSFORM_DRAGGING_INTERVAL_MS = 50;\n\n/**\n * The largest width and height, in pixels, of a `screenshot`. A request for more fails with\n * `invalidParams`; a request without a size gets the view's own size scaled down to fit. It keeps\n * an image well under what an MCP client accepts inline (plan §3.11).\n *\n * @public\n */\nexport const SCREENSHOT_MAX_SIZE = 2048;\n\n/**\n * The most entities one `getColliderOutlines` request outlines; the rest of a longer list are left\n * out and the answer says `truncated`.\n *\n * @public\n */\nexport const COLLIDER_OUTLINES_MAX_ENTITIES = 256;\n\n/**\n * The most numbers all the `lines` of one `getColliderOutlines` answer hold together, 100 000\n * segments: an outline that would pass it is left out, with every one after it, and the answer\n * says `truncated`.\n *\n * @public\n */\nexport const COLLIDER_OUTLINES_MAX_NUMBERS = 600_000;\n\n/**\n * The most parameter values one `sampleAnimation` request may carry. A request with more fails\n * with `invalidParams`.\n *\n * @public\n */\nexport const SAMPLE_ANIMATION_MAX_PARAMETERS = 64;\n\n/**\n * The longest `entity`, `state` or parameter name, in UTF-16 code units, one `sampleAnimation`\n * request may carry. A request with a longer one fails with `invalidParams`. It also bounds the\n * names an error message echoes back.\n *\n * @public\n */\nexport const SAMPLE_ANIMATION_MAX_NAME_LENGTH = 256;\n\n/**\n * A world-space point, `[x, y, z]`, in metres.\n *\n * @public\n */\nexport type Vec3 = readonly [number, number, number];\n\n/**\n * One recoverable problem the engine reported while building or serializing a scene: the engine's\n * `SceneLoadIssue` and `SerializeIssue`.\n *\n * @public\n */\nexport interface SceneIssue {\n /** The engine's diagnostic code, for example `\"IGX-0602\"`. */\n readonly code: string;\n /** The engine's actionable sentence. */\n readonly message: string;\n}\n\n/**\n * One structural problem in a scene file: the engine's `SceneFileIssue`, from `validateSceneFile`.\n *\n * @public\n */\nexport interface SceneFileIssue {\n /** Where the problem is, for example `\"entities/3/transform\"`. */\n readonly path: string;\n /** An actionable description. */\n readonly message: string;\n}\n\n/**\n * The parameters of `openScene`.\n *\n * @public\n */\nexport interface OpenSceneParams {\n /**\n * The whole scene file, as the editor's document holds it: the engine's `SceneFile` object, not\n * its text. It may differ from the file on disk (unsaved edits), so it is the only source the\n * host builds from.\n */\n readonly file: SceneFile;\n /**\n * The asset address the document is saved at, for example `\"scenes/level01.scene.json\"`, or\n * `null` for a document that has never been saved. The host names the scene's asset with it and\n * never loads the file from it.\n */\n readonly address: string | null;\n}\n\n/**\n * The answer to `openScene`, once every entity is built.\n *\n * @public\n */\nexport interface OpenSceneResult {\n /** How many entities the host built, including those expanded from instanced scenes. */\n readonly entityCount: number;\n /** Every recoverable problem the build reported, in order (`SceneBuildResult.issues`). */\n readonly warnings: readonly SceneIssue[];\n /**\n * The editor camera the scene is made for, as the host's engine sees it: `\"2d\"` when the project\n * draws sprites only (`twoD.mode: \"sprite\"`) or the scene's cameras are all `Camera2D`, else\n * `\"3d\"`. The host does not switch to it; the editor sends `setViewMode`. Absent from a host from\n * before it.\n */\n readonly viewMode?: ViewMode;\n}\n\n/**\n * The `data` of the `invalidParams` error `openScene` answers when `validateSceneFile` refuses the\n * file.\n *\n * @public\n */\nexport interface InvalidSceneFileData {\n /** What `validateSceneFile` reported. */\n readonly issues: readonly SceneFileIssue[];\n}\n\n/**\n * The parameters of `applyOps`: one command, as the editor applied it to its document.\n *\n * @public\n */\nexport interface ApplyOpsParams {\n /** The ops, in the order they apply. Undo sends the inverse ops; redo sends the ops again. */\n readonly ops: readonly SceneOp[];\n /** The command's label, for example `\"Move Player\"`, for the host's log. */\n readonly commandName: string;\n /** The editor's id for this command, unique on the channel, for correlating logs and failures. */\n readonly commandId: string;\n}\n\n/**\n * Why the host could not apply one op.\n *\n * @remarks\n * The first ten are `@ignifx/editor-core`'s `OpErrorCode`s, with its meanings, for a world that\n * disagrees with the document the op was checked against. The last two are the host's own.\n *\n * @public\n */\nexport const ApplyOpFailureCode = {\n /** Not an op of the vocabulary. */\n invalidOp: \"invalidOp\",\n /** The target entity uid is not in the open scene. */\n unknownEntity: \"unknownEntity\",\n /** The target component uid is not in the open scene. */\n unknownComponent: \"unknownComponent\",\n /** A new entity or component reuses a uid. */\n duplicateUid: \"duplicateUid\",\n /** A parent outside the scene, or a move under its own subtree. */\n invalidParent: \"invalidParent\",\n /** An index outside the list it positions in. */\n invalidIndex: \"invalidIndex\",\n /** A value of the wrong shape for its field. */\n invalidValue: \"invalidValue\",\n /** A JSON path or override path that does not resolve. */\n invalidPath: \"invalidPath\",\n /** An override op on an entity without an `instance` entry. */\n notAnInstance: \"notAnInstance\",\n /** No override with that identity. */\n unknownOverride: \"unknownOverride\",\n /** The host cannot apply this op to a live world yet; the editor reopens the scene instead. */\n unsupportedOp: \"unsupportedOp\",\n /** The engine threw while applying the op; `diagnostic` carries its `IGX-` code when it had one. */\n engineError: \"engineError\",\n} as const;\n\n/**\n * The union of the codes in `ApplyOpFailureCode`.\n *\n * @public\n */\nexport type ApplyOpFailureCode = (typeof ApplyOpFailureCode)[keyof typeof ApplyOpFailureCode];\n\n/**\n * One op the host could not apply.\n *\n * @public\n */\nexport interface ApplyOpFailure {\n /** The op's index in `ApplyOpsParams.ops`. */\n readonly index: number;\n /** Why it failed. */\n readonly code: ApplyOpFailureCode;\n /** An actionable sentence. */\n readonly message: string;\n /** The engine's diagnostic code, for example `\"IGX-0307\"`, when the engine reported one. */\n readonly diagnostic?: string;\n}\n\n/**\n * The answer to `applyOps`.\n *\n * @remarks\n * The host applies the ops in order and does not stop at a failure, so `applied + failures.length`\n * is the number of ops sent. Any failure means the live world no longer mirrors the document; the\n * editor then sends `openScene` with the whole document again.\n *\n * @public\n */\nexport interface ApplyOpsResult {\n /** How many ops were applied. */\n readonly applied: number;\n /** The ops that were not, in order. */\n readonly failures: readonly ApplyOpFailure[];\n /**\n * Every recoverable problem the engine reported while the host applied these ops, in order: what\n * a subtree an op or an instance rebuild built reported (an override that names nothing in the\n * prefab, a reference that resolves nowhere in the document), in the form of\n * {@link OpenSceneResult}'s `warnings`. The host also logs each one as a `log` warning; this list\n * is the one tied to the command. Empty when there were none; absent from a host from before it,\n * which an editor treats as unknown, not as none.\n */\n readonly warnings?: readonly SceneIssue[];\n}\n\n/**\n * The parameters of `readBack`.\n *\n * @public\n */\nexport interface ReadBackParams {\n /** The entities to serialize; absent for every entity of the open scene. */\n readonly entities?: readonly string[];\n}\n\n/**\n * The answer to `readBack`: the open scene's entities as `serializeScene` writes them from the live\n * world, which is what the document should hold when the mirror is exact.\n *\n * @public\n */\nexport interface ReadBackResult {\n /** The entity records, in tree order, as `serializeScene` writes them. */\n readonly entities: readonly SceneFileEntity[];\n /** The requested uids that name no entity of the open scene, in request order. */\n readonly missing: readonly string[];\n /** The scene's `settings`, or `null` when it has none. */\n readonly settings: JsonObject | null;\n /** What the serializer reported (`SerializeIssue`), in order. */\n readonly issues: readonly SceneIssue[];\n}\n\n/**\n * A selection: the parameters and the answer of `select`, and the parameters of `selectionChanged`.\n *\n * @public\n */\nexport interface EntitySelection {\n /** The selected entities' uids. The last one is the primary selection, which the gizmo follows. */\n readonly entities: readonly string[];\n}\n\n/**\n * What the gizmo does.\n *\n * @public\n */\nexport const GizmoMode = {\n /** Move along axes and planes. */\n translate: \"translate\",\n /** Rotate around axes. */\n rotate: \"rotate\",\n /** Scale along axes and uniformly. */\n scale: \"scale\",\n /** No gizmo; the selection is only outlined. */\n none: \"none\",\n} as const;\n\n/**\n * The union of the modes in `GizmoMode`.\n *\n * @public\n */\nexport type GizmoMode = (typeof GizmoMode)[keyof typeof GizmoMode];\n\n/**\n * The gizmo modes a drag can happen in: every `GizmoMode` but `none`.\n *\n * @public\n */\nexport type GizmoDragMode = Exclude<GizmoMode, typeof GizmoMode.none>;\n\n/**\n * Which axes the gizmo follows.\n *\n * @public\n */\nexport const GizmoSpace = {\n /** The entity's own axes. */\n local: \"local\",\n /** The world's axes. */\n world: \"world\",\n} as const;\n\n/**\n * The union of the spaces in `GizmoSpace`.\n *\n * @public\n */\nexport type GizmoSpace = (typeof GizmoSpace)[keyof typeof GizmoSpace];\n\n/**\n * The gizmo's snapping increments. `0` turns snapping off for that mode.\n *\n * @public\n */\nexport interface GizmoSnap {\n /** The translation step, in metres. */\n readonly translate: number;\n /** The rotation step, in degrees. */\n readonly rotate: number;\n /** The scale step, as a factor added per step (`0.1` snaps scale to tenths). */\n readonly scale: number;\n}\n\n/**\n * The parameters of `setGizmo`.\n *\n * @public\n */\nexport interface SetGizmoParams {\n /** What the gizmo does. */\n readonly mode: GizmoMode;\n /** Which axes it follows. */\n readonly space: GizmoSpace;\n /** The snapping increments, or `null` for no snapping. */\n readonly snap: GizmoSnap | null;\n}\n\n/**\n * The parameters of `frame`.\n *\n * @public\n */\nexport interface FrameParams {\n /** The entities to fit in the view, or `\"all\"` for the whole open scene. */\n readonly entities: readonly string[] | \"all\";\n}\n\n/**\n * The unit of a `pick` point (S0.2 §6.1).\n *\n * @public\n */\nexport const PickUnit = {\n /** CSS pixels from the view's top-left corner: a DOM event's `offsetX` and `offsetY`. */\n css: \"css\",\n /** The canvas's backing-store pixels: CSS pixels times `canvas.width / canvas.clientWidth`. */\n backing: \"backing\",\n} as const;\n\n/**\n * The union of the units in `PickUnit`.\n *\n * @public\n */\nexport type PickUnit = (typeof PickUnit)[keyof typeof PickUnit];\n\n/**\n * The parameters of `pick`.\n *\n * @public\n */\nexport interface PickParams {\n /** The point's x, from the view's left edge, in `unit`. */\n readonly x: number;\n /** The point's y, from the view's top edge, in `unit`. */\n readonly y: number;\n /** The unit of `x` and `y`; the host converts it to whatever its engine's picker takes. */\n readonly unit: PickUnit;\n}\n\n/**\n * A world-space ray from the view's camera through a point of the view.\n *\n * @public\n */\nexport interface PickRay {\n /** Where the ray starts, in metres: the point under the cursor on the camera's near plane. */\n readonly origin: Vec3;\n /** Which way it points: a unit vector. */\n readonly direction: Vec3;\n}\n\n/**\n * The answer to `pick`.\n *\n * @public\n */\nexport interface PickResult {\n /** The scene entity hit, or `null` for a miss. A hit inside an instanced scene names its instance root. */\n readonly entity: string | null;\n /** The world-space hit point, or `null` for a miss or when the picker does not report one. */\n readonly point: Vec3 | null;\n /** How far along the camera ray the hit is, in metres, or `null` for a miss or a 2D pick. */\n readonly distance: number | null;\n /**\n * The ray the view's camera casts through the point, hit or miss, so that an editor can place\n * something where nothing was hit (a 3D editor intersects it with its ground plane, `y = 0`).\n * Absent when the host builds no ray (a headless view, a point outside the canvas) and from a host\n * from before it.\n */\n readonly ray?: PickRay;\n /**\n * Where `ray` meets the 2D world plane `z = 0`, as `[x, y, 0]`: in a 2D scene, the world point\n * under the cursor. Absent when `ray` is, and when the ray runs parallel to the plane or meets it\n * behind its origin.\n */\n readonly plane?: Vec3;\n}\n\n/**\n * The image formats of a `screenshot`.\n *\n * @public\n */\nexport const ScreenshotFormat = {\n /** Lossless, `image/png`. */\n png: \"png\",\n /** Lossy, `image/jpeg`. */\n jpeg: \"jpeg\",\n} as const;\n\n/**\n * The union of the formats in `ScreenshotFormat`.\n *\n * @public\n */\nexport type ScreenshotFormat = (typeof ScreenshotFormat)[keyof typeof ScreenshotFormat];\n\n/**\n * The parameters of `screenshot`.\n *\n * @public\n */\nexport interface ScreenshotParams {\n /** The image width in pixels, 1 to {@link SCREENSHOT_MAX_SIZE}; absent to follow the view. */\n readonly width?: number;\n /** The image height in pixels, 1 to {@link SCREENSHOT_MAX_SIZE}; absent to follow the view. */\n readonly height?: number;\n /** The image format. */\n readonly format: ScreenshotFormat;\n /** The JPEG quality, from 0 to 1; the host's default (0.9) when absent. Ignored for PNG. */\n readonly quality?: number;\n}\n\n/**\n * The answer to `screenshot`.\n *\n * @public\n */\nexport interface ScreenshotResult {\n /** The image as a `data:image/png;base64,…` or `data:image/jpeg;base64,…` URL. */\n readonly dataUrl: string;\n /** The image width in pixels. */\n readonly width: number;\n /** The image height in pixels. */\n readonly height: number;\n}\n\n/**\n * One field of a component schema: the engine's `SchemaFieldDescription`.\n *\n * @public\n */\nexport interface SchemaFieldDescription {\n /** The field kind, for example `\"f32\"` or `\"asset\"`; an editor shows a kind it does not know as JSON. */\n readonly kind: string;\n /** The field's default value, encoded as JSON. */\n readonly default?: JsonValue;\n /** The field's tooltip. */\n readonly description?: string;\n /**\n * The increment of the inspector's drag and spinner controls (`FieldOptions.step`), present only\n * when the field declares one; in degrees for a `quat` field, which an inspector edits as Euler\n * angles.\n */\n readonly step?: number;\n /** `FieldOptions.hidden`: the inspector leaves the field out; it is still saved. */\n readonly hidden?: boolean;\n /** `FieldOptions.readonly`: the inspector shows the field but does not let it be edited. */\n readonly readonly?: boolean;\n /** `FieldOptions.group`: the inspector group the field folds into. */\n readonly group?: string;\n /**\n * An `asset` field's asset type name (`asset(TextureAsset)` → `\"texture\"`), the `type` an asset\n * reference to it carries; absent when the asset token names no type.\n */\n readonly assetType?: string;\n /**\n * A `componentRef` field's accepted component, as its `typeId`, or `null` when the class it was\n * declared with carries no `typeId`; present on every `componentRef` field a 0.3 host describes\n * with core's `describeRegisteredSchemas`.\n */\n readonly componentType?: string | null;\n}\n\n/**\n * One component schema: the engine's `SchemaDescription`, plus the JSON Schema of its `props`.\n *\n * @public\n */\nexport interface SchemaDescription {\n /** The human-readable name. */\n readonly title: string;\n /** `\"components\"` for a component; a file format's name for the engine's file-format entries. */\n readonly format: string;\n /** A one-line summary. */\n readonly description?: string;\n /** Every declared field, in declaration order. */\n readonly fields: Readonly<Record<string, SchemaFieldDescription>>;\n /**\n * Whether an entity may hold more than one of the component (the class's `static allowMultiple`,\n * `true` when it declares nothing); absent on file-format entries and from a host from before\n * core's `describeRegisteredSchemas`, where an editor assumes `true`.\n */\n readonly allowMultiple?: boolean;\n /**\n * Who registered the component: the extension's `name` (the npm package name, for example\n * `@ignifx/3d`), or, for a class the game registered itself, its type id's namespace (`game` for\n * `game/Health`); absent on file-format entries and from a host from before\n * `describeRegisteredSchemas`.\n */\n readonly package?: string;\n /**\n * `true` for the one component every entity carries itself, `ignifx/Transform`: it is never in a\n * scene file's `components` list, an editor neither adds nor removes it, and its fields are the\n * entity record's `transform` block, edited whole with the `setTransform` op rather than prop by\n * prop. Absent on every other entry. A host from before the engine described the transform (engine\n * ask E4) sends no such member.\n */\n readonly builtIn?: boolean;\n /**\n * The components the class lists in `static requires`, as type ids (`null` for a class without a\n * `typeId`), in declaration order. The engine adds each one that is missing whenever the component\n * is added, so an editor adds them itself as part of the same command; a component whose class\n * extends a required one counts. Absent when the class requires nothing, on file-format entries,\n * and from a host from before engine ask E33.\n */\n readonly requires?: readonly (string | null)[];\n /**\n * The type ids of the registered components the class extends, nearest first: each ancestor class\n * registered under its own `static typeId`. The class itself and its unregistered ancestors (an\n * abstract base, `Component`, `Script`) are left out. The engine counts a component whose class\n * extends a required one as present, so an editor treats a `requires` entry as present on an\n * entity when one of its components has that type id or lists it here. Empty when the class\n * extends no registered component; absent on file-format entries and from a host from before\n * engine ask E44, which an editor treats as unknown, not as none.\n */\n readonly extends?: readonly string[];\n /**\n * The JSON Schema of the component's `props` (the engine's `toJsonSchema(schema)`), which adds\n * each field's `minimum`, `maximum`, `enum` and nested shapes; absent for file-format entries.\n */\n readonly propsSchema?: JsonObject;\n}\n\n/**\n * Every schema the host's app knows: the answer to `getSchemas` and the parameters of\n * `schemasChanged`.\n *\n * @public\n */\nexport interface SchemaSet {\n /** The descriptions, keyed by component `typeId` (file formats by `ignifx/<format>-file`). */\n readonly schemas: Readonly<Record<string, SchemaDescription>>;\n}\n\n/**\n * The project's settings as the host's app has them: the answer to `describeSettings`.\n *\n * @public\n */\nexport interface SettingsSet {\n /**\n * Every settings section the app registered (core's and each extension's), keyed by section name,\n * in registration order: the engine's `describeSettings(app)`. Each has `format: \"settings\"`, the\n * registering extension as `package`, field defaults in the settings form (a vector is\n * `{ x, y, z }` and a colour `{ r, g, b, a }`, not the scene file's arrays), and as `propsSchema`\n * the JSON Schema of the section as `ignifx.settings.json` may write it (its entry in the engine's\n * `settingsJsonSchema(app)`).\n */\n readonly sections: Readonly<Record<string, SchemaDescription>>;\n /**\n * The values the app resolved for each section, keyed by section name, in the same settings form:\n * the project's settings over the section's defaults. A value JSON cannot carry (a function, a\n * non-finite number) is left out.\n */\n readonly values: Readonly<Record<string, JsonObject>>;\n}\n\n/**\n * The editor cameras the view can use.\n *\n * @public\n */\nexport const ViewMode = {\n /** The 3D editor camera, gizmos and grid. */\n threeD: \"3d\",\n /** The 2D editor camera, planar gizmos and pixel grid. Needs `HostCapability.viewMode2d`. */\n twoD: \"2d\",\n} as const;\n\n/**\n * The union of the modes in `ViewMode`.\n *\n * @public\n */\nexport type ViewMode = (typeof ViewMode)[keyof typeof ViewMode];\n\n/**\n * The parameters of `setViewMode`.\n *\n * @public\n */\nexport interface SetViewModeParams {\n /** The editor camera to use. */\n readonly mode: ViewMode;\n}\n\n/**\n * The parameters of `setAnimateMaterials`.\n *\n * @public\n */\nexport interface SetAnimateMaterialsParams {\n /** Whether the shader clock (`time` in shader materials and custom post effects) runs. */\n readonly enabled: boolean;\n}\n\n/**\n * One collider's outline in the answer to `getColliderOutlines`.\n *\n * @public\n */\nexport interface ColliderOutlineRecord {\n /** The uid of the entity the collider is on. */\n readonly entity: string;\n /** The collider component's uid. */\n readonly component: string;\n /** Whether the collider is a trigger. */\n readonly isTrigger: boolean;\n /**\n * World-space line segments in metres: every six numbers are one segment, the `x, y, z` of its\n * two ends. A 2D collider's segments lie at its entity's world `z`. Empty for a collider the\n * engine cannot outline, such as a 3D `MeshCollider`.\n */\n readonly lines: readonly number[];\n}\n\n/**\n * The answer to `getColliderOutlines`.\n *\n * @public\n */\nexport interface ColliderOutlineSet {\n /**\n * One record per enabled collider of each requested entity that the open scene has, in request\n * order and then component order. Empty when the project registers no physics extension.\n */\n readonly outlines: readonly ColliderOutlineRecord[];\n /**\n * True when outlines were left out: the request named more than\n * {@link COLLIDER_OUTLINES_MAX_ENTITIES} entities, or the lines would have passed\n * {@link COLLIDER_OUTLINES_MAX_NUMBERS} numbers. The outlines sent are whole.\n */\n readonly truncated: boolean;\n}\n\n/**\n * The parameters of `sampleAnimation`.\n *\n * @remarks\n * The host calls the engine's `Animator.sample(state, normalizedTime, { parameters })` on the\n * entity's `Animator`. A time inside `[0, 1]` is used as given; outside it a looping state wraps\n * and a one-shot state clamps. The state replaces its own layer and every other layer keeps its\n * current pose; nothing else about the animator changes, and in an edit-mode scene view the pose\n * stays until the next sample. Names are at most {@link SAMPLE_ANIMATION_MAX_NAME_LENGTH} long and\n * `parameters` holds at most {@link SAMPLE_ANIMATION_MAX_PARAMETERS} values. An entity the open scene\n * lacks, or one without an `Animator`, is refused with `RpcErrorCode.invalidParams`, and so is\n * whatever the engine refuses (an unknown state or parameter, an entity with no model to pose),\n * with the engine's code as `data.code`.\n *\n * @public\n */\nexport interface SampleAnimationParams {\n /** The uid of the document entity whose `Animator` is posed. */\n readonly entity: string;\n /** The state's name in the animator document. */\n readonly state: string;\n /** How far into the state, where `0` is its start and `1` its end. */\n readonly normalizedTime: number;\n /**\n * Parameter values this sample reads instead of the animator's own, by name: a number for a\n * `float` or `int`, a boolean for a `bool`. A blend-tree state reads its parameter here first.\n */\n readonly parameters?: Readonly<Record<string, number | boolean>>;\n}\n\n/**\n * The answer to `sampleAnimation`.\n *\n * @public\n */\nexport interface SampleAnimationResult {\n /**\n * Whether the pose was written. `false` while the animator document or the model's clips are\n * still loading, and always in a headless host; the editor may send the request again later.\n */\n readonly posed: boolean;\n}\n\n/**\n * The parameters of `sceneOpened`.\n *\n * @public\n */\nexport interface SceneOpenedParams {\n /** The address `openScene` was given. */\n readonly address: string | null;\n /** The file's `name`. */\n readonly name: string;\n /** As in {@link OpenSceneResult}. */\n readonly entityCount: number;\n /** As in {@link OpenSceneResult}. */\n readonly warnings: readonly SceneIssue[];\n /** As in {@link OpenSceneResult}. */\n readonly viewMode?: ViewMode;\n}\n\n/**\n * One error a hot reload ran into.\n *\n * @public\n */\nexport interface HotReloadError {\n /** The error's message (`String(error)` when it is not an `Error`). */\n readonly message: string;\n /** Its `IGX-` code when it is an `IgnifxError`, else `null`. */\n readonly code: string | null;\n /** Its `stack`, or `null` when it has none. Additive in 0.3: a host from before it leaves it out. */\n readonly stack?: string | null;\n}\n\n/**\n * What one hot reload did: the engine's `HotReloadReport`, with its errors made JSON.\n *\n * @public\n */\nexport interface HotReloadReport {\n /** Which operation: a prototype swap, a recreate of instances, or a scene rebuild. */\n readonly kind: \"patch\" | \"recreate\" | \"scene\";\n /** The `typeId`s reloaded, in the order applied. */\n readonly typeIds: readonly string[];\n /** How many live component instances were swapped or re-created, or entities rebuilt. */\n readonly instances: number;\n /** How long it took, in milliseconds. */\n readonly durationMs: number;\n /** Everything that threw on the way. */\n readonly errors: readonly HotReloadError[];\n}\n\n/**\n * The parameters of `hotReloaded`.\n *\n * @public\n */\nexport interface HotReloadedParams {\n /** The report `app.hotReload.onApplied` emitted. */\n readonly report: HotReloadReport;\n}\n\n/**\n * The parameters of `assetReloaded`.\n *\n * @remarks\n * The host reloads an asset in place when the dev server reports it changed on disk and the scene\n * view's app has it loaded: a scene or prefab (`\"scene\"`), whose document instances it rebuilds from\n * the new file with their uids, transforms and overrides, and a model, mesh, material, sprite atlas\n * or shader, which the renderers pick up on their next frame. Any other type, such as a texture, is\n * left as it was loaded and sends nothing. The open document's own file is never reloaded.\n *\n * @public\n */\nexport interface AssetReloadedParams {\n /** The asset's address, relative to the asset root. */\n readonly address: string;\n /** Its asset type, as the manifest records it: `\"scene\"` for a scene or a prefab. */\n readonly type: string;\n /**\n * The uids of the document's instance roots rebuilt from the new file, in document order: those\n * that instance it, directly or through another scene. Empty for any other type.\n */\n readonly entities: readonly string[];\n}\n\n/**\n * The parameters of `transformDragging`.\n *\n * @public\n */\nexport interface TransformDraggingParams {\n /** The dragged entity's uid. */\n readonly entity: string;\n /** The gizmo mode of the drag. */\n readonly mode: GizmoDragMode;\n /** Its local transform now, rounded as the engine writes numbers. */\n readonly after: SceneFileTransform;\n}\n\n/**\n * The parameters of `transformDragged`: the shape of a `setTransform` op plus the drag's mode.\n *\n * @public\n */\nexport interface TransformDraggedParams {\n /** The dragged entity's uid. */\n readonly entity: string;\n /** The gizmo mode of the drag, for the command's name. */\n readonly mode: GizmoDragMode;\n /** Its local transform when the drag started. */\n readonly before: SceneFileTransform;\n /** Its local transform at pointer-up. */\n readonly after: SceneFileTransform;\n}\n\n/**\n * The parameters of `hostError`.\n *\n * @public\n */\nexport interface HostErrorParams {\n /** The engine's `IGX-` code, or `null` when the error had none. */\n readonly code: string | null;\n /** An actionable sentence. */\n readonly message: string;\n /** Extra detail as JSON, when there is any. */\n readonly data?: JsonValue;\n}\n\n/**\n * The `data` of a `hostError` the host sends for an error the app reported through `app.onError`:\n * where it was caught. The host's `message` and `code` are the thrown error's.\n *\n * @remarks\n * `source`, `phase` and `entity` are in every 0.3 host; the other fields are additive in 0.3, sent by\n * a host that lists `HostCapability.logRelay`.\n *\n * @public\n */\nexport interface AppErrorData {\n /** Which boundary caught it: the engine's `ErrorReport.source`, such as `\"lifecycle\"`. */\n readonly source: string;\n /** The phase that was running, as the engine's `Phase` value, or `null` outside a phase. */\n readonly phase: number | null;\n /** That phase's name in the engine's `Phase`, such as `\"Update\"`, or `null`. */\n readonly phaseName?: string | null;\n /** The uid of the entity involved, or `null`. */\n readonly entity: string | null;\n /** The name of the entity involved, or `null`. */\n readonly entityName?: string | null;\n /** The `typeId` of the component involved (its class name when it has none), or `null`. */\n readonly component?: string | null;\n /** The thrown error's `stack`, or `null` when it has none. */\n readonly stack?: string | null;\n}\n\n/**\n * A log line's severity: the engine's `LogLevel`.\n *\n * @public\n */\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\n/**\n * An `Error` a log line carried among its extras, made JSON.\n *\n * @public\n */\nexport interface LoggedError {\n /** The error's message. */\n readonly message: string;\n /** Its `IGX-` code when it is an `IgnifxError`, else `null`. */\n readonly code: string | null;\n /** Its `stack`, or `null` when it has none. */\n readonly stack: string | null;\n}\n\n/**\n * The parameters of `log`: the engine's `LogRecord` without its `data`, which is not JSON, but for\n * the first `Error` in it.\n *\n * @public\n */\nexport interface LogParams {\n /** The severity. */\n readonly level: LogLevel;\n /** The logger's dotted scope, or `null` for the root logger. */\n readonly scope: string | null;\n /** The message. */\n readonly message: string;\n /** The logger clock's reading, in milliseconds. */\n readonly timeMs: number;\n /**\n * The first `Error` among the record's extras, such as the one the app's default `onError` handler\n * logs. Additive in 0.3: a host from before it leaves it out.\n */\n readonly error?: LoggedError;\n}\n\n/**\n * A request whose `params` are required.\n *\n * @typeParam M - The method name.\n * @typeParam P - The parameters.\n *\n * @public\n */\nexport interface RpcRequestWithParams<M extends string, P> extends RpcRequest<M, P> {\n /** The method's parameters. */\n readonly params: P;\n}\n\n/**\n * A notification whose `params` are required.\n *\n * @typeParam M - The method name.\n * @typeParam P - The parameters.\n *\n * @public\n */\nexport interface RpcNotificationWithParams<M extends string, P> extends RpcNotification<M, P> {\n /** The notification's parameters. */\n readonly params: P;\n}\n\n/**\n * Editor → scene host: one of the `SceneMethod`s. `closeScene`, `getSchemas` and `describeSettings`\n * take no parameters.\n *\n * @public\n */\nexport type SceneRequest =\n | RpcRequestWithParams<typeof SceneMethod.openScene, OpenSceneParams>\n | RpcRequest<typeof SceneMethod.closeScene, never>\n | RpcRequestWithParams<typeof SceneMethod.applyOps, ApplyOpsParams>\n | RpcRequestWithParams<typeof SceneMethod.readBack, ReadBackParams>\n | RpcRequestWithParams<typeof SceneMethod.select, EntitySelection>\n | RpcRequestWithParams<typeof SceneMethod.setGizmo, SetGizmoParams>\n | RpcRequestWithParams<typeof SceneMethod.frame, FrameParams>\n | RpcRequestWithParams<typeof SceneMethod.pick, PickParams>\n | RpcRequestWithParams<typeof SceneMethod.screenshot, ScreenshotParams>\n | RpcRequest<typeof SceneMethod.getSchemas, never>\n | RpcRequest<typeof SceneMethod.describeSettings, never>\n | RpcRequestWithParams<typeof SceneMethod.setViewMode, SetViewModeParams>\n | RpcRequestWithParams<typeof SceneMethod.setAnimateMaterials, SetAnimateMaterialsParams>\n | RpcRequestWithParams<typeof SceneMethod.getColliderOutlines, EntitySelection>\n | RpcRequestWithParams<typeof SceneMethod.sampleAnimation, SampleAnimationParams>;\n\n/**\n * The success answer of the `SceneMethod`s that return nothing: `closeScene`, `setGizmo`, `frame`,\n * `setViewMode` and `setAnimateMaterials`.\n *\n * @public\n */\nexport type NullResponse = RpcSuccessResponse<null>;\n\n/**\n * The success answer to `openScene`.\n *\n * @public\n */\nexport type OpenSceneResponse = RpcSuccessResponse<OpenSceneResult>;\n\n/**\n * The success answer to `applyOps`.\n *\n * @public\n */\nexport type ApplyOpsResponse = RpcSuccessResponse<ApplyOpsResult>;\n\n/**\n * The success answer to `readBack`.\n *\n * @public\n */\nexport type ReadBackResponse = RpcSuccessResponse<ReadBackResult>;\n\n/**\n * The success answer to `select`.\n *\n * @public\n */\nexport type SelectResponse = RpcSuccessResponse<EntitySelection>;\n\n/**\n * The success answer to `pick`.\n *\n * @public\n */\nexport type PickResponse = RpcSuccessResponse<PickResult>;\n\n/**\n * The success answer to `screenshot`.\n *\n * @public\n */\nexport type ScreenshotResponse = RpcSuccessResponse<ScreenshotResult>;\n\n/**\n * The success answer to `getSchemas`.\n *\n * @public\n */\nexport type GetSchemasResponse = RpcSuccessResponse<SchemaSet>;\n\n/**\n * The success answer to `describeSettings`.\n *\n * @public\n */\nexport type DescribeSettingsResponse = RpcSuccessResponse<SettingsSet>;\n\n/**\n * The success answer to `getColliderOutlines`.\n *\n * @public\n */\nexport type ColliderOutlinesResponse = RpcSuccessResponse<ColliderOutlineSet>;\n\n/**\n * The success answer to `sampleAnimation`.\n *\n * @public\n */\nexport type SampleAnimationResponse = RpcSuccessResponse<SampleAnimationResult>;\n\n/**\n * Scene host → editor: one of the `SceneNotification`s.\n *\n * @public\n */\nexport type SceneHostNotification =\n | RpcNotificationWithParams<typeof SceneNotification.sceneOpened, SceneOpenedParams>\n | RpcNotificationWithParams<typeof SceneNotification.schemasChanged, SchemaSet>\n | RpcNotificationWithParams<typeof SceneNotification.hotReloaded, HotReloadedParams>\n | RpcNotificationWithParams<typeof SceneNotification.selectionChanged, EntitySelection>\n | RpcNotificationWithParams<typeof SceneNotification.transformDragging, TransformDraggingParams>\n | RpcNotificationWithParams<typeof SceneNotification.transformDragged, TransformDraggedParams>\n | RpcNotificationWithParams<typeof SceneNotification.hostError, HostErrorParams>\n | RpcNotificationWithParams<typeof SceneNotification.log, LogParams>\n | RpcNotificationWithParams<typeof SceneNotification.assetReloaded, AssetReloadedParams>;\n\n// ---------------------------------------------------------------------------------------------\n// Guards\n// ---------------------------------------------------------------------------------------------\n\n/**\n * Tells whether a value is one of an `as const` object's values.\n *\n * @param names - The object.\n * @param value - The value to test.\n * @returns True when `value` is one of the object's values.\n */\nfunction isOneOf(names: Readonly<Record<string, string>>, value: unknown): boolean {\n return typeof value === \"string\" && Object.values(names).includes(value);\n}\n\n/**\n * Tells whether a value is a count: a non-negative safe integer.\n *\n * @param value - The value to test.\n * @returns True for a non-negative safe integer.\n */\nfunction isCount(value: unknown): value is number {\n return Number.isSafeInteger(value) && Number(value) >= 0;\n}\n\n/**\n * Tells whether a value is a non-negative finite number.\n *\n * @param value - The value to test.\n * @returns True for a finite number at least 0.\n */\nfunction isNonNegative(value: unknown): value is number {\n return isFiniteNumber(value) && value >= 0;\n}\n\n/**\n * Tells whether a value is a list of uids.\n *\n * @param value - The value to test.\n * @returns True for an array of non-empty strings.\n */\nfunction isUidList(value: unknown): value is readonly string[] {\n return isArrayOf(value, isUidString);\n}\n\n/**\n * Tells whether a value is a string or `null`.\n *\n * @param value - The value to test.\n * @returns True for a string or `null`.\n */\nfunction isStringOrNull(value: unknown): value is string | null {\n return value === null || isString(value);\n}\n\n/**\n * Checks one engine issue.\n *\n * @param value - The value to test.\n * @returns True for `{ code: string, message: string }`.\n *\n * @public\n */\nexport function isSceneIssue(value: unknown): value is SceneIssue {\n return isRecord(value) && isString(value[\"code\"]) && isString(value[\"message\"]);\n}\n\n/**\n * Checks the parameters of `openScene`.\n *\n * @param value - The received `params`.\n * @returns True for a structurally valid scene file and a string or `null` address.\n *\n * @public\n */\nexport function isOpenSceneParams(value: unknown): value is OpenSceneParams {\n return isRecord(value) && isSceneFile(value[\"file\"]) && isStringOrNull(value[\"address\"]);\n}\n\n/**\n * Checks the result of `openScene`.\n *\n * @param value - The received `result`.\n * @returns True for a count, a list of issues, and an optional view mode.\n *\n * @public\n */\nexport function isOpenSceneResult(value: unknown): value is OpenSceneResult {\n return (\n isRecord(value) &&\n isCount(value[\"entityCount\"]) &&\n isArrayOf(value[\"warnings\"], isSceneIssue) &&\n optionalField(value, \"viewMode\", (mode) => isOneOf(ViewMode, mode))\n );\n}\n\n/**\n * Checks the `data` of the `invalidParams` error `openScene` answers for a file\n * `validateSceneFile` refuses.\n *\n * @param value - The received `error.data`.\n * @returns True for `{ issues: [{ path, message }] }`.\n *\n * @public\n */\nexport function isInvalidSceneFileData(value: unknown): value is InvalidSceneFileData {\n return (\n isRecord(value) &&\n isArrayOf(\n value[\"issues\"],\n (issue): issue is SceneFileIssue => isRecord(issue) && isString(issue[\"path\"]) && isString(issue[\"message\"]),\n )\n );\n}\n\n/**\n * Checks the parameters of `applyOps`.\n *\n * @param value - The received `params`.\n * @returns True when every op passes {@link isSceneOp} and the command has a name and an id.\n *\n * @public\n */\nexport function isApplyOpsParams(value: unknown): value is ApplyOpsParams {\n return (\n isRecord(value) &&\n isArrayOf(value[\"ops\"], isSceneOp) &&\n isString(value[\"commandName\"]) &&\n isUidString(value[\"commandId\"])\n );\n}\n\n/**\n * Checks one failure in the result of `applyOps`.\n *\n * @param value - The value to test.\n * @returns True for `{ index, code, message, diagnostic? }` with a known code.\n */\nfunction isApplyOpFailure(value: unknown): value is ApplyOpFailure {\n return (\n isRecord(value) &&\n isCount(value[\"index\"]) &&\n isOneOf(ApplyOpFailureCode, value[\"code\"]) &&\n isString(value[\"message\"]) &&\n optionalField(value, \"diagnostic\", isString)\n );\n}\n\n/**\n * Checks the result of `applyOps`.\n *\n * @param value - The received `result`.\n * @returns True for a count of applied ops, a list of failures with known codes, and an optional\n * list of issues.\n *\n * @public\n */\nexport function isApplyOpsResult(value: unknown): value is ApplyOpsResult {\n return (\n isRecord(value) &&\n isCount(value[\"applied\"]) &&\n isArrayOf(value[\"failures\"], isApplyOpFailure) &&\n optionalField(value, \"warnings\", (warnings) => isArrayOf(warnings, isSceneIssue))\n );\n}\n\n/**\n * Checks the parameters of `readBack`.\n *\n * @param value - The received `params`.\n * @returns True for an object with an optional list of uids.\n *\n * @public\n */\nexport function isReadBackParams(value: unknown): value is ReadBackParams {\n return isRecord(value) && optionalField(value, \"entities\", isUidList);\n}\n\n/**\n * Checks the result of `readBack`.\n *\n * @param value - The received `result`.\n * @returns True for entity records, missing uids, settings or `null`, and issues.\n *\n * @public\n */\nexport function isReadBackResult(value: unknown): value is ReadBackResult {\n const settings = isRecord(value) ? value[\"settings\"] : undefined;\n return (\n isRecord(value) &&\n isArrayOf(value[\"entities\"], isSceneFileEntity) &&\n isUidList(value[\"missing\"]) &&\n (settings === null || isJsonObject(settings)) &&\n isArrayOf(value[\"issues\"], isSceneIssue)\n );\n}\n\n/**\n * Checks a selection: the parameters and result of `select` and the parameters of\n * `selectionChanged`.\n *\n * @param value - The received `params` or `result`.\n * @returns True for `{ entities: uid[] }`.\n *\n * @public\n */\nexport function isEntitySelection(value: unknown): value is EntitySelection {\n return isRecord(value) && isUidList(value[\"entities\"]);\n}\n\n/**\n * Checks the parameters of `setGizmo`.\n *\n * @param value - The received `params`.\n * @returns True for a known mode and space and a snap of three non-negative numbers, or `null`.\n *\n * @public\n */\nexport function isSetGizmoParams(value: unknown): value is SetGizmoParams {\n if (!isRecord(value)) {\n return false;\n }\n const snap = value[\"snap\"];\n return (\n isOneOf(GizmoMode, value[\"mode\"]) &&\n isOneOf(GizmoSpace, value[\"space\"]) &&\n (snap === null ||\n (isRecord(snap) &&\n isNonNegative(snap[\"translate\"]) &&\n isNonNegative(snap[\"rotate\"]) &&\n isNonNegative(snap[\"scale\"])))\n );\n}\n\n/**\n * Checks the parameters of `frame`.\n *\n * @param value - The received `params`.\n * @returns True for a list of uids or `\"all\"`.\n *\n * @public\n */\nexport function isFrameParams(value: unknown): value is FrameParams {\n return isRecord(value) && (value[\"entities\"] === \"all\" || isUidList(value[\"entities\"]));\n}\n\n/**\n * Checks the parameters of `pick`.\n *\n * @param value - The received `params`.\n * @returns True for finite `x` and `y` and a known unit.\n *\n * @public\n */\nexport function isPickParams(value: unknown): value is PickParams {\n return (\n isRecord(value) && isFiniteNumber(value[\"x\"]) && isFiniteNumber(value[\"y\"]) && isOneOf(PickUnit, value[\"unit\"])\n );\n}\n\n/**\n * Checks a pick ray.\n *\n * @param value - The value to test.\n * @returns True for `{ origin, direction }`, each three finite numbers.\n */\nfunction isPickRay(value: unknown): value is PickRay {\n return isRecord(value) && isNumberTuple(value[\"origin\"], 3) && isNumberTuple(value[\"direction\"], 3);\n}\n\n/**\n * Checks the result of `pick`.\n *\n * @param value - The received `result`.\n * @returns True for a uid or `null`, a point or `null`, a non-negative distance or `null`, an\n * optional ray and an optional plane point.\n *\n * @public\n */\nexport function isPickResult(value: unknown): value is PickResult {\n if (!isRecord(value)) {\n return false;\n }\n const { entity, point, distance } = value;\n return (\n (entity === null || isUidString(entity)) &&\n (point === null || isNumberTuple(point, 3)) &&\n (distance === null || isNonNegative(distance)) &&\n optionalField(value, \"ray\", isPickRay) &&\n optionalField(value, \"plane\", (plane) => isNumberTuple(plane, 3))\n );\n}\n\n/**\n * Tells whether a value is a screenshot side: a whole number from 1 to {@link SCREENSHOT_MAX_SIZE}.\n *\n * @param value - The value to test.\n * @returns True for an integer in range.\n */\nfunction isScreenshotSide(value: unknown): boolean {\n return Number.isSafeInteger(value) && Number(value) >= 1 && Number(value) <= SCREENSHOT_MAX_SIZE;\n}\n\n/**\n * Checks the parameters of `screenshot`.\n *\n * @param value - The received `params`.\n * @returns True for a known format, sizes in range when given, and a quality from 0 to 1 when given.\n *\n * @public\n */\nexport function isScreenshotParams(value: unknown): value is ScreenshotParams {\n return (\n isRecord(value) &&\n isOneOf(ScreenshotFormat, value[\"format\"]) &&\n optionalField(value, \"width\", isScreenshotSide) &&\n optionalField(value, \"height\", isScreenshotSide) &&\n optionalField(value, \"quality\", (quality) => isNonNegative(quality) && quality <= 1)\n );\n}\n\n/**\n * Checks the result of `screenshot`.\n *\n * @param value - The received `result`.\n * @returns True for a PNG or JPEG data URL and sizes in range.\n *\n * @public\n */\nexport function isScreenshotResult(value: unknown): value is ScreenshotResult {\n return (\n isRecord(value) &&\n isString(value[\"dataUrl\"]) &&\n /^data:image\\/(?:png|jpeg);base64,/u.test(value[\"dataUrl\"]) &&\n isScreenshotSide(value[\"width\"]) &&\n isScreenshotSide(value[\"height\"])\n );\n}\n\n/**\n * Checks one field description.\n *\n * @param value - The value to test.\n * @returns True for `{ kind, default?, description?, step?, hidden?, readonly?, group?, assetType?,\n * componentType? }`, ignoring members it does not declare.\n */\nfunction isSchemaFieldDescription(value: unknown): value is SchemaFieldDescription {\n return (\n isRecord(value) &&\n isString(value[\"kind\"]) &&\n optionalField(value, \"default\", (fallback) => isJsonValue(fallback)) &&\n optionalField(value, \"description\", isString) &&\n optionalField(value, \"step\", (step) => isFiniteNumber(step) && step > 0) &&\n optionalField(value, \"hidden\", isBoolean) &&\n optionalField(value, \"readonly\", isBoolean) &&\n optionalField(value, \"group\", isString) &&\n optionalField(value, \"assetType\", isString) &&\n optionalField(value, \"componentType\", (type) => type === null || isString(type))\n );\n}\n\n/**\n * Checks one schema description.\n *\n * @param value - The value to test.\n * @returns True for `{ title, format, description?, fields, allowMultiple?, package?, builtIn?,\n * requires?, extends?, propsSchema? }`, ignoring members it does not declare.\n */\nfunction isSchemaDescription(value: unknown): value is SchemaDescription {\n return (\n isRecord(value) &&\n isString(value[\"title\"]) &&\n isString(value[\"format\"]) &&\n optionalField(value, \"description\", isString) &&\n isRecord(value[\"fields\"]) &&\n Object.values(value[\"fields\"]).every((field) => isSchemaFieldDescription(field)) &&\n optionalField(value, \"allowMultiple\", isBoolean) &&\n optionalField(value, \"package\", isString) &&\n optionalField(value, \"builtIn\", isBoolean) &&\n optionalField(value, \"requires\", (ids) => Array.isArray(ids) && ids.every((id) => isStringOrNull(id))) &&\n optionalField(value, \"extends\", (ids) => isArrayOf(ids, isString)) &&\n optionalField(value, \"propsSchema\", isJsonObject)\n );\n}\n\n/**\n * Checks the result of `getSchemas` and the parameters of `schemasChanged`.\n *\n * @param value - The received `result` or `params`.\n * @returns True for `{ schemas }` whose every entry is a schema description.\n *\n * @public\n */\nexport function isSchemaSet(value: unknown): value is SchemaSet {\n const schemas = isRecord(value) ? value[\"schemas\"] : undefined;\n return isRecord(schemas) && Object.values(schemas).every((schema) => isSchemaDescription(schema));\n}\n\n/**\n * Checks the result of `describeSettings`.\n *\n * @param value - The received `result`.\n * @returns True for `{ sections, values }`: every section a schema description, every value an\n * object.\n *\n * @public\n */\nexport function isSettingsSet(value: unknown): value is SettingsSet {\n if (!isRecord(value)) {\n return false;\n }\n const { sections, values } = value;\n return (\n isRecord(sections) &&\n Object.values(sections).every((section) => isSchemaDescription(section)) &&\n isRecord(values) &&\n Object.values(values).every((section) => isJsonObject(section))\n );\n}\n\n/**\n * Checks the parameters of `setViewMode`.\n *\n * @param value - The received `params`.\n * @returns True for `{ mode: \"3d\" | \"2d\" }`.\n *\n * @public\n */\nexport function isSetViewModeParams(value: unknown): value is SetViewModeParams {\n return isRecord(value) && isOneOf(ViewMode, value[\"mode\"]);\n}\n\n/**\n * Checks the parameters of `setAnimateMaterials`.\n *\n * @param value - The received `params`.\n * @returns True for a boolean `enabled`.\n *\n * @public\n */\nexport function isSetAnimateMaterialsParams(value: unknown): value is SetAnimateMaterialsParams {\n return isRecord(value) && isBoolean(value[\"enabled\"]);\n}\n\n/**\n * Checks one record of `getColliderOutlines`.\n *\n * @param value - The value to test.\n * @returns True for two uids, a boolean, and a list of finite numbers whose length is a multiple of\n * six.\n *\n * @public\n */\nexport function isColliderOutlineRecord(value: unknown): value is ColliderOutlineRecord {\n if (!isRecord(value)) {\n return false;\n }\n const lines = value[\"lines\"];\n return (\n isUidString(value[\"entity\"]) &&\n isUidString(value[\"component\"]) &&\n isBoolean(value[\"isTrigger\"]) &&\n isArrayOf(lines, isFiniteNumber) &&\n lines.length % 6 === 0\n );\n}\n\n/**\n * Checks the result of `getColliderOutlines`.\n *\n * @param value - The received `result`.\n * @returns True for a list of outline records and a boolean `truncated`.\n *\n * @public\n */\nexport function isColliderOutlineSet(value: unknown): value is ColliderOutlineSet {\n return isRecord(value) && isArrayOf(value[\"outlines\"], isColliderOutlineRecord) && isBoolean(value[\"truncated\"]);\n}\n\n/**\n * Checks the parameters of `sampleAnimation`.\n *\n * @param value - The received `params`.\n * @returns True for a uid, a state name, a finite time, and optional parameter values that are\n * finite numbers or booleans, within {@link SAMPLE_ANIMATION_MAX_NAME_LENGTH} and\n * {@link SAMPLE_ANIMATION_MAX_PARAMETERS}.\n *\n * @public\n */\nexport function isSampleAnimationParams(value: unknown): value is SampleAnimationParams {\n return (\n isRecord(value) &&\n isUidString(value[\"entity\"]) &&\n isBoundedName(value[\"entity\"]) &&\n isBoundedName(value[\"state\"]) &&\n isFiniteNumber(value[\"normalizedTime\"]) &&\n optionalField(value, \"parameters\", isSampleParameters)\n );\n}\n\n/**\n * Tells whether a value is a string no longer than {@link SAMPLE_ANIMATION_MAX_NAME_LENGTH}.\n *\n * @param value - The value to test.\n * @returns True for such a string.\n */\nfunction isBoundedName(value: unknown): value is string {\n return isString(value) && value.length <= SAMPLE_ANIMATION_MAX_NAME_LENGTH;\n}\n\n/**\n * Checks the `parameters` of `sampleAnimation`.\n *\n * @param value - The value to test.\n * @returns True for at most {@link SAMPLE_ANIMATION_MAX_PARAMETERS} bounded names, each with a\n * finite number or a boolean.\n */\nfunction isSampleParameters(value: unknown): boolean {\n if (!isRecord(value)) {\n return false;\n }\n const names = Object.keys(value);\n return (\n names.length <= SAMPLE_ANIMATION_MAX_PARAMETERS &&\n names.every((name) => {\n const entry = value[name];\n return name.length <= SAMPLE_ANIMATION_MAX_NAME_LENGTH && (isFiniteNumber(entry) || isBoolean(entry));\n })\n );\n}\n\n/**\n * Checks the result of `sampleAnimation`.\n *\n * @param value - The received `result`.\n * @returns True for `{ posed: boolean }`.\n *\n * @public\n */\nexport function isSampleAnimationResult(value: unknown): value is SampleAnimationResult {\n return isRecord(value) && isBoolean(value[\"posed\"]);\n}\n\n/**\n * Checks the parameters of `sceneOpened`.\n *\n * @param value - The received `params`.\n * @returns True for an address or `null`, a name, a count, issues, and an optional view mode.\n *\n * @public\n */\nexport function isSceneOpenedParams(value: unknown): value is SceneOpenedParams {\n return (\n isRecord(value) &&\n isStringOrNull(value[\"address\"]) &&\n isString(value[\"name\"]) &&\n isOpenSceneResult({ entityCount: value[\"entityCount\"], warnings: value[\"warnings\"], viewMode: value[\"viewMode\"] })\n );\n}\n\n/** The `kind`s of a hot-reload report. */\nconst HOT_RELOAD_KINDS: Readonly<Record<string, string>> = { patch: \"patch\", recreate: \"recreate\", scene: \"scene\" };\n\n/**\n * Checks the parameters of `hotReloaded`.\n *\n * @param value - The received `params`.\n * @returns True for `{ report }` with a known kind, type ids, counts and JSON errors, its strings and\n * lists within `HOST_TEXT_MAX_LENGTH` and `HOST_LIST_MAX_LENGTH`.\n *\n * @public\n */\nexport function isHotReloadedParams(value: unknown): value is HotReloadedParams {\n const report = isRecord(value) ? value[\"report\"] : undefined;\n return (\n isRecord(report) &&\n isOneOf(HOT_RELOAD_KINDS, report[\"kind\"]) &&\n isHostList(report[\"typeIds\"], isHostText) &&\n isCount(report[\"instances\"]) &&\n isNonNegative(report[\"durationMs\"]) &&\n isHostList(\n report[\"errors\"],\n (error): error is HotReloadError =>\n isRecord(error) &&\n isHostText(error[\"message\"]) &&\n isHostTextOrNull(error[\"code\"]) &&\n optionalField(error, \"stack\", isHostTextOrNull),\n )\n );\n}\n\n/**\n * Checks the parameters of `assetReloaded`.\n *\n * @param value - The received `params`.\n * @returns True for `{ address, type, entities }` with a non-empty address and type.\n *\n * @public\n */\nexport function isAssetReloadedParams(value: unknown): value is AssetReloadedParams {\n return (\n isRecord(value) &&\n isString(value[\"address\"]) &&\n value[\"address\"] !== \"\" &&\n isString(value[\"type\"]) &&\n value[\"type\"] !== \"\" &&\n isUidList(value[\"entities\"])\n );\n}\n\n/** The modes a drag can happen in. */\nconst DRAG_MODES: Readonly<Record<string, string>> = {\n translate: GizmoMode.translate,\n rotate: GizmoMode.rotate,\n scale: GizmoMode.scale,\n};\n\n/**\n * Checks the parameters of `transformDragging`.\n *\n * @param value - The received `params`.\n * @returns True for an entity, a drag mode and a transform.\n *\n * @public\n */\nexport function isTransformDraggingParams(value: unknown): value is TransformDraggingParams {\n return (\n isRecord(value) &&\n isUidString(value[\"entity\"]) &&\n isOneOf(DRAG_MODES, value[\"mode\"]) &&\n isSceneFileTransform(value[\"after\"])\n );\n}\n\n/**\n * Checks the parameters of `transformDragged`.\n *\n * @param value - The received `params`.\n * @returns True for an entity, a drag mode and two transforms.\n *\n * @public\n */\nexport function isTransformDraggedParams(value: unknown): value is TransformDraggedParams {\n return isTransformDraggingParams(value) && \"before\" in value && isSceneFileTransform(value.before);\n}\n\n/**\n * Checks the parameters of `hostError`.\n *\n * @param value - The received `params`.\n * @returns True for a code or `null`, a message and optional JSON data, the strings within\n * `HOST_TEXT_MAX_LENGTH`.\n *\n * @public\n */\nexport function isHostErrorParams(value: unknown): value is HostErrorParams {\n return (\n isRecord(value) &&\n isHostTextOrNull(value[\"code\"]) &&\n isHostText(value[\"message\"]) &&\n optionalField(value, \"data\", (data) => isJsonValue(data))\n );\n}\n\n/**\n * Checks the `data` of a `hostError` for an error the app reported.\n *\n * @param value - The received `data`.\n * @returns True for a boundary name, a phase or `null`, an entity uid or `null`, and, when present,\n * a phase name, an entity name, a component and a stack, each a string or `null`; the strings within\n * `HOST_TEXT_MAX_LENGTH`.\n *\n * @public\n */\nexport function isAppErrorData(value: unknown): value is AppErrorData {\n return (\n isRecord(value) &&\n isHostText(value[\"source\"]) &&\n (value[\"phase\"] === null || isCount(value[\"phase\"])) &&\n (value[\"entity\"] === null || isUidString(value[\"entity\"])) &&\n optionalField(value, \"phaseName\", isHostTextOrNull) &&\n optionalField(value, \"entityName\", isHostTextOrNull) &&\n optionalField(value, \"component\", isHostTextOrNull) &&\n optionalField(value, \"stack\", isHostTextOrNull)\n );\n}\n\n/** The severities of a log line. */\nconst LOG_LEVELS: Readonly<Record<string, string>> = { debug: \"debug\", info: \"info\", warn: \"warn\", error: \"error\" };\n\n/**\n * Checks the parameters of `log`.\n *\n * @param value - The received `params`.\n * @returns True for a known level, a scope or `null`, a message and a finite time, the strings\n * within `HOST_TEXT_MAX_LENGTH`.\n *\n * @public\n */\nexport function isLogParams(value: unknown): value is LogParams {\n return (\n isRecord(value) &&\n isOneOf(LOG_LEVELS, value[\"level\"]) &&\n isHostTextOrNull(value[\"scope\"]) &&\n isHostText(value[\"message\"]) &&\n isFiniteNumber(value[\"timeMs\"]) &&\n optionalField(\n value,\n \"error\",\n (error) =>\n isRecord(error) &&\n isHostText(error[\"message\"]) &&\n isHostTextOrNull(error[\"code\"]) &&\n isHostTextOrNull(error[\"stack\"]),\n )\n );\n}\n","// A copy of `packages/editor-protocol/src/version.ts` from `astrum-forge/ignifx-editor` (protocol 0.3).\n// Below this comment it is byte-identical to that file, but for the link rule in `./index.ts`.\n/**\n * The protocol's own version, separate from the editor's and the engine's package versions.\n */\n\n/**\n * A protocol version. `major` changes when a message changes incompatibly; `minor` when messages\n * or fields are added in a way an older peer can ignore. Before 1.0 the minor plays the role of the\n * major (ADR-E008), so every 0.x minor is its own incompatible line.\n *\n * @public\n */\nexport interface ProtocolVersion {\n /** Incremented for incompatible changes. Peers must agree on it. */\n readonly major: number;\n /** Incremented for additions. From 1.0 peers may differ in it; before 1.0 they must agree on it too. */\n readonly minor: number;\n}\n\n/**\n * The protocol version this package describes. The editor sends it in `hello` and the host in\n * `ready`.\n *\n * @public\n */\nexport const PROTOCOL_VERSION: ProtocolVersion = { major: 0, minor: 3 };\n\n/**\n * Tells whether two peers can talk.\n *\n * @remarks\n * The rule is ADR-E008's: the protocol follows SemVer, and until 1.0 its minor plays the role of the\n * major, as the engine's minors do. So from 1.0 two peers are compatible when their majors are\n * equal and the minors are free to differ; before 1.0 the major and the minor must both be equal.\n * The check is symmetric. Which versions the editor accepts beyond it (ADR-E008 has the editor\n * support the current protocol line and the previous one) is the editor's decision, not this\n * function's.\n *\n * @example\n * ```ts\n * protocolVersionIsCompatible({ major: 0, minor: 3 }, { major: 0, minor: 2 }); // false\n * protocolVersionIsCompatible({ major: 1, minor: 0 }, { major: 1, minor: 4 }); // true\n * ```\n *\n * @param a - One peer's protocol version.\n * @param b - The other peer's protocol version.\n * @returns `true` when the versions are on the same compatible line.\n *\n * @public\n */\nexport function protocolVersionIsCompatible(a: ProtocolVersion, b: ProtocolVersion): boolean {\n if (a.major !== b.major) {\n return false;\n }\n return a.major !== 0 || a.minor === b.minor;\n}\n","/**\n * The host half of an editor channel: accepts the `MessagePort` the editor posts to the view's\n * window, runs the `hello`/`ready` handshake, answers requests, and sends heartbeats. The scene\n * host and the play controls each open one.\n */\n\nimport { IgnifxError } from \"@ignifx/core\";\nimport { EditorHostErrorCode, isEditorOrigin } from \"./error-codes.js\";\nimport {\n DEFAULT_HEARTBEAT_INTERVAL_MS,\n HandshakeMethod,\n HostNotification,\n isEditorConnectMessage,\n isRpcMessage,\n JSON_RPC_VERSION,\n PROTOCOL_VERSION,\n protocolVersionIsCompatible,\n RpcErrorCode,\n} from \"./protocol/index.js\";\nimport { isRecord } from \"./protocol/rpc.js\";\nimport type { HelloParams, ReadyResult, RpcErrorResponse, RpcId, RpcSuccessResponse } from \"./protocol/index.js\";\n\n/**\n * Where a host listens for the editor's connect message: the view's `window` in a browser, or any\n * `EventTarget` that dispatches `MessageEvent`s, which is how a headless test stands in for one.\n * Events that are not `MessageEvent`s are ignored.\n *\n * @beta\n */\nexport interface EditorMessageTarget {\n /**\n * Subscribes to window messages.\n *\n * @param type - Always `\"message\"`.\n * @param listener - Receives each message.\n */\n addEventListener(type: \"message\", listener: (event: Event) => void): void;\n /**\n * Unsubscribes a listener added with `addEventListener`.\n *\n * @param type - Always `\"message\"`.\n * @param listener - The listener to remove.\n */\n removeEventListener(type: \"message\", listener: (event: Event) => void): void;\n}\n\n/** A request handler. It may be asynchronous; whatever it throws becomes an `internalError` reply. */\nexport type RequestHandler = (params: unknown) => unknown;\n\n/**\n * A handler's answer that has work to do once the answer is on the port, such as a notification\n * the protocol orders after it (`sceneOpened` after the answer to `openScene`).\n */\nexport class Reply {\n /** The method's result. */\n readonly result: unknown;\n\n /** Runs right after the answer has been sent on the port that asked. */\n readonly after: () => void;\n\n /**\n * Creates the reply.\n *\n * @param result - The method's result.\n * @param after - What to run once the answer is sent.\n */\n constructor(result: unknown, after: () => void) {\n this.result = result;\n this.after = after;\n }\n}\n\n/** A handler's way of answering with a protocol error of its choice rather than `internalError`. */\nexport class RpcFailure extends Error {\n /** The JSON-RPC error code. */\n readonly code: RpcErrorCode;\n\n /** The error's `data`, when it has any. */\n readonly data: unknown;\n\n /**\n * Creates the failure.\n *\n * @param code - The error code.\n * @param message - What went wrong.\n * @param data - Extra detail, as JSON.\n */\n constructor(code: RpcErrorCode, message: string, data?: unknown) {\n super(message);\n this.name = \"RpcFailure\";\n this.code = code;\n this.data = data;\n }\n}\n\n/** A handler's way of refusing its parameters with `invalidParams` rather than `internalError`. */\nexport class InvalidParamsError extends RpcFailure {\n /**\n * Creates the refusal.\n *\n * @param message - What is wrong with the parameters.\n * @param data - Extra detail, as JSON.\n */\n constructor(message: string, data?: unknown) {\n super(RpcErrorCode.invalidParams, message, data);\n this.name = \"InvalidParamsError\";\n }\n}\n\n/** What {@link openChannel} needs. */\nexport interface ChannelOptions {\n /** Where the connect message arrives. */\n readonly target: EditorMessageTarget;\n /** The only origin a port is accepted from. */\n readonly editorOrigin: string;\n /** The `ready` result, sent in answer to a compatible `hello`. */\n readonly ready: ReadyResult;\n /** Methods answered after the handshake, by name. */\n readonly methods: ReadonlyMap<string, RequestHandler>;\n /** Milliseconds between heartbeats. */\n readonly heartbeatIntervalMs: number;\n /** Called each time a port's `hello` has been answered with `ready`, after the answer is sent. */\n readonly onReady?: () => void;\n /**\n * A port that arrived before the channel opened (see {@link connectPortOf}), served at once as\n * though it had just been posted. Its queued messages are read only from then on.\n */\n readonly port?: MessagePort | null;\n}\n\n/** An open channel. */\nexport interface Channel {\n /** Whether a port has been accepted and not replaced or closed. */\n readonly isConnected: boolean;\n /** Whether the current port has completed the handshake. */\n readonly isReady: boolean;\n /**\n * Sends a notification on the current port, once it has completed the handshake; otherwise drops\n * it, since the editor re-sends what a new port needs.\n *\n * @param method - The notification's name.\n * @param params - Its parameters, if any.\n */\n notify(method: string, params?: unknown): void;\n /** Removes the window listener, stops the heartbeat, and closes the port. Idempotent. */\n dispose(): void;\n}\n\n/** A request's answer, and what to run once it is on the port. */\ninterface Answer {\n /** The response envelope. */\n readonly response: RpcSuccessResponse | RpcErrorResponse;\n /** Runs right after the response is sent, or `null`. */\n readonly after: (() => void) | null;\n}\n\n/**\n * Checks the parameters of `hello`.\n *\n * @param value - The received `params`.\n * @returns True when they carry an editor version and an integer protocol version.\n */\nfunction isHelloParams(value: unknown): value is HelloParams {\n if (!isRecord(value) || typeof value[\"editorVersion\"] !== \"string\") {\n return false;\n }\n const protocol = value[\"protocol\"];\n return isRecord(protocol) && Number.isInteger(protocol[\"major\"]) && Number.isInteger(protocol[\"minor\"]);\n}\n\n/**\n * Builds a success response.\n *\n * @param id - The request id.\n * @param result - The result.\n * @returns The envelope.\n */\nfunction success(id: RpcId, result: unknown): RpcSuccessResponse {\n return { jsonrpc: JSON_RPC_VERSION, id, result };\n}\n\n/**\n * Builds an error response.\n *\n * @param id - The request id, or `null` when it could not be read.\n * @param code - The error code.\n * @param message - A short description.\n * @param data - Extra detail, if any.\n * @returns The envelope.\n */\nfunction failure(id: RpcId | null, code: RpcErrorCode, message: string, data?: unknown): RpcErrorResponse {\n const error = data === undefined ? { code, message } : { code, message, data };\n return { jsonrpc: JSON_RPC_VERSION, id, error };\n}\n\n/**\n * Posts one message on a port.\n *\n * @param port - The port the editor handed over.\n * @param message - The envelope to send.\n */\nfunction send(port: MessagePort, message: unknown): void {\n // A `MessagePort` has exactly one peer, so it takes no target origin; the rule is for windows.\n // oxlint-disable-next-line unicorn/require-post-message-target-origin -- see above.\n port.postMessage(message);\n}\n\n/**\n * Checks the options every host shares and throws the documented error for a bad one.\n *\n * @param editorOrigin - The origin the editor is served from.\n * @param heartbeatIntervalMs - The heartbeat period, if given.\n * @returns The heartbeat period with its default applied.\n * @throws IgnifxError `IGX-1801` for an origin that is not `scheme://host[:port]`, `IGX-1803` for a\n * period that is not a positive finite number.\n */\nexport function checkChannelOptions(editorOrigin: string, heartbeatIntervalMs: number | undefined): number {\n if (!isEditorOrigin(editorOrigin)) {\n throw new IgnifxError(\n EditorHostErrorCode.invalidEditorOrigin,\n `\"${editorOrigin}\" is not an origin the editor can be served from.`,\n { hint: 'Pass the editor\\'s origin exactly as the browser reports it, for example \"ignifx-editor://app\".' },\n );\n }\n const interval = heartbeatIntervalMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS;\n if (!Number.isFinite(interval) || interval <= 0) {\n throw new IgnifxError(\n EditorHostErrorCode.invalidOption,\n `heartbeatIntervalMs must be a positive number of milliseconds; got ${String(interval)}.`,\n { context: { option: \"heartbeatIntervalMs\" } },\n );\n }\n return interval;\n}\n\n/**\n * Picks the window a host listens on.\n *\n * @param target - The target the caller passed, if any.\n * @returns That target, or the page's `window`.\n * @throws IgnifxError `IGX-1802` when there is neither, as in Node.\n */\nexport function resolveMessageTarget(target: EditorMessageTarget | undefined): EditorMessageTarget {\n if (target !== undefined) {\n return target;\n }\n if (typeof window === \"undefined\") {\n throw new IgnifxError(\n EditorHostErrorCode.noMessageTarget,\n \"The editor host needs a window to receive the editor's port, and this environment has none.\",\n { hint: \"Pass messageTarget, for example an EventTarget a test dispatches MessageEvents on.\" },\n );\n }\n return window;\n}\n\n/**\n * Reads the port out of a window message, if it is the editor's connect message.\n *\n * @remarks\n * Anyone can post to a window; only the editor's own origin may hand a host a port. The message\n * must come from exactly `editorOrigin`, carry the connect message's data, and transfer exactly\n * one port.\n *\n * @param event - A window message.\n * @param editorOrigin - The only origin a port is accepted from.\n * @returns The port, or `null` when the message is anything else.\n */\nexport function connectPortOf(event: Event, editorOrigin: string): MessagePort | null {\n if (!(event instanceof MessageEvent) || event.origin !== editorOrigin) {\n return null;\n }\n const port = event.ports[0];\n if (!isEditorConnectMessage(event.data) || event.ports.length !== 1 || port === undefined) {\n return null;\n }\n return port;\n}\n\n/**\n * Opens a channel: listens for the editor's connect message and serves whichever port arrived last.\n *\n * @remarks\n * Call it before the host's first `await`. The editor posts the port on the view's `load` event,\n * which can fire while `createApp` is still running, and a message nobody listens for is lost.\n *\n * @param options - The target, origin, handshake answer, methods, and heartbeat period.\n * @returns The channel; dispose it with the host.\n */\nexport function openChannel(options: ChannelOptions): Channel {\n const { target, editorOrigin, ready, methods, heartbeatIntervalMs, onReady } = options;\n let port: MessagePort | null = null;\n let portListener: ((event: MessageEvent) => void) | null = null;\n let isReady = false;\n let heartbeat: ReturnType<typeof setInterval> | null = null;\n let isDisposed = false;\n // Requests are answered one at a time, in arrival order (protocol 0.3): an `applyOps` sent right\n // after an `openScene` must see the scene that request opens.\n let queue: Promise<void> = Promise.resolve();\n\n const stopHeartbeat = (): void => {\n if (heartbeat !== null) {\n clearInterval(heartbeat);\n heartbeat = null;\n }\n };\n\n const closePort = (): void => {\n stopHeartbeat();\n isReady = false;\n if (port !== null && portListener !== null) {\n port.removeEventListener(\"message\", portListener);\n port.close();\n }\n port = null;\n portListener = null;\n };\n\n const handshake = (id: RpcId, params: unknown): RpcSuccessResponse | RpcErrorResponse => {\n if (!isHelloParams(params)) {\n return failure(id, RpcErrorCode.invalidParams, \"hello needs { editorVersion, protocol: { major, minor } }.\");\n }\n if (!protocolVersionIsCompatible(params.protocol, PROTOCOL_VERSION)) {\n return failure(\n id,\n RpcErrorCode.incompatibleProtocol,\n `The editor speaks protocol ${String(params.protocol.major)}.${String(params.protocol.minor)} and this ` +\n `host speaks ${String(PROTOCOL_VERSION.major)}.${String(PROTOCOL_VERSION.minor)}. Update the editor, ` +\n \"or the project's @ignifx packages, so the protocol versions match.\",\n { host: PROTOCOL_VERSION, engineVersion: ready.engineVersion },\n );\n }\n isReady = true;\n return success(id, ready);\n };\n\n const answer = async (id: RpcId, method: string, params: unknown): Promise<Answer> => {\n if (method === HandshakeMethod.hello) {\n return { response: handshake(id, params), after: null };\n }\n if (method === HandshakeMethod.ping) {\n return { response: success(id, \"pong\"), after: null };\n }\n const handler = methods.get(method);\n if (handler === undefined) {\n return {\n response: failure(id, RpcErrorCode.methodNotFound, `This host has no method \"${method}\".`),\n after: null,\n };\n }\n if (!isReady) {\n return { response: failure(id, RpcErrorCode.notReady, `Send hello before \"${method}\".`), after: null };\n }\n try {\n const value: unknown = await handler(params);\n return value instanceof Reply\n ? { response: success(id, value.result), after: value.after }\n : { response: success(id, value), after: null };\n } catch (error) {\n if (error instanceof RpcFailure) {\n return { response: failure(id, error.code, error.message, error.data), after: null };\n }\n const message = error instanceof Error ? error.message : String(error);\n const code = error instanceof IgnifxError ? error.code : null;\n return { response: failure(id, RpcErrorCode.internalError, message, { code }), after: null };\n }\n };\n\n const startHeartbeat = (current: MessagePort): void => {\n if (heartbeat !== null) {\n return;\n }\n const notification = { jsonrpc: JSON_RPC_VERSION, method: HostNotification.heartbeat };\n heartbeat = setInterval(() => {\n send(current, notification);\n }, heartbeatIntervalMs);\n };\n\n const onPortMessage = async (current: MessagePort, data: unknown): Promise<void> => {\n if (!isRpcMessage(data)) {\n send(current, failure(null, RpcErrorCode.invalidRequest, \"Not a JSON-RPC 2.0 message.\"));\n return;\n }\n // Responses and notifications from the editor need no answer, and none is defined yet.\n if (!(\"method\" in data) || !(\"id\" in data)) {\n return;\n }\n const { id, method, params } = data;\n const reply = async (): Promise<void> => {\n const wasReady = isReady;\n const { response, after } = await answer(id, method, params);\n // A reload or a reconnect may have replaced the port while an asynchronous method ran.\n if (current !== port) {\n return;\n }\n send(current, response);\n after?.();\n if (isReady) {\n startHeartbeat(current);\n if (!wasReady && method === HandshakeMethod.hello) {\n onReady?.();\n }\n }\n };\n // `ping` jumps the queue, so a long `openScene` does not look like a hung view.\n if (method === HandshakeMethod.ping) {\n await reply();\n return;\n }\n const next = queue.then(reply);\n // `reply` turns every failure into an answer; the guard keeps one bug from stalling the queue.\n queue = next.catch(() => undefined);\n await next;\n };\n\n const accept = (next: MessagePort): void => {\n closePort();\n const listener = (event: MessageEvent): void => {\n // Detached on purpose: replies go out on the port, and `answer` turns every failure into one.\n void onPortMessage(next, event.data);\n };\n port = next;\n portListener = listener;\n next.addEventListener(\"message\", listener);\n next.start();\n };\n\n const onWindowMessage = (event: Event): void => {\n const next = connectPortOf(event, editorOrigin);\n if (next !== null) {\n accept(next);\n }\n };\n\n target.addEventListener(\"message\", onWindowMessage);\n if (options.port !== undefined && options.port !== null) {\n accept(options.port);\n }\n\n return {\n get isConnected(): boolean {\n return port !== null;\n },\n get isReady(): boolean {\n return port !== null && isReady;\n },\n notify(method: string, params?: unknown): void {\n if (port !== null && isReady) {\n send(\n port,\n params === undefined ? { jsonrpc: JSON_RPC_VERSION, method } : { jsonrpc: JSON_RPC_VERSION, method, params },\n );\n }\n },\n dispose(): void {\n if (isDisposed) {\n return;\n }\n isDisposed = true;\n target.removeEventListener(\"message\", onWindowMessage);\n closePort();\n },\n };\n}\n","/**\n * The app's reports as the editor's Console reads them: log lines, `app.onError` reports and hot\n * reloads, made JSON. The scene view and the play view relay the same shapes.\n */\n\nimport { isIgnifxError, Phase } from \"@ignifx/core\";\nimport { HOST_LIST_MAX_LENGTH, HOST_TEXT_MAX_LENGTH } from \"./protocol/index.js\";\nimport type { AppErrorData, HostErrorParams, HotReloadedParams, LoggedError, LogParams } from \"./protocol/index.js\";\nimport type { App, Component, ErrorReport, HotReloadReport, LogRecord } from \"@ignifx/core\";\n\n/** What ends a string {@link clipHostText} cut. */\nexport const CLIPPED_MARKER = \"… [clipped]\";\n\n/**\n * Cuts a string to `HOST_TEXT_MAX_LENGTH`, the longest the editor accepts in a report: the editor\n * drops a whole report holding a longer one.\n *\n * @param text - The string.\n * @returns It unchanged when short enough, else its start and {@link CLIPPED_MARKER}, exactly\n * `HOST_TEXT_MAX_LENGTH` long or one shorter (a surrogate pair is never split).\n */\nexport function clipHostText(text: string): string {\n if (text.length <= HOST_TEXT_MAX_LENGTH) {\n return text;\n }\n let end = HOST_TEXT_MAX_LENGTH - CLIPPED_MARKER.length;\n const last = text.charCodeAt(end - 1);\n if (last >= 0xd8_00 && last <= 0xdb_ff) {\n end -= 1;\n }\n return `${text.slice(0, end)}${CLIPPED_MARKER}`;\n}\n\n/**\n * Like {@link clipHostText}, passing `null` through.\n *\n * @param text - The string, or `null`.\n * @returns The clipped string, or `null`.\n */\nfunction clipHostTextOrNull(text: string | null): string | null {\n return text === null ? null : clipHostText(text);\n}\n\n/**\n * Keeps the first `HOST_LIST_MAX_LENGTH` items of a list, the most the editor accepts in a report.\n *\n * @param items - The list.\n * @returns It, or its start when longer.\n */\nfunction clipHostList<T>(items: readonly T[]): readonly T[] {\n return items.length <= HOST_LIST_MAX_LENGTH ? items : items.slice(0, HOST_LIST_MAX_LENGTH);\n}\n\n/**\n * Names one of the engine's phases.\n *\n * @param phase - The phase's value.\n * @returns Its name in `Phase`, such as `\"Update\"`, or `null` for a value `Phase` does not have.\n */\nfunction phaseName(phase: number): string | null {\n return Object.entries(Phase).find(([, value]) => value === phase)?.[0] ?? null;\n}\n\n/**\n * Reads a thrown value's message, clipped by {@link clipHostText}.\n *\n * @param error - Whatever was thrown.\n * @returns Its message, or the value as a string when it is not an `Error`.\n */\nexport function messageOf(error: unknown): string {\n return clipHostText(error instanceof Error ? error.message : String(error));\n}\n\n/**\n * Reads a thrown value's stack, clipped by {@link clipHostText}.\n *\n * @param error - Whatever was thrown.\n * @returns Its `stack` when it is an `Error` with one, else `null`.\n */\nfunction stackOf(error: unknown): string | null {\n return error instanceof Error && typeof error.stack === \"string\" && error.stack !== \"\"\n ? clipHostText(error.stack)\n : null;\n}\n\n/**\n * Reads a thrown value's `IGX-` code, clipped by {@link clipHostText}.\n *\n * @param error - Whatever was thrown.\n * @returns The code of an `IgnifxError`, else `null`.\n */\nfunction codeOf(error: unknown): string | null {\n return isIgnifxError(error) ? clipHostText(error.code) : null;\n}\n\n/**\n * Names a component for the editor: its `typeId`, else its class name.\n *\n * @param component - The component.\n * @returns The name, clipped by {@link clipHostText}.\n */\nfunction componentName(component: Component): string {\n const typeId: unknown = Reflect.get(component.constructor, \"typeId\");\n return clipHostText(typeof typeId === \"string\" && typeId !== \"\" ? typeId : component.constructor.name);\n}\n\n/**\n * Builds the parameters of `log` from one record.\n *\n * @param record - The record the app's logger wrote.\n * @returns The level, scope, message and time, and the first `Error` among the extras; each string\n * clipped by {@link clipHostText}.\n */\nexport function logParamsOf(record: LogRecord): LogParams {\n const params: LogParams = {\n level: record.level,\n scope: clipHostTextOrNull(record.scope),\n message: clipHostText(record.message),\n timeMs: record.timeMs,\n };\n const error = record.data.find((value): value is Error => value instanceof Error);\n if (error === undefined) {\n return params;\n }\n const logged: LoggedError = { message: messageOf(error), code: codeOf(error), stack: stackOf(error) };\n return { ...params, error: logged };\n}\n\n/**\n * Builds the parameters of `hostError` from one `app.onError` report.\n *\n * @param report - The report.\n * @returns The thrown error's code and message, and where it was caught; each string clipped by\n * {@link clipHostText}.\n */\nexport function hostErrorParamsOf(report: ErrorReport): HostErrorParams {\n const data: AppErrorData = {\n source: clipHostText(report.source),\n phase: report.phase,\n phaseName: report.phase === null ? null : phaseName(report.phase),\n entity: report.entity?.uid ?? null,\n entityName: clipHostTextOrNull(report.entity?.name ?? null),\n component: report.component === null ? null : componentName(report.component),\n stack: stackOf(report.error),\n };\n return { code: codeOf(report.error), message: messageOf(report.error), data: { ...data } };\n}\n\n/**\n * Builds the parameters of `hotReloaded` from one report.\n *\n * @param report - What `app.hotReload` did.\n * @returns The report, with its errors made JSON; each string clipped by {@link clipHostText} and\n * each list cut to `HOST_LIST_MAX_LENGTH` items.\n */\nexport function hotReloadedParamsOf(report: HotReloadReport): HotReloadedParams {\n return {\n report: {\n kind: report.kind,\n typeIds: clipHostList(report.typeIds).map((typeId) => clipHostText(typeId)),\n instances: report.instances,\n durationMs: report.durationMs,\n errors: clipHostList(report.errors).map((error) => ({\n message: messageOf(error),\n code: codeOf(error),\n stack: stackOf(error),\n })),\n },\n };\n}\n\n/** Where {@link relayAppReports} sends each report. */\nexport interface AppReportSink {\n /** Called with each log line. */\n readonly log: (params: LogParams) => void;\n /** Called with each `app.onError` report. */\n readonly error: (params: HostErrorParams) => void;\n /** Called with each hot reload. */\n readonly hotReloaded: (report: HotReloadReport) => void;\n}\n\n/**\n * Follows an app's log lines, error reports and hot reloads.\n *\n * @param app - The app.\n * @param sink - Where each one goes.\n * @returns A function that stops following.\n */\nexport function relayAppReports(app: App, sink: AppReportSink): () => void {\n const cleanups = [\n app.log.addSink({\n write: (record): void => {\n sink.log(logParamsOf(record));\n },\n }),\n app.onError.connect((report) => {\n sink.error(hostErrorParamsOf(report));\n }),\n app.hotReload.onApplied.connect((report) => {\n sink.hotReloaded(report);\n }),\n ];\n return (): void => {\n for (const cleanup of cleanups) {\n cleanup();\n }\n };\n}\n","/**\n * The scene view's overlay: Babylon Lite's position, rotation and scale gizmos and the selection\n * outline, in core's render overlay over the app's frame. Picking is `app.renderer.pickAsync`'s.\n *\n * This is the only module of the editor host that imports Lite (`CONSTITUTION.md` §3.4). The rest\n * of the host reaches it through {@link createEditorView}, which takes and returns ignifx objects\n * and plain data. Every Lite claim here was read from the pinned `@babylonjs/lite` 1.34\n * `index.d.ts`; the behaviours are the ones spike S0.2 measured (editor repository,\n * `docs/research/spikes/s0.2-gizmos-and-cameras.md`).\n */\n\nimport {\n addToScene,\n attachPositionGizmoToNode,\n attachRotationGizmoToNode,\n attachScaleGizmoToNode,\n createLines,\n createPositionGizmo,\n createRotationGizmo,\n createScaleGizmo,\n isGizmoDragging,\n isGizmoInteracting,\n isGizmoPickPending,\n onBeforeRender,\n setPositionGizmoLocalCoordinates,\n setRotationGizmoLocalCoordinates,\n setScaleGizmoLocalCoordinates,\n} from \"@babylonjs/lite\";\nimport type { Mesh, PointerDrag, SceneContext, SceneNode, Vec3 } from \"@babylonjs/lite\";\nimport type { AppLiteHandles, Entity, RenderOverlay } from \"@ignifx/core\";\n\n/** What a gizmo drag does. */\nexport type ViewGizmoMode = \"translate\" | \"rotate\" | \"scale\";\n\n/** Which handle of the gizmo is dragged. */\nexport type ViewGizmoAxis = \"x\" | \"y\" | \"z\" | \"uniform\";\n\n/** One sub-gizmo's drag. */\nexport interface ViewDrag {\n /** The gizmo's mode. */\n readonly mode: ViewGizmoMode;\n /** The handle. */\n readonly axis: ViewGizmoAxis;\n}\n\n/** Where Lite's gizmo dispatcher is with the current pointer gesture, for the editor camera. */\nexport interface ViewPointerState {\n /** A handle is hovered or dragged: a press there belongs to the gizmo. */\n readonly interacting: boolean;\n /** A gizmo drag is active. */\n readonly dragging: boolean;\n /** The dispatcher is still picking under the last press. */\n readonly pickPending: boolean;\n}\n\n/** An axis-aligned box in world space, in metres. */\nexport interface WorldBounds {\n /** The low corner. */\n readonly min: { readonly x: number; readonly y: number; readonly z: number };\n /** The high corner. */\n readonly max: { readonly x: number; readonly y: number; readonly z: number };\n}\n\n/** The overlay of one scene view. */\nexport interface EditorView {\n /**\n * Sets what the gizmo does; `null` hides every gizmo.\n *\n * @param mode - The mode, or `null` for none.\n */\n setMode(mode: ViewGizmoMode | null): void;\n /**\n * Sets whether the gizmo follows the entity's own axes.\n *\n * @param local - `true` for local axes, `false` for world axes.\n */\n setLocal(local: boolean): void;\n /**\n * Attaches the gizmo to an entity, or detaches it.\n *\n * @param entity - The primary selection, or `null`.\n */\n attach(entity: Entity | null): void;\n /**\n * Outlines entities with a line box over each one's world bounds.\n *\n * @param entities - The selection.\n */\n outline(entities: readonly Entity[]): void;\n /**\n * Shows or hides the gizmo and the outline, for a capture without them.\n *\n * @param visible - Whether they draw.\n */\n setVisible(visible: boolean): void;\n /**\n * Subscribes to every handle's drag start, move and end.\n *\n * @param listener - Receives the phase and the drag.\n */\n onDrag(listener: (phase: \"start\" | \"move\" | \"end\", drag: ViewDrag) => void): void;\n /**\n * Reads the gizmo dispatcher's state for the current pointer gesture.\n *\n * @returns The state.\n */\n pointerState(): ViewPointerState;\n /**\n * The world bounds of the meshes under an entity, glTF models included.\n *\n * @param entity - The entity.\n * @returns The box, or `null` when nothing under it is drawn.\n */\n worldBounds(entity: Entity): WorldBounds | null;\n /** Disposes the overlay and everything in it. */\n dispose(): void;\n}\n\n/** The three axes of a gizmo. */\nconst AXES: readonly (\"x\" | \"y\" | \"z\")[] = [\"x\", \"y\", \"z\"];\n\n/** The outline's colour: the editor's selection orange. */\nconst OUTLINE_COLOR = { r: 1, g: 0.6, b: 0.1, a: 1 };\n\n/** A unit cube's corners, centred on the origin. */\nconst CORNERS: readonly Vec3[] = [\n { x: -0.5, y: -0.5, z: -0.5 },\n { x: 0.5, y: -0.5, z: -0.5 },\n { x: 0.5, y: -0.5, z: 0.5 },\n { x: -0.5, y: -0.5, z: 0.5 },\n { x: -0.5, y: 0.5, z: -0.5 },\n { x: 0.5, y: 0.5, z: -0.5 },\n { x: 0.5, y: 0.5, z: 0.5 },\n { x: -0.5, y: 0.5, z: 0.5 },\n];\n\n/** One polyline over all twelve edges of a cube (three are walked twice), as corner indices. */\nconst OUTLINE_PATH: readonly number[] = [0, 1, 2, 3, 0, 4, 5, 1, 5, 6, 2, 6, 7, 3, 7, 4];\n\n/** The smallest outline side, so a flat or empty box stays visible. */\nconst MIN_OUTLINE_SIDE = 1e-3;\n\n/**\n * Builds the overlay of one scene view.\n *\n * @remarks\n * The gizmos and the outline live in core's render overlay (`app.renderer.openOverlay()`, ADR-0031),\n * whose Lite scenes have the shape Lite's gizmo constructors take as a utility layer. Core draws it\n * over the finished frame at every MSAA setting; Lite's own utility layer blacks out the scene or\n * draws nothing in an ignifx app (S0.2 §3.2).\n *\n * A detached Lite gizmo keeps drawing at its last pose, so a hidden sub-gizmo is collapsed to zero\n * scale; Lite restores the scale when it is attached again (S0.2 §3.3). The outline is a line box,\n * because Lite's bounding-box gizmo drags whatever is pressed inside it (S0.2 §7).\n *\n * @param handles - The app's Lite engine and render scene (`app.lite`).\n * @param overlay - An open render overlay of the same app, which the view now owns.\n * @param canvas - The canvas the gizmo dispatcher listens on.\n * @returns The view.\n */\nexport function createEditorView(\n handles: AppLiteHandles,\n overlay: RenderOverlay,\n canvas: HTMLCanvasElement,\n): EditorView {\n const { engine, scene } = handles;\n const layer = overlay.lite;\n const position = createPositionGizmo(engine, layer);\n const rotation = createRotationGizmo(engine, layer);\n const scale = createScaleGizmo(engine, layer);\n const listeners: ((phase: \"start\" | \"move\" | \"end\", drag: ViewDrag) => void)[] = [];\n const outlines: Mesh[] = [];\n let outlined: readonly Entity[] = [];\n let mode: ViewGizmoMode | null = \"translate\";\n let target: SceneNode | null = null;\n let visible = true;\n\n const wire = (drag: PointerDrag, info: ViewDrag): void => {\n const emit = (phase: \"start\" | \"move\" | \"end\"): void => {\n for (const listener of listeners) {\n listener(phase, info);\n }\n };\n drag.onDragStart.add(() => {\n emit(\"start\");\n });\n drag.onDrag.add(() => {\n emit(\"move\");\n });\n drag.onDragEnd.add(() => {\n emit(\"end\");\n });\n };\n for (const axis of AXES) {\n wire(position[`${axis}Gizmo`].drag, { mode: \"translate\", axis });\n wire(rotation[`${axis}Gizmo`].drag, { mode: \"rotate\", axis });\n wire(scale[`${axis}Gizmo`].drag, { mode: \"scale\", axis });\n }\n wire(scale.uniformScaleGizmo.drag, { mode: \"scale\", axis: \"uniform\" });\n\n const roots: Readonly<Record<ViewGizmoMode, readonly SceneNode[]>> = {\n translate: AXES.map((axis) => position[`${axis}Gizmo`].root),\n rotate: AXES.map((axis) => rotation[`${axis}Gizmo`].root),\n scale: [...AXES.map((axis) => scale[`${axis}Gizmo`].root), scale.uniformScaleGizmo.root],\n };\n\n const applyAttachment = (): void => {\n const shown = visible ? mode : null;\n attachPositionGizmoToNode(position, shown === \"translate\" ? target : null);\n attachRotationGizmoToNode(rotation, shown === \"rotate\" ? target : null);\n attachScaleGizmoToNode(scale, shown === \"scale\" ? target : null);\n for (const which of [\"translate\", \"rotate\", \"scale\"] as const) {\n if (which !== shown || target === null) {\n for (const root of roots[which]) {\n root.scaling.set(0, 0, 0);\n }\n }\n }\n };\n applyAttachment();\n\n const outlineMesh = (index: number): Mesh => {\n const existing = outlines[index];\n if (existing !== undefined) {\n return existing;\n }\n const mesh = createLines(engine, {\n name: \"ignifx-editor-outline\",\n points: OUTLINE_PATH.map((corner) => CORNERS[corner] ?? { x: 0, y: 0, z: 0 }),\n color: OUTLINE_COLOR,\n });\n mesh.pickable = false;\n mesh.visible = false;\n addToScene(layer.scene, mesh);\n outlines.push(mesh);\n return mesh;\n };\n\n onBeforeRender(layer.scene, () => {\n for (const [index, mesh] of outlines.entries()) {\n const entity = visible ? outlined[index] : undefined;\n const bounds =\n entity === undefined || entity.isDestroyed ? null : computeWorldBounds(entity.transform.lite, scene);\n if (bounds === null) {\n mesh.visible = false;\n continue;\n }\n mesh.visible = true;\n mesh.position.set(\n (bounds.min.x + bounds.max.x) / 2,\n (bounds.min.y + bounds.max.y) / 2,\n (bounds.min.z + bounds.max.z) / 2,\n );\n mesh.scaling.set(\n Math.max(MIN_OUTLINE_SIDE, bounds.max.x - bounds.min.x),\n Math.max(MIN_OUTLINE_SIDE, bounds.max.y - bounds.min.y),\n Math.max(MIN_OUTLINE_SIDE, bounds.max.z - bounds.min.z),\n );\n }\n });\n\n return {\n setMode(next: ViewGizmoMode | null): void {\n mode = next;\n applyAttachment();\n },\n setLocal(local: boolean): void {\n setPositionGizmoLocalCoordinates(position, local);\n setRotationGizmoLocalCoordinates(rotation, local);\n setScaleGizmoLocalCoordinates(scale, local);\n },\n attach(entity: Entity | null): void {\n target = entity === null ? null : entity.transform.lite;\n applyAttachment();\n },\n outline(entities: readonly Entity[]): void {\n outlined = [...entities];\n for (let index = 0; index < entities.length; index += 1) {\n outlineMesh(index);\n }\n for (const mesh of outlines.slice(entities.length)) {\n mesh.visible = false;\n }\n },\n setVisible(next: boolean): void {\n visible = next;\n applyAttachment();\n if (!next) {\n for (const mesh of outlines) {\n mesh.visible = false;\n }\n }\n },\n onDrag(listener): void {\n listeners.push(listener);\n },\n pointerState(): ViewPointerState {\n return {\n interacting: isGizmoInteracting(canvas),\n dragging: isGizmoDragging(canvas),\n pickPending: isGizmoPickPending(canvas),\n };\n },\n worldBounds(entity: Entity): WorldBounds | null {\n return computeWorldBounds(entity.transform.lite, scene);\n },\n dispose(): void {\n listeners.length = 0;\n overlay.dispose();\n },\n };\n}\n\n/**\n * A node's parent. Lite types it as a bare world-matrix provider, so it is followed by identity only.\n *\n * @param node - The node.\n * @returns The parent, or `null` at a root.\n */\nfunction parentNode(node: object): object | null {\n const parent: unknown = Reflect.get(node, \"parent\");\n return typeof parent === \"object\" && parent !== null ? parent : null;\n}\n\n/**\n * The world bounds of every visible mesh whose parent chain reaches a node.\n *\n * @remarks\n * Walking `node.children` is not enough: a `Model` parents its cloned glTF root with a bare\n * `parent` assignment, which leaves the entity node's `children` empty (S0.2 §6.1). So the scene's\n * meshes are scanned and kept when their parent chain reaches the node, as Lite's own bounding-box\n * gizmo does.\n *\n * @param root - The entity's node.\n * @param scene - The render scene.\n * @returns The box, or `null` when nothing under the node is drawn.\n */\nfunction computeWorldBounds(root: SceneNode, scene: SceneContext): WorldBounds | null {\n const min = { x: Number.POSITIVE_INFINITY, y: Number.POSITIVE_INFINITY, z: Number.POSITIVE_INFINITY };\n const max = { x: Number.NEGATIVE_INFINITY, y: Number.NEGATIVE_INFINITY, z: Number.NEGATIVE_INFINITY };\n const isUnder = (node: object): boolean => {\n for (let current: object | null = node; current !== null; current = parentNode(current)) {\n if (current === root) {\n return true;\n }\n }\n return false;\n };\n for (const mesh of scene.meshes) {\n const low = mesh.boundMin;\n const high = mesh.boundMax;\n if (low === undefined || high === undefined || mesh.visible === false || !isUnder(mesh)) {\n continue;\n }\n const m = mesh.worldMatrix;\n for (let corner = 0; corner < 8; corner += 1) {\n const x = (corner & 1) === 0 ? low[0] : high[0];\n const y = (corner & 2) === 0 ? low[1] : high[1];\n const z = (corner & 4) === 0 ? low[2] : high[2];\n const wx = (m[0] ?? 0) * x + (m[4] ?? 0) * y + (m[8] ?? 0) * z + (m[12] ?? 0);\n const wy = (m[1] ?? 0) * x + (m[5] ?? 0) * y + (m[9] ?? 0) * z + (m[13] ?? 0);\n const wz = (m[2] ?? 0) * x + (m[6] ?? 0) * y + (m[10] ?? 0) * z + (m[14] ?? 0);\n min.x = Math.min(min.x, wx);\n min.y = Math.min(min.y, wy);\n min.z = Math.min(min.z, wz);\n max.x = Math.max(max.x, wx);\n max.y = Math.max(max.y, wy);\n max.z = Math.max(max.z, wz);\n }\n }\n return Number.isFinite(min.x) ? { min, max } : null;\n}\n","/**\n * Asset hot reload in the scene view (engine ask E23): which changed assets the host reloads in\n * place, how it waits for the new value, and which of the document's instance roots a changed scene\n * or prefab rebuilds (`docs/architecture/17-editor-host.md` §6.1).\n */\n\nimport type { DocumentIndex } from \"./document.js\";\nimport type { App, AssetHandle } from \"@ignifx/core\";\n\n/**\n * A change on disk to one asset, as `@ignifx/vite-plugin`'s `ignifx:asset-changed` event reports\n * it; the event's payload is accepted as it is.\n *\n * @beta\n */\nexport interface EditorAssetChange {\n /** The asset's address, relative to the asset root. */\n readonly address: string;\n /** What happened to the file. */\n readonly kind: \"added\" | \"changed\" | \"removed\";\n}\n\n/** The asset type of a scene or prefab file. */\nexport const SCENE_ASSET_TYPE = \"scene\";\n\n/**\n * The asset types the host reloads in place. A scene or prefab rebuilds the document's instances\n * of it; the renderers read a model, mesh, material and sprite atlas from their handle every frame,\n * and a shader's materials rebuild on its `onReplaced`. A texture is left out: the materials and\n * atlases built from it keep the texture they were given, which the reload would unload.\n */\nexport const IN_PLACE_ASSET_TYPES: readonly string[] = [\n SCENE_ASSET_TYPE,\n \"model\",\n \"mesh\",\n \"material\",\n \"spriteatlas\",\n \"shader\",\n];\n\n/** A pending wait for a reload, which the host settles with `false` when it is disposed. */\nexport interface PendingReload {\n /** Resolves with `true` once the new value is delivered, `false` when the reload failed. */\n readonly replaced: Promise<boolean>;\n /** Stops waiting and resolves {@link PendingReload.replaced} with `false`. */\n cancel(): void;\n}\n\n/**\n * Starts waiting for a handle's next replacement. The assets service reports a failed reload only\n * through `app.onError`, without the address, so any asset failure while waiting ends the wait.\n *\n * @param app - The scene view's app.\n * @param handle - The handle about to be reloaded.\n * @returns The wait.\n */\nexport function waitForReplacement(app: App, handle: AssetHandle): PendingReload {\n let settle: ((replaced: boolean) => void) | null = null;\n const replaced = new Promise<boolean>((resolve) => {\n settle = resolve;\n });\n const disconnects: (() => void)[] = [];\n const finish = (value: boolean): void => {\n for (const disconnect of disconnects.splice(0)) {\n disconnect();\n }\n settle?.(value);\n };\n disconnects.push(\n handle.onReplaced.connect((): void => {\n finish(true);\n }),\n app.onError.connect((report): void => {\n if (report.source === \"asset\") {\n finish(false);\n }\n }),\n );\n return {\n replaced,\n cancel: (): void => {\n finish(false);\n },\n };\n}\n\n/**\n * Collects the addresses a scene asset instances, directly or through the scenes it instances.\n *\n * @param app - The scene view's app.\n * @param address - The scene's address.\n * @param into - The addresses found so far; also guards against a cycle.\n * @returns `into`, with `address` and every scene it pulls in added.\n */\nfunction sceneClosure(app: App, address: string, into: Set<string>): Set<string> {\n if (into.has(address)) {\n return into;\n }\n into.add(address);\n const handle = app.assets.get(address);\n if (handle === null || handle.state !== \"loaded\" || handle.type !== SCENE_ASSET_TYPE) {\n return into;\n }\n const dependencies: unknown = Reflect.get(Object(handle.value), \"dependencies\");\n if (Array.isArray(dependencies)) {\n for (const dependency of dependencies) {\n const nested: unknown = Reflect.get(Object(dependency), \"address\");\n if (typeof nested === \"string\") {\n sceneClosure(app, nested, into);\n }\n }\n }\n return into;\n}\n\n/**\n * The document's instance roots built from a scene, directly or through another scene they\n * instance, in document order. A root inside another root of the list is left out: rebuilding the\n * outer one rebuilds it.\n *\n * @param app - The scene view's app.\n * @param index - The open document's index.\n * @param address - The changed scene's address.\n * @returns The roots' uids.\n */\nexport function instancesOf(app: App, index: DocumentIndex, address: string): readonly string[] {\n const affected = new Set<string>();\n for (const record of index.file.entities) {\n const scene = record.instance?.scene.$asset;\n if (scene !== undefined && sceneClosure(app, scene, new Set()).has(address)) {\n affected.add(record.uid);\n }\n }\n return outermostRoots(index, affected);\n}\n\n/**\n * The document entities of a set that have no ancestor in the set, in the set's order: rebuilding\n * an instance root rebuilds every instance root under it.\n *\n * @param index - The open document's index.\n * @param roots - The uids.\n * @returns The outermost ones.\n */\nexport function outermostRoots(index: DocumentIndex, roots: ReadonlySet<string>): readonly string[] {\n return [...roots].filter((uid) => {\n for (let parent = index.records.get(uid)?.parent ?? null; parent !== null;) {\n if (roots.has(parent)) {\n return false;\n }\n parent = index.records.get(parent)?.parent ?? null;\n }\n return true;\n });\n}\n","/**\n * `getColliderOutlines`: the physics extensions' collider outlines, made JSON. The host reads\n * `app.physics.colliderOutlines` and `app.physics2d.colliderOutlines` by shape, as `@ignifx/devtools`\n * reads `app.physics`, so a project without physics costs the host nothing and the host depends on\n * neither package (ADR-0028, amendment of 2026-10-20).\n */\n\nimport { Component } from \"@ignifx/core\";\nimport { COLLIDER_OUTLINES_MAX_ENTITIES, COLLIDER_OUTLINES_MAX_NUMBERS } from \"../protocol/index.js\";\nimport type { ColliderOutlineRecord, ColliderOutlineSet } from \"../protocol/index.js\";\nimport type { App, Entity } from \"@ignifx/core\";\n\n/** One outline as a physics service answers it. */\ninterface OutlineLike {\n /** The collider. */\n readonly collider: Component;\n /** Whether it is a trigger. */\n readonly isTrigger: boolean;\n /** Its segments: `x, y, z` per end in 3D, `x, y` per end in 2D. */\n readonly lines: Float32Array;\n}\n\n/** How many decimal places a coordinate keeps on the wire: a hundredth of a millimetre. */\nconst WIRE_PRECISION = 1e5;\n\n/**\n * Finds `colliderOutlines` on one of the app's physics services.\n *\n * @param app - The app.\n * @param property - `\"physics\"` or `\"physics2d\"`.\n * @returns A function that outlines an entity's colliders, or `null` when the project does not\n * register that extension (or registers one from before the method).\n */\nfunction outlinerOf(app: App, property: string): ((entity: Entity) => readonly OutlineLike[]) | null {\n const service: unknown = Reflect.get(app, property);\n if (typeof service !== \"object\" || service === null) {\n return null;\n }\n const method: unknown = Reflect.get(service, \"colliderOutlines\");\n if (typeof method !== \"function\") {\n return null;\n }\n return (entity: Entity): readonly OutlineLike[] => {\n const answer: unknown = Reflect.apply(method, service, [entity]);\n return Array.isArray(answer) ? answer.filter(isOutlineLike) : [];\n };\n}\n\n/**\n * Tells whether a value has an outline's shape.\n *\n * @param value - The value.\n * @returns True for a component, a boolean, and a `Float32Array`.\n */\nfunction isOutlineLike(value: unknown): value is OutlineLike {\n return (\n typeof value === \"object\" &&\n value !== null &&\n Reflect.get(value, \"collider\") instanceof Component &&\n typeof Reflect.get(value, \"isTrigger\") === \"boolean\" &&\n Reflect.get(value, \"lines\") instanceof Float32Array\n );\n}\n\n/**\n * Rounds a coordinate for the wire, which also drops the float32 noise (`0.30000001192092896`).\n *\n * @param value - The coordinate.\n * @returns The rounded coordinate.\n */\nfunction wireNumber(value: number): number {\n return Math.round(value * WIRE_PRECISION) / WIRE_PRECISION;\n}\n\n/**\n * Turns 3D segments into wire numbers.\n *\n * @param lines - `x, y, z` per end.\n * @returns The same segments, rounded.\n */\nfunction lines3D(lines: Float32Array): number[] {\n return Array.from(lines, wireNumber);\n}\n\n/**\n * Turns 2D segments into 3D wire numbers at a depth.\n *\n * @param lines - `x, y` per end.\n * @param z - The entity's world `z`.\n * @returns `x, y, z` per end, rounded.\n */\nfunction lines2D(lines: Float32Array, z: number): number[] {\n const out: number[] = [];\n for (let index = 0; index + 1 < lines.length; index += 2) {\n out.push(wireNumber(lines[index] ?? 0), wireNumber(lines[index + 1] ?? 0), wireNumber(z));\n }\n return out;\n}\n\n/**\n * Outlines the colliders of document entities, 3D first and then 2D for each entity, within the\n * protocol's caps: at most `COLLIDER_OUTLINES_MAX_ENTITIES` entities and\n * `COLLIDER_OUTLINES_MAX_NUMBERS` numbers of lines. What passes a cap is left out, whole, and the\n * answer says `truncated`.\n *\n * @param app - The scene view's app.\n * @param requested - The requested entities, as many as asked, before any is looked up.\n * @param resolve - Finds a requested uid's entity in the open scene, or `undefined`.\n * @returns The answer to `getColliderOutlines`.\n */\nexport function colliderOutlinesOf(\n app: App,\n requested: readonly string[],\n resolve: (uid: string) => Entity | undefined,\n): ColliderOutlineSet {\n const outline3D = outlinerOf(app, \"physics\");\n const outline2D = outlinerOf(app, \"physics2d\");\n const outlines: ColliderOutlineRecord[] = [];\n const uids = [...new Set(requested)];\n let truncated = uids.length > COLLIDER_OUTLINES_MAX_ENTITIES;\n let numbers = 0;\n for (const uid of uids.slice(0, COLLIDER_OUTLINES_MAX_ENTITIES)) {\n const entity = resolve(uid);\n if (entity === undefined) {\n continue;\n }\n const z = entity.transform.position.z;\n const found: (readonly [OutlineLike, boolean])[] = [\n ...(outline3D?.(entity) ?? []).map((outline) => [outline, false] as const),\n ...(outline2D?.(entity) ?? []).map((outline) => [outline, true] as const),\n ];\n for (const [outline, is2D] of found) {\n const count = is2D ? (outline.lines.length / 2) * 3 : outline.lines.length;\n if (numbers + count > COLLIDER_OUTLINES_MAX_NUMBERS) {\n truncated = true;\n return { outlines, truncated };\n }\n numbers += count;\n outlines.push({\n entity: uid,\n component: outline.collider.uid,\n isTrigger: outline.isTrigger,\n lines: is2D ? lines2D(outline.lines, z) : lines3D(outline.lines),\n });\n }\n }\n return { outlines, truncated };\n}\n","/**\n * `playStats`: the game's frame rate and frame time from the frame history `app.diagnostics` keeps,\n * and the number of entities its world holds (`docs/architecture/17-editor-host.md` §5).\n */\n\nimport { createFrameSample } from \"@ignifx/core\";\nimport type { PlayStats } from \"./protocol/index.js\";\nimport type { App, Entity, FrameSample, SceneInstance } from \"@ignifx/core\";\n\n/** How much of the frame history the rate is averaged over, in milliseconds of rendered frames. */\nexport const PLAY_STATS_WINDOW_MS = 1000;\n\n/** Milliseconds in one second. */\nconst MILLISECONDS_PER_SECOND = 1000;\n\n/**\n * Counts the entities of a scene instance, members of instanced scenes included.\n *\n * @param scene - The instance.\n * @returns How many entities it holds, destroyed ones left out.\n */\nexport function countEntities(scene: SceneInstance): number {\n let count = 0;\n const pending: Entity[] = [...scene.roots];\n for (let entity = pending.pop(); entity !== undefined; entity = pending.pop()) {\n if (!entity.isDestroyed) {\n count += 1;\n pending.push(...entity.children);\n }\n }\n return count;\n}\n\n/**\n * Rounds a rate for the wire: two decimals are more than the stats strip shows.\n *\n * @param value - The value.\n * @returns It, to the nearest hundredth.\n */\nfunction hundredths(value: number): number {\n return Math.round(value * 100) / 100;\n}\n\n/** Reads a game's stats, with the one frame sample it reads the history into. */\nexport class PlayStatsReader {\n readonly #app: App;\n\n readonly #sample: FrameSample = createFrameSample();\n\n /**\n * Binds a reader to the game's app.\n *\n * @param app - The game's app.\n */\n constructor(app: App) {\n this.#app = app;\n }\n\n /**\n * Reads the stats now.\n *\n * @returns The mean frame time and rate over the newest second of the frame history (both `0`\n * while the frame loop does not run), the world's entity count, and `app.time.frameCount`.\n */\n read(): PlayStats {\n const app = this.#app;\n const diagnostics = app.diagnostics;\n let frames = 0;\n let elapsedMs = 0;\n // A stopped or stepped game has no loop: its history is the past, not a rate.\n if (app.isRunning) {\n for (let offset = 0; offset < diagnostics.historyLength && elapsedMs < PLAY_STATS_WINDOW_MS; offset += 1) {\n elapsedMs += diagnostics.readFrame(offset, this.#sample).rawDeltaMs;\n frames += 1;\n }\n }\n const frameTimeMs = frames > 0 && elapsedMs > 0 ? elapsedMs / frames : 0;\n let entityCount = 0;\n for (const scene of app.world.scenes) {\n entityCount += countEntities(scene);\n }\n return {\n fps: frameTimeMs > 0 ? hundredths(MILLISECONDS_PER_SECOND / frameTimeMs) : 0,\n frameTimeMs: hundredths(frameTimeMs),\n entityCount,\n frameCount: app.time.frameCount,\n };\n }\n}\n","/**\n * The open scene document's live mirror: the scene instance the editor's file is built into, the\n * scene settings the host keeps for it, and the lookups every scene method shares. Only the\n * document's own entities and components are reachable through it: an instanced scene's members and\n * the editor's objects never are (protocol 0.3, \"Document uids only\").\n */\n\nimport {\n canonicalizeNumber,\n CoreErrorCode,\n decodeProps,\n parseOverridePath,\n SCENE_ASSET_TYPE,\n serializeScene,\n} from \"@ignifx/core\";\nimport { countEntities } from \"../play-stats.js\";\nimport type { OpenSceneResult, ReadBackParams, ReadBackResult, SceneIssue } from \"../protocol/index.js\";\nimport type {\n App,\n AssetHandle,\n Component,\n Entity,\n JsonObject,\n JsonValue,\n ReferenceDecoder,\n SceneAsset,\n SceneFile,\n SceneFileComponent,\n SceneFileEntity,\n SceneFileInstance,\n SceneFileOverride,\n SceneInstance,\n UidRemap,\n} from \"@ignifx/core\";\n\n/** Where a document that was never saved is published in the asset cache. */\nexport const UNSAVED_SCENE_ADDRESS = \"memory:scene/unsaved\";\n\n/** The document as the live world holds it now, written by `serializeScene`. */\nexport interface DocumentIndex {\n /** The serialized document, with `engineVersion` omitted. */\n readonly file: SceneFile;\n /** What the serializer reported. */\n readonly issues: readonly SceneIssue[];\n /** Each document entity, by uid. */\n readonly entities: ReadonlyMap<string, Entity>;\n /** Each document entity's record, by uid. */\n readonly records: ReadonlyMap<string, SceneFileEntity>;\n /** Each document component, by uid. */\n readonly components: ReadonlyMap<string, Component>;\n /**\n * Each component an instance root's `add` override gives a member, by uid: not a document\n * component (no op edits it), but a reference in the document may name it, as one in a file may.\n */\n readonly added: ReadonlyMap<string, Component>;\n}\n\n/**\n * Copies a JSON value, so the host's settings never share an object with the editor's message.\n *\n * @param value - The value.\n * @returns A deep copy.\n */\nexport function copyJson<T extends JsonValue>(value: T): T {\n return structuredClone(value);\n}\n\n/**\n * Assigns a component's props decoded from JSON, the way the scene loader does: every schema field\n * the JSON leaves out takes its default.\n *\n * @param component - The component.\n * @param props - The `props` object.\n * @param references - How references resolve.\n * @param only - The fields to assign, if not every one; only their problems are returned.\n * @returns The decoding problems, as `{ code, message }`.\n */\nexport function assignProps(\n component: Component,\n props: JsonObject,\n references: ReferenceDecoder,\n only?: ReadonlySet<string>,\n): SceneIssue[] {\n const decoded = decodeComponentProps(component, props, references, only);\n for (const [name, value] of decoded.values) {\n Reflect.set(component, name, value);\n }\n return decoded.issues;\n}\n\n/**\n * The problems {@link assignProps} would return, without assigning anything.\n *\n * @param component - The component.\n * @param props - The `props` object.\n * @param references - How references resolve.\n * @param only - The fields to decode, if not every one.\n * @returns The decoding problems, as `{ code, message }`.\n */\nexport function propIssues(\n component: Component,\n props: JsonObject,\n references: ReferenceDecoder,\n only?: ReadonlySet<string>,\n): SceneIssue[] {\n return decodeComponentProps(component, props, references, only).issues;\n}\n\n/**\n * Decodes a component's props from JSON, every schema field the JSON leaves out taking its default.\n *\n * @param component - The component.\n * @param props - The `props` object.\n * @param references - How references resolve.\n * @param only - The fields to keep, if not every one.\n * @returns The kept fields' values, and their problems as `{ code, message }`.\n */\nfunction decodeComponentProps(\n component: Component,\n props: JsonObject,\n references: ReferenceDecoder,\n only: ReadonlySet<string> | undefined,\n): { readonly values: ReadonlyMap<string, unknown>; readonly issues: SceneIssue[] } {\n const schema = component.world.registry.describe(component.constructor).schema;\n if (schema === null) {\n return { values: new Map(), issues: [] };\n }\n const decoded = decodeProps(schema, props, references);\n const all = new Map<string, unknown>(Object.entries(decoded.value));\n const values = new Map<string, unknown>();\n for (const name of Object.keys(schema)) {\n if (only === undefined || only.has(name)) {\n values.set(name, all.get(name));\n }\n }\n // An issue's path starts with its field's name, then `.` or `[` for a deeper step.\n const issues = decoded.issues\n .filter((issue) => only === undefined || only.has(issue.path.split(/[.[]/u, 1)[0] ?? \"\"))\n .map((issue) => ({ code: issue.code, message: `${component.uid}.${issue.path}: ${issue.message}` }));\n return { values, issues };\n}\n\n/**\n * Tells a component that the host changed some of its fields, through its `onValidate` hook\n * (`ComponentHooks`), so one that builds something from them (a physics body) rebuilds it.\n *\n * @param component - The component.\n * @param fields - The fields that changed; nothing is called when the list is empty.\n */\nexport function validateFields(component: Component, fields: readonly string[]): void {\n const hook: unknown = Reflect.get(component, \"onValidate\");\n if (fields.length > 0 && typeof hook === \"function\") {\n Reflect.apply(hook, component, [fields]);\n }\n}\n\n/**\n * An override in the form the scene file writes it, which editor-core's document holds: an op\n * sent as `{ op: \"replace\" }` or a transform value with more than six decimals still reads back\n * as the document has it.\n *\n * @param override - The override as an op or a file carried it.\n * @returns The canonical override.\n */\nfunction canonicalOverride(override: SceneFileOverride): SceneFileOverride {\n const op = override.op ?? \"replace\";\n const value = op === \"remove\" ? undefined : canonicalOverrideValue(override.path, override.value);\n return {\n ...(op === \"replace\" ? {} : { op }),\n path: override.path,\n ...(value === undefined ? {} : { value }),\n };\n}\n\n/**\n * A transform override's value with each number canonical; any other value as it is.\n *\n * @param path - The override's path.\n * @param value - Its value.\n * @returns The value to keep.\n */\nfunction canonicalOverrideValue(path: string, value: JsonValue | undefined): JsonValue | undefined {\n const list: unknown = value;\n if (!Array.isArray(list) || !isTransformPath(path)) {\n return value;\n }\n const items: readonly unknown[] = list;\n const numbers: number[] = [];\n for (const item of items) {\n if (typeof item !== \"number\") {\n return value;\n }\n numbers.push(canonicalizeNumber(item));\n }\n return numbers;\n}\n\n/**\n * Whether an override path names a transform field.\n *\n * @param path - The path.\n * @returns `false` too for a path the engine's grammar refuses.\n */\nfunction isTransformPath(path: string): boolean {\n try {\n return parseOverridePath(path).kind === \"transform\";\n } catch {\n return false;\n }\n}\n\n/** The live mirror of the editor's open scene document. */\nexport class DocumentMirror {\n readonly #app: App;\n\n #scene: SceneInstance | null = null;\n\n #address: string | null = null;\n\n #name = \"\";\n\n #settings: JsonObject | null = null;\n\n #index: DocumentIndex | null = null;\n\n /**\n * The fields each document component's record sets, by component uid: the keys of its `props` as\n * the file and the ops since have written them. A field left out takes the schema's default.\n */\n readonly #explicit = new Map<string, Set<string>>();\n\n /**\n * Each instance root's override list as the document holds it, by root uid. The serializer\n * recomputes overrides by diffing the live members with their scene, which after a hot reload\n * that changed a default reads every stale member value as an override.\n */\n readonly #overrides = new Map<string, readonly SceneFileOverride[]>();\n\n /**\n * Each instance root's overrides as the serializer read them right after the host built the root,\n * as JSON text, by root uid. While the serializer still reads the same, the members are as the\n * document's list built them, and `readBack` writes that list.\n */\n readonly #builtAs = new Map<string, string>();\n\n /**\n * Where an `add` puts a component on each instance root itself (`<root>/components` of a one-root\n * scene), or `null`, by root uid, read from the scene the root was last built from. A reload that\n * changes the scene's roots replaces the scene in the cache before the root is rebuilt, while the\n * serializer still writes the root as that build made it.\n */\n readonly #rootPaths = new Map<string, string | null>();\n\n /** Assets loaded for ops, held until the document closes. */\n readonly #handles: AssetHandle[] = [];\n\n /**\n * Creates the mirror for one app.\n *\n * @param app - The scene view's app.\n */\n constructor(app: App) {\n this.#app = app;\n }\n\n /**\n * The open document's scene instance.\n *\n * @returns The instance, or `null` while no document is open.\n */\n get scene(): SceneInstance | null {\n return this.#scene;\n }\n\n /**\n * The address the open document was given, or `null` for one never saved.\n *\n * @returns The address.\n */\n get address(): string | null {\n return this.#address;\n }\n\n /**\n * The open document's file name.\n *\n * @returns The name, or `\"\"` while no document is open.\n */\n get name(): string {\n return this.#name;\n }\n\n /**\n * The document's `settings`, as the host keeps them. `readBack` writes these, because ops edit\n * them; systems that read scene settings read them once, when a scene opens.\n *\n * @returns The settings, or `null` when the document has none.\n */\n get settings(): JsonObject | null {\n return this.#settings;\n }\n\n // The accessor pair is documented on the getter only (API Extractor's `ae-setter-with-docs`).\n // eslint-disable-next-line jsdoc/require-jsdoc -- see the comment above\n set settings(value: JsonObject | null) {\n this.#settings = value;\n this.#index = null;\n }\n\n /**\n * Replaces the open document with a file: unloads the previous one, then builds this one into a\n * new scene instance with the file's uids, loading its assets.\n *\n * @param file - The document's file, already validated.\n * @param address - Where it is saved, or `null`.\n * @returns The entity count and the build's warnings.\n * @throws Whatever `world.loadSceneFile` throws; no document is open afterwards.\n */\n async open(file: SceneFile, address: string | null): Promise<OpenSceneResult> {\n await this.close();\n const where = address ?? UNSAVED_SCENE_ADDRESS;\n const warnings: SceneIssue[] = [];\n const held = await this.#loadDoubledScenes(file.entities);\n let scene: SceneInstance;\n let entities: SceneFileEntity[];\n try {\n entities = withoutDoubleAdds(this.#app, file.entities, where, warnings);\n scene = await this.#app.world.loadSceneFile(\n { ...file, entities },\n {\n address: where,\n onIssue: (issue) => {\n warnings.push({ code: issue.code, message: issue.message });\n },\n },\n );\n } finally {\n for (const handle of held) {\n handle.release();\n }\n }\n this.#scene = scene;\n this.#address = address;\n this.#name = file.name;\n this.#settings = file.settings === undefined ? null : copyJson(file.settings);\n this.recordComponents(entities.flatMap((record) => record.components ?? []));\n this.recordInstances(entities);\n // That index was read before the first frame; the next lookup reads the world again.\n this.invalidate();\n return { entityCount: countEntities(scene), warnings };\n }\n\n /**\n * Loads the scenes of the instance roots whose records may hold the old double form of an added\n * component, so {@link withoutDoubleAdds} can tell where each scene's root is.\n *\n * @param records - The file's entity records.\n * @returns The handles, each with one holder the caller releases.\n */\n async #loadDoubledScenes(records: readonly SceneFileEntity[]): Promise<AssetHandle[]> {\n const handles: AssetHandle[] = [];\n for (const record of records) {\n const instance = record.instance;\n const own = new Set((record.components ?? []).map((component) => component.uid));\n const adds = (instance?.overrides ?? []).flatMap((override) => addedUids(override));\n if (instance === undefined || !adds.some((uid) => own.has(uid))) {\n continue;\n }\n handles.push(\n this.#app.assets.load<SceneAsset>(instance.scene.$asset, { type: instance.scene.type ?? SCENE_ASSET_TYPE }),\n );\n }\n // A load that fails is the build's to report, as it loads the scene again.\n await Promise.allSettled(handles.map(async (handle) => handle.promise));\n return handles;\n }\n\n /** Unloads the open document, if any, and releases the assets its ops loaded. */\n async close(): Promise<void> {\n const scene = this.#scene;\n this.#scene = null;\n this.#address = null;\n this.#name = \"\";\n this.#settings = null;\n this.#index = null;\n this.#explicit.clear();\n this.#overrides.clear();\n this.#builtAs.clear();\n this.#rootPaths.clear();\n if (scene !== null) {\n await this.#app.world.unloadScene(scene);\n }\n for (const handle of this.#handles.splice(0)) {\n handle.release();\n }\n }\n\n /**\n * Keeps asset handles alive until the document closes.\n *\n * @param handles - Handles loaded for an op, each with one holder the mirror now owns.\n */\n retain(handles: readonly AssetHandle[]): void {\n this.#handles.push(...handles);\n }\n\n /**\n * Records which fields document components' records set, replacing what was known of each uid.\n *\n * @param components - The component records, as a file or an op carries them.\n */\n recordComponents(components: readonly SceneFileComponent[]): void {\n for (const component of components) {\n this.recordProps(component.uid, Object.keys(component.props ?? {}));\n }\n }\n\n /**\n * Records the whole set of fields a component's record sets.\n *\n * @param uid - The component's uid.\n * @param fields - The fields.\n */\n recordProps(uid: string, fields: Iterable<string>): void {\n this.#explicit.set(uid, new Set(fields));\n }\n\n /**\n * Records that a component's record now sets a field, or leaves it out.\n *\n * @param uid - The component's uid.\n * @param field - The field.\n * @param isSet - Whether the record sets it.\n */\n recordProp(uid: string, field: string, isSet: boolean): void {\n let fields = this.#explicit.get(uid);\n if (fields === undefined) {\n fields = new Set();\n this.#explicit.set(uid, fields);\n }\n if (isSet) {\n fields.add(field);\n } else {\n fields.delete(field);\n }\n }\n\n /**\n * The fields a document component's record sets.\n *\n * @param uid - The component's uid.\n * @returns The field names, or `null` when the mirror has no record of the component.\n */\n propsSetBy(uid: string): ReadonlySet<string> | null {\n return this.#explicit.get(uid) ?? null;\n }\n\n /**\n * Records the override lists of the instance roots among some entity records the host has just\n * built, and what the serializer reads from those roots now, before anything else can change\n * their members.\n *\n * @param records - The records, as a file or an op carries them.\n */\n recordInstances(records: readonly SceneFileEntity[]): void {\n const roots = records.filter((record) => record.instance !== undefined);\n for (const record of roots) {\n this.recordOverrides(record.uid, record.instance?.overrides ?? []);\n this.#rootPaths.set(\n record.uid,\n record.instance === undefined ? null : rootComponentsPath(this.#app, record.instance),\n );\n }\n if (roots.length === 0) {\n return;\n }\n this.#index = null;\n const index = this.index();\n for (const record of roots) {\n const read = index?.records.get(record.uid)?.instance;\n if (read === undefined) {\n this.#builtAs.delete(record.uid);\n } else {\n this.#builtAs.set(record.uid, JSON.stringify(read.overrides ?? []));\n }\n }\n }\n\n /**\n * Records an instance root's override list, each override in the form the scene file writes and\n * editor-core's document holds: no `op` for a `replace`, no value for a `remove`, and a\n * transform's numbers canonical.\n *\n * @param uid - The root's uid.\n * @param overrides - The list.\n */\n recordOverrides(uid: string, overrides: readonly SceneFileOverride[]): void {\n // A copy, so the list never shares an object with the editor's message.\n this.#overrides.set(uid, structuredClone(overrides).map(canonicalOverride));\n }\n\n /**\n * Where an `add` override puts a component on an instance root itself, in the scene the root was\n * last built from.\n *\n * @param uid - The root's uid.\n * @returns `<scene root uid>/components` when that scene has one root, or `null`.\n */\n rootPathOf(uid: string): string | null {\n return this.#rootPaths.get(uid) ?? null;\n }\n\n /**\n * An instance root's override list as the document holds it.\n *\n * @param uid - The root's uid.\n * @returns The list, or `null` when the mirror has no record of the root.\n */\n overridesOf(uid: string): readonly SceneFileOverride[] | null {\n return this.#overrides.get(uid) ?? null;\n }\n\n /** Forgets the cached index; call it after anything changed the document's structure. */\n invalidate(): void {\n this.#index = null;\n }\n\n /**\n * The document as the live world holds it, serialized once and cached until an op, `open` or\n * `readBack` drops it; the next call serializes the world again. Every lookup (selection, picks,\n * the ops' references) reads this cache, so a lookup after a `readBack` sees the world as that\n * `readBack` did.\n *\n * @returns The index, or `null` while no document is open.\n */\n index(): DocumentIndex | null {\n const scene = this.#scene;\n if (scene === null) {\n return null;\n }\n this.#index ??= this.#buildIndex(scene);\n return this.#index;\n }\n\n /**\n * Serializes the requested entities as the live world has them (protocol `readBack`).\n *\n * @remarks\n * The world is serialized again on every call, not read from the cache, because a `\"run\"`\n * system or a `runInEditMode` script can change it outside an op.\n *\n * An instance root's overrides are the list the document holds, in its order, while the\n * serializer still reads its members as they were built from that list. The serializer's own\n * list is a diff in file order that writes an added component whole and leaves out an override\n * equal to the instanced scene's value, so it never equals the document's; it is written instead\n * once the members read differently, so a change the document did not make still shows.\n *\n * @param params - The uids to read, or none for all.\n * @returns The records in file order, the uids not found, the settings, and the serializer's issues.\n */\n readBack(params: ReadBackParams): ReadBackResult | null {\n this.invalidate();\n const index = this.index();\n if (index === null) {\n return null;\n }\n const requested = params.entities;\n const wanted = requested === undefined ? null : new Set(requested);\n return {\n entities: index.file.entities\n .filter((record) => wanted === null || wanted.has(record.uid))\n .map((record) => this.#withDocumentOverrides(record)),\n missing: requested === undefined ? [] : [...new Set(requested)].filter((uid) => !index.records.has(uid)),\n settings: index.file.settings ?? null,\n issues: index.issues,\n };\n }\n\n /**\n * The nearest document entity at or above an entity: itself, or the instance root it was\n * expanded from (protocol 0.3, \"Document uids only\").\n *\n * @param entity - Any entity.\n * @returns The document entity, or `null` when the entity is not in the document.\n */\n documentEntityOf(entity: Entity | null): Entity | null {\n const index = this.index();\n if (index === null || entity === null || entity.scene !== this.#scene) {\n return null;\n }\n for (let current: Entity | null = entity; current !== null; current = current.parent) {\n if (index.entities.get(current.uid) === current) {\n return current;\n }\n }\n return null;\n }\n\n /**\n * How references in props resolve: document uids first, then the uids of a subtree just built,\n * then the components instances' `add` overrides gave their members, as a reopen resolves them;\n * and assets already loaded in the app's cache.\n *\n * @param built - The uid table of a subtree an op just built, if any.\n * @returns The decoder.\n */\n decoder(built?: UidRemap): ReferenceDecoder {\n const index = this.index();\n const assets = this.#app.assets;\n return {\n entity: (uid: string): Entity | null => index?.entities.get(uid) ?? built?.entity(uid) ?? null,\n component: (uid: string): Component | null =>\n index?.components.get(uid) ?? built?.component(uid) ?? index?.added.get(uid) ?? null,\n asset: (address: string, type: string | null): AssetHandle | null => {\n const handle = assets.get(address);\n return handle !== null && handle.state === \"loaded\" && (type === null || handle.type === type) ? handle : null;\n },\n };\n }\n\n /**\n * An entity's record with the document's override list, when it is an instance root whose\n * members still read as they were built from that list.\n *\n * @param record - The record as the serializer wrote it.\n * @returns The record to read back.\n */\n #withDocumentOverrides(record: SceneFileEntity): SceneFileEntity {\n const read = record.instance;\n const listed = this.#overrides.get(record.uid);\n const built = this.#builtAs.get(record.uid);\n if (read === undefined || listed === undefined || JSON.stringify(read.overrides ?? []) !== built) {\n return record;\n }\n const instance: SceneFileInstance = {\n scene: read.scene,\n ...(read.hash === undefined ? {} : { hash: read.hash }),\n ...(listed.length === 0 ? {} : { overrides: structuredClone(listed) }),\n };\n return withOverrideList(record, instance, this.rootPathOf(record.uid));\n }\n\n /**\n * Serializes the document and indexes its entities and components.\n *\n * @param scene - The document's scene instance.\n * @returns The index.\n */\n #buildIndex(scene: SceneInstance): DocumentIndex {\n const issues: SceneIssue[] = [];\n const file = serializeScene(scene, {\n engineVersion: null,\n settings: this.#settings,\n onIssue: (issue) => {\n issues.push({ code: issue.code, message: issue.message });\n },\n });\n const world = this.#app.world;\n const entities = new Map<string, Entity>();\n const records = new Map<string, SceneFileEntity>();\n const components = new Map<string, Component>();\n const added = new Map<string, Component>();\n for (const record of file.entities) {\n const entity = world.getEntity(record.uid);\n if (entity === null) {\n continue;\n }\n entities.set(record.uid, entity);\n records.set(record.uid, record);\n const uids = new Set((record.components ?? []).map((component) => component.uid));\n for (const component of entity.components) {\n if (uids.has(component.uid) && !component.isDestroyed) {\n components.set(component.uid, component);\n }\n }\n const adds = new Set((record.instance?.overrides ?? []).flatMap((override) => addedUids(override)));\n if (adds.size > 0) {\n collectComponents(entity, adds, added);\n }\n }\n return { file, issues, entities, records, components, added };\n }\n}\n\n/**\n * A file's entity records without the old double form of an added component: before `readBack`\n * wrote each `add` override once, it also wrote one that adds to the root of a one-root scene as\n * the root's own component, with the same uid, so a reopen built it twice. Each is kept once, as the\n * override list adds it, so `readBack` reads the same from the first frame. Only an `add` to the\n * root's component list counts: one on another member that reuses a uid of the root's own\n * components is not the old form, so both are built, with a warning of its own.\n *\n * @param app - The scene view's app, whose cache holds the instanced scenes.\n * @param records - The file's entity records.\n * @param address - The document's address, for the warnings.\n * @param warnings - Gets one `IGX-0608` warning when a record had the double form, and one when a\n * record's list adds to a member with a uid of the root's own components.\n * @returns The records, each collapsed one replaced.\n */\nfunction withoutDoubleAdds(\n app: App,\n records: readonly SceneFileEntity[],\n address: string,\n warnings: SceneIssue[],\n): SceneFileEntity[] {\n const doubled: string[] = [];\n const reused: string[] = [];\n const collapsed = records.map((record) => {\n const instance = record.instance;\n if (instance === undefined || record.components === undefined) {\n return record;\n }\n const single = withOverrideList(record, instance, rootComponentsPath(app, instance));\n const kept = new Set((single.components ?? []).map((component) => component.uid));\n const adds = new Set((instance.overrides ?? []).flatMap((override) => addedUids(override)));\n for (const component of record.components) {\n if (!kept.has(component.uid)) {\n doubled.push(`${record.uid}/${component.uid}`);\n } else if (adds.has(component.uid)) {\n reused.push(`${record.uid}/${component.uid}`);\n }\n }\n return single;\n });\n if (reused.length > 0) {\n warnings.push({\n code: CoreErrorCode.sceneFileInvalid,\n message:\n `${address}: ${reused.join(\", \")}: each of these uids names both an instance root's own component and ` +\n \"one an add override in its list gives a member; both are built.\",\n });\n }\n if (doubled.length > 0) {\n warnings.push({\n code: CoreErrorCode.sceneFileInvalid,\n message:\n `${address}: ${doubled.join(\", \")}: an older editor wrote each of these components both as an ` +\n \"instance root's own and in its override list, with one uid; each is kept once, as the list adds it.\",\n });\n }\n return collapsed;\n}\n\n/**\n * An instance root's record with an instance entry whose override list replaces the serializer's.\n * The serializer writes a component that an `add` override gives the root of a one-root scene as\n * the root's own, so the record leaves out each component the list adds there; a rebuild or a\n * reopen would otherwise add it twice.\n *\n * @param record - The record as the serializer wrote it.\n * @param instance - The instance entry, with the document's list.\n * @param path - `<scene root uid>/components` of the scene the record was written against, when\n * that scene has one root, or `null`.\n * @returns The record.\n */\nexport function withOverrideList(\n record: SceneFileEntity,\n instance: SceneFileInstance,\n path: string | null,\n): SceneFileEntity {\n const adds = new Set(\n (instance.overrides ?? []).filter((override) => override.path === path).flatMap((override) => addedUids(override)),\n );\n const own = record.components ?? [];\n const components = own.filter((component) => !adds.has(component.uid));\n if (components.length === own.length) {\n return { ...record, instance };\n }\n const { components: _written, ...rest } = record;\n return { ...rest, instance, ...(components.length === 0 ? {} : { components }) };\n}\n\n/**\n * The override path of the component list of an instanced scene's root, when the scene has one\n * root: a component an `add` there gives is the instance root's own.\n *\n * @param app - The scene view's app.\n * @param instance - The instance entry.\n * @returns `<root uid>/components`, or `null` for a scene with several roots or none, or one the\n * cache does not hold loaded as a scene.\n */\nfunction rootComponentsPath(app: App, instance: SceneFileInstance): string | null {\n const handle = app.assets.get<SceneAsset>(instance.scene.$asset);\n if (handle === null || handle.state !== \"loaded\" || handle.type !== SCENE_ASSET_TYPE) {\n return null;\n }\n const roots = handle.value.file.entities.filter((entity) => entity.parent === null);\n const root = roots.length === 1 ? roots[0] : undefined;\n return root === undefined ? null : `${root.uid}/components`;\n}\n\n/**\n * The uid of the component an `add` override of a component list adds, as a list.\n *\n * @param override - The override.\n * @returns The uid, or nothing.\n */\nfunction addedUids(override: SceneFileOverride): string[] {\n const value = override.value;\n const uid: unknown =\n override.op === \"add\" && typeof value === \"object\" && value !== null ? Reflect.get(value, \"uid\") : null;\n return typeof uid === \"string\" ? [uid] : [];\n}\n\n/**\n * Finds the live components with some uids in a subtree.\n *\n * @param entity - The subtree's root.\n * @param uids - The uids.\n * @param into - Filled with each one found, by uid.\n */\nfunction collectComponents(entity: Entity, uids: ReadonlySet<string>, into: Map<string, Component>): void {\n for (const component of entity.components) {\n if (uids.has(component.uid) && !component.isDestroyed) {\n into.set(component.uid, component);\n }\n }\n for (const child of entity.children) {\n collectComponents(child, uids, into);\n }\n}\n","/**\n * Defaults that a script's hot reload changes (engine ask E25): which fields of which component\n * types took a new default, and the live world brought in line with the document for them. A field\n * a document component's record leaves out takes the new default; a field it sets keeps its value;\n * a prefab instance whose members hold such a field is rebuilt from its prefab, with its overrides\n * (`docs/architecture/17-editor-host.md` §6.1).\n */\n\nimport { encodeProps } from \"@ignifx/core\";\nimport { validateFields } from \"./document.js\";\nimport type { DocumentIndex, DocumentMirror } from \"./document.js\";\nimport type { App, Component, ComponentType, Entity, ReferenceEncoder } from \"@ignifx/core\";\n\n/** The fields whose default changed, by component type id. */\nexport type ChangedDefaults = ReadonlyMap<string, readonly string[]>;\n\n/** Each field's default as JSON text, by field name. */\ntype FieldDefaults = ReadonlyMap<string, string>;\n\n/** Defaults hold no reference to anything in a file. */\nconst NO_REFERENCES: ReferenceEncoder = {\n entityUid: (): null => null,\n componentUid: (): null => null,\n};\n\n/**\n * Reads a component type's field defaults as the file format writes them; `transient` fields,\n * which no file holds, are left out.\n *\n * @param app - The scene view's app.\n * @param type - The registered type.\n * @returns The defaults, or `null` for a type without a schema.\n */\nfunction defaultsOf(app: App, type: ComponentType): FieldDefaults | null {\n const schema = app.world.registry.describe(type).schema;\n if (schema === null) {\n return null;\n }\n const encoded = encodeProps(schema, {}, NO_REFERENCES);\n return new Map(Object.entries(encoded).map(([name, value]) => [name, JSON.stringify(value)]));\n}\n\n/** The field defaults of every registered type, as the host last saw them. */\nexport class DefaultsTracker {\n readonly #app: App;\n\n readonly #known = new Map<string, FieldDefaults | null>();\n\n /**\n * Reads the defaults of every type registered now.\n *\n * @param app - The scene view's app, started.\n */\n constructor(app: App) {\n this.#app = app;\n for (const [typeId, type] of app.world.registry.registrations()) {\n this.#known.set(typeId, defaultsOf(app, type));\n }\n }\n\n /**\n * Compares the defaults of reloaded types with the ones seen before, and keeps the new ones.\n *\n * @param typeIds - The type ids a hot reload replaced; any other id is ignored.\n * @returns The fields whose default changed or which are new, by type id. A type seen for the\n * first time has no change: no document component was built from it.\n */\n changed(typeIds: readonly string[]): ChangedDefaults {\n const changed = new Map<string, readonly string[]>();\n const registry = this.#app.world.registry;\n for (const typeId of typeIds) {\n const type = registry.get(typeId);\n if (type === null) {\n continue;\n }\n const next = defaultsOf(this.#app, type);\n const previous = this.#known.get(typeId);\n this.#known.set(typeId, next);\n if (previous === undefined || next === null) {\n continue;\n }\n const fields = [...next].filter(([name, value]) => previous?.get(name) !== value).map(([name]) => name);\n if (fields.length > 0) {\n changed.set(typeId, fields);\n }\n }\n return changed;\n }\n}\n\n/**\n * The type id of a live component.\n *\n * @param app - The scene view's app.\n * @param component - The component.\n * @returns Its registered type id, or `null`.\n */\nfunction typeIdOf(app: App, component: Component): string | null {\n return app.world.registry.describe(component.constructor).typeId;\n}\n\n/**\n * Gives every document component the new default of each changed field its record leaves out. A\n * component the mirror has no record of is left alone. A component whose setter or `onValidate`\n * throws is handed to `failed`, and the others still get their defaults.\n *\n * @param app - The scene view's app.\n * @param mirror - The open document.\n * @param index - Its index.\n * @param changed - The changed fields, by type id.\n * @param failed - Called with each component that threw, its type id, and what it threw.\n */\nexport function applyDefaults(\n app: App,\n mirror: DocumentMirror,\n index: DocumentIndex,\n changed: ChangedDefaults,\n failed: (component: Component, typeId: string, error: unknown) => void,\n): void {\n for (const [uid, component] of index.components) {\n const typeId = typeIdOf(app, component) ?? \"\";\n const fields = changed.get(typeId);\n const set = mirror.propsSetBy(uid);\n const schema = app.world.registry.describe(component.constructor).schema;\n if (fields === undefined || set === null || schema === null) {\n continue;\n }\n const assigned: string[] = [];\n try {\n for (const name of fields) {\n const field = Object.hasOwn(schema, name) ? schema[name] : undefined;\n if (field !== undefined && !set.has(name)) {\n Reflect.set(component, name, field.createDefault());\n assigned.push(name);\n }\n }\n validateFields(component, assigned);\n } catch (error) {\n failed(component, typeId, error);\n }\n }\n}\n\n/**\n * The document's instance roots whose members (not the document's own components) include a\n * component of a changed type, in document order. A component the index lists but the mirror has\n * no record of is a member too: one an `add` override gives the root of a one-root prefab, which\n * the serializer writes as the root's own. So every component under a root either takes its new\n * defaults from {@link applyDefaults} or is rebuilt.\n *\n * @param app - The scene view's app.\n * @param mirror - The open document.\n * @param index - Its index.\n * @param changed - The changed fields, by type id.\n * @returns The roots' uids.\n */\nexport function instancesHolding(\n app: App,\n mirror: DocumentMirror,\n index: DocumentIndex,\n changed: ChangedDefaults,\n): ReadonlySet<string> {\n const isMember = (component: Component): boolean =>\n !index.components.has(component.uid) || mirror.propsSetBy(component.uid) === null;\n const roots = new Set<string>();\n for (const record of index.file.entities) {\n const root = index.entities.get(record.uid);\n if (record.instance === undefined || root === undefined) {\n continue;\n }\n const pending: Entity[] = [root];\n for (let entity = pending.pop(); entity !== undefined; entity = pending.pop()) {\n const holds = entity.components.some(\n (component) => isMember(component) && changed.has(typeIdOf(app, component) ?? \"\"),\n );\n if (holds) {\n roots.add(record.uid);\n break;\n }\n pending.push(...entity.children);\n }\n }\n return roots;\n}\n","/**\n * The scene view's 3D editor camera: an ordinary script on an entity of the host's persistent\n * `editor` scene, beside a `Camera` whose priority outranks every camera of the document.\n */\n\nimport { clamp, degToRad, Script } from \"@ignifx/core\";\nimport type { ScriptCallbacks } from \"@ignifx/core\";\n\n/** What the camera asks the gizmo dispatcher before it takes a pointer gesture. */\nexport interface PointerClaims {\n /**\n * Reads the dispatcher's state for the current gesture.\n *\n * @returns Whether a handle is hovered or dragged, and whether a press is still being picked.\n */\n pointerState(): { readonly interacting: boolean; readonly dragging: boolean; readonly pickPending: boolean };\n}\n\n/** A sphere to fit in the view, in world space. */\nexport interface FrameTarget {\n /** Its centre. */\n readonly center: { readonly x: number; readonly y: number; readonly z: number };\n /** Its radius, in metres. */\n readonly radius: number;\n}\n\n/** A click on the view: where, and with which modifier keys. */\nexport interface ViewClick {\n /** The CSS pixel x, from the canvas's left edge. */\n readonly x: number;\n /** The CSS pixel y, from the canvas's top edge. */\n readonly y: number;\n /** Shift, Ctrl or Cmd was held: the click toggles rather than replaces. */\n readonly toggle: boolean;\n}\n\n/**\n * Captures a pointer on the canvas. The pointer may already be gone (released before the listener\n * ran, or an event no device produced), which `setPointerCapture` reports by throwing; the gesture\n * then simply runs uncaptured.\n *\n * @param canvas - The canvas, or `null`.\n * @param pointerId - The pointer.\n * @param capture - `true` to capture, `false` to release.\n */\nexport function setCapture(canvas: HTMLCanvasElement | null, pointerId: number, capture: boolean): void {\n if (canvas === null) {\n return;\n }\n try {\n if (capture) {\n canvas.setPointerCapture(pointerId);\n } else if (canvas.hasPointerCapture(pointerId)) {\n canvas.releasePointerCapture(pointerId);\n }\n } catch {\n // An inactive pointer cannot be captured; nothing else depends on the capture.\n }\n}\n\n/** The camera's vertical field of view, in degrees. */\nexport const EDITOR_CAMERA_FOV = 50;\n\n/** The steepest the camera looks up or down, in degrees. */\nconst MAX_PITCH = 89;\n\n/** How far a press may move, in CSS pixels, and still be a click. */\nconst CLICK_SLOP_PX = 4;\n\n/** The gesture the current pointer press drives. */\ntype Gesture = \"none\" | \"orbit\" | \"fly\" | \"pan\";\n\n/**\n * Orbits, flies and pans around a focus point on DOM pointer events, and frames what it is asked to.\n *\n * @remarks\n * Left drag orbits, middle drag pans, right drag looks around while W, A, S, D, Q and E fly (Shift\n * for speed), the wheel dollies, and a left click is reported to `onClick`. The camera listens in\n * the bubble phase, after Lite's gizmo dispatcher has seen the press in the capture phase, and it\n * yields to the gizmo by the three rules Lite documents for its own controls (S0.2 §4.2): no orbit\n * starts on a hovered handle, a move is held while the press is still being picked, and an orbit\n * stops once a gizmo drag begins.\n */\nexport class EditorCamera extends Script implements ScriptCallbacks {\n /** The type id; the host leaves it out of the schemas it reports. */\n static typeId = \"ignifx-editor/EditorCamera\";\n\n /** The scene view runs in edit mode, where only these scripts get callbacks. */\n static runInEditMode = true;\n\n /** The point the camera orbits and looks at. */\n focus = { x: 0, y: 1, z: 0 };\n\n /** The heading, in degrees; 0 looks along +Z. */\n yaw = 30;\n\n /** The tilt, in degrees; positive looks down. */\n pitch = 25;\n\n /** How far the eye is from the focus, in metres. */\n distance = 12;\n\n /** Whether the camera answers the view's input; the host clears it while the view is in 2D mode. */\n active = true;\n\n /** The gizmo dispatcher, once the view has one. */\n claims: PointerClaims | null = null;\n\n /** Receives each click on the view. */\n onClick: ((click: ViewClick) => void) | null = null;\n\n #canvas: HTMLCanvasElement | null = null;\n\n #gesture: Gesture = \"none\";\n\n #pointer = -1;\n\n #lastX = 0;\n\n #lastY = 0;\n\n #downX = 0;\n\n #downY = 0;\n\n #moved = false;\n\n #gizmoTookGesture = false;\n\n readonly #keys = new Set<string>();\n\n readonly #onPointerDown = (event: PointerEvent): void => {\n if (!this.active || this.#pointer !== -1) {\n return;\n }\n this.#downX = event.offsetX;\n this.#downY = event.offsetY;\n this.#lastX = event.clientX;\n this.#lastY = event.clientY;\n this.#moved = false;\n this.#gizmoTookGesture = false;\n if (event.button === 0) {\n this.#gizmoTookGesture = this.claims?.pointerState().interacting === true;\n this.#gesture = this.#gizmoTookGesture ? \"none\" : \"orbit\";\n } else if (event.button === 1) {\n this.#gesture = \"pan\";\n event.preventDefault();\n } else if (event.button === 2) {\n this.#gesture = \"fly\";\n } else {\n return;\n }\n this.#pointer = event.pointerId;\n setCapture(this.#canvas, event.pointerId, true);\n };\n\n readonly #onPointerMove = (event: PointerEvent): void => {\n if (event.pointerId !== this.#pointer) {\n return;\n }\n const dx = event.clientX - this.#lastX;\n const dy = event.clientY - this.#lastY;\n this.#lastX = event.clientX;\n this.#lastY = event.clientY;\n if (Math.hypot(event.offsetX - this.#downX, event.offsetY - this.#downY) > CLICK_SLOP_PX) {\n this.#moved = true;\n }\n if (this.#gesture === \"orbit\") {\n const state = this.claims?.pointerState();\n if (state?.dragging === true) {\n this.#gizmoTookGesture = true;\n this.#gesture = \"none\";\n return;\n }\n if (state?.pickPending !== true) {\n this.yaw += dx * 0.3;\n this.pitch = clamp(this.pitch + dy * 0.3, -MAX_PITCH, MAX_PITCH);\n }\n } else if (this.#gesture === \"fly\") {\n const eye = this.#eye();\n this.yaw += dx * 0.2;\n this.pitch = clamp(this.pitch + dy * 0.2, -MAX_PITCH, MAX_PITCH);\n const direction = this.#direction();\n this.focus = {\n x: eye.x + direction.x * this.distance,\n y: eye.y + direction.y * this.distance,\n z: eye.z + direction.z * this.distance,\n };\n } else if (this.#gesture === \"pan\") {\n const scale = (this.distance * 0.0016 * (this.#canvas?.clientHeight ?? 800)) / 800;\n const right = this.#right();\n const up = this.#up();\n this.focus = {\n x: this.focus.x + (-dx * right.x + dy * up.x) * scale,\n y: this.focus.y + (-dx * right.y + dy * up.y) * scale,\n z: this.focus.z + (-dx * right.z + dy * up.z) * scale,\n };\n }\n this.apply();\n };\n\n readonly #onPointerUp = (event: PointerEvent): void => {\n if (event.pointerId !== this.#pointer) {\n return;\n }\n setCapture(this.#canvas, event.pointerId, false);\n this.#pointer = -1;\n this.#gesture = \"none\";\n this.#keys.clear();\n if (\n event.button === 0 &&\n !this.#moved &&\n !this.#gizmoTookGesture &&\n this.claims?.pointerState().dragging !== true\n ) {\n this.onClick?.({\n x: event.offsetX,\n y: event.offsetY,\n toggle: event.shiftKey || event.ctrlKey || event.metaKey,\n });\n }\n };\n\n readonly #onWheel = (event: WheelEvent): void => {\n if (!this.active) {\n return;\n }\n event.preventDefault();\n this.distance = clamp(this.distance * Math.exp(event.deltaY * 0.0015), 0.2, 5000);\n this.apply();\n };\n\n readonly #onContextMenu = (event: Event): void => {\n event.preventDefault();\n };\n\n readonly #onKeyDown = (event: KeyboardEvent): void => {\n this.#keys.add(event.code);\n };\n\n readonly #onKeyUp = (event: KeyboardEvent): void => {\n this.#keys.delete(event.code);\n };\n\n /**\n * Starts listening to a canvas's pointer, wheel and key events.\n *\n * @param canvas - The scene view's canvas.\n */\n bind(canvas: HTMLCanvasElement): void {\n this.#canvas = canvas;\n canvas.addEventListener(\"pointerdown\", this.#onPointerDown);\n canvas.addEventListener(\"pointermove\", this.#onPointerMove);\n canvas.addEventListener(\"pointerup\", this.#onPointerUp);\n canvas.addEventListener(\"pointercancel\", this.#onPointerUp);\n canvas.addEventListener(\"wheel\", this.#onWheel, { passive: false });\n canvas.addEventListener(\"contextmenu\", this.#onContextMenu);\n canvas.ownerDocument.addEventListener(\"keydown\", this.#onKeyDown);\n canvas.ownerDocument.addEventListener(\"keyup\", this.#onKeyUp);\n }\n\n /** Stops listening. */\n onDestroy(): void {\n const canvas = this.#canvas;\n if (canvas === null) {\n return;\n }\n canvas.removeEventListener(\"pointerdown\", this.#onPointerDown);\n canvas.removeEventListener(\"pointermove\", this.#onPointerMove);\n canvas.removeEventListener(\"pointerup\", this.#onPointerUp);\n canvas.removeEventListener(\"pointercancel\", this.#onPointerUp);\n canvas.removeEventListener(\"wheel\", this.#onWheel);\n canvas.removeEventListener(\"contextmenu\", this.#onContextMenu);\n canvas.ownerDocument.removeEventListener(\"keydown\", this.#onKeyDown);\n canvas.ownerDocument.removeEventListener(\"keyup\", this.#onKeyUp);\n this.#canvas = null;\n }\n\n /**\n * Fits a sphere in the view: the focus moves to its centre and the distance fits its radius in\n * the field of view, with a margin.\n *\n * @param target - The sphere.\n */\n frame(target: FrameTarget): void {\n this.focus = { x: target.center.x, y: target.center.y, z: target.center.z };\n this.distance = Math.max(0.5, (Math.max(target.radius, 0.25) / Math.sin(degToRad(EDITOR_CAMERA_FOV / 2))) * 1.2);\n this.apply();\n }\n\n /**\n * Flies while the right button is held and a movement key is down.\n *\n * @param deltaTime - The frame's unscaled delta, in seconds.\n */\n update(deltaTime: number): void {\n if (!this.active || this.#gesture !== \"fly\" || this.#keys.size === 0) {\n return;\n }\n const speed = 5 * (this.#keys.has(\"ShiftLeft\") || this.#keys.has(\"ShiftRight\") ? 4 : 1) * deltaTime;\n const direction = this.#direction();\n const right = this.#right();\n const along = (this.#keys.has(\"KeyW\") ? speed : 0) - (this.#keys.has(\"KeyS\") ? speed : 0);\n const across = (this.#keys.has(\"KeyD\") ? speed : 0) - (this.#keys.has(\"KeyA\") ? speed : 0);\n const rise = (this.#keys.has(\"KeyE\") ? speed : 0) - (this.#keys.has(\"KeyQ\") ? speed : 0);\n this.focus = {\n x: this.focus.x + direction.x * along + right.x * across,\n y: this.focus.y + direction.y * along + right.y * across + rise,\n z: this.focus.z + direction.z * along + right.z * across,\n };\n this.apply();\n }\n\n /** Places the camera's entity at the eye, looking at the focus. */\n apply(): void {\n const eye = this.#eye();\n this.transform.localPosition.set(eye.x, eye.y, eye.z);\n this.transform.lookAt(this.focus);\n }\n\n /**\n * The unit view direction; yaw 0 looks along +Z, positive pitch looks down.\n *\n * @returns The direction.\n */\n #direction(): { x: number; y: number; z: number } {\n const yaw = degToRad(this.yaw);\n const pitch = degToRad(this.pitch);\n return { x: Math.cos(pitch) * Math.sin(yaw), y: -Math.sin(pitch), z: Math.cos(pitch) * Math.cos(yaw) };\n }\n\n /**\n * The view's right vector, level with the ground.\n *\n * @returns The vector.\n */\n #right(): { x: number; y: number; z: number } {\n const yaw = degToRad(this.yaw);\n return { x: Math.cos(yaw), y: 0, z: -Math.sin(yaw) };\n }\n\n /**\n * The view's up vector.\n *\n * @returns The vector.\n */\n #up(): { x: number; y: number; z: number } {\n const d = this.#direction();\n const r = this.#right();\n return { x: d.y * r.z - d.z * r.y, y: d.z * r.x - d.x * r.z, z: d.x * r.y - d.y * r.x };\n }\n\n /**\n * The eye position.\n *\n * @returns The point `distance` behind the focus along the view direction.\n */\n #eye(): { x: number; y: number; z: number } {\n const d = this.#direction();\n return {\n x: this.focus.x - d.x * this.distance,\n y: this.focus.y - d.y * this.distance,\n z: this.focus.z - d.z * this.distance,\n };\n }\n}\n","/**\n * The scene view's 2D side: the 2D editor camera's arithmetic, and the parts of `@ignifx/2d` the\n * host reads. The host does not import `@ignifx/2d` (it is not a dependency of this package): it\n * reaches `app.twoD` and the 2D component classes by their names, through the project's own copy,\n * the way `@ignifx/physics-2d` finds a `Tilemap` by its type id (`11-2d-toolkit.md` §2.5).\n */\n\nimport { Camera } from \"@ignifx/core\";\nimport { ViewMode } from \"../protocol/index.js\";\nimport type { App, Component, ComponentType, ConcreteComponentType, Entity, SceneInstance } from \"@ignifx/core\";\n\n/** The type id of `@ignifx/2d`'s `Camera2D`. */\nexport const CAMERA_2D_TYPE = \"ignifx/Camera2D\";\n\n/** The type id of `@ignifx/2d`'s `SpriteRenderer`. */\nexport const SPRITE_RENDERER_TYPE = \"ignifx/SpriteRenderer\";\n\n/** The type id of `@ignifx/2d`'s `Tilemap`. */\nexport const TILEMAP_TYPE = \"ignifx/Tilemap\";\n\n/** `@ignifx/2d`'s default pixels per unit, used when the project has no 2D toolkit. */\nexport const DEFAULT_PIXELS_PER_UNIT = 100;\n\n/**\n * The wheel's zoom steps, in screen pixels per layer pixel (`Camera2D.zoom`): with a pixels-per-unit\n * equal to the art's, a source pixel spans a whole number of screen pixels from 1 up (S0.2 §5).\n */\nexport const ZOOM_STEPS: readonly number[] = [0.125, 0.25, 0.5, 1, 2, 3, 4, 6, 8, 12, 16, 24, 32];\n\n/** The farthest out a frame may zoom. */\nconst MIN_ZOOM = 1 / 64;\n\n/** The farthest in a frame may zoom. */\nconst MAX_ZOOM = 64;\n\n/** How much room a frame leaves around what it fits, as a factor of its size. */\nconst FRAME_MARGIN = 1.2;\n\n/** The smallest extent a frame fits, in metres, so a point or a sliver does not zoom in forever. */\nconst MIN_FRAME_EXTENT = 0.5;\n\n/** An axis-aligned rectangle of the 2D world, in metres, +Y up. */\nexport interface Box2D {\n /** The left edge. */\n readonly minX: number;\n /** The bottom edge. */\n readonly minY: number;\n /** The right edge. */\n readonly maxX: number;\n /** The top edge. */\n readonly maxY: number;\n}\n\n/** What the 2D editor camera shows. */\nexport interface View2D {\n /** The world x at the view's centre, in metres. */\n readonly centerX: number;\n /** The world y at the view's centre, in metres. */\n readonly centerY: number;\n /** Screen pixels per layer pixel, as `Camera2D.zoom`. */\n readonly zoom: number;\n /** Layer pixels per metre. */\n readonly pixelsPerUnit: number;\n /** The view's backing-store width, in pixels. */\n readonly widthPx: number;\n /** The view's backing-store height, in pixels. */\n readonly heightPx: number;\n}\n\n/**\n * The next zoom step in or out from a zoom, which need not be a step itself.\n *\n * @param zoom - The current zoom.\n * @param direction - `1` to zoom in, `-1` to zoom out.\n * @returns The nearest step beyond `zoom` that way, or the last step when there is none.\n */\nexport function stepZoom(zoom: number, direction: 1 | -1): number {\n if (direction > 0) {\n return ZOOM_STEPS.find((step) => step > zoom * 1.0001) ?? ZOOM_STEPS.at(-1) ?? zoom;\n }\n return ZOOM_STEPS.findLast((step) => step < zoom * 0.9999) ?? ZOOM_STEPS[0] ?? zoom;\n}\n\n/**\n * The half-height a camera shows at a zoom: the inverse of `Camera2D`'s\n * `zoom = heightPx / (2 · size · PPU)`.\n *\n * @param zoom - Screen pixels per layer pixel.\n * @param heightPx - The view's backing-store height.\n * @param pixelsPerUnit - Layer pixels per metre.\n * @returns The half-height, in metres.\n */\nexport function orthographicSizeFor(zoom: number, heightPx: number, pixelsPerUnit: number): number {\n return heightPx / (2 * zoom * pixelsPerUnit);\n}\n\n/**\n * The zoom at which a camera shows a half-height: `Camera2D`'s own rule.\n *\n * @param orthographicSize - The half-height, in metres.\n * @param heightPx - The view's backing-store height.\n * @param pixelsPerUnit - Layer pixels per metre.\n * @returns The zoom.\n */\nexport function zoomForSize(orthographicSize: number, heightPx: number, pixelsPerUnit: number): number {\n return heightPx / (2 * orthographicSize * pixelsPerUnit);\n}\n\n/**\n * The world point under a backing-store pixel of the view.\n *\n * @param view - The view.\n * @param x - The pixel x, from the left edge.\n * @param y - The pixel y, from the top edge.\n * @returns The point, in metres, +Y up.\n */\nexport function screenToWorld2D(view: View2D, x: number, y: number): { readonly x: number; readonly y: number } {\n const scale = view.zoom * view.pixelsPerUnit;\n return {\n x: view.centerX + (x - view.widthPx / 2) / scale,\n y: view.centerY - (y - view.heightPx / 2) / scale,\n };\n}\n\n/**\n * Where the view's centre goes when it zooms about a pixel, so the world point under that pixel\n * stays under it.\n *\n * @param view - The view before the zoom.\n * @param x - The pixel x.\n * @param y - The pixel y.\n * @param zoom - The new zoom.\n * @returns The new centre.\n */\nexport function zoomAbout(\n view: View2D,\n x: number,\n y: number,\n zoom: number,\n): { readonly centerX: number; readonly centerY: number } {\n const anchor = screenToWorld2D(view, x, y);\n const scale = zoom * view.pixelsPerUnit;\n return {\n centerX: anchor.x - (x - view.widthPx / 2) / scale,\n centerY: anchor.y + (y - view.heightPx / 2) / scale,\n };\n}\n\n/**\n * The centre and zoom that fit a rectangle in the view, with a margin.\n *\n * @param box - The rectangle.\n * @param widthPx - The view's backing-store width.\n * @param heightPx - The view's backing-store height.\n * @param pixelsPerUnit - Layer pixels per metre.\n * @returns The centre and the zoom.\n */\nexport function fitView(\n box: Box2D,\n widthPx: number,\n heightPx: number,\n pixelsPerUnit: number,\n): { readonly centerX: number; readonly centerY: number; readonly zoom: number } {\n const width = Math.max(box.maxX - box.minX, MIN_FRAME_EXTENT) * FRAME_MARGIN * pixelsPerUnit;\n const height = Math.max(box.maxY - box.minY, MIN_FRAME_EXTENT) * FRAME_MARGIN * pixelsPerUnit;\n const zoom = Math.min(widthPx / width, heightPx / height);\n return {\n centerX: (box.minX + box.maxX) / 2,\n centerY: (box.minY + box.maxY) / 2,\n zoom: Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, Number.isFinite(zoom) && zoom > 0 ? zoom : 1)),\n };\n}\n\n/**\n * Grows a rectangle to take in another.\n *\n * @param box - The rectangle so far, or `null`.\n * @param other - The one to take in.\n * @returns Their union.\n */\nfunction union(box: Box2D | null, other: Box2D): Box2D {\n return box === null\n ? other\n : {\n minX: Math.min(box.minX, other.minX),\n minY: Math.min(box.minY, other.minY),\n maxX: Math.max(box.maxX, other.maxX),\n maxY: Math.max(box.maxY, other.maxY),\n };\n}\n\n// -------------------------------------------------------------------------------------------\n// `@ignifx/2d`, by data\n// -------------------------------------------------------------------------------------------\n\n/** What the host reads of a `TwoDPick`. */\nexport interface TwoDPickLike {\n /** The entity carrying the sprite hit. */\n readonly entity: Entity;\n}\n\n/** What the host passes to `app.twoD.pickAt`, as `@ignifx/2d`'s `TwoDPickOptions`. */\nexport interface TwoDPickOptionsLike {\n /** Restricts the pick to the sprites of the entities this accepts. */\n readonly filter?: (entity: Entity) => boolean;\n /** Whether sprites the game marks `pickable: false` count too. */\n readonly includeUnpickable?: boolean;\n}\n\n/** What the host uses of `app.twoD`, `@ignifx/2d`'s `TwoDService`. */\nexport interface TwoDServiceLike {\n /** `\"sprite\"`, where sprites are the whole frame, or `\"mixed\"`. */\n readonly mode: string;\n /** Layer pixels per metre. */\n readonly pixelsPerUnit: number;\n /**\n * Picks the topmost sprite under a backing-store pixel.\n *\n * @param xPx - The pixel x.\n * @param yPx - The pixel y.\n * @param options - Which sprites count.\n * @returns The hit, or `null`.\n */\n pickAt(xPx: number, yPx: number, options?: TwoDPickOptionsLike): TwoDPickLike | null;\n}\n\n/** What the host reads and writes of a `Camera2D`. */\nexport interface Camera2DLike extends Component {\n /** The half-height it shows, in metres. */\n orthographicSize: number;\n /** Highest enabled wins. */\n priority: number;\n /** Whether zoom and position snap to whole pixels. */\n pixelPerfect: boolean;\n}\n\n/** What the host reads of a `SpriteRenderer`. */\ninterface SpriteLike extends Component {\n /** The world rectangle of the unrotated quad, as the last frame's sync measured it. */\n readonly bounds: {\n readonly min: { readonly x: number; readonly y: number };\n readonly max: { readonly x: number; readonly y: number };\n };\n}\n\n/** What the host reads of a `Tilemap`. */\ninterface TilemapLike extends Component {\n /** Metres per cell; `0` before the map has loaded. */\n readonly cellSize: number;\n /** How many layers the map has. */\n readonly layerCount: number;\n /**\n * A layer's size, in cells.\n *\n * @param layer - The layer's index.\n * @returns The size.\n */\n layerSize(layer: number): { readonly x: number; readonly y: number };\n}\n\n/**\n * The app's 2D service, when the project registers `@ignifx/2d`.\n *\n * @param app - The app.\n * @returns `app.twoD`, or `null`.\n */\nexport function twoDServiceOf(app: App): TwoDServiceLike | null {\n const service: unknown = Reflect.get(app, \"twoD\");\n if (typeof service !== \"object\" || service === null) {\n return null;\n }\n const pickAt: unknown = Reflect.get(service, \"pickAt\");\n const mode: unknown = Reflect.get(service, \"mode\");\n const pixelsPerUnit: unknown = Reflect.get(service, \"pixelsPerUnit\");\n if (typeof pickAt !== \"function\" || typeof mode !== \"string\" || typeof pixelsPerUnit !== \"number\") {\n return null;\n }\n return {\n mode,\n pixelsPerUnit,\n pickAt: (xPx, yPx, options): TwoDPickLike | null => {\n const hit: unknown = Reflect.apply(pickAt, service, [xPx, yPx, options]);\n const entity: unknown = typeof hit === \"object\" && hit !== null ? Reflect.get(hit, \"entity\") : null;\n return isEntity(entity) ? { entity } : null;\n },\n };\n}\n\n/**\n * Tells whether a value is an entity of some world.\n *\n * @param value - The value.\n * @returns True for an object with a uid, a scene and a transform.\n */\nfunction isEntity(value: unknown): value is Entity {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof Reflect.get(value, \"uid\") === \"string\" &&\n typeof Reflect.get(value, \"transform\") === \"object\"\n );\n}\n\n/**\n * Tells whether a component type can be constructed, which `addComponent` needs.\n *\n * @param type - The type.\n * @returns True for a class.\n */\nfunction isConcrete(type: ComponentType): type is ConcreteComponentType {\n return typeof type === \"function\";\n}\n\n/**\n * A registered component class, by type id.\n *\n * @param app - The app.\n * @param typeId - The type id.\n * @returns The class, or `null` when the project does not register it.\n */\nexport function componentTypeOf(app: App, typeId: string): ConcreteComponentType | null {\n const type = app.world.registry.get(typeId);\n return type !== null && isConcrete(type) ? type : null;\n}\n\n/**\n * Tells whether a component is a `Camera2D`.\n *\n * @param component - The component.\n * @returns True when it has the fields the host drives.\n */\nexport function isCamera2DLike(component: Component | null): component is Camera2DLike {\n return (\n component !== null &&\n typeof Reflect.get(component, \"orthographicSize\") === \"number\" &&\n typeof Reflect.get(component, \"priority\") === \"number\" &&\n typeof Reflect.get(component, \"pixelPerfect\") === \"boolean\"\n );\n}\n\n/**\n * Tells whether a component is a `SpriteRenderer`.\n *\n * @param component - The component.\n * @returns True when it reports world bounds.\n */\nfunction isSpriteLike(component: Component): component is SpriteLike {\n const bounds: unknown = Reflect.get(component, \"bounds\");\n return typeof bounds === \"object\" && bounds !== null && \"min\" in bounds && \"max\" in bounds;\n}\n\n/**\n * Tells whether a component is a `Tilemap`.\n *\n * @param component - The component.\n * @returns True when it reports its cell size and layer sizes.\n */\nfunction isTilemapLike(component: Component): component is TilemapLike {\n return (\n typeof Reflect.get(component, \"cellSize\") === \"number\" &&\n typeof Reflect.get(component, \"layerCount\") === \"number\" &&\n typeof Reflect.get(component, \"layerSize\") === \"function\"\n );\n}\n\n/**\n * The 2D world rectangle entities cover: each sprite's quad and each tilemap's extent under them,\n * plus every entity's position, so an entity with nothing drawn, or a sprite not yet synced, still\n * counts.\n *\n * @param app - The app whose registry names the 2D classes.\n * @param entities - The entities.\n * @returns The rectangle, or `null` for none.\n */\nexport function boundsOf2D(app: App, entities: readonly Entity[]): Box2D | null {\n const sprite = componentTypeOf(app, SPRITE_RENDERER_TYPE);\n const tilemap = componentTypeOf(app, TILEMAP_TYPE);\n let box: Box2D | null = null;\n for (const entity of entities) {\n const position = entity.transform.position;\n box = union(box, { minX: position.x, minY: position.y, maxX: position.x, maxY: position.y });\n for (const component of sprite === null ? [] : entity.getComponentsInChildren(sprite, true)) {\n if (isSpriteLike(component)) {\n const { min, max } = component.bounds;\n // An unsynced sprite reports an empty box at the origin; its position already counts.\n if (max.x > min.x && max.y > min.y) {\n box = union(box, { minX: min.x, minY: min.y, maxX: max.x, maxY: max.y });\n }\n }\n }\n for (const component of tilemap === null ? [] : entity.getComponentsInChildren(tilemap, true)) {\n const extent = isTilemapLike(component) ? tilemapBox(component) : null;\n if (extent !== null) {\n box = union(box, extent);\n }\n }\n }\n return box;\n}\n\n/**\n * A tilemap's world rectangle: from its entity's origin, its widest and tallest layer in cells.\n *\n * @param map - The tilemap.\n * @returns The rectangle, or `null` before the map has loaded.\n */\nfunction tilemapBox(map: TilemapLike): Box2D | null {\n let columns = 0;\n let rows = 0;\n for (let layer = 0; layer < map.layerCount; layer += 1) {\n const size = map.layerSize(layer);\n columns = Math.max(columns, size.x);\n rows = Math.max(rows, size.y);\n }\n if (map.cellSize <= 0 || columns === 0 || rows === 0) {\n return null;\n }\n const origin = map.entity.transform.position;\n return {\n minX: origin.x,\n minY: origin.y,\n maxX: origin.x + columns * map.cellSize,\n maxY: origin.y + rows * map.cellSize,\n };\n}\n\n/**\n * The highest-priority enabled `Camera2D` of a scene instance: the camera the level is played through.\n *\n * @param app - The app.\n * @param scene - The document's scene instance.\n * @returns The camera, or `null`.\n */\nexport function levelCamera2D(app: App, scene: SceneInstance | null): Camera2DLike | null {\n const type = componentTypeOf(app, CAMERA_2D_TYPE);\n if (type === null || scene === null) {\n return null;\n }\n let best: Camera2DLike | null = null;\n for (const camera of app.world.components(type)) {\n if (isCamera2DLike(camera) && camera.entity.scene === scene && camera.isEnabledInHierarchy) {\n if (best === null || camera.priority > best.priority) {\n best = camera;\n }\n }\n }\n return best;\n}\n\n/**\n * The editor camera a scene is made for: 2D when the project draws sprites only\n * (`twoD.mode: \"sprite\"`, which skips the 3D pass), or when the scene's cameras are all `Camera2D`\n * and it has at least one; 3D otherwise, and always without `@ignifx/2d`.\n *\n * @param app - The app, after the scene opened (a scene file can override `twoD.mode`).\n * @param scene - The document's scene instance.\n * @returns The mode.\n */\nexport function sceneViewMode(app: App, scene: SceneInstance | null): ViewMode {\n const twoD = twoDServiceOf(app);\n if (twoD === null) {\n return ViewMode.threeD;\n }\n if (twoD.mode === \"sprite\") {\n return ViewMode.twoD;\n }\n const camera2D = componentTypeOf(app, CAMERA_2D_TYPE);\n const inScene = (component: Component): boolean => component.entity.scene === scene;\n const has2D = camera2D !== null && app.world.components(camera2D).some(inScene);\n const has3D = app.world.components(Camera).some(inScene);\n return has2D && !has3D ? ViewMode.twoD : ViewMode.threeD;\n}\n","/**\n * The scene view's 2D editor camera (S0.2 §5): a script on the editor camera's entity that, while\n * the view is in 2D mode, drives an editor-owned `Camera2D` that outranks the level's, and turns\n * the 3D editor camera into a matching orthographic camera looking down +Z at the 2D plane, so\n * the gizmo overlay and the 3D picker see what the sprites show. The level's own `Camera2D` is\n * never touched.\n */\n\nimport { Script } from \"@ignifx/core\";\nimport { setCapture } from \"./editor-camera.js\";\nimport {\n DEFAULT_PIXELS_PER_UNIT,\n fitView,\n orthographicSizeFor,\n screenToWorld2D,\n stepZoom,\n zoomAbout,\n} from \"./view-2d.js\";\nimport type { PointerClaims, ViewClick } from \"./editor-camera.js\";\nimport type { Box2D, Camera2DLike, View2D } from \"./view-2d.js\";\nimport type { Camera, ScriptCallbacks } from \"@ignifx/core\";\n\n/** How far in front of the 2D plane the orthographic eye sits, in metres (it looks along +Z). */\nexport const EYE_DISTANCE_2D = 500;\n\n/** How far a press may move, in CSS pixels, and still be a click. */\nconst CLICK_SLOP_PX = 4;\n\n/** How much wheel travel, in pixels, makes one zoom step; a mouse notch is about 100. */\nconst WHEEL_STEP_PX = 50;\n\n/** The gesture the current pointer press drives. */\ntype Gesture2D = \"none\" | \"click\" | \"pan\";\n\n/**\n * Pans and zooms the 2D view on DOM pointer events, and frames what it is asked to.\n *\n * @remarks\n * Middle drag, right drag, and left drag with Space held pan; the wheel zooms in pixel steps about\n * the cursor; a left click is reported to `onClick`. A press on a gizmo handle is left to the\n * gizmo, by the same rule as the 3D camera (S0.2 §4.2). It does nothing until\n * {@link EditorCamera2D.activate}.\n */\nexport class EditorCamera2D extends Script implements ScriptCallbacks {\n /** The type id; the host leaves it out of the schemas it reports. */\n static typeId = \"ignifx-editor/EditorCamera2D\";\n\n /** The scene view runs in edit mode, where only these scripts get callbacks. */\n static runInEditMode = true;\n\n /** The world x at the view's centre, in metres. */\n centerX = 0;\n\n /** The world y at the view's centre, in metres. */\n centerY = 0;\n\n /** Screen pixels per layer pixel, as `Camera2D.zoom`. */\n zoom = 1;\n\n /**\n * Reads the layer pixels per metre: the project's `twoD.pixelsPerUnit`.\n *\n * @returns The pixels per unit.\n */\n pixelsPerUnit: () => number = () => DEFAULT_PIXELS_PER_UNIT;\n\n /** The gizmo dispatcher, once the view has one. */\n claims: PointerClaims | null = null;\n\n /** Receives each click on the view. */\n onClick: ((click: ViewClick) => void) | null = null;\n\n #active = false;\n\n #eye: Camera | null = null;\n\n #camera2D: Camera2DLike | null = null;\n\n #canvas: HTMLCanvasElement | null = null;\n\n #gesture: Gesture2D = \"none\";\n\n #pointer = -1;\n\n #lastX = 0;\n\n #lastY = 0;\n\n #downX = 0;\n\n #downY = 0;\n\n #moved = false;\n\n #space = false;\n\n #wheel = 0;\n\n /** Whether the entity holds the 2D pose since the last {@link EditorCamera2D.activate}. */\n #posed = false;\n\n readonly #onPointerDown = (event: PointerEvent): void => {\n if (!this.#active || this.#pointer !== -1) {\n return;\n }\n this.#downX = event.offsetX;\n this.#downY = event.offsetY;\n this.#lastX = event.clientX;\n this.#lastY = event.clientY;\n this.#moved = false;\n if (event.button === 0) {\n this.#gesture = this.#space ? \"pan\" : this.claims?.pointerState().interacting === true ? \"none\" : \"click\";\n } else if (event.button === 1 || event.button === 2) {\n this.#gesture = \"pan\";\n event.preventDefault();\n } else {\n return;\n }\n this.#pointer = event.pointerId;\n setCapture(this.#canvas, event.pointerId, true);\n };\n\n readonly #onPointerMove = (event: PointerEvent): void => {\n if (event.pointerId !== this.#pointer) {\n return;\n }\n const dx = event.clientX - this.#lastX;\n const dy = event.clientY - this.#lastY;\n this.#lastX = event.clientX;\n this.#lastY = event.clientY;\n if (Math.hypot(event.offsetX - this.#downX, event.offsetY - this.#downY) > CLICK_SLOP_PX) {\n this.#moved = true;\n }\n if (this.#gesture === \"pan\") {\n const metresPerCssPixel = this.#backingRatio() / (this.zoom * this.pixelsPerUnit());\n this.centerX -= dx * metresPerCssPixel;\n this.centerY += dy * metresPerCssPixel;\n this.apply();\n }\n };\n\n readonly #onPointerUp = (event: PointerEvent): void => {\n if (event.pointerId !== this.#pointer) {\n return;\n }\n setCapture(this.#canvas, event.pointerId, false);\n this.#pointer = -1;\n const gesture = this.#gesture;\n this.#gesture = \"none\";\n if (event.button === 0 && gesture === \"click\" && !this.#moved && this.claims?.pointerState().dragging !== true) {\n this.onClick?.({\n x: event.offsetX,\n y: event.offsetY,\n toggle: event.shiftKey || event.ctrlKey || event.metaKey,\n });\n }\n };\n\n readonly #onWheel = (event: WheelEvent): void => {\n if (!this.#active) {\n return;\n }\n event.preventDefault();\n this.#wheel += event.deltaY;\n if (Math.abs(this.#wheel) < WHEEL_STEP_PX) {\n return;\n }\n const direction = this.#wheel < 0 ? 1 : -1;\n this.#wheel = 0;\n const ratio = this.#backingRatio();\n this.zoomTo(stepZoom(this.zoom, direction), event.offsetX * ratio, event.offsetY * ratio);\n };\n\n readonly #onKeyDown = (event: KeyboardEvent): void => {\n if (event.code === \"Space\") {\n this.#space = true;\n }\n };\n\n readonly #onKeyUp = (event: KeyboardEvent): void => {\n if (event.code === \"Space\") {\n this.#space = false;\n }\n };\n\n /**\n * Gives the camera the components it drives: the 3D editor camera, and the editor's own\n * `Camera2D` when the project has `@ignifx/2d`.\n *\n * @param eye - The 3D editor camera, on this script's entity.\n * @param camera2D - The editor's `Camera2D`, on this script's entity, or `null`.\n */\n attach(eye: Camera, camera2D: Camera2DLike | null): void {\n this.#eye = eye;\n this.#camera2D = camera2D;\n }\n\n /**\n * Whether the view is in 2D mode.\n *\n * @returns True between {@link EditorCamera2D.activate} and {@link EditorCamera2D.deactivate}.\n */\n get active(): boolean {\n return this.#active;\n }\n\n /** Enters 2D mode: enables the editor's `Camera2D` and makes the 3D editor camera orthographic. */\n activate(): void {\n this.#active = true;\n // The 3D camera left the entity turned; the next apply writes the pose whatever it is.\n this.#posed = false;\n if (this.#camera2D !== null) {\n this.#camera2D.enabled = true;\n }\n if (this.#eye !== null) {\n this.#eye.projection = \"orthographic\";\n }\n this.apply();\n }\n\n /** Leaves 2D mode: the level's cameras draw the sprites again, and the 3D camera is perspective. */\n deactivate(): void {\n this.#active = false;\n this.#pointer = -1;\n this.#gesture = \"none\";\n if (this.#camera2D !== null) {\n this.#camera2D.enabled = false;\n }\n if (this.#eye !== null) {\n this.#eye.projection = \"perspective\";\n }\n }\n\n /**\n * Starts listening to a canvas's pointer, wheel and Space key events.\n *\n * @param canvas - The scene view's canvas.\n */\n bind(canvas: HTMLCanvasElement): void {\n this.#canvas = canvas;\n canvas.addEventListener(\"pointerdown\", this.#onPointerDown);\n canvas.addEventListener(\"pointermove\", this.#onPointerMove);\n canvas.addEventListener(\"pointerup\", this.#onPointerUp);\n canvas.addEventListener(\"pointercancel\", this.#onPointerUp);\n canvas.addEventListener(\"wheel\", this.#onWheel, { passive: false });\n canvas.ownerDocument.addEventListener(\"keydown\", this.#onKeyDown);\n canvas.ownerDocument.addEventListener(\"keyup\", this.#onKeyUp);\n }\n\n /** Stops listening. */\n onDestroy(): void {\n const canvas = this.#canvas;\n if (canvas === null) {\n return;\n }\n canvas.removeEventListener(\"pointerdown\", this.#onPointerDown);\n canvas.removeEventListener(\"pointermove\", this.#onPointerMove);\n canvas.removeEventListener(\"pointerup\", this.#onPointerUp);\n canvas.removeEventListener(\"pointercancel\", this.#onPointerUp);\n canvas.removeEventListener(\"wheel\", this.#onWheel);\n canvas.ownerDocument.removeEventListener(\"keydown\", this.#onKeyDown);\n canvas.ownerDocument.removeEventListener(\"keyup\", this.#onKeyUp);\n this.#canvas = null;\n }\n\n /**\n * What the view shows now.\n *\n * @returns The centre, zoom, pixels per unit and backing-store size.\n */\n view(): View2D {\n return {\n centerX: this.centerX,\n centerY: this.centerY,\n zoom: this.zoom,\n pixelsPerUnit: this.pixelsPerUnit(),\n widthPx: Math.max(1, this.#canvas?.width ?? 1),\n heightPx: Math.max(1, this.#canvas?.height ?? 1),\n };\n }\n\n /**\n * The world point under a backing-store pixel.\n *\n * @param x - The pixel x.\n * @param y - The pixel y.\n * @returns The point, in metres, +Y up.\n */\n screenToWorld(x: number, y: number): { readonly x: number; readonly y: number } {\n return screenToWorld2D(this.view(), x, y);\n }\n\n /**\n * Shows a world rectangle: centred, at the zoom that fits it with a margin.\n *\n * @param box - The rectangle, in metres.\n */\n frame(box: Box2D): void {\n const view = this.view();\n const fit = fitView(box, view.widthPx, view.heightPx, view.pixelsPerUnit);\n this.centerX = fit.centerX;\n this.centerY = fit.centerY;\n this.zoom = fit.zoom;\n this.apply();\n }\n\n /**\n * Changes the zoom about a backing-store pixel, keeping the world point under it in place.\n *\n * @param zoom - The new zoom.\n * @param x - The pixel x.\n * @param y - The pixel y.\n */\n zoomTo(zoom: number, x: number, y: number): void {\n const centre = zoomAbout(this.view(), x, y, zoom);\n this.centerX = centre.centerX;\n this.centerY = centre.centerY;\n this.zoom = zoom;\n this.apply();\n }\n\n /** Keeps the shown size in step with the canvas, which can be resized at any time. */\n update(): void {\n if (this.#active) {\n this.apply();\n }\n }\n\n /**\n * Writes the view onto the entity and the two cameras: the entity sits on the view's centre,\n * {@link EYE_DISTANCE_2D} in front of the plane, looking along +Z with +Y up, so its x and y are\n * the `Camera2D`'s centre and its orthographic half-height is the `Camera2D`'s.\n */\n apply(): void {\n if (!this.#active) {\n return;\n }\n const view = this.view();\n const size = orthographicSizeFor(view.zoom, view.heightPx, view.pixelsPerUnit);\n const position = this.transform.localPosition;\n // Called every frame; an unchanged pose is not rewritten, so the transform stays clean.\n if (!this.#posed || position.x !== this.centerX || position.y !== this.centerY) {\n position.set(this.centerX, this.centerY, -EYE_DISTANCE_2D);\n this.transform.lookAt({ x: this.centerX, y: this.centerY, z: 0 });\n this.#posed = true;\n }\n if (this.#eye !== null && this.#eye.orthographicSize !== size) {\n this.#eye.orthographicSize = size;\n }\n if (this.#camera2D !== null && this.#camera2D.orthographicSize !== size) {\n this.#camera2D.orthographicSize = size;\n }\n }\n\n /**\n * The canvas's backing pixels per CSS pixel.\n *\n * @returns `canvas.width / canvas.clientWidth`, or 1 without a laid-out canvas.\n */\n #backingRatio(): number {\n const canvas = this.#canvas;\n return canvas === null || canvas.clientWidth <= 0 ? 1 : canvas.width / canvas.clientWidth;\n }\n}\n","/**\n * The arithmetic of the scene view's methods that needs no GPU: the `pick` unit rule, the ray and\n * plane point a `pick` answers with, the `screenshot` size rule, the transform the drag\n * notifications carry, and gizmo snapping. Each is a pure function, so the headless tests check it\n * directly.\n */\n\nimport { canonicalizeNumber } from \"@ignifx/core\";\nimport { PickUnit, SCREENSHOT_MAX_SIZE } from \"../protocol/index.js\";\nimport type { GizmoSnap, PickParams, PickRay, ScreenshotParams, SceneFileTransform, Vec3 } from \"../protocol/index.js\";\nimport type { Entity, MutableQuat, MutableVec3, Ray } from \"@ignifx/core\";\n\n/** An image or frame size, in pixels. */\nexport interface PixelSize {\n /** The width. */\n readonly width: number;\n /** The height. */\n readonly height: number;\n}\n\n/** The sizes of the view's canvas that the unit rule needs. */\nexport interface ViewSurface {\n /** The backing-store width, `canvas.width`. */\n readonly width: number;\n /** The backing-store height, `canvas.height`. */\n readonly height: number;\n /** The CSS width, `canvas.clientWidth`. */\n readonly clientWidth: number;\n /** The CSS height, `canvas.clientHeight`. */\n readonly clientHeight: number;\n}\n\n/**\n * Reads a render surface's sizes. An `OffscreenCanvas` has no CSS size, so its CSS pixels are its\n * backing pixels.\n *\n * @param surface - The canvas.\n * @returns The sizes.\n */\nexport function viewSurfaceOf(surface: HTMLCanvasElement | OffscreenCanvas): ViewSurface {\n const clientWidth: unknown = Reflect.get(surface, \"clientWidth\");\n const clientHeight: unknown = Reflect.get(surface, \"clientHeight\");\n return {\n width: surface.width,\n height: surface.height,\n clientWidth: typeof clientWidth === \"number\" && clientWidth > 0 ? clientWidth : surface.width,\n clientHeight: typeof clientHeight === \"number\" && clientHeight > 0 ? clientHeight : surface.height,\n };\n}\n\n/**\n * Converts a `pick` point to the backing-store pixels `app.renderer.pickAsync` takes (protocol 0.3,\n * \"The pick unit rule\"; engine ask E3). This is the host's one conversion: the renderer converts\n * on to the CSS pixels Lite's picker wants.\n *\n * @param params - The point and its unit.\n * @param surface - The canvas's sizes.\n * @returns The point in backing-store pixels, or `null` when it is outside the canvas (a miss).\n */\nexport function toBackingPixels(\n params: PickParams,\n surface: ViewSurface,\n): { readonly x: number; readonly y: number } | null {\n const x = params.unit === PickUnit.backing ? params.x : (params.x * surface.width) / surface.clientWidth;\n const y = params.unit === PickUnit.backing ? params.y : (params.y * surface.height) / surface.clientHeight;\n if (x < 0 || y < 0 || x >= surface.width || y >= surface.height) {\n return null;\n }\n return { x, y };\n}\n\n/** The members a `pick` answer gains from the camera ray. */\nexport interface PickRayMembers {\n /** The ray, rounded to the file format's precision. */\n readonly ray: PickRay;\n /** Where the ray meets `z = 0`, or absent when it runs parallel to the plane or meets it behind its origin. */\n readonly plane?: Vec3;\n}\n\n/**\n * Turns a camera ray into a `pick` answer's `ray` and `plane` members (protocol 0.3, additive): the\n * ray as it is, and the point where it meets the 2D world plane `z = 0`. The plane point is\n * computed before rounding, and its `z` is exactly `0`.\n *\n * @param ray - The world-space ray, from `Camera.screenToRay`, with a unit direction.\n * @returns The members, every number rounded with `canonicalizeNumber`.\n */\nexport function pickRayMembers(ray: Ray): PickRayMembers {\n const c = canonicalizeNumber;\n const { origin, direction } = ray;\n const members: PickRayMembers = {\n ray: {\n origin: [c(origin.x), c(origin.y), c(origin.z)],\n direction: [c(direction.x), c(direction.y), c(direction.z)],\n },\n };\n // A ray parallel to the plane never meets it; one whose `t` is negative meets it behind the camera.\n const t = direction.z === 0 ? Number.NaN : -origin.z / direction.z;\n if (!Number.isFinite(t) || t < 0) {\n return members;\n }\n return { ...members, plane: [c(origin.x + direction.x * t), c(origin.y + direction.y * t), 0] };\n}\n\n/**\n * Rounds an image side and keeps it from 1 to {@link SCREENSHOT_MAX_SIZE}.\n *\n * @param side - The side, in pixels.\n * @returns The whole side in range.\n */\nfunction clampSide(side: number): number {\n return Math.min(SCREENSHOT_MAX_SIZE, Math.max(1, Math.round(side)));\n}\n\n/**\n * The size of a `screenshot`: the request's, or the view's backing size scaled down, keeping its\n * aspect, to fit {@link SCREENSHOT_MAX_SIZE}; with one side given the other follows the aspect.\n *\n * @param params - The request; its sizes are already checked to be 1 to 2048.\n * @param view - The captured frame's size.\n * @returns The image size, each side at least 1 and at most 2048.\n */\nexport function screenshotSize(params: ScreenshotParams, view: PixelSize): PixelSize {\n const aspect = view.height > 0 ? view.width / view.height : 1;\n const { width, height } = params;\n if (width !== undefined && height !== undefined) {\n return { width, height };\n }\n if (width !== undefined) {\n return { width, height: clampSide(width / aspect) };\n }\n if (height !== undefined) {\n return { width: clampSide(height * aspect), height };\n }\n const fit = Math.min(1, SCREENSHOT_MAX_SIZE / Math.max(view.width, view.height, 1));\n return { width: clampSide(view.width * fit), height: clampSide(view.height * fit) };\n}\n\n/**\n * Reads an entity's local transform as the scene file writes it, numbers canonicalized.\n *\n * @param entity - The entity.\n * @returns The transform.\n */\nexport function readLocalTransform(entity: Entity): SceneFileTransform {\n const { localPosition: p, localRotation: r, localScale: s } = entity.transform;\n const c = canonicalizeNumber;\n return {\n position: [c(p.x), c(p.y), c(p.z)],\n rotation: [c(r.x), c(r.y), c(r.z), c(r.w)],\n scale: [c(s.x), c(s.y), c(s.z)],\n };\n}\n\n/**\n * Rounds a value to a step; a step of 0 leaves it alone.\n *\n * @param value - The value.\n * @param step - The step.\n * @returns The snapped value.\n */\nfunction snapTo(value: number, step: number): number {\n return step > 0 ? Math.round(value / step) * step : value;\n}\n\n/** A vector or quaternion's channels, as a snapping state holds them. */\ntype Channels = number[];\n\n/**\n * Snaps a gizmo drag after Lite has applied each move (S0.2 §3.4, post-correction). The raw, unsnapped\n * value is kept apart from the node, so the snapped steps do not accumulate rounding.\n */\nexport class DragSnapper {\n readonly #mode: \"translate\" | \"rotate\" | \"scale\";\n\n readonly #snap: GizmoSnap;\n\n readonly #start: Channels;\n\n #raw: Channels;\n\n #written: Channels;\n\n /**\n * Starts snapping one drag.\n *\n * @param mode - The drag's mode.\n * @param snap - The snapping steps.\n * @param entity - The dragged entity, at drag start.\n */\n constructor(mode: \"translate\" | \"rotate\" | \"scale\", snap: GizmoSnap, entity: Entity) {\n this.#mode = mode;\n this.#snap = snap;\n this.#start = this.#read(entity);\n this.#raw = [...this.#start];\n this.#written = [...this.#start];\n }\n\n /**\n * Folds the move Lite just wrote into the raw value and writes the snapped value back.\n *\n * @param entity - The dragged entity.\n */\n apply(entity: Entity): void {\n const now = this.#read(entity);\n if (this.#mode === \"rotate\") {\n this.#applyRotation(entity, now);\n return;\n }\n const step = this.#mode === \"translate\" ? this.#snap.translate : this.#snap.scale;\n if (step <= 0) {\n return;\n }\n this.#raw = this.#raw.map((value, index) => value + (now[index] ?? 0) - (this.#written[index] ?? 0));\n const snapped = this.#raw.map(\n (value, index) => (this.#start[index] ?? 0) + snapTo(value - (this.#start[index] ?? 0), step),\n );\n const target: MutableVec3 =\n this.#mode === \"translate\" ? entity.transform.localPosition : entity.transform.localScale;\n target.set(snapped[0] ?? 0, snapped[1] ?? 0, snapped[2] ?? 0);\n this.#written = snapped;\n }\n\n /**\n * Snaps a rotation drag: a ring turns about one axis, so the turn since drag start is one angle,\n * which is rounded to the step.\n *\n * @param entity - The dragged entity.\n * @param now - Its rotation now, as Lite wrote it.\n */\n #applyRotation(entity: Entity, now: Channels): void {\n const step = this.#snap.rotate;\n if (step <= 0) {\n return;\n }\n // raw = (now · written⁻¹) · raw, then the turn since start = raw · start⁻¹.\n this.#raw = multiply(multiply(now, conjugate(this.#written)), this.#raw);\n const turn = multiply(this.#raw, conjugate(this.#start));\n const sine = Math.hypot(turn[0] ?? 0, turn[1] ?? 0, turn[2] ?? 0);\n if (sine < 1e-9) {\n return;\n }\n const angle = 2 * Math.atan2(sine, turn[3] ?? 1);\n const snapped = (snapTo((angle * 180) / Math.PI, step) * Math.PI) / 180;\n const half = snapped / 2;\n const scale = Math.sin(half) / sine;\n const snappedTurn = [(turn[0] ?? 0) * scale, (turn[1] ?? 0) * scale, (turn[2] ?? 0) * scale, Math.cos(half)];\n const result = multiply(snappedTurn, this.#start);\n const rotation: MutableQuat = entity.transform.localRotation;\n rotation.set(result[0] ?? 0, result[1] ?? 0, result[2] ?? 0, result[3] ?? 1);\n this.#written = result;\n }\n\n /**\n * Reads the channels this drag moves.\n *\n * @param entity - The entity.\n * @returns Position, scale, or the rotation quaternion.\n */\n #read(entity: Entity): Channels {\n const t = entity.transform;\n if (this.#mode === \"rotate\") {\n return [t.localRotation.x, t.localRotation.y, t.localRotation.z, t.localRotation.w];\n }\n const v = this.#mode === \"translate\" ? t.localPosition : t.localScale;\n return [v.x, v.y, v.z];\n }\n}\n\n/**\n * Multiplies two quaternions, `a · b`.\n *\n * @param a - The left operand, `[x, y, z, w]`.\n * @param b - The right operand.\n * @returns The product.\n */\nfunction multiply(a: Channels, b: Channels): Channels {\n const [ax = 0, ay = 0, az = 0, aw = 1] = a;\n const [bx = 0, by = 0, bz = 0, bw = 1] = b;\n return [\n aw * bx + ax * bw + ay * bz - az * by,\n aw * by - ax * bz + ay * bw + az * bx,\n aw * bz + ax * by - ay * bx + az * bw,\n aw * bw - ax * bx - ay * by - az * bz,\n ];\n}\n\n/**\n * A unit quaternion's inverse.\n *\n * @param q - The quaternion.\n * @returns Its conjugate.\n */\nfunction conjugate(q: Channels): Channels {\n return [-(q[0] ?? 0), -(q[1] ?? 0), -(q[2] ?? 0), q[3] ?? 1];\n}\n","/**\n * Turns one gizmo drag into the scene view's drag notifications. It needs no GPU: the view calls\n * it with each part of the gesture, and the headless tests call it directly.\n */\n\nimport { SceneNotification, TRANSFORM_DRAGGING_INTERVAL_MS } from \"../protocol/index.js\";\nimport { DragSnapper, readLocalTransform } from \"./view-math.js\";\nimport type {\n GizmoDragMode,\n GizmoSnap,\n SceneFileTransform,\n TransformDraggedParams,\n TransformDraggingParams,\n} from \"../protocol/index.js\";\nimport type { Entity } from \"@ignifx/core\";\n\n/** One gizmo drag in progress. */\ninterface DragState {\n /** The dragged entity. */\n readonly entity: Entity;\n /** The drag's mode. */\n readonly mode: GizmoDragMode;\n /** The local transform at drag start. */\n readonly before: SceneFileTransform;\n /** The snapping, or `null`. */\n readonly snapper: DragSnapper | null;\n /** When the last `transformDragging` went out, in milliseconds. */\n lastSentMs: number;\n}\n\n/**\n * Sends `transformDragging` and `transformDragged` for gizmo drags, one drag at a time.\n *\n * @remarks\n * Every drag opens with a `transformDragging` and closes with a `transformDragged`, even one that\n * ends where it started, so the editor can hold its undo from pointer-down to pointer-up.\n */\nexport class GizmoDragRelay {\n readonly #notify: (method: string, params: TransformDraggingParams | TransformDraggedParams) => void;\n\n readonly #now: () => number;\n\n #drag: DragState | null = null;\n\n /**\n * Makes a relay.\n *\n * @param notify - Sends one notification to the editor.\n * @param now - The clock, in milliseconds; `performance.now` by default.\n */\n constructor(\n notify: (method: string, params: TransformDraggingParams | TransformDraggedParams) => void,\n now: () => number = () => performance.now(),\n ) {\n this.#notify = notify;\n this.#now = now;\n }\n\n /**\n * Starts a drag and sends its first `transformDragging`, the transform at drag start. A drag in\n * progress is dropped without a `transformDragged`.\n *\n * @param entity - The dragged entity.\n * @param mode - The drag's mode.\n * @param snap - The snapping steps, or `null`.\n */\n start(entity: Entity, mode: GizmoDragMode, snap: GizmoSnap | null): void {\n const before = readLocalTransform(entity);\n this.#drag = {\n entity,\n mode,\n before,\n snapper: snap === null ? null : new DragSnapper(mode, snap, entity),\n lastSentMs: this.#now(),\n };\n this.#notify(SceneNotification.transformDragging, { entity: entity.uid, mode, after: before });\n }\n\n /** Snaps the move the gizmo just made and sends `transformDragging`, at most every 50 ms. */\n move(): void {\n const state = this.#drag;\n if (state === null) {\n return;\n }\n state.snapper?.apply(state.entity);\n const now = this.#now();\n if (now - state.lastSentMs >= TRANSFORM_DRAGGING_INTERVAL_MS) {\n state.lastSentMs = now;\n this.#notify(SceneNotification.transformDragging, {\n entity: state.entity.uid,\n mode: state.mode,\n after: readLocalTransform(state.entity),\n });\n }\n }\n\n /** Ends the drag and sends `transformDragged`, whether or not the transform changed. */\n end(): void {\n const state = this.#drag;\n if (state === null) {\n return;\n }\n this.#drag = null;\n this.#notify(SceneNotification.transformDragged, {\n entity: state.entity.uid,\n mode: state.mode,\n before: state.before,\n after: readLocalTransform(state.entity),\n });\n }\n\n /** Forgets a drag that has no entity, so its moves and end send nothing. */\n clear(): void {\n this.#drag = null;\n }\n}\n","/**\n * JSON helpers the scene ops and the walk for held references share: narrowing JSON, and telling\n * which entities and components a value names.\n */\n\nimport type { JsonObject, JsonValue } from \"@ignifx/core\";\n\n/**\n * The uid of a referenced entity or component.\n *\n * @param target - The field's value.\n * @returns Its uid, or `null` for anything without one.\n */\nexport function uidOf(target: unknown): string | null {\n const uid: unknown = typeof target === \"object\" && target !== null ? Reflect.get(target, \"uid\") : null;\n return typeof uid === \"string\" ? uid : null;\n}\n\n/**\n * Narrows JSON to an object. `Array.isArray` does not remove a readonly array from the union, so the\n * discrimination lives here once.\n *\n * @param value - The JSON.\n * @returns The object, or `null` for anything else.\n */\nexport function asJsonObject(value: JsonValue | undefined): JsonObject | null {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return null;\n }\n // The guard above leaves exactly `JsonObject` of the `JsonValue` union.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return value as JsonObject;\n}\n\n/**\n * Narrows JSON to an array.\n *\n * @param value - The JSON.\n * @returns The array, or `null`.\n */\nexport function asJsonArray(value: JsonValue | undefined): readonly JsonValue[] | null {\n return Array.isArray(value) ? value : null;\n}\n\n/**\n * Tells whether JSON references an entity or component of a set.\n *\n * @param value - The JSON.\n * @param entities - The entity uids.\n * @param components - The component uids.\n * @returns True when a `$entity` or `$component` names one of them.\n */\nexport function pointsInto(\n value: JsonValue | undefined,\n entities: ReadonlySet<string>,\n components: ReadonlySet<string>,\n): boolean {\n const array = asJsonArray(value);\n if (array !== null) {\n return array.some((item) => pointsInto(item, entities, components));\n }\n const object = asJsonObject(value);\n if (object === null) {\n return false;\n }\n const entity = object[\"$entity\"];\n const component = object[\"$component\"];\n return (\n (typeof entity === \"string\" && entities.has(entity)) ||\n (typeof component === \"string\" && components.has(component)) ||\n Object.values(object).some((item) => pointsInto(item, entities, components))\n );\n}\n","/**\n * What instance members outside a subtree that is about to be rebuilt hold in it: the reference\n * fields another instance's overrides aimed at the subtree, read from the live world before the\n * subtree is destroyed, so the rebuild can point them at the new objects.\n */\n\nimport { encodeValue } from \"@ignifx/core\";\nimport { pointsInto, uidOf } from \"./json.js\";\nimport type { DocumentIndex, DocumentMirror } from \"./document.js\";\nimport type { App, Component, Entity, FieldDefinition, JsonObject, JsonValue } from \"@ignifx/core\";\n\n/** What {@link heldByMembers} read from the live world before a subtree was destroyed. */\nexport interface HeldReferences {\n /** Each member component with a field that points into the subtree, and those fields as JSON. */\n readonly fields: ReadonlyMap<Component, JsonObject>;\n /** The entities those fields held, by uid. */\n readonly entities: ReadonlyMap<string, unknown>;\n /** The components those fields held, by uid. */\n readonly components: ReadonlyMap<string, unknown>;\n}\n\n/**\n * The reference fields of instance members outside a subtree that point into it, read from the live\n * world as JSON: what another instance's overrides aimed at the subtree's document entities, or at\n * the components its `add` overrides give. A member is not in the document, so only its live\n * component knows the field; a document component and an added one are read from the document. Only\n * the instances whose override lists point into the subtree are read.\n *\n * @param app - The scene view's app.\n * @param mirror - The open document.\n * @param index - The document, read before the subtree is destroyed.\n * @param subtree - The subtree's root.\n * @param entities - The subtree's document entity uids.\n * @param components - The uids of its document components and the components its overrides add.\n * @returns The fields, and the objects they held.\n */\nexport function heldByMembers(\n app: App,\n mirror: DocumentMirror,\n index: DocumentIndex,\n subtree: Entity,\n entities: ReadonlySet<string>,\n components: ReadonlySet<string>,\n): HeldReferences {\n const fields = new Map<Component, JsonObject>();\n const heldEntities = new Map<string, unknown>();\n const heldComponents = new Map<string, unknown>();\n const registry = app.world.registry;\n const visit = (entity: Entity): void => {\n if (entity === subtree) {\n return;\n }\n for (const component of entity.components) {\n const uid = component.uid;\n if (index.components.get(uid) === component || index.added.get(uid) === component) {\n continue;\n }\n const props: Record<string, JsonValue> = {};\n for (const [name, field] of Object.entries(registry.describe(component.constructor).schema ?? {})) {\n if (!holdsReferences(field)) {\n continue;\n }\n const targets: [Map<string, unknown>, string, unknown][] = [];\n const json = encodeValue(field, Reflect.get(component, name), {\n entityUid: (value) => remember(targets, heldEntities, value),\n componentUid: (value) => remember(targets, heldComponents, value),\n });\n if (pointsInto(json, entities, components)) {\n props[name] = json;\n for (const [into, target, value] of targets) {\n into.set(target, value);\n }\n }\n }\n if (Object.keys(props).length > 0) {\n fields.set(component, props);\n }\n }\n for (const child of entity.children) {\n visit(child);\n }\n };\n for (const record of index.file.entities) {\n const root = index.entities.get(record.uid);\n const aims = (mirror.overridesOf(record.uid) ?? []).some(\n (override) => (override.op ?? \"replace\") === \"replace\" && pointsInto(override.value, entities, components),\n );\n if (root !== undefined && !entities.has(record.uid) && aims) {\n visit(root);\n }\n }\n return { fields, entities: heldEntities, components: heldComponents };\n}\n\n/**\n * Notes a referenced object by its uid, to keep if its field turns out to point into a subtree.\n *\n * @param targets - The field's notes.\n * @param into - Where the note goes if it is kept.\n * @param value - The referenced object.\n * @returns Its uid, or `null` for anything without one.\n */\nfunction remember(\n targets: [Map<string, unknown>, string, unknown][],\n into: Map<string, unknown>,\n value: unknown,\n): string | null {\n const uid = uidOf(value);\n if (uid !== null) {\n targets.push([into, uid, value]);\n }\n return uid;\n}\n\n/**\n * Tells whether a field's value can hold an entity or component reference.\n *\n * @param field - The field.\n * @returns True for a reference, or a list, record, map or optional of one.\n */\nfunction holdsReferences(field: FieldDefinition<unknown>): boolean {\n const spec = field.spec;\n if (spec.kind === \"entityRef\" || spec.kind === \"componentRef\") {\n return true;\n }\n if (spec.kind === \"array\") {\n return holdsReferences(spec.item);\n }\n if (spec.kind === \"record\") {\n return Object.values(spec.fields).some((inner) => holdsReferences(inner));\n }\n if (spec.kind === \"map\") {\n return holdsReferences(spec.value);\n }\n return spec.kind === \"optional\" && holdsReferences(spec.inner);\n}\n","/**\n * `applyOps`: the thirteen scene ops of protocol 0.3, applied to the open document's live world.\n *\n * Each op changes the world the way the editor's `applyOp` changes the document, so that a mirror\n * that started exact stays exact: `readBack` then returns the document's own records. An op that\n * the world disagrees with fails with one of editor-core's codes; the host does not roll back,\n * because the editor reopens the scene after any failure.\n */\n\nimport {\n addComponentFromRecord,\n createSceneAsset,\n decodeValue,\n encodeValue,\n instantiateScene,\n isIgnifxError,\n loadSceneDependencies,\n parseOverridePath,\n SCENE_FILE_FORMAT,\n SCENE_FORMAT_VERSION,\n validateSceneFile,\n} from \"@ignifx/core\";\nimport { ApplyOpFailureCode } from \"../protocol/index.js\";\nimport {\n assignProps,\n copyJson,\n propIssues,\n UNSAVED_SCENE_ADDRESS,\n validateFields,\n withOverrideList,\n} from \"./document.js\";\nimport { heldByMembers } from \"./held-references.js\";\nimport { asJsonArray, asJsonObject, pointsInto, uidOf } from \"./json.js\";\nimport type { DocumentIndex, DocumentMirror } from \"./document.js\";\nimport type {\n AddComponentOp,\n ApplyOpFailure,\n ApplyOpsParams,\n ApplyOpsResult,\n CreateEntityOp,\n InstantiateOp,\n JsonPath,\n RemoveOverrideOp,\n ReparentOp,\n SceneIssue,\n SceneOp,\n SetEntityFieldOp,\n SetOverrideOp,\n SetPropOp,\n SetSceneSettingOp,\n SetTransformOp,\n} from \"../protocol/index.js\";\nimport type {\n App,\n Component,\n Entity,\n FieldDefinition,\n JsonObject,\n JsonValue,\n ReferenceDecoder,\n ReferenceEncoder,\n SceneFile,\n SceneFileComponent,\n SceneFileEntity,\n SceneFileInstance,\n SceneFileOverride,\n} from \"@ignifx/core\";\n\n/** Why one op failed, as `applyOps` reports it. */\nexport class OpFailure extends Error {\n /** The failure code. */\n readonly code: ApplyOpFailureCode;\n\n /** The engine's diagnostic code, when there is one. */\n readonly diagnostic: string | null;\n\n /**\n * Creates the failure.\n *\n * @param code - The failure code.\n * @param message - An actionable sentence.\n * @param diagnostic - The engine's `IGX-` code, if any.\n */\n constructor(code: ApplyOpFailureCode, message: string, diagnostic: string | null = null) {\n super(message);\n this.name = \"OpFailure\";\n this.code = code;\n this.diagnostic = diagnostic;\n }\n}\n\n/** What applying ops needs: the app and the open document. */\ninterface OpContext {\n /** The scene view's app. */\n readonly app: App;\n /** The open document. */\n readonly mirror: DocumentMirror;\n /** Gets the build problems {@link reportBuildIssues} logs, for `applyOps`' result; absent outside it. */\n readonly warnings?: SceneIssue[];\n}\n\n/**\n * Applies one command's ops in order, never stopping at a failure.\n *\n * @param app - The scene view's app.\n * @param mirror - The open document.\n * @param params - The ops and the command they belong to.\n * @returns How many applied, the failures in order, and the build problems the ops met, in order.\n */\nexport async function applyOps(app: App, mirror: DocumentMirror, params: ApplyOpsParams): Promise<ApplyOpsResult> {\n const warnings: SceneIssue[] = [];\n const context: OpContext = { app, mirror, warnings };\n const failures: ApplyOpFailure[] = [];\n let applied = 0;\n for (const [index, op] of params.ops.entries()) {\n try {\n // Ops apply in order, each against the world the previous one left.\n // oxlint-disable-next-line no-await-in-loop -- see above\n await applyOp(context, op);\n applied += 1;\n } catch (error) {\n const failure = toFailure(index, error);\n failures.push(failure);\n app.log.warn(\n `applyOps ${params.commandId} (${params.commandName}): op ${String(index)} (${op.op}) failed: ${failure.code}: ${failure.message}`,\n );\n } finally {\n mirror.invalidate();\n }\n }\n return { applied, failures, warnings };\n}\n\n/**\n * Turns whatever an op threw into its failure record.\n *\n * @param index - The op's index.\n * @param error - What it threw.\n * @returns The failure.\n */\nfunction toFailure(index: number, error: unknown): ApplyOpFailure {\n if (error instanceof OpFailure) {\n return {\n index,\n code: error.code,\n message: error.message,\n ...(error.diagnostic === null ? {} : { diagnostic: error.diagnostic }),\n };\n }\n const message = error instanceof Error ? error.message : String(error);\n return {\n index,\n code: ApplyOpFailureCode.engineError,\n message,\n ...(isIgnifxError(error) ? { diagnostic: error.code } : {}),\n };\n}\n\n/**\n * Applies one op.\n *\n * @param context - The app and the document.\n * @param op - The op.\n */\nasync function applyOp(context: OpContext, op: SceneOp): Promise<void> {\n switch (op.op) {\n case \"createEntity\": {\n await createEntity(context, op);\n return;\n }\n case \"destroyEntity\": {\n requireEntity(context, op.entity).destroyImmediate();\n return;\n }\n case \"reparent\": {\n reparent(context, op);\n return;\n }\n case \"reorder\": {\n const entity = requireEntity(context, op.entity);\n placeAmongSiblings(context, entity, op.index);\n return;\n }\n case \"setEntityField\": {\n setEntityField(context, op);\n return;\n }\n case \"setTransform\": {\n setTransform(requireEntity(context, op.entity), op);\n return;\n }\n case \"addComponent\": {\n await addComponent(context, op);\n return;\n }\n case \"removeComponent\": {\n const component = requireComponent(context, op.component);\n component.entity.removeComponent(component);\n return;\n }\n case \"setProp\": {\n await setProp(context, op);\n return;\n }\n case \"setSceneSetting\": {\n setSceneSetting(context, op);\n return;\n }\n case \"instantiate\": {\n await instantiate(context, op);\n return;\n }\n case \"setOverride\": {\n await setOverride(context, op);\n return;\n }\n case \"removeOverride\": {\n await removeOverride(context, op);\n return;\n }\n default: {\n throw new OpFailure(ApplyOpFailureCode.invalidOp, \"Not an op of the scene op vocabulary.\");\n }\n }\n}\n\n// ---------------------------------------------------------------------------------------------\n// Lookups\n// ---------------------------------------------------------------------------------------------\n\n/**\n * The document's index; the scene methods only call `applyOps` with a document open.\n *\n * @param context - The app and the document.\n * @returns The index.\n */\nfunction indexOf(context: OpContext): DocumentIndex {\n const index = context.mirror.index();\n if (index === null) {\n throw new OpFailure(ApplyOpFailureCode.unknownEntity, \"No scene is open.\");\n }\n return index;\n}\n\n/**\n * A document entity by uid.\n *\n * @param context - The app and the document.\n * @param uid - The uid.\n * @returns The entity.\n */\nfunction requireEntity(context: OpContext, uid: string): Entity {\n const entity = indexOf(context).entities.get(uid);\n if (entity === undefined || entity.isDestroyed) {\n throw new OpFailure(ApplyOpFailureCode.unknownEntity, `No entity ${uid} is in the open scene.`);\n }\n return entity;\n}\n\n/**\n * A document component by uid.\n *\n * @param context - The app and the document.\n * @param uid - The uid.\n * @returns The component.\n */\nfunction requireComponent(context: OpContext, uid: string): Component {\n const component = indexOf(context).components.get(uid);\n if (component === undefined || component.isDestroyed) {\n throw new OpFailure(ApplyOpFailureCode.unknownComponent, `No component ${uid} is in the open scene.`);\n }\n return component;\n}\n\n/**\n * A parent named by an op: a document entity, or `null` for the scene's roots.\n *\n * @param context - The app and the document.\n * @param uid - The parent's uid, or `null`.\n * @returns The parent entity, or `null`.\n */\nfunction requireParent(context: OpContext, uid: string | null): Entity | null {\n if (uid === null) {\n return null;\n }\n const parent = indexOf(context).entities.get(uid);\n if (parent === undefined || parent.isDestroyed) {\n throw new OpFailure(ApplyOpFailureCode.invalidParent, `The parent ${uid} is not in the open scene.`);\n }\n return parent;\n}\n\n/**\n * The document entities among a parent's children, or among the scene's roots.\n *\n * @param context - The app and the document.\n * @param parent - The parent, or `null` for the roots.\n * @param except - An entity to leave out, the one being moved.\n * @returns The document siblings, in order.\n */\nfunction documentSiblings(context: OpContext, parent: Entity | null, except: Entity | null): Entity[] {\n const index = indexOf(context);\n const siblings = parent === null ? (context.mirror.scene?.roots ?? []) : parent.children;\n return siblings.filter((sibling) => sibling !== except && index.entities.get(sibling.uid) === sibling);\n}\n\n/**\n * Checks an insertion index against the document siblings it positions among.\n *\n * @param index - The index, or `undefined` for the end.\n * @param count - How many document siblings there are, the moved entity left out.\n * @returns The index to use.\n */\nfunction checkIndex(index: number | undefined, count: number): number {\n if (index === undefined) {\n return count;\n }\n if (index > count) {\n throw new OpFailure(\n ApplyOpFailureCode.invalidIndex,\n `Index ${String(index)} is past the end of a list of ${String(count)}.`,\n );\n }\n return index;\n}\n\n/**\n * Moves an entity to an index among its document siblings. Members of an instanced scene under the\n * same parent keep their places; the document does not list them.\n *\n * @param context - The app and the document.\n * @param entity - The entity, already under its final parent.\n * @param index - Its index among the document siblings, or `undefined` for the end.\n */\nfunction placeAmongSiblings(context: OpContext, entity: Entity, index: number | undefined): void {\n const others = documentSiblings(context, entity.parent, entity);\n const at = checkIndex(index, others.length);\n const all = (entity.parent === null ? (context.mirror.scene?.roots ?? []) : entity.parent.children).filter(\n (sibling) => sibling !== entity,\n );\n const before = others[at];\n const last = others.at(-1);\n const target = before === undefined ? (last === undefined ? all.length : all.indexOf(last) + 1) : all.indexOf(before);\n entity.setSiblingIndex(target);\n}\n\n// ---------------------------------------------------------------------------------------------\n// Structure\n// ---------------------------------------------------------------------------------------------\n\n/**\n * Checks that every component type a set of records names is registered, before anything is built.\n *\n * @param context - The app and the document.\n * @param components - The component records.\n */\nfunction requireTypes(context: OpContext, components: readonly SceneFileComponent[]): void {\n for (const component of components) {\n if (context.app.world.registry.get(component.type) === null) {\n throw new OpFailure(\n ApplyOpFailureCode.engineError,\n `The component type \"${component.type}\" is not registered; register it with app.registerComponents or check its typeId.`,\n \"IGX-0307\",\n );\n }\n }\n}\n\n/**\n * Checks that new entity and component uids are free in the world and in the document.\n *\n * @param context - The app and the document.\n * @param records - The new entity records.\n */\nfunction requireFreeUids(context: OpContext, records: readonly SceneFileEntity[]): void {\n const index = indexOf(context);\n const seen = new Set<string>();\n const claim = (uid: string, taken: boolean): void => {\n if (taken || seen.has(uid)) {\n throw new OpFailure(ApplyOpFailureCode.duplicateUid, `The uid ${uid} is already in use.`);\n }\n seen.add(uid);\n };\n for (const record of records) {\n claim(record.uid, context.app.world.getEntity(record.uid) !== null);\n for (const component of record.components ?? []) {\n claim(component.uid, index.components.has(component.uid));\n }\n }\n}\n\n/**\n * Checks that new entity records form a scene file `validateSceneFile` accepts, before anything is\n * built: the protocol guard checks their shapes, and this adds the file's rules over them, among\n * them that no instance entry holds two overrides with one identity, which `setOverride` and\n * `removeOverride` could then reach only one of.\n *\n * @param records - The new entity records, parents first.\n */\nfunction requireValidRecords(records: readonly SceneFileEntity[]): void {\n const file: SceneFile = {\n format: SCENE_FILE_FORMAT,\n formatVersion: SCENE_FORMAT_VERSION,\n name: \"\",\n entities: records,\n };\n const issue = validateSceneFile(file)[0];\n if (issue !== undefined) {\n throw new OpFailure(ApplyOpFailureCode.invalidValue, `${issue.path}: ${issue.message}`, \"IGX-0608\");\n }\n}\n\n/**\n * Builds a subtree from entity records under a live parent, with the records' uids, loading the\n * assets they reference first. A reference to a uid the subtree does not declare resolves against\n * the rest of the document, as it would in the whole file: one a document component holds, and one\n * an instance's overrides hold (an added component's, or a member's overridden field). The build's\n * problems are logged as warnings ({@link reportBuildIssues}).\n *\n * @param context - The app and the document.\n * @param records - The subtree's records, parents first; the first is its root.\n * @param parent - The live parent, or `null` for a root of the scene.\n * @param index - The root's index among its document siblings, or `undefined` for the end.\n * @returns The subtree's root.\n */\nasync function buildSubtree(\n context: OpContext,\n records: readonly SceneFileEntity[],\n parent: Entity | null,\n index: number | undefined,\n): Promise<Entity> {\n const [top, ...rest] = records;\n const scene = context.mirror.scene;\n if (top === undefined || scene === null) {\n throw new OpFailure(ApplyOpFailureCode.invalidOp, \"There is nothing to build.\");\n }\n const file: SceneFile = {\n format: SCENE_FILE_FORMAT,\n formatVersion: SCENE_FORMAT_VERSION,\n name: top.name,\n entities: [{ ...top, parent: null }, ...rest],\n };\n const dependencies = await loadSceneDependencies(context.app.assets, file);\n context.mirror.retain(dependencies);\n // Named by the document, so its diagnostics read as a reopen's.\n const asset = await createSceneAsset(documentAddress(context), file, dependencies);\n // The document as it stands without the subtree: an op's new uids are free in it, and a rebuild\n // destroyed the old subtree first.\n const outsideReferences = context.mirror.decoder();\n const built = instantiateScene(context.app.world, asset, {\n scene,\n outsideReferences,\n ...(parent === null ? {} : { parent }),\n });\n context.mirror.invalidate();\n reportBuildIssues(context, built.issues);\n const root = built.roots[0] ?? built.remap.entity(top.uid);\n if (root === null) {\n throw new OpFailure(ApplyOpFailureCode.engineError, `The engine built no entity for ${top.uid}.`);\n }\n placeAmongSiblings(context, root, index);\n return root;\n}\n\n/**\n * The open document's address, which names the subtrees ops build.\n *\n * @param context - The app and the document.\n * @returns Where the document is saved, or `memory:scene/unsaved`.\n */\nfunction documentAddress(context: OpContext): string {\n return context.mirror.address ?? UNSAVED_SCENE_ADDRESS;\n}\n\n/**\n * Writes a subtree build's recoverable problems to the app log, one warning each, the way\n * `world.loadSceneFile` writes a scene's (so a reopen of the document writes the same lines); the\n * host relays them to the editor as `log`. A stale override met while an instance is rebuilt is one.\n * Inside `applyOps` each also goes to the command's `warnings`, as `openScene` reports a build's.\n *\n * @param context - The app and the document.\n * @param issues - The problems, in the order found.\n */\nfunction reportBuildIssues(context: OpContext, issues: readonly SceneIssue[]): void {\n const address = documentAddress(context);\n for (const issue of issues) {\n context.app.log.warn(`${issue.code}: ${address}: ${issue.message}`);\n context.warnings?.push({ code: issue.code, message: issue.message });\n }\n}\n\n/**\n * Applies `createEntity`: the entity and its descendants, with their uids and components.\n *\n * @param context - The app and the document.\n * @param op - The op.\n */\nasync function createEntity(context: OpContext, op: CreateEntityOp): Promise<void> {\n const records = [op.entity, ...(op.descendants ?? [])];\n const parent = requireParent(context, op.entity.parent);\n checkIndex(op.index, documentSiblings(context, parent, null).length);\n requireFreeUids(context, records);\n requireValidRecords(records);\n const inside = new Set([op.entity.uid]);\n for (const record of op.descendants ?? []) {\n if (record.parent === null || !inside.has(record.parent)) {\n throw new OpFailure(\n ApplyOpFailureCode.invalidParent,\n `${record.uid} must be the child of an entity created before it in the same op.`,\n );\n }\n inside.add(record.uid);\n }\n const components = records.flatMap((record) => record.components ?? []);\n requireTypes(context, components);\n await buildSubtree(context, records, parent, op.index);\n context.mirror.recordComponents(components);\n context.mirror.recordInstances(records);\n}\n\n/**\n * Applies `reparent`: the new parent, keeping the local transform, at an index.\n *\n * @param context - The app and the document.\n * @param op - The op.\n */\nfunction reparent(context: OpContext, op: ReparentOp): void {\n const entity = requireEntity(context, op.entity);\n const parent = requireParent(context, op.parent);\n if (parent !== null && (parent === entity || parent.isDescendantOf(entity))) {\n throw new OpFailure(ApplyOpFailureCode.invalidParent, `${entity.name} cannot move under its own subtree.`);\n }\n checkIndex(op.index, documentSiblings(context, parent, entity).length);\n entity.setParent(parent, { worldPositionStays: false });\n placeAmongSiblings(context, entity, op.index);\n}\n\n/**\n * Applies `setEntityField`.\n *\n * @param context - The app and the document.\n * @param op - The op.\n */\nfunction setEntityField(context: OpContext, op: SetEntityFieldOp): void {\n const entity = requireEntity(context, op.entity);\n switch (op.field) {\n case \"name\": {\n entity.name = op.value;\n return;\n }\n case \"active\": {\n entity.active = op.value;\n return;\n }\n case \"static\": {\n entity.isStatic = op.value;\n return;\n }\n case \"layer\": {\n const layer = context.app.world.layers.indexOf(op.value);\n if (layer < 0) {\n throw new OpFailure(\n ApplyOpFailureCode.invalidValue,\n `\"${op.value}\" is not a layer of this project.`,\n \"IGX-0303\",\n );\n }\n entity.layer = layer;\n return;\n }\n case \"tags\": {\n entity.tags.clear();\n for (const tag of op.value) {\n entity.tags.add(tag);\n }\n return;\n }\n default: {\n throw new OpFailure(ApplyOpFailureCode.invalidOp, \"Not an entity field.\");\n }\n }\n}\n\n/**\n * Applies `setTransform`: the local position, rotation and scale. `before` is ignored.\n *\n * @param entity - The entity.\n * @param op - The op.\n */\nfunction setTransform(entity: Entity, op: SetTransformOp): void {\n const { position, rotation, scale } = op.after;\n const transform = entity.transform;\n transform.localPosition.set(position[0], position[1], position[2]);\n transform.localRotation.set(rotation[0], rotation[1], rotation[2], rotation[3]);\n transform.localScale.set(scale[0], scale[1], scale[2]);\n}\n\n/**\n * The number of components an entity lists in the document.\n *\n * @param context - The app and the document.\n * @param entity - The entity.\n * @returns The length of its record's `components`.\n */\nfunction documentComponentCount(context: OpContext, entity: Entity): number {\n return indexOf(context).records.get(entity.uid)?.components?.length ?? 0;\n}\n\n/**\n * Loads the assets a value references, and keeps them for the document.\n *\n * @param context - The app and the document.\n * @param props - The JSON that may name assets.\n */\nasync function loadAssets(context: OpContext, props: JsonValue | undefined): Promise<void> {\n if (props === undefined) {\n return;\n }\n // The scene loader's own walk, over a one-entity file that carries the value as props.\n const file: SceneFile = {\n format: SCENE_FILE_FORMAT,\n formatVersion: SCENE_FORMAT_VERSION,\n name: \"props\",\n entities: [\n {\n uid: \"props\",\n name: \"props\",\n parent: null,\n transform: { position: [0, 0, 0], rotation: [0, 0, 0, 1], scale: [1, 1, 1] },\n components: [{ uid: \"props\", type: \"props\", props: { value: props } }],\n },\n ],\n };\n context.mirror.retain(await loadSceneDependencies(context.app.assets, file));\n}\n\n/**\n * Applies `addComponent`: the registered type, with its uid, `enabled` and decoded props, at an index.\n *\n * @param context - The app and the document.\n * @param op - The op.\n */\nasync function addComponent(context: OpContext, op: AddComponentOp): Promise<void> {\n const entity = requireEntity(context, op.entity);\n if (indexOf(context).components.has(op.component.uid)) {\n throw new OpFailure(ApplyOpFailureCode.duplicateUid, `The uid ${op.component.uid} is already in use.`);\n }\n checkIndex(op.index, documentComponentCount(context, entity));\n requireTypes(context, [op.component]);\n await loadAssets(context, op.component.props);\n const { issues } = addComponentFromRecord(entity, op.component, {\n ...(op.index === undefined ? {} : { index: op.index }),\n references: context.mirror.decoder(),\n });\n context.mirror.recordComponents([op.component]);\n const first = issues[0];\n if (first !== undefined) {\n throw new OpFailure(ApplyOpFailureCode.invalidValue, first.message, first.code);\n }\n}\n\n/**\n * Applies `instantiate`: an instance root, built from its scene asset.\n *\n * @param context - The app and the document.\n * @param op - The op.\n */\nasync function instantiate(context: OpContext, op: InstantiateOp): Promise<void> {\n const parent = requireParent(context, op.parent);\n checkIndex(op.index, documentSiblings(context, parent, null).length);\n const record: SceneFileEntity = {\n uid: op.entity,\n name: op.name,\n parent: op.parent,\n transform: op.transform,\n instance: op.instance,\n };\n requireFreeUids(context, [record]);\n requireValidRecords([record]);\n await buildSubtree(context, [record], parent, op.index);\n context.mirror.recordInstances([record]);\n}\n\n// ---------------------------------------------------------------------------------------------\n// Props and settings\n// ---------------------------------------------------------------------------------------------\n\n/**\n * Reads a schema field's current value as JSON, references written as the uids they point at.\n *\n * @param field - The field.\n * @param value - The live value.\n * @returns The JSON.\n */\nfunction encodeLive(field: FieldDefinition<unknown>, value: unknown): JsonValue {\n const references: ReferenceEncoder = { entityUid: uidOf, componentUid: uidOf };\n return encodeValue(field, value, references);\n}\n\n/**\n * Returns JSON with the value at a path set, or removed, leaving the input unchanged.\n *\n * @param container - The JSON the path starts in.\n * @param path - The steps, at least one: object keys and array indices.\n * @param value - The new value, or `undefined` to remove the key or the array item.\n * @returns The new JSON.\n */\nfunction withValueAt(container: JsonValue, path: JsonPath, value: JsonValue | undefined): JsonValue {\n const [step, ...rest] = path;\n const array = asJsonArray(container);\n if (array !== null && typeof step === \"number\" && step <= array.length) {\n const copy = [...array];\n if (rest.length > 0) {\n const next = copy[step];\n if (next === undefined) {\n throw invalidPath(path);\n }\n copy[step] = withValueAt(next, rest, value);\n } else if (value === undefined) {\n copy.splice(step, 1);\n } else {\n copy[step] = value;\n }\n return copy;\n }\n const object = asJsonObject(container);\n if (object !== null && typeof step === \"string\") {\n if (rest.length > 0) {\n // Own keys only: an inherited one, such as `__proto__`, is not in the document.\n const next = Object.hasOwn(object, step) ? object[step] : undefined;\n if (next === undefined) {\n throw invalidPath(path);\n }\n return { ...object, [step]: withValueAt(next, rest, value) };\n }\n const others = Object.entries(object).filter(([key]) => key !== step);\n return Object.fromEntries(value === undefined ? others : [...others, [step, value]]);\n }\n throw invalidPath(path);\n}\n\n/**\n * The failure for a path that does not resolve.\n *\n * @param path - The path.\n * @returns The failure.\n */\nfunction invalidPath(path: JsonPath): OpFailure {\n return new OpFailure(ApplyOpFailureCode.invalidPath, `The path ${JSON.stringify(path)} does not resolve.`);\n}\n\n/**\n * Applies `setProp`: the value at a path of a component's props, decoded with the field's schema\n * and assigned, the way the inspector writes a field.\n *\n * @param context - The app and the document.\n * @param op - The op.\n */\nasync function setProp(context: OpContext, op: SetPropOp): Promise<void> {\n const component = requireComponent(context, op.component);\n const schema = context.app.world.registry.describe(component.constructor).schema;\n if (schema === null) {\n throw new OpFailure(ApplyOpFailureCode.invalidPath, `${op.component} has no props.`);\n }\n await loadAssets(context, op.value);\n const references = context.mirror.decoder();\n const [name, ...rest] = op.path;\n if (name === undefined) {\n const props = op.value === undefined ? {} : asJsonObject(op.value);\n if (props === null) {\n throw new OpFailure(ApplyOpFailureCode.invalidValue, \"props must be an object.\");\n }\n rejectIssues(assignProps(component, props, references));\n context.mirror.recordProps(op.component, Object.keys(props));\n validateFields(component, Object.keys(schema));\n return;\n }\n const field = typeof name === \"string\" && Object.hasOwn(schema, name) ? schema[name] : undefined;\n if (typeof name !== \"string\" || field === undefined) {\n throw new OpFailure(ApplyOpFailureCode.invalidPath, `${String(name)} is not a field of ${op.component}.`);\n }\n if (rest.length === 0 && op.value === undefined) {\n Reflect.set(component, name, field.createDefault());\n context.mirror.recordProp(op.component, name, false);\n validateFields(component, [name]);\n return;\n }\n const json =\n rest.length > 0 ? withValueAt(encodeLive(field, Reflect.get(component, name)), rest, op.value) : op.value;\n const decoded = decodeValue(field, json ?? null, references);\n rejectIssues(\n decoded.issues.map((issue) => ({\n code: issue.code,\n message: `${op.component}.${name}${issue.path === \"\" ? \"\" : `.${issue.path}`}: ${issue.message}`,\n })),\n );\n Reflect.set(component, name, decoded.value);\n context.mirror.recordProp(op.component, name, true);\n validateFields(component, [name]);\n}\n\n/**\n * Fails the op on the first decoding problem: the value the field got is not the document's.\n *\n * @param issues - The problems.\n */\nfunction rejectIssues(issues: readonly { readonly code: string; readonly message: string }[]): void {\n const first = issues[0];\n if (first !== undefined) {\n throw new OpFailure(ApplyOpFailureCode.invalidValue, first.message, first.code);\n }\n}\n\n/**\n * Applies `setSceneSetting`: the value at a path of the scene's settings.\n *\n * @param context - The app and the document.\n * @param op - The op.\n */\nfunction setSceneSetting(context: OpContext, op: SetSceneSettingOp): void {\n const mirror = context.mirror;\n const next = op.path.length === 0 ? (op.value ?? null) : withValueAt(mirror.settings ?? {}, op.path, op.value);\n const settings = next === null ? null : asJsonObject(next);\n if (next !== null && settings === null) {\n throw new OpFailure(ApplyOpFailureCode.invalidValue, \"settings must be an object.\");\n }\n mirror.settings = settings === null ? null : copyJson(settings);\n}\n\n// ---------------------------------------------------------------------------------------------\n// Overrides\n// ---------------------------------------------------------------------------------------------\n\n/** The op of an override. */\ntype OverrideOp = \"replace\" | \"remove\" | \"add\";\n\n/**\n * The kind an override path parses to.\n *\n * @param path - The path.\n * @returns The kind, or `null` when the engine's grammar refuses it.\n */\nfunction overrideKind(path: string): string | null {\n try {\n return parseOverridePath(path).kind;\n } catch {\n return null;\n }\n}\n\n/**\n * The op an override path implies when none is given, as editor-core reads it.\n *\n * @param path - The path.\n * @returns `\"add\"` for a component list, `\"remove\"` for a whole component, else `\"replace\"`.\n */\nfunction impliedOp(path: string): OverrideOp {\n const kind = overrideKind(path);\n return kind === \"componentList\" ? \"add\" : kind === \"component\" ? \"remove\" : \"replace\";\n}\n\n/**\n * The uid of the component an `add` override adds.\n *\n * @param override - The override.\n * @returns The uid, or `null`.\n */\nfunction addedUid(override: SceneFileOverride): string | null {\n const uid = asJsonObject(override.value)?.[\"uid\"];\n return (override.op ?? \"replace\") === \"add\" && typeof uid === \"string\" ? uid : null;\n}\n\n/**\n * Finds an override by editor-core's identity: its path and op, and for a component `add` the\n * added uid.\n *\n * @param overrides - The list.\n * @param path - The path.\n * @param op - The op.\n * @param added - The added uid, for a component `add`.\n * @returns The index, or `-1`.\n */\nfunction findOverride(\n overrides: readonly SceneFileOverride[],\n path: string,\n op: OverrideOp,\n added: string | null,\n): number {\n return overrides.findIndex(\n (candidate) =>\n candidate.path === path &&\n (candidate.op ?? \"replace\") === op &&\n (overrideKind(path) !== \"componentList\" || addedUid(candidate) === added),\n );\n}\n\n/**\n * Rebuilds an instance root's subtree with an edited override list: the live world has no way to\n * re-apply one override, so the root and its document children are serialized, destroyed and built\n * again from the instanced scene with the new list. References from the rest of the document into\n * the rebuilt subtree, the ones other instances' overrides hold included, are resolved again.\n *\n * The root and the instance roots under it are built with the override lists the document holds, and\n * the edit applies to the root's: the serializer recomputes a list by diffing the live members with\n * their scene, which writes an added component as its whole record and drops an override that\n * matches the scene, so a list read from it no longer follows a default or a prefab the document\n * leaves to them.\n *\n * @param context - The app and the document.\n * @param uid - The instance root.\n * @param edit - Returns the new override list from the document's current one.\n * @param keepHashes - Whether the instances keep the hashes they were built against; without them\n * they build from their scenes' current files without an `IGX-0604` mismatch, as after a reload.\n */\nasync function rebuildInstance(\n context: OpContext,\n uid: string,\n edit: (overrides: readonly SceneFileOverride[]) => readonly SceneFileOverride[],\n keepHashes = true,\n): Promise<void> {\n const index = indexOf(context);\n const root = requireEntity(context, uid);\n const mirror = context.mirror;\n const withDocumentOverrides = (record: SceneFileEntity): SceneFileEntity => {\n if (record.instance === undefined) {\n return record;\n }\n const { scene, hash, overrides: serialized } = record.instance;\n const listed = mirror.overridesOf(record.uid) ?? serialized ?? [];\n const instance: SceneFileInstance = {\n scene,\n ...(hash === undefined || !keepHashes ? {} : { hash }),\n ...(listed.length === 0 ? {} : { overrides: listed }),\n };\n return withOverrideList(record, instance, mirror.rootPathOf(record.uid));\n };\n const found = index.records.get(uid);\n const record = found === undefined ? undefined : withDocumentOverrides(found);\n const instance = record?.instance;\n if (record === undefined || instance === undefined) {\n throw new OpFailure(ApplyOpFailureCode.notAnInstance, `${root.name} (${uid}) has no instance entry.`);\n }\n const overrides = edit(instance.overrides ?? []);\n const top = withOverrideList(\n record,\n {\n scene: instance.scene,\n ...(instance.hash === undefined ? {} : { hash: instance.hash }),\n ...(overrides.length === 0 ? {} : { overrides }),\n },\n mirror.rootPathOf(uid),\n );\n const inside = new Set([uid]);\n const records: SceneFileEntity[] = [top];\n for (const candidate of index.file.entities) {\n if (candidate.parent !== null && inside.has(candidate.parent)) {\n inside.add(candidate.uid);\n records.push(withDocumentOverrides(candidate));\n }\n }\n // An `add` override's component keeps its uid, so the rest of the document may name it, before\n // the edit or after.\n const insideComponents = new Set([\n ...records.flatMap((entry_) => (entry_.components ?? []).map((component) => component.uid)),\n ...[...(instance.overrides ?? []), ...records.flatMap((entry_) => entry_.instance?.overrides ?? [])].flatMap(\n (override) => addedUid(override) ?? [],\n ),\n ]);\n // Read before the subtree goes: destroying it clears every reference field that points at it.\n const held = heldByMembers(context.app, context.mirror, index, root, inside, insideComponents);\n const parent = root.parent;\n const at = documentSiblings(context, parent, null).indexOf(root);\n root.destroyImmediate();\n context.mirror.invalidate();\n await buildSubtree(context, records, parent, at);\n mirror.recordInstances(records);\n const references = context.mirror.decoder();\n const rebuilt = indexOf(context);\n const issues: SceneIssue[] = [];\n const repoint = (\n live: Component | undefined,\n props: JsonObject | undefined,\n decoder: ReferenceDecoder = references,\n ): void => {\n const fields = new Set(\n Object.entries(props ?? {})\n .filter(([, value]) => pointsInto(value, inside, insideComponents))\n .map(([name]) => name),\n );\n // A script's `onDestroy` may have taken the component down with the subtree.\n if (live === undefined || live.isDestroyed || props === undefined || fields.size === 0) {\n return;\n }\n // Every component uid the subtree had resolves, so this decode reports only the problems the\n // fields had when they were built. A rebuild keeps the subtree's document entities, so their\n // uids resolve anyway.\n const asBuilt: ReferenceDecoder = {\n entity: (target) => decoder.entity(target),\n component: (target) => (insideComponents.has(target) ? target : decoder.component(target)),\n asset: (address, type) => decoder.asset(address, type),\n };\n // Only the fields that point in, and only their problems that are new: another reference in\n // the same field that resolves nowhere was reported when it was built.\n const reported = new Set(propIssues(live, props, asBuilt, fields).map((issue) => issue.message));\n issues.push(...assignProps(live, props, decoder, fields).filter((issue) => !reported.has(issue.message)));\n };\n for (const outside of index.file.entities) {\n if (inside.has(outside.uid)) {\n continue;\n }\n for (const component of outside.components ?? []) {\n repoint(rebuilt.components.get(component.uid), component.props);\n }\n // A component another instance's override adds, as the document's list holds it.\n for (const override of mirror.overridesOf(outside.uid) ?? []) {\n const added = addedUid(override);\n const props = asJsonObject(asJsonObject(override.value)?.[\"props\"]);\n if (added !== null && props !== null) {\n repoint(rebuilt.added.get(added), props);\n }\n }\n }\n // The fields other instances' overrides aimed into the subtree, on members that were not rebuilt.\n // Their other references (to their own instance's members, which the document cannot name) keep\n // the objects they held.\n const keep: ReferenceDecoder = {\n entity: (target) => (inside.has(target) ? null : held.entities.get(target)) ?? references.entity(target),\n component: (target) =>\n (insideComponents.has(target) ? null : held.components.get(target)) ?? references.component(target),\n asset: (address, type) => references.asset(address, type),\n };\n for (const [component, props] of held.fields) {\n repoint(component, props, keep);\n }\n // Read as a reopen's: a reference into the subtree that the edit left with nothing to name.\n reportBuildIssues(context, issues);\n}\n\n/**\n * Rebuilds one instance root from its scene asset's current value, keeping its uid, its record\n * (transform, overrides, components) and its document children, as `setOverride` does: what the\n * host does after a hot reload replaced the scene the root instances, or changed a default its\n * members leave out.\n *\n * @param app - The scene view's app.\n * @param mirror - The open document.\n * @param uid - The instance root.\n * @throws OpFailure when the uid names no document entity or one without an instance entry.\n */\nexport async function reloadInstance(app: App, mirror: DocumentMirror, uid: string): Promise<void> {\n try {\n await rebuildInstance({ app, mirror }, uid, (overrides) => overrides, false);\n } finally {\n mirror.invalidate();\n }\n}\n\n/**\n * Applies `setOverride`: replaces the override with the same identity, or inserts it.\n *\n * @param context - The app and the document.\n * @param op - The op.\n */\nasync function setOverride(context: OpContext, op: SetOverrideOp): Promise<void> {\n const override = op.override;\n if (overrideKind(override.path) === null) {\n throw new OpFailure(\n ApplyOpFailureCode.invalidPath,\n `\"${override.path}\" is not an override path the engine can apply.`,\n \"IGX-0609\",\n );\n }\n await loadAssets(context, override.value);\n await rebuildInstance(context, op.entity, (overrides) => {\n const next = [...overrides];\n const existing = findOverride(next, override.path, override.op ?? \"replace\", addedUid(override));\n if (existing >= 0) {\n if (op.index !== undefined && op.index !== existing) {\n throw new OpFailure(\n ApplyOpFailureCode.invalidIndex,\n `The override already exists at index ${String(existing)}.`,\n );\n }\n next[existing] = override;\n return next;\n }\n next.splice(checkIndex(op.index, next.length), 0, override);\n return next;\n });\n}\n\n/**\n * Applies `removeOverride`.\n *\n * @param context - The app and the document.\n * @param op - The op.\n */\nasync function removeOverride(context: OpContext, op: RemoveOverrideOp): Promise<void> {\n await rebuildInstance(context, op.entity, (overrides) => {\n const next = [...overrides];\n const at = findOverride(next, op.path, op.overrideOp ?? impliedOp(op.path), op.added ?? null);\n if (at < 0) {\n throw new OpFailure(ApplyOpFailureCode.unknownOverride, `The instance has no override at \"${op.path}\".`);\n }\n next.splice(at, 1);\n return next;\n });\n}\n","/**\n * `sampleAnimation`: the scene view poses an entity's `Animator` at one point of one state, through\n * the engine's `Animator.sample` (ADR-0028, amendment 2026-10-20). The host depends on core only, so\n * it finds the `Animator` by its type id and calls `sample` by shape.\n */\n\nimport { isIgnifxError } from \"@ignifx/core\";\nimport { InvalidParamsError } from \"../channel.js\";\nimport {\n isSampleAnimationParams,\n SAMPLE_ANIMATION_MAX_NAME_LENGTH,\n SAMPLE_ANIMATION_MAX_PARAMETERS,\n} from \"../protocol/index.js\";\nimport { componentTypeOf } from \"./view-2d.js\";\nimport type { DocumentMirror } from \"./document.js\";\nimport type { SampleAnimationResult } from \"../protocol/index.js\";\nimport type { App } from \"@ignifx/core\";\n\n/** The type id `@ignifx/3d` registers its `Animator` under. */\nexport const ANIMATOR_TYPE_ID = \"ignifx/Animator\";\n\n/**\n * Answers `sampleAnimation` on the open document.\n *\n * @param app - The scene view's app.\n * @param mirror - The open document.\n * @param params - The received `params`.\n * @returns Whether the pose was written.\n * @throws InvalidParamsError for malformed params, an entity the document lacks or one without an\n * `Animator`, and any `IgnifxError` the engine throws, whose code it carries as `data.code`.\n */\nexport function sampleAnimation(app: App, mirror: DocumentMirror, params: unknown): SampleAnimationResult {\n if (!isSampleAnimationParams(params)) {\n throw new InvalidParamsError(\n `sampleAnimation takes { entity: uid, state: string, normalizedTime: number, parameters?: { [name]: number | boolean } }, with names of at most ${String(SAMPLE_ANIMATION_MAX_NAME_LENGTH)} characters and at most ${String(SAMPLE_ANIMATION_MAX_PARAMETERS)} parameters.`,\n );\n }\n const entity = mirror.index()?.entities.get(params.entity);\n if (entity === undefined) {\n throw new InvalidParamsError(`sampleAnimation names ${params.entity}, which is not an entity of the open scene.`);\n }\n const type = componentTypeOf(app, ANIMATOR_TYPE_ID);\n const animator = type === null ? null : entity.getComponent(type);\n const sample: unknown = animator === null ? undefined : Reflect.get(animator, \"sample\");\n if (animator === null || typeof sample !== \"function\") {\n throw new InvalidParamsError(`The entity ${params.entity} has no Animator to sample.`);\n }\n const options = params.parameters === undefined ? [] : [{ parameters: params.parameters }];\n try {\n const posed: unknown = Reflect.apply(sample, animator, [params.state, params.normalizedTime, ...options]);\n return { posed: posed === true };\n } catch (error) {\n if (isIgnifxError(error)) {\n throw new InvalidParamsError(error.message, { code: error.code });\n }\n throw error;\n }\n}\n","/**\n * `getSchemas` and `schemasChanged`: every registered component's schema, as the inspector reads\n * it, plus core's file-format entries.\n */\n\nimport { describeRegisteredSchemas, describeSchemas, toJsonSchema, Transform, transformSchema } from \"@ignifx/core\";\nimport type { SchemaDescription, SchemaSet } from \"../protocol/index.js\";\nimport type { App, ComponentRegistry, ComponentType } from \"@ignifx/core\";\n\n/** The `format` core's component entries carry; file formats carry their own name instead. */\nconst COMPONENTS_FORMAT = \"components\";\n\n/**\n * Describes every component class the app's registry holds (engine, extensions and the project's\n * scripts) with core's `describeRegisteredSchemas`, plus the JSON Schema of its `props` and core's\n * file-format entries.\n *\n * @remarks\n * Each field carries its inspector options (`step`, `hidden`, `readonly`, `group`, an asset's\n * `assetType`, a `componentRef`'s `componentType`), and each component its `allowMultiple` and the\n * `package` that registered it, all optional members of protocol 0.3. A component core describes\n * keeps core's title and summary; any other is titled from its type id. The host's own classes are left out: they are not the\n * document's. `ignifx/Transform` is described with core's `transformSchema()` and carries\n * `builtIn`: its fields are each entity's `transform` block, edited with `setTransform`, and it is\n * never added or removed. Each component also carries `extends` (engine ask E44): the registered\n * components its class derives from, which count as present for a `requires` entry.\n *\n * The set is read from the live registry each time, so a hot reload that adds a field or a script\n * shows in the next `schemasChanged`.\n *\n * @param app - The scene view's app.\n * @param hidden - Type ids to leave out.\n * @returns The set, keyed by type id.\n */\nexport function schemaSet(app: App, hidden: ReadonlySet<string>): SchemaSet {\n const core = describeSchemas();\n const registry = app.world.registry;\n const described = describeRegisteredSchemas(registry, core);\n const schemas: Record<string, SchemaDescription> = {};\n for (const [typeId, type] of registry.registrations()) {\n const description = described[typeId];\n if (hidden.has(typeId) || description === undefined) {\n continue;\n }\n const schema = type === Transform ? transformSchema() : (registry.describe(type).schema ?? {});\n schemas[typeId] = {\n ...description,\n extends: registeredAncestors(registry, type),\n propsSchema: toJsonSchema(schema),\n };\n }\n for (const [id, description] of Object.entries(core)) {\n if (description.format !== COMPONENTS_FORMAT) {\n schemas[id] = description;\n }\n }\n return { schemas };\n}\n\n/**\n * The type ids of the registered component classes a class derives from, nearest first.\n *\n * @remarks\n * `Entity.getComponent`, and so `addComponent`'s `requires` check, matches a class against the\n * attached component's ancestor chain, by class identity. An ancestor is listed when it is\n * registered under its own `static typeId`, the id `requires` names it by; an intermediate class\n * that only inherits a registered parent's `typeId` is not that registration and is left out.\n *\n * @param registry - The app's component registry.\n * @param type - The described class.\n * @returns The ancestors' type ids, the class itself excluded; empty when none is registered.\n */\nfunction registeredAncestors(registry: ComponentRegistry, type: ComponentType): readonly string[] {\n const ids: string[] = [];\n const ancestors = registry.describe(type).ancestors;\n for (let index = 1; index < ancestors.length; index += 1) {\n const ancestor = ancestors[index];\n if (ancestor !== undefined && registry.isRegistered(ancestor)) {\n ids.push(registry.requireTypeId(ancestor));\n }\n }\n return ids;\n}\n","/**\n * `screenshot`'s image encoding: a captured frame scaled to the requested size and written as a\n * PNG or JPEG data URL. It needs a browser's `OffscreenCanvas`, as the capture needs a GPU.\n */\n\nimport type { PixelSize } from \"./view-math.js\";\nimport type { ScreenshotFormat } from \"../protocol/index.js\";\nimport type { RenderCapture } from \"@ignifx/core\";\n\n/** Bytes encoded per `String.fromCharCode` call, to stay under engines' argument limits. */\nconst BASE64_CHUNK = 0x8000;\n\n/**\n * Encodes bytes as base64.\n *\n * @param bytes - The bytes.\n * @returns The base64 text.\n */\nfunction toBase64(bytes: Uint8Array): string {\n let binary = \"\";\n for (let start = 0; start < bytes.length; start += BASE64_CHUNK) {\n binary += String.fromCharCode(...bytes.subarray(start, start + BASE64_CHUNK));\n }\n return btoa(binary);\n}\n\n/**\n * Scales a captured frame to a size and encodes it as a data URL.\n *\n * @param capture - The frame, RGBA8 with the top row first.\n * @param size - The image size.\n * @param format - `\"png\"` or `\"jpeg\"`.\n * @param quality - The JPEG quality, from 0 to 1; ignored for PNG.\n * @returns A `data:image/png;base64,…` or `data:image/jpeg;base64,…` URL.\n * @throws Error when the browser has no 2D canvas context.\n */\nexport async function encodeCapture(\n capture: RenderCapture,\n size: PixelSize,\n format: ScreenshotFormat,\n quality: number,\n): Promise<string> {\n const source = new OffscreenCanvas(capture.width, capture.height);\n const sourceContext = source.getContext(\"2d\");\n const target = new OffscreenCanvas(size.width, size.height);\n const targetContext = target.getContext(\"2d\");\n if (sourceContext === null || targetContext === null) {\n throw new Error(\"This browser has no 2D canvas to encode the screenshot with.\");\n }\n sourceContext.putImageData(new ImageData(new Uint8ClampedArray(capture.data), capture.width, capture.height), 0, 0);\n targetContext.imageSmoothingQuality = \"high\";\n targetContext.drawImage(source, 0, 0, size.width, size.height);\n const type = format === \"png\" ? \"image/png\" : \"image/jpeg\";\n const blob = await target.convertToBlob(format === \"png\" ? { type } : { type, quality });\n return `data:${type};base64,${toBase64(new Uint8Array(await blob.arrayBuffer()))}`;\n}\n","/**\n * `describeSettings`: the project's settings sections, as the editor's settings panel reads them,\n * and the values the app resolved for them.\n */\n\nimport { describeSettings, settingsJsonSchema } from \"@ignifx/core\";\nimport type { JsonObject, JsonValue, SchemaDescription, SettingsSet } from \"../protocol/index.js\";\nimport type { App } from \"@ignifx/core\";\n\n/**\n * Copies a value made of JSON data, leaving out what JSON cannot carry.\n *\n * @param value - The value.\n * @returns The copy, or `undefined` for a function, `undefined`, a symbol, a bigint or a\n * non-finite number.\n */\nfunction jsonCopy(value: unknown): JsonValue | undefined {\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") {\n return value;\n }\n if (typeof value === \"number\") {\n return Number.isFinite(value) ? value : undefined;\n }\n if (Array.isArray(value)) {\n return value.map((item: unknown) => jsonCopy(item) ?? null);\n }\n if (typeof value === \"object\") {\n return jsonObjectCopy(value);\n }\n return undefined;\n}\n\n/**\n * Copies an object's own enumerable members with {@link jsonCopy}.\n *\n * @param value - The object.\n * @returns The copy.\n */\nfunction jsonObjectCopy(value: object): JsonObject {\n const entries: [string, JsonValue][] = [];\n for (const [key, member] of Object.entries(value)) {\n const converted = jsonCopy(member);\n if (converted !== undefined) {\n entries.push([key, converted]);\n }\n }\n // `fromEntries` defines own properties, so a `__proto__` key from a settings file stays an entry;\n // assigning it would hit the prototype setter and lose it.\n return Object.fromEntries(entries);\n}\n\n/**\n * Tells whether a JSON value is an object.\n *\n * @param value - The value.\n * @returns True for an object that is not an array.\n */\nfunction isObject(value: JsonValue | undefined): value is JsonObject {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Describes every settings section the app registered with core's `describeSettings`, each with\n * its JSON Schema from `settingsJsonSchema` as `propsSchema`, and copies the value the app resolved\n * for each section.\n *\n * @remarks\n * Settings are held in the settings form (`{ x, y, z }` for a vector), which is plain data, so a\n * section's value is copied member by member; a member JSON cannot carry is left out. The answer is\n * read from the app each time and sent only on request.\n *\n * @param app - The scene view's app.\n * @returns The sections and their values, keyed by section name in registration order.\n */\nexport function settingsSet(app: App): SettingsSet {\n const described = describeSettings(app);\n const properties = settingsJsonSchema(app)[\"properties\"];\n const sections: Record<string, SchemaDescription> = {};\n const values: Record<string, JsonObject> = {};\n for (const [name, description] of Object.entries(described)) {\n const propsSchema = isObject(properties) ? properties[name] : undefined;\n sections[name] = isObject(propsSchema) ? { ...description, propsSchema } : description;\n const value: unknown = app.settings.section(name);\n values[name] = typeof value === \"object\" && value !== null ? jsonObjectCopy(value) : {};\n }\n return { sections, values };\n}\n","/**\n * The scene methods and notifications of protocol 0.3: what the scene view's host does with the\n * editor's document (`docs/architecture/17-editor-host.md` §6).\n */\n\nimport { Camera, canonicalizeNumber, createRay, isIgnifxError, validateSceneFile } from \"@ignifx/core\";\nimport { clipHostText, hotReloadedParamsOf, messageOf, relayAppReports } from \"../app-reports.js\";\nimport { InvalidParamsError, Reply, RpcFailure } from \"../channel.js\";\nimport { createEditorView } from \"../lite/gizmos.js\";\nimport {\n GizmoMode,\n GizmoSpace,\n HostCapability,\n isApplyOpsParams,\n isEntitySelection,\n isFrameParams,\n isOpenSceneParams,\n isPickParams,\n isReadBackParams,\n isScreenshotParams,\n isSetAnimateMaterialsParams,\n isSetGizmoParams,\n isSetViewModeParams,\n PickUnit,\n RpcErrorCode,\n SCREENSHOT_MAX_SIZE,\n SceneMethod,\n SceneNotification,\n ViewMode,\n} from \"../protocol/index.js\";\nimport {\n IN_PLACE_ASSET_TYPES,\n instancesOf,\n outermostRoots,\n SCENE_ASSET_TYPE,\n waitForReplacement,\n} from \"./asset-reload.js\";\nimport { colliderOutlinesOf } from \"./collider-outlines.js\";\nimport { applyDefaults, DefaultsTracker, instancesHolding } from \"./defaults.js\";\nimport { DocumentMirror } from \"./document.js\";\nimport { EditorCamera2D, EYE_DISTANCE_2D } from \"./editor-camera-2d.js\";\nimport { EDITOR_CAMERA_FOV, EditorCamera } from \"./editor-camera.js\";\nimport { GizmoDragRelay } from \"./gizmo-drag.js\";\nimport { applyOps, reloadInstance } from \"./ops.js\";\nimport { sampleAnimation } from \"./sample-animation.js\";\nimport { schemaSet } from \"./schemas.js\";\nimport { encodeCapture } from \"./screenshot.js\";\nimport { settingsSet } from \"./settings.js\";\nimport {\n boundsOf2D,\n CAMERA_2D_TYPE,\n componentTypeOf,\n DEFAULT_PIXELS_PER_UNIT,\n isCamera2DLike,\n levelCamera2D,\n sceneViewMode,\n twoDServiceOf,\n zoomForSize,\n} from \"./view-2d.js\";\nimport { pickRayMembers, screenshotSize, toBackingPixels, viewSurfaceOf } from \"./view-math.js\";\nimport type { RequestHandler } from \"../channel.js\";\nimport type { EditorAssetChange, PendingReload } from \"./asset-reload.js\";\nimport type { ChangedDefaults } from \"./defaults.js\";\nimport type { ViewClick } from \"./editor-camera.js\";\nimport type { PickRayMembers } from \"./view-math.js\";\nimport type { EditorView, ViewDrag, WorldBounds } from \"../lite/gizmos.js\";\nimport type {\n AssetReloadedParams,\n ColliderOutlineSet,\n GizmoSnap,\n HostErrorParams,\n PickParams,\n PickResult,\n SchemaSet,\n ScreenshotResult,\n SettingsSet,\n} from \"../protocol/index.js\";\nimport type { App, Entity, HotReloadReport, RenderSurface, SceneInstance } from \"@ignifx/core\";\n\n/** The name of the host's persistent scene instance for its own objects. */\nexport const EDITOR_SCENE_NAME = \"editor\";\n\n/** The editor camera's priority: above any camera a document can hold. */\nconst EDITOR_CAMERA_PRIORITY = 1_000_000;\n\n/** What the scene host needs from the host that owns it. */\nexport interface SceneHostOptions {\n /** The capabilities the host announces in `ready`; the methods follow them. */\n readonly capabilities: readonly string[];\n /**\n * Sends a notification on the current port, or drops it when no editor is ready.\n *\n * @param method - The notification.\n * @param params - Its parameters.\n */\n readonly notify: (method: string, params: unknown) => void;\n}\n\n/** A point of the view, in backing-store pixels. */\ninterface BackingPoint {\n /** From the left edge. */\n readonly x: number;\n /** From the top edge. */\n readonly y: number;\n}\n\n/** The gizmo's settings, as `setGizmo` last set them. */\ninterface GizmoSettings {\n /** What it does. */\n readonly mode: GizmoMode;\n /** Which axes it follows. */\n readonly space: GizmoSpace;\n /** The snapping steps, or `null`. */\n readonly snap: GizmoSnap | null;\n}\n\n/**\n * Runs the scene methods against one app, and sends the notifications the app causes.\n *\n * @remarks\n * The host builds it before the app exists, so the channel can answer `hello` at once; every scene\n * method answers `notReady` until {@link SceneHost.start} has run (protocol 0.3, \"Not before the\n * app has started\").\n */\nexport class SceneHost {\n /** The scene methods, by name, for the channel. */\n readonly methods: ReadonlyMap<string, RequestHandler>;\n\n readonly #notify: (method: string, params: unknown) => void;\n\n #app: App | null = null;\n\n #mirror: DocumentMirror | null = null;\n\n #editorScene: SceneInstance | null = null;\n\n #camera: EditorCamera | null = null;\n\n #camera2D: EditorCamera2D | null = null;\n\n /** The editor camera the view uses, as `setViewMode` last set it. */\n #viewMode: ViewMode = ViewMode.threeD;\n\n /** The document the 2D camera was last placed on (see `#documentKey`), or `undefined` for none. */\n #placed2D: string | null | undefined = undefined;\n\n /** Whether the host lists `viewMode2d`. */\n readonly #hasViewMode2D: boolean;\n\n #eye: Camera | null = null;\n\n #canvas: RenderSurface | null = null;\n\n #view: EditorView | null = null;\n\n #selection: readonly string[] = [];\n\n #gizmo: GizmoSettings = { mode: GizmoMode.translate, space: GizmoSpace.world, snap: null };\n\n readonly #drag: GizmoDragRelay;\n\n #started = false;\n\n /** The field defaults seen at start and after each hot reload, from {@link SceneHost.start} on. */\n #defaults: DefaultsTracker | null = null;\n\n readonly #cleanups: (() => void)[] = [];\n\n /** The reloads waiting for their new value; disposing the host cancels them. */\n readonly #reloads = new Set<PendingReload>();\n\n /** The tail of the work that touches the document, run one task at a time. */\n #queue: Promise<unknown> = Promise.resolve();\n\n /**\n * Creates the methods; none answers until the app has started.\n *\n * @param options - The capabilities and the notification sink.\n */\n constructor(options: SceneHostOptions) {\n this.#notify = options.notify;\n this.#drag = new GizmoDragRelay(options.notify);\n const has = (capability: string): boolean => options.capabilities.includes(capability);\n this.#hasViewMode2D = has(HostCapability.viewMode2d);\n const methods = new Map<string, RequestHandler>([\n [SceneMethod.openScene, async (params) => this.#openScene(params)],\n [SceneMethod.closeScene, async () => this.#closeScene()],\n [SceneMethod.applyOps, async (params) => this.#applyOps(params)],\n [SceneMethod.readBack, (params) => this.#readBack(params)],\n [SceneMethod.select, (params) => this.#select(params)],\n [SceneMethod.frame, (params) => this.#frame(params)],\n [SceneMethod.pick, async (params) => this.#pick(params)],\n [SceneMethod.getSchemas, () => this.#getSchemas()],\n [SceneMethod.describeSettings, () => this.#describeSettings()],\n [SceneMethod.setViewMode, (params) => this.#setViewMode(params)],\n [SceneMethod.setAnimateMaterials, (params) => this.#setAnimateMaterials(params)],\n [SceneMethod.getColliderOutlines, (params) => this.#getColliderOutlines(params)],\n [SceneMethod.sampleAnimation, (params) => this.#sampleAnimation(params)],\n ]);\n if (has(HostCapability.gizmos)) {\n methods.set(SceneMethod.setGizmo, (params) => this.#setGizmo(params));\n }\n if (has(HostCapability.screenshot)) {\n methods.set(SceneMethod.screenshot, async (params) => this.#screenshot(params));\n }\n // The channel answers one request at a time; an asset reload's rebuild queues with them.\n this.methods = new Map(\n [...methods].map(([name, handler]) => [name, async (params: unknown) => this.#serial(() => handler(params))]),\n );\n }\n\n /**\n * The persistent scene instance that holds the host's own objects, such as the editor camera.\n *\n * @returns The instance, or `null` before {@link SceneHost.prepare}.\n */\n get editorScene(): SceneInstance | null {\n return this.#editorScene;\n }\n\n /**\n * Prepares the app before it starts: the persistent `editor` scene with the editor camera, and\n * the log, error and hot-reload relays.\n *\n * @param app - The scene view's app, created and not yet started.\n */\n prepare(app: App): void {\n this.#app = app;\n this.#mirror = new DocumentMirror(app);\n const scene = app.world.createScene(EDITOR_SCENE_NAME, { persistent: true });\n this.#editorScene = scene;\n app.registerComponents([EditorCamera, EditorCamera2D]);\n const eye = app.world.createEntity(\"Editor Camera\", { scene });\n this.#eye = eye.addComponent(Camera, {\n fov: EDITOR_CAMERA_FOV,\n near: 0.05,\n far: 5000,\n priority: EDITOR_CAMERA_PRIORITY,\n });\n const camera = eye.addComponent(EditorCamera);\n camera.apply();\n this.#camera = camera;\n // The 2D toolkit's camera, found by its type id: highest priority wins, so while it is enabled\n // the sprites draw through it and the level's own `Camera2D` is left as the file has it.\n const camera2DType = componentTypeOf(app, CAMERA_2D_TYPE);\n const camera2D = camera2DType === null ? null : eye.addComponent(camera2DType);\n if (isCamera2DLike(camera2D)) {\n camera2D.priority = EDITOR_CAMERA_PRIORITY;\n camera2D.pixelPerfect = false;\n camera2D.enabled = false;\n }\n const twoD = eye.addComponent(EditorCamera2D);\n twoD.attach(this.#eye, isCamera2DLike(camera2D) ? camera2D : null);\n twoD.pixelsPerUnit = (): number => twoDServiceOf(app)?.pixelsPerUnit ?? DEFAULT_PIXELS_PER_UNIT;\n this.#camera2D = twoD;\n this.#cleanups.push(\n relayAppReports(app, {\n log: (params): void => {\n this.#notify(SceneNotification.log, params);\n },\n error: (params): void => {\n this.#notify(SceneNotification.hostError, params);\n },\n hotReloaded: (report): void => {\n this.#hotReloaded(report);\n },\n }),\n );\n }\n\n /**\n * Finishes setting up once the app has started: the gizmos and the outline on a canvas, the\n * camera's controls, and the first `schemasChanged`.\n *\n * @param canvas - The view's canvas, or `null` for a headless host.\n * @throws Whatever opening the render overlay throws.\n */\n async start(canvas: RenderSurface | null): Promise<void> {\n const app = this.#requireApp();\n this.#canvas = canvas;\n if (canvas !== null && !app.isHeadless && this.methods.has(SceneMethod.setGizmo) && isDomCanvas(canvas)) {\n const view = createEditorView(app.lite, await app.renderer.openOverlay(), canvas);\n view.onDrag((phase, drag) => {\n this.#onDrag(phase, drag);\n });\n this.#view = view;\n this.#applyGizmo();\n const onClick = (click: ViewClick): void => {\n this.#onClick(click).catch((error: unknown) => {\n const params: HostErrorParams = {\n code: isIgnifxError(error) ? error.code : null,\n message: clipHostText(`Selecting what a click in the view hit: ${messageOf(error)}`),\n data: { x: click.x, y: click.y },\n };\n this.#notify(SceneNotification.hostError, params);\n });\n };\n for (const camera of [this.#camera, this.#camera2D]) {\n if (camera !== null) {\n camera.claims = view;\n camera.onClick = onClick;\n camera.bind(canvas);\n }\n }\n }\n this.#defaults = new DefaultsTracker(app);\n this.#started = true;\n this.sendSchemas();\n }\n\n /** Sends `schemasChanged` once the app has started; the channel calls it after each `ready`. */\n sendSchemas(): void {\n if (this.#started) {\n this.#notify(SceneNotification.schemasChanged, this.#schemas());\n }\n }\n\n /**\n * Reloads an asset that changed on disk, in place, when the app has it loaded and its type is one\n * the renderers follow: a scene or prefab, whose instances in the open document are rebuilt from\n * the new file with their uids, transforms and overrides, or a model, mesh, material, sprite atlas\n * or shader. Sends `assetReloaded` once the new value is in. The open document's own file, a\n * removed file and any other type are left alone.\n *\n * @param change - The address and what happened to it.\n * @returns Whether the asset was reloaded; `false` also when the reload failed, which the app\n * reports as an error.\n */\n async assetChanged(change: EditorAssetChange): Promise<boolean> {\n const app = this.#app;\n const mirror = this.#mirror;\n const { address } = change;\n if (app === null || mirror === null || !this.#started || change.kind === \"removed\") {\n return false;\n }\n const handle = app.assets.get(address);\n if (\n handle === null ||\n handle.state !== \"loaded\" ||\n !IN_PLACE_ASSET_TYPES.includes(handle.type) ||\n (mirror.scene !== null && address === mirror.address)\n ) {\n return false;\n }\n const pending = waitForReplacement(app, handle);\n this.#reloads.add(pending);\n app.assets.reload(address);\n const replaced = await pending.replaced;\n this.#reloads.delete(pending);\n if (!replaced) {\n return false;\n }\n return this.#serial(async () => {\n const index = handle.type === SCENE_ASSET_TYPE ? mirror.index() : null;\n const roots = index === null ? [] : instancesOf(app, index, address);\n const entities = await this.#rebuildInstances(app, mirror, roots, address, { address });\n this.#setSelection(this.#selection);\n const params: AssetReloadedParams = { address, type: handle.type, entities };\n this.#notify(SceneNotification.assetReloaded, params);\n return true;\n });\n }\n\n /**\n * Rebuilds instance roots from their scenes, one after the other; a root that fails is a\n * `hostError`.\n *\n * @param app - The scene view's app.\n * @param mirror - The open document.\n * @param roots - The roots' uids, none inside another.\n * @param cause - What the rebuild follows, for the error's message.\n * @param data - What the error's `data` carries besides the root's uid.\n * @returns The roots rebuilt.\n */\n async #rebuildInstances(\n app: App,\n mirror: DocumentMirror,\n roots: readonly string[],\n cause: string,\n data: Readonly<Record<string, string | readonly string[]>>,\n ): Promise<string[]> {\n const rebuilt: string[] = [];\n for (const uid of roots) {\n try {\n // Each rebuild reads the document the previous one left.\n // oxlint-disable-next-line no-await-in-loop -- see above\n await reloadInstance(app, mirror, uid);\n rebuilt.push(uid);\n } catch (error) {\n const params: HostErrorParams = {\n code: isIgnifxError(error) ? error.code : null,\n message: clipHostText(`Rebuilding ${uid} from ${cause}: ${messageOf(error)}`),\n data: { ...data, entity: uid },\n };\n this.#notify(SceneNotification.hostError, params);\n }\n }\n return rebuilt;\n }\n\n /**\n * Gives the open document the defaults a hot reload changed, where it leaves them out (engine ask\n * E25): each document component's omitted fields take the new default, then each prefab instance\n * whose members hold a changed type is rebuilt from its prefab with its overrides. A component\n * that throws while taking a default is a `hostError`, and the rest still runs.\n *\n * @param changed - The changed fields, by type id.\n */\n async #followDefaults(changed: ChangedDefaults): Promise<void> {\n const app = this.#app;\n const mirror = this.#mirror;\n const index = mirror?.index() ?? null;\n if (app === null || mirror === null || index === null) {\n return;\n }\n applyDefaults(app, mirror, index, changed, (component, typeId, error) => {\n const params: HostErrorParams = {\n code: isIgnifxError(error) ? error.code : null,\n message: clipHostText(`Applying the new defaults of ${typeId} to ${component.uid}: ${messageOf(error)}`),\n data: { typeIds: [typeId], entity: component.entity.uid, component: typeId },\n };\n this.#notify(SceneNotification.hostError, params);\n });\n mirror.invalidate();\n const rebuilt = mirror.index();\n const roots = rebuilt === null ? [] : outermostRoots(rebuilt, instancesHolding(app, mirror, rebuilt, changed));\n if (roots.length > 0) {\n const typeIds = [...changed.keys()];\n const cause = `the new defaults of ${typeIds.join(\", \")}`;\n await this.#rebuildInstances(app, mirror, roots, cause, { typeIds });\n this.#setSelection(this.#selection);\n }\n }\n\n /** Removes the relays and the overlay; the host disposes the app. */\n dispose(): void {\n for (const pending of this.#reloads) {\n pending.cancel();\n }\n for (const cleanup of this.#cleanups.splice(0)) {\n cleanup();\n }\n this.#view?.dispose();\n this.#view = null;\n }\n\n // -------------------------------------------------------------------------------------------\n // Methods\n // -------------------------------------------------------------------------------------------\n\n /**\n * `openScene`: replaces the open document with the editor's file.\n *\n * @param params - `{ file, address }`.\n * @returns The entity count and warnings, then `sceneOpened`.\n */\n async #openScene(params: unknown): Promise<Reply> {\n const mirror = this.#requireMirror(SceneMethod.openScene);\n this.#setSelection([]);\n const file: unknown = typeof params === \"object\" && params !== null ? Reflect.get(params, \"file\") : undefined;\n const issues = file === undefined ? [] : validateSceneFile(file);\n if (issues.length > 0) {\n await mirror.close();\n const list = issues.map((issue) => `${issue.path}: ${issue.message}`).join(\"; \");\n throw new InvalidParamsError(`The scene file is not valid: ${list}`, { issues });\n }\n if (!isOpenSceneParams(params)) {\n throw new InvalidParamsError(\"openScene takes { file: SceneFile, address: string | null }.\");\n }\n const opened = await mirror.open(params.file, params.address);\n const viewMode = sceneViewMode(this.#requireApp(), mirror.scene);\n const result = { entityCount: opened.entityCount, warnings: opened.warnings, viewMode };\n if (this.#viewMode === ViewMode.twoD && this.#placed2D !== this.#documentKey()) {\n this.#place2D();\n }\n return new Reply(result, () => {\n this.#notify(SceneNotification.sceneOpened, {\n address: params.address,\n name: mirror.name,\n entityCount: result.entityCount,\n warnings: result.warnings,\n viewMode,\n });\n });\n }\n\n /**\n * `closeScene`: unloads the open document, if any.\n *\n * @returns `null`.\n */\n async #closeScene(): Promise<null> {\n const mirror = this.#requireMirror(SceneMethod.closeScene);\n this.#setSelection([]);\n await mirror.close();\n return null;\n }\n\n /**\n * `applyOps`: one command's ops, in order.\n *\n * @param params - `{ ops, commandName, commandId }`.\n * @returns How many applied, the failures, and the build problems.\n */\n async #applyOps(params: unknown): Promise<unknown> {\n const mirror = this.#requireMirror(SceneMethod.applyOps);\n if (!isApplyOpsParams(params)) {\n throw new InvalidParamsError(\"applyOps takes { ops: SceneOp[], commandName, commandId }.\");\n }\n this.#requireOpen(SceneMethod.applyOps);\n const result = await applyOps(this.#requireApp(), mirror, params);\n this.#setSelection(this.#selection);\n return result;\n }\n\n /**\n * `readBack`: the open document as the live world has it.\n *\n * @param params - `{ entities? }`.\n * @returns The records, the missing uids, the settings, and the serializer's issues.\n */\n #readBack(params: unknown): unknown {\n const mirror = this.#requireMirror(SceneMethod.readBack);\n if (!isReadBackParams(params)) {\n throw new InvalidParamsError(\"readBack takes { entities?: uid[] }.\");\n }\n this.#requireOpen(SceneMethod.readBack);\n return mirror.readBack(params);\n }\n\n /**\n * `select`: the selection the view outlines and the gizmo follows.\n *\n * @param params - `{ entities }`.\n * @returns The selection kept: the document's uids, in order, without duplicates.\n */\n #select(params: unknown): unknown {\n const mirror = this.#requireMirror(SceneMethod.select);\n if (!isEntitySelection(params)) {\n throw new InvalidParamsError(\"select takes { entities: uid[] }.\");\n }\n const index = mirror.index();\n const kept = [...new Set(params.entities)].filter((uid) => index?.entities.has(uid) === true);\n this.#setSelection(kept);\n return { entities: kept };\n }\n\n /**\n * `setGizmo`: the gizmo's mode, axes and snapping.\n *\n * @param params - `{ mode, space, snap }`.\n * @returns `null`.\n */\n #setGizmo(params: unknown): null {\n this.#requireMirror(SceneMethod.setGizmo);\n if (!isSetGizmoParams(params)) {\n throw new InvalidParamsError(\n 'setGizmo takes { mode, space: \"local\" | \"world\", snap: { translate, rotate, scale } | null }.',\n );\n }\n this.#gizmo = { mode: params.mode, space: params.space, snap: params.snap };\n this.#applyGizmo();\n return null;\n }\n\n /**\n * `frame`: fits entities in the editor camera's view.\n *\n * @param params - `{ entities: uid[] | \"all\" }`.\n * @returns `null`.\n */\n #frame(params: unknown): null {\n const mirror = this.#requireMirror(SceneMethod.frame);\n if (!isFrameParams(params)) {\n throw new InvalidParamsError('frame takes { entities: uid[] | \"all\" }.');\n }\n this.#requireOpen(SceneMethod.frame);\n const index = mirror.index();\n const entities =\n params.entities === \"all\"\n ? [...(mirror.scene?.roots ?? [])]\n : params.entities.flatMap((uid) => {\n const entity = index?.entities.get(uid);\n return entity === undefined ? [] : [entity];\n });\n if (this.#viewMode === ViewMode.twoD) {\n const box = boundsOf2D(this.#requireApp(), entities);\n if (box !== null) {\n this.#camera2D?.frame(box);\n }\n return null;\n }\n const bounds = this.#boundsOf(entities);\n if (bounds !== null) {\n const center = {\n x: (bounds.min.x + bounds.max.x) / 2,\n y: (bounds.min.y + bounds.max.y) / 2,\n z: (bounds.min.z + bounds.max.z) / 2,\n };\n const radius = Math.hypot(bounds.max.x - center.x, bounds.max.y - center.y, bounds.max.z - center.z);\n this.#camera?.frame({ center, radius });\n }\n return null;\n }\n\n /**\n * `pick`: which document entity is under a point of the view. Changes nothing.\n *\n * @param params - `{ x, y, unit }`.\n * @returns The entity, the world point, and the distance, or a miss.\n */\n async #pick(params: unknown): Promise<PickResult> {\n this.#requireMirror(SceneMethod.pick);\n if (!isPickParams(params)) {\n throw new InvalidParamsError('pick takes { x, y, unit: \"css\" | \"backing\" }.');\n }\n return this.#pickAt(params);\n }\n\n /**\n * `screenshot`: the view as an image, without the gizmo and the outline.\n *\n * @param params - `{ width?, height?, format, quality? }`.\n * @returns The data URL and its size.\n */\n async #screenshot(params: unknown): Promise<ScreenshotResult> {\n const app = this.#requireApp();\n this.#requireMirror(SceneMethod.screenshot);\n if (typeof params === \"object\" && params !== null) {\n for (const side of [\"width\", \"height\"]) {\n const value: unknown = Reflect.get(params, side);\n if (\n value !== undefined &&\n (!Number.isSafeInteger(value) || Number(value) < 1 || Number(value) > SCREENSHOT_MAX_SIZE)\n ) {\n throw new InvalidParamsError(\n `screenshot takes a width and height from 1 to ${String(SCREENSHOT_MAX_SIZE)} pixels.`,\n );\n }\n }\n }\n if (!isScreenshotParams(params)) {\n throw new InvalidParamsError('screenshot takes { width?, height?, format: \"png\" | \"jpeg\", quality? }.');\n }\n this.#view?.setVisible(false);\n try {\n const capture = await app.renderer.captureScreenshot();\n const size = screenshotSize(params, capture);\n const dataUrl = await encodeCapture(capture, size, params.format, params.quality ?? 0.9);\n return { dataUrl, width: size.width, height: size.height };\n } finally {\n this.#view?.setVisible(true);\n }\n }\n\n /**\n * `getSchemas`: every registered component's schema.\n *\n * @returns The set.\n */\n #getSchemas(): SchemaSet {\n this.#requireMirror(SceneMethod.getSchemas);\n return this.#schemas();\n }\n\n /**\n * `describeSettings`: the project's settings sections and their resolved values. Sent only on\n * request.\n *\n * @returns The set.\n */\n #describeSettings(): SettingsSet {\n this.#requireMirror(SceneMethod.describeSettings);\n return settingsSet(this.#requireApp());\n }\n\n /**\n * `setAnimateMaterials`: the editor's \"animate materials\" toggle, which runs or holds the shader\n * clock of the scene view (`app.renderer.animateMaterialsInEditMode`).\n *\n * @param params - `{ enabled }`.\n * @returns `null`.\n */\n #setAnimateMaterials(params: unknown): null {\n this.#requireMirror(SceneMethod.setAnimateMaterials);\n if (!isSetAnimateMaterialsParams(params)) {\n throw new InvalidParamsError(\"setAnimateMaterials takes { enabled: boolean }.\");\n }\n this.#requireApp().renderer.animateMaterialsInEditMode = params.enabled;\n return null;\n }\n\n /**\n * `getColliderOutlines`: the world-space outlines of the requested entities' colliders, from the\n * project's physics extensions, for the editor's collider gizmos. Changes nothing.\n *\n * @param params - `{ entities }`.\n * @returns The outlines, within the protocol's caps; uids the open scene does not have are skipped.\n */\n #getColliderOutlines(params: unknown): ColliderOutlineSet {\n const mirror = this.#requireMirror(SceneMethod.getColliderOutlines);\n if (!isEntitySelection(params)) {\n throw new InvalidParamsError(\"getColliderOutlines takes { entities: uid[] }.\");\n }\n this.#requireOpen(SceneMethod.getColliderOutlines);\n const index = mirror.index();\n return colliderOutlinesOf(this.#requireApp(), params.entities, (uid) => index?.entities.get(uid));\n }\n\n /**\n * `sampleAnimation`: poses an entity's `Animator` at one point of one state.\n *\n * @param params - `{ entity, state, normalizedTime, parameters? }`.\n * @returns `{ posed }`.\n */\n #sampleAnimation(params: unknown): unknown {\n const mirror = this.#requireMirror(SceneMethod.sampleAnimation);\n this.#requireOpen(SceneMethod.sampleAnimation);\n return sampleAnimation(this.#requireApp(), mirror, params);\n }\n\n /**\n * `setViewMode`: switches the view between the 3D editor camera and the 2D one. The first switch\n * to 2D on a document starts where the level's own `Camera2D` looks, or frames the document.\n *\n * @param params - `{ mode }`.\n * @returns `null`.\n */\n #setViewMode(params: unknown): null {\n this.#requireMirror(SceneMethod.setViewMode);\n if (!isSetViewModeParams(params)) {\n throw new InvalidParamsError('setViewMode takes { mode: \"3d\" | \"2d\" }.');\n }\n if (params.mode === ViewMode.twoD && (!this.#hasViewMode2D || this.#camera2D === null)) {\n throw new InvalidParamsError(\"This scene view has no 2D view mode; it does not list the viewMode2d capability.\");\n }\n if (params.mode === this.#viewMode) {\n return null;\n }\n this.#viewMode = params.mode;\n const camera = this.#camera;\n const camera2D = this.#camera2D;\n if (params.mode === ViewMode.twoD) {\n if (camera !== null) {\n camera.active = false;\n }\n camera2D?.activate();\n if (this.#placed2D !== this.#documentKey()) {\n this.#place2D();\n }\n } else {\n camera2D?.deactivate();\n if (camera !== null) {\n camera.active = true;\n camera.apply();\n }\n }\n return null;\n }\n\n /**\n * Names the open document for the 2D camera's placement: its address, or `undefined` when none is\n * open. A reopen of the same address (the editor resends `openScene` after a failed op) keeps\n * the view where the user left it.\n *\n * @returns The key.\n */\n #documentKey(): string | null | undefined {\n const mirror = this.#mirror;\n return mirror === null || mirror.scene === null ? undefined : mirror.address;\n }\n\n /**\n * Places the 2D editor camera on the open document: where the level's own `Camera2D` looks, at\n * the half-height it shows, or, without one, around the whole document.\n */\n #place2D(): void {\n const camera2D = this.#camera2D;\n const mirror = this.#mirror;\n if (camera2D === null || mirror === null) {\n return;\n }\n const app = this.#requireApp();\n const scene = mirror.scene;\n this.#placed2D = this.#documentKey();\n const level = levelCamera2D(app, scene);\n if (level !== null) {\n const view = camera2D.view();\n const position = level.entity.transform.position;\n camera2D.centerX = position.x;\n camera2D.centerY = position.y;\n camera2D.zoom = zoomForSize(level.orthographicSize, view.heightPx, view.pixelsPerUnit);\n camera2D.apply();\n return;\n }\n const box = boundsOf2D(app, [...(scene?.roots ?? [])]);\n if (box !== null) {\n camera2D.frame(box);\n }\n }\n\n // -------------------------------------------------------------------------------------------\n // Selection, picking and the gizmo\n // -------------------------------------------------------------------------------------------\n\n /**\n * Sets the selection and updates the outline and the gizmo. Uids that no longer name a document\n * entity are dropped.\n *\n * @param uids - The selection, primary last.\n */\n #setSelection(uids: readonly string[]): void {\n const index = this.#mirror?.index() ?? null;\n const entities: Entity[] = [];\n const kept: string[] = [];\n for (const uid of uids) {\n const entity = index?.entities.get(uid);\n if (entity !== undefined && !entity.isDestroyed) {\n entities.push(entity);\n kept.push(uid);\n }\n }\n this.#selection = kept;\n this.#view?.outline(entities);\n this.#applyGizmo();\n }\n\n /** Attaches the gizmo to the primary selection in the current mode and space. */\n #applyGizmo(): void {\n const view = this.#view;\n if (view === null) {\n return;\n }\n const { mode, space } = this.#gizmo;\n view.setMode(mode === GizmoMode.none ? null : mode);\n view.setLocal(space === GizmoSpace.local);\n const primary = this.#selection.at(-1);\n view.attach(primary === undefined ? null : (this.#mirror?.index()?.entities.get(primary) ?? null));\n }\n\n /**\n * Picks the document's scene at a point of the view: in 3D mode with `app.renderer.pickAsync`,\n * which resolves a glTF model through its nearest entity node, and in 2D mode with\n * `app.twoD.pickAt` first. The hit resolves to its document entity. Hit or miss, the answer\n * carries the editor camera's ray through the point and where it meets `z = 0`.\n *\n * @param params - The point and its unit; it is converted to backing-store pixels once.\n * @returns The pick result; a point outside the canvas, or a headless view, misses without a ray.\n */\n async #pickAt(params: PickParams): Promise<PickResult> {\n const scene = this.#mirror?.scene ?? null;\n const canvas = this.#canvas;\n const at = canvas === null ? null : toBackingPixels(params, viewSurfaceOf(canvas));\n if (at === null) {\n return { entity: null, point: null, distance: null };\n }\n const camera2D = this.#camera2D;\n if (this.#viewMode === ViewMode.twoD && camera2D !== null) {\n return this.#pick2D(at, camera2D, scene);\n }\n const ray = this.#eye?.screenToRay(at.x, at.y) ?? null;\n const cast = ray === null ? {} : pickRayMembers(ray);\n if (scene === null) {\n return { entity: null, point: null, distance: null, ...cast };\n }\n return this.#pick3D(at, scene, cast);\n }\n\n /**\n * Picks in 2D mode: the topmost sprite of the document under the point with `app.twoD.pickAt`,\n * unpickable sprites included, answered with the world point on `z = 0` and no distance. Without\n * a sprite hit, a `\"mixed\"` project (or one without `@ignifx/2d`) goes on to the 3D picker through\n * the orthographic eye. The ray is the eye's, straight down +Z, built from the 2D camera's own\n * arithmetic so it never lags a frame behind a pan.\n *\n * @param at - The point, in backing-store pixels.\n * @param camera2D - The 2D editor camera.\n * @param scene - The document's scene instance, or `null`.\n * @returns The pick result.\n */\n async #pick2D(at: BackingPoint, camera2D: EditorCamera2D, scene: SceneInstance | null): Promise<PickResult> {\n const world = camera2D.screenToWorld(at.x, at.y);\n const ray = createRay();\n ray.origin.x = world.x;\n ray.origin.y = world.y;\n ray.origin.z = -EYE_DISTANCE_2D + (this.#eye?.near ?? 0);\n ray.direction.x = 0;\n ray.direction.y = 0;\n ray.direction.z = 1;\n const cast = pickRayMembers(ray);\n if (scene === null) {\n return { entity: null, point: null, distance: null, ...cast };\n }\n const twoD = twoDServiceOf(this.#requireApp());\n const hit = twoD?.pickAt(at.x, at.y, { includeUnpickable: true, filter: (entity) => entity.scene === scene });\n const entity = this.#mirror?.documentEntityOf(hit?.entity ?? null) ?? null;\n if (entity !== null) {\n const c = canonicalizeNumber;\n return { entity: entity.uid, point: [c(world.x), c(world.y), 0], distance: null, ...cast };\n }\n if (twoD !== null && twoD.mode === \"sprite\") {\n return { entity: null, point: null, distance: null, ...cast };\n }\n return this.#pick3D(at, scene, cast);\n }\n\n /**\n * Picks the document's meshes with `app.renderer.pickAsync`.\n *\n * @param at - The point, in backing-store pixels.\n * @param scene - The document's scene instance.\n * @param cast - The answer's `ray` and `plane`.\n * @returns The pick result.\n */\n async #pick3D(at: BackingPoint, scene: SceneInstance, cast: Partial<PickRayMembers>): Promise<PickResult> {\n const app = this.#requireApp();\n const hit = await app.renderer.pickAsync(at.x, at.y, { filter: (entity) => entity.scene === scene });\n const entity = this.#mirror?.documentEntityOf(hit?.entity ?? null) ?? null;\n if (hit === null || entity === null) {\n return { entity: null, point: null, distance: null, ...cast };\n }\n const c = canonicalizeNumber;\n const point = hit.point;\n return {\n entity: entity.uid,\n point: point === null ? null : [c(point[0]), c(point[1]), c(point[2])],\n distance: c(hit.distance),\n ...cast,\n };\n }\n\n /**\n * A click in the view: a plain click selects what it hits or clears the selection, a click with\n * Shift, Ctrl or Cmd toggles what it hits. A changed selection is applied and sent.\n *\n * @param click - Where, and whether it toggles.\n */\n async #onClick(click: ViewClick): Promise<void> {\n const { entity } = await this.#pickAt({ x: click.x, y: click.y, unit: PickUnit.css });\n const current = this.#selection;\n let next: readonly string[];\n if (click.toggle) {\n next =\n entity === null\n ? current\n : current.includes(entity)\n ? current.filter((uid) => uid !== entity)\n : [...current, entity];\n } else {\n next = entity === null ? [] : [entity];\n }\n if (next.length === current.length && next.every((uid, index) => uid === current[index])) {\n return;\n }\n this.#setSelection(next);\n this.#notify(SceneNotification.selectionChanged, { entities: this.#selection });\n }\n\n /**\n * Hands a gizmo drag of the selection's last entity to {@link GizmoDragRelay}.\n *\n * @param phase - Which part of the gesture.\n * @param drag - The handle.\n */\n #onDrag(phase: \"start\" | \"move\" | \"end\", drag: ViewDrag): void {\n if (phase === \"start\") {\n const uid = this.#selection.at(-1);\n const entity = uid === undefined ? undefined : this.#mirror?.index()?.entities.get(uid);\n if (entity === undefined) {\n this.#drag.clear();\n } else {\n this.#drag.start(entity, drag.mode, this.#gizmo.snap);\n }\n } else if (phase === \"move\") {\n this.#drag.move();\n } else {\n this.#drag.end();\n }\n }\n\n /**\n * The world bounds of entities: their meshes' when the view can measure them, else their\n * positions, so a headless host still frames something.\n *\n * @param entities - The entities.\n * @returns The union box, or `null` for none.\n */\n #boundsOf(entities: readonly Entity[]): WorldBounds | null {\n let min = { x: Number.POSITIVE_INFINITY, y: Number.POSITIVE_INFINITY, z: Number.POSITIVE_INFINITY };\n let max = { x: Number.NEGATIVE_INFINITY, y: Number.NEGATIVE_INFINITY, z: Number.NEGATIVE_INFINITY };\n for (const entity of entities) {\n const p = entity.transform.position;\n const box = this.#view?.worldBounds(entity) ?? { min: p, max: p };\n min = { x: Math.min(min.x, box.min.x), y: Math.min(min.y, box.min.y), z: Math.min(min.z, box.min.z) };\n max = { x: Math.max(max.x, box.max.x), y: Math.max(max.y, box.max.y), z: Math.max(max.z, box.max.z) };\n }\n return Number.isFinite(min.x) ? { min, max } : null;\n }\n\n // -------------------------------------------------------------------------------------------\n // Notifications and guards\n // -------------------------------------------------------------------------------------------\n\n /**\n * Sends `hotReloaded`, then `schemasChanged`.\n *\n * @param report - What `app.hotReload` did.\n */\n #hotReloaded(report: HotReloadReport): void {\n // A \"recreate\" reload replaces component instances, which the document index holds.\n this.#mirror?.invalidate();\n const changed = this.#defaults?.changed(report.typeIds) ?? new Map<string, readonly string[]>();\n if (changed.size > 0) {\n // Queued with the requests, so a request the editor sends after `schemasChanged` sees it done.\n this.#serial(async () => this.#followDefaults(changed)).catch((error: unknown) => {\n const params: HostErrorParams = {\n code: isIgnifxError(error) ? error.code : null,\n message: clipHostText(`Following the new defaults of ${[...changed.keys()].join(\", \")}: ${messageOf(error)}`),\n data: { typeIds: [...changed.keys()] },\n };\n this.#notify(SceneNotification.hostError, params);\n });\n }\n const params = hotReloadedParamsOf(report);\n this.#notify(SceneNotification.hotReloaded, params);\n this.sendSchemas();\n }\n\n /**\n * Runs work that touches the document after everything queued before it.\n *\n * @param task - The work.\n * @returns What the task returns.\n */\n async #serial<T>(task: () => T | Promise<T>): Promise<T> {\n const run = this.#queue.then(task);\n this.#queue = run.catch(() => undefined);\n return run;\n }\n\n /**\n * The schemas, the host's own classes left out.\n *\n * @returns The set.\n */\n #schemas(): SchemaSet {\n return schemaSet(this.#requireApp(), new Set([EditorCamera.typeId, EditorCamera2D.typeId]));\n }\n\n /**\n * The app, once {@link SceneHost.prepare} has run.\n *\n * @returns The app.\n */\n #requireApp(): App {\n const app = this.#app;\n if (app === null) {\n throw new RpcFailure(RpcErrorCode.notReady, \"The scene view is still starting.\");\n }\n return app;\n }\n\n /**\n * The document mirror, once the app has started; otherwise the method answers `notReady`.\n *\n * @param method - The method being answered, for the message.\n * @returns The mirror.\n */\n #requireMirror(method: string): DocumentMirror {\n const mirror = this.#mirror;\n if (!this.#started || mirror === null) {\n throw new RpcFailure(\n RpcErrorCode.notReady,\n `The scene view is still starting; wait for schemasChanged before \"${method}\".`,\n );\n }\n return mirror;\n }\n\n /**\n * Refuses a method that needs an open document while none is open.\n *\n * @param method - The method being answered, for the message.\n */\n #requireOpen(method: string): void {\n if ((this.#mirror?.scene ?? null) === null) {\n throw new RpcFailure(RpcErrorCode.noScene, `No scene is open; send \"openScene\" before \"${method}\".`);\n }\n }\n}\n\n/**\n * Tells whether a render surface is a DOM canvas, which pointer events and Lite's gizmo dispatcher need.\n *\n * @param surface - The surface.\n * @returns True for an `HTMLCanvasElement`.\n */\nfunction isDomCanvas(surface: RenderSurface): surface is HTMLCanvasElement {\n return typeof HTMLCanvasElement !== \"undefined\" && surface instanceof HTMLCanvasElement;\n}\n","/**\n * The scene view's host: the app the editor looks at, built from the project's own `@ignifx/core`,\n * and the channel the editor drives it through.\n */\n\nimport { createApp, VERSION } from \"@ignifx/core\";\nimport { checkChannelOptions, openChannel, resolveMessageTarget } from \"./channel.js\";\nimport { HostCapability, HostKind, PROTOCOL_VERSION } from \"./protocol/index.js\";\nimport { SceneHost } from \"./scene/scene-host.js\";\nimport type { Channel, EditorMessageTarget } from \"./channel.js\";\nimport type { EditorAssetChange } from \"./scene/asset-reload.js\";\nimport type {\n App,\n AssetsCreateOptions,\n ConcreteComponentType,\n CreateAppOptions,\n Extension,\n RenderSurface,\n SceneInstance,\n SettingsInput,\n} from \"@ignifx/core\";\n\n/**\n * Options accepted by {@link startEditorHost}. The app options are the ones the project's `main.ts`\n * passes to `createApp`; the editor host's Vite plugin generates the call that supplies them.\n *\n * @beta\n */\nexport interface EditorHostOptions {\n /**\n * The origin the editor is served from, for example `\"ignifx-editor://app\"`. A port posted from any\n * other origin is ignored.\n */\n readonly editorOrigin: string;\n /** Which view this host runs. Only `\"scene\"` exists in this release. Defaults to `\"scene\"`. */\n readonly hostKind?: typeof HostKind.scene;\n /** The canvas to render into. Without one the app is headless. */\n readonly canvas?: RenderSurface;\n /** Run on Babylon Lite's null engine. Defaults to `true` when there is no `canvas`. */\n readonly headless?: boolean;\n /**\n * Build the app in edit mode (`createApp({ editMode })`, ADR-0028), so the scene view shows the\n * scene without playing it: only scripts whose class sets `static runInEditMode = true` get\n * callbacks, and physics and other game-clock systems hold or skip. Defaults to `true`; pass\n * `false` to run the scene view as a game.\n */\n readonly editMode?: boolean;\n /** The project's extensions, in the order its `main.ts` registers them. */\n readonly extensions?: readonly Extension[];\n /** The project's component classes, registered with `app.registerComponents`. */\n readonly scripts?: readonly ConcreteComponentType[];\n /** Project settings, as `ignifx.config.ts` supplies them (`import.meta.env.IGNIFX_CONFIG`). */\n readonly settings?: SettingsInput;\n /** The asset manifest and `fetch`, as the project's `main.ts` passes them. */\n readonly assets?: AssetsCreateOptions;\n /** A scene address to load before the app starts, through the normal loader. Defaults to none. */\n readonly bootScene?: string | null;\n /**\n * The project's `@ignifx/core` version, reported in `ready`. Used only while core's own\n * `VERSION` is the unstamped `\"0.0.0\"`; the Vite plugin reads it from the project's installed\n * `@ignifx/core/package.json`.\n */\n readonly engineVersion?: string;\n /** Milliseconds between heartbeats once the editor has said `hello`. Defaults to `1000`. */\n readonly heartbeatIntervalMs?: number;\n /** Where the editor's connect message arrives. Defaults to the page's `window`. */\n readonly messageTarget?: EditorMessageTarget;\n}\n\n/**\n * A running scene-view host. The host owns its app: disposing the host disposes the app.\n *\n * @beta\n */\nexport interface EditorHost {\n /** The app the scene view shows. */\n readonly app: App;\n /** The instance of `bootScene`, or `null` when none was given. */\n readonly bootScene: SceneInstance | null;\n /**\n * The persistent scene instance named `editor` that holds the host's own objects, such as the\n * editor camera. It survives every scene the editor opens and is never part of the document.\n */\n readonly editorScene: SceneInstance;\n /** The engine version the host reports in `ready`. */\n readonly engineVersion: string;\n /** Whether the editor has handed the host a port that is still open. */\n readonly isConnected: boolean;\n /**\n * Reloads an asset that changed on disk, in place, through `app.assets.reload`. The generated\n * scene-view module calls it on every `ignifx:asset-changed` event.\n *\n * @remarks\n * Only an asset the app has loaded is reloaded, and only one of the types the renderers follow:\n * a scene or prefab, whose instances in the open document are then rebuilt from the new file with\n * their uids, transforms and overrides, or a model, mesh, material, sprite atlas or shader, which\n * the renderers pick up on their next frame. A texture, a removed file and the open document's\n * own file are left alone. Once the new value is in, the host sends `assetReloaded` with the\n * address, the type and the rebuilt instance roots, so the editor can compare its document with\n * the view instead of reloading it.\n *\n * @param change - The address and what happened to it.\n * @returns Whether the asset was reloaded; `false` when it was left alone or the reload failed,\n * which the app reports as an error (`hostError`).\n */\n assetChanged(change: EditorAssetChange): Promise<boolean>;\n /** Stops the heartbeat, closes the port, and disposes the app. Idempotent. */\n dispose(): void;\n /** Same as {@link EditorHost.dispose}, for `using`. */\n [Symbol.dispose](): void;\n}\n\n/** What core's `VERSION` reads when core runs from source; its build stamps the real number. */\nconst UNSTAMPED_VERSION = \"0.0.0\";\n\n/**\n * Chooses the engine version a host reports.\n *\n * @param fallback - The version the Vite plugin read from the project, if any.\n * @param coreVersion - Core's `VERSION`; a parameter only so tests can give an unstamped one.\n * @returns Core's `VERSION` when it is stamped, else the fallback, else `VERSION`.\n */\nexport function resolveEngineVersion(fallback: string | undefined, coreVersion: string = VERSION): string {\n if (coreVersion !== UNSTAMPED_VERSION) {\n return coreVersion;\n }\n return fallback ?? coreVersion;\n}\n\n/**\n * Starts the scene view's host: listens for the editor's port, creates the app from the project's\n * own `@ignifx/core` (in edit mode unless `editMode` is `false`), registers the project's scripts,\n * loads `bootScene` if one is given, starts the app, and serves the editor protocol's scene methods\n * (protocol 0.3, `docs/architecture/17-editor-host.md` §6).\n *\n * @remarks\n * The host answers `hello` with `ready` and `ping` with `\"pong\"` as soon as a port arrives, even\n * while the app is still being created; the scene methods answer `notReady` until the app has\n * started, and the host's first `schemasChanged` says they are accepted. It accepts a new port\n * whenever the editor sends one, closing the previous port.\n *\n * With a `canvas` the host draws Babylon Lite's gizmos and a selection outline in core's render\n * overlay (`app.renderer.openOverlay()`), answers `screenshot`, and has a 2D view mode\n * (`setViewMode`), which shows the sprites through an editor-owned `Camera2D` and picks them with\n * `app.twoD.pickAt` when the project registers `@ignifx/2d`. A headless host serves every method\n * that needs no GPU.\n *\n * @param options - The editor's origin and the project's app options.\n * @returns The running host, once the app has started.\n * @throws IgnifxError `IGX-1801` for a malformed `editorOrigin`, `IGX-1802` with no window and no\n * `messageTarget`, `IGX-1803` for a bad `heartbeatIntervalMs`. Whatever `createApp`, the scene\n * load, or `start` throws is rethrown after the channel is closed.\n *\n * @example\n * ```ts\n * import { startEditorHost } from \"@ignifx/editor-host\";\n *\n * const host = await startEditorHost({ editorOrigin: \"ignifx-editor://app\", canvas, extensions: [], scripts });\n * ```\n *\n * @beta\n */\nexport async function startEditorHost(options: EditorHostOptions): Promise<EditorHost> {\n const heartbeatIntervalMs = checkChannelOptions(options.editorOrigin, options.heartbeatIntervalMs);\n const engineVersion = resolveEngineVersion(options.engineVersion);\n const capabilities = hasGpuView(options)\n ? [\n HostCapability.heartbeat,\n HostCapability.gizmos,\n HostCapability.screenshot,\n HostCapability.viewMode2d,\n HostCapability.pick2d,\n HostCapability.logRelay,\n HostCapability.hotReloadDefaults,\n ]\n : [HostCapability.heartbeat, HostCapability.logRelay, HostCapability.hotReloadDefaults];\n let channel: Channel | null = null;\n const scene = new SceneHost({\n capabilities,\n notify: (method, params) => {\n channel?.notify(method, params);\n },\n });\n // The channel opens before the first `await`, so a port posted while the app is created is kept.\n const opened = openChannel({\n target: resolveMessageTarget(options.messageTarget),\n editorOrigin: options.editorOrigin,\n ready: {\n engineVersion,\n protocol: PROTOCOL_VERSION,\n capabilities,\n hostKind: options.hostKind ?? HostKind.scene,\n },\n methods: scene.methods,\n heartbeatIntervalMs,\n onReady: () => {\n scene.sendSchemas();\n },\n });\n channel = opened;\n\n let app: App | null = null;\n let bootScene: SceneInstance | null = null;\n try {\n app = await createApp(appOptions(options));\n app.registerComponents(options.scripts ?? []);\n scene.prepare(app);\n // Loaded before `start()`, so the load settles without frames being pumped.\n if (options.bootScene !== undefined && options.bootScene !== null) {\n bootScene = await app.world.loadScene(options.bootScene);\n }\n await app.start();\n await scene.start(options.canvas ?? null);\n } catch (error) {\n scene.dispose();\n opened.dispose();\n app?.dispose();\n throw error;\n }\n\n const started = app;\n const editorScene = scene.editorScene ?? started.world.activeScene;\n const dispose = (): void => {\n scene.dispose();\n opened.dispose();\n started.dispose();\n };\n return {\n app: started,\n bootScene,\n editorScene,\n engineVersion,\n get isConnected(): boolean {\n return opened.isConnected;\n },\n assetChanged: async (change: EditorAssetChange): Promise<boolean> => scene.assetChanged(change),\n dispose,\n [Symbol.dispose]: dispose,\n };\n}\n\n/**\n * Tells whether a host renders: it has a canvas and is not forced headless.\n *\n * @param options - The host options.\n * @returns True when the view draws gizmos and can be captured.\n */\nfunction hasGpuView(options: EditorHostOptions): boolean {\n return options.canvas !== undefined && options.headless !== true;\n}\n\n/**\n * Picks the `createApp` options out of the host options, leaving out the ones that were not given.\n *\n * @param options - The host options.\n * @returns The app options.\n */\nfunction appOptions(options: EditorHostOptions): CreateAppOptions {\n return {\n editMode: options.editMode ?? true,\n ...(options.canvas === undefined ? {} : { canvas: options.canvas }),\n ...(options.headless === undefined ? {} : { headless: options.headless }),\n ...(options.extensions === undefined ? {} : { extensions: options.extensions }),\n ...(options.settings === undefined ? {} : { settings: options.settings }),\n ...(options.assets === undefined ? {} : { assets: options.assets }),\n };\n}\n","/**\n * The play view's controls: the project's own game page, reached by the editor through the app the\n * game's `main.ts` hands to `attachEditorPlayControls(app)` from `virtual:ignifx/editor`.\n */\n\nimport { hotReloadedParamsOf, relayAppReports } from \"./app-reports.js\";\nimport {\n checkChannelOptions,\n connectPortOf,\n InvalidParamsError,\n openChannel,\n Reply,\n resolveMessageTarget,\n} from \"./channel.js\";\nimport { resolveEngineVersion } from \"./host.js\";\nimport { PlayStatsReader } from \"./play-stats.js\";\nimport {\n HostCapability,\n HostKind,\n PlayMethod,\n PlayNotification,\n PlayPhase,\n PROTOCOL_VERSION,\n} from \"./protocol/index.js\";\nimport type { EditorMessageTarget, RequestHandler } from \"./channel.js\";\nimport type { PlayState, PlayStateReport, PlayStats } from \"./protocol/index.js\";\nimport type { App } from \"@ignifx/core\";\n\n/**\n * Options accepted by {@link startEditorPlayControls}.\n *\n * @beta\n */\nexport interface EditorPlayControlsOptions {\n /** The origin the editor is served from; a port posted from any other origin is ignored. */\n readonly editorOrigin: string;\n /** The project's `@ignifx/core` version, reported in `ready` while core's `VERSION` is unstamped. */\n readonly engineVersion?: string;\n /** Milliseconds between heartbeats once the editor has said `hello`. Defaults to `1000`. */\n readonly heartbeatIntervalMs?: number;\n /** Where the editor's connect message arrives. Defaults to the page's `window`. */\n readonly messageTarget?: EditorMessageTarget;\n}\n\n/**\n * The play view's side of an editor channel. The game keeps its app; the controls only drive it.\n *\n * @beta\n */\nexport interface EditorPlayControls {\n /** Whether the editor has handed the page a port that is still open. */\n readonly isConnected: boolean;\n /** Stops the heartbeat and closes the port. The app is left as it is. Idempotent. */\n dispose(): void;\n /** Same as {@link EditorPlayControls.dispose}, for `using`. */\n [Symbol.dispose](): void;\n}\n\n/**\n * A play view whose page listens for the editor's port before the game's app exists, so the\n * editor's first connect message is kept rather than lost.\n *\n * @beta\n */\nexport interface EditorPlayConnector {\n /** Whether a port has arrived and waits for {@link EditorPlayConnector.attach}. */\n readonly hasPendingPort: boolean;\n /**\n * Starts the play controls for the game's app on the port that has arrived, if any, and from\n * then on on every new one. Only the first call takes the waiting port; a later call, or one after\n * `dispose`, opens controls that wait for the editor's next port.\n *\n * @param app - The game's app. The controls never dispose it.\n * @returns The controls.\n */\n attach(app: App): EditorPlayControls;\n /** Stops listening, closes a waiting port, and disposes the controls it attached. Idempotent. */\n dispose(): void;\n /** Same as {@link EditorPlayConnector.dispose}, for `using`. */\n [Symbol.dispose](): void;\n}\n\n/**\n * How many reports the play view keeps while no editor has said `hello`; older ones are dropped.\n */\nconst EARLY_REPORT_LIMIT = 256;\n\n/** One report waiting for the handshake. */\ninterface EarlyReport {\n /** The notification's method. */\n readonly method: string;\n /** Its parameters. */\n readonly params: unknown;\n}\n\n/**\n * Sends the game's log lines, error reports and hot reloads to the editor, keeping the newest\n * {@link EARLY_REPORT_LIMIT} while no handshake has completed and sending them once one has.\n *\n * @param app - The game's app.\n * @param channel - The channel, read when a report arrives.\n * @returns A function that sends what was kept, for the handshake, and one that stops following.\n */\nfunction relayPlayReports(\n app: App,\n channel: () => { readonly isReady: boolean; notify(method: string, params?: unknown): void },\n): { readonly flush: () => void; readonly dispose: () => void } {\n const early: EarlyReport[] = [];\n const send = (method: string, params: unknown): void => {\n const current = channel();\n if (current.isReady) {\n current.notify(method, params);\n return;\n }\n early.push({ method, params });\n if (early.length > EARLY_REPORT_LIMIT) {\n early.shift();\n }\n };\n const dispose = relayAppReports(app, {\n log: (params): void => {\n send(PlayNotification.log, params);\n },\n error: (params): void => {\n send(PlayNotification.hostError, params);\n },\n hotReloaded: (report): void => {\n send(PlayNotification.hotReloaded, hotReloadedParamsOf(report));\n },\n });\n const flush = (): void => {\n const current = channel();\n for (const report of early.splice(0)) {\n current.notify(report.method, report.params);\n }\n };\n return { flush, dispose };\n}\n\n/**\n * Reads the game's state for a reply.\n *\n * @param app - The game's app.\n * @returns The state `play`, `pause`, `step` and `stop` answer with.\n */\nfunction playState(app: App): PlayState {\n return { isRunning: app.isRunning, isPaused: app.time.paused, frameCount: app.time.frameCount };\n}\n\n/**\n * Tells whether the game plays, is paused, or is stopped.\n *\n * @param app - The game's app.\n * @param isStopped - Whether the last control that stopped the loop was `stop`.\n * @returns The phase.\n */\nfunction playPhase(app: App, isStopped: boolean): PlayPhase {\n if (app.isRunning) {\n return app.time.paused ? PlayPhase.paused : PlayPhase.playing;\n }\n // A stepped game has no loop but sits paused on its frame; a stopped one is stopped, paused or not.\n return app.time.paused && !isStopped ? PlayPhase.paused : PlayPhase.stopped;\n}\n\n/**\n * Reads the frame delta of a `step` request.\n *\n * @param app - The game's app, whose fixed step is the default.\n * @param params - The received `params`.\n * @returns The delta in seconds.\n * @throws InvalidParamsError when `deltaSeconds` is present and not a positive finite number.\n */\nfunction stepDelta(app: App, params: unknown): number {\n if (typeof params !== \"object\" || params === null || !(\"deltaSeconds\" in params)) {\n return app.time.fixedDeltaTime;\n }\n const delta = params.deltaSeconds;\n if (typeof delta !== \"number\" || !Number.isFinite(delta) || delta <= 0) {\n throw new InvalidParamsError(\"step needs deltaSeconds to be a positive number of seconds.\");\n }\n return delta;\n}\n\n/**\n * Builds the play methods for one app.\n *\n * @param app - The game's app.\n * @param tracker - Reads the game's phase and reports its changes.\n * @returns The handlers, by method name.\n */\nfunction playMethods(app: App, tracker: PhaseTracker): ReadonlyMap<string, RequestHandler> {\n // Every control answers first, then reports the change it made, in that order on the port.\n const answer = (): Reply => new Reply(playState(app), tracker.report);\n const stats = new PlayStatsReader(app);\n return new Map<string, RequestHandler>([\n [\n PlayMethod.play,\n async (): Promise<Reply> => {\n tracker.isStopped = false;\n app.time.paused = false;\n await app.start();\n return answer();\n },\n ],\n [\n PlayMethod.pause,\n (): Reply => {\n app.time.paused = true;\n return answer();\n },\n ],\n [\n PlayMethod.step,\n (params): Reply => {\n const delta = stepDelta(app, params);\n // `app.step()` refuses to run beside the render loop, so stepping stops it first.\n app.stop();\n tracker.isStopped = false;\n app.time.paused = false;\n app.step(delta);\n app.time.paused = true;\n return answer();\n },\n ],\n [\n PlayMethod.stop,\n (): Reply => {\n app.stop();\n tracker.isStopped = true;\n return answer();\n },\n ],\n [PlayMethod.playState, (): PlayStateReport => tracker.read()],\n [PlayMethod.playStats, (): PlayStats => stats.read()],\n ]);\n}\n\n/** Reads the game's phase and sends `playStateChanged` when it differs from the last one sent. */\ninterface PhaseTracker {\n /** Whether the last control that stopped the loop was `stop` rather than `step`. */\n isStopped: boolean;\n /** Reads the game's state as `playState` answers it. */\n readonly read: () => PlayStateReport;\n /** Sends `playStateChanged` when the phase changed since the editor last saw it. */\n readonly report: () => void;\n /** Takes the current phase as the one the editor knows, after a handshake. */\n readonly reset: () => void;\n}\n\n/**\n * The options every play view checks before it opens a channel.\n *\n * @param options - The options as given.\n * @returns The heartbeat period and the message target.\n */\nfunction checkPlayOptions(options: EditorPlayControlsOptions): {\n heartbeatIntervalMs: number;\n target: EditorMessageTarget;\n} {\n const heartbeatIntervalMs = checkChannelOptions(options.editorOrigin, options.heartbeatIntervalMs);\n return { heartbeatIntervalMs, target: resolveMessageTarget(options.messageTarget) };\n}\n\n/**\n * Opens the play controls' channel.\n *\n * @param app - The game's app.\n * @param options - The editor's origin and the reporting options.\n * @param target - Where the connect message arrives.\n * @param heartbeatIntervalMs - The heartbeat period, which is also how often a change the game\n * makes itself is looked for.\n * @param port - A port that arrived before the app existed, or `null`.\n * @returns The controls.\n */\nfunction openPlayControls(\n app: App,\n options: EditorPlayControlsOptions,\n target: EditorMessageTarget,\n heartbeatIntervalMs: number,\n port: MessagePort | null,\n): EditorPlayControls {\n let lastPhase: PlayPhase | null = null;\n const tracker: PhaseTracker = {\n isStopped: false,\n read: (): PlayStateReport => ({\n state: playPhase(app, tracker.isStopped),\n frameCount: app.time.frameCount,\n time: app.time.time,\n }),\n report: (): void => {\n if (!channel.isReady) {\n return;\n }\n const report = tracker.read();\n if (report.state !== lastPhase) {\n lastPhase = report.state;\n channel.notify(PlayNotification.playStateChanged, report);\n }\n },\n reset: (): void => {\n lastPhase = playPhase(app, tracker.isStopped);\n },\n };\n const channel = openChannel({\n target,\n editorOrigin: options.editorOrigin,\n ready: {\n engineVersion: resolveEngineVersion(options.engineVersion),\n protocol: PROTOCOL_VERSION,\n capabilities: [HostCapability.heartbeat, HostCapability.playControls, HostCapability.logRelay],\n hostKind: HostKind.play,\n },\n methods: playMethods(app, tracker),\n heartbeatIntervalMs,\n onReady: (): void => {\n tracker.reset();\n reports.flush();\n },\n port,\n });\n const reports = relayPlayReports(app, () => channel);\n // The game can pause, stop or start itself; nothing in core announces it, so the controls look.\n const watch = setInterval(tracker.report, heartbeatIntervalMs);\n const dispose = (): void => {\n clearInterval(watch);\n reports.dispose();\n channel.dispose();\n };\n return {\n get isConnected(): boolean {\n return channel.isConnected;\n },\n dispose,\n [Symbol.dispose]: dispose,\n };\n}\n\n/**\n * Lets the editor drive a running game: answers the handshake with `hostKind: \"play\"`, then `play`,\n * `pause`, `step`, `stop`, `playState` and `playStats`, and sends `playStateChanged` when the game's phase\n * changes, and `log`, `hostError` and `hotReloaded` for the game's log lines, `app.onError` reports\n * and hot reloads (the newest 256 from before the handshake right after it).\n *\n * @remarks\n * A game does not call this directly. It calls `attachEditorPlayControls(app)` from\n * `virtual:ignifx/editor`, which the editor host's Vite plugin serves: in `vite dev` that module\n * calls this function, and in a production build it is an empty function, so no editor code ships.\n *\n * @param app - The game's app. The controls never dispose it.\n * @param options - The editor's origin and the reporting options.\n * @returns The controls; dispose them to stop listening.\n * @throws IgnifxError `IGX-1801` for a malformed `editorOrigin`, `IGX-1802` with no window and no\n * `messageTarget`, `IGX-1803` for a bad `heartbeatIntervalMs`.\n *\n * @example\n * ```ts\n * const controls = startEditorPlayControls(app, { editorOrigin: \"ignifx-editor://app\" });\n * controls.dispose();\n * ```\n *\n * @beta\n */\nexport function startEditorPlayControls(app: App, options: EditorPlayControlsOptions): EditorPlayControls {\n const { heartbeatIntervalMs, target } = checkPlayOptions(options);\n return openPlayControls(app, options, target, heartbeatIntervalMs, null);\n}\n\n/**\n * Listens for the editor's connect message before the game's app exists, and keeps the newest port\n * until {@link EditorPlayConnector.attach} hands it the app.\n *\n * @remarks\n * The editor posts its port on the play view's `load` event, which can fire while the game's\n * `main.ts` still awaits `createApp`. `virtual:ignifx/editor` calls this when the module is\n * evaluated, which is before `main.ts` runs, and `attachEditorPlayControls(app)` calls `attach`, so\n * the handshake runs on the port the editor sent first. A port is accepted only from exactly\n * `editorOrigin`; a newer one replaces and closes the one waiting. Nothing is read from the port\n * before `attach`: the editor's `hello` waits in it.\n *\n * @param options - The editor's origin and the reporting options.\n * @returns The connector; dispose it to stop listening.\n * @throws IgnifxError `IGX-1801` for a malformed `editorOrigin`, `IGX-1802` with no window and no\n * `messageTarget`, `IGX-1803` for a bad `heartbeatIntervalMs`.\n *\n * @example\n * ```ts\n * const connector = listenForEditorPlayControls({ editorOrigin: \"ignifx-editor://app\" });\n * const app = await createApp({ headless: true });\n * const controls = connector.attach(app);\n * connector.dispose();\n * ```\n *\n * @beta\n */\nexport function listenForEditorPlayControls(options: EditorPlayControlsOptions): EditorPlayConnector {\n const { heartbeatIntervalMs, target } = checkPlayOptions(options);\n const attached: EditorPlayControls[] = [];\n let pending: MessagePort | null = null;\n let isListening = true;\n let isDisposed = false;\n\n const onWindowMessage = (event: Event): void => {\n const port = connectPortOf(event, options.editorOrigin);\n if (port !== null) {\n pending?.close();\n pending = port;\n }\n };\n const stopListening = (): void => {\n if (isListening) {\n isListening = false;\n target.removeEventListener(\"message\", onWindowMessage);\n }\n };\n target.addEventListener(\"message\", onWindowMessage);\n\n const dispose = (): void => {\n if (isDisposed) {\n return;\n }\n isDisposed = true;\n stopListening();\n pending?.close();\n pending = null;\n for (const controls of attached.splice(0)) {\n controls.dispose();\n }\n };\n return {\n get hasPendingPort(): boolean {\n return pending !== null;\n },\n attach(app: App): EditorPlayControls {\n // The channel's own listener replaces this one in the same turn, so no message falls between.\n stopListening();\n const port = pending;\n pending = null;\n const controls = openPlayControls(app, options, target, heartbeatIntervalMs, port);\n if (!isDisposed) {\n attached.push(controls);\n }\n return controls;\n },\n dispose,\n [Symbol.dispose]: dispose,\n };\n}\n"],"mappings":";;;;;;;;;;;;;AAYA,MAAa,mBAAmB;;;;;;;;;;AAkBhC,MAAa,eAAe;;CAE1B,YAAY;;CAEZ,gBAAgB;;CAEhB,gBAAgB;;CAEhB,eAAe;;CAEf,eAAe;;CAEf,sBAAsB;;;;;CAKtB,UAAU;;CAEV,SAAS;AACX;;;;;;;;;;AAkHA,SAAgB,SAAS,OAAkD;CACzE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;;;;;;;AAQA,SAAS,QAAQ,OAAgC;CAC/C,OAAO,OAAO,UAAU,YAAa,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK;AACzF;;;;;;;AAQA,SAAS,WAAW,OAAmC;CACrD,OACE,SAAS,KAAK,KACd,OAAO,OAAO,YAAY,CAAC,CAAC,MAAM,SAAS,SAAS,MAAM,OAAO,KACjE,OAAO,MAAM,eAAe;AAEhC;;;;;;;;;;AAWA,SAAgB,aAAa,OAAqC;CAChE,IAAI,CAAC,SAAS,KAAK,KAAK,MAAM,eAAA,OAC5B,OAAO;CAET,IAAI,Y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