API Reference
This page documents the public API for each Motif package. All packages are published under the @motif scope on npm.
@motif/schema
Section titled “@motif/schema”Canonical types, Zod 4 schemas, and validation utilities. Every other package imports types from here.
Key Types
Section titled “Key Types”| Type | Description |
|---|---|
SoundtrackPack | The complete authoring document containing all entities |
AudioAsset | A file reference with kind (loop, oneshot, stinger, ambient), duration, BPM, key, tags |
Stem | A playable layer bound to an asset with a role (base, danger, combat, boss, recovery, mystery, faction, accent) |
Scene | A named musical state with stem layers and optional clip layers |
TriggerBinding | A rule mapping runtime state to a scene with priority |
TriggerCondition | A comparison: field, operator (eq, neq, gt, gte, lt, lte, includes), value |
TransitionRule | How music moves between scenes: immediate, crossfade, bar-sync, stinger-then-switch, cooldown-fade |
Clip | A composed musical idea with notes, lane, instrument, BPM, and optional variants |
ClipNote | A single note event: pitch (MIDI 0—127), startTick (480 ticks/beat), durationTicks, velocity |
Cue | A composed piece with ordered sections, tempo, key, and time signature |
CueSection | A structural section with role (intro, body, escalation, climax, outro, transition), duration in bars, and optional scene/clip/intensity overrides |
RuntimeMusicState | Game state shape for trigger evaluation (mode, danger, inCombat, boss, region, faction, etc.) |
Validation
Section titled “Validation”parseSoundtrackPack(data)— Parse and validate a full authoring packparseAudioAsset(data)— Parse a single audio assetvalidatePack(data)— ReturnsValidationResult<SoundtrackPack>withok,data, andissues
@motif/clip-engine
Section titled “@motif/clip-engine”Clip sequencing, 30+ composition transforms, and cue scheduling.
Clip Playback
Section titled “Clip Playback”ClipPlayer— Manages clip playback state and schedulingSceneClipPlayer— Plays clips within a scene contextresolveClipNotes(clip, variantId?)— Resolve the active notes for a clip, using variant if specifiedfilterByIntensity(refs, level)— Filter scene clip refs by intensity tiersortByOrder(refs)— Sort clip refs by playback order
Scheduling
Section titled “Scheduling”scheduleNotes(notes, bpm, startTime)— Convert clip notes to scheduled audio eventsclipLengthSeconds(clip)— Clip duration in seconds based on BPM and lengthBeatsquantizedLaunchTime(time, clip, mode)— Snap a launch time to beat/bar grid
Composition Transforms
Section titled “Composition Transforms”All transforms are pure functions that return new clip objects:
| Transform | Description |
|---|---|
clipTranspose(clip, semitones) | Shift all notes by semitones |
clipTransposeInKey(clip, degrees) | Shift within the clip’s scale |
clipInvert(clip) | Mirror intervals around a center |
clipReverse(clip) | Reverse note order |
clipOctaveShift(clip, octaves) | Shift by octaves |
clipRhythmScale(clip, factor) | Scale note durations |
clipSnapToScale(clip) | Quantize pitches to the clip’s scale |
clipFindOutOfScale(clip) | Identify notes outside the scale |
clipRhythmicVariation(clip) | Randomized rhythmic displacement |
clipMelodicVariation(clip) | Randomized melodic displacement |
clipThinNotes(clip) | Remove low-velocity notes |
clipDensifyNotes(clip) | Fill gaps with new notes |
clipAccentEveryN(clip, n) | Boost velocity on every Nth note |
clipAddGhostHits(clip) | Add quiet ghost notes |
clipRemoveGhostHits(clip) | Strip ghost notes |
clipDeriveIntensity(clip, level) | Generate intensity variant |
clipAddTension(clip) | Add dissonance |
clipBrighten(clip) | Shift toward upper register |
clipPadVoicing(clip) | Expand into pad-style voicing |
clipBassLine(clip) | Derive a bass pattern |
clipArpeggiate(clip) | Convert chords to arpeggios |
createTransformedVariant(clip, transform) | Create a named variant from a transform |
Chord and Scale Tools
Section titled “Chord and Scale Tools”chordPalette(root, scale)— All diatonic chords in a scalediatonicChords(root, scale, count)— Generate chord progressionprogressionFromDegrees(root, scale, degrees)— Chords from Roman numeral degrees
Cue Scheduling
Section titled “Cue Scheduling”resolveCuePlan(cue, pack)— Resolve a cue into a timed playback plansectionAtTick(plan, tick)— Find the active section at a given ticksectionAtBar(plan, bar)— Find the active section at a given barcreateCaptureEvent(tick, bar, beat, action, opts?)— Create a performance capture eventticksPerBar(cue)— Ticks per bar for a cue’s time signature
Constants
Section titled “Constants”TICKS_PER_BEAT= 480TICKS_PER_16TH= 120TICKS_PER_8TH= 240
@motif/scene-mapper
Section titled “@motif/scene-mapper”Trigger evaluation and deterministic scene resolution.
evaluateCondition(condition, state)— Test a single trigger condition against runtime stateevaluateBinding(binding, state)— Test all conditions in a bindingevaluateBindings(pack, state)— Evaluate all bindings in a packresolveScene(pack, state)— Resolve the winning scene: highest priority among matched bindings, pack order as tie-breaker
@motif/runtime-pack
Section titled “@motif/runtime-pack”Export and import runtime packs for game engines.
exportRuntimePack(pack)— Strip an authoring pack to runtime-only data (scenes, bindings, transitions, stems, assets)parseRuntimePack(data)— Parse and validate a runtime pack (throws on failure)safeParseRuntimePack(data)— Parse with structured error reportingvalidateRuntimePack(data)— Returns validation issues without throwingserializeRuntimePack(pack)— Deterministic JSON serializationroundTripRuntimePack(pack)— Export, serialize, parse, validate in one call
@motif/sample-lab
Section titled “@motif/sample-lab”Audio import, trimming, slicing, kit building, and sample instrument creation.
Import
Section titled “Import”buildImportedAsset(filename, durationMs, src)— Create an AudioAsset from file metadata (infers source type and kind from filename)inferSourceType(name)— Detect source type from filename patterns (drums, tonal, ambience, stinger, texture, fx)sourceTypeToKind(sourceType)— Map source type to asset kindfilenameToId(filename)— Sanitize filename to kebab-case ID
applyTrim(asset, startMs, endMs)— Set non-destructive trim regionapplyLoopPoints(asset, loopStartMs, loopEndMs)— Set loop region within an asset
sliceEvenly(assetId, startMs, endMs, count)— Divide a region into equal slicessliceAtOnsets(assetId, onsets, totalEndMs)— Slice at specific time points
Kit and Instrument
Section titled “Kit and Instrument”kitFromSlices(id, name, slices, basePitch)— Build a sample kit from slices, mapping to ascending MIDI pitchescreateSampleInstrument(id, name, assetId, rootNote, pitchMin, pitchMax)— Create a pitched instrument from a single audio source
@motif/automation
Section titled “@motif/automation”Automation lanes, macros, envelopes, and live capture.
createLane(id, name, param, target)— Create a new automation laneaddPoint(lane, point)— Add a keyframe (sorted by time)removePointAt(lane, timeMs, toleranceMs?)— Remove point near a timeupdatePoint(lane, index, update)— Update a point’s value or curveclearLane(lane)— Remove all pointslanesForTarget(lanes, targetId)— Filter lanes by targetlanesForParam(lanes, param)— Filter lanes by parameter
Interpolation
Section titled “Interpolation”evaluateLane(lane, timeMs)— Get interpolated value at any timeinterpolate(from, to, t, curve)— Raw interpolation with curve type (linear,exponential,step,smooth)sampleLane(lane, startMs, endMs, stepMs)— Sample lane at regular intervalsevaluateLanesAt(lanes, targetId, timeMs)— Evaluate all lanes for a target, returns Map of param to value
Macros
Section titled “Macros”defaultMacroState()— Default state with all macros at 0.5createMacroMapping(id, macro, param, weight, opts?)— Create a mapping from macro to parameterevaluateMacros(state, mappings, targetId?)— Get parameter influences from macro stateapplyMacroInfluence(baseValue, influence)— Apply influence, clamped to 0—1
Envelopes
Section titled “Envelopes”createEnvelope(id, targetId, shape, durationMs, position, depth?)— Create a section envelopeevaluateEnvelope(envelope, offsetMs)— Get gain value at a time offset- Shapes:
fade-in,fade-out,swell,duck,filter-rise,filter-fall - Positions:
entryorexit
Capture
Section titled “Capture”createCapture(id, name, source)— Start a capture session (source is aMacroParamorAutomationParam)recordPoint(capture, timeMs, value)— Record a single pointfinalizeCapture(capture, laneId?)— Sort points and optionally link to a laneapplyCaptureToLane(capture, lane)— Replace lane points with captured datamergeCaptureIntoLane(capture, lane)— Merge captured points into existing lanethinCapture(capture, toleranceMs)— Reduce point density
@motif/library
Section titled “@motif/library”Templates, snapshots, branches, favorites, and entity comparison.
Templates
Section titled “Templates”createTemplate(id, name, kind, data, opts?)— Create a reusable template from entity datainstantiateTemplate(template, newId)— Produce new entity data with a fresh IDtemplatesOfKind(templates, kind)— Filter by entity kindsearchTemplates(templates, query)— Search by name or tag
Snapshots
Section titled “Snapshots”takeSnapshot(id, label, entityId, entityKind, data, notes?)— Freeze entity staterestoreSnapshot(snapshot)— Get a copy of the frozen datasnapshotsForEntity(snapshots, entityId)— All snapshots for an entitylatestSnapshot(snapshots, entityId)— Most recent snapshot
Branches
Section titled “Branches”createBranch(id, name, sourceSnapshot, newEntityId, notes?)— Fork from a snapshotinstantiateBranch(snapshot, branch)— Produce entity data for the branchtraceLineage(entityId, branches, snapshots)— Walk the full chain to the rootdescendantBranches(entityId, branches, snapshots)— All branches derived from an entity
Compare
Section titled “Compare”compareEntities(a, b, entityKind, labelA, labelB)— Field-by-field diff returningsame,changed,onlyA,onlyBareEqual(a, b)— Quick structural equality checkdiffCount(a, b)— Count of differing fields
@motif/score-map
Section titled “@motif/score-map”World scoring: motif families, score profiles, cue families, and derivation.
Derivation
Section titled “Derivation”createDerivation(id, sourceId, targetId, transform)— Record a derivationderiveScene(source, newId, transform)— Produce a new scene with a name suffixderivationChain(records, startId)— Walk the full derivation graphderivationsFrom(records, sourceId)— Find all derivations from a sourcederivationsTo(records, targetId)— Find all derivations targeting an entity- Transforms:
intensify,resolve,darken,brighten,simplify,elaborate,reharmonize
@motif/music-theory
Section titled “@motif/music-theory”Scales, chords, motifs, and intensity transforms used by the clip engine.
@motif/audio-engine
Section titled “@motif/audio-engine”Sample playback and voice management using the Web Audio API. Handles loading audio buffers, managing playback voices, and applying gain/pan per voice.
@motif/playback-engine
Section titled “@motif/playback-engine”Real-time mixing, effects (EQ, delay, reverb, compressor), stem bus routing, master gain, and WAV rendering via OfflineAudioContext.
@motif/instrument-rack
Section titled “@motif/instrument-rack”Synth and drum voice management with presets. Categories: drums, bass, pad, lead, pulse.
@motif/asset-index
Section titled “@motif/asset-index”Pack integrity indexing and auditing. Detects orphaned references, duplicate assets, and missing dependencies.
@motif/review
Section titled “@motif/review”Summaries and audit helpers for pack inspection.
@motif/test-kit
Section titled “@motif/test-kit”Fixtures and test utilities for writing tests against Motif packages.