@webmusic/bridge 0.2.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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/component/controls.ts","../src/component/manifest.ts","../src/component/settings.ts","../src/component/document.ts","../src/component/theme.ts","../src/component/surfaces.ts","../src/component/views.ts","../src/component/plugins.ts","../src/component/mount.ts","../src/component/export.ts","../src/version.ts"],"sourcesContent":["// The UI Kit control of a module that shows one (DEC-078, DEC-097), bound to\n// the control the module offers through Kernel's `moduleControlOf`. A rebuild\n// of the graph creates a new module instance; `refresh` moves the binding to\n// it without remounting the control, so a value being dragged is never\n// replaced.\n//\n// A control fills its host (DEC-080): the host is a box of the size the\n// author gave it, or of the control's natural size from `controlSize`.\n\nimport {Button, Choice, Matrix, MessageBox, NumberValue, Toggle, ValueList} from '@webmusic/kernel/message';\nimport {\n NodesModule, PresetModule, bang, floatAtom, floatMessage, intAtom, intMessage, message, parseMessage,\n type Message, type ModuleControl,\n} from '@webmusic/kernel/module';\nimport {\n mountButton, mountDial, mountMatrix, mountMenu, mountMessage, mountMultislider, mountNodes, mountNumber, mountPresetGrid, mountSlider,\n mountTabs, mountToggle,\n type ButtonHandle, type ControlHandle,\n} from '@webmusic/ui/controls';\n\ntype Snapshot = Record<string, unknown>;\n\nexport interface ModuleControlView {\n /** Bind to the module's current control (or none, while it is unresolved). */\n refresh(next: ModuleControl | undefined): void;\n destroy(): void;\n}\n\nconst number = (value: unknown, fallback = 0) => typeof value === 'number' && Number.isFinite(value) ? value : fallback;\nconst bound = (value: unknown) => typeof value === 'number' && Number.isFinite(value) ? value : undefined;\nconst numberMessage = (value: number, float: boolean): Message => float ? floatMessage(value) : intMessage(Math.round(value));\n\n/** The kinds of control a module may show; each is a UI Kit `/controls` presenter. */\nexport const CONTROL_KINDS: readonly string[] = Object.freeze(['button', 'toggle', 'number', 'slider', 'dial', 'message', 'menu', 'tab', 'multislider', 'matrix', 'preset', 'nodes']);\n\ntype Config = Readonly<Record<string, unknown>>;\nconst KIND_OF_TYPE: Readonly<Record<string, string | ((config: Config) => string)>> = Object.freeze({\n [Button.type]: 'button',\n [Toggle.type]: 'toggle',\n [NumberValue.type]: (config: Config) => config.control === 'slider' || config.control === 'dial' ? config.control : 'number',\n [Choice.type]: (config: Config) => config.control === 'tab' ? 'tab' : 'menu',\n [MessageBox.type]: 'message',\n [ValueList.type]: 'multislider',\n [Matrix.type]: 'matrix',\n [PresetModule.type]: 'preset',\n [NodesModule.type]: 'nodes',\n});\n\n/** Which control shows a module record, from its type and options; undefined for a module that shows none. */\nexport function controlKindOf(record: {readonly plugin: {readonly id: string}; readonly config: Config}): string | undefined {\n const kind = KIND_OF_TYPE[record.plugin.id];\n return typeof kind === 'function' ? kind(record.config) : kind;\n}\n\n/** One cell of a control's natural size, in CSS pixels. */\nconst CELL = 32;\n\n/**\n * The natural size of a control of `kind`, in CSS pixels: the size of its\n * box until the author resizes it. The module's options decide how many\n * cells a matrix, a preset grid or tabs have, and how wide a message is.\n */\nexport function controlSize(kind: string, config: Config = {}): {width: number; height: number} {\n const count = (value: unknown, fallback: number, most: number) =>\n typeof value === 'number' && Number.isInteger(value) && value >= 1 ? Math.min(most, value) : fallback;\n const items = Array.isArray(config.items) ? config.items.map(String) : [];\n // The controls draw text in a small monospace face: about 7.5 px a character.\n const wide = (characters: number) => Math.ceil(characters * 7.5) + 18;\n const within = (value: number, least: number, most: number) => Math.min(most, Math.max(least, value));\n switch (kind) {\n case 'number': return {width: 96, height: CELL};\n case 'slider': case 'menu': return {width: 128, height: CELL};\n case 'dial': return {width: 48, height: 64};\n case 'message': return {width: within(wide(typeof config.text === 'string' ? config.text.length : 0), 48, 320), height: CELL};\n case 'tab': return {width: within(items.reduce((sum, item) => sum + wide(item.length), 0), 64, 480), height: CELL};\n case 'multislider': return {width: 128, height: 96};\n case 'matrix': return {width: count(config.columns, 4, 32) * CELL, height: count(config.rows, 4, 32) * CELL};\n case 'preset': { const slots = count(config.count, 16, 64); return {width: Math.min(8, slots) * CELL, height: Math.ceil(slots / 8) * CELL}; }\n case 'nodes': return {width: 160, height: 160};\n default: return {width: CELL, height: CELL};\n }\n}\n\n/** Mount the control of `kind` into `host`; the control fills the host. */\nexport function mountModuleControl(host: HTMLElement, kind: string, options: {cardHost?: HTMLElement; label: string; onError?: (error: unknown) => void}): ModuleControlView {\n let iface: ModuleControl | undefined;\n let release: (() => void) | undefined;\n const listeners = new Set<() => void>();\n const snapshot = (): Snapshot => {\n const value = iface?.snapshot();\n return value && typeof value === 'object' && !Array.isArray(value) ? value as Snapshot : {};\n };\n const send = (value: Message) => iface?.interact(value);\n const subscribe = (notify: () => void) => { listeners.add(notify); return () => { listeners.delete(notify); }; };\n const disabled = () => !iface;\n // One stylesheet for every control in the component's root, not a copy beside each (DEC-094).\n const common = {label: options.label, fill: true, stylesheet: 'shared' as const, onError: options.onError ?? ((error: unknown) => console.error(error))};\n let flashes = 0;\n let handle: ControlHandle;\n\n switch (kind) {\n case 'button':\n handle = mountButton(host, {snapshot: () => ({disabled: disabled()}), press: () => send(bang()), subscribe}, common);\n break;\n case 'toggle':\n handle = mountToggle(host, {snapshot: () => ({on: snapshot().on === true, disabled: disabled()}), setOn: on => send(intMessage(on ? 1 : 0)), subscribe}, common);\n break;\n case 'number':\n handle = mountNumber(host, {snapshot: () => {\n const state = snapshot();\n return {value: number(state.value), min: bound(state.min), max: bound(state.max), float: state.float === true, disabled: disabled()};\n }, setValue: value => send(numberMessage(value, snapshot().float === true)), subscribe}, common);\n break;\n case 'slider':\n case 'dial': {\n const binding = {snapshot: () => {\n const state = snapshot();\n return {value: number(state.value), min: number(state.min), max: number(state.max, 127), float: state.float === true, disabled: disabled()};\n }, setValue: (value: number) => send(numberMessage(value, snapshot().float === true)), subscribe};\n // A slider stands upright in a box taller than it is wide.\n handle = kind === 'slider' ? mountSlider(host, binding, {...common, orientation: 'auto'}) : mountDial(host, binding, common);\n break;\n }\n case 'message':\n handle = mountMessage(host, {snapshot: () => ({text: String(snapshot().text ?? ''), disabled: disabled()}), press: () => send(bang()), subscribe}, common);\n break;\n case 'menu':\n case 'tab': {\n const binding = {snapshot: () => {\n const state = snapshot();\n return {items: Array.isArray(state.items) ? state.items.map(String) : [], index: number(state.index), disabled: disabled()};\n }, select: (index: number) => send(intMessage(index)), subscribe};\n handle = kind === 'menu' ? mountMenu(host, binding, {...common, cardHost: options.cardHost}) : mountTabs(host, binding, common);\n break;\n }\n case 'multislider':\n handle = mountMultislider(host, {snapshot: () => {\n const state = snapshot();\n return {values: Array.isArray(state.values) ? state.values.map(item => number(item)) : [], min: number(state.min), max: number(state.max, 1), float: state.float === true, disabled: disabled()};\n }, setValues: values => {\n const float = snapshot().float === true;\n send(message('list', values.map(value => float ? floatAtom(value) : intAtom(value))));\n }, subscribe}, common);\n break;\n case 'matrix':\n handle = mountMatrix(host, {snapshot: () => {\n const state = snapshot();\n return {columns: number(state.columns, 4), rows: number(state.rows, 4), cells: Array.isArray(state.cells) ? state.cells.map(item => number(item)) : [], disabled: disabled()};\n }, setCell: (column, row, on) => send(message('list', [intAtom(column), intAtom(row), intAtom(on ? 1 : 0)])), subscribe}, common);\n break;\n case 'preset':\n handle = mountPresetGrid(host, {snapshot: () => {\n const state = snapshot();\n return {count: number(state.count, 16), stored: Array.isArray(state.stored) ? state.stored.map(item => number(item)) : [], current: number(state.current), disabled: disabled()};\n }, recall: slot => send(intMessage(slot)), store: slot => send(parseMessage(`store ${slot}`)), clear: slot => send(parseMessage(`clear ${slot}`)), subscribe}, common);\n break;\n case 'nodes':\n handle = mountNodes(host, {snapshot: () => {\n const state = snapshot();\n const nodes = Array.isArray(state.nodes) ? state.nodes as {x: number; y: number; radius: number}[] : [];\n const cursor = (state.cursor ?? {x: 0.5, y: 0.5}) as {x: number; y: number};\n return {nodes, cursor, weights: Array.isArray(state.weights) ? state.weights.map(item => number(item)) : [], disabled: disabled()};\n }, setCursor: (x, y) => send(parseMessage(`cursor ${x.toFixed(4)} ${y.toFixed(4)}`)),\n moveNode: (index, x, y) => send(parseMessage(`node ${index} ${x.toFixed(4)} ${y.toFixed(4)}`)), subscribe}, common);\n break;\n default:\n throw new Error(`No control for ${kind}.`);\n }\n\n const changed = () => {\n // A button flashes whenever its module counts another bang.\n const count = number(snapshot().flashes, flashes);\n if (count > flashes && 'flash' in handle) (handle as ButtonHandle).flash();\n flashes = count;\n for (const listener of [...listeners]) listener();\n };\n\n return {\n refresh(next) {\n if (next === iface) return;\n release?.();\n iface = next;\n flashes = number(snapshot().flashes, 0);\n release = next?.subscribe(changed);\n for (const listener of [...listeners]) listener();\n },\n destroy() { release?.(); listeners.clear(); handle.destroy(); },\n };\n}\n","// Component manifests (DEC-081): what a host needs to place a component in a\n// graph — its ports, its parameters and how it takes the size of its box —\n// so Studio, `mountComponent` and an app place every component the same way,\n// with no code for one component's kind.\n//\n// A code-authored component (one of the packages' Components) declares its\n// manifest here, beside the Elements it names. Each port is bound through a\n// public member the Element already has: an audio input through `analyser`,\n// a source input through `inputModule`, a note output through `module`\n// (DEC-063). A graph-authored component's manifest is derived from its inlet\n// and outlet modules by `projectManifest`.\n//\n// Pure data and functions: no DOM is touched until an Element is defined.\n\nimport {defineAudioLevelAnalyzerElement, defineAudioMeterElement, defineAudioOscilloscopeElement, defineAudioSpectrumAnalyzerElement,\n defineAudioTransientAnalyzerElement} from '@webmusic/audio/analyze/element';\nimport {AUDIO_EFFECT_TYPES, defineAudioEffectElement, defineAudioMixerElement, defineAudioPlayerElement, defineAudioPlaylistElement, defineAudioRecorderElement} from '@webmusic/audio/play/element';\nimport {defineAudioClipViewElement, defineAudioLiveViewElement, defineAudioViewElement} from '@webmusic/audio/view/element';\nimport type {ElementHeightFit} from '@webmusic/kernel/element';\nimport {BufferModule} from '@webmusic/audio/play/headless';\nimport {InletModule, NestedComponent, OutletModule, numberedPort, parseModuleProject, type ModuleProject, type ProjectAssetReference} from '@webmusic/kernel/module';\nimport {defineChordAnalysisElement, defineIntervalAnalysisElement, defineRhythmAnalysisElement,\n defineScaleAnalysisElement} from '@webmusic/score/analyze/element';\nimport {RACK_PART_SOUNDS, SCORE_EFFECT_TYPES, defineNoteInputElement, defineRackControlElement, defineRackPartElement, defineScoreEffectElement, defineScorePlayerElement, defineScoreRecorderElement,\n defineSynthPanelElement} from '@webmusic/score/play/element';\nimport {Effect} from '@webmusic/score/play/headless';\nimport {definePitchViewElement, defineScoreGridViewElement, defineScoreViewElement, defineSheetViewElement} from '@webmusic/score/view/element';\n\n/** A port of a component, as a graph sees it. */\nexport interface ComponentPort {\n readonly id: string;\n readonly family: 'audio' | 'note' | 'source' | 'message';\n readonly direction: 'input' | 'output';\n}\n\n/** A port of a code-authored component, with the Element member that carries it. */\nexport type ComponentPortBinding =\n /** Audio in: the host connects the cord to an AnalyserNode and hands it to the Element's `analyser`. */\n | (ComponentPort & {readonly family: 'audio'; readonly direction: 'input'; readonly bind: 'analyser'; readonly fftSize: number})\n /** A source in: the host hands the upstream module to the Element's `inputModule`. */\n | (ComponentPort & {readonly family: 'source'; readonly direction: 'input'; readonly bind: 'inputModule'})\n /** A source in, for a panel: the host hands the upstream module to the Element's `moduleTarget`, whose parameters and inserts it edits. */\n | (ComponentPort & {readonly family: 'source'; readonly direction: 'input'; readonly bind: 'moduleTarget'})\n /**\n * A source in, for a companion of an audio player: the host hands the\n * upstream box's Element to `player`, which then plays through that player\n * and its Session. With no cord it is linked to nothing, so it never plays\n * by itself outside the graph.\n */\n | (ComponentPort & {readonly family: 'source'; readonly direction: 'input'; readonly bind: 'player'})\n /** Audio in or out of an insert: the host connects the box's input to the Element's `input` and its `output` to the box's output, and gives it the graph's `context`. */\n | (ComponentPort & {readonly family: 'audio'; readonly bind: 'insert'})\n /** Notes in: the host hands the Element's `inputModule` a module whose `notes` output repeats the cords' notes. */\n | (ComponentPort & {readonly family: 'note'; readonly direction: 'input'; readonly bind: 'inputModule'})\n /** Notes out: the host forwards the note output port of the Element's `module`. */\n | (ComponentPort & {readonly family: 'note'; readonly direction: 'output'; readonly bind: 'module'})\n /** A source out: a cord hands the Element's `module` to the `inputModule` of the companion it reaches (DEC-063). */\n | (ComponentPort & {readonly family: 'source'; readonly direction: 'output'; readonly bind: 'module'})\n /**\n * Audio out: the host lends the Element a module context with the graph's\n * audio environment and Session, whose default destination is this port\n * (DEC-084). A player in it joins the graph's Session; a desk's master plays into it.\n */\n | (ComponentPort & {readonly family: 'audio'; readonly direction: 'output'; readonly bind: 'context'})\n /** Audio in: the host admits the cord's audio as one channel of the Element's `module`, labelled `channel`. */\n | (ComponentPort & {readonly family: 'audio'; readonly direction: 'input'; readonly bind: 'admit'; readonly channel: string});\n\n/** A project asset the box's module loads and the host hands to an Element property. */\nexport interface ComponentAsset {\n /** The asset role in the module record; for `entries`, the prefix of its roles (`entry1`, `entry2`, …). */\n readonly role: string;\n /** What it loads as: a Score, an AudioClip, or every matching role as a playlist's `{id, label, clip}` entries, in role order. */\n readonly kind: 'score' | 'clip' | 'entries';\n /** The Element property the loaded value is assigned to. */\n readonly property: string;\n}\n\n/** The project assets a host has for the music its components play, named by what each loads as. */\nexport interface ComponentAssetSources {\n /** The ID of the project asset a Score is loaded from. */\n readonly score?: string;\n /** The ID of the project asset an AudioClip is loaded from. */\n readonly clip?: string;\n /** The IDs of the project assets a playlist queues, in order; without it, `clip` once. */\n readonly entries?: readonly string[];\n}\n\n/**\n * The asset roles of a new box of a component (DEC-094): the `assets` of its\n * module record, so the box plays the host's music instead of waiting. A\n * manifest's `asset` says which role and what it loads as; the host says\n * which of its project assets that is. Returns `undefined` for a component\n * that plays no asset and for one whose kind the host gave no asset for.\n *\n * ```ts\n * const assets = componentAssetRoles(manifest, {score: 'arabesque-midi', clip: 'arabesque-wav'});\n * const record = {plugin: {id: manifest.plugin, version: COMPONENT_PLUGIN_VERSION}, config: {}, ...(assets && {assets})};\n * ```\n */\nexport function componentAssetRoles(manifest: Pick<ComponentManifest, 'asset'>, sources: ComponentAssetSources): Readonly<Record<string, string>> | undefined {\n const wanted = manifest.asset;\n if (!wanted) return undefined;\n if (wanted.kind === 'entries') {\n const entries = sources.entries ?? (sources.clip === undefined ? [] : [sources.clip]);\n if (entries.length === 0) return undefined;\n // `entry1`, `entry2`, …: the host reads them back in role order.\n return Object.freeze(Object.fromEntries(entries.map((id, index) => [`${wanted.role}${index + 1}`, id])));\n }\n const id = sources[wanted.kind];\n return id === undefined ? undefined : Object.freeze({[wanted.role]: id});\n}\n\n/** A value set from the box's arguments, by position. */\nexport interface ComponentParameter {\n /** The key in the module's config. */\n readonly name: string;\n /** The argument's name in the box's usage. */\n readonly label: string;\n readonly kind: 'number' | 'word';\n readonly fallback: number | string;\n readonly min?: number;\n readonly max?: number;\n /** The Element attribute the value is written to. */\n readonly attribute?: string;\n /**\n * The value names a shared buffer the host binds; empty binds nothing until\n * a name is given. `true`: an `<audio-clip-view>` shows and edits it.\n * `'clip'`: its samples are the Element's read-only `clip`. `'take'`: each\n * take the Element records (`webaudio:recorded`) is written to it.\n */\n readonly buffer?: true | 'clip' | 'take';\n /** The words a `word` parameter accepts; without it, any word. */\n readonly choices?: readonly string[];\n /** A comma-separated list, each item one of these words; empty is an empty list. */\n readonly list?: readonly string[];\n}\n\n/** How an Element takes the height of a resized box (DEC-080). Selectors name public parts. */\n/** How a component's Element is made as tall as its box: Kernel's fit, which an Element declares itself (DEC-094). */\nexport type ComponentFit = ElementHeightFit;\n\n/** A code-authored component: how a host places it in a graph. */\nexport interface ComponentManifest {\n /** The name typed into its box. */\n readonly name: string;\n readonly summary: string;\n /** The custom element's tag. */\n readonly tag: string;\n /** The project plugin ID of its module in a graph. */\n readonly plugin: string;\n /** Its ports; with `portsFor`, the ports it has with every argument at its fallback. */\n readonly ports: readonly ComponentPortBinding[];\n /**\n * Ports that follow the box's arguments (DEC-094), such as a desk's strips:\n * given a config, the ports a box with it has. {@link manifestFor} applies it.\n */\n portsFor?(config: Readonly<Record<string, unknown>>): readonly ComponentPortBinding[];\n readonly parameters: readonly ComponentParameter[];\n /** The music it plays, when it plays a project asset; without the asset it waits (DEC-082). */\n readonly asset?: ComponentAsset;\n /** Lend the graph's module context on the box although no audio output needs it: the Element then works in the graph's AudioContext. */\n readonly scope?: true;\n /**\n * An Element that works only inside another, as a declaration inside its\n * owner: the host places it in this container, which the box holds. The\n * manifest's attributes, settings and bindings apply to the inner Element;\n * the container takes its own attributes and lends the inner one its scope.\n */\n readonly container?: {readonly tag: string; readonly attributes?: Readonly<Record<string, string>>; define(): void};\n /** Set Element properties a config describes but no attribute carries, after its parameters are applied. */\n configure?(element: HTMLElement, config: Readonly<Record<string, unknown>>): void;\n /**\n * The host computes the Element's `.spectrogram` from the clip it shows —\n * its own, or its player's — while its `type` is `spectrogram`, because the\n * Element draws a spectrogram only from data given to it.\n */\n readonly spectrogram?: true;\n /** Attributes the Element starts with in a graph; a setting may replace one (DEC-085). */\n readonly attributes?: Readonly<Record<string, string>>;\n /**\n * Attributes a setting never writes: those the host needs as they are.\n */\n readonly locked?: readonly string[];\n /** Natural width in CSS pixels; its natural height is its own. */\n readonly width: number;\n /**\n * How it follows a resized box, in place of the fit its Element declares\n * (DEC-094): given when the manifest holds the Element to one layout, as\n * `keys` does. With neither it keeps its own height, and a box too small\n * for it shows it scaled down (DEC-099).\n */\n readonly fit?: ComponentFit;\n /**\n * The Element shows music longer or wider than itself and scrolls it\n * inside its own frame (DEC-099): notation, a piano roll, lanes of analysis\n * over a score, a recording zoomed into. Every other component shows all\n * of itself in whatever box it is given, and nothing in it scrolls.\n */\n readonly scrolls?: true;\n /**\n * Set when the Element edits a Score through `.editor` and `editable`\n * (DEC-086): while its `editable` attribute is on, its box lends it the\n * document of the box its `source` cord comes from.\n */\n readonly edits?: 'score';\n /** Register the custom element; safe to call again. */\n define(): void;\n}\n\n// The five that DEC-078 placed as view objects keep their plugin IDs, so saved\n// projects and exported components load unchanged.\nexport const KEYS_PLUGIN = 'webmusic.surface.keys';\nexport const SCOPE_PLUGIN = 'webmusic.surface.scope';\nexport const METER_PLUGIN = 'webmusic.surface.meter';\nexport const SPECTRUM_PLUGIN = 'webmusic.surface.spectrum';\nexport const ROLL_PLUGIN = 'webmusic.surface.roll';\n/** Components placed after DEC-081 take their plugin ID from their tag. */\nexport const CLIP_PLUGIN = 'webmusic.component.audio-clip-view';\nexport const LEVEL_PLUGIN = 'webmusic.component.audio-level-analyzer';\n\nconst audioIn = (fftSize: number): ComponentPortBinding => ({id: 'input', family: 'audio', direction: 'input', bind: 'analyser', fftSize});\nconst sourceIn: ComponentPortBinding = {id: 'source', family: 'source', direction: 'input', bind: 'inputModule'};\nconst pluginOf = (tag: string): string => `webmusic.component.${tag}`;\nconst audioOut: ComponentPortBinding = {id: 'output', family: 'audio', direction: 'output', bind: 'context'};\n/** A desk's inputs: each cord is one channel strip, named by its number. */\n// Four strips and the master fit in 424 px.\nconst channelsIn = (count: number): ComponentPortBinding[] => Array.from({length: count}, (_, index) =>\n ({id: `in${index + 1}`, family: 'audio', direction: 'input', bind: 'admit', channel: String(index + 1)}));\n/** How many strips a desk has: its first argument, 1–16 (DEC-094). */\nconst DESK_INPUTS: ComponentParameter = {name: 'inputs', label: 'inputs', kind: 'number', fallback: 4, min: 1, max: 16};\nconst deskPorts = (config: Readonly<Record<string, unknown>>): readonly ComponentPortBinding[] => {\n const value = parameterValue(DESK_INPUTS, config) as number;\n const count = Math.min(DESK_INPUTS.max!, Math.max(DESK_INPUTS.min!, Math.round(value)));\n return Object.freeze([...channelsIn(count), audioOut]);\n};\n\n/** The insert types a Score effect names, in the order a library lists them. */\n// The packages name their own choices (DEC-094); a manifest lists them as they do.\nconst SCORE_EFFECTS = SCORE_EFFECT_TYPES;\n\n/** The packages' Components a graph can hold, in the order a library lists them. */\nexport const OFFICIAL_COMPONENTS: readonly ComponentManifest[] = Object.freeze<ComponentManifest[]>([\n {name: 'keys', summary: 'Piano keyboard: play notes into a synth', tag: 'score-note-input', plugin: KEYS_PLUGIN,\n ports: [{id: 'notes', family: 'note', direction: 'output', bind: 'module'}],\n parameters: [\n {name: 'low', label: 'low', kind: 'number', fallback: 48, min: 0, max: 127, attribute: 'start'},\n {name: 'high', label: 'high', kind: 'number', fallback: 72, min: 0, max: 127, attribute: 'end'},\n ],\n attributes: {layout: 'piano', routing: 'manual', 'aria-label': 'Keyboard'},\n // The box is a piano whose notes the host forwards: its fit and width are a piano's.\n locked: ['layout', 'routing'],\n width: 320, fit: {kind: 'token', property: '--wm-note-height', content: '[part~=\"root\"]', surface: '[part~=\"viewport\"]', least: 24},\n define: () => defineNoteInputElement()},\n {name: 'roll', summary: 'Piano roll following a score', tag: 'score-grid-view', plugin: ROLL_PLUGIN,\n ports: [{id: 'source', family: 'source', direction: 'input', bind: 'inputModule'}],\n parameters: [], attributes: {height: '176', 'note-height': '6'},\n edits: 'score',\n scrolls: true, width: 320,\n define: () => defineScoreGridViewElement()},\n {name: 'scope', summary: 'Oscilloscope of the incoming audio', tag: 'audio-oscilloscope', plugin: SCOPE_PLUGIN,\n ports: [audioIn(2048)],\n parameters: [{name: 'timebaseMs', label: 'milliseconds', kind: 'number', fallback: 10, min: 1, max: 40, attribute: 'timebase-ms'}],\n width: 288,\n define: () => defineAudioOscilloscopeElement()},\n {name: 'meter', summary: 'Level meter of the incoming audio', tag: 'audio-meter', plugin: METER_PLUGIN,\n ports: [audioIn(2048)], parameters: [],\n width: 224,\n define: () => defineAudioMeterElement()},\n {name: 'spectrum', summary: 'Spectrum of the incoming audio', tag: 'audio-spectrum-analyzer', plugin: SPECTRUM_PLUGIN,\n ports: [audioIn(4096)], parameters: [],\n width: 288,\n define: () => defineAudioSpectrumAnalyzerElement()},\n {name: 'level', summary: 'RMS, peak and crest of the incoming audio', tag: 'audio-level-analyzer', plugin: LEVEL_PLUGIN,\n ports: [audioIn(2048)],\n parameters: [{name: 'thresholdDbfs', label: 'threshold dBFS', kind: 'number', fallback: -12, min: -60, max: 0, attribute: 'threshold-dbfs'}],\n width: 288,\n define: () => defineAudioLevelAnalyzerElement()},\n // A buffer's waveform: `buffer` holds the samples and shows nothing (DEC-081).\n {name: 'clip', summary: 'Show and edit the samples of a named buffer', tag: 'audio-clip-view', plugin: CLIP_PLUGIN,\n ports: [],\n parameters: [{name: 'buffer', label: 'name', kind: 'word', fallback: '', buffer: true}],\n attributes: {height: '120'},\n scrolls: true, width: 320,\n define: () => defineAudioClipViewElement()},\n // Placed after the first seven: the packages' other Components that take\n // their data from a cord.\n {name: 'sheet', summary: 'Engraved sheet music following a score', tag: 'score-sheet-view', plugin: pluginOf('score-sheet-view'),\n ports: [sourceIn], parameters: [], attributes: {layout: 'flow', height: '160'},\n edits: 'score',\n scrolls: true, width: 320,\n define: () => defineSheetViewElement()},\n {name: 'view', summary: 'Staff, piano roll or waterfall of a score', tag: 'score-view', plugin: pluginOf('score-view'),\n ports: [sourceIn],\n parameters: [{name: 'type', label: 'type', kind: 'word', fallback: 'staff', choices: ['staff', 'piano-roll', 'waterfall'], attribute: 'type'}],\n attributes: {height: '120'},\n scrolls: true, width: 320,\n define: () => defineScoreViewElement()},\n {name: 'pitch', summary: 'The pitches sounding now, on keys, a staff or frets', tag: 'score-pitch-view', plugin: pluginOf('score-pitch-view'),\n ports: [sourceIn],\n parameters: [{name: 'type', label: 'type', kind: 'word', fallback: 'keyboard', choices: ['keyboard', 'staff', 'fretboard'], attribute: 'type'}],\n width: 320,\n define: () => definePitchViewElement()},\n {name: 'chords', summary: 'Chords of a score as it plays', tag: 'score-chord-analysis', plugin: pluginOf('score-chord-analysis'),\n ports: [sourceIn], parameters: [], scrolls: true, width: 320,\n define: () => defineChordAnalysisElement()},\n {name: 'intervals', summary: 'Intervals of a score as it plays', tag: 'score-interval-analysis', plugin: pluginOf('score-interval-analysis'),\n ports: [sourceIn], parameters: [], scrolls: true, width: 320,\n define: () => defineIntervalAnalysisElement()},\n {name: 'rhythm', summary: 'Rhythm of a score against its beats', tag: 'score-rhythm-analysis', plugin: pluginOf('score-rhythm-analysis'),\n ports: [sourceIn], parameters: [], scrolls: true, width: 320,\n define: () => defineRhythmAnalysisElement()},\n {name: 'degrees', summary: 'Pitches of a score as degrees of a scale', tag: 'score-scale-analysis', plugin: pluginOf('score-scale-analysis'),\n ports: [sourceIn],\n parameters: [\n {name: 'scale', label: 'scale', kind: 'word', fallback: 'major',\n choices: ['major', 'natural-minor', 'harmonic-minor', 'melodic-minor-ascending', 'melodic-minor-descending'], attribute: 'scale'},\n {name: 'tonic', label: 'tonic', kind: 'word', fallback: '', attribute: 'tonic'},\n ],\n scrolls: true, width: 320,\n define: () => defineScaleAnalysisElement()},\n {name: 'transients', summary: 'Onsets in the incoming audio', tag: 'audio-transient-analyzer', plugin: pluginOf('audio-transient-analyzer'),\n ports: [audioIn(2048)], parameters: [], width: 288,\n define: () => defineAudioTransientAnalyzerElement()},\n {name: 'live', summary: 'Scrolling waveform or spectrogram of the incoming audio', tag: 'audio-live-view', plugin: pluginOf('audio-live-view'),\n ports: [audioIn(2048)],\n parameters: [{name: 'type', label: 'type', kind: 'word', fallback: 'waveform', choices: ['waveform', 'spectrogram'], attribute: 'type'}],\n attributes: {height: '64'},\n width: 320,\n define: () => defineAudioLiveViewElement()},\n // Players and desks (DEC-084): each plays in the graph's Session through the\n // module context its box lends it, so its transport and the graph's are one.\n {name: 'player', summary: 'Play a score with its own transport, in the graph\\'s Session', tag: 'score-player', plugin: pluginOf('score-player'),\n ports: [audioOut, {id: 'source', family: 'source', direction: 'output', bind: 'module'}], parameters: [],\n asset: {role: 'source', kind: 'score', property: 'score'},\n attributes: {controls: 'show', 'aria-label': 'Score player'}, width: 320,\n define: () => defineScorePlayerElement()},\n {name: 'track', summary: 'Play a recording with its own transport, in the graph\\'s Session', tag: 'audio-player', plugin: pluginOf('audio-player'),\n ports: [audioOut, {id: 'source', family: 'source', direction: 'output', bind: 'module'}], parameters: [],\n asset: {role: 'source', kind: 'clip', property: 'clip'},\n attributes: {controls: 'show', 'aria-label': 'Audio player'}, width: 320,\n define: () => defineAudioPlayerElement()},\n // A transport alone (DEC-098), named `playbar` because `transport` is the word editors give the object that\n // reads musical time: a player told to conduct the Session it is lent, so the box plays, pauses and\n // seeks whatever the graph holds, a clock with nothing timed on it included. A component draws no transport of\n // its own; one that is played by hand places this, a `player` or a `track`.\n {name: 'playbar', summary: 'Play, pause and seek the graph\\'s Session', tag: 'score-player', plugin: pluginOf('score-player-conduct'),\n ports: [], parameters: [], scope: true,\n attributes: {controls: 'show', session: 'conduct', 'time-control': 'full', 'aria-label': 'Transport'}, locked: ['session'], width: 320,\n define: () => defineScorePlayerElement()},\n {name: 'rack', summary: 'Mixing desk: a fader, mute and solo for each cord in, and a master', tag: 'score-rack-control', plugin: pluginOf('score-rack-control'),\n ports: deskPorts({}), portsFor: deskPorts, parameters: [DESK_INPUTS], attributes: {'aria-label': 'Rack'}, width: 424,\n define: () => defineRackControlElement()},\n {name: 'mixer', summary: 'Audio mixer: a fader, mute and solo for each cord in, and a master', tag: 'audio-mixer', plugin: pluginOf('audio-mixer'),\n ports: deskPorts({}), portsFor: deskPorts, parameters: [DESK_INPUTS], attributes: {'aria-label': 'Mixer'}, width: 424,\n define: () => defineAudioMixerElement()},\n // A recorder takes the notes cabled to it and plays its take into the graph.\n {name: 'recorder', summary: 'Record the incoming notes as a score, replay and export the take', tag: 'score-recorder', plugin: pluginOf('score-recorder'),\n ports: [{id: 'notes', family: 'note', direction: 'input', bind: 'inputModule'}, audioOut], parameters: [],\n attributes: {'aria-label': 'Score recorder'}, width: 320,\n define: () => defineScoreRecorderElement()},\n // A panel attached to the module its cord comes from; without one it shows no controls.\n {name: 'panel', summary: 'Sound, envelope and effect controls of the player cabled to it', tag: 'score-synth-panel', plugin: pluginOf('score-synth-panel'),\n ports: [{id: 'target', family: 'source', direction: 'input', bind: 'moduleTarget'}], parameters: [],\n attributes: {sections: 'sound,envelope,effects', 'aria-label': 'Synth panel'}, width: 320,\n define: () => defineSynthPanelElement()},\n // A read-only waveform of a named buffer; `clip` is the one that edits. The Element's spectrogram and meter types\n // need data a buffer does not carry, so the type stays `waveform`.\n // A read-only drawing: of a named buffer, or of the track cabled to it, following its playhead.\n {name: 'wave', summary: 'Waveform or spectrogram of a named buffer, or of the track cabled to it', tag: 'audio-view', plugin: pluginOf('audio-view'),\n // Its source is its player (DEC-094): the module the cord carries, whose owner the view follows.\n ports: [sourceIn],\n parameters: [\n {name: 'buffer', label: 'name', kind: 'word', fallback: '', buffer: 'clip'},\n {name: 'type', label: 'type', kind: 'word', fallback: 'waveform', choices: ['waveform', 'spectrogram'], attribute: 'type'},\n ],\n spectrogram: true, attributes: {height: '96', 'aria-label': 'Audio view'},\n width: 320,\n define: () => defineAudioViewElement()},\n // The two companions of `track`: cabled from it, they play through it and its Session.\n {name: 'take', summary: 'Record the microphone; the take goes to a named buffer and plays through the track cabled to it', tag: 'audio-recorder', plugin: pluginOf('audio-recorder'),\n ports: [{id: 'player', family: 'source', direction: 'input', bind: 'player'}],\n parameters: [{name: 'buffer', label: 'name', kind: 'word', fallback: '', buffer: 'take'}],\n scope: true, attributes: {'aria-label': 'Audio recorder'}, width: 320,\n define: () => defineAudioRecorderElement()},\n {name: 'playlist', summary: 'A queue of recordings, played in order through the track cabled to it', tag: 'audio-playlist', plugin: pluginOf('audio-playlist'),\n ports: [{id: 'player', family: 'source', direction: 'input', bind: 'player'}, audioOut], parameters: [],\n asset: {role: 'entry', kind: 'entries', property: 'entries'},\n attributes: {'aria-label': 'Playlist'}, width: 320,\n define: () => defineAudioPlaylistElement()},\n // The panel's insert mode: the audio cabled in passes through its effects, then its EQ.\n {name: 'eq', summary: 'Insert: the effects it names, then a three-band equalizer, with their controls', tag: 'score-synth-panel', plugin: pluginOf('score-synth-panel-eq'),\n ports: [{id: 'input', family: 'audio', direction: 'input', bind: 'insert'}, {id: 'output', family: 'audio', direction: 'output', bind: 'insert'}],\n parameters: [{name: 'effects', label: 'effects', kind: 'word', fallback: '', list: SCORE_EFFECTS}],\n attributes: {mode: 'insert', sections: 'effects,eq', 'aria-label': 'Equalizer'}, locked: ['mode'], width: 320,\n configure: (element, config) => {\n const names = String(config.effects ?? '').split(',').map(name => name.trim()).filter(name => (SCORE_EFFECTS as readonly string[]).includes(name));\n (element as HTMLElement & {effects?: unknown[]}).effects = names.map(name => {\n const recipe = (Effect as unknown as Record<string, () => {label?: string}>)[name]!();\n recipe.label = name;\n return recipe;\n });\n },\n define: () => defineSynthPanelElement()},\n // Declarations wrapped as components (DEC-089). An effect is one insert on the player its cord comes from.\n {name: 'effect', summary: 'One insert on the score player cabled to it; its controls are the player\\'s panel', tag: 'score-effect', plugin: pluginOf('score-effect'),\n ports: [{id: 'target', family: 'source', direction: 'input', bind: 'moduleTarget'}],\n parameters: [{name: 'type', label: 'type', kind: 'word', fallback: 'gain', choices: SCORE_EFFECTS, attribute: 'type'}],\n attributes: {'aria-label': 'Effect'}, width: 160,\n define: () => defineScoreEffectElement()},\n {name: 'audio-effect', summary: 'One insert on the track cabled to it', tag: 'audio-effect', plugin: pluginOf('audio-effect'),\n ports: [{id: 'target', family: 'source', direction: 'input', bind: 'moduleTarget'}],\n parameters: [{name: 'type', label: 'type', kind: 'word', fallback: 'gain', choices: AUDIO_EFFECT_TYPES, attribute: 'type'}],\n attributes: {'aria-label': 'Audio effect'}, width: 160,\n define: () => defineAudioEffectElement()},\n // One voice of a desk: placed in a desk of its own, which gives it a strip and plays it into the box's output.\n {name: 'part', summary: 'One voice: a score and an oscillator, with its own fader, in the graph\\'s Session', tag: 'score-rack-part', plugin: pluginOf('score-rack-part'),\n ports: [audioOut, {id: 'source', family: 'source', direction: 'output', bind: 'module'}],\n parameters: [{name: 'sound', label: 'sound', kind: 'word', fallback: 'triangle', choices: RACK_PART_SOUNDS, attribute: 'sound'}],\n asset: {role: 'source', kind: 'score', property: 'score'},\n container: {tag: 'score-rack-control', attributes: {master: 'false', 'aria-label': 'Part'}, define: () => defineRackControlElement()},\n width: 96,\n define: () => defineRackPartElement()},\n]);\n\n\n\n/** The manifest of a plugin ID, if it is an official component's. */\nexport function componentManifestOf(plugin: string): ComponentManifest | undefined {\n return OFFICIAL_COMPONENTS.find(manifest => manifest.plugin === plugin);\n}\n\n/**\n * A manifest as it applies to one box (DEC-094): with `portsFor`, its ports\n * are the ones the box's config gives; otherwise the manifest itself.\n */\nexport function manifestFor(manifest: ComponentManifest, config: Readonly<Record<string, unknown>>): ComponentManifest {\n if (!manifest.portsFor) return manifest;\n return Object.freeze({...manifest, ports: manifest.portsFor(config)});\n}\n\n/** The manifest of a box name, if it names an official component. */\nexport function findComponentManifest(name: string): ComponentManifest | undefined {\n return OFFICIAL_COMPONENTS.find(manifest => manifest.name === name);\n}\n\nconst PORT_FAMILIES: readonly ComponentPort['family'][] = ['message', 'audio', 'note', 'source'];\n\n/**\n * The ports of a component placed in a project, by what it is (DEC-081 rule 3,\n * DEC-089): an official component's from its manifest, a graph-authored one's\n * — a `NestedComponent` — from the channel kinds its options list, as `in<n>`\n * and `out<n>`. Undefined for a module that is not a component. A host that\n * connects components, such as an app's inspector (DEC-092), reads both the\n * same way.\n */\nexport function componentPorts(record: {readonly plugin: {readonly id: string}; readonly config: Readonly<Record<string, unknown>>}): readonly ComponentPort[] | undefined {\n const found = componentManifestOf(record.plugin.id);\n const manifest = found && manifestFor(found, record.config);\n if (manifest) return Object.freeze(manifest.ports.map(({id, family, direction}) => Object.freeze({id, family, direction})));\n if (record.plugin.id !== NestedComponent.type) return undefined;\n const side = (value: unknown, direction: ComponentPort['direction']): ComponentPort[] => Array.isArray(value)\n ? value.flatMap((kind, index) => PORT_FAMILIES.includes(kind as ComponentPort['family'])\n ? [Object.freeze({id: numberedPort(direction === 'input' ? 'in' : 'out', index), family: kind as ComponentPort['family'], direction})] : [])\n : [];\n return Object.freeze([...side(record.config.inlets, 'input'), ...side(record.config.outlets, 'output')]);\n}\n\n/** True when a component only listens: its audio cords are sends, never a replaced route. */\nexport function isListener(plugin: string): boolean {\n const manifest = componentManifestOf(plugin);\n return !!manifest && manifest.ports.length > 0 && manifest.ports.every(port => port.bind === 'analyser');\n}\n\n/** A parameter's value from a config, or its fallback when absent or out of kind. */\nexport function parameterValue(parameter: ComponentParameter, config: Readonly<Record<string, unknown>>): number | string {\n const value = config[parameter.name];\n if (parameter.kind === 'number') return typeof value === 'number' && Number.isFinite(value) ? value : parameter.fallback;\n if (typeof value !== 'string') return parameter.fallback;\n if (parameter.list) return listed(parameter.list, value) ?? parameter.fallback;\n return !parameter.choices || parameter.choices.includes(value) ? value : parameter.fallback;\n}\n\n/** A comma-separated word list, when every item is one of `words`; undefined otherwise. */\nfunction listed(words: readonly string[], value: string): string | undefined {\n const items = value.split(',').map(item => item.trim()).filter(Boolean);\n return items.every(item => words.includes(item)) ? items.join(',') : undefined;\n}\n\n/**\n * A config from a box's argument words, by position. A number out of its\n * range is clamped and a word that is not a number keeps the fallback; either\n * is reported. Returns the config and the first problem, if any.\n */\nexport function configOfArguments(manifest: ComponentManifest, words: readonly string[]): {config: Record<string, number | string>; error?: string} {\n const config: Record<string, number | string> = {};\n let error: string | undefined;\n if (words.length > manifest.parameters.length) error = `${manifest.name} takes ${manifest.parameters.length || 'no'} argument${manifest.parameters.length === 1 ? '' : 's'}.`;\n manifest.parameters.forEach((parameter, index) => {\n const word = words[index];\n if (word === undefined) { config[parameter.name] = parameter.fallback; return; }\n if (parameter.kind === 'word') {\n if (parameter.list) {\n const value = listed(parameter.list, word);\n if (value === undefined) error ??= `${manifest.name} ${parameter.label} must list ${parameter.list.join(', ')}, separated by commas.`;\n config[parameter.name] = value ?? parameter.fallback;\n } else if (parameter.choices && !parameter.choices.includes(word)) {\n error ??= `${manifest.name} ${parameter.label} must be one of ${parameter.choices.join(', ')}.`;\n config[parameter.name] = parameter.fallback;\n } else config[parameter.name] = word;\n return;\n }\n const number = Number(word);\n if (!Number.isFinite(number)) { error ??= `${parameter.label} must be a number.`; config[parameter.name] = parameter.fallback; return; }\n const min = parameter.min ?? -Infinity, max = parameter.max ?? Infinity;\n if (number < min || number > max) error ??= `${manifest.name} ${parameter.label} must be within ${min}–${max}.`;\n config[parameter.name] = Math.min(max, Math.max(min, number));\n });\n return error ? {config, error} : {config};\n}\n\n/** The usage shown for a component's box: its name and arguments with their fallbacks. */\nexport function componentUsage(manifest: ComponentManifest): string {\n return [manifest.name, ...manifest.parameters.map(parameter => parameter.fallback === '' ? `[${parameter.label}]` : `[${parameter.label}=${parameter.fallback}]`)].join(' ');\n}\n\n/** What a graph-authored component offers a host: the ports its inlet and outlet modules make and the resources it loads. */\nexport interface ProjectManifest {\n readonly ports: readonly ComponentPort[];\n readonly assets: readonly ProjectAssetReference[];\n}\n\n// Messages, audio, notes and sources cross a component's edge (DEC-076, DEC-089).\nconst EDGE_FAMILIES: readonly ComponentPort['family'][] = ['message', 'audio', 'note', 'source'];\n\n/**\n * The manifest of a graph-authored component: the ports its inlet and outlet\n * modules make (an inlet of index n is `in<n>`, an outlet `out<n>`, as a\n * `NestedComponent` names them) and its assets. `contextId` picks the component's context; by\n * default the project's top-level contexts.\n */\nexport function projectManifest(input: unknown, contextId?: string): ProjectManifest {\n const project: ModuleProject = parseModuleProject(input);\n const top = new Set(contextId !== undefined ? [contextId] : project.contexts.filter(context => context.parentId === undefined).map(context => context.id));\n const ports = new Map<string, ComponentPort>();\n for (const record of project.modules) {\n const direction = record.plugin.id === InletModule.type ? 'input' : record.plugin.id === OutletModule.type ? 'output' : undefined;\n if (!top.has(record.contextId) || !direction) continue;\n const family = record.config.kind === undefined ? 'message' : record.config.kind as ComponentPort['family'];\n if (!EDGE_FAMILIES.includes(family)) continue;\n const index = record.config.index;\n const number = typeof index === 'number' && Number.isFinite(index) ? Math.max(0, Math.trunc(index)) : 0;\n const id = numberedPort(direction === 'input' ? 'in' : 'out', number);\n if (!ports.has(id)) ports.set(id, Object.freeze({id, family, direction}));\n }\n const order = (port: ComponentPort) => (port.direction === 'input' ? 0 : 1e6) + Number(port.id.replace(/\\D+/g, ''));\n return Object.freeze({\n ports: Object.freeze([...ports.values()].sort((a, b) => order(a) - order(b))),\n assets: Object.freeze([...project.assets]),\n });\n}\n\nconst BUFFER_PLUGIN = BufferModule.type;\n/** Plugin version of the components' modules. */\nexport const COMPONENT_PLUGIN_VERSION = '1.0.0';\n\n/**\n * Move a buffer's waveform out of its box (DEC-081). Before the split a\n * buffer placed in the presentation showed its samples; each such buffer\n * gets a `clip` bound to its name, beside it on the canvas and in its place\n * in the presentation. A project with no presented buffer is returned as\n * it is, so running this again changes nothing.\n */\nexport function migrateBufferViews(input: unknown): ModuleProject {\n const project = parseModuleProject(input);\n const byId = new Map(project.modules.map(record => [record.id, record]));\n const presentation = project.layout.presentation ?? [];\n if (!presentation.some(item => byId.get(item.moduleId)?.plugin.id === BUFFER_PLUGIN)) return project;\n const ids = new Set(project.modules.map(record => record.id));\n const positions = new Map(project.layout.modules.map(item => [item.moduleId, item]));\n const modules = [...project.modules];\n const layout = [...project.layout.modules];\n const clips = new Map<string, string>();\n for (const item of presentation) {\n const record = byId.get(item.moduleId);\n if (record?.plugin.id !== BUFFER_PLUGIN || clips.has(record.id)) continue;\n const name = record.config.name;\n if (typeof name !== 'string' || !name) continue;\n let id = `${record.id}-clip`;\n while (ids.has(id)) id = `${id}_`;\n ids.add(id);\n clips.set(record.id, id);\n modules.push({id, contextId: record.contextId, plugin: {id: CLIP_PLUGIN, version: COMPONENT_PLUGIN_VERSION}, label: `clip ${name}`, config: {buffer: name}});\n const at = positions.get(record.id);\n layout.push({moduleId: id, x: at?.x ?? 0, y: (at?.y ?? 0) + (at?.height ?? 32) + 16});\n }\n return parseModuleProject({\n ...project,\n modules,\n layout: {\n ...project.layout,\n modules: layout,\n // A buffer that names nothing has no waveform to show: it leaves the presentation.\n presentation: presentation.flatMap(item => {\n if (byId.get(item.moduleId)?.plugin.id !== BUFFER_PLUGIN) return [item];\n const clip = clips.get(item.moduleId);\n return clip ? [{...item, moduleId: clip}] : [];\n }),\n },\n });\n}\n","// A component's own settings in a graph (DEC-085): attributes of its Element\n// and custom properties set on it, kept in its module's config under\n// `attributes` and `style`. They are the Element's public settings — the\n// same attributes and tokens a page would write — so a component is set the\n// same way in a graph, in an exported component and pasted into a project.\n//\n// A project file may come from anyone, so nothing here trusts it. An\n// attribute is written only when the Element observes it, which leaves out\n// event handlers and anything else the Element does not read; never when the\n// graph owns it (a source, a connection, an identity), when a box argument\n// writes it, or when the manifest locks it. A custom property is written only\n// under the public `--wm-` prefix and only with a value that fetches nothing.\n//\n// Pure: no DOM is touched beyond reading the Element class's observed\n// attributes from the custom element registry.\n\nimport type {ProjectJsonObject} from '@webmusic/kernel/module';\nimport type {ComponentManifest} from './manifest';\n\n/** A component's settings, as read from its module's config. */\nexport interface ComponentSettings {\n /** Attributes of the Element, by name. */\n readonly attributes: Readonly<Record<string, string>>;\n /** Custom properties set on the Element, by name. */\n readonly style: Readonly<Record<string, string>>;\n}\n\n/** The keys of a module's config that hold its settings. */\nexport type ComponentSettingKind = keyof ComponentSettings;\n\n/**\n * Attributes a graph owns on every component: where its material comes from,\n * what it is connected to, and what identifies it. Cords, assets and the host\n * decide these; a setting never does.\n */\nexport const GRAPH_ATTRIBUTES: readonly string[] = Object.freeze([\n 'id', 'class', 'style', 'slot', 'part', 'is', 'src', 'format', 'peaks-src', 'input', 'port', 'target', 'session', 'sound-font', 'device-id',\n]);\n\nconst TOKEN_NAME = /^--wm-[a-z0-9-]+$/;\n/** Functions that load something: a token's value is a colour, a length or a number, never a resource. */\nconst LOADS = /(?:url|src|image-set|image|cross-fade|element|paint)\\s*\\(/i;\nconst MAX_VALUE = 256;\n\ntype Registry = Pick<CustomElementRegistry, 'get'>;\nconst registryOf = (registry?: Registry): Registry | undefined => registry ?? (globalThis as {customElements?: Registry}).customElements;\n\n/**\n * The attributes a setting may write on a component's Element: those the\n * Element observes, less the graph's, the box arguments' and the manifest's\n * locked ones. Empty until the Element is defined.\n */\nexport function settableAttributes(manifest: ComponentManifest, registry?: Registry): readonly string[] {\n const observed = (registryOf(registry)?.get(manifest.tag) as {observedAttributes?: readonly string[]} | undefined)?.observedAttributes ?? [];\n const taken = new Set([...GRAPH_ATTRIBUTES, ...(manifest.locked ?? []), ...manifest.parameters.flatMap(parameter => parameter.attribute ? [parameter.attribute] : [])]);\n return observed.filter(name => !taken.has(name));\n}\n\n/** True for a custom property and value a setting may write. */\nexport function isStyleSetting(name: string, value: unknown): value is string {\n return TOKEN_NAME.test(name) && typeof value === 'string' && value.trim() !== '' && value.length <= MAX_VALUE && !/[;{}<>]/.test(value) && !LOADS.test(value);\n}\n\nconst entries = (value: unknown): [string, unknown][] =>\n value !== null && typeof value === 'object' && !Array.isArray(value) ? Object.entries(value as Record<string, unknown>) : [];\n\n/**\n * Whose style something shows (DEC-090): its `own`, or, with `inherit`, that\n * of what holds it — a box its component's theme, a component its app's.\n * The choice is the author's, box by box and component by component; the\n * style it sets aside is kept, so choosing `own` again brings it back.\n */\nexport type StyleSource = 'own' | 'inherit';\n\n/** The style source a box's `config` chooses under `styling`; `own` unless it says `inherit`. */\nexport function styleSource(config: Readonly<Record<string, unknown>>): StyleSource {\n return config.styling === 'inherit' ? 'inherit' : 'own';\n}\n\n/** `config` with its style source chosen; `own` is the absence of the key. */\nexport function withStyleSource(config: ProjectJsonObject, source: StyleSource): ProjectJsonObject {\n const {styling: _previous, ...rest} = config;\n return source === 'inherit' ? {...rest, styling: 'inherit'} : rest;\n}\n\n/**\n * True for an attribute that gives an Element one colour of its own: `color`,\n * or a name ending in `-color` such as `note-color` or `wave-color`, as the\n * packages' Elements name them. It is the attribute spelling of a style, so\n * it is set aside with the style of a box that inherits (DEC-094). An\n * attribute that chooses a kind of colouring (`scheme`, `color-map`,\n * `color-mode`, a meter's `theme`) is what the Element does, and stays.\n */\nexport function isColorAttribute(name: string): boolean {\n return name === 'color' || name.endsWith('-color');\n}\n\n/**\n * The settings in `config` that may be applied to the component's Element;\n * anything else in `attributes` or `style` is left out without an error, so\n * a project written for a later Element still loads. A box that inherits its\n * style (DEC-090) has none of its own applied, nor a colour an attribute\n * gives it ({@link isColorAttribute}); its other attributes stay.\n */\nexport function componentSettings(manifest: ComponentManifest, config: Readonly<Record<string, unknown>>, registry?: Registry): ComponentSettings {\n const settable = new Set(settableAttributes(manifest, registry));\n const own = styleSource(config) === 'own';\n const attributes: Record<string, string> = {};\n for (const [name, value] of entries(config.attributes)) {\n if (settable.has(name) && typeof value === 'string' && value.length <= MAX_VALUE && (own || !isColorAttribute(name))) attributes[name] = value;\n }\n const style: Record<string, string> = {};\n if (own) for (const [name, value] of entries(config.style)) if (isStyleSetting(name, value)) style[name] = value.trim();\n return {attributes, style};\n}\n\n/**\n * `config` with one setting written, or removed when `value` is undefined.\n * An empty `attributes` or `style` is dropped, so a component without\n * settings has the config it had before it was given any.\n */\nexport function withComponentSetting(config: ProjectJsonObject, kind: ComponentSettingKind, name: string, value: string | undefined): ProjectJsonObject {\n const group = Object.fromEntries(entries(config[kind]).filter(([key, item]) => key !== name && typeof item === 'string')) as Record<string, string>;\n if (value !== undefined) group[name] = value;\n const {[kind]: _previous, ...rest} = config;\n return Object.keys(group).length ? {...rest, [kind]: group} : rest;\n}\n","// The saved form of an edited score (DEC-087): the Score as its own JSON,\n// gzip-compressed and written as base64 text into the `document` key of the\n// config of the box that plays it. A project stays one JSON document, so an\n// edited score goes wherever the project goes — a file, a copy, an exported\n// module or page — and needs no storage of its own.\n//\n// The Score's JSON is far larger than a project may hold as structure\n// (Arabesque No. 1 is some 400 kB and 40 000 values), and note IDs are made\n// on every load, so neither the plain JSON nor a list of edits against the\n// asset can be kept. Compressed it is about a tenth of that, in strings short\n// enough for the project schema.\n//\n// A project file may come from anyone: the text is bounded before it is\n// decoded, the inflated size while it is inflated, and the result is read by\n// `scoreFromJSON`, which validates it.\n//\n// Pure apart from the platform's compression streams; no DOM, no audio.\n\nimport type {ProjectJsonObject} from '@webmusic/kernel/module';\nimport {scoreFromJSON, type Score} from '@webmusic/score';\n\n/** The `format` of a saved score. */\nexport const SAVED_SCORE_FORMAT = 'webmusic.score+json';\n/** The `encoding` of a saved score. */\nexport const SAVED_SCORE_ENCODING = 'gzip+base64';\n\n/** Strings of a saved score, each short enough for the project schema. */\nconst CHUNK = 32768;\n/** Base64 characters a saved score may hold: about a dozen times Arabesque No. 1, and half of what a project may. */\nconst MAX_ENCODED = 1_000_000;\n/** Bytes of JSON a saved score may inflate to. */\nconst MAX_INFLATED = 24 * 1024 * 1024;\n\ntype Streams = {CompressionStream?: typeof CompressionStream; DecompressionStream?: typeof DecompressionStream};\nconst streams = (): Streams => globalThis as Streams;\n\n/** True where the platform can compress and inflate, which saving and restoring a score need. */\nexport function canSaveScores(): boolean {\n return typeof streams().CompressionStream === 'function' && typeof streams().DecompressionStream === 'function';\n}\n\nasync function through(bytes: Uint8Array, stream: {readonly readable: ReadableStream<Uint8Array>; readonly writable: WritableStream<Uint8Array>}, limit: number): Promise<Uint8Array> {\n const writer = stream.writable.getWriter();\n // A failed write is reported by the read that follows it.\n void writer.write(bytes).then(() => writer.close()).catch(() => {});\n const reader = stream.readable.getReader();\n const parts: Uint8Array[] = [];\n let size = 0;\n for (;;) {\n const {done, value} = await reader.read();\n if (done) break;\n size += value.length;\n if (size > limit) {\n void reader.cancel().catch(() => {});\n throw new RangeError('A saved score exceeds its size limit.');\n }\n parts.push(value);\n }\n const out = new Uint8Array(size);\n let at = 0;\n for (const part of parts) { out.set(part, at); at += part.length; }\n return out;\n}\n\nfunction toBase64(bytes: Uint8Array): string {\n let binary = '';\n for (let at = 0; at < bytes.length; at += 0x8000) binary += String.fromCharCode(...bytes.subarray(at, at + 0x8000));\n return btoa(binary);\n}\n\nfunction fromBase64(text: string): Uint8Array {\n const binary = atob(text);\n const bytes = new Uint8Array(binary.length);\n for (let at = 0; at < binary.length; at += 1) bytes[at] = binary.charCodeAt(at);\n return bytes;\n}\n\n/**\n * `score` as a box's config holds it, or undefined when it cannot be saved:\n * the platform has no compression streams, or the result is too large for a\n * project.\n */\nexport async function encodeScore(score: Score): Promise<ProjectJsonObject | undefined> {\n const Compression = streams().CompressionStream;\n if (!Compression || !canSaveScores()) return undefined;\n const json = new TextEncoder().encode(JSON.stringify(score.toJSON()));\n if (json.length > MAX_INFLATED) return undefined;\n const text = toBase64(await through(json, new Compression('gzip') as never, MAX_ENCODED));\n if (text.length > MAX_ENCODED) return undefined;\n const data: string[] = [];\n for (let at = 0; at < text.length; at += CHUNK) data.push(text.slice(at, at + CHUNK));\n return Object.freeze({format: SAVED_SCORE_FORMAT, encoding: SAVED_SCORE_ENCODING, data: Object.freeze(data)});\n}\n\n/**\n * The Score a box's config holds under `document`. Rejects when the value is\n * not a saved score, is too large, does not inflate, or is not a valid Score.\n */\nexport async function decodeScore(value: unknown): Promise<Score> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) throw new TypeError('A saved score must be an object.');\n const {format, encoding, data} = value as {format?: unknown; encoding?: unknown; data?: unknown};\n if (format !== SAVED_SCORE_FORMAT) throw new TypeError(`A saved score must be in the format ${SAVED_SCORE_FORMAT}.`);\n if (encoding !== SAVED_SCORE_ENCODING) throw new TypeError(`A saved score must be encoded as ${SAVED_SCORE_ENCODING}.`);\n if (!Array.isArray(data) || !data.length || data.some(part => typeof part !== 'string')) throw new TypeError('A saved score must hold its data as strings.');\n let length = 0;\n for (const part of data as string[]) if ((length += part.length) > MAX_ENCODED) throw new RangeError('A saved score exceeds its size limit.');\n const Decompression = streams().DecompressionStream;\n if (!Decompression) throw new Error('This browser cannot inflate a saved score.');\n let packed: Uint8Array;\n try { packed = fromBase64((data as string[]).join('')); } catch { throw new TypeError('A saved score must be base64 text.'); }\n // The size limit is reported as it is; any other failure is data that is not gzip.\n const json = await through(packed, new Decompression('gzip') as never, MAX_INFLATED).catch((error: unknown) => {\n if (error instanceof RangeError) throw error;\n return undefined;\n });\n if (!json) throw new TypeError('A saved score does not inflate.');\n return scoreFromJSON(JSON.parse(new TextDecoder().decode(json)) as never);\n}\n","// The style of a whole component (DEC-088): custom properties kept in its\n// project's `layout.style` and written on the component's own root, where\n// every box inside inherits them. Every presenter and Element resolves its\n// values through `--wm-<part>-<role>` to a shared `--wm-<role>` (see the\n// visual design), so a handful of shared roles restyles a whole component,\n// and a part's own token is the exception a box or a theme may add.\n//\n// Three places set a token, the nearest winning as CSS has it: a box's own\n// settings (DEC-085), the component's theme, and whatever holds the\n// component — a page or an app. A theme is written at the component's host\n// from inside, the lowest place there is, so a rule the page writes for the\n// element wins over it.\n//\n// A project file may come from anyone: a theme takes only what a setting\n// takes — a name under `--wm-` and a value that loads nothing.\n//\n// Pure: strings and plain records; `applyComponentStyle` writes the given element.\n\nimport {parseModuleProject, type ModuleProject} from '@webmusic/kernel/module';\nimport {isStyleSetting, styleSource} from './settings';\n\n// The shared roles are the UI Kit's own list (DEC-094): this entry passes\n// them on, so a host that mounts components need not import the kit for them.\nexport {THEME_TOKENS, themeToken, type ThemeToken, type ThemeTokenKind} from '@webmusic/ui';\n\nconst entries = (value: unknown): [string, unknown][] =>\n value !== null && typeof value === 'object' && !Array.isArray(value) ? Object.entries(value as Record<string, unknown>) : [];\n\n/** The custom properties in `style` that may be written: `--wm-` names with values that load nothing. */\nexport function styleSettings(style: unknown): Readonly<Record<string, string>> {\n const out: Record<string, string> = {};\n for (const [name, value] of entries(style)) if (isStyleSetting(name, value)) out[name] = value.trim();\n return out;\n}\n\n/** The style a box's `config` gives it: its `style` as it may be written, or nothing while the box inherits (DEC-090). */\nexport function ownStyle(config: Readonly<Record<string, unknown>>): Readonly<Record<string, string>> {\n return styleSource(config) === 'inherit' ? {} : styleSettings(config.style);\n}\n\n/** A component's theme: the entries of its project's `layout.style` that may be applied. */\nexport function componentTheme(project: Pick<ModuleProject, 'layout'>): Readonly<Record<string, string>> {\n return styleSettings(project.layout.style);\n}\n\n/** `project` with one theme token written, or removed when `value` is undefined; an empty theme is dropped. */\nexport function withComponentTheme(project: ModuleProject, name: string, value: string | undefined): ModuleProject {\n if (value !== undefined && !isStyleSetting(name, value)) throw new TypeError(`${name} cannot be themed with that value: a theme sets --wm- tokens to values that load nothing.`);\n const style = Object.fromEntries(Object.entries(project.layout.style ?? {}).filter(([key]) => key !== name));\n if (value !== undefined) style[name] = value.trim();\n const {style: _previous, ...layout} = project.layout;\n return parseModuleProject({...project, layout: Object.keys(style).length ? {...layout, style} : layout});\n}\n\n/** `style` as CSS declarations; empty for no entries. */\nexport function styleDeclarations(style: unknown): string {\n return Object.entries(styleSettings(style)).map(([name, value]) => `${name}: ${value};`).join(' ');\n}\n\nconst written = new WeakMap<HTMLElement, Set<string>>();\n\n/**\n * Write `style` on `element` as custom properties and take back those an\n * earlier call wrote that it no longer holds. Used for a box's own style\n * and for a theme on a root the host owns.\n */\nexport function applyComponentStyle(element: HTMLElement, style: unknown): void {\n const next = styleSettings(style);\n const before = written.get(element) ?? new Set<string>();\n for (const name of before) if (!(name in next)) element.style.removeProperty(name);\n for (const [name, value] of Object.entries(next)) element.style.setProperty(name, value);\n written.set(element, new Set(Object.keys(next)));\n}\n","// Components placed in a graph (DEC-081): the runtime side of each official\n// component's box, with no DOM. One project plugin per manifest makes the\n// ports the manifest declares and hands the slot what the Element borrows.\n// Studio and exported components use the same plugins.\n//\n// A slot outlives the runtime modules behind it. A rebuild creates the new\n// module before it disposes the old one, and a failed rebuild disposes the new\n// one and keeps the old, so a slot keeps every provided value in creation\n// order and shows the newest one still provided.\n//\n// A player or desk (DEC-084) plays inside the graph: its box makes an output\n// bus and lends the Element a module context with the graph's audio\n// environment and Session whose default destination is that bus, so the\n// player's engine joins the graph's Session. A desk's inputs are gain nodes,\n// each offered to the Element as one channel to admit.\n//\n// A score a box plays can be edited from a view cabled to it (DEC-086): the\n// first view that asks turns the box's score into a document, which the box\n// then plays and lends to every editing view its `source` cords reach. The\n// surfaces own each document for as long as its box is in the graph, so an\n// edit outlives a rebuild of the graph.\n//\n// An edited score is saved with its box (DEC-087): the box's exported config\n// holds it under `document`, compressed, and a box made from a config that\n// holds one starts with that document. The asset is never written.\n//\n// Ownership: each plugin instance owns its analyser, note port, buses and\n// channel ports, and releases what it provided on dispose. Elements borrow;\n// they never dispose a value. A loaded asset is data, not a resource.\n\nimport {AudioClip} from '@webmusic/audio';\nimport {\n AudioOutputPort, NoteInputPort, NoteOutputPort, SourceRelay, createConnectionLease, routeModuleOutput, sourceOrigin,\n type ConnectionLease, type ModuleContext, type ModuleHandle, type NoteEvent, type ProjectConnector,\n ProjectModuleUnavailableError,\n type ProjectFactoryRequest, type ProjectJson, type ProjectJsonObject, type ProjectModuleInstance, type ProjectPluginFactory, type ProjectPortDescriptor,\n} from '@webmusic/kernel/module';\nimport {Score} from '@webmusic/score';\nimport {createScoreEditor, type ScoreEditor} from '@webmusic/score/view/headless';\nimport {decodeScore, encodeScore} from './document';\nimport {OFFICIAL_COMPONENTS, manifestFor, type ComponentManifest} from './manifest';\n\nconst PLUGIN_VERSION = '1.0.0';\n\n/** One provided value, newest wins while it is provided. */\nclass Provided<T> {\n readonly #values: {value: T}[] = [];\n readonly #listeners = new Set<() => void>();\n get current(): T | undefined { return this.#values[this.#values.length - 1]?.value; }\n provide(value: T): () => void {\n const entry = {value};\n this.#values.push(entry);\n this.#notify();\n return () => {\n const index = this.#values.indexOf(entry);\n if (index < 0) return;\n this.#values.splice(index, 1);\n this.#notify();\n };\n }\n subscribe(listener: () => void): () => void {\n this.#listeners.add(listener);\n return () => { this.#listeners.delete(listener); };\n }\n #notify(): void {\n for (const listener of [...this.#listeners]) {\n try { listener(); } catch (error) { queueMicrotask(() => { throw error; }); }\n }\n }\n}\n\n/** One desk input offered to the Element: admit `port` as the channel of `module`. */\nexport interface SurfaceChannel {\n readonly module: ModuleHandle;\n readonly port: AudioOutputPort;\n}\n\n/** One playlist entry the box loaded: an asset role, the file's name and its clip. */\nexport interface SurfaceEntry {\n readonly id: string;\n readonly label: string;\n readonly clip: AudioClip;\n}\n\n/** What one component's Element borrows, by module ID: one value per binding. */\nexport class SurfaceSlot {\n /** The analyser an audio input hands the Element's `analyser`. */\n readonly analyser = new Provided<AnalyserNode>();\n /** The module a source input hands the Element's `inputModule`, through its `source` cord. */\n readonly source = new Provided<ModuleHandle>();\n /** The note output of the newest module; the Element's `module` plays into it. */\n readonly notes = new Provided<(event: NoteEvent) => void>();\n /** The module context lent to a player or desk: the graph's Session, with this box's output as its destination. */\n readonly context = new Provided<ModuleContext>();\n /** A desk's inputs, which the Element admits as channels. */\n readonly channels = new Provided<readonly SurfaceChannel[]>();\n /** A module whose `notes` output repeats the notes cabled to this box; the Element's `inputModule` listens to it. */\n readonly noteSource = new Provided<ModuleHandle>();\n /** The asset the box loaded for the Element: a Score, an AudioClip, or a playlist's entries. */\n readonly asset = new Provided<Score | AudioClip | readonly SurfaceEntry[]>();\n /** The Element's own module, provided by the host; a source cord from this box carries it. */\n readonly element = new Provided<ModuleHandle>();\n /** An insert's ends: the graph's AudioContext, the node the box's input feeds and the node its output plays from. */\n readonly insert = new Provided<{readonly context: BaseAudioContext; readonly input: AudioNode; readonly output: AudioNode}>();\n /** The Element itself, provided by the host, for a companion that links to its player. */\n readonly elementOwner = new Provided<object>();\n /** The Element of the box a `source` cord comes from, for a `player` binding. */\n readonly sourceOwner = new Provided<object>();\n /** True when a source cord from this box carries the Element's module rather than the box's. */\n forwardsElement = false;\n /** The Score this box plays, when it plays one: what its document starts from. */\n readonly score = new Provided<Score>();\n /** The document this box's score became once a view asked to edit it (DEC-086): the box plays it. */\n readonly document = new Provided<ScoreEditor>();\n /**\n * For a box with a source input: lends the document of the box its cord\n * comes from, making it on the first call. A view calls it when it edits;\n * it returns nothing while that box has no score.\n */\n readonly lender = new Provided<() => ScoreEditor | undefined>();\n}\n\n/** A box's document and what the box saves of it. */\ninterface Kept {\n readonly editor: ScoreEditor;\n /** The content the document began with. */\n readonly initial: string;\n /** The saved score the document began as; none when it began as the box's asset. */\n readonly restored?: ProjectJson;\n /** The content last heard of. */\n seen: string;\n /** The content last encoded and its saved form, which is none when it cannot be saved. */\n saved?: {readonly contentId: string; readonly value: ProjectJsonObject | undefined};\n encoding: boolean;\n release: () => void;\n}\n\n/**\n * What a box that plays a score holds: `original` its asset as loaded,\n * `edited` a score that is saved with the box, `unsaved` an edited score\n * that cannot be saved (too large for a project, or no compression here).\n */\nexport type ComponentDocumentState = 'original' | 'edited' | 'unsaved';\n\nexport class ComponentSurfaces {\n readonly #slots = new Map<string, SurfaceSlot>();\n readonly #byModule = new WeakMap<ModuleHandle, SurfaceSlot>();\n readonly #documents = new Map<string, Kept>();\n readonly #alive = new Map<string, number>();\n readonly #pending = new Set<Promise<void>>();\n readonly #listeners = new Set<() => void>();\n\n /**\n * The document of the box `id`: the editor that owns the score it plays\n * (DEC-086). Made from the box's score the first time it is asked for and\n * kept while the box is in the graph, whatever is rebuilt; undefined while\n * the box has no score. `peek` only looks.\n */\n document(id: string, peek = false): ScoreEditor | undefined {\n const known = this.#documents.get(id);\n if (known || peek) return known?.editor;\n const score = this.slot(id).score.current;\n if (!score) return undefined;\n return this.#keep(id, createScoreEditor(score)).editor;\n }\n\n /**\n * What the box `id` holds of the score it plays (DEC-087); undefined when\n * it plays none.\n */\n documentState(id: string): ComponentDocumentState | undefined {\n const kept = this.#documents.get(id);\n if (!kept) return this.#slots.get(id)?.score.current ? 'original' : undefined;\n const contentId = kept.editor.getSnapshot().contentId;\n if (contentId === kept.initial) return kept.restored === undefined ? 'original' : 'edited';\n // An encoding still under way is taken as one that will be saved.\n return kept.saved?.contentId === contentId && kept.saved?.value === undefined ? 'unsaved' : 'edited';\n }\n\n /**\n * `config` as the box `id` is saved (DEC-087): with its edited score under\n * `document`, and without one once the document is the asset again. A box\n * nobody edited keeps the config it has. The newest edit is encoded off\n * the call, so it is in the config once `settled` resolves; subscribers\n * are told when it is.\n */\n withDocument(id: string, config: ProjectJsonObject): ProjectJsonObject {\n const kept = this.#documents.get(id);\n if (!kept) return config;\n const {document: _previous, ...rest} = config;\n const value = kept.editor.getSnapshot().contentId === kept.initial ? kept.restored : kept.saved?.value ?? kept.restored;\n return value === undefined ? rest : {...rest, document: value};\n }\n\n /**\n * Start the box `id` from the score its `config` saved (DEC-087). A\n * document already edited here stays: it is newer than any config. Rejects\n * with `ProjectModuleUnavailableError` when the saved score cannot be read,\n * so the box stays unresolved with its config, and nothing is lost.\n */\n async revive(id: string, config: ProjectJsonObject, signal?: AbortSignal): Promise<void> {\n const saved = config.document;\n if (saved === undefined || this.#edited(id)) return;\n let editor: ScoreEditor;\n try { editor = createScoreEditor(await decodeScore(saved)); } catch (error) {\n throw new ProjectModuleUnavailableError(`The saved score of ${id} cannot be read: ${error instanceof Error ? error.message : String(error)}`, {cause: error});\n }\n signal?.throwIfAborted();\n if (this.#edited(id)) return;\n // An untouched document made from the asset gives way; its views borrow the restored one.\n const untouched = this.#documents.get(id);\n this.#keep(id, editor, saved);\n untouched?.release();\n this.#notify();\n }\n\n /**\n * Give the box `id` its asset back (DEC-087): its edited document is let\n * go and a new one, made from the score the box loaded, takes its place, so\n * the box plays the asset at once and the views that edit borrow it. The\n * box then saves no score. Nothing happens while the box has no document.\n */\n revert(id: string): void {\n const kept = this.#documents.get(id);\n if (!kept) return;\n const score = this.#slots.get(id)?.score.current;\n if (!score) { this.forget(id); return; }\n // The new document is provided before the old one is released: the box is never without one in between.\n this.#keep(id, createScoreEditor(score));\n kept.release();\n this.#notify();\n }\n\n /**\n * Let go of the document of the box `id`, or of every box, and make none.\n * A host calls it before it shows another project, whose boxes may have\n * the same IDs; `revert` is the one for a box that stays.\n */\n forget(id?: string): void {\n const ids = id === undefined ? [...this.#documents.keys()] : this.#documents.has(id) ? [id] : [];\n for (const key of ids) {\n const kept = this.#documents.get(key)!;\n this.#documents.delete(key);\n kept.release();\n }\n if (ids.length) this.#notify();\n }\n\n /**\n * Count a module of the box `id` as in a graph; call the result when it is\n * disposed. A rebuild makes the new module before it disposes the old one,\n * so the document goes only when the box itself does, and a new box that\n * is given the same ID does not inherit it.\n */\n enter(id: string): () => void {\n this.#alive.set(id, (this.#alive.get(id) ?? 0) + 1);\n let left = false;\n return () => {\n if (left) return;\n left = true;\n const count = (this.#alive.get(id) ?? 1) - 1;\n if (count > 0) { this.#alive.set(id, count); return; }\n this.#alive.delete(id);\n this.forget(id);\n };\n }\n\n /** Told when what a box saves of its score changed: an edit, its encoding, a revert. */\n subscribe(listener: () => void): () => void {\n this.#listeners.add(listener);\n return () => { this.#listeners.delete(listener); };\n }\n\n /** Resolves once every edit made so far is encoded, so `withDocument` holds it. */\n async settled(): Promise<void> {\n while (this.#pending.size) await Promise.all([...this.#pending]);\n }\n\n #edited(id: string): boolean {\n const kept = this.#documents.get(id);\n return !!kept && (kept.restored !== undefined || kept.editor.getSnapshot().contentId !== kept.initial);\n }\n\n #keep(id: string, editor: ScoreEditor, restored?: ProjectJson): Kept {\n const initial = editor.getSnapshot().contentId;\n const kept: Kept = {editor, initial, ...(restored !== undefined ? {restored} : {}), seen: initial, encoding: false, release: () => {}};\n this.#documents.set(id, kept);\n const unsubscribe = editor.subscribe(() => this.#encode(id, kept));\n // Provided for as long as the document is kept: the box plays it.\n const unprovide = this.slot(id).document.provide(editor);\n kept.release = () => { unsubscribe(); unprovide(); };\n return kept;\n }\n\n /** Encode the document's content when it changed; one at a time, the newest last. */\n #encode(id: string, kept: Kept): void {\n if (this.#documents.get(id) !== kept) return;\n const {contentId, content, status} = kept.editor.getSnapshot();\n if (status === 'disposed') return;\n if (contentId !== kept.seen) { kept.seen = contentId; this.#notify(); }\n if (contentId === kept.initial || kept.encoding || kept.saved?.contentId === contentId) return;\n kept.encoding = true;\n const work: Promise<void> = encodeScore(content).catch(() => undefined).then(value => {\n kept.encoding = false;\n this.#pending.delete(work);\n kept.saved = {contentId, value};\n if (this.#documents.get(id) !== kept) return;\n this.#notify();\n this.#encode(id, kept);\n });\n this.#pending.add(work);\n }\n\n #notify(): void {\n for (const listener of [...this.#listeners]) {\n try { listener(); } catch (error) { queueMicrotask(() => { throw error; }); }\n }\n }\n\n slot(id: string): SurfaceSlot {\n let slot = this.#slots.get(id);\n if (!slot) {\n const made = slot = new SurfaceSlot();\n this.#slots.set(id, made);\n // Which box an Element's module belongs to, so a cord that crossed component edges still finds that box (DEC-089).\n made.element.subscribe(() => { const module = made.element.current; if (module) this.#byModule.set(module, made); });\n }\n return slot;\n }\n\n /** The box whose Element's module is `module`'s origin, through any relays. */\n #boxOf(module: ModuleHandle | undefined): SurfaceSlot | undefined {\n const origin = sourceOrigin(module);\n return origin ? this.#byModule.get(origin) : undefined;\n }\n\n /** One plugin per official component's manifest. */\n plugins(): readonly ProjectPluginFactory[] {\n return Object.freeze(OFFICIAL_COMPONENTS.map(manifest => ({\n id: manifest.plugin, version: PLUGIN_VERSION, create: (request: ProjectFactoryRequest) => this.#create(manifest, request),\n })));\n }\n\n /**\n * The runtime connector for `source` cords: a source input follows the\n * upstream module. From a player's box it follows the player's own module,\n * which the host provides once the Element has one.\n */\n readonly connect: ProjectConnector = ({connection, from}) => {\n if (connection.kind !== 'source') return undefined;\n const reached = this.slot(connection.to.moduleId);\n const target = reached.source;\n const sourceId = connection.from.moduleId;\n const upstream = this.#slots.get(sourceId);\n // The cord also offers the source's document to a view that edits; offered again when the source's score\n // arrives and when its document is replaced or let go, so the view asks again. The new offer is made\n // before the old one is withdrawn: a view is never without one in between.\n const origin = this.slot(sourceId);\n let offered: (() => void) | undefined;\n const offer = () => { const previous = offered; offered = reached.lender.provide(() => this.document(sourceId)); previous?.(); };\n offer();\n const unoffers = [origin.score.subscribe(offer), origin.document.subscribe(offer)];\n const withdraw = () => { for (const unoffer of unoffers) unoffer(); offered?.(); offered = undefined; };\n if (!upstream?.forwardsElement) {\n const release = target.provide(from.module);\n const relay = from.module instanceof SourceRelay ? from.module : undefined;\n if (!relay) return createConnectionLease(() => { withdraw(); release(); });\n // Across component edges the cord carries a relay: its origin's box lends the Element a companion links to.\n let owned: (() => void) | undefined;\n const own = () => {\n owned?.();\n const element = this.#boxOf(relay)?.elementOwner.current;\n owned = element ? reached.sourceOwner.provide(element) : undefined;\n };\n own();\n const stop = relay.subscribe(own);\n return createConnectionLease(() => { withdraw(); stop(); owned?.(); owned = undefined; release(); });\n }\n // One provision of the Element's module and one of the Element, each replaced when it changes.\n const follow = <T>(source: Provided<T>, into: Provided<T>): (() => void) => {\n let provided: (() => void) | undefined;\n const apply = () => {\n provided?.();\n const value = source.current;\n provided = value !== undefined ? into.provide(value) : undefined;\n };\n apply();\n const unsubscribe = source.subscribe(apply);\n return () => { unsubscribe(); provided?.(); provided = undefined; };\n };\n const stops = [follow(upstream.element, target), follow(upstream.elementOwner, reached.sourceOwner)];\n return createConnectionLease(() => { withdraw(); for (const stop of stops) stop(); });\n };\n\n /** Synchronous unless the box has an asset to load; the asset loads first, so a failed load leaves nothing behind. */\n #create(manifest: ComponentManifest, request: ProjectFactoryRequest): ProjectModuleInstance | Promise<ProjectModuleInstance> {\n manifest = manifestFor(manifest, request.record.config);\n const wanted = manifest.asset;\n if (wanted?.kind === 'entries') {\n // Every role with the prefix, in number order: `entry2` before `entry10`.\n const roles = Object.keys(request.record.assets ?? {}).filter(role => role.startsWith(wanted.role))\n .sort((a, b) => a.localeCompare(b, undefined, {numeric: true}));\n if (!roles.length) return this.#build(manifest, request, undefined);\n return Promise.all(roles.map(role => request.resolveAsset(role))).then(clips => {\n request.signal.throwIfAborted();\n const entries = clips.map((clip, index) => {\n const role = roles[index]!;\n if (!(clip instanceof AudioClip)) throw new TypeError(`The ${manifest.name} asset ${role} must resolve to an AudioClip.`);\n let label = (request.asset(role)?.uri ?? role).split(/[?#]/)[0]!.split('/').pop() || role;\n try { label = decodeURIComponent(label); } catch { /* Keep the raw name. */ }\n return Object.freeze({id: role, label, clip});\n });\n return this.#build(manifest, request, Object.freeze(entries));\n });\n }\n if (!wanted || !request.asset(wanted.role)) return this.#build(manifest, request, undefined);\n return request.resolveAsset(wanted.role).then(async asset => {\n request.signal.throwIfAborted();\n const loaded = wanted.kind === 'score' ? asset instanceof Score && asset : asset instanceof AudioClip && asset;\n if (!loaded) throw new TypeError(`The ${manifest.name} asset must resolve to ${wanted.kind === 'score' ? 'a Score' : 'an AudioClip'}.`);\n if (!(loaded instanceof Score)) return this.#build(manifest, request, loaded);\n // A box that plays a score starts from the one saved with it (DEC-087).\n const leave = this.enter(request.record.id);\n try {\n await this.revive(request.record.id, request.record.config, request.signal);\n return this.#build(manifest, request, loaded, leave);\n } catch (error) { leave(); throw error; }\n });\n }\n\n #build(manifest: ComponentManifest, {record, context}: ProjectFactoryRequest, asset: Score | AudioClip | readonly SurfaceEntry[] | undefined, leave?: () => void): ProjectModuleInstance {\n const slot = this.slot(record.id);\n const ports: ProjectPortDescriptor[] = [];\n const inputs = new Map<string, AudioNode>();\n const outputs = new Map<string, AudioOutputPort>();\n const notePorts: NoteOutputPort[] = [];\n const noteInputs: NoteInputPort[] = [];\n const channels: SurfaceChannel[] = [];\n const releases: (() => void)[] = [];\n const routes: (() => ConnectionLease)[] = [];\n let insertEnds: {context: BaseAudioContext; input: GainNode; output: GainNode} | undefined;\n let carried: SourceRelay | undefined;\n for (const port of manifest.ports) {\n if (port.bind === 'context') {\n const bus = context.audio.prepare().createGain();\n const output = new AudioOutputPort(bus, {id: port.id});\n outputs.set(port.id, output);\n const lent = context.derive({id: `${record.id}:component`, destination: () => bus, admit: null, target: null});\n routes.push(() => routeModuleOutput(context, module, output));\n // Released in reverse: the Element leaves the context before its bus closes.\n releases.push(() => { output.dispose(); bus.disconnect(); }, slot.context.provide(lent));\n ports.push({id: port.id, kind: 'audio', direction: 'output'});\n } else if (port.bind === 'admit') {\n const input = context.audio.prepare().createGain();\n inputs.set(port.id, input);\n const output = new AudioOutputPort(input, {id: port.id});\n channels.push(Object.freeze({module: Object.freeze({id: port.channel}), port: output}));\n releases.push(() => { output.dispose(); input.disconnect(); });\n ports.push({id: port.id, kind: 'audio', direction: 'input'});\n } else if (port.family === 'source' && port.direction === 'output') {\n slot.forwardsElement = true;\n // A cord from this box carries the Element's module, through a relay that follows it (DEC-089).\n if (!carried) {\n const relay = new SourceRelay(record.id);\n let followed: ConnectionLease | undefined;\n const follow = () => {\n const module = slot.element.current;\n const previous = followed;\n followed = module ? relay.follow(module) : undefined;\n previous?.release();\n };\n follow();\n const stop = slot.element.subscribe(follow);\n releases.push(() => { stop(); followed?.release(); relay.dispose(); });\n carried = relay;\n }\n ports.push({id: port.id, kind: 'source', direction: 'output'});\n } else if (port.bind === 'analyser') {\n const analyser = context.audio.prepare().createAnalyser();\n analyser.fftSize = port.fftSize;\n inputs.set(port.id, analyser);\n const release = slot.analyser.provide(analyser);\n releases.push(() => { release(); analyser.disconnect(); });\n ports.push({id: port.id, kind: 'audio', direction: 'input'});\n } else if (port.family === 'note' && port.direction === 'input') {\n // The cords play into the box; the box repeats them on an output the Element listens to.\n const relay = new NoteOutputPort({id: 'notes'});\n const input = new NoteInputPort({accept: (event: NoteEvent) => {\n if (relay.disposed) return;\n if (event.gate !== 'on' && !relay.held.some(held => held.occurrenceId === event.occurrenceId)) return;\n relay.emit(event);\n }}, {id: port.id, multiplicity: 'sum'});\n noteInputs.push(input);\n const release = slot.noteSource.provide(Object.freeze({id: `${record.id}:notes`, ports: () => [relay]}));\n releases.push(() => { release(); input.dispose(); relay.dispose(); });\n ports.push({id: port.id, kind: 'note', direction: 'input'});\n } else if (port.bind === 'inputModule' || port.bind === 'moduleTarget' || port.bind === 'player') {\n ports.push({id: port.id, kind: 'source', direction: 'input'});\n } else if (port.bind === 'insert') {\n // Both ends are made once, by the first insert port; the Element's chain goes between them.\n if (!insertEnds) {\n const audio = context.audio.prepare();\n const from = audio.createGain(), to = audio.createGain();\n insertEnds = {context: audio, input: from, output: to};\n }\n if (port.direction === 'input') inputs.set(port.id, insertEnds.input);\n else {\n const output = new AudioOutputPort(insertEnds.output, {id: port.id});\n outputs.set(port.id, output);\n routes.push(() => routeModuleOutput(context, module, output));\n releases.push(() => output.dispose());\n }\n ports.push({id: port.id, kind: 'audio', direction: port.direction});\n } else {\n const notes = new NoteOutputPort({id: port.id});\n // A rebuild can drop the port while a key is held: the old port cancels it,\n // and the new one must not see a release it never started.\n const forward = (event: NoteEvent) => {\n if (notes.disposed) return;\n if (event.gate !== 'on' && !notes.held.some(held => held.occurrenceId === event.occurrenceId)) return;\n notes.emit(event);\n };\n const release = slot.notes.provide(forward);\n notePorts.push(notes);\n releases.push(() => { release(); notes.dispose(); });\n ports.push({id: port.id, kind: 'note', direction: 'output'});\n }\n }\n const module: ModuleHandle = {id: record.id,\n ...(notePorts.length || noteInputs.length ? {ports: () => [...notePorts, ...noteInputs]} : {}),\n ...(outputs.size ? {getPort: (name: string) => outputs.get(name)} : {})};\n const registration = notePorts.length || noteInputs.length ? context.registry.register(module) : undefined;\n // The box's output plays to the graph like any module's until a cord replaces it.\n const leases = routes.map(route => route());\n if (insertEnds) {\n const ends = insertEnds;\n releases.push(() => { ends.input.disconnect(); ends.output.disconnect(); }, slot.insert.provide(Object.freeze(ends)));\n }\n // No output needs the context, but the Element works in the graph's AudioContext.\n if (manifest.scope && !manifest.ports.some(port => port.bind === 'context')) releases.push(slot.context.provide(context.derive({id: `${record.id}:component`, admit: null, target: null})));\n if (channels.length) releases.push(slot.channels.provide(Object.freeze(channels)));\n if (asset !== undefined) releases.push(slot.asset.provide(asset));\n // A player's score is what a view cabled to it may edit.\n if (asset instanceof Score) releases.push(slot.score.provide(asset));\n const carries = carried;\n return {\n module,\n ports,\n ...(inputs.size ? {getInput: (name: string) => inputs.get(name)} : {}),\n ...(carries ? {sourceOutput: () => carries} : {}),\n ...(leave ? {exportConfig: () => this.withDocument(record.id, record.config)} : {}),\n dispose: () => {\n for (const lease of leases) lease.release();\n // A desk's channels and the lent context go first, so the Element lets go of them before they close.\n for (const release of releases.reverse()) release();\n registration?.release();\n leave?.();\n },\n };\n }\n}\n","// The packages' own Components inside the boxes of a graph (DEC-078,\n// DEC-081): one Element per box, made, configured, bound and fitted from its\n// component's manifest. Studio and exported components do it the same way;\n// nothing here branches on which component it is.\n//\n// Ownership: the caller owns the element and the release function returned\n// by a bind call. Analysers, note ports, upstream modules, buffers and the\n// module context lent to a player or desk are borrowed from the runtime; an\n// element never disposes them. The bind call owns the context provider on the\n// box and the channel leases it takes from the Element's module.\n\nimport {clipOfBuffer, type SharedBuffers} from '@webmusic/audio/play/headless';\nimport {defineAudioClipViewElement} from '@webmusic/audio/view/element';\nimport {createAudioClipEditor, renderAudioClipEditor, type AudioClipEditor} from '@webmusic/audio/view/headless';\nimport type {AudioClip} from '@webmusic/audio';\nimport {computeSpectrogram} from '@webmusic/audio/analyze';\nimport {elementFitOf, fitElementHeight, notifyModuleContext, observeElementModule, provideModuleContext} from '@webmusic/kernel/element';\nimport type {AudioOutputPort, ConnectionLease, ModuleHandle, NoteEvent, NoteOutputPort, ProjectJsonObject} from '@webmusic/kernel/module';\nimport {OFFICIAL_COMPONENTS, parameterValue, type ComponentManifest} from './manifest';\nimport {componentSettings, type ComponentSettings} from './settings';\nimport type {SurfaceSlot} from './surfaces';\n\ntype ClipElement = HTMLElement & {editor: AudioClipEditor | undefined; editable: boolean};\n/** A module that takes channels: a Rack, or a desk's module (DEC-084). */\ntype Admitting = ModuleHandle & {admit(module: ModuleHandle, port: AudioOutputPort): ConnectionLease};\ntype Bound = HTMLElement & {analyser?: AnalyserNode; inputModule?: ModuleHandle | null; module?: ModuleHandle; editor?: unknown} & Record<string, unknown>;\n/** An explicit link to no player: a companion bound to it waits, and never plays by itself. */\nconst UNLINKED = Object.freeze({player: undefined});\n// An Element announces a new `module` with either event: a new module, or a new scope that makes one.\n// An Element's `module` is followed through Kernel's observeElementModule (DEC-094), which hears both events an\n// Element announces a new module with and reports only a change of identity.\nconst listen = (element: HTMLElement, listener: () => void): (() => void) => observeElementModule(element, () => listener());\nconst admitting = (module: ModuleHandle | undefined): module is Admitting => typeof (module as Partial<Admitting> | undefined)?.admit === 'function';\n\n/** Register the custom element of every official component; safe to call again. */\nexport function defineComponentElements(): void {\n for (const manifest of OFFICIAL_COMPONENTS) manifest.define();\n}\n\n/** A component's Element, configured from its module's config. */\nexport function createComponentElement(manifest: ComponentManifest, config: ProjectJsonObject, document: Document = globalThis.document): HTMLElement {\n manifest.define();\n const element = document.createElement(manifest.tag);\n for (const [name, value] of Object.entries(manifest.attributes ?? {})) element.setAttribute(name, value);\n configureComponentElement(element, manifest, config);\n const container = manifest.container;\n if (!container) return element;\n // A declaration works inside its owner: the box holds the owner, and the owner holds the declaration.\n container.define();\n const outer = document.createElement(container.tag);\n for (const [name, value] of Object.entries(container.attributes ?? {})) outer.setAttribute(name, value);\n outer.append(element);\n return outer;\n}\n\n/** The Element a manifest describes, inside the one a host placed: itself, or the declaration inside its container. */\nexport function componentTarget(element: HTMLElement, manifest: ComponentManifest): HTMLElement {\n return manifest.container && element.localName === manifest.container.tag\n ? element.querySelector<HTMLElement>(`:scope > ${manifest.tag}`) ?? element : element;\n}\n\n/** The settings last applied to each Element, so a removed one gives its attribute or property back. */\nconst applied = new WeakMap<HTMLElement, ComponentSettings>();\n/** What a fit writes on an Element while its box is resized: a setting for it waits until the fit lets go. */\nconst held = new WeakMap<HTMLElement, {readonly attribute?: string; readonly property?: string}>();\n\n/**\n * Apply a config to a component's Element in place: its settings (DEC-085),\n * each attribute over the manifest's own and each custom property on the\n * Element, then each parameter to its attribute. A setting that is gone gives\n * the attribute back to the manifest, or removes it.\n */\nexport function configureComponentElement(placed: HTMLElement, manifest: ComponentManifest, config: ProjectJsonObject): void {\n const element = componentTarget(placed, manifest);\n const settings = componentSettings(manifest, config, element.ownerDocument.defaultView?.customElements);\n const before = applied.get(element);\n const hold = held.get(element);\n for (const name of Object.keys(before?.attributes ?? {})) {\n if (name in settings.attributes || name === hold?.attribute) continue;\n const own = manifest.attributes?.[name];\n if (own === undefined) element.removeAttribute(name); else element.setAttribute(name, own);\n }\n for (const [name, value] of Object.entries(settings.attributes)) {\n if (name !== hold?.attribute && element.getAttribute(name) !== value) element.setAttribute(name, value);\n }\n for (const name of Object.keys(before?.style ?? {})) {\n if (!(name in settings.style) && name !== hold?.property) element.style.removeProperty(name);\n }\n for (const [name, value] of Object.entries(settings.style)) {\n if (name !== hold?.property && element.style.getPropertyValue(name) !== value) element.style.setProperty(name, value);\n }\n applied.set(element, settings);\n for (const parameter of manifest.parameters) {\n if (!parameter.attribute) continue;\n const value = String(parameterValue(parameter, config));\n if (element.getAttribute(parameter.attribute) !== value) element.setAttribute(parameter.attribute, value);\n }\n if (manifest.configure) {\n const values: Record<string, unknown> = {...config};\n for (const parameter of manifest.parameters) values[parameter.name] = parameterValue(parameter, config);\n manifest.configure(element, values);\n }\n}\n\n/** True when a changed config needs a new binding, not only new attributes: a parameter the host binds, or ports that follow the config. */\nexport function rebindsOnConfig(manifest: ComponentManifest): boolean {\n return !!manifest.portsFor || manifest.parameters.some(parameter => parameter.buffer);\n}\n\nexport interface ComponentBindOptions {\n /** Runs inside a pointer or key gesture on the Element, so the caller can resume audio there. */\n readonly onGesture?: () => void;\n /** The shared buffers a buffer parameter names. */\n readonly buffers?: {readonly store: SharedBuffers; readonly context: BaseAudioContext};\n /** Let a shown buffer be edited and written back. */\n readonly editableBuffers?: boolean;\n readonly onError?: (error: unknown) => void;\n}\n\n/**\n * Bind a component's Element to its slot through the members its manifest\n * names: `analyser`, `inputModule` and the note output of `module`, and a\n * shared buffer for a buffer parameter. A player or desk is lent the graph's\n * module context on its box — the Element's parent, which must be there and\n * should be bound before the Element connects — its desk inputs are admitted\n * through `module`, its own `module` is what a source cord carries, and its\n * asset is assigned to the property the manifest names. Returns the release\n * function; take a player or desk off the page before calling it, so that\n * losing the lent context does not make it start a Session of its own.\n */\nexport function bindComponentElement(element: HTMLElement, manifest: ComponentManifest, slot: SurfaceSlot, config: ProjectJsonObject, options: ComponentBindOptions = {}): () => void {\n // The box holds what the host placed; bindings reach the Element the manifest describes.\n const placed = element;\n element = componentTarget(placed, manifest);\n const view = element as Bound;\n const releases: (() => void)[] = [];\n const report = (error: unknown) => { if (options.onError) options.onError(error); else queueMicrotask(() => { throw error; }); };\n if (manifest.scope || manifest.ports.some(port => port.bind === 'context')) {\n const box = placed.parentElement;\n if (!box) throw new Error(`The ${manifest.name} component must be inside its box before it is bound.`);\n // The Element finds its context through the box, as a player nested in another finds its.\n releases.push(provideModuleContext(box, () => slot.context.current));\n releases.push(slot.context.subscribe(() => notifyModuleContext(box)));\n }\n if (manifest.ports.some(port => port.bind === 'insert')) releases.push(bindInsert(view, slot, report));\n // Refreshed by the buffer binding below when it changes the view's clip.\n let refreshSpectrogram = () => {};\n if (manifest.spectrogram) {\n const spectrogram = bindSpectrogram(view, slot, report);\n refreshSpectrogram = spectrogram.refresh;\n releases.push(spectrogram.release);\n }\n if (manifest.ports.some(port => port.bind === 'admit')) {\n let admittedTo: ModuleHandle | undefined, admitted: readonly unknown[] | undefined;\n const leases: ConnectionLease[] = [];\n const retire = () => {\n for (const lease of leases.splice(0)) { try { lease.release(); } catch (error) { report(error); } }\n admittedTo = admitted = undefined;\n };\n // Admitting and releasing notify the desk, which re-enters here: run once more afterwards instead.\n let busy = false, again = false;\n const admit = () => {\n if (busy) { again = true; return; }\n busy = true;\n try {\n do {\n again = false;\n const module = view.module, channels = slot.channels.current;\n if (module === admittedTo && channels === admitted) continue;\n retire();\n if (!admitting(module) || !channels) continue;\n admittedTo = module; admitted = channels;\n for (const channel of channels) {\n try { leases.push(module.admit(channel.module, channel.port)); } catch (error) { report(error); }\n }\n } while (again);\n } finally { busy = false; }\n };\n admit();\n releases.push(slot.channels.subscribe(admit));\n const unlisten = listen(element, admit);\n releases.push(() => { unlisten(); retire(); });\n }\n if (slot.forwardsElement || manifest.ports.some(port => port.family === 'source' && port.direction === 'output')) {\n let provided: {module: ModuleHandle; release: () => void} | undefined;\n const forward = () => {\n const module = view.module;\n if (module === provided?.module) return;\n provided?.release();\n provided = module ? {module, release: slot.element.provide(module)} : undefined;\n };\n forward();\n const unlisten = listen(element, forward);\n const releaseOwner = slot.elementOwner.provide(element);\n releases.push(() => { unlisten(); releaseOwner(); provided?.release(); provided = undefined; });\n }\n if (manifest.asset) {\n const property = manifest.asset.property;\n const plays = manifest.asset.kind;\n const assign = () => {\n // Once a view edits its score (DEC-086) a player plays the document: it is never given a score and an editor at once.\n const document = plays === 'score' ? slot.document.current : undefined;\n if (document) {\n if (view.editor === document) return;\n try {\n if (view[property] !== undefined) view[property] = undefined;\n view.editor = document;\n } catch (error) { report(error); }\n return;\n }\n // A document let go (a reverted score) gives the asset back.\n if (plays === 'score' && view.editor !== undefined) { try { view.editor = undefined; } catch (error) { report(error); } }\n const value = slot.asset.current;\n if (value !== undefined && view[property] !== value) view[property] = value;\n };\n assign();\n releases.push(slot.asset.subscribe(assign));\n if (plays === 'score') releases.push(slot.document.subscribe(assign));\n }\n if (manifest.edits === 'score') {\n // `editable` is the author's switch (DEC-086): while it is on, the view borrows the document of the box its cord\n // comes from; off, it borrows none and follows that box as any view does.\n const lend = () => {\n const on = element.hasAttribute('editable') && element.getAttribute('editable') !== 'false';\n const editor = on ? slot.lender.current?.() : undefined;\n if (view.editor === editor) return;\n try { view.editor = editor; } catch (error) { report(error); }\n };\n lend();\n releases.push(slot.lender.subscribe(lend));\n const Observer = element.ownerDocument.defaultView?.MutationObserver;\n const observer = Observer ? new Observer(lend) : undefined;\n observer?.observe(element, {attributes: true, attributeFilter: ['editable']});\n releases.push(() => { observer?.disconnect(); if (view.editor !== undefined) { try { view.editor = undefined; } catch (error) { report(error); } } });\n }\n for (const port of manifest.ports) {\n if (port.bind === 'context' || port.bind === 'admit' || port.bind === 'insert' || (port.family === 'source' && port.direction === 'output')) continue;\n if (port.bind === 'player') {\n const apply = () => { view.player = slot.sourceOwner.current ?? UNLINKED; };\n apply();\n releases.push(slot.sourceOwner.subscribe(apply));\n } else if (port.bind === 'analyser') {\n const apply = () => { view.analyser = slot.analyser.current; };\n apply();\n releases.push(slot.analyser.subscribe(apply));\n } else if (port.bind === 'inputModule' || port.bind === 'moduleTarget') {\n // Explicit null while nothing is cabled: the Element then borrows nothing by containment.\n const provided = port.family === 'note' ? slot.noteSource : slot.source;\n const member = port.bind;\n const apply = () => { view[member] = provided.current ?? null; };\n apply();\n releases.push(provided.subscribe(apply));\n } else {\n const output = view.module?.ports?.().find(item => item.family === 'note' && item.direction === 'output') as NoteOutputPort | undefined;\n const unsubscribe = output?.subscribe((event: NoteEvent) => {\n try { slot.notes.current?.(event); } catch (error) { queueMicrotask(() => { throw error; }); }\n });\n if (unsubscribe) releases.push(unsubscribe);\n }\n }\n for (const parameter of manifest.parameters) {\n if (!parameter.buffer || !options.buffers) continue;\n const name = String(parameterValue(parameter, config));\n if (!name) continue;\n const {store, context} = options.buffers;\n if (parameter.buffer === 'clip') {\n // Read-only: the buffer's samples are the Element's clip, and follow the buffer.\n const show = () => { const buffer = store.get(name); view.clip = buffer ? clipOfBuffer(buffer) : undefined; refreshSpectrogram(); };\n show();\n const unsubscribe = store.subscribe(name, show);\n releases.push(() => { unsubscribe(); view.clip = undefined; });\n continue;\n }\n if (parameter.buffer === 'take') {\n // Each finished take replaces the buffer, so whatever plays or shows it has the recording.\n const keep = (event: Event) => {\n const clip = (event as CustomEvent<{clip?: {toAudioBuffer(context: BaseAudioContext): AudioBuffer}}>).detail?.clip;\n if (!clip) return;\n try { store.set(name, clip.toAudioBuffer(context)); } catch (error) { report(error); }\n };\n element.addEventListener('webaudio:recorded', keep);\n releases.push(() => element.removeEventListener('webaudio:recorded', keep));\n continue;\n }\n // A setting can turn editing off; it never lends an editor the host does not.\n const editable = options.editableBuffers && componentSettings(manifest, config, element.ownerDocument.defaultView?.customElements).attributes.editable !== 'false';\n if (name) releases.push(bindBufferView(element, name, options.buffers.store, options.buffers.context, {editable, onError: options.onError}));\n }\n const gesture = () => options.onGesture?.();\n placed.addEventListener('pointerdown', gesture);\n placed.addEventListener('keydown', gesture);\n return () => {\n placed.removeEventListener('pointerdown', gesture);\n placed.removeEventListener('keydown', gesture);\n for (const release of releases.reverse()) release();\n };\n}\n\ntype Insert = HTMLElement & {context?: BaseAudioContext; readonly input?: AudioNode; readonly output?: AudioNode};\n\n/**\n * Put an insert Element between its box's ends: give it the graph's\n * AudioContext, then connect the box's input to its `input` and its `output`\n * to the box's output. The Element builds its chain when it connects, so the\n * ends are joined once it has one; its boundary nodes stay the same while its\n * context does. Returns the release function, which disconnects only those\n * two edges.\n */\nfunction bindInsert(view: Bound, slot: SurfaceSlot, report: (error: unknown) => void): () => void {\n const element = view as unknown as Insert;\n let joined: {from: AudioNode; into: AudioNode; out: AudioNode; to: AudioNode} | undefined;\n let released = false;\n const part = () => {\n if (!joined) return;\n const {from, into, out, to} = joined;\n joined = undefined;\n try { from.disconnect(into); } catch { /* Already apart. */ }\n try { out.disconnect(to); } catch { /* Already apart. */ }\n };\n const join = () => {\n if (released) return;\n const ends = slot.insert.current;\n if (!ends) { part(); return; }\n if (element.context !== ends.context) {\n try { element.context = ends.context; } catch (error) { report(error); return; }\n }\n const into = element.input, out = element.output;\n // Not built yet: it builds when it connects, and says so with `webscore:chainchange` (DEC-094).\n if (!into || !out) { part(); return; }\n if (joined?.from === ends.input && joined.into === into && joined.out === out && joined.to === ends.output) return;\n part();\n try {\n ends.input.connect(into);\n out.connect(ends.output);\n joined = {from: ends.input, into, out, to: ends.output};\n } catch (error) { report(error); }\n };\n join();\n const unsubscribe = slot.insert.subscribe(join);\n element.addEventListener('webscore:chainchange', join);\n return () => {\n released = true;\n unsubscribe();\n element.removeEventListener('webscore:chainchange', join);\n part();\n };\n}\n\n/** At most this many columns: a long recording is drawn coarser, not slower. */\nconst SPECTROGRAM_FRAMES = 2048;\nconst SPECTROGRAM_FFT = 1024;\n\n/**\n * While the view's `type` is `spectrogram`, give it the spectrogram of the clip\n * it shows (`resolvedClip`, DEC-094): its own, or its player's — the track its\n * cord comes from. Recomputed when that clip changes; released with the binding.\n */\nfunction bindSpectrogram(view: Bound, slot: SurfaceSlot, report: (error: unknown) => void): {refresh(): void; release(): void} {\n const element = view as unknown as HTMLElement & {clip?: AudioClip; resolvedClip?: AudioClip; spectrogram?: unknown};\n let drawn: AudioClip | undefined;\n let watched: EventTarget | undefined;\n // A player announces a new clip with either event.\n const sourceEvents = ['webaudio:sourcechange', 'webaudio:loaded', 'webaudio:playerchange'];\n const update = () => {\n const owner = slot.sourceOwner.current as (EventTarget & {clip?: AudioClip}) | undefined;\n if (owner !== watched) {\n for (const name of sourceEvents) watched?.removeEventListener(name, update);\n watched = owner;\n for (const name of sourceEvents) watched?.addEventListener(name, update);\n }\n const clip = element.getAttribute('type') === 'spectrogram' ? element.resolvedClip ?? element.clip ?? owner?.clip : undefined;\n if (clip === drawn) return;\n drawn = clip;\n try {\n const channel = clip?.channelData(0);\n if (!clip || !channel) { if (element.spectrogram !== undefined) element.spectrogram = undefined; return; }\n element.spectrogram = computeSpectrogram(channel, clip.sampleRate, {fftSize: SPECTROGRAM_FFT, maxFrames: SPECTROGRAM_FRAMES});\n } catch (error) { report(error); }\n };\n update();\n const unsubscribe = slot.sourceOwner.subscribe(update);\n const Observer = element.ownerDocument.defaultView?.MutationObserver;\n // `type` changes with the box's argument; `.clip` with the buffer, whose binding calls refresh.\n const observer = Observer ? new Observer(update) : undefined;\n observer?.observe(element, {attributes: true, attributeFilter: ['type']});\n return {refresh: update, release: () => {\n unsubscribe();\n observer?.disconnect();\n for (const name of sourceEvents) watched?.removeEventListener(name, update);\n if (drawn !== undefined) { try { element.spectrogram = undefined; } catch (error) { report(error); } }\n }};\n}\n\n/**\n * Make a component's Element as tall as its box (DEC-080): the part that\n * draws takes the height its tools and readouts leave, and follows the box\n * when it is resized. The fit is the one the Element declares (DEC-094), or\n * the manifest's in its place; Kernel's `fitElementHeight` applies it. The\n * element must already be inside the box, which sets its width.\n *\n * All of the component is shown whatever the box (DEC-099): one that cannot\n * be laid out as small as its box — its drawing is at its least height, it\n * has no fit and is taller, or what it holds is wider — is scaled down to\n * it, so a box never cuts a component off and never has to be scrolled.\n * Returns the release function, which gives the element its own size back.\n */\nexport function fitComponentElement(element: HTMLElement, manifest: ComponentManifest, box: HTMLElement | null = element.parentElement): () => void {\n const fit = manifest.fit ?? elementFitOf(element);\n if (!box || typeof element.ownerDocument.defaultView?.ResizeObserver !== 'function') return () => {};\n // No fit: its height is its own, and only the scale follows the box.\n if (!fit) return fitElementHeight(element, box, {contain: true});\n // While the box is resized the fit owns the height: a setting for it waits (DEC-085).\n const setAtStart = applied.get(element)?.attributes.height;\n held.set(element, fit.kind === 'token' ? {property: fit.property} : {attribute: 'height'});\n const release = fitElementHeight(element, box, {fit, contain: true, restore: initial => fit.kind === 'token'\n // The height a setting gave the token comes back with the natural size.\n ? applied.get(element)?.style[fit.property] ?? null\n // The height comes back to its setting as it is now, or to what the Element had before any setting.\n : applied.get(element)?.attributes.height ?? (setAtStart === undefined ? initial : manifest.attributes?.height ?? null)});\n return () => { held.delete(element); release(); };\n}\n\nexport interface BufferViewOptions {\n /** Allow editing; each committed edit is rendered and written back to the buffer. */\n readonly editable?: boolean;\n readonly onError?: (error: unknown) => void;\n}\n\n/**\n * Show a named buffer in an `<audio-clip-view>`, following its changes. With\n * `editable`, a committed edit is rendered and written back, so everything\n * that plays the buffer hears it. Returns the release function.\n */\nexport function bindBufferView(element: HTMLElement, name: string, buffers: SharedBuffers, context: BaseAudioContext, options: BufferViewOptions = {}): () => void {\n defineAudioClipViewElement();\n const view = element as ClipElement;\n let editor: AudioClipEditor | undefined;\n let written: AudioBuffer | undefined;\n let job = 0;\n view.setAttribute('aria-label', `Buffer ${name}`);\n if (options.editable) {\n view.setAttribute('tools', 'delete trim silence gain fade zoom history');\n view.editable = true;\n }\n const show = () => {\n const buffer = buffers.get(name);\n if (buffer && buffer === written) return;\n editor?.dispose();\n editor = buffer ? createAudioClipEditor(clipOfBuffer(buffer)) : undefined;\n view.editor = editor;\n };\n const commit = () => {\n const current = editor;\n if (!current) return;\n const mine = ++job;\n void renderAudioClipEditor(current).then(clip => {\n if (mine !== job || current !== editor) return;\n written = clip.toAudioBuffer(context);\n buffers.set(name, written);\n }).catch(error => options.onError?.(error));\n };\n show();\n const unsubscribe = buffers.subscribe(name, show);\n view.addEventListener('webaudio:editcommit', commit);\n return () => {\n job++;\n unsubscribe();\n view.removeEventListener('webaudio:editcommit', commit);\n view.editor = undefined;\n editor?.dispose();\n };\n}\n","// The plugins and assets a component made in Studio needs (DEC-078), from\n// public entries only, so the same project runs in Studio and in any page\n// that installs the packages.\n\nimport {loadClipFromUrl} from '@webmusic/audio/play';\nimport {\n multichannelPlugin, wamPlugin,\n type ModuleEnvironment, type ProjectAssetReference, type ProjectFactoryRequest, type ProjectModuleInstance, type ProjectPluginFactory,\n type WamPluginOptions,\n} from '@webmusic/kernel/module';\nimport {loadScoreFromUrl} from '@webmusic/score/io';\nimport type {MidiAccessSource, ScorePlayerModule} from '@webmusic/score/play/headless';\nimport type {ScoreEditor} from '@webmusic/score/view/headless';\nimport {createWebMusicProjectPlugins} from '../project';\nimport type {ComponentSurfaces} from './surfaces';\n\nexport interface ComponentPluginOptions {\n /** Where printing, script output and module failures go; see Kernel's `ModuleEnvironment`. */\n readonly modules?: ModuleEnvironment;\n /** The slots of the official components placed in a graph; omit for a component without them. */\n readonly surfaces?: ComponentSurfaces;\n /** Web MIDI for the MIDI modules; one is made when omitted. */\n readonly midi?: MidiAccessSource;\n /** Web Audio Modules: the host group and which URLs to load. Without it, `webmusic.wam` modules stay unresolved. */\n readonly wam?: WamPluginOptions;\n /** More factories, such as prepared DSP processors (`processorPlugin`). */\n readonly extra?: readonly ProjectPluginFactory[];\n}\n\n/**\n * Every plugin a component may use: the standard set of\n * `createWebMusicProjectPlugins` — the Bridge's players, racks, effects and\n * LFO with the module types Kernel, Score and Audio register — `mc.` effects,\n * the official components (DEC-081), Web Audio Modules when configured, and\n * `extra`.\n */\nexport function createComponentPlugins(options: ComponentPluginOptions = {}): readonly ProjectPluginFactory[] {\n // A score player also offers its playback source, for a roll that follows it.\n const bridge = createWebMusicProjectPlugins({modules: options.modules, midi: options.midi}).map(factory => factory.id === 'webmusic.score-player' ? withSourceOutlet(factory, options.surfaces) : factory);\n const effect = bridge.find(factory => factory.id === 'webmusic.effect')!;\n return Object.freeze([\n ...bridge,\n multichannelPlugin(effect),\n ...(options.surfaces ? options.surfaces.plugins() : []),\n ...(options.wam ? [wamPlugin(options.wam)] : []),\n ...(options.extra ?? []),\n ]);\n}\n\n/**\n * The score player with its `source` outlet. With `surfaces`, its box also\n * says which score it plays and plays the document that score becomes once a\n * view edits it (DEC-086): the engine, clock and route stay. The edited\n * score is saved in the box's config and read from it (DEC-087).\n */\nfunction withSourceOutlet(factory: ProjectPluginFactory, surfaces?: ComponentSurfaces): ProjectPluginFactory {\n const source = {id: 'source', kind: 'source' as const, direction: 'output' as const};\n if (!surfaces) return Object.freeze({...factory, create: async (request: ProjectFactoryRequest) => {\n const instance = await factory.create(request);\n return {...instance, ports: [...(instance.ports ?? []), source]};\n }});\n return Object.freeze({...factory, create: async (request: ProjectFactoryRequest) => {\n const {id, config} = request.record;\n const leave = surfaces.enter(id);\n let instance: ProjectModuleInstance | undefined;\n try {\n await surfaces.revive(id, config, request.signal);\n instance = await factory.create(request);\n const created = instance;\n const ports = [...(created.ports ?? []), source];\n const module = created.module as Partial<ScorePlayerModule>;\n const score = module.player?.playback.snapshot().score;\n if (!score || typeof module.setDocumentSource !== 'function') return {...created, ports, dispose: () => { leave(); return created.dispose(); }};\n const slot = surfaces.slot(id);\n let playing: ScoreEditor | undefined;\n // The document when there is one; the constructed score again once it is let go.\n const play = () => {\n const document = slot.document.current;\n if (document === playing) return;\n playing = document;\n module.setDocumentSource!(document);\n };\n const releaseScore = slot.score.provide(score);\n // A box rebuilt after its score was edited, or made from a saved one, plays the document at once.\n play();\n const unsubscribe = slot.document.subscribe(play);\n return {...created, ports,\n exportConfig: () => surfaces.withDocument(id, created.exportConfig?.() ?? config),\n dispose: () => { unsubscribe(); releaseScore(); leave(); return created.dispose(); }};\n } catch (error) {\n leave();\n try { instance?.dispose(); } catch { /* The creation failure is the one to report. */ }\n throw error;\n }\n }});\n}\n\nconst SCORE = /\\.(mid|midi|mxl|musicxml|xml)$/i;\nconst AUDIO = /\\.(wav|mp3|ogg|oga|flac|m4a|aac|webm)$/i;\n\n/**\n * Load a project asset by its URI, relative to `base` (the page by default):\n * MIDI and MusicXML as a Score, audio files as an AudioClip. The media type\n * decides when the file name does not. `embedded` maps an asset URI to a\n * `data:` URI of its bytes, read in its place and by its media type alone.\n * A project's own asset URIs stay short: its schema refuses long ones.\n */\nexport async function resolveComponentAsset(\n asset: ProjectAssetReference, signal: AbortSignal, base?: string | URL, embedded?: Readonly<Record<string, string>>,\n): Promise<unknown> {\n signal.throwIfAborted();\n // An asset carried with the component (DEC-095) is read from its data: URI; the project keeps its own URI.\n const carried = embedded?.[asset.uri];\n const url = carried ?? new URL(asset.uri, base ?? globalThis.location?.href ?? 'http://localhost/').href;\n const inline = url.startsWith('data:');\n // Carried bytes have no file name; their media type says what they are.\n const path = inline ? '' : new URL(url).pathname;\n const type = asset.mediaType ?? (inline ? /^data:([^;,]+)/.exec(url)?.[1] ?? '' : '');\n if (SCORE.test(path) || /midi|musicxml/.test(type)) return loadScoreFromUrl(url);\n if (AUDIO.test(path) || type.startsWith('audio/')) return loadClipFromUrl(url, {signal});\n throw new Error(`No loader for the asset ${inline ? `${carried === undefined ? '' : `${asset.uri}, `}embedded as ${type || 'an unknown type'}` : asset.uri}.`);\n}\n","// A component as a page element (DEC-078, Max's standalone): a project made\n// of modules runs in a ModuleProjectRuntime over the standard plugins and\n// shows its presentation — the modules that show a control and the components placed\n// where the author put them — and nothing else (DEC-098): no transport of its\n// own and no room kept round the contents. A component that is played places\n// a `player`, a `track` or a `playbar`; a host may also call `play()`.\n//\n// Ownership: `mountComponent` creates and disposes the runtime, its audio\n// environment (unless one is lent), the view slots, the elements and their\n// bindings. `destroy()` releases everything it made. A player, playbar or\n// desk placed in the project borrows the runtime's Session (DEC-084), which\n// this host preloads as members join (DEC-069).\n\nimport {sharedBuffersFor} from '@webmusic/audio/play/headless';\nimport {ModuleAudioEnvironment, ModuleProjectRuntime, NestedComponent, PolyComponent, keepProjectSessionPreloaded, ProjectPluginRegistry, moduleControlOf, parseModuleProject,\n type ModuleProject, type ProjectAssetReference, type ProjectModuleRecord, type ProjectPluginFactory} from '@webmusic/kernel/module';\nimport {controlKindOf, controlSize, mountModuleControl, type ModuleControlView} from './controls';\nimport {createComponentPlugins, resolveComponentAsset, type ComponentPluginOptions} from './plugins';\nimport {componentManifestOf, manifestFor, migrateBufferViews} from './manifest';\nimport {ComponentSurfaces} from './surfaces';\nimport type {StyleSource} from './settings';\nimport {applyComponentStyle, ownStyle, styleDeclarations} from './theme';\nimport {bindComponentElement, configureComponentElement, createComponentElement, defineComponentElements, fitComponentElement} from './views';\n\nexport interface MountComponentOptions extends Omit<ComponentPluginOptions, 'surfaces'> {\n /** Replace the standard plugins entirely; `extra`, `midi`, `wam` and `modules` are then ignored. */\n readonly plugins?: readonly ProjectPluginFactory[];\n /** Load an asset; defaults to `resolveComponentAsset` relative to `base`. */\n readonly resolveAsset?: (asset: ProjectAssetReference, signal: AbortSignal) => unknown | Promise<unknown>;\n /** Base URL for asset URIs. Defaults to the page. */\n readonly base?: string | URL;\n /**\n * Assets carried with the component (DEC-095): a project asset URI mapped\n * to a `data:` URI of its bytes, read in place of the address. Ignored when\n * `resolveAsset` is given.\n */\n readonly embedded?: Readonly<Record<string, string>>;\n /** Lend an audio environment; by default the component owns one. */\n readonly audio?: ModuleAudioEnvironment;\n /** Let buffers shown by `clip` components be edited and written back. Default false. */\n readonly editableBuffers?: boolean;\n /** Label of the region. Defaults to the project ID. */\n readonly label?: string;\n /**\n * Whose style the component shows (DEC-090): its `own` theme and its boxes'\n * own styles, the default, or with `inherit` neither, so it takes the style\n * of the page or app that holds it. `ComponentHandle.setStyling` changes it.\n */\n readonly styling?: StyleSource;\n /**\n * Where each shown box goes in a page the host lays out itself (DEC-092):\n * given, the component draws no frame or stage of its own, and\n * each box's Element is put in the element this returns for its record. A\n * box given none is not shown. An official component fills the width of\n * its place; a control keeps its own size. The theme is written\n * on `host`.\n */\n readonly place?: (record: ProjectModuleRecord) => HTMLElement | null | undefined;\n /**\n * Start where the project's Session was when it was saved. By default a\n * component starts at the beginning (DEC-094): where its author last\n * stopped is the editor's state, not the component's.\n */\n readonly keepPosition?: boolean;\n readonly onError?: (error: unknown) => void;\n}\n\nexport interface ComponentHandle {\n readonly runtime: ModuleProjectRuntime;\n /** Settles when the project is restored; rejects with the restore failure. */\n readonly ready: Promise<void>;\n /**\n * The project as it stands: live parameter values and, in the config of\n * each box that plays one, the score as its views edited it (DEC-087).\n * Mounting what it resolves to gives the same component again.\n */\n save(): Promise<ModuleProject>;\n /** Choose whose style the component shows (DEC-090), in place: nothing is rebuilt. */\n setStyling(source: StyleSource): void;\n /** Start the component's Session; call it from a user gesture so audio may start. */\n play(): Promise<void>;\n pause(): Promise<void>;\n destroy(): void;\n}\n\n/**\n * The frame `mountComponent` draws around a presentation (DEC-094, DEC-098),\n * in CSS pixels: the rule around the contents, the height past which its\n * stage scrolls, and the control height its contents are drawn with. The\n * frame holds nothing but the contents — no transport and no room round them\n * — so two boxes placed edge to edge stay edge to edge, and a box at the edge\n * of the presentation meets the rule. Boxes are placed in pixels, so the\n * frame sets `--wm-control-size` in pixels too: a strip is as high in a page\n * with another root font size as it was where its author placed a box under\n * it. A theme may set another size; a component that inherits its style\n * takes the page's. An editor that shows the component as it will be exported\n * reads them here, or asks {@link componentFrame}.\n */\nexport const COMPONENT_FRAME = Object.freeze({rule: 1, maxStageHeight: 640, controlSize: 32});\nconst {rule: RULE, maxStageHeight: MAX_STAGE, controlSize: CONTROL_SIZE} = COMPONENT_FRAME;\n\n/** A rectangle in a presentation's coordinates. */\nexport interface ComponentFrameRect { readonly x: number; readonly y: number; readonly width: number; readonly height: number }\nexport interface ComponentFrameLayout {\n /** The whole frame: the stage and the rule round it. */\n readonly frame: ComponentFrameRect;\n /** The stage as it is shown: at most `COMPONENT_FRAME.maxStageHeight` high. */\n readonly stage: ComponentFrameRect;\n /** How high the stage's contents are; more than `stage.height` when it scrolls. */\n readonly contentHeight: number;\n}\n\n/**\n * Where `mountComponent` draws its frame around boxes placed at these\n * rectangles (DEC-098), in the same coordinates: the stage is the boxes'\n * bounds, from the box furthest up and left to the one furthest down and\n * right, and the rule runs round it. Give each box the size it is drawn at —\n * the size its presentation gives it, or its rendered one. With no boxes the\n * stage is empty at the origin. In a host narrower than the frame, the frame\n * is as wide as the host instead.\n */\nexport function componentFrame(boxes: readonly ComponentFrameRect[]): ComponentFrameLayout {\n const left = boxes.length ? Math.min(...boxes.map(box => box.x)) : 0, top = boxes.length ? Math.min(...boxes.map(box => box.y)) : 0;\n const width = Math.max(0, ...boxes.map(box => box.x + box.width - left)), contentHeight = Math.max(0, ...boxes.map(box => box.y + box.height - top));\n const height = Math.min(contentHeight, MAX_STAGE);\n return Object.freeze({contentHeight, stage: Object.freeze({x: left, y: top, width, height}),\n frame: Object.freeze({x: left - RULE, y: top - RULE, width: width + 2 * RULE, height: height + 2 * RULE})});\n}\n\nconst STYLE = `\n:host { display: block; max-width: 100%; }\n.wmc { box-sizing: border-box; display: flex; flex-direction: column; width: max-content; max-width: 100%; color: var(--wm-foreground, light-dark(#111, #eee)); background: var(--wm-background, var(--wm-surface, light-dark(#fff, #111))); border: var(--wm-component-border, ${RULE}px solid var(--wm-border, light-dark(#111, #eee))); border-radius: var(--wm-component-radius, var(--wm-control-radius, 0)); font: 12px/1.4 var(--wm-font-family, ui-monospace, monospace); }\n.wmc__stage { position: relative; overflow: auto; scrollbar-width: none; }\n.wmc__extent { pointer-events: none; }\n.wmc__stage::-webkit-scrollbar { display: none; }\n.wmc__item { position: absolute; box-sizing: border-box; }\n/* A nested component's contents sit inside its cell, framed as Studio frames them. */\n.wmc__nested { border: 1px solid var(--wm-border, light-dark(#111, #eee)); }\n/* Each Element is a block, as in Studio's boxes, so the width it is given holds. A control lays out\n its own cells to fill its box: made a block, its button, switch or grid shrinks to nothing. */\n.wmc__item:not([data-kind=\"control\"]) > :not(style) { display: block; }\n/* The box carries the width, natural or resized, and the Element fills it: an Element may own its inline width. */\n.wmc__item > :not(style) { box-sizing: border-box; width: 100%; }\n.wmc__item[data-sized] { overflow: hidden; }\n/* Placed by the host in a page of its own (DEC-092): in the flow, a component as wide as its place. */\n.wmc__placed { position: relative; box-sizing: border-box; max-width: 100%; }\n.wmc__placed > :not(style) { box-sizing: border-box; width: 100%; }\n.wmc__placed:not([data-kind=\"control\"]) > :not(style) { display: block; }\n.wmc__placed[data-kind=\"component\"] { width: 100% !important; }\n/* A drawing in a resized box may be shorter than it would choose to be. */\n.wmc__item[data-sized] [part~=\"plot\"] { min-height: 32px; }\n`;\n\n/** One thing a level of a component shows, where its presentation puts it. */\nexport interface ComponentContent {\n readonly record: ProjectModuleRecord;\n readonly x: number;\n readonly y: number;\n readonly width?: number;\n readonly height?: number;\n /** A module that shows a control, an official component, or a nested component set to show what it holds. */\n readonly kind: 'control' | 'component' | 'nested';\n}\n\nconst isShell = (record: ProjectModuleRecord | undefined) => record?.plugin.id === NestedComponent.type || record?.plugin.id === PolyComponent.type;\n\n/** What a module shows in a presentation, if anything. */\nfunction contentKind(record: ProjectModuleRecord): ComponentContent['kind'] | undefined {\n if (componentManifestOf(record.plugin.id)) return 'component';\n if (controlKindOf(record)) return 'control';\n return isShell(record) && record.config.embed === true ? 'nested' : undefined;\n}\n\n/**\n * What one level of a component shows (DEC-089): its controls, its\n * official components and the nested components set to show what they hold,\n * each where the presentation puts it — or, when nothing of that level is\n * placed, where it sits on the canvas. `shell` names a nested component; by\n * default the level is the component itself, everything not inside a nested\n * one. Studio's boxes and `mountComponent` show the same things.\n */\nexport function componentContents(input: unknown, shell?: string): readonly ComponentContent[] {\n const project = parseModuleProject(input);\n const byId = new Map(project.modules.map(record => [record.id, record]));\n const contexts = new Map(project.contexts.map(context => [context.id, context]));\n // A context belongs to the nearest nested component that owns it or one of its parents.\n const owner = (contextId: string): string | undefined => {\n for (let context = contexts.get(contextId); context; context = context.parentId ? contexts.get(context.parentId) : undefined) {\n if (context.ownerModuleId && isShell(byId.get(context.ownerModuleId))) return context.ownerModuleId;\n }\n return undefined;\n };\n // Copies of a poly's voices repeat the first voice; show none of them.\n const members = project.modules.filter(record => owner(record.contextId) === shell && !record.id.includes('~v'));\n const shown = new Map(members.flatMap(record => { const kind = contentKind(record); return kind ? [[record.id, kind] as const] : []; }));\n const placed = (project.layout.presentation ?? []).filter(item => shown.has(item.moduleId));\n if (placed.length) {\n return placed.map(item => ({record: byId.get(item.moduleId)!, x: item.x, y: item.y, kind: shown.get(item.moduleId)!,\n ...(item.width !== undefined ? {width: item.width} : {}), ...(item.height !== undefined ? {height: item.height} : {})}));\n }\n const positions = new Map(project.layout.modules.map(item => [item.moduleId, item]));\n return members.filter(record => shown.has(record.id)).map(record => {\n const at = positions.get(record.id);\n return {record, x: at?.x ?? 0, y: at?.y ?? 0, kind: shown.get(record.id)!,\n ...(at?.width !== undefined ? {width: at.width} : {}), ...(at?.height !== undefined ? {height: at.height} : {})};\n });\n}\n\n/**\n * A member whose score is a document still being applied (DEC-086) cannot\n * prepare yet: a moment, not a failure.\n */\nconst notYetApplied = (error: unknown): boolean => (error as {name?: unknown; code?: unknown} | null)?.name === 'ScoreDocumentApplicationError'\n && (error as {code?: unknown}).code === 'not-ready';\n\n/**\n * Preload a runtime's Session as members join it (DEC-069): the host owns that\n * Session, so a placed player's sound, parameters and inserts are real before\n * the first play. Kernel's `keepProjectSessionPreloaded` with the Score\n * documents' wait (DEC-094); a runtime made with `preload` needs neither.\n * Returns the release function.\n */\nexport function keepComponentSessionPreloaded(runtime: ModuleProjectRuntime, onError: (error: unknown) => void = () => {}): () => void {\n return keepProjectSessionPreloaded(runtime, {transient: notYetApplied, onError});\n}\n\n/** Run `project` in `host` and show its presentation. */\nexport function mountComponent(host: HTMLElement | ShadowRoot, input: unknown, options: MountComponentOptions = {}): ComponentHandle {\n // A presented buffer showed its samples before DEC-081; a `clip` shows them now.\n const project = migrateBufferViews(parseModuleProject(input));\n const document = (host as Node).ownerDocument ?? globalThis.document;\n const report = options.onError ?? ((error: unknown) => console.error(error));\n const surfaces = new ComponentSurfaces();\n const audio = options.audio ?? new ModuleAudioEnvironment();\n const registry = new ProjectPluginRegistry();\n const registrations = (options.plugins ?? createComponentPlugins({...options, surfaces, modules: {onError: report, ...options.modules}}))\n .map(plugin => registry.register(plugin));\n const runtime = new ModuleProjectRuntime({\n audio, plugins: registry, connect: surfaces.connect, onCleanupError: report,\n // The runtime preloads the Session it owns as members join (DEC-069, DEC-094).\n preload: {transient: notYetApplied, onError: report},\n resolveAsset: options.resolveAsset ?? ((asset, signal) => resolveComponentAsset(asset, signal, options.base, options.embedded)),\n });\n defineComponentElements();\n\n const root = document.createElement('div');\n root.className = 'wmc';\n root.setAttribute('role', 'region');\n root.setAttribute('aria-label', options.label ?? project.id);\n const style = document.createElement('style');\n // The component's theme (DEC-088) sits at its host from inside a shadow root, where a rule the page writes for the\n // element wins over it; mounted in a plain host, it is written on the root this function makes.\n const shadowed = typeof (host as ShadowRoot).host === 'object' && (host as ShadowRoot).host !== null;\n const themed = styleDeclarations(project.layout.style);\n // Whose style is shown (DEC-090): inheriting, neither the theme nor any box's own style is written.\n let styling: StyleSource = options.styling === 'inherit' ? 'inherit' : 'own';\n const configOf = (record: ProjectModuleRecord) => styling === 'own' ? record.config : {...record.config, styling: 'inherit'};\n const styled: (() => void)[] = [];\n // A host that places the boxes itself (DEC-092) is given no frame: the root stays off the page.\n const placing = typeof options.place === 'function';\n const themeHost = placing && typeof (host as HTMLElement).style === 'object' ? host as HTMLElement : root;\n // The control size in pixels (DEC-098), under the theme: written where the theme is, before it. Not for a\n // component that inherits its style, nor for boxes a host lays out in its own flow.\n const sized = `${shadowed ? ':host' : '.wmc'} { --wm-control-size: ${CONTROL_SIZE}px; }\\n`;\n const applyTheme = () => {\n const own = styling === 'own';\n style.textContent = `${STYLE}${own && !placing ? sized : ''}${shadowed && themed && own ? `:host { ${themed} }\\n` : ''}`;\n if (!shadowed) applyComponentStyle(themeHost, styling === 'own' ? project.layout.style : undefined);\n };\n applyTheme();\n const stage = document.createElement('div');\n stage.className = 'wmc__stage';\n root.append(stage);\n host.append(style);\n if (!placing) host.append(root);\n\n const resume = () => {\n const context = audio.peek() as AudioContext | undefined;\n if (context?.state === 'suspended' && typeof context.resume === 'function') void context.resume();\n };\n const gestures: EventTarget = placing ? host : root;\n gestures.addEventListener('pointerdown', resume);\n gestures.addEventListener('keydown', resume);\n\n // One element per shown module, made once; a rebuild rebinds controls in place.\n const controls = new Map<string, ModuleControlView>();\n const releases: (() => void)[] = [];\n const buffers = () => { const context = audio.prepare(); return {store: sharedBuffersFor(context), context}; };\n const shown = componentContents(project);\n // The stage's corner, as componentFrame places it: the box furthest up and left. Sizes do not move it.\n const {x: minX, y: minY} = componentFrame(shown.map(item => ({x: item.x, y: item.y, width: 0, height: 0}))).stage;\n // The stage is exactly as large as what it holds (DEC-098), up to its host's\n // width and 640 px high, and scrolls beyond that. Sizes start from each\n // element's nominal size and follow the rendered ones.\n const extent = document.createElement('div');\n extent.className = 'wmc__extent';\n stage.append(extent);\n const cells: {cell: HTMLElement; x: number; y: number; width: number; height: number}[] = [];\n const fit = () => {\n let width = 0, height = 0;\n for (const item of cells) {\n width = Math.max(width, item.x + (item.cell.offsetWidth || item.width));\n height = Math.max(height, item.y + (item.cell.offsetHeight || item.height));\n }\n extent.style.width = `${width}px`;\n extent.style.height = `${height}px`;\n stage.style.height = `${Math.min(height, MAX_STAGE)}px`;\n };\n /**\n * Show one level's contents in `container`, offset by `left` and `top`. A\n * nested component set to show what it holds is a cell of its own, as large\n * as its contents; only the top level's cells size the stage.\n */\n const placeLevel = (contents: readonly ComponentContent[], container: HTMLElement, left: number, top: number, topLevel: boolean) => {\n for (const {record, x, y, width: sizedWidth, height: sizedHeight, kind} of contents) {\n const cell = document.createElement('div');\n cell.className = 'wmc__item';\n // What the cell holds decides how it is laid out: an Element is a block, a control fills its cell.\n cell.dataset.kind = kind;\n cell.style.left = `${x - left}px`;\n cell.style.top = `${y - top}px`;\n // Placed by the host: in the element it gives, in its flow, or not shown at all.\n const place = topLevel && placing ? options.place!(record) : undefined;\n if (topLevel && placing && !place) continue;\n if (place) {\n cell.className = 'wmc__placed';\n cell.style.left = cell.style.top = '';\n releases.push(() => cell.remove());\n }\n const stage = place ?? container;\n const at = {x: x - left, y: y - top};\n const keep = (item: {cell: HTMLElement; x: number; y: number; width: number; height: number}) => { if (topLevel) cells.push(item); };\n if (kind === 'nested') {\n // What a nested component holds, laid out by its own presentation (DEC-089).\n const inner = componentContents(project, record.id);\n // As the component itself (DEC-098): from the box furthest up and left, with no room kept before it.\n const {x: innerLeft, y: innerTop} = componentFrame(inner.map(item => ({x: item.x, y: item.y, width: 0, height: 0}))).stage;\n cell.classList.add('wmc__nested');\n cell.setAttribute('role', 'group');\n cell.setAttribute('aria-label', record.label ?? record.id);\n stage.append(cell);\n placeLevel(inner, cell, innerLeft, innerTop, false);\n const width = Math.max(0, ...inner.map(item => item.x - innerLeft + (item.width ?? 0)));\n const height = Math.max(0, ...inner.map(item => item.y - innerTop + (item.height ?? 0)));\n // The cell takes what its contents take once drawn; until then, what their sizes say.\n const measure = () => {\n let right = width, bottom = height;\n for (const child of cell.children) {\n const element = child as HTMLElement;\n right = Math.max(right, element.offsetLeft + element.offsetWidth);\n bottom = Math.max(bottom, element.offsetTop + element.offsetHeight);\n }\n cell.style.width = `${right}px`;\n cell.style.height = `${bottom}px`;\n };\n measure();\n const observer = typeof ResizeObserver === 'function' ? new ResizeObserver(measure) : undefined;\n for (const child of cell.children) observer?.observe(child);\n releases.push(() => observer?.disconnect());\n keep({cell, ...at, width, height});\n continue;\n }\n // A box resized in Studio keeps its size here; its element fills it.\n const sized = sizedWidth !== undefined && sizedHeight !== undefined;\n if (sized) { cell.style.width = `${sizedWidth}px`; cell.style.height = `${sizedHeight}px`; cell.dataset.sized = 'true'; }\n const found = componentManifestOf(record.plugin.id);\n const manifest = found && manifestFor(found, configOf(record));\n if (manifest) {\n const element = createComponentElement(manifest, configOf(record), document);\n styled.push(() => configureComponentElement(element, manifest, configOf(record)));\n if (!sized) cell.style.width = `${manifest.width}px`;\n cell.append(element);\n keep({cell, ...at, width: sizedWidth ?? manifest.width, height: sizedHeight ?? 180});\n const needsBuffers = manifest.parameters.some(parameter => parameter.buffer);\n releases.push(bindComponentElement(element, manifest, surfaces.slot(record.id), record.config, {\n onGesture: resume, onError: report, editableBuffers: options.editableBuffers, ...(needsBuffers ? {buffers: buffers()} : {}),\n }));\n // Bound before it connects, a player finds the graph's Session on its box at once (DEC-084).\n stage.append(cell);\n // In a resized box the component draws as tall as the box.\n if (sized) releases.push(fitComponentElement(element, manifest, cell));\n } else {\n const kind = controlKindOf(record)!;\n const label = record.label ?? kind;\n // A control fills its cell: the size its author gave it, or its natural one.\n const natural = controlSize(kind, record.config);\n stage.append(cell);\n if (!sized) { cell.style.width = `${natural.width}px`; cell.style.height = `${natural.height}px`; }\n keep({cell, ...at, width: sizedWidth ?? natural.width, height: sizedHeight ?? natural.height});\n // A control takes its own style as a component does (DEC-088).\n const restyle = () => applyComponentStyle(cell, ownStyle(configOf(record)));\n restyle();\n styled.push(restyle);\n controls.set(record.id, mountModuleControl(cell, kind, {label, cardHost: place ? cell : root, onError: report}));\n }\n }\n };\n placeLevel(shown, stage, minX, minY, true);\n fit();\n const resized = typeof ResizeObserver === 'function' ? new ResizeObserver(fit) : undefined;\n for (const {cell} of cells) resized?.observe(cell);\n\n const refresh = () => {\n for (const [id, control] of controls) control.refresh(moduleControlOf(runtime.getModule(id)));\n };\n const stopRuntime = runtime.subscribe(refresh);\n\n let destroyed = false;\n // A component starts at the beginning unless its host keeps the saved position (DEC-094).\n const ready = runtime.restore(options.keepPosition ? project : {...project, session: {...project.session, positionSeconds: 0}}).then(() => refresh());\n ready.catch(report);\n const handle: ComponentHandle = {\n runtime, ready,\n setStyling(source) {\n const next: StyleSource = source === 'inherit' ? 'inherit' : 'own';\n if (destroyed || next === styling) return;\n styling = next;\n applyTheme();\n for (const restyle of styled) restyle();\n },\n async save() {\n await ready;\n // An edit is encoded off the call that made it.\n await surfaces.settled();\n return runtime.exportProject();\n },\n async play() {\n await ready;\n const context = audio.prepare() as AudioContext;\n if (context.state === 'suspended' && typeof context.resume === 'function') await context.resume();\n const session = runtime.session;\n if (!session) return;\n if (session.snapshot.ended) await session.seek(0);\n await session.play();\n },\n async pause() { await runtime.session?.pause(); },\n destroy() {\n if (destroyed) return;\n destroyed = true;\n resized?.disconnect();\n stopRuntime();\n for (const control of controls.values()) control.destroy();\n // Off the page first: a player that loses its lent Session then is\n // leaving, and does not start a Session of its own.\n root.remove();\n style.remove();\n for (const release of releases) { try { release(); } catch (error) { report(error); } }\n runtime.dispose();\n for (const registration of registrations) registration.release();\n if (!options.audio) audio.dispose();\n root.removeEventListener('pointerdown', resume);\n root.removeEventListener('keydown', resume);\n },\n };\n return handle;\n}\n\n/**\n * Define a custom element that runs `project`: each instance mounts it in its\n * shadow root when connected and releases it when disconnected. Returns the\n * element class; an already defined tag is left as it is.\n */\nexport function defineComponentElement(tag: string, project: unknown, options: MountComponentOptions = {}): CustomElementConstructor {\n const existing = customElements.get(tag);\n if (existing) return existing;\n const document = parseModuleProject(project);\n const source = (element: HTMLElement): StyleSource => element.getAttribute('styling') === 'inherit' ? 'inherit' : 'own';\n class WebMusicComponentElement extends HTMLElement {\n /** `styling=\"inherit\"` sets the component's own theme and styles aside for those of what holds it (DEC-090). */\n static readonly observedAttributes = ['styling'];\n #handle?: ComponentHandle;\n attributeChangedCallback(): void { this.#handle?.setStyling(source(this)); }\n /** The running component, while connected. */\n get component(): ComponentHandle | undefined { return this.#handle; }\n connectedCallback(): void {\n if (this.#handle) return;\n const root = this.shadowRoot ?? this.attachShadow({mode: 'open'});\n this.#handle = mountComponent(root, document, {...options, label: this.getAttribute(\"aria-label\") ?? options.label,\n styling: this.hasAttribute('styling') ? source(this) : options.styling});\n }\n disconnectedCallback(): void { this.#handle?.destroy(); this.#handle = undefined; }\n }\n customElements.define(tag, WebMusicComponentElement);\n return WebMusicComponentElement;\n}\n","// Export a component as code (DEC-078): a JavaScript module that defines a\n// custom element, for projects that install the packages, and a standalone\n// HTML page that loads the published packages from a CDN. Under DEC-095 a\n// component can also leave complete in one file: the page or module carries\n// the runtime (`@webmusic/bridge/component/global`), its assets as data URIs\n// and its DSP processors as text, so it runs with nothing installed and\n// nothing published. Pure: strings in, strings out.\n\nimport {parseModuleProject, type ModuleProject, type ProjectPluginFactory} from '@webmusic/kernel/module';\nimport {processorPlugin, type ProcessorDefinition} from '@webmusic/kernel/processor';\nimport {BRIDGE_VERSION} from '../version';\nimport {createComponentPlugins} from './plugins';\nimport {ComponentSurfaces} from './surfaces';\n\nexport interface ComponentExportOptions {\n /** The custom element's tag: lowercase, with a hyphen. */\n readonly tag: string;\n /** Plugin IDs the code supplies through `extra`; others not in the standard set are listed as resources to provide. */\n readonly provided?: readonly string[];\n}\n\nexport interface ComponentPageOptions extends ComponentExportOptions {\n readonly title?: string;\n /** Where `@webmusic/bridge/component` loads from. Defaults to jsDelivr's ESM build of `version`. */\n readonly moduleUrl?: string;\n /** Package version for the default module URL. Defaults to the version of the `@webmusic/bridge` that writes the page. */\n readonly version?: string;\n /** Base URL that asset URIs resolve against in the page. Defaults to the page itself. */\n readonly assetBase?: string;\n}\n\nconst TAG = /^[a-z][a-z0-9._]*-[a-z0-9._-]*$/;\nconst RESERVED = new Set(['annotation-xml', 'color-profile', 'font-face', 'font-face-src', 'font-face-uri', 'font-face-format', 'font-face-name', 'missing-glyph']);\n\nfunction checkTag(tag: string): void {\n if (!TAG.test(tag) || RESERVED.has(tag)) throw new TypeError(`${tag} is not a custom element name: use lowercase letters with a hyphen, such as arabesque-player.`);\n}\n\n/** Plugin IDs the standard component plugins provide. */\nexport function standardPluginIds(): ReadonlySet<string> {\n return new Set(createComponentPlugins({surfaces: new ComponentSurfaces(), midi: undefined}).map(plugin => plugin.id));\n}\n\n/**\n * What a project needs beyond the packages: asset URIs it loads and plugin\n * IDs the standard set does not provide (a prepared DSP processor, a WAM host).\n */\nexport function componentResources(input: unknown, provided: readonly string[] = []): {assets: readonly string[]; plugins: readonly string[]} {\n const project = parseModuleProject(input);\n const known = standardPluginIds();\n const plugins = [...new Set(project.modules.map(module => module.plugin.id))].filter(id => !known.has(id) && !provided.includes(id)).sort();\n return Object.freeze({assets: Object.freeze(project.assets.map(asset => asset.uri)), plugins: Object.freeze(plugins)});\n}\n\n/** The project as a component ships it (DEC-094): from the beginning, not where its author last stopped. */\nconst json = (project: ModuleProject) => JSON.stringify({...project, session: {...project.session, positionSeconds: 0}}, null, 2);\n/** JSON is valid JavaScript, but not inside a `<script>`: a `</script>` in a string would end it. */\nconst scriptSafe = (text: string) => text.replace(/</g, '\\\\u003c').replace(/[\\u2028\\u2029]/g, character => character === '\\u2028' ? '\\\\u2028' : '\\\\u2029');\n\nfunction resourceComment(resources: {assets: readonly string[]; plugins: readonly string[]}): string {\n const lines = [\n ...(resources.assets.length ? ['// Assets it loads, relative to the page:', ...resources.assets.map(uri => `// ${uri}`)] : []),\n ...(resources.plugins.length ? ['// Plugins to supply through `extra` (they stay unresolved until you do):', ...resources.plugins.map(id => `// ${id}`)] : []),\n ];\n return lines.length ? `${lines.join('\\n')}\\n` : '';\n}\n\n/**\n * A JavaScript module that defines `<tag>` for a project that installs the\n * packages: `npm install @webmusic/kernel @webmusic/ui @webmusic/score\n * @webmusic/audio @webmusic/bridge`, import the module, and write `<tag>`.\n */\nexport function componentModuleSource(input: unknown, options: ComponentExportOptions): string {\n checkTag(options.tag);\n const project = parseModuleProject(input);\n return `// <${options.tag}> — a WebMusic component.\n// Needs @webmusic/kernel, @webmusic/ui, @webmusic/score, @webmusic/audio and\n// @webmusic/bridge. Import this module once, then write <${options.tag}></${options.tag}>.\n${resourceComment(componentResources(project, options.provided))}import {defineComponentElement} from '@webmusic/bridge/component';\n\nexport const project = ${json(project)};\n\nexport default defineComponentElement(${JSON.stringify(options.tag)}, project);\n`;\n}\n\n/** A standalone HTML page that runs the component from the published packages. */\nexport function componentPageSource(input: unknown, options: ComponentPageOptions): string {\n checkTag(options.tag);\n const project = parseModuleProject(input);\n const title = (options.title ?? project.id).replace(/[<&]/g, character => character === '<' ? '&lt;' : '&amp;');\n const moduleUrl = options.moduleUrl ?? `https://cdn.jsdelivr.net/npm/@webmusic/bridge@${options.version ?? BRIDGE_VERSION}/component/+esm`;\n const resources = componentResources(project, options.provided);\n const base = options.assetBase === undefined ? '' : `, {base: ${JSON.stringify(options.assetBase)}}`;\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>${title}</title>\n<style>\n :root { color-scheme: light dark; }\n body { margin: 0; padding: 16px; background: light-dark(#fff, #111); color: light-dark(#111, #eee); }\n</style>\n</head>\n<body>\n<${options.tag}></${options.tag}>\n<script type=\"module\">\n${scriptSafe(resourceComment(resources))}import {defineComponentElement} from ${JSON.stringify(moduleUrl)};\nconst project = ${scriptSafe(json(project))};\ndefineComponentElement(${JSON.stringify(options.tag)}, project${base});\n</script>\n</body>\n</html>\n`;\n}\n\n// --- complete in one file (DEC-095) ----------------------------------------------\n\n/** A DSP processor carried inside an exported file: its definition and its worklet module as text. */\nexport interface EmbeddedProcessor {\n readonly definition: ProcessorDefinition;\n /** The worklet module, bundled into one script that imports nothing. */\n readonly worklet: string;\n}\n\nexport interface ComponentStandaloneOptions extends ComponentExportOptions {\n /**\n * The text of `@webmusic/bridge/component/global`: the file\n * `dist/component.global.js` of the installed `@webmusic/bridge`.\n */\n readonly runtime: string;\n /** The page's title; the project's ID when omitted. Ignored by the module. */\n readonly title?: string;\n /**\n * Assets to carry inside the file: a project asset URI mapped to a `data:`\n * URI of its bytes (see {@link componentAssetDataUri}). The file hands them\n * to the element as `embedded`; the project keeps its own URIs. An asset\n * left out is loaded from its URI, relative to the page.\n */\n readonly assets?: Readonly<Record<string, string>>;\n /** DSP processors to carry inside the file. Their plugins need no `extra`. */\n readonly processors?: readonly EmbeddedProcessor[];\n}\n\nconst MEDIA_TYPES: Readonly<Record<string, string>> = Object.freeze({\n mid: 'audio/midi', midi: 'audio/midi', mxl: 'application/vnd.recordare.musicxml', musicxml: 'application/vnd.recordare.musicxml+xml',\n xml: 'application/vnd.recordare.musicxml+xml', wav: 'audio/wav', mp3: 'audio/mpeg', ogg: 'audio/ogg', oga: 'audio/ogg',\n flac: 'audio/flac', m4a: 'audio/mp4', aac: 'audio/aac', webm: 'audio/webm',\n});\n\n/** The media type an asset's file name implies, for the loaders `resolveComponentAsset` chooses between. */\nexport function componentAssetMediaType(uri: string): string | undefined {\n const extension = /\\.([a-z0-9]+)(?:[?#].*)?$/i.exec(uri)?.[1]?.toLowerCase();\n return extension ? MEDIA_TYPES[extension] : undefined;\n}\n\n/**\n * An asset's bytes as a `data:` URI to embed in an exported file. The media\n * type is `type`, else what the URI's file name implies, so the right loader\n * reads it back.\n */\nexport function componentAssetDataUri(uri: string, bytes: Uint8Array, type?: string): string {\n const mediaType = type || componentAssetMediaType(uri) || 'application/octet-stream';\n let binary = '';\n for (let offset = 0; offset < bytes.length; offset += 0x8000) binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000));\n return `data:${mediaType};base64,${btoa(binary)}`;\n}\n\nconst blobUrls = new Map<string, string>();\n\n/**\n * The project plugin of a processor whose worklet module is text: the text\n * becomes a Blob URL, made once per processor version and kept for the\n * page's life, since a registered worklet module cannot be unloaded.\n */\nexport function embeddedProcessorPlugin(definition: ProcessorDefinition, worklet: string): ProjectPluginFactory {\n if (typeof worklet !== 'string' || !worklet.trim()) throw new TypeError('An embedded processor needs its worklet module as text.');\n const key = `${definition.id}@${definition.version}`;\n return processorPlugin(definition, {source: {\n get module() {\n let url = blobUrls.get(key);\n if (!url) { url = URL.createObjectURL(new Blob([worklet], {type: 'text/javascript'})); blobUrls.set(key, url); }\n return url;\n },\n }});\n}\n\n/** Inside a classic `<script>`, `</script` ends the element and `<!--` opens a comment state. */\nconst inlineScript = (text: string) => text.replace(/<\\/(script)/gi, '<\\\\/$1').replace(/<!--/g, '<\\\\!--');\n\nfunction standalone(input: unknown, options: ComponentStandaloneOptions) {\n checkTag(options.tag);\n if (typeof options.runtime !== 'string' || !options.runtime.includes('WebMusicComponent')) {\n throw new TypeError('A complete export needs the text of @webmusic/bridge/component/global as `runtime`.');\n }\n const project = parseModuleProject(input);\n // The bundle's source map stays with the package: a file that carries the runtime names no file beside it.\n const runtime = options.runtime.replace(/\\n?\\/\\/# sourceMappingURL=\\S*\\s*$/, '\\n');\n // The project keeps its own asset URIs (its schema refuses long ones); the bytes travel beside it.\n const embedded: Record<string, string> = {};\n for (const [uri, data] of Object.entries(options.assets ?? {})) {\n if (typeof data !== 'string' || !data.startsWith('data:')) throw new TypeError(`The embedded asset ${uri} must be a data: URI.`);\n if (project.assets.some(asset => asset.uri === uri)) embedded[uri] = data;\n }\n const processors = options.processors ?? [];\n const provided = [...(options.provided ?? []), ...processors.map(processor => processor.definition.id)];\n // What the file still does not hold: assets left as URIs and plugins nobody supplies.\n const resources = componentResources(project, provided);\n const outside = {assets: resources.assets.filter(uri => !(uri in embedded)), plugins: resources.plugins};\n const carriesAssets = Object.keys(embedded).length > 0;\n const settings = [\n ...(carriesAssets ? ['embedded: assets'] : []),\n ...(processors.length ? ['extra: processors.map(processor => WebMusicComponent.embeddedProcessorPlugin(processor.definition, processor.worklet))'] : []),\n ];\n const extra = settings.length ? `, {${settings.join(', ')}}` : '';\n const carried = `${carriesAssets ? `const assets = ${JSON.stringify(embedded)};\\n` : ''}${processors.length\n ? `const processors = ${JSON.stringify(processors.map(processor => ({definition: processor.definition, worklet: processor.worklet})))};\\n`\n : ''}`;\n return {project, outside, extra, carried, runtime};\n}\n\n/**\n * A component complete in one HTML page: the runtime, the project, its\n * embedded assets and processors. Open the file, or serve it from anywhere;\n * it installs nothing and loads nothing it does not carry, apart from assets\n * left out of `assets` and optional engines a feature may ask for.\n */\nexport function componentStandalonePageSource(input: unknown, options: ComponentStandaloneOptions): string {\n const {project, outside, extra, carried, runtime} = standalone(input, options);\n const title = (options.title ?? project.id).replace(/[<&]/g, character => character === '<' ? '&lt;' : '&amp;');\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>${title}</title>\n<style>\n :root { color-scheme: light dark; }\n body { margin: 0; padding: 16px; background: light-dark(#fff, #111); color: light-dark(#111, #eee); }\n</style>\n</head>\n<body>\n<${options.tag}></${options.tag}>\n<script>\n${inlineScript(runtime)}\n</script>\n<script>\n${scriptSafe(resourceComment(outside))}(() => {\nconst project = ${scriptSafe(json(project))};\n${scriptSafe(carried)}WebMusicComponent.defineComponentElement(${JSON.stringify(options.tag)}, project${extra});\n})();\n</script>\n</body>\n</html>\n`;\n}\n\n/**\n * A component complete in one JavaScript module: import the file, with a\n * `<script type=\"module\">` or a bundler, and write `<tag>`. It carries the\n * runtime, so the project that uses it installs no package.\n */\nexport function componentStandaloneModuleSource(input: unknown, options: ComponentStandaloneOptions): string {\n const {project, outside, extra, carried, runtime} = standalone(input, options);\n return `// <${options.tag}> — a WebMusic component, complete in this file.\n// Import this module once, then write <${options.tag}></${options.tag}>. Nothing else is installed.\n${resourceComment(outside)}${runtime}\nexport const project = ${json(project)};\n${carried}\nexport default WebMusicComponent.defineComponentElement(${JSON.stringify(options.tag)}, project${extra});\n`;\n}\n","/**\n * The release of `@webmusic/bridge` this source belongs to.\n * `npm run release:prepare` writes it with the manifests, and\n * `npm run check:release-manifests` rejects a value that differs from them.\n */\nexport const BRIDGE_VERSION = '0.4.0';\n"],"mappings":";;;;;;;;;AASA,SAAQ,QAAQ,QAAQ,QAAQ,YAAY,aAAa,QAAQ,iBAAgB;AACjF;AAAA,EACE;AAAA,EAAa;AAAA,EAAc;AAAA,EAAM;AAAA,EAAW;AAAA,EAAc;AAAA,EAAS;AAAA,EAAY;AAAA,EAAS;AAAA,OAEnF;AACP;AAAA,EACE;AAAA,EAAa;AAAA,EAAW;AAAA,EAAa;AAAA,EAAW;AAAA,EAAc;AAAA,EAAkB;AAAA,EAAY;AAAA,EAAa;AAAA,EAAiB;AA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AAQ,GAAG;AAAA;AAAA,EAE7B,aAAa,OAAO,CAAC;AAAA;AAAA;AAAA,EAGrB,WAAW,gBAAgB,OAAO,CAAC,CAAC;AAAA,kBACpB,WAAW,KAAK,OAAO,CAAC,CAAC;AAAA,EACzC,WAAW,OAAO,CAAC,4CAA4C,KAAK,UAAU,QAAQ,GAAG,CAAC,YAAY,KAAK;AAAA;AAAA;AAAA;AAAA;AAAA;AAM7G;AAOO,SAAS,gCAAgC,OAAgB,SAA6C;AAC3G,QAAM,EAAC,SAAS,SAAS,OAAO,SAAS,QAAO,IAAI,WAAW,OAAO,OAAO;AAC7E,SAAO,OAAO,QAAQ,GAAG;AAAA,0CACe,QAAQ,GAAG,MAAM,QAAQ,GAAG;AAAA,EACpE,gBAAgB,OAAO,CAAC,GAAG,OAAO;AAAA,yBACX,KAAK,OAAO,CAAC;AAAA,EACpC,OAAO;AAAA,0DACiD,KAAK,UAAU,QAAQ,GAAG,CAAC,YAAY,KAAK;AAAA;AAEtG;","names":["entries","id","number","json","parseModuleProject","entries","parseModuleProject","_listeners","notify_fn","entries","module","held","defineAudioClipViewElement","defineAudioClipViewElement","written","NestedComponent","parseModuleProject","NestedComponent","parseModuleProject","stage","sized","kind","parseModuleProject","parseModuleProject"]}