@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.
Files changed (66) hide show
  1. package/LICENSE +87 -0
  2. package/README.md +124 -2
  3. package/dist/analysis-BAPm6c9P.d.mts +75 -0
  4. package/dist/analysis-CRyaJD5D.mjs +294 -0
  5. package/dist/analysis-CRyaJD5D.mjs.map +1 -0
  6. package/dist/analysis.d.mts +3 -0
  7. package/dist/analysis.mjs +3 -0
  8. package/dist/cli-D2DptmOG.mjs +2506 -0
  9. package/dist/cli-D2DptmOG.mjs.map +1 -0
  10. package/dist/convert-als.d.mts +17 -0
  11. package/dist/convert-als.mjs +512 -0
  12. package/dist/convert-als.mjs.map +1 -0
  13. package/dist/convert-midi.d.mts +17 -0
  14. package/dist/convert-midi.mjs +273 -0
  15. package/dist/convert-midi.mjs.map +1 -0
  16. package/dist/fumx.mjs +9 -0
  17. package/dist/fumx.mjs.map +1 -0
  18. package/dist/grammar-Ds8M-PkG.mjs +9836 -0
  19. package/dist/grammar-Ds8M-PkG.mjs.map +1 -0
  20. package/dist/habits.d.mts +71 -0
  21. package/dist/habits.mjs +98 -0
  22. package/dist/habits.mjs.map +1 -0
  23. package/dist/index-Bc9UT9HF.d.mts +795 -0
  24. package/dist/index-C7av_aK1.d.mts +104 -0
  25. package/dist/index-DOfjU43D.d.mts +71 -0
  26. package/dist/index-KxUilka8.d.mts +6 -0
  27. package/dist/index.d.mts +5 -0
  28. package/dist/index.mjs +4 -0
  29. package/dist/lint-Bnl4l0aI.mjs +296 -0
  30. package/dist/lint-Bnl4l0aI.mjs.map +1 -0
  31. package/dist/lint-CJ5lq-Fr.d.mts +37 -0
  32. package/dist/lint.d.mts +3 -0
  33. package/dist/lint.mjs +1 -0
  34. package/dist/mapper.mjs +14 -0
  35. package/dist/mapper.mjs.map +1 -0
  36. package/dist/mix-facts-QCYCXdIA.mjs +7006 -0
  37. package/dist/mix-facts-QCYCXdIA.mjs.map +1 -0
  38. package/dist/presets.d.mts +35 -0
  39. package/dist/presets.mjs +814 -0
  40. package/dist/presets.mjs.map +1 -0
  41. package/dist/read-song-B9342KUK.mjs +13017 -0
  42. package/dist/read-song-B9342KUK.mjs.map +1 -0
  43. package/dist/read-song-CsW4kd7v.d.mts +1326 -0
  44. package/dist/read-song-DW8MLsln.mjs +2783 -0
  45. package/dist/read-song-DW8MLsln.mjs.map +1 -0
  46. package/dist/song-BlIPWk7b.mjs +387 -0
  47. package/dist/song-BlIPWk7b.mjs.map +1 -0
  48. package/dist/song-UZ4T_dj9.d.mts +1477 -0
  49. package/dist/sounding-BCyExbPp.d.mts +20 -0
  50. package/dist/sounding-DYDZFp4e.mjs +41 -0
  51. package/dist/sounding-DYDZFp4e.mjs.map +1 -0
  52. package/dist/style-rules-CjaZTDt_.d.mts +131 -0
  53. package/dist/ticks-D6yACwHt.mjs +26 -0
  54. package/dist/ticks-D6yACwHt.mjs.map +1 -0
  55. package/dist/transform-CeFBPHqb.mjs +108 -0
  56. package/dist/transform-CeFBPHqb.mjs.map +1 -0
  57. package/dist/vite.d.mts +8 -0
  58. package/dist/vite.mjs +127 -0
  59. package/dist/vite.mjs.map +1 -0
  60. package/dist/write-CHtCd-bG.mjs +747 -0
  61. package/dist/write-CHtCd-bG.mjs.map +1 -0
  62. package/package.json +118 -3
  63. package/skills/lint-songs/SKILL.md +54 -0
  64. package/skills/read-fumx/SKILL.md +89 -0
  65. package/skills/use-fumx-tools/SKILL.md +69 -0
  66. package/skills/use-lint-presets/SKILL.md +72 -0
@@ -0,0 +1,2506 @@
1
+ import { runMain } from "@r_masseater/masseater-utils/node-main";
2
+ import { Argument, Command, Flag as Flag$1 } from "effect/cli";
3
+ import { Array, Boolean, Chunk, Console, Effect, FileSystem, Function, Match, Number as Number$1, Option, Order, Path, Predicate, Record, Result, Schema, String as String$1, pipe } from "effect";
4
+ import { a as FumxGeneratedSharedModule, c as TICKS_PER_WHOLE, d as FumxTerminals, i as FumxGeneratedModule, l as fractionOf, n as FumxModule, o as MIXER_PARAMETERS, r as registerChecks, t as readSong, u as FumxGrammar } from "./read-song-B9342KUK.mjs";
5
+ import { Chord, Midi, Note } from "tonal";
6
+ import { AstUtils, GrammarAST, inject } from "langium";
7
+ import { XMLParser } from "fast-xml-parser";
8
+ import { decodeTimeSignatureId } from "ableton-als";
9
+ import { parseMidi } from "midi-file";
10
+ import { createDefaultModule, createDefaultSharedModule, startLanguageServer } from "langium/lsp";
11
+ import { NodeFileSystem } from "langium/node";
12
+ import { ProposedFeatures, createConnection } from "vscode-languageserver/node";
13
+ import { ChildProcess, ChildProcessSpawner } from "effect/process";
14
+ import { groupsOf as groupsOf$1 } from "@r_masseater/masseater-utils/text";
15
+ // package.json
16
+ var version = "0.1.1";
17
+ var description = "Everything for .fumx songs: read a song as a typed value, analyze its keys and chords, import it from TypeScript with Vite, edit it with a language server, convert MIDI and Ableton Live Sets with a check against the original, and lint musical rules such as notes outside the key, part ranges and parallel fifths from vite.config.ts.";
18
+ // src/entities/timeline/model/general-midi.ts
19
+ const PROGRAMS = [
20
+ "acoustic-grand-piano",
21
+ "bright-acoustic-piano",
22
+ "electric-grand-piano",
23
+ "honky-tonk-piano",
24
+ "electric-piano-1",
25
+ "electric-piano-2",
26
+ "harpsichord",
27
+ "clavinet",
28
+ "celesta",
29
+ "glockenspiel",
30
+ "music-box",
31
+ "vibraphone",
32
+ "marimba",
33
+ "xylophone",
34
+ "tubular-bells",
35
+ "dulcimer",
36
+ "drawbar-organ",
37
+ "percussive-organ",
38
+ "rock-organ",
39
+ "church-organ",
40
+ "reed-organ",
41
+ "accordion",
42
+ "harmonica",
43
+ "tango-accordion",
44
+ "acoustic-guitar-nylon",
45
+ "acoustic-guitar-steel",
46
+ "electric-guitar-jazz",
47
+ "electric-guitar-clean",
48
+ "electric-guitar-muted",
49
+ "overdriven-guitar",
50
+ "distortion-guitar",
51
+ "guitar-harmonics",
52
+ "acoustic-bass",
53
+ "electric-bass-finger",
54
+ "electric-bass-pick",
55
+ "fretless-bass",
56
+ "slap-bass-1",
57
+ "slap-bass-2",
58
+ "synth-bass-1",
59
+ "synth-bass-2",
60
+ "violin",
61
+ "viola",
62
+ "cello",
63
+ "contrabass",
64
+ "tremolo-strings",
65
+ "pizzicato-strings",
66
+ "orchestral-harp",
67
+ "timpani",
68
+ "string-ensemble-1",
69
+ "string-ensemble-2",
70
+ "synth-strings-1",
71
+ "synth-strings-2",
72
+ "choir-aahs",
73
+ "voice-oohs",
74
+ "synth-voice",
75
+ "orchestra-hit",
76
+ "trumpet",
77
+ "trombone",
78
+ "tuba",
79
+ "muted-trumpet",
80
+ "french-horn",
81
+ "brass-section",
82
+ "synth-brass-1",
83
+ "synth-brass-2",
84
+ "soprano-sax",
85
+ "alto-sax",
86
+ "tenor-sax",
87
+ "baritone-sax",
88
+ "oboe",
89
+ "english-horn",
90
+ "bassoon",
91
+ "clarinet",
92
+ "piccolo",
93
+ "flute",
94
+ "recorder",
95
+ "pan-flute",
96
+ "blown-bottle",
97
+ "shakuhachi",
98
+ "whistle",
99
+ "ocarina",
100
+ "lead-1-square",
101
+ "lead-2-sawtooth",
102
+ "lead-3-calliope",
103
+ "lead-4-chiff",
104
+ "lead-5-charang",
105
+ "lead-6-voice",
106
+ "lead-7-fifths",
107
+ "lead-8-bass-and-lead",
108
+ "pad-1-new-age",
109
+ "pad-2-warm",
110
+ "pad-3-polysynth",
111
+ "pad-4-choir",
112
+ "pad-5-bowed",
113
+ "pad-6-metallic",
114
+ "pad-7-halo",
115
+ "pad-8-sweep",
116
+ "fx-1-rain",
117
+ "fx-2-soundtrack",
118
+ "fx-3-crystal",
119
+ "fx-4-atmosphere",
120
+ "fx-5-brightness",
121
+ "fx-6-goblins",
122
+ "fx-7-echoes",
123
+ "fx-8-sci-fi",
124
+ "sitar",
125
+ "banjo",
126
+ "shamisen",
127
+ "koto",
128
+ "kalimba",
129
+ "bagpipe",
130
+ "fiddle",
131
+ "shanai",
132
+ "tinkle-bell",
133
+ "agogo",
134
+ "steel-drums",
135
+ "woodblock",
136
+ "taiko-drum",
137
+ "melodic-tom",
138
+ "synth-drum",
139
+ "reverse-cymbal",
140
+ "guitar-fret-noise",
141
+ "breath-noise",
142
+ "seashore",
143
+ "bird-tweet",
144
+ "telephone-ring",
145
+ "helicopter",
146
+ "applause",
147
+ "gunshot"
148
+ ];
149
+ const DRUMS = [
150
+ "acoustic-bass-drum",
151
+ "bass-drum-1",
152
+ "side-stick",
153
+ "acoustic-snare",
154
+ "hand-clap",
155
+ "electric-snare",
156
+ "low-floor-tom",
157
+ "closed-hi-hat",
158
+ "high-floor-tom",
159
+ "pedal-hi-hat",
160
+ "low-tom",
161
+ "open-hi-hat",
162
+ "low-mid-tom",
163
+ "hi-mid-tom",
164
+ "crash-cymbal-1",
165
+ "high-tom",
166
+ "ride-cymbal-1",
167
+ "chinese-cymbal",
168
+ "ride-bell",
169
+ "tambourine",
170
+ "splash-cymbal",
171
+ "cowbell",
172
+ "crash-cymbal-2",
173
+ "vibraslap",
174
+ "ride-cymbal-2",
175
+ "hi-bongo",
176
+ "low-bongo",
177
+ "mute-hi-conga",
178
+ "open-hi-conga",
179
+ "low-conga",
180
+ "high-timbale",
181
+ "low-timbale",
182
+ "high-agogo",
183
+ "low-agogo",
184
+ "cabasa",
185
+ "maracas",
186
+ "short-whistle",
187
+ "long-whistle",
188
+ "short-guiro",
189
+ "long-guiro",
190
+ "claves",
191
+ "hi-wood-block",
192
+ "low-wood-block",
193
+ "mute-cuica",
194
+ "open-cuica",
195
+ "mute-triangle",
196
+ "open-triangle"
197
+ ];
198
+ // src/entities/timeline/model/groups.ts
199
+ const NONE$13 = 0;
200
+ const NEXT$11 = 1;
201
+ const isDrumPart = (part) => part.channel === 9;
202
+ const chordKeyOf = (note) => `${String(note.tick)}:${String(note.end)}:${String(note.velocity)}:${String(note.release)}`;
203
+ const groupOf = (notes) => pipe(Array.head(notes), Option.map((first) => ({
204
+ start: first.tick,
205
+ end: first.end,
206
+ midis: pipe(notes, Array.map((note) => note.midi)),
207
+ velocity: first.velocity,
208
+ release: first.release,
209
+ lyric: Option.none()
210
+ })));
211
+ const stackedOf = (chord) => pipe(chord, Array.map((note, index) => ({
212
+ note,
213
+ layer: pipe(Array.take(chord, index), Array.countBy((earlier) => earlier.midi === note.midi))
214
+ })), Array.groupBy(({ layer }) => String(layer)), Record.values, Array.map((layer) => pipe(layer, Array.map(({ note }) => note))));
215
+ const chordsOf$1 = (part) => {
216
+ if (isDrumPart(part)) return pipe(part.notes, Array.map((note) => [note]));
217
+ return pipe(part.notes, Array.groupBy(chordKeyOf), Record.values, Array.flatMap(stackedOf));
218
+ };
219
+ const byStartThenLonger = Order.combine(Order.mapInput(Order.Number, (group) => group.start), Order.mapInput(Order.flip(Order.Number), (group) => group.end));
220
+ const withLyrics = (part) => (groups) => pipe(groups, Array.map((group, index) => {
221
+ const leads = pipe(Array.get(groups, index - NEXT$11), Option.match({
222
+ onNone: () => true,
223
+ onSome: (previous) => previous.start !== group.start
224
+ }));
225
+ const lyric = pipe(Array.findFirst(part.lyrics, (candidate) => candidate.tick === group.start), Option.filter(() => leads), Option.map((found) => found.text));
226
+ return {
227
+ ...group,
228
+ lyric
229
+ };
230
+ }));
231
+ const groupsOf = (part) => {
232
+ const groups = pipe(chordsOf$1(part), Array.map(groupOf), Array.getSomes);
233
+ return withLyrics(part)(Array.sort(groups, byStartThenLonger));
234
+ };
235
+ const endOfLine = (line) => Option.match(Array.last(line), {
236
+ onNone: () => NONE$13,
237
+ onSome: (group) => group.end
238
+ });
239
+ const placeGroup = (lines, group) => Option.match(Array.findFirstIndex(lines, (line) => endOfLine(line) <= group.start), {
240
+ onNone: () => [...lines, [group]],
241
+ onSome: (index) => pipe(lines, Array.map((line, position) => {
242
+ if (position === index) return [...line, group];
243
+ return line;
244
+ }))
245
+ });
246
+ const linesOf = (groups) => Array.reduce(groups, [], placeGroup);
247
+ // src/entities/timeline/model/names.ts
248
+ const FIRST_SUFFIX = 2;
249
+ const keywordsIn = (node) => new Set(AstUtils.streamAst(node).filter((child) => GrammarAST.isKeyword(child)).map((keyword) => keyword.value));
250
+ const grammar = FumxGrammar();
251
+ const allowedKeywords = pipe(grammar.rules, Array.findFirst((rule) => rule.name === "Name"), Option.match({
252
+ onNone: () => /* @__PURE__ */ new Set(),
253
+ onSome: keywordsIn
254
+ }));
255
+ const allKeywords = Array.fromIterable(keywordsIn(grammar));
256
+ const reserved = new Set(pipe(allKeywords, Array.filter((keyword) => !allowedKeywords.has(keyword))));
257
+ const otherTerminals = pipe(Record.toEntries(FumxTerminals), Array.filter(([name]) => name !== "ID"), Array.map(([, pattern]) => new RegExp(`^(?:${pattern.source})$`, "u")));
258
+ const identifier = new RegExp(`^(?:${FumxTerminals.ID.source})$`, "u");
259
+ const isUsable = (name) => identifier.test(name) && !reserved.has(name) && !pipe(otherTerminals, Array.some((pattern) => pattern.test(name)));
260
+ const slugOf = (text) => pipe(text, String$1.normalize("NFKD"), String$1.toLowerCase, String$1.replaceAll(/[^a-z0-9]+/gu, "-"), String$1.replaceAll(/^[-0-9]+|-+$/gu, ""));
261
+ const nameFrom = (candidates) => pipe(candidates, Array.map(slugOf), Array.findFirst(isUsable), Option.getOrElse(() => "part"));
262
+ const uniqueAmong = (taken) => (name) => pipe(Array.range(FIRST_SUFFIX, taken.size + FIRST_SUFFIX), Array.map((suffix) => `${name}-${String(suffix)}`), Array.prepend(name), Array.findFirst((candidate) => isUsable(candidate) && !taken.has(candidate)), Option.getOrElse(() => `${name}-${String(taken.size)}`));
263
+ // src/entities/timeline/model/plan.ts
264
+ const NONE$12 = 0;
265
+ const NEXT$10 = 1;
266
+ const SHARED = 1;
267
+ const DEFAULT_PROGRAM = 0;
268
+ const drumNameOf = (midi) => Option.getOrElse(Array.get(DRUMS, midi - 35), () => `note-${String(midi)}`);
269
+ const programNameOf = (program) => Option.getOrElse(Array.get(PROGRAMS, program), () => `program-${String(program)}`);
270
+ const controllerKeyOf = ({ controller }) => {
271
+ if (controller.kind === "cc") return `cc ${String(controller.number)}`;
272
+ if (controller.kind === "pressure") return Option.match(controller.midi, {
273
+ onNone: () => "pressure",
274
+ onSome: (midi) => `pressure ${String(midi)}`
275
+ });
276
+ return controller.kind;
277
+ };
278
+ const isLastAtTick = (controls) => (index) => pipe(Option.all([Array.get(controls, index), Array.get(controls, index + NEXT$10)]), Option.match({
279
+ onNone: () => true,
280
+ onSome: ([control, next]) => next.tick !== control.tick || controllerKeyOf(next) !== controllerKeyOf(control)
281
+ }));
282
+ const byControllerThenTick = Order.combine(Order.mapInput(Order.String, controllerKeyOf), Order.mapInput(Order.Number, (control) => control.tick));
283
+ const controlsOf$1 = (part) => {
284
+ const drumProgram = pipe(part.program, Option.filter(() => isDrumPart(part)), Option.map((value) => ({
285
+ tick: NONE$12,
286
+ controller: { kind: "program" },
287
+ value
288
+ })), Option.toArray);
289
+ const sorted = Array.sort([...drumProgram, ...part.controls], byControllerThenTick);
290
+ return pipe(sorted, Array.filter((_control, index) => isLastAtTick(sorted)(index)));
291
+ };
292
+ const programOf = (part) => Option.getOrElse(part.program, () => DEFAULT_PROGRAM);
293
+ const labelOf = (part) => Option.getOrElse(part.name, () => "");
294
+ const instrumentsOf = (parts) => new Map(pipe(parts, Array.filter((part) => !isDrumPart(part)), Array.map(programOf), Array.dedupe, Array.map((program) => [program, nameFrom([programNameOf(program)])])));
295
+ const drumVoicesOf = (parts) => {
296
+ const midis = pipe(parts, Array.filter(isDrumPart), Array.flatMap((part) => part.notes), Array.map((note) => note.midi), Array.dedupe);
297
+ return new Map(pipe(Array.sort(midis, Order.Number), Array.map((midi) => [midi, drumNameOf(midi)])));
298
+ };
299
+ const channelledOf = (shared) => (part) => {
300
+ const label = labelOf(part);
301
+ if (shared.has(label)) return `${label} ch${String(part.channel + NEXT$10)}`;
302
+ return label;
303
+ };
304
+ const fallbackOf = (part) => {
305
+ if (isDrumPart(part)) return "drums";
306
+ return programNameOf(programOf(part));
307
+ };
308
+ const candidatesOf = (shared) => (part) => [
309
+ channelledOf(shared)(part),
310
+ fallbackOf(part),
311
+ `track ${String(part.track)}`
312
+ ];
313
+ const sharedLabelsOf = (parts) => new Set(pipe(parts, Array.groupBy(labelOf), Record.filter((same) => same.length > SHARED), Record.keys));
314
+ const sourceOf = (instruments) => (part) => {
315
+ if (isDrumPart(part)) return { kind: "kit" };
316
+ const program = programOf(part);
317
+ return {
318
+ kind: "instrument",
319
+ instrument: instruments.get(program) ?? "",
320
+ program
321
+ };
322
+ };
323
+ const namesOf = (planned) => new Set(pipe(planned, Array.map((done) => done.name)));
324
+ const UNMIXED = {
325
+ level: {
326
+ decibels: NONE$12,
327
+ pan: NONE$12,
328
+ muted: false
329
+ },
330
+ sends: [],
331
+ envelopes: []
332
+ };
333
+ const NO_PARTS = [];
334
+ const nextPart = (naming) => (planned, part) => {
335
+ const name = uniqueAmong(namesOf(planned))(nameFrom(naming.candidates(part)));
336
+ return Array.append(planned, {
337
+ part,
338
+ name,
339
+ source: sourceOf(naming.instruments)(part),
340
+ lines: linesOf(groupsOf(part)),
341
+ controls: controlsOf$1(part),
342
+ mix: naming.mixes.get(part.track) ?? UNMIXED
343
+ });
344
+ };
345
+ const busesOf = ({ taken, buses }) => {
346
+ const used = new Set(taken);
347
+ const named = [];
348
+ for (const [index, bus] of buses.entries()) {
349
+ const name = uniqueAmong(used)(nameFrom([...Option.toArray(bus.name), `bus ${String(index + NEXT$10)}`]));
350
+ used.add(name);
351
+ named.push({
352
+ name,
353
+ level: bus.level
354
+ });
355
+ }
356
+ return named;
357
+ };
358
+ const planOf = (timeline) => {
359
+ const instruments = instrumentsOf(timeline.parts);
360
+ const candidates = candidatesOf(sharedLabelsOf(timeline.parts));
361
+ const parts = Array.reduce(timeline.parts, NO_PARTS, nextPart({
362
+ instruments,
363
+ candidates,
364
+ mixes: timeline.mix.tracks
365
+ }));
366
+ return {
367
+ parts,
368
+ buses: busesOf({
369
+ taken: namesOf(parts),
370
+ buses: timeline.mix.buses
371
+ }),
372
+ instruments,
373
+ drumVoices: drumVoicesOf(timeline.parts)
374
+ };
375
+ };
376
+ // src/entities/timeline/model/tempo-units.ts
377
+ const MICROSECONDS_PER_MINUTE = 6e7;
378
+ const bpmOf = (microseconds) => MICROSECONDS_PER_MINUTE / microseconds;
379
+ const microsecondsOf = (bpm) => Math.round(MICROSECONDS_PER_MINUTE / bpm);
380
+ // src/entities/timeline/model/compare.ts
381
+ const NONE$11 = 0;
382
+ const NEXT$9 = 1;
383
+ const UNKNOWN$2 = -1;
384
+ const FULL$2 = 127;
385
+ const DEFAULT_RELEASE$3 = 64;
386
+ const DECIMALS$1 = 9;
387
+ const SHOWN = 20;
388
+ const countsOf = (keys) => pipe(keys, Array.groupBy((key) => key), Record.map((same) => same.length));
389
+ const surplusOf = (over) => (under) => pipe(Record.toEntries(over), Array.flatMap(([key, count]) => {
390
+ const left = count - Option.getOrElse(Record.get(under, key), () => NONE$11);
391
+ if (left > NONE$11) return Array.makeBy(left, () => key);
392
+ return [];
393
+ }), Array.take(SHOWN));
394
+ const tallyOf = (expected, actual) => {
395
+ const wanted = countsOf(expected);
396
+ const found = countsOf(actual);
397
+ return {
398
+ expected: expected.length,
399
+ actual: actual.length,
400
+ missing: surplusOf(wanted)(found),
401
+ extra: surplusOf(found)(wanted)
402
+ };
403
+ };
404
+ const byteOf = (share) => Math.round(share * FULL$2);
405
+ const releaseOf$2 = (release) => Option.match(release, {
406
+ onNone: () => DEFAULT_RELEASE$3,
407
+ onSome: byteOf
408
+ });
409
+ const keyOf = (parts) => pipe(parts, Array.map(String), Array.join(" "));
410
+ const expectedNotesOf = (plan) => pipe(plan.parts, Array.flatMap((planned) => pipe(planned.part.notes, Array.map((note) => keyOf([
411
+ planned.name,
412
+ note.tick,
413
+ note.end - note.tick,
414
+ note.midi,
415
+ note.velocity,
416
+ note.release
417
+ ])))));
418
+ const actualNotesOf = ({ plan, song }) => {
419
+ const voices = new Map(pipe(Array.fromIterable(plan.drumVoices), Array.map(([midi, name]) => [name, midi])));
420
+ const notes = pipe(song.notes, Array.map((note) => keyOf([
421
+ note.track,
422
+ note.start,
423
+ note.length,
424
+ note.midi,
425
+ byteOf(note.velocity),
426
+ releaseOf$2(note.releaseVelocity)
427
+ ])));
428
+ const hits = pipe(song.hits, Array.map((hit) => keyOf([
429
+ hit.track,
430
+ hit.start,
431
+ hit.length,
432
+ voices.get(hit.voice) ?? UNKNOWN$2,
433
+ byteOf(hit.velocity),
434
+ releaseOf$2(hit.releaseVelocity)
435
+ ])));
436
+ return [...notes, ...hits];
437
+ };
438
+ const rounded = (value) => String(Number(value.toFixed(DECIMALS$1)));
439
+ const expectedControlsOf = (plan) => pipe(plan.parts, Array.flatMap((planned) => pipe(planned.controls, Array.map((control) => keyOf([
440
+ planned.name,
441
+ controllerKeyOf(control),
442
+ control.tick,
443
+ rounded(control.value)
444
+ ])))));
445
+ const actualControlsOf = (song) => pipe(song.controls, Array.map((control) => keyOf([
446
+ control.track,
447
+ controllerKeyOf({ controller: control.controller }),
448
+ control.start,
449
+ rounded(control.value)
450
+ ])));
451
+ const FLAT = "-";
452
+ const isFlatRepeat = (point, previous) => Option.isNone(point.target) && Option.isNone(previous.target) && previous.microseconds === point.microseconds;
453
+ const changesOf = (points) => pipe(points, Array.filter((point, index) => pipe(Array.get(points, index - NEXT$9), Option.match({
454
+ onNone: () => true,
455
+ onSome: (previous) => !isFlatRepeat(point, previous)
456
+ }))), Array.map(({ tick, microseconds, target }) => keyOf([
457
+ tick,
458
+ microseconds,
459
+ Option.getOrElse(target, () => FLAT)
460
+ ])));
461
+ const expectedTempoOf = (bars) => changesOf(pipe(bars, Array.flatMap((bar) => pipe(bar.tempo, Array.map((step) => ({
462
+ tick: bar.start + step.offset,
463
+ microseconds: step.microseconds,
464
+ target: step.target
465
+ }))))));
466
+ const barPointsOf = (bar) => {
467
+ if (Array.isReadonlyArrayNonEmpty(bar.tempoSteps)) return pipe(bar.tempoSteps, Array.map((step) => ({
468
+ tick: bar.start + step.offset,
469
+ microseconds: microsecondsOf(step.bpm),
470
+ target: pipe(step.target, Option.map(microsecondsOf))
471
+ })));
472
+ return [{
473
+ tick: bar.start,
474
+ microseconds: microsecondsOf(bar.tempo.bpm),
475
+ target: Option.none()
476
+ }];
477
+ };
478
+ const actualTempoOf = (song) => changesOf(pipe(song.bars, Array.flatMap(barPointsOf)));
479
+ const expectedLyricsOf = (plan) => pipe(plan.parts, Array.flatMap((planned) => pipe(planned.lines, Array.flatten, Array.flatMap((group) => pipe(group.lyric, Option.map((text) => keyOf([
480
+ planned.name,
481
+ group.start,
482
+ text
483
+ ])), Option.toArray)))));
484
+ const syllableKeyOf = (note) => pipe(note.lyric, Option.flatMap((lyric) => {
485
+ if (lyric.kind === "syllable") return Option.some(keyOf([
486
+ note.track,
487
+ note.start,
488
+ lyric.text
489
+ ]));
490
+ return Option.none();
491
+ }));
492
+ const actualLyricsOf = (song) => pipe(song.notes, Array.map(syllableKeyOf), Array.getSomes, Array.dedupe);
493
+ const expectedMarksOf = (bars) => pipe(bars, Array.filter((bar) => Array.isReadonlyArrayNonEmpty(bar.marks)), Array.map((bar) => keyOf([bar.start, Array.join(bar.marks, " / ")])));
494
+ const actualMarksOf = (song) => pipe(song.bars, Array.map((bar) => pipe(bar.mark, Option.map((mark) => keyOf([bar.start, mark])))), Array.getSomes);
495
+ const isClean = (tally) => !Array.isReadonlyArrayNonEmpty(tally.missing) && !Array.isReadonlyArrayNonEmpty(tally.extra);
496
+ const compareWithSong = ({ plan, bars, song }) => {
497
+ const tallies = {
498
+ notes: tallyOf(expectedNotesOf(plan), actualNotesOf({
499
+ plan,
500
+ song
501
+ })),
502
+ controls: tallyOf(expectedControlsOf(plan), actualControlsOf(song)),
503
+ tempo: tallyOf(expectedTempoOf(bars), actualTempoOf(song)),
504
+ lyrics: tallyOf(expectedLyricsOf(plan), actualLyricsOf(song)),
505
+ marks: tallyOf(expectedMarksOf(bars), actualMarksOf(song))
506
+ };
507
+ return {
508
+ ...tallies,
509
+ matches: pipe(Record.values(tallies), Array.every(isClean))
510
+ };
511
+ };
512
+ // src/entities/timeline/model/events.ts
513
+ const NO_MIX = {
514
+ tracks: /* @__PURE__ */ new Map(),
515
+ buses: []
516
+ };
517
+ const byTick = Order.mapInput(Order.Number, (timed) => timed.tick);
518
+ const sortedByTick = (items) => Array.sort(items, byTick);
519
+ const byTickThenPitch = Order.combine(Order.mapInput(Order.Number, (note) => note.tick), Order.mapInput(Order.Number, (note) => note.midi));
520
+ const sortedNotes = (notes) => Array.sort(notes, byTickThenPitch);
521
+ // src/entities/timeline/model/cells.ts
522
+ const NONE$10 = 0;
523
+ const FULL$1 = 127;
524
+ const SHARE_DECIMALS = 3;
525
+ const SEMITONE_DECIMALS = 12;
526
+ const LAST = 1;
527
+ const durationText = (length) => {
528
+ if (length === NONE$10) return "0/1";
529
+ return fractionOf(length);
530
+ };
531
+ const restCell = (length) => ({
532
+ head: "rest",
533
+ attributes: [],
534
+ length
535
+ });
536
+ const restsOf = (length) => {
537
+ if (length > NONE$10) return [restCell(length)];
538
+ return [];
539
+ };
540
+ const isRest = (cell) => cell.head === "rest";
541
+ const mergeRests = (merged, cell) => pipe(Array.last(merged), Option.filter((previous) => isRest(previous) && isRest(cell)), Option.match({
542
+ onNone: () => [...merged, cell],
543
+ onSome: (previous) => [...Array.dropRight(merged, LAST), restCell(previous.length + cell.length)]
544
+ }));
545
+ const NO_CELLS = [];
546
+ const cellText = (cell) => Array.join([
547
+ cell.head,
548
+ durationText(cell.length),
549
+ ...cell.attributes
550
+ ], " ");
551
+ const cellsText = (cells) => pipe(Array.reduce(cells, NO_CELLS, mergeRests), Array.map(cellText), Array.join(", "));
552
+ const quoted = (text) => `"${pipe(text, String$1.replaceAll("\\", String.raw`\\`), String$1.replaceAll("\"", String.raw`\"`), String$1.replaceAll("\n", String.raw`\n`), String$1.replaceAll("\r", String.raw`\r`), String$1.replaceAll(" ", String.raw`\t`))}"`;
553
+ const shareText = (value) => String(Number((value / FULL$1).toFixed(SHARE_DECIMALS)));
554
+ const semitoneText = (value) => {
555
+ const text = String(Number(value.toFixed(SEMITONE_DECIMALS)));
556
+ if (value > NONE$10) return `+${text}st`;
557
+ return `${text}st`;
558
+ };
559
+ const pitchText = (midi) => Midi.midiToNoteName(midi, { sharps: true });
560
+ // src/entities/timeline/model/layout.ts
561
+ const NONE$9 = 0;
562
+ const NEXT$8 = 1;
563
+ const QUARTER = 4;
564
+ const DEFAULT_METER = {
565
+ numerator: QUARTER,
566
+ denominator: QUARTER
567
+ };
568
+ const DEFAULT_MICROSECONDS = 5e5;
569
+ const MAX_DECIMALS = 9;
570
+ const endOfSpan = (span) => span.start + span.length;
571
+ const latestAt = (tick) => (items) => pipe(items, Array.filter((item) => item.tick <= tick), Array.last);
572
+ const lengthOf = (signature) => TICKS_PER_WHOLE * signature.numerator / signature.denominator;
573
+ const meterText = (signature) => (length) => {
574
+ const beats = length * signature.denominator / TICKS_PER_WHOLE;
575
+ if (Number.isInteger(beats)) return `${String(beats)}/${String(signature.denominator)}`;
576
+ return fractionOf(length);
577
+ };
578
+ const rampAt = (tempos) => (tick) => pipe(latestAt(tick)(tempos), Option.flatMap((start) => pipe(start.target, Option.flatMap((target) => pipe(Array.findFirst(tempos, (tempo) => tempo.tick > start.tick), Option.map((next) => ({
579
+ start,
580
+ end: next.tick,
581
+ target
582
+ })))))));
583
+ const interpolated = (ramp) => (tick) => {
584
+ const from = bpmOf(ramp.start.microseconds);
585
+ const to = bpmOf(ramp.target);
586
+ const share = (tick - ramp.start.tick) / (ramp.end - ramp.start.tick);
587
+ return microsecondsOf(from + (to - from) * share);
588
+ };
589
+ const rampedAt = (tempos) => (tick, at) => pipe(rampAt(tempos)(tick), Option.map((ramp) => interpolated(ramp)(at)));
590
+ const steadyAt = (tempos) => (tick) => pipe(latestAt(tick)(tempos), Option.match({
591
+ onNone: () => DEFAULT_MICROSECONDS,
592
+ onSome: (tempo) => tempo.microseconds
593
+ }));
594
+ const tempoAt = (tempos) => (tick) => Option.getOrElse(rampedAt(tempos)(tick, tick), () => steadyAt(tempos)(tick));
595
+ const tempoStepsOf = (tempos) => (bar) => {
596
+ const end = endOfSpan(bar);
597
+ const points = [bar.start, ...pipe(tempos, Array.filter((tempo) => tempo.tick > bar.start && tempo.tick < end), Array.map((tempo) => tempo.tick), Array.dedupe)];
598
+ return pipe(points, Array.map((tick, index) => {
599
+ const stepEnd = Option.getOrElse(Array.get(points, index + NEXT$8), () => end);
600
+ return {
601
+ offset: tick - bar.start,
602
+ length: stepEnd - tick,
603
+ microseconds: tempoAt(tempos)(tick),
604
+ target: rampedAt(tempos)(tick, stepEnd)
605
+ };
606
+ }));
607
+ };
608
+ const marksOf = (markers) => (bar) => pipe(markers, Array.filter((marker) => marker.tick >= bar.start && marker.tick < endOfSpan(bar)), Array.map((marker) => marker.text));
609
+ const spanAt = (meters) => (start) => {
610
+ const signature = Option.getOrElse(latestAt(start)(meters), () => DEFAULT_METER);
611
+ const full = start + lengthOf(signature);
612
+ return {
613
+ start,
614
+ length: pipe(Array.findFirst(meters, (meter) => meter.tick > start), Option.match({
615
+ onNone: () => full,
616
+ onSome: (meter) => Math.min(meter.tick, full)
617
+ })) - start,
618
+ signature
619
+ };
620
+ };
621
+ const barsOf = (timeline) => Array.unfold({
622
+ start: NONE$9,
623
+ first: true
624
+ }, (cursor) => {
625
+ if (!cursor.first && cursor.start >= timeline.end) return Option.none();
626
+ const span = spanAt(timeline.meters)(cursor.start);
627
+ const bar = {
628
+ start: span.start,
629
+ length: span.length,
630
+ meter: meterText(span.signature)(span.length),
631
+ tempo: tempoStepsOf(timeline.tempos)(span),
632
+ marks: marksOf(timeline.markers)(span)
633
+ };
634
+ return Option.some([bar, {
635
+ start: endOfSpan(span),
636
+ first: false
637
+ }]);
638
+ });
639
+ const bpmText = (microseconds) => {
640
+ const exact = bpmOf(microseconds);
641
+ return `${pipe(Array.range(NONE$9, MAX_DECIMALS), Array.map((decimals) => String(Number(exact.toFixed(decimals)))), Array.findFirst((candidate) => microsecondsOf(Number(candidate)) === microseconds), Option.getOrElse(() => String(exact)))}bpm`;
642
+ };
643
+ // src/entities/timeline/model/control-lines.ts
644
+ const NEXT$7 = 1;
645
+ const valueText = (control) => {
646
+ if (control.controller.kind === "bend") return semitoneText(control.value);
647
+ return String(control.value);
648
+ };
649
+ const headOf$1 = (planned) => ({ controller }) => {
650
+ if (controller.kind === "pressure") return Option.match(controller.midi, {
651
+ onNone: () => `${planned.name}.pressure`,
652
+ onSome: (midi) => `${planned.name}.pressure ${pitchText(midi)}`
653
+ });
654
+ return `${planned.name}.${controllerKeyOf({ controller })}`;
655
+ };
656
+ const cellsOf$1 = (bar) => (controls) => {
657
+ const lead = pipe(Array.head(controls), Option.map((first) => first.tick - bar.start), Option.toArray, Array.flatMap(restsOf));
658
+ const steps = pipe(controls, Array.map((control, index) => ({
659
+ head: valueText(control),
660
+ attributes: [],
661
+ length: pipe(Array.get(controls, index + NEXT$7), Option.match({
662
+ onNone: () => endOfSpan(bar),
663
+ onSome: (next) => next.tick
664
+ })) - control.tick
665
+ })));
666
+ return [...lead, ...steps];
667
+ };
668
+ const controlLinesOf = (bar) => (planned) => pipe(planned.controls, Array.filter((control) => control.tick >= bar.start && control.tick < endOfSpan(bar)), Array.groupBy((control) => controllerKeyOf(control)), Record.values, Array.map((controls) => pipe(Array.head(controls), Option.map((first) => `${headOf$1(planned)(first)}: ${cellsText(cellsOf$1(bar)(controls))}`))), Array.getSomes);
669
+ // src/entities/timeline/model/mix-lines.ts
670
+ const DECIMALS = 1;
671
+ const PERCENT = 100;
672
+ const NONE$8 = 0;
673
+ const NEXT$6 = 1;
674
+ const amountText = (value, unit) => {
675
+ const text = Number(value.toFixed(DECIMALS));
676
+ if (text > NONE$8) return `+${String(text)}${unit}`;
677
+ return `${String(text)}${unit}`;
678
+ };
679
+ const UNITS = {
680
+ volume: (decibels) => amountText(decibels, "dB"),
681
+ pan: (pan) => amountText(pan * PERCENT, "%")
682
+ };
683
+ const levelWords = (level) => [
684
+ ...pipe(Option.some(level.decibels), Option.filter((decibels) => UNITS.volume(decibels) !== UNITS.volume(NONE$8)), Option.map((decibels) => `volume ${UNITS.volume(decibels)}`), Option.toArray),
685
+ ...pipe(Option.some(level.pan), Option.filter((pan) => UNITS.pan(pan) !== UNITS.pan(NONE$8)), Option.map((pan) => `pan ${UNITS.pan(pan)}`), Option.toArray),
686
+ ...pipe(Option.some("mute"), Option.filter(() => level.muted), Option.toArray)
687
+ ];
688
+ const trackMixWords = ({ mix, buses }) => [...levelWords(mix.level), ...pipe(mix.sends, Array.filter((send) => send.amount > NONE$8), Array.flatMap((send) => pipe(Array.get(buses, send.bus), Option.map((bus) => `send ${bus.name} ${amountText(send.amount * PERCENT, "%")}`), Option.toArray)))];
689
+ const busLineOf = (bus) => Array.join([
690
+ "bus",
691
+ bus.name,
692
+ ...levelWords(bus.level)
693
+ ], " ");
694
+ const valueAt$1 = (points) => (tick) => {
695
+ const before = pipe(points, Array.filter((point) => point.tick <= tick), Array.last);
696
+ const after = pipe(points, Array.findFirst((point) => point.tick > tick));
697
+ return Option.match(before, {
698
+ onNone: () => Option.match(after, {
699
+ onNone: () => NONE$8,
700
+ onSome: (point) => point.value
701
+ }),
702
+ onSome: (left) => Option.match(after, {
703
+ onNone: () => left.value,
704
+ onSome: (right) => left.value + (right.value - left.value) * (tick - left.tick) / (right.tick - left.tick)
705
+ })
706
+ });
707
+ };
708
+ const rampOf = (bar, name) => (envelope) => {
709
+ const at = valueAt$1(envelope.points);
710
+ const unit = UNITS[envelope.parameter];
711
+ const from = unit(at(bar.start));
712
+ const to = unit(at(endOfSpan(bar)));
713
+ return pipe(Option.some(`automate ${name}.${envelope.parameter} ${from} -> ${to} over 1bar`), Option.filter(() => from !== to));
714
+ };
715
+ const automationLinesOf = (bar) => (planned) => pipe(planned.mix.envelopes, Array.filter((envelope) => Array.length(envelope.points) > NEXT$6), Array.map(rampOf(bar, planned.name)), Array.getSomes);
716
+ // src/entities/timeline/model/voice-lines.ts
717
+ const FULL = 127;
718
+ const DEFAULT_RELEASE$2 = 64;
719
+ const SINGLE$2 = 1;
720
+ const touches = (bar) => (group) => {
721
+ if (group.end === group.start) return group.start >= bar.start && group.start < endOfSpan(bar);
722
+ return group.start < endOfSpan(bar) && group.end > bar.start;
723
+ };
724
+ const segmentOf$1 = (bar) => (group) => ({
725
+ group,
726
+ start: Math.max(group.start, bar.start),
727
+ end: Math.min(group.end, endOfSpan(bar))
728
+ });
729
+ const pitchesText = (midis) => {
730
+ if (midis.length === SINGLE$2) return Array.join(pipe(midis, Array.map(pitchText)), "");
731
+ return `[${Array.join(pipe(midis, Array.map(pitchText)), " ")}]`;
732
+ };
733
+ const headOf = (voices) => (group) => Option.match(voices, {
734
+ onNone: () => pitchesText(group.midis),
735
+ onSome: (map) => pipe(Array.head(group.midis), Option.flatMap((midi) => Option.fromNullishOr(map.get(midi))), Option.getOrElse(() => ""))
736
+ });
737
+ const when = (condition, text) => {
738
+ if (condition) return [text];
739
+ return [];
740
+ };
741
+ const attributesOf = ({ group, start, end }) => {
742
+ const last = end === group.end;
743
+ return [
744
+ ...when(group.velocity !== FULL, `vel ${shareText(group.velocity)}`),
745
+ ...when(last && group.release !== DEFAULT_RELEASE$2, `off ${shareText(group.release)}`),
746
+ ...when(!last, "tie"),
747
+ ...pipe(group.lyric, Option.filter(() => start === group.start), Option.map((text) => `lyric ${quoted(text)}`), Option.toArray)
748
+ ];
749
+ };
750
+ const cellsOf = (segments, bar, head) => {
751
+ const placed = Array.reduce(segments, {
752
+ cells: [],
753
+ cursor: bar.start
754
+ }, ({ cells, cursor }, segment) => ({
755
+ cells: [
756
+ ...cells,
757
+ ...restsOf(segment.start - cursor),
758
+ {
759
+ head: head(segment.group),
760
+ attributes: attributesOf(segment),
761
+ length: segment.end - segment.start
762
+ }
763
+ ],
764
+ cursor: segment.end
765
+ }));
766
+ return [...placed.cells, ...restsOf(endOfSpan(bar) - placed.cursor)];
767
+ };
768
+ const lineTextOf = (planned, voices, bar) => (line) => {
769
+ const segments = pipe(line, Array.filter(touches(bar)), Array.map(segmentOf$1(bar)));
770
+ return pipe(Array.head(segments), Option.map((first) => ({
771
+ text: `${planned.name}: ${cellsText(cellsOf(segments, bar, headOf(voices)))}`,
772
+ continues: first.start > first.group.start
773
+ })));
774
+ };
775
+ const continuedFirst = Order.mapInput(Order.Boolean, (voice) => !voice.continues);
776
+ const voiceLinesOf = ({ plan, bar }) => (planned) => {
777
+ const voices = pipe(Option.some(plan.drumVoices), Option.filter(() => planned.source.kind === "kit"));
778
+ const texts = pipe(planned.lines, Array.map(lineTextOf(planned, voices, bar)), Array.getSomes);
779
+ return pipe(Array.sort(texts, continuedFirst), Array.map((voice) => voice.text));
780
+ };
781
+ // src/entities/timeline/model/write.ts
782
+ const SINGLE$1 = 1;
783
+ const INDENT$1 = " ";
784
+ const START$1 = {
785
+ meter: Option.none(),
786
+ microseconds: Option.none()
787
+ };
788
+ const isRamp = (step) => Option.isSome(step.target);
789
+ const stepText = (step) => {
790
+ const ramp = Option.match(step.target, {
791
+ onNone: () => "",
792
+ onSome: (target) => ` -> ${bpmText(target)}`
793
+ });
794
+ return `${bpmText(step.microseconds)}${ramp} ${fractionOf(step.length)}`;
795
+ };
796
+ const isSteady = (bar) => bar.tempo.length <= SINGLE$1 && !pipe(bar.tempo, Array.some(isRamp));
797
+ const tempoLineOf = (bar) => {
798
+ if (isSteady(bar)) return Option.none();
799
+ const steps = pipe(bar.tempo, Array.map(stepText));
800
+ return Option.some(`tempo: ${Array.join(steps, ", ")}`);
801
+ };
802
+ const differs = (previous) => (current) => Option.match(previous, {
803
+ onNone: () => true,
804
+ onSome: (value) => value !== current
805
+ });
806
+ const headerTempoOf = (previous) => (bar) => pipe(Array.head(bar.tempo), Option.filter(() => isSteady(bar)), Option.map((step) => step.microseconds), Option.filter(differs(previous.microseconds)), Option.map((microseconds) => `tempo ${bpmText(microseconds)}`), Option.toArray);
807
+ const barHeadOf = (previous) => (bar) => {
808
+ const meter = pipe(Option.some(bar.meter), Option.filter(differs(previous.meter)), Option.map((current) => `meter ${current}`), Option.toArray);
809
+ const mark = pipe(Option.some(bar.marks), Option.filter(Array.isReadonlyArrayNonEmpty), Option.map((marks) => `mark ${quoted(Array.join(marks, " / "))}`), Option.toArray);
810
+ return Array.join([
811
+ "bar",
812
+ ...meter,
813
+ ...headerTempoOf(previous)(bar),
814
+ ...mark,
815
+ "{"
816
+ ], " ");
817
+ };
818
+ const barBodyOf = (plan) => (bar) => [...Option.toArray(tempoLineOf(bar)), ...pipe(plan.parts, Array.flatMap((planned) => [
819
+ ...voiceLinesOf({
820
+ plan,
821
+ bar
822
+ })(planned),
823
+ ...controlLinesOf(bar)(planned),
824
+ ...automationLinesOf(bar)(planned)
825
+ ]))];
826
+ const afterBar = (bar) => ({
827
+ meter: Option.some(bar.meter),
828
+ microseconds: pipe(Array.last(bar.tempo), Option.map((step) => Option.getOrElse(step.target, () => step.microseconds)))
829
+ });
830
+ const walkStep = (plan) => ({ lines, previous }, bar) => ({
831
+ lines: [
832
+ ...lines,
833
+ "",
834
+ barHeadOf(previous)(bar),
835
+ ...pipe(barBodyOf(plan)(bar), Array.map((line) => `${INDENT$1}${line}`)),
836
+ "}"
837
+ ],
838
+ previous: afterBar(bar)
839
+ });
840
+ const instrumentLinesOf = (plan) => pipe(Array.fromIterable(plan.instruments), Array.map(([program, name]) => `instrument ${name} plugin gm program ${String(program)}`));
841
+ const kitLinesOf = (plan) => {
842
+ if (plan.drumVoices.size < SINGLE$1) return [];
843
+ return [
844
+ "kit gm-drums {",
845
+ ...pipe(Array.fromIterable(plan.drumVoices.values()), Array.map((name) => `${INDENT$1}${name} ${quoted(`gm-drums/${name}.flac`)}`)),
846
+ "}"
847
+ ];
848
+ };
849
+ const sourceWordsOf = (planned) => {
850
+ if (planned.source.kind === "kit") return ["kit gm-drums role drums"];
851
+ return [`instrument ${planned.source.instrument}`];
852
+ };
853
+ const trackLineOf = (plan) => (planned) => Array.join([
854
+ "track",
855
+ planned.name,
856
+ ...sourceWordsOf(planned),
857
+ ...trackMixWords({
858
+ mix: planned.mix,
859
+ buses: plan.buses
860
+ })
861
+ ], " ");
862
+ const headerOf = ({ plan, title }) => [
863
+ `song ${quoted(title)}`,
864
+ "",
865
+ "plugin gm from \"./gm.ts\" { program: number = 0 }",
866
+ "",
867
+ ...instrumentLinesOf(plan),
868
+ ...kitLinesOf(plan),
869
+ "",
870
+ ...pipe(plan.buses, Array.map(busLineOf)),
871
+ ...pipe(plan.parts, Array.map(trackLineOf(plan)))
872
+ ];
873
+ const writeFumx = ({ timeline, title }) => {
874
+ const plan = planOf(timeline);
875
+ const bars = barsOf(timeline);
876
+ const walked = Array.reduce(bars, {
877
+ lines: headerOf({
878
+ plan,
879
+ title
880
+ }),
881
+ previous: START$1
882
+ }, walkStep(plan));
883
+ return {
884
+ text: `${Array.join(walked.lines, "\n")}\n`,
885
+ plan,
886
+ bars
887
+ };
888
+ };
889
+ // src/features/convert-als/model/live-set.ts
890
+ const taggedError$7 = Schema.TaggedError;
891
+ var UnreadableAls = class extends taggedError$7()("UnreadableAls", { message: Schema.String }, { identifier: "UnreadableAls" }) {};
892
+ const REPEATED = /* @__PURE__ */ new Set([
893
+ "MidiTrack",
894
+ "AudioTrack",
895
+ "GroupTrack",
896
+ "ReturnTrack",
897
+ "MidiClip",
898
+ "AudioClip",
899
+ "KeyTrack",
900
+ "MidiNoteEvent",
901
+ "Locator",
902
+ "AutomationEnvelope",
903
+ "FloatEvent",
904
+ "EnumEvent",
905
+ "BoolEvent",
906
+ "TrackSendHolder"
907
+ ]);
908
+ const ATTRIBUTES = "@";
909
+ const parser = new XMLParser({
910
+ ignoreAttributes: false,
911
+ attributeNamePrefix: "",
912
+ attributesGroupName: ATTRIBUTES,
913
+ parseTagValue: false,
914
+ parseAttributeValue: false,
915
+ jPath: false,
916
+ isArray: (name) => REPEATED.has(name)
917
+ });
918
+ const Num = Schema.Struct({ Value: Schema.FiniteFromString });
919
+ const Text = Schema.Struct({ Value: Schema.String });
920
+ const Flag = Schema.Struct({ Value: Schema.Literals(["true", "false"]) });
921
+ const EventSchema = Schema.Struct({
922
+ Time: Schema.FiniteFromString,
923
+ Value: Schema.String
924
+ });
925
+ const EventsSchema = Schema.Struct({
926
+ FloatEvent: EventSchema.pipe(Schema.Array, Schema.optionalKey),
927
+ EnumEvent: EventSchema.pipe(Schema.Array, Schema.optionalKey),
928
+ BoolEvent: EventSchema.pipe(Schema.Array, Schema.optionalKey)
929
+ });
930
+ const EnvelopeSchema = Schema.Struct({
931
+ EnvelopeTarget: Schema.Struct({ PointeeId: Num }),
932
+ Automation: Schema.Struct({ Events: EventsSchema })
933
+ });
934
+ const EnvelopeListSchema = Schema.Struct({ AutomationEnvelope: EnvelopeSchema.pipe(Schema.Array, Schema.optionalKey) });
935
+ const EnvelopesSchema = Schema.Struct({ Envelopes: EnvelopeListSchema });
936
+ const TargetSchema = Schema.Struct({ Id: Schema.FiniteFromString });
937
+ const ParameterSchema = Schema.Struct({
938
+ Manual: Schema.optionalKey(Num),
939
+ AutomationTarget: Schema.optionalKey(TargetSchema),
940
+ ArrangerAutomation: Schema.optionalKey(Schema.Struct({ Events: EventsSchema }))
941
+ });
942
+ const NoteSchema = Schema.Struct({
943
+ Time: Schema.FiniteFromString,
944
+ Duration: Schema.FiniteFromString,
945
+ Velocity: Schema.FiniteFromString,
946
+ OffVelocity: Schema.optionalKey(Schema.FiniteFromString),
947
+ IsEnabled: Schema.optionalKey(Schema.Literals(["true", "false"])),
948
+ Probability: Schema.optionalKey(Schema.FiniteFromString),
949
+ VelocityDeviation: Schema.optionalKey(Schema.FiniteFromString)
950
+ });
951
+ const NoteListSchema = Schema.Struct({ MidiNoteEvent: NoteSchema.pipe(Schema.Array, Schema.optionalKey) });
952
+ const KeyTrackSchema = Schema.Struct({
953
+ Notes: NoteListSchema,
954
+ MidiKey: Num
955
+ });
956
+ const LoopSchema = Schema.Struct({
957
+ LoopStart: Num,
958
+ LoopEnd: Num,
959
+ StartRelative: Num,
960
+ LoopOn: Flag
961
+ });
962
+ const KeyTracksSchema = Schema.Struct({ KeyTrack: KeyTrackSchema.pipe(Schema.Array, Schema.optionalKey) });
963
+ const ClipSchema = Schema.Struct({
964
+ CurrentStart: Num,
965
+ CurrentEnd: Num,
966
+ Loop: LoopSchema,
967
+ Disabled: Schema.optionalKey(Flag),
968
+ Notes: Schema.Struct({ KeyTracks: KeyTracksSchema })
969
+ });
970
+ const NameSchema = Schema.Struct({
971
+ EffectiveName: Schema.optionalKey(Text),
972
+ UserName: Schema.optionalKey(Text)
973
+ });
974
+ const DrumsSchema = Schema.Struct({ DrumGroupDevice: Schema.optionalKey(Schema.Unknown) });
975
+ const DevicesSchema = Schema.Struct({ Devices: Schema.optionalKey(DrumsSchema) });
976
+ const ClipEventsSchema = Schema.Struct({ MidiClip: ClipSchema.pipe(Schema.Array, Schema.optionalKey) });
977
+ const ArrangementSchema = Schema.Struct({ ArrangerAutomation: Schema.Struct({ Events: ClipEventsSchema }) });
978
+ const SendHolderSchema = Schema.Struct({ Send: ParameterSchema });
979
+ const SendsSchema = Schema.Struct({ TrackSendHolder: SendHolderSchema.pipe(Schema.Array, Schema.optionalKey) });
980
+ const SpeakerSchema = Schema.Struct({ Manual: Schema.optionalKey(Flag) });
981
+ const TrackMixerSchema = Schema.Struct({
982
+ Volume: ParameterSchema,
983
+ Pan: ParameterSchema,
984
+ Speaker: Schema.optionalKey(SpeakerSchema),
985
+ Sends: Schema.optionalKey(SendsSchema)
986
+ });
987
+ const TrackChainSchema = Schema.Struct({
988
+ DeviceChain: Schema.optionalKey(DevicesSchema),
989
+ Mixer: Schema.optionalKey(TrackMixerSchema),
990
+ MainSequencer: Schema.Struct({ ClipTimeable: ArrangementSchema })
991
+ });
992
+ const MidiTrackSchema = Schema.Struct({
993
+ Id: Schema.String,
994
+ Name: NameSchema,
995
+ AutomationEnvelopes: Schema.optionalKey(EnvelopesSchema),
996
+ DeviceChain: TrackChainSchema
997
+ });
998
+ const ReturnTrackSchema = Schema.Struct({
999
+ Name: NameSchema,
1000
+ DeviceChain: Schema.Struct({ Mixer: Schema.optionalKey(TrackMixerSchema) })
1001
+ });
1002
+ const MixerSchema = Schema.Struct({
1003
+ Tempo: ParameterSchema,
1004
+ TimeSignature: ParameterSchema
1005
+ });
1006
+ const MasterSchema = Schema.Struct({
1007
+ AutomationEnvelopes: Schema.optionalKey(EnvelopesSchema),
1008
+ DeviceChain: Schema.optionalKey(Schema.Struct({ Mixer: MixerSchema })),
1009
+ MasterChain: Schema.optionalKey(Schema.Struct({ Mixer: MixerSchema }))
1010
+ });
1011
+ const LocatorSchema = Schema.Struct({
1012
+ Time: Num,
1013
+ Name: Text
1014
+ });
1015
+ const TracksSchema = Schema.Struct({
1016
+ MidiTrack: MidiTrackSchema.pipe(Schema.Array, Schema.optionalKey),
1017
+ ReturnTrack: ReturnTrackSchema.pipe(Schema.Array, Schema.optionalKey)
1018
+ });
1019
+ const LocatorListSchema = Schema.Struct({ Locator: LocatorSchema.pipe(Schema.Array, Schema.optionalKey) });
1020
+ const LiveSetSchema = Schema.Struct({
1021
+ Tracks: TracksSchema,
1022
+ MasterTrack: Schema.optionalKey(MasterSchema),
1023
+ MainTrack: Schema.optionalKey(MasterSchema),
1024
+ Locators: Schema.optionalKey(Schema.Struct({ Locators: LocatorListSchema }))
1025
+ });
1026
+ const DocumentSchema = Schema.Struct({ Ableton: Schema.Struct({
1027
+ MajorVersion: Schema.String,
1028
+ MinorVersion: Schema.String,
1029
+ Creator: Schema.optionalKey(Schema.String),
1030
+ LiveSet: LiveSetSchema
1031
+ }) });
1032
+ const decodeDocument = Schema.decodeUnknownEffect(DocumentSchema);
1033
+ const isElement = Schema.is(Schema.Record(Schema.String, Schema.Unknown));
1034
+ const isAttributes = Schema.is(Schema.Record(Schema.String, Schema.String));
1035
+ const flattened = (node) => {
1036
+ if (node === "") return {};
1037
+ if (Array.isArray(node)) return pipe(node, Array.map((child) => flattened(child)));
1038
+ if (isElement(node)) {
1039
+ const { [ATTRIBUTES]: attributes, ...children } = node;
1040
+ const own = pipe(Option.liftPredicate(attributes, isAttributes), Option.getOrElse(() => ({})));
1041
+ return {
1042
+ ...pipe(children, Record.map((child) => flattened(child))),
1043
+ ...own
1044
+ };
1045
+ }
1046
+ return node;
1047
+ };
1048
+ const gunzip = (bytes) => Effect.tryPromise({
1049
+ try: () => new Response(new Blob([Uint8Array.from(bytes)]).stream().pipeThrough(new DecompressionStream("gzip"))).text(),
1050
+ catch: () => UnreadableAls.make({ message: "The file is not a gzipped Live Set (.als)" })
1051
+ });
1052
+ const readAlsDocument = Effect.fn("readAlsDocument")(function* read(bytes) {
1053
+ const xml = yield* gunzip(bytes);
1054
+ const parsed = yield* Effect.try({
1055
+ try: () => flattened(parser.parse(xml)),
1056
+ catch: (cause) => UnreadableAls.make({ message: `Not XML: ${String(cause)}` })
1057
+ });
1058
+ return yield* decodeDocument(parsed).pipe(Effect.mapError((issue) => UnreadableAls.make({ message: `Not a Live Set this converter reads: ${String(issue)}` })));
1059
+ });
1060
+ // src/features/convert-als/model/clips.ts
1061
+ const NONE$7 = 0;
1062
+ const DEFAULT_RELEASE$1 = 64;
1063
+ const modulo = (value, size) => (value % size + size) % size;
1064
+ const passesOf = (clip) => {
1065
+ const start = clip.CurrentStart.Value;
1066
+ const length = clip.CurrentEnd.Value - start;
1067
+ const loopStart = clip.Loop.LoopStart.Value;
1068
+ const loopLength = clip.Loop.LoopEnd.Value - loopStart;
1069
+ if (clip.Loop.LoopOn.Value === "false" || loopLength <= NONE$7) return [{
1070
+ at: start,
1071
+ from: loopStart,
1072
+ to: loopStart + length
1073
+ }];
1074
+ const first = loopStart + modulo(clip.Loop.StartRelative.Value, loopLength);
1075
+ const walk = (elapsed, from, passes) => {
1076
+ if (elapsed >= length) return passes;
1077
+ const span = Math.min(clip.Loop.LoopEnd.Value - from, length - elapsed);
1078
+ return walk(elapsed + span, loopStart, [...passes, {
1079
+ at: start + elapsed,
1080
+ from,
1081
+ to: from + span
1082
+ }]);
1083
+ };
1084
+ return walk(NONE$7, first, []);
1085
+ };
1086
+ const releaseOf$1 = (offVelocity) => pipe(Option.fromUndefinedOr(offVelocity), Option.filter((off) => off !== NONE$7), Option.match({
1087
+ onNone: () => DEFAULT_RELEASE$1,
1088
+ onSome: Math.round
1089
+ }));
1090
+ const sourceNotesOf = (clip) => pipe(clip.Notes.KeyTracks.KeyTrack ?? [], Array.flatMap((keyTrack) => pipe(keyTrack.Notes.MidiNoteEvent ?? [], Array.filter((note) => note.IsEnabled !== "false"), Array.map((note) => ({
1091
+ time: note.Time,
1092
+ end: note.Time + note.Duration,
1093
+ midi: keyTrack.MidiKey.Value,
1094
+ velocity: Math.round(note.Velocity),
1095
+ release: releaseOf$1(note.OffVelocity)
1096
+ })))));
1097
+ const inPass = (notes) => (pass) => pipe(notes, Array.filter((note) => note.time >= pass.from && note.time < pass.to), Array.map((note) => ({
1098
+ beat: pass.at + note.time - pass.from,
1099
+ length: Math.min(note.end, pass.to) - note.time,
1100
+ midi: note.midi,
1101
+ velocity: note.velocity,
1102
+ release: note.release
1103
+ })));
1104
+ const byStartThenPitch = Order.combine(Order.mapInput(Order.Number, (note) => note.beat), Order.mapInput(Order.Number, (note) => note.midi));
1105
+ const isDisabled = (clip) => Option.exists(Option.fromUndefinedOr(clip.Disabled), (flag) => flag.Value === "true");
1106
+ const notesOfClip = (clip) => {
1107
+ if (isDisabled(clip)) return [];
1108
+ const notes = sourceNotesOf(clip);
1109
+ return pipe(passesOf(clip), Array.flatMap(inPass(notes)), Array.sortBy(byStartThenPitch));
1110
+ };
1111
+ const masterOf = (liveSet) => Option.orElse(Option.fromUndefinedOr(liveSet.MasterTrack), () => Option.fromUndefinedOr(liveSet.MainTrack));
1112
+ const mixerOf = (master) => pipe(Option.fromUndefinedOr(master.DeviceChain), Option.orElse(() => Option.fromUndefinedOr(master.MasterChain)), Option.map((chain) => chain.Mixer));
1113
+ const eventsOf = (events) => [
1114
+ ...events.FloatEvent ?? [],
1115
+ ...events.EnumEvent ?? [],
1116
+ ...events.BoolEvent ?? []
1117
+ ];
1118
+ const automationEnvelopesOf = (owner) => pipe(Option.fromUndefinedOr(owner.AutomationEnvelopes), Option.flatMap((envelopes) => Option.fromUndefinedOr(envelopes.Envelopes.AutomationEnvelope)), Option.getOrElse(() => []));
1119
+ const byTime = Order.mapInput(Order.Number, (event) => event.Time);
1120
+ const envelopeOf = (owner) => (parameter) => {
1121
+ const inline = pipe(Option.fromUndefinedOr(parameter.ArrangerAutomation), Option.map((automation) => automation.Events));
1122
+ const pointed = pipe(Option.fromUndefinedOr(parameter.AutomationTarget), Option.flatMap((target) => pipe(automationEnvelopesOf(owner), Array.findFirst((envelope) => envelope.EnvelopeTarget.PointeeId.Value === target.Id))), Option.map((envelope) => envelope.Automation.Events));
1123
+ return pipe(Option.orElse(pointed, () => inline), Option.map(eventsOf), Option.getOrElse(() => []), Array.sortBy(byTime));
1124
+ };
1125
+ const SINGLE = 1;
1126
+ const NEXT$5 = 1;
1127
+ const automationOf = (select) => (liveSet) => pipe(masterOf(liveSet), Option.flatMap((master) => pipe(mixerOf(master), Option.map((mixer) => {
1128
+ const parameter = select(mixer);
1129
+ return {
1130
+ events: envelopeOf(master)(parameter),
1131
+ manual: pipe(Option.fromUndefinedOr(parameter.Manual), Option.map((manual) => manual.Value))
1132
+ };
1133
+ }))));
1134
+ const tempoAutomationOf = automationOf((mixer) => mixer.Tempo);
1135
+ const pointsOf$1 = (events) => pipe(events, Array.map((event) => ({
1136
+ beat: event.Time,
1137
+ value: Number(event.Value)
1138
+ })));
1139
+ const tempoFrom = (resolve) => (liveSet) => pipe(tempoAutomationOf(liveSet), Option.map(resolve), Option.getOrElse(() => []));
1140
+ const tempoEnvelopeOf = tempoFrom(({ events }) => pointsOf$1(events));
1141
+ const manualPointsOf = tempoFrom(({ manual }) => pipe(manual, Option.map((value) => [{
1142
+ beat: 0,
1143
+ value
1144
+ }]), Option.getOrElse(() => [])));
1145
+ const tempoPointsOf = (liveSet) => {
1146
+ const envelope = tempoEnvelopeOf(liveSet);
1147
+ const manual = manualPointsOf(liveSet);
1148
+ if (envelope.length > SINGLE || !Array.isReadonlyArrayNonEmpty(manual)) return envelope;
1149
+ return manual;
1150
+ };
1151
+ const valueAt = (from, to) => (beat) => {
1152
+ if (to.beat === from.beat) return to.value;
1153
+ return from.value + (to.value - from.value) * (beat - from.beat) / (to.beat - from.beat);
1154
+ };
1155
+ const segmentOf = (from, next) => {
1156
+ const start = Math.max(from.beat, 0);
1157
+ return Option.match(next, {
1158
+ onNone: () => ({
1159
+ beat: start,
1160
+ bpm: from.value,
1161
+ target: Option.none()
1162
+ }),
1163
+ onSome: (to) => {
1164
+ const bpm = valueAt(from, to)(start);
1165
+ if (to.beat <= start || to.value === bpm) return {
1166
+ beat: start,
1167
+ bpm,
1168
+ target: Option.none()
1169
+ };
1170
+ return {
1171
+ beat: start,
1172
+ bpm,
1173
+ target: Option.some(to.value)
1174
+ };
1175
+ }
1176
+ });
1177
+ };
1178
+ const keptWith = (kept, segment) => {
1179
+ const earlier = pipe(Chunk.last(kept), Option.filter((last) => last.beat === segment.beat), Option.match({
1180
+ onNone: () => kept,
1181
+ onSome: () => Chunk.dropRight(kept, SINGLE)
1182
+ }));
1183
+ if (pipe(Chunk.last(earlier), Option.exists((last) => Option.isNone(last.target) && Option.isNone(segment.target) && last.bpm === segment.bpm))) return earlier;
1184
+ return Chunk.append(earlier, segment);
1185
+ };
1186
+ const withoutRepeats = (segments) => {
1187
+ let kept = Chunk.empty();
1188
+ for (const segment of segments) kept = keptWith(kept, segment);
1189
+ return Chunk.toReadonlyArray(kept);
1190
+ };
1191
+ const tempoSegmentsOf = (points) => pipe(points, Array.map((point, index) => ({
1192
+ point,
1193
+ next: Array.get(points, index + NEXT$5)
1194
+ })), Array.filter(({ next }) => Option.match(next, {
1195
+ onNone: () => true,
1196
+ onSome: (to) => to.beat > 0
1197
+ })), Array.map(({ point, next }) => segmentOf(point, next)), withoutRepeats);
1198
+ const meterOfId = (beat, id) => pipe(Option.fromNullishOr(decodeTimeSignatureId(id)), Option.map((signature) => ({
1199
+ beat: Math.max(beat, 0),
1200
+ numerator: signature.num,
1201
+ denominator: signature.den
1202
+ })));
1203
+ const metersOf = (liveSet) => pipe(automationOf((mixer) => mixer.TimeSignature)(liveSet), Option.map(({ events, manual }) => {
1204
+ if (events.length > SINGLE || Option.isNone(manual)) return pipe(events, Array.map((event) => meterOfId(event.Time, Number(event.Value))), Array.getSomes, Array.reverse, Array.dedupeAdjacentWith((later, earlier) => later.beat === earlier.beat), Array.reverse);
1205
+ return Option.toArray(meterOfId(0, manual.value));
1206
+ }), Option.getOrElse(() => []));
1207
+ const byBeat = Order.mapInput(Order.Number, (locator) => locator.beat);
1208
+ const locatorsOf = (liveSet) => pipe(Option.fromUndefinedOr(liveSet.Locators), Option.flatMap((locators) => Option.fromUndefinedOr(locators.Locators.Locator)), Option.getOrElse(() => []), Array.map((locator) => ({
1209
+ beat: locator.Time.Value,
1210
+ name: locator.Name.Value
1211
+ })), Array.sortBy(byBeat));
1212
+ // src/features/convert-als/model/ticks.ts
1213
+ const TICKS_PER_BEAT = TICKS_PER_WHOLE / 4;
1214
+ const tickOf = (beat) => {
1215
+ const exact = beat * TICKS_PER_BEAT;
1216
+ return {
1217
+ tick: Math.round(exact),
1218
+ exact: Number.isInteger(exact)
1219
+ };
1220
+ };
1221
+ // src/features/convert-als/model/mix.ts
1222
+ const DECIBELS_PER_DECADE = 20;
1223
+ const SILENT_DECIBELS = -70;
1224
+ const AUDIBLE_SEND = .001;
1225
+ const NONE$6 = 0;
1226
+ const NEXT$4 = 1;
1227
+ const SILENT = 10 ** (SILENT_DECIBELS / DECIBELS_PER_DECADE);
1228
+ const decibelsOf = (gain) => DECIBELS_PER_DECADE * Math.log10(Math.max(gain, SILENT));
1229
+ const [VOLUME, PAN] = MIXER_PARAMETERS;
1230
+ const VALUES = {
1231
+ volume: decibelsOf,
1232
+ pan: (pan) => pan
1233
+ };
1234
+ const RESTING = {
1235
+ volume: NONE$6,
1236
+ pan: NONE$6
1237
+ };
1238
+ const pointsOf = ({ owner, parameter }) => (control) => pipe(envelopeOf(owner)(control), Array.map((event) => ({
1239
+ tick: tickOf(Math.max(event.Time, 0)).tick,
1240
+ value: VALUES[parameter](Number(event.Value))
1241
+ })), Array.filter((point) => Number.isFinite(point.value)));
1242
+ const startOf = (owned) => (control) => pipe(pointsOf(owned)(control), Array.head, Option.map((point) => point.value), Option.orElse(() => pipe(Option.fromUndefinedOr(control.Manual), Option.map((manual) => VALUES[owned.parameter](manual.Value)))), Option.getOrElse(() => RESTING[owned.parameter]));
1243
+ const levelOf = (owner) => (mixer) => ({
1244
+ decibels: startOf({
1245
+ owner,
1246
+ parameter: VOLUME
1247
+ })(mixer.Volume),
1248
+ pan: startOf({
1249
+ owner,
1250
+ parameter: PAN
1251
+ })(mixer.Pan),
1252
+ muted: pipe(Option.fromUndefinedOr(mixer.Speaker), Option.flatMap((speaker) => Option.fromUndefinedOr(speaker.Manual)), Option.exists((manual) => manual.Value === "false"))
1253
+ });
1254
+ const sendsOf = (mixer) => pipe(Option.fromUndefinedOr(mixer.Sends), Option.flatMap((sends) => Option.fromUndefinedOr(sends.TrackSendHolder)), Option.getOrElse(() => []), Array.map((holder, bus) => ({
1255
+ bus,
1256
+ amount: pipe(Option.fromUndefinedOr(holder.Send.Manual), Option.match({
1257
+ onNone: () => NONE$6,
1258
+ onSome: (manual) => manual.Value
1259
+ }))
1260
+ })), Array.filter((send) => send.amount > AUDIBLE_SEND));
1261
+ const envelopesOf = (owner) => (mixer) => pipe([{
1262
+ parameter: "volume",
1263
+ control: mixer.Volume
1264
+ }, {
1265
+ parameter: "pan",
1266
+ control: mixer.Pan
1267
+ }], Array.map(({ parameter, control }) => ({
1268
+ parameter,
1269
+ points: pointsOf({
1270
+ owner,
1271
+ parameter
1272
+ })(control)
1273
+ })), Array.filter((envelope) => envelope.points.length > NEXT$4));
1274
+ const trackMixOf = (track) => pipe(Option.fromUndefinedOr(track.DeviceChain.Mixer), Option.map((mixer) => ({
1275
+ level: levelOf(track)(mixer),
1276
+ sends: sendsOf(mixer),
1277
+ envelopes: envelopesOf(track)(mixer)
1278
+ })));
1279
+ const NO_ENVELOPES = {};
1280
+ const busOf = (nameOf) => (track) => ({
1281
+ name: nameOf(track.Name),
1282
+ level: pipe(Option.fromUndefinedOr(track.DeviceChain.Mixer), Option.match({
1283
+ onNone: () => ({
1284
+ decibels: NONE$6,
1285
+ pan: NONE$6,
1286
+ muted: false
1287
+ }),
1288
+ onSome: levelOf(NO_ENVELOPES)
1289
+ }))
1290
+ });
1291
+ const mixOf = (nameOf) => (liveSet) => ({
1292
+ tracks: new Map(pipe(liveSet.Tracks.MidiTrack ?? [], Array.flatMap((track, index) => pipe(trackMixOf(track), Option.map((mix) => [index, mix]), Option.toArray)))),
1293
+ buses: pipe(liveSet.Tracks.ReturnTrack ?? [], Array.map(busOf(nameOf)))
1294
+ });
1295
+ // src/features/convert-als/model/timeline.ts
1296
+ const MELODIC_CHANNEL = 0;
1297
+ const DRUM_CHANNEL = 9;
1298
+ const NONE$5 = 0;
1299
+ const NEXT$3 = 1;
1300
+ const nameOf = (label) => pipe([label.EffectiveName, label.UserName], Array.map(Option.fromUndefinedOr), Array.getSomes, Array.map((name) => name.Value), Array.findFirst((name) => name !== ""));
1301
+ const isDrumRack = (track) => pipe(Option.fromUndefinedOr(track.DeviceChain.DeviceChain), Option.flatMap((chain) => Option.fromUndefinedOr(chain.Devices)), Option.flatMap((devices) => Option.fromUndefinedOr(devices.DrumGroupDevice)), Option.isSome);
1302
+ const trackNotesOf = (track) => {
1303
+ const played = pipe(track.DeviceChain.MainSequencer.ClipTimeable.ArrangerAutomation.Events.MidiClip ?? [], Array.flatMap(notesOfClip));
1304
+ const placed = pipe(played, Array.map((note) => ({
1305
+ note,
1306
+ start: tickOf(note.beat),
1307
+ end: tickOf(note.beat + note.length)
1308
+ })));
1309
+ return {
1310
+ notes: sortedNotes(pipe(placed, Array.map(({ note, start, end }) => ({
1311
+ tick: start.tick,
1312
+ end: end.tick,
1313
+ midi: note.midi,
1314
+ velocity: note.velocity,
1315
+ release: note.release
1316
+ })))),
1317
+ offGrid: Array.countBy(placed, ({ start, end }) => !start.exact || !end.exact)
1318
+ };
1319
+ };
1320
+ const partOf = (track, index) => {
1321
+ const read = trackNotesOf(track);
1322
+ return {
1323
+ part: {
1324
+ track: index,
1325
+ channel: Boolean.match(isDrumRack(track), {
1326
+ onFalse: () => MELODIC_CHANNEL,
1327
+ onTrue: () => DRUM_CHANNEL
1328
+ }),
1329
+ name: nameOf(track.Name),
1330
+ program: Option.none(),
1331
+ notes: read.notes,
1332
+ controls: [],
1333
+ lyrics: []
1334
+ },
1335
+ offGrid: read.offGrid
1336
+ };
1337
+ };
1338
+ const temposOf = (liveSet) => pipe(tempoSegmentsOf(tempoPointsOf(liveSet)), Array.map((segment) => ({
1339
+ tick: tickOf(segment.beat).tick,
1340
+ microseconds: microsecondsOf(segment.bpm),
1341
+ target: pipe(segment.target, Option.map(microsecondsOf))
1342
+ })));
1343
+ const lastOf = (ticks) => Array.reduce(ticks, NONE$5, (latest, tick) => Math.max(latest, tick));
1344
+ const timelineOf$1 = (liveSet) => {
1345
+ const reads = pipe(liveSet.Tracks.MidiTrack ?? [], Array.map(partOf), Array.filter((read) => Array.isReadonlyArrayNonEmpty(read.part.notes)));
1346
+ const parts = pipe(reads, Array.map((read) => read.part));
1347
+ const markers = sortedByTick(pipe(locatorsOf(liveSet), Array.map((locator) => ({
1348
+ tick: tickOf(locator.beat).tick,
1349
+ text: locator.name
1350
+ }))));
1351
+ const tempos = temposOf(liveSet);
1352
+ const meters = pipe(metersOf(liveSet), Array.map((meter) => ({
1353
+ tick: tickOf(meter.beat).tick,
1354
+ numerator: meter.numerator,
1355
+ denominator: meter.denominator
1356
+ })));
1357
+ const noteEnds = pipe(parts, Array.flatMap((part) => part.notes), Array.map((note) => note.end));
1358
+ const pointEnds = pipe([
1359
+ ...markers,
1360
+ ...tempos,
1361
+ ...meters
1362
+ ], Array.map((point) => point.tick + NEXT$3));
1363
+ return {
1364
+ title: Option.none(),
1365
+ end: lastOf([...noteEnds, ...pointEnds]),
1366
+ offGrid: Array.reduce(reads, NONE$5, (sum, read) => sum + read.offGrid),
1367
+ tempos,
1368
+ meters,
1369
+ markers,
1370
+ parts,
1371
+ mix: mixOf(nameOf)(liveSet)
1372
+ };
1373
+ };
1374
+ // src/features/convert-als/model/convert.ts
1375
+ const alsToFumx = Effect.fn("alsToFumx")(function* convert(input) {
1376
+ const document = yield* readAlsDocument(input.bytes);
1377
+ const timeline = yield* Effect.sync(() => timelineOf$1(document.Ableton.LiveSet)).pipe(Effect.withSpan("timelineOf"));
1378
+ const written = yield* Effect.sync(() => writeFumx({
1379
+ timeline,
1380
+ title: input.title
1381
+ })).pipe(Effect.withSpan("writeFumx"));
1382
+ yield* Effect.annotateCurrentSpan({
1383
+ creator: document.Ableton.Creator ?? "",
1384
+ parts: written.plan.parts.length,
1385
+ bars: written.bars.length
1386
+ });
1387
+ return {
1388
+ ...written,
1389
+ offGrid: timeline.offGrid
1390
+ };
1391
+ });
1392
+ // src/app/round-trip.ts
1393
+ const taggedError$6 = Schema.TaggedError;
1394
+ var InvalidOutput = class extends taggedError$6()("InvalidOutput", {
1395
+ message: Schema.String,
1396
+ text: Schema.String
1397
+ }, { identifier: "InvalidOutput" }) {};
1398
+ const issueText = (issue) => `${String(issue.line)}:${String(issue.column)} ${issue.message}`;
1399
+ const roundTrip = Effect.fn("roundTrip")(function* check(path, fumx) {
1400
+ const read = yield* readSong({
1401
+ path,
1402
+ read: () => Effect.succeed(fumx.text)
1403
+ }).pipe(Effect.withSpan("readSong"));
1404
+ if (read.status === "invalid") return yield* InvalidOutput.make({
1405
+ message: pipe(read.issues, Array.map(issueText), Array.join("\n")),
1406
+ text: fumx.text
1407
+ });
1408
+ const comparison = compareWithSong({
1409
+ plan: fumx.plan,
1410
+ bars: fumx.bars,
1411
+ song: read.song
1412
+ });
1413
+ yield* Effect.annotateCurrentSpan({
1414
+ matches: comparison.matches,
1415
+ notes: comparison.notes.expected
1416
+ });
1417
+ return {
1418
+ text: fumx.text,
1419
+ comparison,
1420
+ adjustments: { offGrid: fumx.offGrid }
1421
+ };
1422
+ });
1423
+ // src/app/als-to-fumx.ts
1424
+ const convertLiveSetFile = Effect.fn("convertLiveSetFile")(function* convert(source) {
1425
+ const fumx = yield* alsToFumx(source);
1426
+ return yield* roundTrip(source.path, fumx);
1427
+ });
1428
+ // src/features/convert-midi/model/channel.ts
1429
+ const NONE$4 = 0;
1430
+ const NEXT$2 = 1;
1431
+ const DEFAULT_RELEASE = 64;
1432
+ const DEFAULT_BEND_RANGE = 2;
1433
+ const CENTS_PER_SEMITONE = 100;
1434
+ const BEND_HALF = 8192;
1435
+ const RPN_MSB = 101;
1436
+ const RPN_LSB = 100;
1437
+ const DATA_MSB = 6;
1438
+ const DATA_LSB = 38;
1439
+ const PITCH_BEND_RPN = 0;
1440
+ const UNSET = 127;
1441
+ const edgeOf$1 = ({ tick, event }) => Match.value(event).pipe(Match.when({ type: "noteOn" }, (on) => Option.some([on.noteNumber, {
1442
+ tick,
1443
+ on: on.velocity > NONE$4,
1444
+ velocity: on.velocity
1445
+ }])), Match.when({ type: "noteOff" }, (off) => Option.some([off.noteNumber, {
1446
+ tick,
1447
+ on: false,
1448
+ velocity: off.velocity
1449
+ }])), Match.orElse(() => Option.none()));
1450
+ const releaseOf = (edge) => {
1451
+ if (edge.velocity === NONE$4) return DEFAULT_RELEASE;
1452
+ return edge.velocity;
1453
+ };
1454
+ const START_PAIRING = {
1455
+ open: [],
1456
+ notes: []
1457
+ };
1458
+ const pairStep = (midi) => (pairing, edge) => {
1459
+ if (edge.on) return {
1460
+ ...pairing,
1461
+ open: [...pairing.open, edge]
1462
+ };
1463
+ return Option.match(Array.head(pairing.open), {
1464
+ onNone: () => pairing,
1465
+ onSome: (started) => ({
1466
+ open: Array.drop(pairing.open, NEXT$2),
1467
+ notes: [...pairing.notes, {
1468
+ tick: started.tick,
1469
+ end: edge.tick,
1470
+ midi,
1471
+ velocity: started.velocity,
1472
+ release: releaseOf(edge)
1473
+ }]
1474
+ })
1475
+ });
1476
+ };
1477
+ const pairedOf = (end) => (edges) => {
1478
+ const midi = pipe(Array.head(edges), Option.match({
1479
+ onNone: () => NONE$4,
1480
+ onSome: ([pitch]) => pitch
1481
+ }));
1482
+ const steps = pipe(edges, Array.map(([, edge]) => edge));
1483
+ const paired = Array.reduce(steps, START_PAIRING, pairStep(midi));
1484
+ const unended = pipe(paired.open, Array.map((started) => ({
1485
+ tick: started.tick,
1486
+ end,
1487
+ midi,
1488
+ velocity: started.velocity,
1489
+ release: DEFAULT_RELEASE
1490
+ })));
1491
+ return [...paired.notes, ...unended];
1492
+ };
1493
+ const notesOf = (end) => (events) => {
1494
+ const notes = pipe(events, Array.map(edgeOf$1), Array.getSomes, Array.groupBy(([midi]) => String(midi)), Record.values, Array.flatMap(pairedOf(end)));
1495
+ return sortedNotes(notes);
1496
+ };
1497
+ const START_RPN = {
1498
+ msb: UNSET,
1499
+ lsb: UNSET,
1500
+ semitones: DEFAULT_BEND_RANGE,
1501
+ cents: NONE$4
1502
+ };
1503
+ const isBendRange = (rpn) => rpn.msb === PITCH_BEND_RPN && rpn.lsb === PITCH_BEND_RPN;
1504
+ const rpnAfter = (rpn) => ({ controllerType, value }) => {
1505
+ if (controllerType === RPN_MSB) return {
1506
+ ...rpn,
1507
+ msb: value
1508
+ };
1509
+ if (controllerType === RPN_LSB) return {
1510
+ ...rpn,
1511
+ lsb: value
1512
+ };
1513
+ if (isBendRange(rpn) && controllerType === DATA_MSB) return {
1514
+ ...rpn,
1515
+ semitones: value
1516
+ };
1517
+ if (isBendRange(rpn) && controllerType === DATA_LSB) return {
1518
+ ...rpn,
1519
+ cents: value
1520
+ };
1521
+ return rpn;
1522
+ };
1523
+ const rpnStep = ([rpn, { event }]) => {
1524
+ if (event.type !== "controller") return rpn;
1525
+ return rpnAfter(rpn)(event);
1526
+ };
1527
+ const controlOf = ([{ tick, event }, rpn]) => Match.value(event).pipe(Match.when({ type: "controller" }, (cc) => Option.some({
1528
+ tick,
1529
+ controller: {
1530
+ kind: "cc",
1531
+ number: cc.controllerType
1532
+ },
1533
+ value: cc.value
1534
+ })), Match.when({ type: "programChange" }, (change) => Option.some({
1535
+ tick,
1536
+ controller: { kind: "program" },
1537
+ value: change.programNumber
1538
+ })), Match.when({ type: "channelAftertouch" }, (pressure) => Option.some({
1539
+ tick,
1540
+ controller: {
1541
+ kind: "pressure",
1542
+ midi: Option.none()
1543
+ },
1544
+ value: pressure.amount
1545
+ })), Match.when({ type: "noteAftertouch" }, (pressure) => Option.some({
1546
+ tick,
1547
+ controller: {
1548
+ kind: "pressure",
1549
+ midi: Option.some(pressure.noteNumber)
1550
+ },
1551
+ value: pressure.amount
1552
+ })), Match.when({ type: "pitchBend" }, (bend) => Option.some({
1553
+ tick,
1554
+ controller: { kind: "bend" },
1555
+ value: bend.value * (rpn.semitones + rpn.cents / CENTS_PER_SEMITONE) / BEND_HALF
1556
+ })), Match.orElse(() => Option.none()));
1557
+ const controlsOf = (events) => pipe(Array.zip(events, Array.scan(events, START_RPN, (rpn, placed) => rpnStep([rpn, placed]))), Array.map(controlOf), Array.getSomes);
1558
+ const isProgram = (control) => control.controller.kind === "program";
1559
+ const initialProgramOf = (read) => pipe(Array.findFirst(read.controls, isProgram), Option.filter((program) => pipe(Array.head(read.notes), Option.match({
1560
+ onNone: () => true,
1561
+ onSome: (note) => program.tick <= note.tick
1562
+ }))));
1563
+ const channelReadOf = (end) => ([channel, events]) => {
1564
+ const read = {
1565
+ channel: Number(channel),
1566
+ notes: notesOf(end)(events),
1567
+ controls: controlsOf(events)
1568
+ };
1569
+ const program = initialProgramOf(read);
1570
+ return {
1571
+ ...read,
1572
+ program: pipe(program, Option.map((control) => control.value)),
1573
+ controls: Option.match(program, {
1574
+ onNone: () => read.controls,
1575
+ onSome: (first) => pipe(read.controls, Array.filter((control) => control !== first))
1576
+ })
1577
+ };
1578
+ };
1579
+ // src/features/convert-midi/model/timeline.ts
1580
+ const QUARTERS_PER_WHOLE = 4;
1581
+ const NONE$3 = 0;
1582
+ const NEXT$1 = 1;
1583
+ const placedOf = (ppq) => (events) => {
1584
+ const raw = Array.scan(events, NONE$3, (tick, event) => tick + event.deltaTime);
1585
+ return pipe(events, Array.map((event, index) => {
1586
+ const exact = Option.getOrElse(Array.get(raw, index + NEXT$1), () => NONE$3) * TICKS_PER_WHOLE / (ppq * QUARTERS_PER_WHOLE);
1587
+ return {
1588
+ tick: Math.round(exact),
1589
+ exact: Number.isInteger(exact),
1590
+ event
1591
+ };
1592
+ }));
1593
+ };
1594
+ const channelEventOf = ({ tick, event }) => {
1595
+ if ("channel" in event) return Option.some({
1596
+ tick,
1597
+ event
1598
+ });
1599
+ return Option.none();
1600
+ };
1601
+ const textOf = ({ tick, event }) => Match.value(event).pipe(Match.when({ type: "trackName" }, (text) => Option.some(["name", {
1602
+ tick,
1603
+ text: text.text
1604
+ }])), Match.when({ type: "lyrics" }, (text) => Option.some(["lyric", {
1605
+ tick,
1606
+ text: text.text
1607
+ }])), Match.when({ type: "marker" }, (text) => Option.some(["marker", {
1608
+ tick,
1609
+ text: text.text
1610
+ }])), Match.orElse(() => Option.none()));
1611
+ const tempoOf = ({ tick, event }) => Match.value(event).pipe(Match.when({ type: "setTempo" }, (tempo) => Option.some({
1612
+ tick,
1613
+ microseconds: tempo.microsecondsPerBeat,
1614
+ target: Option.none()
1615
+ })), Match.orElse(() => Option.none()));
1616
+ const meterOf = ({ tick, event }) => Match.value(event).pipe(Match.when({ type: "timeSignature" }, (meter) => Option.some({
1617
+ tick,
1618
+ numerator: meter.numerator,
1619
+ denominator: meter.denominator
1620
+ })), Match.orElse(() => Option.none()));
1621
+ const textsOf = (placed) => pipe(placed, Array.map(textOf), Array.getSomes, Array.groupBy(([kind]) => kind), Record.map((entries) => pipe(entries, Array.map(([, text]) => text))));
1622
+ const textsIn = (kind) => (read) => Option.getOrElse(Record.get(read.texts, kind), () => []);
1623
+ const byChannel = Order.mapInput(Order.Number, (read) => read.channel);
1624
+ const channelsOf = (end) => (placed) => {
1625
+ const reads = pipe(placed, Array.map(channelEventOf), Array.getSomes, Array.groupBy((item) => String(item.event.channel)), Record.toEntries, Array.map(channelReadOf(end)));
1626
+ return Array.sort(reads, byChannel);
1627
+ };
1628
+ const readTrack = (ppq) => (events) => {
1629
+ const placed = placedOf(ppq)(events);
1630
+ const end = pipe(Array.last(placed), Option.match({
1631
+ onNone: () => NONE$3,
1632
+ onSome: (last) => last.tick
1633
+ }));
1634
+ const texts = textsOf(placed);
1635
+ return {
1636
+ name: pipe(Array.head(textsIn("name")({ texts })), Option.map((text) => text.text)),
1637
+ end,
1638
+ offGrid: Array.countBy(placed, (item) => !item.exact),
1639
+ channels: channelsOf(end)(placed),
1640
+ texts,
1641
+ tempos: pipe(placed, Array.map(tempoOf), Array.getSomes),
1642
+ meters: pipe(placed, Array.map(meterOf), Array.getSomes)
1643
+ };
1644
+ };
1645
+ const isUsed = (read) => Array.isReadonlyArrayNonEmpty(read.notes) || Array.isReadonlyArrayNonEmpty(read.controls) || Option.isSome(read.program);
1646
+ const partsOf = (read, track) => {
1647
+ const lyrics = textsIn("lyric")(read);
1648
+ return pipe(read.channels, Array.filter(isUsed), Array.map((channel) => ({
1649
+ ...channel,
1650
+ track,
1651
+ name: read.name,
1652
+ lyrics: pipe(lyrics, Array.filter((lyric) => pipe(channel.notes, Array.some((note) => note.tick === lyric.tick))))
1653
+ })));
1654
+ };
1655
+ const titleOf = (reads) => pipe(Array.head(reads), Option.filter((read) => !Array.isReadonlyArrayNonEmpty(read.channels)), Option.flatMap((read) => read.name));
1656
+ const endsOf = (read) => [read.end, ...pipe(read.channels, Array.flatMap((channel) => channel.notes), Array.map((note) => note.end))];
1657
+ const sortedFrom = (pick) => (reads) => sortedByTick(pipe(reads, Array.flatMap(pick)));
1658
+ const timelineOf = (midi) => {
1659
+ const reads = pipe(midi.tracks, Array.map(readTrack(midi.header.ticksPerBeat ?? NONE$3)));
1660
+ return {
1661
+ title: titleOf(reads),
1662
+ end: Array.reduce(pipe(reads, Array.flatMap(endsOf)), NONE$3, (latest, tick) => Math.max(latest, tick)),
1663
+ offGrid: Array.reduce(reads, NONE$3, (total, read) => total + read.offGrid),
1664
+ tempos: sortedFrom((read) => read.tempos)(reads),
1665
+ meters: sortedFrom((read) => read.meters)(reads),
1666
+ markers: sortedFrom(textsIn("marker"))(reads),
1667
+ parts: pipe(reads, Array.flatMap((read, index) => partsOf(read, index))),
1668
+ mix: NO_MIX
1669
+ };
1670
+ };
1671
+ // src/features/convert-midi/model/convert.ts
1672
+ const taggedError$5 = Schema.TaggedError;
1673
+ var UnreadableMidi = class extends taggedError$5()("UnreadableMidi", { message: Schema.String }, { identifier: "UnreadableMidi" }) {};
1674
+ const midiToFumx = Effect.fn("midiToFumx")(function* convert(input) {
1675
+ const midi = yield* Effect.try({
1676
+ try: () => parseMidi(input.bytes),
1677
+ catch: (cause) => UnreadableMidi.make({ message: String(cause) })
1678
+ });
1679
+ if (Predicate.isUndefined(midi.header.ticksPerBeat)) return yield* UnreadableMidi.make({ message: "SMPTE time division is not supported" });
1680
+ const timeline = yield* Effect.sync(() => timelineOf(midi)).pipe(Effect.withSpan("timelineOf"));
1681
+ const written = yield* Effect.sync(() => writeFumx({
1682
+ timeline,
1683
+ title: Option.getOrElse(timeline.title, () => input.title)
1684
+ })).pipe(Effect.withSpan("writeFumx"));
1685
+ yield* Effect.annotateCurrentSpan({
1686
+ parts: written.plan.parts.length,
1687
+ bars: written.bars.length
1688
+ });
1689
+ return {
1690
+ ...written,
1691
+ offGrid: timeline.offGrid
1692
+ };
1693
+ });
1694
+ // src/app/midi-to-fumx.ts
1695
+ const convertMidiFile = Effect.fn("convertMidiFile")(function* convert(source) {
1696
+ const fumx = yield* midiToFumx(source);
1697
+ return yield* roundTrip(source.path, fumx);
1698
+ });
1699
+ // src/app/convert-command.ts
1700
+ const INDENT = 2;
1701
+ const taggedError$4 = Schema.TaggedError;
1702
+ var Mismatch = class extends taggedError$4()("Mismatch", { message: Schema.String }, { identifier: "Mismatch" }) {};
1703
+ const encodeSummary = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown, { space: INDENT }));
1704
+ const LIVE_SET = ".als";
1705
+ const convertSource = Effect.fn("convertSource")(function* convertSource(input, source) {
1706
+ if (String$1.endsWith(LIVE_SET)(String$1.toLowerCase(input))) return {
1707
+ converted: yield* convertLiveSetFile(source),
1708
+ from: "Live Set"
1709
+ };
1710
+ return {
1711
+ converted: yield* convertMidiFile(source),
1712
+ from: "MIDI file"
1713
+ };
1714
+ });
1715
+ const convertFile = Effect.fn("convertFile")(function* convertFile(file, out) {
1716
+ const fileSystem = yield* FileSystem.FileSystem;
1717
+ const path = yield* Path.Path;
1718
+ const input = path.resolve(file);
1719
+ const parsed = path.parse(input);
1720
+ const target = Option.match(out, {
1721
+ onNone: () => path.join(parsed.dir, `${parsed.name}.fumx`),
1722
+ onSome: (given) => path.resolve(given)
1723
+ });
1724
+ const bytes = yield* fileSystem.readFile(input);
1725
+ const { converted, from } = yield* convertSource(input, {
1726
+ bytes,
1727
+ title: parsed.name,
1728
+ path: target
1729
+ });
1730
+ yield* fileSystem.writeFileString(target, converted.text);
1731
+ return {
1732
+ from,
1733
+ summary: {
1734
+ output: target,
1735
+ comparison: converted.comparison,
1736
+ adjustments: converted.adjustments
1737
+ }
1738
+ };
1739
+ });
1740
+ /** @internal */
1741
+ const convertCommand = Command.make("convert", {
1742
+ file: Argument.String("file").pipe(Argument.withDescription("A Standard MIDI File (.mid) or an Ableton Live Set (.als); writes it as .fumx, reads it back and fails if any event differs")),
1743
+ out: Flag$1.String("out").pipe(Flag$1.withDescription("Where to write the .fumx file; defaults to the input's name with .fumx"), Flag$1.optional)
1744
+ }, ({ file, out }) => convertFile(file, out).pipe(Effect.tap(({ summary }) => Effect.flatMap(encodeSummary(summary), Console.log)), Effect.filterOrFail(({ summary }) => summary.comparison.matches, ({ from }) => Mismatch.make({ message: `The written .fumx does not reproduce every event of the ${from}` })), Effect.asVoid)).pipe(Command.withDescription("Converts a MIDI file or an Ableton Live Set to .fumx and checks the result against the original"));
1745
+ // src/app/language-server.ts
1746
+ const taggedError$3 = Schema.TaggedError;
1747
+ var MissingTransport = class extends taggedError$3()("MissingTransport", { message: Schema.String }) {};
1748
+ const startServer = () => {
1749
+ const connection = createConnection(ProposedFeatures.all);
1750
+ const shared = inject(createDefaultSharedModule({
1751
+ connection,
1752
+ ...NodeFileSystem
1753
+ }), FumxGeneratedSharedModule);
1754
+ const fumx = inject(createDefaultModule({ shared }), FumxGeneratedModule, FumxModule);
1755
+ shared.ServiceRegistry.register(fumx);
1756
+ registerChecks(fumx);
1757
+ startLanguageServer(shared);
1758
+ };
1759
+ /** @internal */
1760
+ const languageServerCommand = Command.make("language-server", {
1761
+ stdio: Flag$1.Boolean("stdio").pipe(Flag$1.withDescription("Speak the Language Server Protocol over standard input and output"), Flag$1.withDefault(false)),
1762
+ clientProcessId: Flag$1.Int("clientProcessId").pipe(Flag$1.withDescription("The editor's process id, which the editor passes on its own"), Flag$1.optional)
1763
+ }, ({ stdio }) => {
1764
+ if (!stdio) return Effect.fail(MissingTransport.make({ message: "start it with --stdio, the way an editor does" }));
1765
+ return Effect.sync(startServer).pipe(Effect.andThen(Effect.never));
1766
+ }).pipe(Command.withDescription("Serves the .fumx language to an editor over standard input and output"));
1767
+ // ../lint-host/src/entities/rule/model/setting.ts
1768
+ const NO_OPTIONS = {};
1769
+ const settingOf = (entry) => Match.value(entry).pipe(Match.when(Match.string, (severity) => ({
1770
+ severity,
1771
+ options: NO_OPTIONS
1772
+ })), Match.orElse(([severity, options]) => ({
1773
+ severity,
1774
+ options: options ?? NO_OPTIONS
1775
+ })));
1776
+ const optionsOf = (entry) => Match.value(entry).pipe(Match.when(Match.string, () => Option.none()), Match.orElse(([, options]) => Option.fromUndefinedOr(options)));
1777
+ const overridden = (earlier, later) => pipe(optionsOf(later), Option.orElse(() => optionsOf(earlier)), Option.match({
1778
+ onNone: () => later,
1779
+ onSome: (options) => [settingOf(later).severity, options]
1780
+ }));
1781
+ const mergedRules = (layers) => {
1782
+ const merged = {};
1783
+ for (const [name, later] of pipe(layers, Array.flatMap((layer) => Record.toEntries(layer ?? {})))) merged[name] = pipe(Record.get(merged, name), Option.match({
1784
+ onNone: () => later,
1785
+ onSome: (earlier) => overridden(earlier, later)
1786
+ }));
1787
+ return merged;
1788
+ };
1789
+ // ../lint-host/src/entities/rule/model/severity.ts
1790
+ const reportedSeverity = (setting) => Match.value(setting.severity).pipe(Match.when("warn", () => "warn"), Match.orElse(() => "error"));
1791
+ // ../lint-host/src/entities/rule/model/layers.ts
1792
+ const mergedRecords = (records) => pipe(records, Array.flatMap((record) => Record.toEntries(record ?? {})), Record.fromEntries);
1793
+ const layersOf = (config) => {
1794
+ const { extends: bases = [], ...own } = config;
1795
+ return [...pipe(bases, Array.flatMap(layersOf)), own];
1796
+ };
1797
+ const mergedLayers = (layers) => ({
1798
+ plugins: mergedRecords(pipe(layers, Array.map((layer) => layer.plugins))),
1799
+ rules: mergedRules(pipe(layers, Array.map((layer) => layer.rules))),
1800
+ ignores: pipe(layers, Array.flatMap((layer) => layer.ignores ?? [])),
1801
+ overrides: pipe(layers, Array.flatMap((layer) => layer.overrides ?? []))
1802
+ });
1803
+ // ../lint-host/src/shared/lib/fail.ts
1804
+ const taggedError$2 = Schema.TaggedError;
1805
+ var NotUtf8Error = class extends taggedError$2()("NotUtf8Error", { path: Schema.String }) {};
1806
+ // ../lint-host/src/features/run-cli/model/cli.ts
1807
+ const CONFIG_FILES = [
1808
+ "vite.config.ts",
1809
+ "vite.config.mts",
1810
+ "vite.config.js",
1811
+ "vite.config.mjs"
1812
+ ];
1813
+ const FAILED = 1;
1814
+ const DATA_FIRST_ARITY$1 = 2;
1815
+ const STRICT_UTF8 = new TextDecoder("utf-8", { fatal: true });
1816
+ const readSectionIn = (source, root) => Effect.gen(function* readConfig() {
1817
+ const fileSystem = yield* FileSystem.FileSystem;
1818
+ const path = yield* Path.Path;
1819
+ const found = yield* pipe(CONFIG_FILES, Array.map((name) => path.join(root, name)), Effect.filter((file) => fileSystem.exists(file).pipe(Effect.orElseSucceed(() => false))));
1820
+ const loaded = yield* Option.match(Array.head(found), {
1821
+ onNone: () => Effect.succeed({}),
1822
+ onSome: (file) => Effect.tryPromise({
1823
+ try: () => import("vite-plus"),
1824
+ catch: source.failWith("could not load vite-plus")
1825
+ }).pipe(Effect.flatMap(({ resolveConfigFromFile }) => Effect.tryPromise({
1826
+ try: () => resolveConfigFromFile(file),
1827
+ catch: source.failWith(`could not load ${file}`)
1828
+ })))
1829
+ });
1830
+ return source.section(loaded);
1831
+ }).pipe(Effect.withSpan(`${source.name}.config`));
1832
+ Function.dual(DATA_FIRST_ARITY$1, readSectionIn);
1833
+ const trackedFiles = (root, pathspecs) => Effect.gen(function* listFiles() {
1834
+ const output = yield* (yield* ChildProcessSpawner.ChildProcessSpawner).string(ChildProcess.make("git", [
1835
+ "ls-files",
1836
+ "-co",
1837
+ "--exclude-standard",
1838
+ "-z",
1839
+ "--",
1840
+ ...pathspecs
1841
+ ], { cwd: root }));
1842
+ return pipe(String$1.split(output, "\0"), Array.filter(String$1.isNonEmpty));
1843
+ });
1844
+ const requestOf = (config, patterns) => Array.match(patterns, {
1845
+ onEmpty: () => ({ config }),
1846
+ onNonEmpty: (given) => ({
1847
+ config,
1848
+ patterns: given
1849
+ })
1850
+ });
1851
+ const hasError = (found) => pipe(found, Array.some(({ severity }) => severity === "error"));
1852
+ const failWhen = (failed) => Effect.when(Effect.sync(() => {
1853
+ process.exitCode = FAILED;
1854
+ }), Effect.succeed(failed)).pipe(Effect.asVoid);
1855
+ const printAll = (found, format) => Array.match(found, {
1856
+ onEmpty: () => Effect.void,
1857
+ onNonEmpty: (all) => Console.log(pipe(all, Array.map(format), Array.join("\n")))
1858
+ });
1859
+ const readerIn = (root, failWith) => Effect.gen(function* reader() {
1860
+ const fileSystem = yield* FileSystem.FileSystem;
1861
+ const path = yield* Path.Path;
1862
+ return (file) => fileSystem.readFile(path.resolve(root, file)).pipe(Effect.mapError(failWith(`could not read ${file}`)), Effect.flatMap((bytes) => Effect.try({
1863
+ try: () => STRICT_UTF8.decode(bytes),
1864
+ catch: () => NotUtf8Error.make({ path: file })
1865
+ })));
1866
+ });
1867
+ /** @internal */
1868
+ const lintMain = (cli, patterns) => Effect.gen(function* main() {
1869
+ const root = process.cwd();
1870
+ const config = yield* readSectionIn(cli, root);
1871
+ const pathspecs = cli.pathspecs(requestOf(config, patterns));
1872
+ const { files, projectFiles } = yield* Effect.all({
1873
+ files: trackedFiles(root, pathspecs).pipe(Effect.withSpan(`${cli.name}.files`)),
1874
+ projectFiles: trackedFiles(root, []).pipe(Effect.withSpan(`${cli.name}.project`))
1875
+ }, { concurrency: "unbounded" });
1876
+ const read = yield* readerIn(root, cli.failWith);
1877
+ const found = yield* cli.lint({
1878
+ root,
1879
+ files,
1880
+ projectFiles,
1881
+ config,
1882
+ read
1883
+ });
1884
+ yield* printAll(found, cli.format);
1885
+ yield* failWhen(hasError(found));
1886
+ });
1887
+ const variadicOf = ({ name, description }) => Argument.String(name).pipe(Argument.withDescription(description), Argument.variadic());
1888
+ /** @internal */
1889
+ const pathspecArgument = () => variadicOf({
1890
+ name: "pathspec",
1891
+ description: "Git pathspecs of the files to lint, in place of the configured ones"
1892
+ });
1893
+ const present = Function.dual(2, (value, build) => Option.match(value, {
1894
+ onNone: () => ({}),
1895
+ onSome: build
1896
+ }));
1897
+ // ../lint-host/src/shared/lib/trace.ts
1898
+ const SAMPLED = "01";
1899
+ const NOT_SAMPLED = "00";
1900
+ const LINE_START$1 = 0;
1901
+ const flagsOf = (sampled) => Boolean.match(sampled, {
1902
+ onFalse: () => NOT_SAMPLED,
1903
+ onTrue: () => SAMPLED
1904
+ });
1905
+ Effect.currentSpan.pipe(Effect.map((span) => `00-${span.traceId}-${span.spanId}-${flagsOf(span.sampled)}`), Effect.option);
1906
+ const byPosition = Order.combine(Order.mapInput(Order.String, (found) => found.path), Order.combine(Order.mapInput(Order.Number, (found) => found.line), Order.mapInput(Order.Number, (found) => found.column ?? LINE_START$1)));
1907
+ const sortByPosition = (found) => Array.sort(found, byPosition);
1908
+ // ../lint-host/src/shared/lib/diagnostic.ts
1909
+ const diagnosticDetail = (diagnostic) => pipe([diagnostic.detail, diagnostic.context], Array.flatMap((part) => Option.toArray(Option.fromNullishOr(part))), Array.filter((part) => part !== ""), Array.map((part) => ` [${part}]`), Array.join(""));
1910
+ const formatDiagnostic = (diagnostic) => {
1911
+ const column = pipe(Option.fromNullishOr(diagnostic.column), Option.map((value) => `:${String(value)}`), Option.getOrElse(() => ""));
1912
+ return `${diagnostic.path}:${String(diagnostic.line)}${column} ${diagnostic.severity} ${diagnostic.rule} ${diagnostic.message}${diagnosticDetail(diagnostic)}`;
1913
+ };
1914
+ const notUtf8 = (tool) => (path) => ({
1915
+ path,
1916
+ line: 1,
1917
+ column: 1,
1918
+ rule: "utf8",
1919
+ message: `The file is not valid UTF-8, so ${tool} cannot read it`,
1920
+ severity: "error"
1921
+ });
1922
+ // ../lint-host/src/shared/lib/section.ts
1923
+ const sectionOf = ({ name, fallback, prepare = Function.identity }) => {
1924
+ const hasSection = (value) => Predicate.hasProperty(value, name) && Predicate.isObject(value[name]);
1925
+ return (config) => pipe(Option.liftPredicate(config, hasSection), Option.flatMapNullishOr((value) => value[name]), Option.map(prepare), Option.getOrElse(() => fallback));
1926
+ };
1927
+ const pathspecsOf = ({ defaults, unowned = [] }) => ({ config, patterns = [] }) => [
1928
+ ...Array.match(patterns, {
1929
+ onEmpty: () => defaults,
1930
+ onNonEmpty: Function.identity
1931
+ }),
1932
+ ...unowned,
1933
+ ...pipe(config.ignores ?? [], Array.map((glob) => `:(glob,exclude)${glob}`))
1934
+ ];
1935
+ // src/shared/lib/errors.ts
1936
+ const taggedError$1 = Schema.TaggedError;
1937
+ var LintError = class extends taggedError$1()("LintError", { message: Schema.String }) {};
1938
+ const failedWith = (message) => (cause) => LintError.make({ message: `${message}: ${String(cause)}` });
1939
+ // src/features/check-songs/model/extend.ts
1940
+ const flattenConfig = (config) => {
1941
+ const { plugins, rules, ignores } = mergedLayers(layersOf(config));
1942
+ return {
1943
+ plugins,
1944
+ rules,
1945
+ ignores
1946
+ };
1947
+ };
1948
+ // src/features/check-songs/model/read.ts
1949
+ const SEPARATOR$1 = "/";
1950
+ const pathOf = (input) => `${input.root}${SEPARATOR$1}${input.file}`;
1951
+ const readSongFile = Effect.fn("fumx.lint.read")(function* readSongFile(input) {
1952
+ const source = yield* readSong({
1953
+ path: pathOf(input),
1954
+ read: input.read
1955
+ });
1956
+ return {
1957
+ file: input.file,
1958
+ source
1959
+ };
1960
+ });
1961
+ // src/features/check-songs/model/resolve.ts
1962
+ const SEPARATOR = "/";
1963
+ const START = 0;
1964
+ const ENABLED = settingOf("error");
1965
+ const idOf = (plugin, name) => `${plugin}${SEPARATOR}${name}`;
1966
+ const pluginOf = (id) => pipe(String$1.indexOf(SEPARATOR)(id), Option.match({
1967
+ onNone: () => id,
1968
+ onSome: (slash) => String$1.slice(START, slash)(id)
1969
+ }));
1970
+ const rulesOf$2 = (config) => ([plugin, value]) => pipe(Record.toEntries(value.rules), Array.map(([name, rule]) => {
1971
+ const id = idOf(plugin, name);
1972
+ return {
1973
+ id,
1974
+ rule,
1975
+ setting: pipe(config.rules ?? {}, Record.get(id), Option.map(settingOf), Option.getOrElse(() => ENABLED))
1976
+ };
1977
+ }), Array.filter(({ setting }) => setting.severity !== "off"));
1978
+ const resolve = (config) => pipe(Record.toEntries(config.plugins ?? {}), Array.flatMap(rulesOf$2(config)));
1979
+ const unknownPlugins = (config) => pipe(Record.keys(config.rules ?? {}), Array.map(pluginOf), Array.filter((plugin) => !Record.has(config.plugins ?? {}, plugin)), Array.dedupe);
1980
+ const ruleNameOf = (id) => pipe(String$1.indexOf(SEPARATOR)(id), Option.match({
1981
+ onNone: () => "",
1982
+ onSome: (slash) => String$1.slice(slash + 1)(id)
1983
+ }));
1984
+ const isKnownRule = (config) => (id) => pipe(Record.get(config.plugins ?? {}, pluginOf(id)), Option.match({
1985
+ onNone: () => true,
1986
+ onSome: (plugin) => Record.has(plugin.rules, ruleNameOf(id))
1987
+ }));
1988
+ const unknownRules = (config) => pipe(Record.keys(config.rules ?? {}), Array.filter((id) => !isKnownRule(config)(id)));
1989
+ // src/features/analyze-song/model/sounding.ts
1990
+ const NONE$2 = 0;
1991
+ const FIRST$3 = 1;
1992
+ const CENTS = /[+-]\d+c$/u;
1993
+ const pitchClassOf$1 = (note) => {
1994
+ const written = Note.pitchClass(String$1.replace(CENTS, "")(note.spelling));
1995
+ if (String$1.isNonEmpty(written)) return written;
1996
+ return Note.pitchClass(Note.fromMidi(note.midi));
1997
+ };
1998
+ const overlapOf = (left) => (right) => Math.max(NONE$2, Math.min(left.end, right.end) - Math.max(left.start, right.start));
1999
+ const soundingsOf = (song) => {
2000
+ const audible = pipe(song.tracks, Array.filter((track) => !track.mixer.muted));
2001
+ return pipe(song.notes, Array.flatMap((note) => pipe(audible, Array.findFirst((track) => track.name === note.track), Option.map((track) => ({
2002
+ track: note.track,
2003
+ line: note.sourceLine,
2004
+ column: note.sourceColumn,
2005
+ bar: note.bar,
2006
+ role: track.role,
2007
+ midi: note.midi,
2008
+ spelling: note.spelling,
2009
+ pitchClass: pitchClassOf$1(note),
2010
+ start: note.start,
2011
+ end: note.start + Math.round(note.length * note.gate)
2012
+ })), Option.toArray)));
2013
+ };
2014
+ const positionOf = (song) => (tick) => pipe(song.bars, Array.findLast((bar) => bar.start <= tick), Option.match({
2015
+ onNone: () => ({
2016
+ bar: FIRST$3,
2017
+ offset: fractionOf(tick)
2018
+ }),
2019
+ onSome: (bar) => ({
2020
+ bar: bar.index,
2021
+ offset: fractionOf(tick - bar.start)
2022
+ })
2023
+ }));
2024
+ // src/features/check-songs/model/suppressions.ts
2025
+ const DIRECTIVE = /^fumx-(?<kind>ignore-next-line|ignore-file|ignore|disable|enable)(?:\s(?<rest>[\s\S]*))?$/u;
2026
+ const REASON = /\s-{2,}(?:\s|$)/u;
2027
+ const BLOCK_START = "/*";
2028
+ const BLOCK_END = "*/";
2029
+ const LIST = ",";
2030
+ const NEXT = 1;
2031
+ const LINE_START = 0;
2032
+ const kindOf = (text) => Match.value(text).pipe(Match.when("ignore-file", () => "ignore-file"), Match.when("ignore-next-line", () => "ignore-next-line"), Match.when("disable", () => "disable"), Match.when("enable", () => "enable"), Match.orElse(() => "ignore"));
2033
+ const bodyOf = (text) => {
2034
+ if (String$1.startsWith(BLOCK_START)(text)) return pipe(text, String$1.slice(2), String$1.replace(BLOCK_END, ""), String$1.trim);
2035
+ return pipe(text, String$1.slice(2), String$1.trim);
2036
+ };
2037
+ const rulesOf$1 = (rest) => pipe(String$1.split(` ${rest}`, REASON), Array.head, Option.getOrElse(() => ""), String$1.split(LIST), Array.map(String$1.trim), Array.filter(String$1.isNonEmpty));
2038
+ const directiveOf = (comment) => pipe(groupsOf$1(DIRECTIVE)(bodyOf(comment.text)), Option.map((groups) => ({
2039
+ line: comment.line,
2040
+ column: comment.column,
2041
+ kind: kindOf(groups["kind"] ?? ""),
2042
+ rules: rulesOf$1(groups["rest"] ?? "")
2043
+ })));
2044
+ const names = (rule) => (directive) => !Array.isReadonlyArrayNonEmpty(directive.rules) || Array.contains(directive.rules, rule);
2045
+ const isRange = (directive) => directive.kind === "disable" || directive.kind === "enable";
2046
+ const coversLine = (found) => (directive) => names(found.rule)(directive) && Match.value(directive.kind).pipe(Match.when("ignore-file", () => true), Match.when("ignore-next-line", () => directive.line + NEXT === found.line), Match.when("ignore", () => directive.line === found.line), Match.orElse(() => false));
2047
+ const isAfter = (found) => (directive) => directive.line < found.line || directive.line === found.line && directive.column <= (found.column ?? LINE_START);
2048
+ const insideRange = (directives) => (found) => pipe(directives, Array.filter((directive) => isRange(directive) && isAfter(found)(directive) && names(found.rule)(directive)), Array.last, Option.exists((directive) => directive.kind === "disable"));
2049
+ const suppressionsOf = (comments) => {
2050
+ const directives = pipe(comments, Array.map(directiveOf), Array.getSomes);
2051
+ return (found) => pipe(directives, Array.some(coversLine(found))) || insideRange(directives)(found);
2052
+ };
2053
+ // src/features/check-songs/model/run.ts
2054
+ const diagnosticOf = (path, rule) => (report) => ({
2055
+ path,
2056
+ line: report.line,
2057
+ rule: rule.id,
2058
+ message: report.message,
2059
+ severity: reportedSeverity(rule.setting),
2060
+ ...present(Option.fromNullishOr(report.column), (column) => ({ column })),
2061
+ ...present(Option.fromNullishOr(report.detail), (detail) => ({ detail }))
2062
+ });
2063
+ const runOne = (input, soundings) => Effect.fn("fumx.lint.rule")(function* run(rule) {
2064
+ yield* Effect.annotateCurrentSpan({ "fumx.lint.rule": rule.id });
2065
+ const reports = [];
2066
+ yield* Effect.try({
2067
+ try: () => {
2068
+ rule.rule.check({
2069
+ filename: input.path,
2070
+ song: input.song,
2071
+ soundings,
2072
+ options: rule.setting.options,
2073
+ report: (report) => {
2074
+ reports.push(report);
2075
+ }
2076
+ });
2077
+ },
2078
+ catch: failedWith(`${rule.id} failed`)
2079
+ });
2080
+ return pipe(reports, Array.map(diagnosticOf(input.path, rule)));
2081
+ });
2082
+ const runRules = Effect.fn("fumx.lint.rules")(function* runRules(input) {
2083
+ const soundings = soundingsOf(input.song);
2084
+ const suppressed = suppressionsOf(input.comments);
2085
+ const found = yield* pipe(input.rules, Effect.forEach(runOne(input, soundings), { concurrency: 1 }));
2086
+ return pipe(Array.flatten(found), Array.filter((diagnostic) => !suppressed(diagnostic)));
2087
+ });
2088
+ // src/app/run-lint.ts
2089
+ const PARSE_RULE = "fumx/parse";
2090
+ const failIfAny = (problem) => (names) => Array.match(names, {
2091
+ onEmpty: () => Effect.void,
2092
+ onNonEmpty: (found) => Effect.fail(LintError.make({ message: `${problem}: ${Array.join(found, ", ")}` }))
2093
+ });
2094
+ const UNKNOWN_PLUGINS = failIfAny("rules name plugins that are not configured");
2095
+ const UNKNOWN_RULES = failIfAny("rules name rules that their plugins do not have");
2096
+ const checkPlugins = (config) => {
2097
+ const rules = UNKNOWN_RULES(unknownRules(config));
2098
+ return UNKNOWN_PLUGINS(unknownPlugins(config)).pipe(Effect.andThen(rules));
2099
+ };
2100
+ const rulesOf = (config) => {
2101
+ const flat = flattenConfig(config ?? {});
2102
+ return checkPlugins(flat).pipe(Effect.as(resolve(flat)));
2103
+ };
2104
+ const parseDiagnosticsOf = (file) => (issues) => pipe(issues, Array.map((issue) => ({
2105
+ path: file,
2106
+ line: issue.line,
2107
+ column: issue.column,
2108
+ rule: PARSE_RULE,
2109
+ message: issue.message,
2110
+ severity: "error"
2111
+ })));
2112
+ const lintFile = (rules) => (song) => {
2113
+ if (song.source.status === "invalid") return Effect.succeed(parseDiagnosticsOf(song.file)(song.source.issues));
2114
+ return runRules({
2115
+ path: song.file,
2116
+ comments: song.source.outline.comments,
2117
+ song: song.source.song,
2118
+ rules
2119
+ });
2120
+ };
2121
+ const notFound = (path) => Effect.fail(LintError.make({ message: `could not read ${path}` }));
2122
+ const readerOf = (input) => (path) => {
2123
+ if (path === input.path) return Effect.succeed(input.text);
2124
+ return (input.read ?? notFound)(path);
2125
+ };
2126
+ const lintTracked = (rules, input) => Effect.fnUntraced(function* lintOne(file) {
2127
+ const path = pathOf({
2128
+ root: input.root,
2129
+ file
2130
+ });
2131
+ const read = yield* Effect.result(input.read(path));
2132
+ if (Result.isFailure(read) && Schema.is(NotUtf8Error)(read.failure)) return [notUtf8("fumx lint")(file)];
2133
+ const reader = Result.match(read, {
2134
+ onFailure: () => input.read,
2135
+ onSuccess: (text) => readerOf({
2136
+ path,
2137
+ text,
2138
+ read: input.read
2139
+ })
2140
+ });
2141
+ const source = yield* readSongFile({
2142
+ root: input.root,
2143
+ file,
2144
+ read: reader
2145
+ });
2146
+ return yield* lintFile(rules)(source);
2147
+ });
2148
+ const lint = Effect.fn("fumx.lint.lint")(function* lint(input) {
2149
+ const rules = yield* rulesOf(input.config);
2150
+ const found = yield* Effect.forEach(input.files, lintTracked(rules, input), { concurrency: "unbounded" });
2151
+ return sortByPosition(Array.flatten(found));
2152
+ });
2153
+ Effect.fn("fumx.lint.lintText")(function* lintText(input) {
2154
+ const rules = yield* rulesOf(input.config);
2155
+ const source = yield* readSong({
2156
+ path: input.path,
2157
+ read: readerOf(input)
2158
+ });
2159
+ const found = yield* lintFile(rules)({
2160
+ file: input.path,
2161
+ source
2162
+ });
2163
+ return sortByPosition(found);
2164
+ });
2165
+ // src/app/section.ts
2166
+ const fumxSection = sectionOf({
2167
+ name: "fumx",
2168
+ fallback: {}
2169
+ });
2170
+ const lintSection = (config) => pipe(Option.fromUndefinedOr(fumxSection(config).lint), Option.match({
2171
+ onNone: () => ({}),
2172
+ onSome: flattenConfig
2173
+ }));
2174
+ // src/app/lint-command.ts
2175
+ const linter = {
2176
+ name: "fumx.lint",
2177
+ version,
2178
+ description: "Lints .fumx songs with the rules under fumx.lint in vite.config.ts and prints each finding",
2179
+ section: lintSection,
2180
+ pathspecs: pathspecsOf({ defaults: ["*.fumx"] }),
2181
+ lint,
2182
+ format: formatDiagnostic,
2183
+ failWith: failedWith
2184
+ };
2185
+ /** @internal */
2186
+ const lintCommand = Command.make("lint", { pathspecs: pathspecArgument() }, ({ pathspecs }) => lintMain(linter, pathspecs)).pipe(Command.withDescription(linter.description));
2187
+ // src/features/analyze-song/model/chords.ts
2188
+ const FIRST$2 = 1;
2189
+ const HELD_SHARE = .25;
2190
+ const UNKNOWN$1 = "?";
2191
+ const PositionSchema = Schema.Struct({
2192
+ bar: Schema.Int,
2193
+ offset: Schema.String
2194
+ });
2195
+ const ChordSpanSchema = Schema.Struct({
2196
+ from: PositionSchema,
2197
+ to: PositionSchema,
2198
+ start: Schema.Int,
2199
+ end: Schema.Int,
2200
+ symbol: Schema.String,
2201
+ notes: Schema.Array(Schema.String)
2202
+ });
2203
+ const heldIn = (window) => (note) => overlapOf(note)(window) >= (window.end - window.start) * HELD_SHARE;
2204
+ const isHarmonic = (note) => Option.exists(note.role, (role) => role === "bass" || role === "harmony");
2205
+ const OCTAVE$1 = 12;
2206
+ const UNISON = 0;
2207
+ const samePitchClass = (left, right) => (left - right) % OCTAVE$1 === UNISON;
2208
+ const byMidi = Order.mapInput(Order.Number, (note) => note.midi);
2209
+ const harmonicOrAll = (held) => {
2210
+ const harmonic = pipe(held, Array.filter(isHarmonic));
2211
+ if (Array.isReadonlyArrayNonEmpty(harmonic)) return harmonic;
2212
+ return held;
2213
+ };
2214
+ const chordNotesIn = (notes) => (window) => pipe(notes, Array.filter(heldIn(window)), harmonicOrAll, (held) => Array.sort(held, byMidi), Array.dedupeWith((left, right) => samePitchClass(left.midi, right.midi)), Array.map((note) => note.pitchClass));
2215
+ const spells = (notes) => (symbol) => {
2216
+ const spelled = Chord.get(symbol).notes;
2217
+ return spelled.length === notes.length && pipe(spelled, Array.every((note) => Array.contains(notes, note)));
2218
+ };
2219
+ const symbolOf = (notes) => {
2220
+ const candidates = Chord.detect(Array.copy(notes));
2221
+ return pipe(candidates, Array.findFirst(spells(notes)), Option.orElse(() => Array.head(candidates)), Option.getOrElse(() => UNKNOWN$1));
2222
+ };
2223
+ const beatWindowsOf = (song) => pipe(song.bars, Array.flatMap((bar) => {
2224
+ const beat = TICKS_PER_WHOLE / bar.meter.denominator;
2225
+ return Array.makeBy(bar.meter.numerator, (index) => ({
2226
+ start: bar.start + index * beat,
2227
+ end: bar.start + (index + FIRST$2) * beat
2228
+ }));
2229
+ }));
2230
+ const extend = (spans, beat) => Option.match(Array.last(spans), {
2231
+ onNone: () => [beat],
2232
+ onSome: (last) => {
2233
+ if (last.symbol !== beat.symbol || last.end !== beat.start) return [...spans, beat];
2234
+ return [...Array.dropRight(spans, FIRST$2), {
2235
+ ...last,
2236
+ end: beat.end
2237
+ }];
2238
+ }
2239
+ });
2240
+ const beatChordOf = (notes) => (window) => {
2241
+ const held = chordNotesIn(notes)(window);
2242
+ if (!Array.isReadonlyArrayNonEmpty(held)) return Option.none();
2243
+ return Option.some({
2244
+ ...window,
2245
+ notes: held,
2246
+ symbol: symbolOf(held)
2247
+ });
2248
+ };
2249
+ const chordsOf = (song) => {
2250
+ const notes = soundingsOf(song);
2251
+ const beats = pipe(beatWindowsOf(song), Array.map(beatChordOf(notes)), Array.getSomes);
2252
+ const at = positionOf(song);
2253
+ return pipe(Array.reduce(beats, [], extend), Array.map((span) => ({
2254
+ from: at(span.start),
2255
+ to: at(span.end),
2256
+ start: span.start,
2257
+ end: span.end,
2258
+ symbol: span.symbol,
2259
+ notes: span.notes
2260
+ })));
2261
+ };
2262
+ // src/features/analyze-song/model/keys.ts
2263
+ const NONE$1 = 0;
2264
+ const OCTAVE = 12;
2265
+ const SQUARE = 2;
2266
+ const CORRELATION_DIGITS = 3;
2267
+ const UNKNOWN = "?";
2268
+ const MAJOR_PROFILE = {
2269
+ tonic: 6.35,
2270
+ minorSecond: 2.23,
2271
+ majorSecond: 3.48,
2272
+ minorThird: 2.33,
2273
+ majorThird: 4.38,
2274
+ fourth: 4.09,
2275
+ tritone: 2.52,
2276
+ fifth: 5.19,
2277
+ minorSixth: 2.39,
2278
+ majorSixth: 3.66,
2279
+ minorSeventh: 2.29,
2280
+ majorSeventh: 2.88
2281
+ };
2282
+ const MINOR_PROFILE = {
2283
+ tonic: 6.33,
2284
+ minorSecond: 2.68,
2285
+ majorSecond: 3.52,
2286
+ minorThird: 5.38,
2287
+ majorThird: 2.6,
2288
+ fourth: 3.53,
2289
+ tritone: 2.54,
2290
+ fifth: 4.75,
2291
+ minorSixth: 3.98,
2292
+ majorSixth: 2.69,
2293
+ minorSeventh: 3.34,
2294
+ majorSeventh: 3.17
2295
+ };
2296
+ const MAJOR_TONICS = [
2297
+ "C",
2298
+ "Db",
2299
+ "D",
2300
+ "Eb",
2301
+ "E",
2302
+ "F",
2303
+ "F#",
2304
+ "G",
2305
+ "Ab",
2306
+ "A",
2307
+ "Bb",
2308
+ "B"
2309
+ ];
2310
+ const MINOR_TONICS = [
2311
+ "C",
2312
+ "C#",
2313
+ "D",
2314
+ "Eb",
2315
+ "E",
2316
+ "F",
2317
+ "F#",
2318
+ "G",
2319
+ "G#",
2320
+ "A",
2321
+ "Bb",
2322
+ "B"
2323
+ ];
2324
+ const ModeSchema = Schema.Literals(["major", "minor"]);
2325
+ const barRangeFields = {
2326
+ fromBar: Schema.Int,
2327
+ toBar: Schema.Int
2328
+ };
2329
+ const BarRangeSchema = Schema.Struct(barRangeFields);
2330
+ const KeySpanSchema = Schema.Struct({
2331
+ ...barRangeFields,
2332
+ tonic: Schema.String,
2333
+ pitchClass: Schema.Int,
2334
+ mode: ModeSchema,
2335
+ correlation: Schema.Finite
2336
+ });
2337
+ const pitchClassOf = (midi) => (midi % OCTAVE + OCTAVE) % OCTAVE;
2338
+ const addWeight = (window) => (weights, note) => {
2339
+ const share = overlapOf(note)(window);
2340
+ const pitchClass = pitchClassOf(note.midi);
2341
+ return pipe(weights, Array.map((weight, index) => {
2342
+ if (index === pitchClass) return weight + share;
2343
+ return weight;
2344
+ }));
2345
+ };
2346
+ const histogramOf = (window) => (notes) => Array.reduce(notes, Array.makeBy(OCTAVE, () => NONE$1), addWeight(window));
2347
+ const add = (sum, value) => sum + value;
2348
+ const sumOf = (values) => Array.reduce(values, NONE$1, add);
2349
+ const meanOf = (values) => sumOf(values) / values.length;
2350
+ const spreadOf = (values) => {
2351
+ const center = meanOf(values);
2352
+ const squares = pipe(values, Array.map((value) => (value - center) ** SQUARE));
2353
+ return Math.sqrt(sumOf(squares));
2354
+ };
2355
+ const correlationOf = (profile) => (histogram) => {
2356
+ const histogramMean = meanOf(histogram);
2357
+ const profileMean = meanOf(profile);
2358
+ const covariance = sumOf(pipe(Array.zip(histogram, profile), Array.map(([weight, expected]) => (weight - histogramMean) * (expected - profileMean))));
2359
+ const scale = spreadOf(histogram) * spreadOf(profile);
2360
+ if (scale === NONE$1) return NONE$1;
2361
+ return covariance / scale;
2362
+ };
2363
+ const rotated = (tonic) => (profile) => {
2364
+ const weights = Record.values(profile);
2365
+ return Array.makeBy(OCTAVE, (index) => weights[(index - tonic + OCTAVE) % OCTAVE] ?? NONE$1);
2366
+ };
2367
+ const candidatesAt = (histogram) => (tonic) => [{
2368
+ tonic: MAJOR_TONICS[tonic] ?? UNKNOWN,
2369
+ pitchClass: tonic,
2370
+ mode: "major",
2371
+ correlation: correlationOf(rotated(tonic)(MAJOR_PROFILE))(histogram)
2372
+ }, {
2373
+ tonic: MINOR_TONICS[tonic] ?? UNKNOWN,
2374
+ pitchClass: tonic,
2375
+ mode: "minor",
2376
+ correlation: correlationOf(rotated(tonic)(MINOR_PROFILE))(histogram)
2377
+ }];
2378
+ const byCorrelation = Order.flip(Order.mapInput(Order.Number, (candidate) => candidate.correlation));
2379
+ const edgeOf = (song) => (index, end) => pipe(song.bars, Array.findFirst((bar) => bar.index === index), Option.match({
2380
+ onNone: () => NONE$1,
2381
+ onSome: (bar) => bar.start + Number(end) * bar.length
2382
+ }));
2383
+ const keyIn = (song) => (range) => {
2384
+ const edge = edgeOf(song);
2385
+ const histogram = histogramOf({
2386
+ start: edge(range.fromBar, false),
2387
+ end: edge(range.toBar, true)
2388
+ })(soundingsOf(song));
2389
+ if (pipe(histogram, Array.every((weight) => weight === NONE$1))) return Option.none();
2390
+ const candidates = pipe(Array.range(NONE$1, 11), Array.flatMap(candidatesAt(histogram)));
2391
+ return pipe(Array.sort(candidates, byCorrelation), Array.head, Option.map((best) => ({
2392
+ fromBar: range.fromBar,
2393
+ toBar: range.toBar,
2394
+ tonic: best.tonic,
2395
+ pitchClass: best.pitchClass,
2396
+ mode: best.mode,
2397
+ correlation: Number$1.round(best.correlation, CORRELATION_DIGITS)
2398
+ })));
2399
+ };
2400
+ // src/features/analyze-song/model/repeats.ts
2401
+ const FIRST$1 = 1;
2402
+ const SECOND = 2;
2403
+ const fingerprintOf = (song) => (bar) => {
2404
+ const notes = pipe(song.notes, Array.filter((note) => note.bar === bar), Array.map((note) => `${note.track}:${String(note.offset)}:${String(note.midi)}:${String(note.length)}`));
2405
+ const hits = pipe(song.hits, Array.filter((hit) => hit.bar === bar), Array.map((hit) => `${hit.track}:${String(hit.offset)}:${hit.voice}`));
2406
+ const slices = pipe(song.slices, Array.filter((slice) => slice.bar === bar), Array.map((slice) => `${slice.track}:${String(slice.offset)}:${slice.sample}:${String(slice.index)}`));
2407
+ return pipe(Array.sort([
2408
+ ...notes,
2409
+ ...hits,
2410
+ ...slices
2411
+ ], Order.String), Array.join("|"));
2412
+ };
2413
+ const repeatOf = (prints) => (bar) => {
2414
+ const print = prints[bar - FIRST$1] ?? "";
2415
+ return print !== "" && print === prints[bar - SECOND];
2416
+ };
2417
+ const joinRun = (runs, bar) => Option.match(Array.last(runs), {
2418
+ onNone: () => [{
2419
+ fromBar: bar - FIRST$1,
2420
+ toBar: bar
2421
+ }],
2422
+ onSome: (last) => {
2423
+ if (last.toBar !== bar - FIRST$1) return [...runs, {
2424
+ fromBar: bar - FIRST$1,
2425
+ toBar: bar
2426
+ }];
2427
+ return [...Array.dropRight(runs, FIRST$1), {
2428
+ ...last,
2429
+ toBar: bar
2430
+ }];
2431
+ }
2432
+ });
2433
+ const repeatsOf = (song) => {
2434
+ const bars = song.bars.length;
2435
+ const prints = pipe(Array.range(FIRST$1, bars), Array.map(fingerprintOf(song)));
2436
+ const repeated = pipe(Array.range(SECOND, bars), Array.filter(repeatOf(prints)));
2437
+ return Array.reduce(repeated, [], joinRun);
2438
+ };
2439
+ // src/features/analyze-song/model/analysis.ts
2440
+ const FIRST = 1;
2441
+ const NONE = 0;
2442
+ const PHRASE_BARS = 4;
2443
+ const AnalysisSchema = Schema.Struct({
2444
+ bars: Schema.Int,
2445
+ key: Schema.OptionFromNullOr(KeySpanSchema),
2446
+ keys: Schema.Array(KeySpanSchema),
2447
+ chords: Schema.Array(ChordSpanSchema),
2448
+ repeats: Schema.Array(BarRangeSchema)
2449
+ });
2450
+ const phrasesOf = (bars) => Array.makeBy(Math.ceil(bars / PHRASE_BARS), (phrase) => ({
2451
+ fromBar: phrase * PHRASE_BARS + FIRST,
2452
+ toBar: Math.min(bars, (phrase + FIRST) * PHRASE_BARS)
2453
+ }));
2454
+ const analyze = (song) => {
2455
+ const bars = song.bars.length;
2456
+ if (bars === NONE) return {
2457
+ bars,
2458
+ key: Option.none(),
2459
+ keys: [],
2460
+ chords: [],
2461
+ repeats: []
2462
+ };
2463
+ return {
2464
+ bars,
2465
+ key: keyIn(song)({
2466
+ fromBar: FIRST,
2467
+ toBar: bars
2468
+ }),
2469
+ keys: pipe(phrasesOf(bars), Array.map(keyIn(song)), Array.getSomes),
2470
+ chords: chordsOf(song),
2471
+ repeats: repeatsOf(song)
2472
+ };
2473
+ };
2474
+ // src/app/song-report-command.ts
2475
+ const encodeReport = Schema.encodeUnknownEffect(Schema.fromJsonString(AnalysisSchema, { space: 2 }));
2476
+ const taggedError = Schema.TaggedError;
2477
+ var InvalidSong = class extends taggedError()("InvalidSong", { message: Schema.String }, { identifier: "InvalidSong" }) {};
2478
+ /** @internal */
2479
+ const reportCommand = Command.make("report", { file: Argument.String("file").pipe(Argument.withDescription("A .fumx file; reads the files it imports and prints the keys, chords and repeated bars read from its notes")) }, ({ file }) => Effect.gen(function* report() {
2480
+ const fileSystem = yield* FileSystem.FileSystem;
2481
+ const path = yield* Path.Path;
2482
+ const source = yield* readSong({
2483
+ path: path.resolve(file),
2484
+ read: (target) => fileSystem.readFileString(target)
2485
+ });
2486
+ if (source.status === "invalid") {
2487
+ const lines = pipe(source.issues, Array.map((issue) => `${issue.path}:${String(issue.line)}:${String(issue.column)} ${issue.message}`));
2488
+ return yield* InvalidSong.make({ message: Array.join(lines, "\n") });
2489
+ }
2490
+ const encoded = yield* encodeReport(analyze(source.song));
2491
+ return yield* Console.log(encoded);
2492
+ })).pipe(Command.withDescription("Prints, as JSON, the keys, chords and repeated bars read from the notes of a .fumx song"));
2493
+ // src/app/cli.ts
2494
+ const command = Command.make("fumx").pipe(Command.withDescription(description), Command.withSubcommands([
2495
+ lintCommand,
2496
+ reportCommand,
2497
+ convertCommand,
2498
+ languageServerCommand
2499
+ ]));
2500
+ /** @internal */
2501
+ const runCli = () => {
2502
+ command.pipe(Command.run({ version }), runMain("fumx"));
2503
+ };
2504
+ export { runCli };
2505
+
2506
+ //# sourceMappingURL=cli-D2DptmOG.mjs.map