Skip to content

JavaScript/TypeScript Projects API ​

Project, the compiled ProjectTimeline and the offline vocal-edit sessions are the control-thread classes of the headless-DAW side of the package. This page holds their generated signatures and the lifecycle rules they share; the guides linked below teach the workflows.

Where each task lives ​

GoalUseGuide
Start an empty projectnew Project()Project Editing
Build/load a clip + MIDI arrangement and edit itProject (Project.fromJson, toSceneJson, MIDI event helpers)Project Editing
Preserve opaque analysis/assist metadataproject.setAssistSidecar(...), assistSidecars()Project Editing
Classify automation lanesProjectAutomationTargetKind, targetKind on ProjectAutomationLaneDescProject Editing
Render a project to audioproject.bounce({ synthInstruments })Project Bounce
Compile a project into a timeline for the live engineproject.compile({ withTimeline: true }), engine.applyProjectTimeline(...)Project Save & Load
Edit a monophonic vocal take offlinecreateVocalEditSession(...), VocalEditWorkerClientOffline Vocal Editing
typescript
import { Project, synthPresetNames, synthPresetPatch } from '@libraz/libsonare';

const project = Project.fromJson(projectJson);
const { channels, sampleRate } = project.bounce({
  synthInstruments: [{ instrument: synthPresetPatch(synthPresetNames()[0]) }],
});

synthInstruments (like builtinInstruments, sf2Instruments and instruments) takes a list of { destinationId?, instrument } bindings, one per MIDI destination; a binding without a destinationId answers to destination 0.

Lifecycle ​

Create ​

new Project() starts an empty arrangement and Project.fromJson(json) loads a saved one. A ProjectTimeline has no constructor: project.compile({ withTimeline: true }) returns one, and none when an error diagnostic means nothing compiled. createVocalEditSession(request) analyses mono PCM and opens a session; restoreVocalEditSession(request) reopens one from an exported state and the same source PCM. VocalEditWorkerClient creates the same sessions inside a Worker.

Use ​

All of these are offline, control-thread classes: none runs on the audio thread, and none is realtime-safe. Project edits are undoable; bounce() and the vocal renders are synchronous on the calling thread, so move a long vocal render to renderAsync() or the Worker client, and expect Project to refuse another call while an instrument bounce is calling back into JavaScript. To play a project live, compile it and hand the ProjectTimeline to a stopped RealtimeEngine; the engine keeps its own reference, so the timeline can be destroyed right after the apply.

Release ​

The handles are WASM heap objects that the garbage collector cannot reclaim. destroy() is idempotent and [Symbol.dispose]() makes using work, as for every handle (Releasing Native Handles). Destroying a VocalEditSession also destroys every draft it began; a VocalEditDraft, VocalRenderSnapshot and VocalRenderJob each have their own destroy(). The Worker client, session and draft return a Promise from destroy() and support await using.

Errors ​

A refused argument is a TypeError or RangeError; a project document that does not parse is InvalidFormat; a call on a released handle, or a bounce whose derived length does not fit, is InvalidState. The full rule, with the table of codes, is Error Contract. A vocal-edit build is optional: gate on capabilities().features.vocalEdit and read vocalEditAbiVersion().

Project ​

typescript
class Project {
  applyVocalEdit(request: ProjectVocalEditApplyRequest): ProjectVocalEditApplyResult;  // Applies a vocal edit to a clip's audio.
  vocalEditDependencies(): ProjectVocalEditDependency[];  // The vocal-edit dependencies of the project's clips, in clip order.
  rehydrateVocalEdits(
    originals: readonly ProjectVocalOriginalSource[],
    options?: ProjectVocalRehydrateOptions,
  ): ProjectVocalRehydrateItem[];  // Re-renders the stored vocal edits against the original audio.
  constructor();
  static fromJson(document: string): Project;  // Deserialize project JSON into a new Project. Throws if the JSON is malformed, surfacing the joined diagnostic messages.
  static fromJsonWithDiagnostics(document: string): ProjectDeserializeResult;  // Deserialize project JSON and return native warning diagnostics emitted on successful loads, such as dangling source references preserved for repair.
  toJson(): string;  // Serialize the project (+ MIDI content) to deterministic JSON.
  setSampleRate(sampleRate: number): void;  // Set the project sample rate in Hz. Must be an integer in `[8000, 384000]`; anything else throws. Applied through the edit history, so it is undoable.
  addTrack(desc?: ProjectTrackDesc): number;  // Add a track and return its allocated stable id.
  addClip(desc: ProjectClipDesc): number;  // Add an audio or MIDI clip and return its allocated clip id. Audio is given as planar `channels` with its `sampleRate`; a clip with neither is a MIDI clip or a metadata-only audio clip named by `sourceUri`.
  importExternalStems(
    request: ExternalSeparatedStemImportRequest,
  ): ExternalSeparatedStemImportResult;  // Import host-separated PCM through the normal audio-track/clip path.
  addLoopRecordingTakes(desc: ProjectLoopRecordingDesc): ProjectLoopRecordingResult;  // Split captured loop-recording audio into takes and add one clip. `audio` may be interleaved or planar (`Float32Array[]`). The last take is made active unless it is partial and an earlier complete take exists; `partialTail: 'drop'` does not create the partial take. A partial take is marked `"partial": true` in its `takes[]` entry of `toJson()`.
  addMidiClip(startPpq: number, lengthPpq: number): ProjectMidiClipResult;  // Create a MIDI track + clip; returns `{ trackId, clipId }`.
  splitClip(clipId: number, splitPpq: number): number;  // Split a clip at `splitPpq` (in [0, 1e12]) and return the new clip id.
  trimClip(clipId: number, newStartPpq: number, newLengthPpq: number): void;  // Trim a clip's start / length in PPQ.
  moveClip(clipId: number, newStartPpq: number, options?: ProjectMoveClipOptions): void;  // Move a clip to `newStartPpq` (in [0, 1e12]), and to another track when `options.trackId` is given.
  setTrackKind(trackId: number, kind: ProjectTrackKind): void;  // Change a track kind via an undoable edit.
  setClipWarpRef(clipId: number, warpRefId: number): void;  // Set a clip's warp reference id (0 clears it).
  setClipWarpMode(clipId: number, mode: ProjectWarpMode): void;  // Set a clip's warp playback mode.
  setWarpMap(map: ProjectWarpMapDesc): void;  // Add or replace a first-class warp map referenced by clip warp ids.
  removeWarpMap(warpRefId: number): void;  // Remove a first-class warp map by id.
  setTrackMidiDestination(trackId: number, destinationId?: number | null): void;  // Route a track's MIDI to host-instrument `destinationId`. Destination `0`, which every track starts on, is a real id like any other. The compiler stamps every MIDI clip on the track with this id so the engine dispatches its events to the instrument registered for that destination. Routes through an undoable edit command. Builtin, NativeSynth, and SF2 instruments retain source-track provenance inside a shared destination voice pool. With only zero-latency instruments bound, live lanes and channel-strip bounces remain aligned. Configure one live lane per source track that needs strip processing.
  setDestinationInstrument(
    destinationId: number,
    instrument?: ProjectInstrument | null,
    options?: ProjectDestinationInstrumentOptions,
  ): void;  // Set or clear the instrument and optional bank/program for a MIDI destination.
  destinationInstruments(): ProjectDestinationInstrumentBinding<ProjectInstrument>[];  // Every stored instrument binding, in destination-id order.
  // Set a track's linear playback gain (1.0 = unity; >= 0) via an undoable edit.
  //
  // The value reaches the track's audio and MIDI alike, but the stage it lands on follows the track's channel strip. A strip bound by this track alone (including one synthesized for an unbound track) carries the controls on its own fader and panner. A strip several tracks share processes their sum and carries none of them; each track applies its controls upstream instead — on its own clip schedules for audio, on its track lane for MIDI.
  //
  // A MIDI track's gain/pan on a shared strip ride the track lane, which is fed per source track only by an instrument that preserves source-track identity (see setTrackMidiDestination). An opaque host-callback instrument, or one reporting non-zero latency, renders one buffer per destination and has no per-track stage on a shared strip, so its gain/pan do not reach the bounce there; bind such an instrument to a track with an exclusive strip. Mute and solo are unaffected: a silenced MIDI track schedules no events at all.
  setTrackGain(trackId: number, gain: number): void;
  setPartRig(request: PartRigRequest): void;  // Set the rig of one part (0-15), or of the destination's default when `part` is PART_RIG_ALL_PARTS, on MIDI destination `destinationId`, via an undoable edit. `'chain'` takes 1-8 `inserts` and is the only mode that does; a destination no track references is stored and read back all the same. Refused: an insert of the wrong shape (`TypeError`), an out-of-range part, an unknown mode or processor, or inserts on a non-chain mode (`RangeError`), and an insert chain in a build without mastering (`NotSupported`).
  partRig(key: PartRigKey): PartRigEntry | null;  // The stored rig for `key`, or null when none is stored.
  clearPartRig(key: PartRigKey): void;  // Remove the stored rig for `key` via an undoable edit (no-op when absent).
  setTrackMute(trackId: number, mute: boolean): void;  // Set a track's mute flag via an undoable edit (a muted track is silent).
  setTrackSolo(trackId: number, solo: boolean): void;  // Set a track's solo flag via an undoable edit (when any track is soloed, only soloed tracks sound).
  // Set a track's stereo balance in [-1, +1] (0 = center) via an undoable edit.
  //
  // See setTrackGain for which stage a track's controls land on. The pan law that shapes the balance belongs to that stage: the strip's configured law on a channel strip and on the clips of an audio track sharing a strip, and the track lane's law for a MIDI track sharing a strip (the law of whatever strip the host bound to that lane, or a linear balance when none is bound). Every law is normalized so a centered track stays at unity and only the away channel is attenuated, so the difference is a taper, not a level offset.
  setTrackPan(trackId: number, pan: number): void;
  undo(): void;  // Undo the most recent edit.
  redo(): void;  // Redo the most recently undone edit.
  clearHistory(): void;  // Clear the undo/redo history without changing the current project state.
  setMaxUndoDepth(depth: number): void;  // Cap the undo history depth; evicts oldest entries beyond the cap.
  setMaxHistoryBytes(bytes: number): void;  // Set the combined undo/redo history byte cap. Zero disables retention.
  // Replace a MIDI clip's entire event list.
  //
  // Each event is `{ ppq, word0, word1?, sysex? }`; SysEx bytes are copied into the project and can be read back with midiEvents.
  //
  // Only events inside the clip's half-open window `[0, lengthPpq)` (after the source offset) are kept for export; a note still sounding at the clip end, including one whose note-off sits at or past `lengthPpq`, is closed with a note-off at the clip end.
  setMidiEvents(clipId: number, events: ReadonlyArray<ProjectMidiEvent>): void;
  midiEvents(clipId: number): ProjectMidiEvent[];  // Read MIDI events in stable PPQ order, including fresh bytes for each SysEx payload.
  importSmf(data: Uint8Array): number;  // Import an in-memory SMF buffer; returns the first added clip id. Malformed or partially truncated tracks are rejected instead of installing a silently shortened clip.
  exportSmf(): Uint8Array<ArrayBuffer>;  // Export the project's tempo map + MIDI clips to an SMF byte buffer.
  importClipFile(data: Uint8Array): number;  // Import a MIDI 2.0 Clip File (`SMF2CLIP`); returns the first added clip id. Unlike importSmf, MIDI 2.0 channel-voice messages (16-bit velocity, 32-bit CC, per-note / registered controllers, bank-valid Program Change) survive without loss.
  exportClipFile(): Uint8Array<ArrayBuffer>;  // Export the project's tempo map + MIDI clips to a MIDI 2.0 Clip File (`SMF2CLIP`) byte buffer. MIDI 2.0-only events are written without loss — prefer this over exportSmf when MIDI 2.0 fidelity matters.
  setProgram(clipId: number, program: number, options?: ProjectProgramOptions): void;  // Set a MIDI clip's program at source PPQ 0 on one UMP group and channel (both default to 0). Pass `options.bank` to emit a Bank Select; omit it for none.
  bakeMidiFx(request: ProjectMidiFxBakeRequest): ProjectMidiFxBakeResult;  // Destructively bake a MIDI-FX chain into all stored events. Large clips are drained without truncation; failure leaves the original clip unchanged. Setting `withSourceIndex` also returns per-event provenance, so a selection or an editorial annotation can be carried across the bake.
  previewMidiFxCount(request: ProjectMidiFxPreviewRequest): number;  // Count the events bakeMidiFx would produce for this clip and configuration, without mutating the project. The transform is deterministic, so the count matches what the bake goes on to produce.
  validateMidiNotes(clipId: number): ProjectNotePairValidation;  // Pre-flight check for hanging / unmatched notes in a MIDI clip: reports whether every note-on in the exported half-open playback window `[0, lengthPpq)` has a matching note-off (FIFO per group+channel+note). A note still sounding at the clip end is closed there by export, so it validates as paired. Useful before bouncing to catch a stuck note. Throws if `clipId` is unknown or not a MIDI clip.
  // Transcribe mono audio straight into a MIDI clip's event list, **replacing** whatever it held — exactly as setMidiEvents does.
  //
  // The PPQ grid is this project's own tempo map, which is why there is no `tempoBpm` field: a project whose tempo was installed by autoTempo transcribes onto that map rather than onto a second, separately detected tempo. Use the standalone `transcribe` when you want events without a project.
  //
  // Quantizing, tempo detection and key/chord annotation are not done here — see `transcribe` for what each belongs to.
  transcribeToClip(request: ProjectTranscribeRequest): number;
  analyzeTempo(
    samples: Float32Array,
    sampleRate: number,
    options?: ProjectTempoOptions,
  ): ProjectTempoCandidate[];  // Return ranked tempo-octave and detected-meter candidates without editing. Takes `(samples, sampleRate, options?)` or one request object.
  analyzeTempo(request: ProjectAnalyzeTempoRequest): ProjectTempoCandidate[];
  autoTempo(
    samples: Float32Array,
    sampleRate: number,
    options?: ProjectAutoTempoOptions,
  ): ProjectAutoTempoResult;  // Detect and install a ranked tempo candidate; optionally apply the detected meter. Takes `(samples, sampleRate, options?)` or one request object.
  autoTempo(request: ProjectAutoTempoRequest): ProjectAutoTempoResult;
  snapToGrid(ppq: number, strength?: number, division?: number): number;  // Snap `ppq` (in [0, 1e12]) to a bar (`division=0`), beat (`1`), or beat subdivision (`2+`).
  compile(options?: ProjectCompileOptions): ProjectCompileResult;  // Compile the project, surfacing diagnostics. With `{ withTimeline: true }` the result also carries `timeline`: a ProjectTimeline to install with `RealtimeEngine.applyProjectTimeline`, absent when an error diagnostic means nothing compiled.
  // Compile + render the project offline to planar float audio. MIDI tracks render silently unless an instrument kind is bound through the options: `builtinInstruments`, `synthInstruments`, `sf2Instruments` and `instruments`. Each is an array of `{ destinationId?, instrument }` pairs (`destinationId` omitted is destination `0`); an empty array binds nothing. A destination bound twice, within one kind or across kinds, is refused with a `RangeError`.
  //
  // - `builtinInstruments`: BuiltinSynthConfig oscillator synth. A bare config without an `instrument` key is refused by name. - `synthInstruments`: patch-driven NativeSynth (SynthPatch; name a catalog preset through its `preset` field, see synthPresetNames). With `useGmPrograms` enabled, MIDI program changes select the matching General MIDI voice while the patch remains the fallback. An `engineMode: 'sample'` patch reads its PCM from the SampleBank passed as `sampleBank`; the bank must still be alive when the bounce runs. - `sf2Instruments`: GS-compatible SoundFont player fed by the project's default SoundFont or by the binding's `soundFontUri`. Programs the SoundFont does not cover play through the built-in GM fallback bank. - `instruments`: ExternalInstruments you implement in JavaScript. Every callback runs synchronously while this method is blocked, so a callback returning a Promise is refused with a `TypeError`. A callback that throws stops all further callbacks, and the bounce rethrows that first error once it returns (a native failure is reported ahead of it). While the bounce runs, using this project from inside a callback throws `InvalidState`. One instrument shared by tracks that feed different channel strips throws a `SonareError` with `NOT_SUPPORTED`.
  //
  // When `totalFrames` is omitted the render length is derived from the arrangement (plus the instruments' release tail), so a project with content renders without computing a frame count; an empty project yields no frames. `countInBars` prepends silent pre-roll at the initial tempo and meter. A click is mixed after the master only when `metronome.enabled` is `true`. The result is at the project sample rate; a bounce is never resampled.
  bounce(options?: ProjectBounceOptions): ProjectBounceResult;
  loadSoundFont(data: Uint8Array, options?: ProjectSoundFontOptions): void;  // Load SoundFont 2 bytes, replacing the SoundFont at the selected URI. Omit `uri` to select the default. Malformed input leaves the previous font in place.
  clearSoundFont(options?: ProjectSoundFontOptions): void;  // Release the selected SoundFont. Omit `uri` to clear the default SoundFont.
  soundFontPresetCount(options?: ProjectSoundFontOptions): number;  // Number of presets in the selected SoundFont, or zero if it is unloaded.
  soundFontManifest(options?: ProjectSoundFontOptions): Sf2ProgramStatus[];  // Report the SoundFont or synth fallback selected for each played MIDI program.
  removeClip(clipId: number): void;  // Remove a clip (undoable).
  setClipGain(clipId: number, gain: number): void;  // Set a clip's linear playback gain (>= 0; undoable).
  setClipFade(clipId: number, input: ProjectClipFadeInput): void;  // Set a clip's fade-in / fade-out regions from one object whose lengths carry their unit (undoable).
  unresolvedAudioSourceIds(): number[];  // Audio source ids that need decoded PCM after deserialization.
  addAudioSource(uri: string): number;  // Add an unresolved audio source and return its new stable id.
  relinkSource(sourceId: number, uri: string): number;  // Replace an audio source's URI while retaining and returning its stable id.
  unresolvedAudioSources(): ProjectSource[];  // Unresolved audio source descriptors, in the order of unresolvedAudioSourceIds; `nameOrUri` is the full URI.
  setSourceAudio(input: ProjectSourceAudioInput): void;  // Register decoded planar PCM for an existing audio source (undoable).
  setAudioSourceMetadata(input: ProjectAudioSourceMetadataInput): void;  // Replace an audio source's metadata strings as one undoable edit; an omitted string is cleared.
  setClipTakes(
    clipId: number,
    takes: ReadonlyArray<ProjectClipTake>,
    options?: ProjectClipTakesOptions,
  ): void;  // Replace a clip's take list (undoable). `options.activeTakeId` names the take that plays; omit it for the clip's base source.
  setClipCompSegments(clipId: number, segments: ReadonlyArray<ProjectClipCompSegment>): void;  // Replace a clip's comp segments (undoable).
  setClipLoop(clipId: number, input: ProjectClipLoopInput): void;  // Set a clip's loop mode and loop length in PPQ (undoable). `loopCrossfadePpq` is an equal-power crossfade at the loop seam (PPQ, finite and >= 0); omit it for a hard loop. The engine clamps it to the clip's pre-roll and half the loop.
  setClipSource(clipId: number, sourceId: number): void;  // Rebind a clip to a different (already-registered) source (undoable).
  duplicateClip(clipId: number, newStartPpq: number): number;  // Duplicate a clip at `newStartPpq` (in [0, 1e12]; same track); returns the new clip id.
  removeTrack(trackId: number): void;  // Remove a track and its clips (undoable).
  renameTrack(trackId: number, name: string): void;  // Rename a track (undoable).
  setTrackRoute(trackId: number, channelStripRef?: string, outputTarget?: string): void;  // Set a track's mixer-strip binding and output target. Omit either field to clear it.
  addAutomationLane(trackId: number, desc: ProjectAutomationLaneDesc): number;  // Append an automation lane; returns its stable lane id (undoable).
  editAutomationLane(trackId: number, laneId: number, desc: ProjectAutomationLaneEditDesc): void;  // Replace the lane identified by its stable lane id (undoable).
  removeAutomationLane(trackId: number, laneId: number): void;  // Remove the lane identified by its stable lane id (undoable).
  automationLanes(): ProjectAutomationLane[];  // Stored automation lanes sorted by track and target identity.
  annotateKeys(keys: ReadonlyArray<ProjectKeySegment>): void;  // Replace the project's key annotation stream (undoable).
  keyAnnotations(): ProjectKeySegment[];  // Read stored key annotations in project order.
  annotateChords(chords: ReadonlyArray<ProjectChordSymbol>): void;  // Replace the project's chord-symbol annotation stream (undoable).
  chordAnnotations(): ProjectChordSymbol[];  // Read stored chord annotations in project order.
  annotateSections(sections: ReadonlyArray<ProjectSection>): void;  // Replace the project's labeled section annotations (undoable). Sections may overlap.
  sectionAnnotations(): ProjectSection[];  // Read the stored labeled section annotations in project order.
  setAssistSidecar(sidecar: ProjectAssistSidecarInput): void;  // Add or update an opaque assist sidecar via an undoable edit.
  assistSidecars(): ProjectAssistSidecar[];  // Every stored assist sidecar, in stable project order.
  setOverlapPolicy(policy: ProjectOverlapPolicy): void;  // Set the project's clip-overlap policy.
  get overlapPolicy(): ProjectOverlapPolicy;  // The project's clip-overlap policy.
  get sampleRate(): number;  // The project sample rate in Hz.
  countInFrames(countInBars: number): number;  // Count pre-roll frames at the initial tempo and meter using the project rate.
  setMixerScene(scene?: MixSceneDocumentInput): void;  // Replace the project's mixer scene, or clear it by omitting the scene.
  mixerScene(): MixSceneDocument | undefined;  // The typed mixer scene stored on the project, or `undefined` when none is set.
  unresolvedSoundFontUris(): string[];  // Unresolved SoundFont URIs, copied from the project reader.
  setMarker(input: ProjectMarkerInput): number;  // Add or replace a marker. Omit `id` to allocate a new marker; an explicit `0` is refused. Returns the stable marker id.
  markers(): ProjectMarker[];  // Every marker, in stored order.
  tracks(): ProjectTrack[];  // Every track, in stored order.
  clips(): ProjectClip[];  // Every clip, in stored order.
  sources(): ProjectSource[];  // Every audio and MIDI source, in stored order.
  tempoSegments(): ProjectTempoSegment[];  // The tempo map, in the shape setTempoSegments accepts.
  timeSignatures(): ProjectTimeSignatureSegment[];  // The time-signature map, in the shape setTimeSignatures accepts.
  ppqToSec(ppq: number): number;  // Convert a PPQ position in [0, 1e12] to seconds from PPQ zero.
  secToPpq(sec: number): number;  // Convert seconds from PPQ zero to PPQ in [0, 1e12].
  positionAtPpq(ppq: number): ProjectPosition;  // Read the effective tempo, meter, bar and beat at a PPQ position in [0, 1e12].
  barStartPpq(barIndex: number): number;  // Read the PPQ start of a zero-based bar whose index is a safe integer.
  endPpq(): number;  // Read the end in PPQ of the last clip with a valid source and range on an audible track. A track is audible when unmuted and, if any track is soloed, soloed itself. Returns zero when no clip qualifies. Render tails are excluded.
  setTempoSegments(segments: ReadonlyArray<ProjectTempoSegment>): void;  // Replace the project's tempo map with the given segments.
  setTimeSignatures(segments: ReadonlyArray<ProjectTimeSignatureSegment>): void;  // Replace the project's time-signature map with the given segments.
  // Compile diagnostics produced by the most recent successful bounce on this project (e.g. MIDI clips rendering silently without a bound instrument).
  //
  // `undefined` before any bounce succeeds. A clean bounce returns a result with empty diagnostics; a compile failure leaves the last successful result.
  lastBounceCompileResult(): ProjectCompileResult | undefined;
  destroy(): void;  // Release the underlying WASM object. Idempotent, as the Node facade is. Called from a rehydrate cancel callback, the release happens when the outermost rehydrateVocalEdits call returns.
  [Symbol.dispose](): void;  // Releases the handle through destroy, so the instance works with `using`.
}

Project-facing API notes: Both autoTempo(samples, sampleRate, options?) and autoTempo(request) return { bpm, bpmConfidence, timeSignature }; the result includes the detected meter even when applyTimeSignatures is false. analyzeTempo(samples, sampleRate, options?) and analyzeTempo(request) return ranked candidates without editing the project. tempoSegments() and timeSignatures() return the stored arrays as-is; empty lists remain empty and do not materialize effective defaults. setMixerScene(scene?) takes a typed scene object and clears the scene when omitted. Project SoundFont methods take an optional { uri }, soundFontPresetCount({ uri }?) is a method, and an SF2 bounce binding can select a loaded font with soundFontUri. Omit a route string in setTrackRoute to clear that route; supplied strings must be nonempty. Omit an absent chord's romanNumeral; an explicit empty string is refused. setPartRig takes one PartRigRequest object whose part is required; use PART_RIG_ALL_PARTS for the destination default. setMaxUndoDepth(depth) accepts an integer in [1, 500000000] and refuses values outside the range with RangeError rather than clamping them.

ProjectTimeline ​

typescript
class ProjectTimeline {
  destroy(): void;  // Release the underlying WASM object. Idempotent.
  [Symbol.dispose](): void;  // Releases the timeline through destroy, so the instance works with `using`.
}

Vocal edit sessions ​

A session holds the analysed notes, a committed revision and the undo history; a draft is one edit transaction against the committed revision, and a snapshot or job renders a committed revision. Offline Vocal Editing walks through the flow.

typescript
function createVocalEditSession(request: VocalCreateRequest): VocalEditSession

function restoreVocalEditSession(request: VocalRestoreRequest): VocalEditSession

class VocalEditSession {
  destroy(): void;  // Releases the session and every draft it began; calling it again does nothing.
  [Symbol.dispose](): void;  // Releases the handle through destroy, so the instance works with `using`.
  get token(): VocalStateToken;  // The current committed state token.
  get revision(): string;  // The committed revision, a decimal string (64-bit counter).
  notes(): VocalNotesResult;  // The committed notes and transitions.
  analysis(): VocalAnalysis;  // The pitch analysis the session was built from.
  capabilities(): VocalCapabilities;  // What the loaded engine supports.
  get outputLengthSamples(): number;  // Length of the rendered output in samples.
  history(): VocalHistory;  // Whether undo and redo have anything to act on.
  beginEdit(options?: VocalRevisionOptions): VocalEditDraft;  // Opens a draft for batching edits. `expectedRevision` defaults to the current revision; a mismatch is refused with a `revisionConflict` detail.
  undo(options?: VocalRevisionOptions): VocalEditResult;  // Reverts the last commit. `expectedRevision` defaults to the current revision.
  redo(options?: VocalRevisionOptions): VocalEditResult;  // Re-applies the last undone commit. `expectedRevision` defaults to the current revision.
  evaluatePitch(noteId: number): VocalPitchEvaluation;  // Per-frame pitch of one committed note.
  sourceSampleToDestinationSample(noteId: number, sourceSample: number): number;  // Maps a source sample of a note to its position in the output.
  destinationSampleToSourceSample(noteId: number, destinationSample: number): number;  // Maps an output sample of a note back to its source position.
  captureRenderSnapshot(): VocalRenderSnapshot;  // Freezes the committed state for rendering; the snapshot is unaffected by later edits.
  exportState(): Uint8Array;  // Serialises the edit state; pass it to restoreVocalEditSession with the same source PCM.
  _forgetDraft(draft: VocalEditDraft): void;
}

class VocalEditDraft {
  get token(): VocalStateToken;  // The draft's current state token.
  get revision(): string;  // The committed revision the draft was begun from, a decimal string (64-bit counter).
  notes(): VocalNotesResult;  // The draft's notes and transitions, including uncommitted edits.
  apply(request: VocalApplyRequest): VocalEditResult;  // Applies the operations as one batch. Omitting `expectedGeneration` uses the draft's current generation.
  commit(options?: VocalRevisionOptions): VocalEditResult;  // Commits the draft and releases it. `expectedRevision` defaults to the revision the draft was begun from.
  cancel(): void;  // Discards the draft and releases it.
  evaluatePitch(noteId: number): VocalPitchEvaluation;  // Per-frame pitch of one note including uncommitted edits.
  sourceSampleToDestinationSample(noteId: number, sourceSample: number): number;  // Maps a source sample of a note to its position in the output, including uncommitted edits.
  destinationSampleToSourceSample(noteId: number, destinationSample: number): number;  // Maps an output sample of a note back to its source position, including uncommitted edits.
  captureRenderSnapshot(): VocalRenderSnapshot;  // Freezes the draft state for rendering.
  destroy(): void;  // Releases the draft without committing it; calling it again does nothing.
  [Symbol.dispose](): void;  // Releases the handle through destroy, so the instance works with `using`.
}

class VocalRenderSnapshot {
  get outputLengthSamples(): number;  // Length of the rendered output in samples.
  render(request: VocalRenderRequest): VocalRenderResult;  // Renders the requested range synchronously.
  beginRenderJob(request: VocalRenderJobRequest): VocalRenderJob;  // Starts an incremental render that the caller advances with VocalRenderJob.next.
  renderAsync(request: VocalRenderAsyncRequest): Promise<VocalRenderResult>;  // Render one native work unit per macrotask so `request.signal` can stop the job between units. A cancelled job publishes no partial PCM. Every failure rejects: an aborted signal, before or during the render, with a `Cancelled` SonareError.
  destroy(): void;  // Releases the snapshot; calling it again does nothing.
  [Symbol.dispose](): void;  // Releases the handle through destroy, so the instance works with `using`.
}

class VocalRenderJob {
  next(): VocalJobProgress;  // Runs one work unit and reports whether the job is ready to finalise.
  finalize(): VocalRenderResult;  // Collects the rendered PCM and releases the job.
  abort(): void;  // Stops the job; no partial PCM is published.
  destroy(): void;  // Releases the job; calling it again does nothing.
  [Symbol.dispose](): void;  // Releases the handle through destroy, so the instance works with `using`.
}

Worker client ​

typescript
class VocalEditWorkerClient {
  constructor(options?: VocalEditWorkerClientOptions);  // Starts a Worker, or adopts the one in `options.worker`.
  create(
    request: VocalCreateRequest,
    options?: VocalEditWorkerCallOptions,
  ): Promise<VocalEditWorkerSession>;  // Analyses mono PCM in the Worker and opens an editing session.
  restore(
    request: VocalRestoreRequest,
    options?: VocalEditWorkerCallOptions,
  ): Promise<VocalEditWorkerSession>;  // Opens a session in the Worker from an exported state blob and the same source PCM.
  destroy(): Promise<void>;  // Stop accepting calls, cancel outstanding work (rejected with `InvalidState`), release every open session, and terminate the Worker when this client owns it. Resolves once the Worker has acknowledged the release of every session; a second call returns the same promise.
  [Symbol.asyncDispose](): Promise<void>;  // Same as destroy, for `await using`.
}

class VocalEditWorkerSession {
  readonly sessionId: string;  // Identifier of the session inside the Worker.
  readonly created: VocalEditWorkerCreated;  // What the Worker reported when it opened the session.
  get token(): VocalStateToken;  // The committed token as of the last reply the client received.
  get revision(): string;  // The committed revision, a decimal string (64-bit counter); follows replies already received.
  notes(): Promise<VocalNotesResult>;  // The committed notes and transitions.
  analysis(): Promise<VocalAnalysis>;  // The pitch analysis the session was built from.
  capabilities(): Promise<VocalCapabilities>;  // What the loaded engine supports.
  outputLengthSamples(): Promise<number>;  // Length of the rendered output in samples; a round trip to the Worker.
  history(): Promise<VocalHistory>;  // Whether undo and redo have anything to act on.
  evaluatePitch(noteId: number): Promise<VocalPitchEvaluation>;  // Per-frame pitch of one committed note.
  sourceSampleToDestinationSample(noteId: number, sourceSample: number): Promise<number>;  // Maps a source sample of a note to its position in the output.
  destinationSampleToSourceSample(noteId: number, destinationSample: number): Promise<number>;  // Maps an output sample of a note back to its source position.
  beginEdit(options?: VocalRevisionOptions): Promise<VocalEditWorkerDraft>;  // Opens a draft for batching edits. `expectedRevision` defaults to the revision the client last saw; a mismatch is refused with a `revisionConflict` detail.
  undo(options?: VocalRevisionOptions): Promise<VocalEditResult>;  // Reverts the last commit. `expectedRevision` defaults to the current revision.
  redo(options?: VocalRevisionOptions): Promise<VocalEditResult>;  // Re-applies the last undone commit. `expectedRevision` defaults to the current revision.
  exportState(): Promise<Uint8Array>;  // Serialises the edit state; pass it to VocalEditWorkerClient.restore with the same source PCM.
  preview(
    request: VocalRenderAsyncRequest,
    options?: VocalEditWorkerTransferOptions,
  ): Promise<VocalRenderResult>;  // Renders in the Worker: the open draft when there is one, otherwise the committed state. A newer preview supersedes an older one, which then rejects with a `StaleResult` error; `request.signal` aborts with a `Cancelled` error.
  destroy(): Promise<void>;  // Releases the Worker session and any open draft, resolving once the Worker has acknowledged it; later calls on the session are rejected. A second call returns the same promise.
  [Symbol.asyncDispose](): Promise<void>;  // Same as destroy, for `await using`.
}

class VocalEditWorkerDraft {
  get token(): VocalStateToken;  // The draft's token as of the last reply the client received.
  get revision(): string;  // The revision the draft was begun from, a decimal string (64-bit counter).
  notes(): Promise<VocalNotesResult>;  // The draft's notes and transitions, including uncommitted edits.
  apply(
    request: VocalApplyRequest,
    options?: VocalEditWorkerTransferOptions,
  ): Promise<VocalEditResult>;  // Applies the operations as one batch. Omitting `expectedGeneration` uses the generation the draft last reported.
  commit(options?: VocalRevisionOptions): Promise<VocalEditResult>;  // Commits the draft and releases it. `expectedRevision` defaults to the session's revision.
  cancel(): Promise<void>;  // Discards the draft and releases it.
  evaluatePitch(noteId: number): Promise<VocalPitchEvaluation>;  // Per-frame pitch of one note including uncommitted edits.
  sourceSampleToDestinationSample(noteId: number, sourceSample: number): Promise<number>;  // Maps a source sample of a note to its position in the output, including uncommitted edits.
  destinationSampleToSourceSample(noteId: number, destinationSample: number): Promise<number>;  // Maps an output sample of a note back to its source position, including uncommitted edits.
  preview(
    request: VocalRenderAsyncRequest,
    options?: VocalEditWorkerTransferOptions,
  ): Promise<VocalRenderResult>;  // Renders the draft in the Worker. A newer preview supersedes an older one, which then rejects with a `StaleResult` error; `request.signal` aborts with a `Cancelled` error.
  destroy(): Promise<void>;  // Discards the draft if it is still open and resolves once the Worker has acknowledged it; a draft already committed, cancelled or released with its session resolves at once. A second call returns the same promise.
  [Symbol.asyncDispose](): Promise<void>;  // Same as destroy, for `await using`.
}