@r_masseater/fumx 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +87 -0
- package/README.md +124 -2
- package/dist/analysis-BAPm6c9P.d.mts +75 -0
- package/dist/analysis-CRyaJD5D.mjs +294 -0
- package/dist/analysis-CRyaJD5D.mjs.map +1 -0
- package/dist/analysis.d.mts +3 -0
- package/dist/analysis.mjs +3 -0
- package/dist/cli-D2DptmOG.mjs +2506 -0
- package/dist/cli-D2DptmOG.mjs.map +1 -0
- package/dist/convert-als.d.mts +17 -0
- package/dist/convert-als.mjs +512 -0
- package/dist/convert-als.mjs.map +1 -0
- package/dist/convert-midi.d.mts +17 -0
- package/dist/convert-midi.mjs +273 -0
- package/dist/convert-midi.mjs.map +1 -0
- package/dist/fumx.mjs +9 -0
- package/dist/fumx.mjs.map +1 -0
- package/dist/grammar-Ds8M-PkG.mjs +9836 -0
- package/dist/grammar-Ds8M-PkG.mjs.map +1 -0
- package/dist/habits.d.mts +71 -0
- package/dist/habits.mjs +98 -0
- package/dist/habits.mjs.map +1 -0
- package/dist/index-Bc9UT9HF.d.mts +795 -0
- package/dist/index-C7av_aK1.d.mts +104 -0
- package/dist/index-DOfjU43D.d.mts +71 -0
- package/dist/index-KxUilka8.d.mts +6 -0
- package/dist/index.d.mts +5 -0
- package/dist/index.mjs +4 -0
- package/dist/lint-Bnl4l0aI.mjs +296 -0
- package/dist/lint-Bnl4l0aI.mjs.map +1 -0
- package/dist/lint-CJ5lq-Fr.d.mts +37 -0
- package/dist/lint.d.mts +3 -0
- package/dist/lint.mjs +1 -0
- package/dist/mapper.mjs +14 -0
- package/dist/mapper.mjs.map +1 -0
- package/dist/mix-facts-QCYCXdIA.mjs +7006 -0
- package/dist/mix-facts-QCYCXdIA.mjs.map +1 -0
- package/dist/presets.d.mts +35 -0
- package/dist/presets.mjs +814 -0
- package/dist/presets.mjs.map +1 -0
- package/dist/read-song-B9342KUK.mjs +13017 -0
- package/dist/read-song-B9342KUK.mjs.map +1 -0
- package/dist/read-song-CsW4kd7v.d.mts +1326 -0
- package/dist/read-song-DW8MLsln.mjs +2783 -0
- package/dist/read-song-DW8MLsln.mjs.map +1 -0
- package/dist/song-BlIPWk7b.mjs +387 -0
- package/dist/song-BlIPWk7b.mjs.map +1 -0
- package/dist/song-UZ4T_dj9.d.mts +1477 -0
- package/dist/sounding-BCyExbPp.d.mts +20 -0
- package/dist/sounding-DYDZFp4e.mjs +41 -0
- package/dist/sounding-DYDZFp4e.mjs.map +1 -0
- package/dist/style-rules-CjaZTDt_.d.mts +131 -0
- package/dist/ticks-D6yACwHt.mjs +26 -0
- package/dist/ticks-D6yACwHt.mjs.map +1 -0
- package/dist/transform-CeFBPHqb.mjs +108 -0
- package/dist/transform-CeFBPHqb.mjs.map +1 -0
- package/dist/vite.d.mts +8 -0
- package/dist/vite.mjs +127 -0
- package/dist/vite.mjs.map +1 -0
- package/dist/write-CHtCd-bG.mjs +747 -0
- package/dist/write-CHtCd-bG.mjs.map +1 -0
- package/package.json +118 -3
- package/skills/lint-songs/SKILL.md +54 -0
- package/skills/read-fumx/SKILL.md +89 -0
- package/skills/use-fumx-tools/SKILL.md +69 -0
- package/skills/use-lint-presets/SKILL.md +72 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cli-D2DptmOG.mjs","names":["NONE","NEXT","Arr","Rec","chordsOf","Arr","Rec","Str","NONE","NEXT","Arr","controlsOf","Rec","NONE","NEXT","UNKNOWN","FULL","DEFAULT_RELEASE","DECIMALS","Arr","Rec","releaseOf","Arr","NONE","FULL","Arr","Str","NONE","NEXT","Arr","NEXT","headOf","cellsOf","Arr","Rec","NONE","NEXT","Arr","valueAt","DEFAULT_RELEASE","SINGLE","segmentOf","Arr","SINGLE","INDENT","START","Arr","taggedError","Arr","Rec","NONE","DEFAULT_RELEASE","releaseOf","Arr","Arr","NEXT","pointsOf","NONE","NEXT","Arr","NONE","NEXT","Arr","Bool","timelineOf","timelineOf","taggedError","Arr","NONE","NEXT","edgeOf","Arr","Rec","NONE","NEXT","Arr","Rec","taggedError","taggedError","Str","Flag","taggedError","Flag","Arr","Rec","Arr","Rec","taggedError","DATA_FIRST_ARITY","Arr","Fn","Str","Fn","LINE_START","Bool","Arr","Arr","Fn","Arr","taggedError","SEPARATOR","Str","rulesOf","Rec","Arr","NONE","FIRST","pitchClassOf","TonalNote","Str","Arr","Str","rulesOf","Arr","groupsOf","Arr","Arr","manifest.version","FIRST","UNKNOWN","OCTAVE","Arr","NONE","Arr","Num","FIRST","Arr","Arr","Arr","manifest.description","manifest.version"],"sources":["../package.json","../src/entities/timeline/model/general-midi.ts","../src/entities/timeline/model/groups.ts","../src/entities/timeline/model/names.ts","../src/entities/timeline/model/plan.ts","../src/entities/timeline/model/tempo-units.ts","../src/entities/timeline/model/compare.ts","../src/entities/timeline/model/events.ts","../src/entities/timeline/model/cells.ts","../src/entities/timeline/model/layout.ts","../src/entities/timeline/model/control-lines.ts","../src/entities/timeline/model/mix-lines.ts","../src/entities/timeline/model/voice-lines.ts","../src/entities/timeline/model/write.ts","../src/features/convert-als/model/live-set.ts","../src/features/convert-als/model/clips.ts","../src/features/convert-als/model/tempo-map.ts","../src/features/convert-als/model/ticks.ts","../src/features/convert-als/model/mix.ts","../src/features/convert-als/model/timeline.ts","../src/features/convert-als/model/convert.ts","../src/app/round-trip.ts","../src/app/als-to-fumx.ts","../src/features/convert-midi/model/channel.ts","../src/features/convert-midi/model/timeline.ts","../src/features/convert-midi/model/convert.ts","../src/app/midi-to-fumx.ts","../src/app/convert-command.ts","../src/app/language-server.ts","../../lint-host/src/entities/rule/model/setting.ts","../../lint-host/src/entities/rule/model/severity.ts","../../lint-host/src/entities/rule/model/layers.ts","../../lint-host/src/shared/lib/fail.ts","../../lint-host/src/features/run-cli/model/cli.ts","../../lint-host/src/shared/lib/present.ts","../../lint-host/src/shared/lib/trace.ts","../../lint-host/src/shared/lib/diagnostic.ts","../../lint-host/src/shared/lib/section.ts","../src/shared/lib/errors.ts","../src/features/check-songs/model/extend.ts","../src/features/check-songs/model/read.ts","../src/features/check-songs/model/resolve.ts","../src/features/analyze-song/model/sounding.ts","../src/features/check-songs/model/suppressions.ts","../src/features/check-songs/model/run.ts","../src/app/run-lint.ts","../src/app/section.ts","../src/app/lint-command.ts","../src/features/analyze-song/model/chords.ts","../src/features/analyze-song/model/keys.ts","../src/features/analyze-song/model/repeats.ts","../src/features/analyze-song/model/analysis.ts","../src/app/song-report-command.ts","../src/app/cli.ts"],"sourcesContent":["","export const PROGRAMS = [\n \"acoustic-grand-piano\",\n \"bright-acoustic-piano\",\n \"electric-grand-piano\",\n \"honky-tonk-piano\",\n \"electric-piano-1\",\n \"electric-piano-2\",\n \"harpsichord\",\n \"clavinet\",\n \"celesta\",\n \"glockenspiel\",\n \"music-box\",\n \"vibraphone\",\n \"marimba\",\n \"xylophone\",\n \"tubular-bells\",\n \"dulcimer\",\n \"drawbar-organ\",\n \"percussive-organ\",\n \"rock-organ\",\n \"church-organ\",\n \"reed-organ\",\n \"accordion\",\n \"harmonica\",\n \"tango-accordion\",\n \"acoustic-guitar-nylon\",\n \"acoustic-guitar-steel\",\n \"electric-guitar-jazz\",\n \"electric-guitar-clean\",\n \"electric-guitar-muted\",\n \"overdriven-guitar\",\n \"distortion-guitar\",\n \"guitar-harmonics\",\n \"acoustic-bass\",\n \"electric-bass-finger\",\n \"electric-bass-pick\",\n \"fretless-bass\",\n \"slap-bass-1\",\n \"slap-bass-2\",\n \"synth-bass-1\",\n \"synth-bass-2\",\n \"violin\",\n \"viola\",\n \"cello\",\n \"contrabass\",\n \"tremolo-strings\",\n \"pizzicato-strings\",\n \"orchestral-harp\",\n \"timpani\",\n \"string-ensemble-1\",\n \"string-ensemble-2\",\n \"synth-strings-1\",\n \"synth-strings-2\",\n \"choir-aahs\",\n \"voice-oohs\",\n \"synth-voice\",\n \"orchestra-hit\",\n \"trumpet\",\n \"trombone\",\n \"tuba\",\n \"muted-trumpet\",\n \"french-horn\",\n \"brass-section\",\n \"synth-brass-1\",\n \"synth-brass-2\",\n \"soprano-sax\",\n \"alto-sax\",\n \"tenor-sax\",\n \"baritone-sax\",\n \"oboe\",\n \"english-horn\",\n \"bassoon\",\n \"clarinet\",\n \"piccolo\",\n \"flute\",\n \"recorder\",\n \"pan-flute\",\n \"blown-bottle\",\n \"shakuhachi\",\n \"whistle\",\n \"ocarina\",\n \"lead-1-square\",\n \"lead-2-sawtooth\",\n \"lead-3-calliope\",\n \"lead-4-chiff\",\n \"lead-5-charang\",\n \"lead-6-voice\",\n \"lead-7-fifths\",\n \"lead-8-bass-and-lead\",\n \"pad-1-new-age\",\n \"pad-2-warm\",\n \"pad-3-polysynth\",\n \"pad-4-choir\",\n \"pad-5-bowed\",\n \"pad-6-metallic\",\n \"pad-7-halo\",\n \"pad-8-sweep\",\n \"fx-1-rain\",\n \"fx-2-soundtrack\",\n \"fx-3-crystal\",\n \"fx-4-atmosphere\",\n \"fx-5-brightness\",\n \"fx-6-goblins\",\n \"fx-7-echoes\",\n \"fx-8-sci-fi\",\n \"sitar\",\n \"banjo\",\n \"shamisen\",\n \"koto\",\n \"kalimba\",\n \"bagpipe\",\n \"fiddle\",\n \"shanai\",\n \"tinkle-bell\",\n \"agogo\",\n \"steel-drums\",\n \"woodblock\",\n \"taiko-drum\",\n \"melodic-tom\",\n \"synth-drum\",\n \"reverse-cymbal\",\n \"guitar-fret-noise\",\n \"breath-noise\",\n \"seashore\",\n \"bird-tweet\",\n \"telephone-ring\",\n \"helicopter\",\n \"applause\",\n \"gunshot\",\n] as const;\n\nexport const FIRST_DRUM = 35;\n\nexport const DRUMS = [\n \"acoustic-bass-drum\",\n \"bass-drum-1\",\n \"side-stick\",\n \"acoustic-snare\",\n \"hand-clap\",\n \"electric-snare\",\n \"low-floor-tom\",\n \"closed-hi-hat\",\n \"high-floor-tom\",\n \"pedal-hi-hat\",\n \"low-tom\",\n \"open-hi-hat\",\n \"low-mid-tom\",\n \"hi-mid-tom\",\n \"crash-cymbal-1\",\n \"high-tom\",\n \"ride-cymbal-1\",\n \"chinese-cymbal\",\n \"ride-bell\",\n \"tambourine\",\n \"splash-cymbal\",\n \"cowbell\",\n \"crash-cymbal-2\",\n \"vibraslap\",\n \"ride-cymbal-2\",\n \"hi-bongo\",\n \"low-bongo\",\n \"mute-hi-conga\",\n \"open-hi-conga\",\n \"low-conga\",\n \"high-timbale\",\n \"low-timbale\",\n \"high-agogo\",\n \"low-agogo\",\n \"cabasa\",\n \"maracas\",\n \"short-whistle\",\n \"long-whistle\",\n \"short-guiro\",\n \"long-guiro\",\n \"claves\",\n \"hi-wood-block\",\n \"low-wood-block\",\n \"mute-cuica\",\n \"open-cuica\",\n \"mute-triangle\",\n \"open-triangle\",\n] as const;\n\nexport const DRUM_CHANNEL = 9;\n","import { Array as Arr, Option, Order, Record as Rec, pipe } from \"effect\";\n\nimport type { From } from \"#/shared/lib/from.ts\";\n\nimport type { Part, TimelineNote } from \"./events.ts\";\nimport { DRUM_CHANNEL } from \"./general-midi.ts\";\n\nconst NONE = 0;\nconst NEXT = 1;\n\nexport const isDrumPart: From<Part, boolean> = (part) => part.channel === DRUM_CHANNEL;\n\nexport interface Group {\n readonly start: number;\n readonly end: number;\n readonly midis: readonly number[];\n readonly velocity: number;\n readonly release: number;\n readonly lyric: Option.Option<string>;\n}\n\nexport type Line = readonly Group[];\n\nconst chordKeyOf: From<TimelineNote, string> = (note) =>\n `${String(note.tick)}:${String(note.end)}:${String(note.velocity)}:${String(note.release)}`;\n\nconst groupOf: From<readonly TimelineNote[], Option.Option<Group>> = (notes) =>\n pipe(\n Arr.head(notes),\n Option.map((first) => ({\n start: first.tick,\n end: first.end,\n midis: pipe(\n notes,\n Arr.map((note) => note.midi),\n ),\n velocity: first.velocity,\n release: first.release,\n lyric: Option.none(),\n })),\n );\n\nconst stackedOf: From<readonly TimelineNote[], readonly (readonly TimelineNote[])[]> = (chord) =>\n pipe(\n chord,\n Arr.map((note, index) => ({\n note,\n layer: pipe(\n Arr.take(chord, index),\n Arr.countBy((earlier) => earlier.midi === note.midi),\n ),\n })),\n Arr.groupBy(({ layer }) => String(layer)),\n Rec.values,\n Arr.map((layer) =>\n pipe(\n layer,\n Arr.map(({ note }) => note),\n ),\n ),\n );\n\nconst chordsOf: From<Part, readonly (readonly TimelineNote[])[]> = (part) => {\n if (isDrumPart(part)) {\n return pipe(\n part.notes,\n Arr.map((note) => [note]),\n );\n }\n return pipe(part.notes, Arr.groupBy(chordKeyOf), Rec.values, Arr.flatMap(stackedOf));\n};\n\nconst byStartThenLonger = Order.combine(\n Order.mapInput(Order.Number, (group: Group) => group.start),\n Order.mapInput(Order.flip(Order.Number), (group: Group) => group.end),\n);\n\nconst withLyrics =\n (part: Part): From<readonly Group[], readonly Group[]> =>\n (groups) =>\n pipe(\n groups,\n Arr.map((group, index) => {\n const leads = pipe(\n Arr.get(groups, index - NEXT),\n Option.match({\n onNone: () => true,\n onSome: (previous) => previous.start !== group.start,\n }),\n );\n const lyric = pipe(\n Arr.findFirst(part.lyrics, (candidate) => candidate.tick === group.start),\n Option.filter(() => leads),\n Option.map((found) => found.text),\n );\n return { ...group, lyric };\n }),\n );\n\nexport const groupsOf: From<Part, readonly Group[]> = (part) => {\n const groups = pipe(chordsOf(part), Arr.map(groupOf), Arr.getSomes);\n return withLyrics(part)(Arr.sort(groups, byStartThenLonger));\n};\n\nconst endOfLine: From<Line, number> = (line) =>\n Option.match(Arr.last(line), { onNone: () => NONE, onSome: (group) => group.end });\n\nconst placeGroup = (lines: readonly Line[], group: Group): readonly Line[] =>\n Option.match(\n Arr.findFirstIndex(lines, (line) => endOfLine(line) <= group.start),\n {\n onNone: () => [...lines, [group]],\n onSome: (index) =>\n pipe(\n lines,\n Arr.map((line, position): Line => {\n if (position === index) {\n return [...line, group];\n }\n return line;\n }),\n ),\n },\n );\n\nexport const linesOf: From<readonly Group[], readonly Line[]> = (groups) =>\n Arr.reduce(groups, [] as readonly Line[], placeGroup);\n","import { Array as Arr, Option, Record as Rec, String as Str, pipe } from \"effect\";\nimport { AstUtils, GrammarAST } from \"langium\";\n\nimport type { From } from \"#/shared/lib/from.ts\";\nimport { FumxTerminals } from \"#generated/langium/ast.ts\";\nimport { FumxGrammar } from \"#generated/langium/grammar.ts\";\n\nconst FIRST_SUFFIX = 2;\n\nconst keywordsIn: From<GrammarAST.Grammar | GrammarAST.AbstractRule, ReadonlySet<string>> = (\n node,\n) =>\n new Set(\n AstUtils.streamAst(node)\n .filter((child): child is GrammarAST.Keyword => GrammarAST.isKeyword(child))\n .map((keyword) => keyword.value),\n );\n\nconst grammar = FumxGrammar();\n\nconst allowedKeywords = pipe(\n grammar.rules,\n Arr.findFirst((rule) => rule.name === \"Name\"),\n Option.match({ onNone: () => new Set<string>(), onSome: keywordsIn }),\n);\n\nconst allKeywords = Arr.fromIterable(keywordsIn(grammar));\n\nconst reserved = new Set(\n pipe(\n allKeywords,\n Arr.filter((keyword) => !allowedKeywords.has(keyword)),\n ),\n);\n\nconst otherTerminals = pipe(\n Rec.toEntries(FumxTerminals),\n Arr.filter(([name]) => name !== \"ID\"),\n Arr.map(([, pattern]) => new RegExp(`^(?:${pattern.source})$`, \"u\")),\n);\n\nconst identifier = new RegExp(`^(?:${FumxTerminals.ID.source})$`, \"u\");\n\nconst isUsable: From<string, boolean> = (name) =>\n identifier.test(name) &&\n !reserved.has(name) &&\n !pipe(\n otherTerminals,\n Arr.some((pattern) => pattern.test(name)),\n );\n\nconst slugOf: From<string, string> = (text) =>\n pipe(\n text,\n Str.normalize(\"NFKD\"),\n Str.toLowerCase,\n Str.replaceAll(/[^a-z0-9]+/gu, \"-\"),\n Str.replaceAll(/^[-0-9]+|-+$/gu, \"\"),\n );\n\nexport const nameFrom: From<readonly string[], string> = (candidates) =>\n pipe(\n candidates,\n Arr.map(slugOf),\n Arr.findFirst(isUsable),\n Option.getOrElse(() => \"part\"),\n );\n\nexport const uniqueAmong: From<ReadonlySet<string>, From<string, string>> = (taken) => (name) =>\n pipe(\n Arr.range(FIRST_SUFFIX, taken.size + FIRST_SUFFIX),\n Arr.map((suffix) => `${name}-${String(suffix)}`),\n Arr.prepend(name),\n Arr.findFirst((candidate) => isUsable(candidate) && !taken.has(candidate)),\n Option.getOrElse(() => `${name}-${String(taken.size)}`),\n );\n","import { Array as Arr, Option, Order, Record as Rec, pipe } from \"effect\";\n\nimport type { From } from \"#/shared/lib/from.ts\";\n\nimport type { Level, Part, Timeline, TimelineControl, TrackMix } from \"./events.ts\";\nimport { DRUMS, FIRST_DRUM, PROGRAMS } from \"./general-midi.ts\";\nimport { groupsOf, isDrumPart, linesOf } from \"./groups.ts\";\nimport type { Line } from \"./groups.ts\";\nimport { nameFrom, uniqueAmong } from \"./names.ts\";\n\nconst NONE = 0;\nconst NEXT = 1;\nconst SHARED = 1;\nconst DEFAULT_PROGRAM = 0;\n\nexport type Source =\n | { readonly kind: \"instrument\"; readonly instrument: string; readonly program: number }\n | { readonly kind: \"kit\" };\n\nexport interface PlannedPart {\n readonly part: Part;\n readonly name: string;\n readonly source: Source;\n readonly lines: readonly Line[];\n readonly controls: readonly TimelineControl[];\n readonly mix: TrackMix;\n}\n\nexport interface PlannedBus {\n readonly name: string;\n readonly level: Level;\n}\n\nexport interface Plan {\n readonly parts: readonly PlannedPart[];\n readonly buses: readonly PlannedBus[];\n readonly instruments: ReadonlyMap<number, string>;\n readonly drumVoices: ReadonlyMap<number, string>;\n}\n\nconst drumNameOf: From<number, string> = (midi) =>\n Option.getOrElse(Arr.get(DRUMS, midi - FIRST_DRUM), () => `note-${String(midi)}`);\n\nconst programNameOf: From<number, string> = (program) =>\n Option.getOrElse(Arr.get(PROGRAMS, program), () => `program-${String(program)}`);\n\nexport const controllerKeyOf: From<Pick<TimelineControl, \"controller\">, string> = ({\n controller,\n}) => {\n if (controller.kind === \"cc\") {\n return `cc ${String(controller.number)}`;\n }\n if (controller.kind === \"pressure\") {\n return Option.match(controller.midi, {\n onNone: () => \"pressure\",\n onSome: (midi) => `pressure ${String(midi)}`,\n });\n }\n return controller.kind;\n};\n\nconst isLastAtTick: From<readonly TimelineControl[], From<number, boolean>> =\n (controls) => (index) =>\n pipe(\n Option.all([Arr.get(controls, index), Arr.get(controls, index + NEXT)]),\n Option.match({\n onNone: () => true,\n onSome: ([control, next]) =>\n next.tick !== control.tick || controllerKeyOf(next) !== controllerKeyOf(control),\n }),\n );\n\nconst byControllerThenTick = Order.combine(\n Order.mapInput(Order.String, controllerKeyOf),\n Order.mapInput(Order.Number, (control: TimelineControl) => control.tick),\n);\n\nconst controlsOf: From<Part, readonly TimelineControl[]> = (part) => {\n const drumProgram = pipe(\n part.program,\n Option.filter(() => isDrumPart(part)),\n Option.map((value): TimelineControl => ({\n tick: NONE,\n controller: { kind: \"program\" },\n value,\n })),\n Option.toArray,\n );\n const sorted = Arr.sort([...drumProgram, ...part.controls], byControllerThenTick);\n return pipe(\n sorted,\n Arr.filter((_control, index) => isLastAtTick(sorted)(index)),\n );\n};\n\nconst programOf: From<Part, number> = (part) =>\n Option.getOrElse(part.program, () => DEFAULT_PROGRAM);\n\nconst labelOf: From<Part, string> = (part) => Option.getOrElse(part.name, () => \"\");\n\nconst instrumentsOf: From<readonly Part[], ReadonlyMap<number, string>> = (parts) =>\n new Map(\n pipe(\n parts,\n Arr.filter((part) => !isDrumPart(part)),\n Arr.map(programOf),\n Arr.dedupe,\n Arr.map((program) => [program, nameFrom([programNameOf(program)])] as const),\n ),\n );\n\nconst drumVoicesOf: From<readonly Part[], ReadonlyMap<number, string>> = (parts) => {\n const midis = pipe(\n parts,\n Arr.filter(isDrumPart),\n Arr.flatMap((part) => part.notes),\n Arr.map((note) => note.midi),\n Arr.dedupe,\n );\n return new Map(\n pipe(\n Arr.sort(midis, Order.Number),\n Arr.map((midi) => [midi, drumNameOf(midi)] as const),\n ),\n );\n};\n\nconst channelledOf: From<ReadonlySet<string>, From<Part, string>> = (shared) => (part) => {\n const label = labelOf(part);\n if (shared.has(label)) {\n return `${label} ch${String(part.channel + NEXT)}`;\n }\n return label;\n};\n\nconst fallbackOf: From<Part, string> = (part) => {\n if (isDrumPart(part)) {\n return \"drums\";\n }\n return programNameOf(programOf(part));\n};\n\nconst candidatesOf: From<ReadonlySet<string>, From<Part, readonly string[]>> =\n (shared) => (part) => [\n channelledOf(shared)(part),\n fallbackOf(part),\n `track ${String(part.track)}`,\n ];\n\nconst sharedLabelsOf: From<readonly Part[], ReadonlySet<string>> = (parts) =>\n new Set(\n pipe(\n parts,\n Arr.groupBy(labelOf),\n Rec.filter((same) => same.length > SHARED),\n Rec.keys,\n ),\n );\n\nconst sourceOf: From<ReadonlyMap<number, string>, From<Part, Source>> = (instruments) => (part) => {\n if (isDrumPart(part)) {\n return { kind: \"kit\" };\n }\n const program = programOf(part);\n return { kind: \"instrument\", instrument: instruments.get(program) ?? \"\", program };\n};\n\nconst namesOf: From<readonly PlannedPart[], ReadonlySet<string>> = (planned) =>\n new Set(\n pipe(\n planned,\n Arr.map((done) => done.name),\n ),\n );\n\ninterface Naming {\n readonly instruments: Plan[\"instruments\"];\n readonly candidates: From<Part, readonly string[]>;\n readonly mixes: Timeline[\"mix\"][\"tracks\"];\n}\n\nconst UNMIXED: TrackMix = {\n level: { decibels: NONE, pan: NONE, muted: false },\n sends: [],\n envelopes: [],\n};\n\ntype Reducer<State, Item> = (state: State, item: Item) => State;\n\nconst NO_PARTS: readonly PlannedPart[] = [];\n\nconst nextPart: From<Naming, Reducer<readonly PlannedPart[], Part>> =\n (naming) => (planned, part) => {\n const name = uniqueAmong(namesOf(planned))(nameFrom(naming.candidates(part)));\n return Arr.append(planned, {\n part,\n name,\n source: sourceOf(naming.instruments)(part),\n lines: linesOf(groupsOf(part)),\n controls: controlsOf(part),\n mix: naming.mixes.get(part.track) ?? UNMIXED,\n });\n };\n\ntype BusNaming = Readonly<{ taken: ReadonlySet<string>; buses: Timeline[\"mix\"][\"buses\"] }>;\n\nconst busesOf: From<BusNaming, readonly PlannedBus[]> = ({ taken, buses }) => {\n const used = new Set(taken);\n const named: PlannedBus[] = [];\n for (const [index, bus] of buses.entries()) {\n const name = uniqueAmong(used)(\n nameFrom([...Option.toArray(bus.name), `bus ${String(index + NEXT)}`]),\n );\n used.add(name);\n named.push({ name, level: bus.level });\n }\n return named;\n};\n\nexport const planOf: From<Timeline, Plan> = (timeline) => {\n const instruments = instrumentsOf(timeline.parts);\n const candidates = candidatesOf(sharedLabelsOf(timeline.parts));\n const parts = Arr.reduce(\n timeline.parts,\n NO_PARTS,\n nextPart({ instruments, candidates, mixes: timeline.mix.tracks }),\n );\n return {\n parts,\n buses: busesOf({ taken: namesOf(parts), buses: timeline.mix.buses }),\n instruments,\n drumVoices: drumVoicesOf(timeline.parts),\n };\n};\n","import type { From } from \"#/shared/lib/from.ts\";\n\nconst MICROSECONDS_PER_MINUTE = 60_000_000;\n\nexport const bpmOf: From<number, number> = (microseconds) => MICROSECONDS_PER_MINUTE / microseconds;\n\nexport const microsecondsOf: From<number, number> = (bpm) =>\n Math.round(MICROSECONDS_PER_MINUTE / bpm);\n","import { Array as Arr, Option, Record as Rec, pipe } from \"effect\";\n\nimport type { Song } from \"#/entities/song/@x/timeline.ts\";\nimport type { From } from \"#/shared/lib/from.ts\";\n\nimport type { LaidBar } from \"./layout.ts\";\nimport { controllerKeyOf } from \"./plan.ts\";\nimport type { Plan } from \"./plan.ts\";\nimport { microsecondsOf } from \"./tempo-units.ts\";\n\nconst NONE = 0;\nconst NEXT = 1;\nconst UNKNOWN = -1;\nconst FULL = 127;\nconst DEFAULT_RELEASE = 64;\nconst DECIMALS = 9;\nconst SHOWN = 20;\n\nexport interface Tally {\n readonly expected: number;\n readonly actual: number;\n readonly missing: readonly string[];\n readonly extra: readonly string[];\n}\n\nexport interface Comparison {\n readonly notes: Tally;\n readonly controls: Tally;\n readonly tempo: Tally;\n readonly lyrics: Tally;\n readonly marks: Tally;\n readonly matches: boolean;\n}\n\nconst countsOf: From<readonly string[], Readonly<Record<string, number>>> = (keys) =>\n pipe(\n keys,\n Arr.groupBy((key) => key),\n Rec.map((same) => same.length),\n );\n\nconst surplusOf =\n (\n over: Readonly<Record<string, number>>,\n ): From<Readonly<Record<string, number>>, readonly string[]> =>\n (under) =>\n pipe(\n Rec.toEntries(over),\n Arr.flatMap(([key, count]) => {\n const left = count - Option.getOrElse(Rec.get(under, key), () => NONE);\n if (left > NONE) {\n return Arr.makeBy(left, () => key);\n }\n return [];\n }),\n Arr.take(SHOWN),\n );\n\nconst tallyOf = (expected: readonly string[], actual: readonly string[]): Tally => {\n const wanted = countsOf(expected);\n const found = countsOf(actual);\n return {\n expected: expected.length,\n actual: actual.length,\n missing: surplusOf(wanted)(found),\n extra: surplusOf(found)(wanted),\n };\n};\n\nconst byteOf: From<number, number> = (share) => Math.round(share * FULL);\n\nconst releaseOf: From<Option.Option<number>, number> = (release) =>\n Option.match(release, { onNone: () => DEFAULT_RELEASE, onSome: byteOf });\n\nconst keyOf: From<readonly (string | number)[], string> = (parts) =>\n pipe(parts, Arr.map(String), Arr.join(\" \"));\n\nconst expectedNotesOf: From<Plan, readonly string[]> = (plan) =>\n pipe(\n plan.parts,\n Arr.flatMap((planned) =>\n pipe(\n planned.part.notes,\n Arr.map((note) =>\n keyOf([\n planned.name,\n note.tick,\n note.end - note.tick,\n note.midi,\n note.velocity,\n note.release,\n ]),\n ),\n ),\n ),\n );\n\nconst actualNotesOf: From<Omit<CompareInput, \"bars\">, readonly string[]> = ({ plan, song }) => {\n const voices = new Map(\n pipe(\n Arr.fromIterable(plan.drumVoices),\n Arr.map(([midi, name]) => [name, midi] as const),\n ),\n );\n const notes = pipe(\n song.notes,\n Arr.map((note) =>\n keyOf([\n note.track,\n note.start,\n note.length,\n note.midi,\n byteOf(note.velocity),\n releaseOf(note.releaseVelocity),\n ]),\n ),\n );\n const hits = pipe(\n song.hits,\n Arr.map((hit) =>\n keyOf([\n hit.track,\n hit.start,\n hit.length,\n voices.get(hit.voice) ?? UNKNOWN,\n byteOf(hit.velocity),\n releaseOf(hit.releaseVelocity),\n ]),\n ),\n );\n return [...notes, ...hits];\n};\n\nconst rounded: From<number, string> = (value) => String(Number(value.toFixed(DECIMALS)));\n\nconst expectedControlsOf: From<Plan, readonly string[]> = (plan) =>\n pipe(\n plan.parts,\n Arr.flatMap((planned) =>\n pipe(\n planned.controls,\n Arr.map((control) =>\n keyOf([planned.name, controllerKeyOf(control), control.tick, rounded(control.value)]),\n ),\n ),\n ),\n );\n\nconst actualControlsOf: From<Song, readonly string[]> = (song) =>\n pipe(\n song.controls,\n Arr.map((control) =>\n keyOf([\n control.track,\n controllerKeyOf({ controller: control.controller }),\n control.start,\n rounded(control.value),\n ]),\n ),\n );\n\ninterface TempoPoint {\n readonly tick: number;\n readonly microseconds: number;\n readonly target: Option.Option<number>;\n}\n\nconst FLAT = \"-\";\n\nconst isFlatRepeat = (point: TempoPoint, previous: TempoPoint): boolean =>\n Option.isNone(point.target) &&\n Option.isNone(previous.target) &&\n previous.microseconds === point.microseconds;\n\nconst changesOf: From<readonly TempoPoint[], readonly string[]> = (points) =>\n pipe(\n points,\n Arr.filter((point, index) =>\n pipe(\n Arr.get(points, index - NEXT),\n Option.match({\n onNone: () => true,\n onSome: (previous) => !isFlatRepeat(point, previous),\n }),\n ),\n ),\n Arr.map(({ tick, microseconds, target }) =>\n keyOf([tick, microseconds, Option.getOrElse(target, () => FLAT)]),\n ),\n );\n\nconst expectedTempoOf: From<readonly LaidBar[], readonly string[]> = (bars) =>\n changesOf(\n pipe(\n bars,\n Arr.flatMap((bar) =>\n pipe(\n bar.tempo,\n Arr.map((step): TempoPoint => ({\n tick: bar.start + step.offset,\n microseconds: step.microseconds,\n target: step.target,\n })),\n ),\n ),\n ),\n );\n\nconst barPointsOf: From<Song[\"bars\"][number], readonly TempoPoint[]> = (bar) => {\n if (Arr.isReadonlyArrayNonEmpty(bar.tempoSteps)) {\n return pipe(\n bar.tempoSteps,\n Arr.map((step): TempoPoint => ({\n tick: bar.start + step.offset,\n microseconds: microsecondsOf(step.bpm),\n target: pipe(step.target, Option.map(microsecondsOf)),\n })),\n );\n }\n return [{ tick: bar.start, microseconds: microsecondsOf(bar.tempo.bpm), target: Option.none() }];\n};\n\nconst actualTempoOf: From<Song, readonly string[]> = (song) =>\n changesOf(pipe(song.bars, Arr.flatMap(barPointsOf)));\n\nconst expectedLyricsOf: From<Plan, readonly string[]> = (plan) =>\n pipe(\n plan.parts,\n Arr.flatMap((planned) =>\n pipe(\n planned.lines,\n Arr.flatten,\n Arr.flatMap((group) =>\n pipe(\n group.lyric,\n Option.map((text) => keyOf([planned.name, group.start, text])),\n Option.toArray,\n ),\n ),\n ),\n ),\n );\n\nconst syllableKeyOf: From<Song[\"notes\"][number], Option.Option<string>> = (note) =>\n pipe(\n note.lyric,\n Option.flatMap((lyric) => {\n if (lyric.kind === \"syllable\") {\n return Option.some(keyOf([note.track, note.start, lyric.text]));\n }\n return Option.none();\n }),\n );\n\nconst actualLyricsOf: From<Song, readonly string[]> = (song) =>\n pipe(song.notes, Arr.map(syllableKeyOf), Arr.getSomes, Arr.dedupe);\n\nconst expectedMarksOf: From<readonly LaidBar[], readonly string[]> = (bars) =>\n pipe(\n bars,\n Arr.filter((bar) => Arr.isReadonlyArrayNonEmpty(bar.marks)),\n Arr.map((bar) => keyOf([bar.start, Arr.join(bar.marks, \" / \")])),\n );\n\nconst actualMarksOf: From<Song, readonly string[]> = (song) =>\n pipe(\n song.bars,\n Arr.map((bar) =>\n pipe(\n bar.mark,\n Option.map((mark) => keyOf([bar.start, mark])),\n ),\n ),\n Arr.getSomes,\n );\n\nconst isClean: From<Tally, boolean> = (tally) =>\n !Arr.isReadonlyArrayNonEmpty(tally.missing) && !Arr.isReadonlyArrayNonEmpty(tally.extra);\n\nexport interface CompareInput {\n readonly plan: Plan;\n readonly bars: readonly LaidBar[];\n readonly song: Song;\n}\n\nexport const compareWithSong: From<CompareInput, Comparison> = ({ plan, bars, song }) => {\n const tallies = {\n notes: tallyOf(expectedNotesOf(plan), actualNotesOf({ plan, song })),\n controls: tallyOf(expectedControlsOf(plan), actualControlsOf(song)),\n tempo: tallyOf(expectedTempoOf(bars), actualTempoOf(song)),\n lyrics: tallyOf(expectedLyricsOf(plan), actualLyricsOf(song)),\n marks: tallyOf(expectedMarksOf(bars), actualMarksOf(song)),\n };\n return { ...tallies, matches: pipe(Rec.values(tallies), Arr.every(isClean)) };\n};\n","import { Array as Arr, Order } from \"effect\";\nimport type { Option } from \"effect\";\n\nimport type { Controller, MixerParameter } from \"#/entities/song/@x/timeline.ts\";\n\nexport interface Timed {\n readonly tick: number;\n}\n\nexport interface TimelineNote extends Timed {\n readonly end: number;\n readonly midi: number;\n readonly velocity: number;\n readonly release: number;\n}\n\nexport interface TimelineControl extends Timed {\n readonly controller: Controller;\n readonly value: number;\n}\n\nexport interface Text extends Timed {\n readonly text: string;\n}\n\nexport interface Part {\n readonly track: number;\n readonly channel: number;\n readonly name: Option.Option<string>;\n readonly program: Option.Option<number>;\n readonly notes: readonly TimelineNote[];\n readonly controls: readonly TimelineControl[];\n readonly lyrics: readonly Text[];\n}\n\nexport interface Meter extends Timed {\n readonly numerator: number;\n readonly denominator: number;\n}\n\nexport interface TempoChange extends Timed {\n readonly microseconds: number;\n readonly target: Option.Option<number>;\n}\n\nexport interface Level {\n readonly decibels: number;\n readonly pan: number;\n readonly muted: boolean;\n}\n\nexport interface TrackSend {\n readonly bus: number;\n readonly amount: number;\n}\n\nexport type MixParameter = MixerParameter;\n\nexport interface MixPoint extends Timed {\n readonly value: number;\n}\n\nexport interface Envelope {\n readonly parameter: MixParameter;\n readonly points: readonly MixPoint[];\n}\n\nexport interface TrackMix {\n readonly level: Level;\n readonly sends: readonly TrackSend[];\n readonly envelopes: readonly Envelope[];\n}\n\nexport interface BusMix {\n readonly name: Option.Option<string>;\n readonly level: Level;\n}\n\nexport interface Mix {\n readonly tracks: ReadonlyMap<number, TrackMix>;\n readonly buses: readonly BusMix[];\n}\n\nexport const NO_MIX: Mix = { tracks: new Map(), buses: [] };\n\nexport interface Timeline {\n readonly title: Option.Option<string>;\n readonly end: number;\n readonly offGrid: number;\n readonly tempos: readonly TempoChange[];\n readonly meters: readonly Meter[];\n readonly markers: readonly Text[];\n readonly parts: readonly Part[];\n readonly mix: Mix;\n}\n\nconst byTick = Order.mapInput(Order.Number, (timed: Timed) => timed.tick);\n\nexport const sortedByTick = <Item extends Timed>(items: readonly Item[]): readonly Item[] =>\n Arr.sort(items, byTick);\n\nconst byTickThenPitch = Order.combine(\n Order.mapInput(Order.Number, (note: TimelineNote) => note.tick),\n Order.mapInput(Order.Number, (note: TimelineNote) => note.midi),\n);\n\nexport const sortedNotes = (notes: readonly TimelineNote[]): readonly TimelineNote[] =>\n Arr.sort(notes, byTickThenPitch);\n","import { Array as Arr, Option, String as Str, pipe } from \"effect\";\nimport { Midi } from \"tonal\";\n\nimport type { From } from \"#/shared/lib/from.ts\";\nimport { fractionOf } from \"#/shared/lib/ticks.ts\";\n\nconst NONE = 0;\nconst FULL = 127;\nconst SHARE_DECIMALS = 3;\nconst SEMITONE_DECIMALS = 12;\nconst LAST = 1;\n\nexport interface Cell {\n readonly head: string;\n readonly attributes: readonly string[];\n readonly length: number;\n}\n\nexport const durationText: From<number, string> = (length) => {\n if (length === NONE) {\n return \"0/1\";\n }\n return fractionOf(length);\n};\n\nexport const restCell: From<number, Cell> = (length) => ({ head: \"rest\", attributes: [], length });\n\nexport const restsOf: From<number, readonly Cell[]> = (length) => {\n if (length > NONE) {\n return [restCell(length)];\n }\n return [];\n};\n\nconst isRest: From<Cell, boolean> = (cell) => cell.head === \"rest\";\n\nconst mergeRests = (merged: readonly Cell[], cell: Cell): readonly Cell[] =>\n pipe(\n Arr.last(merged),\n Option.filter((previous) => isRest(previous) && isRest(cell)),\n Option.match({\n onNone: () => [...merged, cell],\n onSome: (previous) => [\n ...Arr.dropRight(merged, LAST),\n restCell(previous.length + cell.length),\n ],\n }),\n );\n\nconst NO_CELLS: readonly Cell[] = [];\n\nconst cellText: From<Cell, string> = (cell) =>\n Arr.join([cell.head, durationText(cell.length), ...cell.attributes], \" \");\n\nexport const cellsText: From<readonly Cell[], string> = (cells) =>\n pipe(Arr.reduce(cells, NO_CELLS, mergeRests), Arr.map(cellText), Arr.join(\", \"));\n\nexport const quoted: From<string, string> = (text) =>\n `\"${pipe(\n text,\n Str.replaceAll(\"\\\\\", String.raw`\\\\`),\n Str.replaceAll('\"', String.raw`\\\"`),\n Str.replaceAll(\"\\n\", String.raw`\\n`),\n Str.replaceAll(\"\\r\", String.raw`\\r`),\n Str.replaceAll(\"\\t\", String.raw`\\t`),\n )}\"`;\n\nexport const shareText: From<number, string> = (value) =>\n String(Number((value / FULL).toFixed(SHARE_DECIMALS)));\n\nexport const semitoneText: From<number, string> = (value) => {\n const text = String(Number(value.toFixed(SEMITONE_DECIMALS)));\n if (value > NONE) {\n return `+${text}st`;\n }\n return `${text}st`;\n};\n\nexport const pitchText: From<number, string> = (midi) =>\n Midi.midiToNoteName(midi, { sharps: true });\n","import { Array as Arr, Option, pipe } from \"effect\";\n\nimport type { From } from \"#/shared/lib/from.ts\";\nimport { TICKS_PER_WHOLE, fractionOf } from \"#/shared/lib/ticks.ts\";\n\nimport type { Meter, TempoChange, Text, Timeline } from \"./events.ts\";\nimport { bpmOf, microsecondsOf } from \"./tempo-units.ts\";\n\nconst NONE = 0;\nconst NEXT = 1;\nconst QUARTER = 4;\nconst DEFAULT_METER = { numerator: QUARTER, denominator: QUARTER };\nconst DEFAULT_MICROSECONDS = 500_000;\nconst MAX_DECIMALS = 9;\n\nexport interface LaidTempo {\n readonly offset: number;\n readonly length: number;\n readonly microseconds: number;\n readonly target: Option.Option<number>;\n}\n\nexport interface Span {\n readonly start: number;\n readonly length: number;\n}\n\nexport interface LaidBar extends Span {\n readonly meter: string;\n readonly tempo: readonly LaidTempo[];\n readonly marks: readonly string[];\n}\n\ninterface Signature {\n readonly numerator: number;\n readonly denominator: number;\n}\n\nexport const endOfSpan: From<Span, number> = (span) => span.start + span.length;\n\nconst latestAt =\n (tick: number) =>\n <Item extends { readonly tick: number }>(items: readonly Item[]): Option.Option<Item> =>\n pipe(\n items,\n Arr.filter((item) => item.tick <= tick),\n Arr.last,\n );\n\nconst lengthOf: From<Signature, number> = (signature) =>\n (TICKS_PER_WHOLE * signature.numerator) / signature.denominator;\n\nconst meterText =\n (signature: Signature): From<number, string> =>\n (length) => {\n const beats = (length * signature.denominator) / TICKS_PER_WHOLE;\n if (Number.isInteger(beats)) {\n return `${String(beats)}/${String(signature.denominator)}`;\n }\n return fractionOf(length);\n };\n\ninterface Ramp {\n readonly start: TempoChange;\n readonly end: number;\n readonly target: number;\n}\n\nconst rampAt =\n (tempos: readonly TempoChange[]): From<number, Option.Option<Ramp>> =>\n (tick) =>\n pipe(\n latestAt(tick)(tempos),\n Option.flatMap((start) =>\n pipe(\n start.target,\n Option.flatMap((target) =>\n pipe(\n Arr.findFirst(tempos, (tempo) => tempo.tick > start.tick),\n Option.map((next) => ({ start, end: next.tick, target })),\n ),\n ),\n ),\n ),\n );\n\nconst interpolated =\n (ramp: Ramp): From<number, number> =>\n (tick) => {\n const from = bpmOf(ramp.start.microseconds);\n const to = bpmOf(ramp.target);\n const share = (tick - ramp.start.tick) / (ramp.end - ramp.start.tick);\n return microsecondsOf(from + (to - from) * share);\n };\n\nconst rampedAt =\n (tempos: readonly TempoChange[]) =>\n (tick: number, at: number): Option.Option<number> =>\n pipe(\n rampAt(tempos)(tick),\n Option.map((ramp) => interpolated(ramp)(at)),\n );\n\nconst steadyAt =\n (tempos: readonly TempoChange[]): From<number, number> =>\n (tick) =>\n pipe(\n latestAt(tick)(tempos),\n Option.match({\n onNone: () => DEFAULT_MICROSECONDS,\n onSome: (tempo) => tempo.microseconds,\n }),\n );\n\nconst tempoAt =\n (tempos: readonly TempoChange[]): From<number, number> =>\n (tick) =>\n Option.getOrElse(rampedAt(tempos)(tick, tick), () => steadyAt(tempos)(tick));\n\nconst tempoStepsOf =\n (tempos: readonly TempoChange[]): From<Span, readonly LaidTempo[]> =>\n (bar) => {\n const end = endOfSpan(bar);\n const points = [\n bar.start,\n ...pipe(\n tempos,\n Arr.filter((tempo) => tempo.tick > bar.start && tempo.tick < end),\n Arr.map((tempo) => tempo.tick),\n Arr.dedupe,\n ),\n ];\n return pipe(\n points,\n Arr.map((tick, index) => {\n const stepEnd = Option.getOrElse(Arr.get(points, index + NEXT), () => end);\n return {\n offset: tick - bar.start,\n length: stepEnd - tick,\n microseconds: tempoAt(tempos)(tick),\n target: rampedAt(tempos)(tick, stepEnd),\n };\n }),\n );\n };\n\nconst marksOf =\n (markers: readonly Text[]): From<Span, readonly string[]> =>\n (bar) =>\n pipe(\n markers,\n Arr.filter((marker) => marker.tick >= bar.start && marker.tick < endOfSpan(bar)),\n Arr.map((marker) => marker.text),\n );\n\nconst spanAt =\n (meters: readonly Meter[]): From<number, Span & { readonly signature: Signature }> =>\n (start) => {\n const signature = Option.getOrElse(latestAt(start)(meters), () => DEFAULT_METER);\n const full = start + lengthOf(signature);\n const end = pipe(\n Arr.findFirst(meters, (meter) => meter.tick > start),\n Option.match({ onNone: () => full, onSome: (meter) => Math.min(meter.tick, full) }),\n );\n return { start, length: end - start, signature };\n };\n\nexport const barsOf: From<Timeline, readonly LaidBar[]> = (timeline) =>\n Arr.unfold({ start: NONE, first: true }, (cursor) => {\n if (!cursor.first && cursor.start >= timeline.end) {\n return Option.none();\n }\n const span = spanAt(timeline.meters)(cursor.start);\n const bar: LaidBar = {\n start: span.start,\n length: span.length,\n meter: meterText(span.signature)(span.length),\n tempo: tempoStepsOf(timeline.tempos)(span),\n marks: marksOf(timeline.markers)(span),\n };\n return Option.some([bar, { start: endOfSpan(span), first: false }] as const);\n });\n\nexport const bpmText: From<number, string> = (microseconds) => {\n const exact = bpmOf(microseconds);\n const text = pipe(\n Arr.range(NONE, MAX_DECIMALS),\n Arr.map((decimals) => String(Number(exact.toFixed(decimals)))),\n Arr.findFirst((candidate) => microsecondsOf(Number(candidate)) === microseconds),\n Option.getOrElse(() => String(exact)),\n );\n return `${text}bpm`;\n};\n","import { Array as Arr, Option, Record as Rec, pipe } from \"effect\";\n\nimport type { From } from \"#/shared/lib/from.ts\";\n\nimport { cellsText, pitchText, restsOf, semitoneText } from \"./cells.ts\";\nimport type { Cell } from \"./cells.ts\";\nimport type { TimelineControl } from \"./events.ts\";\nimport { endOfSpan } from \"./layout.ts\";\nimport type { Span } from \"./layout.ts\";\nimport { controllerKeyOf } from \"./plan.ts\";\nimport type { PlannedPart } from \"./plan.ts\";\n\nconst NEXT = 1;\n\nconst valueText: From<TimelineControl, string> = (control) => {\n if (control.controller.kind === \"bend\") {\n return semitoneText(control.value);\n }\n return String(control.value);\n};\n\nconst headOf =\n (planned: PlannedPart): From<TimelineControl, string> =>\n ({ controller }) => {\n if (controller.kind === \"pressure\") {\n return Option.match(controller.midi, {\n onNone: () => `${planned.name}.pressure`,\n onSome: (midi) => `${planned.name}.pressure ${pitchText(midi)}`,\n });\n }\n return `${planned.name}.${controllerKeyOf({ controller })}`;\n };\n\nconst cellsOf =\n (bar: Span): From<readonly TimelineControl[], readonly Cell[]> =>\n (controls) => {\n const lead = pipe(\n Arr.head(controls),\n Option.map((first) => first.tick - bar.start),\n Option.toArray,\n Arr.flatMap(restsOf),\n );\n const steps = pipe(\n controls,\n Arr.map((control, index) => ({\n head: valueText(control),\n attributes: [],\n length:\n pipe(\n Arr.get(controls, index + NEXT),\n Option.match({ onNone: () => endOfSpan(bar), onSome: (next) => next.tick }),\n ) - control.tick,\n })),\n );\n return [...lead, ...steps];\n };\n\nexport const controlLinesOf =\n (bar: Span): From<PlannedPart, readonly string[]> =>\n (planned) =>\n pipe(\n planned.controls,\n Arr.filter((control) => control.tick >= bar.start && control.tick < endOfSpan(bar)),\n Arr.groupBy((control: TimelineControl) => controllerKeyOf(control)),\n Rec.values,\n Arr.map((controls) =>\n pipe(\n Arr.head(controls),\n Option.map((first) => `${headOf(planned)(first)}: ${cellsText(cellsOf(bar)(controls))}`),\n ),\n ),\n Arr.getSomes,\n );\n","import { Array as Arr, Option, pipe } from \"effect\";\n\nimport type { From } from \"#/shared/lib/from.ts\";\n\nimport type { Envelope, Level, MixParameter, MixPoint, TrackMix } from \"./events.ts\";\nimport { endOfSpan } from \"./layout.ts\";\nimport type { Span } from \"./layout.ts\";\nimport type { PlannedBus, PlannedPart } from \"./plan.ts\";\n\nconst DECIMALS = 1;\nconst PERCENT = 100;\nconst NONE = 0;\nconst NEXT = 1;\n\nconst amountText = (value: number, unit: string): string => {\n const text = Number(value.toFixed(DECIMALS));\n if (text > NONE) {\n return `+${String(text)}${unit}`;\n }\n return `${String(text)}${unit}`;\n};\n\nconst UNITS: Readonly<Record<MixParameter, From<number, string>>> = {\n volume: (decibels) => amountText(decibels, \"dB\"),\n pan: (pan) => amountText(pan * PERCENT, \"%\"),\n};\n\nconst levelWords: From<Level, readonly string[]> = (level) => [\n ...pipe(\n Option.some(level.decibels),\n Option.filter((decibels) => UNITS.volume(decibels) !== UNITS.volume(NONE)),\n Option.map((decibels) => `volume ${UNITS.volume(decibels)}`),\n Option.toArray,\n ),\n ...pipe(\n Option.some(level.pan),\n Option.filter((pan) => UNITS.pan(pan) !== UNITS.pan(NONE)),\n Option.map((pan) => `pan ${UNITS.pan(pan)}`),\n Option.toArray,\n ),\n ...pipe(\n Option.some(\"mute\"),\n Option.filter(() => level.muted),\n Option.toArray,\n ),\n];\n\nexport type Mixing = Readonly<{ mix: TrackMix; buses: readonly PlannedBus[] }>;\n\nexport const trackMixWords: From<Mixing, readonly string[]> = ({ mix, buses }) => [\n ...levelWords(mix.level),\n ...pipe(\n mix.sends,\n Arr.filter((send) => send.amount > NONE),\n Arr.flatMap((send) =>\n pipe(\n Arr.get(buses, send.bus),\n Option.map((bus) => `send ${bus.name} ${amountText(send.amount * PERCENT, \"%\")}`),\n Option.toArray,\n ),\n ),\n ),\n];\n\nexport const busLineOf: From<PlannedBus, string> = (bus) =>\n Arr.join([\"bus\", bus.name, ...levelWords(bus.level)], \" \");\n\nconst valueAt =\n (points: readonly MixPoint[]): From<number, number> =>\n (tick) => {\n const before = pipe(\n points,\n Arr.filter((point) => point.tick <= tick),\n Arr.last,\n );\n const after = pipe(\n points,\n Arr.findFirst((point) => point.tick > tick),\n );\n return Option.match(before, {\n onNone: () => Option.match(after, { onNone: () => NONE, onSome: (point) => point.value }),\n onSome: (left) =>\n Option.match(after, {\n onNone: () => left.value,\n onSome: (right) =>\n left.value +\n ((right.value - left.value) * (tick - left.tick)) / (right.tick - left.tick),\n }),\n });\n };\n\nconst rampOf =\n (bar: Span, name: string): From<Envelope, Option.Option<string>> =>\n (envelope) => {\n const at = valueAt(envelope.points);\n const unit = UNITS[envelope.parameter];\n const from = unit(at(bar.start));\n const to = unit(at(endOfSpan(bar)));\n return pipe(\n Option.some(`automate ${name}.${envelope.parameter} ${from} -> ${to} over 1bar`),\n Option.filter(() => from !== to),\n );\n };\n\nexport const automationLinesOf =\n (bar: Span): From<PlannedPart, readonly string[]> =>\n (planned) =>\n pipe(\n planned.mix.envelopes,\n Arr.filter((envelope) => Arr.length(envelope.points) > NEXT),\n Arr.map(rampOf(bar, planned.name)),\n Arr.getSomes,\n );\n","import { Array as Arr, Option, Order, pipe } from \"effect\";\n\nimport type { From } from \"#/shared/lib/from.ts\";\n\nimport { cellsText, pitchText, quoted, restsOf, shareText } from \"./cells.ts\";\nimport type { Cell } from \"./cells.ts\";\nimport type { Group, Line } from \"./groups.ts\";\nimport { endOfSpan } from \"./layout.ts\";\nimport type { Span } from \"./layout.ts\";\nimport type { Plan, PlannedPart } from \"./plan.ts\";\n\nconst FULL = 127;\nconst DEFAULT_RELEASE = 64;\nconst SINGLE = 1;\n\ninterface Segment {\n readonly group: Group;\n readonly start: number;\n readonly end: number;\n}\n\ninterface VoiceText {\n readonly text: string;\n readonly continues: boolean;\n}\n\nconst touches =\n (bar: Span): From<Group, boolean> =>\n (group) => {\n if (group.end === group.start) {\n return group.start >= bar.start && group.start < endOfSpan(bar);\n }\n return group.start < endOfSpan(bar) && group.end > bar.start;\n };\n\nconst segmentOf =\n (bar: Span): From<Group, Segment> =>\n (group) => ({\n group,\n start: Math.max(group.start, bar.start),\n end: Math.min(group.end, endOfSpan(bar)),\n });\n\nconst pitchesText: From<readonly number[], string> = (midis) => {\n if (midis.length === SINGLE) {\n return Arr.join(pipe(midis, Arr.map(pitchText)), \"\");\n }\n return `[${Arr.join(pipe(midis, Arr.map(pitchText)), \" \")}]`;\n};\n\nconst headOf =\n (voices: Option.Option<ReadonlyMap<number, string>>): From<Group, string> =>\n (group) =>\n Option.match(voices, {\n onNone: () => pitchesText(group.midis),\n onSome: (map) =>\n pipe(\n Arr.head(group.midis),\n Option.flatMap((midi) => Option.fromNullishOr(map.get(midi))),\n Option.getOrElse(() => \"\"),\n ),\n });\n\nconst when = (condition: boolean, text: string): readonly string[] => {\n if (condition) {\n return [text];\n }\n return [];\n};\n\nconst attributesOf: From<Segment, readonly string[]> = ({ group, start, end }) => {\n const last = end === group.end;\n return [\n ...when(group.velocity !== FULL, `vel ${shareText(group.velocity)}`),\n ...when(last && group.release !== DEFAULT_RELEASE, `off ${shareText(group.release)}`),\n ...when(!last, \"tie\"),\n ...pipe(\n group.lyric,\n Option.filter(() => start === group.start),\n Option.map((text) => `lyric ${quoted(text)}`),\n Option.toArray,\n ),\n ];\n};\n\nconst cellsOf = (\n segments: readonly Segment[],\n bar: Span,\n head: From<Group, string>,\n): readonly Cell[] => {\n const placed = Arr.reduce(\n segments,\n { cells: [] as readonly Cell[], cursor: bar.start },\n ({ cells, cursor }, segment) => ({\n cells: [\n ...cells,\n ...restsOf(segment.start - cursor),\n {\n head: head(segment.group),\n attributes: attributesOf(segment),\n length: segment.end - segment.start,\n },\n ],\n cursor: segment.end,\n }),\n );\n return [...placed.cells, ...restsOf(endOfSpan(bar) - placed.cursor)];\n};\n\nconst lineTextOf =\n (\n planned: PlannedPart,\n voices: Option.Option<ReadonlyMap<number, string>>,\n bar: Span,\n ): From<Line, Option.Option<VoiceText>> =>\n (line) => {\n const segments = pipe(line, Arr.filter(touches(bar)), Arr.map(segmentOf(bar)));\n return pipe(\n Arr.head(segments),\n Option.map((first) => ({\n text: `${planned.name}: ${cellsText(cellsOf(segments, bar, headOf(voices)))}`,\n continues: first.start > first.group.start,\n })),\n );\n };\n\nconst continuedFirst = Order.mapInput(Order.Boolean, (voice: VoiceText) => !voice.continues);\n\nexport interface VoiceContext {\n readonly plan: Plan;\n readonly bar: Span;\n}\n\nexport const voiceLinesOf: From<VoiceContext, From<PlannedPart, readonly string[]>> =\n ({ plan, bar }) =>\n (planned) => {\n const voices = pipe(\n Option.some(plan.drumVoices),\n Option.filter(() => planned.source.kind === \"kit\"),\n );\n const texts = pipe(planned.lines, Arr.map(lineTextOf(planned, voices, bar)), Arr.getSomes);\n return pipe(\n Arr.sort(texts, continuedFirst),\n Arr.map((voice) => voice.text),\n );\n };\n","import { Array as Arr, Option, pipe } from \"effect\";\n\nimport type { From } from \"#/shared/lib/from.ts\";\nimport { fractionOf } from \"#/shared/lib/ticks.ts\";\n\nimport { quoted } from \"./cells.ts\";\nimport { controlLinesOf } from \"./control-lines.ts\";\nimport type { Timeline } from \"./events.ts\";\nimport { barsOf, bpmText } from \"./layout.ts\";\nimport type { LaidBar, LaidTempo } from \"./layout.ts\";\nimport { automationLinesOf, busLineOf, trackMixWords } from \"./mix-lines.ts\";\nimport { planOf } from \"./plan.ts\";\nimport type { Plan, PlannedPart } from \"./plan.ts\";\nimport { voiceLinesOf } from \"./voice-lines.ts\";\n\nconst SINGLE = 1;\nconst INDENT = \" \";\n\nexport interface Written {\n readonly text: string;\n readonly plan: Plan;\n readonly bars: readonly LaidBar[];\n}\n\ninterface Previous {\n readonly meter: Option.Option<string>;\n readonly microseconds: Option.Option<number>;\n}\n\nconst START: Previous = { meter: Option.none(), microseconds: Option.none() };\n\nconst isRamp: From<LaidTempo, boolean> = (step) => Option.isSome(step.target);\n\nconst stepText: From<LaidTempo, string> = (step) => {\n const ramp = Option.match(step.target, {\n onNone: () => \"\",\n onSome: (target) => ` -> ${bpmText(target)}`,\n });\n return `${bpmText(step.microseconds)}${ramp} ${fractionOf(step.length)}`;\n};\n\nconst isSteady: From<LaidBar, boolean> = (bar) =>\n bar.tempo.length <= SINGLE && !pipe(bar.tempo, Arr.some(isRamp));\n\nconst tempoLineOf: From<LaidBar, Option.Option<string>> = (bar) => {\n if (isSteady(bar)) {\n return Option.none();\n }\n const steps = pipe(bar.tempo, Arr.map(stepText));\n return Option.some(`tempo: ${Arr.join(steps, \", \")}`);\n};\n\nconst differs =\n <Value>(previous: Option.Option<Value>): From<Value, boolean> =>\n (current) =>\n Option.match(previous, { onNone: () => true, onSome: (value) => value !== current });\n\nconst headerTempoOf =\n (previous: Previous): From<LaidBar, readonly string[]> =>\n (bar) =>\n pipe(\n Arr.head(bar.tempo),\n Option.filter(() => isSteady(bar)),\n Option.map((step) => step.microseconds),\n Option.filter(differs(previous.microseconds)),\n Option.map((microseconds) => `tempo ${bpmText(microseconds)}`),\n Option.toArray,\n );\n\nconst barHeadOf =\n (previous: Previous): From<LaidBar, string> =>\n (bar) => {\n const meter = pipe(\n Option.some(bar.meter),\n Option.filter(differs(previous.meter)),\n Option.map((current) => `meter ${current}`),\n Option.toArray,\n );\n const mark = pipe(\n Option.some(bar.marks),\n Option.filter(Arr.isReadonlyArrayNonEmpty),\n Option.map((marks) => `mark ${quoted(Arr.join(marks, \" / \"))}`),\n Option.toArray,\n );\n return Arr.join([\"bar\", ...meter, ...headerTempoOf(previous)(bar), ...mark, \"{\"], \" \");\n };\n\nconst barBodyOf: From<Plan, From<LaidBar, readonly string[]>> = (plan) => (bar) => [\n ...Option.toArray(tempoLineOf(bar)),\n ...pipe(\n plan.parts,\n Arr.flatMap((planned) => [\n ...voiceLinesOf({ plan, bar })(planned),\n ...controlLinesOf(bar)(planned),\n ...automationLinesOf(bar)(planned),\n ]),\n ),\n];\n\ninterface Walk {\n readonly lines: readonly string[];\n readonly previous: Previous;\n}\n\nconst afterBar: From<LaidBar, Previous> = (bar) => ({\n meter: Option.some(bar.meter),\n microseconds: pipe(\n Arr.last(bar.tempo),\n Option.map((step) => Option.getOrElse(step.target, () => step.microseconds)),\n ),\n});\n\nconst walkStep: From<Plan, (walk: Walk, bar: LaidBar) => Walk> =\n (plan) =>\n ({ lines, previous }, bar) => ({\n lines: [\n ...lines,\n \"\",\n barHeadOf(previous)(bar),\n ...pipe(\n barBodyOf(plan)(bar),\n Arr.map((line) => `${INDENT}${line}`),\n ),\n \"}\",\n ],\n previous: afterBar(bar),\n });\n\nconst instrumentLinesOf: From<Plan, readonly string[]> = (plan) =>\n pipe(\n Arr.fromIterable(plan.instruments),\n Arr.map(([program, name]) => `instrument ${name} plugin gm program ${String(program)}`),\n );\n\nconst kitLinesOf: From<Plan, readonly string[]> = (plan) => {\n if (plan.drumVoices.size < SINGLE) {\n return [];\n }\n const voices = pipe(\n Arr.fromIterable(plan.drumVoices.values()),\n Arr.map((name) => `${INDENT}${name} ${quoted(`gm-drums/${name}.flac`)}`),\n );\n return [\"kit gm-drums {\", ...voices, \"}\"];\n};\n\nconst sourceWordsOf: From<PlannedPart, readonly string[]> = (planned) => {\n if (planned.source.kind === \"kit\") {\n return [\"kit gm-drums role drums\"];\n }\n return [`instrument ${planned.source.instrument}`];\n};\n\nconst trackLineOf =\n (plan: Plan): From<PlannedPart, string> =>\n (planned) =>\n Arr.join(\n [\n \"track\",\n planned.name,\n ...sourceWordsOf(planned),\n ...trackMixWords({ mix: planned.mix, buses: plan.buses }),\n ],\n \" \",\n );\n\ninterface Heading {\n readonly plan: Plan;\n readonly title: string;\n}\n\nconst headerOf: From<Heading, readonly string[]> = ({ plan, title }) => [\n `song ${quoted(title)}`,\n \"\",\n 'plugin gm from \"./gm.ts\" { program: number = 0 }',\n \"\",\n ...instrumentLinesOf(plan),\n ...kitLinesOf(plan),\n \"\",\n ...pipe(plan.buses, Arr.map(busLineOf)),\n ...pipe(plan.parts, Arr.map(trackLineOf(plan))),\n];\n\nexport interface WriteInput {\n readonly timeline: Timeline;\n readonly title: string;\n}\n\nexport const writeFumx: From<WriteInput, Written> = ({ timeline, title }) => {\n const plan = planOf(timeline);\n const bars = barsOf(timeline);\n const walked = Arr.reduce(\n bars,\n { lines: headerOf({ plan, title }), previous: START },\n walkStep(plan),\n );\n return { text: `${Arr.join(walked.lines, \"\\n\")}\\n`, plan, bars };\n};\n","import { Array as Arr, Effect, Option, Record as Rec, Schema, pipe } from \"effect\";\nimport { XMLParser } from \"fast-xml-parser\";\n\nconst taggedError = Schema.TaggedError;\n\nexport class UnreadableAls extends taggedError<UnreadableAls, { readonly brand: unique symbol }>()(\n \"UnreadableAls\",\n { message: Schema.String },\n { identifier: \"UnreadableAls\" },\n) {}\n\nconst REPEATED = new Set([\n \"MidiTrack\",\n \"AudioTrack\",\n \"GroupTrack\",\n \"ReturnTrack\",\n \"MidiClip\",\n \"AudioClip\",\n \"KeyTrack\",\n \"MidiNoteEvent\",\n \"Locator\",\n \"AutomationEnvelope\",\n \"FloatEvent\",\n \"EnumEvent\",\n \"BoolEvent\",\n \"TrackSendHolder\",\n]);\n\nconst ATTRIBUTES = \"@\";\n\nconst parser = new XMLParser({\n ignoreAttributes: false,\n attributeNamePrefix: \"\",\n attributesGroupName: ATTRIBUTES,\n parseTagValue: false,\n parseAttributeValue: false,\n jPath: false,\n isArray: (name: string): boolean => REPEATED.has(name),\n});\n\nconst Num = Schema.Struct({ Value: Schema.FiniteFromString });\nconst Text = Schema.Struct({ Value: Schema.String });\nconst Flag = Schema.Struct({ Value: Schema.Literals([\"true\", \"false\"]) });\n\nconst EventSchema = Schema.Struct({ Time: Schema.FiniteFromString, Value: Schema.String });\n\nexport type AutomationEvent = typeof EventSchema.Type;\n\nconst EventsSchema = Schema.Struct({\n FloatEvent: EventSchema.pipe(Schema.Array, Schema.optionalKey),\n EnumEvent: EventSchema.pipe(Schema.Array, Schema.optionalKey),\n BoolEvent: EventSchema.pipe(Schema.Array, Schema.optionalKey),\n});\n\nconst EnvelopeSchema = Schema.Struct({\n EnvelopeTarget: Schema.Struct({ PointeeId: Num }),\n Automation: Schema.Struct({ Events: EventsSchema }),\n});\n\nexport type AutomationEnvelope = typeof EnvelopeSchema.Type;\n\nconst EnvelopeListSchema = Schema.Struct({\n AutomationEnvelope: EnvelopeSchema.pipe(Schema.Array, Schema.optionalKey),\n});\n\nconst EnvelopesSchema = Schema.Struct({ Envelopes: EnvelopeListSchema });\n\nconst TargetSchema = Schema.Struct({ Id: Schema.FiniteFromString });\n\nconst ParameterSchema = Schema.Struct({\n Manual: Schema.optionalKey(Num),\n AutomationTarget: Schema.optionalKey(TargetSchema),\n ArrangerAutomation: Schema.optionalKey(Schema.Struct({ Events: EventsSchema })),\n});\n\nexport type Parameter = typeof ParameterSchema.Type;\n\nconst NoteSchema = Schema.Struct({\n Time: Schema.FiniteFromString,\n Duration: Schema.FiniteFromString,\n Velocity: Schema.FiniteFromString,\n OffVelocity: Schema.optionalKey(Schema.FiniteFromString),\n IsEnabled: Schema.optionalKey(Schema.Literals([\"true\", \"false\"])),\n Probability: Schema.optionalKey(Schema.FiniteFromString),\n VelocityDeviation: Schema.optionalKey(Schema.FiniteFromString),\n});\n\nconst NoteListSchema = Schema.Struct({\n MidiNoteEvent: NoteSchema.pipe(Schema.Array, Schema.optionalKey),\n});\n\nconst KeyTrackSchema = Schema.Struct({ Notes: NoteListSchema, MidiKey: Num });\n\nconst LoopSchema = Schema.Struct({\n LoopStart: Num,\n LoopEnd: Num,\n StartRelative: Num,\n LoopOn: Flag,\n});\n\nconst KeyTracksSchema = Schema.Struct({\n KeyTrack: KeyTrackSchema.pipe(Schema.Array, Schema.optionalKey),\n});\n\nconst ClipSchema = Schema.Struct({\n CurrentStart: Num,\n CurrentEnd: Num,\n Loop: LoopSchema,\n Disabled: Schema.optionalKey(Flag),\n Notes: Schema.Struct({ KeyTracks: KeyTracksSchema }),\n});\n\nexport type AlsClip = typeof ClipSchema.Type;\n\nconst NameSchema = Schema.Struct({\n EffectiveName: Schema.optionalKey(Text),\n UserName: Schema.optionalKey(Text),\n});\n\nconst DrumsSchema = Schema.Struct({ DrumGroupDevice: Schema.optionalKey(Schema.Unknown) });\n\nconst DevicesSchema = Schema.Struct({ Devices: Schema.optionalKey(DrumsSchema) });\n\nconst ClipEventsSchema = Schema.Struct({\n MidiClip: ClipSchema.pipe(Schema.Array, Schema.optionalKey),\n});\n\nconst ArrangementSchema = Schema.Struct({\n ArrangerAutomation: Schema.Struct({ Events: ClipEventsSchema }),\n});\n\nconst SendHolderSchema = Schema.Struct({ Send: ParameterSchema });\n\nconst SendsSchema = Schema.Struct({\n TrackSendHolder: SendHolderSchema.pipe(Schema.Array, Schema.optionalKey),\n});\n\nconst SpeakerSchema = Schema.Struct({ Manual: Schema.optionalKey(Flag) });\n\nconst TrackMixerSchema = Schema.Struct({\n Volume: ParameterSchema,\n Pan: ParameterSchema,\n Speaker: Schema.optionalKey(SpeakerSchema),\n Sends: Schema.optionalKey(SendsSchema),\n});\n\nexport type AlsMixer = typeof TrackMixerSchema.Type;\n\nconst TrackChainSchema = Schema.Struct({\n DeviceChain: Schema.optionalKey(DevicesSchema),\n Mixer: Schema.optionalKey(TrackMixerSchema),\n MainSequencer: Schema.Struct({ ClipTimeable: ArrangementSchema }),\n});\n\nconst MidiTrackSchema = Schema.Struct({\n Id: Schema.String,\n Name: NameSchema,\n AutomationEnvelopes: Schema.optionalKey(EnvelopesSchema),\n DeviceChain: TrackChainSchema,\n});\n\nexport type AlsMidiTrack = typeof MidiTrackSchema.Type;\n\nconst ReturnTrackSchema = Schema.Struct({\n Name: NameSchema,\n DeviceChain: Schema.Struct({ Mixer: Schema.optionalKey(TrackMixerSchema) }),\n});\n\nexport type AlsReturnTrack = typeof ReturnTrackSchema.Type;\n\nconst MixerSchema = Schema.Struct({ Tempo: ParameterSchema, TimeSignature: ParameterSchema });\n\nconst MasterSchema = Schema.Struct({\n AutomationEnvelopes: Schema.optionalKey(EnvelopesSchema),\n DeviceChain: Schema.optionalKey(Schema.Struct({ Mixer: MixerSchema })),\n MasterChain: Schema.optionalKey(Schema.Struct({ Mixer: MixerSchema })),\n});\n\nexport type AlsMaster = typeof MasterSchema.Type;\n\nconst LocatorSchema = Schema.Struct({ Time: Num, Name: Text });\n\nexport type AlsLocator = typeof LocatorSchema.Type;\n\nconst TracksSchema = Schema.Struct({\n MidiTrack: MidiTrackSchema.pipe(Schema.Array, Schema.optionalKey),\n ReturnTrack: ReturnTrackSchema.pipe(Schema.Array, Schema.optionalKey),\n});\n\nconst LocatorListSchema = Schema.Struct({\n Locator: LocatorSchema.pipe(Schema.Array, Schema.optionalKey),\n});\n\nconst LiveSetSchema = Schema.Struct({\n Tracks: TracksSchema,\n MasterTrack: Schema.optionalKey(MasterSchema),\n MainTrack: Schema.optionalKey(MasterSchema),\n Locators: Schema.optionalKey(Schema.Struct({ Locators: LocatorListSchema })),\n});\n\nexport type LiveSet = typeof LiveSetSchema.Type;\n\nconst DocumentSchema = Schema.Struct({\n Ableton: Schema.Struct({\n MajorVersion: Schema.String,\n MinorVersion: Schema.String,\n Creator: Schema.optionalKey(Schema.String),\n LiveSet: LiveSetSchema,\n }),\n});\n\nconst decodeDocument = Schema.decodeUnknownEffect(DocumentSchema);\n\nconst isElement = Schema.is(Schema.Record(Schema.String, Schema.Unknown));\nconst isAttributes = Schema.is(Schema.Record(Schema.String, Schema.String));\n\nconst flattened = (node: unknown): unknown => {\n if (node === \"\") {\n return {};\n }\n if (Arr.isArray(node)) {\n return pipe(\n node,\n Arr.map((child) => flattened(child)),\n );\n }\n if (isElement(node)) {\n const { [ATTRIBUTES]: attributes, ...children } = node;\n const own = pipe(\n Option.liftPredicate(attributes, isAttributes),\n Option.getOrElse((): Readonly<Record<string, string>> => ({})),\n );\n return {\n ...pipe(\n children,\n Rec.map((child) => flattened(child)),\n ),\n ...own,\n };\n }\n return node;\n};\n\nconst gunzip = (bytes: Uint8Array): Effect.Effect<string, UnreadableAls> =>\n Effect.tryPromise({\n try: () =>\n new Response(\n new Blob([Uint8Array.from(bytes)]).stream().pipeThrough(new DecompressionStream(\"gzip\")),\n ).text(),\n catch: () => UnreadableAls.make({ message: \"The file is not a gzipped Live Set (.als)\" }),\n });\n\nexport type AlsDocument = typeof DocumentSchema.Type;\n\nexport const readAlsDocument: (bytes: Uint8Array) => Effect.Effect<AlsDocument, UnreadableAls> =\n Effect.fn(\"readAlsDocument\")(function* read(\n bytes: Uint8Array,\n ): Effect.fn.Return<AlsDocument, UnreadableAls> {\n const xml = yield* gunzip(bytes);\n const parsed = yield* Effect.try({\n try: () => flattened(parser.parse(xml)),\n catch: (cause) => UnreadableAls.make({ message: `Not XML: ${String(cause)}` }),\n });\n return yield* decodeDocument(parsed).pipe(\n Effect.mapError((issue) =>\n UnreadableAls.make({ message: `Not a Live Set this converter reads: ${String(issue)}` }),\n ),\n );\n });\n","import { Array as Arr, Option, Order, pipe } from \"effect\";\n\nimport type { From } from \"#/shared/lib/from.ts\";\n\nimport type { AlsClip } from \"./live-set.ts\";\n\nconst NONE = 0;\n\nexport interface PlayedNote {\n readonly beat: number;\n readonly length: number;\n readonly midi: number;\n readonly velocity: number;\n readonly release: number;\n}\n\ninterface Pass {\n readonly at: number;\n readonly from: number;\n readonly to: number;\n}\n\ninterface SourceNote {\n readonly time: number;\n readonly end: number;\n readonly midi: number;\n readonly velocity: number;\n readonly release: number;\n}\n\nconst DEFAULT_RELEASE = 64;\n\nconst modulo = (value: number, size: number): number => ((value % size) + size) % size;\n\nconst passesOf: From<AlsClip, readonly Pass[]> = (clip) => {\n const start = clip.CurrentStart.Value;\n const length = clip.CurrentEnd.Value - start;\n const loopStart = clip.Loop.LoopStart.Value;\n const loopLength = clip.Loop.LoopEnd.Value - loopStart;\n if (clip.Loop.LoopOn.Value === \"false\" || loopLength <= NONE) {\n return [{ at: start, from: loopStart, to: loopStart + length }];\n }\n const first = loopStart + modulo(clip.Loop.StartRelative.Value, loopLength);\n const walk = (elapsed: number, from: number, passes: readonly Pass[]): readonly Pass[] => {\n if (elapsed >= length) {\n return passes;\n }\n const span = Math.min(clip.Loop.LoopEnd.Value - from, length - elapsed);\n return walk(elapsed + span, loopStart, [\n ...passes,\n { at: start + elapsed, from, to: from + span },\n ]);\n };\n return walk(NONE, first, []);\n};\n\nconst releaseOf = (offVelocity: number | undefined): number =>\n pipe(\n Option.fromUndefinedOr(offVelocity),\n Option.filter((off) => off !== NONE),\n Option.match({ onNone: () => DEFAULT_RELEASE, onSome: Math.round }),\n );\n\nconst sourceNotesOf: From<AlsClip, readonly SourceNote[]> = (clip) =>\n pipe(\n clip.Notes.KeyTracks.KeyTrack ?? [],\n Arr.flatMap((keyTrack) =>\n pipe(\n keyTrack.Notes.MidiNoteEvent ?? [],\n Arr.filter((note) => note.IsEnabled !== \"false\"),\n Arr.map((note): SourceNote => ({\n time: note.Time,\n end: note.Time + note.Duration,\n midi: keyTrack.MidiKey.Value,\n velocity: Math.round(note.Velocity),\n release: releaseOf(note.OffVelocity),\n })),\n ),\n ),\n );\n\nconst inPass =\n (notes: readonly SourceNote[]): From<Pass, readonly PlayedNote[]> =>\n (pass) =>\n pipe(\n notes,\n Arr.filter((note) => note.time >= pass.from && note.time < pass.to),\n Arr.map((note): PlayedNote => ({\n beat: pass.at + note.time - pass.from,\n length: Math.min(note.end, pass.to) - note.time,\n midi: note.midi,\n velocity: note.velocity,\n release: note.release,\n })),\n );\n\nconst byStartThenPitch = Order.combine(\n Order.mapInput(Order.Number, (note: PlayedNote) => note.beat),\n Order.mapInput(Order.Number, (note: PlayedNote) => note.midi),\n);\n\nconst isDisabled: From<AlsClip, boolean> = (clip) =>\n Option.exists(Option.fromUndefinedOr(clip.Disabled), (flag) => flag.Value === \"true\");\n\nexport const notesOfClip: From<AlsClip, readonly PlayedNote[]> = (clip) => {\n if (isDisabled(clip)) {\n return [];\n }\n const notes = sourceNotesOf(clip);\n return pipe(passesOf(clip), Arr.flatMap(inPass(notes)), Arr.sortBy(byStartThenPitch));\n};\n","import { decodeTimeSignatureId } from \"ableton-als\";\nimport { Array as Arr, Chunk, Option, Order, pipe } from \"effect\";\n\nimport type { From } from \"#/shared/lib/from.ts\";\n\nimport type {\n AlsLocator,\n AlsMaster,\n AutomationEnvelope,\n AutomationEvent,\n LiveSet,\n Parameter,\n} from \"./live-set.ts\";\n\nexport const SONG_START = 0;\n\nexport interface Point {\n readonly beat: number;\n readonly value: number;\n}\n\nexport interface TempoSegment {\n readonly beat: number;\n readonly bpm: number;\n readonly target: Option.Option<number>;\n}\n\nexport interface MeterChange {\n readonly beat: number;\n readonly numerator: number;\n readonly denominator: number;\n}\n\nexport interface Locator {\n readonly beat: number;\n readonly name: string;\n}\n\nconst masterOf: From<LiveSet, Option.Option<AlsMaster>> = (liveSet) =>\n Option.orElse(Option.fromUndefinedOr(liveSet.MasterTrack), () =>\n Option.fromUndefinedOr(liveSet.MainTrack),\n );\n\ninterface Mixer {\n readonly Tempo: Parameter;\n readonly TimeSignature: Parameter;\n}\n\nconst mixerOf: From<AlsMaster, Option.Option<Mixer>> = (master) =>\n pipe(\n Option.fromUndefinedOr(master.DeviceChain),\n Option.orElse(() => Option.fromUndefinedOr(master.MasterChain)),\n Option.map((chain) => chain.Mixer),\n );\n\nconst eventsOf = (events: {\n readonly FloatEvent?: readonly AutomationEvent[];\n readonly EnumEvent?: readonly AutomationEvent[];\n readonly BoolEvent?: readonly AutomationEvent[];\n}): readonly AutomationEvent[] => [\n ...(events.FloatEvent ?? []),\n ...(events.EnumEvent ?? []),\n ...(events.BoolEvent ?? []),\n];\n\nexport type Automated = Pick<AlsMaster, \"AutomationEnvelopes\">;\n\nconst automationEnvelopesOf = (owner: Automated): readonly AutomationEnvelope[] =>\n pipe(\n Option.fromUndefinedOr(owner.AutomationEnvelopes),\n Option.flatMap((envelopes) => Option.fromUndefinedOr(envelopes.Envelopes.AutomationEnvelope)),\n Option.getOrElse((): readonly AutomationEnvelope[] => []),\n );\n\nconst byTime = Order.mapInput(Order.Number, (event: AutomationEvent) => event.Time);\n\nexport const envelopeOf =\n (owner: Automated): From<Parameter, readonly AutomationEvent[]> =>\n (parameter) => {\n const inline = pipe(\n Option.fromUndefinedOr(parameter.ArrangerAutomation),\n Option.map((automation) => automation.Events),\n );\n const pointed = pipe(\n Option.fromUndefinedOr(parameter.AutomationTarget),\n Option.flatMap((target) =>\n pipe(\n automationEnvelopesOf(owner),\n Arr.findFirst((envelope) => envelope.EnvelopeTarget.PointeeId.Value === target.Id),\n ),\n ),\n Option.map((envelope) => envelope.Automation.Events),\n );\n return pipe(\n Option.orElse(pointed, () => inline),\n Option.map(eventsOf),\n Option.getOrElse((): readonly AutomationEvent[] => []),\n Arr.sortBy(byTime),\n );\n };\n\nconst SINGLE = 1;\nconst NEXT = 1;\n\ninterface Automation {\n readonly events: readonly AutomationEvent[];\n readonly manual: Option.Option<number>;\n}\n\nconst automationOf =\n (select: From<Mixer, Parameter>): From<LiveSet, Option.Option<Automation>> =>\n (liveSet) =>\n pipe(\n masterOf(liveSet),\n Option.flatMap((master) =>\n pipe(\n mixerOf(master),\n Option.map((mixer): Automation => {\n const parameter = select(mixer);\n return {\n events: envelopeOf(master)(parameter),\n manual: pipe(\n Option.fromUndefinedOr(parameter.Manual),\n Option.map((manual) => manual.Value),\n ),\n };\n }),\n ),\n ),\n );\n\nconst tempoAutomationOf = automationOf((mixer) => mixer.Tempo);\n\nconst pointsOf = (events: readonly AutomationEvent[]): readonly Point[] =>\n pipe(\n events,\n Arr.map((event): Point => ({ beat: event.Time, value: Number(event.Value) })),\n );\n\nconst tempoFrom =\n (resolve: From<Automation, readonly Point[]>): From<LiveSet, readonly Point[]> =>\n (liveSet) =>\n pipe(\n tempoAutomationOf(liveSet),\n Option.map(resolve),\n Option.getOrElse((): readonly Point[] => []),\n );\n\nexport const tempoEnvelopeOf: From<LiveSet, readonly Point[]> = tempoFrom(({ events }) =>\n pointsOf(events),\n);\n\nconst manualPointsOf = tempoFrom(({ manual }) =>\n pipe(\n manual,\n Option.map((value): readonly Point[] => [{ beat: SONG_START, value }]),\n Option.getOrElse((): readonly Point[] => []),\n ),\n);\n\nexport const tempoPointsOf: From<LiveSet, readonly Point[]> = (liveSet) => {\n const envelope = tempoEnvelopeOf(liveSet);\n const manual = manualPointsOf(liveSet);\n if (envelope.length > SINGLE || !Arr.isReadonlyArrayNonEmpty(manual)) {\n return envelope;\n }\n return manual;\n};\n\nconst valueAt =\n (from: Point, to: Point): From<number, number> =>\n (beat) => {\n if (to.beat === from.beat) {\n return to.value;\n }\n return from.value + ((to.value - from.value) * (beat - from.beat)) / (to.beat - from.beat);\n };\n\nconst segmentOf = (from: Point, next: Option.Option<Point>): TempoSegment => {\n const start = Math.max(from.beat, SONG_START);\n return Option.match(next, {\n onNone: () => ({ beat: start, bpm: from.value, target: Option.none() }),\n onSome: (to) => {\n const bpm = valueAt(from, to)(start);\n if (to.beat <= start || to.value === bpm) {\n return { beat: start, bpm, target: Option.none() };\n }\n return { beat: start, bpm, target: Option.some(to.value) };\n },\n });\n};\n\nconst keptWith = (\n kept: Chunk.Chunk<TempoSegment>,\n segment: TempoSegment,\n): Chunk.Chunk<TempoSegment> => {\n const earlier = pipe(\n Chunk.last(kept),\n Option.filter((last) => last.beat === segment.beat),\n Option.match({ onNone: () => kept, onSome: () => Chunk.dropRight(kept, SINGLE) }),\n );\n const redundant = pipe(\n Chunk.last(earlier),\n Option.exists(\n (last) =>\n Option.isNone(last.target) && Option.isNone(segment.target) && last.bpm === segment.bpm,\n ),\n );\n if (redundant) {\n return earlier;\n }\n return Chunk.append(earlier, segment);\n};\n\nconst withoutRepeats = (segments: readonly TempoSegment[]): readonly TempoSegment[] => {\n let kept = Chunk.empty<TempoSegment>();\n for (const segment of segments) {\n kept = keptWith(kept, segment);\n }\n return Chunk.toReadonlyArray(kept);\n};\n\nexport const tempoSegmentsOf: From<readonly Point[], readonly TempoSegment[]> = (points) =>\n pipe(\n points,\n Arr.map((point, index) => ({ point, next: Arr.get(points, index + NEXT) })),\n Arr.filter(({ next }) =>\n Option.match(next, { onNone: () => true, onSome: (to) => to.beat > SONG_START }),\n ),\n Arr.map(({ point, next }) => segmentOf(point, next)),\n withoutRepeats,\n );\n\nconst meterOfId = (beat: number, id: number): Option.Option<MeterChange> =>\n pipe(\n Option.fromNullishOr(decodeTimeSignatureId(id)),\n Option.map((signature) => ({\n beat: Math.max(beat, SONG_START),\n numerator: signature.num,\n denominator: signature.den,\n })),\n );\n\nexport const metersOf: From<LiveSet, readonly MeterChange[]> = (liveSet) =>\n pipe(\n automationOf((mixer) => mixer.TimeSignature)(liveSet),\n Option.map(({ events, manual }) => {\n if (events.length > SINGLE || Option.isNone(manual)) {\n return pipe(\n events,\n Arr.map((event) => meterOfId(event.Time, Number(event.Value))),\n Arr.getSomes,\n Arr.reverse,\n Arr.dedupeAdjacentWith((later, earlier) => later.beat === earlier.beat),\n Arr.reverse,\n );\n }\n return Option.toArray(meterOfId(SONG_START, manual.value));\n }),\n Option.getOrElse((): readonly MeterChange[] => []),\n );\n\nconst byBeat = Order.mapInput(Order.Number, (locator: Locator) => locator.beat);\n\nexport const locatorsOf: From<LiveSet, readonly Locator[]> = (liveSet) =>\n pipe(\n Option.fromUndefinedOr(liveSet.Locators),\n Option.flatMap((locators) => Option.fromUndefinedOr(locators.Locators.Locator)),\n Option.getOrElse((): readonly AlsLocator[] => []),\n Arr.map((locator): Locator => ({ beat: locator.Time.Value, name: locator.Name.Value })),\n Arr.sortBy(byBeat),\n );\n","import type { From } from \"#/shared/lib/from.ts\";\nimport { TICKS_PER_WHOLE } from \"#/shared/lib/ticks.ts\";\n\nconst QUARTERS_PER_WHOLE = 4;\nconst TICKS_PER_BEAT = TICKS_PER_WHOLE / QUARTERS_PER_WHOLE;\n\nexport interface Tick {\n readonly tick: number;\n readonly exact: boolean;\n}\n\nexport const tickOf: From<number, Tick> = (beat) => {\n const exact = beat * TICKS_PER_BEAT;\n return { tick: Math.round(exact), exact: Number.isInteger(exact) };\n};\n","import { Array as Arr, Option, pipe } from \"effect\";\n\nimport { MIXER_PARAMETERS } from \"#/entities/song/index.ts\";\nimport type {\n BusMix,\n Envelope,\n Level,\n Mix,\n MixParameter,\n MixPoint,\n TrackMix,\n TrackSend,\n} from \"#/entities/timeline/index.ts\";\nimport type { From } from \"#/shared/lib/from.ts\";\n\nimport type { AlsMidiTrack, AlsMixer, AlsReturnTrack, LiveSet, Parameter } from \"./live-set.ts\";\nimport { SONG_START, envelopeOf } from \"./tempo-map.ts\";\nimport type { Automated } from \"./tempo-map.ts\";\nimport { tickOf } from \"./ticks.ts\";\n\nconst DECIBELS_PER_DECADE = 20;\nconst SILENT_DECIBELS = -70;\nconst AUDIBLE_SEND = 0.001;\nconst NONE = 0;\nconst NEXT = 1;\n\nconst DECIMAL_BASE = 10;\nconst SILENT = DECIMAL_BASE ** (SILENT_DECIBELS / DECIBELS_PER_DECADE);\n\nconst decibelsOf: From<number, number> = (gain) =>\n DECIBELS_PER_DECADE * Math.log10(Math.max(gain, SILENT));\n\nconst [VOLUME, PAN] = MIXER_PARAMETERS;\n\nconst VALUES: Readonly<Record<MixParameter, From<number, number>>> = {\n volume: decibelsOf,\n pan: (pan) => pan,\n};\n\nconst RESTING: Readonly<Record<MixParameter, number>> = { volume: NONE, pan: NONE };\n\ntype Owned = Readonly<{ owner: Automated; parameter: MixParameter }>;\n\nconst pointsOf =\n ({ owner, parameter }: Owned): From<Parameter, readonly MixPoint[]> =>\n (control) =>\n pipe(\n envelopeOf(owner)(control),\n Arr.map((event) => ({\n tick: tickOf(Math.max(event.Time, SONG_START)).tick,\n value: VALUES[parameter](Number(event.Value)),\n })),\n Arr.filter((point) => Number.isFinite(point.value)),\n );\n\nconst startOf =\n (owned: Owned): From<Parameter, number> =>\n (control) =>\n pipe(\n pointsOf(owned)(control),\n Arr.head,\n Option.map((point) => point.value),\n Option.orElse(() =>\n pipe(\n Option.fromUndefinedOr(control.Manual),\n Option.map((manual) => VALUES[owned.parameter](manual.Value)),\n ),\n ),\n Option.getOrElse(() => RESTING[owned.parameter]),\n );\n\nconst levelOf =\n (owner: Automated): From<AlsMixer, Level> =>\n (mixer) => ({\n decibels: startOf({ owner, parameter: VOLUME })(mixer.Volume),\n pan: startOf({ owner, parameter: PAN })(mixer.Pan),\n muted: pipe(\n Option.fromUndefinedOr(mixer.Speaker),\n Option.flatMap((speaker) => Option.fromUndefinedOr(speaker.Manual)),\n Option.exists((manual) => manual.Value === \"false\"),\n ),\n });\n\nconst sendsOf: From<AlsMixer, readonly TrackSend[]> = (mixer) =>\n pipe(\n Option.fromUndefinedOr(mixer.Sends),\n Option.flatMap((sends) => Option.fromUndefinedOr(sends.TrackSendHolder)),\n Option.getOrElse(() => []),\n Arr.map((holder, bus) => ({\n bus,\n amount: pipe(\n Option.fromUndefinedOr(holder.Send.Manual),\n Option.match({ onNone: () => NONE, onSome: (manual) => manual.Value }),\n ),\n })),\n Arr.filter((send) => send.amount > AUDIBLE_SEND),\n );\n\nconst envelopesOf =\n (owner: Automated): From<AlsMixer, readonly Envelope[]> =>\n (mixer) =>\n pipe(\n [\n { parameter: \"volume\" as const, control: mixer.Volume },\n { parameter: \"pan\" as const, control: mixer.Pan },\n ],\n Arr.map(({ parameter, control }) => ({\n parameter,\n points: pointsOf({ owner, parameter })(control),\n })),\n Arr.filter((envelope) => envelope.points.length > NEXT),\n );\n\nconst trackMixOf: From<AlsMidiTrack, Option.Option<TrackMix>> = (track) =>\n pipe(\n Option.fromUndefinedOr(track.DeviceChain.Mixer),\n Option.map((mixer) => ({\n level: levelOf(track)(mixer),\n sends: sendsOf(mixer),\n envelopes: envelopesOf(track)(mixer),\n })),\n );\n\nconst NO_ENVELOPES: Automated = {};\n\nconst busOf =\n (nameOf: From<AlsReturnTrack[\"Name\"], Option.Option<string>>): From<AlsReturnTrack, BusMix> =>\n (track) => ({\n name: nameOf(track.Name),\n level: pipe(\n Option.fromUndefinedOr(track.DeviceChain.Mixer),\n Option.match({\n onNone: () => ({ decibels: NONE, pan: NONE, muted: false }),\n onSome: levelOf(NO_ENVELOPES),\n }),\n ),\n });\n\nexport const mixOf =\n (nameOf: From<AlsReturnTrack[\"Name\"], Option.Option<string>>): From<LiveSet, Mix> =>\n (liveSet) => ({\n tracks: new Map(\n pipe(\n liveSet.Tracks.MidiTrack ?? [],\n Arr.flatMap((track, index) =>\n pipe(\n trackMixOf(track),\n Option.map((mix) => [index, mix] as const),\n Option.toArray,\n ),\n ),\n ),\n ),\n buses: pipe(liveSet.Tracks.ReturnTrack ?? [], Arr.map(busOf(nameOf))),\n });\n","import { Array as Arr, Boolean as Bool, Option, pipe } from \"effect\";\n\nimport { microsecondsOf, sortedByTick, sortedNotes } from \"#/entities/timeline/index.ts\";\nimport type { Part, TempoChange, Timeline, TimelineNote } from \"#/entities/timeline/index.ts\";\nimport type { From } from \"#/shared/lib/from.ts\";\n\nimport { notesOfClip } from \"./clips.ts\";\nimport type { PlayedNote } from \"./clips.ts\";\nimport type { AlsMidiTrack, LiveSet } from \"./live-set.ts\";\nimport { mixOf } from \"./mix.ts\";\nimport { locatorsOf, metersOf, tempoPointsOf, tempoSegmentsOf } from \"./tempo-map.ts\";\nimport { tickOf } from \"./ticks.ts\";\n\nconst MELODIC_CHANNEL = 0;\nconst DRUM_CHANNEL = 9;\nconst NONE = 0;\nconst NEXT = 1;\n\nconst nameOf: From<AlsMidiTrack[\"Name\"], Option.Option<string>> = (label) =>\n pipe(\n [label.EffectiveName, label.UserName],\n Arr.map(Option.fromUndefinedOr),\n Arr.getSomes,\n Arr.map((name) => name.Value),\n Arr.findFirst((name) => name !== \"\"),\n );\n\nconst isDrumRack: From<AlsMidiTrack, boolean> = (track) =>\n pipe(\n Option.fromUndefinedOr(track.DeviceChain.DeviceChain),\n Option.flatMap((chain) => Option.fromUndefinedOr(chain.Devices)),\n Option.flatMap((devices) => Option.fromUndefinedOr(devices.DrumGroupDevice)),\n Option.isSome,\n );\n\ninterface TrackNotes {\n readonly notes: readonly TimelineNote[];\n readonly offGrid: number;\n}\n\nconst trackNotesOf: From<AlsMidiTrack, TrackNotes> = (track) => {\n const played: readonly PlayedNote[] = pipe(\n track.DeviceChain.MainSequencer.ClipTimeable.ArrangerAutomation.Events.MidiClip ?? [],\n Arr.flatMap(notesOfClip),\n );\n const placed = pipe(\n played,\n Arr.map((note) => ({\n note,\n start: tickOf(note.beat),\n end: tickOf(note.beat + note.length),\n })),\n );\n return {\n notes: sortedNotes(\n pipe(\n placed,\n Arr.map(({ note, start, end }): TimelineNote => ({\n tick: start.tick,\n end: end.tick,\n midi: note.midi,\n velocity: note.velocity,\n release: note.release,\n })),\n ),\n ),\n offGrid: Arr.countBy(placed, ({ start, end }) => !start.exact || !end.exact),\n };\n};\n\ninterface PartRead {\n readonly part: Part;\n readonly offGrid: number;\n}\n\nconst partOf = (track: AlsMidiTrack, index: number): PartRead => {\n const read = trackNotesOf(track);\n return {\n part: {\n track: index,\n channel: Bool.match(isDrumRack(track), {\n onFalse: () => MELODIC_CHANNEL,\n onTrue: () => DRUM_CHANNEL,\n }),\n name: nameOf(track.Name),\n program: Option.none(),\n notes: read.notes,\n controls: [],\n lyrics: [],\n },\n offGrid: read.offGrid,\n };\n};\n\nconst temposOf: From<LiveSet, readonly TempoChange[]> = (liveSet) =>\n pipe(\n tempoSegmentsOf(tempoPointsOf(liveSet)),\n Arr.map((segment): TempoChange => ({\n tick: tickOf(segment.beat).tick,\n microseconds: microsecondsOf(segment.bpm),\n target: pipe(segment.target, Option.map(microsecondsOf)),\n })),\n );\n\nconst lastOf: From<readonly number[], number> = (ticks) =>\n Arr.reduce(ticks, NONE, (latest, tick) => Math.max(latest, tick));\n\nexport const timelineOf: From<LiveSet, Timeline> = (liveSet) => {\n const reads = pipe(\n liveSet.Tracks.MidiTrack ?? [],\n Arr.map(partOf),\n Arr.filter((read) => Arr.isReadonlyArrayNonEmpty(read.part.notes)),\n );\n const parts = pipe(\n reads,\n Arr.map((read) => read.part),\n );\n const markers = sortedByTick(\n pipe(\n locatorsOf(liveSet),\n Arr.map((locator) => ({ tick: tickOf(locator.beat).tick, text: locator.name })),\n ),\n );\n const tempos = temposOf(liveSet);\n const meters = pipe(\n metersOf(liveSet),\n Arr.map((meter) => ({\n tick: tickOf(meter.beat).tick,\n numerator: meter.numerator,\n denominator: meter.denominator,\n })),\n );\n const noteEnds = pipe(\n parts,\n Arr.flatMap((part) => part.notes),\n Arr.map((note) => note.end),\n );\n const pointEnds = pipe(\n [...markers, ...tempos, ...meters],\n Arr.map((point) => point.tick + NEXT),\n );\n return {\n title: Option.none(),\n end: lastOf([...noteEnds, ...pointEnds]),\n offGrid: Arr.reduce(reads, NONE, (sum, read) => sum + read.offGrid),\n tempos,\n meters,\n markers,\n parts,\n mix: mixOf(nameOf)(liveSet),\n };\n};\n","import { Effect } from \"effect\";\n\nimport { writeFumx } from \"#/entities/timeline/index.ts\";\nimport type { Written } from \"#/entities/timeline/index.ts\";\n\nimport { readAlsDocument } from \"./live-set.ts\";\nimport { timelineOf } from \"./timeline.ts\";\n\nexport interface LiveSetFile {\n readonly bytes: Uint8Array;\n readonly title: string;\n}\n\nexport interface Fumx extends Written {\n readonly offGrid: number;\n}\n\nexport const alsToFumx = Effect.fn(\"alsToFumx\")(function* convert(input: LiveSetFile) {\n const document = yield* readAlsDocument(input.bytes);\n const timeline = yield* Effect.sync(() => timelineOf(document.Ableton.LiveSet)).pipe(\n Effect.withSpan(\"timelineOf\"),\n );\n const written = yield* Effect.sync(() => writeFumx({ timeline, title: input.title })).pipe(\n Effect.withSpan(\"writeFumx\"),\n );\n yield* Effect.annotateCurrentSpan({\n creator: document.Ableton.Creator ?? \"\",\n parts: written.plan.parts.length,\n bars: written.bars.length,\n });\n const fumx: Fumx = { ...written, offGrid: timeline.offGrid };\n return fumx;\n});\n","import { Array as Arr, Effect, Schema, pipe } from \"effect\";\n\nimport { compareWithSong } from \"#/entities/timeline/index.ts\";\nimport type { Comparison, Written } from \"#/entities/timeline/index.ts\";\nimport { readSong } from \"#/features/read-song/index.ts\";\nimport type { SourceIssue } from \"#/features/read-song/index.ts\";\n\nconst taggedError = Schema.TaggedError;\n\nexport class InvalidOutput extends taggedError<InvalidOutput, { readonly brand: unique symbol }>()(\n \"InvalidOutput\",\n { message: Schema.String, text: Schema.String },\n { identifier: \"InvalidOutput\" },\n) {}\n\nexport interface Adjustments {\n readonly offGrid: number;\n}\n\nexport interface Converted {\n readonly text: string;\n readonly comparison: Comparison;\n readonly adjustments: Adjustments;\n}\n\nexport interface Checked extends Written {\n readonly offGrid: number;\n}\n\nconst issueText = (issue: SourceIssue): string =>\n `${String(issue.line)}:${String(issue.column)} ${issue.message}`;\n\nexport const roundTrip = Effect.fn(\"roundTrip\")(function* check(path: string, fumx: Checked) {\n const read = yield* readSong({ path, read: () => Effect.succeed(fumx.text) }).pipe(\n Effect.withSpan(\"readSong\"),\n );\n if (read.status === \"invalid\") {\n return yield* InvalidOutput.make({\n message: pipe(read.issues, Arr.map(issueText), Arr.join(\"\\n\")),\n text: fumx.text,\n });\n }\n const comparison = compareWithSong({ plan: fumx.plan, bars: fumx.bars, song: read.song });\n yield* Effect.annotateCurrentSpan({\n matches: comparison.matches,\n notes: comparison.notes.expected,\n });\n const converted: Converted = {\n text: fumx.text,\n comparison,\n adjustments: { offGrid: fumx.offGrid },\n };\n return converted;\n});\n","import { Effect } from \"effect\";\n\nimport { alsToFumx } from \"#/features/convert-als/index.ts\";\nimport type { LiveSetFile } from \"#/features/convert-als/index.ts\";\n\nimport { roundTrip } from \"./round-trip.ts\";\n\nexport interface LiveSetSource extends LiveSetFile {\n readonly path: string;\n}\n\nexport const convertLiveSetFile = Effect.fn(\"convertLiveSetFile\")(function* convert(\n source: LiveSetSource,\n) {\n const fumx = yield* alsToFumx(source);\n return yield* roundTrip(source.path, fumx);\n});\n","import { Array as Arr, Match, Option, Record as Rec, pipe } from \"effect\";\n\nimport { sortedNotes } from \"#/entities/timeline/index.ts\";\nimport type { TimelineControl, TimelineNote } from \"#/entities/timeline/index.ts\";\nimport type { From } from \"#/shared/lib/from.ts\";\n\nimport type { ChannelEvent, PlacedEvent } from \"./placed.ts\";\n\nconst NONE = 0;\nconst NEXT = 1;\nconst DEFAULT_RELEASE = 64;\nconst DEFAULT_BEND_RANGE = 2;\nconst CENTS_PER_SEMITONE = 100;\nconst BEND_HALF = 8192;\nconst RPN_MSB = 101;\nconst RPN_LSB = 100;\nconst DATA_MSB = 6;\nconst DATA_LSB = 38;\nconst PITCH_BEND_RPN = 0;\nconst UNSET = 127;\n\ninterface Edge {\n readonly tick: number;\n readonly on: boolean;\n readonly velocity: number;\n}\n\ntype PitchEdge = readonly [number, Edge];\n\nconst edgeOf: From<PlacedEvent, Option.Option<PitchEdge>> = ({ tick, event }) =>\n Match.value(event).pipe(\n Match.when({ type: \"noteOn\" }, (on): Option.Option<PitchEdge> =>\n Option.some([on.noteNumber, { tick, on: on.velocity > NONE, velocity: on.velocity }]),\n ),\n Match.when({ type: \"noteOff\" }, (off): Option.Option<PitchEdge> =>\n Option.some([off.noteNumber, { tick, on: false, velocity: off.velocity }]),\n ),\n Match.orElse(() => Option.none<PitchEdge>()),\n );\n\ninterface Pairing {\n readonly open: readonly Edge[];\n readonly notes: readonly TimelineNote[];\n}\n\nconst releaseOf: From<Edge, number> = (edge) => {\n if (edge.velocity === NONE) {\n return DEFAULT_RELEASE;\n }\n return edge.velocity;\n};\n\nconst START_PAIRING: Pairing = { open: [], notes: [] };\n\nconst pairStep =\n (midi: number) =>\n (pairing: Pairing, edge: Edge): Pairing => {\n if (edge.on) {\n return { ...pairing, open: [...pairing.open, edge] };\n }\n return Option.match(Arr.head(pairing.open), {\n onNone: () => pairing,\n onSome: (started) => ({\n open: Arr.drop(pairing.open, NEXT),\n notes: [\n ...pairing.notes,\n {\n tick: started.tick,\n end: edge.tick,\n midi,\n velocity: started.velocity,\n release: releaseOf(edge),\n },\n ],\n }),\n });\n };\n\nconst pairedOf =\n (end: number): From<readonly PitchEdge[], readonly TimelineNote[]> =>\n (edges) => {\n const midi = pipe(\n Arr.head(edges),\n Option.match({ onNone: () => NONE, onSome: ([pitch]) => pitch }),\n );\n const steps = pipe(\n edges,\n Arr.map(([, edge]) => edge),\n );\n const paired = Arr.reduce(steps, START_PAIRING, pairStep(midi));\n const unended = pipe(\n paired.open,\n Arr.map((started) => ({\n tick: started.tick,\n end,\n midi,\n velocity: started.velocity,\n release: DEFAULT_RELEASE,\n })),\n );\n return [...paired.notes, ...unended];\n };\n\nconst notesOf =\n (end: number): From<readonly PlacedEvent[], readonly TimelineNote[]> =>\n (events) => {\n const notes = pipe(\n events,\n Arr.map(edgeOf),\n Arr.getSomes,\n Arr.groupBy(([midi]) => String(midi)),\n Rec.values,\n Arr.flatMap(pairedOf(end)),\n );\n return sortedNotes(notes);\n };\n\ninterface Rpn {\n readonly msb: number;\n readonly lsb: number;\n readonly semitones: number;\n readonly cents: number;\n}\n\nconst START_RPN: Rpn = { msb: UNSET, lsb: UNSET, semitones: DEFAULT_BEND_RANGE, cents: NONE };\n\nconst isBendRange: From<Rpn, boolean> = (rpn) =>\n rpn.msb === PITCH_BEND_RPN && rpn.lsb === PITCH_BEND_RPN;\n\ntype ControllerEvent = Extract<ChannelEvent, { readonly type: \"controller\" }>;\n\nconst rpnAfter =\n (rpn: Rpn): From<ControllerEvent, Rpn> =>\n ({ controllerType, value }) => {\n if (controllerType === RPN_MSB) {\n return { ...rpn, msb: value };\n }\n if (controllerType === RPN_LSB) {\n return { ...rpn, lsb: value };\n }\n if (isBendRange(rpn) && controllerType === DATA_MSB) {\n return { ...rpn, semitones: value };\n }\n if (isBendRange(rpn) && controllerType === DATA_LSB) {\n return { ...rpn, cents: value };\n }\n return rpn;\n };\n\nconst rpnStep: From<readonly [Rpn, PlacedEvent], Rpn> = ([rpn, { event }]) => {\n if (event.type !== \"controller\") {\n return rpn;\n }\n return rpnAfter(rpn)(event);\n};\n\nconst controlOf: From<readonly [PlacedEvent, Rpn], Option.Option<TimelineControl>> = ([\n { tick, event },\n rpn,\n]) =>\n Match.value(event).pipe(\n Match.when({ type: \"controller\" }, (cc) =>\n Option.some<TimelineControl>({\n tick,\n controller: { kind: \"cc\", number: cc.controllerType },\n value: cc.value,\n }),\n ),\n Match.when({ type: \"programChange\" }, (change) =>\n Option.some<TimelineControl>({\n tick,\n controller: { kind: \"program\" },\n value: change.programNumber,\n }),\n ),\n Match.when({ type: \"channelAftertouch\" }, (pressure) =>\n Option.some<TimelineControl>({\n tick,\n controller: { kind: \"pressure\", midi: Option.none() },\n value: pressure.amount,\n }),\n ),\n Match.when({ type: \"noteAftertouch\" }, (pressure) =>\n Option.some<TimelineControl>({\n tick,\n controller: { kind: \"pressure\", midi: Option.some(pressure.noteNumber) },\n value: pressure.amount,\n }),\n ),\n Match.when({ type: \"pitchBend\" }, (bend) =>\n Option.some<TimelineControl>({\n tick,\n controller: { kind: \"bend\" },\n value: (bend.value * (rpn.semitones + rpn.cents / CENTS_PER_SEMITONE)) / BEND_HALF,\n }),\n ),\n Match.orElse(() => Option.none<TimelineControl>()),\n );\n\nconst controlsOf: From<readonly PlacedEvent[], readonly TimelineControl[]> = (events) =>\n pipe(\n Arr.zip(\n events,\n Arr.scan(events, START_RPN, (rpn, placed) => rpnStep([rpn, placed])),\n ),\n Arr.map(controlOf),\n Arr.getSomes,\n );\n\nexport interface ChannelRead {\n readonly channel: number;\n readonly notes: readonly TimelineNote[];\n readonly controls: readonly TimelineControl[];\n readonly program: Option.Option<number>;\n}\n\nconst isProgram: From<TimelineControl, boolean> = (control) =>\n control.controller.kind === \"program\";\n\nconst initialProgramOf: From<Omit<ChannelRead, \"program\">, Option.Option<TimelineControl>> = (\n read,\n) =>\n pipe(\n Arr.findFirst(read.controls, isProgram),\n Option.filter((program) =>\n pipe(\n Arr.head(read.notes),\n Option.match({ onNone: () => true, onSome: (note) => program.tick <= note.tick }),\n ),\n ),\n );\n\nexport const channelReadOf =\n (end: number): From<readonly [string, readonly PlacedEvent[]], ChannelRead> =>\n ([channel, events]) => {\n const read = {\n channel: Number(channel),\n notes: notesOf(end)(events),\n controls: controlsOf(events),\n };\n const program = initialProgramOf(read);\n return {\n ...read,\n program: pipe(\n program,\n Option.map((control) => control.value),\n ),\n controls: Option.match(program, {\n onNone: () => read.controls,\n onSome: (first) =>\n pipe(\n read.controls,\n Arr.filter((control) => control !== first),\n ),\n }),\n };\n };\n","import { Array as Arr, Match, Option, Order, Record as Rec, pipe } from \"effect\";\nimport type { MidiData, MidiEvent } from \"midi-file\";\n\nimport { NO_MIX, sortedByTick } from \"#/entities/timeline/index.ts\";\nimport type { Meter, Part, TempoChange, Text, Timed, Timeline } from \"#/entities/timeline/index.ts\";\nimport type { From } from \"#/shared/lib/from.ts\";\nimport { TICKS_PER_WHOLE } from \"#/shared/lib/ticks.ts\";\n\nimport { channelReadOf } from \"./channel.ts\";\nimport type { ChannelRead } from \"./channel.ts\";\nimport type { PlacedEvent } from \"./placed.ts\";\n\nconst QUARTERS_PER_WHOLE = 4;\nconst NONE = 0;\nconst NEXT = 1;\n\ninterface Placed {\n readonly tick: number;\n readonly exact: boolean;\n readonly event: MidiEvent;\n}\n\nconst placedOf =\n (ppq: number): From<readonly MidiEvent[], readonly Placed[]> =>\n (events) => {\n const raw = Arr.scan(events, NONE, (tick, event) => tick + event.deltaTime);\n return pipe(\n events,\n Arr.map((event, index) => {\n const absolute = Option.getOrElse(Arr.get(raw, index + NEXT), () => NONE);\n const exact = (absolute * TICKS_PER_WHOLE) / (ppq * QUARTERS_PER_WHOLE);\n return { tick: Math.round(exact), exact: Number.isInteger(exact), event };\n }),\n );\n };\n\nconst channelEventOf: From<Placed, Option.Option<PlacedEvent>> = ({ tick, event }) => {\n if (\"channel\" in event) {\n return Option.some({ tick, event });\n }\n return Option.none();\n};\n\ntype TextKind = \"name\" | \"lyric\" | \"marker\";\n\ntype KindedText = readonly [TextKind, Text];\n\ninterface TrackRead {\n readonly name: Option.Option<string>;\n readonly end: number;\n readonly offGrid: number;\n readonly channels: readonly ChannelRead[];\n readonly texts: Readonly<Record<string, readonly Text[]>>;\n readonly tempos: readonly TempoChange[];\n readonly meters: readonly Meter[];\n}\n\nconst textOf: From<Placed, Option.Option<KindedText>> = ({ tick, event }) =>\n Match.value(event).pipe(\n Match.when({ type: \"trackName\" }, (text): Option.Option<KindedText> =>\n Option.some([\"name\", { tick, text: text.text }]),\n ),\n Match.when({ type: \"lyrics\" }, (text): Option.Option<KindedText> =>\n Option.some([\"lyric\", { tick, text: text.text }]),\n ),\n Match.when({ type: \"marker\" }, (text): Option.Option<KindedText> =>\n Option.some([\"marker\", { tick, text: text.text }]),\n ),\n Match.orElse(() => Option.none<KindedText>()),\n );\n\nconst tempoOf: From<Placed, Option.Option<TempoChange>> = ({ tick, event }) =>\n Match.value(event).pipe(\n Match.when({ type: \"setTempo\" }, (tempo) =>\n Option.some<TempoChange>({\n tick,\n microseconds: tempo.microsecondsPerBeat,\n target: Option.none(),\n }),\n ),\n Match.orElse(() => Option.none<TempoChange>()),\n );\n\nconst meterOf: From<Placed, Option.Option<Meter>> = ({ tick, event }) =>\n Match.value(event).pipe(\n Match.when({ type: \"timeSignature\" }, (meter) =>\n Option.some<Meter>({ tick, numerator: meter.numerator, denominator: meter.denominator }),\n ),\n Match.orElse(() => Option.none<Meter>()),\n );\n\nconst textsOf: From<readonly Placed[], Readonly<Record<string, readonly Text[]>>> = (placed) =>\n pipe(\n placed,\n Arr.map(textOf),\n Arr.getSomes,\n Arr.groupBy(([kind]): string => kind),\n Rec.map((entries) =>\n pipe(\n entries,\n Arr.map(([, text]) => text),\n ),\n ),\n );\n\nconst textsIn =\n (kind: TextKind): From<Pick<TrackRead, \"texts\">, readonly Text[]> =>\n (read) =>\n Option.getOrElse(Rec.get(read.texts, kind), () => []);\n\nconst byChannel = Order.mapInput(Order.Number, (read: ChannelRead) => read.channel);\n\nconst channelsOf =\n (end: number): From<readonly Placed[], readonly ChannelRead[]> =>\n (placed) => {\n const reads = pipe(\n placed,\n Arr.map(channelEventOf),\n Arr.getSomes,\n Arr.groupBy((item) => String(item.event.channel)),\n Rec.toEntries,\n Arr.map(channelReadOf(end)),\n );\n return Arr.sort(reads, byChannel);\n };\n\nconst readTrack =\n (ppq: number): From<readonly MidiEvent[], TrackRead> =>\n (events) => {\n const placed = placedOf(ppq)(events);\n const end = pipe(\n Arr.last(placed),\n Option.match({ onNone: () => NONE, onSome: (last) => last.tick }),\n );\n const texts = textsOf(placed);\n return {\n name: pipe(\n Arr.head(textsIn(\"name\")({ texts })),\n Option.map((text) => text.text),\n ),\n end,\n offGrid: Arr.countBy(placed, (item) => !item.exact),\n channels: channelsOf(end)(placed),\n texts,\n tempos: pipe(placed, Arr.map(tempoOf), Arr.getSomes),\n meters: pipe(placed, Arr.map(meterOf), Arr.getSomes),\n };\n };\n\nconst isUsed: From<ChannelRead, boolean> = (read) =>\n Arr.isReadonlyArrayNonEmpty(read.notes) ||\n Arr.isReadonlyArrayNonEmpty(read.controls) ||\n Option.isSome(read.program);\n\nconst partsOf = (read: TrackRead, track: number): readonly Part[] => {\n const lyrics = textsIn(\"lyric\")(read);\n return pipe(\n read.channels,\n Arr.filter(isUsed),\n Arr.map((channel) => ({\n ...channel,\n track,\n name: read.name,\n lyrics: pipe(\n lyrics,\n Arr.filter((lyric) =>\n pipe(\n channel.notes,\n Arr.some((note) => note.tick === lyric.tick),\n ),\n ),\n ),\n })),\n );\n};\n\nconst titleOf: From<readonly TrackRead[], Option.Option<string>> = (reads) =>\n pipe(\n Arr.head(reads),\n Option.filter((read) => !Arr.isReadonlyArrayNonEmpty(read.channels)),\n Option.flatMap((read) => read.name),\n );\n\nconst endsOf: From<TrackRead, readonly number[]> = (read) => [\n read.end,\n ...pipe(\n read.channels,\n Arr.flatMap((channel) => channel.notes),\n Arr.map((note) => note.end),\n ),\n];\n\nconst sortedFrom =\n <Item extends Timed>(\n pick: From<TrackRead, readonly Item[]>,\n ): From<readonly TrackRead[], readonly Item[]> =>\n (reads) =>\n sortedByTick(pipe(reads, Arr.flatMap(pick)));\n\nexport const timelineOf: From<MidiData, Timeline> = (midi) => {\n const reads = pipe(midi.tracks, Arr.map(readTrack(midi.header.ticksPerBeat ?? NONE)));\n return {\n title: titleOf(reads),\n end: Arr.reduce(pipe(reads, Arr.flatMap(endsOf)), NONE, (latest, tick) =>\n Math.max(latest, tick),\n ),\n offGrid: Arr.reduce(reads, NONE, (total, read) => total + read.offGrid),\n tempos: sortedFrom((read) => read.tempos)(reads),\n meters: sortedFrom((read) => read.meters)(reads),\n markers: sortedFrom(textsIn(\"marker\"))(reads),\n parts: pipe(\n reads,\n Arr.flatMap((read, index) => partsOf(read, index)),\n ),\n mix: NO_MIX,\n };\n};\n","import { Effect, Option, Schema, Predicate } from \"effect\";\nimport { parseMidi } from \"midi-file\";\n\nimport { writeFumx } from \"#/entities/timeline/index.ts\";\nimport type { Written } from \"#/entities/timeline/index.ts\";\n\nimport { timelineOf } from \"./timeline.ts\";\n\nconst taggedError = Schema.TaggedError;\n\nexport class UnreadableMidi extends taggedError<\n UnreadableMidi,\n { readonly brand: unique symbol }\n>()(\"UnreadableMidi\", { message: Schema.String }, { identifier: \"UnreadableMidi\" }) {}\n\nexport interface MidiFile {\n readonly bytes: Uint8Array;\n readonly title: string;\n}\n\nexport interface Fumx extends Written {\n readonly offGrid: number;\n}\n\nexport const midiToFumx = Effect.fn(\"midiToFumx\")(function* convert(input: MidiFile) {\n const midi = yield* Effect.try({\n try: () => parseMidi(input.bytes),\n catch: (cause) => UnreadableMidi.make({ message: String(cause) }),\n });\n if (Predicate.isUndefined(midi.header.ticksPerBeat)) {\n return yield* UnreadableMidi.make({ message: \"SMPTE time division is not supported\" });\n }\n const timeline = yield* Effect.sync(() => timelineOf(midi)).pipe(Effect.withSpan(\"timelineOf\"));\n const written = yield* Effect.sync(() =>\n writeFumx({ timeline, title: Option.getOrElse(timeline.title, () => input.title) }),\n ).pipe(Effect.withSpan(\"writeFumx\"));\n yield* Effect.annotateCurrentSpan({\n parts: written.plan.parts.length,\n bars: written.bars.length,\n });\n const fumx: Fumx = { ...written, offGrid: timeline.offGrid };\n return fumx;\n});\n","import { Effect } from \"effect\";\n\nimport { midiToFumx } from \"#/features/convert-midi/index.ts\";\nimport type { MidiFile } from \"#/features/convert-midi/index.ts\";\n\nimport { roundTrip } from \"./round-trip.ts\";\n\nexport interface MidiSource extends MidiFile {\n readonly path: string;\n}\n\nexport const convertMidiFile = Effect.fn(\"convertMidiFile\")(function* convert(source: MidiSource) {\n const fumx = yield* midiToFumx(source);\n return yield* roundTrip(source.path, fumx);\n});\n","import { Console, Effect, FileSystem, Option, Path, Schema, String as Str } from \"effect\";\nimport { Argument, Command, Flag } from \"effect/cli\";\n\nimport { convertLiveSetFile } from \"./als-to-fumx.ts\";\nimport { convertMidiFile } from \"./midi-to-fumx.ts\";\n\nconst INDENT = 2;\n\nconst taggedError = Schema.TaggedError;\n\nclass Mismatch extends taggedError<Mismatch, { readonly brand: unique symbol }>()(\n \"Mismatch\",\n { message: Schema.String },\n { identifier: \"Mismatch\" },\n) {}\n\nconst encodeSummary = Schema.encodeUnknownEffect(\n Schema.fromJsonString(Schema.Unknown, { space: INDENT }),\n);\n\ninterface Source {\n readonly bytes: Uint8Array;\n readonly title: string;\n readonly path: string;\n}\n\nconst LIVE_SET = \".als\";\n\nconst convertSource = Effect.fn(\"convertSource\")(function* convertSource(\n input: string,\n source: Source,\n) {\n if (Str.endsWith(LIVE_SET)(Str.toLowerCase(input))) {\n return { converted: yield* convertLiveSetFile(source), from: \"Live Set\" };\n }\n return { converted: yield* convertMidiFile(source), from: \"MIDI file\" };\n});\n\nconst convertFile = Effect.fn(\"convertFile\")(function* convertFile(\n file: string,\n out: Option.Option<string>,\n) {\n const fileSystem = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const input = path.resolve(file);\n const parsed = path.parse(input);\n const target = Option.match(out, {\n onNone: () => path.join(parsed.dir, `${parsed.name}.fumx`),\n onSome: (given) => path.resolve(given),\n });\n const bytes = yield* fileSystem.readFile(input);\n const { converted, from } = yield* convertSource(input, {\n bytes,\n title: parsed.name,\n path: target,\n });\n yield* fileSystem.writeFileString(target, converted.text);\n return {\n from,\n summary: {\n output: target,\n comparison: converted.comparison,\n adjustments: converted.adjustments,\n },\n };\n});\n\n/** @internal */\nexport const convertCommand = Command.make(\n \"convert\",\n {\n file: Argument.String(\"file\").pipe(\n Argument.withDescription(\n \"A Standard MIDI File (.mid) or an Ableton Live Set (.als); writes it as .fumx, reads it back and fails if any event differs\",\n ),\n ),\n out: Flag.String(\"out\").pipe(\n Flag.withDescription(\n \"Where to write the .fumx file; defaults to the input's name with .fumx\",\n ),\n Flag.optional,\n ),\n },\n ({ file, out }) =>\n convertFile(file, out).pipe(\n Effect.tap(({ summary }) => Effect.flatMap(encodeSummary(summary), Console.log)),\n Effect.filterOrFail(\n ({ summary }) => summary.comparison.matches,\n ({ from }) =>\n Mismatch.make({\n message: `The written .fumx does not reproduce every event of the ${from}`,\n }),\n ),\n Effect.asVoid,\n ),\n).pipe(\n Command.withDescription(\n \"Converts a MIDI file or an Ableton Live Set to .fumx and checks the result against the original\",\n ),\n);\n","import { Effect, Schema } from \"effect\";\nimport { Command, Flag } from \"effect/cli\";\nimport { inject } from \"langium\";\nimport { createDefaultModule, createDefaultSharedModule, startLanguageServer } from \"langium/lsp\";\nimport { NodeFileSystem } from \"langium/node\";\nimport { createConnection, ProposedFeatures } from \"vscode-languageserver/node\";\n\nimport { FumxModule, registerChecks } from \"#/features/read-song/index.ts\";\nimport { FumxGeneratedModule, FumxGeneratedSharedModule } from \"#generated/langium/module.ts\";\n\nconst taggedError = Schema.TaggedError;\n\nclass MissingTransport extends taggedError<MissingTransport, { readonly brand: unique symbol }>()(\n \"MissingTransport\",\n { message: Schema.String },\n) {}\n\nconst startServer = (): void => {\n const connection = createConnection(ProposedFeatures.all);\n const shared = inject(\n createDefaultSharedModule({ connection, ...NodeFileSystem }),\n FumxGeneratedSharedModule,\n );\n const fumx = inject(createDefaultModule({ shared }), FumxGeneratedModule, FumxModule);\n shared.ServiceRegistry.register(fumx);\n registerChecks(fumx);\n startLanguageServer(shared);\n};\n\n/** @internal */\nexport const languageServerCommand = Command.make(\n \"language-server\",\n {\n stdio: Flag.Boolean(\"stdio\").pipe(\n Flag.withDescription(\"Speak the Language Server Protocol over standard input and output\"),\n Flag.withDefault(false),\n ),\n clientProcessId: Flag.Int(\"clientProcessId\").pipe(\n Flag.withDescription(\"The editor's process id, which the editor passes on its own\"),\n Flag.optional,\n ),\n },\n ({ stdio }) => {\n if (!stdio) {\n return Effect.fail(\n MissingTransport.make({ message: \"start it with --stdio, the way an editor does\" }),\n );\n }\n return Effect.sync(startServer).pipe(Effect.andThen(Effect.never));\n },\n).pipe(\n Command.withDescription(\"Serves the .fumx language to an editor over standard input and output\"),\n);\n","import { Array as Arr, Match, Option, Record as Rec, pipe } from \"effect\";\n\nexport type Severity = \"off\" | \"warn\" | \"error\";\n\nexport type RuleOptions = Readonly<Record<string, unknown>>;\n\nexport type RuleEntry = Severity | readonly [Severity] | readonly [Severity, RuleOptions];\n\nexport interface Setting {\n readonly severity: Severity;\n readonly options: RuleOptions;\n}\n\nconst NO_OPTIONS: RuleOptions = {};\n\nexport const settingOf = (entry: RuleEntry): Setting =>\n Match.value(entry).pipe(\n Match.when(Match.string, (severity): Setting => ({ severity, options: NO_OPTIONS })),\n Match.orElse(([severity, options]): Setting => ({\n severity,\n options: options ?? NO_OPTIONS,\n })),\n );\n\nconst optionsOf = (entry: RuleEntry): Option.Option<RuleOptions> =>\n Match.value(entry).pipe(\n Match.when(Match.string, () => Option.none()),\n Match.orElse(([, options]) => Option.fromUndefinedOr(options)),\n );\n\nconst overridden = (earlier: RuleEntry, later: RuleEntry): RuleEntry =>\n pipe(\n optionsOf(later),\n Option.orElse(() => optionsOf(earlier)),\n Option.match({\n onNone: () => later,\n onSome: (options): RuleEntry => [settingOf(later).severity, options],\n }),\n );\n\nexport const mergedRules = (\n layers: readonly (Readonly<Record<string, RuleEntry>> | undefined)[],\n): Readonly<Record<string, RuleEntry>> => {\n const merged: Record<string, RuleEntry> = {};\n for (const [name, later] of pipe(\n layers,\n Arr.flatMap((layer) => Rec.toEntries(layer ?? {})),\n )) {\n merged[name] = pipe(\n Rec.get(merged, name),\n Option.match({\n onNone: () => later,\n onSome: (earlier) => overridden(earlier, later),\n }),\n );\n }\n return merged;\n};\n","import { Match } from \"effect\";\n\nimport type { Setting, Severity } from \"./setting.ts\";\n\nexport const reportedSeverity = (setting: Setting): Exclude<Severity, \"off\"> =>\n Match.value(setting.severity).pipe(\n Match.when(\"warn\", (): Exclude<Severity, \"off\"> => \"warn\"),\n Match.orElse((): Exclude<Severity, \"off\"> => \"error\"),\n );\n","import { Array as Arr, Record as Rec, pipe } from \"effect\";\n\nimport { mergedRules } from \"./setting.ts\";\nimport type { RuleEntry } from \"./setting.ts\";\n\nexport interface Layer<Plugin, Override> {\n readonly plugins?: Readonly<Record<string, Plugin>>;\n readonly rules?: Readonly<Record<string, RuleEntry>>;\n readonly ignores?: readonly string[];\n readonly overrides?: readonly Override[];\n}\n\nexport interface Merged<Plugin, Override> {\n readonly plugins: Readonly<Record<string, Plugin>>;\n readonly rules: Readonly<Record<string, RuleEntry>>;\n readonly ignores: readonly string[];\n readonly overrides: readonly Override[];\n}\n\nexport const mergedRecords = <Value>(\n records: readonly (Readonly<Record<string, Value>> | undefined)[],\n): Readonly<Record<string, Value>> =>\n pipe(\n records,\n Arr.flatMap((record) => Rec.toEntries(record ?? {})),\n Rec.fromEntries,\n );\n\nexport const layersOf = <Config extends { readonly extends?: readonly Config[] }>(\n config: Config,\n): readonly Omit<Config, \"extends\">[] => {\n const { extends: bases = [], ...own } = config;\n return [...pipe(bases, Arr.flatMap(layersOf)), own];\n};\n\nexport const mergedLayers = <Plugin, Override>(\n layers: readonly Layer<Plugin, Override>[],\n): Merged<Plugin, Override> => ({\n plugins: mergedRecords(\n pipe(\n layers,\n Arr.map((layer) => layer.plugins),\n ),\n ),\n rules: mergedRules(\n pipe(\n layers,\n Arr.map((layer) => layer.rules),\n ),\n ),\n ignores: pipe(\n layers,\n Arr.flatMap((layer) => layer.ignores ?? []),\n ),\n overrides: pipe(\n layers,\n Arr.flatMap((layer) => layer.overrides ?? []),\n ),\n});\n","import { Schema } from \"effect\";\n\nconst taggedError = Schema.TaggedError;\n\nexport class NotUtf8Error extends taggedError<NotUtf8Error, { readonly brand: unique symbol }>()(\n \"NotUtf8Error\",\n { path: Schema.String },\n) {}\n\nexport type FailWith<Failure> = (message: string) => (cause: unknown) => Failure;\n","import { runMain } from \"@r_masseater/masseater-utils/node-main\";\nimport {\n Array as Arr,\n Console,\n Effect,\n FileSystem,\n Function as Fn,\n Option,\n Path,\n Record as Rec,\n String as Str,\n pipe,\n} from \"effect\";\nimport { Argument, Command, Flag } from \"effect/cli\";\nimport type { PlatformError } from \"effect/PlatformError\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/process\";\n\nimport { NotUtf8Error } from \"#/shared/lib/fail.ts\";\nimport type { FailWith } from \"#/shared/lib/fail.ts\";\n\nconst CONFIG_FILES = [\"vite.config.ts\", \"vite.config.mts\", \"vite.config.js\", \"vite.config.mjs\"];\nconst FAILED = 1;\nconst DATA_FIRST_ARITY = 2;\nconst STRICT_UTF8 = new TextDecoder(\"utf-8\", { fatal: true });\n\nexport interface Reported {\n readonly severity: string;\n}\n\nexport interface LintCall<Config, Failure> {\n readonly root: string;\n readonly files: readonly string[];\n readonly projectFiles: readonly string[];\n readonly config: Config;\n readonly read: (file: string) => Effect.Effect<string, Failure | NotUtf8Error>;\n}\n\nexport interface PathspecRequest<Config> {\n readonly config: Config;\n readonly patterns?: readonly string[];\n}\n\nexport interface SectionSource<Config, Failure> {\n readonly name: string;\n readonly version: string;\n readonly description: string;\n readonly section: (config: unknown) => Config;\n readonly failWith: FailWith<Failure>;\n}\n\nexport interface Cli<Config, Found extends Reported, Failure> extends SectionSource<\n Config,\n Failure\n> {\n readonly pathspecs: (request: PathspecRequest<Config>) => readonly string[];\n readonly lint: (call: LintCall<Config, Failure>) => Effect.Effect<readonly Found[], Failure>;\n readonly format: (found: Found) => string;\n}\n\nexport interface ToolParameter {\n readonly name: string;\n readonly description: string;\n}\n\nexport interface ToolInput {\n readonly flags: ReadonlySet<string>;\n readonly args: readonly string[];\n}\n\nexport interface ToolCall<Config> {\n readonly root: string;\n readonly config: Config;\n readonly input: ToolInput;\n}\n\nexport interface Tool<Config, Found, Failure> extends SectionSource<Config, Failure> {\n readonly flags: readonly ToolParameter[];\n readonly argument: ToolParameter;\n readonly scan: (call: ToolCall<Config>) => Effect.Effect<readonly Found[], Failure>;\n readonly format: (found: Found) => string;\n}\n\n/** @internal */\nexport type CliServices =\n | FileSystem.FileSystem\n | Path.Path\n | ChildProcessSpawner.ChildProcessSpawner;\n\nconst readSectionIn = <Config, Failure>(\n source: SectionSource<Config, Failure>,\n root: string,\n): Effect.Effect<Config, Failure, FileSystem.FileSystem | Path.Path> =>\n Effect.gen(function* readConfig() {\n const fileSystem = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const found = yield* pipe(\n CONFIG_FILES,\n Arr.map((name) => path.join(root, name)),\n Effect.filter((file) => fileSystem.exists(file).pipe(Effect.orElseSucceed(() => false))),\n );\n const loaded = yield* Option.match(Arr.head(found), {\n onNone: () => Effect.succeed<unknown>({}),\n onSome: (file) =>\n Effect.tryPromise({\n try: () => import(\"vite-plus\"),\n catch: source.failWith(\"could not load vite-plus\"),\n }).pipe(\n Effect.flatMap(({ resolveConfigFromFile }) =>\n Effect.tryPromise({\n try: () => resolveConfigFromFile(file),\n catch: source.failWith(`could not load ${file}`),\n }),\n ),\n ),\n });\n return source.section(loaded);\n }).pipe(Effect.withSpan(`${source.name}.config`));\n\n/** @internal */\nexport const readSection: {\n (\n root: string,\n ): <Config, Failure>(\n source: SectionSource<Config, Failure>,\n ) => Effect.Effect<Config, Failure, FileSystem.FileSystem | Path.Path>;\n <Config, Failure>(\n source: SectionSource<Config, Failure>,\n root: string,\n ): Effect.Effect<Config, Failure, FileSystem.FileSystem | Path.Path>;\n} = Fn.dual(DATA_FIRST_ARITY, readSectionIn);\n\nconst trackedFiles = (\n root: string,\n pathspecs: readonly string[],\n): Effect.Effect<readonly string[], PlatformError, ChildProcessSpawner.ChildProcessSpawner> =>\n Effect.gen(function* listFiles() {\n const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n const output = yield* spawner.string(\n ChildProcess.make(\n \"git\",\n [\"ls-files\", \"-co\", \"--exclude-standard\", \"-z\", \"--\", ...pathspecs],\n { cwd: root },\n ),\n );\n return pipe(Str.split(output, \"\\0\"), Arr.filter(Str.isNonEmpty));\n });\n\nconst requestOf = <Config>(config: Config, patterns: readonly string[]): PathspecRequest<Config> =>\n Arr.match(patterns, {\n onEmpty: () => ({ config }),\n onNonEmpty: (given) => ({ config, patterns: given }),\n });\n\nconst hasError = (found: readonly Reported[]): boolean =>\n pipe(\n found,\n Arr.some(({ severity }) => severity === \"error\"),\n );\n\nconst failWhen = (failed: boolean): Effect.Effect<void> =>\n Effect.when(\n Effect.sync(() => {\n process.exitCode = FAILED;\n }),\n Effect.succeed(failed),\n ).pipe(Effect.asVoid);\n\nconst printAll = <Found>(\n found: readonly Found[],\n format: (found: Found) => string,\n): Effect.Effect<void> =>\n Arr.match(found, {\n onEmpty: () => Effect.void,\n onNonEmpty: (all) => Console.log(pipe(all, Arr.map(format), Arr.join(\"\\n\"))),\n });\n\nconst readerIn = <Failure>(\n root: string,\n failWith: FailWith<Failure>,\n): Effect.Effect<\n (file: string) => Effect.Effect<string, Failure | NotUtf8Error>,\n never,\n FileSystem.FileSystem | Path.Path\n> =>\n Effect.gen(function* reader() {\n const fileSystem = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n return (file: string): Effect.Effect<string, Failure | NotUtf8Error> =>\n fileSystem.readFile(path.resolve(root, file)).pipe(\n Effect.mapError(failWith(`could not read ${file}`)),\n Effect.flatMap((bytes) =>\n Effect.try({\n try: () => STRICT_UTF8.decode(bytes),\n catch: () => NotUtf8Error.make({ path: file }),\n }),\n ),\n );\n });\n\n/** @internal */\nexport const lintMain = <Config, Found extends Reported, Failure>(\n cli: Cli<Config, Found, Failure>,\n patterns: readonly string[],\n): Effect.Effect<void, Failure | PlatformError, CliServices> =>\n Effect.gen(function* main() {\n const root = process.cwd();\n const config = yield* readSectionIn(cli, root);\n const pathspecs = cli.pathspecs(requestOf(config, patterns));\n const { files, projectFiles } = yield* Effect.all(\n {\n files: trackedFiles(root, pathspecs).pipe(Effect.withSpan(`${cli.name}.files`)),\n projectFiles: trackedFiles(root, []).pipe(Effect.withSpan(`${cli.name}.project`)),\n },\n { concurrency: \"unbounded\" },\n );\n const read = yield* readerIn(root, cli.failWith);\n const found = yield* cli.lint({ root, files, projectFiles, config, read });\n yield* printAll(found, cli.format);\n yield* failWhen(hasError(found));\n });\n\nconst toolMainOf =\n <Config, Found, Failure>(tool: Tool<Config, Found, Failure>) =>\n (input: ToolInput): Effect.Effect<void, Failure | PlatformError, CliServices> =>\n Effect.gen(function* main() {\n const root = process.cwd();\n const config = yield* readSectionIn(tool, root);\n const found = yield* tool.scan({ root, config, input });\n yield* printAll(found, tool.format);\n yield* failWhen(Arr.isReadonlyArrayNonEmpty(found));\n });\n\nconst variadicOf = ({ name, description }: ToolParameter): Argument.Argument<readonly string[]> =>\n Argument.String(name).pipe(Argument.withDescription(description), Argument.variadic());\n\nconst flagsOf = (flags: readonly ToolParameter[]): Readonly<Record<string, Flag.Flag<boolean>>> =>\n Rec.fromEntries(\n pipe(\n flags,\n Arr.map(({ name, description }) => [\n name,\n Flag.Boolean(name).pipe(Flag.withDescription(description), Flag.withDefault(false)),\n ]),\n ),\n );\n\nconst setFlags = (values: Readonly<Record<string, boolean>>): ReadonlySet<string> =>\n new Set(pipe(values, Rec.filter(Fn.identity), Rec.keys));\n\nexport const runTool = <Config, Found, Failure>(tool: Tool<Config, Found, Failure>): void => {\n const command = Command.make(\n tool.name,\n { args: variadicOf(tool.argument), flags: flagsOf(tool.flags) },\n ({ args, flags }) => toolMainOf(tool)({ args, flags: setFlags(flags) }),\n ).pipe(Command.withDescription(tool.description));\n command.pipe(Command.run({ version: tool.version }), runMain(tool.name));\n};\n\n/** @internal */\nexport const pathspecArgument = (): Argument.Argument<readonly string[]> =>\n variadicOf({\n name: \"pathspec\",\n description: \"Git pathspecs of the files to lint, in place of the configured ones\",\n });\n\nexport const runCli = <Config, Found extends Reported, Failure>(\n cli: Cli<Config, Found, Failure>,\n): void => {\n const command = Command.make(cli.name, { pathspecs: pathspecArgument() }, ({ pathspecs }) =>\n lintMain(cli, pathspecs),\n ).pipe(Command.withDescription(cli.description));\n command.pipe(Command.run({ version: cli.version }), runMain(cli.name));\n};\n","import { Function as Fn, Option } from \"effect\";\n\nconst DATA_FIRST_ARITY = 2;\n\nexport const present: {\n <Value, Fields extends object>(\n build: (value: Value) => Fields,\n ): (value: Option.Option<Value>) => Partial<Fields>;\n <Value, Fields extends object>(\n value: Option.Option<Value>,\n build: (value: Value) => Fields,\n ): Partial<Fields>;\n} = Fn.dual(\n DATA_FIRST_ARITY,\n <Value, Fields extends object>(\n value: Option.Option<Value>,\n build: (value: Value) => Fields,\n ): Partial<Fields> => Option.match(value, { onNone: (): Partial<Fields> => ({}), onSome: build }),\n);\n","import { Array as Arr, Boolean as Bool, Effect, Order } from \"effect\";\nimport type { Option } from \"effect\";\n\nconst SAMPLED = \"01\";\nconst NOT_SAMPLED = \"00\";\n\nexport interface Positioned {\n readonly path: string;\n readonly line: number;\n readonly column?: number;\n}\n\nconst LINE_START = 0;\n\nconst flagsOf = (sampled: boolean): string =>\n Bool.match(sampled, { onFalse: () => NOT_SAMPLED, onTrue: () => SAMPLED });\n\nexport const traceparent: Effect.Effect<Option.Option<string>> = Effect.currentSpan.pipe(\n Effect.map((span) => `00-${span.traceId}-${span.spanId}-${flagsOf(span.sampled)}`),\n Effect.option,\n);\n\nconst byPosition: Order.Order<Positioned> = Order.combine(\n Order.mapInput(Order.String, (found: Positioned) => found.path),\n Order.combine(\n Order.mapInput(Order.Number, (found: Positioned) => found.line),\n Order.mapInput(Order.Number, (found: Positioned) => found.column ?? LINE_START),\n ),\n);\n\nexport const sortByPosition = <Found extends Positioned>(found: readonly Found[]): Found[] =>\n Arr.sort(found, byPosition);\n","import { Array as Arr, Option, pipe } from \"effect\";\n\nexport interface Reportable {\n readonly path: string;\n readonly line: number;\n readonly column?: number | undefined;\n readonly rule: string;\n readonly message: string;\n readonly detail?: string | undefined;\n readonly context?: string | undefined;\n readonly severity: string;\n}\n\nexport const diagnosticDetail = (diagnostic: Reportable): string =>\n pipe(\n [diagnostic.detail, diagnostic.context],\n Arr.flatMap((part) => Option.toArray(Option.fromNullishOr(part))),\n Arr.filter((part) => part !== \"\"),\n Arr.map((part) => ` [${part}]`),\n Arr.join(\"\"),\n );\n\nexport const formatDiagnostic = (diagnostic: Reportable): string => {\n const column = pipe(\n Option.fromNullishOr(diagnostic.column),\n Option.map((value) => `:${String(value)}`),\n Option.getOrElse(() => \"\"),\n );\n return `${diagnostic.path}:${String(diagnostic.line)}${column} ${diagnostic.severity} ${diagnostic.rule} ${diagnostic.message}${diagnosticDetail(diagnostic)}`;\n};\n\nexport interface NotUtf8 {\n readonly path: string;\n readonly line: number;\n readonly column: number;\n readonly rule: string;\n readonly message: string;\n readonly severity: \"error\";\n}\n\nexport const notUtf8 =\n (tool: string) =>\n (path: string): NotUtf8 => ({\n path,\n line: 1,\n column: 1,\n rule: \"utf8\",\n message: `The file is not valid UTF-8, so ${tool} cannot read it`,\n severity: \"error\",\n });\n","import { Array as Arr, Function as Fn, Option, Predicate, pipe } from \"effect\";\n\nexport interface SectionRequest<Config extends object> {\n readonly name: string;\n readonly fallback: Config;\n readonly prepare?: (section: Config) => Config;\n}\n\nexport const sectionOf = <Config extends object>({\n name,\n fallback,\n prepare = Fn.identity,\n}: SectionRequest<Config>): ((config: unknown) => Config) => {\n const hasSection = (value: unknown): value is Readonly<Record<string, Config>> =>\n Predicate.hasProperty(value, name) && Predicate.isObject(value[name]);\n return (config) =>\n pipe(\n Option.liftPredicate(config, hasSection),\n Option.flatMapNullishOr((value) => value[name]),\n Option.map(prepare),\n Option.getOrElse(() => fallback),\n );\n};\n\nexport interface Ignoring {\n readonly ignores?: readonly string[] | undefined;\n}\n\nexport interface Pathspecs {\n readonly defaults: readonly string[];\n readonly unowned?: readonly string[];\n}\n\nexport const pathspecsOf =\n ({ defaults, unowned = [] }: Pathspecs) =>\n ({\n config,\n patterns = [],\n }: {\n readonly config: Ignoring;\n readonly patterns?: readonly string[];\n }): readonly string[] => [\n ...Arr.match(patterns, { onEmpty: () => defaults, onNonEmpty: Fn.identity }),\n ...unowned,\n ...pipe(\n config.ignores ?? [],\n Arr.map((glob) => `:(glob,exclude)${glob}`),\n ),\n ];\n","import { Schema } from \"effect\";\n\nconst taggedError = Schema.TaggedError;\n\nexport class LintError extends taggedError<LintError, { readonly brand: unique symbol }>()(\n \"LintError\",\n { message: Schema.String },\n) {}\n\nexport const failedWith =\n (message: string) =>\n (cause: unknown): LintError =>\n LintError.make({ message: `${message}: ${String(cause)}` });\n","import { layersOf, mergedLayers } from \"@masseater.dev/lint-host\";\n\nimport type { LintConfig } from \"./types.ts\";\n\nexport const flattenConfig = (config: LintConfig): LintConfig => {\n const { plugins, rules, ignores } = mergedLayers(layersOf(config));\n return { plugins, rules, ignores };\n};\n","import type { NotUtf8Error } from \"@masseater.dev/lint-host\";\nimport { Effect } from \"effect\";\n\nimport { readSong } from \"#/features/read-song/@x/check-songs.ts\";\nimport type { SongSource } from \"#/features/read-song/@x/check-songs.ts\";\nimport type { LintError } from \"#/shared/lib/errors.ts\";\n\nconst SEPARATOR = \"/\";\n\nexport interface SongFile {\n readonly file: string;\n readonly source: SongSource;\n}\n\nexport type Read = (path: string) => Effect.Effect<string, LintError | NotUtf8Error>;\n\nexport interface ReadInput {\n readonly root: string;\n readonly file: string;\n readonly read: Read;\n}\n\nexport const pathOf = (input: Omit<ReadInput, \"read\">): string =>\n `${input.root}${SEPARATOR}${input.file}`;\n\nexport const readSongFile = Effect.fn(\"fumx.lint.read\")(function* readSongFile(input: ReadInput) {\n const source = yield* readSong({ path: pathOf(input), read: input.read });\n return { file: input.file, source } satisfies SongFile;\n});\n","import { settingOf } from \"@masseater.dev/lint-host\";\nimport type { Setting } from \"@masseater.dev/lint-host\";\nimport { Array as Arr, Option, Record as Rec, String as Str, pipe } from \"effect\";\n\nimport type { LintConfig, Plugin, Rule } from \"./types.ts\";\n\nconst SEPARATOR = \"/\";\nconst START = 0;\nconst ENABLED: Setting = settingOf(\"error\");\n\nexport interface ResolvedRule {\n readonly id: string;\n readonly rule: Rule;\n readonly setting: Setting;\n}\n\ntype PluginEntry = readonly [string, Plugin];\n\nconst idOf = (plugin: string, name: string): string => `${plugin}${SEPARATOR}${name}`;\n\nconst pluginOf = (id: string): string =>\n pipe(\n Str.indexOf(SEPARATOR)(id),\n Option.match({\n onNone: () => id,\n onSome: (slash) => Str.slice(START, slash)(id),\n }),\n );\n\nconst rulesOf =\n (config: LintConfig) =>\n ([plugin, value]: PluginEntry): readonly ResolvedRule[] =>\n pipe(\n Rec.toEntries(value.rules),\n Arr.map(([name, rule]): ResolvedRule => {\n const id = idOf(plugin, name);\n return {\n id,\n rule,\n setting: pipe(\n config.rules ?? {},\n Rec.get(id),\n Option.map(settingOf),\n Option.getOrElse(() => ENABLED),\n ),\n };\n }),\n Arr.filter(({ setting }) => setting.severity !== \"off\"),\n );\n\nexport const resolve = (config: LintConfig): readonly ResolvedRule[] =>\n pipe(Rec.toEntries(config.plugins ?? {}), Arr.flatMap(rulesOf(config)));\n\nexport const unknownPlugins = (config: LintConfig): readonly string[] =>\n pipe(\n Rec.keys(config.rules ?? {}),\n Arr.map(pluginOf),\n Arr.filter((plugin) => !Rec.has(config.plugins ?? {}, plugin)),\n Arr.dedupe,\n );\n\nconst ruleNameOf = (id: string): string =>\n pipe(\n Str.indexOf(SEPARATOR)(id),\n Option.match({\n onNone: () => \"\",\n onSome: (slash) => Str.slice(slash + SEPARATOR.length)(id),\n }),\n );\n\nconst isKnownRule =\n (config: LintConfig) =>\n (id: string): boolean =>\n pipe(\n Rec.get(config.plugins ?? {}, pluginOf(id)),\n Option.match({\n onNone: () => true,\n onSome: (plugin) => Rec.has(plugin.rules, ruleNameOf(id)),\n }),\n );\n\nexport const unknownRules = (config: LintConfig): readonly string[] =>\n pipe(\n Rec.keys(config.rules ?? {}),\n Arr.filter((id) => !isKnownRule(config)(id)),\n );\n","import { Array as Arr, Option, String as Str, pipe } from \"effect\";\nimport { Note as TonalNote } from \"tonal\";\n\nimport type { Note, Role, Song } from \"#/entities/song/index.ts\";\nimport { fractionOf } from \"#/shared/lib/ticks.ts\";\n\nconst NONE = 0;\nconst FIRST = 1;\n\nexport interface Span {\n readonly start: number;\n readonly end: number;\n}\n\nexport interface Sounding extends Span {\n readonly track: string;\n readonly line: number;\n readonly column: number;\n readonly bar: number;\n readonly role: Option.Option<Role>;\n readonly midi: number;\n readonly spelling: string;\n readonly pitchClass: string;\n}\n\nconst CENTS = /[+-]\\d+c$/u;\n\nconst pitchClassOf = (note: Note): string => {\n const written = TonalNote.pitchClass(Str.replace(CENTS, \"\")(note.spelling));\n if (Str.isNonEmpty(written)) {\n return written;\n }\n return TonalNote.pitchClass(TonalNote.fromMidi(note.midi));\n};\n\nexport const overlapOf =\n (left: Span) =>\n (right: Span): number =>\n Math.max(NONE, Math.min(left.end, right.end) - Math.max(left.start, right.start));\n\nexport const soundingsOf = (song: Song): readonly Sounding[] => {\n const audible = pipe(\n song.tracks,\n Arr.filter((track) => !track.mixer.muted),\n );\n return pipe(\n song.notes,\n Arr.flatMap((note) =>\n pipe(\n audible,\n Arr.findFirst((track) => track.name === note.track),\n Option.map((track) => ({\n track: note.track,\n line: note.sourceLine,\n column: note.sourceColumn,\n bar: note.bar,\n role: track.role,\n midi: note.midi,\n spelling: note.spelling,\n pitchClass: pitchClassOf(note),\n start: note.start,\n end: note.start + Math.round(note.length * note.gate),\n })),\n Option.toArray,\n ),\n ),\n );\n};\n\nexport const positionOf =\n (song: Song) =>\n (tick: number): { readonly bar: number; readonly offset: string } =>\n pipe(\n song.bars,\n Arr.findLast((bar) => bar.start <= tick),\n Option.match({\n onNone: () => ({ bar: FIRST, offset: fractionOf(tick) }),\n onSome: (bar) => ({ bar: bar.index, offset: fractionOf(tick - bar.start) }),\n }),\n );\n","import { groupsOf } from \"@r_masseater/masseater-utils/text\";\nimport { Array as Arr, Match, Option, String as Str, pipe } from \"effect\";\n\nimport type { SourceComment } from \"#/features/read-song/@x/check-songs.ts\";\n\nconst DIRECTIVE =\n /^fumx-(?<kind>ignore-next-line|ignore-file|ignore|disable|enable)(?:\\s(?<rest>[\\s\\S]*))?$/u;\nconst REASON = /\\s-{2,}(?:\\s|$)/u;\nconst LINE_MARK = \"//\";\nconst BLOCK_START = \"/*\";\nconst BLOCK_END = \"*/\";\nconst LIST = \",\";\nconst NEXT = 1;\nconst LINE_START = 0;\n\ntype Kind = \"ignore\" | \"ignore-next-line\" | \"ignore-file\" | \"disable\" | \"enable\";\n\ninterface Directive {\n readonly line: number;\n readonly column: number;\n readonly kind: Kind;\n readonly rules: readonly string[];\n}\n\nexport interface Suppressed {\n readonly line: number;\n readonly column?: number;\n readonly rule: string;\n}\n\nconst kindOf = (text: string): Kind =>\n Match.value(text).pipe(\n Match.when(\"ignore-file\", (): Kind => \"ignore-file\"),\n Match.when(\"ignore-next-line\", (): Kind => \"ignore-next-line\"),\n Match.when(\"disable\", (): Kind => \"disable\"),\n Match.when(\"enable\", (): Kind => \"enable\"),\n Match.orElse((): Kind => \"ignore\"),\n );\n\nconst bodyOf = (text: string): string => {\n if (Str.startsWith(BLOCK_START)(text)) {\n return pipe(text, Str.slice(BLOCK_START.length), Str.replace(BLOCK_END, \"\"), Str.trim);\n }\n return pipe(text, Str.slice(LINE_MARK.length), Str.trim);\n};\n\nconst rulesOf = (rest: string): readonly string[] =>\n pipe(\n Str.split(` ${rest}`, REASON),\n Arr.head,\n Option.getOrElse(() => \"\"),\n Str.split(LIST),\n Arr.map(Str.trim),\n Arr.filter(Str.isNonEmpty),\n );\n\nconst directiveOf = (comment: SourceComment): Option.Option<Directive> =>\n pipe(\n groupsOf(DIRECTIVE)(bodyOf(comment.text)),\n Option.map((groups) => ({\n line: comment.line,\n column: comment.column,\n kind: kindOf(groups[\"kind\"] ?? \"\"),\n rules: rulesOf(groups[\"rest\"] ?? \"\"),\n })),\n );\n\nconst names =\n (rule: string) =>\n (directive: Directive): boolean =>\n !Arr.isReadonlyArrayNonEmpty(directive.rules) || Arr.contains(directive.rules, rule);\n\nconst isRange = (directive: Directive): boolean =>\n directive.kind === \"disable\" || directive.kind === \"enable\";\n\nconst coversLine =\n (found: Suppressed) =>\n (directive: Directive): boolean =>\n names(found.rule)(directive) &&\n Match.value(directive.kind).pipe(\n Match.when(\"ignore-file\", () => true),\n Match.when(\"ignore-next-line\", () => directive.line + NEXT === found.line),\n Match.when(\"ignore\", () => directive.line === found.line),\n Match.orElse(() => false),\n );\n\nconst isAfter =\n (found: Suppressed) =>\n (directive: Directive): boolean =>\n directive.line < found.line ||\n (directive.line === found.line && directive.column <= (found.column ?? LINE_START));\n\nconst insideRange =\n (directives: readonly Directive[]) =>\n (found: Suppressed): boolean =>\n pipe(\n directives,\n Arr.filter(\n (directive) =>\n isRange(directive) && isAfter(found)(directive) && names(found.rule)(directive),\n ),\n Arr.last,\n Option.exists((directive) => directive.kind === \"disable\"),\n );\n\nexport const suppressionsOf = (\n comments: readonly SourceComment[],\n): ((found: Suppressed) => boolean) => {\n const directives = pipe(comments, Arr.map(directiveOf), Arr.getSomes);\n return (found) => pipe(directives, Arr.some(coversLine(found))) || insideRange(directives)(found);\n};\n","import { present, reportedSeverity } from \"@masseater.dev/lint-host\";\nimport { Array as Arr, Effect, Option, pipe } from \"effect\";\n\nimport type { Song } from \"#/entities/song/index.ts\";\nimport { soundingsOf } from \"#/features/analyze-song/@x/check-songs.ts\";\nimport type { Sounding } from \"#/features/analyze-song/@x/check-songs.ts\";\nimport type { SourceComment } from \"#/features/read-song/@x/check-songs.ts\";\nimport { failedWith } from \"#/shared/lib/errors.ts\";\nimport type { LintError } from \"#/shared/lib/errors.ts\";\n\nimport type { ResolvedRule } from \"./resolve.ts\";\nimport { suppressionsOf } from \"./suppressions.ts\";\nimport type { Diagnostic, Report } from \"./types.ts\";\n\nexport interface RunInput {\n readonly path: string;\n readonly comments: readonly SourceComment[];\n readonly song: Song;\n readonly rules: readonly ResolvedRule[];\n}\n\nconst diagnosticOf =\n (path: string, rule: ResolvedRule) =>\n (report: Report): Diagnostic => ({\n path,\n line: report.line,\n rule: rule.id,\n message: report.message,\n severity: reportedSeverity(rule.setting),\n ...present(Option.fromNullishOr(report.column), (column) => ({ column })),\n ...present(Option.fromNullishOr(report.detail), (detail) => ({ detail })),\n });\n\nconst runOne = (\n input: RunInput,\n soundings: readonly Sounding[],\n): ((rule: ResolvedRule) => Effect.Effect<readonly Diagnostic[], LintError>) =>\n Effect.fn(\"fumx.lint.rule\")(function* run(rule: ResolvedRule) {\n yield* Effect.annotateCurrentSpan({ \"fumx.lint.rule\": rule.id });\n const reports: Report[] = [];\n yield* Effect.try({\n try: () => {\n rule.rule.check({\n filename: input.path,\n song: input.song,\n soundings,\n options: rule.setting.options,\n report: (report) => {\n reports.push(report);\n },\n });\n },\n catch: failedWith(`${rule.id} failed`),\n });\n return pipe(reports, Arr.map(diagnosticOf(input.path, rule)));\n });\n\nexport const runRules = Effect.fn(\"fumx.lint.rules\")(function* runRules(input: RunInput) {\n const soundings = soundingsOf(input.song);\n const suppressed = suppressionsOf(input.comments);\n const found = yield* pipe(\n input.rules,\n Effect.forEach(runOne(input, soundings), { concurrency: 1 }),\n );\n return pipe(\n Arr.flatten(found),\n Arr.filter((diagnostic) => !suppressed(diagnostic)),\n );\n});\n","import { NotUtf8Error, notUtf8, sortByPosition } from \"@masseater.dev/lint-host\";\nimport { Array as Arr, Effect, Result, Schema, pipe } from \"effect\";\n\nimport { readSong } from \"#/app/index.ts\";\nimport type { SourceIssue } from \"#/app/index.ts\";\nimport {\n flattenConfig,\n pathOf,\n readSongFile,\n resolve,\n runRules,\n unknownPlugins,\n unknownRules,\n} from \"#/features/check-songs/index.ts\";\nimport type {\n Diagnostic,\n LintConfig,\n Read,\n ResolvedRule,\n SongFile,\n} from \"#/features/check-songs/index.ts\";\nimport { LintError } from \"#/shared/lib/errors.ts\";\n\nconst PARSE_RULE = \"fumx/parse\";\n\nexport interface LintInput {\n readonly root: string;\n readonly files: readonly string[];\n readonly read: Read;\n readonly config?: LintConfig;\n}\n\nexport interface TextInput {\n readonly path: string;\n readonly text: string;\n readonly read?: Read;\n readonly config?: LintConfig;\n}\n\nconst failIfAny =\n (problem: string) =>\n (names: readonly string[]): Effect.Effect<void, LintError> =>\n Arr.match(names, {\n onEmpty: () => Effect.void,\n onNonEmpty: (found) =>\n Effect.fail(LintError.make({ message: `${problem}: ${Arr.join(found, \", \")}` })),\n });\n\nconst UNKNOWN_PLUGINS = failIfAny(\"rules name plugins that are not configured\");\nconst UNKNOWN_RULES = failIfAny(\"rules name rules that their plugins do not have\");\n\nconst checkPlugins = (config: LintConfig): Effect.Effect<void, LintError> => {\n const rules = UNKNOWN_RULES(unknownRules(config));\n return UNKNOWN_PLUGINS(unknownPlugins(config)).pipe(Effect.andThen(rules));\n};\n\nconst rulesOf = (\n config: LintConfig | undefined,\n): Effect.Effect<readonly ResolvedRule[], LintError> => {\n const flat = flattenConfig(config ?? {});\n return checkPlugins(flat).pipe(Effect.as(resolve(flat)));\n};\n\nconst parseDiagnosticsOf =\n (file: string) =>\n (issues: readonly SourceIssue[]): readonly Diagnostic[] =>\n pipe(\n issues,\n Arr.map((issue): Diagnostic => ({\n path: file,\n line: issue.line,\n column: issue.column,\n rule: PARSE_RULE,\n message: issue.message,\n severity: \"error\",\n })),\n );\n\nconst lintFile =\n (rules: readonly ResolvedRule[]) =>\n (song: SongFile): Effect.Effect<readonly Diagnostic[], LintError> => {\n if (song.source.status === \"invalid\") {\n return Effect.succeed(parseDiagnosticsOf(song.file)(song.source.issues));\n }\n return runRules({\n path: song.file,\n comments: song.source.outline.comments,\n song: song.source.song,\n rules,\n });\n };\n\nconst notFound = (path: string): Effect.Effect<string, LintError> =>\n Effect.fail(LintError.make({ message: `could not read ${path}` }));\n\nconst readerOf =\n (input: TextInput): Read =>\n (path) => {\n if (path === input.path) {\n return Effect.succeed(input.text);\n }\n return (input.read ?? notFound)(path);\n };\n\nconst lintTracked = (\n rules: readonly ResolvedRule[],\n input: LintInput,\n): ((file: string) => Effect.Effect<readonly Diagnostic[], LintError>) =>\n Effect.fnUntraced(function* lintOne(\n file: string,\n ): Effect.fn.Return<readonly Diagnostic[], LintError> {\n const path = pathOf({ root: input.root, file });\n const read = yield* Effect.result(input.read(path));\n if (Result.isFailure(read) && Schema.is(NotUtf8Error)(read.failure)) {\n return [notUtf8(\"fumx lint\")(file)];\n }\n const reader = Result.match(read, {\n onFailure: () => input.read,\n onSuccess: (text): Read => readerOf({ path, text, read: input.read }),\n });\n const source = yield* readSongFile({ root: input.root, file, read: reader });\n return yield* lintFile(rules)(source);\n });\n\nexport const lint = Effect.fn(\"fumx.lint.lint\")(function* lint(input: LintInput) {\n const rules = yield* rulesOf(input.config);\n const found = yield* Effect.forEach(input.files, lintTracked(rules, input), {\n concurrency: \"unbounded\",\n });\n return sortByPosition<Diagnostic>(Arr.flatten(found));\n});\n\nexport const lintText = Effect.fn(\"fumx.lint.lintText\")(function* lintText(input: TextInput) {\n const rules = yield* rulesOf(input.config);\n const source = yield* readSong({ path: input.path, read: readerOf(input) });\n const found = yield* lintFile(rules)({ file: input.path, source });\n return sortByPosition<Diagnostic>(found);\n});\n","import { pathspecsOf, sectionOf } from \"@masseater.dev/lint-host\";\nimport type { PathspecRequest } from \"@masseater.dev/lint-host\";\nimport { Option, pipe } from \"effect\";\n\nimport { flattenConfig } from \"#/features/check-songs/index.ts\";\nimport type { FumxConfig, LintConfig } from \"#/features/check-songs/index.ts\";\n\nexport type PathspecInput = PathspecRequest<LintConfig>;\n\nconst fumxSection = sectionOf<FumxConfig>({ name: \"fumx\", fallback: {} });\n\nexport const lintSection = (config: unknown): LintConfig =>\n pipe(\n Option.fromUndefinedOr(fumxSection(config).lint),\n Option.match({ onNone: (): LintConfig => ({}), onSome: flattenConfig }),\n );\n\nexport const songPathspecs = pathspecsOf({ defaults: [\"*.fumx\"] });\n","import { formatDiagnostic, lintMain, pathspecArgument } from \"@masseater.dev/lint-host\";\nimport manifest from \"@r_masseater/fumx/package.json\" with { type: \"json\" };\nimport { Command } from \"effect/cli\";\n\nimport { failedWith } from \"#/shared/lib/errors.ts\";\n\nimport { lint } from \"./run-lint.ts\";\nimport { lintSection, songPathspecs } from \"./section.ts\";\n\nconst linter = {\n name: \"fumx.lint\",\n version: manifest.version,\n description:\n \"Lints .fumx songs with the rules under fumx.lint in vite.config.ts and prints each finding\",\n section: lintSection,\n pathspecs: songPathspecs,\n lint,\n format: formatDiagnostic,\n failWith: failedWith,\n};\n\n/** @internal */\nexport const lintCommand = Command.make(\n \"lint\",\n { pathspecs: pathspecArgument() },\n ({ pathspecs }) => lintMain(linter, pathspecs),\n).pipe(Command.withDescription(linter.description));\n","import { Array as Arr, Option, Order, Schema, pipe } from \"effect\";\nimport { Chord } from \"tonal\";\n\nimport type { Song } from \"#/entities/song/index.ts\";\nimport { TICKS_PER_WHOLE } from \"#/shared/lib/ticks.ts\";\n\nimport { overlapOf, positionOf, soundingsOf } from \"./sounding.ts\";\nimport type { Sounding, Span } from \"./sounding.ts\";\n\nconst FIRST = 1;\nconst HELD_SHARE = 0.25;\nconst UNKNOWN = \"?\";\n\nconst PositionSchema = Schema.Struct({ bar: Schema.Int, offset: Schema.String });\n\nexport const ChordSpanSchema = Schema.Struct({\n from: PositionSchema,\n to: PositionSchema,\n start: Schema.Int,\n end: Schema.Int,\n symbol: Schema.String,\n notes: Schema.Array(Schema.String),\n});\n\nexport type ChordSpan = typeof ChordSpanSchema.Type;\n\ninterface BeatChord extends Span {\n readonly symbol: string;\n readonly notes: readonly string[];\n}\n\nconst heldIn =\n (window: Span) =>\n (note: Sounding): boolean =>\n overlapOf(note)(window) >= (window.end - window.start) * HELD_SHARE;\n\nconst isHarmonic = (note: Sounding): boolean =>\n Option.exists(note.role, (role) => role === \"bass\" || role === \"harmony\");\n\nconst OCTAVE = 12;\n\nconst UNISON = 0;\n\nconst samePitchClass = (left: number, right: number): boolean => (left - right) % OCTAVE === UNISON;\n\nconst byMidi = Order.mapInput(Order.Number, (note: Sounding) => note.midi);\n\nconst harmonicOrAll = (held: readonly Sounding[]): readonly Sounding[] => {\n const harmonic = pipe(held, Arr.filter(isHarmonic));\n if (Arr.isReadonlyArrayNonEmpty(harmonic)) {\n return harmonic;\n }\n return held;\n};\n\nconst chordNotesIn =\n (notes: readonly Sounding[]) =>\n (window: Span): readonly string[] =>\n pipe(\n notes,\n Arr.filter(heldIn(window)),\n harmonicOrAll,\n (held) => Arr.sort(held, byMidi),\n Arr.dedupeWith((left, right) => samePitchClass(left.midi, right.midi)),\n Arr.map((note) => note.pitchClass),\n );\n\nconst spells =\n (notes: readonly string[]) =>\n (symbol: string): boolean => {\n const spelled = Chord.get(symbol).notes;\n return (\n spelled.length === notes.length &&\n pipe(\n spelled,\n Arr.every((note) => Arr.contains(notes, note)),\n )\n );\n };\n\nconst symbolOf = (notes: readonly string[]): string => {\n const candidates = Chord.detect(Arr.copy(notes));\n return pipe(\n candidates,\n Arr.findFirst(spells(notes)),\n Option.orElse(() => Arr.head(candidates)),\n Option.getOrElse(() => UNKNOWN),\n );\n};\n\nconst beatWindowsOf = (song: Song): readonly Span[] =>\n pipe(\n song.bars,\n Arr.flatMap((bar) => {\n const beat = TICKS_PER_WHOLE / bar.meter.denominator;\n return Arr.makeBy(bar.meter.numerator, (index) => ({\n start: bar.start + index * beat,\n end: bar.start + (index + FIRST) * beat,\n }));\n }),\n );\n\nconst extend = (spans: readonly BeatChord[], beat: BeatChord): readonly BeatChord[] =>\n Option.match(Arr.last(spans), {\n onNone: () => [beat],\n onSome: (last) => {\n if (last.symbol !== beat.symbol || last.end !== beat.start) {\n return [...spans, beat];\n }\n return [...Arr.dropRight(spans, FIRST), { ...last, end: beat.end }];\n },\n });\n\nconst beatChordOf =\n (notes: readonly Sounding[]) =>\n (window: Span): Option.Option<BeatChord> => {\n const held = chordNotesIn(notes)(window);\n if (!Arr.isReadonlyArrayNonEmpty(held)) {\n return Option.none();\n }\n return Option.some({ ...window, notes: held, symbol: symbolOf(held) });\n };\n\nexport const chordsOf = (song: Song): readonly ChordSpan[] => {\n const notes = soundingsOf(song);\n const beats = pipe(beatWindowsOf(song), Arr.map(beatChordOf(notes)), Arr.getSomes);\n const at = positionOf(song);\n return pipe(\n Arr.reduce(beats, [] as readonly BeatChord[], extend),\n Arr.map((span) => ({\n from: at(span.start),\n to: at(span.end),\n start: span.start,\n end: span.end,\n symbol: span.symbol,\n notes: span.notes,\n })),\n );\n};\n","import { Array as Arr, Number as Num, Option, Order, Record, Schema, pipe } from \"effect\";\n\nimport type { Song } from \"#/entities/song/index.ts\";\n\nimport { overlapOf, soundingsOf } from \"./sounding.ts\";\nimport type { Sounding, Span } from \"./sounding.ts\";\n\nconst FIRST = 1;\nconst NONE = 0;\nconst OCTAVE = 12;\nconst SQUARE = 2;\nconst CORRELATION_DIGITS = 3;\nconst UNKNOWN = \"?\";\n\nconst MAJOR_PROFILE = {\n tonic: 6.35,\n minorSecond: 2.23,\n majorSecond: 3.48,\n minorThird: 2.33,\n majorThird: 4.38,\n fourth: 4.09,\n tritone: 2.52,\n fifth: 5.19,\n minorSixth: 2.39,\n majorSixth: 3.66,\n minorSeventh: 2.29,\n majorSeventh: 2.88,\n};\n\nconst MINOR_PROFILE = {\n tonic: 6.33,\n minorSecond: 2.68,\n majorSecond: 3.52,\n minorThird: 5.38,\n majorThird: 2.6,\n fourth: 3.53,\n tritone: 2.54,\n fifth: 4.75,\n minorSixth: 3.98,\n majorSixth: 2.69,\n minorSeventh: 3.34,\n majorSeventh: 3.17,\n};\n\nconst MAJOR_TONICS = [\"C\", \"Db\", \"D\", \"Eb\", \"E\", \"F\", \"F#\", \"G\", \"Ab\", \"A\", \"Bb\", \"B\"];\nconst MINOR_TONICS = [\"C\", \"C#\", \"D\", \"Eb\", \"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"Bb\", \"B\"];\n\nconst ModeSchema = Schema.Literals([\"major\", \"minor\"]);\n\ntype Mode = typeof ModeSchema.Type;\n\nconst barRangeFields = { fromBar: Schema.Int, toBar: Schema.Int };\n\nexport const BarRangeSchema = Schema.Struct(barRangeFields);\n\nexport type BarRange = typeof BarRangeSchema.Type;\n\nexport const KeySpanSchema = Schema.Struct({\n ...barRangeFields,\n tonic: Schema.String,\n pitchClass: Schema.Int,\n mode: ModeSchema,\n correlation: Schema.Finite,\n});\n\nexport type KeySpan = typeof KeySpanSchema.Type;\n\ninterface Candidate {\n readonly tonic: string;\n readonly pitchClass: number;\n readonly mode: Mode;\n readonly correlation: number;\n}\n\nconst pitchClassOf = (midi: number): number => ((midi % OCTAVE) + OCTAVE) % OCTAVE;\n\nconst addWeight =\n (window: Span) =>\n (weights: readonly number[], note: Sounding): readonly number[] => {\n const share = overlapOf(note)(window);\n const pitchClass = pitchClassOf(note.midi);\n return pipe(\n weights,\n Arr.map((weight, index) => {\n if (index === pitchClass) {\n return weight + share;\n }\n return weight;\n }),\n );\n };\n\nconst histogramOf =\n (window: Span) =>\n (notes: readonly Sounding[]): readonly number[] =>\n Arr.reduce(\n notes,\n Arr.makeBy(OCTAVE, () => NONE),\n addWeight(window),\n );\n\nconst add = (sum: number, value: number): number => sum + value;\n\nconst sumOf = (values: readonly number[]): number => Arr.reduce(values, NONE, add);\n\nconst meanOf = (values: readonly number[]): number => sumOf(values) / values.length;\n\nconst spreadOf = (values: readonly number[]): number => {\n const center = meanOf(values);\n const squares = pipe(\n values,\n Arr.map((value) => (value - center) ** SQUARE),\n );\n return Math.sqrt(sumOf(squares));\n};\n\nconst correlationOf =\n (profile: readonly number[]) =>\n (histogram: readonly number[]): number => {\n const histogramMean = meanOf(histogram);\n const profileMean = meanOf(profile);\n const covariance = sumOf(\n pipe(\n Arr.zip(histogram, profile),\n Arr.map(([weight, expected]) => (weight - histogramMean) * (expected - profileMean)),\n ),\n );\n const scale = spreadOf(histogram) * spreadOf(profile);\n if (scale === NONE) {\n return NONE;\n }\n return covariance / scale;\n };\n\nconst rotated =\n (tonic: number) =>\n (profile: Readonly<Record<string, number>>): readonly number[] => {\n const weights = Record.values(profile);\n return Arr.makeBy(OCTAVE, (index) => weights[(index - tonic + OCTAVE) % OCTAVE] ?? NONE);\n };\n\nconst candidatesAt =\n (histogram: readonly number[]) =>\n (tonic: number): readonly Candidate[] => [\n {\n tonic: MAJOR_TONICS[tonic] ?? UNKNOWN,\n pitchClass: tonic,\n mode: \"major\",\n correlation: correlationOf(rotated(tonic)(MAJOR_PROFILE))(histogram),\n },\n {\n tonic: MINOR_TONICS[tonic] ?? UNKNOWN,\n pitchClass: tonic,\n mode: \"minor\",\n correlation: correlationOf(rotated(tonic)(MINOR_PROFILE))(histogram),\n },\n ];\n\nconst byCorrelation = Order.flip(\n Order.mapInput(Order.Number, (candidate: Candidate) => candidate.correlation),\n);\n\nconst edgeOf =\n (song: Song) =>\n (index: number, end: boolean): number =>\n pipe(\n song.bars,\n Arr.findFirst((bar) => bar.index === index),\n Option.match({\n onNone: () => NONE,\n onSome: (bar) => bar.start + Number(end) * bar.length,\n }),\n );\n\nexport const keyIn =\n (song: Song) =>\n (range: BarRange): Option.Option<KeySpan> => {\n const edge = edgeOf(song);\n const histogram = histogramOf({\n start: edge(range.fromBar, false),\n end: edge(range.toBar, true),\n })(soundingsOf(song));\n const silent = pipe(\n histogram,\n Arr.every((weight) => weight === NONE),\n );\n if (silent) {\n return Option.none();\n }\n const candidates = pipe(Arr.range(NONE, OCTAVE - FIRST), Arr.flatMap(candidatesAt(histogram)));\n return pipe(\n Arr.sort(candidates, byCorrelation),\n Arr.head,\n Option.map((best) => ({\n fromBar: range.fromBar,\n toBar: range.toBar,\n tonic: best.tonic,\n pitchClass: best.pitchClass,\n mode: best.mode,\n correlation: Num.round(best.correlation, CORRELATION_DIGITS),\n })),\n );\n };\n","import { Array as Arr, Option, Order, pipe } from \"effect\";\n\nimport type { Song } from \"#/entities/song/index.ts\";\n\nimport type { BarRange } from \"./keys.ts\";\n\nconst FIRST = 1;\nconst SECOND = 2;\n\nconst fingerprintOf =\n (song: Song) =>\n (bar: number): string => {\n const notes = pipe(\n song.notes,\n Arr.filter((note) => note.bar === bar),\n Arr.map(\n (note) =>\n `${note.track}:${String(note.offset)}:${String(note.midi)}:${String(note.length)}`,\n ),\n );\n const hits = pipe(\n song.hits,\n Arr.filter((hit) => hit.bar === bar),\n Arr.map((hit) => `${hit.track}:${String(hit.offset)}:${hit.voice}`),\n );\n const slices = pipe(\n song.slices,\n Arr.filter((slice) => slice.bar === bar),\n Arr.map(\n (slice) => `${slice.track}:${String(slice.offset)}:${slice.sample}:${String(slice.index)}`,\n ),\n );\n return pipe(Arr.sort([...notes, ...hits, ...slices], Order.String), Arr.join(\"|\"));\n };\n\nconst repeatOf =\n (prints: readonly string[]) =>\n (bar: number): boolean => {\n const print = prints[bar - FIRST] ?? \"\";\n return print !== \"\" && print === prints[bar - SECOND];\n };\n\nconst joinRun = (runs: readonly BarRange[], bar: number): readonly BarRange[] =>\n Option.match(Arr.last(runs), {\n onNone: () => [{ fromBar: bar - FIRST, toBar: bar }],\n onSome: (last) => {\n if (last.toBar !== bar - FIRST) {\n return [...runs, { fromBar: bar - FIRST, toBar: bar }];\n }\n return [...Arr.dropRight(runs, FIRST), { ...last, toBar: bar }];\n },\n });\n\nexport const repeatsOf = (song: Song): readonly BarRange[] => {\n const bars = song.bars.length;\n const prints = pipe(Arr.range(FIRST, bars), Arr.map(fingerprintOf(song)));\n const repeated = pipe(Arr.range(SECOND, bars), Arr.filter(repeatOf(prints)));\n return Arr.reduce(repeated, [] as readonly BarRange[], joinRun);\n};\n","import { Array as Arr, Option, Schema, pipe } from \"effect\";\n\nimport type { Song } from \"#/entities/song/index.ts\";\n\nimport { ChordSpanSchema, chordsOf } from \"./chords.ts\";\nimport { BarRangeSchema, KeySpanSchema, keyIn } from \"./keys.ts\";\nimport type { BarRange } from \"./keys.ts\";\nimport { repeatsOf } from \"./repeats.ts\";\n\nconst FIRST = 1;\nconst NONE = 0;\nconst PHRASE_BARS = 4;\n\nexport const AnalysisSchema = Schema.Struct({\n bars: Schema.Int,\n key: Schema.OptionFromNullOr(KeySpanSchema),\n keys: Schema.Array(KeySpanSchema),\n chords: Schema.Array(ChordSpanSchema),\n repeats: Schema.Array(BarRangeSchema),\n});\n\nexport type Analysis = typeof AnalysisSchema.Type;\n\nconst phrasesOf = (bars: number): readonly BarRange[] =>\n Arr.makeBy(Math.ceil(bars / PHRASE_BARS), (phrase) => ({\n fromBar: phrase * PHRASE_BARS + FIRST,\n toBar: Math.min(bars, (phrase + FIRST) * PHRASE_BARS),\n }));\n\nexport const analyze = (song: Song): Analysis => {\n const bars = song.bars.length;\n if (bars === NONE) {\n return { bars, key: Option.none(), keys: [], chords: [], repeats: [] };\n }\n return {\n bars,\n key: keyIn(song)({ fromBar: FIRST, toBar: bars }),\n keys: pipe(phrasesOf(bars), Arr.map(keyIn(song)), Arr.getSomes),\n chords: chordsOf(song),\n repeats: repeatsOf(song),\n };\n};\n","import { Array as Arr, Console, Effect, FileSystem, Path, Schema, pipe } from \"effect\";\nimport { Argument, Command } from \"effect/cli\";\n\nimport { AnalysisSchema, analyze } from \"#/features/analyze-song/index.ts\";\nimport { readSong } from \"#/features/read-song/index.ts\";\n\nconst INDENT = 2;\n\nconst encodeReport = Schema.encodeUnknownEffect(\n Schema.fromJsonString(AnalysisSchema, { space: INDENT }),\n);\n\nconst taggedError = Schema.TaggedError;\n\nclass InvalidSong extends taggedError<InvalidSong, { readonly brand: unique symbol }>()(\n \"InvalidSong\",\n { message: Schema.String },\n { identifier: \"InvalidSong\" },\n) {}\n\n/** @internal */\nexport const reportCommand = Command.make(\n \"report\",\n {\n file: Argument.String(\"file\").pipe(\n Argument.withDescription(\n \"A .fumx file; reads the files it imports and prints the keys, chords and repeated bars read from its notes\",\n ),\n ),\n },\n ({ file }) =>\n Effect.gen(function* report() {\n const fileSystem = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const source = yield* readSong({\n path: path.resolve(file),\n read: (target) => fileSystem.readFileString(target),\n });\n if (source.status === \"invalid\") {\n const lines = pipe(\n source.issues,\n Arr.map(\n (issue) =>\n `${issue.path}:${String(issue.line)}:${String(issue.column)} ${issue.message}`,\n ),\n );\n return yield* InvalidSong.make({ message: Arr.join(lines, \"\\n\") });\n }\n const encoded = yield* encodeReport(analyze(source.song));\n return yield* Console.log(encoded);\n }),\n).pipe(\n Command.withDescription(\n \"Prints, as JSON, the keys, chords and repeated bars read from the notes of a .fumx song\",\n ),\n);\n","import manifest from \"@r_masseater/fumx/package.json\" with { type: \"json\" };\nimport { runMain } from \"@r_masseater/masseater-utils/node-main\";\nimport { Command } from \"effect/cli\";\n\nimport { convertCommand } from \"./convert-command.ts\";\nimport { languageServerCommand } from \"./language-server.ts\";\nimport { lintCommand } from \"./lint-command.ts\";\nimport { reportCommand } from \"./song-report-command.ts\";\n\nconst command = Command.make(\"fumx\").pipe(\n Command.withDescription(manifest.description),\n Command.withSubcommands([lintCommand, reportCommand, convertCommand, languageServerCommand]),\n);\n\n/** @internal */\nexport const runCli = (): void => {\n command.pipe(Command.run({ version: manifest.version }), runMain(\"fumx\"));\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;ACAA,MAAa,WAAW;CACtB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAIA,MAAa,QAAQ;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AC9KA,MAAMA,UAAO;AACb,MAAMC,UAAO;AAEb,MAAa,cAAmC,SAAS,KAAK,YAAA;AAa9D,MAAM,cAA0C,SAC9C,GAAG,OAAO,KAAK,IAAI,EAAE,GAAG,OAAO,KAAK,GAAG,EAAE,GAAG,OAAO,KAAK,QAAQ,EAAE,GAAG,OAAO,KAAK,OAAO;AAE1F,MAAM,WAAgE,UACpE,KACEC,MAAI,KAAK,KAAK,GACd,OAAO,KAAK,WAAW;CACrB,OAAO,MAAM;CACb,KAAK,MAAM;CACX,OAAO,KACL,OACAA,MAAI,KAAK,SAAS,KAAK,IAAI,CAC7B;CACA,UAAU,MAAM;CAChB,SAAS,MAAM;CACf,OAAO,OAAO,KAAK;AACrB,EAAE,CACJ;AAEF,MAAM,aAAkF,UACtF,KACE,OACAA,MAAI,KAAK,MAAM,WAAW;CACxB;CACA,OAAO,KACLA,MAAI,KAAK,OAAO,KAAK,GACrBA,MAAI,SAAS,YAAY,QAAQ,SAAS,KAAK,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