@motionscript/core 0.3.0 → 0.4.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/CHANGELOG.md +16 -0
- package/dist/browser/chunks/{chunk-65DNLAPH.js → chunk-LJSYPGYX.js} +2 -2
- package/dist/browser/chunks/chunk-LJSYPGYX.js.map +7 -0
- package/dist/browser/index.js +1 -1
- package/dist/browser/manifest.json +1 -1
- package/dist/browser/sdk.js +1 -1
- package/dist/document/registry.d.ts.map +1 -1
- package/dist/document/registry.js +5 -4
- package/dist/document/registry.js.map +1 -1
- package/package.json +1 -1
- package/dist/browser/chunks/chunk-65DNLAPH.js.map +0 -7
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../../../src/attributes/audio/schedule.ts", "../../../src/attributes/audio/sound.ts", "../../../src/attributes/audio/effects/union.ts", "../../../src/attributes/audio/transition.ts", "../../../src/attributes/audio/request.ts", "../../../src/attributes/shape/shaders/pack.ts", "../../../src/project/tree.ts", "../../../src/components/trees/node/node-walk.ts", "../../../src/components/trees/node/node-editor-state.ts", "../../../src/components/trees/root/canvas2d-node.ts", "../../../src/components/builtins/geometry/geometry.ts", "../../../src/components/builtins/geometry/composite.ts", "../../../src/components/builtins/layout/layout.ts", "../../../src/components/builtins/text/text.ts", "../../../src/components/builtins/providers/providers.ts", "../../../src/components/builtins/audio/audio.ts", "../../../src/components/builtins/media/media.ts", "../../../src/render3d/camera.ts", "../../../src/components/builtins/three/three.ts", "../../../src/components/builtins/three/canvas3d.ts", "../../../src/document/types.ts", "../../../src/document/project.ts", "../../../src/document/migrate.ts", "../../../src/document/validate.ts", "../../../src/document/missing-node.ts", "../../../src/document/vocabulary.ts", "../../../src/document/builtins.ts", "../../../src/document/deny-globals.ts", "../../../src/document/registry.ts", "../../../src/document/placement.ts", "../../../src/document/audio.ts", "../../../src/document/command-traits.ts", "../../../src/document/diff.ts", "../../../src/document/expression/refs.ts", "../../../src/document/doc-index.ts", "../../../src/document/settled-index.ts", "../../../src/document/timeline-patch.ts", "../../../src/document/timeline.ts", "../../../src/render/descriptors/richtext.ts", "../../../src/render/descriptors/path.ts", "../../../src/render/text-layout.ts", "../../../src/render/render-issue.ts", "../../../src/render3d/builders.ts", "../../../src/render3d/segments.ts", "../../../src/render3d/rounded-box.ts", "../../../src/render3d/transform.ts", "../../../src/render3d/geometry.ts", "../../../src/render3d/matrix4.ts", "../../../src/render3d/bounds3d.ts", "../../../src/render3d/material.ts", "../../../src/assets/manager.ts", "../../../src/assets/scope.ts", "../../../src/util/scheduler.ts", "../../../src/runtime/frame-time.ts", "../../../src/runtime/placement.ts", "../../../src/runtime/clip-instance.ts", "../../../src/assets/asset-index.ts", "../../../src/runtime/asset-refine.ts", "../../../src/runtime/asset-update.ts", "../../../src/runtime/audio-index.ts", "../../../src/runtime/clip-store.ts", "../../../src/runtime/state-evaluator.ts", "../../../src/runtime/settle.ts", "../../../src/runtime/project-assets.ts", "../../../src/runtime/asset-timeline.ts", "../../../src/runtime/node-picking3d.ts", "../../../src/runtime/node-picking.ts", "../../../src/runtime/text-geometry.ts", "../../../src/runtime/playback-controller.ts", "../../../src/assets/catalog.ts", "../../../src/runtime/playback.ts", "../../../src/platform/ticker.ts", "../../../src/platform/stepped-clock.ts", "../../../src/runtime/session.ts", "../../../src/util/csv.ts", "../../../src/util/deprecate.ts", "../../../src/util/generateList.ts", "../../../src/util/reference.ts", "../../../src/util/random.ts", "../../../src/tween/stepper.ts"],
|
|
4
|
-
"sourcesContent": ["import type { AssetCatalog } from \"@/assets/catalog\";\nimport { resolveAudioEffects, type AudioEffectsInput } from \"./effects/chain\";\nimport { integrateSpeedToClipTime, isRamp, sourceTimeAtClipElapsed, staticValue, type Param } from \"./ramp\";\nimport type { AudioTransition } from \"./transition\";\nimport type { AudioBusStop, AudioRequest } from \"./request\";\n\n/** One clip a command's sound plays, in its clip's seconds. */\nexport interface AudioClip {\n src: string;\n at?: number;\n /** When it is cut, however much of it is left. */\n until?: number;\n /** In-point inside the source, in seconds. */\n trimStart?: number;\n /** Out-point inside the source. Absent plays to the source's end. */\n trimEnd?: number;\n loop?: boolean;\n volume?: Param;\n /** Playback rate; a ramp runs over source seconds after `trimStart`. */\n speed?: Param;\n effects?: AudioEffectsInput;\n transitionIn?: AudioTransition;\n transitionOut?: AudioTransition;\n /** Source-adjacent first — see {@link AudioRequest.bus}. */\n bus?: readonly AudioBusStop[];\n /** Sound nobody asked for by name — see {@link AudioRequest.optional}. */\n optional?: boolean;\n}\n\nfunction scalarSpeed(speed: number): number {\n return Number.isFinite(speed) && speed > 0 ? speed : 1;\n}\n\n/** Clip seconds spent playing the first `sourceElapsed` of `sourceLength` source seconds at `speed`; must match the device's `playbackRate` schedule or a request ends before or after its sound. */\nexport function clipTimeAtSource(speed: Param, sourceLength: number, sourceElapsed: number = sourceLength): number {\n if (isRamp(speed)) return integrateSpeedToClipTime(speed, sourceLength, sourceElapsed);\n return Math.max(0, Math.min(sourceElapsed, sourceLength)) / scalarSpeed(speed);\n}\n\n/** Inverse of {@link clipTimeAtSource}: the source seconds reached `clipElapsed` clip seconds in. */\nexport function sourceTimeAtClip(speed: Param, sourceLength: number, clipElapsed: number): number {\n if (isRamp(speed)) return sourceTimeAtClipElapsed(speed, sourceLength, clipElapsed);\n return Math.max(0, Math.min(sourceLength, clipElapsed * scalarSpeed(speed)));\n}\n\n/** How long a clip lasts on the timeline: its trimmed source at its speed. `trimEnd` absent plays to `mediaDuration`. */\nexport function clipDurationOf(clip: { readonly trimStart?: number; readonly trimEnd?: number; readonly speed?: Param }, mediaDuration: number): number {\n const length = Math.max(0, (clip.trimEnd ?? mediaDuration) - (clip.trimStart ?? 0));\n return clipTimeAtSource(clip.speed ?? 1, length);\n}\n\n/** The request `clip` schedules: bounded with an end (a trim or `until`), **open** otherwise so a bed nothing cuts continues across later tracks (see `AudioRequest.open`). */\nexport function requestOf(clip: AudioClip, catalog: AssetCatalog, ownerKey: string, n: number): AudioRequest {\n const at = clip.at ?? 0;\n const until = clip.until ?? Infinity;\n const trimStart = clip.trimStart ?? 0;\n const trimEnd = clip.trimEnd ?? Infinity;\n const loop = clip.loop ?? false;\n const effects = resolveAudioEffects(clip.effects);\n // Read even when the length goes unused: a missing file throws here, as a\n // build error, rather than playing silence.\n const mediaDuration = catalog.getMediaDuration(clip.src);\n\n let speed = clip.speed ?? 1;\n if (loop && isRamp(speed)) {\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(`[motionscript] A speed ramp on a looping clip (${clip.src}) has no one source axis to run over; it plays at its start value.`);\n }\n speed = staticValue(speed, 1);\n }\n const sourceLength = Math.max(0, (Number.isFinite(trimEnd) ? trimEnd : mediaDuration) - trimStart);\n\n const request: AudioRequest = {\n id: `${ownerKey}|${clip.src}|${at}|${n}`,\n src: clip.src,\n startAt: at,\n endAt: Infinity,\n trimStart,\n volume: clip.volume ?? 1,\n speed,\n loop,\n ownerId: ownerKey,\n };\n if (isRamp(speed)) request.sourceLength = sourceLength;\n if (effects.length > 0) request.effects = effects;\n if (clip.transitionIn) request.transitionIn = clip.transitionIn;\n if (clip.transitionOut) request.transitionOut = clip.transitionOut;\n if (clip.bus) request.bus = clip.bus;\n if (clip.optional) request.optional = true;\n\n // A loop repeats the trimmed region, so a `trimEnd` bounds one pass and says\n // nothing about when the clip stops: only a cut (`until`) ends it, and with\n // none it runs open to the project end like any other bed.\n if (loop && trimEnd > trimStart && Number.isFinite(trimEnd)) request.trimEnd = trimEnd;\n\n if (loop && Number.isFinite(until)) {\n request.endAt = until;\n } else if (loop) {\n request.open = true;\n } else if (Number.isFinite(trimEnd)) {\n request.endAt = Math.min(until, at + clipTimeAtSource(speed, sourceLength));\n } else {\n const natural = clipTimeAtSource(speed, sourceLength);\n if (Number.isFinite(until)) {\n request.endAt = Math.min(until, at + natural);\n } else {\n request.open = true;\n request.mediaDuration = natural;\n }\n }\n return request;\n}\n", "import type { AudioEffect } from \"@/attributes/audio/effects/union\";\nimport { type AudioEffectsInput, resolveAudioEffects } from \"@/attributes/audio/effects/chain\";\nimport type { Param } from \"@/attributes/audio/ramp\";\nimport { clipTimeAtSource } from \"@/attributes/audio/schedule\";\n\ninterface SoundPropsBase {\n src: string;\n volume?: Param;\n /** Playback rate; a ramp runs over source seconds after `trimStart`. */\n speed?: Param;\n loop?: boolean;\n /** Audio effects applied to the clip (gain, eq, tremolo, echo). */\n effects?: AudioEffectsInput;\n}\n\n/** Author-facing sound props with two mutually exclusive bounds: `{ trimStart?, trimEnd? }` (explicit in/out points into the source) or `{ duration? }` (sugar for `trimStart: 0, trimEnd: duration`). With neither `trimEnd` nor `duration` the clip runs to the source's full length (from the asset catalog); `trimStart` defaults to 0. */\nexport type SoundProps =\n | (SoundPropsBase & { trimStart?: number; trimEnd?: number; duration?: undefined })\n | (SoundPropsBase & { duration?: number; trimStart?: undefined; trimEnd?: undefined });\n\n/** A clip's resolved props and how long it runs; what a node plays is declared through `declareAudio`, this is only the arithmetic over one clip. */\nexport class Sound {\n readonly src: string;\n volume: Param;\n speed: Param;\n loop: boolean;\n trimStart: number;\n trimEnd: number;\n effects: AudioEffect[];\n\n constructor(props: SoundProps) {\n this.src = props.src;\n this.volume = props.volume ?? 1;\n this.speed = props.speed ?? 1;\n this.loop = props.loop ?? false;\n this.trimStart = props.trimStart ?? 0;\n this.trimEnd = props.trimEnd ?? props.duration ?? Infinity;\n this.effects = resolveAudioEffects(props.effects);\n }\n\n /** Clip seconds `trimmedSourceLength` source seconds take at this clip's speed. */\n clipDurationFor(trimmedSourceLength: number): number {\n return clipTimeAtSource(this.speed, trimmedSourceLength);\n }\n\n /** Clip seconds, speed profile applied; `undefined` when nothing bounds the clip. */\n get clipDuration(): number | undefined {\n return this.trimEnd !== Infinity\n ? this.clipDurationFor(this.trimEnd - this.trimStart)\n : undefined;\n }\n}\n", "import type { GainEffect } from \"./implementations/gain\";\nimport type { HighPassEffect } from \"./implementations/highpass\";\nimport type { LowPassEffect } from \"./implementations/lowpass\";\nimport type { TremoloEffect } from \"./implementations/tremolo\";\nimport type { EchoEffect } from \"./implementations/echo\";\nimport { paramKey } from \"../ramp\";\n\n/** Every concrete audio effect a sound or a bus can carry. */\nexport type AudioEffect =\n | GainEffect\n | HighPassEffect\n | LowPassEffect\n | TremoloEffect\n | EchoEffect;\n\n/**\n * Equal for two chains exactly when they sound the same. A device keys its\n * playback by it, so an edited effect tears down the stale source rather than\n * playing it until the next stop.\n */\nexport function effectsKey(effects: readonly AudioEffect[] | undefined): string {\n if (!effects || effects.length === 0) return \"\";\n return effects.map((f) => {\n switch (f.type) {\n case \"gain\":\n return `gain:${paramKey(f.value)}`;\n case \"highpass\":\n case \"lowpass\":\n return `${f.type}:${paramKey(f.frequency)}:${paramKey(f.q)}`;\n case \"tremolo\":\n return `tremolo:${paramKey(f.rate)}:${paramKey(f.depth)}`;\n case \"echo\":\n return `echo:${paramKey(f.delay)}:${paramKey(f.feedback)}:${paramKey(f.mix)}`;\n }\n }).join(\"|\");\n}\n", "import { easeOfSpec, type EaseSpec } from \"@/tween/ease/spec\";\nimport type { EasingFunction } from \"@/tween/ease/type\";\n\n/** What happens as a clip enters (`transitionIn`) or leaves (`transitionOut`): a fade over its first or last `duration` clip seconds. A cross-fade is two overlapping clips, the first with a `transitionOut` and the second a `transitionIn` as long as the overlap; equal-power shapes are complementary, so the pair needs no link. */\nexport interface AudioTransition {\n readonly duration: number;\n /**\n * Progress through the transition (x, 0→1) to how far it has come (y, the\n * gain for a fade), read as entering; a `transitionOut` plays it backwards.\n * Default `\"equalPower\"`, sin(πx/2).\n */\n readonly curve?: \"equalPower\" | EaseSpec;\n}\n\nconst EQUAL_POWER: EasingFunction = (x) => Math.sin((Math.max(0, Math.min(1, x)) * Math.PI) / 2);\nconst shapes = new WeakMap<EaseSpec, EasingFunction>();\n\nfunction shapeOf(transition: AudioTransition): EasingFunction {\n const curve = transition.curve;\n if (curve === undefined || curve === \"equalPower\") return EQUAL_POWER;\n let shape = shapes.get(curve);\n if (!shape) shapes.set(curve, (shape = easeOfSpec(curve)));\n return shape;\n}\n\n/**\n * The two transitions' durations on a clip `length` seconds long: shrunk in\n * proportion when together they would overrun it.\n */\nexport function transitionSpans(length: number, transitionIn?: AudioTransition, transitionOut?: AudioTransition): { readonly in: number; readonly out: number } {\n const wanted = { in: Math.max(0, transitionIn?.duration ?? 0), out: Math.max(0, transitionOut?.duration ?? 0) };\n if (!Number.isFinite(length)) return { in: wanted.in, out: 0 };\n const total = wanted.in + wanted.out;\n if (total <= length || total === 0) return wanted;\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(`[motionscript] Transitions of ${total.toFixed(3)}s overrun a ${length.toFixed(3)}s clip; both are shortened to fit.`);\n }\n const scale = Math.max(0, length) / total;\n return { in: wanted.in * scale, out: wanted.out * scale };\n}\n\n/**\n * The gain the transitions put on a clip at `t` of its `length` seconds: 1\n * outside both. An open clip (`length` not finite) has no end to leave from.\n */\nexport function transitionGainAt(t: number, length: number, transitionIn?: AudioTransition, transitionOut?: AudioTransition): number {\n const spans = transitionSpans(length, transitionIn, transitionOut);\n let gain = 1;\n if (transitionIn && spans.in > 0 && t < spans.in) gain *= Math.max(0, shapeOf(transitionIn)(Math.max(0, t) / spans.in));\n if (transitionOut && spans.out > 0 && t > length - spans.out) gain *= Math.max(0, shapeOf(transitionOut)(Math.max(0, length - t) / spans.out));\n return gain;\n}\n\nexport function transitionKey(transition: AudioTransition | undefined): string {\n if (!transition) return \"_\";\n return `${transition.duration}:${typeof transition.curve === \"object\" ? JSON.stringify(transition.curve) : transition.curve ?? \"equalPower\"}`;\n}\n", "import { effectsKey, type AudioEffect } from \"@/attributes/audio/effects/union\";\nimport { paramKey, type Param } from \"@/attributes/audio/ramp\";\nimport { transitionKey, type AudioTransition } from \"@/attributes/audio/transition\";\n\n/** One bus a clip's signal passes through to the master: a flattened snapshot of an {@link AudioBus} node (core describes the graph, a platform builds it). {@link id} makes it a *bus* rather than per-clip processing: clips naming the same id share one live chain, so a bus reverb is one tail fed by both. */\nexport interface AudioBusStop {\n id: string;\n /** Linear gain. A {@link Param}, so a bus fade is a ramp rather than a per-frame write. */\n volume: Param;\n /** -1 hard left … +1 hard right. */\n pan: Param;\n mute: boolean;\n /** Applied in array order, index 0 closest to the source. */\n effects?: AudioEffect[];\n transitionIn?: AudioTransition;\n transitionOut?: AudioTransition;\n /** When the bus is present, in the same seconds as the request carrying the stop: what ramps in {@link volume} or {@link effects} (and their transitions) run over. Not the clip's span, because one bus feeds many clips and its fade must mean one thing to all. */\n startAt: number;\n endAt: number;\n}\n\n/** Everything about a stop that changes what passes through it, as a string, so a device can tell an edited bus from the one it built. */\nexport function busStopKey(stop: AudioBusStop): string {\n return `${stop.id}:${paramKey(stop.volume)}:${paramKey(stop.pan)}:${stop.mute ? 1 : 0}:${effectsKey(stop.effects)}:${transitionKey(stop.transitionIn)}:${transitionKey(stop.transitionOut)}:${stop.startAt}:${stop.endAt}`;\n}\n\nexport interface AudioRequest {\n id: string;\n src: string;\n\n /** The clip timestamp when the audio should START playing. */\n startAt: number; // in seconds\n\n /** The clip timestamp when the audio STOPS. Always a number: **`Infinity` is the open sentinel**, never null/undefined (an unstopped clip carries it until {@link open} resolution pins it to the project end). Test with `Number.isFinite(endAt)`; a `?? Infinity` guard is dead code. */\n endAt: number; // in seconds\n\n /** True when started and left running at its scene's end (neither stopped nor finite-trimmed). Open requests skip the per-scene audio clamp and **continue across scene boundaries**: `assembleTimeline` shifts them to absolute time and resolves `endAt = min(startAt + mediaDuration, projectTotalDuration)`. */\n open?: boolean;\n\n /** Source media length, carried on **open** requests so the cross-scene end resolves at assembly without re-reading the catalog. Ignored for bounded requests. */\n mediaDuration?: number;\n\n /** Offset in seconds to skip ahead in the audio file. Default: 0 */\n trimStart: number;\n\n /** Out-point inside the source in seconds, carried **only by a looping request that has one**: a device loops `[trimStart, trimEnd)` instead of the whole buffer. Otherwise {@link endAt} already ends playback there and this is absent. */\n trimEnd?: number;\n\n /** Linear gain over the clip's own seconds. Default 1. */\n volume: Param;\n /** Playback rate, default 1. A ramp runs over the first {@link sourceLength} source seconds after `trimStart`. */\n speed?: Param;\n /** The source seconds a speed ramp is placed on; carried only with one, so the device and the timeline place it alike. */\n sourceLength?: number;\n loop: boolean; // Default: false\n\n /** Audio effects applied in array order (index 0 closest to the source). */\n effects?: AudioEffect[];\n /** A gain over the clip's first and last seconds, on top of {@link volume}. */\n transitionIn?: AudioTransition;\n transitionOut?: AudioTransition;\n\n /** The buses this clip feeds, **source-adjacent first** like {@link effects}, so the chain reads in signal order: clip effects, each stop, then master. Absent goes straight to the master. */\n bus?: readonly AudioBusStop[];\n\n /** The owner key of the declaring node (its document row's id, plus the path below that row for a composite's node), so a timeline can draw the waveform on that node's bar. Never affects playback. */\n ownerId?: string;\n\n /** The sound of something that is also a picture (a video's own track): a source with no audio is silence for such a request, not a failure. Not part of the request's identity. */\n optional?: boolean;\n}", "import type { ShaderUniformRecord } from \"./uniforms\";\nimport type { ShaderLanguage } from \"./language\";\n\n/**\n * A **shader pack**: a program plus what a host may edit about it, the interchange format for a shader (authored as\n * JSON, handed to `Fills.shader` or `Effects.shader`). A bare source string says nothing about which uniforms are\n * editable, their panel names or ranges. **Two scopes, one shape**: a fill paints inside a shape's path and may\n * sample textures, an effect paints over a layer and may sample what is beneath it; as union arms,\n * `Fills.shader(anEffectShader)` is a compile error instead of a first-frame failure.\n */\nexport type Shader = FillShader | EffectShader;\n\nexport interface ShaderBase {\n /** Format tag, so a file that is not one of these can be told from one merely from a newer version. */\n $kind?: string;\n /** Provenance, when the pack came from a library row. **Not** how it is registered: `Registry.addShader` takes the key separately (as `addNode` does), so the file stays portable. */\n id?: string;\n name: string;\n description?: string;\n /** The language `source` is written in; normalising a pack stamps WGSL when absent. */\n language?: ShaderLanguage;\n /** The program. WGSL: a fill defines `fn fill(in: FillIn) -> vec4f`, an effect `fn effect(in: EffectIn) -> vec4f`; uniforms are the members of `struct Params`, which `properties` name in their `inputs`. */\n source: string;\n /** Uniform values the properties do not cover, by name. */\n uniforms?: ShaderUniformRecord;\n /** The editable values, by property id. */\n properties: Record<string, ShaderProperty>;\n}\n\nexport interface FillShader extends ShaderBase {\n scope: \"fill\";\n /** The images the program samples, by name; WGSL `sample_texture(uv)` samples the first. The applying fill supplies each `src`. */\n textures?: readonly { name: string; description?: string }[];\n}\n\nexport interface EffectShader extends ShaderBase {\n scope: \"effect\";\n /** Whether the program runs on the backdrop path (`sample_src` reads what is beneath the node). A fact about the **program**, not the instance, which keeps the cross-cutting `mode`; the builder defaults `mode` to `\"backdrop\"` from this and a caller may override. */\n backdrop?: boolean;\n}\n\nexport type ShaderProperty = KnownShaderProperty | UnknownShaderProperty;\n\nexport type KnownShaderProperty =\n | NumberProperty\n | SliderProperty\n | AngleProperty\n | HueProperty\n | BooleanProperty\n | ColorProperty\n | VectorProperty\n | PointProperty;\n\ninterface ShaderPropertyBase {\n name?: string;\n /** The uniform each of this property's components writes: one editable value may span several (a scalar names `value`; a point `value` for a `float2`, or `x` and `y` for two floats). */\n inputs: Record<string, string>;\n}\n\n/** A scalar, drawn as a number input. */\nexport interface NumberProperty extends ShaderPropertyBase {\n kind: \"number\";\n default: number;\n min?: number;\n max?: number;\n step?: number;\n}\n\n/** A scalar with a bounded range, drawn as a slider. */\nexport interface SliderProperty extends ShaderPropertyBase {\n kind: \"slider\";\n default: number;\n min: number;\n max: number;\n step?: number;\n}\n\n/** Degrees, matching every other angle in the library. */\nexport interface AngleProperty extends ShaderPropertyBase {\n kind: \"angle\";\n default: number;\n}\n\n/** Degrees around the colour wheel. */\nexport interface HueProperty extends ShaderPropertyBase {\n kind: \"hue\";\n default: number;\n}\n\n/** Written to its uniform as 1 or 0, since a `bool` cannot be a uniform member in WGSL. */\nexport interface BooleanProperty extends ShaderPropertyBase {\n kind: \"boolean\";\n default: boolean;\n}\n\n/** RGBA in 0–1. A CSS string is accepted and parsed, so theme tokens work. */\nexport interface ColorProperty extends ShaderPropertyBase {\n kind: \"color\";\n default: string | readonly number[];\n}\n\n/** A fixed-width run of floats. */\nexport interface VectorProperty extends ShaderPropertyBase {\n kind: \"vector\";\n default: readonly number[];\n}\n\n/** Two floats, as one `float2` or as separate `x`/`y` uniforms. */\nexport interface PointProperty extends ShaderPropertyBase {\n kind: \"point\";\n default: readonly number[] | { x: number; y: number };\n}\n\n/** A property whose kind this vocabulary version does not name. Open at the edges on purpose: a newer pack draws the controls a host knows and says so about the rest. Its `default` is still written to its `inputs`, so the shader renders correctly. */\nexport interface UnknownShaderProperty extends ShaderPropertyBase {\n kind: string;\n default?: unknown;\n [option: string]: unknown;\n}\n\nconst KNOWN_KINDS = new Set([\n \"number\", \"slider\", \"angle\", \"hue\", \"boolean\", \"color\", \"vector\", \"point\",\n]);\n\n/** Whether `property` is one this version knows how to draw. */\nexport function isKnownShaderProperty(property: ShaderProperty): property is KnownShaderProperty {\n return KNOWN_KINDS.has(property.kind);\n}\n\n/** Ceiling on properties in one pack, so a malformed import cannot exhaust a host. */\nexport const MAX_SHADER_PROPERTIES = 64;\n\n/** Ceiling on source length, matching what a compile cache can reasonably hold. */\nexport const MAX_SHADER_SOURCE = 64_000;\n\n/** Validates and normalises an authored pack. **Throws** when it is structurally not one (no source, no usable scope): a silent empty shader is an unexplained blank frame. **Warns and drops** a malformed property, since the rest still works (the same split as `normalizeUniforms`). */\nexport function normalizeShaderPack(input: unknown): Shader {\n if (typeof input !== \"object\" || input === null) {\n throw new Error(\"A shader pack must be an object.\");\n }\n const raw = input as Record<string, unknown>;\n\n const scope = raw.scope;\n if (scope !== \"fill\" && scope !== \"effect\") {\n throw new Error(\n `A shader pack needs scope \"fill\" or \"effect\", got ${JSON.stringify(scope)}. ` +\n `The two are written against different contracts — a fill has no backdrop to ` +\n `sample and an effect has no shape box to map coordinates onto.`,\n );\n }\n\n const source = typeof raw.source === \"string\" ? raw.source.trim() : \"\";\n if (source === \"\") throw new Error(`Shader pack \"${String(raw.name ?? \"?\")}\" has no source.`);\n if (source.length > MAX_SHADER_SOURCE) {\n throw new Error(\n `Shader pack \"${String(raw.name ?? \"?\")}\" source is ${source.length} characters, ` +\n `over the ${MAX_SHADER_SOURCE} ceiling.`,\n );\n }\n\n if (raw.language !== undefined && raw.language !== \"wgsl\") {\n throw new Error(\n `Shader pack \"${String(raw.name ?? \"?\")}\" is written in ${JSON.stringify(raw.language)}; ` +\n `only WGSL is supported. Port it to WGSL.`,\n );\n }\n\n const base: ShaderBase = {\n ...(typeof raw.$kind === \"string\" ? { $kind: raw.$kind } : {}),\n ...(typeof raw.id === \"string\" ? { id: raw.id } : {}),\n name: typeof raw.name === \"string\" && raw.name !== \"\" ? raw.name : \"Shader\",\n ...(typeof raw.description === \"string\" ? { description: raw.description } : {}),\n language: \"wgsl\",\n source,\n ...(isRecord(raw.uniforms) ? { uniforms: raw.uniforms as ShaderUniformRecord } : {}),\n properties: normalizeProperties(raw.properties, String(raw.name ?? \"?\")),\n };\n\n if (scope === \"fill\") {\n const textures = Array.isArray(raw.textures)\n ? (raw.textures as unknown[]).filter((t): t is { name: string; description?: string } =>\n isRecord(t) && typeof t.name === \"string\").map((t) => ({ name: t.name, ...(typeof t.description === \"string\" ? { description: t.description } : {}) }))\n : [];\n return {\n ...base,\n scope: \"fill\",\n ...(textures.length ? { textures } : {}),\n };\n }\n return { ...base, scope: \"effect\", ...(raw.backdrop === true ? { backdrop: true } : {}) };\n}\n\nfunction normalizeProperties(input: unknown, where: string): Record<string, ShaderProperty> {\n if (!isRecord(input)) return {};\n const out: Record<string, ShaderProperty> = {};\n const claimed = new Map<string, string>();\n\n for (const [id, value] of Object.entries(input)) {\n if (Object.keys(out).length >= MAX_SHADER_PROPERTIES) {\n warn(`shader \"${where}\" declares more than ${MAX_SHADER_PROPERTIES} properties; the rest are ignored.`);\n break;\n }\n if (!isRecord(value) || typeof value.kind !== \"string\") {\n warn(`shader \"${where}\" property \"${id}\" has no kind; ignored.`);\n continue;\n }\n const inputs = value.inputs;\n if (!isRecord(inputs) || Object.keys(inputs).length === 0) {\n warn(`shader \"${where}\" property \"${id}\" names no uniform in \"inputs\"; ignored.`);\n continue;\n }\n let conflict = false;\n for (const uniform of Object.values(inputs)) {\n if (typeof uniform !== \"string\") {\n warn(`shader \"${where}\" property \"${id}\" has a non-string uniform name; ignored.`);\n conflict = true;\n break;\n }\n const prior = claimed.get(uniform);\n if (prior !== undefined) {\n // Two properties writing one uniform means the panel has two\n // controls for one value and whichever resolves last silently wins.\n warn(`shader \"${where}\" properties \"${prior}\" and \"${id}\" both write uniform \"${uniform}\"; \"${id}\" ignored.`);\n conflict = true;\n break;\n }\n claimed.set(uniform, id);\n }\n if (conflict) continue;\n\n out[id] = value as unknown as ShaderProperty;\n }\n return out;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nconst warned = new Set<string>();\n\n/** Warn once per message — a pack may be normalised on every scene build. */\nfunction warn(message: string): void {\n if (warned.has(message)) return;\n if (warned.size > 256) warned.clear();\n warned.add(message);\n console.warn(`[shader] ${message}`);\n}\n", "/** Structural key for a node within its scene: the child-index path from the scene root joined with \".\" (root is \"\"). Not every node has an authored id (children a composite builds get a UUID), so lifespan tracking keys on this; the build is deterministic, so a slot has the same path in precomp and playback. */\n/** @internal */\nexport function nodePath(parentPath: string, childIndex: number): string {\n return parentPath === \"\" ? String(childIndex) : `${parentPath}.${childIndex}`;\n}\n\n/** @internal */\nexport interface NodeState {\n id: string;\n type: string;\n properties: Record<string, any>;\n\n\n}\n\n/** A single audio clip a node exposes for timeline display, in clip seconds; `src` is the fetchable source. */\n/** @internal */\nexport interface WaveformInfo {\n src: string;\n /** Clip timestamp (seconds) when the clip starts. */\n startTime: number;\n /** Clip timestamp (seconds) when the clip ends, or null if open-ended. */\n endTime: number | null;\n}\n\nexport interface TreeState {\n /** The node's `NodeSpec.id` for a document row, else a per-instance UUID (changes on rebuild for a composite-built node; {@link path} is stable for both). */\n id: string;\n /** Structural path from the scene root (`\"\"` root, `\"0.2\"` third child of the first), stable across rebuilds for every node so a host can key selection and overrides on it; what `getNodeBox` / `setNodeOverride` accept. */\n path: string;\n type: string;\n meta?: Record<string, unknown>;\n /** Audio clips owned by this node, for waveform rendering in the timeline. */\n waveform?: WaveformInfo[];\n /** Absolute timeline frame at which this node first appears; undefined when unknown (no precomp data). */\n startFrame?: number;\n /** Absolute timeline frame at which this node was last present; with startFrame bounds the track bar to its true lifespan. */\n endFrame?: number;\n children: TreeState[];\n}", "import { nodePath } from \"@/project/tree\";\nimport type { AssetScope } from \"@/assets/scope\";\nimport type { Node } from \"./node\";\n\n/**\n * The subtree traversals the runtime drives, as free functions over a {@link Node}: what's left on `Node` is what a\n * node *is*, what's here is what the engine *does to* one. Every walk stops at an unmounted node (see {@link Node.mounted}).\n *\n * @internal\n */\n\n/** Declares one node's own assets, never its children's, so each declaration stays attributable. */\nexport function declareNode(node: Node, scope: AssetScope): void {\n node.declareAssets(scope);\n}\n\n/** {@link declareNode} over `root` and every mounted descendant, in every dimension. */\nexport function declareTree(root: Node, scope: AssetScope): void {\n if (!root.mounted) return;\n declareNode(root, scope);\n const children = root._allChildren;\n for (let i = 0; i < children.length; i++) declareTree(children[i], scope);\n}\n\n/** Visits `root` and every mounted descendant with its structural path, indexed over every dimension's children so a path doesn't shift when a sibling of another dimension comes or goes (as a filtered `children` index would). */\nexport function forEachOwner(root: Node, visit: (node: Node, path: string) => void): void {\n visitOwners(root, \"\", visit);\n}\n\nfunction visitOwners(node: Node, path: string, visit: (node: Node, path: string) => void): void {\n if (!node.mounted) return;\n visit(node, path);\n const children = node._allChildren;\n for (let i = 0; i < children.length; i++) visitOwners(children[i], nodePath(path, i), visit);\n}\n\n/** Binds `node` with `host`'s catalog, context and clock without adopting it: `AssetDeclaration`'s `bindSubtree` for a `Tex.surface` source. */\nexport function bindDetached(host: Node, node: Node): void {\n (host as unknown as { attachDetached(node: Node): void }).attachDetached(node);\n}\n\n/** Samples every node's derived render state (currently motion) for this frame. `attach` normally does it as it advances the clock; this is the seam for the priming path, which seeds the same state without moving time (see `StateEvaluator.resetSlot`). */\nexport function sampleTree(node: Node): void {\n node._sample();\n for (const child of node.children) sampleTree(child);\n}\n\n/** Records the subtree's current positions as the motion history's previous frame at `at`, deriving no velocity. The driven path calls it with props evaluated one frame back, so the following {@link sampleTree} measures against the timeline rather than wherever the playhead was. */\nexport function primeMotionTree(node: Node, at: number): void {\n node._primeMotion(at);\n for (const child of node.children) primeMotionTree(child, at);\n}\n", "import { Node } from \"./node\";\n\n/** What an editor says about one node, as against the document. Neither field is a prop (not authored, no tweening, not part of the scene's meaning: an exported frame is the same whether or not a layer was folded away); they arrive on the side and are applied over the tree. */\nexport interface NodeEditorState {\n /** Hides the node and everything under it: no paint, no pick, no layout slot (a hidden child of a row gives up its cell and gap, like `display: none`). The node **stays in the tree**, since dropping it would renumber later siblings' structural paths, which a host's boxes, lifespans and picking are keyed on. */\n hidden?: boolean;\n /** Takes the node out of reach of the pointer, picture untouched (Figma's padlock). Not a weaker {@link hidden}: a locked node still draws, lays out and confines its children, and only declines being the answer to a pick. Its children stay pickable, as locking a group is about the group. */\n locked?: boolean;\n}\n\n/** Editor state for a whole tree, keyed by {@link Node.key}; a record so the applying walk's per-node ask isn't a scan. */\nexport type NodeEditorStates = Record<string, NodeEditorState>;\n\n/** Pushes `states` onto the tree under `root`, resolved onto the nodes so `render` and the pick walk read a local field. Called once per frame from `ClipInstance.attach` (after the tree is built, before layout), so a node appearing this frame gets its state this frame. A node with no `key`, or an unmentioned one, is reset: the record is the whole truth, so a dropped key is an unhidden node. */\nexport function applyEditorStates(root: Node, states: NodeEditorStates | undefined): void {\n const walk = (node: Node): void => {\n const state = node.key !== undefined ? states?.[node.key] : undefined;\n node._setEditorState(state?.hidden === true, state?.locked === true);\n for (const child of node._allChildren) walk(child);\n };\n walk(root);\n}\n", "import { RenderContext2D, RenderPass2D } from \"@/render/render-context2d\";\nimport { Graphics2D } from \"@/render/graphics2d\";\nimport { Clip } from \"@/render/clip\";\nimport { type Command, type CommandArgs } from \"@/tween/command\";\nimport { command } from \"@/tween/command-decorator\";\nimport { lerpLookAt, type LookAt, type SpaceCamera } from \"@/attributes/layout/space3d\";\nimport { NO_PROJECTION_3D, type Projection3D } from \"@/attributes/layout/matrix2d\";\nimport { Alignment } from \"@/attributes/layout/alignment\";\nimport type { FlowMode, FlowProps, FlowSettings, GapSize } from \"@/layout/types\";\nimport { fillOps } from \"@/attributes/shape/fill/registry\";\nimport { FillResolved } from \"@/attributes/shape/fill/union\";\nimport { Fill } from \"@/attributes/shape/fill/chain\";\nimport type { AssetScope } from \"@/assets/scope\";\nimport { CameraScope, Node2D, NodeConfig, Node2DProps } from \"@/components/trees/2d/node2d\";\nimport { spaceRootFrame } from \"@/components/trees/2d/node-space\";\nimport type { Node, NodeDimension } from \"@/components/trees/node/node\";\nimport { NodeAudio } from \"@/components/trees/audio/node-audio\";\nimport { declareMembers, property } from \"@/attributes/properties/decorator\";\nimport { alignmentProperty, fillProperty, flowProperty } from \"@/attributes/properties/typed\";\n\n/** @internal */\nexport interface Canvas2DProps extends Node2DProps, FlowProps {\n /** Background fill layer(s): any loose fill value or a {@link FillChain}, painted behind the children. */\n fill: Fill;\n /** Overlay layer(s), same loose values as {@link fill}, painted over the fill **and** the children (clipped to the viewport): e.g. a VHS-grain image or video across the scene. */\n overlay: Fill;\n /** Camera magnification factor. Values > 1 zoom in; < 1 zoom out. */\n zoom: number;\n /** World-space point mapped to the viewport centre. In a {@link space3D} it is also what the camera orbits, and `z` puts it in depth (as a node's `depth`: negative `z` flies in). */\n lookAt: LookAt;\n /** Rotation of the camera view in degrees (clockwise). */\n heading: number;\n /** Places the children in one 3D space seen through this camera, rather than each projecting through its own perspective: their `depth` and tilt become positions and turns in that space and siblings paint far to near. A switch, not read off the camera's numbers, so turning it on can't jump a tween. While on, `perspective` is the camera's distance from {@link lookAt} at `dolly: 0` (CSS's convention: that plane draws 1:1, `0` is parallel) and the stage's own tilt and depth are unused. */\n space3D: boolean;\n /** Degrees about the vertical axis through {@link lookAt}. 0 is head-on; positive moves the camera to the right. Same as `Camera3D`. */\n orbit: number;\n /** Degrees above the layers. Positive looks down on them. Same as `Camera3D`. */\n elevation: number;\n /** Px the camera has moved in toward {@link lookAt}. Inert with no perspective, as depth is. */\n dolly: number;\n}\n\n/** The single root container every clip document builds into: a {@link Node2D} that is the clip's layout frame and camera. It lays children out, paints a scene-wide `fill` and `overlay`, and views them through a viewport transform (`zoom`, `lookAt`, `heading`). Not a shape: no stroke, shadow, corner or `start`/`end`. Its layout props are the arrangement {@link Node2D} lays children out by ({@link flowArrangement}). */\n/** @internal */\nexport class Canvas2D extends Node2D<Canvas2DProps> {\n\n // Declared loose (`Fill`) so assignment and reads share one type; the accessor stores the resolved value via the mapper.\n declare fill: Fill;\n declare overlay: Fill;\n\n declare flow: FlowMode;\n declare readonly gap: GapSize;\n declare readonly wrap: boolean;\n // `undefined` means \"follow `gap`\", not \"missing\" — see FlowProps.crossGap.\n declare readonly crossGap: number | undefined;\n declare readonly columns: number;\n // Declared loose as `Alignment`; the accessor stores the resolved per-axis `Vector2` pivot. See Rect.\n declare align: Alignment;\n\n /** Camera magnification factor (default: 1). */\n declare zoom: number;\n /** World-space focus point (default: {x:0, y:0}). */\n declare lookAt: LookAt;\n /** Camera view rotation in degrees (default: 0). */\n declare heading: number;\n declare space3D: boolean;\n declare orbit: number;\n declare elevation: number;\n declare dolly: number;\n\n constructor(props: NodeConfig<Canvas2D, Canvas2DProps>) {\n super(props);\n }\n\n // Camera motion commands mirroring the Camera node's viewport commands.\n\n /** Animate `zoom`. Values > 1 zoom in; < 1 zoom out. */\n zoomTo(args: CommandArgs<{ zoom: number }> & { duration: number }): Command<Canvas2DProps> {\n return this.to({ data: args.data as Partial<Canvas2DProps>, duration: args.duration, easing: args.easing });\n }\n\n /** Pan — animate `lookAt`, the world-space point mapped to the viewport center. `z` moves it in depth. */\n panTo(args: CommandArgs<{ lookAt: LookAt }> & { duration: number }): Command<Canvas2DProps> {\n return this.to({ data: args.data as Partial<Canvas2DProps>, duration: args.duration, easing: args.easing });\n }\n\n /** Swings the camera round {@link lookAt}. Argument names are the 3D components' `orbitTo` less `zoom` (here the lens, with its own command). */\n orbitTo(args: CommandArgs<{ orbit?: number; elevation?: number }> & { duration: number }): Command<Canvas2DProps> {\n return this.to({ data: args.data as Partial<Canvas2DProps>, duration: args.duration, easing: args.easing });\n }\n\n /** Move the camera in toward {@link lookAt} (positive) or back out. */\n dollyTo(args: CommandArgs<{ dolly: number }> & { duration: number }): Command<Canvas2DProps> {\n return this.to({ data: args.data as Partial<Canvas2DProps>, duration: args.duration, easing: args.easing });\n }\n\n /** Animate the view rotation (`heading`), in degrees clockwise. */\n headingTo(args: CommandArgs<{ heading: number }> & { duration: number }): Command<Canvas2DProps> {\n return this.to({ data: args.data as Partial<Canvas2DProps>, duration: args.duration, easing: args.easing });\n }\n\n fillTo(args: CommandArgs<Fill, FillResolved[]> & { duration: number }): Command<Canvas2DProps> {\n const from = this.fill as FillResolved[];\n const target = fillOps.resolve(args.data as Fill);\n const lerp = args.lerp ?? fillOps.lerp;\n return this.command<Canvas2DProps>(t => ({ fill: lerp(from, target, t) }) as Partial<Canvas2DProps>, args.duration, args.easing);\n }\n\n overlayTo(args: CommandArgs<Fill, FillResolved[]> & { duration: number }): Command<Canvas2DProps> {\n const from = this.overlay as FillResolved[];\n const target = fillOps.resolve(args.data as Fill);\n const lerp = args.lerp ?? fillOps.lerp;\n return this.command<Canvas2DProps>(t => ({ overlay: lerp(from, target, t) }) as Partial<Canvas2DProps>, args.duration, args.easing);\n }\n\n protected override flowArrangement(): FlowSettings {\n return this;\n }\n\n // The viewport-sized background box behind the children.\n private shapeGraphics(): Graphics2D {\n return new Graphics2D().rect({\n width: this.layoutBounds.width,\n height: this.layoutBounds.height,\n });\n }\n\n protected override renderSelf(draw: RenderContext2D): void {\n const fill = this.fill as FillResolved[];\n if (fill.length === 0) return;\n draw.draw(this.shapeGraphics().fill(fill));\n }\n\n // Overlay over fill + children, clipped to the viewport silhouette.\n protected override renderOverlay(ctx: RenderContext2D): void {\n const overlay = this.overlay as FillResolved[];\n if (overlay.length === 0) return;\n ctx.draw(this.shapeGraphics().fill(overlay));\n }\n\n /** Accepts audio children as well as 2D ones: the scene root is where the two trees meet (as `Canvas3D`), so a voiceover lives in the document showing the picture it narrates. Nothing partitions them: `Node2D.children` already filters to its own kind and the audio declaration walk reads the unfiltered list. */\n protected override acceptsChild(child: Node): boolean {\n return child.dimension === \"2d\" || child.dimension === \"audio\";\n }\n\n override get _childTrees(): readonly NodeDimension[] {\n return [\"2d\", \"audio\"];\n }\n\n /** This node's children in the audio tree. */\n get childrenAudio(): NodeAudio[] {\n return this._allChildren.filter((c): c is NodeAudio => c instanceof NodeAudio);\n }\n\n // The world container, not a shape, so it declares its own `fill`/`overlay`.\n override declareAssets(assets: AssetScope): void {\n super.declareAssets(assets);\n assets.fill(this.fill as FillResolved[]);\n assets.fill(this.overlay as FillResolved[]);\n }\n\n // The viewport outline — used for `clip` and as the area backdrop effects\n // are confined to.\n protected override clipSelf(): Clip {\n return new Clip().rect({\n width: this.layoutBounds.width,\n height: this.layoutBounds.height,\n });\n }\n\n // Views the laid-out world through the camera viewport transform (the identity at rest, so a plain layout root pays\n // nothing). Non-null exactly when renderChildren opens a camera, so node picking inserts the same scope in the same\n // place and skips the at-rest fast path, where nothing is pushed.\n override _cameraScope(): CameraScope | null {\n if (this.space3D) return null;\n if (this.zoom === 1 && this.heading === 0 && this.lookAt.x === 0 && this.lookAt.y === 0) return null;\n return { lookAt: this.lookAt, zoom: this.zoom, heading: this.heading };\n }\n\n override _spaceCamera(): SpaceCamera | null {\n if (!this.space3D) return null;\n const rect = this.layoutBounds;\n return {\n perspective: this.perspective,\n orbit: this.orbit,\n elevation: this.elevation,\n dolly: this.dolly,\n lookAt: this.lookAt,\n zoom: this.zoom,\n heading: this.heading,\n viewportX: rect?.x ?? 0,\n viewportY: -(rect?.y ?? 0),\n };\n }\n\n // In a space the stage's own tilt and depth would turn the whole scene as\n // one flat card; its `perspective` is the camera's instead.\n protected override _projection(): Projection3D {\n return this.space3D ? NO_PROJECTION_3D : super._projection();\n }\n\n protected override renderChildren(ctx: RenderPass2D): void {\n const camera = this._spaceCamera();\n if (camera) {\n this._renderInSpace(ctx, spaceRootFrame(this, camera));\n return;\n }\n if (this.zoom === 1 && this.heading === 0 && this.lookAt.x === 0 && this.lookAt.y === 0) {\n super.renderChildren(ctx);\n return;\n }\n\n const rect = this.layoutBounds;\n const w = rect?.width ?? 0;\n const h = rect?.height ?? 0;\n const cx = rect?.x ?? 0;\n const cy = rect?.y ?? 0;\n\n ctx.beginCamera(\n { x: cx, y: -cy, width: w, height: h },\n this.lookAt,\n this.zoom,\n this.heading,\n );\n\n for (const child of this._children) if (child instanceof Node2D) child.render(ctx);\n\n ctx.endCamera();\n }\n}\n\ndeclareMembers(Canvas2D, {\n fill: fillProperty(),\n overlay: fillProperty(),\n flow: flowProperty(),\n gap: property({ default: 0 }),\n wrap: property({ default: false }),\n crossGap: property({ default: undefined }),\n columns: property({ default: 1 }),\n align: alignmentProperty(),\n zoom: property({ default: 1 }),\n lookAt: property({ default: { x: 0, y: 0 }, tween: lerpLookAt }),\n heading: property({ default: 0 }),\n space3D: property({ default: false }),\n orbit: property({ default: 0 }),\n elevation: property({ default: 0 }),\n dolly: property({ default: 0 }),\n\n zoomTo: command({ args: [{ key: \"zoom\", kind: \"number\", min: 0.01, step: 0.1, unit: \"×\" }] }),\n panTo: command({ args: [{ key: \"lookAt\", kind: \"vector2\", properties: { x: { kind: \"number\" }, y: { kind: \"number\" }, z: { kind: \"number\" } } }] }),\n orbitTo: command({ args: [{ key: \"orbit\", kind: \"number\", step: 1, unit: \"°\" }, { key: \"elevation\", kind: \"number\", step: 1, unit: \"°\" }] }),\n dollyTo: command({ args: [{ key: \"dolly\", kind: \"number\", step: 10 }] }),\n headingTo: command({ args: [{ key: \"heading\", kind: \"number\", step: 1, unit: \"°\" }] }),\n fillTo: command(),\n overlayTo: command(),\n});\n", "import { lerpCornerScalarStyle, type CornerStyle, type RectCornerStyle } from \"@/attributes/shape/corners/corner-style\";\nimport { pathOps } from \"@/attributes/shape/path/ops\";\nimport { STAR_DEFAULT_POINTS, STAR_DEFAULT_RATIO, type ShapeOutlineKind } from \"@/components/builtins/geometry/shape-outline\";\nimport type { NodeOf } from \"@/components/factory/api\";\nimport { component2d } from \"@/components/factory/component2d\";\nimport { Types } from \"@/components/factory/types\";\nimport * as Corners from \"@/components/modules/corners\";\nimport * as Flow from \"@/components/modules/flow\";\nimport * as Paint from \"@/components/modules/paint\";\nimport * as Shapes from \"@/components/modules/shapes\";\nimport type { Node2DProps } from \"@/components/trees/2d/node2d\";\nimport type { Fill } from \"@/attributes/shape/fill/chain\";\nimport type { Stroke } from \"@/attributes/shape/stroke/stroke\";\nimport type { Shadow } from \"@/attributes/shape/shadow/shadow\";\nimport type { FlowProps } from \"@/layout/types\";\nimport type { RectCornerRadius } from \"@/attributes/shape/corners/corner-radius\";\nimport type { PathData } from \"@/render/descriptors/path\";\n\n/**\n * The geometry built-ins: paint, the flow engine for children (clear of the\n * stroke), and each one's outline.\n */\n\nconst scalarCorners = {\n cornerRadius: Types.number(0),\n cornerStyle: Types.custom<CornerStyle>(\"rounded\", { lerp: lerpCornerScalarStyle }),\n};\n\nexport const Rect = component2d({\n key: \"rect\",\n state: { ...Paint.state, ...Flow.state, ...Corners.state },\n commands: { ...Paint.commands },\n measure: (measurer, state, children) => Flow.measure(measurer, state, children, Paint.inset(state)),\n layout: (box, state, children) => Flow.layout(box, state, children, Paint.inset(state)),\n render: (ctx, state) => Paint.draw(ctx, state, Corners.rect(ctx.size, state)),\n});\n\nexport const Ellipse = component2d({\n key: \"ellipse\",\n state: {\n ...Paint.state, ...Flow.state,\n startAngle: Types.number(0),\n sweep: Types.number(360),\n ratio: Types.number(0),\n },\n commands: { ...Paint.commands },\n measure: (measurer, state, children) => Flow.measure(measurer, state, children, Paint.inset(state)),\n layout: (box, state, children) => Flow.layout(box, state, children, Paint.inset(state)),\n render: (ctx, state) => Paint.draw(ctx, state, Shapes.ellipse(ctx.size, state)),\n});\n\nexport const Polygon = component2d({\n key: \"polygon\",\n state: { ...Paint.state, ...Flow.state, sides: Types.number(5), ...scalarCorners },\n commands: { ...Paint.commands },\n measure: (measurer, state, children) => Flow.measure(measurer, state, children, Paint.inset(state)),\n layout: (box, state, children) => Flow.layout(box, state, children, Paint.inset(state)),\n render: (ctx, state) => Paint.draw(ctx, state, Shapes.polygon(ctx.size, state)),\n});\n\nexport const Polygram = component2d({\n key: \"polygram\",\n state: { ...Paint.state, ...Flow.state, sides: Types.number(5), ratio: Types.number(0.5), ...scalarCorners },\n commands: { ...Paint.commands },\n measure: (measurer, state, children) => Flow.measure(measurer, state, children, Paint.inset(state)),\n layout: (box, state, children) => Flow.layout(box, state, children, Paint.inset(state)),\n render: (ctx, state) => Paint.draw(ctx, state, Shapes.polygram(ctx.size, state)),\n});\n\n/** The document's `path`: `data` in the unit space of its own box, so a resize is a width/height write. */\nexport const PathShape = component2d({\n key: \"path\",\n state: { ...Paint.state, ...Flow.state, data: Types.path },\n commands: { ...Paint.commands },\n measure: (measurer, state, children) => Flow.measure(measurer, state, children, Paint.inset(state)),\n layout: (box, state, children) => Flow.layout(box, state, children, Paint.inset(state)),\n render: (ctx, state) => Paint.draw(ctx, state, Shapes.unitPath(ctx.size, state.data), { clipShape: Shapes.box(ctx.size) }),\n});\n\n/** Path data drawn at face value, hugging it: geometry written in code. */\nexport const Path = component2d({\n key: \"facePath\",\n state: { ...Paint.state, ...Flow.state, data: Types.path },\n defaults: { width: \"hug\", height: \"hug\" },\n commands: { ...Paint.commands },\n measure: (_measurer, state) => {\n const intrinsic = pathOps.size(state.data);\n const pad = state.padding;\n return { width: intrinsic.width + pad.left + pad.right, height: intrinsic.height + pad.top + pad.bottom };\n },\n layout: (box, state, children) => Flow.layout(box, state, children, Paint.inset(state)),\n render: (ctx, state) => Paint.draw(ctx, state, Shapes.facePath(state.data), { clipShape: null }),\n});\n\nfunction boundsShape<const K extends string>(key: K, kind: ShapeOutlineKind) {\n return component2d({\n key,\n state: { ...Paint.state, ...Flow.state, ...scalarCorners },\n commands: { ...Paint.commands },\n measure: (measurer, state, children) => Flow.measure(measurer, state, children, Paint.inset(state)),\n layout: (box, state, children) => Flow.layout(box, state, children, Paint.inset(state)),\n render: (ctx, state) => Paint.draw(ctx, state, Shapes.outline(kind, ctx.size, state), { clipShape: Shapes.box(ctx.size) }),\n });\n}\n\nexport const Triangle = boundsShape(\"triangle\", \"triangle\");\nexport const RightTriangle = boundsShape(\"rightTriangle\", \"rightTriangle\");\nexport const Pentagon = boundsShape(\"pentagon\", \"pentagon\");\nexport const Hexagon = boundsShape(\"hexagon\", \"hexagon\");\nexport const Octagon = boundsShape(\"octagon\", \"octagon\");\n\nexport const Star = component2d({\n key: \"star\",\n state: {\n ...Paint.state, ...Flow.state, ...scalarCorners,\n points: Types.number(STAR_DEFAULT_POINTS),\n ratio: Types.number(STAR_DEFAULT_RATIO),\n },\n commands: { ...Paint.commands },\n measure: (measurer, state, children) => Flow.measure(measurer, state, children, Paint.inset(state)),\n layout: (box, state, children) => Flow.layout(box, state, children, Paint.inset(state)),\n render: (ctx, state) => Paint.draw(ctx, state, Shapes.outline(\"star\", ctx.size, {\n cornerRadius: state.cornerRadius, cornerStyle: state.cornerStyle, sides: Math.max(3, Math.round(state.points)), ratio: state.ratio,\n }), { clipShape: Shapes.box(ctx.size) }),\n});\n\nexport type Rect = NodeOf<typeof Rect>;\nexport type Ellipse = NodeOf<typeof Ellipse>;\nexport type Polygon = NodeOf<typeof Polygon>;\nexport type Polygram = NodeOf<typeof Polygram>;\nexport type PathShape = NodeOf<typeof PathShape>;\nexport type Path = NodeOf<typeof Path>;\nexport type Triangle = NodeOf<typeof Triangle>;\nexport type RightTriangle = NodeOf<typeof RightTriangle>;\nexport type Pentagon = NodeOf<typeof Pentagon>;\nexport type Hexagon = NodeOf<typeof Hexagon>;\nexport type Octagon = NodeOf<typeof Octagon>;\nexport type Star = NodeOf<typeof Star>;\n\n// What code building a shape names its props as. A call's own type is `CallProps<typeof Rect>`.\n\nexport interface PaintProps extends Node2DProps {\n /** Fill layer(s): a CSS color string (solid), a fill prop object, an already-resolved fill, or a {@link FillChain} from `Fills`. */\n fill?: Fill;\n /** Stroke layer(s): a {@link StrokeProp}, an array, or already resolved; each `fill` takes the same loose values as the top-level fill. */\n stroke?: Stroke;\n /** Shadow layer(s): a {@link ShadowProp}, an array, or already resolved; each `fill` takes the same loose values as the top-level fill. */\n shadow?: Shadow;\n start?: number;\n end?: number;\n}\n\nexport interface ShapeProps extends PaintProps, FlowProps {\n /** Overlay layer(s), the same loose values as {@link PaintProps.fill}, painted over this node's fill **and** children (clipped to its silhouette) but under the stroke: e.g. a VHS-grain image or video across the subtree. */\n overlay?: Fill;\n}\n\nexport type FlexSize = number | \"fill\" | \"hug\";\n\nexport interface RectProps extends ShapeProps {\n /** Corner radius in pixels — uniform, per-corner, or per-axis. */\n cornerRadius: RectCornerRadius;\n /** How each corner is shaped once it has a radius: `'rounded'` or `'angled'`. */\n cornerStyle: RectCornerStyle;\n}\n\nexport interface EllipseProps extends ShapeProps {\n ratio: number;\n sweep: number;\n startAngle: number;\n}\n\nexport interface PolygonProps extends ShapeProps {\n /** Number of sides. Must be ≥ 3. */\n sides: number;\n /** Vertex rounding radius in pixels. */\n cornerRadius: number;\n /** Vertex shape: `'rounded'` (circular arc) or `'angled'` (chamfer). */\n cornerStyle: CornerStyle;\n}\n\nexport interface PolygramProps extends ShapeProps {\n /** Number of outer points. Must be ≥ 3. */\n sides: number;\n /** Inner-to-outer radius ratio (0–1): how deeply the points are cut. At 1 it degenerates into a regular polygon. */\n ratio: number;\n /** Vertex rounding radius in pixels applied to both inner and outer vertices. */\n cornerRadius: number;\n /** Vertex shape: `'rounded'` (circular arc) or `'angled'` (chamfer). */\n cornerStyle: CornerStyle;\n}\n\nexport interface PathShapeProps extends ShapeProps {\n /** The geometry, as an SVG `d` string in the node's **unit box** (see {@link PathData}). */\n data: PathData\n}\n\nexport interface PathProps extends ShapeProps {\n data: PathData;\n}\n\n/**\n * The named shapes (triangle, right triangle, pentagon, hexagon, octagon, star) as engine nodes. They fill their box\n * rather than inscribing in it like a `Polygon` (which leaves a gap under a triangle's base; see `./shape-outline`),\n * and are separate types rather than a switch because \"which shape is this\" is picked once and must be visible at a\n * glance in the layers panel.\n *\n * The silhouette goes to the renderer as a `path` op, not a `polygon`, so corner rounding is ours: the engine's\n * polygon rounds the inscribed figure, and rounding a stretched one is a different arc at every vertex. The shape on\n * screen and the one after converting to a Path node are also built by the same function.\n *\n * The outline is rebuilt per draw, not cached: it is a handful of trig per vertex on at most ten vertices, and a cache\n * keyed on width, height, radius, style and the two parametric fields costs more to keep honest than it saves.\n */\nexport interface BoundsShapeProps extends ShapeProps {\n /** Vertex rounding radius in pixels. */\n cornerRadius: number\n /** Vertex shape: `'rounded'` (circular arc) or `'angled'` (chamfer). */\n cornerStyle: CornerStyle\n}\n", "import type { NodeOf } from \"@/components/factory/api\";\nimport { component2d } from \"@/components/factory/component2d\";\nimport { Types } from \"@/components/factory/types\";\nimport * as Flow from \"@/components/modules/flow\";\nimport * as Paint from \"@/components/modules/paint\";\nimport type { BooleanOperation } from \"@/attributes/mask/boolean\";\nimport type { Node2DProps } from \"@/components/trees/2d/node2d\";\nimport type { ShapeProps } from \"@/components/builtins/geometry/geometry\";\nimport type { MaskMode } from \"@/attributes/mask/mask\";\n\n/**\n * The compositing built-ins: children drawn as one. `op`, `mode` and\n * `inverted` are entries, where the classes kept them in unlisted slots, so a\n * host lists them and a command can switch them.\n */\n\n/** Its children become one shape by `op`, painted with its own fill, stroke and shadow. */\nexport const BooleanGroup = component2d({\n key: \"boolean\",\n state: { ...Paint.state, ...Flow.state, op: Types.oneOf([\"union\", \"subtract\", \"intersect\", \"exclude\"]) },\n commands: { ...Paint.commands },\n measure: (measurer, state, children) => Flow.measure(measurer, state, children, Paint.inset(state)),\n layout: (box, state, children) => Flow.layout(box, state, children, Paint.inset(state)),\n render: (ctx, state) => ctx.merge(state.op, state),\n});\n\n/** Its first child is the stencil the rest draw through. */\nexport const MaskGroup = component2d({\n key: \"mask\",\n state: { mode: Types.oneOf([\"alpha\", \"vector\", \"luminance\"]), inverted: false },\n render: (ctx, state) => ctx.mask(state),\n});\n\nexport type BooleanGroup = NodeOf<typeof BooleanGroup>;\nexport type MaskGroup = NodeOf<typeof MaskGroup>;\n\n// What code building a boolean or a mask names its props as.\n\nexport interface BooleanGroupProps extends ShapeProps {\n op: BooleanOperation;\n}\n\nexport interface MaskGroupProps extends Node2DProps {\n // How the mask shape determines content visibility:\n // \"alpha\" — mask alpha drives content alpha (default; matches Figma)\n // \"vector\" — fast hard clip using the mask's outline only\n // \"luminance\" — mask brightness drives content alpha\n mode: MaskMode;\n // When true, content shows where the mask is *not* (Figma's \"subtract\" mask).\n inverted: boolean;\n}\n", "import { lerpLookAt, type LookAt } from \"@/attributes/layout/space3d\";\nimport type { NodeOf } from \"@/components/factory/api\";\nimport { component2d } from \"@/components/factory/component2d\";\nimport { commandsFor } from \"@/components/factory/commands-for\";\nimport { Types } from \"@/components/factory/types\";\nimport * as Aim from \"@/components/modules/aim\";\nimport * as Corners from \"@/components/modules/corners\";\nimport * as Flow from \"@/components/modules/flow\";\nimport * as Paint from \"@/components/modules/paint\";\nimport type { Vector2 } from \"@/attributes/layout/vector2\";\nimport type { RectCornerRadius } from \"@/attributes/shape/corners/corner-radius\";\nimport type { RectCornerStyle } from \"@/attributes/shape/corners/corner-style\";\nimport type { ShapeProps } from \"@/components/builtins/geometry/geometry\";\nimport type { Node2DProps } from \"@/components/trees/2d/node2d\";\n\n/** A framed viewport: painted like a rect, its children seen through a camera aimed inside it. */\nexport const Camera = component2d({\n key: \"camera\",\n state: { ...Paint.state, ...Flow.state, ...Aim.state, ...Corners.state },\n commands: { ...Paint.commands, ...Aim.commands },\n measure: (measurer, state, children) => Flow.measure(measurer, state, children, Paint.inset(state)),\n layout: (box, state, children) => Flow.layout(box, state, children, Paint.inset(state)),\n render: (ctx, state) => Paint.draw(ctx, state, Corners.rect(ctx.size, state), { children: () => Aim.camera(ctx, state) }),\n});\n\nconst orbit = {\n lookAt: Types.custom<LookAt>({ x: 0, y: 0 }, {\n lerp: lerpLookAt, kind: \"vector2\", properties: { x: { kind: \"number\" }, y: { kind: \"number\" }, z: { kind: \"number\" } },\n }),\n zoom: Types.number(1, { min: 0.01, step: 0.1, unit: \"×\" }),\n heading: Types.number(0, { step: 1, unit: \"°\" }),\n orbit: Types.number(0, { step: 1, unit: \"°\" }),\n elevation: Types.number(0, { step: 1, unit: \"°\" }),\n dolly: Types.number(0, { step: 10 }),\n orbitSpeed: Types.number(0),\n};\n\n/** The stage's 2.5D camera for one subtree: its children stand in one space, orbited in depth. */\nexport const OrbitCamera = component2d({\n key: \"orbitCamera\",\n state: orbit,\n defaults: { width: \"hug\", height: \"hug\", perspective: 1000 },\n commands: commandsFor(orbit, {\n orbitTo: { args: [\"orbit\", \"elevation\"] },\n dollyTo: { args: [\"dolly\"] },\n zoomTo: { args: [\"zoom\"] },\n panTo: { args: [\"lookAt\"] },\n headingTo: { args: [\"heading\"] },\n }),\n render: (ctx, state) => ctx.space({\n perspective: state.perspective,\n orbit: state.orbit + state.orbitSpeed * ctx.time.total,\n elevation: state.elevation,\n dolly: state.dolly,\n lookAt: state.lookAt,\n zoom: state.zoom,\n heading: state.heading,\n viewportX: 0,\n viewportY: 0,\n }),\n});\n\n/** Its children laid out in a box turned by `angle`, and turned with it: the box it reports is the turned one's bounds. */\nexport const RotatedBox = component2d({\n key: \"rotated-box\",\n state: { angle: Types.number(-90) },\n defaults: { rotation: (state) => state.angle },\n measure: (measurer, state, children) => {\n const { cos, sin } = turn(state.angle);\n const { width: w, height: h } = measurer.max;\n const ortho = Math.abs(state.angle % 180) === 90;\n const room = w !== undefined && h !== undefined\n ? { width: w * cos + h * sin, height: w * sin + h * cos }\n : { width: ortho ? h : w, height: ortho ? w : h };\n let width = 0;\n let height = 0;\n for (const child of children) {\n const size = child.measure(room);\n width = Math.max(width, size.width);\n height = Math.max(height, size.height);\n }\n return { width: width * cos + height * sin, height: width * sin + height * cos };\n },\n layout: (box, state, children) => {\n const { cos, sin } = turn(state.angle);\n const turned = { x: 0, y: 0, width: box.width * cos + box.height * sin, height: box.width * sin + box.height * cos };\n return Flow.layout(turned, state as unknown as Flow.FlowState, children);\n },\n});\n\nfunction turn(angle: number): { cos: number; sin: number } {\n const rad = angle * (Math.PI / 180);\n return { cos: Math.abs(Math.cos(rad)), sin: Math.abs(Math.sin(rad)) };\n}\n\nexport type Camera = NodeOf<typeof Camera>;\nexport type OrbitCamera = NodeOf<typeof OrbitCamera>;\nexport type RotatedBox = NodeOf<typeof RotatedBox>;\n\n// What code building a camera or a rotated box names its props as.\n\nexport interface CameraProps extends ShapeProps {\n /** Magnification factor. Values > 1 zoom in; < 1 zoom out. */\n zoom: number;\n /** World-space point mapped to the camera viewport's centre (what it is pointed at); same name and meaning as `Graphics3D.perspective({ lookAt })`. */\n lookAt: Vector2;\n /** Rotation of the camera view in degrees (clockwise). */\n heading: number;\n /**\n * A node of the camera's world to keep in view, by id: the camera is aimed\n * at its centre each frame, and {@link lookAt} becomes an offset from it.\n */\n follow: string;\n /** Corner radius in pixels — uniform, per-corner, or per-axis. */\n cornerRadius: RectCornerRadius;\n /** How each corner is shaped once it has a radius: `'rounded'` or `'angled'`. */\n cornerStyle: RectCornerStyle;\n}\n\nexport interface OrbitCameraProps extends Node2DProps {\n /** The point the camera orbits and looks at; `z` puts it in depth, as a node's `depth` does. */\n lookAt: LookAt;\n /** Lens zoom, applied after the projection. Values > 1 zoom in. */\n zoom: number;\n /** Roll of the view in degrees, clockwise. */\n heading: number;\n /** Degrees about the vertical axis through {@link lookAt}. 0 is head-on; positive moves the camera right. */\n orbit: number;\n /** Degrees above the layers. Positive looks down on them. */\n elevation: number;\n /** Px the camera has moved in toward {@link lookAt}. Inert with no perspective. */\n dolly: number;\n /** Degrees per second the camera orbits on its own — a turntable. */\n orbitSpeed: number;\n}\n", "import { fillOps } from \"@/attributes/shape/fill/registry\";\nimport { strokeOps } from \"@/attributes/shape/stroke/stroke\";\nimport type { ResolvedTextRun, TextRun, TextSpan, FontStyle, TextAlign, TextCase, TextDecoration, VerticalAlign } from \"@/attributes/text/types\";\nimport { formatNumber } from \"@/components/builtins/text/number-format\";\nimport { numberNodePattern } from \"@/components/builtins/text/number-pattern\";\nimport type { PathData } from \"@/render/descriptors/path\";\nimport { PathBuilder } from \"@/render/descriptors/path-builder\";\nimport type { NodeOf } from \"@/components/factory/api\";\nimport { component2d } from \"@/components/factory/component2d\";\nimport { Types } from \"@/components/factory/types\";\nimport * as Paint from \"@/components/modules/paint\";\nimport * as TextLayout from \"@/components/modules/text-layout\";\nimport * as TextStyle from \"@/components/modules/text-style\";\n\nimport type { Node2DProps } from \"@/components/trees/2d/node2d\";\nimport type { Fill } from \"@/attributes/shape/fill/chain\";\nimport type { Stroke } from \"@/attributes/shape/stroke/stroke\";\nimport type { PaintProps } from \"@/components/builtins/geometry/geometry\";\nimport type { Shadow } from \"@/attributes/shape/shadow/shadow\";\n\n/**\n * The text built-ins. A glyph node paints like a shape, but has no outline to\n * lay an overlay over, so it takes Paint without one; its face comes from\n * TextStyle, which inherits what the author left unset.\n */\n\nconst { overlay: _overlay, ...glyphPaint } = Paint.state;\nconst { overlayTo: _overlayTo, ...glyphCommands } = Paint.commands;\n\n/** Glyphs hug themselves; `'autofit'` fills the box it fits to. */\nconst autofits = (state: { readonly fontSize: number | \"autofit\" }) => (state.fontSize === \"autofit\" ? \"fill\" : \"hug\");\n\nconst NO_RUNS: readonly never[] = [];\n\nfunction resolvePath(value: PathData | PathBuilder | null | undefined): PathData | null {\n if (value == null) return null;\n return value instanceof PathBuilder ? value.toCommands() : value;\n}\n\nfunction resolveRuns(value: TextRun[] | null | undefined): ResolvedTextRun[] {\n if (!Array.isArray(value)) return [];\n return value.map(({ fill, stroke, ...run }) => ({\n ...run,\n ...(fill === undefined ? {} : { fill: fillOps.resolve(fill) }),\n ...(stroke === undefined ? {} : { stroke: strokeOps.resolve(stroke) }),\n }));\n}\n\nconst textState = {\n ...glyphPaint,\n ...TextStyle.state,\n text: Types.text(\"\", { typing: true }),\n wrap: false,\n path: Types.custom<PathData | PathBuilder | null, PathData | null>(null, { resolve: resolvePath }),\n runs: Types.custom<TextRun[], ResolvedTextRun[]>([], { resolve: resolveRuns, animatable: false }),\n};\n\nconst textSource = (state: { readonly text: string; readonly wrap: boolean; readonly path: PathData | null; readonly runs: ResolvedTextRun[] }) =>\n ({ text: state.text, wraps: state.wrap, glyphPath: state.path, runs: state.runs });\n\n/** Copy somebody typed: wraps when asked, rides a path, styles stretches of itself. */\nexport const Text = component2d({\n key: \"text\",\n allowedChildren: [],\n state: textState,\n defaults: {\n width: (state) => (state.fontSize === \"autofit\" || state.wrap ? \"fill\" : \"hug\"),\n height: autofits,\n },\n commands: {\n ...glyphCommands,\n append: {\n args: { text: Types.text(\"\", { multiline: true }) },\n run: (timeline, state) => timeline.tween({ text: state.text + timeline.args.text }),\n },\n prepend: {\n args: { text: Types.text(\"\", { multiline: true }) },\n run: (timeline, state) => timeline.tween({ text: timeline.args.text + state.text }),\n },\n },\n load: (loader, state) => TextLayout.load(loader, state, textSource(state)),\n measure: (measurer, state) => TextLayout.measure(measurer, state, textSource(state)),\n render: (ctx, state) => TextLayout.draw(ctx, state, textSource(state)),\n});\n\nconst numberState = {\n ...glyphPaint,\n ...TextStyle.state,\n value: 0,\n format: Types.custom<NumberFormat>(\"number\"),\n customPattern: \"\",\n fractionDigits: 0,\n grouped: true,\n currencySymbol: \"$\",\n};\n\nconst numberSource = (state: Parameters<typeof numberNodePattern>[0] & { readonly value: number }) =>\n ({ text: formatNumber(state.value, numberNodePattern(state)), wraps: false, glyphPath: null, runs: NO_RUNS });\n\n/** A figure, formatted from its value: a quantity, not copy. */\nexport const NumberNode = component2d({\n key: \"number\",\n allowedChildren: [],\n state: numberState,\n defaults: { width: autofits, height: autofits },\n commands: { ...glyphCommands, countTo: { args: [\"value\"] } },\n load: (loader, state) => TextLayout.load(loader, state, numberSource(state)),\n measure: (measurer, state) => TextLayout.measure(measurer, state, numberSource(state)),\n render: (ctx, state) => TextLayout.draw(ctx, state, numberSource(state)),\n});\n\nconst { verticalAlign: _v, textDecoration: _d, textCase: _c, minFontSize: _m, ...richStyle } = TextStyle.state;\n\n/** Spans of text, each styled on its own, set on lines that break only where they say. */\nexport const RichText = component2d({\n key: \"richtext\",\n allowedChildren: [],\n state: {\n ...glyphPaint,\n ...richStyle,\n fontSize: Types.number(48, { inherit: TextStyle.inherit(\"fontSize\", { autofit: false }) }),\n spans: Types.custom<TextSpan | TextSpan[], TextSpan[]>([], {\n resolve: (v) => (v == null ? [] : Array.isArray(v) ? v : [v]),\n }),\n },\n defaults: { width: \"hug\", height: \"hug\" },\n commands: { ...glyphCommands },\n load: (loader, state) => TextLayout.loadRichText(loader, state),\n measure: (measurer, state) => TextLayout.measureRichText(measurer, state),\n render: (ctx, state) => TextLayout.drawRichText(ctx, state),\n});\n\n/** The face text below it is set in, field by field, over whatever is inherited from above. */\nexport const DefaultTextStyle = component2d({\n key: \"default-text-style\",\n state: TextStyle.provided,\n provide: (state, inherited) => TextStyle.provide(state, inherited),\n render: (ctx, state) => ctx.textStyle(TextStyle.current(state), () => ctx.children()),\n});\n\nexport type Text = NodeOf<typeof Text>;\nexport type NumberNode = NodeOf<typeof NumberNode>;\nexport type RichText = NodeOf<typeof RichText>;\nexport type DefaultTextStyle = NodeOf<typeof DefaultTextStyle>;\n\n// What code building a text node names its props as.\n\n/** The fields a string is shaped and set by, shared by every node that draws glyphs. */\nexport interface TextBaseProps extends PaintProps {\n fontSize: number | 'autofit';\n fontFamily: string;\n fontWeight: number;\n fontStyle: FontStyle;\n letterSpacing: number;\n lineHeight: number;\n textAlign: TextAlign;\n verticalAlign: VerticalAlign;\n textDecoration: TextDecoration;\n textCase: TextCase;\n minFontSize: number;\n /** Name of a `theme.typography` preset (e.g. `\"header\"`) supplying any text-style prop not set explicitly. Precedence: explicit prop, then preset, then an inherited `<DefaultTextStyle>`. */\n variant: string;\n}\n\nexport interface TextProps extends TextBaseProps {\n text: string;\n /** Wrap onto more lines once the text runs out of width. */\n wrap: boolean;\n /** Wraps the text around a path (text-on-path), taking the same shapes as {@link Path}'s `d` (SVG string, `PathCommand[]`, {@link PathBuilder}). Single line: `wrap`, `\\n` and `runs` are ignored. */\n path: PathData | PathBuilder;\n /** Stretches of `text` styled apart from the node (see {@link TextRun}); the later of two overlapping runs wins, offsets past the end style nothing, ignored on a `path`. */\n runs: TextRun[];\n}\n\n/** How a {@link NumberNode}'s value is written: `'custom'` hands {@link NumberProps.customPattern} over verbatim; the others compose a pattern from {@link NumberProps.fractionDigits} and {@link NumberProps.grouped}. */\nexport type NumberFormat = \"currency\" | \"percent\" | \"number\" | \"custom\";\n\nexport interface NumberProps extends TextBaseProps {\n /** The numeric value to display. Tweenable — `to({ value })` counts. */\n value: number;\n /** How the figure is written: `'number'` (default), `'currency'` (prefixed with {@link NumberProps.currencySymbol}), `'percent'` (x100 and `%`, so `0.42` is `42%`), `'custom'` ({@link NumberProps.customPattern}, verbatim). */\n format: NumberFormat;\n /** The pattern when {@link NumberProps.format} is `'custom'`, in the grammar `formatNumber` takes (`#,##0.00`, `0.0%`, `$#,##0`). */\n customPattern: string;\n /** Fixed decimal places, always exactly this many so a counting animation doesn't flicker trailing digits across an integer boundary. */\n fractionDigits: number;\n /** Group digits in threes — `1,000` rather than `1000`. */\n grouped: boolean;\n /** The symbol a `'currency'` figure is prefixed with. */\n currencySymbol: string;\n}\n\nexport interface RichTextProps extends PaintProps {\n spans: TextSpan | TextSpan[];\n /** Default font family inherited by spans that don't set one. */\n fontFamily: string;\n /** Default font size inherited by spans that don't set one. */\n fontSize: number;\n /** Default font weight inherited by spans that don't set one. */\n fontWeight: number;\n /** Default font style inherited by spans that don't set one. */\n fontStyle: FontStyle;\n /** Default letter spacing inherited by spans that don't set one. */\n letterSpacing: number;\n /** Line height multiplier applied to each run's font size. */\n lineHeight: number;\n textAlign: TextAlign;\n /** Name of a `theme.typography` preset (e.g. `\"body\"`) supplying node-level defaults not set explicitly, which `runs()` folds into each span. Precedence: explicit prop, then preset, then an inherited `<DefaultTextStyle>`. */\n variant: string;\n}\n\nexport interface DefaultTextStyleProps extends Node2DProps {\n fontFamily: string;\n fontSize: number | 'autofit';\n fontWeight: number;\n fontStyle: FontStyle;\n letterSpacing: number;\n lineHeight: number;\n textAlign: TextAlign;\n fill: Fill;\n stroke: Stroke;\n shadow: Shadow;\n}\n", "import { DataToken, SeedToken, ThemeToken } from \"@/runtime/builtin-context\";\nimport type { Context } from \"@/util/context\";\nimport { provides, type NodeOf, type Provided } from \"@/components/factory/api\";\nimport { component2d } from \"@/components/factory/component2d\";\nimport { Types } from \"@/components/factory/types\";\nimport type { Node2DProps } from \"@/components/trees/2d/node2d\";\n\n/** Hands its subtree `value` under `context`, or the context's default when it has no value. */\nexport const Provider = component2d({\n key: \"provider\",\n state: { context: Types.custom<Context<unknown> | undefined>(undefined), value: Types.custom<unknown>(undefined) },\n provide: (state) => (state.context ? [provides(state.context, state.value !== undefined ? state.value : state.context.defaultValue)] : []),\n});\n\n/** Lays its theme and data over what it inherits, and seeds the randomness below it. */\nexport const ThemeProvider = component2d({\n key: \"theme-provider\",\n state: {\n theme: Types.custom<Record<string, unknown> | undefined>(undefined),\n data: Types.custom<Record<string, unknown> | undefined>(undefined),\n seed: Types.custom<string | number | undefined>(undefined),\n },\n provide: (state, inherited) => {\n const out: Provided[] = [];\n if (state.theme) out.push(provides(ThemeToken, { ...inherited(ThemeToken), ...state.theme }));\n if (state.data) out.push(provides(DataToken, { ...inherited(DataToken), ...state.data }));\n if (state.seed !== undefined) out.push(provides(SeedToken, state.seed));\n return out;\n },\n});\n\nexport type Provider = NodeOf<typeof Provider>;\nexport type ThemeProvider = NodeOf<typeof ThemeProvider>;\n\n// What code building a provider names its props as.\n\nexport interface ProviderProps<T> extends Node2DProps {\n /** The context token this provider supplies to its descendants. */\n context: Context<T>;\n /** The value to provide. Omitted → the token's default value. */\n value: T;\n}\n\nexport interface ThemeProviderProps extends Node2DProps {\n /** Named values (e.g. colors) merged onto any ancestor theme, read via\n * `node.useContext(ThemeToken)`. */\n theme: Record<string, unknown>;\n /** Arbitrary data merged onto any ancestor data bag, read via\n * `node.useContext(DataToken)`. */\n data: Record<string, unknown>;\n /** A default seed passed down the tree, read via `node.useContext(SeedToken)`. */\n seed: string | number;\n}\n", "import { lerpParam, type Param } from \"@/attributes/audio/ramp\";\nimport type { NodeOf } from \"@/components/factory/api\";\nimport { componentAudio } from \"@/components/factory/component-audio\";\nimport { Types } from \"@/components/factory/types\";\nimport type { NodeAudioProps } from \"@/components/trees/audio/node-audio\";\n\n/**\n * The audio built-ins. A sound plays when a command says so: its `play` runs\n * for the command's span, or to the source's end when the command has no length.\n * A document's `sound` row with no `play` of its own gets one over its span.\n */\n\n/** A clip from the catalog, playing into the buses it sits in. */\nexport const SoundNode = componentAudio({\n key: \"sound\",\n state: {\n src: Types.custom<string>(undefined as unknown as string),\n trimStart: 0,\n trimEnd: Types.custom<number | undefined>(undefined),\n loop: false,\n speed: Types.custom<Param>(1, { lerp: lerpParam, kind: \"audioParam\" }),\n },\n allowedChildren: [],\n commands: {\n play: (timeline, state) => timeline.sound(state.src, {\n trimStart: state.trimStart,\n trimEnd: state.trimEnd,\n loop: state.loop,\n volume: state.volume,\n speed: state.speed,\n effects: state.effects,\n transitionIn: state.transitionIn,\n transitionOut: state.transitionOut,\n }),\n },\n});\n\n/** A mix of the sounds and buses in it; `solo` silences its siblings. */\nexport const AudioBus = componentAudio({\n key: \"audioBus\",\n state: { solo: false },\n});\n\nexport type SoundNode = NodeOf<typeof SoundNode>;\nexport type AudioBus = NodeOf<typeof AudioBus>;\n\n// What code building a sound or a bus names its props as.\n\nexport interface AudioBusProps extends NodeAudioProps {\n /** Silence every other bus that is not itself soloed. */\n solo: boolean;\n}\n\nexport interface SoundNodeProps extends NodeAudioProps {\n /** Path/URL of the audio (or video) asset. Must exist in the asset manifest. */\n src: string;\n /** In-point inside the source file, in seconds. Defaults to 0. */\n trimStart: number;\n /** Out-point inside the source file. Defaults to the source's full length. */\n trimEnd: number | undefined;\n /** Repeat the trimmed clip until it is removed. */\n loop: boolean;\n /**\n * Playback-rate multiplier, pitch included: 2 plays twice as fast and takes\n * half the clip time. A ramp runs over source seconds after `trimStart`.\n */\n speed: Param;\n}\n", "import type { Alignment } from \"@/attributes/layout/alignment\";\nimport type { InsetsResolved } from \"@/attributes/layout/insets\";\nimport type { Vector2 } from \"@/attributes/layout/vector2\";\nimport { resolveAudioEffects, type AudioEffectsInput } from \"@/attributes/audio/effects/chain\";\nimport type { AudioEffect } from \"@/attributes/audio/effects/union\";\nimport type { ImageFit, ImageMatrix, ImageCrop } from \"@/attributes/shape/fill/implementations/image\";\nimport { sourceTimeFor, type VideoFillProp, type VideoFillResolved } from \"@/attributes/shape/fill/implementations/video\";\nimport { resolveFill, UNSET_MEDIA_FILL } from \"@/attributes/shape/fill/registry\";\nimport type { FillProp } from \"@/attributes/shape/fill/union\";\nimport { resolveChainAdjustments, type VideoAdjustment } from \"@/attributes/shape/filters/chain\";\nimport { lerpFilterArray, type AnyFilter } from \"@/attributes/shape/filters/registry\";\nimport { Graphics2D } from \"@/render/graphics2d\";\nimport type { NodeOf, Values } from \"@/components/factory/api\";\nimport { component2d } from \"@/components/factory/component2d\";\nimport { Types } from \"@/components/factory/types\";\nimport * as Corners from \"@/components/modules/corners\";\nimport * as Flow from \"@/components/modules/flow\";\nimport * as Paint from \"@/components/modules/paint\";\nimport { internalsOf } from \"@/components/factory/views\";\nimport type { RectProps } from \"@/components/builtins/geometry/geometry\";\n\n/** Video: a rect painted with a playing picture under its fill, plus the picture's sound. Sound plays from `play`; a `video` row with no `play` gets one per segment, or one over its span while it plays. */\n\nconst video = {\n src: Types.custom<string | undefined>(undefined),\n fit: Types.custom<ImageFit | undefined>(undefined),\n crop: Types.insets,\n zoom: 1,\n anchor: Types.alignment,\n matrix: Types.custom<ImageMatrix | undefined>(undefined),\n filters: Types.custom<VideoAdjustment, AnyFilter[]>([] as never, {\n resolve: (v) => resolveChainAdjustments(v),\n lerp: lerpFilterArray,\n }),\n playing: true,\n timestamp: Types.custom<number | null | undefined>(undefined),\n trimStart: Types.custom<number | undefined>(undefined),\n trimEnd: Types.custom<number | undefined>(undefined),\n speed: Types.custom<number | undefined>(undefined),\n loop: Types.custom<\"forward\" | \"reverse\" | \"none\" | undefined>(undefined),\n duration: Types.custom<number | undefined>(undefined),\n volume: 1,\n muted: false,\n audioEffects: Types.custom<AudioEffectsInput, AudioEffect[]>([] as never, { resolve: (v) => resolveAudioEffects(v) }),\n bus: Types.custom<string | undefined>(undefined),\n segments: Types.custom<readonly VideoSegment[]>([]),\n};\n\ntype VideoState = Values<typeof video> & { readonly crop: InsetsResolved; readonly anchor: Alignment };\n\n/** Source seconds played by `elapsed` clip seconds into the segments, or `null` without any. */\nfunction playedAt(s: VideoState, elapsed: number): number | null {\n if (s.segments.length === 0) return null;\n let played = 0;\n for (const segment of s.segments) {\n if (elapsed <= segment.at) break;\n played += Math.min(elapsed - segment.at, segment.duration) * (segment.speed ?? s.speed ?? 1);\n }\n return played;\n}\n\nfunction scheduledTimestamp(s: VideoState, elapsed: number): number | undefined {\n const played = playedAt(s, elapsed);\n if (played === null) return undefined;\n const start = s.trimStart ?? 0;\n const first = s.segments[0];\n return sourceTimeFor(played + (first ? first.from - start : 0), start, s.trimEnd ?? Infinity, s.loop, s.duration);\n}\n\nconst pictures = new WeakMap<object, { readonly key: string; readonly fill: VideoFillResolved }>();\n\n/** The frame to paint, resolved once per change of what it depends on. */\nfunction pictureOf(host: object, s: VideoState, elapsed: number): VideoFillResolved | null {\n if (!s.src) {\n pictures.delete(host);\n return null;\n }\n const scheduled = scheduledTimestamp(s, elapsed);\n const crop = s.crop;\n const anchor = s.anchor as unknown as Vector2;\n const key = [\n s.src, s.fit ?? \"\", s.zoom, s.playing ? 1 : 0, crop.left, crop.right, crop.top, crop.bottom, anchor.x, anchor.y,\n s.timestamp ?? \"\", s.trimStart ?? \"\", s.trimEnd ?? \"\", s.speed ?? \"\", s.loop ?? \"\", s.duration ?? \"\", scheduled ?? \"\",\n ].join(\"|\");\n const kept = pictures.get(host);\n if (kept && kept.key === key) return kept.fill;\n const prop: VideoFillProp = {\n type: \"video\", src: s.src, fit: s.fit, crop: s.crop, zoom: s.zoom, anchor: s.anchor, matrix: s.matrix,\n preset: { adjustments: s.filters }, playing: s.playing, timestamp: s.timestamp ?? scheduled,\n trimStart: s.trimStart, trimEnd: s.trimEnd, speed: s.speed, loop: s.loop, duration: s.duration,\n };\n const fill = resolveFill(prop as FillProp) as VideoFillResolved;\n pictures.set(host, { key, fill });\n return fill;\n}\n\nexport const Video = component2d({\n key: \"video\",\n state: { ...Paint.state, ...Flow.state, ...Corners.state, ...video },\n commands: {\n ...Paint.commands,\n /** Its sound: from `from` in the source for a segment, or as it plays. Cut when the command ends. */\n play: {\n args: {\n from: Types.custom<number | undefined>(undefined),\n volume: Types.custom<number | undefined>(undefined),\n speed: Types.custom<number | undefined>(undefined),\n },\n run: (timeline, state) => {\n const s = state as unknown as VideoState;\n const segment = timeline.args.from !== undefined;\n if (!s.src || s.muted || (!segment && !s.playing)) return timeline.together([]);\n const speed = timeline.args.speed ?? s.speed ?? 1;\n const loop = !segment && (s.loop ?? \"none\") !== \"none\";\n return timeline.sound(s.src, {\n volume: timeline.args.volume ?? s.volume,\n loop,\n trimStart: segment ? timeline.args.from : s.trimStart,\n trimEnd: s.trimEnd,\n speed,\n effects: s.audioEffects,\n bus: s.bus,\n optional: true,\n closed: !loop,\n });\n },\n },\n },\n load: (loader, state) => {\n if (!state.src) return;\n loader.fill(resolveFill({\n type: \"video\", src: state.src, preset: { adjustments: state.filters }, trimStart: state.trimStart, trimEnd: state.trimEnd,\n } as unknown as FillProp));\n },\n measure: (measurer, state, children) => Flow.measure(measurer, state, children, Paint.inset(state)),\n layout: (box, state, children) => Flow.layout(box, state, children, Paint.inset(state)),\n render: (ctx, state) => {\n const s = state as unknown as VideoState & Values<typeof Paint.state> & Values<typeof Corners.state>;\n const picture = pictureOf(internalsOf(ctx).host, s, ctx.time.elapsed);\n const outline = { width: ctx.size.width, height: ctx.size.height, cornerRadius: s.cornerRadius, cornerStyle: s.cornerStyle, start: s.start, end: s.end };\n Paint.draw(ctx, state, Corners.rect(ctx.size, state), {\n fill: [(picture ?? UNSET_MEDIA_FILL), ...state.fill] as never,\n // The overlay lies on the picture only, masked by it.\n overlay: () => (picture\n ? new Graphics2D().mask().rect(outline).fill([picture] as never).applyMask().rect(outline).fill(state.overlay).endMask()\n : null),\n });\n },\n});\n\nexport type Video = NodeOf<typeof Video>;\n\n// What code building a video names its props as, and the segments it plays.\n\nexport interface VideoProps extends RectProps {\n src?: string;\n /** How the (cropped) frame is scaled into the node's bounds. Default 'fill'. */\n fit?: ImageFit;\n /** Window onto the source frame, in fractions of its own size, applied before `fit`. */\n crop?: ImageCrop;\n /** Magnification on top of the fitted scale. `1` (default) is the fitted size. */\n zoom?: number;\n /** The point held fixed as `zoom` scales; also the alignment when it doesn't cover. */\n anchor?: Alignment;\n /** Raw frame→shape matrix; bypasses `crop`/`fit`/`zoom`/`anchor` and the bounds. */\n matrix?: ImageMatrix;\n /** Visual filters applied to the rendered frame (blur, color, posterizeTime, echo, …). */\n filters?: VideoAdjustment;\n /** Whether playback advances with the node's clock (drives both picture and sound). Default true. */\n playing?: boolean;\n /** Explicit source time to show, in seconds. Omitted, the picture is timed from the moment this node appeared; set it to drive the playhead, or `null` to hand it back to the clock (`set()` merges a partial, so `undefined` won't clear it). */\n timestamp?: number | null;\n trimStart?: number;\n trimEnd?: number;\n /** Playback-rate multiplier for both picture and audio. Default 1. */\n speed?: number;\n loop?: 'forward' | 'reverse' | 'none';\n /** Length of one loop cycle, in seconds. Defaults to the trimmed clip length. */\n duration?: number;\n /** Audio volume in [0, 1]. Default 1. */\n volume?: number;\n /** Silence the video's audio track without affecting the picture. Default false. */\n muted?: boolean;\n /** Audio effects applied to the video's sound track (gain, eq, echo, …). */\n audioEffects?: AudioEffectsInput;\n /** The node id of an `AudioBus` in this clip to route the video's sound into. A `Video` is a `Node2D` so can't sit under a bus, its audio being welded to its picture; naming one (the same id a `SoundNode` under that bus writes as `parentId`) lets dialogue share a bus, so ducking the group is one edit. An id matching no bus routes to the master. */\n bus?: string;\n /**\n * An explicit **playback schedule**: stretches of this node's own clock during which the clip advances, and where in\n * the source each starts. Omitted, the clip runs from the moment the node appears, at `speed`. Given, `playing` and\n * `timestamp` are superseded: the picture takes its source time from the segment covering the current `elapsed`, and\n * sound is scheduled one clip per segment. It exists because a **pause** can't be expressed otherwise: `playing: false`\n * holds the first frame and the sound runs on the node's clock regardless, so a frozen picture would drift from it. A\n * schedule states that a paused stretch consumes no source, so they can't come apart. Still a pure function of the\n * clock: scrub, playthrough and export agree.\n */\n segments?: readonly VideoSegment[];\n\n}\n\n/** One stretch of a {@link Video}'s own clock during which its source advances (see {@link VideoProps.segments}). Trim and loop apply on top, so a schedule says when the clip runs and the clip's props say which part of the file it runs through. */\nexport interface VideoSegment {\n /** Second on the node's own clock (`NodeTime.elapsed`) this segment begins. */\n at: number;\n /** Source in-point for it, in seconds. */\n from: number;\n /** How long it runs, in seconds of the node's clock; `Infinity` for a clip left running (the open sentinel `AudioRequest.endAt` uses), resolved against the clip's length. */\n duration: number;\n /** Playback rate through it. Defaults to the node's own `speed`. */\n speed?: number;\n /** Linear gain for its sound. Defaults to the node's own `volume`. */\n volume?: number;\n}\n", "import type { Passthrough3D } from \"./geometry\";\nimport type { Transform3D } from \"./transform\";\nimport { resolveVector3, type Vector3, type Vector3Input } from \"./vector3\";\n\n/**\n * What every camera has. Placement has two non-redundant halves: {@link Transform3D} `position` + `lookAt` suits a\n * shot pinned to something (and a camera in a moving rig); the polar half ({@link target}, {@link orbit},\n * {@link elevation}, {@link distance}) suits a shot *about* the subject and animates cleanly, where `position` would\n * need sines composed by hand every frame. Setting any polar field derives `position` and `lookAt`, so the halves\n * are never in force at once. See {@link resolveCameraPlacement}.\n */\nexport interface CameraCommon3D extends Transform3D, Passthrough3D {\n /** The point the camera looks at, and orbits around. Default origin. */\n target?: Vector3Input;\n /** Azimuth around {@link target}, in **degrees**. 0 looks down −Z. */\n orbit?: number;\n /** Angle above the horizon, in **degrees**. Clamped just short of vertical. */\n elevation?: number;\n distance?: number;\n\n /** Near and far clip planes, derived from the scene's bounds when omitted (right far more often than any constant: too near a `far` clips the scene's back, too far a `near` clips its front; a tiny `near` costs depth precision only on standard-Z renderers). */\n near?: number;\n far?: number;\n /** Zoom factor applied on top of the projection. */\n zoom?: number;\n}\n\n/** A perspective camera: converging rays, so distant things shrink. The default unless you need an orthographic projection's flat look. */\nexport interface PerspectiveCameraData3D extends CameraCommon3D {\n type: \"perspective\";\n /** Vertical field of view in **degrees**. Default 50. */\n fov?: number;\n}\n\n/** An orthographic camera: parallel rays, so size is independent of distance (isometric views, technical diagrams, 2.5D). {@link frustumHeight} sets the visible world height and the width follows the aspect; an asymmetric frustum is a `params` override, as four explicit edges are a projection-matrix feature, not framing. */\nexport interface OrthographicCameraData3D extends CameraCommon3D {\n type: \"orthographic\";\n /** Visible world-space height; width follows the node's aspect. Default 10. */\n frustumHeight?: number;\n}\n\n/** Every camera a scene can be viewed through. Discriminated on `type`. */\nexport type CameraData3D = PerspectiveCameraData3D | OrthographicCameraData3D;\n\n/** True when the camera is placed polar-ly. `target` is deliberately excluded: alone it is `lookAt` under a friendlier name and only becomes a placement once an orbit field is set; including it would discard `position` the moment a camera named a subject. */\n/** What an unset polar field of an orbiting camera reads as. */\nexport const ORBIT_CAMERA_DEFAULTS = { orbit: 0, elevation: 0, distance: 10 } as const;\n\nexport function isOrbitCamera3D(camera: CameraData3D): boolean {\n return camera.orbit !== undefined\n || camera.elevation !== undefined\n || camera.distance !== undefined;\n}\n\n/** A camera's effective position and aim, shared by the renderer and the editor's picking geometry so they can't disagree about where the camera is. Polar fields win over `position`/`lookAt` when any is set. */\nexport function resolveCameraPlacement(camera: CameraData3D): {\n position: Vector3;\n lookAt: Vector3 | undefined;\n} {\n const target = resolveVector3(camera.target ?? 0);\n\n if (!isOrbitCamera3D(camera)) {\n // `target` is the subject either way, so a position-placed camera still aims at it.\n const aim = camera.lookAt ?? camera.target;\n return {\n position: resolveVector3(camera.position ?? 0),\n lookAt: aim === undefined ? undefined : resolveVector3(aim),\n };\n }\n\n const distance = camera.distance ?? ORBIT_CAMERA_DEFAULTS.distance;\n const azimuth = ((camera.orbit ?? ORBIT_CAMERA_DEFAULTS.orbit) * Math.PI) / 180;\n // Just short of the pole: at ±90° the view is parallel to up and the look-at basis is undefined (the shot would snap to an arbitrary roll).\n const elevation = (clamp(camera.elevation ?? ORBIT_CAMERA_DEFAULTS.elevation, -89.9, 89.9) * Math.PI) / 180;\n\n const horizontal = Math.cos(elevation) * distance;\n\n return {\n position: {\n x: target.x + Math.sin(azimuth) * horizontal,\n y: target.y + Math.sin(elevation) * distance,\n z: target.z + Math.cos(azimuth) * horizontal,\n },\n lookAt: target,\n };\n}\n\nfunction clamp(value: number, low: number, high: number): number {\n return value < low ? low : value > high ? high : value;\n}\n", "import type { Color } from \"@/attributes/shape/fill/color/parser\";\nimport { ORBIT_CAMERA_DEFAULTS, type CameraData3D } from \"@/render3d/camera\";\nimport { lerpFill3D, type Fill3D } from \"@/render3d/fill3d\";\nimport type { Geometry3D, PolyhedronGeometry3D, BoxGeometry3D, CapsuleGeometry3D, CircleGeometry3D, ConeGeometry3D, CylinderGeometry3D, ExtrudeGeometry3D, LatheGeometry3D, PlaneGeometry3D, RingGeometry3D, SphereGeometry3D, TorusGeometry3D, TorusKnotGeometry3D, TubeGeometry3D } from \"@/render3d/geometry\";\nimport { Graphics3D, type LineStroke3D, type ModelAnimation3D } from \"@/render3d/graphics3d\";\nimport type { LightData3D, AmbientLightData3D, AreaLightData3D, DirectionalLightData3D, HemisphereLightData3D, PointLightData3D, SpotLightData3D } from \"@/render3d/light\";\nimport type { Material3D, Shading3D } from \"@/render3d/material\";\nimport type { EnvironmentData3D, FogData3D } from \"@/render3d/scene-settings\";\nimport type { Segments3D } from \"@/render3d/segments\";\nimport type { Transform3D, Blend3D, Faces3D } from \"@/render3d/transform\";\nimport type { Vector3Input } from \"@/render3d/vector3\";\nimport type { NodeOf } from \"@/components/factory/api\";\nimport { component3d } from \"@/components/factory/component3d\";\nimport { Types } from \"@/components/factory/types\";\nimport * as Material from \"@/components/modules/material\";\nimport { defined, optional, optionalColor, optionalNumber, optionalVector3, stated } from \"@/components/modules/three-entries\";\nimport type { Node3DProps } from \"@/components/trees/three/node3d\";\nimport type { Texture3D } from \"@/render3d/texture\";\n\n/** The 3D tree: groups, meshes, other drawables, lights, camera, fog and environment. */\n\nexport const Group3D = component3d({ key: \"group3d\" });\nexport type Group3D = NodeOf<typeof Group3D>;\n\nconst mesh = { geometry: optional<Geometry3D>(), ...Material.state };\n\nexport const Mesh3D = component3d({\n key: \"mesh3d\",\n state: mesh,\n render: (ctx, s) => ctx.draw(Material.mesh(s, s.geometry)),\n});\nexport type Mesh3D = NodeOf<typeof Mesh3D>;\n\nconst sweep = { startAngle: optional<number>(), sweep: optional<number>() };\nconst SWEEP_KEYS = [\"startAngle\", \"sweep\"] as const;\n\n/** A mesh of one built-in shape: `keys` are the entries its geometry descriptor takes. */\nfunction shape3d<const K extends string, const S extends Record<string, ReturnType<typeof optional>>>(\n key: K, type: Geometry3D[\"type\"], own: S, keys: readonly string[],\n) {\n return component3d({\n key,\n state: { ...mesh, ...own },\n render: (ctx, s) => ctx.draw(Material.mesh(s as never, stated<Geometry3D>(type, s, keys))),\n });\n}\n\nexport const Box3D = shape3d(\"box3d\", \"box\", {\n width: optional<number>(), height: optional<number>(), depth: optional<number>(),\n cornerRadius: optional<number>(), segments: optional<Segments3D>(),\n}, [\"width\", \"height\", \"depth\", \"cornerRadius\", \"segments\"]);\nexport type Box3D = NodeOf<typeof Box3D>;\n\nexport const Sphere3D = shape3d(\"sphere3d\", \"sphere\", {\n radius: optional<number>(), segments: optional<Segments3D>(), ...sweep,\n startLatitude: optional<number>(), latitudeSweep: optional<number>(),\n}, [\"radius\", \"segments\", \"startLatitude\", \"latitudeSweep\", ...SWEEP_KEYS]);\nexport type Sphere3D = NodeOf<typeof Sphere3D>;\n\nexport const Plane3D = shape3d(\"plane3d\", \"plane\", {\n width: optional<number>(), height: optional<number>(), segments: optional<Segments3D>(),\n}, [\"width\", \"height\", \"segments\"]);\nexport type Plane3D = NodeOf<typeof Plane3D>;\n\nexport const Cylinder3D = shape3d(\"cylinder3d\", \"cylinder\", {\n radius: optional<number | readonly [number, number]>(), height: optional<number>(),\n segments: optional<Segments3D>(), capped: optional<boolean>(), ...sweep,\n}, [\"radius\", \"height\", \"segments\", \"capped\", ...SWEEP_KEYS]);\nexport type Cylinder3D = NodeOf<typeof Cylinder3D>;\n\nexport const Cone3D = shape3d(\"cone3d\", \"cone\", {\n radius: optional<number>(), height: optional<number>(), segments: optional<Segments3D>(), capped: optional<boolean>(), ...sweep,\n}, [\"radius\", \"height\", \"segments\", \"capped\", ...SWEEP_KEYS]);\nexport type Cone3D = NodeOf<typeof Cone3D>;\n\nexport const Torus3D = shape3d(\"torus3d\", \"torus\", {\n radius: optional<number>(), thickness: optional<number>(), segments: optional<Segments3D>(), ...sweep,\n}, [\"radius\", \"thickness\", \"segments\", ...SWEEP_KEYS]);\nexport type Torus3D = NodeOf<typeof Torus3D>;\n\nexport const TorusKnot3D = shape3d(\"torus-knot3d\", \"torusKnot\", {\n radius: optional<number>(), thickness: optional<number>(), segments: optional<Segments3D>(),\n windings: optional<readonly [number, number]>(),\n}, [\"radius\", \"thickness\", \"segments\", \"windings\"]);\nexport type TorusKnot3D = NodeOf<typeof TorusKnot3D>;\n\nexport const Circle3D = shape3d(\"circle3d\", \"circle\", {\n radius: optional<number>(), segments: optional<Segments3D>(), ...sweep,\n}, [\"radius\", \"segments\", ...SWEEP_KEYS]);\nexport type Circle3D = NodeOf<typeof Circle3D>;\n\nexport const Ring3D = shape3d(\"ring3d\", \"ring\", {\n radius: optional<number>(), innerRadius: optional<number>(), segments: optional<Segments3D>(), ...sweep,\n}, [\"radius\", \"innerRadius\", \"segments\", ...SWEEP_KEYS]);\nexport type Ring3D = NodeOf<typeof Ring3D>;\n\nexport const Capsule3D = shape3d(\"capsule3d\", \"capsule\", {\n radius: optional<number>(), height: optional<number>(), segments: optional<Segments3D>(),\n}, [\"radius\", \"height\", \"segments\"]);\nexport type Capsule3D = NodeOf<typeof Capsule3D>;\n\nexport const Polyhedron3D = component3d({\n key: \"polyhedron3d\",\n state: { ...mesh, shape: Types.custom<PolyhedronGeometry3D[\"shape\"]>(\"icosahedron\"), radius: optional<number>(), segments: optional<Segments3D>() },\n render: (ctx, s) => ctx.draw(Material.mesh(s, stated<Geometry3D>(\"polyhedron\", s, [\"shape\", \"radius\", \"segments\"]))),\n});\nexport type Polyhedron3D = NodeOf<typeof Polyhedron3D>;\n\nexport const Extrude3D = shape3d(\"extrude3d\", \"extrude\", {\n path: optional<unknown>(), depth: optional<number>(), segments: optional<Segments3D>(), bevel: optional<unknown>(),\n}, [\"path\", \"depth\", \"segments\", \"bevel\"]);\nexport type Extrude3D = NodeOf<typeof Extrude3D>;\n\nexport const Lathe3D = shape3d(\"lathe3d\", \"lathe\", {\n points: optional<readonly unknown[]>(), segments: optional<Segments3D>(), ...sweep,\n}, [\"points\", \"segments\", ...SWEEP_KEYS]);\nexport type Lathe3D = NodeOf<typeof Lathe3D>;\n\nexport const Tube3D = shape3d(\"tube3d\", \"tube\", {\n points: optional<readonly Vector3Input[]>(), radius: optional<number>(), segments: optional<Segments3D>(), closed: optional<boolean>(),\n}, [\"points\", \"radius\", \"segments\", \"closed\"]);\nexport type Tube3D = NodeOf<typeof Tube3D>;\n\nexport const Instances3D = component3d({\n key: \"instances3d\",\n state: { ...mesh, instances: optional<readonly Transform3D[]>(), colors: optional<readonly Color[]>() },\n render: (ctx, s) => {\n if (!s.geometry || !s.instances?.length) return;\n ctx.draw(new Graphics3D().instances(s.geometry, Material.single(s), s.instances, { colors: s.colors }));\n },\n});\nexport type Instances3D = NodeOf<typeof Instances3D>;\n\nexport const Points3D = component3d({\n key: \"points3d\",\n state: mesh,\n render: (ctx, s) => {\n if (s.geometry) ctx.draw(new Graphics3D().points(s.geometry, Material.points(s)));\n },\n});\nexport type Points3D = NodeOf<typeof Points3D>;\n\nexport const Line3D = component3d({\n key: \"line3d\",\n state: {\n points: optional<readonly Vector3Input[]>(),\n geometry: optional<Geometry3D>(),\n closed: Types.custom(false),\n segments: Types.custom(false),\n stroke: optional<LineStroke3D>(),\n opacity: optional<number>(),\n material: optional<Material3D>(),\n },\n render: (ctx, s) => {\n if (!s.geometry && !s.points?.length) return;\n ctx.draw(new Graphics3D().line({\n points: s.geometry ? undefined : s.points, geometry: s.geometry, closed: s.closed, segments: s.segments,\n stroke: s.stroke, opacity: s.opacity, material: s.material,\n }));\n },\n});\nexport type Line3D = NodeOf<typeof Line3D>;\n\nexport const Sprite3D = component3d({\n key: \"sprite3d\",\n state: {\n fill: Types.custom<Fill3D | undefined>(undefined, { lerp: lerpFill3D as never }),\n opacity: optional<number>(),\n material: optional<Material3D>(),\n },\n render: (ctx, s) => ctx.draw(new Graphics3D().sprite({ fill: s.fill as Fill3D, opacity: s.opacity, material: s.material })),\n});\nexport type Sprite3D = NodeOf<typeof Sprite3D>;\n\nexport const Model3D = component3d({\n key: \"model3d\",\n state: {\n src: optional<string>(),\n animation: optional<readonly ModelAnimation3D[] | ModelAnimation3D>(),\n override: optional<Readonly<Record<string, Material3D>>>(),\n },\n render: (ctx, s) => {\n if (s.src) ctx.draw(new Graphics3D().model({ src: s.src, animation: s.animation, override: s.override }));\n },\n});\nexport type Model3D = NodeOf<typeof Model3D>;\n\n/**\n * A loaded model with its animation as two flat entries, `clip` (a name, or the index as a string; empty is the\n * first) and `clipTime` (seconds), since the timeline tweens a number but `Model3D.animation` is a list of records.\n * Still sampled at an explicit time, so seeking and playing give the same pose. Before a file is picked it draws an\n * unlit wireframe unit box, as a node recording no geometry has no box to pick or outline. Not registered: an\n * editor's node, not document API.\n */\nexport const ModelView3D = component3d({\n key: \"modelView3d\",\n state: {\n src: optional<string>(),\n animation: optional<readonly ModelAnimation3D[] | ModelAnimation3D>(),\n override: optional<Readonly<Record<string, Material3D>>>(),\n clip: \"\",\n clipTime: 0,\n },\n render: (ctx, s) => {\n if (!s.src) {\n ctx.draw(new Graphics3D().box({\n width: 1, height: 1, depth: 1,\n material: { type: \"basic\", color: \"#6b7280\", wireframe: true, transparent: true, opacity: 0.7 },\n }));\n return;\n }\n ctx.draw(new Graphics3D().model({ src: s.src, animation: { clip: modelClip(s.clip), time: s.clipTime }, override: s.override }));\n },\n});\nexport type ModelView3D = NodeOf<typeof ModelView3D>;\n\n/** A clip name, or a whole number as an index (`\"0\"` is the first clip, not one named `0`), or unset when empty. */\nfunction modelClip(clip: string): string | number | undefined {\n const trimmed = clip.trim();\n if (trimmed === \"\") return undefined;\n const index = Number(trimmed);\n return Number.isInteger(index) && index >= 0 ? index : trimmed;\n}\n\n/** A light that casts no shadow unless asked: shadow maps cost a render each. */\nconst castsNoShadow = { shadow: false } as const;\n\nexport const AmbientLight3D = component3d({\n key: \"ambient-light3d\",\n state: { color: optionalColor(), intensity: optional<number>() },\n render: (ctx, s) => ctx.light(stated<LightData3D>(\"ambient\", s, [\"color\", \"intensity\"])),\n});\nexport type AmbientLight3D = NodeOf<typeof AmbientLight3D>;\n\nexport const HemisphereLight3D = component3d({\n key: \"hemisphere-light3d\",\n state: { sky: optionalColor(), ground: optionalColor(), intensity: optional<number>() },\n render: (ctx, s) => ctx.light(stated<LightData3D>(\"hemisphere\", s, [\"sky\", \"ground\", \"intensity\"])),\n});\nexport type HemisphereLight3D = NodeOf<typeof HemisphereLight3D>;\n\nexport const DirectionalLight3D = component3d({\n key: \"directional-light3d\",\n state: { color: optionalColor(), intensity: optional<number>(), target: optionalVector3(\"origin\") },\n defaults: castsNoShadow,\n render: (ctx, s) => ctx.light(stated<LightData3D>(\"directional\", s, [\"color\", \"intensity\", \"target\", \"shadow\"])),\n});\nexport type DirectionalLight3D = NodeOf<typeof DirectionalLight3D>;\n\nexport const PointLight3D = component3d({\n key: \"point-light3d\",\n state: { color: optionalColor(), intensity: optional<number>(), distance: optional<number>(), decay: optional<number>() },\n defaults: castsNoShadow,\n render: (ctx, s) => ctx.light(stated<LightData3D>(\"point\", s, [\"color\", \"intensity\", \"distance\", \"decay\", \"shadow\"])),\n});\nexport type PointLight3D = NodeOf<typeof PointLight3D>;\n\nexport const SpotLight3D = component3d({\n key: \"spot-light3d\",\n state: {\n color: optionalColor(), intensity: optional<number>(), distance: optional<number>(), angle: optional<number>(),\n penumbra: optional<number>(), decay: optional<number>(), target: optionalVector3(\"origin\"),\n },\n defaults: castsNoShadow,\n render: (ctx, s) => ctx.light(stated<LightData3D>(\"spot\", s, [\"color\", \"intensity\", \"distance\", \"angle\", \"penumbra\", \"decay\", \"target\", \"shadow\"])),\n});\nexport type SpotLight3D = NodeOf<typeof SpotLight3D>;\n\nexport const AreaLight3D = component3d({\n key: \"area-light3d\",\n state: { color: optionalColor(), intensity: optional<number>(), width: optional<number>(), height: optional<number>() },\n render: (ctx, s) => ctx.light(stated<LightData3D>(\"area\", s, [\"color\", \"intensity\", \"width\", \"height\"])),\n});\nexport type AreaLight3D = NodeOf<typeof AreaLight3D>;\n\nconst CAMERA_KEYS = [\"target\", \"orbit\", \"elevation\", \"distance\", \"fov\", \"frustumHeight\", \"near\", \"far\", \"zoom\"] as const;\nconst ORBIT_KEYS = [\"orbit\", \"elevation\", \"distance\"] as const;\n\nexport const Camera3D = component3d({\n key: \"camera3d\",\n state: {\n type: Types.custom<CameraData3D[\"type\"]>(\"perspective\"),\n target: optionalVector3(\"origin\"),\n orbit: optional<number>(),\n elevation: optional<number>(),\n distance: optional<number>(),\n fov: optional<number>(),\n frustumHeight: optional<number>(),\n near: optional<number>(),\n far: optional<number>(),\n zoom: optional<number>(),\n },\n commands: {\n /** Only the given angles move, each from where it stands (the orbit default while unset). */\n orbitTo: {\n args: {\n orbit: optionalNumber({ step: 1, unit: \"°\" }),\n elevation: optionalNumber({ min: -89, max: 89, step: 1, unit: \"°\" }),\n distance: optionalNumber({ min: 0.01, step: 0.1 }),\n },\n run: (timeline, s) => {\n const from = {\n orbit: s.orbit ?? ORBIT_CAMERA_DEFAULTS.orbit,\n elevation: s.elevation ?? ORBIT_CAMERA_DEFAULTS.elevation,\n distance: s.distance ?? ORBIT_CAMERA_DEFAULTS.distance,\n };\n return timeline.animate((t) => {\n const out: Record<string, number> = {};\n for (const key of ORBIT_KEYS) {\n const end = timeline.args[key];\n if (end !== undefined) out[key] = from[key] + (end - from[key]) * t;\n }\n return out;\n });\n },\n },\n lookTo: { args: [\"target\"] },\n },\n render: (ctx, s) => {\n const data: Record<string, unknown> = { type: s.type };\n for (const key of CAMERA_KEYS) if (s[key] !== undefined) data[key] = s[key];\n ctx.camera(data as unknown as CameraData3D);\n },\n});\nexport type Camera3D = NodeOf<typeof Camera3D>;\n\nexport const Fog3D = component3d({\n key: \"fog3d\",\n state: { color: optionalColor(), near: optional<number>(), far: optional<number>(), density: optional<number>() },\n render: (ctx, s) => {\n const out: FogData3D = {};\n if (s.color !== undefined) out.color = s.color as Color;\n if (s.density !== undefined) out.density = s.density;\n else {\n if (s.near !== undefined) out.near = s.near;\n if (s.far !== undefined) out.far = s.far;\n }\n ctx.fog(out);\n },\n});\nexport type Fog3D = NodeOf<typeof Fog3D>;\n\nexport const Environment3D = component3d({\n key: \"environment3d\",\n state: {\n src: optional<string>(),\n faces: optional<readonly string[]>(),\n preset: optional<\"studio\">(),\n intensity: optional<number>(),\n background: optional<boolean>(),\n blur: optional<number>(),\n },\n render: (ctx, s) => {\n if (s.src === undefined && s.faces === undefined && s.preset === undefined) return ctx.environment(null);\n const out = defined<EnvironmentData3D>(s, [\"src\", \"faces\", \"preset\", \"intensity\", \"background\", \"blur\"]);\n if (s.rotationX || s.rotationY || s.rotationZ) out.rotation = [s.rotationX, s.rotationY, s.rotationZ];\n ctx.environment(out);\n },\n});\nexport type Environment3D = NodeOf<typeof Environment3D>;\n\n// What code building a 3D node names its props as.\n\ntype ParamsOf<G extends { type: string }> = Omit<G, \"type\">;\n/** A light's params, minus its discriminant and its shadow, which is a node prop of its own. */\ntype LightParamsOf<L extends { type: string }> = Omit<L, \"type\" | \"shadow\">;\n\nexport type Group3DProps = Node3DProps;\n\n/** The material shorthand as node props: exactly the keys {@link MaterialShorthand3D} promotes onto `Graphics3D` sugar methods, so `Box3D({ fill: \"red\" })` and `g3.box({ fill: \"red\" })` describe the same mesh, and each is tweenable. Renderer knobs (`depthWrite`, `alphaTest`, ...) live only on a `Mat.*` descriptor passed through {@link material}; `transparent` is derived; texture slots are fills. */\nexport interface Material3DProps {\n /** A full descriptor (or an array, for multi-material). Wins over the rest. */\n material: Material3D | readonly Material3D[] | undefined;\n /** What the surface is made of — the same value a 2D `fill` takes. */\n fill: Fill3D;\n opacity: number;\n roughness: number;\n metalness: number;\n emission: Color | undefined;\n emissionStrength: number;\n normalMap: Texture3D | undefined;\n roughnessMap: Texture3D | undefined;\n metalnessMap: Texture3D | undefined;\n aoMap: Texture3D | undefined;\n alphaMap: Texture3D | undefined;\n envMapIntensity: number;\n wireframe: boolean;\n /** Facet or smooth shading. Default `\"smooth\"`. */\n shading: Shading3D;\n /** Which faces to rasterize. Default `\"front\"`. */\n faces: Faces3D;\n vertexColors: boolean;\n blend: Blend3D;\n /** Shade with an unlit `basic` material instead of `standard`. */\n unlit: boolean;\n}\n\nexport interface Mesh3DProps extends Node3DProps, Partial<Material3DProps> {\n /** The geometry to draw. Set directly, or built from a geometry component's entries. */\n geometry: Geometry3D;\n}\n\nexport interface Box3DProps extends Mesh3DProps, Partial<ParamsOf<BoxGeometry3D>> { }\n\nexport interface Sphere3DProps extends Mesh3DProps, Partial<ParamsOf<SphereGeometry3D>> { }\n\nexport interface Plane3DProps extends Mesh3DProps, Partial<ParamsOf<PlaneGeometry3D>> { }\n\nexport interface Cylinder3DProps extends Mesh3DProps, Partial<ParamsOf<CylinderGeometry3D>> { }\n\nexport interface Cone3DProps extends Mesh3DProps, Partial<ParamsOf<ConeGeometry3D>> { }\n\nexport interface Torus3DProps extends Mesh3DProps, Partial<ParamsOf<TorusGeometry3D>> { }\n\nexport interface TorusKnot3DProps extends Mesh3DProps, Partial<ParamsOf<TorusKnotGeometry3D>> { }\n\nexport interface Circle3DProps extends Mesh3DProps, Partial<ParamsOf<CircleGeometry3D>> { }\n\nexport interface Ring3DProps extends Mesh3DProps, Partial<ParamsOf<RingGeometry3D>> { }\n\nexport interface Capsule3DProps extends Mesh3DProps, Partial<ParamsOf<CapsuleGeometry3D>> { }\n\nexport interface Polyhedron3DProps extends Mesh3DProps, Partial<ParamsOf<PolyhedronGeometry3D>> { }\n\nexport interface Extrude3DProps extends Mesh3DProps, Partial<ParamsOf<ExtrudeGeometry3D>> { }\n\nexport interface Lathe3DProps extends Mesh3DProps, Partial<ParamsOf<LatheGeometry3D>> { }\n\nexport interface Tube3DProps extends Mesh3DProps, Partial<ParamsOf<TubeGeometry3D>> { }\n\nexport interface Instances3DProps extends Mesh3DProps {\n /** Per-instance placement. Its length drives the instance count. */\n instances: readonly Transform3D[];\n /** Per-instance tint. Needs a material that reads instance colour. */\n colors: readonly Color[] | undefined;\n}\n\nexport type Points3DProps = Mesh3DProps;\n\nexport interface Line3DProps extends Node3DProps {\n /** The polyline's vertices. Give this or {@link geometry}, not both. */\n points: readonly Vector3Input[];\n /** An explicit geometry to draw the lines of (`Geo.edges(...)` for a wireframe outline); wins over {@link points}. */\n geometry: Geometry3D;\n closed: boolean;\n segments: boolean;\n stroke: LineStroke3D | undefined;\n opacity: number | undefined;\n material: Material3D | undefined;\n}\n\nexport interface Sprite3DProps extends Node3DProps {\n /** What the billboard shows — the same value a 2D `fill` takes. */\n fill: Fill3D;\n opacity: number | undefined;\n material: Material3D | undefined;\n}\n\nexport interface Model3DProps extends Node3DProps {\n /** Path to a glTF/GLB file. **Only glTF/GLB loads**; any other format (an OBJ included) resolves to an empty slot and draws nothing. */\n src: string;\n /** Baked animation clips, each sampled at an **explicit** time so a model is identical whether played forward or scrubbed to. */\n animation: readonly ModelAnimation3D[] | ModelAnimation3D | undefined;\n /** Replace materials on the loaded graph, keyed by mesh or material name. */\n override: Readonly<Record<string, Material3D>> | undefined;\n}\n\nexport interface AmbientLight3DProps extends Node3DProps, Partial<LightParamsOf<AmbientLightData3D>> { }\n\nexport interface HemisphereLight3DProps extends Node3DProps, Partial<LightParamsOf<HemisphereLightData3D>> { }\n\nexport interface DirectionalLight3DProps extends Node3DProps, Partial<LightParamsOf<DirectionalLightData3D>> { }\n\nexport interface PointLight3DProps extends Node3DProps, Partial<LightParamsOf<PointLightData3D>> { }\n\nexport interface SpotLight3DProps extends Node3DProps, Partial<LightParamsOf<SpotLightData3D>> { }\n\nexport interface AreaLight3DProps extends Node3DProps, Partial<LightParamsOf<AreaLightData3D>> { }\n\n/**\n * The camera: where the scene is viewed from. One node for both projections (`type=\"orthographic\"` is the flat one),\n * as a perspective and an orthographic camera are one object with a projection setting.\n *\n * Camera3D({ target: [0, 0.2, 0], orbit: -18, elevation: 12, distance: 13, fov: 42 })\n *\n * `target`/`orbit`/`elevation`/`distance` place the camera in polar coordinates around what it looks at, which is\n * what a camera move almost always is (via `position` it is a sin/cos pair recomputed every frame). `position` and\n * `lookAt` still work for a pinned shot; setting any polar field takes over, so the two are never half applied.\n * Parenting to a moving `Group3D` carries the shot with the rig.\n *\n * `near`/`far` come from the scene bounds unless set, and aspect always tracks the viewport's layout box. An\n * asymmetric orthographic frustum is a `params` override. A scene with no camera gets a default framing; with\n * several, the last wins.\n */\nexport interface Camera3DProps extends Node3DProps {\n /** `\"perspective\"` (default) or `\"orthographic\"`. */\n type: CameraData3D[\"type\"];\n /** The point the camera looks at and orbits around: `lookAt` under a name that reads right beside `orbit`, and the centre they turn about when any polar field is set. */\n target: Vector3Input | undefined;\n /** Azimuth around {@link target}, in **degrees**. */\n orbit: number | undefined;\n /** Angle above the horizon, in **degrees**. */\n elevation: number | undefined;\n distance: number | undefined;\n /** Perspective only: vertical field of view in **degrees**. Default 50. */\n fov: number | undefined;\n /** Orthographic only: visible world height. Default 10. */\n frustumHeight: number | undefined;\n near: number | undefined;\n far: number | undefined;\n zoom: number | undefined;\n}\n\n/** The two scene-wide nodes, fog and environment. Nodes because they are about the space (fog the air, environment the sky); positionless, so declaring two of a kind is not an error but only the last takes effect. Shadows, tone mapping and post effects are `Canvas3D` props, and the backdrop is the viewport's 2D `fill`. */\n\nexport interface Fog3DProps extends Node3DProps {\n /** Defaults to the viewport's own fill. */\n color: Color | undefined;\n /** Distance at which fog starts. Linear fog. */\n near: number | undefined;\n /** Distance at which fog is total. Linear fog. */\n far: number | undefined;\n /** Exponential-squared falloff. Wins over {@link near}/{@link far}. */\n density: number | undefined;\n}\n\nexport interface Environment3DProps extends Node3DProps {\n /**\n * A 360° panorama — `.hdr`/`.exr` for real IBL, or a plain image.\n * **Inert today**: no backend loads it, so only `preset` renders.\n */\n src: string | undefined;\n /** Six cubemap faces in three's order: +X, −X, +Y, −Y, +Z, −Z. **Inert today**: no backend loads them. */\n faces: readonly string[] | undefined;\n /** A generated studio interior. Needs no asset. The only environment that renders. */\n preset: \"studio\" | undefined;\n intensity: number | undefined;\n /** Also draw it behind the scene, as an infinitely distant sky. */\n background: boolean | undefined;\n /** Blur the background only, 0–1. The lighting stays sharp. */\n blur: number | undefined;\n}\n", "import type { NodeOf } from \"@/components/factory/api\";\nimport { component2d } from \"@/components/factory/component2d\";\nimport * as Corners from \"@/components/modules/corners\";\nimport * as Flow from \"@/components/modules/flow\";\nimport * as Paint from \"@/components/modules/paint\";\nimport * as View3D from \"@/components/modules/view3d\";\nimport type { PostEffect3D, Shadows3D, ToneMapping3D } from \"@/render3d/scene-settings\";\nimport type { RectProps } from \"@/components/builtins/geometry/geometry\";\nimport type { Color } from \"@/attributes/shape/fill/color/parser\";\n\n/**\n * The 3D viewport: a rect whose top fill layer is its 3D children's scene, seen\n * by their camera (or the default one), with its 2D children drawn over it.\n */\nexport const Canvas3D = component2d({\n key: \"canvas3d\",\n state: { ...Paint.state, ...Flow.state, ...Corners.state, ...View3D.state },\n defaults: { width: \"fill\", height: \"fill\" },\n commands: { ...Paint.commands, ...View3D.commands },\n allowedChildren: [\"2d\", \"3d\"],\n load: (loader) => View3D.load(loader),\n measure: (measurer, state, children) => Flow.measure(measurer, state, children, Paint.inset(state)),\n layout: (box, state, children) => Flow.layout(box, state, children, Paint.inset(state)),\n render: (ctx, state) => View3D.draw(ctx, state),\n});\n\nexport type Canvas3D = NodeOf<typeof Canvas3D>;\n\n// What code building a 3D viewport names its props as.\n\nexport interface Canvas3DProps extends RectProps {\n /** Ceiling on the 3D buffer's device-pixel ratio, default 2; lower it for an expensive scene (renders smaller, scaled up on composite). */\n maxPixelRatio: number;\n /** Multisample the 3D pass. Default true. */\n antialias: boolean;\n /** Turns shadow casting on for the scene: a switch, or `{ quality }`. A render setting, so a prop rather than a `<Shadows3D>` node (it has no position, and two of them meant one silently did nothing). */\n shadows: Shadows3D;\n /** How HDR colour is compressed to what the screen can show. Default `\"aces\"`. */\n tone: ToneMapping3D;\n /** Stops of exposure applied before tone mapping. Default 1. */\n exposure: number;\n /** Post-processing inside the 3D composite: `bloom`, `ssao`, `dof`, `outline`. Short by design: the 2D `effects` chain already runs over the composited result, so only passes needing depth, object ids or pre-tone-mapping HDR radiance are here. **Inert today**: the chain is recorded and no pass is applied (the first set warns in development); use the viewport's 2D `effects`. */\n post: PostEffect3D | readonly PostEffect3D[];\n /** The camera as three numbers rather than a `<Camera3D>` child, so a timeline `to` can tween it, a scrub reproduce it, and a drag-to-orbit write the values the timeline reads. Only read when the scene has no camera of its own. */\n\n /** Camera orbit about the vertical axis, in **degrees**. Animate this to spin. */\n orbit: number;\n /** Camera elevation above the ground plane, in **degrees**. */\n elevation: number;\n /** Camera distance from the origin, in scene units. */\n zoom: number;\n /** Vertical field of view, in **degrees**. */\n fov: number;\n /** Strength of the ambient fill. */\n ambientIntensity: number;\n /** Colour of the ambient fill. White leaves the meshes' own colours alone. */\n ambientColor: Color;\n /** Strength of the key light; the rim light is derived from it. */\n keyIntensity: number;\n /** Colour of the key light, and of the rim derived from it. */\n keyColor: Color;\n\n /** Whether the ground plane is drawn. **Off by default**: it is an authoring reference, not part of the picture. */\n showGrid: boolean;\n /** Total extent of the grid, in scene units. */\n gridSize: number;\n /** How many cells across it. */\n gridDivisions: number;\n /** Every Nth line is drawn heavier. */\n gridMajorEvery: number;\n gridColor: Color;\n gridMajorColor: Color;\n /** Whether the two coloured axis lines are drawn. Off by default, as above. */\n showAxes: boolean;\n axisXColor: Color;\n axisZColor: Color;\n /** How much of the way to the edge the grid has faded out, in `[0, 1]`. */\n gridFade: number;\n /** What the grid fades into when the node's own fills don't answer. **Derived, not authored**: the horizon dissolves into the first solid layer of `fill` (the background), falling back to this only when the stack has none; a different colour would ring the horizon with a halo, so there is nothing to keep in step (see {@link Canvas3DView.fadeColor}). Same rule as fog with no colour (`View3D.scene`). */\n gridFadeColor: Color;\n}\n", "import type { EaseSpec } from \"@/tween/ease/spec\";\nimport { loopPasses, type LoopSpec } from \"@/tween/loop\";\nimport type { Theme } from \"@/project/config\";\n\n/**\n * A loop is stored on a {@link CommandSpec} like an {@link EaseSpec}, but its arithmetic lives with the tweens\n * (`tween/loop.ts`).\n */\nexport type { LoopDirection, LoopSpec } from \"@/tween/loop\";\n\n/**\n * The clip document, as data: JSON-serializable by construction (no functions, no class instances), so it\n * round-trips through a file or a database column. Nodes are code (a class registered under a string key,\n * `document/registry.ts`, where anything JSON cannot express belongs); documents are data.\n */\n\n/**\n * One node as a flat row, not a nested tree: a command addresses its target by `id`, and \"move this under\n * that\" stays a single-field edit (`parentId` is a self-referencing foreign key). The scene root is the one\n * row with `id: \"\"`, `type: \"canvas2d\"` and `parentId: null`.\n */\nexport interface NodeSpec {\n id: string;\n /**\n * Registry key of the node's class. A key the registry lacks builds as an inert placeholder keeping the row's\n * id, props and children, reported in `buildErrors` (`missing-node.ts`), so one missing component costs one\n * node, not the clip.\n */\n type: string;\n /**\n * The handle an **expression** names this node by: `\"=[card.x]\"` reads the `x` of the node keyed `card`.\n *\n * Optional and never generated, unlike {@link id}: a node has one because an author wrote one. Unique per\n * document, or `[card.x]` would mean whichever row was read last. A `parentId` or `targetId` is always an\n * {@link id}, never a key. Not a display label.\n */\n key?: string;\n parentId: string | null;\n /** Load-bearing: a `row`/`column` parent lays its children out in exactly this order. */\n layerOrder: number;\n /**\n * **Sparse**: only what differs from the type's declared defaults, which keeps a document diff small and lets\n * a change to a default reach existing documents.\n */\n props: Record<string, unknown>;\n}\n\n/**\n * A {@link NodeSpec} placed on a clip's clock. The span is a field of the node, not a pair of commands, so a\n * node is the same row in a still or a composition. Not `start`/`end`: a painted node owns those as path-trim\n * props.\n */\nexport interface TimedNodeSpec extends NodeSpec {\n /** Absent is `0`. */\n startAt?: number;\n /** Absent is never: it stays to the clip's end. */\n endAt?: number;\n}\n\n/**\n * A named value in neither the tree nor the command list, so a change happens in one place: twelve nodes\n * fading together are one `variableTo` and twelve props bound to `\"=[fade]\"`.\n *\n * A variable has no presence span: it holds its declared {@link value} from t=0 until a command changes it,\n * since an expression naming one that \"does not exist yet\" would be a broken document. Only an expression\n * reads a variable, and only in a prop, so variables cannot cycle; a prop reading another node's prop\n * (`[key.x]`) can, and `validate.ts` refuses it.\n */\nexport interface VariableSpec {\n /** Commands target it and `[id]` in an expression names it: one key, so nothing to keep in sync. */\n id: string;\n name?: string;\n /**\n * Any JSON value; a lone `\"=[x]\"` hands it through untouched. It is also the type every command that writes it\n * is expected to produce.\n */\n value: unknown;\n /**\n * Registry key (`\"number\"`, `\"vector2\"`, `\"vector3\"`, `\"color\"`, `\"step\"`, or one from `Registry.addLerp`); a\n * command may override it per tween. Absent is `\"number\"` for a numeric {@link value}, else `\"step\"`: snap at\n * the end rather than interpolate garbage.\n */\n lerp?: string;\n}\n\nexport type { EaseSpec } from \"@/tween/ease/spec\";\n\n/**\n * One command placed on the timeline. Sequence is `b.at === a.at + a.duration`, parallel is two commands\n * sharing an `at`, wait is a gap. Because every span is declared rather than discovered, the scene's duration,\n * asset windows and node lifespans are readable straight off the document (`runtime/analysis.ts`).\n */\nexport interface CommandSpec {\n id: string;\n /**\n * Registry key: `\"to\"`, `\"set\"`, `\"variableTo\"`, or any `command()` method a node class exposes. A command\n * changes what a node holds, never whether it exists; that is its {@link TimedNodeSpec} span.\n */\n type: string;\n /**\n * The node this command acts on, or `null` for the scene root (the `Canvas2D` with `id: \"\"`: layout frame,\n * background paint and camera).\n *\n * A variable command (`\"variableTo\"`, `\"variableSet\"`) names a {@link VariableSpec} here; the command type\n * says which table. Ids are unique across nodes and variables so a host grouping rows by `targetId` cannot\n * conflate the two.\n */\n targetId: string | null;\n /**\n * Seconds, not frames, so the same scene at 30 and 60 fps is the same animation. Frames are derived (`at *\n * fps`).\n */\n at: number;\n /**\n * Seconds one pass takes. Absent or `0` is a stamp: it applies at once. One pass, not the whole span, so\n * {@link loop}ing repeats the motion rather than squeezing it into the same time. The span is {@link\n * commandSpan}.\n */\n duration?: number;\n easing?: EaseSpec;\n /**\n * A placement field, not part of {@link args}: the runtime wraps the built command, so every command type\n * loops by the same code. Absent runs it once.\n */\n loop?: LoopSpec;\n /**\n * Shape is per command type: `\"to\"`/`\"set\"`'s is the props diff, `\"variableTo\"`'s carries the `value`, a named\n * command carries its leading arguments by parameter name.\n */\n args: Record<string, unknown>;\n}\n\n/**\n * A **still**: a node tree and nothing else, one frame. Its own type because a still is edited and validated\n * differently: one carrying a duration or a half-applied tween should not be representable. The scene root is\n * the row in {@link nodes} with `id: \"\"` and `type: \"canvas2d\"`; omitting it gets the default root.\n */\nexport interface StillDocument {\n kind: \"still\";\n /** Absent is format 0 (written before the field existed); see `migrate.ts`. */\n formatVersion?: number;\n /** Order is irrelevant: `parentId`/`layerOrder` carry the structure. */\n nodes: NodeSpec[];\n variables?: VariableSpec[];\n /**\n * Colour tokens and typography presets this clip resolves against. On the clip, not only the project, because\n * a theme is part of what a clip looks like; a project's own `theme` is the default for clips that declare\n * none.\n */\n theme?: Theme;\n}\n\n/**\n * A **composition**: a still's node tree placed in time, plus the commands that animate it. The nodes are the\n * same rows a still holds, each with its own span. The root is the row with `id: \"\"` and `type: \"canvas2d\"`,\n * as on a still; a command targeting `null` animates it.\n */\nexport interface CompositionDocument {\n kind: \"composition\";\n /** Absent is format 0 (written before the field existed); see `migrate.ts`. */\n formatVersion?: number;\n /** Order is irrelevant: `parentId`/`layerOrder` carry the structure. */\n nodes: TimedNodeSpec[];\n variables?: VariableSpec[];\n /** Order is irrelevant; `at` is the placement. */\n commands: CommandSpec[];\n /** Colour tokens and typography presets this clip resolves against; see {@link StillDocument.theme}. */\n theme?: Theme;\n\n /**\n * Total seconds. Defaults to the last moment anything happens (a command's end, or a node's start or finite\n * end); set it to hold the final frame or cut a scene short.\n */\n duration?: number;\n}\n\n/**\n * An **audio document**: a bus tree placed in time, with the commands that move it. Reads like {@link\n * CompositionDocument}. The root is implicit: `targetId: null` and `parentId: null` name the row with `id: \"\"`\n * and `type: \"audioBus\"`. There is no still case, since sound with no timeline is silence.\n */\nexport interface AudioDocument {\n kind: \"audio\";\n /** Absent is format 0 (written before the field existed); see `migrate.ts`. */\n formatVersion?: number;\n nodes: TimedNodeSpec[];\n variables?: VariableSpec[];\n /** Order is irrelevant; `at` is the placement. */\n commands: CommandSpec[];\n /** Same rule as {@link CompositionDocument}. */\n duration?: number;\n}\n\nexport type VisualDocument = StillDocument | CompositionDocument;\n\n/**\n * One union rather than two lists, because a track is a placement and does not care which. A composition's\n * `canvas2d` root already takes audio children, so an {@link AudioDocument} is the clip for when there is no\n * picture to go with the sound.\n */\nexport type ClipDocument = VisualDocument | AudioDocument;\n\nexport function isStillDocument(doc: VisualDocument): doc is StillDocument {\n return doc.kind === \"still\";\n}\n\nexport function isCompositionDocument(doc: VisualDocument): doc is CompositionDocument {\n return doc.kind === \"composition\";\n}\n\nexport function isAudioDocument(doc: ClipDocument): doc is AudioDocument {\n return doc.kind === \"audio\";\n}\n\nexport function hasTimeline(doc: ClipDocument): doc is CompositionDocument | AudioDocument {\n return doc.kind !== \"still\";\n}\n\n/**\n * A real id rather than a missing one. A host storing its root under another id maps it here at the boundary\n * where its rows become a document.\n */\nexport const ROOT_NODE_ID = \"\";\n\nexport interface NodeSpan {\n start: number;\n end: number;\n}\n\nexport function nodeSpan(spec: NodeSpec | TimedNodeSpec): NodeSpan {\n const timed = spec as TimedNodeSpec;\n return { start: timed.startAt ?? 0, end: timed.endAt ?? Infinity };\n}\n\n/**\n * A node's own span intersected with every ancestor's: a child cannot outlive its parent. Empty (`start >=\n * end`) when the spans never overlap; `undefined` for an id no row declares.\n */\nexport function effectiveSpan(nodes: readonly (NodeSpec | TimedNodeSpec)[], id: string): NodeSpan | undefined {\n return effectiveSpanIn(new Map(nodes.map((n) => [n.id, n])), id);\n}\n\n/** {@link effectiveSpan} for every row at once, each ancestor chain walked once. */\nexport function effectiveSpans(nodes: readonly (NodeSpec | TimedNodeSpec)[]): Map<string, NodeSpan> {\n const byId = new Map(nodes.map((n) => [n.id, n]));\n const spans = new Map<string, NodeSpan>();\n const chain: (NodeSpec | TimedNodeSpec)[] = [];\n const inChain = new Set<string>();\n for (const start of byId.values()) {\n if (spans.has(start.id)) continue;\n chain.length = 0;\n inChain.clear();\n let above: NodeSpan | undefined;\n let spec: NodeSpec | TimedNodeSpec | undefined = start;\n while (spec) {\n const known = spans.get(spec.id);\n if (known) {\n above = known;\n break;\n }\n if (inChain.has(spec.id)) {\n /**\n * A parent cycle has no top to fold down from; an invalid document gets the single-id answer for each member.\n */\n for (const member of chain) spans.set(member.id, effectiveSpanIn(byId, member.id)!);\n chain.length = 0;\n break;\n }\n chain.push(spec);\n inChain.add(spec.id);\n spec = spec.parentId === null ? undefined : byId.get(spec.parentId);\n }\n for (let i = chain.length - 1; i >= 0; i--) {\n const span = nodeSpan(chain[i]);\n if (above) {\n span.start = Math.max(span.start, above.start);\n span.end = Math.min(span.end, above.end);\n }\n spans.set(chain[i].id, span);\n above = span;\n }\n }\n return spans;\n}\n\n/** @internal {@link effectiveSpan} over an id map a caller already holds. */\nexport function effectiveSpanIn(\n byId: ReadonlyMap<string, NodeSpec | TimedNodeSpec>,\n id: string,\n): NodeSpan | undefined {\n let spec = byId.get(id);\n if (!spec) return undefined;\n const span = nodeSpan(spec);\n const seen = new Set<string>();\n while (spec.parentId !== null && !seen.has(spec.id)) {\n seen.add(spec.id);\n const parent = byId.get(spec.parentId);\n if (!parent) break;\n const own = nodeSpan(parent);\n span.start = Math.max(span.start, own.start);\n span.end = Math.min(span.end, own.end);\n spec = parent;\n }\n return span;\n}\n\n/** What a timed node becomes when it lands in a still. */\nexport function untimed(spec: NodeSpec | TimedNodeSpec): NodeSpec {\n const { startAt: _startAt, endAt: _endAt, ...rest } = spec as TimedNodeSpec;\n return rest;\n}\n\n/**\n * One pass, or every pass of a counted loop. An unlimited loop counts as **one**: it runs for as long as there\n * is clip, and letting it answer here would make a command ask for a scene that can never end.\n */\nexport function commandSpan(command: CommandSpec): number {\n const duration = command.duration ?? 0;\n if (duration <= 0 || !command.loop || command.loop.count === null) return duration;\n return duration * loopPasses(command.loop);\n}\n\n/**\n * Its declared `duration`, else the last moment anything happens (a command's end, a node's arrival or finite\n * departure). A still has none.\n */\nexport function documentDuration(doc: ClipDocument): number {\n if (!hasTimeline(doc)) return 0;\n if (doc.duration !== undefined) return doc.duration;\n let end = 0;\n for (const command of doc.commands) {\n end = Math.max(end, command.at + commandSpan(command));\n }\n for (const node of doc.nodes) {\n if (node.startAt !== undefined) end = Math.max(end, node.startAt);\n if (node.endAt !== undefined && Number.isFinite(node.endAt)) end = Math.max(end, node.endAt);\n }\n return end;\n}\n", "import type { Size2D } from \"@/attributes/layout/size\";\nimport type { Theme } from \"@/project/config\";\n\nimport type { ClipDocument, VisualDocument } from \"./types\";\nimport { documentDuration } from \"./types\";\n\n/**\n * The project as data: a whole video, the one thing the runtime plays. It is the clip document's idea one\n * level up: rows placed at times, evaluated rather than played.\n *\n * One list of tracks serves picture and sound, since a {@link ClipDocument} is a still, a composition or an\n * audio document and a composition already carries both. Array position is paint order, first entry at the\n * back, as in a `fill` array: a background is the first track, an overlay the last, a cross-dissolve two\n * tracks whose spans overlap and whose clips fade themselves.\n */\nexport interface ProjectDocument {\n kind: \"project\";\n /** Absent is format 0 (written before the field existed); see `migrate.ts`. */\n formatVersion?: number;\n name: string;\n /** Target frame rate. Defaults to 60. */\n fps?: number;\n /** Output canvas dimensions in pixels. Defaults to 1920×1080. */\n viewport?: Size2D;\n theme?: Theme;\n /** Array position is paint order; the first entry is at the back. */\n tracks: Track[];\n}\n\n/**\n * One clip placed on the project timeline. The clip document is inline, not referenced by id: a shared id\n * would cost an id space, a resolution step and a dangling-reference failure mode, and would not buy\n * deduplication, since repeated content mostly differs per placement (a lower third with different text).\n */\nexport interface Track {\n /**\n * Stable identity, so the runtime can keep a track's built tree across an edit that leaves its clip untouched.\n */\n id: string;\n name?: string;\n clip: ClipDocument;\n /**\n * Second on the project timeline at which this clip's own clock reads 0. Authored, never derived from the row\n * above, so a start cannot move because a neighbour changed.\n */\n startAt?: number;\n /**\n * Required, so a project's length is arithmetic over its tracks rather than measured out of a media file: a\n * three-minute music bed cannot silently stretch a thirty-second edit. Longer than the document holds its last\n * frame; shorter cuts it off, which is also what lets a still (no length at all) be a backdrop.\n */\n duration: number;\n}\n\nexport function isProjectDocument(doc: unknown): doc is ProjectDocument {\n return typeof doc === \"object\" && doc !== null && (doc as ProjectDocument).kind === \"project\";\n}\n\n/**\n * A lone still or composition becomes the only track of a project around it. Viewport and fps describe the\n * output, not the clip, so they come from the caller.\n */\nexport function asProjectDocument(\n doc: ProjectDocument | VisualDocument,\n output: { name?: string; viewport?: Size2D; fps?: number } = {},\n): ProjectDocument {\n if (isProjectDocument(doc)) return doc;\n return {\n kind: \"project\",\n ...(doc.formatVersion !== undefined && { formatVersion: doc.formatVersion }),\n name: output.name ?? \"Untitled\",\n fps: output.fps,\n viewport: output.viewport,\n theme: doc.theme,\n tracks: [{ id: \"clip\", clip: doc, duration: documentDuration(doc) }],\n };\n}\n", "import type { ProjectDocument } from \"./project\";\nimport type { ClipDocument } from \"./types\";\n\n/**\n * Saved documents outlive the engine that wrote them, so each carries its format and this module carries every\n * step from one format to the next. A step is a pure function over JSON: it never mutates its input and never\n * needs a registry, so a host can run it over a row it has not opened. Steps only go up; a document newer than\n * the engine is refused with {@link DocumentTooNewError} rather than read as whatever it resembles.\n */\n\n/** The format this engine reads natively and writes. A document without `formatVersion` is format 0. */\nexport const DOCUMENT_FORMAT_VERSION = 3;\n\nexport class DocumentTooNewError extends Error {\n readonly version: number;\n readonly supported: number;\n\n constructor(version: number, supported: number = DOCUMENT_FORMAT_VERSION) {\n super(\n `This document is format ${version}, newer than this engine reads (format ${supported}). ` +\n `Open it with a newer engine.`,\n );\n this.name = \"DocumentTooNewError\";\n this.version = version;\n this.supported = supported;\n }\n}\n\nexport type JsonDocument = Record<string, unknown>;\n\nexport interface DocumentChange {\n from: number;\n path: string;\n message: string;\n}\n\nexport type NoteChange = (path: string, message: string) => void;\n\n/** The step from format {@link from} to `from + 1`. */\nexport interface DocumentMigration {\n readonly from: number;\n readonly description: string;\n /** Run on every clip document, standalone or inside a project's track. */\n readonly clip?: (clip: JsonDocument, note: NoteChange) => JsonDocument;\n readonly project?: (project: JsonDocument, note: NoteChange) => JsonDocument;\n}\n\nexport interface DocumentMigrationResult<T> {\n document: T;\n from: number;\n to: number;\n changes: DocumentChange[];\n}\n\n/**\n * A release that changes what a stored document means adds the next step here, bumps {@link\n * DOCUMENT_FORMAT_VERSION}, and gives the step a test (`tests/migrate.test.ts`).\n */\nexport const DOCUMENT_MIGRATIONS: readonly DocumentMigration[] = [\n {\n from: 0,\n description: \"Documents start carrying `formatVersion`; a clip's retired `constants` rows become `variables`.\",\n clip: (clip, note) => {\n if (!Array.isArray(clip.constants)) return clip;\n const { constants, ...rest } = clip;\n const variables = Array.isArray(rest.variables) ? [...rest.variables] : [];\n for (const row of constants as unknown[]) {\n if (typeof row !== \"object\" || row === null) {\n variables.push(row);\n continue;\n }\n const { kind: _kind, ...variable } = row as Record<string, unknown>;\n variables.push(variable);\n }\n note(\"constants\", `${constants.length} constant row(s) moved into \\`variables\\`.`);\n return { ...rest, variables };\n },\n },\n {\n from: 1,\n description:\n \"SkSL is retired: every shader fill, shader effect and shader pack written in it says `language: \\\"sksl\\\"`, \" +\n \"the `sksl` effect key becomes `shader`, and `coords` is dropped.\",\n clip: (clip, note) => retireSkSL(clip, \"\", note) as JsonDocument,\n },\n {\n from: 2,\n description: \"An image or video fill's retired `filters` prop moves into `preset.adjustments`.\",\n clip: (clip, note) => retireFillFilters(clip, \"\", note) as JsonDocument,\n },\n];\n\n/** SkSL's entry point or an SkSL `uniform` declaration, neither of which a WGSL source can contain. */\nconst SKSL_SOURCE = /\\b(?:half4|float4|vec4)\\s+main\\s*\\(|^\\s*uniform\\s+\\w+\\s+\\w+/m;\n\ntype JsonObject = Record<string, unknown>;\n\nconst isObject = (value: unknown): value is JsonObject =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n// Fills and effects sit in node props, named fills, effect and filter arrays,\n// command values and tween keyframes alike, so the whole clip is walked.\nfunction retireSkSL(value: unknown, path: string, note: NoteChange): unknown {\n if (Array.isArray(value)) {\n let out: unknown[] | undefined;\n value.forEach((item, i) => {\n const next = retireSkSL(item, `${path}[${i}]`, note);\n if (next !== item) (out ??= [...value])[i] = next;\n });\n return out ?? value;\n }\n if (!isObject(value)) return value;\n let out: JsonObject | undefined;\n for (const [key, item] of Object.entries(value)) {\n const next = retireSkSL(item, path ? `${path}.${key}` : key, note);\n if (next !== item) (out ??= { ...value })[key] = next;\n }\n return retireShader(out ?? value, path, note);\n}\n\nfunction retireShader(shader: JsonObject, path: string, note: NoteChange): JsonObject {\n const legacyKey = shader.type === \"sksl\";\n const isShader = legacyKey\n || (shader.type === \"shader\" && (typeof shader.source === \"string\" || typeof shader.shader === \"string\"))\n || ((shader.scope === \"fill\" || shader.scope === \"effect\") && typeof shader.source === \"string\");\n if (!isShader) return shader;\n\n const out: JsonObject = { ...shader };\n if (legacyKey) out.type = \"shader\";\n const moved = out.type === \"shader\" && typeof out.shader === \"string\" && out.source === undefined;\n if (moved) {\n out.source = out.shader;\n delete out.shader;\n }\n // The `sksl` key meant SkSL whatever its source looked like, unless it said otherwise.\n const sksl = out.language === \"sksl\"\n || (out.language === undefined && (legacyKey || SKSL_SOURCE.test(typeof out.source === \"string\" ? out.source : \"\")));\n const stamped = sksl && out.language === undefined;\n if (stamped) out.language = \"sksl\";\n const hadCoords = \"coords\" in out;\n delete out.coords;\n\n if (sksl) note(path, \"SkSL shaders no longer draw; port it to WGSL.\");\n else if (legacyKey) note(path, \"The retired `sksl` effect key is now `shader`.\");\n else if (moved) note(path, \"The shader's `shader` field is now `source`.\");\n else if (hadCoords) note(path, \"`coords` dropped; it only ever applied to SkSL.\");\n return legacyKey || moved || stamped || hadCoords ? out : shader;\n}\n\n// Image and video fills sit in node props, named fills, command values and tween\n// keyframes alike, so the whole clip is walked. A `Video` node's own `filters` prop\n// lives in its `props`, which has no `type`, so it is never mistaken for a fill's.\nfunction retireFillFilters(value: unknown, path: string, note: NoteChange): unknown {\n if (Array.isArray(value)) {\n let out: unknown[] | undefined;\n value.forEach((item, i) => {\n const next = retireFillFilters(item, `${path}[${i}]`, note);\n if (next !== item) (out ??= [...value])[i] = next;\n });\n return out ?? value;\n }\n if (!isObject(value)) return value;\n let out: JsonObject | undefined;\n for (const [key, item] of Object.entries(value)) {\n const next = retireFillFilters(item, path ? `${path}.${key}` : key, note);\n if (next !== item) (out ??= { ...value })[key] = next;\n }\n const fill = out ?? value;\n if (!(\"filters\" in fill) || !(fill.type === \"image\" || fill.type === \"video\") || typeof fill.src !== \"string\") return fill;\n\n const { filters, preset, ...rest } = fill;\n // A fill that somehow carried both keeps its preset's chain, as `resolveMediaPreset` always read it.\n const keeps = isObject(preset) && preset.adjustments !== undefined;\n note(path, keeps ? \"`filters` dropped; the fill's `preset.adjustments` already says the grade.\" : \"`filters` moved to `preset.adjustments`.\");\n if (keeps || (preset !== undefined && !isObject(preset))) return { ...rest, preset };\n return { ...rest, preset: { ...(isObject(preset) ? preset : {}), adjustments: filters } };\n}\n\nexport function documentFormatVersion(doc: unknown): number {\n if (typeof doc !== \"object\" || doc === null) return 0;\n const version = (doc as { formatVersion?: unknown }).formatVersion;\n if (version === undefined) return 0;\n if (typeof version !== \"number\" || !Number.isInteger(version) || version < 0) {\n throw new TypeError(`formatVersion must be a whole number >= 0 (got ${JSON.stringify(version)}).`);\n }\n return version;\n}\n\n/**\n * Bring a still, composition, audio or project document up to\n * {@link DOCUMENT_FORMAT_VERSION}.\n *\n * A clip inside a project with no `formatVersion` of its own is read at the\n * project's, since it was written alongside it. Anything that is not a\n * document comes back untouched, for validation to describe.\n */\nexport function migrateDocument<T extends ProjectDocument | ClipDocument>(doc: T): DocumentMigrationResult<T>;\nexport function migrateDocument(doc: unknown): DocumentMigrationResult<unknown>;\nexport function migrateDocument(doc: unknown): DocumentMigrationResult<unknown> {\n return migrateDocumentWith(doc, DOCUMENT_MIGRATIONS, DOCUMENT_FORMAT_VERSION);\n}\n\n/** @internal {@link migrateDocument} over a given list of steps, for a test pinning the runner. */\nexport function migrateDocumentWith(\n doc: unknown,\n migrations: readonly DocumentMigration[],\n target: number,\n): DocumentMigrationResult<unknown> {\n const from = documentFormatVersion(doc);\n if (from > target) throw new DocumentTooNewError(from, target);\n if (typeof doc !== \"object\" || doc === null || Array.isArray(doc)) {\n return { document: doc, from, to: from, changes: [] };\n }\n const changes: DocumentChange[] = [];\n const json = doc as JsonDocument;\n const migrated = json.kind === \"project\"\n ? migrateProject(json, from, migrations, target, changes)\n : migrateClip(json, from, migrations, target, changes, \"\");\n return { document: migrated, from, to: target, changes };\n}\n\nfunction stepsBetween(from: number, to: number, migrations: readonly DocumentMigration[]): DocumentMigration[] {\n const steps: DocumentMigration[] = [];\n for (let version = from; version < to; version++) {\n const step = migrations.find((m) => m.from === version);\n if (!step) throw new Error(`No document migration from format ${version} to ${version + 1}.`);\n steps.push(step);\n }\n return steps;\n}\n\nfunction noteInto(changes: DocumentChange[], from: number, prefix: string): NoteChange {\n return (path, message) => changes.push({ from, path: prefix && path ? `${prefix}.${path}` : prefix || path, message });\n}\n\n/** `stamp` false leaves a clip that inherits its project's version without a field of its own. */\nfunction migrateClip(\n clip: JsonDocument,\n from: number,\n migrations: readonly DocumentMigration[],\n target: number,\n changes: DocumentChange[],\n prefix: string,\n stamp = true,\n): JsonDocument {\n if (from === target) return clip;\n let out = clip;\n for (const step of stepsBetween(from, target, migrations)) {\n if (step.clip) out = step.clip(out, noteInto(changes, step.from, prefix));\n }\n return stamp ? { ...out, formatVersion: target } : out;\n}\n\nfunction migrateProject(\n project: JsonDocument,\n from: number,\n migrations: readonly DocumentMigration[],\n target: number,\n changes: DocumentChange[],\n): JsonDocument {\n let out = project;\n if (from < target) {\n for (const step of stepsBetween(from, target, migrations)) {\n if (step.project) out = step.project(out, noteInto(changes, step.from, \"\"));\n }\n }\n let tracksChanged = false;\n const tracks = Array.isArray(out.tracks)\n ? (out.tracks as unknown[]).map((track, i) => {\n if (typeof track !== \"object\" || track === null) return track;\n const clip = (track as { clip?: unknown }).clip;\n if (typeof clip !== \"object\" || clip === null || Array.isArray(clip)) return track;\n const own = (clip as { formatVersion?: unknown }).formatVersion !== undefined;\n const version = own ? documentFormatVersion(clip) : from;\n if (version > target) throw new DocumentTooNewError(version, target);\n const next = migrateClip(clip as JsonDocument, version, migrations, target, changes, `tracks[${i}].clip`, own);\n if (next === clip) return track;\n tracksChanged = true;\n return { ...(track as object), clip: next };\n })\n : out.tracks;\n if (from === target && !tracksChanged) return project;\n return { ...out, ...(tracksChanged ? { tracks } : {}), formatVersion: target };\n}\n", "import { isEaseCurve } from \"@/tween/ease/curve\";\nimport { EASE_KINDS } from \"@/tween/ease/spec\";\nimport { expressionOps } from \"./expression/ops\";\nimport { DOCUMENT_FORMAT_VERSION } from \"./migrate\";\nimport type { Registry } from \"./registry\";\nimport type {\n AudioDocument,\n ClipDocument,\n CommandSpec,\n CompositionDocument,\n EaseSpec,\n LoopSpec,\n NodeSpec,\n StillDocument,\n TimedNodeSpec,\n VariableSpec,\n} from \"./types\";\nimport { effectiveSpanIn } from \"./types\";\n\n/**\n * Hand-rolled because `@motionscript/core` has no runtime dependencies. Checks structure, not props (a node\n * class checks those where applied): what spans rows, i.e. that a parent exists, the tree has no cycle, and a\n * command's target is present when it runs. Audio rows are the exception: a ramp or transition is JSON their\n * nodes read unchecked, and one a device cannot schedule fails long after the document was accepted.\n */\n\nexport interface ValidationIssue {\n path: string;\n message: string;\n}\n\nexport interface ValidateOptions {\n /**\n * Also report every node type and command this registry cannot build. A build stands an inert placeholder in\n * for an unknown type and skips an unknown command, so this is the strict check.\n */\n registry?: Registry;\n}\n\nexport interface ValidationResult {\n valid: boolean;\n issues: ValidationIssue[];\n}\n\nconst LOOP_DIRECTIONS = new Set([\"normal\", \"reverse\", \"alternate\"]);\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\nfunction isTime(v: unknown): v is number {\n return typeof v === \"number\" && Number.isFinite(v) && v >= 0;\n}\n\nfunction checkEase(ease: unknown, path: string, issues: ValidationIssue[]): void {\n if (ease === undefined) return;\n if (!isPlainObject(ease)) {\n issues.push({ path, message: \"easing must be an object with a `kind`.\" });\n return;\n }\n const { kind, args } = ease as Partial<EaseSpec>;\n if (typeof kind !== \"string\" || !EASE_KINDS.has(kind)) {\n issues.push({\n path: `${path}.kind`,\n message: `easing kind must be one of ${[...EASE_KINDS].join(\", \")} (got ${JSON.stringify(kind)}).`,\n });\n return;\n }\n if (kind === \"custom\" && args !== undefined && typeof args !== \"string\" && !isEaseCurve(args)) {\n issues.push({\n path: `${path}.args`,\n message: \"a custom easing's args must be its curve — two or more `{ x, y }` points — or a registered ease's key.\",\n });\n }\n}\n\n/** An audio ease runs on a device with no `Registry`, so a custom one has to be its drawn curve. */\nfunction checkAudioEase(ease: unknown, path: string, issues: ValidationIssue[]): void {\n checkEase(ease, path, issues);\n if (isPlainObject(ease) && ease.kind === \"custom\" && !isEaseCurve(ease.args)) {\n issues.push({ path: `${path}.args`, message: \"an audio ease cannot name a registered ease; draw its curve (two or more `{ x, y }` points) instead.\" });\n }\n}\n\nfunction checkParam(value: unknown, path: string, issues: ValidationIssue[]): void {\n if (value === undefined || (typeof value === \"number\" && Number.isFinite(value)) || expressionOps.isSource(value)) return;\n if (!isPlainObject(value) || !Array.isArray(value.keys)) {\n issues.push({ path, message: \"must be a finite number, an expression or a ramp, `{ keys: [{ at, value }, …] }`.\" });\n return;\n }\n value.keys.forEach((key: unknown, i: number) => {\n const at = `${path}.keys[${i}]`;\n if (!isPlainObject(key)) {\n issues.push({ path: at, message: \"a ramp key must be an object.\" });\n return;\n }\n if ((key.at === undefined) === (key.before === undefined) || !isTime(key.at ?? key.before)) {\n issues.push({ path: at, message: \"a ramp key needs exactly one of `at` (seconds after the start) or `before` (seconds before the end), >= 0.\" });\n }\n if (typeof key.value !== \"number\" || !Number.isFinite(key.value)) {\n issues.push({ path: `${at}.value`, message: \"a ramp key's value must be a finite number.\" });\n }\n checkAudioEase(key.ease, `${at}.ease`, issues);\n });\n}\n\nconst TRANSITION_KEYS = new Set([\"duration\", \"curve\"]);\n\nfunction checkTransition(transition: unknown, path: string, issues: ValidationIssue[]): void {\n if (transition === undefined) return;\n if (!isPlainObject(transition)) {\n issues.push({ path, message: \"a transition must be an object, `{ duration, curve? }`.\" });\n return;\n }\n if (!isTime(transition.duration)) {\n issues.push({ path: `${path}.duration`, message: \"a transition's duration must be a finite number of seconds >= 0.\" });\n }\n if (transition.curve !== undefined && transition.curve !== \"equalPower\") checkAudioEase(transition.curve, `${path}.curve`, issues);\n for (const key of Object.keys(transition)) {\n if (!TRANSITION_KEYS.has(key)) issues.push({ path: `${path}.${key}`, message: `a transition has no \"${key}\" (yet): only duration and curve.` });\n }\n}\n\nfunction checkAudioProps(type: string, props: Record<string, unknown>, path: string, issues: ValidationIssue[]): void {\n if (\"filters\" in props) {\n issues.push({ path: `${path}.filters`, message: \"audio `filters` was renamed to `effects`.\" });\n }\n for (const name of [\"volume\", \"pan\", ...(type === \"sound\" ? [\"speed\"] : [])]) checkParam(props[name], `${path}.${name}`, issues);\n if (type === \"sound\" && props.loop === true && isPlainObject(props.speed)) {\n issues.push({ path: `${path}.speed`, message: \"a looping sound cannot ramp its speed: there is no one pass of the source for the ramp to run over.\" });\n }\n const effects = props.effects;\n if (effects !== undefined) {\n const list = Array.isArray(effects) ? effects : [effects];\n list.forEach((effect: unknown, i: number) => {\n const at = Array.isArray(effects) ? `${path}.effects[${i}]` : `${path}.effects`;\n if (!isPlainObject(effect) || typeof effect.type !== \"string\") {\n issues.push({ path: at, message: \"an effect must be an object with a `type`.\" });\n return;\n }\n for (const [field, value] of Object.entries(effect)) {\n if (field !== \"type\") checkParam(value, `${at}.${field}`, issues);\n }\n });\n }\n checkTransition(props.transitionIn, `${path}.transitionIn`, issues);\n checkTransition(props.transitionOut, `${path}.transitionOut`, issues);\n}\n\nfunction checkLoop(loop: unknown, path: string, issues: ValidationIssue[]): void {\n if (loop === undefined) return;\n if (!isPlainObject(loop)) {\n issues.push({ path, message: \"loop must be an object with a `count`.\" });\n return;\n }\n const { direction, count } = loop as Partial<LoopSpec>;\n if (count !== null && (typeof count !== \"number\" || !Number.isInteger(count) || count < 0)) {\n issues.push({\n path: `${path}.count`,\n message: \"loop count must be a whole number of repeats >= 0, or null to repeat for the rest of the clip.\",\n });\n }\n if (direction !== undefined && !LOOP_DIRECTIONS.has(direction)) {\n issues.push({\n path: `${path}.direction`,\n message: `loop direction must be one of ${[...LOOP_DIRECTIONS].join(\", \")} (got ${JSON.stringify(direction)}).`,\n });\n }\n}\n\nfunction checkNodeSpec(node: unknown, path: string, issues: ValidationIssue[]): node is NodeSpec {\n if (!isPlainObject(node)) {\n issues.push({ path, message: \"node must be an object.\" });\n return false;\n }\n let ok = true;\n const { id, type, parentId, layerOrder, props, key } = node as Partial<NodeSpec>;\n\n /**\n * `\"\"` is reserved for the scene root (see `checkRootShape`); any other node needs a real id, since an empty\n * one could never be a command's target.\n */\n if (typeof id !== \"string\") {\n issues.push({ path: `${path}.id`, message: \"id must be a string.\" });\n ok = false;\n }\n if (typeof type !== \"string\" || type.length === 0) {\n issues.push({ path: `${path}.type`, message: \"type must be a non-empty string.\" });\n ok = false;\n }\n if (parentId !== null && typeof parentId !== \"string\") {\n issues.push({ path: `${path}.parentId`, message: \"parentId must be a node id or null.\" });\n ok = false;\n }\n if (typeof layerOrder !== \"number\" || !Number.isFinite(layerOrder)) {\n issues.push({ path: `${path}.layerOrder`, message: \"layerOrder must be a finite number.\" });\n ok = false;\n }\n if (!isPlainObject(props)) {\n issues.push({ path: `${path}.props`, message: \"props must be an object (`{}` when nothing is set).\" });\n ok = false;\n } else if (type === \"sound\" || type === \"audioBus\") {\n checkAudioProps(type, props, `${path}.props`, issues);\n }\n if (key !== undefined) {\n if (typeof key !== \"string\" || key.length === 0) {\n issues.push({ path: `${path}.key`, message: \"key must be a non-empty string when present.\" });\n ok = false;\n } else if (key.includes(\"]\") || key.includes(\".\")) {\n /**\n * `[key.prop]` is the reference syntax, so either character names something an expression could never spell.\n */\n issues.push({\n path: `${path}.key`,\n message: `node key \"${key}\" cannot contain \"]\" or \".\" — it is referenced as \"[${key}.prop]\".`,\n });\n ok = false;\n }\n }\n return ok;\n}\n\ninterface NodeSite {\n spec: NodeSpec;\n path: string;\n}\n\n/**\n * Keys are their own namespace, separate from {@link checkIdSpace}: `[x]` is always a variable and `[x.p]`\n * always a node, and a key is never a `targetId`. Unique among keys all the same, or `[card.x]` would read\n * whichever row the build reached last.\n */\nfunction checkNodeKeys(sites: readonly NodeSite[], issues: ValidationIssue[]): Map<string, NodeSite> {\n const byKey = new Map<string, NodeSite>();\n for (const site of sites) {\n const key = site.spec.key;\n if (typeof key !== \"string\" || key.length === 0) continue;\n const existing = byKey.get(key);\n if (existing) {\n issues.push({\n path: `${site.path}.key`,\n message: `duplicate node key \"${key}\" (also declared at ${existing.path}).`,\n });\n continue;\n }\n byKey.set(key, site);\n }\n return byKey;\n}\n\n/**\n * The row with `id: \"\"` is the root: unparented and of the document kind's root type (`canvas2d` for a scene,\n * `audioBus` for audio). `targetId: null` names it.\n */\nfunction checkRootShape(\n spec: NodeSpec,\n path: string,\n rootType: string,\n issues: ValidationIssue[],\n): void {\n if (spec.id !== \"\") return;\n if (spec.type !== rootType || spec.parentId !== null) {\n issues.push({\n path,\n message: `the node with id \"\" is this document's root and must be \\`{ type: \"${rootType}\", parentId: null }\\`.`,\n });\n }\n}\n\nfunction checkCommandSpec(cmd: unknown, path: string, issues: ValidationIssue[]): cmd is CommandSpec {\n if (!isPlainObject(cmd)) {\n issues.push({ path, message: \"command must be an object.\" });\n return false;\n }\n let ok = true;\n const { id, type, targetId, at, duration, args } = cmd as Partial<CommandSpec>;\n\n if (typeof id !== \"string\" || id.length === 0) {\n issues.push({ path: `${path}.id`, message: \"id must be a non-empty string.\" });\n ok = false;\n }\n if (typeof type !== \"string\" || type.length === 0) {\n issues.push({ path: `${path}.type`, message: \"type must be a non-empty string.\" });\n ok = false;\n }\n if (targetId !== null && typeof targetId !== \"string\") {\n issues.push({ path: `${path}.targetId`, message: \"targetId must be a node id, or null for the scene root.\" });\n ok = false;\n }\n if (!isTime(at)) {\n issues.push({ path: `${path}.at`, message: \"at must be a finite number of seconds >= 0.\" });\n ok = false;\n }\n if (duration !== undefined && !isTime(duration)) {\n issues.push({ path: `${path}.duration`, message: \"duration must be a finite number of seconds >= 0.\" });\n ok = false;\n }\n if (!isPlainObject(args)) {\n issues.push({ path: `${path}.args`, message: \"args must be an object (`{}` when there are none).\" });\n ok = false;\n }\n checkEase((cmd as Partial<CommandSpec>).easing, `${path}.easing`, issues);\n checkLoop((cmd as Partial<CommandSpec>).loop, `${path}.loop`, issues);\n return ok;\n}\n\ninterface VariableSite {\n spec: VariableSpec;\n path: string;\n}\n\nfunction checkVariableSpec(v: unknown, path: string, issues: ValidationIssue[]): v is VariableSpec {\n if (!isPlainObject(v)) {\n issues.push({ path, message: \"variable must be an object.\" });\n return false;\n }\n let ok = true;\n const { id, name, value, lerp } = v as Partial<VariableSpec>;\n\n if (typeof id !== \"string\" || id.length === 0) {\n issues.push({ path: `${path}.id`, message: \"id must be a non-empty string.\" });\n ok = false;\n } else if (id.includes(\"]\")) {\n /**\n * `[id]` is the reference syntax, so a `]` in an id names something an expression could never spell.\n */\n issues.push({ path: `${path}.id`, message: `variable id \"${id}\" cannot contain \"]\" — it is referenced as \"[${id}]\".` });\n ok = false;\n }\n if (name !== undefined && typeof name !== \"string\") {\n issues.push({ path: `${path}.name`, message: \"name must be a string when present.\" });\n ok = false;\n }\n if (!(\"value\" in (v as object))) {\n issues.push({ path: `${path}.value`, message: \"value is required — a variable is what it holds before anything changes it.\" });\n ok = false;\n } else if (expressionOps.isSource(value)) {\n issues.push({\n path: `${path}.value`,\n message: \"a variable holds a value, not an expression — only a node prop can be bound.\",\n });\n ok = false;\n }\n if (lerp !== undefined && typeof lerp !== \"string\") {\n issues.push({ path: `${path}.lerp`, message: \"lerp must be a registered lerp key when present.\" });\n ok = false;\n }\n return ok;\n}\n\nfunction variableRows(rows: unknown, issues: ValidationIssue[]): VariableSite[] {\n if (rows === undefined) return [];\n if (!Array.isArray(rows)) {\n issues.push({ path: \"variables\", message: \"variables must be an array.\" });\n return [];\n }\n const sites: VariableSite[] = [];\n rows.forEach((v, i) => {\n const path = `variables[${i}]`;\n if (checkVariableSpec(v, path, issues)) sites.push({ spec: v, path });\n });\n return sites;\n}\n\nfunction checkVariables(sites: VariableSite[], issues: ValidationIssue[]): Map<string, VariableSite> {\n const byId = new Map<string, VariableSite>();\n for (const site of sites) {\n const existing = byId.get(site.spec.id);\n if (existing) {\n issues.push({\n path: `${site.path}.id`,\n message: `duplicate variable id \"${site.spec.id}\" (also declared at ${existing.path}).`,\n });\n continue;\n }\n byId.set(site.spec.id, site);\n }\n return byId;\n}\n\n/**\n * `undefined` when the ref has no dot and so names a variable. The dot is the discriminator in the parser,\n * here and in `ClipTimeline`.\n */\nfunction splitNodeRef(ref: string): { key: string; prop: string } | undefined {\n const dot = ref.indexOf(\".\");\n return dot < 0 ? undefined : { key: ref.slice(0, dot), prop: ref.slice(dot + 1) };\n}\n\n/**\n * A formula that does not parse, one naming an undeclared variable, and one naming a node key nothing carries.\n * All are silent otherwise: the first would throw from deep inside a build, the others would bind a prop to\n * nothing.\n */\nfunction checkExpressions(\n value: unknown,\n path: string,\n declared: ReadonlySet<string>,\n keyed: ReadonlySet<string>,\n issues: ValidationIssue[],\n): void {\n for (const site of expressionOps.collect(value, path)) {\n const parsed = expressionOps.tryParse(site.source);\n if (\"error\" in parsed) {\n issues.push({ path: site.path, message: parsed.error });\n continue;\n }\n for (const ref of parsed.expression.refs) {\n const node = splitNodeRef(ref);\n if (!node) {\n if (declared.has(ref)) continue;\n issues.push({\n path: site.path,\n message: keyed.has(ref)\n ? `expression references \"[${ref}]\", which is a node key — a node is not a value, ` +\n `so name the prop too: \"[${ref}.x]\".`\n : `expression references \"[${ref}]\", which this document does not declare. ` +\n `Declared: ${[...declared].map((k) => `[${k}]`).join(\", \") || \"none\"}.`,\n });\n continue;\n }\n if (node.key.length === 0 || node.prop.length === 0 || node.prop.includes(\".\")) {\n issues.push({\n path: site.path,\n message: `expression references \"[${ref}]\", which is not a node reference — one is \"[key.prop]\".`,\n });\n continue;\n }\n if (keyed.has(node.key)) continue;\n issues.push({\n path: site.path,\n message:\n `expression references \"[${ref}]\", but no node in this document is keyed \"${node.key}\". ` +\n `Keyed: ${[...keyed].join(\", \") || \"none\"}.`,\n });\n }\n }\n}\n\ninterface BoundProp {\n id: string;\n path: string;\n reads: string[];\n}\n\n/**\n * Per top-level prop, the granularity a binding is installed at (`bindProps` binds each key), so a formula\n * nested inside `padding` makes `padding` the prop that reads.\n */\nfunction boundProps(key: string, props: unknown, path: string, out: BoundProp[]): void {\n if (!isPlainObject(props)) return;\n for (const prop of Object.keys(props)) {\n const reads: string[] = [];\n for (const site of expressionOps.collect(props[prop], `${path}.${prop}`)) {\n const parsed = expressionOps.tryParse(site.source);\n if (\"error\" in parsed) continue;\n for (const ref of parsed.expression.refs) {\n if (splitNodeRef(ref)) reads.push(ref);\n }\n }\n if (reads.length > 0) out.push({ id: `${key}.${prop}`, path: `${path}.${prop}`, reads });\n }\n}\n\n/**\n * Refuse a prop that reads a prop that reads it back. Variables cannot cycle (nothing reads a variable), but\n * `[key.prop]` can. At runtime `PropSlot.get` refuses to re-enter and returns the last settled value, so a\n * cycle would otherwise be a frame that quietly disagrees with the document.\n *\n * Edges are per prop, not per node: `a.x -> b.y -> a.z` terminates and must not be rejected.\n */\nfunction checkExpressionCycles(bound: readonly BoundProp[], issues: ValidationIssue[]): void {\n const byId = new Map(bound.map((b) => [b.id, b]));\n const settled = new Set<string>();\n const stack: string[] = [];\n const reported = new Set<string>();\n\n const walk = (id: string): void => {\n const entry = byId.get(id);\n // A prop nothing binds cannot continue a chain: it holds a literal.\n if (!entry || settled.has(id)) return;\n const at = stack.indexOf(id);\n if (at >= 0) {\n if (!reported.has(id)) {\n const cycle = [...stack.slice(at), id];\n for (const member of cycle) reported.add(member);\n issues.push({\n path: entry.path,\n message: `expression cycle ${cycle.join(\" → \")} — a prop cannot read a prop that reads it back.`,\n });\n }\n return;\n }\n stack.push(id);\n for (const next of entry.reads) walk(next);\n stack.pop();\n settled.add(id);\n };\n\n for (const entry of bound) walk(entry.id);\n}\n\n/**\n * Check ids are unique, every `parentId` resolves, and no node is its own ancestor. A parent loop makes the\n * layout walk recurse until the stack overflows, with a trace pointing at the layout engine rather than the\n * two rows.\n */\nfunction checkTree(sites: readonly NodeSite[], issues: ValidationIssue[]): void {\n /**\n * `sites` holds only rows that passed their shape check, so a position in it is not a position in the\n * document: every issue path comes from the site.\n */\n const bySite = new Map<string, NodeSite>();\n for (const site of sites) {\n if (bySite.has(site.spec.id)) {\n issues.push({ path: `${site.path}.id`, message: `duplicate node id \"${site.spec.id}\".` });\n continue;\n }\n bySite.set(site.spec.id, site);\n }\n\n for (const site of sites) {\n const parent = site.spec.parentId;\n if (parent !== null && !bySite.has(parent)) {\n issues.push({\n path: `${site.path}.parentId`,\n message: `parentId \"${parent}\" is not a node in this document.`,\n });\n }\n }\n\n // Walk each node to the root; a revisit within one walk is a cycle.\n const settled = new Set<string>();\n for (const { spec: node } of sites) {\n if (settled.has(node.id)) continue;\n const seen = new Set<string>();\n let cursor: NodeSpec | undefined = node;\n while (cursor) {\n if (seen.has(cursor.id)) {\n issues.push({\n path: `${bySite.get(cursor.id)?.path}.parentId`,\n message: `node \"${cursor.id}\" is its own ancestor — parent chain forms a cycle.`,\n });\n break;\n }\n seen.add(cursor.id);\n if (settled.has(cursor.id)) break;\n const parentId: string | null = cursor.parentId;\n cursor = parentId === null ? undefined : bySite.get(parentId)?.spec;\n }\n for (const id of seen) settled.add(id);\n }\n}\n\n/**\n * Nodes and variables share one id space: a command names its target with one field, and a host groups\n * timeline rows by `targetId`, so a collision would draw two unrelated things on one track. A {@link\n * NodeSpec.key} is deliberately not in this space (see {@link checkNodeKeys}).\n */\nfunction checkIdSpace(\n nodes: NodeSpec[],\n variables: Map<string, VariableSite>,\n issues: ValidationIssue[],\n): void {\n for (const node of nodes) {\n const clash = variables.get(node.id);\n if (clash) {\n issues.push({\n path: `${clash.path}.id`,\n message: `\"${node.id}\" is already a node id — nodes and variables share one id space.`,\n });\n }\n }\n}\n\n/**\n * Refuse the fields the format folded away, by name: a document written before nodes carried spans would\n * otherwise fail as \"nodes must be an array\" or an unresolved `[id]`, neither of which names the fix.\n */\nfunction checkRetiredFields(doc: object, issues: ValidationIssue[]): void {\n if ((doc as { constants?: unknown }).constants !== undefined) {\n issues.push({\n path: \"constants\",\n message: \"constants were merged into `variables` — move each row there and drop its `kind`.\",\n });\n }\n}\n\nfunction checkFormatVersion(doc: object, issues: ValidationIssue[]): void {\n const version = (doc as { formatVersion?: unknown }).formatVersion;\n if (version === undefined) return;\n if (typeof version !== \"number\" || !Number.isInteger(version) || version < 0) {\n issues.push({ path: \"formatVersion\", message: \"formatVersion must be a whole number >= 0 when present.\" });\n } else if (version > DOCUMENT_FORMAT_VERSION) {\n issues.push({\n path: \"formatVersion\",\n message: `format ${version} is newer than this engine reads (${DOCUMENT_FORMAT_VERSION}) — open it with a newer engine.`,\n });\n }\n}\n\nconst RETIRED_PROJECT_FIELDS: Readonly<Record<string, string>> = {\n visualTracks: \"visual and audio tracks were merged into `tracks` — move each row there.\",\n audioTracks: \"visual and audio tracks were merged into `tracks` — move each row there.\",\n backgrounds: \"a background is a track — put it first in `tracks`.\",\n overlays: \"an overlay is a track — put it last in `tracks`.\",\n commands: \"a project has no commands — each clip carries its own.\",\n constants: \"a project has no constants — declare `variables` in each clip.\",\n};\n\nfunction checkVocabulary(\n sites: readonly NodeSite[],\n commands: readonly { spec: CommandSpec; path: string }[],\n rootType: string,\n variables: ReadonlyMap<string, VariableSite>,\n registry: Registry,\n issues: ValidationIssue[],\n): void {\n const typeOf = new Map<string, string>([[\"\", rootType]]);\n for (const site of sites) {\n typeOf.set(site.spec.id, site.spec.type);\n if (!registry.hasNode(site.spec.type)) {\n issues.push({ path: `${site.path}.type`, message: `node type \"${site.spec.type}\" is not registered.` });\n }\n }\n for (const { spec, path } of commands) {\n if (registry.command(spec.type)) continue;\n if (spec.targetId !== null && variables.has(spec.targetId)) {\n issues.push({ path: `${path}.type`, message: `\"${spec.type}\" is not a variable command.` });\n continue;\n }\n const type = typeOf.get(spec.targetId ?? \"\");\n if (type === undefined || !registry.hasNode(type)) continue;\n if (!registry.takesCommand(type, spec.type)) {\n issues.push({ path: `${path}.type`, message: `node type \"${type}\" has no command \"${spec.type}\".` });\n }\n }\n}\n\n/**\n * Checked the same way whichever clip kind holds them: a cycle or missing parent is the same bug in a still\n * and a composition.\n */\nfunction checkNodes(nodes: unknown, rootType: string, issues: ValidationIssue[]): NodeSite[] {\n if (!Array.isArray(nodes)) {\n issues.push({ path: \"nodes\", message: \"nodes must be an array.\" });\n return [];\n }\n const sites: NodeSite[] = [];\n nodes.forEach((n, i) => {\n const path = `nodes[${i}]`;\n if (checkNodeSpec(n, path, issues)) {\n sites.push({ spec: n, path });\n checkRootShape(n, path, rootType, issues);\n }\n });\n checkTree(sites, issues);\n return sites;\n}\n\nfunction checkSpan(spec: TimedNodeSpec, path: string, issues: ValidationIssue[]): void {\n const { startAt, endAt } = spec;\n if (startAt !== undefined && !isTime(startAt)) {\n issues.push({ path: `${path}.startAt`, message: \"startAt must be a finite number of seconds >= 0.\" });\n }\n if (endAt !== undefined && !isTime(endAt)) {\n issues.push({ path: `${path}.endAt`, message: \"endAt must be a finite number of seconds >= 0.\" });\n }\n if (isTime(endAt) && endAt <= (isTime(startAt) ? startAt : 0)) {\n issues.push({ path: `${path}.endAt`, message: `endAt (${endAt}s) must be after startAt (${startAt ?? 0}s).` });\n }\n if (spec.id === \"\" && (startAt !== undefined || endAt !== undefined)) {\n issues.push({ path, message: \"the root is present for the whole clip — it cannot carry startAt or endAt.\" });\n }\n}\n\nfunction validateStill(doc: StillDocument, issues: ValidationIssue[], registry: Registry | undefined): void {\n checkRetiredFields(doc, issues);\n if ((doc as { commands?: unknown }).commands !== undefined) {\n issues.push({\n path: \"commands\",\n message: \"a still has no timeline, so no commands — make it a composition to animate it.\",\n });\n }\n\n const variables = checkVariables(variableRows(doc.variables, issues), issues);\n const sites = checkNodes(doc.nodes, \"canvas2d\", issues);\n for (const site of sites) {\n const { startAt, endAt } = site.spec as TimedNodeSpec;\n if (startAt !== undefined || endAt !== undefined) {\n issues.push({\n path: site.path,\n message: \"a still has no timeline — drop startAt/endAt, or make it a composition.\",\n });\n }\n }\n const ok = sites.map((s) => s.spec);\n checkIdSpace(ok, variables, issues);\n if (registry) checkVocabulary(sites, [], \"canvas2d\", variables, registry, issues);\n const keyed = checkNodeKeys(sites, issues);\n\n const declared = new Set(variables.keys());\n const keys = new Set(keyed.keys());\n const bound: BoundProp[] = [];\n for (const site of sites) {\n checkExpressions(site.spec.props, `${site.path}.props`, declared, keys, issues);\n if (site.spec.key) boundProps(site.spec.key, site.spec.props, `${site.path}.props`, bound);\n }\n checkExpressionCycles(bound, issues);\n}\n\nfunction validateComposition(doc: CompositionDocument, issues: ValidationIssue[], registry: Registry | undefined): void {\n validateTimedDocument(doc, \"canvas2d\", issues, registry);\n}\n\n/**\n * An audio document is structurally a composition with `audioBus` as the root type, so the checks are shared:\n * a cycle, duplicate id or command running before its target is the same message in any clip kind.\n */\nfunction validateAudio(doc: AudioDocument, issues: ValidationIssue[], registry: Registry | undefined): void {\n validateTimedDocument(doc, \"audioBus\", issues, registry);\n}\n\n/** Command types the format no longer has, and where what they did went. */\nconst RETIRED_COMMANDS: Readonly<Record<string, string>> = {\n add: \"a node is a row in `nodes` — its `startAt` is when it enters.\",\n variable: \"a variable is declared in `variables`.\",\n};\n\nfunction validateTimedDocument(\n doc: CompositionDocument | AudioDocument,\n rootType: string,\n issues: ValidationIssue[],\n registry: Registry | undefined,\n): void {\n checkRetiredFields(doc, issues);\n if (!Array.isArray(doc.commands)) {\n issues.push({ path: \"commands\", message: \"commands must be an array.\" });\n return;\n }\n if (doc.duration !== undefined && !isTime(doc.duration)) {\n issues.push({ path: \"duration\", message: \"duration must be a finite number of seconds >= 0.\" });\n }\n\n /** Gathered first: every expression check needs to know what is declared. */\n const variables = checkVariables(variableRows(doc.variables, issues), issues);\n\n const nodeSites = checkNodes(doc.nodes, rootType, issues);\n for (const site of nodeSites) checkSpan(site.spec as TimedNodeSpec, site.path, issues);\n const nodes = nodeSites.map((s) => s.spec);\n checkIdSpace(nodes, variables, issues);\n const keyed = checkNodeKeys(nodeSites, issues);\n\n /** Each with the row it was authored in: a position in this list is not a position in `commands`. */\n const valid: { spec: CommandSpec; path: string }[] = [];\n const ids = new Set<string>();\n doc.commands.forEach((c: unknown, i: number) => {\n if (!checkCommandSpec(c, `commands[${i}]`, issues)) return;\n if (ids.has(c.id)) {\n issues.push({ path: `commands[${i}].id`, message: `duplicate command id \"${c.id}\".` });\n return;\n }\n const retired = RETIRED_COMMANDS[c.type];\n if (retired) {\n issues.push({ path: `commands[${i}].type`, message: `there is no \"${c.type}\" command — ${retired}` });\n return;\n }\n ids.add(c.id);\n valid.push({ spec: c, path: `commands[${i}]` });\n });\n\n /**\n * A command cannot act on a node that is not there yet: the one ordering rule, and the one a timeline editor\n * breaks by dragging a tween earlier than its node. \"There\" is the effective span (a child cannot enter before\n * its parent). A variable target is exempt: it holds its declared value from t=0.\n */\n const byId = new Map(nodes.map((n) => [n.id, n]));\n if (registry) checkVocabulary(nodeSites, valid, rootType, variables, registry, issues);\n for (const { spec: c, path } of valid) {\n if (c.targetId === null) continue;\n if (variables.has(c.targetId)) continue;\n const span = effectiveSpanIn(byId, c.targetId);\n if (span === undefined) {\n issues.push({\n path: `${path}.targetId`,\n message: `targetId \"${c.targetId}\" is not a node or variable in this document.`,\n });\n } else if (c.at < span.start) {\n issues.push({\n path: `${path}.at`,\n message: `command runs at ${c.at}s but its target \"${c.targetId}\" is not present until ${span.start}s.`,\n });\n }\n }\n\n /**\n * Expressions wherever a prop can be authored: node props (root included), a `to`/`set` props bag, or a named\n * command's arguments.\n */\n const declared = new Set(variables.keys());\n const keys = new Set(keyed.keys());\n for (const site of nodeSites) {\n checkExpressions(site.spec.props, `${site.path}.props`, declared, keys, issues);\n }\n for (const { spec: c, path } of valid) checkExpressions(c.args, `${path}.args`, declared, keys, issues);\n\n /**\n * Cycles over the two places a binding is installed: a node's own props and `set`, the one command whose args\n * reach `node.set()`.\n */\n const bound: BoundProp[] = [];\n for (const site of nodeSites) {\n if (site.spec.key) boundProps(site.spec.key, site.spec.props, `${site.path}.props`, bound);\n }\n for (const { spec: c, path } of valid) {\n if (c.type !== \"set\" || c.targetId === null) continue;\n const key = byId.get(c.targetId)?.key;\n if (key) boundProps(key, c.args, `${path}.args`, bound);\n }\n checkExpressionCycles(bound, issues);\n}\n\n/** Returns every issue rather than throwing on the first, so a host can show the list. */\nexport function validateDocument(doc: unknown, options: ValidateOptions = {}): ValidationResult {\n const issues: ValidationIssue[] = [];\n\n if (!isPlainObject(doc)) {\n return { valid: false, issues: [{ path: \"\", message: \"document must be an object.\" }] };\n }\n checkFormatVersion(doc, issues);\n const { registry } = options;\n const kind = (doc as Partial<ClipDocument>).kind;\n if (kind === \"still\") {\n validateStill(doc as unknown as StillDocument, issues, registry);\n } else if (kind === \"composition\") {\n validateComposition(doc as unknown as CompositionDocument, issues, registry);\n } else if (kind === \"audio\") {\n validateAudio(doc as unknown as AudioDocument, issues, registry);\n } else {\n issues.push({\n path: \"kind\",\n message: `kind must be \"still\", \"composition\" or \"audio\" (got ${JSON.stringify(kind)}).`,\n });\n }\n\n return { valid: issues.length === 0, issues };\n}\n\n/**\n * Each clip is validated by the same rules as a standalone one, with issues prefixed by the track that carries\n * it.\n */\nexport function validateProjectDocument(doc: unknown, options: ValidateOptions = {}): ValidationResult {\n const issues: ValidationIssue[] = [];\n\n if (!isPlainObject(doc)) {\n return { valid: false, issues: [{ path: \"\", message: \"document must be an object.\" }] };\n }\n const project = doc as Record<string, unknown>;\n if (project.kind !== \"project\") {\n issues.push({ path: \"kind\", message: `kind must be \"project\" (got ${JSON.stringify(project.kind)}).` });\n }\n if (typeof project.name !== \"string\" || project.name.length === 0) {\n issues.push({ path: \"name\", message: \"name must be a non-empty string.\" });\n }\n if (project.fps !== undefined && (typeof project.fps !== \"number\" || !(project.fps > 0) || !Number.isFinite(project.fps))) {\n issues.push({ path: \"fps\", message: \"fps must be a positive number when present.\" });\n }\n checkFormatVersion(project, issues);\n for (const [field, message] of Object.entries(RETIRED_PROJECT_FIELDS)) {\n if (project[field] !== undefined) issues.push({ path: field, message });\n }\n\n /**\n * Zero tracks is legitimate: a new project has no clips, and every host of this array treats an empty one as\n * ordinary (`exportProject`/`mixTimelineAudio` no-op, `screenshotProject` raises its own \"nothing to\n * screenshot\").\n */\n if (!Array.isArray(project.tracks)) {\n issues.push({ path: \"tracks\", message: \"tracks must be an array.\" });\n return { valid: false, issues };\n }\n\n const ids = new Set<string>();\n project.tracks.forEach((raw, i) => {\n const path = `tracks[${i}]`;\n if (!isPlainObject(raw)) {\n issues.push({ path, message: \"track must be an object.\" });\n return;\n }\n const track = raw as Record<string, unknown>;\n\n if (typeof track.id !== \"string\" || track.id.length === 0) {\n issues.push({ path: `${path}.id`, message: \"id must be a non-empty string.\" });\n } else if (ids.has(track.id)) {\n issues.push({ path: `${path}.id`, message: `duplicate track id \"${track.id}\".` });\n } else {\n ids.add(track.id);\n }\n if (track.name !== undefined && typeof track.name !== \"string\") {\n issues.push({ path: `${path}.name`, message: \"name must be a string when present.\" });\n }\n if (track.startAt !== undefined && !isTime(track.startAt)) {\n issues.push({ path: `${path}.startAt`, message: \"startAt must be a finite number of seconds >= 0.\" });\n }\n /**\n * Required, not defaulted: a length that falls back to a media file's would silently stretch a three-minute\n * bed into a thirty-second edit.\n */\n if (!isTime(track.duration)) {\n issues.push({\n path: `${path}.duration`,\n message: \"duration is required, and must be a finite number of seconds >= 0.\",\n });\n }\n\n if (track.clip === undefined) {\n issues.push({ path: `${path}.clip`, message: \"clip is required — a track places a clip document inline.\" });\n return;\n }\n for (const issue of clipIssuesOf(track.clip, options)) {\n issues.push({ path: `${path}.clip${issue.path ? `.${issue.path}` : \"\"}`, message: issue.message });\n }\n });\n\n return { valid: issues.length === 0, issues };\n}\n\n/**\n * Keyed by clip object: a host re-validates the whole project after every edit, which replaces only the clip\n * it touched. A clip mutated in place is not seen again (the identity contract `Session.replace` holds).\n */\nconst CLIP_ISSUES = new WeakMap<object, readonly ValidationIssue[]>();\n\nfunction clipIssuesOf(clip: unknown, options: ValidateOptions): readonly ValidationIssue[] {\n if (!isPlainObject(clip) || options.registry) return validateDocument(clip, options).issues;\n let issues = CLIP_ISSUES.get(clip);\n if (!issues) {\n issues = validateDocument(clip).issues;\n CLIP_ISSUES.set(clip, issues);\n }\n return issues;\n}\n\nexport function assertValidProjectDocument(doc: unknown, options?: ValidateOptions): void {\n const { valid, issues } = validateProjectDocument(doc, options);\n if (!valid) {\n const detail = issues.map((i) => ` ${i.path || \"<root>\"}: ${i.message}`).join(\"\\n\");\n throw new Error(`Invalid project document:\\n${detail}`);\n }\n}\n\n/** For a caller with no UI to show issues in. */\nexport function assertValidDocument(doc: unknown, options?: ValidateOptions): ClipDocument {\n const { valid, issues } = validateDocument(doc, options);\n if (!valid) {\n const detail = issues.map((i) => ` ${i.path || \"<root>\"}: ${i.message}`).join(\"\\n\");\n throw new Error(`Invalid clip document:\\n${detail}`);\n }\n return doc as ClipDocument;\n}\n", "import { getPropertyMeta } from \"@/attributes/properties/decorator\";\nimport { component2d } from \"@/components/factory/component2d\";\nimport { component3d } from \"@/components/factory/component3d\";\nimport { componentAudio } from \"@/components/factory/component-audio\";\nimport type { Node, NodeDimension } from \"@/components/trees/node/node\";\nimport type { NodeSpec } from \"./types\";\n\n/**\n * What a build puts where a row names a type its registry lacks: a node that keeps the row's id, placement and\n * children and draws nothing itself, so one unknown type costs one node, not the clip, and an editor still\n * shows the row where it was. None of these is registered, so no document can name one.\n */\n\nexport interface MissingNodeInfo {\n type: string;\n props: Readonly<Record<string, unknown>>;\n}\n\nconst MissingNode2D = component2d({ key: \"missingNode2d\" });\nconst MissingNode3D = component3d({ key: \"missingNode3d\" });\nconst MissingNodeAudio = componentAudio({ key: \"missingNodeAudio\" });\n\ntype PlaceholderCtor = new (props?: Record<string, unknown>) => Node;\n\nconst PLACEHOLDERS: Record<NodeDimension, PlaceholderCtor> = {\n \"2d\": MissingNode2D.node as unknown as PlaceholderCtor,\n \"3d\": MissingNode3D.node as unknown as PlaceholderCtor,\n audio: MissingNodeAudio.node as unknown as PlaceholderCtor,\n};\n\n/** Placement it keeps; nothing that would draw or composite. */\nconst DRAWS = new Set([\"effects\", \"blend\", \"clip\", \"shadow\"]);\n\nconst KEPT = Object.fromEntries(Object.entries(PLACEHOLDERS).map(([dimension, ctor]) => [\n dimension,\n new Set(getPropertyMeta(Object.create(ctor.prototype) as object).map((m) => m.key).filter((key) => !DRAWS.has(key))),\n])) as unknown as Record<NodeDimension, ReadonlySet<string>>;\n\nconst MISSING = new WeakMap<Node, MissingNodeInfo>();\n\n/** Stands in for every placeholder's class when a build compares a live node's class with its row's. */\nexport const MISSING_TYPE: unique symbol = Symbol(\"missingNodeType\");\n\n/** @internal A placeholder for `spec`, in `dimension`, taking what it can of `props` (the literal half of the row's). */\nexport function missingNode(dimension: NodeDimension, spec: NodeSpec, props: Record<string, unknown>): Node {\n const node = new PLACEHOLDERS[dimension]({\n ...placeholderProps(dimension, props),\n id: spec.id,\n ...(spec.key !== undefined && { key: spec.key }),\n });\n MISSING.set(node, { type: spec.type, props: spec.props });\n return node;\n}\n\n/** @internal Of a props bag, what a placeholder of `dimension` takes. */\nexport function placeholderProps(dimension: NodeDimension, props: Record<string, unknown>): Record<string, unknown> {\n const kept = KEPT[dimension];\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(props)) if (kept.has(key)) out[key] = value;\n return out;\n}\n\n/** So a host can mark the row and keep its props for when the type is back. */\nexport function missingNodeOf(node: Node): MissingNodeInfo | undefined {\n return MISSING.get(node);\n}\n", "import type { Registry } from \"./registry\";\n\n/**\n * What a stored document can name and rely on, as JSON: every node type, its props with their defaults (a row\n * is sparse, so a changed default changes every document that leaves the prop out), and its commands. Each\n * release snapshots it beside its fixture documents, so a test can tell what a change takes away from\n * documents already saved.\n */\nexport interface RegistryVocabulary {\n nodes: Record<string, { properties: Record<string, { kind: string; default?: unknown }>; commands: string[] }>;\n /** The commands that resolve without a node type: `to`, `set`, the paints, the variable commands. */\n commands: string[];\n}\n\nexport function registryVocabulary(registry: Registry): RegistryVocabulary {\n const nodes: RegistryVocabulary[\"nodes\"] = {};\n for (const key of registry.nodeKeys()) {\n const properties: RegistryVocabulary[\"nodes\"][string][\"properties\"] = {};\n for (const [prop, described] of Object.entries(registry.describe(key)?.properties ?? {})) {\n properties[prop] = {\n kind: described.kind,\n ...(described.default !== undefined && { default: JSON.parse(JSON.stringify(described.default)) as unknown }),\n };\n }\n nodes[key] = { properties, commands: registry.commandKeys(key) };\n }\n return { nodes, commands: registry.commandKeys() };\n}\n\nexport interface VocabularyBreak {\n name: string;\n what: \"node type removed\" | \"prop removed\" | \"default changed\" | \"command removed\";\n}\n\nexport function vocabularyBreaks(prev: RegistryVocabulary, next: RegistryVocabulary): VocabularyBreak[] {\n const out: VocabularyBreak[] = [];\n for (const command of prev.commands) {\n if (!next.commands.includes(command)) out.push({ name: command, what: \"command removed\" });\n }\n for (const [type, was] of Object.entries(prev.nodes)) {\n const now = next.nodes[type];\n if (!now) {\n out.push({ name: type, what: \"node type removed\" });\n continue;\n }\n for (const [prop, { default: before }] of Object.entries(was.properties)) {\n const after = now.properties[prop];\n if (!after) out.push({ name: `${type}.${prop}`, what: \"prop removed\" });\n else if (JSON.stringify(before) !== JSON.stringify(after.default)) out.push({ name: `${type}.${prop}`, what: \"default changed\" });\n }\n for (const command of was.commands) {\n if (!now.commands.includes(command)) out.push({ name: `${type}.${command}`, what: \"command removed\" });\n }\n }\n return out;\n}\n", "import type { Fill } from \"@/attributes/shape/fill/chain\";\nimport type { Shadow } from \"@/attributes/shape/shadow/shadow\";\nimport type { Stroke } from \"@/attributes/shape/stroke/stroke\";\nimport type { Vector2 } from \"@/attributes/layout/vector2\";\nimport { driveCommand, type Command, type CommandArgs } from \"@/tween/command\";\nimport type { EasingFunction } from \"@/tween/ease/type\";\nimport type { Node } from \"@/components/trees/node/node\";\nimport type { Node2D } from \"@/components/trees/2d/node2d\";\n\nimport { BooleanGroup, MaskGroup } from \"@/components/builtins/geometry/composite\";\nimport { Ellipse, PathShape, Polygon, Polygram, Rect } from \"@/components/builtins/geometry/geometry\";\nimport { Camera, OrbitCamera, RotatedBox } from \"@/components/builtins/layout/layout\";\nimport { Video } from \"@/components/builtins/media/media\";\nimport { AudioBus, SoundNode } from \"@/components/builtins/audio/audio\";\nimport { Canvas2D } from \"@/components/trees/root/canvas2d-node\";\nimport { Provider, ThemeProvider } from \"@/components/builtins/providers/providers\";\nimport { DefaultTextStyle, NumberNode, RichText, Text } from \"@/components/builtins/text/text\";\nimport { Canvas3D } from \"@/components/builtins/three/canvas3d\";\nimport {\n AmbientLight3D, AreaLight3D, Box3D, Camera3D, Capsule3D, Circle3D, Cone3D, Cylinder3D, DirectionalLight3D,\n Environment3D, Extrude3D, Fog3D, Group3D, HemisphereLight3D, Instances3D, Lathe3D, Line3D, Mesh3D, Model3D,\n Plane3D, PointLight3D, Points3D, Polyhedron3D, Ring3D, Sphere3D, SpotLight3D, Sprite3D, Torus3D, TorusKnot3D, Tube3D,\n} from \"@/components/builtins/three/three\";\n\nimport { lerpVector2 } from \"@/attributes/layout/vector2\";\nimport { lerpColor } from \"@/attributes/shape/fill/lerp\";\nimport { parseColor } from \"@/attributes/shape/fill/color/parser\";\nimport { lerpVector3 } from \"@/render3d/vector3\";\nimport { lerpNumber } from \"@/tween/lerp\";\n\nimport type { NodeConstructor, Registry, VariableLerp } from \"./registry\";\n\n/**\n * The keys here are document API: a stored scene names its nodes and animations with these strings, so\n * renaming one silently breaks every document that used it. Spelled out rather than derived from\n * `constructor.name`, which a minifier may mangle.\n */\n\nconst NODE_TYPES: Record<string, NodeConstructor> = {\n canvas2d: Canvas2D as unknown as NodeConstructor,\n provider: Provider as unknown as NodeConstructor,\n \"theme-provider\": ThemeProvider as unknown as NodeConstructor,\n \"default-text-style\": DefaultTextStyle as unknown as NodeConstructor,\n\n rect: Rect as unknown as NodeConstructor,\n ellipse: Ellipse as unknown as NodeConstructor,\n /**\n * The unit-box path, not `path-node.ts`'s face-value `Path`: a stored `data` is a fraction of the node's own\n * box, so a resize is an ordinary `width`/`height` write and every editor gizmo works unchanged\n * (`box-path-node.ts` has the argument). `Path` draws its `d` at face value, for geometry written in code, and\n * is reached by importing the class, not by naming a type in a document.\n */\n path: PathShape as unknown as NodeConstructor,\n polygon: Polygon as unknown as NodeConstructor,\n polygram: Polygram as unknown as NodeConstructor,\n boolean: BooleanGroup as unknown as NodeConstructor,\n mask: MaskGroup as unknown as NodeConstructor,\n\n camera: Camera as unknown as NodeConstructor,\n orbitCamera: OrbitCamera as unknown as NodeConstructor,\n \"rotated-box\": RotatedBox as unknown as NodeConstructor,\n\n text: Text as unknown as NodeConstructor,\n richtext: RichText as unknown as NodeConstructor,\n number: NumberNode as unknown as NodeConstructor,\n\n video: Video as unknown as NodeConstructor,\n\n /** `audioBus` is also the root of an AudioDocument, as `canvas2d` is of a scene. */\n audioBus: AudioBus as unknown as NodeConstructor,\n sound: SoundNode as unknown as NodeConstructor,\n\n canvas3d: Canvas3D as unknown as NodeConstructor,\n group3d: Group3D as unknown as NodeConstructor,\n mesh3d: Mesh3D as unknown as NodeConstructor,\n box3d: Box3D as unknown as NodeConstructor,\n sphere3d: Sphere3D as unknown as NodeConstructor,\n plane3d: Plane3D as unknown as NodeConstructor,\n circle3d: Circle3D as unknown as NodeConstructor,\n cylinder3d: Cylinder3D as unknown as NodeConstructor,\n cone3d: Cone3D as unknown as NodeConstructor,\n capsule3d: Capsule3D as unknown as NodeConstructor,\n torus3d: Torus3D as unknown as NodeConstructor,\n \"torus-knot3d\": TorusKnot3D as unknown as NodeConstructor,\n tube3d: Tube3D as unknown as NodeConstructor,\n lathe3d: Lathe3D as unknown as NodeConstructor,\n extrude3d: Extrude3D as unknown as NodeConstructor,\n ring3d: Ring3D as unknown as NodeConstructor,\n polyhedron3d: Polyhedron3D as unknown as NodeConstructor,\n points3d: Points3D as unknown as NodeConstructor,\n line3d: Line3D as unknown as NodeConstructor,\n sprite3d: Sprite3D as unknown as NodeConstructor,\n instances3d: Instances3D as unknown as NodeConstructor,\n model3d: Model3D as unknown as NodeConstructor,\n camera3d: Camera3D as unknown as NodeConstructor,\n \"ambient-light3d\": AmbientLight3D as unknown as NodeConstructor,\n \"directional-light3d\": DirectionalLight3D as unknown as NodeConstructor,\n \"point-light3d\": PointLight3D as unknown as NodeConstructor,\n \"spot-light3d\": SpotLight3D as unknown as NodeConstructor,\n \"hemisphere-light3d\": HemisphereLight3D as unknown as NodeConstructor,\n \"area-light3d\": AreaLight3D as unknown as NodeConstructor,\n fog3d: Fog3D as unknown as NodeConstructor,\n environment3d: Environment3D as unknown as NodeConstructor,\n};\n\ntype EasedMethod = (args: CommandArgs) => Command<Record<string, unknown>>;\n\nfunction paintCommand(method: string, argKey: string) {\n return (\n target: Node,\n args: Record<string, unknown>,\n duration: number,\n easing?: EasingFunction,\n ): Command<Record<string, unknown>> => {\n const fn = (target as unknown as Record<string, unknown>)[method];\n if (typeof fn !== \"function\") {\n throw new Error(\n `Command \"${method}\" is not available on ${target.constructor.name}.`,\n );\n }\n return (fn as EasedMethod).call(target, { data: args[argKey] as Record<string, unknown>, duration, easing });\n };\n}\n\n/**\n * Deliberately the small set a variable holds (a number, a point, a colour), not one per attribute: a variable\n * drives props through an expression, so it only carries the quantity that varies. Anything else is a\n * `registry.addLerp` away.\n */\nconst VARIABLE_LERPS: Record<string, VariableLerp> = {\n number: lerpNumber as VariableLerp,\n vector2: lerpVector2 as VariableLerp,\n vector3: lerpVector3 as VariableLerp,\n /**\n * Returns a CSS string because that is what the prop on the far side of the expression takes; `parseColor`\n * also reads theme tokens and the `\"white/10\"` opacity suffix.\n */\n color: ((from, to, t) => {\n const [r, g, b, a] = lerpColor(parseColor(String(from)), parseColor(String(to)), t);\n const channel = (v: number) => Math.round(Math.min(Math.max(v, 0), 1) * 255);\n return `rgba(${channel(r)}, ${channel(g)}, ${channel(b)}, ${Number(a.toFixed(4))})`;\n }) as VariableLerp,\n /**\n * Hold `from` until the tween lands, then take `to`. The default for a non-numeric variable: a discrete value\n * has no midpoint, and inventing one produces a frame that is neither state.\n */\n step: ((from, to, t) => (t >= 1 ? to : from)) as VariableLerp,\n};\n\n/**\n * Called from `Registry`'s own constructor, so the vocabulary is a value dependency of the engine: a public\n * call at module scope could be deleted by `sideEffects: false`, with an \"unknown node type rect\" failure\n * pointing nowhere near the cause.\n *\n * @internal\n */\nexport function installBuiltins(registry: Registry): void {\n for (const [key, ctor] of Object.entries(NODE_TYPES)) {\n registry.addNode(key, ctor);\n }\n for (const [key, lerp] of Object.entries(VARIABLE_LERPS)) {\n registry.addLerp(key, lerp);\n }\n\n // `args` is the props diff, with no wrapper key: `to`/`set` carry exactly one argument and a node's props are\n // already a known-shape bag.\n registry.addCommand(\"to\", (target, args, duration, easing) =>\n (target as Node2D).to({\n /**\n * Copied: `_prepareStep` expands sugar into its target in place, which would rewrite the document row a diff\n * compares by identity.\n */\n data: { ...args } as Record<string, never>,\n duration,\n easing,\n }) as unknown as Command<Record<string, unknown>>);\n\n /**\n * A stamp: `duration` is ignored, which is what a keyframe editor's \"set this here\" needs. `binds` because its\n * args reach `set()` verbatim, so an expression among them is a binding: this is how a prop starts following a\n * variable partway through a scene.\n */\n registry.addCommand(\"set\", (target, args) => {\n const props = args as Record<string, never>;\n return driveCommand(0, () => {\n (target as Node2D).set(props);\n }) as unknown as Command<Record<string, unknown>>;\n }, { binds: true });\n\n // Node-less rather than per-type, like `to` and `set`: generic over every painted node, and they take a\n // `TweenOptions` bag where an ordinary command takes a bare easing function, so they need their own factory.\n // Each declares the one key it reads, in the kind its property uses, so a host draws the same paint stack for\n // the command as for the prop.\n registry.addCommand(\"fillTo\", paintCommand(\"fillTo\", \"fill\"), { args: [{ key: \"fill\", kind: \"fills\" }], method: \"fillTo\" });\n registry.addCommand(\"overlayTo\", paintCommand(\"overlayTo\", \"overlay\"), { args: [{ key: \"overlay\", kind: \"fills\" }], method: \"overlayTo\" });\n registry.addCommand(\"strokeTo\", paintCommand(\"strokeTo\", \"stroke\"), { args: [{ key: \"stroke\", kind: \"strokes\" }], method: \"strokeTo\" });\n registry.addCommand(\"shadowTo\", paintCommand(\"shadowTo\", \"shadow\"), { args: [{ key: \"shadow\", kind: \"shadows\" }], method: \"shadowTo\" });\n\n // Transform, camera, text and `restore` commands are `command()` methods that `Registry.addNode` publishes off\n // the classes; see `document/registry.ts`.\n\n // The one command that drives many nodes at once: every prop bound to `\"=[id]\"` follows what this writes.\n registry.addVariableCommand(\"variableTo\", (target, args, duration, easing) => {\n const to = (args as { value?: unknown }).value;\n const lerpKey = (args as { lerp?: unknown }).lerp;\n const override = typeof lerpKey === \"string\" ? registry.lerp(lerpKey) : undefined;\n if (lerpKey !== undefined && !override) {\n throw new Error(\n `A \"lerp\" param must name a registered lerp (variable \"${target.id}\"), ` +\n `got ${JSON.stringify(lerpKey)}. Registered: ${registry.lerpKeys().join(\", \")}.`,\n );\n }\n const lerp = override ?? target.lerp;\n\n // `from` is captured on the command's first evaluation, as a node's `to()` does: the timeline builds commands\n // in order and runs each to `at(1)`, so the capture sees the state its predecessors left. Captured once, it is\n // a pure function of `t`.\n let from: unknown;\n let captured = false;\n return driveCommand(duration, (t) => {\n if (!captured) {\n from = target.get();\n captured = true;\n }\n target.set(lerp(from, to, t));\n }, easing) as unknown as Command<Record<string, unknown>>;\n });\n\n registry.addVariableCommand(\"variableSet\", (target, args) =>\n driveCommand(0, () => {\n target.set((args as { value?: unknown }).value);\n }) as unknown as Command<Record<string, unknown>>);\n\n // `restore` pops the layer a `save` pushed and is published off `Node`'s own `command()`; `save` is not one,\n // so it is registered here. Both are commands so the pair sits on the timeline, and a seek past the save\n // computes the value from the chain rather than accumulating it.\n registry.addCommand(\"save\", (target) =>\n driveCommand(0, () => {\n (target as Node2D).save();\n }) as unknown as Command<Record<string, unknown>>);\n}\n\nexport type { Fill, Shadow, Stroke, Vector2 };\n", "/**\n * Hardening, not a sandbox. A dynamic node's compiled JS runs under `new Function` in the host's own realm,\n * which the architecture forces: the node must be a live class satisfying `instanceof` against the host's\n * loaded `core`, and that cannot cross a worker or iframe boundary. Each name below becomes a factory\n * parameter bound to `undefined` (and strict-mode `this` is `undefined`), closing the easy paths.\n *\n * A determined script still reaches the global object through the intrinsics (`({}).constructor.constructor`\n * is `Function`); closing that would mean poisoning `Object.prototype` and `Function`, which breaks the engine\n * itself. The real security boundary is whatever gate the host puts in front of `Registry.addNodeFromSource`.\n */\n\n/**\n * Grouped by what each would be used for, so the list is auditable; leaving one out is the bug. Scoped to a\n * browser-realm page (a tab, or headless's Playwright page), not Node globals.\n */\nexport const DENIED_GLOBALS: readonly string[] = [\n // Reaching the global object, and from it everything else.\n \"globalThis\",\n \"window\",\n \"self\",\n \"top\",\n \"parent\",\n \"frames\",\n\n /**\n * Evaluating more code. `eval` is missing on purpose: strict mode forbids it as a binding name, so naming it\n * would make `new Function` throw and every dynamic node stop linking. It stays reachable, one more reason\n * this file is not the security boundary.\n */\n \"Function\",\n \"importScripts\",\n\n // The DOM: reading the page, and `document.cookie`.\n \"document\",\n \"navigator\",\n \"location\",\n \"history\",\n \"screen\",\n \"customElements\",\n\n /** Anywhere to send what was found (`navigator.sendBeacon` needs `navigator`, already denied above). */\n \"fetch\",\n \"XMLHttpRequest\",\n \"WebSocket\",\n \"EventSource\",\n \"Request\",\n \"Response\",\n \"Headers\",\n\n // Anywhere to read a credential from.\n \"localStorage\",\n \"sessionStorage\",\n \"indexedDB\",\n \"caches\",\n \"cookieStore\",\n \"crypto\",\n\n // Other threads and other documents.\n \"Worker\",\n \"SharedWorker\",\n \"ServiceWorker\",\n \"MessageChannel\",\n \"BroadcastChannel\",\n \"postMessage\",\n\n // Things that ask the user for something, or leave the page.\n \"alert\",\n \"confirm\",\n \"prompt\",\n \"open\",\n \"print\",\n \"Notification\",\n];\n\n/**\n * Names strict mode refuses to bind: they would break linking for every dynamic node rather than protect\n * anything. Checked rather than trusted, because adding one fails at evaluation, on whichever node compiles\n * first, naming neither the list nor the culprit.\n */\nconst UNBINDABLE = new Set([\"eval\", \"arguments\"]);\n\nconst illegal = DENIED_GLOBALS.filter((name) => UNBINDABLE.has(name));\nif (illegal.length > 0) {\n throw new Error(\n `DENIED_GLOBALS cannot contain ${illegal.join(\", \")}: strict mode forbids ` +\n `binding those names, so no dynamic node would link at all. See the note in this file.`,\n );\n}\n", "import type { Node, NodeDimension } from \"@/components/trees/node/node\";\nimport type { Command, CommandArgs } from \"@/tween/command\";\nimport type { EasingFunction } from \"@/tween/ease/type\";\nimport { getPropertyMeta, type PropertyEditor } from \"@/attributes/properties/decorator\";\nimport { getCommandMeta, type CommandArg, type CommandArgDescriptor } from \"@/tween/command-decorator\";\nimport {\n normalizeShaderPack,\n type EffectShader,\n type FillShader,\n type Shader,\n} from \"@/attributes/shape/shaders/pack\";\nimport { installBuiltins } from \"./builtins\";\nimport { DENIED_GLOBALS } from \"./deny-globals\";\nimport { getNodeDescriptor } from \"./node-decorator\";\nimport { applyPropEvolution, propEvolutionOf } from \"./prop-evolution\";\nimport type { NodePropertyDescriptor, NodeTypeDescriptor } from \"./node-descriptor\";\nimport type { NodeSpec } from \"./types\";\n\n/**\n * Resolve to the host's sdk barrel. The published name comes first; the two after it are earlier unscoped\n * names, kept so older scripts still compile.\n */\nconst SDK_SPECIFIERS: readonly string[] = [\"@motionscript/sdk\", \"motionscript\", \"motion-script\"];\n\nexport type NodeConstructor = new (props?: Record<string, unknown>) => Node;\n\nexport type NodeTypeMap = Record<string, NodeConstructor>;\n\nexport type ShaderPackMap = Record<string, unknown>;\n\n/**\n * Called once per compile, in timeline order, with `target` already in the state the previous command left:\n * that fixes the command's `from` and makes `Command.at(t)` pure thereafter.\n */\nexport type CommandFactory = (\n target: Node,\n args: Record<string, unknown>,\n duration: number,\n easing?: EasingFunction,\n) => Command<Record<string, unknown>>;\n\n/**\n * A handle, not the cell, so a command cannot subscribe to it, rebind it or hold it past the build: each would\n * stop it being a pure function of `t`.\n */\nexport interface VariableTarget {\n readonly id: string;\n get(): unknown;\n set(value: unknown): void;\n /** A command may use a different lerp when its args ask (`variableTo` does). */\n readonly lerp: VariableLerp;\n}\n\n/** Same contract as {@link CommandFactory}, against a variable instead of a node. */\nexport type VariableCommandFactory = (\n target: VariableTarget,\n args: Record<string, unknown>,\n duration: number,\n easing?: EasingFunction,\n) => Command<Record<string, unknown>>;\n\n/** Widened to `unknown`: a variable's type is a fact of the document, not of a class. */\nexport type VariableLerp = (from: unknown, to: unknown, t: number) => unknown;\n\n/**\n * `scope` picks the table `CommandSpec.targetId` is looked up in, so a variable command reuses the field a\n * node command uses.\n */\nexport type CommandTypeEntry =\n | {\n key: string;\n scope: \"node\";\n factory: CommandFactory;\n /**\n * Declared by the paint commands, one key each. Absent for `to`/`set`, whose args are the props diff.\n */\n args?: readonly CommandArgDescriptor[];\n /**\n * Args are a props diff that reaches `set()`, so an expression compiles to a binding. A flag, not a name\n * check: `to` tweens towards a value, and binding a formula there would interpolate towards `NaN`.\n */\n binds?: boolean;\n /**\n * The method it runs on its target (the paint commands call the node's own `fillTo`). A type without it, or\n * one that withdrew it, does not take the command ({@link Registry.takesCommand}).\n */\n method?: string;\n }\n | {\n key: string;\n scope: \"variable\";\n factory: VariableCommandFactory;\n };\n\n/**\n * Built from the whole prototype chain, so a `Card` extending `Rect` answers to `fadeTo` as it does to\n * `.fadeTo()`. Inherited entries are copied into each type, so nothing collides.\n */\nexport interface NodeTypeRecord {\n key: string;\n ctor: NodeConstructor;\n commands: ReadonlyMap<string, NodeCommandEntry>;\n /** Always present, however the type was registered. */\n descriptor: NodeTypeDescriptor;\n}\n\nexport interface NodeCommandEntry {\n method: string;\n /** A bare name normalises to `{ key, kind: \"unknown\" }`. */\n args: readonly CommandArgDescriptor[];\n /**\n * Present and true for an entrance (`CommandMeta.entrance`), so a host can offer one when the node is added.\n */\n entrance?: true;\n}\n\n/**\n * Host-supplied: `core` has no compiler dependency and cannot import the `@motionscript/sdk` barrel (that\n * package depends on `core`).\n */\nexport interface DynamicNodeConfig {\n /**\n * Must be the host's already-loaded sdk instance, or `instanceof` silently fails against it. The earlier\n * unscoped specifiers resolve to the same object.\n */\n sdk: Record<string, unknown>;\n /**\n * Consulted after the sdk specifiers, so they cannot be shadowed. Each must be the host's loaded instance, for\n * the same `instanceof` reason.\n */\n modules?: Readonly<Record<string, unknown>>;\n /** Host-injected, never bundled. */\n compile: (source: string) => Promise<string>;\n}\n\nexport interface RegistryOptions {\n /**\n * A record names the key outright, which asserts the class agrees: a rename on either side throws here rather\n * than surfacing as an unknown type at render.\n */\n nodes?: NodeTypeMap | readonly NodeConstructor[];\n shaders?: ShaderPackMap;\n lerps?: Record<string, VariableLerp>;\n eases?: Record<string, EasingFunction>;\n dynamicNodes?: DynamicNodeConfig;\n /**\n * Fail the build on an unknown node type or command, instead of standing in a placeholder and recording it in\n * `buildErrors`.\n */\n strict?: boolean;\n /**\n * Only for a test asserting on the seeding, or a deliberately tiny vocabulary: a document naming `\"rect\"` will\n * not compile without it.\n */\n builtins?: boolean;\n}\n\n/**\n * An instance, not module-scope tables: what a document can name is a property of the engine opening it, so\n * two engines in one process disagree freely.\n *\n * Commands are per node type (a method on a class); only those that must resolve without a node\n * (variable-scoped, generic prop writers) sit in a table of their own.\n */\nexport class Registry {\n /** Ceiling, so an import cannot evict a workspace's own shaders by volume. */\n static readonly MAX_SHADERS = 512;\n\n readonly strict: boolean;\n\n constructor(options: RegistryOptions = {}) {\n this._dynamicNodes = options.dynamicNodes;\n this.strict = options.strict === true;\n if (options.builtins !== false) installBuiltins(this);\n if (Array.isArray(options.nodes)) {\n for (const ctor of options.nodes) this.addNode(ctor);\n } else {\n for (const [key, ctor] of Object.entries(options.nodes ?? {})) this.addNode(key, ctor);\n }\n for (const [key, lerp] of Object.entries(options.lerps ?? {})) this.addLerp(key, lerp);\n for (const [key, ease] of Object.entries(options.eases ?? {})) this.addEase(key, ease);\n for (const [key, pack] of Object.entries(options.shaders ?? {})) this.addShader(key, pack);\n }\n\n /**\n * Register a node class with its commands and descriptor. Commands come off the class's `command()` methods,\n * read through an object over the prototype so no constructor runs (it may expect props, build children or\n * touch a clock).\n *\n * Re-registering the same class under a key is a no-op (hot reload, a duplicated dependency); a different\n * class throws, since a document would render differently by registration order. `replace: true` opts out, for\n * a recompiled node (see {@link addNodeFromSource}).\n */\n addNode(ctor: NodeConstructor, options?: { replace?: boolean }): this;\n addNode(type: string | NodeTypeDescriptor, ctor: NodeConstructor, options?: { replace?: boolean }): this;\n addNode(\n type: string | NodeTypeDescriptor | NodeConstructor,\n ctorOrOptions?: NodeConstructor | { replace?: boolean },\n maybeOptions?: { replace?: boolean },\n ): this {\n const isTwoArgForm = typeof ctorOrOptions === \"function\";\n // A component (`component2d(...)`) registers as the node class it generated.\n const given = (isTwoArgForm ? ctorOrOptions : type) as NodeConstructor & { node?: NodeConstructor };\n const cls = typeof given.node === \"function\" ? given.node : given;\n const options = isTwoArgForm ? maybeOptions : ctorOrOptions as { replace?: boolean } | undefined;\n const declared = isTwoArgForm ? type as string | NodeTypeDescriptor : getNodeDescriptor(cls);\n if (declared === undefined) {\n throw new Error(\n `${cls.name || \"The class\"} is no component, so it has no document key. ` +\n `Make it with component2d({ key }), or register it explicitly: addNode(\"myKey\", TheClass).`,\n );\n }\n const descriptor: NodeTypeDescriptor = typeof declared === \"string\" ? { key: declared } : declared;\n const key = descriptor.key;\n\n const existing = this._nodes.get(key);\n if (existing) {\n if (existing.ctor === cls) return this;\n if (!options?.replace) {\n throw new Error(\n `Node type \"${key}\" is already registered to a different class ` +\n `(${existing.ctor.name} vs ${cls.name}). Keys must be unique — a document ` +\n `naming this type would otherwise resolve differently depending on registration order.`,\n );\n }\n }\n\n const commands = new Map<string, NodeCommandEntry>();\n for (const meta of getCommandMeta(Object.create(cls.prototype) as object)) {\n commands.set(meta.key, {\n method: meta.method,\n args: this._describeArgs(meta.args),\n ...(meta.entrance ? { entrance: true as const } : {}),\n });\n }\n\n this._nodes.set(key, {\n key,\n ctor: cls,\n commands,\n // Derived, never declared: see `NodeTypeDescriptor.properties`.\n descriptor: this._describeEvolution(cls, {\n ...descriptor,\n dimension: this._describeDimension(cls),\n holds: this._describeHolds(cls),\n properties: this._describeProperties(cls),\n }),\n });\n return this;\n }\n\n /**\n * The script must `export default` a component whose `key` supplies the registry key, as {@link addNode} reads\n * it: one way to name a dynamic node's key. Requires `dynamicNodes`; `core` only calls the host-supplied\n * `compile` and links the result.\n */\n async addNodeFromSource(source: string, options?: { replace?: boolean }): Promise<NodeConstructor> {\n if (!this._dynamicNodes) {\n throw new Error(\n \"addNodeFromSource needs `dynamicNodes: { sdk, compile }` on the Registry constructor.\",\n );\n }\n const js = await this._dynamicNodes.compile(source);\n const ctor = this._evalNodeModule(js);\n this.addNode(ctor, options);\n return ctor;\n }\n\n node(key: string): NodeTypeRecord | undefined {\n return this._nodes.get(key);\n }\n\n hasNode(key: string): boolean {\n return this._nodes.has(key);\n }\n\n nodeKeys(): string[] {\n return [...this._nodes.keys()].sort();\n }\n\n describe(key: string): NodeTypeDescriptor | undefined {\n return this._nodes.get(key)?.descriptor;\n }\n\n /**\n * The props pass through the type's evolution first (`migrateNodeProps`).\n *\n * `props` overrides the spec's own so the timeline can leave expression-bound props out of the constructor,\n * which reads raw props for defaults like size, and `set()` them after. The spec's `id` outranks both, so\n * {@link Node.id} is the document's identity. `key` rides along only when the row has one: `applyEditorStates`\n * keys on {@link Node.key}, and an absent row key must not overwrite one passed in `props`.\n */\n instantiate(spec: NodeSpec, props?: Record<string, unknown>): Node {\n const record = this._nodes.get(spec.type);\n if (!record) {\n throw new Error(\n `Unknown node type \"${spec.type}\" (node ${spec.id}). ` +\n `This registry knows: ${this.nodeKeys().join(\", \") || \"nothing\"}.`,\n );\n }\n const evolution = propEvolutionOf(record.ctor);\n const given = props ?? spec.props;\n return new record.ctor({\n ...(evolution ? applyPropEvolution(evolution, given).props : given),\n id: spec.id,\n ...(spec.key !== undefined && { key: spec.key }),\n });\n }\n\n /** Same uniqueness rule as {@link addNode}. */\n addCommand(\n key: string,\n factory: CommandFactory,\n options?: { binds?: boolean; args?: readonly CommandArg[]; method?: string },\n ): this {\n if (this._claimed(key, factory)) return this;\n this._commands.set(key, {\n key,\n scope: \"node\",\n factory,\n ...(options?.args ? { args: this._describeArgs(options.args) } : {}),\n binds: options?.binds,\n ...(options?.method ? { method: options.method } : {}),\n });\n return this;\n }\n\n /**\n * A host's seam for its own variable commands (a spring, a wiggle); the returned {@link Command} must be a\n * pure function of `t`.\n */\n addVariableCommand(key: string, factory: VariableCommandFactory): this {\n if (this._claimed(key, factory)) return this;\n this._commands.set(key, { key, scope: \"variable\", factory });\n return this;\n }\n\n command(key: string): CommandTypeEntry | undefined {\n return this._commands.get(key);\n }\n\n /**\n * Dispatches by calling the named method, never by testing against a class: a forked component is a different\n * class carrying the same source, so `instanceof` against the original is false.\n */\n nodeCommand(nodeTypeKey: string, commandKey: string): CommandFactory | undefined {\n const record = this._nodes.get(nodeTypeKey);\n const entry = record?.commands.get(commandKey);\n if (!entry) return undefined;\n return (target, args, duration, easing) => {\n const fn = (target as unknown as Record<string, unknown>)[entry.method];\n if (typeof fn !== \"function\") {\n throw new Error(\n `Command \"${commandKey}\" needs a \"${entry.method}\" method on ` +\n `${target.constructor.name}, which has none.`,\n );\n }\n const data: Record<string, unknown> = {};\n for (const arg of entry.args) data[arg.key] = args[arg.key];\n return (fn as (args: CommandArgs) => Command<Record<string, unknown>>)\n .call(target, { data, duration, easing });\n };\n }\n\n /**\n * A node takes what its own table publishes, plus node-less commands that act on a node (`to`, `fillTo`)\n * unless the method they run is one the type lacks.\n */\n takesCommand(nodeTypeKey: string, commandKey: string): boolean {\n const record = this._nodes.get(nodeTypeKey);\n if (!record) return false;\n if (record.commands.has(commandKey)) return true;\n const global = this._commands.get(commandKey);\n if (global?.scope !== \"node\") return false;\n if (global.method === undefined) return true;\n return typeof (record.ctor.prototype as Record<string, unknown>)[global.method] === \"function\";\n }\n\n commandKeys(nodeTypeKey?: string): string[] {\n const keys = nodeTypeKey === undefined\n ? this._commands.keys()\n : this._nodes.get(nodeTypeKey)?.commands.keys() ?? [];\n return [...keys].sort();\n }\n\n /** Same uniqueness rule as {@link addNode}. */\n addLerp(key: string, lerp: VariableLerp): this {\n const existing = this._lerps.get(key);\n if (existing && existing !== lerp) {\n throw new Error(\n `Variable lerp \"${key}\" is already registered to a different function. Keys must be unique.`,\n );\n }\n this._lerps.set(key, lerp);\n return this;\n }\n\n lerp(key: string): VariableLerp | undefined {\n return this._lerps.get(key);\n }\n\n lerpKeys(): string[] {\n return [...this._lerps.keys()].sort();\n }\n\n /**\n * A numeric variable with no declared lerp interpolates; anything else snaps at the end. Guessing a structural\n * lerp off one sample would blend objects that merely share an `x` key.\n */\n requireLerp(key: string | undefined, value: unknown, where: string): VariableLerp {\n const resolved = key ?? (typeof value === \"number\" ? \"number\" : \"step\");\n const lerp = this._lerps.get(resolved);\n if (!lerp) {\n throw new Error(\n `Unknown variable lerp \"${resolved}\" (${where}). ` +\n `Registered: ${this.lerpKeys().join(\", \") || \"none\"}.`,\n );\n }\n return lerp;\n }\n\n /** Referenced as `{ kind: \"custom\", args: key }`. Same uniqueness rule as {@link addNode}. */\n addEase(key: string, ease: EasingFunction): this {\n const existing = this._eases.get(key);\n if (existing && existing !== ease) {\n throw new Error(\n `Ease \"${key}\" is already registered to a different function. Keys must be unique.`,\n );\n }\n this._eases.set(key, ease);\n return this;\n }\n\n ease(key: string): EasingFunction | undefined {\n return this._eases.get(key);\n }\n\n easeKeys(): string[] {\n return [...this._eases.keys()].sort();\n }\n\n /**\n * The key is an argument, not a pack field (as in {@link addNode}), so a file stays portable between projects;\n * a pack's own `id` is provenance. The pack is normalised on the way in.\n *\n * Re-registering an equal pack is a no-op: the same file imported twice yields two equal objects, and throwing\n * there would defeat the uniqueness rule. `replace: true` overwrites with a different pack, for a live-edited\n * shader.\n */\n addShader(key: string, pack: unknown, options?: { replace?: boolean }): Shader {\n const normalized = normalizeShaderPack(pack);\n const existing = this._shaders.get(key);\n if (existing) {\n if (\n existing.scope === normalized.scope\n && existing.source === normalized.source\n && existing.name === normalized.name\n ) return existing;\n if (!options?.replace) {\n throw new Error(\n `Shader \"${key}\" is already registered to a different pack ` +\n `(\"${existing.name}\" vs \"${normalized.name}\"). Keys must be unique — a document ` +\n `naming this shader would otherwise resolve differently depending on registration order.`,\n );\n }\n } else if (this._shaders.size >= Registry.MAX_SHADERS) {\n throw new Error(\n `Cannot register shader \"${key}\": the ${Registry.MAX_SHADERS}-shader ceiling is reached.`,\n );\n }\n this._shaders.set(key, normalized);\n return normalized;\n }\n\n shader(key: string): Shader | undefined {\n return this._shaders.get(key);\n }\n\n /**\n * The typed accessors deliver the compile error the union promises: {@link shader} returns `Shader`, and an\n * unnarrowed call site could pass an effect pack to `Fills.shader`.\n */\n fillShader(key: string): FillShader | undefined {\n const pack = this._shaders.get(key);\n return pack?.scope === \"fill\" ? pack : undefined;\n }\n\n effectShader(key: string): EffectShader | undefined {\n const pack = this._shaders.get(key);\n return pack?.scope === \"effect\" ? pack : undefined;\n }\n\n shaderKeys(): string[] {\n return [...this._shaders.keys()].sort();\n }\n\n private readonly _nodes = new Map<string, NodeTypeRecord>();\n private readonly _commands = new Map<string, CommandTypeEntry>();\n private readonly _lerps = new Map<string, VariableLerp>();\n private readonly _eases = new Map<string, EasingFunction>();\n private readonly _shaders = new Map<string, Shader>();\n private readonly _dynamicNodes?: DynamicNodeConfig;\n\n /**\n * `new Function` in-realm, never a blob module or a worker (see {@link DynamicNodeConfig} and\n * `deny-globals.ts`). `require()` is locked to the sdk specifiers and the host's `modules`, own keys only so\n * `require(\"constructor\")` cannot reach `Object`. No relative imports: a dynamic node is one script.\n */\n private _evalNodeModule(js: string): NodeConstructor {\n const { sdk, modules } = this._dynamicNodes!;\n const require = (specifier: string): unknown => {\n if (SDK_SPECIFIERS.includes(specifier)) return sdk;\n if (modules && Object.hasOwn(modules, specifier)) return modules[specifier];\n const available = [\"@motionscript/sdk\", ...Object.keys(modules ?? {})];\n throw new Error(\n `\"${specifier}\" isn't available to a custom node. It can require ` +\n `${available.map((s) => `\"${s}\"`).join(\", \")}; a host supplies more through \\`dynamicNodes.modules\\`.`,\n );\n };\n const mod = { exports: {} as Record<string, unknown> };\n // The script runs one function in from the parameters that deny the\n // globals, so its own top-level `const frames` shadows a denied name\n // instead of redeclaring a parameter. A body that closes that function\n // early is still inside the outer one, which denies the same names.\n const factory = new Function(\n \"exports\", \"require\", \"module\", ...DENIED_GLOBALS,\n `\"use strict\";\\nreturn function () {\\n${js}\\n};`,\n );\n factory(mod.exports, require, mod)();\n\n const ctor = mod.exports.default as (NodeConstructor & { node?: NodeConstructor }) | undefined;\n if (typeof ctor !== \"function\" || getNodeDescriptor(typeof ctor.node === \"function\" ? ctor.node : ctor) === undefined) {\n throw new Error(\"This script must `export default` a component: `component2d({ key: \\\"…\\\", … })`.\");\n }\n return ctor;\n }\n\n /** See {@link addNode} for why. */\n private _claimed(key: string, factory: CommandFactory | VariableCommandFactory): boolean {\n const existing = this._commands.get(key);\n if (!existing) return false;\n if (existing.factory === factory) return true;\n throw new Error(\n `Command type \"${key}\" is already registered to a different factory. Keys must be unique.`,\n );\n }\n\n /** The whole prototype chain, so a component publishes the box its tree's base declares too. */\n private _describeProperties(ctor: NodeConstructor): Record<string, NodePropertyDescriptor> {\n const out: Record<string, NodePropertyDescriptor> = {};\n for (const meta of getPropertyMeta(Object.create(ctor.prototype) as object)) {\n const editor: PropertyEditor = meta.editor ?? {};\n out[meta.key] = {\n ...editor,\n kind: editor.kind ?? this._inferKind(meta.default),\n ...(meta.default !== undefined ? { default: meta.default } : {}),\n };\n }\n return out;\n }\n\n private _describeEvolution(ctor: NodeConstructor, descriptor: NodeTypeDescriptor): NodeTypeDescriptor {\n const evolution = propEvolutionOf(ctor);\n if (!evolution) return descriptor;\n const properties = { ...descriptor.properties };\n for (const [key, message] of Object.entries(evolution.deprecated)) {\n if (properties[key]) properties[key] = { ...properties[key], deprecated: message };\n }\n const renamed = Object.keys(evolution.renamed).length > 0 ? { renamed: { ...evolution.renamed } } : {};\n return { ...descriptor, ...renamed, properties };\n }\n\n /** `Node.dimension` is a getter so it answers from the prototype, before any field initializer has run. */\n private _describeDimension(ctor: NodeConstructor): NodeDimension | undefined {\n const dimension = (Object.create(ctor.prototype) as Node).dimension;\n return typeof dimension === \"string\" ? dimension : undefined;\n }\n\n private _describeHolds(ctor: NodeConstructor): readonly NodeDimension[] | undefined {\n const trees = (Object.create(ctor.prototype) as Partial<Node>)._childTrees;\n return Array.isArray(trees) ? [...trees] : undefined;\n }\n\n /**\n * A function default is a reactive binding, not a value, so it says nothing about the control; those declare a\n * kind or take \"unknown\", which a host draws read-only.\n */\n private _inferKind(value: unknown): string {\n switch (typeof value) {\n case \"number\": return \"number\";\n case \"string\": return \"text\";\n case \"boolean\": return \"boolean\";\n case \"object\":\n if (value === null) return \"unknown\";\n return Array.isArray(value) && value.every(v => typeof v === \"number\")\n ? \"vector\"\n : \"object\";\n default: return \"unknown\";\n }\n }\n\n private _describeArgs(args: readonly CommandArg[] | undefined): CommandArgDescriptor[] {\n return (args ?? []).map((arg) =>\n typeof arg === \"string\" ? { key: arg, kind: \"unknown\" } : { kind: \"unknown\", ...arg });\n }\n}\n", "import type { Registry } from \"./registry\";\nimport { ROOT_NODE_ID, type NodeSpec } from \"./types\";\n\n/**\n * Where a node type may go, read off the registry without building anything: what a host needs before offering\n * a type under a parent, accepting a drop, or letting an assistant create a row.\n *\n * A parent that takes no children takes none. The two trees do not mix (a `Node3D` lives under a Canvas 3D or\n * another 3D node, and nothing else does). A type naming where it goes ({@link NodeTypeDescriptor.within})\n * goes only there, and a {@link NodeTypeDescriptor.closed} parent takes only the types that name it. {@link\n * NodeTypeDescriptor.beside} is about siblings and kept apart because a host can meet it by adding one.\n *\n * Only a leaf is enforced when a document is built (`allowedChildren: []` throws on a child); a node in any\n * other wrong place builds and as a rule draws nothing, and this says why.\n */\n\nexport type PlacementIssue =\n | { kind: \"leaf\"; parent: string }\n | { kind: \"dimension\"; parent: string | null }\n | { kind: \"within\"; within: readonly string[] }\n | { kind: \"closed\"; parent: string }\n | { kind: \"beside\"; beside: readonly string[] };\n\nexport interface PlacementOptions {\n /**\n * A host's own sense of one type standing for another: a copy of a component under a new key is still that\n * component to whatever goes inside it.\n */\n isA?: (type: string, name: string) => boolean;\n}\n\nconst CANVAS_3D = \"canvas3d\";\n\nexport function nodeTypeIsA(registry: Registry, type: string, name: string): boolean {\n const seen = new Set<string>();\n for (let at: string | undefined = type; at !== undefined && !seen.has(at); at = registry.describe(at)?.parentKey) {\n if (at === name) return true;\n seen.add(at);\n }\n return false;\n}\n\nfunction among(registry: Registry, type: string, names: readonly string[], options: PlacementOptions): boolean {\n return names.some((name) => nodeTypeIsA(registry, type, name) || options.isA?.(type, name) === true);\n}\n\n/** A `null` parent is the document's own root, which is 2D and names nothing. */\nexport function parentIssue(\n registry: Registry,\n child: string,\n parent: string | null,\n options: PlacementOptions = {},\n): PlacementIssue | null {\n const own = registry.describe(child);\n const holder = parent === null ? undefined : registry.describe(parent);\n if (parent !== null && (holder?.layout?.acceptsChildren === false || holder?.holds?.length === 0)) return { kind: \"leaf\", parent };\n\n const within = own?.within ?? [];\n if (within.length > 0 && (parent === null || !among(registry, parent, within, options))) {\n return { kind: \"within\", within };\n }\n if (parent !== null && holder?.closed === true && !among(registry, parent, within, options)) {\n return { kind: \"closed\", parent };\n }\n\n const inThree = parent !== null && (holder?.dimension === \"3d\" || holder?.holds?.includes(\"3d\") === true || among(registry, parent, [CANVAS_3D], options));\n if ((own?.dimension === \"3d\") !== inThree) return { kind: \"dimension\", parent };\n return null;\n}\n\n/** `null` when it needs none or has one. */\nexport function siblingIssue(\n registry: Registry,\n child: string,\n siblings: readonly string[],\n options: PlacementOptions = {},\n): PlacementIssue | null {\n const beside = registry.describe(child)?.beside ?? [];\n if (beside.length === 0 || siblings.some((type) => among(registry, type, beside, options))) return null;\n return { kind: \"beside\", beside };\n}\n\n/**\n * With the first reason. A node of an unregistered type is left out: that is a build error, and says so\n * itself.\n */\nexport function placementIssues(\n registry: Registry,\n nodes: readonly Pick<NodeSpec, \"id\" | \"type\" | \"parentId\">[],\n options: PlacementOptions = {},\n): Map<string, PlacementIssue> {\n // A document may write its stage as a row or leave it out: either way its children's parent is the root.\n const parentOf = (node: Pick<NodeSpec, \"parentId\">) => (node.parentId === ROOT_NODE_ID ? null : node.parentId);\n const byId = new Map(nodes.map((node) => [node.id, node]));\n const children = new Map<string | null, string[]>();\n for (const node of nodes) {\n if (node.id === ROOT_NODE_ID) continue;\n const under = children.get(parentOf(node));\n if (under) under.push(node.type);\n else children.set(parentOf(node), [node.type]);\n }\n const issues = new Map<string, PlacementIssue>();\n for (const node of nodes) {\n if (node.id === ROOT_NODE_ID || !registry.hasNode(node.type)) continue;\n const parentId = parentOf(node);\n const parentType = parentId === null ? null : (byId.get(parentId)?.type ?? null);\n const issue =\n parentIssue(registry, node.type, parentType, options) ??\n siblingIssue(registry, node.type, without(children.get(parentId) ?? [], node.type), options);\n if (issue) issues.set(node.id, issue);\n }\n return issues;\n}\n\n// The node's own type once: a second area is a sibling of the first, the first is not its own.\nfunction without(types: readonly string[], own: string): string[] {\n const at = types.indexOf(own);\n return at === -1 ? [...types] : [...types.slice(0, at), ...types.slice(at + 1)];\n}\n", "import type { AudioDocument, ClipDocument, CommandSpec, CompositionDocument, NodeSpec, TimedNodeSpec, VisualDocument } from \"./types\";\nimport { isAudioDocument, isStillDocument, nodeSpan } from \"./types\";\n\n/**\n * Namespaced like every other synthesized id in the document layer, so it can never collide with an authored\n * one.\n */\nconst AUDIO_ROOT_ID = \"@bus\";\n\nfunction defaultRootBus(): NodeSpec {\n return { id: AUDIO_ROOT_ID, type: \"audioBus\", parentId: null, layerOrder: 0, props: {} };\n}\n\nfunction clipRoot(): NodeSpec {\n return { id: \"\", type: \"canvas2d\", parentId: null, layerOrder: 0, props: {} };\n}\n\n/**\n * An audio document, as the composition it already is: one evaluator runs sound, so a bus fade and a\n * rectangle's fade cannot drift. Only the root needs arranging. A clip's root is always a `Canvas2D`, so the\n * bus becomes its single audio child under {@link AUDIO_ROOT_ID} and every `targetId: null` / `parentId: null`\n * is rewritten to name it. The canvas draws nothing and lays out an empty box once, the whole cost of a clip\n * that is only sound.\n */\nexport function loweredAudioDocument(doc: AudioDocument): CompositionDocument {\n const nodes: TimedNodeSpec[] = [clipRoot()];\n if (!doc.nodes.some(isRootBus)) nodes.push(defaultRootBus());\n for (const spec of doc.nodes) nodes.push(reparent(spec));\n\n return {\n kind: \"composition\",\n duration: doc.duration,\n variables: doc.variables,\n nodes,\n commands: doc.commands.map(retarget),\n };\n}\n\nfunction isRootBus(spec: NodeSpec): boolean {\n return spec.id === \"\" && spec.type === \"audioBus\";\n}\n\nfunction reparent(spec: TimedNodeSpec): TimedNodeSpec {\n if (isRootBus(spec)) return { ...spec, id: AUDIO_ROOT_ID, parentId: null };\n /**\n * `null` is the document's convention for \"the root\"; `\"\"` is the same row named by id, which `checkTree` also\n * resolves.\n */\n if (spec.parentId === null || spec.parentId === \"\") return { ...spec, parentId: AUDIO_ROOT_ID };\n return spec;\n}\n\nfunction retarget(command: CommandSpec): CommandSpec {\n if (command.targetId === null || command.targetId === \"\") {\n return { ...command, targetId: AUDIO_ROOT_ID };\n }\n return command;\n}\n\nexport { AUDIO_ROOT_ID };\n\n/**\n * A `sound` or `video` row with no `play` command of its own gets one: a sound over its span (open-ended, to\n * its own end), a video once per segment or over its span while it plays.\n */\nexport function withPlayedSounds(doc: CompositionDocument): CompositionDocument {\n const played = new Set(doc.commands.filter((c) => c.type === \"play\").map((c) => c.targetId));\n const added: CommandSpec[] = [];\n for (const spec of doc.nodes) {\n if ((spec.type !== \"sound\" && spec.type !== \"video\") || played.has(spec.id)) continue;\n const { start, end } = nodeSpan(spec);\n const segments = spec.type === \"video\" ? (spec.props as { segments?: unknown }).segments : undefined;\n if (Array.isArray(segments) && segments.length > 0) {\n (segments as { at: number; from: number; duration: number; speed?: number; volume?: number }[]).forEach((segment, i) => {\n added.push({\n // An endless segment plays to the source's end: a command has no endless length.\n id: `@play:${spec.id}:${i}`, type: \"play\", targetId: spec.id, at: start + segment.at,\n duration: Number.isFinite(segment.duration) ? segment.duration : 0,\n args: {\n from: segment.from,\n ...(segment.speed !== undefined && { speed: segment.speed }),\n ...(segment.volume !== undefined && { volume: segment.volume }),\n },\n });\n });\n continue;\n }\n added.push({\n id: `@play:${spec.id}`, type: \"play\", targetId: spec.id, at: start,\n duration: Number.isFinite(end) ? end - start : 0, args: {},\n });\n }\n return added.length === 0 ? doc : { ...doc, commands: [...doc.commands, ...added] };\n}\n\nexport function clipDocument(doc: ClipDocument): VisualDocument {\n const lowered = isAudioDocument(doc) ? loweredAudioDocument(doc) : doc;\n return isStillDocument(lowered) ? lowered : withPlayedSounds(lowered);\n}\n", "import { Node } from \"@/components/trees/node/node\";\nimport { expressionOps } from \"./expression/ops\";\nimport { Registry, type NodeConstructor } from \"./registry\";\nimport type { CommandSpec, NodeSpec } from \"./types\";\nimport { ROOT_NODE_ID } from \"./types\";\n\n/**\n * Read off the document and the registry without building anything. Only the library's own implementations are\n * described: a command resolving to a component's method could do anything, so it is `known: false` and\n * assumed to read and write layout.\n */\nexport interface CommandTraits {\n scope: \"node\" | \"variable\";\n /** Resolves to the library's own implementation, so the rules below hold for it. */\n known: boolean;\n lifecycle: boolean;\n /** Building it can read a laid-out box, so it must be built against a settled tree. */\n readsLayout: boolean;\n writesLayout: boolean;\n}\n\nexport const ALIGNMENT_KEYS: readonly string[] = [\n \"center\", \"topLeft\", \"topRight\", \"bottomLeft\", \"bottomRight\",\n \"topCenter\", \"bottomCenter\", \"centerLeft\", \"centerRight\",\n];\n\nconst SKIPPED: CommandTraits = { scope: \"node\", known: true, lifecycle: false, readsLayout: false, writesLayout: false };\n\n/**\n * `null` when it resolves to nothing (compiling it throws). One the build skips (aimed at a placeholder, or\n * unpublished by its target's type) writes nothing, which is known. For `targetId: null` a document with no\n * explicit root row may pass `undefined` as `target`. Resolves as `ClipTimeline._buildPlaced` does.\n */\nexport function commandTraits(registry: Registry, spec: CommandSpec, target: NodeSpec | undefined): CommandTraits | null {\n const lifecycle = LIFECYCLE.has(spec.type);\n const global = registry.command(spec.type);\n if (global?.scope === \"variable\") {\n const known = VARIABLE_COMMANDS.has(spec.type);\n return { scope: \"variable\", known, lifecycle, readsLayout: !known, writesLayout: false };\n }\n\n const row = target ?? (spec.targetId === null ? DEFAULT_ROOT : undefined);\n const record = row ? registry.node(row.type) : undefined;\n if (!row) return null;\n if (!record) return registry.strict ? null : SKIPPED;\n\n let chain: readonly string[] | undefined;\n if (global) {\n chain = GLOBAL_NODE_COMMANDS[spec.type];\n if (chain && typeof methodOf(record.ctor, chain[0]) !== \"function\") return null;\n } else {\n const entry = record.commands.get(spec.type);\n if (!entry) return registry.strict ? null : SKIPPED;\n // A method published under a core command's key is not the core command.\n chain = entry.method === spec.type ? NODE_COMMANDS[spec.type] : undefined;\n }\n\n const known = !lifecycle && chain !== undefined && implementsCore(record.ctor, chain);\n if (!known) return { scope: \"node\", known, lifecycle, readsLayout: true, writesLayout: true };\n\n const args = spec.args ?? {};\n const props = row.props ?? {};\n const written = writtenKeys(spec.type, args);\n return {\n scope: \"node\",\n known,\n lifecycle,\n readsLayout: readsLayout(spec.type, args, props, written),\n writesLayout: written === undefined || written.some((key) => !isLayoutNeutralProp(registry, row.type, key)),\n };\n}\n\n/**\n * Whether it may be held at its end values once finished instead of run (`settled-index.ts`): the library's\n * own implementation of a command whose `at` reads only what it captured when built. Expression args bind live\n * values, so they keep it running. A component's own commands are marked by the factory.\n */\nexport function holdsWhenFinished(traits: CommandTraits | null, spec: CommandSpec): boolean {\n return traits !== null && traits.known && !traits.lifecycle && HELD.has(spec.type)\n && expressionOps.collect(spec.args ?? {}, \"\").length === 0;\n}\n\n/** The nodes whose boxes it may read when built, beside its own target. */\nexport function commandNodeRefs(registry: Registry, spec: CommandSpec, target: NodeSpec | undefined): string[] {\n const global = registry.command(spec.type);\n const row = target ?? (spec.targetId === null ? DEFAULT_ROOT : undefined);\n const descriptors = global\n ? (global.scope === \"node\" ? global.args : undefined)\n : row ? registry.node(row.type)?.commands.get(spec.type)?.args : undefined;\n const refs: string[] = [];\n for (const descriptor of descriptors ?? []) {\n const value = spec.args?.[descriptor.key];\n if (descriptor.kind === \"nodeRef\" && typeof value === \"string\" && value !== \"\") refs.push(value);\n }\n return refs;\n}\n\nexport function isContextProvider(registry: Registry, type: string): boolean {\n const ctor = registry.node(type)?.ctor;\n return ctor !== undefined && methodOf(ctor, \"provideContext\") !== methodOf(Node, \"provideContext\");\n}\n\n/** An unparsable expression counts: it fails the build anyway. */\nexport function hasNodeRef(value: unknown): boolean {\n for (const site of expressionOps.collect(value, \"\")) {\n const parsed = expressionOps.tryParse(site.source);\n if (\"error\" in parsed || parsed.expression.refs.some((ref) => ref.includes(\".\"))) return true;\n }\n return false;\n}\n\n/**\n * Every node's placement is applied after layout; past that, answered only for the library's own classes,\n * since a custom node may lay itself out from anything.\n */\nexport function isLayoutNeutralProp(registry: Registry, type: string, key: string): boolean {\n const record = registry.node(type);\n if (!record) return false;\n // Sound has no box, and the 2D walk skips an audio child.\n if (record.descriptor.dimension === \"audio\") return true;\n if (isPlacementProp(registry, type, key)) return true;\n return coreLibrary().ctors.has(record.ctor) && NEUTRAL_KEYS.has(key);\n}\n\n/** Whether `key` is placement every node of `type` holds as a plain slot, read only once a frame is drawn. */\nexport function isPlacementProp(registry: Registry, type: string, key: string): boolean {\n const dimension = registry.node(type)?.descriptor.dimension;\n return dimension === \"3d\" ? PLACEMENT_3D.has(key) : dimension === \"2d\" && PLACEMENT_2D.has(key);\n}\n\n/** Placement, on a row with no prop its node turns into placement when built (`topLeft` binds `x` and `y`). */\nexport function writesPlacementInPlace(registry: Registry, row: NodeSpec, key: string): boolean {\n const dimension = registry.node(row.type)?.descriptor.dimension;\n const sugar = dimension === \"3d\" ? PLACEMENT_SUGAR_3D : PLACEMENT_SUGAR_2D;\n return isPlacementProp(registry, row.type, key) && !Object.keys(row.props).some((prop) => sugar.has(prop));\n}\n\nconst LIFECYCLE = new Set([\"removeChildAt\", \"addChildAt\", \"reparent\"]);\n\nconst VARIABLE_COMMANDS = new Set([\"variableTo\", \"variableSet\"]);\n\n/**\n * Known commands that are pure functions of `t`. A new one joins once `held-class-commands.test.ts` covers it.\n */\nconst HELD = new Set([\n \"to\", \"set\", \"moveTo\", \"fadeTo\", \"rotateTo\", \"scaleTo\", \"layoutTo\", \"effectTo\", \"pulse\", \"wiggle\",\n \"fillTo\", \"strokeTo\", \"shadowTo\", \"overlayTo\", \"progressTo\", \"zoomTo\", \"panTo\", \"headingTo\",\n \"variableTo\", \"variableSet\",\n]);\n\nconst NEUTRAL_KEYS = new Set([\n \"x\", \"y\", \"rotation\", \"scale\", \"opacity\", \"fill\", \"stroke\", \"shadow\", \"overlay\",\n \"effects\", \"blend\", \"transformOrigin\", \"zoom\", \"lookAt\", \"heading\",\n]);\n\nconst PLACEMENT_2D = new Set([\"x\", \"y\", \"rotation\", \"scale\", \"opacity\"]);\n\nconst PLACEMENT_3D = new Set([\"x\", \"y\", \"z\", \"rotationX\", \"rotationY\", \"rotationZ\", \"scaleX\", \"scaleY\", \"scaleZ\"]);\n\nconst PLACEMENT_SUGAR_2D = new Set([\n \"center\", \"topLeft\", \"topRight\", \"bottomLeft\", \"bottomRight\", \"topCenter\", \"bottomCenter\", \"centerLeft\", \"centerRight\",\n]);\n\nconst PLACEMENT_SUGAR_3D = new Set([\"position\", \"rotation\", \"scale\"]);\n\nconst DEFAULT_ROOT: NodeSpec = { id: ROOT_NODE_ID, type: \"canvas2d\", parentId: null, layerOrder: 0, props: {} };\n\n/**\n * Each command's behaviour as the methods on its target it runs through; a class overriding any of them is\n * running something else under the command's name.\n */\nconst TO = [\"to\", \"_prepareStep\", \"_writeProp\"];\nconst PAINT = [\"command\", \"set\", \"_writeProp\"];\n\nconst GLOBAL_NODE_COMMANDS: Readonly<Record<string, readonly string[]>> = {\n to: TO,\n set: [\"set\", \"_writeProp\"],\n save: [\"save\"],\n fillTo: [\"fillTo\", ...PAINT],\n overlayTo: [\"overlayTo\", ...PAINT],\n strokeTo: [\"strokeTo\", ...PAINT],\n shadowTo: [\"shadowTo\", ...PAINT],\n};\n\nconst NODE_COMMANDS: Readonly<Record<string, readonly string[]>> = {\n ...GLOBAL_NODE_COMMANDS,\n restore: [\"restore\", \"_prepareStep\", \"_writeProp\"],\n fadeTo: [\"fadeTo\", ...TO],\n rotateTo: [\"rotateTo\", ...TO],\n scaleTo: [\"scaleTo\", ...TO],\n layoutTo: [\"layoutTo\", ...TO],\n effectTo: [\"effectTo\", ...TO],\n progressTo: [\"progressTo\", ...TO],\n pulse: [\"pulse\", ...PAINT],\n wiggle: [\"wiggle\", ...PAINT],\n flash: [\"flash\", ...PAINT],\n moveTo: [\"moveTo\", ...TO, \"command\", \"set\"],\n zoomTo: [\"zoomTo\", ...TO],\n panTo: [\"panTo\", ...TO],\n headingTo: [\"headingTo\", ...TO],\n countTo: [\"countTo\", ...TO],\n append: [\"append\", ...TO],\n prepend: [\"prepend\", ...TO],\n // Plays its node's sound: scheduled ahead of time, writing nothing.\n play: [\"play\"],\n};\n\n/** Named commands' writes. `to`/`set` write their args; absent means \"anything\". */\nconst WRITES: Readonly<Record<string, readonly string[]>> = {\n fadeTo: [\"opacity\"],\n rotateTo: [\"rotation\"],\n scaleTo: [\"scale\"],\n layoutTo: [\"width\", \"height\", \"padding\"],\n effectTo: [\"effects\"],\n progressTo: [\"start\", \"end\"],\n pulse: [\"scale\"],\n wiggle: [\"rotation\"],\n flash: [\"start\", \"end\"],\n moveTo: [\"x\", \"y\"],\n zoomTo: [\"zoom\"],\n panTo: [\"lookAt\"],\n headingTo: [\"heading\"],\n fillTo: [\"fill\"],\n overlayTo: [\"overlay\"],\n strokeTo: [\"stroke\"],\n shadowTo: [\"shadow\"],\n play: [],\n};\n\nconst READS_FROM = new Set(Object.keys(NODE_COMMANDS).filter((type) => type !== \"set\" && type !== \"save\"));\n\nfunction readsLayout(\n type: string,\n args: Record<string, unknown>,\n props: Record<string, unknown>,\n written: readonly string[] | undefined,\n): boolean {\n // Resolved against the node's own box the moment the step is prepared.\n if (hasAlignmentKey(args)) return true;\n // Aimed at another node's box.\n if (type === \"moveTo\" && typeof args.target === \"string\" && args.target !== \"\") return true;\n /**\n * An alignment-authored node's x/y are bindings over its box, and a node-ref expression may read another\n * node's (`[card.x]` on an aligned card): taking a `from`, or a snapshot, evaluates them.\n */\n const aligned = hasAlignmentKey(props);\n const refBound = nodeRefKeys(props);\n if (type === \"save\" || type === \"restore\") return aligned || refBound.size > 0;\n if (!READS_FROM.has(type)) return false;\n const touched = type === \"append\" || type === \"prepend\" ? [\"text\"] : type === \"countTo\" ? [\"value\"] : written ?? [];\n return touched.some((key) => refBound.has(key) || (aligned && (key === \"x\" || key === \"y\")));\n}\n\nfunction writtenKeys(type: string, args: Record<string, unknown>): readonly string[] | undefined {\n const named = WRITES[type];\n if (named) return named;\n if (type !== \"to\" && type !== \"set\") return undefined;\n const keys: string[] = [];\n for (const key of Object.keys(args)) {\n if (key === \"size\") keys.push(\"width\", \"height\");\n else if (type === \"to\" && key === \"pivot\") keys.push(\"transformOrigin\");\n else if (type === \"to\" && ALIGNMENT_KEYS.includes(key)) keys.push(\"x\", \"y\", \"transformOrigin\");\n else keys.push(key);\n }\n return keys;\n}\n\nfunction hasAlignmentKey(values: Record<string, unknown>): boolean {\n return ALIGNMENT_KEYS.some((key) => values[key] !== undefined);\n}\n\nconst REF_KEYS = new WeakMap<object, ReadonlySet<string>>();\n\nfunction nodeRefKeys(props: Record<string, unknown>): ReadonlySet<string> {\n let keys = REF_KEYS.get(props);\n if (!keys) {\n const found = new Set<string>();\n for (const key of Object.keys(props)) {\n if (hasNodeRef(props[key])) found.add(key);\n }\n REF_KEYS.set(props, (keys = found));\n }\n return keys;\n}\n\nfunction methodOf(ctor: abstract new (...args: never[]) => unknown, name: string): unknown {\n return (ctor.prototype as Record<string, unknown>)[name];\n}\n\nconst KNOWN = new WeakMap<object, Map<readonly string[], boolean>>();\n\nfunction implementsCore(ctor: NodeConstructor, chain: readonly string[]): boolean {\n let byChain = KNOWN.get(ctor);\n if (!byChain) KNOWN.set(ctor, (byChain = new Map()));\n let known = byChain.get(chain);\n if (known === undefined) {\n // A method the class lacks entirely is not an override of one.\n known = chain.every((name) => {\n const impl = methodOf(ctor, name);\n return impl === undefined || coreImplementations(name).has(impl);\n });\n byChain.set(chain, known);\n }\n return known;\n}\n\ninterface CoreLibrary {\n ctors: ReadonlySet<NodeConstructor>;\n methods: Map<string, ReadonlySet<unknown>>;\n}\n\nlet core: CoreLibrary | null = null;\n\nfunction coreLibrary(): CoreLibrary {\n if (!core) {\n // A registry seeds itself with exactly what the library ships, so a fresh one is that list.\n const seeded = new Registry();\n core = { ctors: new Set(seeded.nodeKeys().map((key) => seeded.node(key)!.ctor)), methods: new Map() };\n }\n return core;\n}\n\nfunction coreImplementations(name: string): ReadonlySet<unknown> {\n const library = coreLibrary();\n let impls = library.methods.get(name);\n if (!impls) {\n const found = new Set<unknown>();\n for (const ctor of library.ctors) {\n for (let proto = ctor.prototype; proto && proto !== Object.prototype; proto = Object.getPrototypeOf(proto)) {\n const own = Object.getOwnPropertyDescriptor(proto, name);\n if (own && typeof own.value === \"function\") found.add(own.value);\n }\n }\n library.methods.set(name, (impls = found));\n }\n return impls;\n}\n", "import { clipDocument } from \"./audio\";\nimport {\n documentDuration,\n nodeSpan,\n ROOT_NODE_ID,\n type ClipDocument,\n type CommandSpec,\n type NodeSpec,\n type VisualDocument,\n type TimedNodeSpec,\n type VariableSpec,\n} from \"./types\";\n\n/**\n * Key order is irrelevant, an `undefined`-valued key equals an absent one (neither survives serialization),\n * arrays are ordered.\n */\nexport function jsonEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (typeof a !== \"object\" || typeof b !== \"object\" || a === null || b === null) {\n return a !== a && b !== b;\n }\n if (Array.isArray(a)) {\n if (!Array.isArray(b) || a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (!jsonEqual(a[i], b[i])) return false;\n }\n return true;\n }\n if (Array.isArray(b)) return false;\n const ao = a as Record<string, unknown>;\n const bo = b as Record<string, unknown>;\n let defined = 0;\n for (const key of Object.keys(ao)) {\n const value = ao[key];\n if (value === undefined) continue;\n defined++;\n if (!jsonEqual(value, bo[key])) return false;\n }\n for (const key of Object.keys(bo)) {\n if (bo[key] !== undefined) defined--;\n }\n return defined === 0;\n}\n\nexport interface RowChanges {\n added: Set<string>;\n removed: Set<string>;\n changed: Set<string>;\n}\n\nexport interface ClipDiff {\n /** Nothing semantic differs — the two documents build the same clip. */\n identical: boolean;\n kindChanged: boolean;\n themeChanged: boolean;\n rootChanged: boolean;\n duration: boolean;\n nodes: RowChanges & {\n respec: Set<string>;\n moved: Set<string>;\n span: Set<string>;\n reorderedParents: Set<string>;\n };\n commands: RowChanges & {\n reorderedAts: Set<number>;\n };\n /** A `name` is a label and never counts. */\n variables: RowChanges;\n remappedKeys: Set<string>;\n}\n\nfunction emptyDiff(): ClipDiff {\n return {\n identical: true,\n kindChanged: false,\n themeChanged: false,\n rootChanged: false,\n duration: false,\n nodes: {\n added: new Set(), removed: new Set(), changed: new Set(),\n respec: new Set(), moved: new Set(), span: new Set(), reorderedParents: new Set(),\n },\n commands: { added: new Set(), removed: new Set(), changed: new Set(), reorderedAts: new Set() },\n variables: { added: new Set(), removed: new Set(), changed: new Set() },\n remappedKeys: new Set(),\n };\n}\n\n/**\n * Only semantic fields are compared, so an edit that cannot change what the clip builds (a variable's `name`,\n * key order inside `props`, `startAt: 0` against an absent one) is not a change. Audio documents are compared\n * as the compositions they lower to.\n */\nexport function diffClip(prev: ClipDocument, next: ClipDocument): ClipDiff {\n const diff = emptyDiff();\n if (prev === next) return diff;\n\n if (prev.kind !== next.kind) {\n diff.kindChanged = true;\n diff.identical = false;\n return diff;\n }\n\n const p = lowered(prev);\n const n = lowered(next);\n\n diff.themeChanged = !jsonEqual((prev as { theme?: unknown }).theme, (next as { theme?: unknown }).theme);\n diff.duration = documentDuration(p) !== documentDuration(n);\n\n if (prev.nodes !== next.nodes) diffNodes(p.nodes, n.nodes, diff);\n if (prev.variables !== next.variables) diffVariables(p.variables ?? [], n.variables ?? [], diff);\n const prevCommands = p.kind === \"composition\" ? p.commands : [];\n const nextCommands = n.kind === \"composition\" ? n.commands : [];\n if ((prev as { commands?: unknown }).commands !== (next as { commands?: unknown }).commands) {\n diffCommands(prevCommands, nextCommands, diff);\n }\n\n diff.identical = !diff.themeChanged && !diff.rootChanged && !diff.duration\n && diff.remappedKeys.size === 0\n && rowsEmpty(diff.nodes) && diff.nodes.reorderedParents.size === 0\n && rowsEmpty(diff.commands) && diff.commands.reorderedAts.size === 0\n && rowsEmpty(diff.variables);\n return diff;\n}\n\nfunction lowered(doc: ClipDocument): VisualDocument {\n return clipDocument(doc);\n}\n\nfunction rowsEmpty(rows: RowChanges): boolean {\n return rows.added.size === 0 && rows.removed.size === 0 && rows.changed.size === 0;\n}\n\nconst DEFAULT_ROOT: NodeSpec = { id: ROOT_NODE_ID, type: \"canvas2d\", parentId: null, layerOrder: 0, props: {} };\n\nfunction diffNodes(prevRows: readonly TimedNodeSpec[], nextRows: readonly TimedNodeSpec[], diff: ClipDiff): void {\n const prev = byId(prevRows);\n const next = byId(nextRows);\n const changes = diff.nodes;\n\n const prevRoot = prev.get(ROOT_NODE_ID) ?? DEFAULT_ROOT;\n const nextRoot = next.get(ROOT_NODE_ID) ?? DEFAULT_ROOT;\n diff.rootChanged = prevRoot !== nextRoot && !sameNode(prevRoot, nextRoot);\n\n for (const [id, a] of prev) {\n if (id === ROOT_NODE_ID) continue;\n const b = next.get(id);\n if (!b) {\n changes.removed.add(id);\n continue;\n }\n if (a === b) continue;\n let changed = false;\n if (a.type !== b.type || a.key !== b.key || !jsonEqual(a.props, b.props)) {\n changes.respec.add(id);\n changed = true;\n }\n if (a.parentId !== b.parentId) {\n changes.moved.add(id);\n changed = true;\n }\n if (!sameSpan(a, b)) {\n changes.span.add(id);\n changed = true;\n }\n if (changed || a.layerOrder !== b.layerOrder) changes.changed.add(id);\n }\n for (const id of next.keys()) {\n if (id !== ROOT_NODE_ID && !prev.has(id)) changes.added.add(id);\n }\n\n const prevKeys = keyed(prevRows);\n for (const [key, id] of keyed(nextRows)) {\n const was = prevKeys.get(key);\n if (was !== undefined && was !== id) diff.remappedKeys.add(key);\n }\n\n const prevOrder = siblingOrder(prevRows);\n const nextOrder = siblingOrder(nextRows);\n for (const [parent, before] of prevOrder) {\n const after = nextOrder.get(parent);\n if (after && !sameRelativeOrder(before, after)) changes.reorderedParents.add(parent);\n }\n}\n\nfunction sameNode(a: NodeSpec, b: NodeSpec): boolean {\n return a.type === b.type\n && a.key === b.key\n && a.parentId === b.parentId\n && a.layerOrder === b.layerOrder\n && jsonEqual(a.props, b.props)\n && sameSpan(a, b);\n}\n\nfunction sameSpan(a: NodeSpec, b: NodeSpec): boolean {\n const sa = nodeSpan(a);\n const sb = nodeSpan(b);\n return sa.start === sb.start && sa.end === sb.end;\n}\n\nfunction diffCommands(prevRows: readonly CommandSpec[], nextRows: readonly CommandSpec[], diff: ClipDiff): void {\n const prev = byId(prevRows);\n const next = byId(nextRows);\n const changes = diff.commands;\n\n for (const [id, a] of prev) {\n const b = next.get(id);\n if (!b) {\n changes.removed.add(id);\n continue;\n }\n if (a === b) continue;\n if (\n a.type !== b.type\n || a.targetId !== b.targetId\n || a.at !== b.at\n || (a.duration ?? 0) !== (b.duration ?? 0)\n || !jsonEqual(a.easing, b.easing)\n || !jsonEqual(a.loop, b.loop)\n || !jsonEqual(a.args, b.args)\n ) {\n changes.changed.add(id);\n }\n }\n for (const id of next.keys()) {\n if (!prev.has(id)) changes.added.add(id);\n }\n\n const prevAts = groupByAt(prevRows);\n const nextAts = groupByAt(nextRows);\n for (const [at, before] of prevAts) {\n const after = nextAts.get(at);\n if (after && !sameRelativeOrder(before, after)) changes.reorderedAts.add(at);\n }\n}\n\nfunction diffVariables(prevRows: readonly VariableSpec[], nextRows: readonly VariableSpec[], diff: ClipDiff): void {\n const prev = byId(prevRows);\n const next = byId(nextRows);\n const changes = diff.variables;\n for (const [id, a] of prev) {\n const b = next.get(id);\n if (!b) {\n changes.removed.add(id);\n continue;\n }\n if (a !== b && (a.lerp !== b.lerp || !jsonEqual(a.value, b.value))) changes.changed.add(id);\n }\n for (const id of next.keys()) {\n if (!prev.has(id)) changes.added.add(id);\n }\n}\n\nfunction byId<T extends { id: string }>(rows: readonly T[]): Map<string, T> {\n const out = new Map<string, T>();\n for (const row of rows) out.set(row.id, row);\n return out;\n}\n\nfunction keyed(rows: readonly NodeSpec[]): Map<string, string> {\n const out = new Map<string, string>();\n for (const row of rows) if (row.key) out.set(row.key, row.id);\n return out;\n}\n\nfunction siblingOrder(rows: readonly NodeSpec[]): Map<string, string[]> {\n const groups = new Map<string, Array<{ id: string; order: number; index: number }>>();\n rows.forEach((row, index) => {\n if (row.id === ROOT_NODE_ID) return;\n const parent = row.parentId ?? ROOT_NODE_ID;\n let list = groups.get(parent);\n if (!list) groups.set(parent, list = []);\n list.push({ id: row.id, order: row.layerOrder, index });\n });\n const out = new Map<string, string[]>();\n for (const [parent, list] of groups) {\n list.sort((a, b) => (a.order - b.order) || (a.index - b.index));\n out.set(parent, list.map((e) => e.id));\n }\n return out;\n}\n\nfunction groupByAt(rows: readonly CommandSpec[]): Map<number, string[]> {\n const out = new Map<number, string[]>();\n for (const row of rows) {\n let list = out.get(row.at);\n if (!list) out.set(row.at, list = []);\n list.push(row.id);\n }\n return out;\n}\n\nfunction sameRelativeOrder(a: readonly string[], b: readonly string[]): boolean {\n const inB = new Set(b);\n const inA = new Set(a);\n const sharedA = a.filter((id) => inB.has(id));\n const sharedB = b.filter((id) => inA.has(id));\n if (sharedA.length !== sharedB.length) return false;\n for (let i = 0; i < sharedA.length; i++) {\n if (sharedA[i] !== sharedB[i]) return false;\n }\n return true;\n}\n", "import { expressionOps } from \"./ops\";\n\n/**\n * `undefined` when the ref has no dot and so names a variable. The dot is the discriminator in the parser\n * (which hands the bracket's contents over as one opaque name), the validator and `ClipTimeline`.\n */\nexport function splitNodeRef(ref: string): { key: string; prop: string } | undefined {\n const dot = ref.indexOf(\".\");\n return dot < 0 ? undefined : { key: ref.slice(0, dot), prop: ref.slice(dot + 1) };\n}\n\nexport interface ExpressionRefs {\n vars: string[];\n keys: Array<[key: string, prop: string]>;\n /** Expressions that failed to parse; their references are not in the lists above. */\n unparsable: number;\n}\n\nexport function expressionRefs(value: unknown, path = \"\"): ExpressionRefs {\n const vars: string[] = [];\n const keys: Array<[string, string]> = [];\n let unparsable = 0;\n const seen = new Set<string>();\n for (const site of expressionOps.collect(value, path)) {\n const parsed = expressionOps.tryParse(site.source);\n if (\"error\" in parsed) {\n unparsable++;\n continue;\n }\n for (const ref of parsed.expression.refs) {\n if (seen.has(ref)) continue;\n seen.add(ref);\n const node = splitNodeRef(ref);\n if (node) keys.push([node.key, node.prop]);\n else vars.push(ref);\n }\n }\n return { vars, keys, unparsable };\n}\n", "import { clipDocument } from \"./audio\";\nimport { expressionRefs, type ExpressionRefs } from \"./expression/refs\";\nimport {\n documentDuration,\n nodeSpan,\n ROOT_NODE_ID,\n type ClipDocument,\n type CommandSpec,\n type NodeSpan,\n type VisualDocument,\n type TimedNodeSpec,\n type VariableSpec,\n} from \"./types\";\n\nexport type InitialKey = \"mounted\" | \"unmounted\" | \"absent\";\n\n/**\n * When compile baselines a node not present at t=0: at the first command `at` inside its own span, mounted or\n * not at that moment.\n */\nexport type CaptureKey = \"none\" | \"arrival-mounted\" | \"arrival-unmounted\";\n\n/** Any one means rebuild. */\nexport interface DocIndexIssues {\n duplicateIds: boolean;\n duplicateKeys: boolean;\n unresolvedParent: boolean;\n cycle: boolean;\n invalidRoot: boolean;\n unparsable: boolean;\n /** An expression naming a variable or node key the document does not declare. */\n unresolvedRefs: boolean;\n}\n\nexport interface DocIndex {\n /** Audio documents are indexed as the composition they lower to. */\n readonly doc: VisualDocument;\n readonly nodes: ReadonlyMap<string, TimedNodeSpec>;\n readonly nodeCount: number;\n readonly variables: ReadonlyMap<string, VariableSpec>;\n readonly commands: ReadonlyMap<string, CommandSpec>;\n /** `at`, ties by array index. */\n readonly ordered: readonly CommandSpec[];\n /** Command ids per target in timeline order; the root's under `\"\"`. */\n readonly byTarget: ReadonlyMap<string, readonly string[]>;\n readonly keyed: ReadonlyMap<string, string>;\n /** Nodes whose props (or `set` args) read a variable, or a keyed node's prop. */\n readonly dependents: {\n byVar: ReadonlyMap<string, ReadonlySet<string>>;\n byKey: ReadonlyMap<string, ReadonlySet<string>>;\n };\n readonly duration: number;\n readonly issues: DocIndexIssues;\n\n children(parentId: string): readonly string[];\n descendants(id: string): string[];\n ownSpan(id: string): NodeSpan | undefined;\n /** Half-open. */\n effSpan(id: string): NodeSpan | undefined;\n targetOf(spec: CommandSpec): string;\n commandsAt(at: number): readonly CommandSpec[];\n /** References per top-level prop, from the row's props and every `set` targeting it. */\n bindings(id: string): ReadonlyMap<string, ExpressionRefs>;\n refs(id: string): ExpressionRefs;\n initialKey(id: string): InitialKey;\n captureKey(id: string): CaptureKey;\n captureTime(id: string): number | undefined;\n}\n\nexport function indexDocument(doc: ClipDocument): DocIndex {\n return new DocumentIndex(clipDocument(doc));\n}\n\nconst NO_REFS: ExpressionRefs = Object.freeze({ vars: [], keys: [], unparsable: 0 }) as ExpressionRefs;\nconst NO_BINDINGS: ReadonlyMap<string, ExpressionRefs> = new Map();\nconst EMPTY: readonly never[] = [];\n\nfunction contains(span: NodeSpan | undefined, t: number): boolean {\n return span !== undefined && t >= span.start && t < span.end;\n}\n\nclass DocumentIndex implements DocIndex {\n readonly nodes = new Map<string, TimedNodeSpec>();\n readonly nodeCount: number;\n readonly variables = new Map<string, VariableSpec>();\n readonly commands = new Map<string, CommandSpec>();\n readonly ordered: readonly CommandSpec[];\n readonly byTarget = new Map<string, string[]>();\n readonly keyed = new Map<string, string>();\n readonly dependents = { byVar: new Map<string, Set<string>>(), byKey: new Map<string, Set<string>>() };\n readonly duration: number;\n readonly issues: DocIndexIssues = {\n duplicateIds: false,\n duplicateKeys: false,\n unresolvedParent: false,\n cycle: false,\n invalidRoot: false,\n unparsable: false,\n unresolvedRefs: false,\n };\n\n constructor(readonly doc: VisualDocument) {\n this.duration = documentDuration(doc);\n const commandRows = doc.kind === \"composition\" ? doc.commands : [];\n\n this._indexNodes(doc.nodes);\n this.nodeCount = this.nodes.size - 1;\n for (const spec of doc.variables ?? []) {\n if (this.variables.has(spec.id) || this.nodes.has(spec.id)) this.issues.duplicateIds = true;\n this.variables.set(spec.id, spec);\n }\n\n this.ordered = commandRows\n .map((spec, index) => ({ spec, index }))\n .sort((a, b) => (a.spec.at - b.spec.at) || (a.index - b.index))\n .map((e) => e.spec);\n for (const spec of this.ordered) {\n if (this.commands.has(spec.id)) this.issues.duplicateIds = true;\n this.commands.set(spec.id, spec);\n const target = this.targetOf(spec);\n let list = this.byTarget.get(target);\n if (!list) this.byTarget.set(target, list = []);\n list.push(spec.id);\n let atList = this._byAt.get(spec.at);\n if (!atList) this._byAt.set(spec.at, atList = []);\n atList.push(spec);\n }\n this._ats = [...this._byAt.keys()];\n\n this._indexRefs(commandRows);\n }\n\n children(parentId: string): readonly string[] {\n return this._children.get(parentId) ?? EMPTY;\n }\n\n descendants(id: string): string[] {\n const out: string[] = [];\n const seen = new Set<string>([id]);\n const stack = [...this.children(id)].reverse();\n while (stack.length > 0) {\n const child = stack.pop()!;\n if (seen.has(child)) continue;\n seen.add(child);\n out.push(child);\n const grand = this.children(child);\n for (let i = grand.length - 1; i >= 0; i--) stack.push(grand[i]);\n }\n return out;\n }\n\n ownSpan(id: string): NodeSpan | undefined {\n const spec = this.nodes.get(id);\n return spec ? nodeSpan(spec) : undefined;\n }\n\n effSpan(id: string): NodeSpan | undefined {\n const memo = this._eff.get(id);\n if (memo) return memo;\n if (!this.nodes.has(id)) return undefined;\n\n const chain: TimedNodeSpec[] = [];\n const seen = new Set<string>();\n let base: NodeSpan = { start: 0, end: Infinity };\n let cursor = this.nodes.get(id);\n while (cursor) {\n const known = this._eff.get(cursor.id);\n if (known) {\n base = known;\n break;\n }\n if (seen.has(cursor.id)) break;\n seen.add(cursor.id);\n chain.push(cursor);\n if (cursor.id === ROOT_NODE_ID || cursor.parentId === null) break;\n cursor = this.nodes.get(cursor.parentId);\n }\n for (let i = chain.length - 1; i >= 0; i--) {\n const own = nodeSpan(chain[i]);\n base = { start: Math.max(base.start, own.start), end: Math.min(base.end, own.end) };\n this._eff.set(chain[i].id, base);\n }\n return this._eff.get(id);\n }\n\n targetOf(spec: CommandSpec): string {\n return spec.targetId ?? ROOT_NODE_ID;\n }\n\n commandsAt(at: number): readonly CommandSpec[] {\n return this._byAt.get(at) ?? EMPTY;\n }\n\n bindings(id: string): ReadonlyMap<string, ExpressionRefs> {\n return this._bindings.get(id) ?? NO_BINDINGS;\n }\n\n refs(id: string): ExpressionRefs {\n return this._refs.get(id) ?? NO_REFS;\n }\n\n initialKey(id: string): InitialKey {\n if (!contains(this.ownSpan(id), 0)) return \"absent\";\n return contains(this.effSpan(id), 0) ? \"mounted\" : \"unmounted\";\n }\n\n captureKey(id: string): CaptureKey {\n const at = this.captureTime(id);\n if (at === undefined) return \"none\";\n return contains(this.effSpan(id), at) ? \"arrival-mounted\" : \"arrival-unmounted\";\n }\n\n captureTime(id: string): number | undefined {\n const own = this.ownSpan(id);\n if (!own || contains(own, 0)) return undefined;\n let lo = 0;\n let hi = this._ats.length;\n while (lo < hi) {\n const mid = (lo + hi) >> 1;\n if (this._ats[mid] < own.start) lo = mid + 1;\n else hi = mid;\n }\n const at = this._ats[lo];\n return at !== undefined && at < own.end ? at : undefined;\n }\n\n private readonly _children = new Map<string, string[]>();\n private readonly _eff = new Map<string, NodeSpan>();\n private readonly _byAt = new Map<number, CommandSpec[]>();\n private _ats: number[] = [];\n private readonly _bindings = new Map<string, Map<string, ExpressionRefs>>();\n private readonly _refs = new Map<string, ExpressionRefs>();\n\n private _indexNodes(rows: readonly TimedNodeSpec[]): void {\n const siblings = new Map<string, Array<{ id: string; order: number; index: number }>>();\n rows.forEach((spec, index) => {\n if (this.nodes.has(spec.id)) this.issues.duplicateIds = true;\n this.nodes.set(spec.id, spec);\n if (spec.key) {\n if (this.keyed.has(spec.key)) this.issues.duplicateKeys = true;\n this.keyed.set(spec.key, spec.id);\n }\n if (spec.id === ROOT_NODE_ID) {\n if (spec.type !== \"canvas2d\" || spec.parentId !== null) this.issues.invalidRoot = true;\n return;\n }\n const parent = spec.parentId ?? ROOT_NODE_ID;\n let list = siblings.get(parent);\n if (!list) siblings.set(parent, list = []);\n list.push({ id: spec.id, order: spec.layerOrder, index });\n });\n if (!this.nodes.has(ROOT_NODE_ID)) {\n this.nodes.set(ROOT_NODE_ID, { id: ROOT_NODE_ID, type: \"canvas2d\", parentId: null, layerOrder: 0, props: {} });\n }\n for (const [parent, list] of siblings) {\n list.sort((a, b) => (a.order - b.order) || (a.index - b.index));\n this._children.set(parent, list.map((e) => e.id));\n }\n\n const settled = new Set<string>([ROOT_NODE_ID]);\n for (const spec of this.nodes.values()) {\n if (spec.parentId !== null && !this.nodes.has(spec.parentId)) this.issues.unresolvedParent = true;\n const seen = new Set<string>();\n let cursor: TimedNodeSpec | undefined = spec;\n while (cursor && !settled.has(cursor.id)) {\n if (seen.has(cursor.id)) {\n this.issues.cycle = true;\n break;\n }\n seen.add(cursor.id);\n cursor = cursor.parentId === null ? undefined : this.nodes.get(cursor.parentId);\n }\n for (const id of seen) settled.add(id);\n }\n }\n\n private _indexRefs(commandRows: readonly CommandSpec[]): void {\n for (const spec of this.nodes.values()) this._bind(spec.id, spec.props);\n for (const command of commandRows) {\n if (command.type === \"set\") {\n const target = this.targetOf(command);\n if (this.nodes.has(target)) {\n this._bind(target, command.args);\n continue;\n }\n }\n if (expressionRefs(command.args).unparsable > 0) this.issues.unparsable = true;\n }\n\n for (const [id, props] of this._bindings) {\n const vars = new Set<string>();\n const keys = new Map<string, [string, string]>();\n let unparsable = 0;\n for (const refs of props.values()) {\n for (const v of refs.vars) vars.add(v);\n for (const pair of refs.keys) keys.set(`${pair[0]}.${pair[1]}`, pair);\n unparsable += refs.unparsable;\n }\n this._refs.set(id, { vars: [...vars], keys: [...keys.values()], unparsable });\n\n for (const v of vars) {\n if (!this.variables.has(v)) this.issues.unresolvedRefs = true;\n let readers = this.dependents.byVar.get(v);\n if (!readers) this.dependents.byVar.set(v, readers = new Set());\n readers.add(id);\n }\n for (const [key] of keys.values()) {\n if (!this.keyed.has(key)) this.issues.unresolvedRefs = true;\n let readers = this.dependents.byKey.get(key);\n if (!readers) this.dependents.byKey.set(key, readers = new Set());\n readers.add(id);\n }\n }\n }\n\n private _bind(id: string, props: Record<string, unknown> | undefined): void {\n if (!props) return;\n for (const prop of Object.keys(props)) {\n const found = expressionRefs(props[prop]);\n if (found.unparsable > 0) this.issues.unparsable = true;\n if (found.vars.length === 0 && found.keys.length === 0) continue;\n let table = this._bindings.get(id);\n if (!table) this._bindings.set(id, table = new Map());\n const existing = table.get(prop);\n if (!existing) {\n table.set(prop, found);\n continue;\n }\n const vars = new Set([...existing.vars, ...found.vars]);\n const keys = new Map([...existing.keys, ...found.keys].map((p) => [`${p[0]}.${p[1]}`, p] as const));\n table.set(prop, { vars: [...vars], keys: [...keys.values()], unparsable: existing.unparsable + found.unparsable });\n }\n }\n}\n", "import { clamp01 } from \"@/util/clamp\";\nimport { observeSlots } from \"@/props/observer\";\nimport type { PropSlot, PropSnapshot } from \"@/props/slot\";\nimport { settles, type Command } from \"@/tween/command\";\n\nexport interface SettlePlaced {\n readonly start: number;\n /** An entrance holds `at(0)` from here. */\n readonly holdFrom?: number;\n readonly duration: number;\n readonly command: Command<Record<string, unknown>>;\n readonly writes: ReadonlySet<PropSlot<unknown>>;\n /** What it may read while it runs. */\n readonly reads?: ReadonlySet<PropSlot<unknown>>;\n}\n\n/**\n * Evaluation that holds finished commands instead of running them. A command marked {@link settling} leaves\n * fixed end values, so once finished it is a stored write per slot (only the latest-placed finished writer\n * counts) and a frame costs a lookup per written slot plus the commands still running; the timeline's length\n * drops out.\n *\n * Unmarked commands, and marked ones still running, run in placement order. After each, a slot it writes whose\n * held writer was placed later gets that writer's value back, so placement order still decides. This relies on\n * the timeline's restore: a command writes nothing while running that it did not write while being built.\n *\n * A held end value is in place before every command runs, so one an earlier unmarked command reads (a `save`)\n * would reach it early: a marked command writing a slot an earlier unmarked one read is run as if unmarked.\n */\nexport class SettledIndex {\n static build(placed: readonly SettlePlaced[]): SettledIndex | null {\n const finish = new Float64Array(placed.length).fill(NaN);\n const writers = new Map<PropSlot<unknown>, Writer[]>();\n const replayed: number[] = [];\n const running: number[] = [];\n const read = new Set<PropSlot<unknown>>();\n for (let i = 0; i < placed.length; i++) {\n const p = placed[i];\n const marked = settles(p.command);\n const end = marked && !readEarlier(p.writes, read) ? finishTime(p.start, p.duration) : NaN;\n if (Number.isNaN(end)) {\n if (!marked && p.reads) for (const slot of p.reads) read.add(slot);\n replayed.push(i);\n continue;\n }\n finish[i] = end;\n if (end > (p.holdFrom ?? p.start)) running.push(i);\n /** Only what `at(1)` writes is an end value; a slot written only while building is not held. */\n const written = new Set<PropSlot<unknown>>();\n observeSlots({ read: () => { }, write: (slot) => written.add(slot) }, () => p.command.at(1));\n for (const slot of written) {\n const list = writers.get(slot);\n const writer = { order: i, finish: end, end: slot.snapshot() };\n if (list) list.push(writer);\n else writers.set(slot, [writer]);\n }\n }\n if (replayed.length === placed.length) return null;\n return new SettledIndex(placed, finish, [...writers].map(([slot, list]) => new Track(slot, list)), replayed, running);\n }\n\n holds(index: number): boolean {\n return !Number.isNaN(this._finish[index]);\n }\n\n evaluate(placed: readonly SettlePlaced[], seconds: number): void {\n const tracks = this._tracks;\n const held = this._held;\n for (let k = 0; k < tracks.length; k++) {\n const w = (held[k] = tracks[k].at(seconds));\n if (w >= 0) tracks[k].slot.restoreFrom(tracks[k].ends[w]);\n }\n\n const replayed = this._replayed;\n const long = this._long;\n const bin = this._binOf(seconds);\n const binEnd = this._binStart[bin + 1];\n let a = 0;\n let b = this._binStart[bin];\n let c = 0;\n for (; ;) {\n const ia = a < replayed.length ? replayed[a] : NONE;\n const ib = b < binEnd ? this._binItems[b] : NONE;\n const ic = c < long.length ? long[c] : NONE;\n let i: number;\n if (ia < ib && ia < ic) {\n i = ia;\n a++;\n } else if (ib < ic) {\n i = ib;\n b++;\n } else if (ic !== NONE) {\n i = ic;\n c++;\n } else {\n break;\n }\n\n const p = placed[i];\n /** An unmarked finish is NaN, which no time reaches. */\n if (seconds < (p.holdFrom ?? p.start) || this._finish[i] <= seconds) continue;\n p.command.at(seconds < p.start ? 0 : clamp01(p.duration > 0 ? (seconds - p.start) / p.duration : 1));\n for (let f = this._fixStart[i]; f < this._fixStart[i + 1]; f++) {\n const k = this._fixTracks[f];\n const w = held[k];\n if (w >= 0 && tracks[k].order[w] > i) tracks[k].slot.restoreFrom(tracks[k].ends[w]);\n }\n }\n }\n\n private constructor(\n placed: readonly SettlePlaced[],\n private readonly _finish: Float64Array,\n private readonly _tracks: readonly Track[],\n private readonly _replayed: readonly number[],\n running: readonly number[],\n ) {\n this._held = new Int32Array(_tracks.length);\n\n /** One spanning many bins is checked on every evaluation instead. */\n let from = Infinity;\n let to = -Infinity;\n for (const i of running) {\n from = Math.min(from, placed[i].holdFrom ?? placed[i].start);\n to = Math.max(to, _finish[i]);\n }\n const bins = Math.max(1, Math.min(MAX_BINS, running.length));\n this._from = Number.isFinite(from) ? from : 0;\n this._width = to > from ? (to - from) / bins : 1;\n this._bins = bins;\n const items: number[][] = Array.from({ length: bins }, () => []);\n const long: number[] = [];\n for (const i of running) {\n const first = this._binOf(placed[i].holdFrom ?? placed[i].start);\n const last = this._binOf(_finish[i]);\n if (last - first > MAX_SPAN) long.push(i);\n else for (let bin = first; bin <= last; bin++) items[bin].push(i);\n }\n this._long = long;\n this._binStart = new Int32Array(bins + 1);\n for (let bin = 0; bin < bins; bin++) this._binStart[bin + 1] = this._binStart[bin] + items[bin].length;\n this._binItems = Int32Array.from(items.flat());\n\n const trackOf = new Map<PropSlot<unknown>, number>(_tracks.map((track, k) => [track.slot, k]));\n const fixes: number[] = [];\n this._fixStart = new Int32Array(placed.length + 1);\n for (let i = 0; i < placed.length; i++) {\n for (const slot of placed[i].writes) {\n const k = trackOf.get(slot);\n if (k !== undefined) fixes.push(k);\n }\n this._fixStart[i + 1] = fixes.length;\n }\n this._fixTracks = Int32Array.from(fixes);\n }\n\n private readonly _held: Int32Array;\n private readonly _from: number;\n private readonly _width: number;\n private readonly _bins: number;\n private readonly _binStart: Int32Array;\n private readonly _binItems: Int32Array;\n private readonly _long: readonly number[];\n private readonly _fixStart: Int32Array;\n private readonly _fixTracks: Int32Array;\n\n private _binOf(seconds: number): number {\n const bin = Math.floor((seconds - this._from) / this._width);\n return bin < 0 ? 0 : bin >= this._bins ? this._bins - 1 : bin;\n }\n}\n\nfunction readEarlier(writes: ReadonlySet<PropSlot<unknown>>, read: ReadonlySet<PropSlot<unknown>>): boolean {\n if (read.size === 0) return false;\n for (const slot of writes) if (read.has(slot)) return true;\n return false;\n}\n\nconst NONE = 0x7fffffff;\nconst MAX_BINS = 1024;\nconst MAX_SPAN = 32;\n\ninterface Writer {\n order: number;\n finish: number;\n end: PropSnapshot<unknown>;\n}\n\nclass Track {\n readonly finish: Float64Array;\n readonly order: Int32Array;\n readonly ends: PropSnapshot<unknown>[];\n private readonly _best: Int32Array;\n\n constructor(readonly slot: PropSlot<unknown>, writers: Writer[]) {\n writers.sort((x, y) => x.finish - y.finish || x.order - y.order);\n this.finish = Float64Array.from(writers, (w) => w.finish);\n this.order = Int32Array.from(writers, (w) => w.order);\n this.ends = writers.map((w) => w.end);\n this._best = new Int32Array(writers.length);\n let best = 0;\n for (let i = 0; i < writers.length; i++) {\n if (this.order[i] > this.order[best]) best = i;\n this._best[i] = best;\n }\n }\n\n at(seconds: number): number {\n let lo = 0;\n let hi = this.finish.length;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if (this.finish[mid] <= seconds) lo = mid + 1;\n else hi = mid;\n }\n return lo === 0 ? -1 : this._best[lo - 1];\n }\n}\n\n/**\n * By the timeline's own arithmetic, `(t - start) / duration >= 1`; `start + duration` can miss it by a\n * rounding step either way. NaN when it cannot be pinned down, which leaves the command running every\n * evaluation.\n */\nfunction finishTime(start: number, duration: number): number {\n if (!(duration > 0)) return start;\n const done = (t: number) => (t - start) / duration >= 1;\n let t = start + duration;\n if (!Number.isFinite(t)) return NaN;\n for (let i = 0; !done(t); i++) {\n if (i === 8) return NaN;\n t = step(t, true);\n }\n for (let i = 0; i < 8; i++) {\n const down = step(t, false);\n if (!done(down)) return t;\n t = down;\n }\n return NaN;\n}\n\nconst BITS = new Float64Array(1);\nconst INTS = new BigInt64Array(BITS.buffer);\n\nfunction step(x: number, up: boolean): number {\n if (x === 0) return up ? Number.MIN_VALUE : -Number.MIN_VALUE;\n BITS[0] = x;\n INTS[0] += (x > 0) === up ? 1n : -1n;\n return BITS[0];\n}\n", "import type { CommandTraits } from \"./command-traits\";\nimport { jsonEqual, type ClipDiff } from \"./diff\";\nimport type { DocIndex } from \"./doc-index\";\nimport type { ExpressionRefs } from \"./expression/refs\";\nimport { nodeSpan, ROOT_NODE_ID, type CommandSpec, type NodeSpan, type NodeSpec } from \"./types\";\n\n/** What the planner needs to know about code, so it can be exercised without a registry. */\nexport interface PatchEnvironment {\n traits(spec: CommandSpec, target: NodeSpec | undefined): CommandTraits | null;\n nodeRefs?(spec: CommandSpec, target: NodeSpec | undefined): readonly string[];\n isContextProvider(type: string): boolean;\n isLayoutNeutralProp(type: string, key: string): boolean;\n /** Whether a new `key` on `row` is written onto its live node rather than a new one. Absent writes none in place. */\n writesInPlace?(row: NodeSpec, key: string): boolean;\n ctorOf(id: string): unknown;\n registeredCtor(type: string): unknown;\n /** A type's tree; `\"audio\"` rows are left out of layout decisions. Absent treats every type as laid out. */\n dimensionOf?(type: string): string | undefined;\n}\n\nexport interface TimelinePatch {\n prev: DocIndex;\n next: DocIndex;\n diff: ClipDiff;\n added: ReadonlySet<string>;\n removed: ReadonlySet<string>;\n reinstantiate: ReadonlySet<string>;\n inPlace: ReadonlySet<string>;\n detach: ReadonlySet<string>;\n dirtyNodes: ReadonlySet<string>;\n dirtyVariables: ReadonlySet<string>;\n /** Clean chains that must run for dirty ones to build against the right values. */\n replay: ReadonlySet<string> | \"all\";\n captures: ReadonlyArray<{ at: number; id: string }>;\n layoutChanged: boolean;\n}\n\nexport interface PatchOptions {\n /** Rebuild instead once more than this fraction of nodes would be re-instantiated. Default 0.5. */\n rebuildFraction?: number;\n /** Patch whenever at most this many nodes would be re-instantiated, whatever the fraction. Default {@link MIN_REBUILD_NODES}. */\n minRebuildNodes?: number;\n}\n\n/**\n * A rebuild of a small clip is not cheaper than patching it: the runtime also throws away the track's asset\n * index, sweeps it again and republishes it.\n */\nexport const MIN_REBUILD_NODES = 16;\n\n/**\n * `null` when only a rebuild is sound. Every rule errs towards doing more: a node marked dirty that did not\n * need it costs one chain rebuild, while one missed renders a frame that disagrees with a fresh build of the\n * same document.\n */\nexport function planTimelinePatch(\n prev: DocIndex,\n next: DocIndex,\n diff: ClipDiff,\n env: PatchEnvironment,\n options: PatchOptions = {},\n): TimelinePatch | null {\n if (diff.kindChanged || diff.themeChanged) return null;\n if (structurallyFaulty(prev) || structurallyFaulty(next)) return null;\n const prevRoot = prev.nodes.get(ROOT_NODE_ID)!;\n const nextRoot = next.nodes.get(ROOT_NODE_ID)!;\n // The canvas is never re-instantiated, so only props it can be reset and re-set to are patched.\n if (diff.rootChanged && !onlyPropsDiffer(prevRoot, nextRoot)) return null;\n if (next.issues.unparsable || next.issues.unresolvedRefs) return null;\n if (diff.remappedKeys.size > 0) return null;\n\n const prevTraits = traitsOf(prev, env);\n const nextTraits = prevTraits && traitsOf(next, env);\n if (!prevTraits || !nextTraits) return null;\n\n const { added, removed, respec, moved, span, reorderedParents } = diff.nodes;\n const targeted = (id: string): boolean => (next.byTarget.get(id)?.length ?? 0) > 0;\n const anyCommand = (index: DocIndex, traits: Map<string, CommandTraits>, id: string, test: (t: CommandTraits) => boolean) =>\n index.byTarget.get(id)?.some((cid) => test(traits.get(cid)!)) ?? false;\n const unknownEither = (id: string) =>\n anyCommand(prev, prevTraits, id, (t) => !t.known) || anyCommand(next, nextTraits, id, (t) => !t.known);\n const laidOut = (index: DocIndex, id: string) => {\n const type = index.nodes.get(id)?.type;\n return type === undefined || env.dimensionOf?.(type) !== \"audio\";\n };\n const laidOutEither = (id: string) => laidOut(prev, id) || laidOut(next, id);\n const kept: string[] = [];\n for (const id of next.nodes.keys()) {\n if (id !== ROOT_NODE_ID && prev.nodes.has(id)) kept.push(id);\n }\n\n const R = new Set<string>();\n const isProvider = (id: string) => {\n const a = prev.nodes.get(id)?.type;\n const b = next.nodes.get(id)?.type;\n return (a !== undefined && env.isContextProvider(a)) || (b !== undefined && env.isContextProvider(b));\n };\n const reinstantiate = (id: string) => {\n if (R.has(id)) return;\n R.add(id);\n // A provider among the descendants needs no recursion: its subtree is already in this one.\n if (isProvider(id)) for (const d of next.descendants(id)) R.add(d);\n };\n\n const inPlace = new Set<string>();\n for (const id of respec) {\n if (placementOnly(prev, next, id, env)) inPlace.add(id);\n else reinstantiate(id);\n }\n for (const id of moved) {\n reinstantiate(id);\n if (providerAbove(prev, id, env) || providerAbove(next, id, env)) {\n for (const d of next.descendants(id)) R.add(d);\n }\n }\n for (const id of [...added, ...removed]) {\n if (isProvider(id)) for (const d of next.descendants(id)) R.add(d);\n }\n let reregistered = false;\n for (const id of kept) {\n const live = env.ctorOf(id);\n if (live !== undefined && env.registeredCtor(next.nodes.get(id)!.type) !== live) {\n reinstantiate(id);\n if (laidOutEither(id)) reregistered = true;\n }\n if (targeted(id) && prev.initialKey(id) !== next.initialKey(id)) reinstantiate(id);\n }\n\n const DN = new Set<string>();\n const DV = new Set<string>();\n const mark = (id: string) => {\n if (next.variables.has(id)) DV.add(id);\n else if (next.nodes.has(id)) DN.add(id);\n };\n\n for (const cid of diff.commands.added) mark(next.targetOf(next.commands.get(cid)!));\n for (const cid of diff.commands.removed) mark(prev.targetOf(prev.commands.get(cid)!));\n for (const cid of diff.commands.changed) {\n mark(prev.targetOf(prev.commands.get(cid)!));\n mark(next.targetOf(next.commands.get(cid)!));\n }\n for (const id of new Set([...prev.byTarget.keys(), ...next.byTarget.keys()])) {\n if (!sameList(prev.byTarget.get(id), next.byTarget.get(id))) mark(id);\n }\n for (const at of diff.commands.reorderedAts) {\n for (const spec of prev.commandsAt(at)) mark(prev.targetOf(spec));\n for (const spec of next.commandsAt(at)) mark(next.targetOf(spec));\n }\n /**\n * An unlimited loop is built to fill the clip it found, so a clip that grew or shrank rebuilds it though\n * nothing on the command changed.\n */\n if (diff.duration) {\n for (const spec of next.commands.values()) {\n if (spec.loop?.count === null) mark(next.targetOf(spec));\n }\n }\n for (const id of diff.variables.added) DV.add(id);\n for (const id of diff.variables.changed) DV.add(id);\n\n const presenceChanged = new Set<string>();\n for (const id of kept) {\n if (!sameSpan(prev.effSpan(id), next.effSpan(id))) {\n presenceChanged.add(id);\n if (targeted(id)) DN.add(id);\n } else if (\n targeted(id)\n && (prev.captureKey(id) !== next.captureKey(id) || prev.captureTime(id) !== next.captureTime(id))\n ) {\n DN.add(id);\n }\n }\n\n let L = reorderedParents.size > 0 || reregistered\n || [...added].some((id) => laidOut(next, id))\n || [...removed].some((id) => laidOut(prev, id))\n || [...moved].some(laidOutEither)\n || [...span].some(laidOutEither)\n || [...respec].some((id) => laidOutEither(id) && respecTouchesLayout(prev.nodes.get(id)!, next.nodes.get(id)!, env))\n || (diff.rootChanged && respecTouchesLayout(prevRoot, nextRoot, env));\n\n /** Anything reading one of them through `[key.prop]` builds its chain from different values. */\n const valueChanged = new Set<string>([...added, ...removed, ...presenceChanged, ...inPlace]);\n if (diff.rootChanged) valueChanged.add(ROOT_NODE_ID);\n const aimed = [...nodeReaders(prev, env), ...nodeReaders(next, env)];\n const bindsLayout = (reader: string, reads: (refs: ExpressionRefs) => boolean) => {\n const type = next.nodes.get(reader)?.type;\n if (type === undefined || env.dimensionOf?.(type) === \"audio\") return false;\n for (const [prop, refs] of next.bindings(reader)) {\n if (reads(refs) && !env.isLayoutNeutralProp(type, prop)) return true;\n }\n return false;\n };\n\n let size = -1;\n while (size !== DN.size + DV.size + R.size + valueChanged.size + (L ? 1 : 0)) {\n size = DN.size + DV.size + R.size + valueChanged.size + (L ? 1 : 0);\n\n for (const id of R) if (targeted(id)) DN.add(id);\n for (const id of R) valueChanged.add(id);\n for (const id of DN) valueChanged.add(id);\n\n for (const v of DV) {\n for (const reader of next.dependents.byVar.get(v) ?? []) {\n valueChanged.add(reader);\n if (!L && bindsLayout(reader, (refs) => refs.vars.includes(v))) L = true;\n }\n }\n for (const id of valueChanged) {\n for (const key of keysOf(prev, next, id)) {\n for (const reader of next.dependents.byKey.get(key) ?? []) {\n valueChanged.add(reader);\n if (!L && bindsLayout(reader, (refs) => refs.keys.some(([k]) => k === key))) L = true;\n }\n }\n }\n // Where a named node is depends on every ancestor too.\n for (const { reader, ref } of aimed) {\n if (lineageIn(prev, ref, valueChanged) || lineageIn(next, ref, valueChanged)) valueChanged.add(reader);\n }\n for (const id of valueChanged) if (next.nodes.has(id) && targeted(id)) DN.add(id);\n\n for (const id of DN) {\n if (id !== ROOT_NODE_ID && unknownEither(id)) reinstantiate(id);\n }\n\n if (!L) {\n for (const id of [...DN, ...DV]) {\n if (anyCommand(prev, prevTraits, id, (t) => t.writesLayout) || anyCommand(next, nextTraits, id, (t) => t.writesLayout)) {\n L = true;\n break;\n }\n }\n }\n if (L) {\n for (const id of next.byTarget.keys()) {\n if (next.nodes.has(id) && anyCommand(next, nextTraits, id, (t) => t.readsLayout)) DN.add(id);\n }\n }\n }\n\n if (DN.has(ROOT_NODE_ID) && unknownEither(ROOT_NODE_ID)) return null;\n const limit = Math.max((options.rebuildFraction ?? 0.5) * next.nodeCount, options.minRebuildNodes ?? MIN_REBUILD_NODES);\n if (R.size > limit) return null;\n for (const id of R) inPlace.delete(id);\n\n let replay: Set<string> | \"all\";\n const dirtyTargets = [...DN, ...DV];\n if (dirtyTargets.some((id) => anyCommand(next, nextTraits, id, (t) => t.readsLayout || !t.known))) {\n replay = \"all\";\n } else {\n replay = new Set<string>();\n const queue: string[] = [];\n const visited = new Set<string>();\n for (const id of DN) {\n const refs = next.refs(id);\n if (refs.vars.length === 0 && refs.keys.length === 0) continue;\n if (!(next.byTarget.get(id) ?? []).some((cid) => next.commands.get(cid)!.type !== \"set\")) continue;\n visited.add(id);\n queue.push(id);\n }\n while (queue.length > 0) {\n const refs = next.refs(queue.pop()!);\n for (const v of refs.vars) {\n if (!DV.has(v) && targeted(v)) replay.add(v);\n }\n for (const [key] of refs.keys) {\n const id = next.keyed.get(key);\n if (id === undefined) continue;\n if (!DN.has(id) && targeted(id)) replay.add(id);\n if (!visited.has(id)) {\n visited.add(id);\n queue.push(id);\n }\n }\n }\n }\n\n const detach = new Set<string>([...removed, ...R]);\n for (const parent of reorderedParents) {\n for (const child of next.children(parent)) if (prev.nodes.has(child)) detach.add(child);\n }\n for (const id of R) {\n for (const child of next.children(id)) detach.add(child);\n }\n\n const captures: Array<{ at: number; id: string }> = [];\n for (const id of new Set([...DN, ...R, ...added])) {\n if (!targeted(id)) continue;\n const at = next.captureTime(id);\n if (at !== undefined) captures.push({ at, id });\n }\n captures.sort((a, b) => a.at - b.at);\n\n return {\n prev,\n next,\n diff,\n added,\n removed,\n reinstantiate: R,\n inPlace,\n detach,\n dirtyNodes: DN,\n dirtyVariables: DV,\n replay,\n captures,\n layoutChanged: L,\n };\n}\n\nfunction structurallyFaulty(index: DocIndex): boolean {\n const { duplicateIds, duplicateKeys, unresolvedParent, cycle, invalidRoot } = index.issues;\n return duplicateIds || duplicateKeys || unresolvedParent || cycle || invalidRoot;\n}\n\n/**\n * `null` when one cannot be patched at all: it does not resolve, it changes structure, or its target is not\n * the kind its scope names.\n */\nfunction traitsOf(index: DocIndex, env: PatchEnvironment): Map<string, CommandTraits> | null {\n const out = new Map<string, CommandTraits>();\n for (const spec of index.ordered) {\n const targetId = index.targetOf(spec);\n const target = index.nodes.get(targetId);\n const traits = env.traits(spec, target);\n if (!traits || traits.lifecycle) return null;\n if (traits.scope === \"variable\" ? !index.variables.has(targetId) : !target) return null;\n out.set(spec.id, traits);\n }\n return out;\n}\n\nfunction nodeReaders(index: DocIndex, env: PatchEnvironment): Array<{ reader: string; ref: string }> {\n if (!env.nodeRefs) return [];\n const out: Array<{ reader: string; ref: string }> = [];\n for (const spec of index.ordered) {\n const reader = index.targetOf(spec);\n for (const ref of env.nodeRefs(spec, index.nodes.get(reader))) out.push({ reader, ref });\n }\n return out;\n}\n\nfunction lineageIn(index: DocIndex, id: string, set: ReadonlySet<string>): boolean {\n const seen = new Set<string>();\n let cursor: string | undefined = id;\n while (cursor !== undefined && !seen.has(cursor)) {\n if (set.has(cursor)) return true;\n seen.add(cursor);\n const spec = index.nodes.get(cursor);\n if (!spec || cursor === ROOT_NODE_ID) return false;\n cursor = spec.parentId ?? ROOT_NODE_ID;\n }\n return false;\n}\n\nfunction providerAbove(index: DocIndex, id: string, env: PatchEnvironment): boolean {\n const seen = new Set<string>([id]);\n let cursor = index.nodes.get(id);\n while (cursor && cursor.id !== ROOT_NODE_ID) {\n const parentId: string = cursor.parentId ?? ROOT_NODE_ID;\n if (seen.has(parentId)) return false;\n seen.add(parentId);\n cursor = index.nodes.get(parentId);\n if (cursor && env.isContextProvider(cursor.type)) return true;\n }\n return false;\n}\n\nfunction onlyPropsDiffer(a: NodeSpec, b: NodeSpec): boolean {\n const sa = nodeSpan(a);\n const sb = nodeSpan(b);\n return a.type === b.type && a.key === b.key && a.parentId === b.parentId && a.layerOrder === b.layerOrder\n && sa.start === sb.start && sa.end === sb.end;\n}\n\nfunction placementOnly(prev: DocIndex, next: DocIndex, id: string, env: PatchEnvironment): boolean {\n const a = prev.nodes.get(id)!;\n const b = next.nodes.get(id)!;\n if (!env.writesInPlace || a.type !== b.type || a.key !== b.key) return false;\n const was = prev.bindings(id);\n const is = next.bindings(id);\n for (const key of new Set([...Object.keys(a.props), ...Object.keys(b.props)])) {\n if (jsonEqual(a.props[key], b.props[key])) continue;\n // A prop taken out would go back to its default, which only a new instance knows.\n if (b.props[key] === undefined || was.has(key) || is.has(key) || !env.writesInPlace(b, key)) return false;\n }\n return true;\n}\n\nfunction respecTouchesLayout(a: NodeSpec, b: NodeSpec, env: PatchEnvironment): boolean {\n if (a.type !== b.type || a.key !== b.key) return true;\n for (const key of new Set([...Object.keys(a.props), ...Object.keys(b.props)])) {\n if (!jsonEqual(a.props[key], b.props[key]) && !env.isLayoutNeutralProp(b.type, key)) return true;\n }\n return false;\n}\n\nfunction keysOf(prev: DocIndex, next: DocIndex, id: string): string[] {\n const out: string[] = [];\n const a = prev.nodes.get(id)?.key;\n const b = next.nodes.get(id)?.key;\n if (a) out.push(a);\n if (b && b !== a) out.push(b);\n return out;\n}\n\nfunction sameSpan(a: NodeSpan | undefined, b: NodeSpan | undefined): boolean {\n return a?.start === b?.start && a?.end === b?.end;\n}\n\nfunction sameList(a: readonly string[] | undefined, b: readonly string[] | undefined): boolean {\n if (a === b) return true;\n if (!a || !b || a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;\n return true;\n}\n", "import { clamp01 } from \"@/util/clamp\";\nimport { applySnapshotLayer, captureLayer, type PropLayer, type ReactiveHost } from \"@/components/trees/node/node-reactive\";\nimport type { Node, NodeDimension } from \"@/components/trees/node/node\";\nimport type { Canvas2D } from \"@/components/trees/root/canvas2d-node\";\nimport { _observer, PropSlot, type PropSnapshot } from \"@/props/slot\";\nimport { LAYOUT_SLOT, observeSlots, PRESENCE_PREFIX, unobserved, VAR_PREFIX, type SlotObserver } from \"@/props/observer\";\nimport { driveCommand, loopCommand, settles, settling, type Command } from \"@/tween/command\";\nimport { loopRepeats } from \"@/tween/loop\";\nimport type { EasingFunction } from \"@/tween/ease/type\";\nimport { easeOfSpec } from \"@/tween/ease/spec\";\nimport { commandNodeRefs, commandTraits, hasNodeRef, holdsWhenFinished, isContextProvider, isLayoutNeutralProp, writesPlacementInPlace } from \"./command-traits\";\nimport { diffClip, jsonEqual } from \"./diff\";\nimport { indexDocument, type DocIndex } from \"./doc-index\";\nimport { expressionOps } from \"./expression/ops\";\nimport { MISSING_TYPE, missingNode, missingNodeOf, placeholderProps } from \"./missing-node\";\nimport { migrateNodeProps } from \"./prop-evolution\";\nimport type { VariableResolver } from \"./expression/types\";\nimport type { Registry, VariableTarget } from \"./registry\";\nimport { SettledIndex } from \"./settled-index\";\nimport { commandSoundsOf } from \"@/components/factory/timeline\";\nimport type { SoundOptions } from \"@/components/factory/api\";\nimport { planTimelinePatch, type PatchEnvironment, type TimelinePatch } from \"./timeline-patch\";\nimport type { CommandSpec, EaseSpec, NodeSpec, NodeSpan, VisualDocument, VariableSpec } from \"./types\";\nimport { documentDuration, effectiveSpanIn, isStillDocument, nodeSpan, ROOT_NODE_ID } from \"./types\";\n\nexport interface PlacedSound {\n readonly node: Node;\n readonly at: number;\n readonly until: number | undefined;\n readonly src: string;\n readonly options: SoundOptions;\n}\n\nexport interface TimelineIssue {\n code: \"unknown-node-type\" | \"unknown-command\";\n message: string;\n nodeId?: string;\n commandId?: string;\n type: string;\n}\n\nexport interface PlacedCommandInfo {\n readonly spec: CommandSpec;\n readonly start: number;\n /** Zero is a stamp: it applies in full from `start` onward. */\n readonly duration: number;\n /** `start`, or for an entrance the earlier time its first frame is held from. */\n readonly holdFrom: number;\n readonly writes: ReadonlySet<PropSlot<unknown>>;\n readonly readsLayout: boolean;\n}\n\ninterface PlacedCommand extends PlacedCommandInfo {\n readonly command: Command<Record<string, unknown>>;\n readonly writes: Set<PropSlot<unknown>>;\n /** What an unmarked one may read while it runs: its owner's slots and what it read while built. Empty for a marked one. */\n readonly reads: ReadonlySet<PropSlot<unknown>>;\n /** Its neighbours decide it, so it is worked out again after every compile and update. */\n holdFrom: number;\n readonly entrance: boolean;\n readonly owner: LiveNode | LiveVariable;\n}\n\n/** A plain slot: a prop bound to `() => slot.get()` re-reads it, so nothing in the node layer knows variables exist. */\ninterface LiveVariable {\n spec: VariableSpec;\n /** Kept across an update: every binding compiled against it captured {@link read}, which reads this. */\n cell: PropSlot<unknown>;\n read: () => unknown;\n target: VariableTarget;\n baseline: unknown;\n}\n\ninterface LiveNode {\n spec: NodeSpec;\n node: Node;\n /** Every reactive cell as the build left it, before any command or arrival touched it. */\n initial: PropLayer;\n initialStackDepth: number;\n /** What evaluation restores: {@link initial}, or the node as it arrived when it enters later. */\n baseline: PropLayer;\n baseStackDepth: number;\n /** A slot, so a `[key.prop]` read under an observer depends on it: the node answering can come and go. */\n presence: PropSlot<boolean>;\n}\n\ninterface WalkStep {\n at: number;\n spec?: CommandSpec;\n capture?: string;\n}\n\nfunction resolveEase(ease: EaseSpec | undefined, registry: Registry): EasingFunction | undefined {\n if (!ease) return undefined;\n return easeOfSpec(ease, (key) => registry.ease(key), () => registry.easeKeys());\n}\n\n/** By `at`, then document order: commands sharing an `at` run in parallel and the later one wins a shared prop, as in `commandParallel`. */\nfunction inTimelineOrder(commands: readonly CommandSpec[]): CommandSpec[] {\n return commands\n .map((spec, index) => ({ spec, index }))\n .sort((a, b) => (a.spec.at - b.spec.at) || (a.index - b.index))\n .map((e) => e.spec);\n}\n\nconst NO_SLOTS: ReadonlySet<PropSlot<unknown>> = new Set();\n\n/**\n * Only an unmarked command can read live state while it runs, so only its reads are kept. A slot\n * snapshot (`save`) reads without reporting it, so everything it acts on counts as read.\n */\nfunction readsOf(command: Command<Record<string, unknown>>, recorder: WriteRecorder, owned: Iterable<PropSlot<unknown>>): ReadonlySet<PropSlot<unknown>> {\n if (settles(command)) return NO_SLOTS;\n for (const slot of owned) recorder.reads.add(slot);\n return recorder.reads;\n}\n\n/** Marks the command `settling` when `held`; a looped one is wrapped after, and runs. */\nfunction heldIf(held: boolean, made: Command<Record<string, unknown>> | void): Command<Record<string, unknown>> | void {\n return held && made ? settling(made) : made;\n}\n\nfunction defaultRootSpec(): NodeSpec {\n return { id: ROOT_NODE_ID, type: \"canvas2d\", parentId: null, layerOrder: 0, props: {} };\n}\n\n/**\n * Split out the scene root, which is the canvas itself: not something `build` instantiates or `syncPresence`\n * parents. Synthesizes the default when the document left it out.\n */\nfunction splitRoot(specs: NodeSpec[]): { root: NodeSpec; rest: NodeSpec[] } {\n const rest: NodeSpec[] = [];\n let root: NodeSpec | undefined;\n for (const spec of specs) {\n if (spec.id === ROOT_NODE_ID && spec.type === \"canvas2d\") {\n root = spec;\n continue;\n }\n rest.push(spec);\n }\n return { root: root ?? defaultRootSpec(), rest };\n}\n\n/** Read off the document, not accumulated in playback, so a seek lands the same from any direction. A still's nodes carry no span: always present. */\nfunction presenceOf(doc: VisualDocument): Map<string, NodeSpan> {\n const spans = new Map<string, NodeSpan>();\n for (const node of doc.nodes) spans.set(node.id, nodeSpan(node));\n spans.delete(ROOT_NODE_ID);\n return spans;\n}\n\n/**\n * A compiled clip document, evaluable at any time in any order. Commands are built in `at` order, each run to\n * `at(1)` before the next is built, because a command reads its start value from the node when constructed;\n * the restored baseline undoes that. Expressions bind props to variable slots and recompute on read, so a\n * node driven only by expressions is never restored.\n */\nexport class ClipTimeline {\n constructor(doc: VisualDocument, registry: Registry, private readonly canvas: Canvas2D) {\n this._doc = doc;\n this._registry = registry;\n const { root, rest } = splitRoot(doc.nodes);\n this._rootSpec = root;\n this._specs = rest;\n this._varSpecs = doc.variables ?? [];\n // Built from the rows rather than from the tree: an expression resolves its\n // references the moment it compiles, which is before most nodes exist.\n this._keyed = new Map(\n [root, ...rest]\n .filter((spec): spec is NodeSpec & { key: string } => !!spec.key)\n .map((spec) => [spec.key, spec.id]),\n );\n this._spans = presenceOf(doc);\n // Declared, not measured, so it is known before anything is built.\n this._duration = documentDuration(doc);\n }\n\n get duration(): number {\n return this._duration;\n }\n\n /** Once per timeline: the nodes it makes belong to that canvas. */\n build(): void {\n // Variables first: an expression resolves its `[id]`s the moment it compiles.\n this._buildVariables();\n\n this._pristineRoot = captureLayer(this.canvas as unknown as ReactiveHost);\n this._applyRootProps();\n\n for (const spec of this._specs) {\n this._live.set(spec.id, {\n spec,\n node: this._instantiate(spec),\n initial: NO_LAYER,\n initialStackDepth: 0,\n baseline: NO_LAYER,\n baseStackDepth: 0,\n presence: new PropSlot<boolean>(false, null, PRESENCE_PREFIX + spec.id),\n });\n }\n\n // Before any document child lands, so a composite's own children keep their indices.\n this._baseChildCount.set(ROOT_NODE_ID, this.canvas._allChildren.length);\n for (const [id, entry] of this._live) {\n this._baseChildCount.set(id, entry.node._allChildren.length);\n }\n\n this.syncPresence(0);\n\n // The root's baseline too: `targetId: null` commands animate the camera and scene fill.\n this._root = {\n spec: this._rootSpec,\n node: this.canvas,\n initial: NO_LAYER,\n initialStackDepth: 0,\n baseline: NO_LAYER,\n baseStackDepth: 0,\n presence: new PropSlot<boolean>(true, null, PRESENCE_PREFIX + ROOT_NODE_ID),\n };\n for (const entry of this._live.values()) captureInitial(entry);\n captureInitial(this._root);\n this._baselined = new Set(this._present);\n for (const id of this._present) {\n if (this._live.get(id)?.node.mounted === false) {\n this._baselined.delete(id);\n this._unmounted.add(id);\n }\n }\n }\n\n /**\n * Build every command against the laid-out tree, then put the tree back. Separate from {@link build} because a\n * command may read post-layout state (an animated `removeChildAt` pins the departing child to its rendered\n * width, zero until layout runs). `settle` re-lays out whenever the walk changes the tree.\n */\n compile(settle: () => void = () => { }): void {\n this._settled = null;\n this._compileCommands(settle);\n this._restoreBaselines();\n const moved = this.syncPresence(0);\n if (this._restoreDisplaced(this._collectDisplaced()) || moved) settle();\n this._holdEntrances();\n this._indexSettled();\n }\n\n variableValue(id: string): unknown {\n return this._vars.get(id)?.cell.get();\n }\n\n variables(): readonly VariableSpec[] {\n return this._varSpecs;\n }\n\n get presenceTime(): number {\n return this._presenceIndex().time;\n }\n\n commandSounds(): PlacedSound[] {\n const out: PlacedSound[] = [];\n for (const placed of this._placed) {\n const played = commandSoundsOf(placed.command);\n if (!played) continue;\n for (const sound of played.sounds) {\n out.push({\n node: played.host,\n at: placed.start + sound.at,\n until: sound.until === undefined ? undefined : placed.start + sound.until,\n src: sound.src,\n options: sound.options,\n });\n }\n }\n return out;\n }\n\n placedCommands(): readonly PlacedCommandInfo[] {\n return this._placed;\n }\n\n issues(): TimelineIssue[] {\n const out: TimelineIssue[] = [];\n for (const { spec, node } of this._live.values()) {\n const missing = missingNodeOf(node);\n if (!missing) continue;\n out.push({\n code: \"unknown-node-type\",\n nodeId: spec.id,\n type: missing.type,\n message: `Unknown node type \"${missing.type}\" (node ${spec.id}): it builds as an empty placeholder, keeping its children.`,\n });\n }\n out.push(...this._skipped.values());\n return out;\n }\n\n /**\n * Pure in `seconds`: any order, either direction. Restoring the baseline first is what makes it so, or a prop\n * written by a not-yet-started command would keep the last evaluation's value. `onWrite` reports each\n * command write (not the restore) with its index in {@link placedCommands}.\n */\n evaluateAt(seconds: number, onWrite?: (index: number, slot: PropSlot<unknown>) => void): void {\n if (onWrite) {\n // Unobserved: a baseline holds prop cells, never presence or structure, so\n // an observer watching for those learns nothing from a write per cell.\n unobserved(() => this._restoreBaselines());\n this._evaluateObserved(seconds, onWrite);\n return;\n }\n\n if (this._settled) {\n this._restoreBaselines(this._wholeRestore);\n for (const { slot, baseline } of this._slotRestore) slot.restoreFrom(baseline);\n this._settled.evaluate(this._placed, seconds);\n return;\n }\n this._restoreBaselines();\n for (const placed of this._placed) {\n if (seconds < placed.holdFrom) continue;\n const local = seconds < placed.start ? 0\n : placed.duration > 0 ? (seconds - placed.start) / placed.duration\n : 1;\n // Held at `at(1)` once finished, so an early write persists (as in `commandSequence`).\n placed.command.at(clamp01(local));\n }\n }\n\n /**\n * Add and remove document nodes so the tree matches `seconds`; returns whether anything moved. Structural, so\n * separate from {@link evaluateAt}: it changes what layout walks. Call it ahead of the evaluation.\n */\n syncPresence(seconds: number): boolean {\n const rows = this._presenceIndex().crossed(seconds);\n if (rows.length === 0) return false;\n\n const arrivals: PresenceRow[] = [];\n const departures: PresenceRow[] = [];\n for (const row of rows) {\n const wanted = within(row, seconds);\n if (wanted !== this._present.has(row.id)) (wanted ? arrivals : departures).push(row);\n }\n this._arrived = arrivals;\n if (arrivals.length === 0 && departures.length === 0) return false;\n\n // Detach first: `remove` unmounts the whole subtree, so a node moving\n // parents is never briefly in two places.\n departures.sort(byDocumentOrder);\n for (const row of departures) {\n this._present.delete(row.id);\n row.siblings.add(row.slot, -1);\n const entry = this._live.get(row.id);\n if (!entry) continue;\n entry.presence.set(false);\n this._parentNodeOf(entry.spec)?.remove(entry.node);\n }\n\n // After whatever the parent built for itself, at the row's place among present siblings. Ascending per\n // parent, so every earlier sibling is already in place.\n arrivals.sort(byDocumentOrder);\n const byParent = new Map<SiblingCounts, PresenceRow[]>();\n for (const row of arrivals) {\n const group = byParent.get(row.siblings);\n if (group) group.push(row);\n else byParent.set(row.siblings, [row]);\n }\n for (const [siblings, group] of byParent) {\n group.sort((a, b) => a.slot - b.slot);\n const parent = siblings.parentId === ROOT_NODE_ID ? this.canvas : this._live.get(siblings.parentId)?.node;\n const base = this._baseChildCount.get(siblings.parentId) ?? 0;\n for (const row of group) {\n this._present.add(row.id);\n const index = base + siblings.before(row.slot);\n siblings.add(row.slot, 1);\n const child = this._live.get(row.id);\n if (!child) continue;\n child.presence.set(true);\n parent?.addChildAt({ data: { child: child.node, index } });\n }\n }\n return true;\n }\n\n liveNode(id: string): Node | undefined {\n return id === ROOT_NODE_ID ? this.canvas : this._live.get(id)?.node;\n }\n\n /** A row's props before any command acted on it; the same at every time, unlike the live props. A bound prop answers through its binding. */\n baselineProps(id: string): Record<string, unknown> | undefined {\n const entry = id === ROOT_NODE_ID ? this._root : this._live.get(id);\n if (!entry) return undefined;\n const layer = entry.baseline === NO_LAYER ? entry.initial : entry.baseline;\n const props: Record<string, unknown> = {};\n for (const [key, snap] of layer) props[key] = snap.fn ? snap.fn() : snap.value;\n return props;\n }\n\n presenceSlot(id: string): PropSlot<boolean> | undefined {\n return id === ROOT_NODE_ID ? this._root?.presence : this._live.get(id)?.presence;\n }\n\n variableSlot(id: string): PropSlot<unknown> | undefined {\n return this._vars.get(id)?.cell;\n }\n\n /**\n * How to bring this built timeline to `next` in place, or `null` when only a\n * fresh build is sound. An audio document must be lowered by the caller first.\n */\n planUpdate(next: VisualDocument): TimelinePatch | null {\n const prev = this._docIndex ??= indexDocument(this._doc);\n return planTimelinePatch(prev, indexDocument(next), diffClip(this._doc, next), this._patchEnvironment());\n }\n\n /**\n * Apply a {@link planUpdate} result. The canvas must be attached at time 0\n * first, as for {@link build}; `prepare` samples and lays out like the step\n * between build and compile, `settle` like compile's. A throw leaves the\n * timeline unusable — dispose it and build fresh.\n */\n applyUpdate(patch: TimelinePatch, settle: () => void, prepare: () => void): void {\n if (!this._root) throw new Error(\"ClipTimeline.applyUpdate needs a built timeline.\");\n if (patch.prev !== this._docIndex) {\n throw new Error(\"This patch was planned against a different version of the document.\");\n }\n\n this._settled = null;\n this._restoreBaselines();\n this.syncPresence(0);\n\n this._updateVariables(patch);\n this._keyed.clear();\n for (const [key, id] of patch.next.keyed) this._keyed.set(key, id);\n\n const fresh = this._updateStructure(patch);\n\n for (const entry of fresh) {\n captureInitial(entry);\n const id = entry.spec.id;\n if (!this._present.has(id)) continue;\n if (entry.node.mounted) this._baselined.add(id);\n else this._unmounted.add(id);\n }\n for (const id of patch.inPlace) {\n const entry = this._live.get(id);\n if (entry) this._writeInPlace(entry, patch.prev.nodes.get(id)!);\n }\n if (patch.diff.rootChanged) {\n const host = this.canvas as unknown as ReactiveHost;\n applySnapshotLayer(host, this._pristineRoot);\n host._stateStack.length = 0;\n this._applyRootProps();\n captureInitial(this._root);\n }\n for (const id of patch.dirtyNodes) {\n const entry = id === ROOT_NODE_ID ? this._root : this._live.get(id);\n if (entry && !fresh.has(entry)) resetToInitial(entry);\n }\n prepare();\n\n const previous = new Map<string, PlacedCommand>();\n for (const placed of this._placed) previous.set(placed.spec.id, placed);\n const rebuilt = this._walkPatch(patch, previous, settle);\n\n const dirty = (id: string) => patch.dirtyNodes.has(id) || patch.dirtyVariables.has(id);\n const placed: PlacedCommand[] = [];\n const touched = new Set<TouchedOwner>();\n this._animated = [];\n this._animatedVars = [];\n this._animatedParts = [];\n if (!isStillDocument(this._doc)) {\n for (const spec of patch.next.ordered) {\n let entry = rebuilt.get(spec.id);\n if (!entry && !dirty(patch.next.targetOf(spec))) {\n const old = previous.get(spec.id);\n if (old) entry = old.spec === spec ? old : { ...old, spec };\n }\n if (!entry) continue;\n placed.push(entry);\n this._touch(entry, touched);\n }\n }\n this._placed = placed;\n for (const id of this._skipped.keys()) if (!patch.next.commands.has(id)) this._skipped.delete(id);\n\n this._restoreBaselines();\n const moved = this.syncPresence(0);\n if (this._restoreDisplaced(this._collectDisplaced()) || moved) settle();\n this._holdEntrances();\n this._indexSettled();\n }\n\n private _doc: VisualDocument;\n private readonly _registry: Registry;\n private _rootSpec: NodeSpec;\n private _specs: NodeSpec[];\n private _varSpecs: readonly VariableSpec[];\n private _spans: Map<string, NodeSpan>;\n private _duration: number;\n private _docIndex: DocIndex | null = null;\n /** The canvas's cells before the root row was applied — what a patched root row resets to. */\n private _pristineRoot: PropLayer = NO_LAYER;\n\n private readonly _live = new Map<string, LiveNode>();\n private readonly _vars = new Map<string, LiveVariable>();\n /** Node ids by {@link NodeSpec.key}. Read off the document, so it needs no build. */\n private readonly _keyed: Map<string, string>;\n private _placed: PlacedCommand[] = [];\n private readonly _skipped = new Map<string, TimelineIssue>();\n /** Built after every compile and update, when any placed command is marked settling (`tween/command`). */\n private _settled: SettledIndex | null = null;\n /** With {@link _settled}: the animated nodes an unmarked command writes, put back whole… */\n private _wholeRestore: LiveNode[] = [];\n /** …and, on every other animated node, the baseline of each slot a marked command writes. */\n private _slotRestore: SlotBaseline[] = [];\n private _root: LiveNode | null = null;\n /**\n * Only nodes some command writes: restoring static nodes every frame is most of the frame on a large scene. A\n * prop bound to a variable needs no restore (the binding is the recompute), so expression-only nodes never enter.\n */\n private _animated: LiveNode[] = [];\n private _animatedVars: LiveVariable[] = [];\n /** Slots on a part a node built for itself that a command writes. A part is no row; see {@link _notePartWrite}. */\n private _animatedParts: PropSlot<unknown>[] = [];\n private readonly _partBaselines = new WeakMap<PropSlot<unknown>, PropSnapshot<unknown>>();\n /** Children each parent built for itself, which the document must not disturb. */\n private readonly _baseChildCount = new Map<string, number>();\n private readonly _present = new Set<string>();\n private _baselined = new Set<string>();\n /** Rows present at 0 that a lifecycle command (`removeChildAt`, `reparent`) took out of their parent. Presence only moves a row across its own span. */\n private _displaced: LiveNode[] = [];\n /** Rows that arrived, or were built, while an ancestor was out of the tree and wait for it — see {@link _baselineArrival}. */\n private readonly _unmounted = new Set<string>();\n private _presence: PresenceIndex | null = null;\n private _arrived: readonly PresenceRow[] = [];\n\n /**\n * A reference with a dot (`[card.x]`) reads another node's prop; without one, a variable.\n *\n * A node reference resolves late, on every read: `build` binds in document order and presence changes with\n * time, so the node may not exist yet or be absent at *t*. It answers `undefined` (`NaN` through arithmetic,\n * loud in the first frame) rather than throwing, which would make an `add` at 2s a crash at 0s.\n */\n private readonly _resolveVariable: VariableResolver = (name) => {\n const dot = name.indexOf(\".\");\n if (dot > 0) {\n const id = this._keyed.get(name.slice(0, dot));\n if (id === undefined) return undefined;\n const prop = name.slice(dot + 1);\n return () => (this._nodeById(id) as unknown as Record<string, unknown> | undefined)?.[prop];\n }\n return this._vars.get(name)?.read;\n };\n\n /** Gated on `mounted`, not {@link _present}, which only settles at the end of {@link syncPresence}: a read mid-insertion would be stale. */\n private _nodeById(id: string): Node | undefined {\n if (id === ROOT_NODE_ID) return this.canvas;\n const entry = this._live.get(id);\n if (!entry) return undefined;\n if (_observer !== null) this._readPresence(entry);\n return entry.node.mounted ? entry.node : undefined;\n }\n\n /** The row's presence and every document ancestor's — an ancestor leaving unmounts it too. */\n private _readPresence(entry: LiveNode): void {\n let at: LiveNode | undefined = entry;\n for (let depth = 0; at && depth <= this._live.size; depth++) {\n at.presence.get();\n at = at.spec.parentId === null ? undefined : this._live.get(at.spec.parentId);\n }\n }\n\n private _applyRootProps(): void {\n const { literal, bindings } = expressionOps.bindProps(this._rootSpec.props, this._resolveVariable);\n this.canvas.set({ ...literal, ...bindings } as never);\n }\n\n private _instantiate(spec: NodeSpec, rows: readonly NodeSpec[] = this._specs): Node {\n const props = migrateNodeProps(this._registry, spec.type, spec.props).props;\n const { literal, bindings, hasBindings } = expressionOps.bindProps(props, this._resolveVariable);\n if (!this._registry.strict && !this._registry.hasNode(spec.type)) {\n const dimension = this._placeholderDimension(spec, rows);\n const node = missingNode(dimension, spec, literal);\n const bound = placeholderProps(dimension, bindings);\n if (Object.keys(bound).length > 0) node.set(bound as never);\n return node;\n }\n const node = this._registry.instantiate(spec, literal);\n // Applied after construction rather than through it: see `instantiate`.\n if (hasBindings) node.set(bindings as never);\n return node;\n }\n\n /** One slot per variable for the whole build: a variable has no presence span. */\n private _buildVariables(): void {\n for (const spec of this._varSpecs) {\n if (this._vars.has(spec.id)) {\n throw new Error(\n `Duplicate variable id \"${spec.id}\". Ids must be unique — an expression ` +\n `writing \"[${spec.id}]\" would otherwise name whichever declaration was read last.`,\n );\n }\n this._vars.set(spec.id, this._liveVariable(spec));\n }\n }\n\n private _liveVariable(spec: VariableSpec): LiveVariable {\n const cell = new PropSlot<unknown>(spec.value, null, VAR_PREFIX + spec.id);\n return {\n spec,\n cell,\n read: () => cell.get(),\n target: this._variableTarget(spec, cell),\n baseline: spec.value,\n };\n }\n\n private _variableTarget(spec: VariableSpec, cell: PropSlot<unknown>): VariableTarget {\n const lerp = this._registry.requireLerp(spec.lerp, spec.value, `variable \"${spec.id}\"`);\n return { id: spec.id, get: () => cell.get(), set: (v) => cell.set(v), lerp };\n }\n\n /**\n * Put every animated node back to its authored state. The save stack is truncated with the props: `save` and\n * `restore` are commands, so a `save` re-runs on every evaluation and the stack would grow per frame, and a\n * `restore` would pop another seek's layer.\n */\n private _restoreBaselines(nodes: readonly LiveNode[] = this._animated): void {\n // Structure before props: a node put back is attached, and the baseline is\n // what it holds once attached.\n this._restoreDisplaced(this._displaced);\n\n // Variables first, so a prop bound to one recomputes against the restored\n // value rather than a stale one.\n for (const entry of this._animatedVars) entry.cell.set(entry.baseline);\n\n for (const entry of nodes) {\n const host = entry.node as unknown as ReactiveHost;\n applySnapshotLayer(host, entry.baseline);\n if (host._stateStack.length > entry.baseStackDepth) {\n host._stateStack.length = entry.baseStackDepth;\n }\n }\n\n for (const slot of this._animatedParts) slot.restoreFrom(this._partBaselines.get(slot)!);\n }\n\n /**\n * Build every command, in timeline order, against a node holding what its predecessors left. The tree moves to\n * each command's `at` first: an unmounted node hands back an inert stepper the command caches, so a tween on a\n * node entering at 2s built against the t=0 tree would never move. Arrivals are baselined here, before\n * anything touches them. Re-layout only where something reads it ({@link _settleWindows}).\n */\n private _compileCommands(settle: () => void): void {\n if (isStillDocument(this._doc)) return;\n\n const touched = new Set<TouchedOwner>();\n const ordered = inTimelineOrder(this._doc.commands);\n const refBound = this._refBound(ordered);\n const settles = this._settleWindows(ordered, (i) => this._readsLayout(ordered[i], refBound));\n\n for (let i = 0; i < ordered.length; i++) {\n const spec = ordered[i];\n if (this.syncPresence(spec.at)) {\n // Every node present but not yet baselined arrived in this sync:\n // one that left and came back was baselined the first time.\n for (const row of this._arrived) {\n if (!this._baselined.has(row.id)) this._baselineArrival(row.id);\n }\n this._baselineMounted();\n if (settles[i]) settle();\n }\n\n const placed = this._buildPlaced(spec);\n if (!placed) continue;\n this._placed.push(placed);\n this._touch(placed, touched);\n }\n }\n\n /**\n * Building runs every marked command to its end, which the restore then undoes.\n * A node only marked commands write keeps every other slot at its baseline from\n * here on, so an evaluation puts back only the slots they write.\n */\n private _indexSettled(): void {\n const index = (this._settled = SettledIndex.build(this._placed));\n if (!index) return;\n this._restoreBaselines();\n\n const whole = new Set<LiveNode | LiveVariable>();\n const written = new Map<LiveNode, Set<PropSlot<unknown>>>();\n this._placed.forEach((placed, i) => {\n const held = index.holds(i);\n if (!held) whole.add(placed.owner);\n for (const slot of placed.writes) {\n const host = slot._host;\n const entry = host === null ? undefined : host.id === ROOT_NODE_ID ? this._root! : this._live.get(host.id);\n if (!entry) continue;\n if (!held) whole.add(entry);\n else if (written.has(entry)) written.get(entry)!.add(slot);\n else written.set(entry, new Set([slot]));\n }\n });\n this._wholeRestore = [];\n this._slotRestore = [];\n for (const entry of this._animated) {\n const slots = whole.has(entry) ? null : slotBaselines(entry, written.get(entry));\n if (slots) this._slotRestore.push(...slots);\n else this._wholeRestore.push(entry);\n }\n }\n\n private _collectDisplaced(): LiveNode[] {\n const out: LiveNode[] = [];\n for (const id of this._present) {\n const entry = this._live.get(id);\n const parent = entry && this._declaredParent(id);\n if (entry && parent && entry.node.parent !== parent) out.push(entry);\n }\n out.sort((a, b) => this._presenceIndex().row(a.spec.id)!.slot - this._presenceIndex().row(b.spec.id)!.slot);\n return (this._displaced = out);\n }\n\n /** Put displaced rows back where {@link syncPresence} would have inserted them. */\n private _restoreDisplaced(entries: readonly LiveNode[]): boolean {\n let moved = false;\n for (const entry of entries) {\n const id = entry.spec.id;\n const row = this._presenceIndex().row(id);\n const parent = this._declaredParent(id);\n if (!row || !parent || !this._present.has(id) || entry.node.parent === parent) continue;\n entry.node.parent?.remove(entry.node);\n const base = this._baseChildCount.get(row.siblings.parentId) ?? 0;\n parent.addChildAt({ data: { child: entry.node, index: base + row.siblings.before(row.slot) } });\n moved = true;\n }\n return moved;\n }\n\n private _declaredParent(id: string): Node | undefined {\n const parentId = this._presenceIndex().row(id)?.siblings.parentId;\n if (parentId === undefined) return undefined;\n return parentId === ROOT_NODE_ID ? this.canvas : this._live.get(parentId)?.node;\n }\n\n /**\n * A baseline is the node as attached: an unmounted node's cells hold pre-attach values, lacking what it inherits.\n * A row arriving while an ancestor is out of the tree (a child entering before its parent) waits in\n * {@link _unmounted} for {@link _baselineMounted}.\n */\n private _baselineArrival(id: string): void {\n const entry = this._live.get(id);\n if (entry && !entry.node.mounted) {\n this._unmounted.add(id);\n return;\n }\n if (entry) captureBaseline(entry);\n this._baselined.add(id);\n this._unmounted.delete(id);\n }\n\n private _baselineMounted(): void {\n for (const id of this._unmounted) {\n const entry = this._live.get(id);\n if (!entry) {\n this._unmounted.delete(id);\n } else if (entry.node.mounted) {\n captureBaseline(entry);\n this._baselined.add(id);\n this._unmounted.delete(id);\n }\n }\n }\n\n /**\n * Build one command against the current tree and run it to its end, leaving its target where the next\n * command's `from` must start: `node.to({ x: 100 })` reads `x` at construction, so skipping this would give\n * every chained step the same `from`. Undone by {@link _restoreBaselines}. Throws when the target names no\n * row; a command its target's type lacks, or any aimed at a placeholder, is skipped and recorded (`null`)\n * unless the registry is strict.\n */\n private _buildPlaced(spec: CommandSpec): PlacedCommand | null {\n // The global table is consulted first: it holds only what resolves without a node (variable-scoped\n // commands, generic prop writers), and `scope` decides whether there is a node to look up. Everything\n // else is a method on the target's own type.\n let entry = this._registry.command(spec.type);\n if (entry?.scope !== \"variable\") {\n const missing = missingNodeOf(this._targetOrThrow(spec).node);\n if (missing) {\n return this._skip(spec, `Command ${spec.id} (\"${spec.type}\") targets \"${spec.targetId}\", a placeholder for unknown node type \"${missing.type}\"; it is skipped.`, spec.type);\n }\n }\n if (!entry) {\n const typeKey = this._targetOrThrow(spec).entry.spec.type;\n const factory = this._registry.nodeCommand(typeKey, spec.type);\n if (!factory) {\n const message = `Node type \"${typeKey}\" has no command \"${spec.type}\" ` +\n `(command ${spec.id}). It publishes: ` +\n `${this._registry.commandKeys(typeKey).join(\", \") || \"none\"}.` +\n (LEGACY_COMMAND_HINTS[spec.type] ? ` ${LEGACY_COMMAND_HINTS[spec.type]}` : \"\");\n if (this._registry.strict) throw new Error(message);\n return this._skip(spec, `${message} It is skipped.`, spec.type);\n }\n entry = { key: spec.type, scope: \"node\", factory };\n }\n this._skipped.delete(spec.id);\n\n const duration = spec.duration ?? 0;\n const easing = resolveEase(spec.easing, this._registry);\n const recorder = new WriteRecorder(this._notePartWrite);\n // Applied inside `buildToEnd`, so `at(1)` is the loop's end (back at the start for an odd number of\n // `alternate` passes). A looped command carries every pass's span, so a seek into the fourth repetition lands in it.\n const loop = loopRepeats(spec.loop) ? spec.loop : undefined;\n const repeat = (made: Command<Record<string, unknown>> | void) =>\n (made && loop ? loopCommand(made, loop, this._unlimitedFill(spec.at)) : made);\n\n if (entry.scope === \"variable\") {\n const variable = spec.targetId === null ? undefined : this._vars.get(spec.targetId);\n if (!variable) {\n throw new Error(\n `Command ${spec.id} (\"${spec.type}\") targets variable \"${spec.targetId}\", ` +\n `which this document does not declare.`,\n );\n }\n this._assertNoExpressions(spec);\n const { factory } = entry;\n const held = holdsWhenFinished(commandTraits(this._registry, spec, undefined), spec);\n const command = observeSlots(recorder, () =>\n buildToEnd(() => repeat(heldIf(held, factory(variable.target, spec.args, duration, easing)))));\n return { spec, start: spec.at, holdFrom: spec.at, entrance: false, duration: loop ? command.duration : duration, command, writes: recorder.writes, reads: readsOf(command, recorder, [variable.cell]), readsLayout: recorder.readsLayout, owner: variable };\n }\n\n const target = this._targetOrThrow(spec);\n // `to` and `set` carry a props diff, so a renamed prop is renamed there too.\n const given = PROP_DIFF_COMMANDS.has(spec.type)\n ? migrateNodeProps(this._registry, target.entry.spec.type, spec.args).props\n : spec.args;\n const args = entry.binds ? this._bindArgs(given) : (this._assertNoExpressions(spec), given);\n const { factory } = entry;\n const held = holdsWhenFinished(commandTraits(this._registry, spec, target.entry.spec), spec);\n const command = observeSlots(recorder, () =>\n buildToEnd(() => repeat(heldIf(held, factory(target.node, args, duration, easing)))));\n const entrance = entry.scope === \"node\" && this._registry.node(target.entry.spec.type)?.commands.get(spec.type)?.entrance === true;\n return { spec, start: spec.at, holdFrom: spec.at, entrance, duration: loop ? command.duration : duration, command, writes: recorder.writes, reads: readsOf(command, recorder, (target.node as unknown as ReactiveHost).__cells?.slots.values() ?? []), readsLayout: recorder.readsLayout, owner: target.entry };\n }\n\n /**\n * Hold each entrance's first frame back from its `at` so its node never shows at rest ahead of it: back to the\n * later of the target's arrival and the latest end of an earlier command writing a slot it writes. A command\n * writing other slots on the same node (a `moveTo` while it waits) does not stop it.\n */\n private _holdEntrances(): void {\n const ended = new Map<PropSlot<unknown>, number>();\n let byId: Map<string, NodeSpec> | undefined;\n for (const placed of this._placed) {\n placed.holdFrom = placed.start;\n if (placed.entrance) {\n const id = placed.owner.spec.id;\n byId ??= new Map(this._specs.map((s) => [s.id, s]));\n let from = id === ROOT_NODE_ID ? 0 : effectiveSpanIn(byId, id)?.start ?? placed.start;\n for (const slot of placed.writes) from = Math.max(from, ended.get(slot) ?? -Infinity);\n if (from < placed.start) placed.holdFrom = Math.max(0, from);\n }\n const end = placed.start + placed.duration;\n for (const slot of placed.writes) {\n if (!(end <= (ended.get(slot) ?? -Infinity))) ended.set(slot, end);\n }\n }\n }\n\n /** `documentDuration` counts one pass of an unlimited loop: a lone spinner is one turn, in a ten-second scene it turns for ten. */\n private _unlimitedFill(at: number): number {\n return Math.max(0, this._duration - at);\n }\n\n /**\n * Put everything a command writes into the restore lists. A command is not confined to its target\n * (`Cursor.click` throws a control), and an unrestored node would hold the last evaluation's value, making a\n * frame depend on how the playhead got there. A slot on a part a node built has no row, so it is restored on\n * its own to the state {@link _notePartWrite} saw.\n */\n private _touch(placed: PlacedCommand, touched: Set<TouchedOwner>): void {\n this._touchOwner(placed.owner, touched);\n for (const slot of placed.writes) {\n const host = slot._host;\n if (host === null) continue;\n const entry = host.id === ROOT_NODE_ID ? this._root : this._live.get(host.id);\n if (entry) {\n this._touchOwner(entry, touched);\n } else if (this._partBaselines.has(slot) && !touched.has(slot)) {\n touched.add(slot);\n this._animatedParts.push(slot);\n }\n }\n }\n\n private _touchOwner(owner: LiveNode | LiveVariable, touched: Set<TouchedOwner>): void {\n if (touched.has(owner)) return;\n touched.add(owner);\n if (\"cell\" in owner) this._animatedVars.push(owner);\n else this._animated.push(owner);\n }\n\n /**\n * Save a part's slot the first time a command is about to write it. Called before the write lands, while a\n * command is built: earlier commands have run to their end but none wrote this slot, so it holds what the\n * part was built with.\n */\n private readonly _notePartWrite = (slot: PropSlot<unknown>): void => {\n const host = slot._host;\n if (host === null || this._partBaselines.has(slot)) return;\n if (host.id === ROOT_NODE_ID || this._live.has(host.id)) return;\n this._partBaselines.set(slot, slot.snapshot());\n };\n\n /** A command declaring `binds` has args that are a props diff reaching `node.set()`, where a function is a binding. */\n private _bindArgs(args: Record<string, unknown>): Record<string, unknown> {\n const { literal, bindings } = expressionOps.bindProps(args, this._resolveVariable, \"args\");\n return { ...literal, ...bindings };\n }\n\n /**\n * A tween's destination is a value read once at compile, so an expression there could only mean its build-time\n * value. Fail rather than coerce, as `NodeSpec.type` does.\n */\n private _assertNoExpressions(spec: CommandSpec): void {\n const found = expressionOps.collect(spec.args, \"args\");\n if (found.length === 0) return;\n const { path, source } = found[0];\n throw new Error(\n `Command ${spec.id} (\"${spec.type}\") carries an expression at ${path}: ${JSON.stringify(source)}. ` +\n `Expressions bind a prop to a variable; they are not tween destinations. ` +\n `Bind the prop where the node is authored (or with a \"set\" command) and animate the variable ` +\n `with \"variableTo\" instead.`,\n );\n }\n\n private _skip(spec: CommandSpec, message: string, type: string): null {\n this._skipped.set(spec.id, {\n code: \"unknown-command\",\n commandId: spec.id,\n ...(spec.targetId !== null && { nodeId: spec.targetId }),\n type,\n message,\n });\n return null;\n }\n\n /**\n * The tree a placeholder for `spec` belongs to: its children's, else the one\n * its parent holds — a viewport holding two trees gives the one it adds.\n */\n private _placeholderDimension(spec: NodeSpec, rows: readonly NodeSpec[]): NodeDimension {\n const byId = new Map(rows.map((row) => [row.id, row]));\n const seen = new Set<string>();\n const of = (row: NodeSpec): NodeDimension => {\n seen.add(row.id);\n for (const child of rows) {\n if (child.parentId !== row.id) continue;\n const dimension = this._registry.describe(child.type)?.dimension;\n if (dimension) return dimension;\n }\n const parent = row.parentId === null ? undefined : byId.get(row.parentId);\n if (!parent) return \"2d\";\n const described = this._registry.describe(parent.type);\n if (!described) return seen.has(parent.id) ? \"2d\" : of(parent);\n const holds = (described.holds ?? []).filter((d) => d !== \"audio\");\n if (holds.length === 0) return described.holds?.includes(\"audio\") ? \"audio\" : described.dimension ?? \"2d\";\n return holds.find((d) => d !== described.dimension) ?? holds[0];\n };\n return of(spec);\n }\n\n /** The live node a node-scoped command targets; one error, naming the `targetId`, when no row has it. */\n private _targetOrThrow(spec: CommandSpec): { id: string; node: Node; entry: LiveNode } {\n const target = this._targetOf(spec);\n if (!target) {\n throw new Error(\n `Command ${spec.id} (\"${spec.type}\") targets node \"${spec.targetId}\", ` +\n `which this document does not declare.`,\n );\n }\n return target;\n }\n\n private _targetOf(spec: CommandSpec): { id: string; node: Node; entry: LiveNode } | null {\n if (spec.targetId === null) {\n return this._root ? { id: ROOT_NODE_ID, node: this._root.node, entry: this._root } : null;\n }\n const entry = this._live.get(spec.targetId);\n return entry ? { id: spec.targetId, node: entry.node, entry } : null;\n }\n\n private _evaluateObserved(seconds: number, onWrite: (index: number, slot: PropSlot<unknown>) => void): void {\n let index = 0;\n const observer: SlotObserver = { read: () => { }, write: (slot) => onWrite(index, slot) };\n observeSlots(observer, () => {\n for (; index < this._placed.length; index++) {\n const placed = this._placed[index];\n if (seconds < placed.holdFrom) continue;\n const local = seconds < placed.start ? 0 : placed.duration > 0 ? (seconds - placed.start) / placed.duration : 1;\n placed.command.at(clamp01(local));\n }\n });\n }\n\n /**\n * Mark the steps that open a presence window needing a settle: a window is\n * the run of steps between two changes to the tree, and it needs one only\n * when a step in it reads layout.\n *\n * At the window's start rather than just before its first reader, because a\n * reader must see the boxes as they stood when the window opened — a size tween\n * built earlier in the same window has already run to its end by then, and a\n * settle after it would hand the reader that end state instead.\n */\n private _settleWindows(steps: readonly { at: number }[], reads: (index: number) => boolean): Uint8Array {\n const index = this._presenceIndex();\n const settles = new Uint8Array(steps.length);\n // -1 is the window the tree was already laid out for.\n let opener = -1;\n let previous = index.time;\n for (let i = 0; i < steps.length; i++) {\n const { at } = steps[i];\n if (index.differs(previous, at)) opener = i;\n previous = at;\n if (opener < 0 || settles[opener]) continue;\n if (reads(i)) settles[opener] = 1;\n }\n return settles;\n }\n\n private _readsLayout(spec: CommandSpec, refBound: ReadonlySet<string>): boolean {\n const id = spec.targetId ?? ROOT_NODE_ID;\n const target = spec.targetId === null ? this._rootSpec : this._live.get(spec.targetId)?.spec;\n const traits = commandTraits(this._registry, spec, target);\n return traits === null || traits.readsLayout || refBound.has(id);\n }\n\n /**\n * Targets of a binding command carrying a node reference: a binding a `set`\n * installs mid-scene can read another node's box, and a `from` taken over it\n * later evaluates it.\n */\n private _refBound(commands: readonly CommandSpec[]): Set<string> {\n const out = new Set<string>();\n for (const spec of commands) {\n const entry = this._registry.command(spec.type);\n if (entry?.scope === \"node\" && entry.binds && hasNodeRef(spec.args)) out.add(spec.targetId ?? ROOT_NODE_ID);\n }\n return out;\n }\n\n private _presenceIndex(): PresenceIndex {\n return this._presence ??= new PresenceIndex(this._specs, this._spans);\n }\n\n private _parentNodeOf(spec: NodeSpec): Node | undefined {\n if (spec.parentId === null) return this.canvas;\n return this._live.get(spec.parentId)?.node;\n }\n\n private _patchEnvironment(): PatchEnvironment {\n const registry = this._registry;\n return {\n traits: (spec, target) => commandTraits(registry, spec, target),\n nodeRefs: (spec, target) => commandNodeRefs(registry, spec, target),\n isContextProvider: (type) => isContextProvider(registry, type),\n isLayoutNeutralProp: (type, key) => isLayoutNeutralProp(registry, type, key),\n writesInPlace: (row, key) => writesPlacementInPlace(registry, row, key),\n ctorOf: (id) => {\n const node = this._live.get(id)?.node;\n return node && missingNodeOf(node) ? MISSING_TYPE : node?.constructor;\n },\n registeredCtor: (type) => registry.node(type)?.ctor ?? (registry.strict ? undefined : MISSING_TYPE),\n dimensionOf: (type) => registry.node(type)?.descriptor.dimension,\n };\n }\n\n private _writeInPlace(entry: LiveNode, was: NodeSpec): void {\n const changed: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(entry.spec.props)) {\n if (!jsonEqual(was.props[key], value)) changed[key] = value;\n }\n resetToInitial(entry);\n const { literal, bindings } = expressionOps.bindProps(changed, this._resolveVariable);\n entry.node.set({ ...literal, ...bindings } as never);\n captureInitial(entry);\n }\n\n private _updateVariables(patch: TimelinePatch): void {\n const { added, removed, changed } = patch.diff.variables;\n for (const id of removed) this._vars.delete(id);\n for (const id of added) this._vars.set(id, this._liveVariable(patch.next.variables.get(id)!));\n for (const id of changed) {\n const spec = patch.next.variables.get(id)!;\n const entry = this._vars.get(id);\n if (!entry) {\n this._vars.set(id, this._liveVariable(spec));\n continue;\n }\n entry.baseline = spec.value;\n entry.target = this._variableTarget(spec, entry.cell);\n }\n for (const spec of patch.next.variables.values()) {\n const entry = this._vars.get(spec.id);\n if (entry) entry.spec = spec;\n }\n // Restoring only resets animated variables, so a changed value nothing animates would never land.\n for (const id of patch.dirtyVariables) {\n const entry = this._vars.get(id);\n if (entry) entry.cell.set(entry.baseline);\n }\n }\n\n /**\n * Take detached rows out of the tree, replace and add instances, swap in the\n * next document's rows, and re-insert whatever is present at 0. Returns the\n * entries holding a new instance.\n */\n private _updateStructure(patch: TimelinePatch): Set<LiveNode> {\n const { next } = patch;\n\n for (const id of patch.detach) {\n const entry = this._live.get(id);\n if (!entry) continue;\n entry.node.parent?.remove(entry.node);\n entry.presence.set(false);\n this._present.delete(id);\n }\n\n const isDocumentNode = (node: Node) => this._live.get(node.id)?.node === node;\n for (const id of patch.removed) {\n const entry = this._live.get(id);\n if (!entry) continue;\n disposeBuilt(entry.node, isDocumentNode);\n this._live.delete(id);\n this._baseChildCount.delete(id);\n this._baselined.delete(id);\n this._unmounted.delete(id);\n }\n for (const id of patch.reinstantiate) {\n const entry = this._live.get(id);\n if (entry) disposeBuilt(entry.node, isDocumentNode);\n }\n\n const { root, rest } = splitRoot(next.doc.nodes);\n const fresh = new Set<LiveNode>();\n for (const spec of rest) {\n let entry = this._live.get(spec.id);\n if (entry && !patch.reinstantiate.has(spec.id)) {\n entry.spec = spec;\n continue;\n }\n const node = this._instantiate(spec, rest);\n if (entry) {\n entry.spec = spec;\n entry.node = node;\n this._baselined.delete(spec.id);\n this._unmounted.delete(spec.id);\n } else {\n entry = {\n spec,\n node,\n initial: NO_LAYER,\n initialStackDepth: 0,\n baseline: NO_LAYER,\n baseStackDepth: 0,\n presence: new PropSlot<boolean>(false, null, PRESENCE_PREFIX + spec.id),\n };\n this._live.set(spec.id, entry);\n }\n this._baseChildCount.set(spec.id, node._allChildren.length);\n fresh.add(entry);\n }\n\n this._doc = next.doc;\n this._docIndex = next;\n this._rootSpec = root;\n this._root!.spec = root;\n this._specs = rest;\n this._varSpecs = next.doc.variables ?? [];\n this._spans = presenceOf(next.doc);\n this._duration = documentDuration(next.doc);\n\n // A fresh index knows nothing is in the tree, so seed it with what still is.\n const index = this._presence = new PresenceIndex(this._specs, this._spans);\n for (const id of [...this._present]) {\n const row = index.row(id);\n if (row && within(row, 0)) {\n row.siblings.add(row.slot, 1);\n continue;\n }\n this._present.delete(id);\n const entry = this._live.get(id);\n if (!entry) continue;\n entry.presence.set(false);\n entry.node.parent?.remove(entry.node);\n }\n this.syncPresence(0);\n return fresh;\n }\n\n /**\n * Rebuild the dirty chains in the next document's timeline order, replaying the\n * clean chains they build against and taking arrival baselines where compile\n * would have. Returns the rebuilt commands by id.\n */\n private _walkPatch(\n patch: TimelinePatch,\n previous: ReadonlyMap<string, PlacedCommand>,\n settle: () => void,\n ): Map<string, PlacedCommand> {\n const rebuilt = new Map<string, PlacedCommand>();\n if (isStillDocument(this._doc)) return rebuilt;\n\n const { next } = patch;\n const dirty = (id: string) => patch.dirtyNodes.has(id) || patch.dirtyVariables.has(id);\n const refBound = this._refBound(next.ordered);\n let replay = patch.replay;\n // A settle for a binding over another node's box has to see every chain at its `at`.\n if (replay !== \"all\" && [...refBound].some(dirty)) replay = \"all\";\n\n const steps: WalkStep[] = [];\n const { captures } = patch;\n let c = 0;\n for (const spec of next.ordered) {\n while (c < captures.length && captures[c].at <= spec.at) steps.push({ at: captures[c].at, capture: captures[c++].id });\n const id = next.targetOf(spec);\n if (replay === \"all\" || dirty(id) || replay.has(id)) steps.push({ at: spec.at, spec });\n }\n for (; c < captures.length; c++) steps.push({ at: captures[c].at, capture: captures[c].id });\n\n const settles = this._settleWindows(steps, (i) => {\n const spec = steps[i].spec;\n return spec !== undefined && dirty(next.targetOf(spec)) && this._readsLayout(spec, refBound);\n });\n\n let pending = false;\n for (let i = 0; i < steps.length; i++) {\n const step = steps[i];\n if (settles[i]) pending = true;\n if (this.syncPresence(step.at)) this._baselineMounted();\n if (step.capture !== undefined) {\n this._baselined.delete(step.capture);\n this._baselineArrival(step.capture);\n continue;\n }\n // After this `at`'s captures, as compile baselines arrivals before it settles.\n if (pending) {\n settle();\n pending = false;\n }\n const spec = step.spec!;\n const old = previous.get(spec.id);\n if (old && !dirty(next.targetOf(spec))) {\n old.command.at(1);\n continue;\n }\n const placed = this._buildPlaced(spec);\n if (placed) rebuilt.set(spec.id, placed);\n }\n return rebuilt;\n }\n}\n\n/** A document written before nodes carried spans would otherwise get a \"no command\" error naming nothing fixable. */\nconst LEGACY_COMMAND_HINTS: Readonly<Record<string, string>> = {\n add: \"A node is a row in `nodes`, entering at its `startAt`.\",\n remove: \"A node leaves at its `endAt`.\",\n variable: \"A variable is declared in `variables`.\",\n};\n\nconst NO_LAYER: PropLayer = new Map();\n\nconst PROP_DIFF_COMMANDS: ReadonlySet<string> = new Set([\"to\", \"set\"]);\n\ntype TouchedOwner = LiveNode | LiveVariable | PropSlot<unknown>;\n\nclass WriteRecorder implements SlotObserver {\n readonly writes = new Set<PropSlot<unknown>>();\n readonly reads = new Set<PropSlot<unknown>>();\n readsLayout = false;\n\n /** `firstWrite` runs the first time a slot is written, before the write lands. */\n constructor(private readonly firstWrite: (slot: PropSlot<unknown>) => void) { }\n\n read(slot: PropSlot<unknown>): void {\n if (slot._name === LAYOUT_SLOT) this.readsLayout = true;\n this.reads.add(slot);\n }\n\n write(slot: PropSlot<unknown>): void {\n if (this.writes.has(slot)) return;\n this.firstWrite(slot);\n this.writes.add(slot);\n }\n}\n\n/**\n * Build a command and run it to its end. A factory that acts at once and returns\n * nothing (`restore` with no duration) has already done this build's `at(1)`, so\n * it becomes a stamp that acts again on every later evaluation.\n */\nfunction buildToEnd(make: () => Command<Record<string, unknown>> | void): Command<Record<string, unknown>> {\n const made = make();\n if (made) {\n made.at(1);\n return made;\n }\n return driveCommand(0, () => {\n make();\n }) as unknown as Command<Record<string, unknown>>;\n}\n\n/**\n * Snapshot a node's prop slots at its authored state. Taken while it is mounted:\n * an unmounted node's cells hold pre-attach values.\n */\nfunction captureBaseline(entry: LiveNode): void {\n const host = entry.node as unknown as ReactiveHost;\n entry.baseline = captureLayer(host);\n entry.baseStackDepth = host._stateStack.length;\n}\n\ninterface SlotBaseline {\n slot: PropSlot<unknown>;\n baseline: PropSnapshot<unknown>;\n}\n\nfunction slotBaselines(entry: LiveNode, slots: ReadonlySet<PropSlot<unknown>> | undefined): SlotBaseline[] | null {\n if (!slots) return [];\n const cells = (entry.node as unknown as ReactiveHost).__cells?.slots;\n if (!cells) return null;\n const out: SlotBaseline[] = [];\n for (const [key, slot] of cells) {\n const baseline = slots.has(slot) ? entry.baseline.get(key) : undefined;\n if (baseline) out.push({ slot, baseline });\n }\n return out.length === slots.size ? out : null;\n}\n\nfunction captureInitial(entry: LiveNode): void {\n captureBaseline(entry);\n entry.initial = entry.baseline;\n entry.initialStackDepth = entry.baseStackDepth;\n}\n\nfunction resetToInitial(entry: LiveNode): void {\n const host = entry.node as unknown as ReactiveHost;\n applySnapshotLayer(host, entry.initial);\n if (host._stateStack.length > entry.initialStackDepth) host._stateStack.length = entry.initialStackDepth;\n entry.baseline = entry.initial;\n entry.baseStackDepth = entry.initialStackDepth;\n}\n\n/** Dispose `node` and whatever it built for itself; a document child it still holds is left alone. */\nfunction disposeBuilt(node: Node, isDocumentNode: (node: Node) => boolean): void {\n for (const child of node._allChildren) {\n if (!isDocumentNode(child)) disposeBuilt(child, isDocumentNode);\n }\n node.dispose();\n}\n\ninterface PresenceRow {\n id: string;\n start: number;\n end: number;\n order: number;\n slot: number;\n siblings: SiblingCounts;\n pass: number;\n}\n\nfunction within(row: PresenceRow, seconds: number): boolean {\n return seconds >= row.start && seconds < row.end;\n}\n\nfunction byDocumentOrder(a: PresenceRow, b: PresenceRow): number {\n return a.order - b.order;\n}\n\n/**\n * How many of one parent's document children are present before a given slot — a\n * Fenwick tree, so an insert index costs O(log siblings) rather than a walk over\n * every sibling.\n */\nclass SiblingCounts {\n constructor(readonly parentId: string, size: number) {\n this._tree = new Int32Array(size + 1);\n }\n\n add(slot: number, delta: number): void {\n for (let i = slot + 1; i < this._tree.length; i += i & -i) this._tree[i] += delta;\n }\n\n before(slot: number): number {\n let count = 0;\n for (let i = slot; i > 0; i -= i & -i) count += this._tree[i];\n return count;\n }\n\n private readonly _tree: Int32Array;\n}\n\n/** Every span boundary sorted by time, with a cursor at the last time synced: a move visits only rows with a boundary between, however far. */\nclass PresenceIndex {\n time = -Infinity;\n\n constructor(specs: readonly NodeSpec[], spans: ReadonlyMap<string, NodeSpan>) {\n const byParent = new Map<string, { spec: NodeSpec; order: number }[]>();\n specs.forEach((spec, order) => {\n if (!spans.has(spec.id)) return;\n const parentId = spec.parentId ?? ROOT_NODE_ID;\n const group = byParent.get(parentId);\n if (group) group.push({ spec, order });\n else byParent.set(parentId, [{ spec, order }]);\n });\n for (const [parentId, group] of byParent) {\n // Stable, so a `layerOrder` tie keeps document order.\n group.sort((a, b) => a.spec.layerOrder - b.spec.layerOrder);\n const siblings = new SiblingCounts(parentId, group.length);\n group.forEach(({ spec, order }, slot) => {\n const { start, end } = spans.get(spec.id)!;\n const row: PresenceRow = { id: spec.id, start, end, order, slot, siblings, pass: 0 };\n this._rows.set(spec.id, row);\n this._events.push({ time: start, row });\n if (Number.isFinite(end)) this._events.push({ time: end, row });\n });\n }\n this._events.sort((a, b) => a.time - b.time);\n }\n\n /** Each row with a boundary between the last time synced and `seconds`, once. Moves the cursor. */\n crossed(seconds: number): readonly PresenceRow[] {\n this.time = seconds;\n const target = this._upperBound(seconds);\n if (target === this._cursor) return NO_ROWS;\n const from = Math.min(target, this._cursor);\n const to = Math.max(target, this._cursor);\n this._cursor = target;\n const pass = ++this._pass;\n const rows: PresenceRow[] = [];\n for (let k = from; k < to; k++) {\n const { row } = this._events[k];\n if (row.pass === pass) continue;\n row.pass = pass;\n rows.push(row);\n }\n return rows;\n }\n\n /** Whether any row is present at one of `a`, `b` and not the other. Moves nothing. */\n differs(a: number, b: number): boolean {\n const from = this._upperBound(Math.min(a, b));\n const to = this._upperBound(Math.max(a, b));\n for (let k = from; k < to; k++) {\n const { row } = this._events[k];\n if (within(row, a) !== within(row, b)) return true;\n }\n return false;\n }\n\n row(id: string): PresenceRow | undefined {\n return this._rows.get(id);\n }\n\n private readonly _events: { time: number; row: PresenceRow }[] = [];\n private readonly _rows = new Map<string, PresenceRow>();\n private _cursor = 0;\n private _pass = 0;\n\n private _upperBound(seconds: number): number {\n let lo = 0;\n let hi = this._events.length;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if (this._events[mid].time <= seconds) lo = mid + 1;\n else hi = mid;\n }\n return lo;\n }\n}\n\nconst NO_ROWS: readonly PresenceRow[] = [];\n", "import type { ResolvedTextSpan, TextAlign } from \"@/attributes/text/types\";\nimport { ShapeAlignmentInput, ShapeState, resolveShapeAlignment, resolveShapePivot, stripShapeAlignmentKeys } from \"./shape\";\n\nexport interface RichTextState extends ShapeState {\n spans: ResolvedTextSpan[];\n /** A named typography preset — see {@link TextState.variant}. Applied per span. */\n variant?: string;\n lineHeight: number;\n textAlign: TextAlign;\n width: number;\n height: number;\n}\n\nexport function withRichTextDescriptor(descriptor: Partial<RichTextState> & ShapeAlignmentInput): RichTextState {\n const width = descriptor.width ?? 0;\n const height = descriptor.height ?? 0;\n const { x, y, pivot } = resolveShapeAlignment(descriptor, width, height);\n return {\n ...stripShapeAlignmentKeys(descriptor),\n rotation: descriptor.rotation ?? 0,\n scale: descriptor.scale ?? 1,\n x,\n y,\n start: descriptor.start ?? 0,\n end: descriptor.end ?? 1,\n pivot: resolveShapePivot(pivot),\n spans: descriptor.spans ?? [],\n lineHeight: descriptor.lineHeight ?? 1.2,\n textAlign: descriptor.textAlign ?? 'center',\n width,\n height,\n };\n}\n", "import { ShapeState, resolveShapePivot } from \"./shape\";\n\nexport type PathCommand =\n | { type: \"M\"; x: number; y: number }\n | { type: \"m\"; x: number; y: number }\n | { type: \"L\"; x: number; y: number }\n | { type: \"l\"; x: number; y: number }\n | { type: \"H\"; x: number }\n | { type: \"h\"; x: number }\n | { type: \"V\"; y: number }\n | { type: \"v\"; y: number }\n | { type: \"C\"; x1: number; y1: number; x2: number; y2: number; x: number; y: number }\n | { type: \"c\"; x1: number; y1: number; x2: number; y2: number; x: number; y: number }\n | { type: \"S\"; x2: number; y2: number; x: number; y: number }\n | { type: \"s\"; x2: number; y2: number; x: number; y: number }\n | { type: \"Q\"; x1: number; y1: number; x: number; y: number }\n | { type: \"q\"; x1: number; y1: number; x: number; y: number }\n | { type: \"T\"; x: number; y: number }\n | { type: \"t\"; x: number; y: number }\n | { type: \"A\"; rx: number; ry: number; rotation: number; largeArc: 0 | 1; sweep: 0 | 1; x: number; y: number }\n | { type: \"a\"; rx: number; ry: number; rotation: number; largeArc: 0 | 1; sweep: 0 | 1; x: number; y: number }\n | { type: \"Z\" | \"z\" };\n\n\n\nexport type PathData = string | PathCommand[];\n\nexport function toPathString(d: PathData): string {\n if (typeof d === \"string\") return d;\n return d.map(cmd => {\n switch (cmd.type) {\n case \"M\": case \"m\": return `${cmd.type} ${cmd.x} ${cmd.y}`;\n case \"L\": case \"l\": return `${cmd.type} ${cmd.x} ${cmd.y}`;\n case \"T\": case \"t\": return `${cmd.type} ${cmd.x} ${cmd.y}`;\n case \"H\": case \"h\": return `${cmd.type} ${cmd.x}`;\n case \"V\": case \"v\": return `${cmd.type} ${cmd.y}`;\n case \"C\": case \"c\": return `${cmd.type} ${cmd.x1} ${cmd.y1} ${cmd.x2} ${cmd.y2} ${cmd.x} ${cmd.y}`;\n case \"S\": case \"s\": return `${cmd.type} ${cmd.x2} ${cmd.y2} ${cmd.x} ${cmd.y}`;\n case \"Q\": case \"q\": return `${cmd.type} ${cmd.x1} ${cmd.y1} ${cmd.x} ${cmd.y}`;\n case \"A\": case \"a\": return `${cmd.type} ${cmd.rx} ${cmd.ry} ${cmd.rotation} ${cmd.largeArc} ${cmd.sweep} ${cmd.x} ${cmd.y}`;\n case \"Z\": case \"z\": return cmd.type;\n }\n }).join(\" \");\n}\n\n/** An axis-aligned bounding box in path coordinates: [minX, minY, maxX, maxY]. */\nexport type PathBounds = readonly [number, number, number, number];\n\nexport interface PathState extends ShapeState {\n data: PathData;\n /** Explicit frame to centre the path against, as [minX, minY, maxX, maxY] in the path's own space; its centre lands on the local origin instead of the path's own bbox centre. For paths sharing one layout frame (per-glyph LaTeX tokens): the same whole-shape bounds on each keeps the relative positions that self-centring would collapse. */\n centerBounds?: PathBounds;\n}\n\nexport function withPathDescriptor(descriptor: Partial<PathState>): PathState {\n return {\n\n rotation: descriptor.rotation ?? 0,\n scale: descriptor.scale ?? 1,\n x: descriptor.x ?? 0,\n y: descriptor.y ?? 0,\n start: descriptor.start ?? 0,\n end: descriptor.end ?? 1,\n width: descriptor.width ?? 0,\n height: descriptor.height ?? 0,\n pivot: resolveShapePivot(descriptor.pivot),\n\n data: descriptor.data ?? \"\",\n centerBounds: descriptor.centerBounds,\n };\n}\n", "import type { TextState } from \"./descriptors/text\";\n\n/**\n * Where a laid-out run of text put its characters: what an editor needs to draw its own caret and selection over\n * rendered glyphs. **Space**: block-local canvas pixels, origin at the block's centre, **y down**, before the node's\n * transform (what the backend shapes into at origin `(0, 0)`); {@link nodeTextLayout} lifts it to viewport space.\n * **Carets, not glyph boxes**: a cursor lives between characters, so n characters have n + 1 positions, and a list of\n * glyph boxes leaves the run's start and end implicit and forces the host to reason about advances, kerning and\n * trailing whitespace.\n */\n\n/** One laid-out line of a text block. */\nexport interface TextBlockLine {\n /** Character range this line covers, `[start, end)`, as offsets into the block's whole string; a hard line break belongs to neither line. */\n start: number;\n end: number;\n /** Top and bottom of the line box, block-local. */\n top: number;\n bottom: number;\n /** The x of every caret slot, block-local, in offset order: `carets[i]` is the slot at character `start + i`, so there are `end - start + 1` (one before each character plus one after the last). Left-to-right; bidirectional text isn't modelled in v1. */\n carets: number[];\n}\n\n/** A shaped text block: its lines and the size shaping produced. `width`/`height` are the block's own extent (what a hugging node measures to), not the box it may be aligned within. */\nexport interface TextBlockLayout {\n lines: TextBlockLine[];\n width: number;\n height: number;\n}\n\n/** The caret slot count a layout implies (one past the last character). Lines exclude their break, so summing slots would count breaks twice and lose the final position; read it off the last line. */\nexport function caretCount(layout: TextBlockLayout): number {\n const last = layout.lines[layout.lines.length - 1];\n return last ? last.end + 1 : 1;\n}\n\n/** Something that can report where a shaped text block put its characters. Narrower than {@link RenderContext2D}: `nodeTextLayout` needs only this call, and typing against the whole context would make a caret measurement look like it needs a renderer rather than a shaper. */\nexport interface TextBlockSource {\n layoutTextBlock(state: Partial<TextState>): TextBlockLayout | null;\n}\n\n/** Narrows `value` to a {@link TextBlockSource}, or `null` when it can't report glyph positions. A capability check, not a cast: a {@link MeasureContext2D} answers how *wide* text is, but where each character *landed* needs a shaper that keeps line boxes; a host without one should get \"no caret model\", not a crash. */\nexport function asTextBlockSource(value: unknown): TextBlockSource | null {\n return typeof (value as TextBlockSource | null)?.layoutTextBlock === \"function\"\n ? value as TextBlockSource\n : null;\n}\n", "/**\n * What a render issue is about:\n *\n * - `missing`: a feature the backend does not draw (`feature` names it).\n * - `shader`: a user shader that does not compile, or one that is not WGSL (an SkSL shader from an old document).\n * - `params`: a shader's uniforms and its `struct Params` disagree (a value with no member, a member with no value).\n * - `gpu`: a WebGPU validation or out-of-memory error.\n * - `device-lost`: the GPU device was lost; the backend is drawing on a new one.\n * - `crashed`: the backend itself failed and draws nothing more on this page.\n */\nexport type RenderIssueKind = \"missing\" | \"shader\" | \"params\" | \"gpu\" | \"device-lost\" | \"crashed\";\n\n/** Something a frame drew without throwing but not as the document says. */\nexport interface RenderIssue {\n kind: RenderIssueKind;\n message: string;\n /** What is affected, as the backend names it (`blend:color-dodge`, `text:path`, `fill:shader`). */\n feature?: string;\n /** The node it was found on, when the backend knows. */\n nodeId?: string;\n}\n\n/** A backend's issue as a typed one; a bare string is the shader message backends reported before issues were typed. */\nexport function toRenderIssue(issue: RenderIssue | string): RenderIssue {\n return typeof issue === \"string\" ? { kind: \"shader\", message: issue } : issue;\n}\n\n/** One key per kind, feature and node: what an issue list is deduplicated by. */\nexport function renderIssueKey(issue: RenderIssue): string {\n return `${issue.kind}|${issue.feature ?? \"\"}|${issue.nodeId ?? \"\"}|${issue.feature ? \"\" : issue.message}`;\n}\n\n/**\n * The backend lost what it draws with while a render was under way, so the\n * frames already drawn cannot be trusted. Thrown by exports and stills on a\n * `device-lost` or `crashed` issue; `retryable` says whether the same render\n * can simply run again (the backend recovered on a new device).\n */\nexport class RenderBackendError extends Error {\n override readonly name = \"RenderBackendError\";\n readonly retryable: boolean;\n\n constructor(readonly issue: RenderIssue) {\n super(issue.message);\n this.retryable = issue.kind === \"device-lost\";\n }\n}\n\n/** Whether an issue means the frames drawn around it are not to be trusted. */\nexport function isFatalRenderIssue(issue: RenderIssue): boolean {\n return issue.kind === \"device-lost\" || issue.kind === \"crashed\";\n}\n", "import type {\n BoxGeometry3D, BufferGeometry3D, CapsuleGeometry3D, CircleGeometry3D,\n ConeGeometry3D, CylinderGeometry3D, EdgesGeometry3D, ExtrudeGeometry3D,\n Geometry3D, LatheGeometry3D, ModelGeometry3D, ParametricGeometry3D,\n PlaneGeometry3D, PolyhedronGeometry3D, RingGeometry3D, SphereGeometry3D,\n TorusGeometry3D, TorusKnotGeometry3D, TubeGeometry3D, WireframeGeometry3D,\n} from \"./geometry\";\nimport type {\n BasicMaterial3D, DepthMaterial3D, LambertMaterial3D, LineBasicMaterial3D,\n LineDashedMaterial3D, MatcapMaterial3D, NormalMaterial3D, PhongMaterial3D,\n PhysicalMaterial3D, PointsMaterial3D, ShaderMaterial3D, ShadowMaterial3D,\n SpriteMaterial3D, StandardMaterial3D, ToonMaterial3D,\n} from \"./material\";\nimport type { DataTexture3D, ImageTexture3D, SurfaceSource3D, SurfaceTexture3D, TextureOptions3D } from \"./texture\";\n\n/** A descriptor's own params, with the `type` discriminant removed. */\ntype ParamsOf<T> = Omit<T, \"type\">;\n\n/**\n * Geometry descriptors: plain values, so hoist one and share it across meshes; the renderer dedupes by identity,\n * uploading a shared geometry to the GPU once.\n *\n * const brick = Geo.box({ width: 1, height: 0.5, depth: 0.5 });\n * g.mesh(brick, red, { position: [0, 0, 0] })\n * .mesh(brick, red, { position: [1, 0, 0] }); // same GPU buffer\n */\nexport const Geo = {\n box: (o?: ParamsOf<BoxGeometry3D>): BoxGeometry3D => ({ type: \"box\", ...o }),\n sphere: (o?: ParamsOf<SphereGeometry3D>): SphereGeometry3D => ({ type: \"sphere\", ...o }),\n plane: (o?: ParamsOf<PlaneGeometry3D>): PlaneGeometry3D => ({ type: \"plane\", ...o }),\n cylinder: (o?: ParamsOf<CylinderGeometry3D>): CylinderGeometry3D => ({ type: \"cylinder\", ...o }),\n cone: (o?: ParamsOf<ConeGeometry3D>): ConeGeometry3D => ({ type: \"cone\", ...o }),\n torus: (o?: ParamsOf<TorusGeometry3D>): TorusGeometry3D => ({ type: \"torus\", ...o }),\n torusKnot: (o?: ParamsOf<TorusKnotGeometry3D>): TorusKnotGeometry3D => ({ type: \"torusKnot\", ...o }),\n circle: (o?: ParamsOf<CircleGeometry3D>): CircleGeometry3D => ({ type: \"circle\", ...o }),\n ring: (o?: ParamsOf<RingGeometry3D>): RingGeometry3D => ({ type: \"ring\", ...o }),\n capsule: (o?: ParamsOf<CapsuleGeometry3D>): CapsuleGeometry3D => ({ type: \"capsule\", ...o }),\n\n tetrahedron: (o?: Omit<ParamsOf<PolyhedronGeometry3D>, \"shape\">): PolyhedronGeometry3D =>\n ({ type: \"polyhedron\", shape: \"tetrahedron\", ...o }),\n octahedron: (o?: Omit<ParamsOf<PolyhedronGeometry3D>, \"shape\">): PolyhedronGeometry3D =>\n ({ type: \"polyhedron\", shape: \"octahedron\", ...o }),\n icosahedron: (o?: Omit<ParamsOf<PolyhedronGeometry3D>, \"shape\">): PolyhedronGeometry3D =>\n ({ type: \"polyhedron\", shape: \"icosahedron\", ...o }),\n dodecahedron: (o?: Omit<ParamsOf<PolyhedronGeometry3D>, \"shape\">): PolyhedronGeometry3D =>\n ({ type: \"polyhedron\", shape: \"dodecahedron\", ...o }),\n\n extrude: (o: ParamsOf<ExtrudeGeometry3D>): ExtrudeGeometry3D => ({ type: \"extrude\", ...o }),\n lathe: (o: ParamsOf<LatheGeometry3D>): LatheGeometry3D => ({ type: \"lathe\", ...o }),\n tube: (o: ParamsOf<TubeGeometry3D>): TubeGeometry3D => ({ type: \"tube\", ...o }),\n\n /** Raw vertex buffers — any mesh you can compute. */\n buffer: (o: ParamsOf<BufferGeometry3D>): BufferGeometry3D => ({ type: \"buffer\", ...o }),\n /** A surface sampled over a `[0,1]²` grid. Sugar over {@link Geo.buffer}. */\n parametric: (o: ParamsOf<ParametricGeometry3D>): ParametricGeometry3D => ({ type: \"parametric\", ...o }),\n\n /** The hard edges of another geometry — a clean outline, no triangulation diagonals. */\n edges: (source: Geometry3D, o?: Omit<ParamsOf<EdgesGeometry3D>, \"source\">): EdgesGeometry3D =>\n ({ type: \"edges\", source, ...o }),\n /** Every triangle edge of another geometry. */\n wireframe: (source: Geometry3D): WireframeGeometry3D => ({ type: \"wireframe\", source }),\n\n model: (src: string, o?: Omit<ParamsOf<ModelGeometry3D>, \"src\">): ModelGeometry3D =>\n ({ type: \"modelGeometry\", src, ...o }),\n} as const;\n\n/** Material descriptors, shareable values: one hoisted material across many meshes compiles one shader program instead of N. Prefer {@link Mat.standard}; {@link Mat.physical} only for clearcoat, transmission, sheen or iridescence (costlier per pixel); {@link Mat.shader} is the escape hatch. */\nexport const Mat = {\n basic: (o?: ParamsOf<BasicMaterial3D>): BasicMaterial3D => ({ type: \"basic\", ...o }),\n standard: (o?: ParamsOf<StandardMaterial3D>): StandardMaterial3D => ({ type: \"standard\", ...o }),\n physical: (o?: ParamsOf<PhysicalMaterial3D>): PhysicalMaterial3D => ({ type: \"physical\", ...o }),\n phong: (o?: ParamsOf<PhongMaterial3D>): PhongMaterial3D => ({ type: \"phong\", ...o }),\n lambert: (o?: ParamsOf<LambertMaterial3D>): LambertMaterial3D => ({ type: \"lambert\", ...o }),\n toon: (o?: ParamsOf<ToonMaterial3D>): ToonMaterial3D => ({ type: \"toon\", ...o }),\n normal: (o?: ParamsOf<NormalMaterial3D>): NormalMaterial3D => ({ type: \"normal\", ...o }),\n depth: (o?: ParamsOf<DepthMaterial3D>): DepthMaterial3D => ({ type: \"depth\", ...o }),\n matcap: (o?: ParamsOf<MatcapMaterial3D>): MatcapMaterial3D => ({ type: \"matcap\", ...o }),\n points: (o?: ParamsOf<PointsMaterial3D>): PointsMaterial3D => ({ type: \"points\", ...o }),\n lineBasic: (o?: ParamsOf<LineBasicMaterial3D>): LineBasicMaterial3D => ({ type: \"lineBasic\", ...o }),\n lineDashed: (o?: ParamsOf<LineDashedMaterial3D>): LineDashedMaterial3D => ({ type: \"lineDashed\", ...o }),\n sprite: (o?: ParamsOf<SpriteMaterial3D>): SpriteMaterial3D => ({ type: \"sprite\", ...o }),\n shadow: (o?: ParamsOf<ShadowMaterial3D>): ShadowMaterial3D => ({ type: \"shadow\", ...o }),\n /** Raw GLSL. Uniform *values* are free to animate; source changes recompile. */\n shader: (o: ParamsOf<ShaderMaterial3D>): ShaderMaterial3D => ({ type: \"shader\", ...o }),\n} as const;\n\n/** Texture descriptors. {@link Tex.image} takes a manifest path loaded through the ordinary image pipeline (pixels resident before the frame draws); a bare string works anywhere a texture is expected, so it is only needed for sampler options. */\nexport const Tex = {\n image: (src: string, o?: TextureOptions3D): ImageTexture3D => ({ src, ...o }),\n /** A texture from raw RGBA8888 bytes — gradient ramps, noise, LUTs. */\n data: (\n data: ArrayLike<number>,\n width: number,\n height: number,\n o?: TextureOptions3D & { revision?: number },\n ): DataTexture3D => ({ data, width, height, ...o }),\n /**\n * A texture painted from Motion Script's own 2D output, the bridge onto 3D geometry. `source` is a **value**: a\n * built `Graphics2D`, or a `Node2D` subtree for real layout, shaped `Text` or a loaded `Image`.\n *\n * const scope = new Graphics2D().line({ points: trace(phase()) }).stroke(…);\n * g3.plane({ fill: scope }); // sized for you\n *\n * const stats = new Rect({ flow: \"vertical\", padding: 48, children: [Text({ text: \"CPU\" })] });\n * g3.plane({ fill: Tex.surface(stats, { width: 1024, height: 640 }) });\n *\n * `width`/`height` are the buffer's resolution, default 512 (a source handed straight to `fill` gets the same\n * defaults, so the builder is only for pinning a resolution or sampler option). **Hoist the source**: see {@link SurfaceTexture3D}.\n */\n surface: (\n source: SurfaceSource3D,\n o?: TextureOptions3D & { width?: number; height?: number; maxPixelRatio?: number },\n ): SurfaceTexture3D => ({\n width: 512,\n height: 512,\n ...o,\n source,\n }),\n} as const;\n", "/** Subdivision counts as one name. three spells this ten ways (`widthSegments`, `radialSegments`, `tubularSegments`, `detail`, ...); every geometry here takes one {@link Segments3D} and documents the per-axis meaning on the shape. A scalar applies to every axis (just raising resolution); a tuple is per-axis in the shape's documented order. */\nexport type Segments3D =\n | number\n | readonly [number]\n | readonly [number, number]\n | readonly [number, number, number];\n\n/** Resolves a {@link Segments3D} against a shape's per-axis defaults: a scalar broadcasts, a tuple fills what it names, `undefined` is all defaults (an unset `segments` never pins a resolution invented at a call site). Floored and clamped to at least 1, since a fractional or zero count reaches three as a degenerate geometry, not an error. */\nexport function segmentsOf(\n value: Segments3D | undefined,\n defaults: readonly number[],\n): number[] {\n if (value === undefined) return defaults.map(clampSegment);\n if (typeof value === \"number\") return defaults.map(() => clampSegment(value));\n return defaults.map((fallback, index) => clampSegment(value[index] ?? fallback));\n}\n\nfunction clampSegment(value: number): number {\n return Math.max(1, Math.floor(value));\n}\n", "import type { BufferGeometry3D } from \"./geometry\";\n\n/**\n * A box with rounded edges and corners, evaluated into vertex buffers. three has no rounded box in core (its\n * `RoundedBoxGeometry` is an addon, and importing addons would defeat the lazy `import(\"three\")` boundary), so it is\n * built here as plain data, backend-agnostic and GPU-free like `evaluateParametric`.\n *\n * The surface is the Minkowski sum of an inner box (each half-extent reduced by `radius`) and a sphere of that\n * radius: 26 patches (6 flat faces, 12 quarter-cylinder edges, 8 spherical-octant corners), each a grid of\n * `core + radius * direction`, where `direction` is also the vertex normal, so lighting is exact.\n */\nexport interface RoundedBoxOptions {\n width: number;\n height: number;\n depth: number;\n radius: number;\n /** Face subdivision per axis, as `[x, y, z]`. */\n segments: readonly [number, number, number];\n}\n\ntype Vec3 = readonly [number, number, number];\n\n/** A patch grid, before it is tessellated into the output buffers. */\ninterface Grid {\n /** Position at grid coordinate `(u, v)`, both in `[0, 1]`. */\n position: (u: number, v: number) => Vec3;\n normal: (u: number, v: number) => Vec3;\n uSteps: number;\n vSteps: number;\n}\n\n/** Arc resolution for the rounded regions, derived from how round the box is rather than exposed: `segments` means face subdivision everywhere else, and a second count would only ever be \"enough to look smooth\", a function of radius relative to the box. */\nfunction arcSegmentsFor(radius: number, maxHalf: number): number {\n if (maxHalf <= 0) return 3;\n return Math.max(3, Math.min(16, Math.round((radius / maxHalf) * 40)));\n}\n\n/** Builds the rounded box's vertex buffers as a plain {@link BufferGeometry3D}, so the renderer's buffer path uploads it and `Geo.edges`/`Geo.wireframe` derive from it. */\nexport function evaluateRoundedBox(options: RoundedBoxOptions): BufferGeometry3D {\n const half: Vec3 = [options.width / 2, options.height / 2, options.depth / 2];\n const maxHalf = Math.max(half[0], half[1], half[2]);\n const radius = Math.max(0, Math.min(options.radius, half[0], half[1], half[2]));\n\n // The inner box the sphere sweeps around; clamped at zero so a radius equal to a half-extent degenerates to a line rather than folding the surface inside out.\n const box: Vec3 = [\n Math.max(0, half[0] - radius),\n Math.max(0, half[1] - radius),\n Math.max(0, half[2] - radius),\n ];\n\n const arc = arcSegmentsFor(radius, maxHalf);\n\n const position: number[] = [];\n const normal: number[] = [];\n const uv: number[] = [];\n const index: number[] = [];\n\n for (const grid of patches(half, box, radius, options.segments, arc)) {\n emit(grid, half, position, normal, uv, index);\n }\n\n return {\n type: \"buffer\",\n position: new Float32Array(position),\n normal: new Float32Array(normal),\n uv: new Float32Array(uv),\n index: new Uint32Array(index),\n staticData: true,\n };\n}\n\n/** The 26 patches, in face then edge then corner order. */\nfunction* patches(\n half: Vec3,\n box: Vec3,\n radius: number,\n segments: readonly [number, number, number],\n arc: number,\n): Generator<Grid> {\n const AXES = [0, 1, 2] as const;\n const SIGNS = [-1, 1] as const;\n\n // 6 faces: flat, spanning the inner box on the two free axes and pinned at the full half-extent on their own; subdivided by `segments` (what a displacement map reads).\n for (const axis of AXES) {\n const u = (axis + 1) % 3;\n const v = (axis + 2) % 3;\n for (const sign of SIGNS) {\n const face = axisVector(axis, sign);\n yield {\n uSteps: segments[u],\n vSteps: segments[v],\n normal: () => face,\n position: (a, b) => {\n const point: number[] = [0, 0, 0];\n point[axis] = sign * half[axis];\n point[u] = lerp(-box[u], box[u], a);\n point[v] = lerp(-box[v], box[v], b);\n return point as unknown as Vec3;\n },\n };\n }\n }\n\n if (radius <= 0) return;\n\n // 12 edges: a quarter cylinder. The direction sweeps 90 degrees in the plane\n // of the two pinned axes while the core slides along the third.\n for (const axis of AXES) {\n const a = (axis + 1) % 3;\n const b = (axis + 2) % 3;\n for (const signA of SIGNS) {\n for (const signB of SIGNS) {\n yield {\n uSteps: arc,\n vSteps: segments[axis],\n normal: (t) => {\n const angle = (t * Math.PI) / 2;\n const dir: number[] = [0, 0, 0];\n dir[a] = signA * Math.cos(angle);\n dir[b] = signB * Math.sin(angle);\n return dir as unknown as Vec3;\n },\n position: (t, s) => {\n const angle = (t * Math.PI) / 2;\n const point: number[] = [0, 0, 0];\n point[a] = signA * (box[a] + radius * Math.cos(angle));\n point[b] = signB * (box[b] + radius * Math.sin(angle));\n point[axis] = lerp(-box[axis], box[axis], s);\n return point as unknown as Vec3;\n },\n };\n }\n }\n }\n\n // 8 corners: a spherical octant around a fixed corner of the inner box.\n for (const signX of SIGNS) {\n for (const signY of SIGNS) {\n for (const signZ of SIGNS) {\n const corner: Vec3 = [signX * box[0], signY * box[1], signZ * box[2]];\n const direction = (u: number, v: number): Vec3 => {\n const polar = (u * Math.PI) / 2;\n const azimuth = (v * Math.PI) / 2;\n return [\n signX * Math.sin(polar) * Math.cos(azimuth),\n signY * Math.cos(polar),\n signZ * Math.sin(polar) * Math.sin(azimuth),\n ];\n };\n yield {\n uSteps: arc,\n vSteps: arc,\n normal: direction,\n position: (u, v) => {\n const dir = direction(u, v);\n return [\n corner[0] + radius * dir[0],\n corner[1] + radius * dir[1],\n corner[2] + radius * dir[2],\n ];\n },\n };\n }\n }\n }\n}\n\n/** Tessellates one patch into the output buffers. Winding is decided per triangle by comparing its normal to the surface normal at that vertex, not by reasoning about sign combinations: 26 patches are 26 chances to get a handedness backwards, and one inverted face on a `faces: \"front\"` mesh is a visible hole. Degenerate triangles (a corner octant's pole, quads of a zero-extent patch) are dropped rather than given an undefined normal. */\nfunction emit(\n grid: Grid,\n half: Vec3,\n position: number[],\n normal: number[],\n uv: number[],\n index: number[],\n): void {\n const base = position.length / 3;\n const uCount = grid.uSteps + 1;\n const vCount = grid.vSteps + 1;\n\n for (let vi = 0; vi < vCount; vi++) {\n for (let ui = 0; ui < uCount; ui++) {\n const u = grid.uSteps === 0 ? 0 : ui / grid.uSteps;\n const v = grid.vSteps === 0 ? 0 : vi / grid.vSteps;\n const point = grid.position(u, v);\n const dir = grid.normal(u, v);\n position.push(point[0], point[1], point[2]);\n normal.push(dir[0], dir[1], dir[2]);\n const [s, t] = planarUv(point, dir, half);\n uv.push(s, t);\n }\n }\n\n for (let vi = 0; vi < grid.vSteps; vi++) {\n for (let ui = 0; ui < grid.uSteps; ui++) {\n const a = base + vi * uCount + ui;\n const b = a + 1;\n const c = a + uCount;\n const d = c + 1;\n pushTriangle(position, normal, index, a, c, b);\n pushTriangle(position, normal, index, b, c, d);\n }\n }\n}\n\n/** Emit one triangle, flipped if its winding faces away from the surface normal. */\nfunction pushTriangle(\n position: number[],\n normal: number[],\n index: number[],\n a: number,\n b: number,\n c: number,\n): void {\n const ax = position[a * 3], ay = position[a * 3 + 1], az = position[a * 3 + 2];\n const bx = position[b * 3], by = position[b * 3 + 1], bz = position[b * 3 + 2];\n const cx = position[c * 3], cy = position[c * 3 + 1], cz = position[c * 3 + 2];\n\n const ux = bx - ax, uy = by - ay, uz = bz - az;\n const vx = cx - ax, vy = cy - ay, vz = cz - az;\n\n const nx = uy * vz - uz * vy;\n const ny = uz * vx - ux * vz;\n const nz = ux * vy - uy * vx;\n\n // A collapsed quad (a pole, or a patch with no extent): no orientation and no area.\n if (nx * nx + ny * ny + nz * nz < 1e-20) return;\n\n const facing = nx * normal[a * 3] + ny * normal[a * 3 + 1] + nz * normal[a * 3 + 2];\n\n if (facing >= 0) index.push(a, b, c);\n else index.push(a, c, b);\n}\n\n/** A planar UV projected along the axis the normal points most down. Approximate on purpose: faces get an exact box-projected UV (what a texture on a rounded box is almost always for) and arcs a continuous projection that meets them without a seam; an exact arc-length unwrap would need a per-patch atlas, a texturing feature rather than a shape one. */\nfunction planarUv(point: Vec3, dir: Vec3, half: Vec3): [number, number] {\n const ax = Math.abs(dir[0]);\n const ay = Math.abs(dir[1]);\n const az = Math.abs(dir[2]);\n\n const axis = ax >= ay && ax >= az ? 0 : ay >= az ? 1 : 2;\n const u = (axis + 1) % 3;\n const v = (axis + 2) % 3;\n\n return [\n half[u] === 0 ? 0.5 : 0.5 + point[u] / (2 * half[u]),\n half[v] === 0 ? 0.5 : 0.5 + point[v] / (2 * half[v]),\n ];\n}\n\nfunction axisVector(axis: number, sign: number): Vec3 {\n const out: number[] = [0, 0, 0];\n out[axis] = sign;\n return out as unknown as Vec3;\n}\n\nfunction lerp(from: number, to: number, t: number): number {\n return from + (to - from) * t;\n}\n", "import type { Euler3, Quaternion, Vector3Input } from \"./vector3\";\n\n/** Shadow tuning for a light. `mapSize`, `near`, `far`, `bias` and `normalBias` are derived by the renderer (the right bias depends on scene scale); {@link params} is applied straight onto the light's `shadow` object for the rare scene that overrides one. */\nexport interface ShadowOptions3D {\n /** 0 hard-edged → 1 very soft. Default 0.5. */\n softness?: number;\n /** Half-extent of a directional light's orthographic shadow frustum, world units. Sized to the scene bounds when omitted; too large is blocky, too small clips. */\n extent?: number;\n /** Escape hatch, assigned onto the renderer's shadow object. */\n params?: Record<string, unknown>;\n}\n\n/**\n * A node's relationship to shadows. Objects default to `true` (cast and receive) with the viewport's own `shadows`\n * switch deciding, so enabling shadows is enough without tagging every mesh. For a light it says whether it casts a\n * shadow map, and the object form tunes that map.\n *\n * Every light casting by default is a real cost once shadows are on (a point light needs a six-face cube map):\n * turn fill lights off with `shadow={false}` and leave the key light casting.\n */\nexport type Shadow3D = boolean | \"cast\" | \"receive\" | ShadowOptions3D;\n\nexport function shadowCasts(mode: Shadow3D | undefined): boolean {\n if (mode === undefined || mode === true) return true;\n if (mode === false) return false;\n return mode === \"cast\" || typeof mode === \"object\";\n}\n\nexport function shadowReceives(mode: Shadow3D | undefined): boolean {\n if (mode === undefined || mode === true) return true;\n if (mode === false) return false;\n return mode === \"receive\" || typeof mode === \"object\";\n}\n\n/** A light's shadow tuning, or `null` when it casts none. */\nexport function resolveShadowOptions3D(mode: Shadow3D | undefined): ShadowOptions3D | null {\n if (!shadowCasts(mode)) return null;\n return typeof mode === \"object\" ? mode : {};\n}\n\n/**\n * Placement of a single 3D object; an omitted field means identity, so `{}` is a no-op. Rotation is in **degrees**\n * (matching 2D `rotation`); the renderer converts. No hand-written key: a node stamps its id on the scope it opens,\n * and a drawable is keyed by that id plus a content signature, so conditional builders reuse the right cache entry.\n */\nexport interface Transform3D {\n /** Position in the parent's local space. Default origin. */\n position?: Vector3Input;\n /** Euler rotation in **degrees**, applied in `order` (default `\"XYZ\"`); ignored when {@link quaternion} is set. */\n rotation?: Vector3Input | Euler3;\n /** Unit quaternion; wins over {@link rotation}. Use it (with `slerpQuaternion`) for tumbles where Euler would gimbal. */\n quaternion?: Quaternion;\n /** Per-axis scale; a scalar scales uniformly. Default 1. */\n scale?: Vector3Input;\n /** World-space point to orient toward, applied after {@link position}; wins over {@link rotation} and {@link quaternion}. */\n lookAt?: Vector3Input;\n /** Hide without removing (keeps the cached object alive). Default true. */\n visible?: boolean;\n /** Shadow participation. Default `true` — see {@link Shadow3D}. */\n shadow?: Shadow3D;\n /** Draw-order override, for tuning transparent sorting. */\n renderOrder?: number;\n /**\n * Node identity, stamped by `Scene3D.begin` so the renderer caches a group against the node that opened it; never written by an author.\n *\n * @internal\n */\n key?: string;\n}\n\n/** Which faces of a surface are rasterized. */\nexport type Faces3D = \"front\" | \"back\" | \"both\";\n\n/** How a drawn colour combines with what is already in the framebuffer. */\nexport type Blend3D = \"normal\" | \"additive\" | \"subtractive\" | \"multiply\" | \"none\";\n", "import type { PathData } from \"@/render/descriptors/path\";\nimport type { PathBuilder } from \"@/render/descriptors/path-builder\";\nimport { type Color, parseColor } from \"@/attributes/shape/fill/color/parser\";\nimport type { Vector3, Vector3Input } from \"./vector3\";\nimport type { Segments3D } from \"./segments\";\n\n/**\n * Anything not modelled by a named field, assigned straight onto the constructed object: the last resort, unsafe by\n * construction (it bypasses the type system, and any change is a full rebuild since the renderer can't know what a\n * key affects). **Applied** to materials, lights (and a light's `shadow`) and cameras; **not** to geometries, the\n * environment or post effects, where it is recorded and nothing reads it (in development the first warns). Set a\n * geometry's own fields instead.\n */\nexport interface Passthrough3D {\n params?: Record<string, unknown>;\n}\n\n/**\n /** A partial revolution shared by every shape that has one: `startAngle` / `sweep` in degrees as 2D `Ellipse` says them, replacing three's per-shape spellings (`thetaStart`, `thetaLength`, `phiStart`, `phiLength`, `arc`). */\nexport interface Sweep3D {\n /** Where the revolution begins, in **degrees**. Default 0. */\n startAngle?: number;\n /** How far it runs, in **degrees**. Default 360 (or 180 for a half sweep). */\n sweep?: number;\n}\n\n/** A box. `cornerRadius` is the same control `Rect` has in 2D and rounds all twelve edges; see `evaluateRoundedBox` for how the surface is built. */\nexport interface BoxGeometry3D extends Passthrough3D {\n type: \"box\";\n width?: number;\n height?: number;\n depth?: number;\n /** Rounds every edge and corner. Clamped to the smallest half-extent. */\n cornerRadius?: number;\n /** Face subdivision, as `[x, y, z]`. Default 1. */\n segments?: Segments3D;\n}\n\n/** A sphere, or a wedge/band of one via {@link Sweep3D} and the latitude pair. */\nexport interface SphereGeometry3D extends Passthrough3D, Sweep3D {\n type: \"sphere\";\n radius?: number;\n /** `[longitude, latitude]`. Default `[32, 16]`. */\n segments?: Segments3D;\n /** Vertical band start, in **degrees** from the north pole. Default 0. */\n startLatitude?: number;\n /** Vertical band extent, in **degrees**. Default 180 (pole to pole). */\n latitudeSweep?: number;\n}\n\nexport interface PlaneGeometry3D extends Passthrough3D {\n type: \"plane\";\n width?: number;\n height?: number;\n /** `[width, height]`. Raise to subdivide for per-vertex displacement. */\n segments?: Segments3D;\n}\n\n/** A cylinder, or any tapered tube: `radius` takes `[top, bottom]` for a taper. */\nexport interface CylinderGeometry3D extends Passthrough3D, Sweep3D {\n type: \"cylinder\";\n /** A scalar, or `[top, bottom]` to taper. Default 1. */\n radius?: number | readonly [number, number];\n height?: number;\n /** `[radial, height]`. Default `[32, 1]`. */\n segments?: Segments3D;\n /** Draw the end caps. Default true. */\n capped?: boolean;\n}\n\nexport interface ConeGeometry3D extends Passthrough3D, Sweep3D {\n type: \"cone\";\n radius?: number;\n height?: number;\n /** `[radial, height]`. Default `[32, 1]`. */\n segments?: Segments3D;\n /** Draw the base cap. Default true. */\n capped?: boolean;\n}\n\nexport interface TorusGeometry3D extends Passthrough3D, Sweep3D {\n type: \"torus\";\n /** Distance from the centre to the middle of the ring. */\n radius?: number;\n /** Thickness of the ring itself. Default 0.4. */\n thickness?: number;\n /** `[radial, tubular]`. Default `[16, 48]`. */\n segments?: Segments3D;\n}\n\nexport interface TorusKnotGeometry3D extends Passthrough3D {\n type: \"torusKnot\";\n radius?: number;\n /** Thickness of the strand. Default 0.4. */\n thickness?: number;\n /** `[tubular, radial]`. Default `[64, 8]`. */\n segments?: Segments3D;\n /** Winding counts as `[around the axis, around the torus]`. Default `[2, 3]`. */\n windings?: readonly [number, number];\n}\n\nexport interface CircleGeometry3D extends Passthrough3D, Sweep3D {\n type: \"circle\";\n radius?: number;\n /** Default 32. */\n segments?: Segments3D;\n}\n\n/** A flat annulus — a disc with a hole. */\nexport interface RingGeometry3D extends Passthrough3D, Sweep3D {\n type: \"ring\";\n /** Outer radius. Default 1. */\n radius?: number;\n /** Inner radius — the size of the hole. Default 0.5. */\n innerRadius?: number;\n /** `[around, radial]`. Default `[32, 1]`. */\n segments?: Segments3D;\n}\n\nexport interface CapsuleGeometry3D extends Passthrough3D {\n type: \"capsule\";\n /** Default 0.5. */\n radius?: number;\n /** Length of the straight mid-section, excluding the caps. Default 1. */\n height?: number;\n /** `[radial, cap]`. Default `[16, 8]`. */\n segments?: Segments3D;\n}\n\nexport interface PolyhedronGeometry3D extends Passthrough3D {\n type: \"polyhedron\";\n shape: \"tetrahedron\" | \"octahedron\" | \"icosahedron\" | \"dodecahedron\";\n radius?: number;\n /** Subdivision. Raising this on an icosahedron approximates a sphere. */\n segments?: Segments3D;\n}\n\n/** How an extrusion's edge is chamfered. A bare number is the bevel's size. */\nexport interface Bevel3D {\n size?: number;\n thickness?: number;\n offset?: number;\n segments?: number;\n}\n\n/** A 2D outline swept into a solid. `path` takes the same `PathData` or {@link PathBuilder} as the 2D `Path` node, so an existing outline extrudes with no new vocabulary. */\nexport interface ExtrudeGeometry3D extends Passthrough3D {\n type: \"extrude\";\n path: PathData | PathBuilder;\n depth?: number;\n /** Curve flattening resolution. Default 12. */\n segments?: Segments3D;\n /** A number is the bevel size; an object tunes the rest. Omit for no bevel. */\n bevel?: number | Bevel3D;\n}\n\n/** A profile revolved about the Y axis — vases, bowls, turned shapes. */\nexport interface LatheGeometry3D extends Passthrough3D, Sweep3D {\n type: \"lathe\";\n /** Profile points in the XY plane; `x` is the radius, `y` the height. */\n points: readonly Vector3Input[];\n /** Default 12. */\n segments?: Segments3D;\n}\n\n/** A circular cross-section swept along a 3D curve. */\nexport interface TubeGeometry3D extends Passthrough3D {\n type: \"tube\";\n points: readonly Vector3Input[];\n radius?: number;\n /** `[along the curve, around it]`. Default `[64, 8]`. */\n segments?: Segments3D;\n closed?: boolean;\n}\n\n/** Raw vertex buffers: the escape hatch that makes any computable mesh expressible as pure data. `position` (`[x, y, z, ...]`) is required; `index` shares vertices between faces; omit `normal` and set {@link computeNormals} to derive them. */\nexport interface BufferGeometry3D extends Passthrough3D {\n type: \"buffer\";\n /** Flat `xyz` triples. */\n position: ArrayLike<number>;\n /** Flat `xyz` triples. Omit and set {@link computeNormals} to derive them. */\n normal?: ArrayLike<number>;\n /** Flat `uv` pairs. */\n uv?: ArrayLike<number>;\n /** Flat linear `rgb` triples. Needs `vertexColors: true` on the material. */\n color?: ArrayLike<number>;\n /** Triangle indices into the arrays above. */\n index?: ArrayLike<number>;\n /** Derive vertex normals after upload — needed for correct lighting. */\n computeNormals?: boolean;\n /** Bump after mutating an array **in place** to force a re-upload: reusing one `Float32Array` across frames is the fast way to animate a mesh but defeats identity comparison. Omitted, the renderer re-uploads every frame (correct by default); set {@link staticData} once the data stops changing. */\n revision?: number;\n /**\n * Declare the arrays immutable, so the renderer compares by identity alone\n * and skips the per-frame re-upload. Only safe when you never mutate in place.\n */\n staticData?: boolean;\n}\n\n/** One evaluated vertex of a {@link ParametricGeometry3D} surface. */\nexport type ParametricVertex3D = Vector3 | readonly [number, number, number];\n\n/**\n * A surface sampled over a `[0,1] x [0,1]` grid: the ergonomic form of {@link BufferGeometry3D} for procedural\n * meshes. Core evaluates the callbacks into vertex buffers, so the descriptor stays plain data; it re-evaluates\n * every frame, so read the node's props and frame time inside `vertex`.\n *\n * Geo.parametric({\n * segments: [70, 70],\n * vertex: (u, v) => ({ x: (u - 0.5) * 20, y: wave(u, v, t), z: (v - 0.5) * 20 }),\n * computeNormals: true,\n * })\n */\nexport interface ParametricGeometry3D extends Passthrough3D {\n type: \"parametric\";\n /** Grid resolution as `[u, v]`, or one number for both. */\n segments: Segments3D;\n /** Position for grid coordinate `(u, v)`, both in `[0, 1]`. */\n vertex: (u: number, v: number) => ParametricVertex3D;\n /** Optional per-vertex colour. Needs `vertexColors: true` on the material. */\n color?: (u: number, v: number, position: Vector3) => Color;\n /** Derive vertex normals. Almost always wanted for a lit surface. */\n computeNormals?: boolean;\n /** A value that changes exactly when {@link vertex} would return something different; supply it and the surface re-evaluates only when it moves. Omitted, it re-evaluates every frame (`segments: 80` is ~6.6k `vertex` calls plus normals and a buffer re-upload, on any frame at all). The renderer can't inspect what the `vertex` closure captured, so derive this from exactly those captures; omit it for a surface that varies with time. Same role as {@link BufferGeometry3D.revision}. */\n revision?: number;\n}\n\n/** The hard edges of another geometry as line segments, for a clean wireframe without triangulation diagonals. Draw with `Graphics3D.line({ segments: true })`. */\nexport interface EdgesGeometry3D extends Passthrough3D {\n type: \"edges\";\n source: Geometry3D;\n /** Minimum dihedral angle in **degrees** for an edge to count. Default 1. */\n thresholdAngle?: number;\n}\n\n/** Every triangle edge of another geometry, as line segments. */\nexport interface WireframeGeometry3D extends Passthrough3D {\n type: \"wireframe\";\n source: Geometry3D;\n}\n\n/** Geometry taken from a loaded model file, by node name. */\nexport interface ModelGeometry3D extends Passthrough3D {\n type: \"modelGeometry\";\n src: string;\n /** Which node of the model to take. Defaults to the first mesh found. */\n node?: string;\n}\n\n/** Normalize {@link CylinderGeometry3D.radius} to its `[top, bottom]` pair. */\nexport function cylinderRadii(\n radius: number | readonly [number, number] | undefined,\n): [number, number] {\n if (radius === undefined) return [1, 1];\n if (typeof radius === \"number\") return [radius, radius];\n return [radius[0] ?? 1, radius[1] ?? radius[0] ?? 1];\n}\n\n/** Normalize {@link ExtrudeGeometry3D.bevel} to its full option set, or `null`. */\nexport function resolveBevel3D(bevel: number | Bevel3D | undefined): Required<Bevel3D> | null {\n if (bevel === undefined) return null;\n const options = typeof bevel === \"number\" ? { size: bevel } : bevel;\n const size = options.size ?? 0.1;\n return {\n size,\n // Scaled off `size` rather than defaulted independently, so the one-number\n // form produces a bevel with sane proportions instead of a sliver.\n thickness: options.thickness ?? size * 2,\n offset: options.offset ?? 0,\n segments: options.segments ?? 3,\n };\n}\n\n/** Evaluates a {@link ParametricGeometry3D} into vertex buffers. In core so the grid/winding maths is backend-agnostic and unit-testable without a GPU; the renderer calls it at draw time (not record time), so the cost is paid only when rasterized, never during the asset-tracking replay. The grid is `(segments + 1)²` vertices wound counter-clockwise, so front faces point along +Y for a surface in the XZ plane. */\nexport function evaluateParametric(geometry: ParametricGeometry3D): BufferGeometry3D {\n const resolved = geometry.segments;\n const [uSegments, vSegments] = typeof resolved === \"number\"\n ? [resolved, resolved]\n : [resolved[0] ?? 1, resolved[1] ?? resolved[0] ?? 1];\n\n const uCount = Math.max(1, Math.floor(uSegments)) + 1;\n const vCount = Math.max(1, Math.floor(vSegments)) + 1;\n\n const position = new Float32Array(uCount * vCount * 3);\n const uv = new Float32Array(uCount * vCount * 2);\n const color = geometry.color ? new Float32Array(uCount * vCount * 3) : undefined;\n\n const scratch: Vector3 = { x: 0, y: 0, z: 0 };\n\n for (let vi = 0; vi < vCount; vi++) {\n const v = vi / (vCount - 1);\n for (let ui = 0; ui < uCount; ui++) {\n const u = ui / (uCount - 1);\n const index = vi * uCount + ui;\n\n const vertex = geometry.vertex(u, v);\n if (Array.isArray(vertex)) {\n scratch.x = vertex[0]; scratch.y = vertex[1]; scratch.z = vertex[2];\n } else {\n const p = vertex as Vector3;\n scratch.x = p.x; scratch.y = p.y; scratch.z = p.z;\n }\n\n position[index * 3] = scratch.x;\n position[index * 3 + 1] = scratch.y;\n position[index * 3 + 2] = scratch.z;\n\n uv[index * 2] = u;\n uv[index * 2 + 1] = v;\n\n if (color && geometry.color) {\n const rgba = resolveLinearRgb(geometry.color(u, v, scratch));\n color[index * 3] = rgba[0];\n color[index * 3 + 1] = rgba[1];\n color[index * 3 + 2] = rgba[2];\n }\n }\n }\n\n // Two triangles per cell. Uint32 because a 256² grid already exceeds Uint16.\n const index = new Uint32Array((uCount - 1) * (vCount - 1) * 6);\n let cursor = 0;\n for (let vi = 0; vi < vCount - 1; vi++) {\n for (let ui = 0; ui < uCount - 1; ui++) {\n const a = vi * uCount + ui;\n const b = a + 1;\n const c = a + uCount;\n const d = c + 1;\n index[cursor++] = a; index[cursor++] = c; index[cursor++] = b;\n index[cursor++] = b; index[cursor++] = c; index[cursor++] = d;\n }\n }\n\n return {\n type: \"buffer\",\n position,\n uv,\n color,\n index,\n computeNormals: geometry.computeNormals,\n params: geometry.params,\n };\n}\n\n/** A {@link Color} as **linear-light** RGB, which a vertex-colour buffer must hold (the renderer samples it into linear space with no decode). `parseColor` returns gamma-encoded sRGB, so skipping the inversion renders vertex-coloured surfaces washed out. */\nfunction resolveLinearRgb(color: Color): readonly [number, number, number] {\n const [r, g, b] = typeof color === \"string\" ? parseColor(color) : color;\n return [srgbToLinear(r), srgbToLinear(g), srgbToLinear(b)];\n}\n\n/** Inverse sRGB transfer function (IEC 61966-2-1), per channel. */\nfunction srgbToLinear(channel: number): number {\n return channel <= 0.04045\n ? channel / 12.92\n : Math.pow((channel + 0.055) / 1.055, 2.4);\n}\n\n/** Every geometry a mesh can be built from, discriminated on `type`. */\nexport type Geometry3D =\n | BoxGeometry3D\n | SphereGeometry3D\n | PlaneGeometry3D\n | CylinderGeometry3D\n | ConeGeometry3D\n | TorusGeometry3D\n | TorusKnotGeometry3D\n | CircleGeometry3D\n | RingGeometry3D\n | CapsuleGeometry3D\n | PolyhedronGeometry3D\n | ExtrudeGeometry3D\n | LatheGeometry3D\n | TubeGeometry3D\n | BufferGeometry3D\n | ParametricGeometry3D\n | EdgesGeometry3D\n | WireframeGeometry3D\n | ModelGeometry3D;\n", "import { quaternionFromEuler, resolveVector3, type Euler3, type Quaternion, type Vector3, type Vector3Input } from \"./vector3\";\nimport type { Transform3D } from \"./transform\";\n\n/**\n * 4×4 matrix maths in **column-major order**, three's layout, so a matrix built here and one read off a\n * `THREE.Object3D` are the same sixteen numbers in the same slots.\n *\n * ```\n * | m0 m4 m8 m12 |\n * | m1 m5 m9 m13 |\n * | m2 m6 m10 m14 |\n * | m3 m7 m11 m15 |\n * ```\n *\n * Exists for {@link projectNode3D}, the walk that says where a 3D node's pixels landed, and holds only the maths\n * that walk needs. Each function mirrors a specific three behaviour (`Object3D.lookAt`'s two orientations,\n * `PerspectiveCamera.updateProjectionMatrix`'s zoom, an `OrthographicCamera`'s frustum from `frustumHeight`), since\n * a selection box a few pixels off the render is worse than none. Nothing here imports a renderer, so `three`\n * stays inside `@motionscript/browser`.\n */\n\n/** A 4×4 matrix as sixteen numbers, column-major. See the module note. */\n/** @internal */\nexport type Matrix4 = readonly number[];\n\n/** A homogeneous point — what {@link applyMatrix4} returns before the divide. */\n/** @internal */\nexport interface Vector4 extends Vector3 {\n w: number;\n}\n\n/** @internal The identity matrix. */\nexport function identity4(): Matrix4 {\n return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];\n}\n\n/** `a · b`: applies `b` first, then `a`. Composing a parent with a child gives the child's world transform, the convention of {@link import(\"@/attributes/layout/matrix2d\").multiply} one dimension down. */\n/** @internal */\nexport function multiply4(a: Matrix4, b: Matrix4): Matrix4 {\n const out = new Array<number>(16);\n for (let col = 0; col < 4; col++) {\n const b0 = b[col * 4], b1 = b[col * 4 + 1], b2 = b[col * 4 + 2], b3 = b[col * 4 + 3];\n out[col * 4] = a[0] * b0 + a[4] * b1 + a[8] * b2 + a[12] * b3;\n out[col * 4 + 1] = a[1] * b0 + a[5] * b1 + a[9] * b2 + a[13] * b3;\n out[col * 4 + 2] = a[2] * b0 + a[6] * b1 + a[10] * b2 + a[14] * b3;\n out[col * 4 + 3] = a[3] * b0 + a[7] * b1 + a[11] * b2 + a[15] * b3;\n }\n return out;\n}\n\n/** The inverse, or `null` when `m` is singular (a zero scale on any axis); a camera with no inverse has no view, so the caller draws no boxes rather than dividing into `NaN`. */\n/** @internal */\nexport function invert4(m: Matrix4): Matrix4 | null {\n const [\n n11, n21, n31, n41,\n n12, n22, n32, n42,\n n13, n23, n33, n43,\n n14, n24, n34, n44,\n ] = m;\n\n const t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44;\n const t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44;\n const t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44;\n const t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;\n\n const determinant = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;\n if (determinant === 0) return null;\n const d = 1 / determinant;\n\n return [\n t11 * d,\n (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * d,\n (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * d,\n (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * d,\n\n t12 * d,\n (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * d,\n (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * d,\n (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * d,\n\n t13 * d,\n (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * d,\n (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * d,\n (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * d,\n\n t14 * d,\n (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * d,\n (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * d,\n (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * d,\n ];\n}\n\n/** @internal Map a point through `m`, keeping `w` — the caller does the divide. */\nexport function applyMatrix4(m: Matrix4, p: Vector3): Vector4 {\n const { x, y, z } = p;\n return {\n x: m[0] * x + m[4] * y + m[8] * z + m[12],\n y: m[1] * x + m[5] * y + m[9] * z + m[13],\n z: m[2] * x + m[6] * y + m[10] * z + m[14],\n w: m[3] * x + m[7] * y + m[11] * z + m[15],\n };\n}\n\n/** @internal Translation, rotation and scale composed into one matrix. */\nexport function compose4(position: Vector3, rotation: Quaternion, scale: Vector3): Matrix4 {\n const { x, y, z, w } = rotation;\n const x2 = x + x, y2 = y + y, z2 = z + z;\n const xx = x * x2, xy = x * y2, xz = x * z2;\n const yy = y * y2, yz = y * z2, zz = z * z2;\n const wx = w * x2, wy = w * y2, wz = w * z2;\n\n return [\n (1 - (yy + zz)) * scale.x, (xy + wz) * scale.x, (xz - wy) * scale.x, 0,\n (xy - wz) * scale.y, (1 - (xx + zz)) * scale.y, (yz + wx) * scale.y, 0,\n (xz + wy) * scale.z, (yz - wx) * scale.z, (1 - (xx + yy)) * scale.z, 0,\n position.x, position.y, position.z, 1,\n ];\n}\n\n/** The rotation aiming `eye`'s **−Z** at `target`, as three's `Matrix4.lookAt(eye, target, up)`. Callers reproduce `Object3D.lookAt`'s two cases by argument order: a camera or light aims −Z and passes `(position, target)`; everything else aims **+Z**, i.e. `(target, position)` (three's asymmetry; see `applyTransform` in the renderer). A degenerate pair (eye on target, up parallel to the view) has no orientation; three nudges `z` by `1e-4` and so does this, so they agree rather than one producing `NaN`. */\n/** @internal */\nexport function lookAtRotation4(eye: Vector3, target: Vector3, up: Vector3 = UP): Matrix4 {\n let zx = eye.x - target.x, zy = eye.y - target.y, zz = eye.z - target.z;\n let length = Math.hypot(zx, zy, zz);\n if (length === 0) {\n zz = 1;\n length = 1;\n }\n zx /= length; zy /= length; zz /= length;\n\n let xx = up.y * zz - up.z * zy;\n let xy = up.z * zx - up.x * zz;\n let xz = up.x * zy - up.y * zx;\n let xLength = Math.hypot(xx, xy, xz);\n if (xLength === 0) {\n // Up is parallel to the view direction: three's own nudge, so both pick the same arbitrary roll.\n if (Math.abs(up.z) === 1) zx += 1e-4;\n else zz += 1e-4;\n length = Math.hypot(zx, zy, zz);\n zx /= length; zy /= length; zz /= length;\n xx = up.y * zz - up.z * zy;\n xy = up.z * zx - up.x * zz;\n xz = up.x * zy - up.y * zx;\n xLength = Math.hypot(xx, xy, xz);\n }\n xx /= xLength; xy /= xLength; xz /= xLength;\n\n const yx = zy * xz - zz * xy;\n const yy = zz * xx - zx * xz;\n const yz = zx * xy - zy * xx;\n\n return [xx, xy, xz, 0, yx, yy, yz, 0, zx, zy, zz, 0, 0, 0, 0, 1];\n}\n\n/** three's default up vector, which nothing in the descriptors overrides yet. */\nconst UP: Vector3 = { x: 0, y: 1, z: 0 };\n\n/** A {@link Transform3D} as a matrix in the parent's space. Precedence is the renderer's, `lookAt` > `quaternion` > `rotation` (each a complete orientation statement). `lookAt` names a world-space point, so it is resolved against `parentWorld` (as `Object3D.lookAt`): a node in a rotated group undoes that rotation. Pass `null` at the scene root. */\n/** @internal */\nexport function transformMatrix4(transform: Transform3D | undefined, parentWorld: Matrix4 | null): Matrix4 {\n if (!transform) return identity4();\n\n const position = resolveVector3(transform.position);\n const scale = resolveVector3(transform.scale === undefined ? 1 : transform.scale);\n\n if (transform.lookAt !== undefined) {\n const target = resolveVector3(transform.lookAt);\n // `lookAt` is measured from the node's world position, not its local origin.\n const world = parentWorld\n ? applyMatrix4(parentWorld, position)\n : { ...position, w: 1 };\n const origin = { x: world.x, y: world.y, z: world.z };\n // +Z at the target: the non-camera branch of `Object3D.lookAt` (cameras go through `cameraMatrix4`).\n let rotation = lookAtRotation4(target, origin);\n if (parentWorld) {\n const inverseParent = invert4(rotationOf4(parentWorld));\n if (inverseParent) rotation = multiply4(inverseParent, rotation);\n }\n // T · R · S, the order {@link compose4} produces; spelled out because the rotation arrived as a matrix.\n return multiply4(multiply4(translation4(position), rotation), scale4(scale));\n }\n\n const quaternion = transform.quaternion ?? quaternionFromEuler(eulerOf(transform.rotation));\n return compose4(position, quaternion, scale);\n}\n\n/** A `Vector3Input | Euler3` as an {@link Euler3}, defaulting to no rotation. */\nfunction eulerOf(rotation: Vector3Input | Euler3 | undefined): Euler3 {\n const angles = resolveVector3(rotation as Vector3Input | undefined);\n return { ...angles, order: (rotation as Euler3 | undefined)?.order };\n}\n\n/** @internal Pure translation. */\nexport function translation4(position: Vector3): Matrix4 {\n return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, position.x, position.y, position.z, 1];\n}\n\n/** Pure per-axis scale. */\nfunction scale4(scale: Vector3): Matrix4 {\n return [scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1];\n}\n\n/** `m`'s rotation with translation and scale divided out (three's `Matrix4.extractRotation`), used to undo a parent's orientation when resolving a `lookAt`; a zero-length basis vector leaves that column as identity. */\n/** @internal */\nexport function rotationOf4(m: Matrix4): Matrix4 {\n const sx = Math.hypot(m[0], m[1], m[2]) || 1;\n const sy = Math.hypot(m[4], m[5], m[6]) || 1;\n const sz = Math.hypot(m[8], m[9], m[10]) || 1;\n return [\n m[0] / sx, m[1] / sx, m[2] / sx, 0,\n m[4] / sy, m[5] / sy, m[6] / sy, 0,\n m[8] / sz, m[9] / sz, m[10] / sz, 0,\n 0, 0, 0, 1,\n ];\n}\n\n/** A perspective projection matching `PerspectiveCamera.updateProjectionMatrix`, including `zoom`, which three applies by narrowing the frustum rather than scaling the result. */\n/** @internal */\nexport function perspective4(fov: number, aspect: number, near: number, far: number, zoom: number): Matrix4 {\n const top = near * Math.tan((fov * Math.PI) / 360) / zoom;\n const height = 2 * top;\n const width = aspect * height;\n const left = -0.5 * width;\n return frustum4(left, left + width, top, top - height, near, far);\n}\n\n/** three's `Matrix4.makePerspective`, with its reversed-`bottom` convention. */\nfunction frustum4(left: number, right: number, top: number, bottom: number, near: number, far: number): Matrix4 {\n const x = (2 * near) / (right - left);\n const y = (2 * near) / (top - bottom);\n const a = (right + left) / (right - left);\n const b = (top + bottom) / (top - bottom);\n const c = -(far + near) / (far - near);\n const d = (-2 * far * near) / (far - near);\n return [x, 0, 0, 0, 0, y, 0, 0, a, b, c, -1, 0, 0, d, 0];\n}\n\n/** An orthographic projection matching `OrthographicCamera.updateProjectionMatrix`: `zoom` widens the frustum about its centre rather than scaling the result. */\n/** @internal */\nexport function orthographic4(left: number, right: number, top: number, bottom: number, near: number, far: number, zoom: number): Matrix4 {\n const dx = (right - left) / (2 * zoom);\n const dy = (top - bottom) / (2 * zoom);\n const cx = (right + left) / 2;\n const cy = (top + bottom) / 2;\n\n const l = cx - dx, r = cx + dx, t = cy + dy, b = cy - dy;\n const w = 1 / (r - l);\n const h = 1 / (t - b);\n const p = 1 / (far - near);\n return [\n 2 * w, 0, 0, 0,\n 0, 2 * h, 0, 0,\n 0, 0, -2 * p, 0,\n -(r + l) * w, -(t + b) * h, -(far + near) * p, 1,\n ];\n}\n", "import { cylinderRadii, type Geometry3D } from \"./geometry\";\nimport { applyMatrix4, type Matrix4 } from \"./matrix4\";\nimport { resolveVector3, type Vector3 } from \"./vector3\";\n\n/**\n * Axis-aligned bounds for the 3D descriptors, for an editor to box a mesh it did not build.\n *\n * **Analytic, not sampled**: each primitive's extent falls out of its parameters, so it is a table of formulas that\n * costs nothing per pointer move. Defaults are *three's*, since a descriptor omitting `radius` renders at three's 1\n * and a box round a different number would sit in the wrong place.\n *\n * **Conservative where not exact**: a partial sweep is bounded by the full figure, since the exact answer is an\n * arc-endpoint problem per shape per axis and a box that cuts through the mesh is worse than one a little loose.\n *\n * **`null` means \"no answer\", not \"empty\"**: a loaded model file, a rasterized path, or a user callback that may read\n * the frame clock can't be measured here. The caller draws no box; a wrong box is worse than none.\n */\n\n/** An axis-aligned box. `min` is corner-wise minimum, not a point on the mesh. */\nexport interface Box3 {\n min: Vector3;\n max: Vector3;\n}\n\n/** @internal A box centred on the origin with the given half-extents. */\nexport function centeredBox3(hx: number, hy: number, hz: number): Box3 {\n return { min: { x: -hx, y: -hy, z: -hz }, max: { x: hx, y: hy, z: hz } };\n}\n\n/** @internal The union of two boxes; either may be `null`. */\nexport function unionBox3(a: Box3 | null, b: Box3 | null): Box3 | null {\n if (!a) return b;\n if (!b) return a;\n return {\n min: { x: Math.min(a.min.x, b.min.x), y: Math.min(a.min.y, b.min.y), z: Math.min(a.min.z, b.min.z) },\n max: { x: Math.max(a.max.x, b.max.x), y: Math.max(a.max.y, b.max.y), z: Math.max(a.max.z, b.max.z) },\n };\n}\n\n/** @internal The box's eight corners, in no particular order. */\nexport function corners3(box: Box3): Vector3[] {\n const { min, max } = box;\n return [\n { x: min.x, y: min.y, z: min.z },\n { x: max.x, y: min.y, z: min.z },\n { x: min.x, y: max.y, z: min.z },\n { x: max.x, y: max.y, z: min.z },\n { x: min.x, y: min.y, z: max.z },\n { x: max.x, y: min.y, z: max.z },\n { x: min.x, y: max.y, z: max.z },\n { x: max.x, y: max.y, z: max.z },\n ];\n}\n\n/** `box` mapped through `m` and re-bounded: the AABB of the transformed AABB, not of the mesh (a rotated box's corner-bounds are larger than the shape), erring in the safe direction (see the module note). */\n/** @internal */\nexport function transformBox3(box: Box3, m: Matrix4): Box3 {\n let minX = Infinity, minY = Infinity, minZ = Infinity;\n let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity;\n for (const corner of corners3(box)) {\n const p = applyMatrix4(m, corner);\n if (p.x < minX) minX = p.x;\n if (p.y < minY) minY = p.y;\n if (p.z < minZ) minZ = p.z;\n if (p.x > maxX) maxX = p.x;\n if (p.y > maxY) maxY = p.y;\n if (p.z > maxZ) maxZ = p.z;\n }\n return { min: { x: minX, y: minY, z: minZ }, max: { x: maxX, y: maxY, z: maxZ } };\n}\n\n/** The local-space bounds of a geometry descriptor, or `null` when it can't be measured from the descriptor alone (see the module note). */\nexport function geometryBounds3D(geometry: Geometry3D | undefined): Box3 | null {\n if (!geometry) return null;\n\n switch (geometry.type) {\n // three centres a box on its origin; the defaults are 1 on every axis.\n case \"box\":\n return centeredBox3(\n (geometry.width ?? 1) / 2,\n (geometry.height ?? 1) / 2,\n (geometry.depth ?? 1) / 2,\n );\n\n // Full sphere even for a wedge — see the module note on partial sweeps.\n case \"sphere\":\n return centeredBox3(geometry.radius ?? 1, geometry.radius ?? 1, geometry.radius ?? 1);\n\n // Flat in XY, facing +Z. Zero depth is correct rather than degenerate:\n // the projected box of a plane seen edge-on genuinely is a line.\n case \"plane\":\n return centeredBox3((geometry.width ?? 1) / 2, (geometry.height ?? 1) / 2, 0);\n\n // A cone is a cylinder with one radius zeroed, and three models it as its\n // own type — so the two share nothing here but the shape of the answer.\n case \"cylinder\": {\n const [top, bottom] = cylinderRadii(geometry.radius);\n const radius = Math.max(top, bottom);\n return centeredBox3(radius, (geometry.height ?? 1) / 2, radius);\n }\n case \"cone\": {\n const radius = geometry.radius ?? 1;\n return centeredBox3(radius, (geometry.height ?? 1) / 2, radius);\n }\n\n // The ring lies in XY and the tube swells it in Z by its own radius.\n case \"torus\": {\n const radius = geometry.radius ?? 1;\n const tube = geometry.thickness ?? 0.4;\n return centeredBox3(radius + tube, radius + tube, tube);\n }\n\n // three's knot curve is `radius * (2 + cos(qu/p)) / 2` in XY and\n // `radius * sin(qu/p) / 2` in Z, so it reaches 1.5·radius across and\n // 0.5·radius deep before the tube is added.\n case \"torusKnot\": {\n const radius = geometry.radius ?? 1;\n const tube = geometry.thickness ?? 0.4;\n return centeredBox3(radius * 1.5 + tube, radius * 1.5 + tube, radius * 0.5 + tube);\n }\n\n case \"circle\":\n return centeredBox3(geometry.radius ?? 1, geometry.radius ?? 1, 0);\n\n case \"ring\": {\n const outer = geometry.radius ?? 1;\n return centeredBox3(outer, outer, 0);\n }\n\n // `height` is the straight mid-section only, so the caps add a radius at\n // each end — the one place three's naming would mislead a reader here. Its\n // default radius is 0.5, not three's 1: the renderer builds core's default,\n // so a box drawn round three's would be twice too wide.\n case \"capsule\": {\n const radius = geometry.radius ?? 0.5;\n return centeredBox3(radius, (geometry.height ?? 1) / 2 + radius, radius);\n }\n\n // Every platonic solid is inscribed in its radius, so the sphere bounds\n // it — loosely for a tetrahedron, exactly for a subdivided icosahedron.\n case \"polyhedron\": {\n const radius = geometry.radius ?? 1;\n return centeredBox3(radius, radius, radius);\n }\n\n // A profile revolved about Y: the widest |x| becomes the radius in both\n // ground axes, and the profile's own y range carries straight over.\n case \"lathe\": {\n let radius = 0;\n let minY = Infinity;\n let maxY = -Infinity;\n for (const point of geometry.points) {\n const p = resolveVector3(point);\n radius = Math.max(radius, Math.abs(p.x));\n minY = Math.min(minY, p.y);\n maxY = Math.max(maxY, p.y);\n }\n if (!Number.isFinite(minY)) return null;\n return { min: { x: -radius, y: minY, z: -radius }, max: { x: radius, y: maxY, z: radius } };\n }\n\n // The path's own extent, swollen by the tube radius on every axis. The\n // curve bulges outside its control points, so this is a lower bound made\n // safe by the radius rather than an exact one.\n case \"tube\": {\n const points = geometry.points.map((point) => resolveVector3(point));\n const box = pointsBounds3(points);\n if (!box) return null;\n return expandBox3(box, geometry.radius ?? 1);\n }\n\n // Raw vertex data — the one case that is a walk, because there is nothing\n // else to read it off.\n case \"buffer\":\n return positionBounds3(geometry.position);\n\n // A derived geometry has its source's extent: an outline of a shape is\n // the same size as the shape.\n case \"edges\":\n case \"wireframe\":\n return geometryBounds3D(geometry.source);\n\n // Three that need what this package hasn't got: a rasterized 2D path, a\n // callback that may read the clock, and a file off the network.\n case \"extrude\":\n case \"parametric\":\n case \"modelGeometry\":\n default:\n return null;\n }\n}\n\n/** Bounds of a point list, or `null` when it is empty. */\nfunction pointsBounds3(points: readonly Vector3[]): Box3 | null {\n if (points.length === 0) return null;\n let minX = Infinity, minY = Infinity, minZ = Infinity;\n let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity;\n for (const p of points) {\n if (p.x < minX) minX = p.x;\n if (p.y < minY) minY = p.y;\n if (p.z < minZ) minZ = p.z;\n if (p.x > maxX) maxX = p.x;\n if (p.y > maxY) maxY = p.y;\n if (p.z > maxZ) maxZ = p.z;\n }\n return { min: { x: minX, y: minY, z: minZ }, max: { x: maxX, y: maxY, z: maxZ } };\n}\n\n/** Bounds of a flat `[x, y, z, …]` position buffer. */\nfunction positionBounds3(position: ArrayLike<number>): Box3 | null {\n if (position.length < 3) return null;\n let minX = Infinity, minY = Infinity, minZ = Infinity;\n let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity;\n for (let i = 0; i + 2 < position.length; i += 3) {\n const x = position[i], y = position[i + 1], z = position[i + 2];\n if (x < minX) minX = x;\n if (y < minY) minY = y;\n if (z < minZ) minZ = z;\n if (x > maxX) maxX = x;\n if (y > maxY) maxY = y;\n if (z > maxZ) maxZ = z;\n }\n return { min: { x: minX, y: minY, z: minZ }, max: { x: maxX, y: maxY, z: maxZ } };\n}\n\n/** `box` grown by `by` on every axis. */\nfunction expandBox3(box: Box3, by: number): Box3 {\n return {\n min: { x: box.min.x - by, y: box.min.y - by, z: box.min.z - by },\n max: { x: box.max.x + by, y: box.max.y + by, z: box.max.z + by },\n };\n}\n", "import type { Color } from \"@/attributes/shape/fill/color/parser\";\nimport type { Vector2 } from \"@/attributes/layout/vector2\";\nimport type { Vector3 } from \"./vector3\";\nimport type { Passthrough3D } from \"./geometry\";\nimport type { Blend3D, Faces3D } from \"./transform\";\nimport type { Texture3D } from \"./texture\";\n\n/** Facet or smooth shading. `\"flat\"` gives one normal per triangle. */\nexport type Shading3D = \"smooth\" | \"flat\";\n\n/** State every material shares. Fields in the first block are uniform writes the renderer mutates in place, so they're free to animate; **structural** fields change the compiled shader, so changing one mid-timeline forces a recompile: set them once. */\nexport interface MaterialCommon3D extends Passthrough3D {\n /** 0–1. Free to animate; blending is turned on for you below 1. */\n opacity?: number;\n /** Hide without removing. Free to animate. */\n visible?: boolean;\n\n /**\n * **Structural, and normally derived.** The renderer turns blending on whenever the material needs it (`opacity`\n * below 1, a colour with alpha, an `alphaMap`, transmission), so a fade needs no second flag. Set it only to *force*\n * blending on an opaque material (draw order); `false` doesn't turn off blending a lower alpha requires.\n */\n transparent?: boolean;\n /** **Structural.** Discard fragments below this alpha. Cheap cutout transparency. */\n alphaTest?: number;\n /** **Structural.** Which faces to rasterize. Default `\"front\"`. */\n faces?: Faces3D;\n /** **Structural.** Draw edges only. */\n wireframe?: boolean;\n /** **Structural.** How the colour combines with the framebuffer. */\n blend?: Blend3D;\n /** **Structural.** Read per-vertex colours from the geometry's `color` buffer. */\n vertexColors?: boolean;\n /** **Structural.** Apply the scene's tone mapping. Default true. */\n toneMapped?: boolean;\n\n /** Write to the depth buffer. **Derived unless stated**: a blended surface doesn't write depth and an opaque one does (three defaults `true`, so a translucent mesh would occlude what's drawn after it). Set it for a translucent surface that should occlude. */\n depthWrite?: boolean;\n /** Test against the depth buffer. Turn off to force draw-on-top. */\n depthTest?: boolean;\n /** Nudge depth to break z-fighting between coplanar surfaces. */\n polygonOffset?: boolean;\n polygonOffsetFactor?: number;\n polygonOffsetUnits?: number;\n /** Smooth gradient banding. */\n dithering?: boolean;\n}\n\n/** Maps shared by the lit shading models. */\ninterface CommonMaps3D {\n /** Base colour (albedo). Sampled as sRGB. */\n map?: Texture3D;\n /** Per-pixel opacity, read from the red channel. */\n alphaMap?: Texture3D;\n /** Ambient occlusion, read from the red channel. Needs a second UV set. */\n aoMap?: Texture3D;\n aoMapIntensity?: number;\n /** Tangent-space normals. Sampled as linear data, not colour. */\n normalMap?: Texture3D;\n /** Normal strength, per axis. A number applies to both. */\n normalScale?: number | Vector2;\n /** Displaces vertices along their normals. Needs a subdivided geometry. */\n displacementMap?: Texture3D;\n displacementScale?: number;\n displacementBias?: number;\n /** Reflected environment. Usually inherited from the scene's environment. */\n envMap?: Texture3D;\n /** Multiplies light received from the environment. */\n envMapIntensity?: number;\n /** Baked light added on top, unaffected by scene lights. */\n lightMap?: Texture3D;\n lightMapIntensity?: number;\n}\n\n/** Emission shared by the lit shading models. */\ninterface Emissive3D {\n /** Self-illumination colour. Does not light other objects (see `post` bloom). */\n emission?: Color;\n emissionStrength?: number;\n emissionMap?: Texture3D;\n}\n\n/** Unlit — a flat colour, ignoring every light. The cheapest material. */\nexport interface BasicMaterial3D extends MaterialCommon3D, CommonMaps3D {\n type: \"basic\";\n color?: Color;\n}\n\n/** Physically based metal/rough shading, the sensible default; `roughness` and `metalness` are free to animate. */\nexport interface StandardMaterial3D extends MaterialCommon3D, CommonMaps3D, Emissive3D {\n type: \"standard\";\n color?: Color;\n /** 0 mirror-smooth → 1 fully diffuse. */\n roughness?: number;\n /** 0 dielectric → 1 metal. Metals tint their reflections by `color`. */\n metalness?: number;\n roughnessMap?: Texture3D;\n metalnessMap?: Texture3D;\n /** **Structural.** Facet or smooth shading. Default `\"smooth\"`. */\n shading?: Shading3D;\n}\n\n/** {@link StandardMaterial3D} plus clearcoat, transmission (real refraction), sheen and iridescence. Costs more per pixel; prefer `standard` unless needed. */\nexport interface PhysicalMaterial3D extends Omit<StandardMaterial3D, \"type\"> {\n type: \"physical\";\n /** A second specular lobe over the base — car paint, lacquer, varnish. */\n clearcoat?: number;\n clearcoatRoughness?: number;\n clearcoatMap?: Texture3D;\n clearcoatNormalMap?: Texture3D;\n clearcoatRoughnessMap?: Texture3D;\n /** Light transmitted *through* the surface — glass, water. Blends for you. */\n transmission?: number;\n transmissionMap?: Texture3D;\n /** Wall thickness for transmission tinting. */\n thickness?: number;\n thicknessMap?: Texture3D;\n /** Volumetric absorption colour at {@link attenuationDistance}. */\n attenuationColor?: Color;\n attenuationDistance?: number;\n /** Index of refraction. 1.5 glass, 1.33 water, 2.42 diamond. */\n ior?: number;\n /** Retroreflective sheen — cloth, velvet, dust. */\n sheen?: number;\n sheenColor?: Color;\n sheenRoughness?: number;\n /** Thin-film interference — soap bubbles, oil slicks, beetle shells. */\n iridescence?: number;\n iridescenceIOR?: number;\n iridescenceThicknessRange?: readonly [number, number];\n /** Strength/tint of the dielectric specular highlight. */\n specularIntensity?: number;\n specularColor?: Color;\n /** Anisotropic (brushed-metal) highlight stretching. */\n anisotropy?: number;\n /** Degrees. */\n anisotropyRotation?: number;\n}\n\n/** Classic Blinn-Phong: a diffuse term plus a tight specular highlight. */\nexport interface PhongMaterial3D extends MaterialCommon3D, CommonMaps3D, Emissive3D {\n type: \"phong\";\n color?: Color;\n specular?: Color;\n /** Highlight tightness. Higher is smaller and sharper. */\n shininess?: number;\n specularMap?: Texture3D;\n /** **Structural.** */\n shading?: Shading3D;\n}\n\n/** Diffuse-only Lambertian shading. Cheap; good for matte and unlit-ish looks. */\nexport interface LambertMaterial3D extends MaterialCommon3D, CommonMaps3D, Emissive3D {\n type: \"lambert\";\n color?: Color;\n /** **Structural.** */\n shading?: Shading3D;\n}\n\n/** Banded cel shading. `gradientMap` controls the steps. */\nexport interface ToonMaterial3D extends MaterialCommon3D, CommonMaps3D, Emissive3D {\n type: \"toon\";\n color?: Color;\n gradientMap?: Texture3D;\n}\n\n/** Surface normals as RGB. A debugging workhorse. */\nexport interface NormalMaterial3D extends MaterialCommon3D {\n type: \"normal\";\n /** **Structural.** */\n shading?: Shading3D;\n}\n\n/** Depth as greyscale. For debugging and custom depth passes. */\nexport interface DepthMaterial3D extends MaterialCommon3D {\n type: \"depth\";\n}\n\n/** Lit by a pre-baked sphere image. Very cheap, very stylizable. */\nexport interface MatcapMaterial3D extends MaterialCommon3D {\n type: \"matcap\";\n color?: Color;\n matcap?: Texture3D;\n map?: Texture3D;\n normalMap?: Texture3D;\n normalScale?: number | Vector2;\n}\n\n/** Shading for a `points` cloud. */\nexport interface PointsMaterial3D extends MaterialCommon3D {\n type: \"points\";\n color?: Color;\n size?: number;\n /** Shrink distant points with perspective. Default true. */\n sizeAttenuation?: boolean;\n map?: Texture3D;\n alphaMap?: Texture3D;\n}\n\n/** Shading for a `line`. `width` is capped at 1px by most WebGL implementations and **nothing substitutes a mesh-backed line**; draw a `tube` for a thick one. */\nexport interface LineBasicMaterial3D extends MaterialCommon3D {\n type: \"lineBasic\";\n color?: Color;\n width?: number;\n}\n\n/** A dashed line. Requires computed line distances, which the renderer handles. */\nexport interface LineDashedMaterial3D extends MaterialCommon3D {\n type: \"lineDashed\";\n color?: Color;\n width?: number;\n dashSize?: number;\n gapSize?: number;\n /** Offset along the line — animate for a marching-ants effect. */\n scale?: number;\n}\n\n/** Shading for a camera-facing `sprite`. */\nexport interface SpriteMaterial3D extends MaterialCommon3D {\n type: \"sprite\";\n color?: Color;\n map?: Texture3D;\n /** Degrees. */\n rotation?: number;\n}\n\n/** Receives shadows onto an otherwise invisible surface. For AR-style grounding. */\nexport interface ShadowMaterial3D extends MaterialCommon3D {\n type: \"shadow\";\n color?: Color;\n}\n\n/** A shader uniform value. Narrow on purpose: plain, inspectable, interpolable data keeps a shader-driven scene seekable. */\nexport type Uniform3D =\n | number\n | boolean\n | Color\n | Vector2\n | Vector3\n | { x: number; y: number; z: number; w: number }\n | readonly number[]\n | Texture3D;\n\n/** Raw GLSL, both stages. Uniform **values** are cheap in-place writes; uniform *names* and the shader **source** are structural (changing either recompiles). {@link extends} is declared but **not read yet**: a shader always replaces the model, so scene lighting, shadows and fog don't reach it (the first material setting it warns in development). */\nexport interface ShaderMaterial3D extends MaterialCommon3D {\n type: \"shader\";\n /** Vertex stage source. */\n vertex: string;\n /** Fragment stage source. */\n fragment: string;\n uniforms?: Readonly<Record<string, Uniform3D>>;\n /** `#define`s injected ahead of both stages. **Structural.** */\n defines?: Readonly<Record<string, string | number | boolean>>;\n /** Wraps a built-in shading model so scene lighting, shadows and fog still apply; null (default) is a raw shader. **Not implemented**: no backend reads it. */\n extends?: \"standard\" | \"basic\" | \"phong\" | null;\n /** Skip three's automatic attribute/uniform prelude (a raw shader). */\n raw?: boolean;\n}\n\n/** Every material a drawable can be shaded with. Discriminated on `type`. */\nexport type Material3D =\n | BasicMaterial3D\n | StandardMaterial3D\n | PhysicalMaterial3D\n | PhongMaterial3D\n | LambertMaterial3D\n | ToonMaterial3D\n | NormalMaterial3D\n | DepthMaterial3D\n | MatcapMaterial3D\n | PointsMaterial3D\n | LineBasicMaterial3D\n | LineDashedMaterial3D\n | SpriteMaterial3D\n | ShadowMaterial3D\n | ShaderMaterial3D;\n\n/** Fields the renderer writes in place without recompiling; everything else is structural and rebuilds the material. Shared by the reconciler and the `MeshShorthand` desugarer so they can't disagree about what is cheap. */\nexport const MUTABLE_MATERIAL_KEYS: readonly string[] = [\n \"color\", \"opacity\", \"visible\", \"emission\", \"emissionStrength\",\n \"roughness\", \"metalness\", \"shininess\", \"specular\", \"reflectivity\",\n \"clearcoat\", \"clearcoatRoughness\", \"transmission\", \"thickness\", \"ior\",\n \"sheen\", \"sheenColor\", \"sheenRoughness\", \"iridescence\", \"iridescenceIOR\",\n \"specularIntensity\", \"specularColor\", \"anisotropy\", \"anisotropyRotation\",\n \"attenuationColor\", \"attenuationDistance\",\n \"aoMapIntensity\", \"lightMapIntensity\", \"envMapIntensity\",\n \"normalScale\", \"displacementScale\", \"displacementBias\",\n \"size\", \"width\", \"dashSize\", \"gapSize\", \"scale\", \"rotation\",\n \"depthWrite\", \"depthTest\", \"polygonOffsetFactor\", \"polygonOffsetUnits\",\n];\n\n/** Fields that change the compiled shader program: changing one forces a rebuild, so never tween them (the renderer warns when one changes repeatedly). `transparent` is also derived, but flips at most once per material (the first frame a fade leaves full opacity) and the renderer latches it; see `needsBlending`. */\nexport const STRUCTURAL_MATERIAL_KEYS: readonly string[] = [\n \"transparent\", \"alphaTest\", \"faces\", \"wireframe\", \"blend\",\n \"vertexColors\", \"toneMapped\", \"shading\", \"dithering\",\n \"polygonOffset\", \"raw\", \"extends\", \"defines\",\n];\n", "import { AudioRequest, busStopKey } from \"@/attributes/audio/request\";\nimport { effectsKey } from \"@/attributes/audio/effects/union\";\nimport { paramKey } from \"@/attributes/audio/ramp\";\nimport { transitionKey } from \"@/attributes/audio/transition\";\nimport { AssetRecord, Disposer, LoaderFn } from \"@/assets/record\";\nimport { AudioSink } from \"@/platform/audio-sink\";\nimport { StorageAdapter } from \"@/platform/storage-adapter\";\nimport { AssetTrack, AssetTimelineResult } from \"@/runtime/asset-timeline\";\n\n/** Coordinates asset loading and audio synchronization during playback over an {@link AssetTimelineResult}, delegating storage/audio work to platform adapters. */\nexport class AssetManager {\n private precomp: AssetTimelineResult;\n private readonly storageAdapter: StorageAdapter;\n private readonly audioDevice: AudioSink;\n\n /** `null` after a swap: whatever the device holds belongs to the previous precomp. */\n private lastAudioRequestKey: string | null = \"\";\n private lastAudioSrcs: ReadonlySet<string> | null = new Set();\n private audioFetching = new Map<string, Promise<void>>();\n /** Sources whose fetch or decode failed, with why, so they are not refetched every sync. A source leaves when no request in the window names it any more (and, once reported, when a new precomp arrives) so it is tried afresh when wanted. One that failed quietly (see {@link AudioRequest.optional}) survives a precomp: a video with no audio track would otherwise be fetched whole on every edit. */\n private audioFailed = new Map<string, unknown>();\n /** The failed sources already reported to {@link onError}. */\n private audioReported = new Set<string>();\n /** Sources a request in the last window asked for by name, not as a picture's own sound. */\n private audioRequired: ReadonlySet<string> = new Set();\n /** Keys of the loaders a track measures against, which no window may evict. */\n private layoutGateKeys: ReadonlySet<string>;\n private disposed = false;\n\n private loaderDisposers = new Map<string, Disposer>();\n /** In-flight loader runs, keyed by loader key, to dedupe concurrent calls. */\n private loaderInFlight = new Map<string, Promise<void>>();\n\n /** @param onError Told once per source when audio a request asked for cannot be fetched or decoded. Defaults to `console.error`. */\n constructor(\n precomp: AssetTimelineResult,\n storageAdapter: StorageAdapter,\n audioDevice: AudioSink,\n private readonly onError: (error: Error) => void = (error) => console.error(`[AssetManager] ${error.message}`),\n ) {\n this.precomp = precomp;\n this.layoutGateKeys = layoutGatesOf(precomp);\n this.storageAdapter = storageAdapter;\n this.audioDevice = audioDevice;\n }\n\n /** Swaps in a new precomp (a document swap), keeping warm loader disposers and in-flight audio fetches so a single-track edit doesn't refetch unchanged assets. Resets the audio signature to force a reschedule, including into an empty window (how removed audio stops). */\n setPrecomp(precomp: AssetTimelineResult): void {\n this.precomp = precomp;\n this.layoutGateKeys = layoutGatesOf(precomp);\n for (const src of this.audioReported) this.audioFailed.delete(src);\n this.audioReported.clear();\n this.lastAudioRequestKey = null;\n this.lastAudioSrcs = null;\n }\n\n /** Blocking load for seek and initial render: waits for every asset whose `cacheAt <= frame <= endFrame`, then schedules audio. */\n async loadAt(frame: number): Promise<void> {\n const jobs: Promise<void>[] = [];\n\n for (const [key, track] of this.precomp.assets) {\n if (track.record.type === 'loader') {\n const job = this.syncLoader(key, track, frame);\n if (job) jobs.push(job);\n continue;\n }\n if (track.cacheAt <= frame && track.record.endFrame >= frame) {\n jobs.push(this.storageAdapter.loadAsset(key, track.record));\n }\n }\n\n await Promise.all(jobs);\n if (this.audioDevice.schedulesAudio) this.syncAudio(frame);\n }\n\n /** Whether `key` — a loader key or a stored asset's — is resident now. */\n isReady(key: string): boolean {\n return this.loaderDisposers.has(key) || this.storageAdapter.isLoaded(key);\n }\n\n /** Loads `records` whatever their windows say: layout gates must be resident before a track measures regardless of the frame drawn. */\n async loadRecords(records: readonly AssetRecord[]): Promise<void> {\n await Promise.all(records.map((record) => record.type === 'loader'\n ? this.runLoader(record.src, record.load)\n : this.storageAdapter.loadAsset(record.src, record)));\n }\n\n /** Non-blocking prefetch after each render tick; fires loads for assets whose `cacheAt` window was reached. */\n prefetch(frame: number): void {\n for (const [key, track] of this.precomp.assets) {\n if (track.record.type === 'loader') {\n this.syncLoader(key, track, frame)?.catch(err => {\n console.error(`[AssetManager] loader failed for ${key}:`, err);\n });\n continue;\n }\n if (track.cacheAt <= frame && track.record.endFrame >= frame) {\n this.storageAdapter.loadAsset(key, track.record).catch(err => {\n console.error(`[AssetManager] prefetch failed for ${key}:`, err);\n });\n }\n }\n }\n\n /** Drives one loader toward the state `frame` requires: inside `[cacheAt, discardAt]` run it (deduped, skipped once loaded), outside dispose it if loaded. Returns the in-flight promise a blocking caller can await, else `undefined`. */\n private syncLoader(key: string, track: AssetTrack, frame: number): Promise<void> | undefined {\n if (track.record.type !== 'loader') return undefined;\n const discardAt = track.discardAt ?? Infinity;\n const inWindow = track.cacheAt <= frame && frame <= discardAt;\n\n if (!inWindow) {\n // A layout gate is loaded by `loadRecords` whatever frame is drawn; disposing it here made `isReady` false and the next frame load it again.\n if (this.layoutGateKeys.has(key)) return undefined;\n const dispose = this.loaderDisposers.get(key);\n if (dispose) {\n this.loaderDisposers.delete(key);\n dispose();\n }\n return undefined;\n }\n\n return this.runLoader(key, track.record.load);\n }\n\n private runLoader(key: string, load: LoaderFn): Promise<void> | undefined {\n if (this.loaderDisposers.has(key)) return undefined;\n const existing = this.loaderInFlight.get(key);\n if (existing) return existing;\n\n const job = load()\n .then(disposer => {\n // A loader resolving nothing keeps its result resident on purpose (see `LoaderFn`); a no-op disposer keeps `loaderDisposers.has(key)` the single \"already loaded\" test.\n this.loaderDisposers.set(key, disposer ?? NO_DISPOSE);\n })\n .finally(() => {\n this.loaderInFlight.delete(key);\n });\n this.loaderInFlight.set(key, job);\n return job;\n }\n\n dispose(): void {\n for (const dispose of this.loaderDisposers.values()) dispose();\n this.loaderDisposers.clear();\n this.loaderInFlight.clear();\n this.disposed = true;\n }\n\n /** Pushes the current audio working set to the AudioSink after each render tick. */\n syncAudio(frame: number): void {\n const currentTime = frame / this.precomp.fps;\n\n const inWindow: AudioRequest[] = [];\n const srcs = new Set<string>();\n const required = new Set<string>();\n const seen = new Set<string>();\n\n const consider = (req: AudioRequest, offsetSecs: number): void => {\n const globalStart = offsetSecs + req.startAt;\n const globalEnd = offsetSecs + req.endAt;\n\n if (globalEnd < currentTime || globalStart > currentTime + 10) return;\n // Ahead of the dedupe: the flag is not part of a request's identity.\n if (!req.optional) required.add(req.src);\n\n const stableId = stableKey(req, offsetSecs);\n if (seen.has(stableId)) return;\n seen.add(stableId);\n\n inWindow.push({\n ...req,\n id: stableId,\n startAt: globalStart,\n endAt: globalEnd,\n // A bus's span is in its request's seconds, so it moves with it.\n ...(req.bus && {\n bus: req.bus.map((s) => ({ ...s, startAt: offsetSecs + s.startAt, endAt: offsetSecs + s.endAt })),\n }),\n });\n srcs.add(req.src);\n };\n\n for (const track of this.precomp.tracks) {\n const offsetSecs = track.startFrame / this.precomp.fps;\n for (const req of track.audioRequests) consider(req, offsetSecs);\n }\n\n this.audioRequired = required;\n for (const src of srcs) {\n if (!this.audioDevice.has(src) && !this.audioFetching.has(src) && !this.audioFailed.has(src)) {\n const job = this.storageAdapter.fetchAudioData(src)\n .then(data => this.audioDevice.append(src, data))\n .catch(cause => this.failAudio(src, cause))\n .finally(() => this.audioFetching.delete(src));\n this.audioFetching.set(src, job);\n }\n }\n // A failed source nothing asks for any more is forgotten so it is tried afresh when wanted; one that failed quietly is reported when a request for its sound arrives.\n for (const [src, cause] of this.audioFailed) {\n if (!srcs.has(src)) {\n this.audioFailed.delete(src);\n this.audioReported.delete(src);\n } else if (required.has(src)) {\n this.reportAudio(src, cause);\n }\n }\n\n const requestKey = audioSignature(inWindow);\n if (requestKey !== this.lastAudioRequestKey) {\n this.audioDevice.schedule(inWindow);\n this.lastAudioRequestKey = requestKey;\n }\n if (this.lastAudioSrcs === null || !setsEqual(this.lastAudioSrcs, srcs)) {\n this.audioDevice.retain(srcs);\n this.lastAudioSrcs = srcs;\n }\n }\n\n /** Record that `src` could not be loaded, and say so if a request asked for its sound. */\n private failAudio(src: string, cause: unknown): void {\n if (this.disposed) return;\n this.audioFailed.set(src, cause);\n if (this.audioRequired.has(src)) this.reportAudio(src, cause);\n }\n\n /** Say that `src` could not be loaded, once, until it is wanted afresh. */\n private reportAudio(src: string, cause: unknown): void {\n if (this.audioReported.has(src)) return;\n this.audioReported.add(src);\n const message = cause instanceof Error ? cause.message : String(cause);\n this.onError(new Error(`audio \"${src}\" could not be loaded: ${message}`, { cause }));\n }\n}\n\nfunction layoutGatesOf(precomp: AssetTimelineResult): ReadonlySet<string> {\n const keys = new Set<string>();\n for (const track of precomp.tracks) for (const key of track.layoutGates ?? []) keys.add(key);\n return keys;\n}\n\n/** Stand-in for a loader that resolved nothing — see the note in {@link AssetManager.syncLoader}. */\nconst NO_DISPOSE: Disposer = () => { };\n\n/** A deterministic key for an audio request's playback identity, including its effects, ramps, transitions and bus chain: editing any changes what it sounds like, so the device must stop the stale source and rebuild the graph. */\nfunction stableKey(req: AudioRequest, clipOffsetSecs: number): string {\n return `${req.src}|${clipOffsetSecs + req.startAt}|${clipOffsetSecs + req.endAt}|${req.trimStart}|${req.trimEnd ?? \"_\"}|${req.loop ? 1 : 0}|${paramKey(req.volume)}|${paramKey(req.speed)}|${req.sourceLength ?? \"_\"}|${effectsKey(req.effects)}|${transitionKey(req.transitionIn)}|${transitionKey(req.transitionOut)}|${busKey(req.bus)}`;\n}\n\nfunction busKey(bus: AudioRequest[\"bus\"]): string {\n if (!bus || bus.length === 0) return \"\";\n return bus.map(busStopKey).join(\">\");\n}\n\n/** Produce a stable hash of the active audio request set to detect scheduling changes. */\nfunction audioSignature(reqs: readonly AudioRequest[]): string {\n if (reqs.length === 0) return \"\";\n return reqs.map(r => r.id).sort().join(\"\\n\");\n}\n\nfunction setsEqual(a: ReadonlySet<string>, b: ReadonlySet<string>): boolean {\n if (a.size !== b.size) return false;\n for (const v of a) if (!b.has(v)) return false;\n return true;\n}\n", "import type { AssetCatalog } from \"./catalog\";\nimport type { LoaderFn } from \"./record\";\nimport type { FillResolved } from \"@/attributes/shape/fill/union\";\nimport type { NodeEffect } from \"@/attributes/shape/effects/union\";\nimport type { Node } from \"@/components/trees/node/node\";\nimport { declareFill } from \"@/attributes/shape/fill/registry\";\nimport { declareEffect } from \"@/attributes/shape/effects/registry\";\nimport { declareTree } from \"@/components/trees/node/node-walk\";\n\n/** Whether an asset has to be resident before layout measures, or only before a frame draws. */\nexport type AssetGate = \"layout\" | \"render\";\n\nexport type AssetDecl =\n | { type: \"image\"; src: string }\n | { type: \"video\"; src: string; trimStart: number; trimEnd: number }\n | { type: \"font\"; family: string; weight: number }\n | { type: \"loader\"; key: string; load: LoaderFn; gate: AssetGate };\n\n/** What a node's `declareAssets` states its needs into. A declaration must be a pure function of the props and context it reads (never `layoutBounds`, `time` or writes) because the runtime re-runs it only when something it read changes. Deduped by {@link assetKey}. */\nexport interface AssetScope {\n readonly catalog: AssetCatalog;\n image(src: string): void;\n video(src: string, trim?: { start?: number; end?: number }): void;\n /** Gates layout: text is measured against the face. */\n font(family: string, weight?: number | string): void;\n /** `gate` defaults to `\"render\"`; pass `\"layout\"` for a load measurement depends on. */\n loader(key: string, load: LoaderFn, options?: { gate?: AssetGate }): void;\n fill(fills: FillResolved | readonly FillResolved[]): void;\n effects(effects: readonly NodeEffect[]): void;\n /** A detached subtree this node draws (a `Tex.surface` node source), declared as part of this node. */\n subtree(node: Node): void;\n}\n\n/** Fonts key by family alone: `loadFont` registers every weight at once and a variable weight renders through `fontVariations`, so a weight in the key would mint an entry per frame of a weight tween. */\nexport function assetKey(decl: AssetDecl): string {\n switch (decl.type) {\n case \"image\":\n case \"video\":\n return decl.src;\n case \"font\":\n return decl.family;\n case \"loader\":\n return decl.key;\n }\n}\n\n/** Anything unparseable lands on 400, which is what an unspecified weight means anyway. */\nexport function normalizeWeight(weight: number | string | undefined): number {\n if (typeof weight === \"number\") return Number.isFinite(weight) ? weight : 400;\n if (typeof weight === \"string\") return parseInt(weight, 10) || 400;\n return 400;\n}\n\nexport interface AssetDeclarationOptions {\n /** Binds a detached subtree (catalog, context, clock) before it declares. */\n bindSubtree?: (node: Node) => void;\n /** Replaces the default {@link declareTree} walk over a subtree. */\n onSubtree?: (node: Node, scope: AssetScope) => void;\n}\n\n/** The {@link AssetScope} that collects: one declaration pass, keyed and validated. Unknown images and videos throw here, against the node that declared them. */\nexport class AssetDeclaration implements AssetScope {\n readonly catalog: AssetCatalog;\n\n constructor(catalog: AssetCatalog, options: AssetDeclarationOptions = {}) {\n this.catalog = catalog;\n this._options = options;\n }\n\n get declarations(): ReadonlyMap<string, AssetDecl> {\n return this._decls;\n }\n\n // An empty `src` is an unset media slot — it paints the checkerboard, not a\n // missing asset — so it declares nothing.\n image(src: string): void {\n if (!src || this._decls.has(src)) return;\n this.catalog.getImageMeta(src);\n this._decls.set(src, { type: \"image\", src });\n }\n\n video(src: string, trim?: { start?: number; end?: number }): void {\n if (!src || this._decls.has(src)) return;\n this.catalog.getVideoMeta(src);\n this._decls.set(src, {\n type: \"video\",\n src,\n trimStart: trim?.start ?? 0,\n trimEnd: trim?.end ?? this.catalog.getVideoDuration(src),\n });\n }\n\n font(family: string, weight?: number | string): void {\n if (!family || this._decls.has(family)) return;\n this._decls.set(family, { type: \"font\", family, weight: normalizeWeight(weight) });\n }\n\n loader(key: string, load: LoaderFn, options?: { gate?: AssetGate }): void {\n const gate = options?.gate ?? \"render\";\n const existing = this._decls.get(key);\n if (existing === undefined) {\n this._decls.set(key, { type: \"loader\", key, load, gate });\n return;\n }\n if (existing.type !== \"loader\") return;\n if (existing.load !== load && process.env.NODE_ENV !== \"production\") {\n console.warn(\n `[assets] Loader \"${key}\" was declared with a different load function; the first is kept. ` +\n `Hoist the function so every declaration of the key hands over the same one.`,\n );\n }\n // Layout is the stricter gate, so it wins whichever declaration asked first.\n if (gate === \"layout\" && existing.gate !== \"layout\") {\n this._decls.set(key, { ...existing, gate });\n }\n }\n\n fill(fills: FillResolved | readonly FillResolved[]): void {\n if (!fills) return;\n if (!Array.isArray(fills)) {\n declareFill(fills as FillResolved, this);\n return;\n }\n for (const fill of fills as readonly FillResolved[]) declareFill(fill, this);\n }\n\n effects(effects: readonly NodeEffect[]): void {\n if (!effects) return;\n for (const effect of effects) declareEffect(effect, this);\n }\n\n subtree(node: Node): void {\n this._subtrees ??= new Set();\n if (this._subtrees.has(node)) return;\n this._subtrees.add(node);\n this._options.bindSubtree?.(node);\n if (this._options.onSubtree) this._options.onSubtree(node, this);\n else declareTree(node, this);\n }\n\n private readonly _options: AssetDeclarationOptions;\n private readonly _decls = new Map<string, AssetDecl>();\n private _subtrees: Set<Node> | undefined;\n}\n", "/** Event-loop yielding for work that must stay interruptible: a long synchronous loop cannot be cancelled since nothing can run to *ask* it to stop. `StateEvaluator`'s backward-seek replay yields periodically through {@link yieldToScheduler}, which lets a newer seek supersede one in flight. Core has no DOM, so every mechanism is feature-detected and works in a browser, Node and vitest. */\n\n/** Monotonic-ish clock in milliseconds. `performance` is absent in some hosts. */\nexport function now(): number {\n return typeof performance !== \"undefined\" && typeof performance.now === \"function\"\n ? performance.now()\n : Date.now();\n}\n\ntype SchedulerWithYield = { yield?: () => Promise<void> };\n\n/** `scheduler.yield()` when the host has it (Chrome 129+), else undefined. */\nfunction nativeYield(): (() => Promise<void>) | undefined {\n const s = (globalThis as { scheduler?: SchedulerWithYield }).scheduler;\n return typeof s?.yield === \"function\" ? s.yield.bind(s) : undefined;\n}\n\n/** One shared `MessageChannel`: a channel per yield would allocate (and leak until GC) thousands of ports over one scrub. Callbacks queue FIFO and each posted message drains one, so resolution order matches call order. */\nlet channel: MessageChannel | null = null;\nconst queue: (() => void)[] = [];\n\nfunction messageChannelYield(): Promise<void> | null {\n if (typeof MessageChannel !== \"function\") return null;\n if (!channel) {\n channel = new MessageChannel();\n channel.port1.onmessage = () => queue.shift()?.();\n // Node keeps the event loop alive for an open port, which would hang vitest on exit; browsers have no unref.\n (channel.port1 as unknown as { unref?: () => void }).unref?.();\n (channel.port2 as unknown as { unref?: () => void }).unref?.();\n }\n return new Promise<void>(resolve => {\n queue.push(resolve);\n channel!.port2.postMessage(null);\n });\n}\n\n/**\n * Yields to the event loop so pending input, timers and rendering run before the caller resumes. A **macrotask**, not a\n * microtask (`await Promise.resolve()` drains in the same task and starves what we yield for); not\n * `requestAnimationFrame` either, which caps at the display rate and stops in a background tab, stalling headless\n * export and tests. Preference: `scheduler.yield()` (continuation priority, so a sliced task isn't starved), then\n * `MessageChannel` (a true unclamped macrotask), then `setTimeout(0)` (clamps to ~4 ms once nested).\n */\nexport function yieldToScheduler(): Promise<void> {\n const native = nativeYield();\n if (native) return native();\n return messageChannelYield() ?? new Promise<void>(resolve => setTimeout(resolve, 0));\n}\n\n/** Drop the shared channel. Tests only — the next yield lazily rebuilds it. */\nexport function __resetSchedulerForTests(): void {\n channel?.port1.close();\n channel?.port2.close();\n channel = null;\n queue.length = 0;\n}\n", "export type FrameSpec =\n | { kind: 'frame'; frame: number }\n | { kind: 'first' }\n | { kind: 'last' };\n\n/** A few ulps at any frame count a clip can reach. */\nconst FRAME_TOLERANCE = 1e-9;\n\n/**\n * `frame * (1 / fps)`, not `frame / fps`: the two disagree in the last bit, and every frame-to-time conversion\n * must be this one so a span boundary falls on the same side of a frame wherever it is asked.\n */\nexport function clipFrameToTime(frame: number, fps: number): number {\n return frame * (1 / fps);\n}\n\n/**\n * Within float error of a whole frame is that frame: `123 * (1 / 60)` times `60` is `122.99999999999999`, and\n * a floor or ceil of that is a frame off.\n */\nexport function clipTimeToFrame(seconds: number, fps: number): number {\n const frame = seconds * fps;\n const nearest = Math.round(frame);\n return Math.abs(frame - nearest) <= FRAME_TOLERANCE * Math.max(1, Math.abs(frame)) ? nearest : frame;\n}\n\nexport function frameSpecAtTime(seconds: number, fps: number): FrameSpec {\n return { kind: 'frame', frame: Math.round(clipTimeToFrame(seconds, fps)) };\n}\n", "import type { Track } from \"@/document/project\";\nimport type { NodeSpan } from \"@/document/types\";\nimport { clipFrameToTime, clipTimeToFrame } from \"./frame-time\";\n\n/** One track's span on the project timeline. `endFrame` is inclusive. */\nexport interface TrackSpan {\n id: string;\n /** Also paint order: first is at the back. */\n index: number;\n startFrame: number;\n endFrame: number;\n}\n\n/**\n * Rounded up, so a length off a frame boundary covers its last partial frame, and never less than one, so a\n * still is drawn.\n */\nexport function trackFrameCount(seconds: number, fps: number): number {\n if (typeof seconds !== \"number\" || !Number.isFinite(seconds)) return 1;\n return Math.max(1, Math.ceil(clipTimeToFrame(seconds, fps)));\n}\n\n/**\n * A start rounds to the nearest frame while a length rounds up: a start is a point, and flooring it would put\n * every track a frame early.\n */\nexport function placeTracks(tracks: readonly Track[], fps: number): TrackSpan[] {\n return tracks.map((track, index) => {\n const startFrame = Math.max(0, Math.round(clipTimeToFrame(track.startAt ?? 0, fps)));\n return { id: track.id, index, startFrame, endFrame: startFrame + trackFrameCount(track.duration, fps) - 1 };\n });\n}\n\n/** Not the sum of their lengths, since gaps and overlaps are both legal. */\nexport function totalFramesOf(spans: readonly { endFrame: number }[]): number {\n let total = 0;\n for (const span of spans) total = Math.max(total, span.endFrame + 1);\n return total;\n}\n\nexport function spansCovering(spans: readonly TrackSpan[], frame: number): TrackSpan[] {\n return spans.filter(span => frame >= span.startFrame && frame <= span.endFrame);\n}\n\n/** Clamped, so a frame held past the end shows where the track stops. */\nexport function frameTime(frame: number, fps: number, duration: number): number {\n return Math.min(clipFrameToTime(frame, fps), duration);\n}\n\n/** `null` when it covers none. */\nexport function spanFrames(\n span: Readonly<NodeSpan>,\n fps: number,\n frameCount: number,\n): { startFrame: number; endFrame: number } | null {\n const last = frameCount - 1;\n const at = (frame: number) => frameTime(frame, fps, Infinity);\n\n let startFrame = Math.min(last + 1, Math.max(0, Math.ceil(span.start * fps)));\n while (startFrame > 0 && at(startFrame - 1) >= span.start) startFrame--;\n while (startFrame <= last && at(startFrame) < span.start) startFrame++;\n\n let endFrame = last;\n if (span.end !== Infinity) {\n endFrame = Math.max(-1, Math.min(last, Math.ceil(span.end * fps)));\n while (endFrame >= 0 && at(endFrame) >= span.end) endFrame--;\n while (endFrame < last && at(endFrame + 1) < span.end) endFrame++;\n }\n return startFrame <= endFrame ? { startFrame, endFrame } : null;\n}\n", "import type { AssetCatalog } from \"@/assets/catalog\";\nimport type { Size2D } from \"@/attributes/layout/size\";\nimport { clipDocument } from \"@/document/audio\";\nimport type { Registry } from \"@/document/registry\";\nimport { ClipTimeline, type PlacedCommandInfo, type PlacedSound, type TimelineIssue } from \"@/document/timeline\";\nimport type { TimelinePatch } from \"@/document/timeline-patch\";\nimport type { PropSlot } from \"@/props/slot\";\nimport {\n effectiveSpans,\n ROOT_NODE_ID,\n type ClipDocument,\n type NodeSpan,\n type VisualDocument,\n} from \"@/document/types\";\nimport type { Node } from \"@/components/trees/node/node\";\nimport { applyEditorStates, type NodeEditorStates } from \"@/components/trees/node/node-editor-state\";\nimport { primeMotionTree, sampleTree } from \"@/components/trees/node/node-walk\";\nimport { Canvas2D } from \"@/components/trees/root/canvas2d-node\";\nimport { nodePath } from \"@/project/tree\";\nimport type { MeasureContext2D } from \"@/render/measure-context\";\nimport type { RenderPass2D } from \"@/render/render-context2d\";\nimport { ContextMap } from \"@/util/context\";\n\nexport interface RuntimeScope {\n registry: Registry;\n viewport: Size2D;\n fps: number;\n assets: AssetCatalog;\n measurer: MeasureContext2D;\n}\n\n/**\n * One track's clip, live: the viewport-sized {@link Canvas2D} it builds into and the timeline compiled over\n * it. Built once, then asked for a time. Nothing resets one (a caller needing a fresh tree builds a new\n * instance), so the measuring pass and the evaluator each hold their own instead of taking turns.\n */\nexport class ClipInstance {\n readonly canvas: Canvas2D;\n\n constructor(clip: ClipDocument, duration: number, private readonly _scope: RuntimeScope) {\n this._clip = clip;\n this._duration = duration;\n this._doc = lowered(clip);\n const { width, height } = _scope.viewport;\n /**\n * Seeded here because this canvas is the document's root row yet the one node no `Registry.instantiate` makes:\n * `ClipTimeline` applies that row's props with `set()`, which writes property fields only, so an unseeded root\n * would report a UUID no document row mentions.\n */\n this.canvas = new Canvas2D({ id: ROOT_NODE_ID, width, height, flow: \"freeform\" });\n this._timeline = new ClipTimeline(this._doc, _scope.registry, this.canvas);\n this._indexRows();\n }\n\n get duration(): number {\n return this._duration;\n }\n\n get clip(): ClipDocument {\n return this._clip;\n }\n\n /** See `ClipTimeline.compile`. `measurer` stands in for the scope's during the build only. */\n build(measurer: MeasureContext2D = this._scope.measurer): void {\n this.attach(0);\n this._timeline.build();\n this.sample();\n this.layout(measurer);\n this._timeline.compile(() => {\n this.sample();\n this.layout(measurer);\n });\n this.layout(measurer);\n }\n\n /**\n * `false` means the change needs a fresh instance (see `planTimelinePatch`); the tree is untouched then. A\n * throw leaves the tree unusable: dispose it and build fresh.\n */\n update(next: ClipDocument, duration: number): boolean {\n if (next === this._clip) {\n this._duration = duration;\n return true;\n }\n const patch = this.planUpdate(next);\n if (!patch) return false;\n this.applyUpdate(patch, next, duration);\n return true;\n }\n\n planUpdate(next: ClipDocument): TimelinePatch | null {\n return this._timeline.planUpdate(lowered(next));\n }\n\n applyUpdate(\n patch: TimelinePatch,\n next: ClipDocument,\n duration: number,\n measurer: MeasureContext2D = this._scope.measurer,\n ): void {\n this.attach(0);\n const relayout = () => {\n this.sample();\n this.layout(measurer);\n };\n this._timeline.applyUpdate(patch, relayout, relayout);\n this.layout(measurer);\n this._clip = next;\n this._doc = patch.next.doc;\n this._duration = duration;\n this._indexRows();\n }\n\n placedCommands(): readonly PlacedCommandInfo[] {\n return this._timeline.placedCommands();\n }\n\n issues(): TimelineIssue[] {\n return this._timeline.issues();\n }\n\n commandSounds(): PlacedSound[] {\n return this._timeline.commandSounds();\n }\n\n /** The presence is put back after. */\n atPresence<T>(seconds: number, read: () => T): T {\n const was = this._timeline.presenceTime;\n this._timeline.syncPresence(seconds);\n try {\n return read();\n } finally {\n this._timeline.syncPresence(was);\n }\n }\n\n evaluateAt(seconds: number, onWrite?: (index: number, slot: PropSlot<unknown>) => void): void {\n this._timeline.syncPresence(seconds);\n this._timeline.evaluateAt(seconds, onWrite);\n }\n\n attach(seconds: number, editor?: NodeEditorStates): void {\n this.canvas.attach({ assets: this._scope.assets, context: ContextMap.EMPTY, time: seconds });\n /**\n * Before layout, so a node that appeared this frame gets its editor state on that frame, and a hidden one is\n * out of the flow before it is measured.\n */\n applyEditorStates(this.canvas, editor);\n }\n\n layout(measurer: MeasureContext2D = this._scope.measurer): void {\n const { width, height } = this._scope.viewport;\n this.canvas.layout({ x: 0, y: 0, width, height }, measurer);\n }\n\n render(pass: RenderPass2D): void {\n this.canvas.render(pass);\n }\n\n sample(): void {\n sampleTree(this.canvas);\n }\n\n primeMotion(at: number): void {\n primeMotionTree(this.canvas, at);\n }\n\n node(rowId: string): Node | undefined {\n return this._timeline.liveNode(rowId);\n }\n\n baselineProps(rowId: string): Record<string, unknown> | undefined {\n return this._timeline.baselineProps(rowId);\n }\n\n rowSpans(): NodeSpan[] {\n return [...this._rows.values()].map((row) => row.span);\n }\n\n rowSpan(id: string): NodeSpan | undefined {\n return this._rows.get(id)?.span;\n }\n\n ownerKeyOf(node: Node): string | undefined {\n let below = \"\";\n for (let current: Node = node; ;) {\n if (current === this.canvas || this._timeline.liveNode(current.id) === current) {\n const row = current === this.canvas ? ROOT_NODE_ID : current.id;\n return below === \"\" ? row : `${row}/${below}`;\n }\n const parent = current.parent;\n if (!parent) return undefined;\n const index = parent._allChildren.indexOf(current);\n below = below === \"\" ? String(index) : `${index}.${below}`;\n current = parent;\n }\n }\n\n /** A composite-built node takes the nearest row ancestor's span. The canvas spans the clip. */\n spanOf(node: Node): NodeSpan | undefined {\n for (let current: Node | null = node; current; current = current.parent) {\n if (current === this.canvas) return { start: 0, end: this.duration };\n const span = this._rowSpan(current);\n if (span) return { ...span };\n }\n return undefined;\n }\n\n /**\n * Visit every mounted node, parents first, with its span, structural path and owner key: the nearest row's id\n * plus the path below that row for a composite-built node. A UUID changes on every build and a root path\n * whenever an earlier sibling enters or leaves; this does neither.\n */\n forEachOwner(visit: (node: Node, ownerKey: string, span: NodeSpan, path: string) => void): void {\n const walk = (node: Node, row: string, below: string, span: NodeSpan, path: string): void => {\n if (!node.mounted) return;\n const own = node === this.canvas ? undefined : this._rowSpan(node);\n if (own) {\n row = node.id;\n below = \"\";\n span = own;\n }\n visit(node, below === \"\" ? row : `${row}/${below}`, span, path);\n const children = node._allChildren;\n for (let i = 0; i < children.length; i++) {\n walk(children[i], row, below === \"\" ? String(i) : `${below}.${i}`, span, nodePath(path, i));\n }\n };\n walk(this.canvas, ROOT_NODE_ID, \"\", { start: 0, end: this.duration }, \"\");\n }\n\n dispose(): void {\n for (const child of this.canvas.children) child.dispose();\n this.canvas.dispose();\n }\n\n private _clip: ClipDocument;\n private _doc: VisualDocument;\n private _duration: number;\n private readonly _timeline: ClipTimeline;\n private readonly _rows = new Map<string, { parentId: string | null; span: NodeSpan }>();\n\n private _indexRows(): void {\n this._rows.clear();\n const spans = effectiveSpans(this._doc.nodes);\n for (const spec of this._doc.nodes) {\n if (spec.id === ROOT_NODE_ID) continue;\n this._rows.set(spec.id, { parentId: spec.parentId, span: spans.get(spec.id)! });\n }\n }\n\n /**\n * The parent is checked as well as the id, because a composite can hand its own id down to a child it builds.\n */\n private _rowSpan(node: Node): NodeSpan | undefined {\n const row = this._rows.get(node.id);\n if (!row) return undefined;\n const parent = node.parent;\n const placed = row.parentId === null || row.parentId === ROOT_NODE_ID\n ? parent === this.canvas\n : parent !== null && parent.id === row.parentId;\n return placed ? row.span : undefined;\n }\n}\n\nfunction lowered(clip: ClipDocument): VisualDocument {\n return clipDocument(clip);\n}\n", "import type { AssetRecord } from \"./record\";\nimport { assetKey, type AssetDecl } from \"./scope\";\n\nexport interface AssetSegment {\n key: string;\n decl: AssetDecl;\n startFrame: number;\n /** Inclusive. `Infinity` runs to the clip's end. */\n endFrame: number;\n}\n\nexport interface AssetDelta {\n /** Keys whose record appeared, disappeared, or changed window or content. */\n readonly keys: ReadonlySet<string>;\n}\n\ninterface OwnerSegments {\n declared: Map<string, AssetSegment[]>;\n /** Found missing at draw time rather than declared; cleared by the owner's next `setOwner`. */\n learned: Map<string, AssetSegment[]>;\n}\n\ninterface KeyEntry {\n record: AssetRecord;\n layout: boolean;\n}\n\nconst NO_OWNERS: ReadonlySet<string> = new Set();\n\n/** One clip's asset windows, per owner, in clip-local frames. Owners replace their segments wholesale, and a key's record (the union window over every owner that needs it) is recomputed only for keys an update touched. Records keep the {@link AssetRecord} shape so the manager, exporter and mixer read them unchanged. */\nexport class AssetIndex {\n constructor(frameCount: number) {\n this._frameCount = Math.max(0, frameCount);\n }\n\n setOwner(ownerKey: string, segments: readonly AssetSegment[]): AssetDelta {\n const touched = new Set<string>();\n const previous = this._owners.get(ownerKey);\n if (previous) this._unlink(ownerKey, previous, touched);\n\n const next: OwnerSegments = { declared: new Map(), learned: new Map() };\n for (const segment of segments) {\n if (!(segment.endFrame >= segment.startFrame)) continue;\n appendSegment(next.declared, { ...segment });\n }\n if (next.declared.size > 0) {\n this._owners.set(ownerKey, next);\n this._link(ownerKey, next, touched);\n } else {\n this._owners.delete(ownerKey);\n }\n return this._refresh(touched);\n }\n\n removeOwner(ownerKey: string): AssetDelta {\n const previous = this._owners.get(ownerKey);\n if (!previous) return { keys: new Set() };\n const touched = new Set<string>();\n this._unlink(ownerKey, previous, touched);\n this._owners.delete(ownerKey);\n return this._refresh(touched);\n }\n\n learn(ownerKey: string, decl: AssetDecl, frame: number): AssetDelta {\n const key = assetKey(decl);\n let owner = this._owners.get(ownerKey);\n if (!owner) {\n owner = { declared: new Map(), learned: new Map() };\n this._owners.set(ownerKey, owner);\n }\n const list = owner.learned.get(key) ?? [];\n const at = list.findIndex((s) => frame >= s.startFrame - 1 && frame <= s.endFrame + 1);\n if (at < 0) {\n list.push({ key, decl, startFrame: frame, endFrame: frame });\n } else {\n // Replaced rather than widened in place: `segmentsOf` hands these out.\n const hit = list[at];\n list[at] = {\n ...hit,\n startFrame: Math.min(hit.startFrame, frame),\n endFrame: Math.max(hit.endFrame, frame),\n };\n }\n owner.learned.set(key, list);\n let owners = this._byKey.get(key);\n if (!owners) this._byKey.set(key, (owners = new Set()));\n owners.add(ownerKey);\n return this._refresh(new Set([key]));\n }\n\n setFrameCount(frameCount: number): AssetDelta {\n const next = Math.max(0, frameCount);\n if (next === this._frameCount) return { keys: new Set() };\n this._frameCount = next;\n return this._refresh(new Set(this._byKey.keys()));\n }\n\n owners(key: string): ReadonlySet<string> {\n return this._byKey.get(key) ?? NO_OWNERS;\n }\n\n /** Declared segments, then learned ones. */\n segmentsOf(ownerKey: string): readonly AssetSegment[] {\n const owner = this._owners.get(ownerKey);\n if (!owner) return [];\n const out: AssetSegment[] = [];\n for (const list of owner.declared.values()) out.push(...list);\n for (const list of owner.learned.values()) out.push(...list);\n return out;\n }\n\n /** Declared segments only — what a partial re-declaration keeps the front of. */\n declaredSegmentsOf(ownerKey: string): readonly AssetSegment[] {\n const owner = this._owners.get(ownerKey);\n if (!owner) return [];\n const out: AssetSegment[] = [];\n for (const list of owner.declared.values()) out.push(...list);\n return out;\n }\n\n ownerKeys(): IterableIterator<string> {\n return this._owners.keys();\n }\n\n records(): ReadonlyMap<string, AssetRecord> {\n return this._records;\n }\n\n /** Fonts, and loaders any owner declared with `gate: \"layout\"`. */\n layoutGates(): readonly AssetRecord[] {\n if (this._layoutGates === null) {\n const gates: AssetRecord[] = [];\n for (const entry of this._entries.values()) {\n if (entry.layout) gates.push(entry.record);\n }\n this._layoutGates = gates;\n }\n return this._layoutGates;\n }\n\n private _frameCount: number;\n private readonly _owners = new Map<string, OwnerSegments>();\n private readonly _byKey = new Map<string, Set<string>>();\n private readonly _entries = new Map<string, KeyEntry>();\n private readonly _records = new Map<string, AssetRecord>();\n private _layoutGates: AssetRecord[] | null = null;\n\n private _link(ownerKey: string, owner: OwnerSegments, touched: Set<string>): void {\n for (const key of owner.declared.keys()) {\n let owners = this._byKey.get(key);\n if (!owners) this._byKey.set(key, (owners = new Set()));\n owners.add(ownerKey);\n touched.add(key);\n }\n }\n\n private _unlink(ownerKey: string, owner: OwnerSegments, touched: Set<string>): void {\n for (const map of [owner.declared, owner.learned]) {\n for (const key of map.keys()) {\n const owners = this._byKey.get(key);\n if (owners) {\n owners.delete(ownerKey);\n if (owners.size === 0) this._byKey.delete(key);\n }\n touched.add(key);\n }\n }\n }\n\n private _refresh(keys: ReadonlySet<string>): AssetDelta {\n const changed = new Set<string>();\n for (const key of keys) {\n const previous = this._entries.get(key);\n const next = this._compute(key);\n if (next === undefined) {\n if (previous === undefined) continue;\n this._entries.delete(key);\n this._records.delete(key);\n } else if (previous !== undefined && previous.layout === next.layout && sameRecord(previous.record, next.record)) {\n continue;\n } else {\n this._entries.set(key, next);\n this._records.set(key, next.record);\n }\n changed.add(key);\n }\n if (changed.size > 0) this._layoutGates = null;\n return { keys: changed };\n }\n\n private _compute(key: string): KeyEntry | undefined {\n const owners = this._byKey.get(key);\n if (!owners) return undefined;\n const last = this._frameCount - 1;\n let first: AssetSegment | undefined;\n let start = Infinity;\n let end = -Infinity;\n let layoutLoader = false;\n\n const visit = (list: AssetSegment[] | undefined): void => {\n if (!list) return;\n for (const segment of list) {\n const from = Math.max(0, segment.startFrame);\n const to = Math.min(last, segment.endFrame);\n if (to < from) continue;\n // The earliest segment speaks for the key.\n if (from < start) {\n start = from;\n first = segment;\n }\n if (to > end) end = to;\n if (segment.decl.type === \"loader\" && segment.decl.gate === \"layout\") layoutLoader = true;\n }\n };\n for (const ownerKey of owners) {\n const owner = this._owners.get(ownerKey);\n if (!owner) continue;\n visit(owner.declared.get(key));\n visit(owner.learned.get(key));\n }\n\n if (first === undefined) return undefined;\n return {\n record: recordOf(first.decl, start, end),\n layout: first.decl.type === \"font\" || layoutLoader,\n };\n }\n}\n\nfunction appendSegment(map: Map<string, AssetSegment[]>, segment: AssetSegment): void {\n const list = map.get(segment.key);\n if (list) list.push(segment);\n else map.set(segment.key, [segment]);\n}\n\nfunction recordOf(decl: AssetDecl, startFrame: number, endFrame: number): AssetRecord {\n switch (decl.type) {\n case \"image\":\n return { type: \"image\", startFrame, endFrame, src: decl.src };\n case \"video\":\n return {\n type: \"video\", startFrame, endFrame, src: decl.src,\n trimStart: decl.trimStart, trimEnd: decl.trimEnd,\n };\n case \"font\":\n return { type: \"font\", startFrame, endFrame, fontWeight: decl.weight, fontFamily: decl.family, src: decl.family };\n case \"loader\":\n return { type: \"loader\", src: decl.key, startFrame, endFrame, load: decl.load };\n }\n}\n\nfunction sameRecord(a: AssetRecord, b: AssetRecord): boolean {\n if (a.type !== b.type || a.src !== b.src || a.startFrame !== b.startFrame || a.endFrame !== b.endFrame) return false;\n switch (a.type) {\n case \"video\": {\n const v = b as typeof a;\n return a.trimStart === v.trimStart && a.trimEnd === v.trimEnd;\n }\n case \"font\":\n return a.fontWeight === (b as typeof a).fontWeight;\n case \"loader\":\n return a.load === (b as typeof a).load;\n default:\n return true;\n }\n}\n", "import type { AssetSegment } from \"@/assets/asset-index\";\nimport type { AssetCatalog } from \"@/assets/catalog\";\nimport { AssetDeclaration, type AssetDecl } from \"@/assets/scope\";\nimport type { NodeSpan } from \"@/document/types\";\nimport { Node as NodeClass, type Node } from \"@/components/trees/node/node\";\nimport { bindDetached, declareNode } from \"@/components/trees/node/node-walk\";\nimport {\n LAYOUT_SLOT,\n observeSlots,\n PRESENCE_PREFIX,\n slotLabel,\n STRUCTURE_SLOT,\n unobserved,\n type SlotObserver,\n} from \"@/props/observer\";\nimport { getPropSlot, type PropHost } from \"@/props/host\";\nimport type { PropSlot } from \"@/props/slot\";\nimport type { ClipInstance } from \"./clip-instance\";\nimport { frameTime, spanFrames } from \"./placement\";\n\nexport interface RefineOptions {\n fps: number;\n frameCount: number;\n catalog: AssetCatalog;\n /** A limited owner's segments start no earlier than its frame: the caller keeps what it had before. */\n owners?: ReadonlyMap<string, number>;\n /**\n * Like {@link owners}, for every owner a composite built below each row (keys a caller cannot know ahead).\n */\n below?: ReadonlyMap<string, number>;\n /** False only watches owners arrive, for a caller that wants `onArrive` alone. */\n declare?: boolean;\n /** Binds a `Tex.surface` source before it declares. Defaults to the declaring node's scope. */\n bindSubtree?: (node: Node) => void;\n onArrive?: (node: Node, ownerKey: string, span: NodeSpan, frame: number) => void;\n onPhase?: (phase: \"evaluate\" | \"declare\") => void;\n /** Declarations of earlier sweeps over the same catalog, taken back where what they read is unchanged. */\n memo?: DeclarationMemo;\n}\n\ninterface Remembered {\n ctor: unknown;\n /** Each slot read, as the owner key of its node and its prop name: what a rebuilt tree reproduces. */\n reads: readonly (readonly [host: string, name: string])[];\n values: readonly unknown[];\n decls: ReadonlyMap<string, AssetDecl>;\n}\n\n/**\n * What each owner declared on each frame a sweep ran it, so a later sweep (after an edit that rebuilt a node or\n * its commands but left what the declaration reads as it was) takes the result back instead of running the\n * declaration again: a declaration is a pure function of the slots it reads, and a 3D component's runs its whole\n * `render`. Valid for one catalog, since a declaration consults it.\n */\nexport class DeclarationMemo {\n recall(ownerKey: string, frame: number): Remembered | undefined {\n return this._byOwner.get(ownerKey)?.get(frame);\n }\n\n remember(ownerKey: string, frame: number, entry: Remembered): void {\n let frames = this._byOwner.get(ownerKey);\n if (!frames) this._byOwner.set(ownerKey, (frames = new Map()));\n frames.set(frame, entry);\n }\n\n forget(ownerKey: string): void {\n this._byOwner.delete(ownerKey);\n }\n\n private readonly _byOwner = new Map<string, Map<number, Remembered>>();\n}\n\nexport interface OwnerResult {\n ownerKey: string;\n nodeId: string | undefined;\n segments: AssetSegment[];\n deps: ReadonlySet<PropSlot<unknown>>;\n /** A throwing declaration: the owner keeps no segments, and `prop` names the last slot it read. */\n error?: { message: string; stack?: string; prop?: string };\n}\n\nexport interface RefineResult {\n owners: Map<string, OwnerResult>;\n readers: Map<PropSlot<unknown>, Set<string>>;\n}\n\n/**\n * A declaration is a pure function of the slots it reads, so an owner is declared at arrival and again only on\n * frames where something could have changed one of those slots: every frame a command writing one is active\n * (which catches a swap part-way through a command, and overlapping writers), the first frame after it ends,\n * and any frame the tree's presence or structure changed under a read. A redeclaration whose dependencies hold\n * the values they held reuses its result.\n *\n * Yields after each frame it evaluates. The instance must be built; the sweep leaves it at an arbitrary time.\n */\nexport function* refineAssets(instance: ClipInstance, options: RefineOptions): Generator<void, RefineResult, void> {\n const sweep = new Sweep(instance, options);\n while (sweep.step()) yield;\n return sweep.result();\n}\n\ninterface Placed {\n id: string;\n /** `to < from` when it lands between frames. */\n from: number;\n to: number;\n writes: Set<PropSlot<unknown>>;\n}\n\ninterface Declared {\n frame: number;\n decls: ReadonlyMap<string, AssetDecl>;\n}\n\ninterface OwnerState {\n key: string;\n node: Node;\n span: NodeSpan;\n /** The first frame this sweep may declare the owner on. */\n from: number;\n present: boolean;\n arrivedAt: number;\n arrived: boolean;\n intervals: [number, number][];\n history: Declared[];\n deps: PropSlot<unknown>[] | null;\n values: unknown[];\n /** A presence or structure slot it read was written: the values cannot tell. */\n stale: boolean;\n allDeps: Set<PropSlot<unknown>>;\n scheduled: Set<number>;\n rounds: number;\n error?: OwnerResult[\"error\"];\n}\n\nconst MAX_REQUEUES = 3;\n\nclass Sweep {\n constructor(private readonly _instance: ClipInstance, private readonly _options: RefineOptions) {\n this._last = _options.frameCount - 1;\n\n const { owners, below } = _options;\n const limited = owners !== undefined || below !== undefined;\n if (this._last < 0 || (limited && (owners?.size ?? 0) + (below?.size ?? 0) === 0)) return;\n if (limited) {\n this._start = Infinity;\n for (const from of [...owners?.values() ?? [], ...below?.values() ?? []]) {\n this._start = Math.min(this._start, Math.max(0, from));\n }\n }\n if (this._start > this._last) return;\n this._walked = this._start - 1;\n\n this._placed = _instance.placedCommands().map((p) => ({\n id: p.spec.id,\n ...this._activeFrames(p.holdFrom, p.start - p.holdFrom + p.duration),\n writes: new Set(p.writes),\n }));\n for (let i = 0; i < this._placed.length; i++) {\n for (const slot of this._placed[i].writes) this._addWriter(slot, i);\n }\n\n this._enqueue(this._start);\n for (const span of this._structureSpans()) {\n const frames = spanFrames(span, _options.fps, _options.frameCount);\n if (!frames) continue;\n this._structureFrame(frames.startFrame);\n this._structureFrame(frames.endFrame + 1);\n }\n for (const placed of this._placed) {\n if (![...placed.writes].some(isPseudo)) continue;\n this._forEachDueFrame(placed, this._start, (frame) => this._structureFrame(frame));\n }\n }\n\n step(): boolean {\n const frame = heapPop(this._heap);\n if (frame === undefined) return false;\n this._queued.delete(frame);\n this._frame = frame;\n this._dueTaken = false;\n this._evaluate(frame);\n this._declareDue(frame);\n return this._heap.length > 0;\n }\n\n result(): RefineResult {\n const owners = new Map<string, OwnerResult>();\n const readers = new Map<PropSlot<unknown>, Set<string>>();\n for (const owner of this._owners.values()) {\n const intervals = owner.present\n ? [...owner.intervals, [owner.arrivedAt, Infinity] as [number, number]]\n : owner.intervals;\n owners.set(owner.key, {\n ownerKey: owner.key,\n nodeId: owner.node.id,\n segments: owner.error ? [] : segmentsOf(owner.history, intervals),\n deps: owner.allDeps,\n ...(owner.error && { error: owner.error }),\n });\n for (const slot of owner.allDeps) {\n let keys = readers.get(slot);\n if (!keys) readers.set(slot, (keys = new Set()));\n keys.add(owner.key);\n }\n }\n for (const key of this._options.owners?.keys() ?? []) {\n if (!owners.has(key)) owners.set(key, { ownerKey: key, nodeId: undefined, segments: [], deps: new Set() });\n }\n return { owners, readers };\n }\n\n private readonly _last: number;\n private _start = 0;\n private _walked = -1;\n private _placed: Placed[] = [];\n private readonly _writers = new Map<PropSlot<unknown>, number[]>();\n private readonly _heap: number[] = [];\n private readonly _queued = new Set<number>();\n private readonly _due = new Map<number, Set<OwnerState>>();\n private readonly _structureFrames = new Set<number>();\n private readonly _owners = new Map<string, OwnerState>();\n private readonly _readers = new Map<PropSlot<unknown>, Set<OwnerState>>();\n private readonly _pseudo = new Set<PropSlot<unknown>>();\n /** Owners re-queued from before the frame being processed. */\n private readonly _rewound = new Set<OwnerState>();\n private _frame = -1;\n private _dueTaken = false;\n /** Read once: in Node, `process.env` is a lookup per access, and it sat on every declaration. */\n private readonly _dev = isDev();\n\n private readonly _presenceObserver: SlotObserver = {\n read: () => { },\n write: (slot) => { if (isPseudo(slot)) this._pseudo.add(slot); },\n };\n\n /**\n * Limited to named owners, only their rows' spans: an effective span already folds in every ancestor's, and\n * visiting every row's edges would make one edited node cost a walk of the clip.\n */\n private _structureSpans(): NodeSpan[] {\n const { owners, below } = this._options;\n if (owners === undefined && below === undefined) return this._instance.rowSpans();\n const rows = new Set<string>(below?.keys());\n for (const key of owners?.keys() ?? []) {\n const slash = key.indexOf(\"/\");\n rows.add(slash < 0 ? key : key.slice(0, slash));\n }\n const spans: NodeSpan[] = [];\n for (const row of rows) {\n const span = this._instance.rowSpan(row);\n if (span) spans.push(span);\n }\n return spans;\n }\n\n private _activeFrames(start: number, duration: number): { from: number; to: number } {\n const { fps } = this._options;\n const end = start + Math.max(0, duration);\n let from = Math.max(0, Math.ceil(start * fps));\n while (from > 0 && frameTime(from - 1, fps, Infinity) >= start) from--;\n while (frameTime(from, fps, Infinity) < start) from++;\n let to = Math.max(-1, Math.floor(end * fps));\n while (frameTime(to + 1, fps, Infinity) <= end) to++;\n while (to >= 0 && frameTime(to, fps, Infinity) > end) to--;\n return { from, to };\n }\n\n private _evaluate(frame: number): void {\n this._options.onPhase?.(\"evaluate\");\n const seconds = frameTime(frame, this._options.fps, this._instance.duration);\n /**\n * Clocks move only where the tree can change, and before it does, so a node is attached in the state it\n * arrives in. Declarations must not read them.\n */\n if (frame > this._walked && (frame === this._start || this._structureFrames.has(frame))) {\n this._instance.attach(seconds);\n }\n this._pseudo.clear();\n // Presence moves before the commands run, outside the observer `onWrite` reports through.\n observeSlots(this._presenceObserver, () => this._instance.evaluateAt(seconds, (index, slot) => {\n if (isPseudo(slot)) this._pseudo.add(slot);\n this._commandWrote(index, slot);\n }));\n\n /**\n * Presence only moves forward: a frame revisited for a re-queued owner reads what it recorded the first time.\n */\n if (frame <= this._walked) return;\n if (frame === this._start || this._pseudo.size > 0) this._reconcile(frame);\n for (const slot of this._pseudo) {\n for (const owner of this._readers.get(slot) ?? []) {\n owner.stale = true;\n this._queueOwner(owner, frame);\n }\n }\n this._walked = frame;\n }\n\n private _reconcile(frame: number): void {\n const seen = new Set<OwnerState>();\n this._instance.forEachOwner((node, key, span) => {\n const from = this._limitOf(key);\n if (from === undefined) return;\n let owner = this._owners.get(key);\n if (!owner) {\n owner = {\n key, node, span, from,\n present: false, arrivedAt: -1, arrived: false,\n intervals: [], history: [], deps: null, values: [], stale: true,\n allDeps: new Set(), scheduled: new Set(), rounds: 0,\n };\n this._owners.set(key, owner);\n }\n seen.add(owner);\n if (owner.node !== node) {\n owner.node = node;\n owner.stale = true;\n if (owner.present) this._queueOwner(owner, Math.max(frame, owner.from));\n }\n if (owner.present) return;\n owner.present = true;\n owner.arrivedAt = Math.max(frame, owner.from);\n owner.stale = true;\n this._queueOwner(owner, owner.arrivedAt);\n if (!owner.arrived) {\n owner.arrived = true;\n this._options.onArrive?.(node, key, span, frame);\n }\n });\n for (const owner of this._owners.values()) {\n if (!owner.present || seen.has(owner)) continue;\n if (frame - 1 >= owner.arrivedAt) owner.intervals.push([owner.arrivedAt, frame - 1]);\n owner.present = false;\n }\n }\n\n /** The first frame `key` may be declared on, or `undefined` when the sweep is limited to others. */\n private _limitOf(key: string): number | undefined {\n const { owners, below } = this._options;\n if (owners === undefined && below === undefined) return this._start;\n let from = owners?.get(key);\n if (below) {\n for (let slash = key.indexOf(\"/\"); slash >= 0; slash = key.indexOf(\"/\", slash + 1)) {\n const row = below.get(key.slice(0, slash));\n if (row !== undefined && (from === undefined || row < from)) from = row;\n }\n }\n return from;\n }\n\n private _declareDue(frame: number): void {\n this._dueTaken = true;\n const owners = this._due.get(frame);\n this._due.delete(frame);\n if (this._options.declare === false) return;\n for (const owner of owners ?? []) {\n if (owner.error || this._rewound.has(owner) || !presentAt(owner, frame)) continue;\n if (!owner.stale && unchanged(owner)) continue;\n this._declare(owner, frame);\n }\n // A rewound owner comes back to this frame after the ones it missed, so its history stays in frame order.\n for (const owner of this._rewound) this._queueOwner(owner, frame);\n this._rewound.clear();\n }\n\n private _declare(owner: OwnerState, frame: number): void {\n this._options.onPhase?.(\"declare\");\n if (this._recall(owner, frame)) return;\n const node = owner.node;\n const reads = new Set<PropSlot<unknown>>();\n const writes: PropSlot<unknown>[] = [];\n let lastRead: PropSlot<unknown> | undefined;\n let readLayout = false;\n let readClock = false;\n let bound = false;\n const bind = this._options.bindSubtree ?? ((sub: Node) => bindDetached(node, sub));\n const declaration = new AssetDeclaration(this._options.catalog, {\n bindSubtree: (sub) => {\n bound = true;\n unobserved(() => bind(sub));\n },\n });\n\n try {\n observeSlots({\n read: (slot) => {\n reads.add(slot);\n lastRead = slot;\n if (slot._name === LAYOUT_SLOT) readLayout = true;\n },\n write: (slot) => { writes.push(slot); },\n clock: () => { readClock = true; },\n }, () => declareNode(node, declaration));\n } catch (err) {\n const e = err instanceof Error ? err : new Error(String(err));\n owner.error = { message: e.message, stack: e.stack, ...(lastRead && { prop: slotLabel(lastRead) }) };\n return;\n }\n\n if (this._dev) {\n const type = node.constructor.name;\n if (writes.length > 0) {\n const labels = [...new Set(writes.map(slotLabel))].join(\", \");\n warnOnce(`${type}:write:${labels}`,\n `[assets] ${type} wrote ${labels} while declaring its assets. A declaration is re-run only ` +\n `when something it read changes, so a write there is a frame-order dependency.`);\n }\n if (readLayout) {\n warnOnce(`${type}:layout`,\n `[assets] ${type}.declareAssets read layoutBounds. Declarations run without layout; ` +\n `decode size follows the draw, so declare the asset without a size.`);\n }\n if (readClock) {\n warnOnce(`${type}:clock`,\n `[assets] ${type}.declareAssets read time. Declarations are re-run only when a prop ` +\n `they read changes, so anything following the clock is missed between those frames.`);\n }\n }\n\n const deps = [...reads];\n const values = deps.map((slot) => slot.get());\n const memo = this._options.memo;\n if (memo && !bound && !readLayout && !readClock && writes.length === 0) {\n const named = this._named(owner, deps);\n if (named) {\n memo.remember(owner.key, frame, {\n ctor: node.constructor, reads: named, values, decls: declaration.declarations,\n });\n }\n }\n this._settle(owner, frame, deps, values, declaration.declarations);\n }\n\n /** A declaration this owner made on `frame` in an earlier sweep, when every slot it read holds what it held. */\n private _recall(owner: OwnerState, frame: number): boolean {\n const entry = this._options.memo?.recall(owner.key, frame);\n if (!entry || entry.ctor !== owner.node.constructor) return false;\n const deps: PropSlot<unknown>[] = [];\n const values: unknown[] = [];\n for (let i = 0; i < entry.reads.length; i++) {\n const [host, name] = entry.reads[i];\n const node = host === owner.key ? owner.node : this._owners.get(host)?.node;\n const slot = node && getPropSlot(node as unknown as PropHost, name);\n if (!slot) return false;\n const value = unobserved(() => slot.get());\n if (!sameValue(value, entry.values[i])) return false;\n deps.push(slot);\n values.push(value);\n }\n this._settle(owner, frame, deps, values, entry.decls);\n return true;\n }\n\n /** `null` when a read cannot be named again in a rebuilt tree: a slot of no owner, presence or structure. */\n private _named(owner: OwnerState, deps: readonly PropSlot<unknown>[]): [string, string][] | null {\n const out: [string, string][] = [];\n for (const slot of deps) {\n const host = slot._host;\n if (!(host instanceof NodeClass) || isPseudo(slot)) return null;\n const key = host === owner.node ? owner.key : this._instance.ownerKeyOf(host);\n if (key === undefined) return null;\n out.push([key, slot._name]);\n }\n return out;\n }\n\n private _settle(\n owner: OwnerState,\n frame: number,\n deps: PropSlot<unknown>[],\n values: unknown[],\n decls: ReadonlyMap<string, AssetDecl>,\n ): void {\n owner.stale = false;\n owner.deps = deps;\n owner.values = values;\n for (const slot of deps) {\n if (owner.allDeps.has(slot)) continue;\n owner.allDeps.add(slot);\n let set = this._readers.get(slot);\n if (!set) this._readers.set(slot, (set = new Set()));\n set.add(owner);\n }\n\n const previous = owner.history[owner.history.length - 1];\n if (!previous || previous.frame < owner.arrivedAt || !sameDecls(previous.decls, decls)) {\n owner.history.push({ frame, decls });\n }\n this._scheduleWriters(owner, frame + 1);\n }\n\n private _scheduleWriters(owner: OwnerState, from: number): void {\n for (const slot of owner.deps ?? []) {\n const writers = this._writers.get(slot);\n if (!writers) continue;\n for (const index of writers) {\n if (owner.scheduled.has(index)) continue;\n owner.scheduled.add(index);\n this._forEachDueFrame(this._placed[index], from, (frame) => this._queueOwner(owner, frame));\n }\n }\n }\n\n private _forEachDueFrame(placed: Placed, from: number, visit: (frame: number) => void): void {\n const first = Math.max(from, placed.from);\n const last = Math.min(this._last, placed.to);\n for (let frame = first; frame <= last; frame++) visit(frame);\n const after = Math.max(placed.to + 1, placed.from);\n if (after >= from && after <= this._last) visit(after);\n }\n\n /**\n * A command wrote a slot compile did not see it write. Its readers may have missed every frame of it, so each\n * is re-queued from where the command starts.\n */\n private _commandWrote(index: number, slot: PropSlot<unknown>): void {\n const placed = this._placed[index];\n if (!placed || placed.writes.has(slot)) return;\n placed.writes.add(slot);\n this._addWriter(slot, index);\n\n if (this._dev) {\n warnOnce(`command:${placed.id}:${slotLabel(slot)}`,\n `[assets] Command ${placed.id} wrote ${slotLabel(slot)} at frame ${this._frame}, which compile did not ` +\n `record it writing. Owners reading it are re-declared over the command's span.`);\n }\n for (const owner of this._readers.get(slot) ?? []) this._requeue(owner, Math.max(placed.from, owner.from), placed.id);\n }\n\n private _requeue(owner: OwnerState, from: number, commandId: string): void {\n if (owner.error) return;\n if (from > this._frame) {\n this._scheduleWriters(owner, from);\n return;\n }\n if (from === this._frame) {\n this._queueOwner(owner, from);\n return;\n }\n if (owner.rounds >= MAX_REQUEUES) {\n if (this._dev) {\n warnOnce(`requeue:${owner.key}`,\n `[assets] ${owner.key} was re-queued ${MAX_REQUEUES} times (last by command ${commandId}); ` +\n `its asset windows may be incomplete.`);\n }\n return;\n }\n owner.rounds++;\n owner.history = owner.history.filter((entry) => entry.frame < from);\n owner.stale = true;\n owner.scheduled.clear();\n // Every presence interval that starts in reach lost its arrival declaration too.\n this._queueOwner(owner, from);\n for (const [start] of owner.intervals) if (start > from) this._queueOwner(owner, start);\n if (owner.present && owner.arrivedAt > from) this._queueOwner(owner, owner.arrivedAt);\n // Presence and structure were only watched going forward; revisit their frames in reach.\n if (owner.deps?.some(isPseudo)) {\n for (const frame of this._structureFrames) {\n if (frame >= from && frame <= this._walked) this._queueOwner(owner, frame);\n }\n }\n this._rewound.add(owner);\n }\n\n private _addWriter(slot: PropSlot<unknown>, index: number): void {\n const list = this._writers.get(slot);\n if (list) list.push(index);\n else this._writers.set(slot, [index]);\n }\n\n private _structureFrame(frame: number): void {\n if (frame <= this._start || frame > this._last) return;\n this._structureFrames.add(frame);\n this._enqueue(frame);\n }\n\n private _queueOwner(owner: OwnerState, frame: number): void {\n if (frame > this._last) return;\n let set = this._due.get(frame);\n if (!set) this._due.set(frame, (set = new Set()));\n set.add(owner);\n this._enqueue(frame);\n }\n\n private _enqueue(frame: number): void {\n if (this._queued.has(frame) || (frame === this._frame && !this._dueTaken)) return;\n this._queued.add(frame);\n heapPush(this._heap, frame);\n }\n}\n\nfunction isPseudo(slot: PropSlot<unknown>): boolean {\n return slot._name === STRUCTURE_SLOT || slot._name.startsWith(PRESENCE_PREFIX);\n}\n\nfunction presentAt(owner: OwnerState, frame: number): boolean {\n if (owner.present && frame >= owner.arrivedAt) return true;\n for (const [start, end] of owner.intervals) if (frame >= start && frame <= end) return true;\n return false;\n}\n\nfunction unchanged(owner: OwnerState): boolean {\n const deps = owner.deps;\n if (deps === null) return false;\n for (let i = 0; i < deps.length; i++) {\n if (!Object.is(deps[i].get(), owner.values[i])) return false;\n }\n return true;\n}\n\n/** Equal values, looking into plain arrays and records: a rebuilt node maps a stated colour to a new array. */\nfunction sameValue(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true;\n if (Array.isArray(a)) {\n if (!Array.isArray(b) || a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) if (!sameValue(a[i], b[i])) return false;\n return true;\n }\n if (!isPlain(a) || !isPlain(b)) return false;\n const keys = Object.keys(a);\n if (keys.length !== Object.keys(b).length) return false;\n for (const key of keys) if (!Object.hasOwn(b, key) || !sameValue(a[key], b[key])) return false;\n return true;\n}\n\nfunction isPlain(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null) return false;\n const proto = Object.getPrototypeOf(value) as unknown;\n return proto === Object.prototype || proto === null;\n}\n\nfunction sameDecls(a: ReadonlyMap<string, AssetDecl>, b: ReadonlyMap<string, AssetDecl>): boolean {\n if (a.size !== b.size) return false;\n for (const [key, decl] of a) {\n const other = b.get(key);\n if (!other || !sameDecl(decl, other)) return false;\n }\n return true;\n}\n\n/** A font is its family: the record keeps the first weight, so a weight tween is one segment. */\nfunction sameDecl(a: AssetDecl, b: AssetDecl): boolean {\n switch (a.type) {\n case \"image\": return b.type === \"image\" && a.src === b.src;\n case \"video\": return b.type === \"video\" && a.src === b.src && a.trimStart === b.trimStart && a.trimEnd === b.trimEnd;\n case \"font\": return b.type === \"font\" && a.family === b.family;\n case \"loader\": return b.type === \"loader\" && a.key === b.key && a.load === b.load && a.gate === b.gate;\n }\n}\n\n/** An owner's declarations laid over its presence: each key open from the entry that declares it to the one that drops it. */\nfunction segmentsOf(history: readonly Declared[], intervals: readonly [number, number][]): AssetSegment[] {\n const out: AssetSegment[] = [];\n for (const [start, end] of intervals) {\n const open = new Map<string, AssetSegment>();\n for (const entry of history) {\n if (entry.frame < start || entry.frame > end) continue;\n for (const [key, segment] of open) {\n const next = entry.decls.get(key);\n if (next && sameDecl(segment.decl, next)) continue;\n out.push({ ...segment, endFrame: entry.frame - 1 });\n open.delete(key);\n }\n for (const [key, decl] of entry.decls) {\n if (!open.has(key)) open.set(key, { key, decl, startFrame: entry.frame, endFrame: end });\n }\n }\n for (const segment of open.values()) out.push({ ...segment, endFrame: end });\n }\n return out;\n}\n\nfunction isDev(): boolean {\n return process.env.NODE_ENV !== \"production\";\n}\n\nconst warned = new Set<string>();\n\nfunction warnOnce(key: string, message: string): void {\n if (warned.has(key)) return;\n warned.add(key);\n console.warn(message);\n}\n\nfunction heapPush(heap: number[], value: number): void {\n let i = heap.length;\n heap.push(value);\n while (i > 0) {\n const parent = (i - 1) >> 1;\n if (heap[parent] <= value) break;\n heap[i] = heap[parent];\n i = parent;\n }\n heap[i] = value;\n}\n\nfunction heapPop(heap: number[]): number | undefined {\n if (heap.length === 0) return undefined;\n const top = heap[0];\n const tail = heap.pop()!;\n if (heap.length === 0) return top;\n let i = 0;\n for (;;) {\n const left = 2 * i + 1;\n if (left >= heap.length) break;\n const right = left + 1;\n const child = right < heap.length && heap[right] < heap[left] ? right : left;\n if (heap[child] >= tail) break;\n heap[i] = heap[child];\n i = child;\n }\n heap[i] = tail;\n return top;\n}\n", "import { jsonEqual } from \"@/document/diff\";\nimport type { DocIndex } from \"@/document/doc-index\";\nimport type { TimelinePatch } from \"@/document/timeline-patch\";\nimport { ROOT_NODE_ID, type NodeSpec } from \"@/document/types\";\nimport { Node } from \"@/components/trees/node/node\";\nimport { LAYOUT_SLOT, PRESENCE_PREFIX, STRUCTURE_SLOT, VAR_PREFIX } from \"@/props/observer\";\nimport type { PropSlot } from \"@/props/slot\";\nimport type { ClipInstance } from \"./clip-instance\";\nimport { frameTime } from \"./placement\";\n\n/**\n * Named by what a rebuild of the clip reproduces (the owner key of the node holding it plus the prop's name),\n * so what a declaration read survives the instance it was read on.\n */\nexport type SlotId = string;\n\nconst HOSTED = \"\\u001f\";\nconst HOSTLESS = \"\\u001e\";\n/** A host no document row built: a detached `Tex.surface` source, say. */\nconst DETACHED = \"\\u001d\";\n\nexport function hostSlotId(ownerKey: string, name: string): SlotId {\n return ownerKey + HOSTED + name;\n}\n\nexport function hostlessSlotId(name: string): SlotId {\n return HOSTLESS + name;\n}\n\nfunction hostOf(id: SlotId): string | undefined {\n if (id.startsWith(HOSTLESS) || id.startsWith(DETACHED)) return undefined;\n return id.slice(0, id.lastIndexOf(HOSTED));\n}\n\nfunction nameOf(id: SlotId): string {\n if (id.startsWith(HOSTLESS) || id.startsWith(DETACHED)) return id.slice(1);\n return id.slice(id.lastIndexOf(HOSTED) + 1);\n}\n\nexport class SlotNamer {\n constructor(private readonly _instance: ClipInstance) { }\n\n idOf(slot: PropSlot<unknown>): SlotId {\n const host = slot._host;\n if (host === null) return HOSTLESS + slot._name;\n let key = this._keys.get(host);\n if (key === undefined) {\n key = host instanceof Node ? this._instance.ownerKeyOf(host) ?? null : null;\n this._keys.set(host, key);\n }\n return key === null ? DETACHED + slot._name : hostSlotId(key, slot._name);\n }\n\n idsOf(slots: Iterable<PropSlot<unknown>>): SlotId[] {\n const out: SlotId[] = [];\n for (const slot of slots) out.push(this.idOf(slot));\n return out;\n }\n\n private readonly _keys = new Map<object, string | null>();\n}\n\n/** Every row prefix of an owner key: `a/0.1` is below `a`. A row id may itself hold a slash. */\nfunction rowsAbove(key: string): string[] {\n const out: string[] = [];\n for (let slash = key.indexOf(\"/\"); slash >= 0; slash = key.indexOf(\"/\", slash + 1)) out.push(key.slice(0, slash));\n return out;\n}\n\nfunction addTo<K, V>(map: Map<K, Set<V>>, key: K, value: V): void {\n let set = map.get(key);\n if (!set) map.set(key, (set = new Set()));\n set.add(value);\n}\n\nfunction removeFrom<K, V>(map: Map<K, Set<V>>, key: K, value: V): boolean {\n const set = map.get(key);\n if (!set) return false;\n set.delete(value);\n if (set.size > 0) return false;\n map.delete(key);\n return true;\n}\n\nconst NONE: ReadonlySet<never> = new Set();\n\nexport class OwnerDependencies {\n set(ownerKey: string, slots: Iterable<SlotId>): void {\n this.remove(ownerKey);\n const own = new Set(slots);\n this._deps.set(ownerKey, own);\n for (const row of rowsAbove(ownerKey)) addTo(this._ownersBelow, row, ownerKey);\n for (const id of own) {\n if (!this._readers.has(id)) this._index(id);\n addTo(this._readers, id, ownerKey);\n }\n }\n\n remove(ownerKey: string): void {\n const own = this._deps.get(ownerKey);\n if (!own) return;\n this._deps.delete(ownerKey);\n for (const row of rowsAbove(ownerKey)) removeFrom(this._ownersBelow, row, ownerKey);\n for (const id of own) {\n if (removeFrom(this._readers, id, ownerKey)) this._unindex(id);\n }\n }\n\n has(ownerKey: string): boolean {\n return this._deps.has(ownerKey);\n }\n\n depsOf(ownerKey: string): ReadonlySet<SlotId> {\n return this._deps.get(ownerKey) ?? NONE;\n }\n\n readersOf(id: SlotId): ReadonlySet<string> {\n return this._readers.get(id) ?? NONE;\n }\n\n ownersBelow(row: string): ReadonlySet<string> {\n return this._ownersBelow.get(row) ?? NONE;\n }\n\n slotsHostedBy(ownerKey: string): ReadonlySet<SlotId> {\n return this._byHost.get(ownerKey) ?? NONE;\n }\n\n *slotsHostedBelow(row: string): Generator<SlotId> {\n for (const host of this._hostsBelow.get(row) ?? NONE) yield* this.slotsHostedBy(host);\n }\n\n slotsNamed(name: string): ReadonlySet<SlotId> {\n return this._byName.get(name) ?? NONE;\n }\n\n private readonly _deps = new Map<string, Set<SlotId>>();\n private readonly _readers = new Map<SlotId, Set<string>>();\n private readonly _ownersBelow = new Map<string, Set<string>>();\n private readonly _byHost = new Map<string, Set<SlotId>>();\n private readonly _hostsBelow = new Map<string, Set<string>>();\n private readonly _byName = new Map<string, Set<SlotId>>();\n\n private _index(id: SlotId): void {\n addTo(this._byName, nameOf(id), id);\n const host = hostOf(id);\n if (host === undefined) return;\n addTo(this._byHost, host, id);\n for (const row of rowsAbove(host)) addTo(this._hostsBelow, row, host);\n }\n\n private _unindex(id: SlotId): void {\n removeFrom(this._byName, nameOf(id), id);\n const host = hostOf(id);\n if (host === undefined) return;\n if (removeFrom(this._byHost, host, id)) {\n for (const row of rowsAbove(host)) removeFrom(this._hostsBelow, row, host);\n }\n }\n}\n\nexport interface PlacedWrites {\n start: number;\n writes: readonly SlotId[];\n}\n\nexport interface DirtyInput {\n patch: TimelinePatch;\n deps: OwnerDependencies;\n /** Keyed by recorded write set: a set on both sides belongs to a command the patch did not rebuild. */\n before: ReadonlyMap<object, PlacedWrites>;\n after: ReadonlyMap<object, PlacedWrites>;\n fps: number;\n propsOf(rowId: string): ReadonlySet<string> | undefined;\n buildsChildren(rowId: string): boolean;\n isContextProvider(type: string): boolean;\n}\n\nexport interface DirtyOwners {\n owners: Map<string, number>;\n below: Map<string, number>;\n removed: Set<string>;\n /** Of the above, owners and rows declared from no later than they arrive — their audio is redone too. */\n arrivalOwners: Set<string>;\n arrivalBelow: Set<string>;\n}\n\n/**\n * Each from the first frame it can differ on. Every rule reads the recorded dependencies, so an edit no\n * declaration read (a position, a size, a tween of either) names nobody. Rules err towards naming an owner:\n * one named needlessly costs its declarations over its frames, one missed keeps a window a fresh build would\n * not have.\n */\nexport function dirtyOwners(input: DirtyInput): DirtyOwners {\n const { patch, deps, fps } = input;\n const { prev, next, diff } = patch;\n const out: DirtyOwners = {\n owners: new Map(),\n below: new Map(),\n removed: new Set(),\n arrivalOwners: new Set(),\n arrivalBelow: new Set(),\n };\n\n const lower = (map: Map<string, number>, key: string, frame: number) => {\n const at = map.get(key);\n if (at === undefined || frame < at) map.set(key, frame);\n };\n const owner = (key: string, frame: number, arrival: boolean) => {\n lower(out.owners, key, frame);\n if (arrival) out.arrivalOwners.add(key);\n };\n const readers = (id: SlotId, frame: number, arrival: boolean) => {\n for (const key of deps.readersOf(id)) owner(key, frame, arrival);\n };\n const below = (row: string, frame: number) => {\n if (!input.buildsChildren(row) && deps.ownersBelow(row).size === 0) return;\n lower(out.below, row, frame);\n out.arrivalBelow.add(row);\n };\n const startOf = (index: DocIndex, id: string): number => {\n const span = index.effSpan(id);\n return span ? firstFrameAt(span.start, fps) : Infinity;\n };\n const placement = (id: string, frame: number) => {\n readers(hostlessSlotId(PRESENCE_PREFIX + id), frame, true);\n readers(hostSlotId(id, STRUCTURE_SLOT), frame, true);\n for (const index of [prev, next]) {\n const spec = index.nodes.get(id);\n if (spec) readers(hostSlotId(spec.parentId ?? ROOT_NODE_ID, STRUCTURE_SLOT), frame, true);\n }\n };\n const hosted = (row: string, frame: number, names: ReadonlySet<string> | null) => {\n for (const id of deps.slotsHostedBy(row)) {\n const name = nameOf(id);\n if (names === null || names.has(name) || name === STRUCTURE_SLOT) readers(id, frame, true);\n }\n for (const id of deps.slotsHostedBelow(row)) readers(id, frame, true);\n };\n\n for (const [writes, placed] of input.before) {\n if (input.after.has(writes)) continue;\n const frame = firstFrameAt(placed.start, fps);\n for (const id of placed.writes) readers(id, frame, false);\n }\n for (const [writes, placed] of input.after) {\n if (input.before.has(writes)) continue;\n const frame = firstFrameAt(placed.start, fps);\n for (const id of placed.writes) readers(id, frame, false);\n }\n\n for (const id of diff.variables.changed) readers(hostlessSlotId(VAR_PREFIX + id), 0, true);\n if (patch.layoutChanged) {\n for (const id of deps.slotsNamed(LAYOUT_SLOT)) readers(id, 0, true);\n }\n for (const parent of diff.nodes.reorderedParents) readers(hostSlotId(parent, STRUCTURE_SLOT), 0, true);\n\n for (const id of diff.nodes.removed) {\n const from = startOf(prev, id);\n out.removed.add(id);\n placement(id, from);\n hosted(id, from, null);\n }\n for (const id of diff.nodes.added) {\n const from = startOf(next, id);\n if (from === Infinity) continue;\n owner(id, from, true);\n below(id, from);\n placement(id, from);\n }\n for (const id of next.nodes.keys()) {\n if (id === ROOT_NODE_ID || !prev.nodes.has(id)) continue;\n const a = prev.effSpan(id);\n const b = next.effSpan(id);\n if (a?.start === b?.start && a?.end === b?.end) continue;\n const from = Math.min(startOf(prev, id), startOf(next, id));\n if (from === Infinity) continue;\n owner(id, from, true);\n below(id, from);\n placement(id, from);\n }\n\n const changedRows = new Set([...patch.reinstantiate, ...diff.nodes.added, ...diff.nodes.removed]);\n for (const id of patch.reinstantiate) {\n const names = changedProps(id, input, changedRows);\n hosted(id, 0, names);\n below(id, 0);\n for (const key of [id, ...deps.ownersBelow(id)]) {\n for (const dep of deps.depsOf(key)) {\n if (!dep.startsWith(DETACHED)) continue;\n owner(key, 0, true);\n break;\n }\n }\n if (diff.nodes.moved.has(id)) placement(id, 0);\n }\n for (const id of patch.inPlace) {\n const names = changedSlots(prev.nodes.get(id)!, next.nodes.get(id)!, input.propsOf(id) ?? new Set());\n for (const slot of deps.slotsHostedBy(id)) {\n if (names === null || names.has(nameOf(slot))) readers(slot, 0, true);\n }\n }\n if (diff.rootChanged) {\n const props = input.propsOf(ROOT_NODE_ID);\n hosted(ROOT_NODE_ID, 0, props ? changedSlots(prev.nodes.get(ROOT_NODE_ID)!, next.nodes.get(ROOT_NODE_ID)!, props) : null);\n }\n return out;\n}\n\n/**\n * `null` when every slot it holds must be taken as changed: a new type, a new place, a new context above it,\n * or a prop that is not a slot of its own and so reaches its state some other way.\n */\nfunction changedProps(id: string, input: DirtyInput, changedRows: ReadonlySet<string>): ReadonlySet<string> | null {\n const { prev, next, diff } = input.patch;\n const a = prev.nodes.get(id);\n const b = next.nodes.get(id);\n if (!a || !b || !diff.nodes.respec.has(id) || diff.nodes.moved.has(id) || a.type !== b.type || a.key !== b.key) return null;\n for (const index of [prev, next]) {\n if (providerChangedAbove(index, id, changedRows, input)) return null;\n }\n const props = input.propsOf(id);\n return props ? changedSlots(a, b, props) : null;\n}\n\nfunction changedSlots(a: NodeSpec, b: NodeSpec, slots: ReadonlySet<string>): ReadonlySet<string> | null {\n const names = new Set<string>();\n for (const key of new Set([...Object.keys(a.props), ...Object.keys(b.props)])) {\n if (jsonEqual(a.props[key], b.props[key])) continue;\n if (!slots.has(key)) return null;\n names.add(key);\n }\n return names;\n}\n\nfunction providerChangedAbove(index: DocIndex, id: string, changed: ReadonlySet<string>, input: DirtyInput): boolean {\n const seen = new Set<string>([id]);\n let parentId = index.nodes.get(id)?.parentId ?? null;\n while (parentId !== null && parentId !== ROOT_NODE_ID && !seen.has(parentId)) {\n seen.add(parentId);\n const spec = index.nodes.get(parentId);\n if (!spec) return false;\n if (changed.has(parentId) && input.isContextProvider(spec.type)) return true;\n parentId = spec.parentId;\n }\n return false;\n}\n\nexport function firstFrameAt(seconds: number, fps: number): number {\n if (!(seconds > 0)) return 0;\n if (!Number.isFinite(seconds)) return Infinity;\n let frame = Math.max(0, Math.ceil(seconds * fps));\n while (frame > 0 && frameTime(frame - 1, fps, Infinity) >= seconds) frame--;\n while (frameTime(frame, fps, Infinity) < seconds) frame++;\n return frame;\n}\n", "import type { AudioRequest } from \"@/attributes/audio/request\";\n\n/** Every owner's declared audio, kept apart so one owner can change without redeclaring the rest. */\nexport class AudioIndex {\n setOwner(ownerKey: string, requests: AudioRequest[]): boolean {\n if (requests.length === 0) return this.removeOwner(ownerKey);\n const prior = this._owners.get(ownerKey);\n if (prior && sameValue(prior, requests)) return false;\n this._owners.set(ownerKey, requests);\n return true;\n }\n\n removeOwner(ownerKey: string): boolean {\n return this._owners.delete(ownerKey);\n }\n\n requests(): AudioRequest[] {\n const out: AudioRequest[] = [];\n for (const requests of this._owners.values()) out.push(...requests);\n return out;\n }\n\n private readonly _owners = new Map<string, AudioRequest[]>();\n}\n\nfunction sameValue(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true;\n if (typeof a !== \"object\" || typeof b !== \"object\" || a === null || b === null) return false;\n if (Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) return false;\n const keys = Object.keys(a);\n if (keys.length !== Object.keys(b).length) return false;\n for (const key of keys) {\n if (!sameValue((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key])) return false;\n }\n return true;\n}\n", "import { AssetIndex, type AssetSegment } from \"@/assets/asset-index\";\nimport type { AssetRecord } from \"@/assets/record\";\nimport type { AssetDecl } from \"@/assets/scope\";\nimport type { AudioBusStop, AudioRequest } from \"@/attributes/audio/request\";\nimport { isContextProvider } from \"@/document/command-traits\";\nimport { diffClip, jsonEqual } from \"@/document/diff\";\nimport type { ProjectDocument, Track } from \"@/document/project\";\nimport type { TimelinePatch } from \"@/document/timeline-patch\";\nimport type { ClipDocument, NodeSpan } from \"@/document/types\";\nimport type { Node } from \"@/components/trees/node/node\";\nimport type { PropHost } from \"@/props/host\";\nimport type { PropSlot } from \"@/props/slot\";\nimport type { MeasureContext2D } from \"@/render/measure-context\";\nimport { now, yieldToScheduler } from \"@/util/scheduler\";\nimport { DeclarationMemo, refineAssets, type OwnerResult, type RefineResult } from \"./asset-refine\";\nimport { dirtyOwners, OwnerDependencies, SlotNamer, type DirtyOwners, type PlacedWrites, type SlotId } from \"./asset-update\";\nimport { AudioIndex } from \"./audio-index\";\nimport { requestOf } from \"@/attributes/audio/schedule\";\nimport { busPathOf, busPathTo, findBusById, NodeAudio } from \"@/components/trees/audio/node-audio\";\n\nconst COMMAND_AUDIO = \"@commands\";\nimport { ClipInstance, type RuntimeScope } from \"./clip-instance\";\nimport type { PlacedSound } from \"@/document/timeline\";\nimport { placeTracks, spanFrames, trackFrameCount, type TrackSpan } from \"./placement\";\nimport type { BuildError, AssetTimelineProfile, TrackAssets, TrackAssetsProfile } from \"./asset-timeline\";\n\n/** Half a 60 Hz frame, leaving the other half for input and paint. */\nexport const DEFAULT_PRECOMP_BUDGET_MS = 8;\n\nexport interface ClipStoreOptions {\n profile?: AssetTimelineProfile;\n /** False declares no assets: owners are only watched arriving, for their audio. */\n assets?: boolean;\n /** False, with `assets` false too, refines nothing — the store only builds. */\n audio?: boolean;\n /** False disposes an instance as soon as its refinement lands, for a caller that never draws. */\n keepInstances?: boolean;\n /** Absent takes every gate as resident. */\n isReady?: (key: string) => boolean;\n}\n\nexport interface StoreRunOptions {\n /** Wall-clock ms before yielding; `0` yields between every frame evaluated. */\n budgetMs?: number;\n /** Polled after every yield; true leaves the build parked where it is. */\n isCancelled?: () => boolean;\n onProgress?: () => void;\n}\n\nexport interface StoreUpdate {\n /** Asset keys whose clip-local record changed, per track refined in place. */\n deltas: Map<string, ReadonlySet<string>>;\n /** Tracks whose built state was thrown away and starts again. */\n rebuilt: string[];\n}\n\ntype Refinement = \"assets\" | \"audio\" | \"none\";\n\ninterface Entry {\n track: Track;\n frameCount: number;\n instance: ClipInstance | null;\n steps: Generator<void, void, void> | null;\n running: boolean;\n /** Replaced or disposed while it was running; torn down once it returns. */\n discarded: boolean;\n profile: TrackAssetsProfile | undefined;\n discovered: TrackAssets | null;\n errors: BuildError[];\n index: AssetIndex;\n audio: AudioIndex;\n commandAudio: Set<string>;\n /** By owner, for one refinement; dropped when the track's audio is published. */\n commandSounds: Map<string, PlacedSound[]> | null;\n deps: OwnerDependencies;\n assetDeps: Map<string, readonly SlotId[]>;\n audioDeps: Map<string, readonly SlotId[]>;\n ownerErrors: Map<string, BuildError>;\n audioErrors: Map<string, BuildError>;\n issues: BuildError[];\n /** Nothing draws until the clip changes or the track is rebuilt. */\n failure: BuildError | null;\n refineError: BuildError | null;\n /** Bumped whenever something other than an evaluator moved the instance. */\n generation: number;\n writes: WeakMap<ReadonlySet<PropSlot<unknown>>, PlacedWrites>;\n /** Gate keys compile measured, or refinement found, before they were resident. */\n unready: Set<string>;\n /** Outlives a rebuild of the track; a catalog or theme change starts a new one. */\n memo: DeclarationMemo;\n}\n\n/**\n * One build per track, shared by whoever needs it, so the evaluator draws the tree discovery refined rather\n * than building its own. A build runs as a generator so a background driver can park it between slices;\n * whoever needs the track sooner drains the parked build. Dependencies are kept by {@link SlotId}, which a\n * rebuild reproduces, so an instance can be rebuilt without refining.\n */\nexport class ClipStore {\n constructor(project: ProjectDocument, private readonly _scope: RuntimeScope, options: ClipStoreOptions = {}) {\n this._options = options;\n this._refine = options.assets !== false ? \"assets\" : options.audio !== false ? \"audio\" : \"none\";\n this._project = project;\n for (const track of project.tracks) this._entries.set(track.id, this._fresh(track));\n this._spans = placeTracks(project.tracks, _scope.fps);\n }\n\n get project(): ProjectDocument {\n return this._project;\n }\n\n get tracks(): readonly Track[] {\n return this._project.tracks;\n }\n\n get spans(): readonly TrackSpan[] {\n return this._spans;\n }\n\n get version(): number {\n return this._version;\n }\n\n get profile(): AssetTimelineProfile | undefined {\n return this._options.profile;\n }\n\n /**\n * A track holding the same clip keeps everything; a changed clip whose tree patches in place re-declares only\n * the owners the patch can have changed; anything else starts again. A theme change starts every track again,\n * since colours resolve against it as props are written.\n */\n setProject(next: ProjectDocument): StoreUpdate {\n const update: StoreUpdate = { deltas: new Map(), rebuilt: [] };\n if (this._disposed || next === this._project) return update;\n const themeChanged = !jsonEqual(this._project.theme, next.theme);\n this._project = next;\n\n const previous = this._entries;\n this._entries = new Map();\n for (const track of next.tracks) {\n const old = previous.get(track.id);\n const entry = old && !themeChanged ? this._reconcile(old, track, update) : this._fresh(track);\n if (old && entry !== old) update.rebuilt.push(track.id);\n this._entries.set(track.id, entry);\n }\n let changed = update.rebuilt.length > 0 || previous.size !== this._entries.size;\n for (const [id, old] of previous) {\n if (this._entries.get(id) === old) continue;\n this._discard(old);\n changed = true;\n }\n const spans = placeTracks(next.tracks, this._scope.fps);\n if (changed || !sameSpans(spans, this._spans)) this._version++;\n this._spans = spans;\n return update;\n }\n\n /**\n * For a change the document does not carry: the catalog gained an entry, so a track that failed for want of\n * it, or measured against the old size, must be rebuilt. {@link setProject} cannot tell, since it compares\n * documents.\n */\n reset(): void {\n if (this._disposed) return;\n const previous = this._entries;\n this._entries = new Map();\n for (const track of this._project.tracks) this._entries.set(track.id, this._fresh(track));\n for (const old of previous.values()) this._discard(old);\n this._version++;\n }\n\n ensureBuilt(trackId: string): ClipInstance | null {\n const entry = this._entries.get(trackId);\n if (!entry || entry.running || this._disposed) return null;\n if (entry.steps) this._drain(entry);\n if (!entry.instance && !entry.failure) {\n this._start(entry, true, this._refine !== \"none\" && !entry.discovered);\n this._drain(entry);\n }\n return entry.instance;\n }\n\n discover(trackId: string): void {\n const entry = this._entries.get(trackId);\n if (!entry || entry.running || this._disposed) return;\n if (this._refine === \"none\") {\n this.ensureBuilt(trackId);\n return;\n }\n if (entry.discovered) return;\n if (!entry.steps) this._start(entry, !entry.instance, true);\n this._drain(entry);\n }\n\n /**\n * A build whose track changed while parked is dropped; a cancelled one stays parked for whoever needs the\n * track next.\n */\n async runAsync(options: StoreRunOptions = {}): Promise<void> {\n const { budgetMs = DEFAULT_PRECOMP_BUDGET_MS, isCancelled, onProgress } = options;\n if (this._refine === \"none\") return;\n for (;;) {\n if (this._disposed || isCancelled?.()) return;\n const entry = this._nextUndiscovered();\n if (!entry) return;\n if (!entry.steps) this._start(entry, !entry.instance, true);\n\n let deadline = now() + budgetMs;\n let finished = this._step(entry);\n while (!finished) {\n if (now() >= deadline) {\n entry.profile?.suspend();\n await yieldToScheduler();\n if (this._disposed || isCancelled?.()) return;\n if (entry.discarded || !entry.steps) break;\n entry.profile?.resume();\n deadline = now() + budgetMs;\n }\n finished = this._step(entry);\n }\n if (!entry.discarded && entry.discovered) onProgress?.();\n }\n }\n\n instanceOf(trackId: string): ClipInstance | null {\n const entry = this._entries.get(trackId);\n return entry && !entry.steps ? entry.instance : null;\n }\n\n generationOf(trackId: string): number {\n return this._entries.get(trackId)?.generation ?? -1;\n }\n\n failed(trackId: string): boolean {\n return !!this._entries.get(trackId)?.failure;\n }\n\n isDiscovered(trackId: string): boolean {\n return !!this._entries.get(trackId)?.discovered;\n }\n\n trackAssets(trackId: string): TrackAssets | undefined {\n return this._entries.get(trackId)?.discovered ?? undefined;\n }\n\n errorsOf(trackId: string): readonly BuildError[] {\n const entry = this._entries.get(trackId);\n return entry?.discovered ? entry.errors : [];\n }\n\n ownersOf(trackId: string, key: string): ReadonlySet<string> {\n return this._entries.get(trackId)?.index.owners(key) ?? new Set();\n }\n\n layoutGates(trackId: string): readonly AssetRecord[] {\n const entry = this._entries.get(trackId);\n return entry?.discovered ? entry.index.layoutGates() : [];\n }\n\n learn(trackId: string, ownerKey: string, decl: AssetDecl, localFrame: number): boolean {\n const entry = this._entries.get(trackId);\n if (!entry?.discovered) return false;\n if (entry.index.learn(ownerKey, decl, localFrame).keys.size === 0) return false;\n return this._refresh(entry);\n }\n\n /**\n * A gate becomes resident once, so a track rebuilds at most once per gate. Every such track is rebuilt, not\n * only one with a layout-reading command: a node may keep what it measured (`code` caches token advances), and\n * only a fresh tree drops metrics taken against the fallback face.\n */\n settleGates(trackIds: Iterable<string>): boolean {\n const isReady = this._options.isReady;\n if (!isReady) return false;\n let rebuilt = false;\n for (const id of trackIds) {\n const entry = this._entries.get(id);\n if (!entry || entry.unready.size === 0 || !entry.instance || entry.steps || entry.running) continue;\n const gates = entry.discovered ? new Set(entry.index.layoutGates().map((record) => record.src)) : null;\n let arrived = false;\n for (const key of [...entry.unready]) {\n if (gates && !gates.has(key)) {\n // Nothing loads a face no owner declared, so waiting on it is waiting forever.\n entry.unready.delete(key);\n } else if (isReady(key)) {\n arrived = true;\n }\n }\n if (!arrived) continue;\n this._rebuildInstance(entry);\n rebuilt = true;\n }\n return rebuilt;\n }\n\n /**\n * Keeps what refinement found. For an editor override written straight onto a live prop, which the timeline\n * would never restore.\n */\n rebuild(trackId: string): void {\n const entry = this._entries.get(trackId);\n if (!entry || entry.running || entry.steps) return;\n entry.instance?.dispose();\n entry.instance = null;\n entry.unready.clear();\n entry.generation++;\n if (entry.failure) {\n entry.failure = null;\n entry.discovered = null;\n this._version++;\n }\n }\n\n /** Dispose `trackId`'s tree, keeping its index and audio; a later {@link ensureBuilt} builds it without refining. */\n release(trackId: string): void {\n const entry = this._entries.get(trackId);\n if (!entry || !entry.instance || entry.running || entry.steps || !entry.discovered) return;\n entry.instance.dispose();\n entry.instance = null;\n entry.generation++;\n }\n\n trim(frame: number, horizon: number): void {\n for (let i = 0; i < this._spans.length; i++) {\n const span = this._spans[i];\n if (span.endFrame >= frame - horizon && span.startFrame <= frame + horizon) continue;\n this.release(span.id);\n }\n }\n\n dispose(): void {\n this._disposed = true;\n for (const entry of this._entries.values()) this._discard(entry);\n }\n\n private readonly _options: ClipStoreOptions;\n private readonly _refine: Refinement;\n private _project: ProjectDocument;\n private _entries = new Map<string, Entry>();\n private _spans: TrackSpan[];\n private _version = 0;\n private _disposed = false;\n\n private _fresh(track: Track, memo = new DeclarationMemo()): Entry {\n const frameCount = trackFrameCount(track.duration, this._scope.fps);\n return {\n track,\n frameCount,\n instance: null,\n steps: null,\n running: false,\n discarded: false,\n profile: undefined,\n discovered: null,\n errors: [],\n index: new AssetIndex(frameCount),\n audio: new AudioIndex(),\n commandAudio: new Set(),\n commandSounds: null,\n deps: new OwnerDependencies(),\n assetDeps: new Map(),\n audioDeps: new Map(),\n ownerErrors: new Map(),\n audioErrors: new Map(),\n issues: [],\n failure: null,\n refineError: null,\n generation: 0,\n writes: new WeakMap(),\n unready: new Set(),\n memo,\n };\n }\n\n private _reconcile(entry: Entry, track: Track, update: StoreUpdate): Entry {\n const frameCount = trackFrameCount(track.duration, this._scope.fps);\n // A declaration may read the theme outside any slot.\n const memo = jsonEqual(themeOf(entry.track.clip), themeOf(track.clip)) ? entry.memo : undefined;\n if (entry.track.clip === track.clip) return this._resize(entry, track, frameCount);\n if (entry.steps || entry.failure) return this._fresh(track, memo);\n if (!entry.instance) {\n return entry.discovered && diffClip(entry.track.clip, track.clip).identical\n ? this._resize(entry, track, frameCount)\n : this._fresh(track, memo);\n }\n\n const instance = entry.instance;\n let patch: TimelinePatch | null;\n try {\n patch = instance.planUpdate(track.clip);\n } catch {\n patch = null;\n }\n if (!patch) return this._fresh(track, memo);\n /** Nothing to apply; the tree keeps the document it was built from, which diffs the same. */\n if (patch.diff.identical) return this._resize(entry, track, frameCount);\n\n const refined = entry.discovered !== null && this._refine !== \"none\";\n const before = refined ? this._placedWrites(entry) : undefined;\n try {\n this._compile(entry, (measurer) => instance.applyUpdate(patch, track.clip, track.duration, measurer));\n } catch {\n return this._fresh(track, memo);\n }\n entry.issues = issuesOf(track.id, instance);\n entry.generation++;\n entry.track = track;\n if (!refined) {\n entry.frameCount = frameCount;\n return entry;\n }\n if (frameCount > entry.frameCount) {\n // The frames past the old end were never swept.\n this._undiscover(entry, frameCount);\n return entry;\n }\n\n const dirty = dirtyOwners({\n patch,\n deps: entry.deps,\n before: before!,\n after: this._placedWrites(entry),\n fps: this._scope.fps,\n propsOf: (id) => {\n const node = instance.node(id) as (Node & PropHost) | undefined;\n return node ? new Set(node.__cells?.slots.keys() ?? []) : undefined;\n },\n buildsChildren: (id) => {\n const node = instance.node(id);\n return !!node && node._allChildren.some((child) => instance.node(child.id) !== child);\n },\n isContextProvider: (type) => isContextProvider(this._scope.registry, type),\n });\n const keys = this._applyDirty(entry, dirty, frameCount);\n if (frameCount !== entry.frameCount) {\n entry.frameCount = frameCount;\n for (const key of entry.index.setFrameCount(frameCount).keys) keys.add(key);\n }\n if (this._refresh(entry)) update.deltas.set(track.id, keys);\n return entry;\n }\n\n /** A shorter clip clips the index; a longer one was never swept past its old end. */\n private _resize(entry: Entry, track: Track, frameCount: number): Entry {\n const duration = entry.track.duration;\n entry.track = track;\n if (track.duration === duration) return entry;\n if (entry.steps) return this._fresh(track, entry.memo);\n entry.instance?.update(entry.instance.clip, track.duration);\n if (this._refine === \"none\" || !entry.discovered) {\n entry.frameCount = frameCount;\n } else if (frameCount > entry.frameCount) {\n this._undiscover(entry, frameCount);\n } else if (frameCount !== entry.frameCount) {\n entry.frameCount = frameCount;\n entry.index.setFrameCount(frameCount);\n this._refresh(entry);\n }\n return entry;\n }\n\n private _undiscover(entry: Entry, frameCount: number): void {\n entry.frameCount = frameCount;\n entry.discovered = null;\n this._version++;\n }\n\n private _discard(entry: Entry): void {\n entry.discarded = true;\n if (entry.running) return;\n entry.steps?.return(undefined);\n entry.steps = null;\n entry.instance?.dispose();\n entry.instance = null;\n }\n\n private _nextUndiscovered(): Entry | undefined {\n let best: Entry | undefined;\n let bestStart = Infinity;\n for (const span of this._spans) {\n const entry = this._entries.get(span.id);\n if (!entry || entry.discovered || entry.running) continue;\n if (!best || span.startFrame < bestStart) {\n best = entry;\n bestStart = span.startFrame;\n }\n }\n return best;\n }\n\n private _start(entry: Entry, build: boolean, refine: boolean): void {\n const index = this._project.tracks.findIndex((track) => track.id === entry.track.id);\n entry.profile = refine ? this._options.profile?.track(index, entry.track.id) : undefined;\n entry.steps = this._steps(entry, build, refine);\n }\n\n private _drain(entry: Entry): void {\n while (entry.steps && !this._step(entry)) { /* drained */ }\n }\n\n private _step(entry: Entry): boolean {\n const steps = entry.steps;\n if (!steps) return true;\n entry.running = true;\n let result: IteratorResult<void, void>;\n try {\n result = steps.next();\n } finally {\n entry.running = false;\n }\n entry.generation++;\n if (entry.discarded || this._disposed) {\n if (!result.done) steps.return(undefined);\n entry.steps = null;\n entry.instance?.dispose();\n entry.instance = null;\n return true;\n }\n if (!result.done) return false;\n entry.steps = null;\n return true;\n }\n\n /** Yields only between frames, where the tree is consistent. */\n private *_steps(entry: Entry, build: boolean, refine: boolean): Generator<void, void, void> {\n const profile = entry.profile;\n const { fps, assets: catalog } = this._scope;\n if (build) {\n profile?.enter(\"build\");\n entry.unready.clear();\n try {\n const instance = new ClipInstance(entry.track.clip, entry.track.duration, this._scope);\n entry.instance = instance;\n this._compile(entry, (measurer) => instance.build(measurer));\n entry.issues = issuesOf(entry.track.id, instance);\n } catch (err) {\n entry.instance?.dispose();\n entry.instance = null;\n entry.failure = buildErrorOf(entry.track.id, err);\n entry.issues = [];\n if (refine) {\n this._resetAssets(entry);\n this._refresh(entry, true);\n profile?.done(entry.frameCount);\n }\n return;\n }\n if (!refine) return;\n yield;\n }\n\n const instance = entry.instance!;\n const frameCount = entry.frameCount;\n this._resetAssets(entry);\n const audioSlots = new Map<string, PropSlot<unknown>[]>();\n try {\n const refined = yield* refineAssets(instance, {\n fps,\n frameCount,\n catalog,\n declare: this._refine === \"assets\",\n memo: entry.memo,\n onPhase: (phase) => profile?.enter(phase),\n onArrive: (_node, ownerKey) => {\n profile?.enter(\"audio\");\n this._declareAudio(entry, ownerKey, audioSlots);\n },\n });\n this._commit(entry, refined, audioSlots);\n } catch (err) {\n entry.refineError = buildErrorOf(entry.track.id, err);\n }\n const isReady = this._options.isReady;\n if (isReady) {\n for (const record of entry.index.layoutGates()) {\n if (record.type === \"loader\" && !isReady(record.src)) entry.unready.add(record.src);\n }\n }\n this._refresh(entry, true);\n profile?.done(frameCount);\n if (this._options.keepInstances === false) {\n instance.dispose();\n entry.instance = null;\n }\n }\n\n private _resetAssets(entry: Entry): void {\n entry.index = new AssetIndex(entry.frameCount);\n entry.audio = new AudioIndex();\n entry.commandAudio = new Set();\n entry.commandSounds = null;\n entry.deps = new OwnerDependencies();\n entry.assetDeps.clear();\n entry.audioDeps.clear();\n entry.ownerErrors.clear();\n entry.audioErrors.clear();\n entry.refineError = null;\n }\n\n private _commit(entry: Entry, refined: RefineResult, audioSlots: ReadonlyMap<string, PropSlot<unknown>[]>): void {\n const namer = new SlotNamer(entry.instance!);\n for (const owner of refined.owners.values()) {\n const key = owner.ownerKey;\n if (owner.error) entry.ownerErrors.set(key, this._ownerError(entry, owner));\n else entry.index.setOwner(key, owner.segments);\n entry.assetDeps.set(key, namer.idsOf(owner.deps));\n }\n for (const [key, slots] of audioSlots) entry.audioDeps.set(key, namer.idsOf(slots));\n for (const key of new Set([...entry.assetDeps.keys(), ...entry.audioDeps.keys()])) this._link(entry, key);\n }\n\n private _applyDirty(entry: Entry, dirty: DirtyOwners, frameCount: number): Set<string> {\n const keys = new Set<string>();\n const collect = (delta: { keys: ReadonlySet<string> }) => {\n for (const key of delta.keys) keys.add(key);\n };\n for (const row of dirty.removed) {\n for (const key of [row, ...entry.deps.ownersBelow(row)]) this._drop(entry, key, collect);\n }\n if (dirty.owners.size === 0 && dirty.below.size === 0) return keys;\n\n const instance = entry.instance!;\n const { fps, assets: catalog } = this._scope;\n const seen = new Set<string>();\n const audioSlots = new Map<string, PropSlot<unknown>[]>();\n const sweep = refineAssets(instance, {\n fps,\n frameCount,\n catalog,\n owners: dirty.owners,\n below: dirty.below,\n declare: this._refine === \"assets\",\n memo: entry.memo,\n onArrive: (_node, ownerKey, span, frame) => {\n seen.add(ownerKey);\n // Audio is declared as an owner arrives, which a sweep starting later never sees.\n if (frame === spanFrames(span, fps, frameCount)?.startFrame) {\n this._declareAudio(entry, ownerKey, audioSlots);\n }\n },\n });\n let step = sweep.next();\n while (!step.done) step = sweep.next();\n entry.generation++;\n const refined = step.value;\n\n const fromOf = (key: string): number => {\n let from = dirty.owners.get(key);\n for (let slash = key.indexOf(\"/\"); slash >= 0; slash = key.indexOf(\"/\", slash + 1)) {\n const row = dirty.below.get(key.slice(0, slash));\n if (row !== undefined && (from === undefined || row < from)) from = row;\n }\n return from ?? 0;\n };\n const fromArrival = (key: string): boolean => {\n if (dirty.arrivalOwners.has(key)) return true;\n for (let slash = key.indexOf(\"/\"); slash >= 0; slash = key.indexOf(\"/\", slash + 1)) {\n if (dirty.arrivalBelow.has(key.slice(0, slash))) return true;\n }\n return false;\n };\n\n const candidates = new Set(refined.owners.keys());\n for (const row of dirty.below.keys()) for (const key of entry.deps.ownersBelow(row)) candidates.add(key);\n const namer = new SlotNamer(instance);\n for (const key of candidates) {\n const from = fromOf(key);\n const owner = refined.owners.get(key);\n if (!owner && from === 0) {\n this._drop(entry, key, collect);\n continue;\n }\n const kept = from > 0 ? keptBefore(entry.index.declaredSegmentsOf(key), from) : [];\n if (owner?.error) entry.ownerErrors.set(key, this._ownerError(entry, owner));\n else entry.ownerErrors.delete(key);\n collect(entry.index.setOwner(key, owner && !owner.error ? [...kept, ...owner.segments] : kept));\n if (owner) {\n const ids = namer.idsOf(owner.deps);\n entry.assetDeps.set(key, from > 0 ? [...new Set([...entry.assetDeps.get(key) ?? [], ...ids])] : ids);\n }\n if (fromArrival(key) && !seen.has(key)) {\n entry.audio.removeOwner(key);\n entry.audioDeps.delete(key);\n entry.audioErrors.delete(key);\n }\n this._link(entry, key);\n }\n for (const [key, slots] of audioSlots) {\n entry.audioDeps.set(key, namer.idsOf(slots));\n this._link(entry, key);\n }\n return keys;\n }\n\n private _drop(entry: Entry, key: string, collect: (delta: { keys: ReadonlySet<string> }) => void): void {\n collect(entry.index.removeOwner(key));\n entry.audio.removeOwner(key);\n entry.assetDeps.delete(key);\n entry.audioDeps.delete(key);\n entry.ownerErrors.delete(key);\n entry.audioErrors.delete(key);\n entry.deps.remove(key);\n entry.memo.forget(key);\n }\n\n private _link(entry: Entry, key: string): void {\n const assets = entry.assetDeps.get(key);\n const audio = entry.audioDeps.get(key);\n if (assets === undefined && audio === undefined) entry.deps.remove(key);\n else entry.deps.set(key, [...assets ?? [], ...audio ?? []]);\n }\n\n /** Reads no slots, but is linked for audio like every arrival. */\n private _declareAudio(entry: Entry, ownerKey: string, slots: Map<string, PropSlot<unknown>[]>): void {\n slots.set(ownerKey, []);\n const sounds = entry.instance ? this._commandSoundsOf(entry, entry.instance).get(ownerKey) : undefined;\n if (sounds) return this._setCommandAudio(entry, entry.instance!, ownerKey, sounds);\n entry.audio.removeOwner(ownerKey);\n entry.audioErrors.delete(ownerKey);\n }\n\n /**\n * A sound is scheduled ahead of time from where its command sits, not written per frame. Rebuilt whenever the\n * track's audio is published, so an edited command moves its sound.\n */\n private _declareCommandAudio(entry: Entry): void {\n const instance = entry.instance;\n entry.commandSounds = null;\n if (!instance || this._refine === \"none\") return;\n const byOwner = this._commandSoundsOf(entry, instance);\n for (const key of entry.commandAudio) {\n if (byOwner.has(key)) continue;\n entry.audio.removeOwner(key);\n entry.audioErrors.delete(key);\n }\n entry.commandAudio = new Set(byOwner.keys());\n for (const [key, sounds] of byOwner) this._setCommandAudio(entry, instance, key, sounds);\n entry.commandSounds = null;\n }\n\n /** The placed commands' sounds, under the row that plays each, so a request keeps its id and its waveform its row. */\n private _commandSoundsOf(entry: Entry, instance: ClipInstance): Map<string, PlacedSound[]> {\n if (entry.commandSounds) return entry.commandSounds;\n const byOwner = new Map<string, PlacedSound[]>();\n for (const sound of instance.commandSounds()) {\n const key = instance.ownerKeyOf(sound.node) ?? COMMAND_AUDIO;\n const list = byOwner.get(key);\n if (list) list.push(sound);\n else byOwner.set(key, [sound]);\n }\n return (entry.commandSounds = byOwner);\n }\n\n private _setCommandAudio(entry: Entry, instance: ClipInstance, key: string, sounds: readonly PlacedSound[]): void {\n const catalog = this._scope.assets;\n const spanOf = (node: Node): NodeSpan => {\n const found = instance.spanOf(node);\n if (!found) throw new Error(`${node.className} is not in the tree, so it has no span.`);\n return found;\n };\n try {\n const requests = sounds.map((sound, n) => {\n const { bus: busId, closed, ...options } = sound.options;\n // The buses as they stand when the sound starts: a bus may since have left.\n const bus = instance.atPresence(sound.at, () => {\n const target = busId ? findBusById(sound.node, busId) : null;\n return target ? busPathTo(target, spanOf) : sound.node instanceof NodeAudio ? busPathOf(sound.node, spanOf) : undefined;\n });\n const trimEnd = options.trimEnd ?? (closed ? catalog.getMediaDuration(sound.src) : undefined);\n return requestOf({ ...options, trimEnd, src: sound.src, at: sound.at, until: sound.until, bus }, catalog, key, n);\n });\n entry.audio.setOwner(key, requests);\n entry.audioErrors.delete(key);\n entry.commandAudio.add(key);\n } catch (err) {\n entry.audio.removeOwner(key);\n entry.audioErrors.set(key, { ...buildErrorOf(entry.track.id, err), nodeId: sounds[0].node.id });\n }\n }\n\n private _ownerError(entry: Entry, owner: OwnerResult): BuildError {\n const error = owner.error!;\n return {\n trackId: entry.track.id,\n message: error.message,\n ...(error.stack !== undefined && { stack: error.stack }),\n ...(owner.nodeId !== undefined && { nodeId: owner.nodeId }),\n ...(error.prop !== undefined && { prop: error.prop }),\n };\n }\n\n /** A snapshot, so a result already handed out does not change; nothing bumps when nothing would differ. */\n private _refresh(entry: Entry, landed = false): boolean {\n this._declareCommandAudio(entry);\n const prior = entry.discovered;\n const { fps } = this._scope;\n const records = prior && sameRecords(prior.assetRecords, entry.index.records())\n ? prior.assetRecords\n : new Map(entry.index.records());\n const audioRequests = clampAudioToClip(entry.audio.requests(), entry.frameCount / fps);\n const layoutGates = entry.index.layoutGates().map((record) => record.src);\n const errors = [\n ...entry.issues,\n ...entry.audioErrors.values(),\n ...entry.ownerErrors.values(),\n ...(entry.failure ? [entry.failure] : []),\n ...(entry.refineError ? [entry.refineError] : []),\n ];\n if (!landed && prior && records === prior.assetRecords && prior.frameCount === entry.frameCount\n && sameValue(prior.audioRequests, audioRequests) && sameValue(prior.layoutGates, layoutGates)\n && sameValue(entry.errors, errors)) {\n return false;\n }\n entry.discovered = {\n id: entry.track.id,\n discovered: true,\n frameCount: entry.frameCount,\n startFrame: 0,\n audioRequests,\n assetRecords: records,\n layoutGates,\n };\n entry.errors = errors;\n this._version++;\n return true;\n }\n\n private _placedWrites(entry: Entry): Map<object, PlacedWrites> {\n const instance = entry.instance!;\n const out = new Map<object, PlacedWrites>();\n let namer: SlotNamer | undefined;\n for (const placed of instance.placedCommands()) {\n let named = entry.writes.get(placed.writes);\n /** An entrance's hold moves with its neighbours while its write set stays. */\n if (!named || named.start !== placed.holdFrom) {\n namer ??= new SlotNamer(instance);\n named = { start: placed.holdFrom, writes: namer.idsOf(placed.writes) };\n entry.writes.set(placed.writes, named);\n }\n out.set(placed.writes, named);\n }\n return out;\n }\n\n /** A layout-reading command built against a non-resident face captured the fallback's metrics. */\n private _compile(entry: Entry, run: (measurer: MeasureContext2D) => void): void {\n const isReady = this._options.isReady;\n const inner = this._scope.measurer;\n if (!isReady) {\n run(inner);\n return;\n }\n const families = new Set<string>();\n run({\n measureText(text, fontSize, fontFamily, fontWeight, letterSpacing, fontStyle) {\n families.add(fontFamily);\n return inner.measureText(text, fontSize, fontFamily, fontWeight, letterSpacing, fontStyle);\n },\n });\n for (const family of families) {\n if (!isReady(family)) entry.unready.add(family);\n }\n }\n\n private _rebuildInstance(entry: Entry): void {\n entry.instance?.dispose();\n entry.instance = null;\n entry.generation++;\n this._start(entry, true, false);\n this._drain(entry);\n if (entry.failure && entry.discovered) this._refresh(entry);\n }\n}\n\nfunction issuesOf(trackId: string, instance: ClipInstance): BuildError[] {\n return instance.issues().map(({ code, message, nodeId, commandId }) => ({\n trackId,\n message,\n code,\n ...(nodeId !== undefined && { nodeId }),\n ...(commandId !== undefined && { commandId }),\n }));\n}\n\nfunction buildErrorOf(trackId: string, err: unknown): BuildError {\n const e = err instanceof Error ? err : new Error(String(err));\n return { trackId, message: e.message, stack: e.stack };\n}\n\nfunction keptBefore(segments: readonly AssetSegment[], from: number): AssetSegment[] {\n const out: AssetSegment[] = [];\n for (const segment of segments) {\n if (segment.startFrame >= from) continue;\n out.push(segment.endFrame >= from ? { ...segment, endFrame: from - 1 } : segment);\n }\n return out;\n}\n\n/**\n * Confine a clip's bounded audio to its own `[0, clipDuration)`, so a source outlasting the track does not\n * sound past its cut. Open requests pass through, to be resolved against the project total on assembly.\n *\n * Every bus is confined: a bus is a node of this clip, so one nothing removes is present until the clip ends,\n * and that is the span its curves run over.\n */\nfunction clampAudioToClip(requests: readonly AudioRequest[], clipDuration: number): AudioRequest[] {\n const out: AudioRequest[] = [];\n for (const req of requests) {\n const bus = req.bus && clampBusToClip(req.bus, clipDuration);\n const clamped = bus === req.bus ? { ...req } : { ...req, bus };\n if (req.open) {\n out.push(clamped);\n continue;\n }\n if (req.startAt >= clipDuration) continue;\n const endAt = Math.min(req.endAt, clipDuration);\n if (endAt <= req.startAt) continue;\n out.push(endAt === req.endAt ? clamped : { ...clamped, endAt });\n }\n return out;\n}\n\nfunction clampBusToClip(bus: readonly AudioBusStop[], clipDuration: number): readonly AudioBusStop[] {\n if (bus.every((stop) => stop.endAt <= clipDuration)) return bus;\n return bus.map((stop) => (stop.endAt <= clipDuration ? stop : { ...stop, endAt: clipDuration }));\n}\n\nfunction sameRecords(a: ReadonlyMap<string, AssetRecord>, b: ReadonlyMap<string, AssetRecord>): boolean {\n if (a.size !== b.size) return false;\n for (const [key, record] of a) {\n const other = b.get(key);\n if (!other || !sameValue(record, other)) return false;\n }\n return true;\n}\n\nfunction sameSpans(a: readonly TrackSpan[], b: readonly TrackSpan[]): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (a[i].id !== b[i].id || a[i].startFrame !== b[i].startFrame || a[i].endFrame !== b[i].endFrame) return false;\n }\n return true;\n}\n\nfunction sameValue(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true;\n if (typeof a !== \"object\" || typeof b !== \"object\" || a === null || b === null) return false;\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n const keys = Object.keys(a);\n if (keys.length !== Object.keys(b).length) return false;\n for (const key of keys) {\n if (!sameValue((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key])) return false;\n }\n return true;\n}\n\nfunction themeOf(clip: ClipDocument): unknown {\n return \"theme\" in clip ? clip.theme : undefined;\n}\n", "import type { ProjectDocument, Track } from \"@/document/project\";\nimport { isAudioDocument } from \"@/document/types\";\nimport type { NodeEditorStates } from \"@/components/trees/node/node-editor-state\";\nimport type { Canvas2D } from \"@/components/trees/root/canvas2d-node\";\nimport type { MeasureContext2D } from \"@/render/measure-context\";\nimport type { RenderPass2D } from \"@/render/render-context2d\";\nimport type { ClipInstance, RuntimeScope } from \"./clip-instance\";\nimport { ClipStore } from \"./clip-store\";\nimport { clipFrameToTime } from \"./frame-time\";\nimport { frameTime, placeTracks, spansCovering, type TrackSpan } from \"./placement\";\n\ninterface Slot {\n track: Track;\n span: TrackSpan;\n instance: ClipInstance | null;\n /** The store's generation for the track when {@link instance} was last evaluated. */\n generation: number;\n}\n\n/**\n * Puts a project's tracks into the state for a frame, then lays out and draws the ones covering it, back to\n * front.\n *\n * Trees come from a {@link ClipStore}: a track's is built the first time it covers a frame (or taken as\n * discovery left it) and thereafter only asked for times, so a seek costs the same in either direction. The\n * store owns them; anything it does to one moves its generation, and this evaluates again. Overlapping tracks\n * composite by draw order alone, which lets a translucent track show the one beneath it.\n */\nexport class StateEvaluator {\n constructor(project: ProjectDocument, private readonly _scope: RuntimeScope, store?: ClipStore) {\n this._owned = store === undefined;\n this._store = store ?? new ClipStore(project, _scope, { assets: false, audio: false });\n this._slots = this._slotsFor(project.tracks, new Map());\n this._currentTrackId = firstVisual(this._slots)?.track.id ?? null;\n }\n\n get currentFrame(): number {\n return this._currentFrame;\n }\n\n /**\n * Over a hole, the last one there was. An audio clip is a canvas drawing nothing, so it is never what an\n * editor picks from.\n */\n get currentTrackId(): string | null {\n return this._currentTrackId;\n }\n\n get currentCanvas(): Canvas2D | null {\n return this.currentInstance?.canvas ?? null;\n }\n\n get currentInstance(): ClipInstance | null {\n const slot = this._slotOf(this._currentTrackId);\n if (!slot?.instance) return null;\n return slot.instance === this._store.instanceOf(slot.track.id) ? slot.instance : null;\n }\n\n get activeTrackIds(): string[] {\n return this._active.map(slot => slot.track.id);\n }\n\n stateAt(frame: number): void {\n if (this._disposed) return;\n const target = Math.max(0, Math.floor(frame));\n const active = this._slotsToDraw(target);\n\n /**\n * Evaluation is idempotent, so a repeat would only cost. Compared by slot, not count: a swap can change which\n * tracks are on screen without changing how many.\n */\n if (!this._stale && target === this._currentFrame && sameSlots(active, this._active)\n && active.every(slot => this._settled(slot))) {\n return;\n }\n\n this._active = active;\n const topmost = firstVisual([...active].reverse());\n if (topmost) this._currentTrackId = topmost.track.id;\n\n for (const slot of active) slot.instance = this._store.ensureBuilt(slot.track.id);\n for (const slot of active) {\n if (!slot.instance) continue;\n this._evaluate(slot, target - slot.span.startFrame);\n slot.generation = this._store.generationOf(slot.track.id);\n }\n\n this._currentFrame = target;\n this._stale = false;\n }\n\n layout(measurer: MeasureContext2D = this._scope.measurer): void {\n for (const slot of this._active) this._live(slot)?.layout(measurer);\n }\n\n render(pass: RenderPass2D): void {\n for (const slot of this._active) this._live(slot)?.render(pass);\n }\n\n invalidate(): void {\n this._stale = true;\n }\n\n /**\n * The way back to what the document says for a node nothing animates: the timeline restores only what its\n * commands write, so a value written onto a live prop (an editor's override) survives re-evaluation.\n */\n rebuild(trackId: string | null = this._currentTrackId): void {\n if (trackId === null) return;\n this._store.rebuild(trackId);\n this._stale = true;\n }\n\n /**\n * The store decides what each track keeps (see {@link ClipStore.setProject}); a store shared with a precomp\n * has already taken it, and taking it twice is a no-op.\n */\n setProject(next: ProjectDocument): void {\n if (this._disposed) return;\n this._store.setProject(next);\n const prior = new Map(this._slots.map(slot => [slot.track.id, slot]));\n this._slots = this._slotsFor(next.tracks, prior);\n\n const kept = new Set(this._slots);\n for (const id of this._editorStates.keys()) {\n if (!this._slotOf(id)) this._editorStates.delete(id);\n }\n\n /**\n * Keep drawing what survived until the next evaluation: a repaint can land in between, and an emptied set\n * would paint a blank frame over an edit.\n */\n this._active = this._active.filter(slot => kept.has(slot));\n if (!this._slotOf(this._currentTrackId)) {\n this._currentTrackId = firstVisual(this._slots)?.track.id ?? null;\n }\n this._stale = true;\n }\n\n setEditorStates(trackId: string, states: NodeEditorStates | undefined): void {\n if (states) this._editorStates.set(trackId, states);\n else this._editorStates.delete(trackId);\n this._stale = true;\n }\n\n dispose(): void {\n this._disposed = true;\n this._active = [];\n for (const slot of this._slots) slot.instance = null;\n if (this._owned) this._store.dispose();\n }\n\n private readonly _store: ClipStore;\n private readonly _owned: boolean;\n private _slots: Slot[];\n private _active: Slot[] = [];\n private _currentFrame = 0;\n private _currentTrackId: string | null;\n /** Kept apart from the frame, so \"evaluate again\" never reads as \"frame -1\". */\n private _stale = false;\n private _disposed = false;\n private readonly _editorStates = new Map<string, NodeEditorStates>();\n\n private _slotsFor(tracks: readonly Track[], prior: ReadonlyMap<string, Slot>): Slot[] {\n const spans = placeTracks(tracks, this._scope.fps);\n return tracks.map((track, i) => {\n const old = prior.get(track.id);\n if (old) {\n old.track = track;\n old.span = spans[i];\n return old;\n }\n return { track, span: spans[i], instance: null, generation: -1 };\n });\n }\n\n private _slotOf(trackId: string | null): Slot | undefined {\n return trackId === null ? undefined : this._slots.find(slot => slot.track.id === trackId);\n }\n\n private _settled(slot: Slot): boolean {\n const id = slot.track.id;\n if (!slot.instance) return this._store.failed(id);\n return slot.instance === this._store.instanceOf(id) && slot.generation === this._store.generationOf(id);\n }\n\n private _live(slot: Slot): ClipInstance | null {\n return slot.instance && slot.instance === this._store.instanceOf(slot.track.id) ? slot.instance : null;\n }\n\n /**\n * Hold the final stack past the end of the project, so a frame parked beyond the last one keeps showing the\n * picture; a gap in the middle is a real hole and draws nothing.\n */\n private _slotsToDraw(frame: number): Slot[] {\n const spans = this._slots.map(slot => slot.span);\n let covering = spansCovering(spans, frame);\n if (covering.length === 0) {\n const last = Math.max(-1, ...spans.map(span => span.endFrame));\n if (frame > last && last >= 0) covering = spansCovering(spans, last);\n }\n return covering.map(span => this._slots[span.index]);\n }\n\n /**\n * The track runs on its own clock. The frame before is evaluated too and stamped as motion history: motion is\n * a property of the frame, not of the seek that reached it.\n */\n private _evaluate(slot: Slot, localFrame: number): void {\n const instance = slot.instance!;\n const dt = clipFrameToTime(1, this._scope.fps);\n /**\n * Clamped so a frame held past the end shows where the track stops: a track can cut its clip short, and the\n * clip goes on past the cut.\n */\n const time = frameTime(localFrame, this._scope.fps, slot.track.duration);\n instance.attach(time, this._editorStates.get(slot.track.id));\n\n const previous = Math.max(0, time - dt);\n instance.evaluateAt(previous);\n instance.layout();\n instance.primeMotion(previous);\n\n instance.evaluateAt(time);\n instance.layout();\n instance.sample();\n }\n}\n\nfunction firstVisual(slots: readonly Slot[]): Slot | undefined {\n return slots.find(slot => !isAudioDocument(slot.track.clip));\n}\n\nfunction sameSlots(a: readonly Slot[], b: readonly Slot[]): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;\n return true;\n}\n", "import type { StorageAdapter } from \"@/platform/storage-adapter\";\n\n/**\n * Bounded because a broken asset must degrade a frame rather than hang an export; four covers the longest real\n * chain (three runtime, its resources, a video frame, an exact image level discovered by that frame's draw).\n */\nexport const SETTLE_PASSES = 4;\n\nexport type SettleOutcome = \"settled\" | \"exhausted\" | \"superseded\";\n\n/**\n * `isCurrent` is checked before every render and after every await, so a seek overtaken by a newer one stops\n * drawing a frame nobody wants.\n */\nexport async function renderSettled(\n render: () => void,\n adapter: Pick<StorageAdapter, \"warmPendingDecodes\">,\n isCurrent: () => boolean,\n): Promise<SettleOutcome> {\n for (let pass = 0; pass < SETTLE_PASSES; pass++) {\n if (!isCurrent()) return \"superseded\";\n render();\n const warmed = await adapter.warmPendingDecodes();\n if (!warmed) return \"settled\";\n if (!isCurrent()) return \"superseded\";\n }\n return \"exhausted\";\n}\n", "import type { AssetCatalog } from \"@/assets/catalog\";\nimport type { AssetRecord, ImageRecord, VideoRecord } from \"@/assets/record\";\n\n/** With the load/evict windows the asset manager uses to keep memory bounded. */\nexport interface AssetTrack {\n record: AssetRecord;\n /** Larger decodes get more lead time. Always <= startFrame. */\n cacheAt: number;\n /** `null` keeps it (fonts). Always >= endFrame when set. */\n discardAt: number | null;\n}\n\nexport interface TrackRecords {\n id: string;\n startFrame: number;\n records: ReadonlyMap<string, AssetRecord>;\n}\n\n/**\n * Kept up to date key by key: an edit to one track touches only the keys its records changed, so the cost of\n * republishing follows the edit. The map handed out is replaced, never mutated, so a result already published\n * stays as it was.\n */\nexport class ProjectAssets {\n constructor(private readonly _fps: number, private readonly _catalog: AssetCatalog) { }\n\n update(tracks: readonly TrackRecords[]): ReadonlyMap<string, AssetTrack> {\n const touched = new Set<string>();\n const live = new Set<string>();\n for (const track of tracks) {\n live.add(track.id);\n const prior = this._tracks.get(track.id);\n if (prior && prior.records === track.records && prior.startFrame === track.startFrame) continue;\n const moved = !prior || prior.startFrame !== track.startFrame;\n for (const [key, record] of track.records) {\n const before = prior?.records.get(key);\n if (moved || !before || !sameRecord(before, record)) touched.add(key);\n this._holders(key).add(track.id);\n }\n if (prior) {\n for (const key of prior.records.keys()) {\n if (track.records.has(key)) continue;\n touched.add(key);\n this._release(key, track.id);\n }\n }\n this._tracks.set(track.id, { id: track.id, startFrame: track.startFrame, records: track.records });\n }\n for (const [id, prior] of this._tracks) {\n if (live.has(id)) continue;\n this._tracks.delete(id);\n for (const key of prior.records.keys()) {\n touched.add(key);\n this._release(key, id);\n }\n }\n\n let next: Map<string, AssetTrack> | undefined;\n for (const key of touched) {\n const entry = this._entryOf(key);\n const current = this._map.get(key);\n if (entry === undefined) {\n if (current === undefined) continue;\n next ??= new Map(this._map);\n next.delete(key);\n } else if (current === undefined || !sameTrack(current, entry)) {\n next ??= new Map(this._map);\n next.set(key, entry);\n }\n }\n if (next) this._map = next;\n return this._map;\n }\n\n private readonly _tracks = new Map<string, TrackRecords>();\n private readonly _byKey = new Map<string, Set<string>>();\n private _map: ReadonlyMap<string, AssetTrack> = new Map();\n\n private _holders(key: string): Set<string> {\n let holders = this._byKey.get(key);\n if (!holders) this._byKey.set(key, (holders = new Set()));\n return holders;\n }\n\n private _release(key: string, trackId: string): void {\n const holders = this._byKey.get(key);\n if (!holders) return;\n holders.delete(trackId);\n if (holders.size === 0) this._byKey.delete(key);\n }\n\n private _entryOf(key: string): AssetTrack | undefined {\n const holders = this._byKey.get(key);\n if (!holders) return undefined;\n let merged: AssetRecord | undefined;\n for (const id of holders) {\n const track = this._tracks.get(id)!;\n const record = track.records.get(key);\n if (record) merged = mergeRecord(merged, shiftRecord(record, track.startFrame));\n }\n return merged && assetTrackOf(merged, this._fps, this._catalog);\n }\n}\n\nfunction shiftRecord(record: AssetRecord, offset: number): AssetRecord {\n if (offset === 0) return record;\n return { ...record, startFrame: record.startFrame + offset, endFrame: record.endFrame + offset };\n}\n\n/** An asset several tracks use resolves to one window over all of it. */\nfunction mergeRecord(existing: AssetRecord | undefined, record: AssetRecord): AssetRecord {\n if (!existing) return record;\n return {\n ...existing,\n startFrame: Math.min(existing.startFrame, record.startFrame),\n endFrame: Math.max(existing.endFrame, record.endFrame),\n } as AssetRecord;\n}\n\n/** What a full decode costs, which lead time scales with. Nothing for a source the catalog cannot size. */\nfunction intrinsicMB(record: ImageRecord | VideoRecord, catalog: AssetCatalog): number {\n let size: { width: number; height: number };\n try {\n size = record.type === \"image\" ? catalog.getImageMeta(record.src) : catalog.getVideoMeta(record.src);\n } catch {\n return 0;\n }\n if (!(size.width > 0) && !(size.height > 0)) return 0;\n return decodedMB(size.width, size.height);\n}\n\n/** Clamped: a 4K image gets about 64, a thumbnail the minimum. */\nconst LEADS_PER_MB = 2;\nconst MIN_LEAD = 2;\nconst MAX_LEAD = 120;\nconst TAIL_FRAMES = 30;\n\nfunction decodedMB(width: number, height: number): number {\n return (width * height * 4) / (1024 * 1024);\n}\n\nfunction leadFrames(mb: number): number {\n return Math.min(MAX_LEAD, Math.max(MIN_LEAD, Math.round(mb * LEADS_PER_MB)));\n}\n\n/** Fonts are pinned from frame 0 and never evicted. */\nfunction assetTrackOf(entry: AssetRecord, fps: number, catalog: AssetCatalog): AssetTrack | undefined {\n switch (entry.type) {\n case \"image\": {\n const lead = leadFrames(intrinsicMB(entry, catalog));\n return { record: entry, cacheAt: Math.max(0, entry.startFrame - lead), discardAt: entry.endFrame + TAIL_FRAMES };\n }\n case \"video\": {\n // Heavier to decode than an image: double the lead, plus a second\n // so a short clip still gets real headroom.\n const lead = Math.min(MAX_LEAD, leadFrames(intrinsicMB(entry, catalog)) * 2 + Math.round(fps));\n return { record: entry, cacheAt: Math.max(0, entry.startFrame - lead), discardAt: entry.endFrame + TAIL_FRAMES };\n }\n case \"font\":\n return { record: entry, cacheAt: 0, discardAt: null };\n case \"loader\":\n // Cheap and needed for the whole span it is requested over.\n return { record: entry, cacheAt: Math.max(0, entry.startFrame - MAX_LEAD), discardAt: entry.endFrame + TAIL_FRAMES };\n default:\n return undefined;\n }\n}\n\nfunction sameTrack(a: AssetTrack, b: AssetTrack): boolean {\n return a.cacheAt === b.cacheAt && a.discardAt === b.discardAt && sameRecord(a.record, b.record);\n}\n\nexport function sameRecord(a: AssetRecord, b: AssetRecord): boolean {\n if (a === b) return true;\n if (a.type !== b.type || a.src !== b.src || a.startFrame !== b.startFrame || a.endFrame !== b.endFrame) return false;\n switch (a.type) {\n case \"video\": {\n const v = b as typeof a;\n return a.trimStart === v.trimStart && a.trimEnd === v.trimEnd;\n }\n case \"font\": {\n const v = b as typeof a;\n return a.fontWeight === v.fontWeight && a.fontFamily === v.fontFamily;\n }\n case \"loader\":\n return a.load === (b as typeof a).load;\n default:\n return true;\n }\n}\n", "import { AudioRequest } from \"@/attributes/audio/request\";\nimport { AssetRecord } from \"@/assets/record\";\nimport type { AssetDecl } from \"@/assets/scope\";\nimport type { ProjectDocument } from \"@/document/project\";\nimport type { RenderIssue } from \"@/render/render-issue\";\nimport { now } from \"@/util/scheduler\";\nimport type { RuntimeScope } from \"./clip-instance\";\nimport { ClipStore, DEFAULT_PRECOMP_BUDGET_MS } from \"./clip-store\";\nimport { spansCovering, totalFramesOf } from \"./placement\";\nimport { ProjectAssets, type AssetTrack } from \"./project-assets\";\n\nexport type { AssetTrack } from \"./project-assets\";\n\nexport interface BuildError {\n trackId: string;\n message: string;\n stack?: string;\n /** The node whose declaration threw, when one owner failed rather than the whole clip. */\n nodeId?: string;\n prop?: string;\n /**\n * Present when the build stepped around the problem instead of failing: a row of an unregistered type built as\n * an empty placeholder (`nodeId`), or a command no node publishes, skipped (`commandId`). The rest of the clip\n * draws.\n */\n code?: \"unknown-node-type\" | \"unknown-command\";\n commandId?: string;\n issue?: RenderIssue;\n}\n\n/** In clip-local frames, so a pass survives its track moving; only `startFrame` depends on where it sits. */\nexport interface TrackAssets {\n id: string;\n /** Whether the pass has run. An undiscovered track has its span but no assets or audio yet. */\n discovered: boolean;\n frameCount: number;\n startFrame: number;\n audioRequests: AudioRequest[];\n /** Asset usage in clip-local frames, keyed by stable asset key (src; family for a font). */\n assetRecords: ReadonlyMap<string, AssetRecord>;\n /** Keys that must be resident before layout measures: fonts, and loaders declared with `gate: \"layout\"`. */\n layoutGates?: string[];\n}\n\nexport type AssetTimelinePhase =\n | \"build\"\n | \"declare\"\n | \"evaluate\"\n | \"audio\";\n\nconst ASSET_TIMELINE_PHASES: readonly AssetTimelinePhase[] = [\"build\", \"declare\", \"evaluate\", \"audio\"];\n\nexport interface TrackAssetsTiming {\n trackId: string;\n trackIndex: number;\n frameCount: number;\n totalMs: number;\n phases: Record<AssetTimelinePhase, number>;\n}\n\nexport type AssetTimelineTimings = (TrackAssetsTiming | undefined)[];\n\n/**\n * `enter` closes whichever phase was open and starts the named one; `suspend`/`resume` bracket a yield so\n * parked time is not billed to the open phase.\n */\nexport interface TrackAssetsProfile {\n enter(phase: AssetTimelinePhase): void;\n suspend(): void;\n resume(): void;\n done(frameCount: number): void;\n}\n\n/** A seam, so core carries no environment assumption. */\nexport interface AssetTimelineProfile {\n track(trackIndex: number, trackId: string): TrackAssetsProfile;\n}\n\nexport function createAssetTimelineProfile(): AssetTimelineProfile & { timings: AssetTimelineTimings } {\n const timings: AssetTimelineTimings = [];\n return {\n timings,\n track(trackIndex: number, trackId: string): TrackAssetsProfile {\n const phases = Object.fromEntries(\n ASSET_TIMELINE_PHASES.map(p => [p, 0]),\n ) as Record<AssetTimelinePhase, number>;\n let open: AssetTimelinePhase | null = null;\n let since = now();\n let totalMs = 0;\n const close = () => {\n const elapsed = now() - since;\n if (open) phases[open] += elapsed;\n totalMs += elapsed;\n };\n return {\n enter(phase) {\n close();\n open = phase;\n since = now();\n },\n suspend() {\n close();\n open = null;\n },\n resume() {\n since = now();\n },\n done(frameCount) {\n close();\n open = null;\n timings[trackIndex] = { trackId, trackIndex, frameCount, totalMs, phases };\n },\n };\n },\n };\n}\n\nexport interface AssetTimelineResult {\n fps: number;\n tracks: TrackAssets[];\n totalFrames: number;\n totalDuration: number;\n assets: ReadonlyMap<string, AssetTrack>;\n buildErrors: BuildError[];\n /** True once every track has been discovered. Spans and totals are exact either way. */\n complete: boolean;\n timings?: AssetTimelineTimings;\n}\n\nexport interface AssetTimelineOptions {\n profile?: AssetTimelineProfile;\n /**\n * Shared with an evaluator so each track builds once. Absent, the view owns a store that drops each tree once\n * refined; nothing it builds is drawn.\n */\n store?: ClipStore;\n /** False declares audio alone, at arrival — for a caller that only mixes. Ignored with `store`. */\n assets?: boolean;\n}\n\nexport interface RunAsyncOptions {\n /** Wall-clock ms before yielding. Defaults to {@link DEFAULT_PRECOMP_BUDGET_MS}; `0` yields between every frame evaluated. */\n budgetMs?: number;\n isCancelled?: () => boolean;\n onProgress?: (result: AssetTimelineResult) => void;\n}\n\n/**\n * A view over a {@link ClipStore}, which holds the builds, indices and audio. Spans come from the document, so\n * this decides which assets a frame needs, never where a track sits. A result is the same object until\n * something in it changes, so a caller can tell a republish from a no-op by identity.\n */\nexport class AssetTimeline {\n constructor(project: ProjectDocument, private readonly _scope: RuntimeScope, options: AssetTimelineOptions = {}) {\n this._owned = options.store === undefined;\n this._store = options.store ?? new ClipStore(project, _scope, {\n profile: options.profile,\n assets: options.assets,\n keepInstances: false,\n });\n this._assets = new ProjectAssets(_scope.fps, _scope.assets);\n }\n\n get store(): ClipStore {\n return this._store;\n }\n\n get discoveredCount(): number {\n let n = 0;\n for (const track of this._store.tracks) if (this._store.isDiscovered(track.id)) n++;\n return n;\n }\n\n result(): AssetTimelineResult {\n return this._assemble();\n }\n\n ensureCovering(frame: number): AssetTimelineResult {\n for (const span of spansCovering(this._store.spans, frame)) this._store.discover(span.id);\n return this._assemble();\n }\n\n run(): AssetTimelineResult {\n for (const track of this._store.tracks) this._store.discover(track.id);\n return this._assemble();\n }\n\n /**\n * A pass whose track changed while parked is dropped, and the scan picks again from the document as it is now.\n */\n async runAsync(options: RunAsyncOptions = {}): Promise<AssetTimelineResult> {\n const { budgetMs = DEFAULT_PRECOMP_BUDGET_MS, isCancelled, onProgress } = options;\n await this._store.runAsync({\n budgetMs,\n isCancelled,\n onProgress: onProgress && (() => onProgress(this._assemble())),\n });\n return this._assemble();\n }\n\n setProject(next: ProjectDocument): AssetTimelineResult {\n this._store.setProject(next);\n return this._assemble();\n }\n\n /** A track not discovered yet is left alone: its pass will declare for itself. */\n learn(trackId: string, ownerKey: string, decl: AssetDecl, localFrame: number): AssetTimelineResult {\n this._store.learn(trackId, ownerKey, decl, localFrame);\n return this._assemble();\n }\n\n /** Dispose the store this view owns; a shared one is its owner's to dispose. */\n dispose(): void {\n if (this._owned) this._store.dispose();\n }\n\n private readonly _store: ClipStore;\n private readonly _owned: boolean;\n private readonly _assets: ProjectAssets;\n private _result: AssetTimelineResult | null = null;\n private _version = -1;\n\n private _assemble(): AssetTimelineResult {\n const store = this._store;\n if (this._result && this._version === store.version) return this._result;\n const { fps } = this._scope;\n const spans = store.spans;\n const totalFrames = totalFramesOf(spans);\n const totalDuration = totalFrames / fps;\n const tracks: TrackAssets[] = [];\n const buildErrors: BuildError[] = [];\n let complete = true;\n\n const local: TrackAssets[] = spans.map((span) => {\n const found = store.trackAssets(span.id);\n if (!found) complete = false;\n buildErrors.push(...store.errorsOf(span.id));\n return found ?? undiscovered(span.id, span.endFrame - span.startFrame + 1);\n });\n const assets = this._assets.update(local.map((track, i) => ({\n id: track.id,\n startFrame: spans[i].startFrame,\n records: track.assetRecords,\n })));\n for (let i = 0; i < local.length; i++) {\n tracks.push(resolveOpenAudio({ ...local[i], startFrame: spans[i].startFrame }, fps, totalDuration));\n }\n\n const profiled = store.profile as (AssetTimelineProfile & { timings?: AssetTimelineTimings }) | undefined;\n this._version = store.version;\n return this._result = {\n fps,\n tracks,\n totalFrames,\n totalDuration,\n assets,\n buildErrors,\n complete,\n timings: profiled?.timings?.slice(),\n };\n }\n}\n\nfunction undiscovered(id: string, frameCount: number): TrackAssets {\n return {\n id,\n discovered: false,\n frameCount,\n startFrame: 0,\n audioRequests: [],\n assetRecords: new Map(),\n layoutGates: [],\n };\n}\n\n/** The `open` marker is kept, so the next assembly re-resolves it. */\nfunction resolveOpenAudio(track: TrackAssets, fps: number, totalDuration: number): TrackAssets {\n if (!track.audioRequests.some((r) => r.open)) return track;\n\n const offset = track.startFrame / fps;\n const audioRequests = track.audioRequests.map((req) => {\n if (!req.open) return req;\n const absStart = offset + req.startAt;\n const naturalEnd = req.loop\n ? totalDuration\n : Math.min(absStart + (req.mediaDuration ?? 0), totalDuration);\n return { ...req, endAt: Math.max(req.startAt, naturalEnd - offset) };\n });\n return { ...track, audioRequests };\n}\n", "import { Node } from \"@/components/trees/node/node\";\nimport { Node3D, parentSpaceOf } from \"@/components/trees/three/node3d\";\nimport type { Node2D } from \"@/components/trees/2d/node2d\";\nimport type { Vector2 } from \"@/attributes/layout/vector2\";\nimport { applyToPoint, invert, type Matrix2D } from \"@/attributes/layout/matrix2d\";\nimport { resolveCameraPlacement, type CameraData3D } from \"@/render3d/camera\";\nimport type { Scene3D, Scene3DOp } from \"@/render3d/scene3d\";\nimport type { Transform3D } from \"@/render3d/transform\";\nimport {\n geometryBounds3D, transformBox3, unionBox3, centeredBox3, corners3, type Box3,\n} from \"@/render3d/bounds3d\";\nimport {\n applyMatrix4, identity4, invert4, lookAtRotation4, multiply4, orthographic4,\n perspective4, transformMatrix4, translation4, type Matrix4,\n} from \"@/render3d/matrix4\";\nimport type { Vector3 } from \"@/render3d/vector3\";\nimport { nodePath } from \"@/project/tree\";\nimport type { NodeBox } from \"./node-picking\";\n\n/**\n * Where a `Node3D`'s pixels landed: the 3D half of `node-picking.ts`.\n *\n * The answer is a 2D box: the screen-space AABB of the node's projected world-space AABB, in the `Canvas3D`'s\n * own plane. It composes with everything the 2D side does (the canvas's rotation, its ancestors', a camera\n * scope above it) by being mapped through the canvas's `renderMatrix` as {@link nodeBox} maps a corner.\n *\n * Bounds come from the recorded {@link Scene3D} (the seam render and the asset pass both build, which measures\n * a custom `renderSelf` for free); paths come from the tree, because a path is a child index and ops carry\n * none. The two meet on `Node3D.id`, which the scene records as the `key` on every `push`.\n *\n * Nothing here imports `node-picking.ts` at runtime: the canvas's box and CTM arrive as a {@link\n * Canvas3DFrame}, so the dependency runs one way (the `NodeBox` import is type-only).\n *\n * A box is not clipped to the viewport: a mesh drifted off the canvas reports where it went, though no pixels\n * are drawn. {@link pickIn} only consults this file for a point already inside the rect. Every entry point\n * records the scene afresh, so a host calling {@link collectBoxes} on every pointer move over many viewports\n * pays one scene build per viewport per move.\n */\n\n/** @internal */\n/** A 2D node over a 3D scene (a `Canvas3D`): its 3D children are picked through the scene it builds. */\nexport interface Viewport3D extends Node2D {\n _isViewport3D(): boolean;\n _scene3D(): Scene3D | null;\n}\n\nexport function isViewport3D(node: unknown): node is Viewport3D {\n return typeof (node as Partial<Viewport3D> | null)?._isViewport3D === \"function\" && (node as Viewport3D)._isViewport3D();\n}\n\nexport interface Canvas3DFrame {\n /**\n * Its folded `rotation`/`scale`/`opacity` carry to every 3D node inside it: a mesh has none of its own, and\n * cursor angles and pixels-per-unit are questions about the plane the box is drawn in.\n */\n box: NodeBox;\n matrix: Matrix2D;\n}\n\n/**\n * Ordered by depth, not draw order (the one divergence from {@link collectBoxes}): a 3D scene has no draw\n * order to speak of, so \"topmost\" means \"nearest\". Empty when the scene has no camera that resolves, the\n * canvas has no size, or nothing can be measured (see {@link geometryBounds3D}).\n */\n/** @internal */\nexport function collectBoxes3D(canvas: Viewport3D, frame: Canvas3DFrame, path: string): NodeBox[] {\n const projection = canvas3DProjection(canvas);\n if (!projection) return [];\n\n const out: { box: NodeBox; depth: number }[] = [];\n for (const entry of nodes3DOf(canvas, path)) {\n const world = projection.boxes.get(entry.node.id);\n if (!world) continue;\n const projected = projectBox3(world, projection);\n if (!projected) continue;\n out.push({\n box: toNodeBox(entry.node, entry.path, projected.rect, frame),\n depth: projected.depth,\n });\n }\n /**\n * View space looks down -Z, so a nearer node has the larger (less negative) z: descending puts the front\n * first.\n */\n out.sort((a, b) => b.depth - a.depth);\n return out.map((entry) => entry.box);\n}\n\n/**\n * Where arbitrary points around one `Node3D` land on screen, for a gizmo. All points come back in the same\n * viewport space as {@link NodeBox}. A `null` entry is behind the camera (the per-point version of {@link\n * projectBox3}'s eye-plane guard).\n *\n * Not `@internal`, unlike {@link projectNode3D}: a host gets this back from\n * `projectNode3DAt`/`PlaybackController.projectNode3D`.\n */\nexport interface Node3DFrame {\n origin: Vector2 | null;\n /**\n * `parentPoints` transformed by the node's parent's world matrix then projected: the frame\n * `Node3DProps.position` is expressed in, so a move or scale handle belongs here and `{ ...position, x:\n * position.x + 1 }` projects to where nudging `x` by one unit lands.\n */\n parentPoints: (Vector2 | null)[];\n /**\n * `localPoints` transformed by the node's own world matrix then projected, for geometry tracking its current\n * orientation (a rotation ring).\n */\n localPoints: (Vector2 | null)[];\n /**\n * What the node and its children draw, as a box in the node's own frame (the one `localPoints` are in), so a\n * selection box projected through `localPoints` hugs the mesh at any orientation. `null` when nothing it draws\n * has an extent core can measure (a light; a model, whose file core never reads) or it is hidden.\n */\n bounds: Box3 | null;\n}\n\nconst ORIGIN_3D: Vector3 = { x: 0, y: 0, z: 0 };\n\n/**\n * `null` when the canvas has no projection (see {@link canvas3DProjection}) or the path does not resolve.\n * `canvasPath` is the same root {@link collectBoxes3D} and {@link pickNode3D} are handed.\n */\n/** @internal */\nexport function projectNode3D(\n canvas: Viewport3D,\n frame: Canvas3DFrame,\n canvasPath: string,\n targetPath: string,\n parentPoints: readonly Vector3[],\n localPoints: readonly Vector3[],\n): Node3DFrame | null {\n const entry = nodes3DOf(canvas, canvasPath).find((e) => e.path === targetPath);\n if (!entry) return null;\n\n const projection = canvas3DProjection(canvas, entry.node.id);\n if (!projection) return null;\n\n const own = projection.matrices.get(entry.node.id);\n const parent = projection.parentMatrices.get(entry.node.id);\n if (!own || !parent) return null;\n\n const project = (matrix: Matrix4, points: readonly Vector3[]): (Vector2 | null)[] =>\n points.map((point) => projectPoint3(matrix, point, projection, frame));\n\n // A parent with coordinates of its own places the node by them, so that is the frame its position is in.\n const space = parentSpaceOf(entry.node);\n const placed = space ? parentPoints.map((point) => space.toLocal(point.x, point.y, point.z)) : parentPoints;\n\n return {\n origin: projectPoint3(own, ORIGIN_3D, projection, frame),\n parentPoints: project(parent, placed),\n localPoints: project(own, localPoints),\n bounds: projection.localBounds,\n };\n}\n\n/**\n * `null` when it lands behind the camera. The single-point sibling of {@link projectBox3}: no edges to clip.\n */\nfunction projectPoint3(\n matrix: Matrix4,\n point: Vector3,\n projection: Canvas3DProjection,\n frame: Canvas3DFrame,\n): Vector2 | null {\n const world = applyMatrix4(matrix, point);\n const clip = applyMatrix4(projection.clip, { x: world.x, y: world.y, z: world.z });\n if (clip.w <= MIN_CLIP_W) return null;\n\n const ndcX = clip.x / clip.w;\n const ndcY = clip.y / clip.w;\n const rectX = projection.centerX + ndcX * (projection.width / 2);\n const rectY = projection.centerY + ndcY * (projection.height / 2);\n\n const p = applyToPoint(frame.matrix, { x: rectX, y: -rectY });\n return { x: p.x, y: -p.y };\n}\n\n/**\n * The box, not the mesh. `tolerance` is grab-slop in scene units, applied in the canvas's own plane so it\n * stays a constant on-screen distance.\n */\n/** @internal */\nexport function pickNode3D(\n canvas: Viewport3D,\n frame: Canvas3DFrame,\n point: Vector2,\n tolerance: number,\n path: string,\n): NodeBox | null {\n const projection = canvas3DProjection(canvas);\n if (!projection) return null;\n\n /**\n * Into the canvas's own plane, undoing everything above it in one step: the inverse `containsPoint` takes,\n * with the same y-flips.\n */\n const inverse = invert(frame.matrix);\n if (!inverse) return null;\n const mapped = applyToPoint(inverse, { x: point.x, y: -point.y });\n const local = { x: mapped.x, y: -mapped.y };\n\n let best: { node: Node3D; path: string; rect: Rect2D } | null = null;\n let bestDepth = -Infinity;\n for (const entry of nodes3DOf(canvas, path)) {\n const world = projection.boxes.get(entry.node.id);\n if (!world) continue;\n const projected = projectBox3(world, projection);\n if (!projected) continue;\n if (!rectContains(projected.rect, local, tolerance)) continue;\n if (projected.depth <= bestDepth) continue;\n bestDepth = projected.depth;\n best = { node: entry.node, path: entry.path, rect: projected.rect };\n }\n return best ? toNodeBox(best.node, best.path, best.rect, frame) : null;\n}\n\ninterface Node3DEntry {\n node: Node3D;\n path: string;\n}\n\n/**\n * Indexed against {@link Node._allChildren} rather than `children`, so a mesh and a HUD label under one\n * viewport are numbered the way the author wrote them.\n */\nfunction nodes3DOf(canvas: Viewport3D, path: string): Node3DEntry[] {\n const out: Node3DEntry[] = [];\n walk3D(canvas._allChildren, path, out);\n return out;\n}\n\nfunction walk3D(children: readonly Node[], parentPath: string, out: Node3DEntry[]): void {\n for (let i = 0; i < children.length; i++) {\n const child = children[i];\n if (!(child instanceof Node3D)) continue;\n const path = nodePath(parentPath, i);\n out.push({ node: child, path });\n walk3D(child._allChildren, path, out);\n }\n}\n\ninterface Canvas3DProjection {\n boxes: Map<string, Box3>;\n matrices: Map<string, Matrix4>;\n parentMatrices: Map<string, Matrix4>;\n clip: Matrix4;\n view: Matrix4;\n width: number;\n height: number;\n centerX: number;\n centerY: number;\n /** The `boundsKey` node's extent in its own frame, when one was asked for. */\n localBounds: Box3 | null;\n}\n\nfunction canvas3DProjection(canvas: Viewport3D, boundsKey?: string): Canvas3DProjection | null {\n const bounds = canvas._localBounds();\n if (!(bounds.width > 0) || !(bounds.height > 0)) return null;\n\n const scene = canvas._scene3D();\n if (!scene) return null;\n const walked = walkScene3D(scene, boundsKey);\n if (walked.boxes.size === 0) return null;\n\n const view = invert4(walked.camera);\n if (!view) return null;\n\n const aspect = bounds.width / bounds.height;\n return {\n boxes: walked.boxes,\n matrices: walked.matrices,\n parentMatrices: walked.parentMatrices,\n clip: multiply4(projectionMatrix(walked.descriptor, aspect), view),\n view,\n width: bounds.width,\n height: bounds.height,\n centerX: bounds.x,\n centerY: bounds.y,\n localBounds: walked.localBounds,\n };\n}\n\ninterface Scope3D {\n key: string | undefined;\n matrix: Matrix4;\n visible: boolean;\n box: Box3 | null;\n}\n\ninterface WalkedScene3D {\n boxes: Map<string, Box3>;\n /** Captured at `push`, unlike `boxes`, which needs children merged in at `pop`. */\n matrices: Map<string, Matrix4>;\n parentMatrices: Map<string, Matrix4>;\n camera: Matrix4;\n descriptor: CameraData3D | null;\n localBounds: Box3 | null;\n}\n\n/**\n * A node's box is the union of everything it drew and its children drew, so a `Group3D` that draws nothing is\n * still selectable as what it contains. An invisible scope contributes nothing: `visible: false` is skipped by\n * the renderer, and letting it inflate its parent's box would put that box round empty space. The 2D walk\n * skips `opacity: 0` on the same grounds.\n */\nfunction walkScene3D(scene: Scene3D, boundsKey?: string): WalkedScene3D {\n const boxes = new Map<string, Box3>();\n const matrices = new Map<string, Matrix4>();\n const parentMatrices = new Map<string, Matrix4>();\n const root: Scope3D = { key: undefined, matrix: identity4(), visible: true, box: null };\n const stack: Scope3D[] = [root];\n let camera: Matrix4 | null = null;\n let descriptor: CameraData3D | null = null;\n /** Where the `boundsKey` scope sits on the stack while it is open, and the way back into its own frame. */\n let target: { depth: number; inverse: Matrix4 } | null = null;\n let localBounds: Box3 | null = null;\n\n const top = (): Scope3D => stack[stack.length - 1];\n\n for (const op of scene.ops()) {\n const scope = top();\n switch (op.kind) {\n case \"push\": {\n const matrix = scopeMatrix(scope.matrix, op.transform);\n if (op.transform?.key !== undefined) {\n matrices.set(op.transform.key, matrix);\n parentMatrices.set(op.transform.key, scope.matrix);\n if (op.transform.key === boundsKey) {\n const inverse = invert4(matrix);\n if (inverse) target = { depth: stack.length, inverse };\n }\n }\n stack.push({\n key: op.transform?.key,\n matrix,\n visible: scope.visible && op.transform?.visible !== false,\n box: null,\n });\n break;\n }\n case \"pop\": {\n /**\n * The root frame is never popped: `Node3D.render` brackets its own begin/end and `Scene3D.assertBalanced`\n * catches a hand-built scene that does not. Guarding keeps a malformed op list from reading past the stack.\n */\n if (stack.length === 1) break;\n if (target?.depth === stack.length - 1) target = null;\n const closed = stack.pop() as Scope3D;\n if (!closed.visible || !closed.box) break;\n if (closed.key !== undefined) boxes.set(closed.key, closed.box);\n const parent = top();\n parent.box = unionBox3(parent.box, closed.box);\n break;\n }\n case \"camera\": {\n descriptor = op.camera;\n camera = cameraMatrix4(op.camera, scope.matrix);\n break;\n }\n case \"light\":\n /** A light has no extent, so a node that is only a light gets no box and cannot be picked. */\n break;\n default: {\n if (!scope.visible) break;\n const drawn = drawableBox3(op, scope.matrix);\n if (drawn) scope.box = unionBox3(scope.box, drawn);\n if (target) localBounds = unionBox3(localBounds, drawableBox3(op, scope.matrix, target.inverse));\n break;\n }\n }\n }\n\n return {\n boxes,\n matrices,\n parentMatrices,\n camera: camera ?? DEFAULT_CAMERA_MATRIX,\n descriptor,\n localBounds,\n };\n}\n\nfunction scopeMatrix(parent: Matrix4, transform: Transform3D | undefined): Matrix4 {\n return multiply4(parent, transformMatrix4(transform, parent));\n}\n\n/** In world space, or in the frame `into` maps world space to. */\nfunction drawableBox3(op: Scene3DOp, parent: Matrix4, into?: Matrix4): Box3 | null {\n if (op.kind === \"model\") return null; // its extent arrives with the file\n if (!(\"transform\" in op)) return null;\n\n const world = scopeMatrix(parent, op.transform);\n const matrix = into ? multiply4(into, world) : world;\n\n if (op.kind === \"sprite\") {\n /**\n * Three's `Sprite` has no geometry to ask: the one place the extent is assumed rather than read (a\n * camera-facing unit quad scaled by its transform).\n */\n return transformBox3(centeredBox3(0.5, 0.5, 0), matrix);\n }\n\n if (!(\"geometry\" in op)) return null;\n const local = geometryBounds3D(op.geometry);\n if (!local) return null;\n\n if (op.kind === \"instances\") {\n /**\n * Every instance is placed inside the op's own transform, so the union is taken in that space and mapped out\n * once.\n */\n let box: Box3 | null = null;\n for (const instance of op.instances) {\n box = unionBox3(box, transformBox3(local, transformMatrix4(instance, null)));\n }\n return box ? transformBox3(box, matrix) : null;\n }\n\n return transformBox3(local, matrix);\n}\n\n/**\n * `lookAt` takes the camera branch of three's `Object3D.lookAt` (-Z at the target, where every other node aims\n * +Z), resolved against the camera's world position so a camera in an animated rig points where the author\n * said. See {@link lookAtRotation4}.\n *\n * The polar placement (`target`/`orbit`/`elevation`/`distance`) comes from {@link resolveCameraPlacement}, the\n * same call the renderer makes: two derivations of \"where is the camera\" could disagree, and a gizmo drawn\n * against a camera nobody renders is worse than none.\n */\nfunction cameraMatrix4(descriptor: CameraData3D, parent: Matrix4): Matrix4 {\n const placement = resolveCameraPlacement(descriptor);\n\n if (placement.lookAt === undefined) {\n return multiply4(parent, transformMatrix4({ ...descriptor, position: placement.position }, parent));\n }\n const placed = applyMatrix4(parent, placement.position);\n const origin: Vector3 = { x: placed.x, y: placed.y, z: placed.z };\n return multiply4(translation4(origin), lookAtRotation4(origin, placement.lookAt));\n}\n\n/**\n * Pulled back along +Z, aimed at the origin. Mirrors `applyCamera`'s fallback, which makes a bare `g.box()`\n * render, and so pickable.\n */\nconst DEFAULT_CAMERA_MATRIX: Matrix4 = multiply4(\n translation4({ x: 0, y: 0, z: 5 }),\n lookAtRotation4({ x: 0, y: 0, z: 5 }, { x: 0, y: 0, z: 0 }),\n);\n\nconst DEFAULT_FOV = 50;\nconst DEFAULT_NEAR = 0.1;\nconst DEFAULT_FAR = 1000;\n\nfunction projectionMatrix(descriptor: CameraData3D | null, aspect: number): Matrix4 {\n if (descriptor === null) {\n return perspective4(DEFAULT_FOV, aspect, DEFAULT_NEAR, DEFAULT_FAR, 1);\n }\n if (descriptor.type === \"perspective\") {\n return perspective4(\n descriptor.fov ?? DEFAULT_FOV,\n /**\n * Always the node's own aspect: overriding it stretched the render, so a gizmo could only be wrong by\n * agreeing with one.\n */\n aspect,\n descriptor.near ?? DEFAULT_NEAR,\n descriptor.far ?? DEFAULT_FAR,\n descriptor.zoom ?? 1,\n );\n }\n /**\n * `frustumHeight` sets the visible world height and the width follows the node's aspect. The same rule as\n * `applyCamera`, restated because that one lives in the renderer, which core cannot import.\n */\n const halfHeight = (descriptor.frustumHeight ?? 10) / 2;\n return orthographic4(\n -halfHeight * aspect,\n halfHeight * aspect,\n halfHeight,\n -halfHeight,\n descriptor.near ?? DEFAULT_NEAR,\n descriptor.far ?? DEFAULT_FAR,\n descriptor.zoom ?? 1,\n );\n}\n\ninterface Rect2D {\n minX: number;\n minY: number;\n maxX: number;\n maxY: number;\n}\n\nconst BOX_EDGES: readonly (readonly [number, number])[] = [\n [0, 1], [2, 3], [4, 5], [6, 7],\n [0, 2], [1, 3], [4, 6], [5, 7],\n [0, 4], [1, 5], [2, 6], [3, 7],\n];\n\n/** A point at `w = 0` is on the plane through the eye and projects to infinity. */\nconst MIN_CLIP_W = 1e-4;\n\n/**\n * How far outside the canvas a projected box may reach, as a multiple of the canvas's size. A box straddling\n * the eye plane genuinely extends to the horizon, which is a useless answer for an overlay (a rectangle a\n * million pixels wide). Clamping keeps it pointing the right way, and is only reached when the box is already\n * unusable as a target.\n */\nconst OFFSCREEN_LIMIT = 8;\n\n/**\n * The world box projected into the canvas's plane, plus its view-space depth. Edges are clipped rather than\n * corners clamped: a corner behind the eye projects reflected through the origin, so bounding the raw eight\n * would put the box on the wrong side. Entirely-behind boxes keep no edges, which is how a node behind the\n * camera stops being selectable.\n */\nfunction projectBox3(\n world: Box3,\n projection: Canvas3DProjection,\n): { rect: Rect2D; depth: number } | null {\n const corners = corners3(world);\n const clip = corners.map((corner) => applyMatrix4(projection.clip, corner));\n\n let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;\n let any = false;\n\n const include = (x: number, y: number, w: number) => {\n const ndcX = x / w;\n const ndcY = y / w;\n if (ndcX < minX) minX = ndcX;\n if (ndcY < minY) minY = ndcY;\n if (ndcX > maxX) maxX = ndcX;\n if (ndcY > maxY) maxY = ndcY;\n any = true;\n };\n\n for (const [a, b] of BOX_EDGES) {\n const p = clip[a];\n const q = clip[b];\n const pIn = p.w > MIN_CLIP_W;\n const qIn = q.w > MIN_CLIP_W;\n if (!pIn && !qIn) continue;\n if (pIn) include(p.x, p.y, p.w);\n if (qIn) include(q.x, q.y, q.w);\n if (pIn === qIn) continue;\n // Exactly one end is in front: cut the edge where `w` reaches the plane.\n const t = (MIN_CLIP_W - p.w) / (q.w - p.w);\n include(p.x + (q.x - p.x) * t, p.y + (q.y - p.y) * t, MIN_CLIP_W);\n }\n\n if (!any) return null;\n\n const halfWidth = projection.width / 2;\n const halfHeight = projection.height / 2;\n const limitX = halfWidth * OFFSCREEN_LIMIT;\n const limitY = halfHeight * OFFSCREEN_LIMIT;\n\n const rect: Rect2D = {\n minX: clamp(projection.centerX + minX * halfWidth, projection.centerX - limitX, projection.centerX + limitX),\n maxX: clamp(projection.centerX + maxX * halfWidth, projection.centerX - limitX, projection.centerX + limitX),\n minY: clamp(projection.centerY + minY * halfHeight, projection.centerY - limitY, projection.centerY + limitY),\n maxY: clamp(projection.centerY + maxY * halfHeight, projection.centerY - limitY, projection.centerY + limitY),\n };\n\n /**\n * Depth is taken at the box centre in view space (camera looks down -Z, so nearer is larger). One point rather\n * than eight: this orders \"which of two overlapping nodes did you mean\".\n */\n const centre: Vector3 = {\n x: (world.min.x + world.max.x) / 2,\n y: (world.min.y + world.max.y) / 2,\n z: (world.min.z + world.max.z) / 2,\n };\n const viewed = applyMatrix4(projection.view, centre);\n\n return { rect, depth: viewed.z };\n}\n\nfunction clamp(value: number, low: number, high: number): number {\n return value < low ? low : value > high ? high : value;\n}\n\nfunction rectContains(rect: Rect2D, point: Vector2, slop: number): boolean {\n return point.x >= rect.minX - slop\n && point.x <= rect.maxX + slop\n && point.y >= rect.minY - slop\n && point.y <= rect.maxY + slop;\n}\n\n/**\n * The corner mapping is {@link worldAnchors}': y flipped in and back out, since the CTM is canvas y-down and\n * everything around it y-up. Done here rather than via `worldAnchors` so the rect keeps its own centre: it is\n * axis-aligned in the canvas's plane but not centred on its origin.\n *\n * `rotation`, `scale` and `opacity` are the canvas's: a mesh's own mean nothing in two dimensions, and a host\n * reads these for the plane the box was drawn in.\n */\nfunction toNodeBox(node: Node3D, path: string, rect: Rect2D, frame: Canvas3DFrame): NodeBox {\n const at = (x: number, y: number): Vector2 => {\n const p = applyToPoint(frame.matrix, { x, y: -y });\n return { x: p.x, y: -p.y };\n };\n return {\n id: node.id,\n path,\n type: node.className,\n topLeft: at(rect.minX, rect.maxY),\n topRight: at(rect.maxX, rect.maxY),\n bottomRight: at(rect.maxX, rect.minY),\n bottomLeft: at(rect.minX, rect.minY),\n center: at((rect.minX + rect.maxX) / 2, (rect.minY + rect.maxY) / 2),\n width: rect.maxX - rect.minX,\n height: rect.maxY - rect.minY,\n rotation: frame.box.rotation,\n scale: frame.box.scale,\n opacity: frame.box.opacity,\n /**\n * A locked Canvas3D is already unpickable above, so reaching here means the viewport is free; a mesh locks on\n * its own account.\n */\n locked: node.locked,\n };\n}\n", "import { Node } from \"@/components/trees/node/node\";\nimport { Node2D, type NodeHandle } from \"@/components/trees/2d/node2d\";\nimport { Vector2 } from \"@/attributes/layout/vector2\";\nimport { Matrix2D, multiply, invert, applyToPoint, cameraMatrix, translation, isProjective } from \"@/attributes/layout/matrix2d\";\nimport { worldAnchors } from \"@/components/trees/2d/node-transform\";\nimport { spaceChildFrame, spaceChildOrder, spaceFrameForChildren, spaceFrameOf, spaceRootFrame } from \"@/components/trees/2d/node-space\";\nimport { multiplyAffine3, spaceScreenMatrix } from \"@/attributes/layout/space3d\";\nimport { nodePath } from \"@/project/tree\";\nimport { collectBoxes3D, isViewport3D, pickNode3D, projectNode3D, type Canvas3DFrame, type Node3DFrame, type Viewport3D } from \"./node-picking3d\";\nimport type { Vector3 } from \"@/render3d/vector3\";\n\n/**\n * Pure geometry for editor-style direct manipulation, with no controller state so it runs against hand-built\n * trees. Everything is in viewport space: origin at the viewport centre, y-up, units = viewport pixels. That\n * is `Node2D.global`'s space plus the camera (see {@link renderMatrix}).\n */\n\n/**\n * Unlike {@link Node2D.global} this folds in any active camera scope, so it describes where the pixels\n * actually landed, for a selection overlay.\n */\nexport interface NodeBox {\n /** Changes on every rebuild; key across rebuilds by {@link path}. */\n id: string;\n /** Structural path from the scene root (`\"\"` is the root); stable across rebuilds. */\n path: string;\n type: string;\n /** Rotated/scaled, not axis-aligned. */\n topLeft: Vector2;\n topRight: Vector2;\n bottomRight: Vector2;\n bottomLeft: Vector2;\n center: Vector2;\n /**\n * The node's layout size, or the ink's own extent where the two differ (see {@link Node2D._localBounds}; a\n * boolean group reports its children's ink).\n */\n width: number;\n height: number;\n /** Degrees clockwise, camera included. */\n rotation: number;\n scale: number;\n /** `0` means the node is present but invisible. */\n opacity: number;\n /**\n * The editor's padlock, see {@link NodeEditorState.locked}. A locked node is never returned by {@link\n * pickNode}; it appears in {@link collectBoxes} so a host can still outline one selected from its layer tree.\n */\n locked: boolean;\n}\n\n/**\n * The renderer's CTM at `node`: every ancestor's local matrix from the root down, with a camera scope wherever\n * an ancestor pushes one ({@link Node2D._cameraScope}). A node inside a 2.5D space is placed by its frame\n * instead (the projection from its plane to the space root's, built by `node-space.ts` as the renderer does),\n * so it is a homography and `nodeBox` reports the projected corners.\n *\n * Mirrors the render walk exactly, including the camera's `translate(rect.x, -rect.y)`: if a box disagrees\n * with the pixels, the divergence is here. Shared with `text-geometry.ts` so a caret and the box around its\n * node come from one walk.\n */\n/** @internal */\nexport function renderMatrix(node: Node2D): Matrix2D {\n const frame = spaceFrameOf(node);\n if (frame) return multiply(renderMatrix(frame.root), frame.screen);\n const parent = node.parent;\n return parent ? multiply(childrenMatrix(parent), node._localMatrix()) : node._localMatrix();\n}\n\n/**\n * Its render matrix, then whatever camera it opens. For a space root that is the camera over its own plane;\n * inside a space it is the parent's own frame, since a child's place is measured in its parent's plane.\n */\nfunction childrenMatrix(parent: Node2D): Matrix2D {\n const m = renderMatrix(parent);\n const camera = parent._spaceCamera();\n if (camera) return multiply(m, spaceRootFrame(parent, camera).screen);\n const cam = parent._cameraScope();\n if (!cam) return m;\n const r = parent.layoutBounds;\n return multiply(m, cameraMatrix(r.x, -r.y, cam.lookAt, cam.zoom, cam.heading));\n}\n\n/**\n * Where `point` lands on the plane the node at `path` moves in when its `x`/`y` change, in its parent's frame:\n * centred on the parent (on its slot for a node a parent places, see `ChildPlacement`), y-up, through any\n * camera in between and pushed out to the node's own `depth` in a space. `null` when the path names no 2D node\n * below the root, or the plane cannot be reached (edge-on, or the point is behind the camera).\n *\n * Two answers differ by exactly the `x`/`y` change that carries the node from one point to the other, which a\n * move handle needs once a node can sit in depth. Under a parent with coordinates of its own\n * (`Node2D._planeOf`) the answer is in them.\n */\nexport function parentPlanePointAt(root: Node2D, path: string, point: Vector2): Vector2 | null {\n if (path === \"\") return null;\n const node = nodeAt(root, path);\n const parent = node instanceof Node2D ? node.parent : null;\n if (!(node instanceof Node2D) || !parent) return null;\n const m = movePlaneMatrix(node, parent);\n const inv = invert(m);\n if (!inv) return null;\n const p = applyToPoint(inv, { x: point.x, y: -point.y });\n if (behindCamera(m, p)) return null;\n const plane = parent._planeOf(node);\n if (!plane) return { x: p.x, y: -p.y };\n // A slot's frame is already centred on the node's box; the parent's is not.\n const box = node._placement() ? null : node.layoutBounds;\n return plane.toCoords(p.x - (box?.x ?? 0), (box?.y ?? 0) - p.y);\n}\n\n/**\n * Where `point` lands in the coordinates the node at `path` positions its children in ({@link\n * Node2D._planeOf}): the `x`/`y` a child takes to be centred there. `null` when its children are positioned in\n * pixels, which is how a host tells the two apart.\n */\nexport function childPlanePointAt(root: Node2D, path: string, point: Vector2): Vector2 | null {\n const parent = nodeAt(root, path);\n if (!(parent instanceof Node2D)) return null;\n const plane = parent._planeOf(null);\n if (!plane) return null;\n const inv = invert(childrenMatrix(parent));\n if (!inv) return null;\n const p = applyToPoint(inv, { x: point.x, y: -point.y });\n return plane.toCoords(p.x, -p.y);\n}\n\n/**\n * What keeps the node at `path` looking the same once it moves under `parentPath`, as a design tool does: each\n * of `offsets` carried to the one that puts its centre at the same place, plus the `turn` to add to its\n * rotation and the `scale` to multiply by so the parents' own turn and scale, cameras included, are undone.\n * `null` when that parent arranges children in a run or grid, sits inside the node, or either is missing.\n */\nexport function reparentPlacementAt(\n root: Node2D, path: string, parentPath: string, offsets: readonly Vector2[],\n): ReparentPlacement | null {\n const node = nodeAt(root, path);\n const to = nodeAt(root, parentPath);\n const from = node instanceof Node2D ? node.parent : null;\n if (!(node instanceof Node2D) || !(from instanceof Node2D) || !(to instanceof Node2D)) return null;\n for (let at: Node | null = to; at; at = at.parent) if (at === node) return null;\n const box = node.layoutBounds;\n const plane = to._planeOf(null);\n const slot = plane ? null : to._slotFor({ width: box?.width ?? 0, height: box?.height ?? 0 });\n if (!plane && !slot) return null;\n const along = movePlaneMatrix(node, from);\n const back = invert(along);\n const into = invert(childrenMatrix(to));\n if (!back || !into) return null;\n\n const placed = node._placement();\n const was = childFold(from);\n const will = childFold(to);\n const turn = was.rotation + (placed?.rotation ?? 0) - will.rotation;\n const scale = will.scale === 0 ? 1 : (was.scale * (placed?.scale ?? 1)) / will.scale;\n const shift = node._centreShift(node.rotation + turn, node.scale * scale);\n\n // The plane the node's x/y move it on, where its centre is drawn now.\n const here = applyToPoint(back, applyToPoint(renderMatrix(node), { x: 0, y: 0 }));\n const own = from._planeOf(node);\n const pixels = (offset: Vector2): Vector2 => (own ? { ...own.toOffset(offset.x, offset.y) } : offset);\n const now = pixels({ x: node.x, y: node.y });\n const moved = offsets.map((offset) => {\n const o = pixels(offset);\n const drawn = applyToPoint(along, { x: here.x + o.x - now.x, y: here.y - (o.y - now.y) });\n const centre = applyToPoint(into, drawn);\n const x = centre.x - shift.x;\n const y = centre.y - shift.y;\n return plane ? plane.toCoords(x, -y) : { x: x - slot!.x, y: slot!.y - y };\n });\n return { offsets: moved, turn, scale };\n}\n\nexport interface ReparentPlacement {\n offsets: Vector2[];\n /** Degrees clockwise to add to the node's rotation. */\n turn: number;\n /** The factor to multiply the node's scale by. */\n scale: number;\n}\n\nfunction childFold(parent: Node2D): { rotation: number; scale: number } {\n const folded = foldedTransform(parent);\n const cam = parent._cameraScope();\n return cam ? { rotation: folded.rotation - cam.heading, scale: folded.scale * cam.zoom } : folded;\n}\n\nexport function nodeHandlesAt(root: Node2D, path: string): NodeHandle[] | null {\n const node = nodeAt(root, path);\n if (!(node instanceof Node2D)) return null;\n const m = renderMatrix(node);\n return node._handles().map(({ prop, at }) => {\n const p = applyToPoint(m, { x: at.x, y: -at.y });\n return { prop, at: { x: p.x, y: -p.y } };\n });\n}\n\n/** `null` when there is no such handle or the point is off the node's plane. */\nexport function handleValueAt(root: Node2D, path: string, prop: string, point: Vector2): Vector2 | null {\n const node = nodeAt(root, path);\n if (!(node instanceof Node2D)) return null;\n const m = renderMatrix(node);\n const inv = invert(m);\n if (!inv) return null;\n const p = applyToPoint(inv, { x: point.x, y: -point.y });\n if (behindCamera(m, p)) return null;\n return node._handleValue(prop, { x: p.x, y: -p.y });\n}\n\n/** The parent's frame at the node's depth, onto the screen: the plane its `x`/`y` slide it across. */\nfunction movePlaneMatrix(node: Node2D, parent: Node2D): Matrix2D {\n const frame = spaceFrameOf(node) ? spaceFrameForChildren(parent) : null;\n if (!frame) {\n // A slotted node's `x`/`y` move it within its slot, which may be turned.\n const slot = node._slotMatrix();\n return slot ? multiply(childrenMatrix(parent), slot) : childrenMatrix(parent);\n }\n const slot = node._slotAffine();\n const plane = slot ? multiplyAffine3(frame.view, slot) : frame.view;\n const atDepth = multiplyAffine3(plane, [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, node.depth]);\n return multiply(renderMatrix(frame.root), spaceScreenMatrix(frame.camera, atDepth));\n}\n\n/**\n * Under a perspective the inverse also answers for the plane's reflection behind the camera: a point there\n * projects to the same pixel with a negative `w` and is not on screen.\n */\nfunction behindCamera(m: Matrix2D, local: Vector2): boolean {\n return isProjective(m) && (m.g ?? 0) * local.x + (m.h ?? 0) * local.y + (m.i ?? 1) <= 0;\n}\n\n/**\n * The same accumulation as {@link Node2D.global}, extended with camera scopes: a camera multiplies scale by\n * its `zoom` and adds `-heading` to rotation (the renderer applies `rotate(-heading)`).\n */\nfunction foldedTransform(node: Node2D): { rotation: number; scale: number; opacity: number } {\n let rotation = 0;\n let scale = 1;\n let opacity = 1;\n for (let n: Node2D | null = node; n; n = n.parent) {\n const slot = n._placement();\n rotation += n.rotation + (slot?.rotation ?? 0);\n scale *= n.scale * (slot?.scale ?? 1);\n opacity *= n.opacity * (slot?.opacity ?? 1);\n // Skip the node's own camera: it scopes its children, not itself.\n const cam = n !== node ? n._cameraScope() : null;\n if (cam) {\n rotation -= cam.heading;\n scale *= cam.zoom;\n }\n }\n return { rotation, scale, opacity };\n}\n\nexport function nodeBox(node: Node2D, path: string): NodeBox {\n const b = node._localBounds();\n /**\n * `worldAnchors` maps offsets centred on the matrix's origin, so shift the matrix onto the bounds' own centre\n * first: that lets a node whose ink is off-centre report a box on the ink. The matrix is canvas y-down; the\n * bounds are y-up, hence the sign on y.\n */\n const m = b.x === 0 && b.y === 0\n ? renderMatrix(node)\n : multiply(renderMatrix(node), translation(b.x, -b.y));\n const anchors = worldAnchors(m, b.width / 2, b.height / 2);\n const folded = foldedTransform(node);\n return {\n id: node.id,\n path,\n type: node.className,\n topLeft: anchors.topLeft,\n topRight: anchors.topRight,\n bottomRight: anchors.bottomRight,\n bottomLeft: anchors.bottomLeft,\n center: anchors.center,\n width: b.width,\n height: b.height,\n rotation: folded.rotation,\n scale: folded.scale,\n opacity: folded.opacity,\n locked: node.locked,\n };\n}\n\n/**\n * The one entry point that answers for a 3D node too, which a bare {@link nodeBox} cannot: a mesh has no box\n * of its own, only a projection into the viewport that holds it, and finding that viewport is part of\n * resolving the path (see `node-picking3d.ts`). Walks {@link Node._allChildren}, the paths every structural\n * walk produces.\n */\nexport function nodeBoxAt(root: Node2D, path: string): NodeBox | null {\n if (path === \"\") return nodeBox(root, path);\n\n let node: Node = root;\n let canvas: { node: Viewport3D; path: string } | null = null;\n const segments = path.split(\".\");\n for (let i = 0; i < segments.length; i++) {\n if (isViewport3D(node)) canvas = { node, path: prefixPath(segments, i) };\n const next = node._allChildren[Number(segments[i])];\n if (!next) return null;\n node = next;\n }\n\n if (node instanceof Node2D) return nodeBox(node, path);\n /**\n * A `Node3D` cannot be parented anywhere but a viewport (the engine throws), so a `null` here is a malformed\n * tree.\n */\n if (!canvas) return null;\n const frame = canvas3DFrame(canvas.node, canvas.path);\n return collectBoxes3D(canvas.node, frame, canvas.path).find((box) => box.path === path) ?? null;\n}\n\n/**\n * The resolution half of {@link nodeBoxAt}, for callers that want the node\n * (`PlaybackController.getNodePropsAt`).\n */\nexport function nodeAt(root: Node2D, path: string): Node | null {\n if (path === \"\") return root;\n let node: Node = root;\n for (const segment of path.split(\".\")) {\n const next = node._allChildren[Number(segment)];\n if (!next) return null;\n node = next;\n }\n return node;\n}\n\nfunction prefixPath(segments: readonly string[], count: number): string {\n return segments.slice(0, count).join(\".\");\n}\n\n/**\n * A gizmo's counterpart to {@link nodeBoxAt}, for where an arbitrary point near the node lands on screen; see\n * {@link Node3DFrame}. `null` for a 2D path too: {@link nodeBox} already answers everything a 2D handle needs.\n */\nexport function projectNode3DAt(\n root: Node2D,\n path: string,\n parentPoints: readonly Vector3[],\n localPoints: readonly Vector3[],\n): Node3DFrame | null {\n if (path === \"\") return null;\n\n let node: Node = root;\n let canvas: { node: Viewport3D; path: string } | null = null;\n const segments = path.split(\".\");\n for (let i = 0; i < segments.length; i++) {\n if (isViewport3D(node)) canvas = { node, path: prefixPath(segments, i) };\n const next = node._allChildren[Number(segments[i])];\n if (!next) return null;\n node = next;\n }\n\n if (node instanceof Node2D || !canvas) return null;\n const frame = canvas3DFrame(canvas.node, canvas.path);\n return projectNode3D(canvas.node, frame, canvas.path, path, parentPoints, localPoints);\n}\n\n/**\n * Children paint over their parent and later siblings over earlier ones, so the walk tests children\n * last-to-first before the node itself.\n *\n * Skips fully transparent nodes (a scene built with spawn delays keeps not-yet-visible nodes at `opacity: 0`).\n * A node that clips, or pushes a camera, confines its subtree. The scene root is never returned.\n *\n * The hit region is {@link Node2D.hitTestSelf}: the rotated layout box by default, the declared outline for\n * shapes. `tolerance` is grab-slop in scene units applied outward from the ink; a host passes its\n * zoom-corrected pixel slop.\n *\n * Cost: {@link renderMatrix} walks to the root per node, so a pick is O(depth^2); scene trees are shallow,\n * fine at pointer rate. If it matters, thread the accumulated matrix down the walk.\n */\nexport function pickNode(root: Node2D, point: Vector2, tolerance = 0): NodeBox | null {\n return pickIn(root, \"\", point, tolerance, true);\n}\n\nfunction pickIn(node: Node2D, path: string, point: Vector2, tolerance: number, isRoot: boolean): NodeBox | null {\n if (node.opacity === 0 || node.hidden) return null;\n const drawn = spaceVisibility(node, isRoot);\n if (drawn === \"none\") return null;\n\n const inside = drawn === \"all\" && containsPoint(node, point, tolerance);\n /**\n * A clipping node (or one opening a camera viewport) gates its subtree, unless it draws nothing of its own.\n */\n if (!inside && drawn === \"all\" && node._confinesChildren()) return null;\n\n /**\n * A `Canvas3D`'s children come in both dimensions, and its 2D ones are indexed against the whole list; see\n * {@link childSlots}.\n */\n const children = childSlots(node);\n const order = paintOrder(node, children);\n for (let k = order.length - 1; k >= 0; k--) {\n const i = order[k];\n const slot = children[i];\n if (slot === null) continue;\n const hit = pickIn(slot, nodePath(path, i), point, tolerance, false);\n if (hit) return hit;\n }\n\n /**\n * The 3D scene draws under the 2D children and over the canvas's own fill, so it is tested in that order: a\n * HUD label beats the mesh behind it, the mesh beats the viewport.\n */\n if (isViewport3D(node) && inside) {\n const hit = pickNode3D(node, canvas3DFrame(node, path), point, tolerance, path);\n if (hit) return hit;\n }\n\n if (isRoot) return null;\n /**\n * A locked node declines to be the answer but still gated its subtree above, so a click inside a locked group\n * lands on nothing rather than falling through.\n */\n if (node.locked) return null;\n return inside ? nodeBox(node, path) : null;\n}\n\n/**\n * In draw order (parents before children). Skips `opacity: 0` nodes and the root, as {@link pickNode} does.\n *\n * A `Canvas3D` also contributes a box per `Node3D` inside it (see `node-picking3d.ts`), after the viewport's\n * own box and before its 2D children's, where the 3D pass is painted; among themselves near camera first.\n */\nexport function collectBoxes(node: Node2D, path: string, out: NodeBox[], isRoot: boolean): void {\n if (node.opacity === 0 || node.hidden) return;\n const drawn = spaceVisibility(node, isRoot);\n if (drawn === \"none\") return;\n /**\n * Locked nodes keep their box so a host can outline one picked from its layer tree; the box carries the flag\n * so a marquee can leave it out without a second walk.\n */\n if (!isRoot && drawn === \"all\") out.push(nodeBox(node, path));\n\n if (isViewport3D(node)) {\n for (const box of collectBoxes3D(node, canvas3DFrame(node, path), path)) out.push(box);\n }\n\n const children = childSlots(node);\n for (const i of paintOrder(node, children)) {\n const slot = children[i];\n if (slot !== null) collectBoxes(slot, nodePath(path, i), out, false);\n }\n}\n\n/**\n * `\"all\"` outside a space and for a node facing the camera; `\"children\"` for one edge-on or behind the lens,\n * whose own paint is skipped while its children, placed by frames of their own, are not; `\"none\"` for one the\n * renderer skips outright (a hidden back face, or a flattening node with nothing on screen).\n */\nfunction spaceVisibility(node: Node2D, isRoot: boolean): \"all\" | \"children\" | \"none\" {\n if (isRoot) return \"all\";\n const frame = spaceFrameOf(node);\n if (!frame) return \"all\";\n if (!node.backfaceVisible && frame.facesAway) return \"none\";\n if (frame.paints) return \"all\";\n return node._rendersChildrenInSpace() ? \"children\" : \"none\";\n}\n\n/**\n * The slots of `children` in the order the renderer paints them: authored\n * order, except among siblings in a space, which paint far to near.\n */\nfunction paintOrder(node: Node2D, children: readonly (Node2D | null)[]): number[] {\n const natural = children.map((_, i) => i);\n const frame = spaceFrameForChildren(node);\n if (!frame) return natural;\n const slots = natural.filter((i) => children[i] !== null);\n const frames = slots.map((i) => spaceChildFrame(frame, children[i]!));\n return spaceChildOrder(frames).map((k) => slots[k]);\n}\n\n/**\n * Everywhere but a `Canvas3D` this is just `children`. A `Canvas3D` holds both dimensions and its\n * `Node2D.children` drops the meshes, which would renumber its HUD children and hand each the path of an\n * earlier sibling; so its slots come from the authored list with the 3D ones blanked, keeping the document's\n * indices.\n */\nfunction childSlots(node: Node2D): readonly (Node2D | null)[] {\n if (!(isViewport3D(node))) return node.children;\n return node._allChildren.map((child) => (child instanceof Node2D ? child : null));\n}\n\nfunction canvas3DFrame(canvas: Viewport3D, path: string): Canvas3DFrame {\n return { box: nodeBox(canvas, path), matrix: renderMatrix(canvas) };\n}\n\nfunction containsPoint(node: Node2D, point: Vector2, tolerance: number): boolean {\n const m = renderMatrix(node);\n const inv = invert(m);\n if (!inv) return false; // zero scale — nothing to hit\n /**\n * The render matrix works in canvas (y-down) space and `worldAnchors` flips y in and out, so the inverse does\n * the same to land in the node's centred, y-up local frame (what `hitTestSelf` and the clip descriptors use).\n */\n const p = applyToPoint(inv, { x: point.x, y: -point.y });\n if (behindCamera(m, p)) return false;\n return node._hitTestSelf({ x: p.x, y: -p.y }, tolerance);\n}\n", "import { Node2D } from \"@/components/trees/2d/node2d\";\nimport { Text } from \"@/components/builtins/text/text\";\nimport { textStateOf } from \"@/components/modules/text-layout\";\nimport { Vector2 } from \"@/attributes/layout/vector2\";\nimport { applyToPoint } from \"@/attributes/layout/matrix2d\";\nimport { caretCount, type TextBlockSource } from \"@/render/text-layout\";\nimport { renderMatrix } from \"./node-picking\";\n\n/**\n * The measurement a host needs to draw its own text cursor and selection over the rendered glyphs. In viewport\n * space, as {@link NodeBox}, so a caret and its selection box come out of the same walk and cannot disagree.\n *\n * The host draws from these rather than approximating glyph positions itself: a DOM input laid over the canvas\n * drifts the moment the font, line height or wrapping does, and CSS `line-height` and the renderer's height\n * multiplier are not the same quantity.\n */\nexport interface NodeTextLayout {\n path: string;\n text: string;\n /**\n * `carets[i]` sits before character `i` and the last after the final character, so there are `text.length + 1`\n * and an offset is always a valid index. Each is a segment, not a point: a rotated node's cursor is a rotated\n * line, drawn from `top` to `bottom`.\n */\n carets: TextCaret[];\n /**\n * For Home/End and vertical arrow keys. A hard line break belongs to neither line, so `lines[n].end` and\n * `lines[n + 1].start` differ by one there.\n */\n lines: { start: number; end: number }[];\n}\n\nexport interface TextCaret {\n offset: number;\n top: Vector2;\n bottom: Vector2;\n}\n\nexport interface TextRangeQuad {\n topLeft: Vector2;\n topRight: Vector2;\n bottomRight: Vector2;\n bottomLeft: Vector2;\n}\n\n/**\n * `null` when it has none to report: not a {@link Text}, nothing shaped yet, or a shape the caret model does\n * not cover (see {@link RenderContext2D.layoutTextBlock}). The block-local layout comes from the backend,\n * where glyphs are positioned.\n */\nexport function nodeTextLayout(\n node: Node2D,\n path: string,\n source: TextBlockSource,\n): NodeTextLayout | null {\n // A text's state is what it last drew.\n const state = node instanceof Text ? textStateOf(node) : null;\n if (!state) return null;\n const block = source.layoutTextBlock(state);\n if (!block) return null;\n\n const m = renderMatrix(node);\n /**\n * The block is laid out about the node's own origin, which is also where `_localBounds` centres the box, so a\n * block-local offset is a node-local one. Block coordinates are canvas y-down, the space the matrix works in,\n * so unlike `worldAnchors` only the result is flipped to y-up.\n */\n const at = (x: number, y: number): Vector2 => {\n const p = applyToPoint(m, { x, y });\n return { x: p.x, y: -p.y };\n };\n\n const carets: TextCaret[] = new Array(caretCount(block));\n const lines: { start: number; end: number }[] = [];\n for (const line of block.lines) {\n lines.push({ start: line.start, end: line.end });\n for (let i = 0; i < line.carets.length; i++) {\n const x = line.carets[i];\n carets[line.start + i] = {\n offset: line.start + i,\n top: at(x, line.top),\n bottom: at(x, line.bottom),\n };\n }\n }\n\n return { path, text: (node as unknown as { text: string }).text, carets, lines };\n}\n\n/**\n * Nearest slot by distance to the caret segment, not its midpoint: a click below a short first line should\n * land on that line's nearest slot, and midpoints would pull it toward whichever line's centre is closer. It\n * also stays correct for rotated and scaled text, since the slots arrive transformed.\n */\nexport function caretOffsetAt(layout: NodeTextLayout, point: Vector2): number {\n let best = 0;\n let bestDistance = Infinity;\n for (const caret of layout.carets) {\n const d = distanceToSegment(point, caret.top, caret.bottom);\n if (d < bestDistance) {\n bestDistance = d;\n best = caret.offset;\n }\n }\n return best;\n}\n\n/**\n * One per line the range touches, because a range spanning a line break covers two disjoint areas and one\n * enclosing box would paint over the gap.\n */\nexport function caretRangeQuads(\n layout: NodeTextLayout,\n start: number,\n end: number,\n): TextRangeQuad[] {\n const from = Math.max(0, Math.min(start, end));\n const to = Math.min(layout.carets.length - 1, Math.max(start, end));\n const quads: TextRangeQuad[] = [];\n for (const line of layout.lines) {\n const a = Math.max(from, line.start);\n const b = Math.min(to, line.end);\n if (a >= b) continue; // empty on this line\n const left = layout.carets[a];\n const right = layout.carets[b];\n quads.push({\n topLeft: left.top,\n topRight: right.top,\n bottomRight: right.bottom,\n bottomLeft: left.bottom,\n });\n }\n return quads;\n}\n\nfunction distanceToSegment(p: Vector2, a: Vector2, b: Vector2): number {\n const dx = b.x - a.x;\n const dy = b.y - a.y;\n const lengthSq = dx * dx + dy * dy;\n // A degenerate segment (a zero-height line box) is just a point.\n const t = lengthSq === 0\n ? 0\n : Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / lengthSq));\n return Math.hypot(p.x - (a.x + t * dx), p.y - (a.y + t * dy));\n}\n", "import { AssetManager } from \"../assets/manager\";\nimport { MeasureContext2D } from \"../render/measure-context\";\nimport { CanvasRenderContext2D } from \"../render/canvas-render-context2d\";\nimport { asTextBlockSource } from \"../render/text-layout\";\nimport { renderIssueKey, toRenderIssue, type RenderIssue } from \"../render/render-issue\";\nimport { StateEvaluator } from \"./state-evaluator\";\nimport { renderSettled, SETTLE_PASSES, type SettleOutcome } from \"./settle\";\nimport { NodeState, TreeState, WaveformInfo, nodePath } from \"@/project/tree\";\nimport { AudioRequest } from \"@/attributes/audio/request\";\nimport { StorageAdapter } from \"../platform/storage-adapter\";\nimport { BuildError, AssetTimeline, AssetTimelineResult, type AssetTimelineProfile } from \"./asset-timeline\";\nimport { ClipStore, DEFAULT_PRECOMP_BUDGET_MS } from \"./clip-store\";\nimport type { AssetDecl } from \"@/assets/scope\";\nimport { yieldToScheduler } from \"@/util/scheduler\";\nimport { Ticker, TimeCallback } from \"@/platform/ticker\";\nimport { AudioSink } from \"@/platform/audio-sink\";\nimport { AssetCatalog } from \"@/assets/catalog\";\nimport { AssetNotLoadedError } from \"@/assets/errors\";\nimport type { AssetRecord } from \"@/assets/record\";\nimport { Size2D } from \"@/attributes/layout/size\";\nimport { Node } from \"@/components/trees/node/node\";\nimport { Node2D, type NodeHandle } from \"@/components/trees/2d/node2d\";\nimport type { NodeEditorStates } from \"@/components/trees/node/node-editor-state\";\nimport type { ProjectDocument } from \"@/document/project\";\nimport type { Registry } from \"@/document/registry\";\nimport { Vector2 } from \"@/attributes/layout/vector2\";\nimport { NodeBox, childPlanePointAt, collectBoxes, handleValueAt, nodeAt, nodeBoxAt, nodeHandlesAt, parentPlanePointAt, pickNode, projectNode3DAt, reparentPlacementAt, type ReparentPlacement } from \"./node-picking\";\nimport type { Node3DFrame } from \"./node-picking3d\";\nimport type { Vector3 } from \"@/render3d/vector3\";\nimport { NodeTextLayout, nodeTextLayout } from \"./text-geometry\";\nimport { spanFrames, spansCovering, trackFrameCount, type TrackSpan } from \"./placement\";\nimport { clipFrameToTime, clipTimeToFrame } from \"./frame-time\";\n\n/** Keys are prop names the node accepts; see {@link PlaybackController.setNodeOverride}. */\nexport type NodeOverride = Record<string, unknown>;\n\nexport type ControllerParams = {\n project: ProjectDocument;\n registry: Registry;\n renderContext: CanvasRenderContext2D;\n measurer: MeasureContext2D;\n storageAdapter: StorageAdapter;\n masterClock: Ticker;\n audioDevice: AudioSink;\n assets: AssetCatalog;\n /**\n * Wall-clock ms background discovery may run before yielding. `0` in tests yields between every sample\n * interval, making preemption deterministic.\n */\n precompBudgetMs?: number;\n precompProfile?: AssetTimelineProfile;\n /** Passed at construction so a fast first track cannot publish before the caller attaches. */\n onPrecompProgress?: (result: AssetTimelineResult) => void;\n};\n\n/**\n * Plays a project document: discovers what frame 0 needs, then streams the rest of the asset timeline in\n * behind the first paint. Each tick loads the frame's assets, evaluates and lays out the tracks on screen,\n * renders, then prefetches upcoming frames.\n */\nexport class PlaybackController {\n private renderContext: CanvasRenderContext2D;\n private measurer: MeasureContext2D;\n private storageAdapter: StorageAdapter;\n private masterClock: Ticker;\n private stateEvaluator: StateEvaluator;\n private assetManager: AssetManager;\n private audioDevice: AudioSink;\n /**\n * Held because {@link recoverMissingAsset} must build a record for a source no pass declared, from what the\n * catalog knows of it.\n */\n private readonly assetCatalog: AssetCatalog;\n /**\n * Called synchronously at the end of every painted frame, on the same task as the draw, for a host drawing\n * over the canvas (a selection box, a caret) that must measure the tree for the frame just drawn rather than\n * trail a fast scrub. Called after the draw, so a throwing listener is never mistaken for a render failure.\n */\n onFramePainted?: (frame: number) => void;\n\n private disposed = false;\n private precompRunning = false;\n /**\n * Every render pass but {@link repaint} loads the frame's assets first, so `repaint` waits on this before\n * drawing one of its own.\n */\n private hasPainted = false;\n /**\n * Bumped by every seek, tick and swap. A render pass captures it at entry and bails before painting if a newer\n * pass began, so a superseded seek never stamps a stale frame over a newer one.\n */\n private seekGeneration = 0;\n private readonly precompBudgetMs: number;\n private readonly onPrecompProgress?: (result: AssetTimelineResult) => void;\n readonly fps: number;\n readonly viewport: Size2D;\n private readonly precomper: AssetTimeline;\n private readonly store: ClipStore;\n /**\n * Re-applied after every state evaluation, keyed by structural path so they survive a rebuild. See {@link\n * setNodeOverride}.\n */\n private readonly overrides = new Map<string, NodeOverride>();\n precomp: AssetTimelineResult;\n\n get spans(): readonly TrackSpan[] {\n return this.precomp.tracks.map((track, index) => ({\n id: track.id,\n index,\n startFrame: track.startFrame,\n endFrame: track.startFrame + track.frameCount - 1,\n }));\n }\n\n get totalFrames(): number {\n return this.precomp.totalFrames;\n }\n\n get totalDuration(): number {\n return this.precomp.totalDuration;\n }\n\n get currentTrackId(): string | null {\n return this.stateEvaluator.currentTrackId;\n }\n\n /**\n * Discovery errors plus any thrown while drawing: one list, because a consumer says the same thing about both\n * (this frame is not what the document says).\n */\n get buildErrors(): BuildError[] {\n if (this.renderErrors.length === 0) return this.precomp.buildErrors;\n return [...this.precomp.buildErrors, ...this.renderErrors];\n }\n\n /**\n * Deduplicated by message. A render throws per frame, at pointer rate while scrubbing, and left to propagate\n * it would be an unhandled rejection and a canvas that stopped drawing.\n */\n private readonly renderErrors: BuildError[] = [];\n\n onRenderError?: (errors: BuildError[]) => void;\n\n /**\n * Swallowing is the point: one bad frame must not take down the clock loop. Reported once per distinct\n * message.\n */\n private captureRenderError(error: unknown, frame?: number, issue?: RenderIssue): void {\n const e = error instanceof Error ? error : new Error(String(error));\n /**\n * A frame can reach for an asset no pass declared (an override previewing an edit puts a picture on a node\n * before the rebuild that would declare it has run). The error names the source, so load it and paint again.\n */\n if (frame !== undefined && this.recoverMissingAsset(e, frame)) return;\n if (issue) {\n const key = renderIssueKey(issue);\n if (this.renderErrors.some((prior) => prior.issue && renderIssueKey(prior.issue) === key)) return;\n } else if (this.renderErrors.some((prior) => !prior.issue && prior.message === e.message)) return;\n this.renderErrors.push({\n trackId: this.stateEvaluator.currentTrackId ?? \"\",\n message: e.message,\n ...(issue ? { issue, ...(issue.nodeId !== undefined && { nodeId: issue.nodeId }) } : { stack: e.stack }),\n });\n this.onRenderError?.(this.buildErrors);\n }\n\n /**\n * Widen the drawing track's index by what the draw found missing, so the next visit to this frame loads it\n * ahead. The owner is the node the error names, else whoever declared the source elsewhere in the clip.\n */\n private learnMissingAsset(error: AssetNotLoadedError, frame: number): void {\n const decl = declOf(error, this.assetCatalog);\n if (!decl) return;\n for (const trackId of [...this.stateEvaluator.activeTrackIds].reverse()) {\n const instance = this.store.instanceOf(trackId);\n const track = this.precomp.tracks.find((t) => t.id === trackId);\n if (!instance || !track) continue;\n let ownerKey: string | undefined;\n if (error.nodeId !== undefined) {\n instance.forEachOwner((node, key) => {\n if (ownerKey === undefined && node.id === error.nodeId) ownerKey = key;\n });\n }\n ownerKey ??= this.store.ownersOf(trackId, error.src).values().next().value;\n if (ownerKey === undefined) continue;\n const next = this.precomper.learn(trackId, ownerKey, decl, Math.floor(frame) - track.startFrame);\n if (next !== this.precomp) this.adoptPrecomp(next);\n return;\n }\n }\n\n /**\n * Sources already tried by {@link recoverMissingAsset}, so a picture that cannot be fetched is reported rather\n * than re-fetched every frame of a drag. Cleared by {@link clearRenderErrors}.\n */\n private readonly rescuedAssets = new Set<string>();\n\n /**\n * Deliberately narrow: only {@link AssetNotLoadedError}, only a source the catalog can describe, once per\n * source.\n */\n private recoverMissingAsset(error: Error, frame: number): boolean {\n if (!(error instanceof AssetNotLoadedError)) return false;\n // Audio is fetched on demand by the audio device, not through the storage adapter.\n if (error.assetType === \"audio\") return false;\n const token = `${error.assetType}:${error.src}`;\n if (this.rescuedAssets.has(token)) return false;\n this.rescuedAssets.add(token);\n // Once per source, like the rescue: a source that never loads would otherwise republish every frame.\n this.learnMissingAsset(error, frame);\n\n const record = this.recordFor(error.assetType, error.src, frame);\n if (!record) return false;\n\n void this.storageAdapter.loadAsset(error.src, record)\n .then(() => {\n if (this.disposed) return;\n this.renderAt(this.stateEvaluator.currentFrame);\n this.settleTrailing();\n })\n .catch((cause) => {\n if (this.disposed) return;\n // No `frame`, so it cannot come back through here a second time.\n this.captureRenderError(\n new Error(`${error.message}\\n\\nLoading it directly also failed: ${String(cause)}`),\n );\n });\n return true;\n }\n\n /** `null` when the catalog has never heard of `src`. */\n private recordFor(type: AssetNotLoadedError[\"assetType\"], src: string, frame: number): AssetRecord | null {\n try {\n if (type === \"font\") {\n // 400 is what an unsuffixed font key assumes.\n return {\n type: \"font\", src, startFrame: frame, endFrame: frame,\n fontFamily: src, fontWeight: 400,\n };\n }\n if (type === \"image\") {\n // Throws for a source the catalog has never heard of.\n this.assetCatalog.getImageMeta(src);\n return { type: \"image\", src, startFrame: frame, endFrame: frame };\n }\n this.assetCatalog.getVideoMeta(src);\n return {\n type: \"video\", src, startFrame: frame, endFrame: frame,\n trimStart: 0, trimEnd: this.assetCatalog.getVideoDuration(src),\n };\n } catch {\n return null;\n }\n }\n\n clearRenderErrors(): void {\n this.rescuedAssets.clear();\n if (this.renderErrors.length === 0) return;\n this.renderErrors.length = 0;\n this.onRenderError?.(this.buildErrors);\n }\n\n constructor(params: ControllerParams) {\n const { project } = params;\n if (project.fps === undefined || project.viewport === undefined) {\n throw new Error(\"PlaybackController takes a project whose fps and viewport are resolved — see Session.\");\n }\n this.renderContext = params.renderContext;\n this.measurer = params.measurer;\n this.masterClock = params.masterClock;\n this.storageAdapter = params.storageAdapter;\n this.audioDevice = params.audioDevice;\n this.fps = project.fps;\n this.viewport = project.viewport;\n this.precompBudgetMs = params.precompBudgetMs ?? DEFAULT_PRECOMP_BUDGET_MS;\n this.onPrecompProgress = params.onPrecompProgress;\n this.assetCatalog = params.assets;\n\n const scope = {\n registry: params.registry,\n viewport: this.viewport,\n fps: this.fps,\n assets: params.assets,\n measurer: this.measurer,\n };\n this.store = new ClipStore(project, scope, {\n profile: params.precompProfile,\n // Nothing is resident before the manager exists, which is what the first build should see.\n isReady: (key) => this.assetManager?.isReady(key) ?? false,\n });\n this.precomper = new AssetTimeline(project, scope, { store: this.store });\n /**\n * Only what frame 0 needs; the rest streams in behind the first paint, so time-to-first-frame is O(tracks on\n * screen), not O(project).\n */\n this.precomp = this.precomper.ensureCovering(0);\n this.stateEvaluator = new StateEvaluator(project, scope, this.store);\n this.assetManager = new AssetManager(\n this.precomp, this.storageAdapter, this.audioDevice,\n (error) => this.captureRenderError(error),\n );\n\n this.masterClock.setDuration(this.totalDuration);\n\n this.masterClock.onPlay((t, speed, reverse) => {\n this.audioDevice.play(t, speed, reverse);\n this.storageAdapter.setPlaying(true);\n });\n this.masterClock.onPause(() => {\n this.audioDevice.stop();\n this.storageAdapter.setPlaying(false);\n });\n this.masterClock.onTick(async (currentTime: number) => {\n /**\n * A tick is also a render pass: claim a generation so a stale paused seek cannot paint after the clock moved\n * on, and vice versa.\n */\n const gen = ++this.seekGeneration;\n const frame = clipTimeToFrame(currentTime, this.fps);\n if (frame >= this.totalFrames) this.masterClock.pause();\n this.discoverThrough(frame);\n await this.loadFrame(frame);\n if (!this.isCurrent(gen)) return;\n this.audioDevice.syncTo(currentTime);\n this.renderAt(frame);\n this.assetManager.prefetch(frame);\n this.trimAround(frame);\n });\n\n this.startBackgroundPrecomp();\n }\n\n /** Deferred behind a yield so the first frame paints before this competes for the main thread. */\n private startBackgroundPrecomp(): void {\n if (this.precompRunning || this.disposed || this.precomp.complete) return;\n this.precompRunning = true;\n void (async () => {\n try {\n await yieldToScheduler();\n /**\n * Looped: a document swapped in during the pass's last step has no yield left for the pass to notice it by.\n */\n while (!this.disposed && !this.precomp.complete) {\n const final = await this.precomper.runAsync({\n budgetMs: this.precompBudgetMs,\n isCancelled: () => this.disposed,\n onProgress: result => this.adoptPrecomp(result),\n });\n if (this.disposed) return;\n if (!this.precomp.complete) this.adoptPrecomp(final);\n }\n } finally {\n this.precompRunning = false;\n }\n })();\n }\n\n /**\n * `setPrecomp` resets the asset manager's audio signature, which reschedules audio a new result changed.\n */\n private adoptPrecomp(next: AssetTimelineResult): void {\n if (this.disposed) return;\n this.precomp = next;\n this.assetManager.setPrecomp(next);\n this.masterClock.setDuration(this.totalDuration);\n this.onPrecompProgress?.(next);\n }\n\n /**\n * A track nobody discovered has no asset windows, so its frame would reach for decodes nothing loaded. Cheap\n * once they are: runs every tick.\n */\n private discoverThrough(frame: number): void {\n const next = this.precomper.ensureCovering(Math.floor(frame));\n if (next !== this.precomp) this.adoptPrecomp(next);\n }\n\n /**\n * Also the layout gates of every track covering it: a face must be resident before text measures, whatever its\n * window says.\n */\n private async loadFrame(frame: number): Promise<void> {\n const gates: AssetRecord[] = [];\n for (const span of spansCovering(this.store.spans, Math.floor(frame))) {\n for (const record of this.store.layoutGates(span.id)) {\n if (!this.assetManager.isReady(record.src)) gates.push(record);\n }\n }\n if (gates.length === 0) {\n await this.assetManager.loadAt(frame);\n return;\n }\n await Promise.all([this.assetManager.loadAt(frame), this.assetManager.loadRecords(gates)]);\n }\n\n private trimAround(frame: number): void {\n if (Math.abs(frame - this.lastTrimFrame) < this.fps) return;\n this.lastTrimFrame = frame;\n this.store.trim(Math.floor(frame), Math.ceil(TRIM_HORIZON_SECONDS * this.fps));\n }\n\n private lastTrimFrame = 0;\n\n get isPlaying(): boolean {\n return this.masterClock.isPlaying;\n }\n\n get currentTime(): number {\n return this.masterClock.currentTime;\n }\n\n get currentFrame(): number {\n return clipTimeToFrame(this.masterClock.currentTime, this.fps);\n }\n\n onTime(cb: TimeCallback): void {\n this.masterClock.onTime(cb);\n }\n\n onPlay(cb: () => void): void {\n this.masterClock.onPlay(() => cb());\n }\n\n onPause(cb: () => void): void {\n this.masterClock.onPause(cb);\n }\n\n private isCurrent(gen: number): boolean {\n return !this.disposed && gen === this.seekGeneration;\n }\n\n private renderAt(frame: number): void {\n /**\n * A disposed controller's surface is freed; an in-flight seek (StrictMode double-mount, HMR) can resolve after\n * `dispose()`.\n */\n if (this.disposed) return;\n this.hasPainted = true;\n this.renders++;\n try {\n /** A track whose compile measured a face before it loaded builds again now that it has. */\n this.store.settleGates(spansCovering(this.store.spans, Math.floor(frame)).map((span) => span.id));\n /**\n * Inside the guard too: a command can throw at a time, and a missing font throws while measuring.\n */\n this.stateEvaluator.stateAt(frame);\n /**\n * After evaluation, before layout: an override beats what the document evaluated to, and layout sees it.\n */\n this.applyOverrides();\n this.stateEvaluator.layout(this.measurer);\n this.renderContext.execute(() => {\n this.stateEvaluator.render(this.renderContext);\n });\n for (const raw of this.renderContext.takeRenderIssues()) {\n const issue = toRenderIssue(raw);\n this.captureRenderError(new Error(issue.message), undefined, issue);\n }\n } catch (error) {\n this.captureRenderError(error, frame);\n }\n this.announcePaint(frame);\n }\n\n private announcePaint(frame: number): void {\n if (!this.onFramePainted) return;\n try {\n this.onFramePainted(Math.floor(frame));\n } catch (error) {\n console.error(\"[PlaybackController] onFramePainted listener threw:\", error);\n }\n }\n\n /** Pauses playback first. Waits for required assets before rendering, then prefetches upcoming frames. */\n async seek(frame: number): Promise<void> {\n if (this.disposed) return;\n const gen = ++this.seekGeneration;\n this.paintInFlight = gen;\n try {\n const clamped = Math.max(0, Math.min(frame, this.totalFrames));\n this.masterClock.pause();\n this.discoverThrough(clamped);\n this.masterClock.seek(clipFrameToTime(clamped, this.fps));\n await this.loadFrame(clamped);\n if (!this.isCurrent(gen)) return;\n /**\n * A cold seek can land on a video frame or image no draw has asked for yet: the render asks, the adapter\n * warms, the frame paints again.\n */\n if (await this.settle(() => this.renderAt(clamped), gen) === \"superseded\") return;\n this.assetManager.prefetch(clamped);\n this.trimAround(clamped);\n } finally {\n this.paintLanded(gen);\n }\n }\n\n /**\n * A track whose clip is unchanged keeps its tree and discovery; one whose clip patches in place re-declares\n * only the owners the edit can reach, and republishes the asset timeline only when that changed it.\n *\n * The swap does not paint: it loads the frame's assets first and the canvas keeps the last complete frame\n * until then, better than a current frame with a hole where an added picture has not arrived. See {@link\n * pendingSwap}.\n */\n setProject(next: ProjectDocument): void {\n if (this.disposed) return;\n /**\n * Claimed before anything is touched, so a seek parked on a yield unwinds rather than painting into a timeline\n * that moved under it.\n */\n const gen = ++this.seekGeneration;\n\n this.precomper.setProject(next);\n this.stateEvaluator.setProject(next);\n // Adopts only when the swap changed what is published — an edit no declaration read changes nothing.\n this.discoverThrough(this.currentFrame);\n this.clearRenderErrors();\n this.masterClock.setDuration(this.totalDuration);\n\n // The timeline may now be shorter than where the playhead sat.\n const frame = Math.min(this.currentFrame, Math.max(0, this.totalFrames - 1));\n this.pendingSwap = gen;\n this.paintInFlight = gen;\n this.lastReplacePaint = this.loadAndRepaint(frame, gen);\n this.startBackgroundPrecomp();\n }\n\n /**\n * Build every track again and repaint, as a swap to the same document would if it could tell: a clip that\n * failed for want of an entry the catalog now has builds, and one measured against an old size is measured\n * again.\n */\n reconcileCatalog(): void {\n if (this.disposed) return;\n this.store.reset();\n this.setProject(this.store.project);\n }\n\n whenReplaced(): Promise<void> {\n return this.lastReplacePaint;\n }\n\n private lastReplacePaint: Promise<void> = Promise.resolve();\n\n /**\n * The generation claimed by the swap whose paint has not landed, or `0`. {@link repaint} stands down while it\n * names the current generation: the swap owes a paint that reads every override as it stands. A generation,\n * not a flag, because a seek can supersede the swap and an uncleared flag would disable `repaint` for the\n * session.\n */\n private pendingSwap = 0;\n\n private async loadAndRepaint(frame: number, gen: number): Promise<void> {\n try {\n try {\n await this.loadFrame(frame);\n } catch (err) {\n console.error(\"[PlaybackController] swap asset load failed:\", err);\n return;\n }\n await this.settle(() => this.renderAt(frame), gen);\n } finally {\n // Only this swap's claim is released: a newer one has written its own.\n if (this.pendingSwap === gen) this.pendingSwap = 0;\n this.paintLanded(gen);\n }\n }\n\n /** Reposition the clock to `frame` without interrupting playback. */\n seekWhilePlaying(frame: number): void {\n // Invalidate any in-flight paused seek so its late render can't paint over\n // the live playback position.\n ++this.seekGeneration;\n const clamped = Math.max(0, Math.min(frame, this.totalFrames));\n this.masterClock.seek(clipFrameToTime(clamped, this.fps));\n }\n\n /**\n * Renders afresh (the drawing buffer may have been cleared since the last tick) and loads the frame's assets\n * first.\n */\n async screenshot(): Promise<string | undefined> {\n const frame = this.stateEvaluator.currentFrame;\n const gen = ++this.seekGeneration;\n this.paintInFlight = gen;\n try {\n await this.loadFrame(frame);\n if (!this.isCurrent(gen)) return undefined;\n // A capture is kept, not glanced at, so it waits for the upgrades a preview paints behind.\n if (await this.settle(() => this.renderAt(frame), gen, true) === \"superseded\") return undefined;\n return this.renderContext.screenshot();\n } finally {\n this.paintLanded(gen);\n }\n }\n\n private async settle(render: () => void, gen: number, upgrades = false): Promise<SettleOutcome> {\n const adapter = upgrades ? settlingUpgrades(this.storageAdapter) : this.storageAdapter;\n const outcome = await renderSettled(render, adapter, () => this.isCurrent(gen));\n if (outcome === \"exhausted\") {\n console.warn(`[PlaybackController] frame ${this.stateEvaluator.currentFrame} still had decodes pending after ${SETTLE_PASSES} passes`);\n }\n return outcome;\n }\n\n /**\n * The generation of the seek, swap or screenshot still on its way to its paint, or `0`. A repaint behind\n * decodes leaves that paint to it; see {@link settleTrailing}.\n */\n private paintInFlight = 0;\n\n private renders = 0;\n\n private repaintOwedSince: number | null = null;\n\n /** Unless a newer paint has claimed since; repaints behind what it drew. */\n private paintLanded(gen: number): void {\n if (this.paintInFlight !== gen || this.disposed) return;\n this.paintInFlight = 0;\n if (this.repaintOwedSince !== null) {\n const stale = this.renders === this.repaintOwedSince;\n this.repaintOwedSince = null;\n if (stale && !this.isPlaying) this.renderAt(this.stateEvaluator.currentFrame);\n }\n this.settleTrailing();\n }\n\n /**\n * With each node's frame range on the project timeline and its waveforms attached. `null` before any track is\n * built.\n */\n getTreeState(): TreeState | null {\n const instance = this.stateEvaluator.currentInstance;\n if (!instance) return null;\n const track = this.precomp.tracks.find(t => t.id === this.stateEvaluator.currentTrackId);\n const trackStart = track?.startFrame ?? 0;\n const frameCount = track?.frameCount ?? trackFrameCount(instance.duration, this.fps);\n\n const bars = new Map<string, { startFrame: number; endFrame: number }>();\n const pathOfOwner = new Map<string, string>();\n instance.forEachOwner((_node, ownerKey, span, path) => {\n pathOfOwner.set(ownerKey, path);\n const frames = spanFrames(span, this.fps, frameCount);\n if (frames) {\n bars.set(path, { startFrame: trackStart + frames.startFrame, endFrame: trackStart + frames.endFrame });\n }\n });\n const waveformsByPath = waveformsByOwner(track?.audioRequests ?? [], pathOfOwner);\n return nodeToTreeState(instance.canvas, \"\", bars, waveformsByPath);\n }\n\n getNodeState(nodeId: string): NodeState | null {\n const canvas = this.stateEvaluator.currentCanvas;\n if (!canvas) return null;\n const node = findNode(canvas, nodeId);\n if (!node) return null;\n return { id: node.id, type: node.className, properties: node.properties };\n }\n\n /**\n * What a document node holds before any command acted on it, whatever frame is showing: the props an editor\n * shows for the node itself, where {@link getNodeState} is the node at this frame.\n */\n getNodeInitialProps(nodeId: string): NodeState[\"properties\"] | null {\n return this.stateEvaluator.currentInstance?.baselineProps(nodeId) ?? null;\n }\n\n getNodeBox(path: string): NodeBox | null {\n const canvas = this.stateEvaluator.currentCanvas;\n if (!canvas) return null;\n // Through `nodeBoxAt`, so a path naming a mesh inside a `Canvas3D`\n // resolves too — see `node-picking3d.ts`.\n return nodeBoxAt(canvas, path);\n }\n\n /** In the node's own coordinate space, the space {@link setNodeOverride} writes into. */\n getNodePropsAt(path: string): NodeState[\"properties\"] | null {\n const canvas = this.stateEvaluator.currentCanvas;\n if (!canvas) return null;\n const node = nodeAt(canvas, path);\n return node ? node.properties : null;\n }\n\n getNodeBoxes(): NodeBox[] {\n const canvas = this.stateEvaluator.currentCanvas;\n if (!canvas) return [];\n const out: NodeBox[] = [];\n collectBoxes(canvas, \"\", out, true);\n return out;\n }\n\n projectNode3D(\n path: string,\n parentPoints: readonly Vector3[],\n localPoints: readonly Vector3[],\n ): Node3DFrame | null {\n const canvas = this.stateEvaluator.currentCanvas;\n if (!canvas) return null;\n return projectNode3DAt(canvas, path, parentPoints, localPoints);\n }\n\n parentPlanePoint(path: string, point: Vector2): Vector2 | null {\n const canvas = this.stateEvaluator.currentCanvas;\n if (!canvas) return null;\n return parentPlanePointAt(canvas, path, point);\n }\n\n childPlanePoint(path: string, point: Vector2): Vector2 | null {\n const canvas = this.stateEvaluator.currentCanvas;\n if (!canvas) return null;\n return childPlanePointAt(canvas, path, point);\n }\n\n reparentPlacement(path: string, parentPath: string, offsets: readonly Vector2[]): ReparentPlacement | null {\n const canvas = this.stateEvaluator.currentCanvas;\n if (!canvas) return null;\n return reparentPlacementAt(canvas, path, parentPath, offsets);\n }\n\n nodeHandles(path: string): NodeHandle[] | null {\n const canvas = this.stateEvaluator.currentCanvas;\n if (!canvas) return null;\n return nodeHandlesAt(canvas, path);\n }\n\n handleValue(path: string, prop: string, point: Vector2): Vector2 | null {\n const canvas = this.stateEvaluator.currentCanvas;\n if (!canvas) return null;\n return handleValueAt(canvas, path, prop, point);\n }\n\n /** `null` when the path does not resolve, the node is not text, or the measurer has no caret model. */\n getTextLayout(path: string): NodeTextLayout | null {\n const canvas = this.stateEvaluator.currentCanvas;\n if (!canvas) return null;\n const node = findNodeByPath(canvas, path);\n return node instanceof Node2D\n ? this.textLayoutOf(node, path)\n : null;\n }\n\n private textLayoutOf(node: Node2D, path: string): NodeTextLayout | null {\n const source = asTextBlockSource(this.measurer);\n return source ? nodeTextLayout(node, path, source) : null;\n }\n\n /** `tolerance` is grab-slop in scene units: the host's pixel slop divided by its preview zoom. */\n pickNode(point: Vector2, tolerance = 0): NodeBox | null {\n const canvas = this.stateEvaluator.currentCanvas;\n if (!canvas) return null;\n return pickNode(canvas, point, tolerance);\n }\n\n /**\n * Layer transient prop values over a node, on top of what the document evaluates to, re-applied after every\n * evaluation until cleared. For an editor dragging at pointer rate without rebuilding anything; the host\n * commits to its document on drop and clears the override.\n */\n setNodeOverride(path: string, props: NodeOverride): void {\n const existing = this.overrides.get(path);\n this.overrides.set(path, existing ? { ...existing, ...props } : { ...props });\n this.applyOverrides();\n }\n\n /**\n * Drop one node's overrides, or all when `path` is omitted, and repaint.\n *\n * Rebuilds the current track's tree: an override was written straight onto a live prop, and the timeline only\n * restores what its own commands write. Cheap enough for pointer-up, the only place it belongs. `path` is\n * structural, not an id: a node a composite built for itself has no authored one.\n */\n clearNodeOverrides(path?: string): void {\n const cleared = path === undefined\n ? (this.overrides.size > 0 && (this.overrides.clear(), true))\n : this.overrides.delete(path);\n if (!cleared) return;\n this.stateEvaluator.rebuild();\n // Through `repaint` for both of its guards — see there.\n this.repaint();\n }\n\n /** Not authored, so it rides beside the document. */\n setEditorStates(trackId: string, states: NodeEditorStates | undefined): void {\n this.stateEvaluator.setEditorStates(trackId, states);\n this.repaint();\n }\n\n /**\n * Cheap enough for a pointer-rate drag loop: `stateAt` early-returns for the frame already current.\n *\n * Does nothing before the first frame has been drawn (the last complete frame is a blank surface, which should\n * stay up), nor between a swap and its paint, which owes one of its own. See {@link pendingSwap}.\n */\n repaint(): void {\n if (!this.hasPainted) return;\n if (this.pendingSwap !== 0 && this.isCurrent(this.pendingSwap)) return;\n this.renderAt(this.stateEvaluator.currentFrame);\n this.settleTrailing();\n }\n\n /**\n * Repaint a paused frame as the decodes its draw asked for land: one it could not draw at all, and an upgrade\n * of one drawn below demand, which no paint waits for. Never while playing (the next tick picks them up). A\n * seek, swap or screenshot still on its way paints for itself, and once more when it lands if an upgrade\n * arrived after its render.\n */\n private settleTrailing(): void {\n if (this.trailingSettle || this.disposed || this.isPlaying || !this.hasBackgroundDecodes()) return;\n void this.repaintBehindDecodes().catch((error) => {\n console.error(\"[PlaybackController] background decode failed:\", error);\n });\n }\n\n private trailingSettle = false;\n\n private hasBackgroundDecodes(): boolean {\n return this.storageAdapter.hasPendingDecodes() || this.storageAdapter.hasPendingUpgrades();\n }\n\n private async repaintBehindDecodes(): Promise<void> {\n // Released in `finally` on the same turn as the return, so a paint landing\n // right after this gives up can start the next one.\n this.trailingSettle = true;\n try {\n for (let pass = 0; pass < SETTLE_PASSES && this.hasBackgroundDecodes(); pass++) {\n const [decoded, upgraded] = await Promise.all([\n this.storageAdapter.warmPendingDecodes(),\n this.storageAdapter.warmPendingUpgrades(),\n ]);\n if (!(decoded || upgraded) || this.disposed || this.isPlaying) return;\n if (this.paintInFlight !== 0) {\n this.repaintOwedSince = this.renders;\n return;\n }\n this.renderAt(this.stateEvaluator.currentFrame);\n }\n } finally {\n this.trailingSettle = false;\n }\n }\n\n private applyOverrides(): void {\n if (this.overrides.size === 0) return;\n const canvas = this.stateEvaluator.currentCanvas;\n if (!canvas) return;\n for (const [path, props] of this.overrides) {\n findNodeByPath(canvas, path)?.set(props as never);\n }\n }\n\n play(speed: number = 1, reverse: boolean = false): void {\n if (this.currentFrame >= this.totalFrames) {\n this.seek(0).then(() => this.masterClock.play(speed, reverse)).catch(() => { });\n return;\n }\n this.masterClock.play(speed, reverse);\n }\n\n pause(): void {\n this.masterClock.pause();\n }\n\n setMuted(muted: boolean): void {\n this.audioDevice.setMuted(muted);\n }\n\n dispose(): void {\n this.disposed = true;\n this.masterClock.dispose();\n this.audioDevice.dispose();\n this.stateEvaluator.dispose();\n this.store.dispose();\n this.assetManager.dispose();\n }\n}\n\n/** How far from the playhead a built tree is kept, in seconds. */\nconst TRIM_HORIZON_SECONDS = 30;\n\nfunction settlingUpgrades(adapter: StorageAdapter): Pick<StorageAdapter, \"warmPendingDecodes\"> {\n return {\n async warmPendingDecodes() {\n const [decoded, upgraded] = await Promise.all([adapter.warmPendingDecodes(), adapter.warmPendingUpgrades()]);\n return decoded || upgraded;\n },\n };\n}\n\nfunction declOf(error: AssetNotLoadedError, catalog: AssetCatalog): AssetDecl | undefined {\n switch (error.assetType) {\n case \"image\":\n return { type: \"image\", src: error.src };\n case \"font\":\n return { type: \"font\", family: error.src, weight: 400 };\n case \"video\":\n try {\n return { type: \"video\", src: error.src, trimStart: 0, trimEnd: catalog.getVideoDuration(error.src) };\n } catch {\n return undefined;\n }\n default:\n return undefined;\n }\n}\n\n/**\n * Indexed over the authored child list, the one every structural-path walk reads, so selection, bars and\n * `getNodeBox` share one set of paths.\n */\nfunction nodeToTreeState(\n node: Node,\n path: string,\n bars: ReadonlyMap<string, { startFrame: number; endFrame: number }>,\n waveformsByPath: ReadonlyMap<string, WaveformInfo[]>,\n): TreeState {\n const state: TreeState = {\n id: node.id,\n path,\n type: node.className,\n children: node._allChildren.map((c, i) => nodeToTreeState(c, nodePath(path, i), bars, waveformsByPath)),\n };\n const waveform = waveformsByPath.get(path);\n if (waveform && waveform.length > 0) state.waveform = waveform;\n const bar = bars.get(path);\n if (bar) {\n state.startFrame = bar.startFrame;\n state.endFrame = bar.endFrame;\n }\n return state;\n}\n\n/**\n * Keyed by the structural path their owner has in the tree right now; a request whose owner is not in the tree\n * has no bar to land on.\n */\nfunction waveformsByOwner(\n requests: readonly AudioRequest[],\n pathOfOwner: ReadonlyMap<string, string>,\n): Map<string, WaveformInfo[]> {\n const byPath = new Map<string, WaveformInfo[]>();\n for (const req of requests) {\n const path = req.ownerId !== undefined ? pathOfOwner.get(req.ownerId) : \"\";\n if (path === undefined) continue;\n const info: WaveformInfo = {\n src: req.src,\n startTime: req.startAt,\n endTime: Number.isFinite(req.endAt) ? req.endAt : null,\n };\n const list = byPath.get(path);\n if (list) list.push(info);\n else byPath.set(path, [info]);\n }\n return byPath;\n}\n\n/** The node at a structural path (`\"\"` = root, `\"0.2\"` = third child of the first), walking the authored list. */\nfunction findNodeByPath(root: Node2D, path: string): Node | null {\n if (path === \"\") return root;\n let node: Node = root;\n for (const seg of path.split(\".\")) {\n const next = node._allChildren[Number(seg)];\n if (!next) return null;\n node = next;\n }\n return node;\n}\n\nfunction findNode(root: Node, id: string): Node | null {\n if (root.id === id) return root;\n\n for (const child of root._allChildren) {\n const found = findNode(child, id);\n if (found) return found;\n }\n\n return null;\n}\n", "import { type AudioMeta, type FontMeta, type ImageMeta, AssetManifest, type VideoMeta } from \"./manifest\";\n\n/**\n * What a scene can ask about available assets: strictly read-only *metadata* (dimensions, durations, font faces).\n * Loading is the {@link AssetManager}'s job. Reachable as `node.assets` and `stage.assets`.\n *\n * **Every lookup throws on a miss rather than returning `undefined`**: a missing asset is a typo or deleted file, best\n * surfaced during the precomp pass (a `BuildError`) rather than as a shape that silently fails to paint at playback.\n * An interface so a host can supply its own; {@link ManifestAssetCatalog} is built from the project's manifest.\n */\nexport interface AssetCatalog {\n getImageMeta(src: string): ImageMeta;\n\n getVideoMeta(src: string): VideoMeta;\n\n getAudioMeta(src: string): AudioMeta;\n\n getFontMeta(key: string): FontMeta;\n\n /** Every face registered for a family across weights and slants, so the font matcher can resolve any weight to the nearest file. Empty if unknown. */\n getFontFamilyMetas(fontFamily: string): FontMeta[];\n\n /** Playback duration of a video, in seconds. */\n getVideoDuration(src: string): number;\n\n /** Playback duration of an audio file, in seconds. */\n getAudioDuration(src: string): number;\n\n /** Duration of any *playable* source: audio first, falling back to video, so a video `src` can drive a `Sound` without a duplicate audio-only entry. @throws If `src` is in neither manifest. */\n getMediaDuration(src: string): number;\n\n /** An image's intrinsic pixel dimensions. */\n getImageSize(src: string): { width: number; height: number };\n}\n\n/** The {@link AssetCatalog} the runtime builds: a query engine over a static {@link AssetManifest}. */\nexport class ManifestAssetCatalog implements AssetCatalog {\n constructor(private manifest: AssetManifest) { }\n\n /** Points this catalog at `manifest` in place: a session hands one catalog to the controller, clip store and every node's `assets`, so replacing the object would leave them on the old one. */\n reconcile(manifest: AssetManifest): void {\n this.manifest = manifest;\n }\n\n /** Normalizes a caller's asset `src` to the manifest key: the path relative to the public folder, forward slashes, no leading `./` or `/`. Authors write bare filenames, `./sub/file.png`, `/sub/file.png` or backslash paths. Fonts are keyed `family@weight` and skip this. */\n private normalizeKey(src: string): string {\n return src.replace(/\\\\/g, '/').replace(/^\\.\\//, '').replace(/^\\/+/, '');\n }\n\n getImageMeta(src: string): ImageMeta {\n const meta = this.manifest.image[this.normalizeKey(src)];\n if (!meta) throw new Error(`Image asset not found: \"${src}\". Check the file exists in your public folder and the src matches its filename.`);\n return meta;\n }\n\n getVideoMeta(src: string): VideoMeta {\n const meta = this.manifest.video[this.normalizeKey(src)];\n if (!meta) throw new Error(`Video asset not found: \"${src}\". Check the file exists in your public folder and the src matches its filename.`);\n return meta;\n }\n\n getAudioMeta(src: string): AudioMeta {\n const meta = this.manifest.audio[this.normalizeKey(src)];\n if (!meta) throw new Error(`No audio metadata for src: ${src}`);\n return meta;\n }\n\n getFontMeta(key: string): FontMeta {\n const meta = this.manifest.font[key];\n if (!meta) throw new Error(`No font metadata for key: ${key}`);\n return meta;\n }\n\n getFontFamilyMetas(fontFamily: string): FontMeta[] {\n return Object.values(this.manifest.font).filter(meta => meta.fontFamily === fontFamily);\n }\n\n getVideoDuration(src: string): number {\n return this.getVideoMeta(src).duration;\n }\n\n getAudioDuration(src: string): number {\n return this.getAudioMeta(src).duration;\n }\n\n getMediaDuration(src: string): number {\n const key = this.normalizeKey(src);\n const audio = this.manifest.audio[key];\n if (audio) return audio.duration;\n const video = this.manifest.video[key];\n if (video) return video.duration;\n throw new Error(`Audio asset not found: \"${src}\". Check the file exists in your public folder and the src matches its filename.`);\n }\n\n getImageSize(src: string): { width: number; height: number } {\n const { width, height } = this.getImageMeta(src);\n return { width, height };\n }\n}\n", "import { TimeCallback } from \"@/platform/ticker\";\nimport { PlaybackController } from \"./playback-controller\";\n\n/**\n * Realtime transport over a `Session`, reached as `session.playback`. `null` when the environment has no clock\n * (a headless export has no wall clock to sync to): an absence rather than a no-op, so a UI can ask whether a\n * transport exists and hide its scrub bar. Thin on purpose: it is all `PlaybackController`'s, kept so \"what a\n * session is\" and \"what is playing it\" are separable.\n */\nexport class Playback {\n /** @internal — constructed by `Session`, never directly. */\n constructor(private readonly controller: PlaybackController) { }\n\n get isPlaying(): boolean {\n return this.controller.isPlaying;\n }\n\n get frame(): number {\n return this.controller.currentFrame;\n }\n\n play(speed = 1, reverse = false): void {\n this.controller.play(speed, reverse);\n }\n\n pause(): void {\n this.controller.pause();\n }\n\n /**\n * Without the await a paused scrub needs. Use `Session.seekFrame` when paused: it resolves once the frame is\n * drawn.\n */\n seekFrame(frame: number): void {\n this.controller.seekWhilePlaying(frame);\n }\n\n setMuted(muted: boolean): void {\n this.controller.setMuted(muted);\n }\n\n onTime(callback: TimeCallback): void {\n this.controller.onTime(callback);\n }\n\n onPlay(callback: () => void): void {\n this.controller.onPlay(callback);\n }\n\n onPause(callback: () => void): void {\n this.controller.onPause(callback);\n }\n}\n", "/** Called every animation frame with the current playhead time (seconds). Must return a Promise so the clock can await all renderers before advancing. */\nexport type TickCallback = (time: number) => Promise<void>;\n\n/** Fired when playback starts. Receives the time at which playback began, the playback speed multiplier, and whether playback is reversed. */\nexport type PlayCallback = (time: number, speed: number, reverse: boolean) => void;\n\n/** Fired when the playhead reaches a new frame: once per frame, not per animation frame (see {@link Ticker.setCurrentTime}), so a rAF-driven subclass on a high-refresh display keeps the extra positions to itself. */\nexport type TimeCallback = (time: number) => void;\n\n/**\n * Platform-agnostic base for driving playback. Subclasses implement the frame loop (rAF in the browser, a setInterval\n * in Node) and call `setCurrentTime` / `tick`; `Ticker` owns the subscriber lists and shared playback state. Register\n * listeners via `onTick` / `onPlay` / `onPause` / `onTime`, set `setDuration`, and `dispose` when done.\n *\n * `play`, `pause` and `seek` take effect before they return, so any order of them in one turn leaves the clock where\n * the last one put it. A time listener or tick callback may `seek` (a host looping wraps to the start when it hears the\n * end), so a subclass must read the end of a run again afterwards. At the end of a run it reports a final tick and pauses.\n */\nexport abstract class Ticker {\n private _isPlaying: boolean = false;\n private _currentTime: number = 0;\n protected _duration: number = 0;\n\n get isPlaying(): boolean {\n return this._isPlaying;\n }\n\n get currentTime(): number {\n return this._currentTime;\n }\n\n get duration(): number {\n return this._duration;\n }\n\n setDuration(duration: number): void {\n this._duration = duration;\n }\n\n /**\n * Updates the playhead and notifies time listeners; no-ops if the time hasn't changed. `notify: false` keeps the\n * clock exact (`pause`/`play` anchor their elapsed-time maths on it, so it advances every loop frame) while keeping\n * subscribers quiet: a subclass that knows its frame rate fires {@link onTime} once per frame, not per animation\n * frame (on a 144Hz display that was a React render per refresh to drive a 60fps render).\n */\n protected setCurrentTime(t: number, notify: boolean = true): void {\n if (this._currentTime === t) return;\n this._currentTime = t;\n if (!notify) return;\n for (const cb of this.timeCallbacks) cb(t);\n }\n\n protected setPlaying(playing: boolean): void {\n this._isPlaying = playing;\n }\n\n play(speed: number, reverse: boolean): void {\n this._isPlaying = true;\n for (const cb of this.playCallbacks) cb(this._currentTime, speed, reverse);\n }\n\n /** Awaits all tick callbacks in parallel. Subclasses call this once per frame after updating `currentTime`. */\n protected async tick(): Promise<void> {\n await Promise.all(this.tickCallbacks.map(c => c(this._currentTime)));\n }\n\n pause(): void {\n this._isPlaying = false;\n for (const cb of this.pauseCallbacks) cb();\n }\n\n /** Moves the playhead to `t` (seconds). Subclasses decide whether this also triggers a tick. */\n abstract seek(t: number): void;\n\n protected tickCallbacks: TickCallback[] = [];\n protected playCallbacks: PlayCallback[] = [];\n protected pauseCallbacks: (() => void)[] = [];\n protected timeCallbacks: TimeCallback[] = [];\n\n /** Clears all registered callbacks. Call when tearing down a scene to avoid memory leaks. */\n dispose() {\n this.tickCallbacks.length = 0;\n this.playCallbacks.length = 0;\n this.pauseCallbacks.length = 0;\n this.timeCallbacks.length = 0;\n }\n\n onTick(callback: TickCallback) {\n this.tickCallbacks.push(callback);\n }\n\n onPlay(callback: PlayCallback) {\n this.playCallbacks.push(callback);\n }\n\n onPause(callback: () => void) {\n this.pauseCallbacks.push(callback);\n }\n\n onTime(callback: TimeCallback) {\n this.timeCallbacks.push(callback);\n }\n}\n", "import { Ticker } from \"./ticker\";\n\n/** A clock with no wall clock behind it: the playhead is wherever it was last put. What a headless session runs on: an export has no realtime to sync to (and must not, since a wall-clock export drifts), so the platform reports `null` from `createTicker` and a session stands this in, keeping everything that is not transport (seeking, picking, reading a node's box, drawing) as in a browser. `play()` is not a no-op override: with `playback === null` nothing reaches it. @internal */\nexport class SteppedClock extends Ticker {\n seek(t: number): void {\n this.setCurrentTime(t);\n }\n}\n", "import { Size2D } from \"@/attributes/layout/size\";\nimport { AssetManifest } from \"@/assets/manifest\";\nimport { ManifestAssetCatalog } from \"@/assets/catalog\";\nimport { setTheme } from \"@/attributes/shape/fill/color/parser\";\nimport { asProjectDocument, type ProjectDocument } from \"@/document/project\";\nimport type { VisualDocument } from \"@/document/types\";\nimport { assertValidProjectDocument } from \"@/document/validate\";\nimport { migrateDocument } from \"@/document/migrate\";\nimport { ExportStillRequest, ExportVideoRequest, ExportedStill } from \"@/platform/exporter\";\nimport { Engine, EngineRenderContext } from \"./engine\";\nimport { Playback } from \"./playback\";\nimport { clipTimeToFrame } from \"./frame-time\";\nimport { PlaybackController } from \"./playback-controller\";\nimport { AssetTimelineResult } from \"./asset-timeline\";\nimport { StorageAdapter } from \"@/platform/storage-adapter\";\nimport { SteppedClock } from \"@/platform/stepped-clock\";\n\n/** A lone still or composition is the one track of a project around it. */\nexport interface SessionSource {\n document: ProjectDocument | VisualDocument;\n /** A lone clip document carries neither; these also win over a project's own. */\n viewport?: Size2D;\n fps?: number;\n}\n\nexport interface OpenOptions extends SessionSource {\n /**\n * A canvas in a browser, a size headlessly; the platform's render context narrows it. Omit to open without\n * mounting, for a session that only exports.\n */\n target?: unknown;\n onPrecompProgress?: (result: AssetTimelineResult) => void;\n}\n\n/**\n * Cheap relative to its engine (a surface and a playhead; the caches belong to the engine), so many sessions\n * over one engine is the intended shape: a preview, a filmstrip, an export.\n *\n * The theme is still applied through a process-global registry (`setTheme`), re-applied immediately before\n * anything draws, so concurrent sessions with different themes would contend. Isolating that means threading a\n * context through every colour parse.\n */\nexport class Session {\n readonly viewport: Size2D;\n readonly fps: number;\n\n /** @internal — created by `Engine.open`, never directly. */\n constructor(\n private readonly engine: Engine,\n options: OpenOptions,\n ) {\n this._override = { viewport: options.viewport, fps: options.fps };\n this._project = resolveProjectDocument(options.document, options, engine);\n this.viewport = this._project.viewport!;\n this.fps = this._project.fps!;\n\n this._catalog = new ManifestAssetCatalog(engine.manifest);\n /**\n * The controller, its clip store and every node's `assets` hold this object, so a new one would reach only the\n * storage adapter.\n */\n this._unsubscribe = engine._onManifestChange((manifest: AssetManifest) => {\n this._catalog.reconcile(manifest);\n this._storage.setCatalog(this._catalog);\n this._controller.reconcileCatalog();\n });\n\n const deps = { catalog: this._catalog, viewport: this.viewport, fps: this.fps };\n this._storage = engine.platform.createStorageAdapter(deps);\n this._renderContext = engine.platform.createRenderContext(this._storage);\n const measurer = engine.platform.createMeasureContext(this._storage);\n const audioDevice = engine.platform.createAudioSink();\n const masterClock = engine.platform.createTicker(this.fps, audioDevice);\n\n // Before the first measuring pass, which resolves theme tokens.\n this.applyGlobals();\n\n if (options.target !== undefined) this._renderContext.mount(options.target);\n\n /**\n * `null` means no realtime transport here, not \"nothing works\": seeking, picking and drawing are the same\n * headlessly, so a stepped clock stands in and only `playback` reports the absence.\n */\n this._controller = new PlaybackController({\n project: this._project,\n registry: engine._registry,\n renderContext: this._renderContext,\n measurer,\n storageAdapter: this._storage,\n masterClock: masterClock ?? new SteppedClock(),\n audioDevice,\n assets: this._catalog,\n onPrecompProgress: options.onPrecompProgress,\n });\n this._playback = masterClock === null ? null : new Playback(this._controller);\n }\n\n get document(): ProjectDocument {\n return this._project;\n }\n\n get playback(): Playback | null {\n return this._playback;\n }\n\n /**\n * Exposed rather than proxied: `Session` covers the document (what is open, where it draws, how it encodes),\n * the controller inspecting and manipulating a live frame. Always present, including headlessly (see\n * `SteppedClock`).\n */\n get controller(): PlaybackController {\n return this._controller;\n }\n\n /** A host reads it to resize or re-frame the view. */\n get surface(): EngineRenderContext {\n return this._renderContext;\n }\n\n get duration(): number {\n return this._controller.totalDuration;\n }\n\n get totalFrames(): number {\n return this._controller.totalFrames;\n }\n\n async seek(seconds: number): Promise<void> {\n await this.seekFrame(Math.round(clipTimeToFrame(seconds, this.fps)));\n }\n\n async seekFrame(frame: number): Promise<void> {\n this.applyGlobals();\n await this._controller.seek(frame);\n }\n\n /**\n * The new document is diffed against the playing one and each built tree patched in place; a track is rebuilt\n * only when its change cannot be patched, and a theme change rebuilds every track. Documents are compared by\n * content with identity as the fast path, so treat them as immutable. The output's size and rate cannot change\n * under a live surface; a document asking for different ones needs a session of its own.\n */\n replace(document: ProjectDocument | VisualDocument): void {\n const next = resolveProjectDocument(document, this._override, this);\n if (next.fps !== this.fps || next.viewport!.width !== this.viewport.width\n || next.viewport!.height !== this.viewport.height) {\n throw new Error(\n `Cannot replace a ${this.viewport.width}×${this.viewport.height} @ ${this.fps}fps document with a ` +\n `${next.viewport!.width}×${next.viewport!.height} @ ${next.fps}fps one — open a new session.`,\n );\n }\n this._project = next;\n this.applyGlobals();\n this._controller.setProject(next);\n }\n\n image(options: Partial<Omit<ExportStillRequest, \"project\" | \"registry\">> = {}): Promise<ExportedStill> {\n this.applyGlobals();\n return this.engine.exporter.exportStill({\n ...options,\n frame: options.frame ?? { kind: \"last\" },\n project: this._project,\n registry: this.engine._registry,\n manifest: options.manifest ?? this.engine.manifest,\n });\n }\n\n export(options: Omit<ExportVideoRequest, \"project\" | \"registry\"> = {}): Promise<Uint8Array | void> {\n this.applyGlobals();\n return this.engine.exporter.exportVideo({\n ...options,\n project: this._project,\n registry: this.engine._registry,\n manifest: options.manifest ?? this.engine.manifest,\n });\n }\n\n dispose(): void {\n this._unsubscribe();\n this._controller.dispose();\n this._renderContext.dispose();\n }\n\n /** Another session may have written it since. */\n private applyGlobals(): void {\n setTheme(this._project.theme);\n }\n\n private readonly _override: { viewport?: Size2D; fps?: number };\n private _project: ProjectDocument;\n private readonly _catalog: ManifestAssetCatalog;\n private readonly _storage: StorageAdapter;\n private readonly _renderContext: EngineRenderContext;\n private readonly _controller: PlaybackController;\n private readonly _playback: Playback | null;\n private readonly _unsubscribe: () => void;\n}\n\n/**\n * `override` first, then the document's own, then `fallback`. Migrated and validated once, here, so every host\n * that renders a document agrees on which size wins. Throws `DocumentTooNewError` for a format this engine\n * cannot read. A migration that changed only the version stamp plays the document as given, so a host\n * replacing the same object keeps the identity fast path.\n */\nexport function resolveProjectDocument(\n document: ProjectDocument | VisualDocument,\n override: { viewport?: Size2D; fps?: number },\n fallback: { viewport: Size2D; fps: number },\n): ProjectDocument {\n const opened = asProjectDocument(document);\n const migrated = migrateDocument(opened);\n const project = migrated.changes.length > 0 ? migrated.document : opened;\n const resolved: ProjectDocument = {\n ...project,\n viewport: override.viewport ?? project.viewport ?? fallback.viewport,\n fps: override.fps ?? project.fps ?? fallback.fps,\n };\n assertValidProjectDocument(resolved);\n return resolved;\n}\n", "/** One parsed data record: column name → cell value (string, or number/boolean\n * when the column auto-coerces — see {@link ParseCSVOptions.numeric} and\n * {@link ParseCSVOptions.boolean}). */\nexport type DataRecord = Record<string, string | number | boolean>;\n\nexport interface ParseCSVOptions {\n /** Field separator. Default: ','. */\n delimiter?: string;\n /** Columns to coerce to `number`: an explicit list forces just those, `false` disables coercion, and the default auto-detects (numeric only if every non-empty cell parses as a finite number, so a text column with a stray numeric-looking value isn't partially coerced). */\n numeric?: string[] | boolean;\n /** Columns to coerce to `boolean`, as {@link numeric}; auto-detect makes a column boolean only if every non-empty cell is exactly `\"true\"` or `\"false\"`. Never applied to a column already numeric. */\n boolean?: string[] | boolean;\n}\n\n/** Parses CSV text into row records keyed by the header row. Handles quoted fields (embedded delimiters, newlines, `\"\"` escapes) and CRLF/LF. Synchronous and dependency-free, so safe at module-eval time on `?raw` text. */\nexport function parseCSV(text: string, options: ParseCSVOptions = {}): DataRecord[] {\n const delimiter = options.delimiter ?? ',';\n const rows = splitRows(text, delimiter);\n if (rows.length === 0) return [];\n\n const header = rows[0].map(cell => cell.trim());\n const body = rows.slice(1);\n\n const records: Record<string, string>[] = body.map(row => {\n const record: Record<string, string> = {};\n header.forEach((key, i) => { record[key] = row[i] ?? ''; });\n return record;\n });\n\n const numericCols = resolveNumericColumns(header, records, options.numeric);\n const booleanCols = resolveBooleanColumns(header, records, numericCols, options.boolean);\n if (numericCols.length === 0 && booleanCols.length === 0) return records;\n\n return records.map(record => {\n const out: DataRecord = { ...record };\n for (const col of numericCols) {\n const raw = record[col];\n if (raw === '') continue;\n out[col] = Number(raw);\n }\n for (const col of booleanCols) {\n const raw = record[col];\n if (raw === '') continue;\n out[col] = raw === 'true';\n }\n return out;\n });\n}\n\n/** Only ever an inlined literal: the `@motionscript/vite-plugin` macro replaces `parseData(\"file.csv\")` call sites with the parsed rows before this runs. This body exists so the call type-checks and an unresolved call site (no plugin, non-literal argument) fails loudly instead of returning nothing. */\nexport function parseData(file: string, _options?: ParseCSVOptions): DataRecord[] {\n throw new Error(\n `parseData(\"${file}\") must be called with a static string literal so the ` +\n `@motionscript/vite-plugin macro can inline it at build time. If you're seeing ` +\n `this error at runtime, either the plugin isn't installed/registered, or this ` +\n `call's argument isn't a plain string literal.`\n );\n}\n\nfunction resolveNumericColumns(\n header: string[],\n records: Record<string, string>[],\n numeric: string[] | boolean | undefined,\n): string[] {\n if (numeric === false) return [];\n if (Array.isArray(numeric)) return numeric;\n\n return header.filter(col => {\n let sawValue = false;\n for (const record of records) {\n const raw = record[col];\n if (raw === '') continue;\n if (!Number.isFinite(Number(raw))) return false;\n sawValue = true;\n }\n return sawValue;\n });\n}\n\nfunction resolveBooleanColumns(\n header: string[],\n records: Record<string, string>[],\n numericCols: string[],\n bool: string[] | boolean | undefined,\n): string[] {\n if (bool === false) return [];\n if (Array.isArray(bool)) return bool;\n\n const numericSet = new Set(numericCols);\n return header.filter(col => {\n if (numericSet.has(col)) return false;\n let sawValue = false;\n for (const record of records) {\n const raw = record[col];\n if (raw === '') continue;\n if (raw !== 'true' && raw !== 'false') return false;\n sawValue = true;\n }\n return sawValue;\n });\n}\n\n/** Splits raw CSV text into rows of unquoted cells. A hand-rolled scanner, not `split(',')`, so quoted fields can contain the delimiter, newlines and `\"\"` escapes. */\nfunction splitRows(text: string, delimiter: string): string[][] {\n const rows: string[][] = [];\n let row: string[] = [];\n let field = '';\n let inQuotes = false;\n let sawAnyField = false;\n\n const pushField = () => { row.push(field); field = ''; };\n const pushRow = () => { pushField(); rows.push(row); row = []; sawAnyField = false; };\n\n for (let i = 0; i < text.length; i++) {\n const ch = text[i];\n\n if (inQuotes) {\n if (ch === '\"') {\n if (text[i + 1] === '\"') { field += '\"'; i++; }\n else inQuotes = false;\n } else {\n field += ch;\n }\n continue;\n }\n\n if (ch === '\"') { inQuotes = true; sawAnyField = true; continue; }\n if (ch === delimiter) { sawAnyField = true; pushField(); continue; }\n if (ch === '\\r') continue;\n if (ch === '\\n') { if (sawAnyField || field) pushRow(); continue; }\n field += ch;\n sawAnyField = true;\n }\n // Flush a final row left over when the text has no trailing newline.\n if (sawAnyField || field) pushRow();\n\n return rows;\n}\n", "/**\n * Retiring an export: it keeps working, warns once in development, and names the release that removes it.\n * Pair it with a `@deprecated … Remove in X.Y.Z.` doc comment naming the same release; editors read that, and\n * `scripts/check-deprecations.mjs` fails CI once the package reaches it. A constant or type takes the comment\n * alone. A component's retired prop stays for good under its spec's `deprecated`, since saved documents set it.\n */\n\nexport interface Deprecation {\n /** The name callers import, as the warning prints it. */\n readonly name: string;\n /** What to write instead, as code: `\"seriesPaint(series).fill\"`. */\n readonly use: string;\n /** The release that removes it: the next major (`\"1.0.0\"`, or the next minor while on 0.x). */\n readonly removeIn: string;\n}\n\nconst warned = new Set<string>();\n\n/** `process` is absent in a browser that loads the ES modules unbundled; a bundler replaces the whole read. */\nfunction isProduction(): boolean {\n return typeof process !== \"undefined\" && process.env?.NODE_ENV === \"production\";\n}\n\n/** The sentence a deprecation warns with. */\nexport function deprecationMessage(notice: Deprecation): string {\n return `[motionscript] ${notice.name} is deprecated and will be removed in ${notice.removeIn}; use ${notice.use} instead.`;\n}\n\n/**\n * Warn about `notice` once per name, in development only. For a use `deprecate` cannot wrap: a deprecated\n * option read inside a function that otherwise stays.\n */\nexport function warnDeprecated(notice: Deprecation): void {\n if (isProduction() || warned.has(notice.name)) return;\n warned.add(notice.name);\n console.warn(deprecationMessage(notice));\n}\n\n/**\n * `fn`, unchanged in what it does and how it is typed, warning on its first call that `notice.use` replaces it.\n * A class is not a function here: wrapping one would break `new` and `instanceof`.\n */\nexport function deprecate<F extends (...args: never[]) => unknown>(fn: F, notice: Deprecation): F {\n const wrapped = function (this: unknown, ...args: Parameters<F>): ReturnType<F> {\n warnDeprecated(notice);\n return fn.apply(this, args) as ReturnType<F>;\n };\n Object.defineProperty(wrapped, \"name\", { value: notice.name });\n return wrapped as unknown as F;\n}\n\n/** Forget what has been warned, so a test can see the same warning again. @internal */\nexport function resetDeprecationWarnings(): void {\n warned.clear();\n}\n", "/**\n * Generates an array of size `n` populated by a generator function.\n * Mirrored after Dart's List.generate.\n */\nexport const generateList = <T>(n: number, generator: (index: number) => T): T[] => {\n // Use a traditional loop for maximum performance inside animation/render cycles\n const result = new Array(n);\n for (let i = 0; i < n; i++) {\n result[i] = generator(i);\n }\n return result;\n};\n", "/**\n * A callable reference that acts as both getter and setter.\n * - `ref()` → returns the current value (throws if not yet assigned)\n * - `ref(value)` → sets the current value\n */\nexport interface Reference<T> {\n (): T;\n (node: T | null): void;\n /** Phantom (never assigned or called): puts `T` in a *contravariant* position, which makes {@link RefTarget} safe: the zero-arg getter `(): T` is assignable to any `(x) => void`, so a slot typed as just the setter would accept a `Reference` of an unrelated node type. @internal */\n readonly __accepts?: (node: T) => void;\n}\n\n/**\n * A slot that can *receive* a `T`: a `Reference<T>`, or one declared as any **supertype** of `T`. The widening is\n * deliberate: the framework only writes into a ref (`props.ref(this)`) and the author only reads, so a `Rect` into a\n * `Reference<Node2D>` is sound. The opposite direction stays an error (a `Reference<Rect>` on a `Text` would type reads\n * as a `Rect`). A plain setter function is accepted too, for React-style callback refs.\n */\nexport type RefTarget<T> = {\n (node: T | null): void;\n readonly __accepts?: (node: T) => void;\n};\n\n/** Creates a typed reference holder, like React's `createRef` but one overloaded function rather than a `{ current }` object. */\nexport function createRef<T>(): Reference<T> {\n let current: T | null = null;\n\n function ref(): T;\n function ref(node: T | null): void;\n function ref(node?: T | null): T | void {\n if (node !== undefined) {\n current = node;\n } else {\n if (current === null) {\n throw new Error(\"Reference not assigned yet\");\n }\n return current;\n }\n }\n\n return ref;\n}\n", "/** Deterministic mulberry32 PRNG: the same seed gives the same sequence. Scene authors use the {@link Random} facade from `stage.random(seed)`, which wraps this. */\nexport class SeedGenerator {\n private state: number = 0;\n\n constructor(seed: string | number) {\n this.setSeed(seed);\n }\n\n /** String seeds are hashed via djb2 into a 32-bit integer. */\n setSeed(seed: string | number) {\n this.state = typeof seed === 'string'\n ? seed.split('').reduce((a, b) => { a = ((a << 5) - a) + b.charCodeAt(0); return a & a; }, 0)\n : seed;\n }\n\n next() {\n this.state |= 0; this.state = this.state + 0x6D2B79F5 | 0;\n var t = Math.imul(this.state ^ this.state >>> 15, 1 | this.state);\n t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;\n return ((t ^ t >>> 14) >>> 0) / 4294967296;\n }\n}\n\n/** Upper bound of {@link Random.nextInt} / {@link Random.intArray} (2^32). */\nconst UINT32_RANGE = 4294967296;\n\n/**\n * A seeded random source handed out by `stage.random(seed)`; wraps a {@link SeedGenerator} (mulberry32). Determinism\n * is scoped per source: scenes each get their own reproducible stream without a shared stage-level seed.\n *\n * Two families that are NOT interchangeable: **independent draws** (`nextFloat`/`nextInt`/`gauss` and array forms,\n * uncorrelated; `gauss` changes only the distribution) and the **correlated field** `noise(t)`, where nearby inputs\n * give nearby values, the right tool for smooth motion (drift, shake, waves).\n */\nexport class Random {\n /** The seed this source rewinds to; set by {@link adopt}. */\n private _seed!: string | number;\n\n /** Numeric form of {@link _seed}, used to mix `noise`'s lattice; kept in lockstep through {@link adopt}. */\n private numericSeed!: number;\n\n private readonly gen: SeedGenerator;\n\n /** A spare gaussian sample from the last Box–Muller pair (see {@link gauss}). */\n private spareGauss: number | null = null;\n\n constructor(seed: string | number) {\n this.gen = new SeedGenerator(seed);\n this.adopt(seed);\n }\n\n /** The seed this source rewinds to. Assigning re-anchors the source (as `reset(seed)`): draws reproduce that seed's sequence and `noise`'s lattice shifts to match. */\n get seed(): string | number {\n return this._seed;\n }\n set seed(seed: string | number) {\n this.adopt(seed);\n }\n\n /** Numeric form of a seed (strings hashed djb2-style), shared so the constructor, setter and {@link reset} derive `numericSeed` identically. */\n private static toNumeric(seed: string | number): number {\n return typeof seed === 'string'\n ? seed.split('').reduce((a, b) => (a << 5) - a + b.charCodeAt(0), 0)\n : seed;\n }\n\n /** Takes `seed` as the new origin and rewinds to it; the single seed-adoption path behind the constructor, {@link seed} and a seeded {@link reset}. */\n private adopt(seed: string | number): void {\n this._seed = seed;\n this.numericSeed = Random.toNumeric(seed);\n this.gen.setSeed(seed);\n this.spareGauss = null;\n }\n\n /** The next float in `[from, to)`, default `[0, 1)`. */\n nextFloat(from: number = 0, to: number = 1): number {\n return this.gen.next() * (to - from) + from;\n }\n\n /** The next integer in `[from, to)`, default the full unsigned 32-bit range. */\n nextInt(from: number = 0, to: number = UINT32_RANGE): number {\n return Math.floor(this.gen.next() * (to - from)) + from;\n }\n\n /** `size` independent floats in `[from, to)`. */\n floatArray(size: number, from: number = 0, to: number = 1): number[] {\n const out = new Array<number>(size);\n for (let i = 0; i < size; i++) out[i] = this.nextFloat(from, to);\n return out;\n }\n\n /** `size` independent integers in `[from, to)`. */\n intArray(size: number, from: number = 0, to: number = UINT32_RANGE): number[] {\n const out = new Array<number>(size);\n for (let i = 0; i < size; i++) out[i] = this.nextInt(from, to);\n return out;\n }\n\n /** A normal sample (default standard). Uses the polar Box–Muller transform, which yields two normals per pair of uniforms; the spare is cached for the next call. */\n gauss(mean: number = 0, stdev: number = 1): number {\n if (this.spareGauss !== null) {\n const z = this.spareGauss;\n this.spareGauss = null;\n return mean + stdev * z;\n }\n // Rejection-sample a point in the unit circle, then map to two normals.\n let u: number, v: number, s: number;\n do {\n u = this.gen.next() * 2 - 1;\n v = this.gen.next() * 2 - 1;\n s = u * u + v * v;\n } while (s >= 1 || s === 0);\n const mul = Math.sqrt(-2 * Math.log(s) / s);\n this.spareGauss = v * mul;\n return mean + stdev * (u * mul);\n }\n\n /**\n * Smooth 1-D value noise in `[0, 1]`: lattice points around `time * frequency` interpolated with a smoothstep.\n * Unlike {@link nextFloat}/{@link gauss}, nearby `time` inputs give nearby values (camera shake, drift, waves).\n * Higher `frequency` means more crests across the same span.\n */\n noise(time: number, frequency: number = 1): number {\n const t = time * frequency;\n const i = Math.floor(t);\n const f = t - i;\n // Smoothstep: maps f through 3f²-2f³ to ease in/out between lattice points.\n const curve = f * f * (3 - 2 * f);\n const r1 = this.latticeValue(i);\n const r2 = this.latticeValue(i + 1);\n return r1 + (r2 - r1) * curve;\n }\n\n /** Rewinds so the next draws reproduce a sequence from the start. With a `seed`, adopts it as the new origin first (equivalent to assigning {@link seed}), e.g. in a node's constructor for a distinct stream. */\n reset(seed: string | number = this._seed): void {\n this.adopt(seed);\n }\n\n /** Deterministic value in `[0, 1)` for lattice point `x`, mixed with the seed via `sin`. Pure in `x`, so {@link noise} is stable regardless of preceding draws. */\n private latticeValue(x: number): number {\n const h = Math.sin(x + this.numericSeed) * 10000;\n return h - Math.floor(h);\n }\n}\n", "/** A flat animation driver. `advance(dt)` moves forward `dt` seconds and returns `true` once complete (final value applied); prime it at t=0 via `seek(0)` before the first `advance`. `seek(elapsed)` is the absolute-time half a {@link Command}'s `at` is built on: any time, in any order, so a timeline can evaluate a frame without playing the ones before it. */\n/** @internal */\nexport interface TweenStepper {\n /** Jumps to the value at `elapsed` seconds; `0` primes the stepper before the first {@link advance}. */\n seek(elapsed: number): void;\n /** Advances by `dt` seconds; returns `true` when finished and the final value is applied. */\n advance(dt: number): boolean;\n}\n\n/** Implemented by anything that can produce a {@link TweenStepper}: a {@link Command}, or anything a host drives directly. */\nexport interface Steppable {\n _stepper(): TweenStepper;\n}\n\nexport function isSteppable(x: unknown): x is Steppable {\n return typeof (x as Steppable)?._stepper === \"function\";\n}\n"],
|
|
5
|
-
"mappings": "y7CA6BA,SAASA,GAAYC,EAAa,CAC9B,OAAO,OAAO,SAASA,CAAK,GAAKA,EAAQ,EAAIA,EAAQ,CACzD,CAGM,SAAUC,GAAiBD,EAAcE,EAAsBC,EAAwBD,EAAY,CACrG,OAAIE,GAAOJ,CAAK,EAAUK,GAAyBL,EAAOE,EAAcC,CAAa,EAC9E,KAAK,IAAI,EAAG,KAAK,IAAIA,EAAeD,CAAY,CAAC,EAAIH,GAAYC,CAAK,CACjF,CAGM,SAAUM,GAAiBN,EAAcE,EAAsBK,EAAmB,CACpF,OAAIH,GAAOJ,CAAK,EAAUQ,GAAwBR,EAAOE,EAAcK,CAAW,EAC3E,KAAK,IAAI,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C,YAAK,WAAaD,EAAIE,EACfN,EAAOC,GAASE,EAAIG,EAC/B,CAOA,MAAMC,EAAcC,EAAoB,EAAC,CACrC,IAAMjB,EAAIgB,EAAOC,EACXT,EAAI,KAAK,MAAMR,CAAC,EAChBkB,EAAIlB,EAAIQ,EAERW,EAAQD,EAAIA,GAAK,EAAI,EAAIA,GACzBE,EAAK,KAAK,aAAaZ,CAAC,EACxBa,EAAK,KAAK,aAAab,EAAI,CAAC,EAClC,OAAOY,GAAMC,EAAKD,GAAMD,CAC5B,CAGA,MAAMtB,EAAwB,KAAK,MAAK,CACpC,KAAK,MAAMA,CAAI,CACnB,CAGQ,aAAayB,EAAS,CAC1B,IAAMC,EAAI,KAAK,IAAID,EAAI,KAAK,WAAW,EAAI,IAC3C,OAAOC,EAAI,KAAK,MAAMA,CAAC,CAC3B,GChIE,SAAUC,GAAYC,EAAU,CAClC,OAAO,OAAQA,GAAiB,UAAa,UACjD",
|
|
6
|
-
"names": ["scalarSpeed", "speed", "clipTimeAtSource", "sourceLength", "sourceElapsed", "isRamp", "integrateSpeedToClipTime", "sourceTimeAtClip", "clipElapsed", "sourceTimeAtClipElapsed", "clipDurationOf", "clip", "mediaDuration", "length", "requestOf", "catalog", "ownerKey", "n", "at", "until", "trimStart", "trimEnd", "loop", "effects", "resolveAudioEffects", "staticValue", "request", "natural", "Sound", "props", "resolveAudioEffects", "trimmedSourceLength", "clipTimeAtSource", "effectsKey", "effects", "f", "paramKey", "EQUAL_POWER", "x", "shapes", "shapeOf", "transition", "curve", "shape", "easeOfSpec", "transitionSpans", "length", "transitionIn", "transitionOut", "wanted", "total", "scale", "transitionGainAt", "t", "spans", "gain", "transitionKey", "busStopKey", "stop", "paramKey", "effectsKey", "transitionKey", "KNOWN_KINDS", "isKnownShaderProperty", "property", "MAX_SHADER_PROPERTIES", "MAX_SHADER_SOURCE", "normalizeShaderPack", "input", "raw", "scope", "source", "base", "isRecord", "normalizeProperties", "textures", "t", "where", "out", "claimed", "id", "value", "warn", "inputs", "conflict", "uniform", "prior", "warned", "message", "nodePath", "parentPath", "childIndex", "declareNode", "node", "scope", "declareTree", "root", "children", "i", "bindDetached", "host", "node", "sampleTree", "child", "primeMotionTree", "at", "applyEditorStates", "root", "states", "walk", "node", "state", "child", "Canvas2D", "Node2D", "props", "args", "from", "target", "fillOps", "lerp", "t", "Graphics2D", "draw", "fill", "ctx", "overlay", "child", "c", "NodeAudio", "assets", "Clip", "rect", "NO_PROJECTION_3D", "camera", "spaceRootFrame", "w", "h", "cx", "cy", "declareMembers", "fillProperty", "flowProperty", "property", "alignmentProperty", "lerpLookAt", "command", "scalarCorners", "Types", "lerpCornerScalarStyle", "Rect", "component2d", "state", "commands", "measurer", "children", "measure", "inset", "box", "layout", "ctx", "draw", "rect", "Ellipse", "ellipse", "Polygon", "polygon", "Polygram", "polygram", "PathShape", "unitPath", "Path", "_measurer", "intrinsic", "pathOps", "pad", "facePath", "boundsShape", "key", "kind", "outline", "Triangle", "RightTriangle", "Pentagon", "Hexagon", "Octagon", "Star", "STAR_DEFAULT_POINTS", "STAR_DEFAULT_RATIO", "BooleanGroup", "component2d", "state", "Types", "commands", "measurer", "children", "measure", "inset", "box", "layout", "ctx", "MaskGroup", "Camera", "component2d", "state", "commands", "measurer", "children", "measure", "inset", "box", "layout", "ctx", "draw", "rect", "camera", "orbit", "Types", "lerpLookAt", "OrbitCamera", "commandsFor", "RotatedBox", "cos", "sin", "turn", "w", "h", "ortho", "room", "width", "height", "child", "size", "turned", "angle", "rad", "_overlay", "glyphPaint", "state", "_overlayTo", "glyphCommands", "commands", "autofits", "NO_RUNS", "resolvePath", "value", "PathBuilder", "resolveRuns", "fill", "stroke", "run", "fillOps", "strokeOps", "textState", "Types", "textSource", "Text", "component2d", "timeline", "loader", "load", "measurer", "measure", "ctx", "draw", "numberState", "numberSource", "formatNumber", "numberNodePattern", "NumberNode", "_v", "_d", "_c", "_m", "richStyle", "RichText", "inherit", "v", "loadRichText", "measureRichText", "drawRichText", "DefaultTextStyle", "provided", "inherited", "provide", "current", "Provider", "component2d", "Types", "state", "provides", "ThemeProvider", "inherited", "out", "ThemeToken", "DataToken", "SeedToken", "SoundNode", "componentAudio", "Types", "lerpParam", "timeline", "state", "AudioBus", "video", "Types", "v", "resolveChainAdjustments", "lerpFilterArray", "resolveAudioEffects", "playedAt", "s", "elapsed", "played", "segment", "scheduledTimestamp", "start", "first", "sourceTimeFor", "pictures", "pictureOf", "host", "scheduled", "crop", "anchor", "key", "kept", "prop", "fill", "resolveFill", "Video", "component2d", "state", "commands", "timeline", "speed", "loop", "loader", "measurer", "children", "measure", "inset", "box", "layout", "ctx", "picture", "internalsOf", "outline", "draw", "rect", "UNSET_MEDIA_FILL", "Graphics2D", "ORBIT_CAMERA_DEFAULTS", "isOrbitCamera3D", "camera", "resolveCameraPlacement", "target", "resolveVector3", "aim", "distance", "azimuth", "elevation", "clamp", "horizontal", "value", "low", "high", "Group3D", "component3d", "mesh", "optional", "state", "Mesh3D", "ctx", "s", "sweep", "SWEEP_KEYS", "shape3d", "key", "type", "own", "keys", "stated", "Box3D", "Sphere3D", "Plane3D", "Cylinder3D", "Cone3D", "Torus3D", "TorusKnot3D", "Circle3D", "Ring3D", "Capsule3D", "Polyhedron3D", "Types", "Extrude3D", "Lathe3D", "Tube3D", "Instances3D", "Graphics3D", "single", "Points3D", "points", "Line3D", "Sprite3D", "lerpFill3D", "Model3D", "ModelView3D", "modelClip", "clip", "trimmed", "index", "castsNoShadow", "AmbientLight3D", "optionalColor", "HemisphereLight3D", "DirectionalLight3D", "optionalVector3", "PointLight3D", "SpotLight3D", "AreaLight3D", "CAMERA_KEYS", "ORBIT_KEYS", "Camera3D", "optionalNumber", "timeline", "from", "ORBIT_CAMERA_DEFAULTS", "t", "out", "end", "data", "Fog3D", "Environment3D", "defined", "Canvas3D", "component2d", "state", "commands", "loader", "load", "measurer", "children", "measure", "inset", "box", "layout", "ctx", "draw", "isStillDocument", "doc", "isCompositionDocument", "isAudioDocument", "hasTimeline", "ROOT_NODE_ID", "nodeSpan", "spec", "timed", "effectiveSpan", "nodes", "id", "effectiveSpanIn", "n", "effectiveSpans", "byId", "spans", "chain", "inChain", "start", "above", "known", "member", "i", "span", "seen", "parent", "own", "untimed", "_startAt", "_endAt", "rest", "commandSpan", "command", "duration", "loopPasses", "documentDuration", "end", "node", "isProjectDocument", "doc", "asProjectDocument", "output", "documentDuration", "DOCUMENT_FORMAT_VERSION", "DocumentTooNewError", "version", "supported", "DOCUMENT_MIGRATIONS", "clip", "note", "constants", "rest", "variables", "row", "_kind", "variable", "retireSkSL", "retireFillFilters", "SKSL_SOURCE", "isObject", "value", "path", "out", "item", "next", "key", "retireShader", "shader", "legacyKey", "moved", "sksl", "stamped", "hadCoords", "i", "fill", "filters", "preset", "keeps", "documentFormatVersion", "doc", "migrateDocument", "migrateDocumentWith", "migrations", "target", "from", "changes", "json", "migrateProject", "migrateClip", "stepsBetween", "to", "steps", "step", "m", "noteInto", "prefix", "message", "stamp", "project", "tracksChanged", "tracks", "track", "own", "LOOP_DIRECTIONS", "isPlainObject", "v", "isTime", "checkEase", "ease", "path", "issues", "kind", "args", "EASE_KINDS", "isEaseCurve", "checkAudioEase", "checkParam", "value", "expressionOps", "key", "i", "at", "TRANSITION_KEYS", "checkTransition", "transition", "checkAudioProps", "type", "props", "name", "effects", "effect", "field", "checkLoop", "loop", "direction", "count", "checkNodeSpec", "node", "ok", "id", "parentId", "layerOrder", "checkNodeKeys", "sites", "byKey", "site", "existing", "checkRootShape", "spec", "rootType", "checkCommandSpec", "cmd", "targetId", "duration", "checkVariableSpec", "lerp", "variableRows", "rows", "checkVariables", "byId", "splitNodeRef", "ref", "dot", "checkExpressions", "declared", "keyed", "parsed", "k", "boundProps", "out", "prop", "reads", "checkExpressionCycles", "bound", "b", "settled", "stack", "reported", "walk", "entry", "cycle", "member", "next", "checkTree", "bySite", "parent", "seen", "cursor", "checkIdSpace", "nodes", "variables", "clash", "checkRetiredFields", "doc", "checkFormatVersion", "version", "RETIRED_PROJECT_FIELDS", "checkVocabulary", "commands", "registry", "typeOf", "checkNodes", "n", "checkSpan", "startAt", "endAt", "validateStill", "s", "keys", "validateComposition", "validateTimedDocument", "validateAudio", "RETIRED_COMMANDS", "nodeSites", "valid", "ids", "c", "retired", "span", "effectiveSpanIn", "validateDocument", "options", "validateProjectDocument", "project", "message", "raw", "track", "issue", "clipIssuesOf", "CLIP_ISSUES", "clip", "assertValidProjectDocument", "detail", "assertValidDocument", "MissingNode2D", "component2d", "MissingNode3D", "component3d", "MissingNodeAudio", "componentAudio", "PLACEHOLDERS", "DRAWS", "KEPT", "dimension", "ctor", "getPropertyMeta", "m", "key", "MISSING", "MISSING_TYPE", "missingNode", "spec", "props", "node", "placeholderProps", "kept", "out", "value", "missingNodeOf", "registryVocabulary", "registry", "nodes", "key", "properties", "prop", "described", "vocabularyBreaks", "prev", "next", "out", "command", "type", "was", "now", "before", "after", "NODE_TYPES", "Canvas2D", "Provider", "ThemeProvider", "DefaultTextStyle", "Rect", "Ellipse", "PathShape", "Polygon", "Polygram", "BooleanGroup", "MaskGroup", "Camera", "OrbitCamera", "RotatedBox", "Text", "RichText", "NumberNode", "Video", "AudioBus", "SoundNode", "Canvas3D", "Group3D", "Mesh3D", "Box3D", "Sphere3D", "Plane3D", "Circle3D", "Cylinder3D", "Cone3D", "Capsule3D", "Torus3D", "TorusKnot3D", "Tube3D", "Lathe3D", "Extrude3D", "Ring3D", "Polyhedron3D", "Points3D", "Line3D", "Sprite3D", "Instances3D", "Model3D", "Camera3D", "AmbientLight3D", "DirectionalLight3D", "PointLight3D", "SpotLight3D", "HemisphereLight3D", "AreaLight3D", "Fog3D", "Environment3D", "paintCommand", "method", "argKey", "target", "args", "duration", "easing", "fn", "VARIABLE_LERPS", "lerpNumber", "lerpVector2", "lerpVector3", "from", "to", "g", "b", "a", "lerpColor", "parseColor", "channel", "v", "installBuiltins", "registry", "key", "ctor", "lerp", "props", "driveCommand", "lerpKey", "override", "captured", "t", "DENIED_GLOBALS", "UNBINDABLE", "illegal", "name", "SDK_SPECIFIERS", "Registry", "_Registry", "options", "installBuiltins", "ctor", "key", "lerp", "ease", "pack", "type", "ctorOrOptions", "maybeOptions", "isTwoArgForm", "given", "cls", "declared", "getNodeDescriptor", "descriptor", "existing", "commands", "meta", "getCommandMeta", "source", "js", "spec", "props", "record", "evolution", "propEvolutionOf", "applyPropEvolution", "factory", "nodeTypeKey", "commandKey", "entry", "target", "args", "duration", "easing", "fn", "data", "arg", "global", "value", "where", "resolved", "normalized", "normalizeShaderPack", "sdk", "modules", "require", "specifier", "available", "s", "mod", "DENIED_GLOBALS", "out", "getPropertyMeta", "editor", "properties", "message", "renamed", "dimension", "trees", "v", "CANVAS_3D", "nodeTypeIsA", "registry", "type", "name", "seen", "at", "among", "names", "options", "parentIssue", "child", "parent", "own", "holder", "within", "inThree", "siblingIssue", "siblings", "beside", "placementIssues", "nodes", "parentOf", "node", "ROOT_NODE_ID", "byId", "children", "under", "issues", "parentId", "parentType", "issue", "without", "types", "AUDIO_ROOT_ID", "defaultRootBus", "clipRoot", "loweredAudioDocument", "doc", "nodes", "isRootBus", "spec", "reparent", "retarget", "command", "withPlayedSounds", "doc", "played", "c", "added", "spec", "start", "end", "nodeSpan", "segments", "segment", "i", "clipDocument", "lowered", "isAudioDocument", "loweredAudioDocument", "isStillDocument", "ALIGNMENT_KEYS", "SKIPPED", "commandTraits", "registry", "spec", "target", "lifecycle", "LIFECYCLE", "global", "known", "VARIABLE_COMMANDS", "row", "DEFAULT_ROOT", "record", "chain", "GLOBAL_NODE_COMMANDS", "methodOf", "entry", "NODE_COMMANDS", "implementsCore", "args", "props", "written", "writtenKeys", "readsLayout", "key", "isLayoutNeutralProp", "holdsWhenFinished", "traits", "HELD", "expressionOps", "commandNodeRefs", "descriptors", "refs", "descriptor", "value", "isContextProvider", "type", "ctor", "Node", "hasNodeRef", "site", "parsed", "ref", "isPlacementProp", "coreLibrary", "NEUTRAL_KEYS", "dimension", "PLACEMENT_3D", "PLACEMENT_2D", "writesPlacementInPlace", "sugar", "PLACEMENT_SUGAR_3D", "PLACEMENT_SUGAR_2D", "prop", "ROOT_NODE_ID", "TO", "PAINT", "WRITES", "READS_FROM", "hasAlignmentKey", "aligned", "refBound", "nodeRefKeys", "named", "keys", "values", "REF_KEYS", "found", "name", "KNOWN", "byChain", "impl", "coreImplementations", "core", "seeded", "Registry", "library", "impls", "proto", "own", "jsonEqual", "a", "b", "i", "ao", "bo", "defined", "key", "value", "emptyDiff", "diffClip", "prev", "next", "diff", "p", "lowered", "n", "documentDuration", "diffNodes", "diffVariables", "prevCommands", "nextCommands", "diffCommands", "rowsEmpty", "doc", "clipDocument", "rows", "DEFAULT_ROOT", "ROOT_NODE_ID", "prevRows", "nextRows", "byId", "changes", "prevRoot", "nextRoot", "sameNode", "id", "changed", "sameSpan", "prevKeys", "keyed", "was", "prevOrder", "siblingOrder", "nextOrder", "parent", "before", "after", "sameRelativeOrder", "sa", "nodeSpan", "sb", "prevAts", "groupByAt", "nextAts", "at", "out", "row", "groups", "index", "list", "e", "inB", "inA", "sharedA", "sharedB", "splitNodeRef", "ref", "dot", "expressionRefs", "value", "path", "vars", "keys", "unparsable", "seen", "site", "expressionOps", "parsed", "node", "indexDocument", "doc", "DocumentIndex", "clipDocument", "NO_REFS", "NO_BINDINGS", "EMPTY", "contains", "span", "t", "documentDuration", "commandRows", "spec", "index", "a", "b", "e", "target", "list", "atList", "parentId", "id", "out", "seen", "stack", "child", "grand", "i", "nodeSpan", "memo", "chain", "base", "cursor", "known", "ROOT_NODE_ID", "own", "at", "lo", "hi", "mid", "rows", "siblings", "parent", "settled", "command", "expressionRefs", "props", "vars", "keys", "unparsable", "refs", "v", "pair", "readers", "key", "prop", "found", "table", "existing", "p", "SettledIndex", "_SettledIndex", "placed", "finish", "writers", "replayed", "running", "read", "i", "p", "marked", "settles", "end", "readEarlier", "finishTime", "slot", "written", "observeSlots", "list", "writer", "Track", "index", "seconds", "tracks", "held", "k", "w", "long", "bin", "binEnd", "a", "b", "c", "ia", "NONE", "ib", "ic", "clamp01", "f", "_finish", "_tracks", "_replayed", "from", "to", "bins", "MAX_BINS", "items", "first", "last", "MAX_SPAN", "trackOf", "track", "fixes", "writes", "x", "y", "best", "lo", "hi", "mid", "start", "duration", "done", "t", "step", "down", "BITS", "INTS", "up", "MIN_REBUILD_NODES", "planTimelinePatch", "prev", "next", "diff", "env", "options", "structurallyFaulty", "prevRoot", "ROOT_NODE_ID", "nextRoot", "onlyPropsDiffer", "prevTraits", "traitsOf", "nextTraits", "added", "removed", "respec", "moved", "span", "reorderedParents", "targeted", "id", "anyCommand", "index", "traits", "test", "cid", "unknownEither", "t", "laidOut", "type", "laidOutEither", "kept", "R", "isProvider", "a", "b", "reinstantiate", "d", "inPlace", "placementOnly", "providerAbove", "reregistered", "live", "DN", "DV", "mark", "sameList", "at", "spec", "presenceChanged", "sameSpan", "L", "respecTouchesLayout", "valueChanged", "aimed", "nodeReaders", "bindsLayout", "reader", "reads", "prop", "refs", "size", "v", "key", "keysOf", "k", "ref", "lineageIn", "limit", "replay", "queue", "visited", "detach", "parent", "child", "captures", "duplicateIds", "duplicateKeys", "unresolvedParent", "cycle", "invalidRoot", "out", "targetId", "target", "set", "seen", "cursor", "parentId", "sa", "nodeSpan", "sb", "was", "is", "jsonEqual", "i", "resolveEase", "ease", "registry", "easeOfSpec", "key", "inTimelineOrder", "commands", "spec", "index", "a", "b", "NO_SLOTS", "readsOf", "command", "recorder", "owned", "settles", "slot", "heldIf", "held", "made", "settling", "defaultRootSpec", "ROOT_NODE_ID", "splitRoot", "specs", "rest", "root", "presenceOf", "doc", "spans", "node", "nodeSpan", "ClipTimeline", "canvas", "documentDuration", "captureLayer", "NO_LAYER", "PropSlot", "PRESENCE_PREFIX", "id", "entry", "captureInitial", "settle", "moved", "out", "placed", "played", "commandSoundsOf", "sound", "missing", "missingNodeOf", "seconds", "onWrite", "unobserved", "baseline", "local", "clamp01", "rows", "arrivals", "departures", "row", "wanted", "within", "byDocumentOrder", "byParent", "group", "siblings", "parent", "base", "child", "layer", "props", "snap", "next", "prev", "indexDocument", "planTimelinePatch", "diffClip", "patch", "prepare", "fresh", "host", "applySnapshotLayer", "resetToInitial", "previous", "rebuilt", "dirty", "touched", "isStillDocument", "old", "name", "dot", "prop", "_observer", "at", "depth", "literal", "bindings", "expressionOps", "migrateNodeProps", "hasBindings", "dimension", "missingNode", "bound", "placeholderProps", "cell", "VAR_PREFIX", "lerp", "v", "nodes", "ordered", "refBound", "SettledIndex", "whole", "written", "i", "slots", "slotBaselines", "entries", "parentId", "captureBaseline", "typeKey", "factory", "message", "LEGACY_COMMAND_HINTS", "duration", "easing", "WriteRecorder", "loop", "loopRepeats", "repeat", "loopCommand", "variable", "holdsWhenFinished", "commandTraits", "observeSlots", "buildToEnd", "target", "given", "PROP_DIFF_COMMANDS", "args", "entrance", "ended", "byId", "s", "from", "effectiveSpanIn", "end", "owner", "found", "path", "source", "type", "seen", "of", "described", "holds", "d", "steps", "reads", "opener", "traits", "hasNodeRef", "PresenceIndex", "commandNodeRefs", "isContextProvider", "isLayoutNeutralProp", "writesPlacementInPlace", "MISSING_TYPE", "was", "changed", "value", "jsonEqual", "added", "removed", "isDocumentNode", "disposeBuilt", "replay", "captures", "c", "pending", "step", "firstWrite", "LAYOUT_SLOT", "make", "driveCommand", "cells", "SiblingCounts", "size", "delta", "count", "order", "start", "NO_ROWS", "to", "pass", "k", "lo", "hi", "mid", "withRichTextDescriptor", "descriptor", "width", "height", "x", "y", "pivot", "resolveShapeAlignment", "stripShapeAlignmentKeys", "resolveShapePivot", "toPathString", "d", "cmd", "withPathDescriptor", "descriptor", "resolveShapePivot", "caretCount", "layout", "last", "asTextBlockSource", "value", "toRenderIssue", "issue", "renderIssueKey", "RenderBackendError", "isFatalRenderIssue", "Geo", "o", "source", "src", "Mat", "Tex", "data", "width", "height", "segmentsOf", "value", "defaults", "clampSegment", "fallback", "index", "arcSegmentsFor", "radius", "maxHalf", "evaluateRoundedBox", "options", "half", "box", "arc", "position", "normal", "uv", "index", "grid", "patches", "emit", "segments", "AXES", "SIGNS", "axis", "u", "v", "sign", "face", "axisVector", "a", "b", "point", "lerp", "signA", "signB", "t", "angle", "dir", "s", "signX", "signY", "signZ", "corner", "direction", "polar", "azimuth", "base", "uCount", "vCount", "vi", "ui", "planarUv", "c", "d", "pushTriangle", "ax", "ay", "az", "bx", "by", "bz", "cx", "cy", "cz", "ux", "uy", "uz", "vx", "vy", "vz", "nx", "ny", "nz", "out", "from", "to", "shadowCasts", "mode", "shadowReceives", "resolveShadowOptions3D", "cylinderRadii", "radius", "resolveBevel3D", "bevel", "options", "size", "evaluateParametric", "geometry", "resolved", "uSegments", "vSegments", "uCount", "vCount", "position", "uv", "color", "scratch", "vi", "v", "ui", "u", "index", "vertex", "p", "rgba", "resolveLinearRgb", "cursor", "a", "b", "c", "d", "r", "g", "parseColor", "srgbToLinear", "channel", "identity4", "multiply4", "a", "b", "out", "col", "b0", "b1", "b2", "b3", "invert4", "m", "n11", "n21", "n31", "n41", "n12", "n22", "n32", "n42", "n13", "n23", "n33", "n43", "n14", "n24", "n34", "n44", "t11", "t12", "t13", "t14", "determinant", "d", "applyMatrix4", "p", "x", "y", "z", "compose4", "position", "rotation", "scale", "w", "x2", "y2", "z2", "xx", "xy", "xz", "yy", "yz", "zz", "wx", "wy", "wz", "lookAtRotation4", "eye", "target", "up", "UP", "zx", "zy", "length", "xLength", "yx", "transformMatrix4", "transform", "parentWorld", "resolveVector3", "world", "origin", "inverseParent", "rotationOf4", "translation4", "scale4", "quaternion", "quaternionFromEuler", "eulerOf", "sx", "sy", "sz", "perspective4", "fov", "aspect", "near", "far", "zoom", "top", "height", "width", "left", "frustum4", "right", "bottom", "c", "orthographic4", "dx", "dy", "cx", "cy", "r", "t", "h", "centeredBox3", "hx", "hy", "hz", "unionBox3", "a", "b", "corners3", "box", "min", "max", "transformBox3", "m", "minX", "minY", "minZ", "maxX", "maxY", "maxZ", "corner", "p", "applyMatrix4", "geometryBounds3D", "geometry", "top", "bottom", "cylinderRadii", "radius", "tube", "outer", "point", "resolveVector3", "points", "pointsBounds3", "expandBox3", "positionBounds3", "position", "i", "x", "y", "z", "by", "MUTABLE_MATERIAL_KEYS", "STRUCTURAL_MATERIAL_KEYS", "AssetManager", "precomp", "storageAdapter", "audioDevice", "onError", "error", "layoutGatesOf", "src", "frame", "jobs", "key", "track", "job", "records", "record", "err", "discardAt", "dispose", "load", "existing", "disposer", "NO_DISPOSE", "currentTime", "inWindow", "srcs", "required", "seen", "consider", "req", "offsetSecs", "globalStart", "globalEnd", "stableId", "stableKey", "s", "data", "cause", "requestKey", "audioSignature", "setsEqual", "message", "keys", "clipOffsetSecs", "paramKey", "effectsKey", "transitionKey", "busKey", "bus", "busStopKey", "reqs", "r", "a", "b", "v", "assetKey", "decl", "normalizeWeight", "weight", "AssetDeclaration", "catalog", "options", "src", "trim", "family", "key", "load", "gate", "existing", "fills", "declareFill", "fill", "effects", "effect", "declareEffect", "node", "declareTree", "now", "nativeYield", "s", "channel", "queue", "messageChannelYield", "resolve", "yieldToScheduler", "native", "__resetSchedulerForTests", "clipFrameToTime", "frame", "fps", "clipTimeToFrame", "seconds", "nearest", "frameSpecAtTime", "trackFrameCount", "seconds", "fps", "clipTimeToFrame", "placeTracks", "tracks", "track", "index", "startFrame", "totalFramesOf", "spans", "total", "span", "spansCovering", "frame", "frameTime", "duration", "clipFrameToTime", "spanFrames", "frameCount", "last", "at", "endFrame", "ClipInstance", "clip", "duration", "_scope", "lowered", "width", "height", "Canvas2D", "ROOT_NODE_ID", "ClipTimeline", "measurer", "next", "patch", "relayout", "seconds", "read", "was", "onWrite", "editor", "ContextMap", "applyEditorStates", "pass", "sampleTree", "at", "primeMotionTree", "rowId", "row", "id", "node", "below", "current", "parent", "index", "span", "visit", "walk", "path", "own", "children", "i", "nodePath", "child", "spans", "effectiveSpans", "spec", "clipDocument", "NO_OWNERS", "AssetIndex", "frameCount", "ownerKey", "segments", "touched", "previous", "next", "segment", "appendSegment", "decl", "frame", "key", "assetKey", "owner", "list", "at", "s", "hit", "owners", "out", "gates", "entry", "map", "keys", "changed", "sameRecord", "last", "first", "start", "end", "layoutLoader", "visit", "from", "to", "recordOf", "startFrame", "endFrame", "a", "b", "v", "DeclarationMemo", "ownerKey", "frame", "entry", "frames", "refineAssets", "instance", "options", "sweep", "Sweep", "MAX_REQUEUES", "_instance", "_options", "owners", "below", "limited", "from", "p", "slot", "span", "spanFrames", "placed", "isPseudo", "heapPop", "readers", "owner", "intervals", "segmentsOf", "keys", "key", "isDev", "rows", "slash", "spans", "row", "start", "duration", "fps", "end", "frameTime", "to", "seconds", "observeSlots", "index", "seen", "node", "presentAt", "unchanged", "reads", "writes", "lastRead", "readLayout", "readClock", "bound", "bind", "sub", "bindDetached", "declaration", "AssetDeclaration", "unobserved", "LAYOUT_SLOT", "declareNode", "err", "e", "slotLabel", "type", "labels", "warnOnce", "deps", "values", "memo", "named", "host", "name", "getPropSlot", "value", "sameValue", "out", "Node", "decls", "set", "previous", "sameDecls", "writers", "visit", "first", "last", "after", "commandId", "list", "heapPush", "STRUCTURE_SLOT", "PRESENCE_PREFIX", "i", "a", "b", "isPlain", "proto", "decl", "other", "sameDecl", "history", "open", "segment", "next", "warned", "message", "heap", "parent", "top", "tail", "left", "right", "child", "HOSTED", "HOSTLESS", "DETACHED", "hostSlotId", "ownerKey", "name", "hostlessSlotId", "hostOf", "id", "nameOf", "SlotNamer", "_instance", "slot", "host", "key", "Node", "slots", "out", "rowsAbove", "slash", "addTo", "map", "value", "set", "removeFrom", "NONE", "OwnerDependencies", "own", "row", "dirtyOwners", "input", "patch", "deps", "fps", "prev", "next", "diff", "lower", "frame", "at", "owner", "arrival", "readers", "below", "startOf", "index", "span", "firstFrameAt", "placement", "PRESENCE_PREFIX", "STRUCTURE_SLOT", "spec", "ROOT_NODE_ID", "hosted", "names", "writes", "placed", "VAR_PREFIX", "LAYOUT_SLOT", "parent", "from", "a", "b", "changedRows", "changedProps", "dep", "changedSlots", "props", "providerChangedAbove", "jsonEqual", "changed", "seen", "parentId", "seconds", "frameTime", "AudioIndex", "ownerKey", "requests", "prior", "sameValue", "out", "a", "b", "keys", "key", "COMMAND_AUDIO", "DEFAULT_PRECOMP_BUDGET_MS", "ClipStore", "project", "_scope", "options", "track", "placeTracks", "next", "update", "themeChanged", "jsonEqual", "previous", "old", "entry", "changed", "id", "spans", "sameSpans", "trackId", "budgetMs", "isCancelled", "onProgress", "deadline", "now", "finished", "yieldToScheduler", "key", "ownerKey", "decl", "localFrame", "trackIds", "isReady", "rebuilt", "gates", "record", "arrived", "frame", "horizon", "i", "span", "memo", "DeclarationMemo", "frameCount", "trackFrameCount", "AssetIndex", "AudioIndex", "OwnerDependencies", "themeOf", "diffClip", "instance", "patch", "refined", "before", "measurer", "issuesOf", "dirty", "dirtyOwners", "node", "child", "type", "isContextProvider", "keys", "duration", "best", "bestStart", "build", "refine", "index", "steps", "result", "profile", "fps", "catalog", "ClipInstance", "err", "buildErrorOf", "audioSlots", "refineAssets", "phase", "_node", "namer", "SlotNamer", "owner", "slots", "collect", "delta", "row", "seen", "sweep", "spanFrames", "step", "fromOf", "from", "slash", "fromArrival", "candidates", "kept", "keptBefore", "ids", "assets", "audio", "sounds", "byOwner", "sound", "list", "spanOf", "found", "requests", "n", "busId", "closed", "bus", "target", "findBusById", "busPathTo", "NodeAudio", "busPathOf", "trimEnd", "requestOf", "error", "landed", "prior", "records", "sameRecords", "audioRequests", "clampAudioToClip", "layoutGates", "errors", "sameValue", "out", "placed", "named", "run", "inner", "families", "text", "fontSize", "fontFamily", "fontWeight", "letterSpacing", "fontStyle", "family", "code", "message", "nodeId", "commandId", "e", "segments", "segment", "clipDuration", "req", "clampBusToClip", "clamped", "endAt", "stop", "a", "b", "other", "clip", "StateEvaluator", "project", "_scope", "store", "ClipStore", "firstVisual", "slot", "frame", "target", "active", "sameSlots", "topmost", "measurer", "pass", "trackId", "next", "prior", "kept", "id", "states", "tracks", "spans", "placeTracks", "track", "i", "old", "covering", "spansCovering", "last", "span", "localFrame", "instance", "dt", "clipFrameToTime", "time", "frameTime", "previous", "slots", "isAudioDocument", "a", "b", "SETTLE_PASSES", "renderSettled", "render", "adapter", "isCurrent", "pass", "ProjectAssets", "_fps", "_catalog", "tracks", "touched", "live", "track", "prior", "moved", "key", "record", "before", "sameRecord", "id", "next", "entry", "current", "sameTrack", "holders", "trackId", "merged", "mergeRecord", "shiftRecord", "assetTrackOf", "offset", "existing", "intrinsicMB", "catalog", "size", "decodedMB", "LEADS_PER_MB", "MIN_LEAD", "MAX_LEAD", "TAIL_FRAMES", "width", "height", "leadFrames", "mb", "fps", "lead", "a", "b", "v", "ASSET_TIMELINE_PHASES", "createAssetTimelineProfile", "timings", "trackIndex", "trackId", "phases", "p", "open", "since", "now", "totalMs", "close", "elapsed", "phase", "frameCount", "AssetTimeline", "project", "_scope", "options", "ClipStore", "ProjectAssets", "n", "track", "frame", "span", "spansCovering", "budgetMs", "DEFAULT_PRECOMP_BUDGET_MS", "isCancelled", "onProgress", "next", "ownerKey", "decl", "localFrame", "store", "fps", "spans", "totalFrames", "totalFramesOf", "totalDuration", "tracks", "buildErrors", "complete", "local", "found", "undiscovered", "assets", "i", "resolveOpenAudio", "profiled", "id", "r", "offset", "audioRequests", "req", "absStart", "naturalEnd", "isViewport3D", "node", "collectBoxes3D", "canvas", "frame", "path", "projection", "canvas3DProjection", "out", "entry", "nodes3DOf", "world", "projected", "projectBox3", "toNodeBox", "a", "b", "ORIGIN_3D", "projectNode3D", "canvasPath", "targetPath", "parentPoints", "localPoints", "e", "own", "parent", "project", "matrix", "points", "point", "projectPoint3", "space", "parentSpaceOf", "placed", "applyMatrix4", "clip", "MIN_CLIP_W", "ndcX", "ndcY", "rectX", "rectY", "p", "applyToPoint", "pickNode3D", "tolerance", "inverse", "invert", "mapped", "local", "best", "bestDepth", "rectContains", "walk3D", "children", "parentPath", "i", "child", "Node3D", "nodePath", "boundsKey", "bounds", "scene", "walked", "walkScene3D", "view", "invert4", "aspect", "multiply4", "projectionMatrix", "boxes", "matrices", "parentMatrices", "stack", "identity4", "camera", "descriptor", "target", "localBounds", "top", "op", "scope", "scopeMatrix", "closed", "unionBox3", "cameraMatrix4", "drawn", "drawableBox3", "DEFAULT_CAMERA_MATRIX", "transform", "transformMatrix4", "into", "transformBox3", "centeredBox3", "geometryBounds3D", "box", "instance", "placement", "resolveCameraPlacement", "origin", "translation4", "lookAtRotation4", "DEFAULT_FOV", "DEFAULT_NEAR", "DEFAULT_FAR", "perspective4", "halfHeight", "orthographic4", "BOX_EDGES", "OFFSCREEN_LIMIT", "corners3", "corner", "minX", "minY", "maxX", "maxY", "any", "include", "y", "w", "q", "pIn", "qIn", "t", "halfWidth", "limitX", "limitY", "rect", "clamp", "centre", "viewed", "value", "low", "high", "slop", "at", "x", "renderMatrix", "node", "frame", "spaceFrameOf", "multiply", "parent", "childrenMatrix", "m", "camera", "spaceRootFrame", "cam", "r", "cameraMatrix", "parentPlanePointAt", "root", "path", "point", "nodeAt", "Node2D", "movePlaneMatrix", "inv", "invert", "p", "applyToPoint", "behindCamera", "plane", "box", "childPlanePointAt", "reparentPlacementAt", "parentPath", "offsets", "to", "from", "at", "slot", "along", "back", "into", "placed", "was", "childFold", "will", "turn", "scale", "shift", "here", "own", "pixels", "offset", "now", "o", "drawn", "centre", "x", "y", "folded", "foldedTransform", "nodeHandlesAt", "prop", "handleValueAt", "spaceFrameForChildren", "multiplyAffine3", "atDepth", "spaceScreenMatrix", "local", "isProjective", "rotation", "opacity", "n", "nodeBox", "b", "translation", "anchors", "worldAnchors", "nodeBoxAt", "canvas", "segments", "isViewport3D", "prefixPath", "next", "canvas3DFrame", "collectBoxes3D", "segment", "count", "projectNode3DAt", "parentPoints", "localPoints", "i", "projectNode3D", "pickNode", "tolerance", "pickIn", "isRoot", "spaceVisibility", "inside", "containsPoint", "children", "childSlots", "order", "paintOrder", "k", "hit", "nodePath", "pickNode3D", "collectBoxes", "out", "natural", "_", "slots", "frames", "spaceChildFrame", "spaceChildOrder", "child", "nodeTextLayout", "node", "path", "source", "state", "Text", "textStateOf", "block", "m", "renderMatrix", "at", "x", "y", "p", "applyToPoint", "carets", "caretCount", "lines", "line", "i", "caretOffsetAt", "layout", "point", "best", "bestDistance", "caret", "d", "distanceToSegment", "caretRangeQuads", "start", "end", "from", "to", "quads", "b", "left", "right", "a", "dx", "dy", "lengthSq", "t", "PlaybackController", "track", "index", "error", "frame", "issue", "e", "key", "renderIssueKey", "prior", "decl", "declOf", "trackId", "instance", "t", "ownerKey", "node", "next", "AssetNotLoadedError", "token", "record", "cause", "type", "src", "params", "project", "DEFAULT_PRECOMP_BUDGET_MS", "scope", "ClipStore", "AssetTimeline", "StateEvaluator", "AssetManager", "speed", "reverse", "currentTime", "gen", "clipTimeToFrame", "yieldToScheduler", "final", "result", "gates", "span", "spansCovering", "TRIM_HORIZON_SECONDS", "cb", "raw", "toRenderIssue", "clamped", "clipFrameToTime", "err", "render", "upgrades", "adapter", "settlingUpgrades", "outcome", "renderSettled", "stale", "trackStart", "frameCount", "trackFrameCount", "bars", "pathOfOwner", "_node", "path", "frames", "spanFrames", "waveformsByPath", "waveformsByOwner", "nodeToTreeState", "nodeId", "canvas", "findNode", "nodeBoxAt", "nodeAt", "out", "collectBoxes", "parentPoints", "localPoints", "projectNode3DAt", "point", "parentPlanePointAt", "childPlanePointAt", "parentPath", "offsets", "reparentPlacementAt", "nodeHandlesAt", "prop", "handleValueAt", "findNodeByPath", "Node2D", "source", "asTextBlockSource", "nodeTextLayout", "tolerance", "pickNode", "props", "existing", "states", "pass", "decoded", "upgraded", "muted", "catalog", "state", "c", "i", "nodePath", "waveform", "bar", "requests", "byPath", "req", "info", "list", "root", "seg", "id", "child", "found", "ManifestAssetCatalog", "manifest", "src", "meta", "key", "fontFamily", "audio", "video", "width", "height", "Playback", "controller", "speed", "reverse", "frame", "muted", "callback", "Ticker", "duration", "t", "notify", "cb", "playing", "speed", "reverse", "c", "callback", "SteppedClock", "Ticker", "t", "Session", "engine", "options", "resolveProjectDocument", "ManifestAssetCatalog", "manifest", "deps", "measurer", "audioDevice", "masterClock", "PlaybackController", "SteppedClock", "Playback", "seconds", "clipTimeToFrame", "frame", "document", "next", "setTheme", "override", "fallback", "opened", "asProjectDocument", "migrated", "migrateDocument", "project", "resolved", "assertValidProjectDocument", "parseCSV", "text", "options", "delimiter", "rows", "splitRows", "header", "cell", "records", "row", "record", "key", "i", "numericCols", "resolveNumericColumns", "booleanCols", "resolveBooleanColumns", "out", "col", "raw", "parseData", "file", "_options", "numeric", "sawValue", "bool", "numericSet", "field", "inQuotes", "sawAnyField", "pushField", "pushRow", "ch", "warned", "isProduction", "deprecationMessage", "notice", "warnDeprecated", "deprecate", "fn", "wrapped", "args", "generateList", "generator", "result", "i", "createRef", "current", "ref", "node", "SeedGenerator", "seed", "a", "b", "t", "UINT32_RANGE", "Random", "_Random", "from", "to", "size", "out", "i", "mean", "stdev", "z", "u", "v", "s", "mul", "time", "frequency", "f", "curve", "r1", "r2", "x", "h", "isSteppable", "x"]
|
|
7
|
-
}
|