@r_masseater/song-format 0.0.0 → 0.2.0

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 (53) hide show
  1. package/LICENSE +87 -0
  2. package/README.md +92 -1
  3. package/dist/analysis.d.mts +95 -0
  4. package/dist/analysis.mjs +328 -0
  5. package/dist/analysis.mjs.map +1 -0
  6. package/dist/convert-als.d.mts +18 -0
  7. package/dist/convert-als.mjs +504 -0
  8. package/dist/convert-als.mjs.map +1 -0
  9. package/dist/convert-midi.d.mts +18 -0
  10. package/dist/convert-midi.mjs +273 -0
  11. package/dist/convert-midi.mjs.map +1 -0
  12. package/dist/fumx-language-server.mjs +23 -0
  13. package/dist/fumx-language-server.mjs.map +1 -0
  14. package/dist/fumx-module-CmHFC-eI.mjs +12513 -0
  15. package/dist/fumx-module-CmHFC-eI.mjs.map +1 -0
  16. package/dist/fumx-module-DJQrnEVm.mjs +2660 -0
  17. package/dist/fumx-module-DJQrnEVm.mjs.map +1 -0
  18. package/dist/grammar-86_uhiTo.mjs +9836 -0
  19. package/dist/grammar-86_uhiTo.mjs.map +1 -0
  20. package/dist/index-Cup9xTad.d.mts +105 -0
  21. package/dist/index-DPt8MZ6e.d.mts +796 -0
  22. package/dist/index-JXjnMHXw.d.mts +1350 -0
  23. package/dist/index.d.mts +9 -0
  24. package/dist/index.mjs +4 -0
  25. package/dist/language.d.mts +13 -0
  26. package/dist/language.mjs +3 -0
  27. package/dist/mapper.mjs +14 -0
  28. package/dist/mapper.mjs.map +1 -0
  29. package/dist/midi-to-fumx.mjs +1223 -0
  30. package/dist/midi-to-fumx.mjs.map +1 -0
  31. package/dist/read-song-CNrfcHrY.mjs +123 -0
  32. package/dist/read-song-CNrfcHrY.mjs.map +1 -0
  33. package/dist/read-song-CSIhaAEB.mjs +122 -0
  34. package/dist/read-song-CSIhaAEB.mjs.map +1 -0
  35. package/dist/run-main-Bf32CgzU.mjs +26 -0
  36. package/dist/run-main-Bf32CgzU.mjs.map +1 -0
  37. package/dist/song-3Zm9g84K.d.mts +1478 -0
  38. package/dist/song-CYFBSTbH.mjs +387 -0
  39. package/dist/song-CYFBSTbH.mjs.map +1 -0
  40. package/dist/song-report.mjs +351 -0
  41. package/dist/song-report.mjs.map +1 -0
  42. package/dist/ticks-CXehHP2w.mjs +27 -0
  43. package/dist/ticks-CXehHP2w.mjs.map +1 -0
  44. package/dist/transform-DQm5wTlA.mjs +489 -0
  45. package/dist/transform-DQm5wTlA.mjs.map +1 -0
  46. package/dist/vite.d.mts +3 -0
  47. package/dist/vite.mjs +128 -0
  48. package/dist/vite.mjs.map +1 -0
  49. package/dist/write-CS-ZjoQB.mjs +746 -0
  50. package/dist/write-CS-ZjoQB.mjs.map +1 -0
  51. package/package.json +127 -6
  52. package/skills/read-fumx/SKILL.md +86 -0
  53. package/skills/use-fumx-tools/SKILL.md +65 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"midi-to-fumx.mjs","names":["INDENT","taggedError","NONE","NEXT","Arr","Rec","Arr","Rec","Str","NONE","NEXT","Arr","controlsOf","Rec","NONE","NEXT","FULL","DEFAULT_RELEASE","DECIMALS","Arr","Rec","releaseOf","Arr","NONE","FULL","Arr","Str","NONE","NEXT","Arr","NEXT","headOf","cellsOf","Arr","Rec","NONE","NEXT","Arr","DEFAULT_RELEASE","SINGLE","Arr","Arr","NONE","NEXT","Arr","Rec","Arr","Rec","taggedError","Arr"],"sources":["../src/app/convert-command.ts","../src/entities/timeline/model/general-midi.ts","../src/entities/timeline/model/groups.ts","../src/entities/timeline/model/names.ts","../src/entities/timeline/model/plan.ts","../src/entities/timeline/model/tempo-units.ts","../src/entities/timeline/model/compare.ts","../src/entities/timeline/model/events.ts","../src/entities/timeline/model/cells.ts","../src/entities/timeline/model/layout.ts","../src/entities/timeline/model/control-lines.ts","../src/entities/timeline/model/mix-lines.ts","../src/entities/timeline/model/voice-lines.ts","../src/entities/timeline/model/write.ts","../src/features/convert-midi/model/channel.ts","../src/features/convert-midi/model/timeline.ts","../src/features/convert-midi/model/convert.ts","../src/app/round-trip.ts","../src/app/midi-to-fumx.ts","../bin/midi-to-fumx.ts"],"sourcesContent":["import { runMain } from \"@r_masseater/node-main\";\nimport { Console, Effect, FileSystem, Option, Path, Schema } from \"effect\";\nimport { Argument, Command, Flag } from \"effect/cli\";\n\nimport type { Converted } from \"./round-trip.ts\";\n\nconst INDENT = 2;\n\nconst taggedError = Schema.TaggedError;\n\nclass Mismatch extends taggedError<Mismatch, { readonly brand: unique symbol }>()(\n \"Mismatch\",\n { message: Schema.String },\n { identifier: \"Mismatch\" },\n) {}\n\nconst encodeSummary = Schema.encodeUnknownEffect(\n Schema.fromJsonString(Schema.Unknown, { space: INDENT }),\n);\n\nexport interface Source {\n readonly bytes: Uint8Array;\n readonly title: string;\n readonly path: string;\n}\n\nexport interface ConvertCommand<Failure> {\n readonly name: string;\n readonly input: string;\n readonly source: string;\n readonly convert: (source: Source) => Effect.Effect<Converted, Failure>;\n}\n\nexport const convertMain = <Failure>(spec: ConvertCommand<Failure>): void => {\n const convertFile = Effect.fn(\"convertFile\")(function* convertFile(\n file: string,\n out: Option.Option<string>,\n ) {\n const fileSystem = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const input = path.resolve(file);\n const parsed = path.parse(input);\n const target = Option.match(out, {\n onNone: () => path.join(parsed.dir, `${parsed.name}.fumx`),\n onSome: (given) => path.resolve(given),\n });\n const bytes = yield* fileSystem.readFile(input);\n const converted = yield* spec.convert({ bytes, title: parsed.name, path: target });\n yield* fileSystem.writeFileString(target, converted.text);\n return { output: target, comparison: converted.comparison, adjustments: converted.adjustments };\n });\n const command = Command.make(\n spec.name,\n {\n file: Argument.String(\"file\").pipe(Argument.withDescription(spec.input)),\n out: Flag.String(\"out\").pipe(\n Flag.withDescription(\n `Where to write the .fumx file; defaults to the ${spec.source}'s name with .fumx`,\n ),\n Flag.optional,\n ),\n },\n ({ file, out }) =>\n convertFile(file, out).pipe(\n Effect.tap((summary) => Effect.flatMap(encodeSummary(summary), Console.log)),\n Effect.filterOrFail(\n (summary) => summary.comparison.matches,\n () =>\n Mismatch.make({\n message: `The written .fumx does not reproduce every event of the ${spec.source}`,\n }),\n ),\n Effect.asVoid,\n ),\n );\n runMain(spec.name)(Command.run(command, { version: \"0.0.0\" }));\n};\n","export const PROGRAMS = [\n \"acoustic-grand-piano\",\n \"bright-acoustic-piano\",\n \"electric-grand-piano\",\n \"honky-tonk-piano\",\n \"electric-piano-1\",\n \"electric-piano-2\",\n \"harpsichord\",\n \"clavinet\",\n \"celesta\",\n \"glockenspiel\",\n \"music-box\",\n \"vibraphone\",\n \"marimba\",\n \"xylophone\",\n \"tubular-bells\",\n \"dulcimer\",\n \"drawbar-organ\",\n \"percussive-organ\",\n \"rock-organ\",\n \"church-organ\",\n \"reed-organ\",\n \"accordion\",\n \"harmonica\",\n \"tango-accordion\",\n \"acoustic-guitar-nylon\",\n \"acoustic-guitar-steel\",\n \"electric-guitar-jazz\",\n \"electric-guitar-clean\",\n \"electric-guitar-muted\",\n \"overdriven-guitar\",\n \"distortion-guitar\",\n \"guitar-harmonics\",\n \"acoustic-bass\",\n \"electric-bass-finger\",\n \"electric-bass-pick\",\n \"fretless-bass\",\n \"slap-bass-1\",\n \"slap-bass-2\",\n \"synth-bass-1\",\n \"synth-bass-2\",\n \"violin\",\n \"viola\",\n \"cello\",\n \"contrabass\",\n \"tremolo-strings\",\n \"pizzicato-strings\",\n \"orchestral-harp\",\n \"timpani\",\n \"string-ensemble-1\",\n \"string-ensemble-2\",\n \"synth-strings-1\",\n \"synth-strings-2\",\n \"choir-aahs\",\n \"voice-oohs\",\n \"synth-voice\",\n \"orchestra-hit\",\n \"trumpet\",\n \"trombone\",\n \"tuba\",\n \"muted-trumpet\",\n \"french-horn\",\n \"brass-section\",\n \"synth-brass-1\",\n \"synth-brass-2\",\n \"soprano-sax\",\n \"alto-sax\",\n \"tenor-sax\",\n \"baritone-sax\",\n \"oboe\",\n \"english-horn\",\n \"bassoon\",\n \"clarinet\",\n \"piccolo\",\n \"flute\",\n \"recorder\",\n \"pan-flute\",\n \"blown-bottle\",\n \"shakuhachi\",\n \"whistle\",\n \"ocarina\",\n \"lead-1-square\",\n \"lead-2-sawtooth\",\n \"lead-3-calliope\",\n \"lead-4-chiff\",\n \"lead-5-charang\",\n \"lead-6-voice\",\n \"lead-7-fifths\",\n \"lead-8-bass-and-lead\",\n \"pad-1-new-age\",\n \"pad-2-warm\",\n \"pad-3-polysynth\",\n \"pad-4-choir\",\n \"pad-5-bowed\",\n \"pad-6-metallic\",\n \"pad-7-halo\",\n \"pad-8-sweep\",\n \"fx-1-rain\",\n \"fx-2-soundtrack\",\n \"fx-3-crystal\",\n \"fx-4-atmosphere\",\n \"fx-5-brightness\",\n \"fx-6-goblins\",\n \"fx-7-echoes\",\n \"fx-8-sci-fi\",\n \"sitar\",\n \"banjo\",\n \"shamisen\",\n \"koto\",\n \"kalimba\",\n \"bagpipe\",\n \"fiddle\",\n \"shanai\",\n \"tinkle-bell\",\n \"agogo\",\n \"steel-drums\",\n \"woodblock\",\n \"taiko-drum\",\n \"melodic-tom\",\n \"synth-drum\",\n \"reverse-cymbal\",\n \"guitar-fret-noise\",\n \"breath-noise\",\n \"seashore\",\n \"bird-tweet\",\n \"telephone-ring\",\n \"helicopter\",\n \"applause\",\n \"gunshot\",\n] as const;\n\nexport const FIRST_DRUM = 35;\n\nexport const DRUMS = [\n \"acoustic-bass-drum\",\n \"bass-drum-1\",\n \"side-stick\",\n \"acoustic-snare\",\n \"hand-clap\",\n \"electric-snare\",\n \"low-floor-tom\",\n \"closed-hi-hat\",\n \"high-floor-tom\",\n \"pedal-hi-hat\",\n \"low-tom\",\n \"open-hi-hat\",\n \"low-mid-tom\",\n \"hi-mid-tom\",\n \"crash-cymbal-1\",\n \"high-tom\",\n \"ride-cymbal-1\",\n \"chinese-cymbal\",\n \"ride-bell\",\n \"tambourine\",\n \"splash-cymbal\",\n \"cowbell\",\n \"crash-cymbal-2\",\n \"vibraslap\",\n \"ride-cymbal-2\",\n \"hi-bongo\",\n \"low-bongo\",\n \"mute-hi-conga\",\n \"open-hi-conga\",\n \"low-conga\",\n \"high-timbale\",\n \"low-timbale\",\n \"high-agogo\",\n \"low-agogo\",\n \"cabasa\",\n \"maracas\",\n \"short-whistle\",\n \"long-whistle\",\n \"short-guiro\",\n \"long-guiro\",\n \"claves\",\n \"hi-wood-block\",\n \"low-wood-block\",\n \"mute-cuica\",\n \"open-cuica\",\n \"mute-triangle\",\n \"open-triangle\",\n] as const;\n\nexport const DRUM_CHANNEL = 9;\n","import { Array as Arr, Option, Order, Record as Rec, pipe } from \"effect\";\n\nimport type { From } from \"#/shared/lib/from.ts\";\n\nimport type { Part, TimelineNote } from \"./events.ts\";\nimport { DRUM_CHANNEL } from \"./general-midi.ts\";\n\nconst NONE = 0;\nconst NEXT = 1;\n\nexport const isDrumPart: From<Part, boolean> = (part) => part.channel === DRUM_CHANNEL;\n\nexport interface Group {\n readonly start: number;\n readonly end: number;\n readonly midis: readonly number[];\n readonly velocity: number;\n readonly release: number;\n readonly lyric: Option.Option<string>;\n}\n\nexport type Line = readonly Group[];\n\nconst chordKeyOf: From<TimelineNote, string> = (note) =>\n `${String(note.tick)}:${String(note.end)}:${String(note.velocity)}:${String(note.release)}`;\n\nconst groupOf: From<readonly TimelineNote[], Option.Option<Group>> = (notes) =>\n pipe(\n Arr.head(notes),\n Option.map((first) => ({\n start: first.tick,\n end: first.end,\n midis: pipe(\n notes,\n Arr.map((note) => note.midi),\n ),\n velocity: first.velocity,\n release: first.release,\n lyric: Option.none(),\n })),\n );\n\nconst stackedOf: From<readonly TimelineNote[], readonly (readonly TimelineNote[])[]> = (chord) =>\n pipe(\n chord,\n Arr.map((note, index) => ({\n note,\n layer: pipe(\n Arr.take(chord, index),\n Arr.countBy((earlier) => earlier.midi === note.midi),\n ),\n })),\n Arr.groupBy(({ layer }) => String(layer)),\n Rec.values,\n Arr.map((layer) =>\n pipe(\n layer,\n Arr.map(({ note }) => note),\n ),\n ),\n );\n\nconst chordsOf: From<Part, readonly (readonly TimelineNote[])[]> = (part) => {\n if (isDrumPart(part)) {\n return pipe(\n part.notes,\n Arr.map((note) => [note]),\n );\n }\n return pipe(part.notes, Arr.groupBy(chordKeyOf), Rec.values, Arr.flatMap(stackedOf));\n};\n\nconst byStartThenLonger = Order.combine(\n Order.mapInput(Order.Number, (group: Group) => group.start),\n Order.mapInput(Order.flip(Order.Number), (group: Group) => group.end),\n);\n\nconst withLyrics =\n (part: Part): From<readonly Group[], readonly Group[]> =>\n (groups) =>\n pipe(\n groups,\n Arr.map((group, index) => {\n const leads = pipe(\n Arr.get(groups, index - NEXT),\n Option.match({\n onNone: () => true,\n onSome: (previous) => previous.start !== group.start,\n }),\n );\n const lyric = pipe(\n Arr.findFirst(part.lyrics, (candidate) => candidate.tick === group.start),\n Option.filter(() => leads),\n Option.map((found) => found.text),\n );\n return { ...group, lyric };\n }),\n );\n\nexport const groupsOf: From<Part, readonly Group[]> = (part) => {\n const groups = pipe(chordsOf(part), Arr.map(groupOf), Arr.getSomes);\n return withLyrics(part)(Arr.sort(groups, byStartThenLonger));\n};\n\nconst endOfLine: From<Line, number> = (line) =>\n Option.match(Arr.last(line), { onNone: () => NONE, onSome: (group) => group.end });\n\nconst placeGroup = (lines: readonly Line[], group: Group): readonly Line[] =>\n Option.match(\n Arr.findFirstIndex(lines, (line) => endOfLine(line) <= group.start),\n {\n onNone: () => [...lines, [group]],\n onSome: (index) =>\n pipe(\n lines,\n Arr.map((line, position): Line => {\n if (position === index) {\n return [...line, group];\n }\n return line;\n }),\n ),\n },\n );\n\nexport const linesOf: From<readonly Group[], readonly Line[]> = (groups) =>\n Arr.reduce(groups, [] as readonly Line[], placeGroup);\n","import { Array as Arr, Option, Record as Rec, String as Str, pipe } from \"effect\";\nimport { AstUtils, GrammarAST } from \"langium\";\n\nimport type { From } from \"#/shared/lib/from.ts\";\nimport { FumxTerminals } from \"#generated/langium/ast.ts\";\nimport { FumxGrammar } from \"#generated/langium/grammar.ts\";\n\nconst FIRST_SUFFIX = 2;\n\nconst keywordsIn: From<GrammarAST.Grammar | GrammarAST.AbstractRule, ReadonlySet<string>> = (\n node,\n) =>\n new Set(\n AstUtils.streamAst(node)\n .filter((child): child is GrammarAST.Keyword => GrammarAST.isKeyword(child))\n .map((keyword) => keyword.value),\n );\n\nconst grammar = FumxGrammar();\n\nconst allowedKeywords = pipe(\n grammar.rules,\n Arr.findFirst((rule) => rule.name === \"Name\"),\n Option.match({ onNone: () => new Set<string>(), onSome: keywordsIn }),\n);\n\nconst allKeywords = Arr.fromIterable(keywordsIn(grammar));\n\nconst reserved = new Set(\n pipe(\n allKeywords,\n Arr.filter((keyword) => !allowedKeywords.has(keyword)),\n ),\n);\n\nconst otherTerminals = pipe(\n Rec.toEntries(FumxTerminals),\n Arr.filter(([name]) => name !== \"ID\"),\n Arr.map(([, pattern]) => new RegExp(`^(?:${pattern.source})$`, \"u\")),\n);\n\nconst identifier = new RegExp(`^(?:${FumxTerminals.ID.source})$`, \"u\");\n\nconst isUsable: From<string, boolean> = (name) =>\n identifier.test(name) &&\n !reserved.has(name) &&\n !pipe(\n otherTerminals,\n Arr.some((pattern) => pattern.test(name)),\n );\n\nconst slugOf: From<string, string> = (text) =>\n pipe(\n text,\n Str.normalize(\"NFKD\"),\n Str.toLowerCase,\n Str.replaceAll(/[^a-z0-9]+/gu, \"-\"),\n Str.replaceAll(/^[-0-9]+|-+$/gu, \"\"),\n );\n\nexport const nameFrom: From<readonly string[], string> = (candidates) =>\n pipe(\n candidates,\n Arr.map(slugOf),\n Arr.findFirst(isUsable),\n Option.getOrElse(() => \"part\"),\n );\n\nexport const uniqueAmong: From<ReadonlySet<string>, From<string, string>> = (taken) => (name) =>\n pipe(\n Arr.range(FIRST_SUFFIX, taken.size + FIRST_SUFFIX),\n Arr.map((suffix) => `${name}-${String(suffix)}`),\n Arr.prepend(name),\n Arr.findFirst((candidate) => isUsable(candidate) && !taken.has(candidate)),\n Option.getOrElse(() => `${name}-${String(taken.size)}`),\n );\n","import { Array as Arr, Option, Order, Record as Rec, pipe } from \"effect\";\n\nimport type { From } from \"#/shared/lib/from.ts\";\n\nimport type { Level, Part, Timeline, TimelineControl, TrackMix } from \"./events.ts\";\nimport { DRUMS, FIRST_DRUM, PROGRAMS } from \"./general-midi.ts\";\nimport { groupsOf, isDrumPart, linesOf } from \"./groups.ts\";\nimport type { Line } from \"./groups.ts\";\nimport { nameFrom, uniqueAmong } from \"./names.ts\";\n\nconst NONE = 0;\nconst NEXT = 1;\nconst SHARED = 1;\nconst DEFAULT_PROGRAM = 0;\n\nexport type Source =\n | { readonly kind: \"instrument\"; readonly instrument: string; readonly program: number }\n | { readonly kind: \"kit\" };\n\nexport interface PlannedPart {\n readonly part: Part;\n readonly name: string;\n readonly source: Source;\n readonly lines: readonly Line[];\n readonly controls: readonly TimelineControl[];\n readonly mix: TrackMix;\n}\n\nexport interface PlannedBus {\n readonly name: string;\n readonly level: Level;\n}\n\nexport interface Plan {\n readonly parts: readonly PlannedPart[];\n readonly buses: readonly PlannedBus[];\n readonly instruments: ReadonlyMap<number, string>;\n readonly drumVoices: ReadonlyMap<number, string>;\n}\n\nconst drumNameOf: From<number, string> = (midi) =>\n Option.getOrElse(Arr.get(DRUMS, midi - FIRST_DRUM), () => `note-${String(midi)}`);\n\nconst programNameOf: From<number, string> = (program) =>\n Option.getOrElse(Arr.get(PROGRAMS, program), () => `program-${String(program)}`);\n\nexport const controllerKeyOf: From<Pick<TimelineControl, \"controller\">, string> = ({\n controller,\n}) => {\n if (controller.kind === \"cc\") {\n return `cc ${String(controller.number)}`;\n }\n if (controller.kind === \"pressure\") {\n return Option.match(controller.midi, {\n onNone: () => \"pressure\",\n onSome: (midi) => `pressure ${String(midi)}`,\n });\n }\n return controller.kind;\n};\n\nconst isLastAtTick: From<readonly TimelineControl[], From<number, boolean>> =\n (controls) => (index) =>\n pipe(\n Option.all([Arr.get(controls, index), Arr.get(controls, index + NEXT)]),\n Option.match({\n onNone: () => true,\n onSome: ([control, next]) =>\n next.tick !== control.tick || controllerKeyOf(next) !== controllerKeyOf(control),\n }),\n );\n\nconst byControllerThenTick = Order.combine(\n Order.mapInput(Order.String, controllerKeyOf),\n Order.mapInput(Order.Number, (control: TimelineControl) => control.tick),\n);\n\nconst controlsOf: From<Part, readonly TimelineControl[]> = (part) => {\n const drumProgram = pipe(\n part.program,\n Option.filter(() => isDrumPart(part)),\n Option.map((value): TimelineControl => ({\n tick: NONE,\n controller: { kind: \"program\" },\n value,\n })),\n Option.toArray,\n );\n const sorted = Arr.sort([...drumProgram, ...part.controls], byControllerThenTick);\n return pipe(\n sorted,\n Arr.filter((_control, index) => isLastAtTick(sorted)(index)),\n );\n};\n\nconst programOf: From<Part, number> = (part) =>\n Option.getOrElse(part.program, () => DEFAULT_PROGRAM);\n\nconst labelOf: From<Part, string> = (part) => Option.getOrElse(part.name, () => \"\");\n\nconst instrumentsOf: From<readonly Part[], ReadonlyMap<number, string>> = (parts) =>\n new Map(\n pipe(\n parts,\n Arr.filter((part) => !isDrumPart(part)),\n Arr.map(programOf),\n Arr.dedupe,\n Arr.map((program) => [program, nameFrom([programNameOf(program)])] as const),\n ),\n );\n\nconst drumVoicesOf: From<readonly Part[], ReadonlyMap<number, string>> = (parts) => {\n const midis = pipe(\n parts,\n Arr.filter(isDrumPart),\n Arr.flatMap((part) => part.notes),\n Arr.map((note) => note.midi),\n Arr.dedupe,\n );\n return new Map(\n pipe(\n Arr.sort(midis, Order.Number),\n Arr.map((midi) => [midi, drumNameOf(midi)] as const),\n ),\n );\n};\n\nconst channelledOf: From<ReadonlySet<string>, From<Part, string>> = (shared) => (part) => {\n const label = labelOf(part);\n if (shared.has(label)) {\n return `${label} ch${String(part.channel + NEXT)}`;\n }\n return label;\n};\n\nconst fallbackOf: From<Part, string> = (part) => {\n if (isDrumPart(part)) {\n return \"drums\";\n }\n return programNameOf(programOf(part));\n};\n\nconst candidatesOf: From<ReadonlySet<string>, From<Part, readonly string[]>> =\n (shared) => (part) => [\n channelledOf(shared)(part),\n fallbackOf(part),\n `track ${String(part.track)}`,\n ];\n\nconst sharedLabelsOf: From<readonly Part[], ReadonlySet<string>> = (parts) =>\n new Set(\n pipe(\n parts,\n Arr.groupBy(labelOf),\n Rec.filter((same) => same.length > SHARED),\n Rec.keys,\n ),\n );\n\nconst sourceOf: From<ReadonlyMap<number, string>, From<Part, Source>> = (instruments) => (part) => {\n if (isDrumPart(part)) {\n return { kind: \"kit\" };\n }\n const program = programOf(part);\n return { kind: \"instrument\", instrument: instruments.get(program) ?? \"\", program };\n};\n\nconst namesOf: From<readonly PlannedPart[], ReadonlySet<string>> = (planned) =>\n new Set(\n pipe(\n planned,\n Arr.map((done) => done.name),\n ),\n );\n\ninterface Naming {\n readonly instruments: Plan[\"instruments\"];\n readonly candidates: From<Part, readonly string[]>;\n readonly mixes: Timeline[\"mix\"][\"tracks\"];\n}\n\nconst UNMIXED: TrackMix = {\n level: { decibels: NONE, pan: NONE, muted: false },\n sends: [],\n envelopes: [],\n};\n\ntype Reducer<State, Item> = (state: State, item: Item) => State;\n\nconst NO_PARTS: readonly PlannedPart[] = [];\n\nconst nextPart: From<Naming, Reducer<readonly PlannedPart[], Part>> =\n (naming) => (planned, part) => {\n const name = uniqueAmong(namesOf(planned))(nameFrom(naming.candidates(part)));\n return Arr.append(planned, {\n part,\n name,\n source: sourceOf(naming.instruments)(part),\n lines: linesOf(groupsOf(part)),\n controls: controlsOf(part),\n mix: naming.mixes.get(part.track) ?? UNMIXED,\n });\n };\n\ntype BusNaming = Readonly<{ taken: ReadonlySet<string>; buses: Timeline[\"mix\"][\"buses\"] }>;\n\nconst busesOf: From<BusNaming, readonly PlannedBus[]> = ({ taken, buses }) => {\n const used = new Set(taken);\n const named: PlannedBus[] = [];\n for (const [index, bus] of buses.entries()) {\n const name = uniqueAmong(used)(\n nameFrom([...Option.toArray(bus.name), `bus ${String(index + NEXT)}`]),\n );\n used.add(name);\n named.push({ name, level: bus.level });\n }\n return named;\n};\n\nexport const planOf: From<Timeline, Plan> = (timeline) => {\n const instruments = instrumentsOf(timeline.parts);\n const candidates = candidatesOf(sharedLabelsOf(timeline.parts));\n const parts = Arr.reduce(\n timeline.parts,\n NO_PARTS,\n nextPart({ instruments, candidates, mixes: timeline.mix.tracks }),\n );\n return {\n parts,\n buses: busesOf({ taken: namesOf(parts), buses: timeline.mix.buses }),\n instruments,\n drumVoices: drumVoicesOf(timeline.parts),\n };\n};\n","import type { From } from \"#/shared/lib/from.ts\";\n\nconst MICROSECONDS_PER_MINUTE = 60_000_000;\n\nexport const bpmOf: From<number, number> = (microseconds) => MICROSECONDS_PER_MINUTE / microseconds;\n\nexport const microsecondsOf: From<number, number> = (bpm) =>\n Math.round(MICROSECONDS_PER_MINUTE / bpm);\n","import { Array as Arr, Option, Record as Rec, pipe } from \"effect\";\n\nimport type { Song } from \"#/entities/song/@x/timeline.ts\";\nimport type { From } from \"#/shared/lib/from.ts\";\n\nimport type { LaidBar } from \"./layout.ts\";\nimport { controllerKeyOf } from \"./plan.ts\";\nimport type { Plan } from \"./plan.ts\";\nimport { microsecondsOf } from \"./tempo-units.ts\";\n\nconst NONE = 0;\nconst NEXT = 1;\nconst UNKNOWN = -1;\nconst FULL = 127;\nconst DEFAULT_RELEASE = 64;\nconst DECIMALS = 9;\nconst SHOWN = 20;\n\nexport interface Tally {\n readonly expected: number;\n readonly actual: number;\n readonly missing: readonly string[];\n readonly extra: readonly string[];\n}\n\nexport interface Comparison {\n readonly notes: Tally;\n readonly controls: Tally;\n readonly tempo: Tally;\n readonly lyrics: Tally;\n readonly marks: Tally;\n readonly matches: boolean;\n}\n\nconst countsOf: From<readonly string[], Readonly<Record<string, number>>> = (keys) =>\n pipe(\n keys,\n Arr.groupBy((key) => key),\n Rec.map((same) => same.length),\n );\n\nconst surplusOf =\n (\n over: Readonly<Record<string, number>>,\n ): From<Readonly<Record<string, number>>, readonly string[]> =>\n (under) =>\n pipe(\n Rec.toEntries(over),\n Arr.flatMap(([key, count]) => {\n const left = count - Option.getOrElse(Rec.get(under, key), () => NONE);\n if (left > NONE) {\n return Arr.makeBy(left, () => key);\n }\n return [];\n }),\n Arr.take(SHOWN),\n );\n\nconst tallyOf = (expected: readonly string[], actual: readonly string[]): Tally => {\n const wanted = countsOf(expected);\n const found = countsOf(actual);\n return {\n expected: expected.length,\n actual: actual.length,\n missing: surplusOf(wanted)(found),\n extra: surplusOf(found)(wanted),\n };\n};\n\nconst byteOf: From<number, number> = (share) => Math.round(share * FULL);\n\nconst releaseOf: From<Option.Option<number>, number> = (release) =>\n Option.match(release, { onNone: () => DEFAULT_RELEASE, onSome: byteOf });\n\nconst keyOf: From<readonly (string | number)[], string> = (parts) =>\n pipe(parts, Arr.map(String), Arr.join(\" \"));\n\nconst expectedNotesOf: From<Plan, readonly string[]> = (plan) =>\n pipe(\n plan.parts,\n Arr.flatMap((planned) =>\n pipe(\n planned.part.notes,\n Arr.map((note) =>\n keyOf([\n planned.name,\n note.tick,\n note.end - note.tick,\n note.midi,\n note.velocity,\n note.release,\n ]),\n ),\n ),\n ),\n );\n\nconst actualNotesOf: From<Omit<CompareInput, \"bars\">, readonly string[]> = ({ plan, song }) => {\n const voices = new Map(\n pipe(\n Arr.fromIterable(plan.drumVoices),\n Arr.map(([midi, name]) => [name, midi] as const),\n ),\n );\n const notes = pipe(\n song.notes,\n Arr.map((note) =>\n keyOf([\n note.track,\n note.start,\n note.length,\n note.midi,\n byteOf(note.velocity),\n releaseOf(note.releaseVelocity),\n ]),\n ),\n );\n const hits = pipe(\n song.hits,\n Arr.map((hit) =>\n keyOf([\n hit.track,\n hit.start,\n hit.length,\n voices.get(hit.voice) ?? UNKNOWN,\n byteOf(hit.velocity),\n releaseOf(hit.releaseVelocity),\n ]),\n ),\n );\n return [...notes, ...hits];\n};\n\nconst rounded: From<number, string> = (value) => String(Number(value.toFixed(DECIMALS)));\n\nconst expectedControlsOf: From<Plan, readonly string[]> = (plan) =>\n pipe(\n plan.parts,\n Arr.flatMap((planned) =>\n pipe(\n planned.controls,\n Arr.map((control) =>\n keyOf([planned.name, controllerKeyOf(control), control.tick, rounded(control.value)]),\n ),\n ),\n ),\n );\n\nconst actualControlsOf: From<Song, readonly string[]> = (song) =>\n pipe(\n song.controls,\n Arr.map((control) =>\n keyOf([\n control.track,\n controllerKeyOf({ controller: control.controller }),\n control.start,\n rounded(control.value),\n ]),\n ),\n );\n\ninterface TempoPoint {\n readonly tick: number;\n readonly microseconds: number;\n readonly target: Option.Option<number>;\n}\n\nconst FLAT = \"-\";\n\nconst isFlatRepeat = (point: TempoPoint, previous: TempoPoint): boolean =>\n Option.isNone(point.target) &&\n Option.isNone(previous.target) &&\n previous.microseconds === point.microseconds;\n\nconst changesOf: From<readonly TempoPoint[], readonly string[]> = (points) =>\n pipe(\n points,\n Arr.filter((point, index) =>\n pipe(\n Arr.get(points, index - NEXT),\n Option.match({\n onNone: () => true,\n onSome: (previous) => !isFlatRepeat(point, previous),\n }),\n ),\n ),\n Arr.map(({ tick, microseconds, target }) =>\n keyOf([tick, microseconds, Option.getOrElse(target, () => FLAT)]),\n ),\n );\n\nconst expectedTempoOf: From<readonly LaidBar[], readonly string[]> = (bars) =>\n changesOf(\n pipe(\n bars,\n Arr.flatMap((bar) =>\n pipe(\n bar.tempo,\n Arr.map((step): TempoPoint => ({\n tick: bar.start + step.offset,\n microseconds: step.microseconds,\n target: step.target,\n })),\n ),\n ),\n ),\n );\n\nconst barPointsOf: From<Song[\"bars\"][number], readonly TempoPoint[]> = (bar) => {\n if (Arr.isReadonlyArrayNonEmpty(bar.tempoSteps)) {\n return pipe(\n bar.tempoSteps,\n Arr.map((step): TempoPoint => ({\n tick: bar.start + step.offset,\n microseconds: microsecondsOf(step.bpm),\n target: pipe(step.target, Option.map(microsecondsOf)),\n })),\n );\n }\n return [{ tick: bar.start, microseconds: microsecondsOf(bar.tempo.bpm), target: Option.none() }];\n};\n\nconst actualTempoOf: From<Song, readonly string[]> = (song) =>\n changesOf(pipe(song.bars, Arr.flatMap(barPointsOf)));\n\nconst expectedLyricsOf: From<Plan, readonly string[]> = (plan) =>\n pipe(\n plan.parts,\n Arr.flatMap((planned) =>\n pipe(\n planned.lines,\n Arr.flatten,\n Arr.flatMap((group) =>\n pipe(\n group.lyric,\n Option.map((text) => keyOf([planned.name, group.start, text])),\n Option.toArray,\n ),\n ),\n ),\n ),\n );\n\nconst syllableKeyOf: From<Song[\"notes\"][number], Option.Option<string>> = (note) =>\n pipe(\n note.lyric,\n Option.flatMap((lyric) => {\n if (lyric.kind === \"syllable\") {\n return Option.some(keyOf([note.track, note.start, lyric.text]));\n }\n return Option.none();\n }),\n );\n\nconst actualLyricsOf: From<Song, readonly string[]> = (song) =>\n pipe(song.notes, Arr.map(syllableKeyOf), Arr.getSomes, Arr.dedupe);\n\nconst expectedMarksOf: From<readonly LaidBar[], readonly string[]> = (bars) =>\n pipe(\n bars,\n Arr.filter((bar) => Arr.isReadonlyArrayNonEmpty(bar.marks)),\n Arr.map((bar) => keyOf([bar.start, Arr.join(bar.marks, \" / \")])),\n );\n\nconst actualMarksOf: From<Song, readonly string[]> = (song) =>\n pipe(\n song.bars,\n Arr.map((bar) =>\n pipe(\n bar.mark,\n Option.map((mark) => keyOf([bar.start, mark])),\n ),\n ),\n Arr.getSomes,\n );\n\nconst isClean: From<Tally, boolean> = (tally) =>\n !Arr.isReadonlyArrayNonEmpty(tally.missing) && !Arr.isReadonlyArrayNonEmpty(tally.extra);\n\nexport interface CompareInput {\n readonly plan: Plan;\n readonly bars: readonly LaidBar[];\n readonly song: Song;\n}\n\nexport const compareWithSong: From<CompareInput, Comparison> = ({ plan, bars, song }) => {\n const tallies = {\n notes: tallyOf(expectedNotesOf(plan), actualNotesOf({ plan, song })),\n controls: tallyOf(expectedControlsOf(plan), actualControlsOf(song)),\n tempo: tallyOf(expectedTempoOf(bars), actualTempoOf(song)),\n lyrics: tallyOf(expectedLyricsOf(plan), actualLyricsOf(song)),\n marks: tallyOf(expectedMarksOf(bars), actualMarksOf(song)),\n };\n return { ...tallies, matches: pipe(Rec.values(tallies), Arr.every(isClean)) };\n};\n","import { Array as Arr, Order } from \"effect\";\nimport type { Option } from \"effect\";\n\nimport type { Controller, MixerParameter } from \"#/entities/song/@x/timeline.ts\";\n\nexport interface Timed {\n readonly tick: number;\n}\n\nexport interface TimelineNote extends Timed {\n readonly end: number;\n readonly midi: number;\n readonly velocity: number;\n readonly release: number;\n}\n\nexport interface TimelineControl extends Timed {\n readonly controller: Controller;\n readonly value: number;\n}\n\nexport interface Text extends Timed {\n readonly text: string;\n}\n\nexport interface Part {\n readonly track: number;\n readonly channel: number;\n readonly name: Option.Option<string>;\n readonly program: Option.Option<number>;\n readonly notes: readonly TimelineNote[];\n readonly controls: readonly TimelineControl[];\n readonly lyrics: readonly Text[];\n}\n\nexport interface Meter extends Timed {\n readonly numerator: number;\n readonly denominator: number;\n}\n\nexport interface TempoChange extends Timed {\n readonly microseconds: number;\n readonly target: Option.Option<number>;\n}\n\nexport interface Level {\n readonly decibels: number;\n readonly pan: number;\n readonly muted: boolean;\n}\n\nexport interface TrackSend {\n readonly bus: number;\n readonly amount: number;\n}\n\nexport type MixParameter = MixerParameter;\n\nexport interface MixPoint extends Timed {\n readonly value: number;\n}\n\nexport interface Envelope {\n readonly parameter: MixParameter;\n readonly points: readonly MixPoint[];\n}\n\nexport interface TrackMix {\n readonly level: Level;\n readonly sends: readonly TrackSend[];\n readonly envelopes: readonly Envelope[];\n}\n\nexport interface BusMix {\n readonly name: Option.Option<string>;\n readonly level: Level;\n}\n\nexport interface Mix {\n readonly tracks: ReadonlyMap<number, TrackMix>;\n readonly buses: readonly BusMix[];\n}\n\nexport const NO_MIX: Mix = { tracks: new Map(), buses: [] };\n\nexport interface Timeline {\n readonly title: Option.Option<string>;\n readonly end: number;\n readonly offGrid: number;\n readonly tempos: readonly TempoChange[];\n readonly meters: readonly Meter[];\n readonly markers: readonly Text[];\n readonly parts: readonly Part[];\n readonly mix: Mix;\n}\n\nconst byTick = Order.mapInput(Order.Number, (timed: Timed) => timed.tick);\n\nexport const sortedByTick = <Item extends Timed>(items: readonly Item[]): readonly Item[] =>\n Arr.sort(items, byTick);\n\nconst byTickThenPitch = Order.combine(\n Order.mapInput(Order.Number, (note: TimelineNote) => note.tick),\n Order.mapInput(Order.Number, (note: TimelineNote) => note.midi),\n);\n\nexport const sortedNotes = (notes: readonly TimelineNote[]): readonly TimelineNote[] =>\n Arr.sort(notes, byTickThenPitch);\n","import { Array as Arr, Option, String as Str, pipe } from \"effect\";\nimport { Midi } from \"tonal\";\n\nimport type { From } from \"#/shared/lib/from.ts\";\nimport { fractionOf } from \"#/shared/lib/ticks.ts\";\n\nconst NONE = 0;\nconst FULL = 127;\nconst SHARE_DECIMALS = 3;\nconst SEMITONE_DECIMALS = 12;\nconst LAST = 1;\n\nexport interface Cell {\n readonly head: string;\n readonly attributes: readonly string[];\n readonly length: number;\n}\n\nexport const durationText: From<number, string> = (length) => {\n if (length === NONE) {\n return \"0/1\";\n }\n return fractionOf(length);\n};\n\nexport const restCell: From<number, Cell> = (length) => ({ head: \"rest\", attributes: [], length });\n\nexport const restsOf: From<number, readonly Cell[]> = (length) => {\n if (length > NONE) {\n return [restCell(length)];\n }\n return [];\n};\n\nconst isRest: From<Cell, boolean> = (cell) => cell.head === \"rest\";\n\nconst mergeRests = (merged: readonly Cell[], cell: Cell): readonly Cell[] =>\n pipe(\n Arr.last(merged),\n Option.filter((previous) => isRest(previous) && isRest(cell)),\n Option.match({\n onNone: () => [...merged, cell],\n onSome: (previous) => [\n ...Arr.dropRight(merged, LAST),\n restCell(previous.length + cell.length),\n ],\n }),\n );\n\nconst NO_CELLS: readonly Cell[] = [];\n\nconst cellText: From<Cell, string> = (cell) =>\n Arr.join([cell.head, durationText(cell.length), ...cell.attributes], \" \");\n\nexport const cellsText: From<readonly Cell[], string> = (cells) =>\n pipe(Arr.reduce(cells, NO_CELLS, mergeRests), Arr.map(cellText), Arr.join(\", \"));\n\nexport const quoted: From<string, string> = (text) =>\n `\"${pipe(\n text,\n Str.replaceAll(\"\\\\\", String.raw`\\\\`),\n Str.replaceAll('\"', String.raw`\\\"`),\n Str.replaceAll(\"\\n\", String.raw`\\n`),\n Str.replaceAll(\"\\r\", String.raw`\\r`),\n Str.replaceAll(\"\\t\", String.raw`\\t`),\n )}\"`;\n\nexport const shareText: From<number, string> = (value) =>\n String(Number((value / FULL).toFixed(SHARE_DECIMALS)));\n\nexport const semitoneText: From<number, string> = (value) => {\n const text = String(Number(value.toFixed(SEMITONE_DECIMALS)));\n if (value > NONE) {\n return `+${text}st`;\n }\n return `${text}st`;\n};\n\nexport const pitchText: From<number, string> = (midi) =>\n Midi.midiToNoteName(midi, { sharps: true });\n","import { Array as Arr, Option, pipe } from \"effect\";\n\nimport type { From } from \"#/shared/lib/from.ts\";\nimport { TICKS_PER_WHOLE, fractionOf } from \"#/shared/lib/ticks.ts\";\n\nimport type { Meter, TempoChange, Text, Timeline } from \"./events.ts\";\nimport { bpmOf, microsecondsOf } from \"./tempo-units.ts\";\n\nconst NONE = 0;\nconst NEXT = 1;\nconst QUARTER = 4;\nconst DEFAULT_METER = { numerator: QUARTER, denominator: QUARTER };\nconst DEFAULT_MICROSECONDS = 500_000;\nconst MAX_DECIMALS = 9;\n\nexport interface LaidTempo {\n readonly offset: number;\n readonly length: number;\n readonly microseconds: number;\n readonly target: Option.Option<number>;\n}\n\nexport interface Span {\n readonly start: number;\n readonly length: number;\n}\n\nexport interface LaidBar extends Span {\n readonly meter: string;\n readonly tempo: readonly LaidTempo[];\n readonly marks: readonly string[];\n}\n\ninterface Signature {\n readonly numerator: number;\n readonly denominator: number;\n}\n\nexport const endOfSpan: From<Span, number> = (span) => span.start + span.length;\n\nconst latestAt =\n (tick: number) =>\n <Item extends { readonly tick: number }>(items: readonly Item[]): Option.Option<Item> =>\n pipe(\n items,\n Arr.filter((item) => item.tick <= tick),\n Arr.last,\n );\n\nconst lengthOf: From<Signature, number> = (signature) =>\n (TICKS_PER_WHOLE * signature.numerator) / signature.denominator;\n\nconst meterText =\n (signature: Signature): From<number, string> =>\n (length) => {\n const beats = (length * signature.denominator) / TICKS_PER_WHOLE;\n if (Number.isInteger(beats)) {\n return `${String(beats)}/${String(signature.denominator)}`;\n }\n return fractionOf(length);\n };\n\ninterface Ramp {\n readonly start: TempoChange;\n readonly end: number;\n readonly target: number;\n}\n\nconst rampAt =\n (tempos: readonly TempoChange[]): From<number, Option.Option<Ramp>> =>\n (tick) =>\n pipe(\n latestAt(tick)(tempos),\n Option.flatMap((start) =>\n pipe(\n start.target,\n Option.flatMap((target) =>\n pipe(\n Arr.findFirst(tempos, (tempo) => tempo.tick > start.tick),\n Option.map((next) => ({ start, end: next.tick, target })),\n ),\n ),\n ),\n ),\n );\n\nconst interpolated =\n (ramp: Ramp): From<number, number> =>\n (tick) => {\n const from = bpmOf(ramp.start.microseconds);\n const to = bpmOf(ramp.target);\n const share = (tick - ramp.start.tick) / (ramp.end - ramp.start.tick);\n return microsecondsOf(from + (to - from) * share);\n };\n\nconst rampedAt =\n (tempos: readonly TempoChange[]) =>\n (tick: number, at: number): Option.Option<number> =>\n pipe(\n rampAt(tempos)(tick),\n Option.map((ramp) => interpolated(ramp)(at)),\n );\n\nconst steadyAt =\n (tempos: readonly TempoChange[]): From<number, number> =>\n (tick) =>\n pipe(\n latestAt(tick)(tempos),\n Option.match({\n onNone: () => DEFAULT_MICROSECONDS,\n onSome: (tempo) => tempo.microseconds,\n }),\n );\n\nconst tempoAt =\n (tempos: readonly TempoChange[]): From<number, number> =>\n (tick) =>\n Option.getOrElse(rampedAt(tempos)(tick, tick), () => steadyAt(tempos)(tick));\n\nconst tempoStepsOf =\n (tempos: readonly TempoChange[]): From<Span, readonly LaidTempo[]> =>\n (bar) => {\n const end = endOfSpan(bar);\n const points = [\n bar.start,\n ...pipe(\n tempos,\n Arr.filter((tempo) => tempo.tick > bar.start && tempo.tick < end),\n Arr.map((tempo) => tempo.tick),\n Arr.dedupe,\n ),\n ];\n return pipe(\n points,\n Arr.map((tick, index) => {\n const stepEnd = Option.getOrElse(Arr.get(points, index + NEXT), () => end);\n return {\n offset: tick - bar.start,\n length: stepEnd - tick,\n microseconds: tempoAt(tempos)(tick),\n target: rampedAt(tempos)(tick, stepEnd),\n };\n }),\n );\n };\n\nconst marksOf =\n (markers: readonly Text[]): From<Span, readonly string[]> =>\n (bar) =>\n pipe(\n markers,\n Arr.filter((marker) => marker.tick >= bar.start && marker.tick < endOfSpan(bar)),\n Arr.map((marker) => marker.text),\n );\n\nconst spanAt =\n (meters: readonly Meter[]): From<number, Span & { readonly signature: Signature }> =>\n (start) => {\n const signature = Option.getOrElse(latestAt(start)(meters), () => DEFAULT_METER);\n const full = start + lengthOf(signature);\n const end = pipe(\n Arr.findFirst(meters, (meter) => meter.tick > start),\n Option.match({ onNone: () => full, onSome: (meter) => Math.min(meter.tick, full) }),\n );\n return { start, length: end - start, signature };\n };\n\nexport const barsOf: From<Timeline, readonly LaidBar[]> = (timeline) =>\n Arr.unfold({ start: NONE, first: true }, (cursor) => {\n if (!cursor.first && cursor.start >= timeline.end) {\n return Option.none();\n }\n const span = spanAt(timeline.meters)(cursor.start);\n const bar: LaidBar = {\n start: span.start,\n length: span.length,\n meter: meterText(span.signature)(span.length),\n tempo: tempoStepsOf(timeline.tempos)(span),\n marks: marksOf(timeline.markers)(span),\n };\n return Option.some([bar, { start: endOfSpan(span), first: false }] as const);\n });\n\nexport const bpmText: From<number, string> = (microseconds) => {\n const exact = bpmOf(microseconds);\n const text = pipe(\n Arr.range(NONE, MAX_DECIMALS),\n Arr.map((decimals) => String(Number(exact.toFixed(decimals)))),\n Arr.findFirst((candidate) => microsecondsOf(Number(candidate)) === microseconds),\n Option.getOrElse(() => String(exact)),\n );\n return `${text}bpm`;\n};\n","import { Array as Arr, Option, Record as Rec, pipe } from \"effect\";\n\nimport type { From } from \"#/shared/lib/from.ts\";\n\nimport { cellsText, pitchText, restsOf, semitoneText } from \"./cells.ts\";\nimport type { Cell } from \"./cells.ts\";\nimport type { TimelineControl } from \"./events.ts\";\nimport { endOfSpan } from \"./layout.ts\";\nimport type { Span } from \"./layout.ts\";\nimport { controllerKeyOf } from \"./plan.ts\";\nimport type { PlannedPart } from \"./plan.ts\";\n\nconst NEXT = 1;\n\nconst valueText: From<TimelineControl, string> = (control) => {\n if (control.controller.kind === \"bend\") {\n return semitoneText(control.value);\n }\n return String(control.value);\n};\n\nconst headOf =\n (planned: PlannedPart): From<TimelineControl, string> =>\n ({ controller }) => {\n if (controller.kind === \"pressure\") {\n return Option.match(controller.midi, {\n onNone: () => `${planned.name}.pressure`,\n onSome: (midi) => `${planned.name}.pressure ${pitchText(midi)}`,\n });\n }\n return `${planned.name}.${controllerKeyOf({ controller })}`;\n };\n\nconst cellsOf =\n (bar: Span): From<readonly TimelineControl[], readonly Cell[]> =>\n (controls) => {\n const lead = pipe(\n Arr.head(controls),\n Option.map((first) => first.tick - bar.start),\n Option.toArray,\n Arr.flatMap(restsOf),\n );\n const steps = pipe(\n controls,\n Arr.map((control, index) => ({\n head: valueText(control),\n attributes: [],\n length:\n pipe(\n Arr.get(controls, index + NEXT),\n Option.match({ onNone: () => endOfSpan(bar), onSome: (next) => next.tick }),\n ) - control.tick,\n })),\n );\n return [...lead, ...steps];\n };\n\nexport const controlLinesOf =\n (bar: Span): From<PlannedPart, readonly string[]> =>\n (planned) =>\n pipe(\n planned.controls,\n Arr.filter((control) => control.tick >= bar.start && control.tick < endOfSpan(bar)),\n Arr.groupBy((control: TimelineControl) => controllerKeyOf(control)),\n Rec.values,\n Arr.map((controls) =>\n pipe(\n Arr.head(controls),\n Option.map((first) => `${headOf(planned)(first)}: ${cellsText(cellsOf(bar)(controls))}`),\n ),\n ),\n Arr.getSomes,\n );\n","import { Array as Arr, Option, pipe } from \"effect\";\n\nimport type { From } from \"#/shared/lib/from.ts\";\n\nimport type { Envelope, Level, MixParameter, MixPoint, TrackMix } from \"./events.ts\";\nimport { endOfSpan } from \"./layout.ts\";\nimport type { Span } from \"./layout.ts\";\nimport type { PlannedBus, PlannedPart } from \"./plan.ts\";\n\nconst DECIMALS = 1;\nconst PERCENT = 100;\nconst NONE = 0;\nconst NEXT = 1;\n\nconst amountText = (value: number, unit: string): string => {\n const text = Number(value.toFixed(DECIMALS));\n if (text > NONE) {\n return `+${String(text)}${unit}`;\n }\n return `${String(text)}${unit}`;\n};\n\nconst UNITS: Readonly<Record<MixParameter, From<number, string>>> = {\n volume: (decibels) => amountText(decibels, \"dB\"),\n pan: (pan) => amountText(pan * PERCENT, \"%\"),\n};\n\nconst levelWords: From<Level, readonly string[]> = (level) => [\n ...pipe(\n Option.some(level.decibels),\n Option.filter((decibels) => UNITS.volume(decibels) !== UNITS.volume(NONE)),\n Option.map((decibels) => `volume ${UNITS.volume(decibels)}`),\n Option.toArray,\n ),\n ...pipe(\n Option.some(level.pan),\n Option.filter((pan) => UNITS.pan(pan) !== UNITS.pan(NONE)),\n Option.map((pan) => `pan ${UNITS.pan(pan)}`),\n Option.toArray,\n ),\n ...pipe(\n Option.some(\"mute\"),\n Option.filter(() => level.muted),\n Option.toArray,\n ),\n];\n\nexport type Mixing = Readonly<{ mix: TrackMix; buses: readonly PlannedBus[] }>;\n\nexport const trackMixWords: From<Mixing, readonly string[]> = ({ mix, buses }) => [\n ...levelWords(mix.level),\n ...pipe(\n mix.sends,\n Arr.filter((send) => send.amount > NONE),\n Arr.flatMap((send) =>\n pipe(\n Arr.get(buses, send.bus),\n Option.map((bus) => `send ${bus.name} ${amountText(send.amount * PERCENT, \"%\")}`),\n Option.toArray,\n ),\n ),\n ),\n];\n\nexport const busLineOf: From<PlannedBus, string> = (bus) =>\n Arr.join([\"bus\", bus.name, ...levelWords(bus.level)], \" \");\n\nconst valueAt =\n (points: readonly MixPoint[]): From<number, number> =>\n (tick) => {\n const before = pipe(\n points,\n Arr.filter((point) => point.tick <= tick),\n Arr.last,\n );\n const after = pipe(\n points,\n Arr.findFirst((point) => point.tick > tick),\n );\n return Option.match(before, {\n onNone: () => Option.match(after, { onNone: () => NONE, onSome: (point) => point.value }),\n onSome: (left) =>\n Option.match(after, {\n onNone: () => left.value,\n onSome: (right) =>\n left.value +\n ((right.value - left.value) * (tick - left.tick)) / (right.tick - left.tick),\n }),\n });\n };\n\nconst rampOf =\n (bar: Span, name: string): From<Envelope, Option.Option<string>> =>\n (envelope) => {\n const at = valueAt(envelope.points);\n const unit = UNITS[envelope.parameter];\n const from = unit(at(bar.start));\n const to = unit(at(endOfSpan(bar)));\n return pipe(\n Option.some(`automate ${name}.${envelope.parameter} ${from} -> ${to} over 1bar`),\n Option.filter(() => from !== to),\n );\n };\n\nexport const automationLinesOf =\n (bar: Span): From<PlannedPart, readonly string[]> =>\n (planned) =>\n pipe(\n planned.mix.envelopes,\n Arr.filter((envelope) => Arr.length(envelope.points) > NEXT),\n Arr.map(rampOf(bar, planned.name)),\n Arr.getSomes,\n );\n","import { Array as Arr, Option, Order, pipe } from \"effect\";\n\nimport type { From } from \"#/shared/lib/from.ts\";\n\nimport { cellsText, pitchText, quoted, restsOf, shareText } from \"./cells.ts\";\nimport type { Cell } from \"./cells.ts\";\nimport type { Group, Line } from \"./groups.ts\";\nimport { endOfSpan } from \"./layout.ts\";\nimport type { Span } from \"./layout.ts\";\nimport type { Plan, PlannedPart } from \"./plan.ts\";\n\nconst FULL = 127;\nconst DEFAULT_RELEASE = 64;\nconst SINGLE = 1;\n\ninterface Segment {\n readonly group: Group;\n readonly start: number;\n readonly end: number;\n}\n\ninterface VoiceText {\n readonly text: string;\n readonly continues: boolean;\n}\n\nconst touches =\n (bar: Span): From<Group, boolean> =>\n (group) => {\n if (group.end === group.start) {\n return group.start >= bar.start && group.start < endOfSpan(bar);\n }\n return group.start < endOfSpan(bar) && group.end > bar.start;\n };\n\nconst segmentOf =\n (bar: Span): From<Group, Segment> =>\n (group) => ({\n group,\n start: Math.max(group.start, bar.start),\n end: Math.min(group.end, endOfSpan(bar)),\n });\n\nconst pitchesText: From<readonly number[], string> = (midis) => {\n if (midis.length === SINGLE) {\n return Arr.join(pipe(midis, Arr.map(pitchText)), \"\");\n }\n return `[${Arr.join(pipe(midis, Arr.map(pitchText)), \" \")}]`;\n};\n\nconst headOf =\n (voices: Option.Option<ReadonlyMap<number, string>>): From<Group, string> =>\n (group) =>\n Option.match(voices, {\n onNone: () => pitchesText(group.midis),\n onSome: (map) =>\n pipe(\n Arr.head(group.midis),\n Option.flatMap((midi) => Option.fromNullishOr(map.get(midi))),\n Option.getOrElse(() => \"\"),\n ),\n });\n\nconst when = (condition: boolean, text: string): readonly string[] => {\n if (condition) {\n return [text];\n }\n return [];\n};\n\nconst attributesOf: From<Segment, readonly string[]> = ({ group, start, end }) => {\n const last = end === group.end;\n return [\n ...when(group.velocity !== FULL, `vel ${shareText(group.velocity)}`),\n ...when(last && group.release !== DEFAULT_RELEASE, `off ${shareText(group.release)}`),\n ...when(!last, \"tie\"),\n ...pipe(\n group.lyric,\n Option.filter(() => start === group.start),\n Option.map((text) => `lyric ${quoted(text)}`),\n Option.toArray,\n ),\n ];\n};\n\nconst cellsOf = (\n segments: readonly Segment[],\n bar: Span,\n head: From<Group, string>,\n): readonly Cell[] => {\n const placed = Arr.reduce(\n segments,\n { cells: [] as readonly Cell[], cursor: bar.start },\n ({ cells, cursor }, segment) => ({\n cells: [\n ...cells,\n ...restsOf(segment.start - cursor),\n {\n head: head(segment.group),\n attributes: attributesOf(segment),\n length: segment.end - segment.start,\n },\n ],\n cursor: segment.end,\n }),\n );\n return [...placed.cells, ...restsOf(endOfSpan(bar) - placed.cursor)];\n};\n\nconst lineTextOf =\n (\n planned: PlannedPart,\n voices: Option.Option<ReadonlyMap<number, string>>,\n bar: Span,\n ): From<Line, Option.Option<VoiceText>> =>\n (line) => {\n const segments = pipe(line, Arr.filter(touches(bar)), Arr.map(segmentOf(bar)));\n return pipe(\n Arr.head(segments),\n Option.map((first) => ({\n text: `${planned.name}: ${cellsText(cellsOf(segments, bar, headOf(voices)))}`,\n continues: first.start > first.group.start,\n })),\n );\n };\n\nconst continuedFirst = Order.mapInput(Order.Boolean, (voice: VoiceText) => !voice.continues);\n\nexport interface VoiceContext {\n readonly plan: Plan;\n readonly bar: Span;\n}\n\nexport const voiceLinesOf: From<VoiceContext, From<PlannedPart, readonly string[]>> =\n ({ plan, bar }) =>\n (planned) => {\n const voices = pipe(\n Option.some(plan.drumVoices),\n Option.filter(() => planned.source.kind === \"kit\"),\n );\n const texts = pipe(planned.lines, Arr.map(lineTextOf(planned, voices, bar)), Arr.getSomes);\n return pipe(\n Arr.sort(texts, continuedFirst),\n Arr.map((voice) => voice.text),\n );\n };\n","import { Array as Arr, Option, pipe } from \"effect\";\n\nimport type { From } from \"#/shared/lib/from.ts\";\nimport { fractionOf } from \"#/shared/lib/ticks.ts\";\n\nimport { quoted } from \"./cells.ts\";\nimport { controlLinesOf } from \"./control-lines.ts\";\nimport type { Timeline } from \"./events.ts\";\nimport { barsOf, bpmText } from \"./layout.ts\";\nimport type { LaidBar, LaidTempo } from \"./layout.ts\";\nimport { automationLinesOf, busLineOf, trackMixWords } from \"./mix-lines.ts\";\nimport { planOf } from \"./plan.ts\";\nimport type { Plan, PlannedPart } from \"./plan.ts\";\nimport { voiceLinesOf } from \"./voice-lines.ts\";\n\nconst SINGLE = 1;\nconst INDENT = \" \";\n\nexport interface Written {\n readonly text: string;\n readonly plan: Plan;\n readonly bars: readonly LaidBar[];\n}\n\ninterface Previous {\n readonly meter: Option.Option<string>;\n readonly microseconds: Option.Option<number>;\n}\n\nconst START: Previous = { meter: Option.none(), microseconds: Option.none() };\n\nconst isRamp: From<LaidTempo, boolean> = (step) => Option.isSome(step.target);\n\nconst stepText: From<LaidTempo, string> = (step) => {\n const ramp = Option.match(step.target, {\n onNone: () => \"\",\n onSome: (target) => ` -> ${bpmText(target)}`,\n });\n return `${bpmText(step.microseconds)}${ramp} ${fractionOf(step.length)}`;\n};\n\nconst tempoLineOf: From<LaidBar, Option.Option<string>> = (bar) => {\n if (bar.tempo.length <= SINGLE && !pipe(bar.tempo, Arr.some(isRamp))) {\n return Option.none();\n }\n const steps = pipe(bar.tempo, Arr.map(stepText));\n return Option.some(`tempo: ${Arr.join(steps, \", \")}`);\n};\n\nconst differs =\n <Value>(previous: Option.Option<Value>): From<Value, boolean> =>\n (current) =>\n Option.match(previous, { onNone: () => true, onSome: (value) => value !== current });\n\nconst headerTempoOf =\n (previous: Previous): From<LaidBar, readonly string[]> =>\n (bar) =>\n pipe(\n Arr.head(bar.tempo),\n Option.filter(() => bar.tempo.length === SINGLE && !pipe(bar.tempo, Arr.some(isRamp))),\n Option.map((step) => step.microseconds),\n Option.filter(differs(previous.microseconds)),\n Option.map((microseconds) => `tempo ${bpmText(microseconds)}`),\n Option.toArray,\n );\n\nconst barHeadOf =\n (previous: Previous): From<LaidBar, string> =>\n (bar) => {\n const meter = pipe(\n Option.some(bar.meter),\n Option.filter(differs(previous.meter)),\n Option.map((current) => `meter ${current}`),\n Option.toArray,\n );\n const mark = pipe(\n Option.some(bar.marks),\n Option.filter(Arr.isReadonlyArrayNonEmpty),\n Option.map((marks) => `mark ${quoted(Arr.join(marks, \" / \"))}`),\n Option.toArray,\n );\n return Arr.join([\"bar\", ...meter, ...headerTempoOf(previous)(bar), ...mark, \"{\"], \" \");\n };\n\nconst barBodyOf: From<Plan, From<LaidBar, readonly string[]>> = (plan) => (bar) => [\n ...Option.toArray(tempoLineOf(bar)),\n ...pipe(\n plan.parts,\n Arr.flatMap((planned) => [\n ...voiceLinesOf({ plan, bar })(planned),\n ...controlLinesOf(bar)(planned),\n ...automationLinesOf(bar)(planned),\n ]),\n ),\n];\n\ninterface Walk {\n readonly lines: readonly string[];\n readonly previous: Previous;\n}\n\nconst afterBar: From<LaidBar, Previous> = (bar) => ({\n meter: Option.some(bar.meter),\n microseconds: pipe(\n Arr.last(bar.tempo),\n Option.map((step) => Option.getOrElse(step.target, () => step.microseconds)),\n ),\n});\n\nconst walkStep: From<Plan, (walk: Walk, bar: LaidBar) => Walk> =\n (plan) =>\n ({ lines, previous }, bar) => ({\n lines: [\n ...lines,\n \"\",\n barHeadOf(previous)(bar),\n ...pipe(\n barBodyOf(plan)(bar),\n Arr.map((line) => `${INDENT}${line}`),\n ),\n \"}\",\n ],\n previous: afterBar(bar),\n });\n\nconst instrumentLinesOf: From<Plan, readonly string[]> = (plan) =>\n pipe(\n Arr.fromIterable(plan.instruments),\n Arr.map(([program, name]) => `instrument ${name} plugin gm program ${String(program)}`),\n );\n\nconst kitLinesOf: From<Plan, readonly string[]> = (plan) => {\n if (plan.drumVoices.size < SINGLE) {\n return [];\n }\n const voices = pipe(\n Arr.fromIterable(plan.drumVoices.values()),\n Arr.map((name) => `${INDENT}${name} ${quoted(`gm-drums/${name}.flac`)}`),\n );\n return [\"kit gm-drums {\", ...voices, \"}\"];\n};\n\nconst sourceWordsOf: From<PlannedPart, readonly string[]> = (planned) => {\n if (planned.source.kind === \"kit\") {\n return [\"kit gm-drums role drums\"];\n }\n return [`instrument ${planned.source.instrument}`];\n};\n\nconst trackLineOf =\n (plan: Plan): From<PlannedPart, string> =>\n (planned) =>\n Arr.join(\n [\n \"track\",\n planned.name,\n ...sourceWordsOf(planned),\n ...trackMixWords({ mix: planned.mix, buses: plan.buses }),\n ],\n \" \",\n );\n\ninterface Heading {\n readonly plan: Plan;\n readonly title: string;\n}\n\nconst headerOf: From<Heading, readonly string[]> = ({ plan, title }) => [\n `song ${quoted(title)}`,\n \"\",\n 'plugin gm from \"./gm.ts\" { program: number = 0 }',\n \"\",\n ...instrumentLinesOf(plan),\n ...kitLinesOf(plan),\n \"\",\n ...pipe(plan.buses, Arr.map(busLineOf)),\n ...pipe(plan.parts, Arr.map(trackLineOf(plan))),\n];\n\nexport interface WriteInput {\n readonly timeline: Timeline;\n readonly title: string;\n}\n\nexport const writeFumx: From<WriteInput, Written> = ({ timeline, title }) => {\n const plan = planOf(timeline);\n const bars = barsOf(timeline);\n const walked = Arr.reduce(\n bars,\n { lines: headerOf({ plan, title }), previous: START },\n walkStep(plan),\n );\n return { text: `${Arr.join(walked.lines, \"\\n\")}\\n`, plan, bars };\n};\n","import { Array as Arr, Match, Option, Record as Rec, pipe } from \"effect\";\n\nimport { sortedNotes } from \"#/entities/timeline/index.ts\";\nimport type { TimelineControl, TimelineNote } from \"#/entities/timeline/index.ts\";\nimport type { From } from \"#/shared/lib/from.ts\";\n\nimport type { ChannelEvent, PlacedEvent } from \"./placed.ts\";\n\nconst NONE = 0;\nconst NEXT = 1;\nconst DEFAULT_RELEASE = 64;\nconst DEFAULT_BEND_RANGE = 2;\nconst CENTS_PER_SEMITONE = 100;\nconst BEND_HALF = 8192;\nconst RPN_MSB = 101;\nconst RPN_LSB = 100;\nconst DATA_MSB = 6;\nconst DATA_LSB = 38;\nconst PITCH_BEND_RPN = 0;\nconst UNSET = 127;\n\ninterface Edge {\n readonly tick: number;\n readonly on: boolean;\n readonly velocity: number;\n}\n\ntype PitchEdge = readonly [number, Edge];\n\nconst edgeOf: From<PlacedEvent, Option.Option<PitchEdge>> = ({ tick, event }) =>\n Match.value(event).pipe(\n Match.when({ type: \"noteOn\" }, (on): Option.Option<PitchEdge> =>\n Option.some([on.noteNumber, { tick, on: on.velocity > NONE, velocity: on.velocity }]),\n ),\n Match.when({ type: \"noteOff\" }, (off): Option.Option<PitchEdge> =>\n Option.some([off.noteNumber, { tick, on: false, velocity: off.velocity }]),\n ),\n Match.orElse(() => Option.none<PitchEdge>()),\n );\n\ninterface Pairing {\n readonly open: readonly Edge[];\n readonly notes: readonly TimelineNote[];\n}\n\nconst releaseOf: From<Edge, number> = (edge) => {\n if (edge.velocity === NONE) {\n return DEFAULT_RELEASE;\n }\n return edge.velocity;\n};\n\nconst START_PAIRING: Pairing = { open: [], notes: [] };\n\nconst pairStep =\n (midi: number) =>\n (pairing: Pairing, edge: Edge): Pairing => {\n if (edge.on) {\n return { ...pairing, open: [...pairing.open, edge] };\n }\n return Option.match(Arr.head(pairing.open), {\n onNone: () => pairing,\n onSome: (started) => ({\n open: Arr.drop(pairing.open, NEXT),\n notes: [\n ...pairing.notes,\n {\n tick: started.tick,\n end: edge.tick,\n midi,\n velocity: started.velocity,\n release: releaseOf(edge),\n },\n ],\n }),\n });\n };\n\nconst pairedOf =\n (end: number): From<readonly PitchEdge[], readonly TimelineNote[]> =>\n (edges) => {\n const midi = pipe(\n Arr.head(edges),\n Option.match({ onNone: () => NONE, onSome: ([pitch]) => pitch }),\n );\n const steps = pipe(\n edges,\n Arr.map(([, edge]) => edge),\n );\n const paired = Arr.reduce(steps, START_PAIRING, pairStep(midi));\n const unended = pipe(\n paired.open,\n Arr.map((started) => ({\n tick: started.tick,\n end,\n midi,\n velocity: started.velocity,\n release: DEFAULT_RELEASE,\n })),\n );\n return [...paired.notes, ...unended];\n };\n\nconst notesOf =\n (end: number): From<readonly PlacedEvent[], readonly TimelineNote[]> =>\n (events) => {\n const notes = pipe(\n events,\n Arr.map(edgeOf),\n Arr.getSomes,\n Arr.groupBy(([midi]) => String(midi)),\n Rec.values,\n Arr.flatMap(pairedOf(end)),\n );\n return sortedNotes(notes);\n };\n\ninterface Rpn {\n readonly msb: number;\n readonly lsb: number;\n readonly semitones: number;\n readonly cents: number;\n}\n\nconst START_RPN: Rpn = { msb: UNSET, lsb: UNSET, semitones: DEFAULT_BEND_RANGE, cents: NONE };\n\nconst isBendRange: From<Rpn, boolean> = (rpn) =>\n rpn.msb === PITCH_BEND_RPN && rpn.lsb === PITCH_BEND_RPN;\n\ntype ControllerEvent = Extract<ChannelEvent, { readonly type: \"controller\" }>;\n\nconst rpnAfter =\n (rpn: Rpn): From<ControllerEvent, Rpn> =>\n ({ controllerType, value }) => {\n if (controllerType === RPN_MSB) {\n return { ...rpn, msb: value };\n }\n if (controllerType === RPN_LSB) {\n return { ...rpn, lsb: value };\n }\n if (isBendRange(rpn) && controllerType === DATA_MSB) {\n return { ...rpn, semitones: value };\n }\n if (isBendRange(rpn) && controllerType === DATA_LSB) {\n return { ...rpn, cents: value };\n }\n return rpn;\n };\n\nconst rpnStep: From<readonly [Rpn, PlacedEvent], Rpn> = ([rpn, { event }]) => {\n if (event.type !== \"controller\") {\n return rpn;\n }\n return rpnAfter(rpn)(event);\n};\n\nconst controlOf: From<readonly [PlacedEvent, Rpn], Option.Option<TimelineControl>> = ([\n { tick, event },\n rpn,\n]) =>\n Match.value(event).pipe(\n Match.when({ type: \"controller\" }, (cc) =>\n Option.some<TimelineControl>({\n tick,\n controller: { kind: \"cc\", number: cc.controllerType },\n value: cc.value,\n }),\n ),\n Match.when({ type: \"programChange\" }, (change) =>\n Option.some<TimelineControl>({\n tick,\n controller: { kind: \"program\" },\n value: change.programNumber,\n }),\n ),\n Match.when({ type: \"channelAftertouch\" }, (pressure) =>\n Option.some<TimelineControl>({\n tick,\n controller: { kind: \"pressure\", midi: Option.none() },\n value: pressure.amount,\n }),\n ),\n Match.when({ type: \"noteAftertouch\" }, (pressure) =>\n Option.some<TimelineControl>({\n tick,\n controller: { kind: \"pressure\", midi: Option.some(pressure.noteNumber) },\n value: pressure.amount,\n }),\n ),\n Match.when({ type: \"pitchBend\" }, (bend) =>\n Option.some<TimelineControl>({\n tick,\n controller: { kind: \"bend\" },\n value: (bend.value * (rpn.semitones + rpn.cents / CENTS_PER_SEMITONE)) / BEND_HALF,\n }),\n ),\n Match.orElse(() => Option.none<TimelineControl>()),\n );\n\nconst controlsOf: From<readonly PlacedEvent[], readonly TimelineControl[]> = (events) =>\n pipe(\n Arr.zip(\n events,\n Arr.scan(events, START_RPN, (rpn, placed) => rpnStep([rpn, placed])),\n ),\n Arr.map(controlOf),\n Arr.getSomes,\n );\n\nexport interface ChannelRead {\n readonly channel: number;\n readonly notes: readonly TimelineNote[];\n readonly controls: readonly TimelineControl[];\n readonly program: Option.Option<number>;\n}\n\nconst isProgram: From<TimelineControl, boolean> = (control) =>\n control.controller.kind === \"program\";\n\nconst initialProgramOf: From<Omit<ChannelRead, \"program\">, Option.Option<TimelineControl>> = (\n read,\n) =>\n pipe(\n Arr.findFirst(read.controls, isProgram),\n Option.filter((program) =>\n pipe(\n Arr.head(read.notes),\n Option.match({ onNone: () => true, onSome: (note) => program.tick <= note.tick }),\n ),\n ),\n );\n\nexport const channelReadOf =\n (end: number): From<readonly [string, readonly PlacedEvent[]], ChannelRead> =>\n ([channel, events]) => {\n const read = {\n channel: Number(channel),\n notes: notesOf(end)(events),\n controls: controlsOf(events),\n };\n const program = initialProgramOf(read);\n return {\n ...read,\n program: pipe(\n program,\n Option.map((control) => control.value),\n ),\n controls: Option.match(program, {\n onNone: () => read.controls,\n onSome: (first) =>\n pipe(\n read.controls,\n Arr.filter((control) => control !== first),\n ),\n }),\n };\n };\n","import { Array as Arr, Match, Option, Order, Record as Rec, pipe } from \"effect\";\nimport type { MidiData, MidiEvent } from \"midi-file\";\n\nimport { NO_MIX, sortedByTick } from \"#/entities/timeline/index.ts\";\nimport type { Meter, Part, TempoChange, Text, Timed, Timeline } from \"#/entities/timeline/index.ts\";\nimport type { From } from \"#/shared/lib/from.ts\";\nimport { TICKS_PER_WHOLE } from \"#/shared/lib/ticks.ts\";\n\nimport { channelReadOf } from \"./channel.ts\";\nimport type { ChannelRead } from \"./channel.ts\";\nimport type { PlacedEvent } from \"./placed.ts\";\n\nconst QUARTERS_PER_WHOLE = 4;\nconst NONE = 0;\nconst NEXT = 1;\n\ninterface Placed {\n readonly tick: number;\n readonly exact: boolean;\n readonly event: MidiEvent;\n}\n\nconst placedOf =\n (ppq: number): From<readonly MidiEvent[], readonly Placed[]> =>\n (events) => {\n const raw = Arr.scan(events, NONE, (tick, event) => tick + event.deltaTime);\n return pipe(\n events,\n Arr.map((event, index) => {\n const absolute = Option.getOrElse(Arr.get(raw, index + NEXT), () => NONE);\n const exact = (absolute * TICKS_PER_WHOLE) / (ppq * QUARTERS_PER_WHOLE);\n return { tick: Math.round(exact), exact: Number.isInteger(exact), event };\n }),\n );\n };\n\nconst channelEventOf: From<Placed, Option.Option<PlacedEvent>> = ({ tick, event }) => {\n if (\"channel\" in event) {\n return Option.some({ tick, event });\n }\n return Option.none();\n};\n\ntype TextKind = \"name\" | \"lyric\" | \"marker\";\n\ntype KindedText = readonly [TextKind, Text];\n\ninterface TrackRead {\n readonly name: Option.Option<string>;\n readonly end: number;\n readonly offGrid: number;\n readonly channels: readonly ChannelRead[];\n readonly texts: Readonly<Record<string, readonly Text[]>>;\n readonly tempos: readonly TempoChange[];\n readonly meters: readonly Meter[];\n}\n\nconst textOf: From<Placed, Option.Option<KindedText>> = ({ tick, event }) =>\n Match.value(event).pipe(\n Match.when({ type: \"trackName\" }, (text): Option.Option<KindedText> =>\n Option.some([\"name\", { tick, text: text.text }]),\n ),\n Match.when({ type: \"lyrics\" }, (text): Option.Option<KindedText> =>\n Option.some([\"lyric\", { tick, text: text.text }]),\n ),\n Match.when({ type: \"marker\" }, (text): Option.Option<KindedText> =>\n Option.some([\"marker\", { tick, text: text.text }]),\n ),\n Match.orElse(() => Option.none<KindedText>()),\n );\n\nconst tempoOf: From<Placed, Option.Option<TempoChange>> = ({ tick, event }) =>\n Match.value(event).pipe(\n Match.when({ type: \"setTempo\" }, (tempo) =>\n Option.some<TempoChange>({\n tick,\n microseconds: tempo.microsecondsPerBeat,\n target: Option.none(),\n }),\n ),\n Match.orElse(() => Option.none<TempoChange>()),\n );\n\nconst meterOf: From<Placed, Option.Option<Meter>> = ({ tick, event }) =>\n Match.value(event).pipe(\n Match.when({ type: \"timeSignature\" }, (meter) =>\n Option.some<Meter>({ tick, numerator: meter.numerator, denominator: meter.denominator }),\n ),\n Match.orElse(() => Option.none<Meter>()),\n );\n\nconst textsOf: From<readonly Placed[], Readonly<Record<string, readonly Text[]>>> = (placed) =>\n pipe(\n placed,\n Arr.map(textOf),\n Arr.getSomes,\n Arr.groupBy(([kind]): string => kind),\n Rec.map((entries) =>\n pipe(\n entries,\n Arr.map(([, text]) => text),\n ),\n ),\n );\n\nconst textsIn =\n (kind: TextKind): From<Pick<TrackRead, \"texts\">, readonly Text[]> =>\n (read) =>\n Option.getOrElse(Rec.get(read.texts, kind), () => []);\n\nconst byChannel = Order.mapInput(Order.Number, (read: ChannelRead) => read.channel);\n\nconst channelsOf =\n (end: number): From<readonly Placed[], readonly ChannelRead[]> =>\n (placed) => {\n const reads = pipe(\n placed,\n Arr.map(channelEventOf),\n Arr.getSomes,\n Arr.groupBy((item) => String(item.event.channel)),\n Rec.toEntries,\n Arr.map(channelReadOf(end)),\n );\n return Arr.sort(reads, byChannel);\n };\n\nconst readTrack =\n (ppq: number): From<readonly MidiEvent[], TrackRead> =>\n (events) => {\n const placed = placedOf(ppq)(events);\n const end = pipe(\n Arr.last(placed),\n Option.match({ onNone: () => NONE, onSome: (last) => last.tick }),\n );\n const texts = textsOf(placed);\n return {\n name: pipe(\n Arr.head(textsIn(\"name\")({ texts })),\n Option.map((text) => text.text),\n ),\n end,\n offGrid: Arr.countBy(placed, (item) => !item.exact),\n channels: channelsOf(end)(placed),\n texts,\n tempos: pipe(placed, Arr.map(tempoOf), Arr.getSomes),\n meters: pipe(placed, Arr.map(meterOf), Arr.getSomes),\n };\n };\n\nconst isUsed: From<ChannelRead, boolean> = (read) =>\n Arr.isReadonlyArrayNonEmpty(read.notes) ||\n Arr.isReadonlyArrayNonEmpty(read.controls) ||\n Option.isSome(read.program);\n\nconst partsOf = (read: TrackRead, track: number): readonly Part[] => {\n const lyrics = textsIn(\"lyric\")(read);\n return pipe(\n read.channels,\n Arr.filter(isUsed),\n Arr.map((channel) => ({\n ...channel,\n track,\n name: read.name,\n lyrics: pipe(\n lyrics,\n Arr.filter((lyric) =>\n pipe(\n channel.notes,\n Arr.some((note) => note.tick === lyric.tick),\n ),\n ),\n ),\n })),\n );\n};\n\nconst titleOf: From<readonly TrackRead[], Option.Option<string>> = (reads) =>\n pipe(\n Arr.head(reads),\n Option.filter((read) => !Arr.isReadonlyArrayNonEmpty(read.channels)),\n Option.flatMap((read) => read.name),\n );\n\nconst endsOf: From<TrackRead, readonly number[]> = (read) => [\n read.end,\n ...pipe(\n read.channels,\n Arr.flatMap((channel) => channel.notes),\n Arr.map((note) => note.end),\n ),\n];\n\nconst sortedFrom =\n <Item extends Timed>(\n pick: From<TrackRead, readonly Item[]>,\n ): From<readonly TrackRead[], readonly Item[]> =>\n (reads) =>\n sortedByTick(pipe(reads, Arr.flatMap(pick)));\n\nexport const timelineOf: From<MidiData, Timeline> = (midi) => {\n const reads = pipe(midi.tracks, Arr.map(readTrack(midi.header.ticksPerBeat ?? NONE)));\n return {\n title: titleOf(reads),\n end: Arr.reduce(pipe(reads, Arr.flatMap(endsOf)), NONE, (latest, tick) =>\n Math.max(latest, tick),\n ),\n offGrid: Arr.reduce(reads, NONE, (total, read) => total + read.offGrid),\n tempos: sortedFrom((read) => read.tempos)(reads),\n meters: sortedFrom((read) => read.meters)(reads),\n markers: sortedFrom(textsIn(\"marker\"))(reads),\n parts: pipe(\n reads,\n Arr.flatMap((read, index) => partsOf(read, index)),\n ),\n mix: NO_MIX,\n };\n};\n","import { Effect, Option, Schema, Predicate } from \"effect\";\nimport { parseMidi } from \"midi-file\";\n\nimport { writeFumx } from \"#/entities/timeline/index.ts\";\nimport type { Written } from \"#/entities/timeline/index.ts\";\n\nimport { timelineOf } from \"./timeline.ts\";\n\nconst taggedError = Schema.TaggedError;\n\nexport class UnreadableMidi extends taggedError<\n UnreadableMidi,\n { readonly brand: unique symbol }\n>()(\"UnreadableMidi\", { message: Schema.String }, { identifier: \"UnreadableMidi\" }) {}\n\nexport interface MidiFile {\n readonly bytes: Uint8Array;\n readonly title: string;\n}\n\nexport interface Fumx extends Written {\n readonly offGrid: number;\n}\n\nexport const midiToFumx = Effect.fn(\"midiToFumx\")(function* convert(input: MidiFile) {\n const midi = yield* Effect.try({\n try: () => parseMidi(input.bytes),\n catch: (cause) => UnreadableMidi.make({ message: String(cause) }),\n });\n if (Predicate.isUndefined(midi.header.ticksPerBeat)) {\n return yield* UnreadableMidi.make({ message: \"SMPTE time division is not supported\" });\n }\n const timeline = yield* Effect.sync(() => timelineOf(midi)).pipe(Effect.withSpan(\"timelineOf\"));\n const written = yield* Effect.sync(() =>\n writeFumx({ timeline, title: Option.getOrElse(timeline.title, () => input.title) }),\n ).pipe(Effect.withSpan(\"writeFumx\"));\n yield* Effect.annotateCurrentSpan({\n parts: written.plan.parts.length,\n bars: written.bars.length,\n });\n const fumx: Fumx = { ...written, offGrid: timeline.offGrid };\n return fumx;\n});\n","import { Array as Arr, Effect, Schema, pipe } from \"effect\";\n\nimport { compareWithSong } from \"#/entities/timeline/index.ts\";\nimport type { Comparison, Written } from \"#/entities/timeline/index.ts\";\nimport { readSong } from \"#/features/read-song/index.ts\";\nimport type { SourceIssue } from \"#/features/read-song/index.ts\";\n\nconst taggedError = Schema.TaggedError;\n\nexport class InvalidOutput extends taggedError<InvalidOutput, { readonly brand: unique symbol }>()(\n \"InvalidOutput\",\n { message: Schema.String, text: Schema.String },\n { identifier: \"InvalidOutput\" },\n) {}\n\nexport interface Adjustments {\n readonly offGrid: number;\n}\n\nexport interface Converted {\n readonly text: string;\n readonly comparison: Comparison;\n readonly adjustments: Adjustments;\n}\n\nexport interface Checked extends Written {\n readonly offGrid: number;\n}\n\nconst issueText = (issue: SourceIssue): string =>\n `${String(issue.line)}:${String(issue.column)} ${issue.message}`;\n\nexport const roundTrip = Effect.fn(\"roundTrip\")(function* check(path: string, fumx: Checked) {\n const read = yield* readSong({ path, read: () => Effect.succeed(fumx.text) }).pipe(\n Effect.withSpan(\"readSong\"),\n );\n if (read.status === \"invalid\") {\n return yield* InvalidOutput.make({\n message: pipe(read.issues, Arr.map(issueText), Arr.join(\"\\n\")),\n text: fumx.text,\n });\n }\n const comparison = compareWithSong({ plan: fumx.plan, bars: fumx.bars, song: read.song });\n yield* Effect.annotateCurrentSpan({\n matches: comparison.matches,\n notes: comparison.notes.expected,\n });\n const converted: Converted = {\n text: fumx.text,\n comparison,\n adjustments: { offGrid: fumx.offGrid },\n };\n return converted;\n});\n","import { Effect } from \"effect\";\n\nimport { midiToFumx } from \"#/features/convert-midi/index.ts\";\nimport type { MidiFile } from \"#/features/convert-midi/index.ts\";\n\nimport { roundTrip } from \"./round-trip.ts\";\n\nexport interface MidiSource extends MidiFile {\n readonly path: string;\n}\n\nexport const convertMidiFile = Effect.fn(\"convertMidiFile\")(function* convert(source: MidiSource) {\n const fumx = yield* midiToFumx(source);\n return yield* roundTrip(source.path, fumx);\n});\n","#!/usr/bin/env node\nimport { convertMain } from \"#/app/convert-command.ts\";\nimport { convertMidiFile } from \"#/app/midi-to-fumx.ts\";\n\nconvertMain({\n name: \"midi-to-fumx\",\n input: \"A Standard MIDI File (.mid)\",\n source: \"MIDI file\",\n convert: convertMidiFile,\n});\n"],"mappings":";;;;;;;;;;AAMA,MAAMA,WAAS;AAEf,MAAMC,gBAAc,OAAO;AAE3B,IAAM,WAAN,cAAuBA,cAAyD,CAAC,CAC/E,YACA,EAAE,SAAS,OAAO,OAAO,GACzB,EAAE,YAAY,WAAW,CAC3B,CAAC,CAAC,CAAC;AAEH,MAAM,gBAAgB,OAAO,oBAC3B,OAAO,eAAe,OAAO,SAAS,EAAE,OAAOD,SAAO,CAAC,CACzD;AAeA,MAAa,eAAwB,SAAwC;CAC3E,MAAM,cAAc,OAAO,GAAG,aAAa,CAAC,CAAC,UAAU,YACrD,MACA,KACA;EACA,MAAM,aAAa,OAAO,WAAW;EACrC,MAAM,OAAO,OAAO,KAAK;EACzB,MAAM,QAAQ,KAAK,QAAQ,IAAI;EAC/B,MAAM,SAAS,KAAK,MAAM,KAAK;EAC/B,MAAM,SAAS,OAAO,MAAM,KAAK;GAC/B,cAAc,KAAK,KAAK,OAAO,KAAK,GAAG,OAAO,KAAK,MAAM;GACzD,SAAS,UAAU,KAAK,QAAQ,KAAK;EACvC,CAAC;EACD,MAAM,QAAQ,OAAO,WAAW,SAAS,KAAK;EAC9C,MAAM,YAAY,OAAO,KAAK,QAAQ;GAAE;GAAO,OAAO,OAAO;GAAM,MAAM;EAAO,CAAC;EACjF,OAAO,WAAW,gBAAgB,QAAQ,UAAU,IAAI;EACxD,OAAO;GAAE,QAAQ;GAAQ,YAAY,UAAU;GAAY,aAAa,UAAU;EAAY;CAChG,CAAC;CACD,MAAM,UAAU,QAAQ,KACtB,KAAK,MACL;EACE,MAAM,SAAS,OAAO,MAAM,CAAC,CAAC,KAAK,SAAS,gBAAgB,KAAK,KAAK,CAAC;EACvE,KAAK,KAAK,OAAO,KAAK,CAAC,CAAC,KACtB,KAAK,gBACH,kDAAkD,KAAK,OAAO,mBAChE,GACA,KAAK,QACP;CACF,IACC,EAAE,MAAM,UACP,YAAY,MAAM,GAAG,CAAC,CAAC,KACrB,OAAO,KAAK,YAAY,OAAO,QAAQ,cAAc,OAAO,GAAG,QAAQ,GAAG,CAAC,GAC3E,OAAO,cACJ,YAAY,QAAQ,WAAW,eAE9B,SAAS,KAAK,EACZ,SAAS,2DAA2D,KAAK,SAC3E,CAAC,CACL,GACA,OAAO,MACT,CACJ;CACA,QAAQ,KAAK,IAAI,CAAC,CAAC,QAAQ,IAAI,SAAS,EAAE,SAAS,QAAQ,CAAC,CAAC;AAC/D;;AC5EA,MAAa,WAAW;CACtB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;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,CAAC,CAChG,iBACA;CAAE,SAAS,OAAO;CAAQ,MAAM,OAAO;AAAO,GAC9C,EAAE,YAAY,gBAAgB,CAChC,CAAC,CAAC,CAAC;AAgBH,MAAM,aAAa,UACjB,GAAG,OAAO,MAAM,IAAI,EAAE,GAAG,OAAO,MAAM,MAAM,EAAE,GAAG,MAAM;AAEzD,MAAa,YAAY,OAAO,GAAG,WAAW,CAAC,CAAC,UAAU,MAAM,MAAc,MAAe;CAC3F,MAAM,OAAO,OAAO,SAAS;EAAE;EAAM,YAAY,OAAO,QAAQ,KAAK,IAAI;CAAE,CAAC,CAAC,CAAC,KAC5E,OAAO,SAAS,UAAU,CAC5B;CACA,IAAI,KAAK,WAAW,WAClB,OAAO,OAAO,cAAc,KAAK;EAC/B,SAAS,KAAK,KAAK,QAAQC,MAAI,IAAI,SAAS,GAAGA,MAAI,KAAK,IAAI,CAAC;EAC7D,MAAM,KAAK;CACb,CAAC;CAEH,MAAM,aAAa,gBAAgB;EAAE,MAAM,KAAK;EAAM,MAAM,KAAK;EAAM,MAAM,KAAK;CAAK,CAAC;CACxF,OAAO,OAAO,oBAAoB;EAChC,SAAS,WAAW;EACpB,OAAO,WAAW,MAAM;CAC1B,CAAC;CAMD,OAAO;EAJL,MAAM,KAAK;EACX;EACA,aAAa,EAAE,SAAS,KAAK,QAAQ;CAExB;AACjB,CAAC;;AEjDD,YAAY;CACV,MAAM;CACN,OAAO;CACP,QAAQ;CACR,SDG6B,OAAO,GAAG,iBAAiB,CAAC,CAAC,UAAU,QAAQ,QAAoB;EAChG,MAAM,OAAO,OAAO,WAAW,MAAM;EACrC,OAAO,OAAO,UAAU,OAAO,MAAM,IAAI;CAC3C,CCNW;AACX,CAAC"}
@@ -0,0 +1,123 @@
1
+ import { G as isSong } from "./grammar-86_uhiTo.mjs";
2
+ import { a as importedUriOf, i as compileSong, n as createFumxServices, o as isNamed } from "./fumx-module-DJQrnEVm.mjs";
3
+ import { Array, Effect, Option, Predicate, pipe } from "effect";
4
+ import { CstUtils, GrammarUtils, URI, isLeafCstNode } from "langium";
5
+ // src/features/read-song/model/comments.ts
6
+ const KINDS = ["SL_COMMENT", "ML_COMMENT"];
7
+ const FIRST$1 = 1;
8
+ const leavesOf = (cst) => CstUtils.streamCst(cst).filter((node) => isLeafCstNode(node)).toArray();
9
+ const isComment = (leaf) => leaf.hidden && Array.contains(KINDS, leaf.tokenType.name);
10
+ const commentsOf = (root) => pipe(Option.fromNullishOr(root.$cstNode), Option.map(leavesOf), Option.getOrElse(() => []), Array.filter(isComment), Array.map((leaf) => ({
11
+ line: leaf.range.start.line + FIRST$1,
12
+ column: leaf.range.start.character + FIRST$1,
13
+ text: leaf.text
14
+ })));
15
+ // src/features/read-song/model/outline.ts
16
+ const emptyOutline = {
17
+ title: Option.none(),
18
+ names: [],
19
+ imports: [],
20
+ files: [],
21
+ comments: []
22
+ };
23
+ const spanOf = (node) => ({
24
+ start: node.offset,
25
+ end: node.end
26
+ });
27
+ const propertySpanOf = (node) => (property) => pipe(Option.fromNullishOr(GrammarUtils.findNodeForProperty(node.$cstNode, property)), Option.map(spanOf));
28
+ const namesOf = (song) => pipe(song.declarations, Array.filter(isNamed), Array.flatMap((declaration) => pipe(propertySpanOf(declaration)("name"), Option.map((span) => ({
29
+ type: declaration.$type,
30
+ name: declaration.name,
31
+ span
32
+ })), Option.toArray)));
33
+ const importsOf = (song) => pipe(song.imports, Array.flatMap((node) => pipe(propertySpanOf(node)("path"), Option.map((span) => ({
34
+ path: importedUriOf(node).fsPath,
35
+ span
36
+ })), Option.toArray)));
37
+ const outlineOf = (files) => (song) => ({
38
+ title: propertySpanOf(song)("title"),
39
+ names: namesOf(song),
40
+ imports: importsOf(song),
41
+ files,
42
+ comments: commentsOf(song)
43
+ });
44
+ // src/features/read-song/model/read-song.ts
45
+ const FIRST = 1;
46
+ const ERROR = 1;
47
+ const messageOf = (message) => {
48
+ if (Predicate.isString(message)) return message;
49
+ return message.value;
50
+ };
51
+ const loader = (services) => (read) => {
52
+ const { LangiumDocuments, LangiumDocumentFactory } = services.shared.workspace;
53
+ const load = (uri) => Effect.gen(function* loadDocument() {
54
+ if (LangiumDocuments.hasDocument(uri)) return;
55
+ const text = yield* read(uri.fsPath);
56
+ if (Option.isNone(text)) return;
57
+ const document = LangiumDocumentFactory.fromString(text.value, uri);
58
+ LangiumDocuments.addDocument(document);
59
+ yield* Effect.forEach(document.parseResult.value.imports, (node) => load(importedUriOf(node)), {
60
+ concurrency: 1,
61
+ discard: true
62
+ });
63
+ });
64
+ return load;
65
+ };
66
+ const issuesOf = (document) => pipe(document.diagnostics ?? [], Array.filter((diagnostic) => diagnostic.severity === ERROR), Array.map((diagnostic) => ({
67
+ path: document.uri.fsPath,
68
+ line: diagnostic.range.start.line + FIRST,
69
+ column: diagnostic.range.start.character + FIRST,
70
+ start: document.textDocument.offsetAt(diagnostic.range.start),
71
+ end: document.textDocument.offsetAt(diagnostic.range.end),
72
+ message: messageOf(diagnostic.message)
73
+ })));
74
+ const builtOf = (services) => (entry) => Effect.gen(function* build() {
75
+ const { workspace } = services.shared;
76
+ const documents = workspace.LangiumDocuments.all.toArray();
77
+ yield* Effect.promise(() => workspace.DocumentBuilder.build(documents, { validation: true }));
78
+ const files = pipe(documents, Array.map((document) => document.uri.fsPath));
79
+ const root = pipe(Option.fromNullishOr(workspace.LangiumDocuments.getDocument(entry)), Option.map((document) => document.parseResult.value), Option.filter(isSong));
80
+ const outline = pipe(root, Option.map(outlineOf(files)), Option.getOrElse(() => ({
81
+ ...emptyOutline,
82
+ files
83
+ })));
84
+ const issues = pipe(documents, Array.flatMap(issuesOf));
85
+ if (Array.isReadonlyArrayNonEmpty(issues)) return {
86
+ status: "invalid",
87
+ issues,
88
+ outline
89
+ };
90
+ return Option.match(root, {
91
+ onNone: () => ({
92
+ status: "invalid",
93
+ issues: [],
94
+ outline
95
+ }),
96
+ onSome: (song) => ({
97
+ status: "valid",
98
+ song: compileSong(song).value,
99
+ outline
100
+ })
101
+ });
102
+ });
103
+ const readSong = Effect.fnUntraced(function* read(files) {
104
+ const services = createFumxServices();
105
+ const entry = URI.file(files.path);
106
+ yield* loader(services)((path) => Effect.option(files.read(path)))(entry);
107
+ if (!services.shared.workspace.LangiumDocuments.hasDocument(entry)) return {
108
+ status: "invalid",
109
+ issues: [{
110
+ path: files.path,
111
+ line: FIRST,
112
+ column: FIRST,
113
+ start: 0,
114
+ end: 0,
115
+ message: "ファイルを読めません"
116
+ }],
117
+ outline: emptyOutline
118
+ };
119
+ return yield* builtOf(services)(entry);
120
+ });
121
+ export { readSong as t };
122
+
123
+ //# sourceMappingURL=read-song-CNrfcHrY.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"read-song-CNrfcHrY.mjs","names":["FIRST","Arr","Arr","Arr"],"sources":["../src/features/read-song/model/comments.ts","../src/features/read-song/model/outline.ts","../src/features/read-song/model/read-song.ts"],"sourcesContent":["import { Array as Arr, Option, pipe } from \"effect\";\nimport { CstUtils, isLeafCstNode } from \"langium\";\nimport type { AstNode, CstNode, LeafCstNode } from \"langium\";\n\nimport type { From } from \"./problem.ts\";\n\nconst KINDS = [\"SL_COMMENT\", \"ML_COMMENT\"];\nconst FIRST = 1;\n\nexport interface SourceComment {\n readonly line: number;\n readonly column: number;\n readonly text: string;\n}\n\nconst leavesOf: From<CstNode, readonly LeafCstNode[]> = (cst) =>\n CstUtils.streamCst(cst)\n .filter((node) => isLeafCstNode(node))\n .toArray();\n\nconst isComment: From<LeafCstNode, boolean> = (leaf) =>\n leaf.hidden && Arr.contains(KINDS, leaf.tokenType.name);\n\nexport const commentsOf: From<AstNode, readonly SourceComment[]> = (root) =>\n pipe(\n Option.fromNullishOr(root.$cstNode),\n Option.map(leavesOf),\n Option.getOrElse((): readonly LeafCstNode[] => []),\n Arr.filter(isComment),\n Arr.map((leaf) => ({\n line: leaf.range.start.line + FIRST,\n column: leaf.range.start.character + FIRST,\n text: leaf.text,\n })),\n );\n","import { Array as Arr, Option, pipe } from \"effect\";\nimport { GrammarUtils } from \"langium\";\nimport type { AstNode, CstNode } from \"langium\";\n\nimport type { Song as SongNode } from \"#generated/langium/ast.ts\";\n\nimport { commentsOf } from \"./comments.ts\";\nimport type { SourceComment } from \"./comments.ts\";\nimport { isNamed } from \"./declarations.ts\";\nimport type { Named } from \"./declarations.ts\";\nimport type { From } from \"./problem.ts\";\nimport { importedUriOf } from \"./scope.ts\";\n\nexport interface Span {\n readonly start: number;\n readonly end: number;\n}\n\nexport interface NamedSpan {\n readonly type: Named[\"$type\"];\n readonly name: string;\n readonly span: Span;\n}\n\nexport interface ImportSpan {\n readonly path: string;\n readonly span: Span;\n}\n\nexport interface Outline {\n readonly title: Option.Option<Span>;\n readonly names: readonly NamedSpan[];\n readonly imports: readonly ImportSpan[];\n readonly files: readonly string[];\n readonly comments: readonly SourceComment[];\n}\n\nexport const emptyOutline: Outline = {\n title: Option.none(),\n names: [],\n imports: [],\n files: [],\n comments: [],\n};\n\nconst spanOf: From<CstNode, Span> = (node) => ({ start: node.offset, end: node.end });\n\nconst propertySpanOf: From<AstNode, From<string, Option.Option<Span>>> = (node) => (property) =>\n pipe(\n Option.fromNullishOr(GrammarUtils.findNodeForProperty(node.$cstNode, property)),\n Option.map(spanOf),\n );\n\nconst namesOf: From<SongNode, readonly NamedSpan[]> = (song) =>\n pipe(\n song.declarations,\n Arr.filter(isNamed),\n Arr.flatMap((declaration) =>\n pipe(\n propertySpanOf(declaration)(\"name\"),\n Option.map((span) => ({ type: declaration.$type, name: declaration.name, span })),\n Option.toArray,\n ),\n ),\n );\n\nconst importsOf: From<SongNode, readonly ImportSpan[]> = (song) =>\n pipe(\n song.imports,\n Arr.flatMap((node) =>\n pipe(\n propertySpanOf(node)(\"path\"),\n Option.map((span) => ({ path: importedUriOf(node).fsPath, span })),\n Option.toArray,\n ),\n ),\n );\n\nexport const outlineOf: From<readonly string[], From<SongNode, Outline>> = (files) => (song) => ({\n title: propertySpanOf(song)(\"title\"),\n names: namesOf(song),\n imports: importsOf(song),\n files,\n comments: commentsOf(song),\n});\n","import { Array as Arr, Effect, Option, Predicate, pipe } from \"effect\";\nimport { URI } from \"langium\";\nimport type { LangiumDocument } from \"langium\";\nimport type { Diagnostic } from \"vscode-languageserver\";\n\nimport type { Song } from \"#/entities/song/index.ts\";\nimport { isSong } from \"#generated/langium/ast.ts\";\nimport type { Song as SongNode } from \"#generated/langium/ast.ts\";\n\nimport { compileSong } from \"./compile.ts\";\nimport { createFumxServices } from \"./fumx-module.ts\";\nimport type { FumxServices } from \"./fumx-module.ts\";\nimport { emptyOutline, outlineOf } from \"./outline.ts\";\nimport type { Outline } from \"./outline.ts\";\nimport type { From } from \"./problem.ts\";\nimport { importedUriOf } from \"./scope.ts\";\n\nconst FIRST = 1;\nconst ERROR = 1;\n\nexport interface SourceIssue {\n readonly path: string;\n readonly line: number;\n readonly column: number;\n readonly start: number;\n readonly end: number;\n readonly message: string;\n}\n\nexport type SongSource =\n | {\n readonly status: \"invalid\";\n readonly issues: readonly SourceIssue[];\n readonly outline: Outline;\n }\n | { readonly status: \"valid\"; readonly song: Song; readonly outline: Outline };\n\nexport interface SongFiles<Failure> {\n readonly path: string;\n readonly read: (path: string) => Effect.Effect<string, Failure>;\n}\n\nconst messageOf: From<Diagnostic[\"message\"], string> = (message) => {\n if (Predicate.isString(message)) {\n return message;\n }\n return message.value;\n};\n\ntype Reader = From<string, Effect.Effect<Option.Option<string>>>;\n\nconst loader: From<FumxServices, From<Reader, From<URI, Effect.Effect<void>>>> =\n (services) => (read) => {\n const { LangiumDocuments, LangiumDocumentFactory } = services.shared.workspace;\n const load: From<URI, Effect.Effect<void>> = (uri) =>\n Effect.gen(function* loadDocument() {\n if (LangiumDocuments.hasDocument(uri)) {\n return;\n }\n const text = yield* read(uri.fsPath);\n if (Option.isNone(text)) {\n return;\n }\n const document = LangiumDocumentFactory.fromString<SongNode>(text.value, uri);\n LangiumDocuments.addDocument(document);\n yield* Effect.forEach(\n document.parseResult.value.imports,\n (node) => load(importedUriOf(node)),\n { concurrency: 1, discard: true },\n );\n });\n return load;\n };\n\nconst issuesOf: From<LangiumDocument, readonly SourceIssue[]> = (document) =>\n pipe(\n document.diagnostics ?? [],\n Arr.filter((diagnostic) => diagnostic.severity === ERROR),\n Arr.map((diagnostic) => ({\n path: document.uri.fsPath,\n line: diagnostic.range.start.line + FIRST,\n column: diagnostic.range.start.character + FIRST,\n start: document.textDocument.offsetAt(diagnostic.range.start),\n end: document.textDocument.offsetAt(diagnostic.range.end),\n message: messageOf(diagnostic.message),\n })),\n );\n\nconst builtOf: From<FumxServices, From<URI, Effect.Effect<SongSource>>> = (services) => (entry) =>\n Effect.gen(function* build() {\n const { workspace } = services.shared;\n const documents = workspace.LangiumDocuments.all.toArray();\n yield* Effect.promise(() => workspace.DocumentBuilder.build(documents, { validation: true }));\n const files = pipe(\n documents,\n Arr.map((document) => document.uri.fsPath),\n );\n const root = pipe(\n Option.fromNullishOr(workspace.LangiumDocuments.getDocument(entry)),\n Option.map((document) => document.parseResult.value),\n Option.filter(isSong),\n );\n const outline = pipe(\n root,\n Option.map(outlineOf(files)),\n Option.getOrElse(() => ({ ...emptyOutline, files })),\n );\n const issues = pipe(documents, Arr.flatMap(issuesOf));\n if (Arr.isReadonlyArrayNonEmpty(issues)) {\n return { status: \"invalid\", issues, outline };\n }\n return Option.match(root, {\n onNone: (): SongSource => ({ status: \"invalid\", issues: [], outline }),\n onSome: (song): SongSource => ({ status: \"valid\", song: compileSong(song).value, outline }),\n });\n });\n\nexport const readSong = Effect.fnUntraced(function* read<Failure>(\n files: SongFiles<Failure>,\n): Effect.fn.Return<SongSource> {\n const services = createFumxServices();\n const entry = URI.file(files.path);\n yield* loader(services)((path) => Effect.option(files.read(path)))(entry);\n if (!services.shared.workspace.LangiumDocuments.hasDocument(entry)) {\n return {\n status: \"invalid\",\n issues: [\n {\n path: files.path,\n line: FIRST,\n column: FIRST,\n start: 0,\n end: 0,\n message: \"ファイルを読めません\",\n },\n ],\n outline: emptyOutline,\n };\n }\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CACF;EACA,SAAS;CACX;CAEF,OAAO,OAAO,QAAQ,QAAQ,CAAC,CAAC,KAAK;AACvC,CAAC"}
@@ -0,0 +1,122 @@
1
+ import { a as importedUriOf, i as compileSong, n as createFumxServices, o as isNamed, p as isSong } from "./fumx-module-CmHFC-eI.mjs";
2
+ import { CstUtils, GrammarUtils, URI, isLeafCstNode } from "langium";
3
+ import { Array, Effect, Option, Predicate, pipe } from "effect";
4
+ // src/features/read-song/model/comments.ts
5
+ const KINDS = ["SL_COMMENT", "ML_COMMENT"];
6
+ const FIRST$1 = 1;
7
+ const leavesOf = (cst) => CstUtils.streamCst(cst).filter((node) => isLeafCstNode(node)).toArray();
8
+ const isComment = (leaf) => leaf.hidden && Array.contains(KINDS, leaf.tokenType.name);
9
+ const commentsOf = (root) => pipe(Option.fromNullishOr(root.$cstNode), Option.map(leavesOf), Option.getOrElse(() => []), Array.filter(isComment), Array.map((leaf) => ({
10
+ line: leaf.range.start.line + FIRST$1,
11
+ column: leaf.range.start.character + FIRST$1,
12
+ text: leaf.text
13
+ })));
14
+ // src/features/read-song/model/outline.ts
15
+ const emptyOutline = {
16
+ title: Option.none(),
17
+ names: [],
18
+ imports: [],
19
+ files: [],
20
+ comments: []
21
+ };
22
+ const spanOf = (node) => ({
23
+ start: node.offset,
24
+ end: node.end
25
+ });
26
+ const propertySpanOf = (node) => (property) => pipe(Option.fromNullishOr(GrammarUtils.findNodeForProperty(node.$cstNode, property)), Option.map(spanOf));
27
+ const namesOf = (song) => pipe(song.declarations, Array.filter(isNamed), Array.flatMap((declaration) => pipe(propertySpanOf(declaration)("name"), Option.map((span) => ({
28
+ type: declaration.$type,
29
+ name: declaration.name,
30
+ span
31
+ })), Option.toArray)));
32
+ const importsOf = (song) => pipe(song.imports, Array.flatMap((node) => pipe(propertySpanOf(node)("path"), Option.map((span) => ({
33
+ path: importedUriOf(node).fsPath,
34
+ span
35
+ })), Option.toArray)));
36
+ const outlineOf = (files) => (song) => ({
37
+ title: propertySpanOf(song)("title"),
38
+ names: namesOf(song),
39
+ imports: importsOf(song),
40
+ files,
41
+ comments: commentsOf(song)
42
+ });
43
+ // src/features/read-song/model/read-song.ts
44
+ const FIRST = 1;
45
+ const ERROR = 1;
46
+ const messageOf = (message) => {
47
+ if (Predicate.isString(message)) return message;
48
+ return message.value;
49
+ };
50
+ const loader = (services) => (read) => {
51
+ const { LangiumDocuments, LangiumDocumentFactory } = services.shared.workspace;
52
+ const load = (uri) => Effect.gen(function* loadDocument() {
53
+ if (LangiumDocuments.hasDocument(uri)) return;
54
+ const text = yield* read(uri.fsPath);
55
+ if (Option.isNone(text)) return;
56
+ const document = LangiumDocumentFactory.fromString(text.value, uri);
57
+ LangiumDocuments.addDocument(document);
58
+ yield* Effect.forEach(document.parseResult.value.imports, (node) => load(importedUriOf(node)), {
59
+ concurrency: 1,
60
+ discard: true
61
+ });
62
+ });
63
+ return load;
64
+ };
65
+ const issuesOf = (document) => pipe(document.diagnostics ?? [], Array.filter((diagnostic) => diagnostic.severity === ERROR), Array.map((diagnostic) => ({
66
+ path: document.uri.fsPath,
67
+ line: diagnostic.range.start.line + FIRST,
68
+ column: diagnostic.range.start.character + FIRST,
69
+ start: document.textDocument.offsetAt(diagnostic.range.start),
70
+ end: document.textDocument.offsetAt(diagnostic.range.end),
71
+ message: messageOf(diagnostic.message)
72
+ })));
73
+ const builtOf = (services) => (entry) => Effect.gen(function* build() {
74
+ const { workspace } = services.shared;
75
+ const documents = workspace.LangiumDocuments.all.toArray();
76
+ yield* Effect.promise(() => workspace.DocumentBuilder.build(documents, { validation: true }));
77
+ const files = pipe(documents, Array.map((document) => document.uri.fsPath));
78
+ const root = pipe(Option.fromNullishOr(workspace.LangiumDocuments.getDocument(entry)), Option.map((document) => document.parseResult.value), Option.filter(isSong));
79
+ const outline = pipe(root, Option.map(outlineOf(files)), Option.getOrElse(() => ({
80
+ ...emptyOutline,
81
+ files
82
+ })));
83
+ const issues = pipe(documents, Array.flatMap(issuesOf));
84
+ if (Array.isReadonlyArrayNonEmpty(issues)) return {
85
+ status: "invalid",
86
+ issues,
87
+ outline
88
+ };
89
+ return Option.match(root, {
90
+ onNone: () => ({
91
+ status: "invalid",
92
+ issues: [],
93
+ outline
94
+ }),
95
+ onSome: (song) => ({
96
+ status: "valid",
97
+ song: compileSong(song).value,
98
+ outline
99
+ })
100
+ });
101
+ });
102
+ const readSong = Effect.fnUntraced(function* read(files) {
103
+ const services = createFumxServices();
104
+ const entry = URI.file(files.path);
105
+ yield* loader(services)((path) => Effect.option(files.read(path)))(entry);
106
+ if (!services.shared.workspace.LangiumDocuments.hasDocument(entry)) return {
107
+ status: "invalid",
108
+ issues: [{
109
+ path: files.path,
110
+ line: FIRST,
111
+ column: FIRST,
112
+ start: 0,
113
+ end: 0,
114
+ message: "ファイルを読めません"
115
+ }],
116
+ outline: emptyOutline
117
+ };
118
+ return yield* builtOf(services)(entry);
119
+ });
120
+ export { readSong as t };
121
+
122
+ //# sourceMappingURL=read-song-CSIhaAEB.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"read-song-CSIhaAEB.mjs","names":["FIRST","Arr","Arr","Arr"],"sources":["../src/features/read-song/model/comments.ts","../src/features/read-song/model/outline.ts","../src/features/read-song/model/read-song.ts"],"sourcesContent":["import { Array as Arr, Option, pipe } from \"effect\";\nimport { CstUtils, isLeafCstNode } from \"langium\";\nimport type { AstNode, CstNode, LeafCstNode } from \"langium\";\n\nimport type { From } from \"./problem.ts\";\n\nconst KINDS = [\"SL_COMMENT\", \"ML_COMMENT\"];\nconst FIRST = 1;\n\nexport interface SourceComment {\n readonly line: number;\n readonly column: number;\n readonly text: string;\n}\n\nconst leavesOf: From<CstNode, readonly LeafCstNode[]> = (cst) =>\n CstUtils.streamCst(cst)\n .filter((node) => isLeafCstNode(node))\n .toArray();\n\nconst isComment: From<LeafCstNode, boolean> = (leaf) =>\n leaf.hidden && Arr.contains(KINDS, leaf.tokenType.name);\n\nexport const commentsOf: From<AstNode, readonly SourceComment[]> = (root) =>\n pipe(\n Option.fromNullishOr(root.$cstNode),\n Option.map(leavesOf),\n Option.getOrElse((): readonly LeafCstNode[] => []),\n Arr.filter(isComment),\n Arr.map((leaf) => ({\n line: leaf.range.start.line + FIRST,\n column: leaf.range.start.character + FIRST,\n text: leaf.text,\n })),\n );\n","import { Array as Arr, Option, pipe } from \"effect\";\nimport { GrammarUtils } from \"langium\";\nimport type { AstNode, CstNode } from \"langium\";\n\nimport type { Song as SongNode } from \"#generated/langium/ast.ts\";\n\nimport { commentsOf } from \"./comments.ts\";\nimport type { SourceComment } from \"./comments.ts\";\nimport { isNamed } from \"./declarations.ts\";\nimport type { Named } from \"./declarations.ts\";\nimport type { From } from \"./problem.ts\";\nimport { importedUriOf } from \"./scope.ts\";\n\nexport interface Span {\n readonly start: number;\n readonly end: number;\n}\n\nexport interface NamedSpan {\n readonly type: Named[\"$type\"];\n readonly name: string;\n readonly span: Span;\n}\n\nexport interface ImportSpan {\n readonly path: string;\n readonly span: Span;\n}\n\nexport interface Outline {\n readonly title: Option.Option<Span>;\n readonly names: readonly NamedSpan[];\n readonly imports: readonly ImportSpan[];\n readonly files: readonly string[];\n readonly comments: readonly SourceComment[];\n}\n\nexport const emptyOutline: Outline = {\n title: Option.none(),\n names: [],\n imports: [],\n files: [],\n comments: [],\n};\n\nconst spanOf: From<CstNode, Span> = (node) => ({ start: node.offset, end: node.end });\n\nconst propertySpanOf: From<AstNode, From<string, Option.Option<Span>>> = (node) => (property) =>\n pipe(\n Option.fromNullishOr(GrammarUtils.findNodeForProperty(node.$cstNode, property)),\n Option.map(spanOf),\n );\n\nconst namesOf: From<SongNode, readonly NamedSpan[]> = (song) =>\n pipe(\n song.declarations,\n Arr.filter(isNamed),\n Arr.flatMap((declaration) =>\n pipe(\n propertySpanOf(declaration)(\"name\"),\n Option.map((span) => ({ type: declaration.$type, name: declaration.name, span })),\n Option.toArray,\n ),\n ),\n );\n\nconst importsOf: From<SongNode, readonly ImportSpan[]> = (song) =>\n pipe(\n song.imports,\n Arr.flatMap((node) =>\n pipe(\n propertySpanOf(node)(\"path\"),\n Option.map((span) => ({ path: importedUriOf(node).fsPath, span })),\n Option.toArray,\n ),\n ),\n );\n\nexport const outlineOf: From<readonly string[], From<SongNode, Outline>> = (files) => (song) => ({\n title: propertySpanOf(song)(\"title\"),\n names: namesOf(song),\n imports: importsOf(song),\n files,\n comments: commentsOf(song),\n});\n","import { Array as Arr, Effect, Option, Predicate, pipe } from \"effect\";\nimport { URI } from \"langium\";\nimport type { LangiumDocument } from \"langium\";\nimport type { Diagnostic } from \"vscode-languageserver\";\n\nimport type { Song } from \"#/entities/song/index.ts\";\nimport { isSong } from \"#generated/langium/ast.ts\";\nimport type { Song as SongNode } from \"#generated/langium/ast.ts\";\n\nimport { compileSong } from \"./compile.ts\";\nimport { createFumxServices } from \"./fumx-module.ts\";\nimport type { FumxServices } from \"./fumx-module.ts\";\nimport { emptyOutline, outlineOf } from \"./outline.ts\";\nimport type { Outline } from \"./outline.ts\";\nimport type { From } from \"./problem.ts\";\nimport { importedUriOf } from \"./scope.ts\";\n\nconst FIRST = 1;\nconst ERROR = 1;\n\nexport interface SourceIssue {\n readonly path: string;\n readonly line: number;\n readonly column: number;\n readonly start: number;\n readonly end: number;\n readonly message: string;\n}\n\nexport type SongSource =\n | {\n readonly status: \"invalid\";\n readonly issues: readonly SourceIssue[];\n readonly outline: Outline;\n }\n | { readonly status: \"valid\"; readonly song: Song; readonly outline: Outline };\n\nexport interface SongFiles<Failure> {\n readonly path: string;\n readonly read: (path: string) => Effect.Effect<string, Failure>;\n}\n\nconst messageOf: From<Diagnostic[\"message\"], string> = (message) => {\n if (Predicate.isString(message)) {\n return message;\n }\n return message.value;\n};\n\ntype Reader = From<string, Effect.Effect<Option.Option<string>>>;\n\nconst loader: From<FumxServices, From<Reader, From<URI, Effect.Effect<void>>>> =\n (services) => (read) => {\n const { LangiumDocuments, LangiumDocumentFactory } = services.shared.workspace;\n const load: From<URI, Effect.Effect<void>> = (uri) =>\n Effect.gen(function* loadDocument() {\n if (LangiumDocuments.hasDocument(uri)) {\n return;\n }\n const text = yield* read(uri.fsPath);\n if (Option.isNone(text)) {\n return;\n }\n const document = LangiumDocumentFactory.fromString<SongNode>(text.value, uri);\n LangiumDocuments.addDocument(document);\n yield* Effect.forEach(\n document.parseResult.value.imports,\n (node) => load(importedUriOf(node)),\n { concurrency: 1, discard: true },\n );\n });\n return load;\n };\n\nconst issuesOf: From<LangiumDocument, readonly SourceIssue[]> = (document) =>\n pipe(\n document.diagnostics ?? [],\n Arr.filter((diagnostic) => diagnostic.severity === ERROR),\n Arr.map((diagnostic) => ({\n path: document.uri.fsPath,\n line: diagnostic.range.start.line + FIRST,\n column: diagnostic.range.start.character + FIRST,\n start: document.textDocument.offsetAt(diagnostic.range.start),\n end: document.textDocument.offsetAt(diagnostic.range.end),\n message: messageOf(diagnostic.message),\n })),\n );\n\nconst builtOf: From<FumxServices, From<URI, Effect.Effect<SongSource>>> = (services) => (entry) =>\n Effect.gen(function* build() {\n const { workspace } = services.shared;\n const documents = workspace.LangiumDocuments.all.toArray();\n yield* Effect.promise(() => workspace.DocumentBuilder.build(documents, { validation: true }));\n const files = pipe(\n documents,\n Arr.map((document) => document.uri.fsPath),\n );\n const root = pipe(\n Option.fromNullishOr(workspace.LangiumDocuments.getDocument(entry)),\n Option.map((document) => document.parseResult.value),\n Option.filter(isSong),\n );\n const outline = pipe(\n root,\n Option.map(outlineOf(files)),\n Option.getOrElse(() => ({ ...emptyOutline, files })),\n );\n const issues = pipe(documents, Arr.flatMap(issuesOf));\n if (Arr.isReadonlyArrayNonEmpty(issues)) {\n return { status: \"invalid\", issues, outline };\n }\n return Option.match(root, {\n onNone: (): SongSource => ({ status: \"invalid\", issues: [], outline }),\n onSome: (song): SongSource => ({ status: \"valid\", song: compileSong(song).value, outline }),\n });\n });\n\nexport const readSong = Effect.fnUntraced(function* read<Failure>(\n files: SongFiles<Failure>,\n): Effect.fn.Return<SongSource> {\n const services = createFumxServices();\n const entry = URI.file(files.path);\n yield* loader(services)((path) => Effect.option(files.read(path)))(entry);\n if (!services.shared.workspace.LangiumDocuments.hasDocument(entry)) {\n return {\n status: \"invalid\",\n issues: [\n {\n path: files.path,\n line: FIRST,\n column: FIRST,\n start: 0,\n end: 0,\n message: \"ファイルを読めません\",\n },\n ],\n outline: emptyOutline,\n };\n }\n return yield* builtOf(services)(entry);\n});\n"],"mappings":";;;;AAMA,MAAM,QAAQ,CAAC,cAAc,YAAY;AACzC,MAAMA,UAAQ;AAQd,MAAM,YAAmD,QACvD,SAAS,UAAU,GAAG,CAAC,CACpB,QAAQ,SAAS,cAAc,IAAI,CAAC,CAAC,CACrC,QAAQ;AAEb,MAAM,aAAyC,SAC7C,KAAK,UAAUC,MAAI,SAAS,OAAO,KAAK,UAAU,IAAI;AAExD,MAAa,cAAuD,SAClE,KACE,OAAO,cAAc,KAAK,QAAQ,GAClC,OAAO,IAAI,QAAQ,GACnB,OAAO,gBAAwC,CAAC,CAAC,GACjDA,MAAI,OAAO,SAAS,GACpBA,MAAI,KAAK,UAAU;CACjB,MAAM,KAAK,MAAM,MAAM,OAAOD;CAC9B,QAAQ,KAAK,MAAM,MAAM,YAAYA;CACrC,MAAM,KAAK;AACb,EAAE,CACJ;;ACGF,MAAa,eAAwB;CACnC,OAAO,OAAO,KAAK;CACnB,OAAO,CAAC;CACR,SAAS,CAAC;CACV,OAAO,CAAC;CACR,UAAU,CAAC;AACb;AAEA,MAAM,UAA+B,UAAU;CAAE,OAAO,KAAK;CAAQ,KAAK,KAAK;AAAI;AAEnF,MAAM,kBAAoE,UAAU,aAClF,KACE,OAAO,cAAc,aAAa,oBAAoB,KAAK,UAAU,QAAQ,CAAC,GAC9E,OAAO,IAAI,MAAM,CACnB;AAEF,MAAM,WAAiD,SACrD,KACE,KAAK,cACLE,MAAI,OAAO,OAAO,GAClBA,MAAI,SAAS,gBACX,KACE,eAAe,WAAW,CAAC,CAAC,MAAM,GAClC,OAAO,KAAK,UAAU;CA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AM,KAAK,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK;CACxE,IAAI,CAAC,SAAS,OAAO,UAAU,iBAAiB,YAAY,KAAK,GAC/D,OAAO;EACL,QAAQ;EACR,QAAQ,CACN;GACE,MAAM,MAAM;GACZ,MAAM;GACN,QAAQ;GACR,OAAO;GACP,KAAK;GACL,SAAS;EACX,CACF;EACA,SAAS;CACX;CAEF,OAAO,OAAO,QAAQ,QAAQ,CAAC,CAAC,KAAK;AACvC,CAAC"}
@@ -0,0 +1,26 @@
1
+ import { Effect, Layer, Option } from "effect";
2
+ import { runMain } from "@effect/platform-node/NodeRuntime";
3
+ import { layer } from "@effect/platform-node/NodeServices";
4
+ import { FetchHttpClient } from "effect/http";
5
+ import { Otlp, OtlpSerialization } from "effect/observability";
6
+ // ../node-main/src/features/run-main/model/run-main.ts
7
+ const platform = Layer.mergeAll(layer, FetchHttpClient.layer);
8
+ const runWithTracingAnd = ({ serviceName, services, onFailure }) => (program) => {
9
+ const tracing = Otlp.layerFromConfig({ resource: { serviceName } }).pipe(Layer.provide(OtlpSerialization.layerJson), Layer.provide(FetchHttpClient.layer));
10
+ const provided = Layer.provideMerge(services, platform);
11
+ const report = Option.fromNullishOr(onFailure);
12
+ const reported = Option.match(report, {
13
+ onNone: () => program,
14
+ onSome: (handler) => Effect.tapCause(program, handler)
15
+ });
16
+ runMain(Layer.mergeAll(tracing, provided).pipe(Layer.build, Effect.flatMap((context) => Effect.provideContext(reported, context)), Effect.scoped), { disableErrorReporting: Option.isSome(report) });
17
+ };
18
+ const runWithTracing = (serviceName) => runWithTracingAnd({
19
+ serviceName,
20
+ services: Layer.empty
21
+ });
22
+ /** @internal */
23
+ const runMain$1 = runWithTracing;
24
+ export { runMain$1 as t };
25
+
26
+ //# sourceMappingURL=run-main-Bf32CgzU.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-main-Bf32CgzU.mjs","names":["nodeServices","runMain"],"sources":["../../node-main/src/features/run-main/model/run-main.ts"],"sourcesContent":["import { runMain as nodeRuntimeRunMain } from \"@effect/platform-node/NodeRuntime\";\nimport { layer as nodeServices } from \"@effect/platform-node/NodeServices\";\nimport type { NodeServices } from \"@effect/platform-node/NodeServices\";\nimport { Effect, Layer, Option } from \"effect\";\nimport type { Cause } from \"effect\";\nimport { FetchHttpClient } from \"effect/http\";\nimport type { HttpClient } from \"effect/http\";\nimport { Otlp, OtlpSerialization } from \"effect/observability\";\n\n/** @internal */\nexport type Platform = NodeServices | HttpClient.HttpClient;\n\n/** @internal */\nexport type Run<Provided> = <Success, Failure>(\n program: Effect.Effect<Success, Failure, Platform | Provided>,\n) => void;\n\n/** @internal */\nexport type Report<Provided> = <Failure>(\n cause: Cause.Cause<Failure>,\n) => Effect.Effect<void, never, Platform | Provided>;\n\nconst platform = Layer.mergeAll(nodeServices, FetchHttpClient.layer);\n\nconst runWithTracingAnd =\n <Provided, LayerFailure>({\n serviceName,\n services,\n onFailure,\n }: Readonly<{\n serviceName: string;\n services: Layer.Layer<Provided, LayerFailure, Platform>;\n onFailure?: Report<Provided>;\n }>): Run<Provided> =>\n (program) => {\n const tracing = Otlp.layerFromConfig({ resource: { serviceName } }).pipe(\n Layer.provide(OtlpSerialization.layerJson),\n Layer.provide(FetchHttpClient.layer),\n );\n const provided = Layer.provideMerge(services, platform);\n const report = Option.fromNullishOr(onFailure);\n const reported = Option.match(report, {\n onNone: () => program,\n onSome: (handler) => Effect.tapCause(program, handler),\n });\n nodeRuntimeRunMain(\n Layer.mergeAll(tracing, provided).pipe(\n Layer.build,\n Effect.flatMap((context) => Effect.provideContext(reported, context)),\n Effect.scoped,\n ),\n { disableErrorReporting: Option.isSome(report) },\n );\n };\n\nconst runWithTracing = (serviceName: string): Run<never> =>\n runWithTracingAnd({ serviceName, services: Layer.empty });\n\n/** @internal */\nexport const runMainWith = runWithTracingAnd;\n\n/** @internal */\nexport const runMain = runWithTracing;\n"],"mappings":";;;;;;AAsBA,MAAM,WAAW,MAAM,SAASA,OAAc,gBAAgB,KAAK;AAEnE,MAAM,qBACqB,EACvB,aACA,UACA,iBAMD,YAAY;CACX,MAAM,UAAU,KAAK,gBAAgB,EAAE,UAAU,EAAE,YAAY,EAAE,CAAC,CAAC,CAAC,KAClE,MAAM,QAAQ,kBAAkB,SAAS,GACzC,MAAM,QAAQ,gBAAgB,KAAK,CACrC;CACA,MAAM,WAAW,MAAM,aAAa,UAAU,QAAQ;CACtD,MAAM,SAAS,OAAO,cAAc,SAAS;CAC7C,MAAM,WAAW,OAAO,MAAM,QAAQ;EACpC,cAAc;EACd,SAAS,YAAY,OAAO,SAAS,SAAS,OAAO;CACvD,CAAC;CACD,QACE,MAAM,SAAS,SAAS,QAAQ,CAAC,CAAC,KAChC,MAAM,OACN,OAAO,SAAS,YAAY,OAAO,eAAe,UAAU,OAAO,CAAC,GACpE,OAAO,MACT,GACA,EAAE,uBAAuB,OAAO,OAAO,MAAM,EAAE,CACjD;AACF;AAEF,MAAM,kBAAkB,gBACtB,kBAAkB;CAAE;CAAa,UAAU,MAAM;AAAM,CAAC;;AAM1D,MAAaC,YAAU"}