JavaScript API Reference
Music terms in config
form, key, isMinor, character, scale, and targetBars map API values to musical decisions. For the non-programming vocabulary behind those fields, see the Music Primer for Engineers and Option Relationships.
Initialization
init(options?)
Loads and initializes the WASM module. Must be called before creating any BachGenerator instances.
import { init } from '@libraz/midi-sketch-bach'
await init()import { init } from '@libraz/midi-sketch-bach'
await init({ wasmPath: '/wasm/bach.wasm' })Parameters:
| Parameter | Type | Description |
|---|---|---|
options.wasmPath | string | Path to the .wasm file. Required in browser environments. |
Returns: Promise<void>
Safe to call concurrently
Overlapping init() calls share one in-flight load instead of instantiating the module twice, so you can call it from every entry point that needs the engine. Passing a different wasmPath while a load is still running throws.
BachGenerator
The main class for generating Bach-style compositions.
Constructor
const generator = new BachGenerator()Creates a new generator instance. Call init() before creating any instances.
generate(config?)
Generates a composition based on the provided configuration.
generator.generate({
form: 'fugue',
key: 2,
isMinor: true,
character: 'severe',
bpm: 80,
seed: 42
})Parameters: See BachConfig below.
Returns: void
Strict validation
Invalid form, key, character, instrument, or scale values — and out-of-range bpm (anything other than 0 or 40--200) — throw an error instead of silently falling back to a default. Forbidden character/form and instrument/form combinations (see Option Relationships) also throw.
Each failure carries its own error string after a Generation failed: prefix, for example Invalid BPM (must be 0 or 40-200) or Incompatible instrument for this form. When the composer itself fails its counterpoint validation, call getDiagnostic() for the rule-level detail. Every generate() call discards the previous result first, so after any failure the result getters throw (see what each getter returns after a call).
getMidi()
Returns the generated composition as Standard MIDI File data.
const midi = generator.getMidi()
// midi is a Uint8Array containing a valid .mid fileReturns: Uint8Array
getEvents()
Returns structured event data with metadata and individual note events.
const events = generator.getEvents()
console.log(events.form) // "fugue"
console.log(events.key) // "D_minor"
console.log(events.bpm) // 80
console.log(events.total_bars) // 44
console.log(events.tempos) // Tempo map
console.log(events.time_signatures) // Meter map
console.log(events.tracks) // Array of TrackDataEvent pitches match the MIDI output
getEvents() and getMidi() describe the same playback: output-key pitches and post-articulation durations. For the engine's internal pitches and notated durations, use getGenerated().
bpm alone will not place a note on the clock
events.bpm is only the starting tempo. Most forms add a final ritardando, but Trio Sonata does not. Prelude and Fugue, Toccata and Fugue, and Fantasia and Fugue also change tempo at the fugue entry. Walk the tempo map instead of assuming a constant tempo.
Returns: EventData
getGenerated()
Returns the generated.v1 document: a flat, index-addressable note list for scoring and analysis rather than playback.
const generated = generator.getGenerated()
console.log(generated.schema_version) // "generated.v1"
console.log(generated.ticks_per_beat) // 480
console.log(generated.notes[0])
// { index, start_tick, duration, pitch, voice, velocity }Returns: GeneratedData. Throws when the most recent generate() did not succeed.
getEvents() and getGenerated() describe the same notes in two coordinate systems:
getEvents() / getMidi() | getGenerated() / getProvenance() | |
|---|---|---|
| Pitch | Output key, plus any whole-octave shift for the instrument's range | Engine's internal C frame, before transposition |
duration | Playback gate after character articulation | Notated length captured before articulation; FinalScore validation and texture metrics use it |
| Layout | tracks[].notes[] | One flat notes array addressed by index |
| Note source | Optional source?, lowercase: "material", "compose", "ornament" | Not on the note; getProvenance() carries it in PascalCase: "Material", "Compose", "Ornament" |
generated.v1 fields
| Field | Presence | Content |
|---|---|---|
schema_version | always | "generated.v1" |
ticks_per_beat | always | 480 |
duration_ticks | always | Length of the piece in ticks |
tempos | optional in the type | Tempo map { tick, bpm }[]; every generate() result carries it |
notes | always | { index, start_tick, duration, pitch, voice, velocity }[] |
counterpoint_observations | always | One tally per rule that matched, sorted by rule_id; empty when nothing matched |
informational_findings | always | Findings kept as evidence without failing validation; may be empty |
wave_veto | always | Figuration-wave counters, all zero when no layer fired |
info | optional | Analysis blocks, each present only when non-empty (next table) |
The generated.v1 schema is the wire contract. The package exports GeneratedData and its element types, CounterpointObservation, InformationalFinding, WaveVeto, GeneratedInfo and RuleGeometry, so each can be imported by name.
info blocks, as emitted for a default request in each form:
| Block | Emitted by | Content |
|---|---|---|
subject_features | fugue, prelude_and_fugue, toccata_and_fugue, fantasia_and_fugue | Per subject: length, range_semitones, unique_pitch_classes, opening_interval, unique_intervals, max_leap |
stream_segregation | cello_prelude | Per span: detected and cell-based stream counts, stream_separation_semitones, transition_note_indices |
texture_metrics | all ten forms | max_active_voices, avg_active_voices, mono_ratio, compass_violation_count, register_overlap_ratio, and per-voice silence_ratio, max_repeated_run, min_pitch, max_pitch |
counterpoint_observations entries are { rule_id, geometry, total, gated, exempted }. geometry is linear for a melodic succession in one voice, vertical for a relation between simultaneous voices or the harmonic plan, and unclassified for a rule with no geometry entry. total is the match count before routing, gated counts findings routed to blocking validation failures, and exempted counts generation-pass findings suppressed because every operand is an immutable Material or Ornament source. For most rules total - gated - exempted is the number of informational findings; countersubject_invertible informational entries carry no tally.
informational_findings entries are { span_id, rule_id, geometry, kind } with a nullable span_id and a kind of StructuralFail, MusicalFail or ConfigFail. A form's counterpoint budget can still promote a matched closed vertical rule to a blocking failure; that failure has no span and does not change the tally.
wave_veto counts how often each reactive figuration-wave layer changed a note. total sums the six counters that changed a note; anchor_fault_held counts an unrepairable anchor fault that was left in place and is reported separately.
getProvenance()
Returns the provenance.v1 document: one record per generated note, index-parallel with getGenerated().notes, describing how that note was chosen.
const provenance = generator.getProvenance()
const note = provenance.notes[0]
console.log(note.voice_intent) // "SubjectCarrier"
console.log(note.source) // "Material" | "Compose" | "Ornament"
// Rule masks are decimal strings — parse them as BigInt, never as Number
const satisfied = BigInt(note.satisfied_rules)
const high = note.satisfied_rules_high ? BigInt(note.satisfied_rules_high) : 0nReturns: ProvenanceData. Throws when the most recent generate() did not succeed.
Each entry of notes is a ProvenanceNote:
| Field | Type | Content |
|---|---|---|
index | number | Position in getGenerated().notes |
span_id | number | null | Owning span, or null when there is none |
voice_intent | string | Role the voice plays at this note, such as "SubjectCarrier" or "FigurationCarrier" |
source | "Material" | "Compose" | "Ornament" | How the note was produced |
candidate_score | number | Candidate-search score of the chosen note |
rejected_alternatives | number | Candidates the search rejected for this note; 0 for authored material |
satisfied_rules | string | Rule bits 0--63 as a base-10 string |
satisfied_rules_high | string, optional | Rule bits 64--127; omitted when no high bit is set |
authored_note | { start_tick, duration, pitch }, optional | The carrier's note as authored, before the ornament pass subdivided it; only on notes that declare one |
shadow_score, shadow_winning_pitch, shadow_winning_pitch_without_markov | number, optional | Corpus-scorer audit, only on "Compose" notes. A shadow_winning_pitch that differs from the emitted pitch means the scorer disagreed with the committed choice |
Rule masks are strings
A JavaScript number cannot hold all 64 bits of a rule mask, so satisfied_rules and satisfied_rules_high are base-10 strings. Parse them with BigInt().
Bit 64, the first bit of satisfied_rules_high, marks countersubject membership only. Whether the countersubject is invertible is reported by the countersubject_invertible entry in getGenerated().informational_findings, not by a rule bit.
getDiagnostic()
Returns the diagnostic.v1 document from the most recent composer validation failure, or null when the last generation succeeded.
try {
generator.generate({ form: 'fugue', seed: 42 })
} catch {
const diagnostic = generator.getDiagnostic()
for (const failure of diagnostic?.validation.failures ?? []) {
console.log(failure.kind, failure.rule_id, failure.span_id)
}
}getDiagnostic() returns null after a successful generate(), after a configuration error, and before any generation. Read it in the catch branch when generation reports a composer or final-validation failure.
Returns: DiagnosticData | null
getInfo()
Returns the resolved settings of the most recent generation.
const info = generator.getInfo()
console.log(info.seedUsed) // resolved seed (non-zero, even when seed: 0 was requested)
console.log(info.totalBars) // resolved bar count
console.log(info.bpm) // actual BPM used
console.log(info.trackCount) // number of tracksWhen you pass seed: 0 (random), the actual seed chosen for this run is reported as getInfo().seedUsed. Reuse that value to reproduce the same output. getInfo().totalBars (or getEvents().total_bars) reports the length after snapping and clamping; targetBars is a request, not a guarantee.
Returns: BachInfo
What each getter returns after a call
Every generate() starts by discarding the previous result, so the table describes the instance after the latest call only.
| Latest call | getMidi(), getEvents(), getGenerated(), getProvenance() | getDiagnostic() | getInfo() |
|---|---|---|---|
No generate() yet | throw | null | throw |
| Success | data | null | all five fields |
| Configuration error (invalid value, forbidden pair, unknown instrument) | throw | null | throw |
| Composer or final validation failure | throw | diagnostic.v1 | seedUsed and bpm resolved; totalBars, totalTicks and trackCount are 0 |
| MIDI writer failure | throw | null | same as the row above |
A valid request is not expected to reach the last two rows. If one does, getInfo() still reports the seed a seed: 0 run drew, so you can pass it back to replay the failure.
destroy()
Frees WASM memory allocated by this generator. Always call this when done.
generator.destroy()WARNING
After calling destroy(), the generator instance must not be used again. Create a new BachGenerator if you need to generate another piece.
BachConfig
Configuration object passed to generate(). All fields are optional.
| Field | Type | Default | Description |
|---|---|---|---|
form | FormId | FormName | "fugue" | Musical form (0--9 or name). See Forms and Presets Reference. |
key | KeyId | KeyName | 0 | Key as a pitch class (0=C, 1=C#, 2=D, ... 11=B) or its canonical name ("C", "C#", "D", "Eb", "E", "F", "F#", "G", "Ab", "A", "Bb", "B"). |
isMinor | boolean | false | Minor key when true, major when false |
bpm | number | 100 | Starting tempo in BPM. 0 uses the default of 100; any other value must be in 40--200 (out of range throws). |
seed | number | 0 | Unsigned 32-bit random seed. 0 picks a random non-zero seed, reported via getInfo().seedUsed. |
character | CharacterId | CharacterName | "severe" | Subject character ("severe", "playful", "noble", "restless"). Matched exactly in lowercase; invalid value throws. |
instrument | InstrumentId | InstrumentName | Form default | Instrument ("organ", "harpsichord", "piano", "violin", "cello"). Must be one the form accepts, otherwise it throws. "guitar" is reserved and no form accepts it. |
scale | DurationScaleId | DurationScaleName | "short" | Length multiplier of the form's natural length: "short" (1x), "medium" (2x), "long" (3x), "full" (4x), then snapped and clamped. Invalid value throws. |
targetBars | number | -- | Integer 0--65535; larger values, negatives and fractions throw. 0 uses scale; a positive value overrides it, is rounded to the form's bar grid and clamped to [form minimum, 128], so 129 or 65535 simply give 128. See Option Relationships. |
Name strings are matched exactly
Form, key, character, instrument and scale names must match the canonical spelling: lowercase, except keys, which use their canonical case such as "Eb". "Fugue", "g", "FULL" and "Severe" all throw.
Voice count follows the form, unknown keys are dropped
BachConfig has no numVoices field: the form determines the voice count (see Forms). The JavaScript wrapper copies only the nine BachConfig fields into the request, so any other property, numVoices included, is silently dropped. The raw C JSON interface behaves differently: it rejects unknown keys with Unknown configuration field, and accepts num_voices only as an integer from 0 to 255, which it then ignores.
Form Values
Forms can be specified by number or name string:
| Number | String |
|---|---|
0 | "fugue" |
1 | "prelude_and_fugue" |
2 | "trio_sonata" |
3 | "chorale_prelude" |
4 | "toccata_and_fugue" |
5 | "passacaglia" |
6 | "fantasia_and_fugue" |
7 | "cello_prelude" |
8 | "chaconne" |
9 | "goldberg_variations" |
Instrument Values
| Number | String | Accepted by |
|---|---|---|
0 | "organ" | Forms 0--6 |
1 | "harpsichord" | Goldberg Variations |
2 | "piano" | Goldberg Variations |
3 | "violin" | Chaconne |
4 | "cello" | Cello Prelude |
5 | "guitar" | Reserved; always rejected |
Each form is written for a specific instrument, and the engine rejects anything outside that form's column. Omit instrument to take the form's default. getInstruments() still lists guitar, but no form accepts it.
Character Values
| Number | String | Description |
|---|---|---|
0 | "severe" | Strict, intellectually rigorous (default) |
1 | "playful" | Light, agile, rhythmically lively |
2 | "noble" | Stately, broad, dignified |
3 | "restless" | Driving, chromatic, dramatically charged |
The character also controls note-release articulation and the controller level. At 480 ticks per beat, the declared separations are Noble 24, Severe 40, Playful 56, and Restless 72 ticks; Cello Prelude and Chaconne halve those values, and cantus-firmus voices use zero. The controller offsets keep the arc shape unchanged.
Scale Values
scale multiplies the form's natural length (see Forms); a positive targetBars overrides it. The result is rounded to the form's bar grid and clamped to [form minimum, 128].
| Number | String | Multiplier |
|---|---|---|
0 | "short" | 1x (default) |
1 | "medium" | 2x |
2 | "long" | 3x |
3 | "full" | 4x; Goldberg Variations uses a special complete 128-bar layout |
Two rules shape the resulting numbers. A fugue's natural length is 44 bars, so "long" would be 132 and "full" 176, both beyond the 128 cap. And scales stay distinct at the cap: when a scale and the next one would both reach 128, the shorter drops one grid step, so a fugue's "long" is 124 bars, not 128. The per-form bar counts (fugue 44 / 88 / 124 / 128, for example) are listed in Option Relationships and Presets Reference.
------|-----------|------------|----------|----------| | fugue | 44 | 88 | 124 | 128 | | prelude_and_fugue | 24 | 48 | 72 | 96 | | trio_sonata, chorale_prelude, chaconne | 16 | 32 | 48 | 64 | | toccata_and_fugue, fantasia_and_fugue | 32 | 64 | 96 | 128 | | passacaglia | 24 | 48 | 72 | 96 | | cello_prelude | 8 | 16 | 24 | 32 | | goldberg_variations | 20 | 40 | 60 | 128 (aria, all 30 variations, aria da capo) |
Response Types
EventData
interface EventData {
form: string // Form name (e.g., "fugue")
key: string // Requested key name (e.g., "D_minor")
bpm: number // Starting tempo
seed: number // Resolved seed used for generation
total_ticks: number // Total duration in MIDI ticks
total_bars: number // Total bar count
description: string // Human-readable description
tempos: Array<{ tick: number; bpm: number }>
time_signatures: Array<{ tick: number; numerator: number; denominator: number }>
tracks: TrackData[] // Array of track data
}tempos always starts with an entry at tick 0 carrying bpm. time_signatures reports the form's meter — 4/4 for most forms, 3/4 for Passacaglia and Chaconne.
TrackData
interface TrackData {
name: string // Track name (e.g., "Voice 0", "Voice 1")
channel: number // MIDI channel (0-15)
program: number // General MIDI program number
note_count: number // Number of notes in this track
control_changes: Array<{ tick: number; controller: number; value: number }>
notes: NoteEvent[] // Array of note events
}control_changes is an already-merged, duplicate-free performance curve. Organ and harpsichord tracks use CC 7 (channel volume); piano, violin, and cello tracks use CC 11 (expression); guitar tracks have no continuous-expression profile. CC 7 changes playback level and does not select organ stops. Character offsets shift the curve relative to Severe: Noble +5, Severe 0, Playful -7, Restless +2.
NoteEvent
interface NoteEvent {
pitch: number // MIDI note number (0-127), transposed to the output key and range
velocity: number // Note velocity (0-127)
start_tick: number // Start time in MIDI ticks
duration: number // Post-articulation playback gate in MIDI ticks
voice: number // Voice index
source?: NoteSource // Provenance: "material" | "compose" | "ornament"
}Note duration and provenance
duration in getEvents() is the playback gate after character-dependent articulation. For notes shorter than an eighth (240 ticks at 480 ticks per beat), the declared release scales with the note; a final guard retains at least half of the note's duration. Each voice's final onset remains whole. source records how a note was created: later velocity or articulation changes do not turn an existing material or compose note into ornament.
Note provenance (source)
source is optional in the type, and getEvents() sets it on every note. It records how the note was produced, in lowercase here and in PascalCase in getProvenance():
"material"— fixed material assigned by the form (subjects, ground basses, cantus firmus)."compose"— selected by the candidate search against the harmonic plan."ornament"— added by the deterministic ornament pass (trills, mordents, Nachschlag).
Converting Ticks to Seconds
Ticks are musical time; seconds are wall-clock time. Because the tempo changes within a piece, converting between them means walking the tempo map segment by segment.
const PPQ = 480
function secondsAtTick(tick, events) {
const tempos = [...events.tempos].sort((a, b) => a.tick - b.tick)
let seconds = 0
let previousTick = 0
let bpm = tempos[0].bpm
for (const tempo of tempos) {
if (tempo.tick <= 0) {
bpm = tempo.bpm
continue
}
if (tempo.tick >= tick) break
seconds += ((tempo.tick - previousTick) / PPQ) * (60 / bpm)
previousTick = tempo.tick
bpm = tempo.bpm
}
return seconds + ((tick - previousTick) / PPQ) * (60 / bpm)
}
const events = generator.getEvents()
const total = secondsAtTick(events.total_ticks, events)
const noteStart = secondsAtTick(events.tracks[0].notes[0].start_tick, events)A note's duration in seconds is the difference between the two endpoints, not the duration converted on its own:
const start = secondsAtTick(note.start_tick, events)
const end = secondsAtTick(note.start_tick + note.duration, events)
const durationSeconds = end - startBar and beat numbers come from the meter map the same way — (480 * 4) / denominator ticks per beat, times numerator for a bar:
function timeSignatureAtTick(tick, events) {
let active = events.time_signatures[0]
for (const signature of events.time_signatures) {
if (signature.tick > tick) break
active = signature
}
return active
}Preset Enumeration Functions
These functions return arrays of PresetInfo objects describing available options.
The examples below assume that await init() has completed as shown in Initialization.
getForms()
import { getForms } from '@libraz/midi-sketch-bach'
const forms = getForms()
// [{ id: 0, name: "fugue", display: "Fugue" }, ...]getInstruments()
import { getInstruments } from '@libraz/midi-sketch-bach'
const instruments = getInstruments()
// [{ id: 0, name: "organ" }, ...]getCharacters()
import { getCharacters } from '@libraz/midi-sketch-bach'
const characters = getCharacters()
// [{ id: 0, name: "severe" }, ...]The names are lowercase and are the exact strings character accepts, so they can be passed back into generate() unchanged.
getKeys()
import { getKeys } from '@libraz/midi-sketch-bach'
const keys = getKeys()
// [{ id: 0, name: "C" }, { id: 1, name: "C#" }, ...]These are the canonical key names, so either the id or the name can be passed as key.
getScales()
import { getScales } from '@libraz/midi-sketch-bach'
const scales = getScales()
// [{ id: 0, name: "short" }, ...]getDefaultInstrumentForForm(formId: number): number
Returns the default instrument ID for a form ID.
import { getDefaultInstrumentForForm } from '@libraz/midi-sketch-bach'
const instrumentId = getDefaultInstrumentForForm(7)
// 4 (cello)Parameters: formId: number
Returns: number. Valid form IDs are 0--9. Invalid or out-of-range values return 0 (organ).
getVersion()
import { getVersion } from '@libraz/midi-sketch-bach'
const version = getVersion()
console.log(version) // current engine version stringComplete Examples
Generate and Save a Fugue
import { init, BachGenerator } from '@libraz/midi-sketch-bach'
import { writeFileSync } from 'fs'
await init()
const generator = new BachGenerator()
generator.generate({
form: 'fugue',
key: 2,
isMinor: true,
character: 'severe',
bpm: 76,
seed: 12345
})
writeFileSync('fugue-d-minor.mid', generator.getMidi())
const events = generator.getEvents()
console.log(`Generated: ${events.description}`)
console.log(`Bars: ${events.total_bars}, Tracks: ${events.tracks.length}`)
for (const track of events.tracks) {
console.log(` ${track.name}: ${track.note_count} notes`)
}
generator.destroy()Generate All Forms
import { init, BachGenerator, getForms } from '@libraz/midi-sketch-bach'
import { writeFileSync } from 'fs'
await init()
const forms = getForms()
const generator = new BachGenerator()
for (const form of forms) {
generator.generate({
form: form.name,
key: 2,
isMinor: true,
seed: 42
})
// form.name is already snake_case (e.g. "prelude_and_fugue"); use form.display for a human-readable label
const filename = `bach-${form.name}.mid`
writeFileSync(filename, generator.getMidi())
console.log(`Saved: ${filename}`)
}
generator.destroy()Browser: Generate and Download
import { init, BachGenerator } from '@libraz/midi-sketch-bach'
await init({ wasmPath: '/wasm/bach.wasm' })
const generator = new BachGenerator()
generator.generate({
form: 'fugue',
key: 0,
isMinor: false
})
const midi = generator.getMidi()
const blob = new Blob([midi], { type: 'audio/midi' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = 'bach-fugue.mid'
a.click()
URL.revokeObjectURL(url)
generator.destroy()