barmark 0.0.3 → 0.1.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 (41) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/LICENSE +21 -0
  3. package/README.md +74 -9
  4. package/dist/chart/barLine.d.ts +26 -0
  5. package/dist/chart/barLine.js +242 -0
  6. package/dist/chart/directives.d.ts +14 -0
  7. package/dist/chart/directives.js +108 -0
  8. package/dist/chart/document.d.ts +7 -0
  9. package/dist/chart/document.js +116 -0
  10. package/dist/chart/expand.d.ts +14 -0
  11. package/dist/chart/expand.js +271 -0
  12. package/dist/chart/index.d.ts +7 -0
  13. package/dist/chart/index.js +6 -0
  14. package/dist/chart/parse.d.ts +3 -0
  15. package/dist/chart/parse.js +17 -0
  16. package/dist/chart/print.d.ts +25 -0
  17. package/dist/chart/print.js +144 -0
  18. package/dist/chart/types.d.ts +130 -0
  19. package/dist/chart/types.js +1 -0
  20. package/dist/chords/harte.d.ts +16 -0
  21. package/dist/chords/harte.js +122 -0
  22. package/dist/chords/index.d.ts +6 -0
  23. package/dist/chords/index.js +4 -0
  24. package/dist/chords/intervals.d.ts +11 -0
  25. package/dist/chords/intervals.js +60 -0
  26. package/dist/chords/noteSet.d.ts +3 -0
  27. package/dist/chords/noteSet.js +73 -0
  28. package/dist/chords/parse.d.ts +6 -0
  29. package/dist/chords/parse.js +116 -0
  30. package/dist/chords/print.d.ts +5 -0
  31. package/dist/chords/print.js +10 -0
  32. package/dist/chords/suffixes.d.ts +13 -0
  33. package/dist/chords/suffixes.js +49 -0
  34. package/dist/chords/types.d.ts +30 -0
  35. package/dist/chords/types.js +1 -0
  36. package/dist/chords/vocabulary.d.ts +41 -0
  37. package/dist/chords/vocabulary.js +207 -0
  38. package/dist/index.d.ts +2 -0
  39. package/dist/index.js +2 -0
  40. package/package.json +36 -6
  41. package/index.js +0 -11
package/CHANGELOG.md ADDED
@@ -0,0 +1,52 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+ While the version is 0.x, a minor release may change the grammar or the API.
8
+ Releases follow the process in [RELEASING.md](RELEASING.md).
9
+
10
+ ## [Unreleased]
11
+
12
+ ## [0.1.0] - 2026-10-31
13
+
14
+ The first working release: the reference parser and printer for the
15
+ [grammar v0.1 draft](docs/grammar-v0.1-draft.md).
16
+
17
+ ### Added
18
+
19
+ - **`parseChart(text)`** reads a whole `.chart.md` chart into the document as written (title, sections, directives, bar lines, text) and the bars in play order. Every bar carries its section, key, meter, tempo and feel. Section replays, `x N` and `|: :|` repeats, open repeats (`x ...`), `%` simile, `->` elision, fermatas (`...`) and one-bar meters (`[2/4]`) are all expanded. Problems come back as errors and warnings with line numbers, and the parser never throws.
20
+ - **`printChart(text)`** rewrites a chart in canonical form: standard spellings (`♯`→`#`, `X2`/`×2`→`x2`, `→`→`->`, `…`→`...`, `NC`→`N.C.`), the fewest slots per cell (`| G / D / |` → `| G D |`), and tidy directives and headings. Printing keeps the meaning (same bars, same errors) and is stable. Lines with errors, and lyrics, print exactly as written.
21
+ - **`parseChord(symbol)`** reads a chord symbol (Appendix A's vocabulary, with aliases such as `CM7`→`Cmaj7` rejected with a suggestion) into its root, intervals, spelled pitches, bass and canonical spelling.
22
+ - **`parseNoteSet("{D E! G}")`** reads a chord given by its notes, with optional octaves and a marked root.
23
+ - **Harte labels:** `toHarte` writes the Harte (2005) label for any chord or note set, and `harteToBarmark` converts a Harte label back. Every label in the McGill Billboard and Isophonics Beatles datasets converts with exactly the same notes.
24
+ - TypeScript declarations ship with the package.
25
+
26
+ ### Changed
27
+
28
+ - The package is ESM only, with an `exports` map, and needs Node 20 or later. The 0.0.x placeholder's `VERSION` and throwing `parse()` are gone.
29
+
30
+ ## [0.0.3] - 2026-10-31
31
+
32
+ ### Changed
33
+
34
+ - **The README links the grammar v0.1 draft.**
35
+
36
+ ## [0.0.2] - 2026-10-31
37
+
38
+ ### Technical
39
+
40
+ - **First publish through npm trusted publishing** (OIDC, with provenance), from the GitHub release workflow.
41
+
42
+ ## [0.0.1] - 2026-10-30
43
+
44
+ ### Added
45
+
46
+ - **A placeholder package that holds the `barmark` name** while the spec and parser are written.
47
+
48
+ [Unreleased]: https://github.com/kevinpeckham/barmark/compare/v0.1.0...HEAD
49
+ [0.1.0]: https://github.com/kevinpeckham/barmark/compare/v0.0.3...v0.1.0
50
+ [0.0.3]: https://github.com/kevinpeckham/barmark/compare/v0.0.2...v0.0.3
51
+ [0.0.2]: https://github.com/kevinpeckham/barmark/releases/tag/v0.0.2
52
+ [0.0.1]: https://www.npmjs.com/package/barmark/v/0.0.1
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kevin Peckham
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,16 +1,81 @@
1
1
  # barmark
2
2
 
3
- Markdown-inspired plain-text notation for chord charts — the bar grid
3
+ Markdown-inspired plain-text notation for chord charts: the bar grid
4
4
  musicians already write (`| D | A |`), specified precisely enough for
5
5
  machines.
6
6
 
7
- This package currently reserves the name while the spec and reference
8
- parser are written. The grammar draft (v0.1, for review) is
9
- [docs/grammar-v0.1-draft.md](https://github.com/kevinpeckham/barmark/blob/main/docs/grammar-v0.1-draft.md);
10
- the founding brief, prior art and roadmap live in
11
- [BRIEF.md](https://github.com/kevinpeckham/barmark/blob/main/BRIEF.md).
7
+ ```
8
+ # Example Song
9
+ key: D, time: 4/4, tempo: 145
12
10
 
13
- A barmark file is a markdown file: the extension is `.chart.md`.
11
+ ## Verse
12
+ |: D | A | Bm | G :|
13
+ | Em | / | A | A7 |
14
14
 
15
- - Spec license: CC-BY 4.0 (when published)
16
- - Code license: MIT
15
+ ## Chorus
16
+ | G / D / | A | Bm / / A | G |
17
+
18
+ ## Verse
19
+ ## Chorus x2
20
+ ```
21
+
22
+ A barmark file is a markdown file, with the extension `.chart.md`. The
23
+ grammar is [docs/grammar-v0.1-draft.md](docs/grammar-v0.1-draft.md)
24
+ (draft v0.1, for review), and [examples/](examples/) has a full chart.
25
+
26
+ ## Install
27
+
28
+ ```
29
+ npm install barmark
30
+ ```
31
+
32
+ ESM only, Node 20 or later (or Bun, Deno and browsers), with TypeScript
33
+ declarations included and no runtime dependencies.
34
+
35
+ ## Use
36
+
37
+ ```ts
38
+ import { parseChart, printChart, parseChord, harteToBarmark } from "barmark";
39
+
40
+ const chart = parseChart(text);
41
+ chart.title; // "Example Song"
42
+ chart.bars; // every bar in play order: slots, section, key, meter, tempo, feel
43
+ chart.sections; // each section as played, with its first and last bar
44
+ chart.diagnostics; // errors and warnings, each with a line number
45
+
46
+ printChart(text); // the chart in canonical form (same meaning, standard spelling)
47
+
48
+ const chord = parseChord("Bm7(b5)");
49
+ if (chord.ok) chord.value.pitches; // ["B", "D", "F", "A"]
50
+ if (chord.ok) chord.value.harte; // "B:hdim7"
51
+
52
+ harteToBarmark("A:sus4(b7,9)"); // "A9sus4"
53
+ ```
54
+
55
+ - **`parseChart`** never throws. A line with an error is left out of the
56
+ play order and reported, and the rest of the chart still reads.
57
+ - **`printChart`** changes spelling and layout only: lines with errors and
58
+ lyrics print exactly as written.
59
+ - **Harte labels** ([Harte et al., 2005](https://ismir2005.ismir.net/proceedings/1080.pdf))
60
+ convert both ways. Every label in the McGill Billboard and Isophonics
61
+ Beatles datasets converts to barmark with exactly the same notes.
62
+
63
+ ## Develop
64
+
65
+ ```
66
+ bun install
67
+ bun test # the test suite
68
+ bun run check # Biome and the TypeScript typecheck
69
+ bun run verify:package # build, check the npm package, import it in Node
70
+ ```
71
+
72
+ CI runs these on every push and pull request. Releases follow
73
+ [RELEASING.md](RELEASING.md); changes are in [CHANGELOG.md](CHANGELOG.md),
74
+ and lessons learned along the way are in [FINDINGS.md](FINDINGS.md). The
75
+ project's founding brief, prior art and roadmap are in
76
+ [BRIEF.md](BRIEF.md).
77
+
78
+ ## License
79
+
80
+ The code is MIT ([LICENSE](LICENSE)). The grammar specification will be
81
+ published under CC-BY 4.0.
@@ -0,0 +1,26 @@
1
+ import type { ChartDiagnostic, Line, Repeat } from "./types.js";
2
+ type BarsLine = Extract<Line, {
3
+ kind: "bars";
4
+ }>;
5
+ /** The `x N` or `x ...` count after a bar line or heading, checked against the spec's limits. */
6
+ export declare function readRepeat(count: string, line: number, diagnostics: ChartDiagnostic[]): Repeat;
7
+ /**
8
+ * Split an `x N` or `x ...` tail (`X` and `×` accepted) off the end of `text`, scanning from the
9
+ * right so long whitespace runs stay linear. With `boundary`, the `x` must
10
+ * start the text or follow whitespace (`## Box2` is a name).
11
+ */
12
+ export declare function repeatTail(text: string, boundary: boolean): {
13
+ rest: string;
14
+ count: string;
15
+ } | null;
16
+ /** The `x N` a mistyped repeat (`x2` in a cell, `2x`, `(x2)`) most likely meant, or null. */
17
+ export declare function misplacedRepeat(token: string): string | null;
18
+ /**
19
+ * One bar line: cells between pipes, each cell's slots, the `|:` and `:|`
20
+ * marks and an `x N` tail. Any error drops the whole line (`bars` is null).
21
+ */
22
+ export declare function parseBarLine(text: string, line: number): {
23
+ bars: BarsLine | null;
24
+ diagnostics: ChartDiagnostic[];
25
+ };
26
+ export {};
@@ -0,0 +1,242 @@
1
+ import { parseNoteSet } from "../chords/noteSet.js";
2
+ import { parseChord } from "../chords/parse.js";
3
+ import { parseMeter } from "./directives.js";
4
+ const FERMATA = new Set(["...", "…"]);
5
+ const SILENCE = new Set(["--", "–", "—"]);
6
+ /** The `x N` or `x ...` count after a bar line or heading, checked against the spec's limits. */
7
+ export function readRepeat(count, line, diagnostics) {
8
+ if (FERMATA.has(count))
9
+ return "open";
10
+ const n = Number(count);
11
+ if (!Number.isSafeInteger(n)) {
12
+ diagnostics.push({
13
+ line,
14
+ severity: "error",
15
+ message: "a repeat count this large is not a number of passes",
16
+ token: `x${count}`,
17
+ });
18
+ return null;
19
+ }
20
+ if (n < 2) {
21
+ diagnostics.push({
22
+ line,
23
+ severity: "error",
24
+ message: "a repeat count must be at least 2",
25
+ token: `x${count}`,
26
+ });
27
+ return null;
28
+ }
29
+ if (n > 8)
30
+ diagnostics.push({
31
+ line,
32
+ severity: "warning",
33
+ message: "an unusually large repeat count",
34
+ token: `x${count}`,
35
+ });
36
+ return n;
37
+ }
38
+ /**
39
+ * Split an `x N` or `x ...` tail (`X` and `×` accepted) off the end of `text`, scanning from the
40
+ * right so long whitespace runs stay linear. With `boundary`, the `x` must
41
+ * start the text or follow whitespace (`## Box2` is a name).
42
+ */
43
+ export function repeatTail(text, boundary) {
44
+ const t = text.trimEnd();
45
+ const x = Math.max(t.lastIndexOf("x"), t.lastIndexOf("X"), t.lastIndexOf("×"));
46
+ if (x < 0)
47
+ return null;
48
+ const count = t.slice(x + 1).trim();
49
+ if (!/^(\d+|\.\.\.|…)$/.test(count))
50
+ return null;
51
+ const rest = t.slice(0, x);
52
+ if (boundary && rest !== "" && !/\s/.test(rest.at(-1) ?? ""))
53
+ return null;
54
+ return { rest: rest.trimEnd(), count };
55
+ }
56
+ /** The `x N` a mistyped repeat (`x2` in a cell, `2x`, `(x2)`) most likely meant, or null. */
57
+ export function misplacedRepeat(token) {
58
+ const m = /^\(?\s*[xX×]\s*(\d+|\.\.\.|…)\s*\)?$/.exec(token) ?? /^\(?\s*(\d+)\s*[xX×]\s*\)?$/.exec(token);
59
+ return m ? `x${m[1]}` : null;
60
+ }
61
+ /** Diagnostics listed per line before the rest are summarized. */
62
+ const MAX_LINE_DIAGNOSTICS = 20;
63
+ /** Split a group on `_`, leaving any `_` inside braces to the note set. */
64
+ function groupMembers(token) {
65
+ const out = [""];
66
+ let depth = 0;
67
+ for (const ch of token) {
68
+ if (ch === "{")
69
+ depth++;
70
+ if (ch === "}")
71
+ depth = Math.max(0, depth - 1);
72
+ if (ch === "_" && depth === 0)
73
+ out.push("");
74
+ else
75
+ out[out.length - 1] += ch;
76
+ }
77
+ return out;
78
+ }
79
+ /** Whitespace-separated tokens, keeping a brace group whole. */
80
+ function tokens(text) {
81
+ const out = [];
82
+ let current = "";
83
+ let depth = 0;
84
+ for (const ch of text) {
85
+ if (ch === "{")
86
+ depth++;
87
+ if (ch === "}")
88
+ depth = Math.max(0, depth - 1);
89
+ if (/\s/.test(ch) && depth === 0) {
90
+ if (current)
91
+ out.push(current);
92
+ current = "";
93
+ }
94
+ else
95
+ current += ch;
96
+ }
97
+ if (current)
98
+ out.push(current);
99
+ return out;
100
+ }
101
+ /**
102
+ * One bar line: cells between pipes, each cell's slots, the `|:` and `:|`
103
+ * marks and an `x N` tail. Any error drops the whole line (`bars` is null).
104
+ */
105
+ export function parseBarLine(text, line) {
106
+ const diagnostics = [];
107
+ let listed = 0;
108
+ const add = (d) => {
109
+ listed++;
110
+ if (listed <= MAX_LINE_DIAGNOSTICS)
111
+ diagnostics.push(d);
112
+ else if (listed === MAX_LINE_DIAGNOSTICS + 1)
113
+ diagnostics.push({
114
+ line,
115
+ severity: "error",
116
+ message: "further problems on this line are not listed",
117
+ token: "",
118
+ });
119
+ };
120
+ const error = (message, token, suggestion) => {
121
+ add({ line, severity: "error", message, token, ...(suggestion ? { suggestion } : {}) });
122
+ return null;
123
+ };
124
+ const warn = (message, token) => add({ line, severity: "warning", message, token });
125
+ let body = text.trim();
126
+ let repeat = null;
127
+ const lastPipe = body.lastIndexOf("|");
128
+ const tail = repeatTail(body.slice(lastPipe + 1), true);
129
+ if (tail) {
130
+ body = body.slice(0, lastPipe + 1) + tail.rest;
131
+ repeat = readRepeat(tail.count, line, diagnostics);
132
+ }
133
+ const opens = body.startsWith("|:");
134
+ if (opens)
135
+ body = `|${body.slice(2)}`;
136
+ const closes = body.endsWith(":|");
137
+ if (closes)
138
+ body = `${body.slice(0, -2)}|`;
139
+ if (/\|\d/.test(body))
140
+ error("endings are not supported in v0.1", /\|\d+/.exec(body)?.[0] ?? "|");
141
+ if (body.includes(":|") || body.includes("|:"))
142
+ error("|: must open a bar line and :| must close one", body.includes(":|") ? ":|" : "|:");
143
+ // A misplaced mark makes the cells unreadable: report it once, not again as chords.
144
+ if (diagnostics.some((d) => d.severity === "error"))
145
+ return { bars: null, diagnostics };
146
+ const parts = body.split("|").slice(1);
147
+ if (parts.at(-1)?.trim() === "")
148
+ parts.pop();
149
+ else
150
+ warn("missing trailing |", parts.at(-1)?.trim() ?? "");
151
+ const simple = (token) => {
152
+ if (token === "/")
153
+ return { kind: "hold" };
154
+ if (SILENCE.has(token))
155
+ return { kind: "silence" };
156
+ if (token === "-")
157
+ return error("a lone - is not a slot; silence is --", token, "--");
158
+ if (token === "?") {
159
+ warn("unknown harmony", token);
160
+ return { kind: "unknown" };
161
+ }
162
+ if (/^n\.?c\.?$/i.test(token))
163
+ return { kind: "nc" };
164
+ const misplaced = misplacedRepeat(token);
165
+ if (misplaced)
166
+ return error("a repeat is written x N after the final |", token, misplaced);
167
+ if (token === "%" || FERMATA.has(token))
168
+ return error(`${token} must be alone in a cell`, token);
169
+ const r = token.startsWith("{") ? parseNoteSet(token) : parseChord(token);
170
+ if (!r.ok)
171
+ return error(r.error.message, token, r.error.suggestion);
172
+ for (const w of r.warnings)
173
+ warn(w.message, w.token);
174
+ return { kind: "chord", chord: r.value };
175
+ };
176
+ if (parts.length === 0)
177
+ error("a bar line needs at least one cell", text.trim());
178
+ const cells = [];
179
+ for (const raw of parts) {
180
+ let rest = raw.trim();
181
+ if (!rest) {
182
+ error("an empty cell; use / to hold or % to repeat", "| |");
183
+ continue;
184
+ }
185
+ let meter = null;
186
+ const bracket = /^\[([^\]]*)\]/.exec(rest);
187
+ if (bracket) {
188
+ meter = parseMeter(bracket[1] ?? "");
189
+ if (!meter)
190
+ error("not a time signature", bracket[0]);
191
+ rest = rest.slice(bracket[0].length).trim();
192
+ }
193
+ if (rest.includes("[")) {
194
+ error("a [n/d] meter must start its cell", rest);
195
+ continue;
196
+ }
197
+ const list = tokens(rest);
198
+ if (list.length === 0) {
199
+ error("a cell needs at least one slot", raw.trim());
200
+ continue;
201
+ }
202
+ if (list.length === 1 && meter && (list[0] === "%" || FERMATA.has(list[0] ?? ""))) {
203
+ error("a one-bar meter cannot go on % or ...", rest);
204
+ continue;
205
+ }
206
+ if (list.length === 1 && !meter && list[0] === "%") {
207
+ cells.push({ kind: "simile" });
208
+ continue;
209
+ }
210
+ if (list.length === 1 && !meter && FERMATA.has(list[0] ?? "")) {
211
+ cells.push({ kind: "fermata" });
212
+ continue;
213
+ }
214
+ const slots = [];
215
+ for (const token of list) {
216
+ const parts = groupMembers(token);
217
+ if (parts.length === 1) {
218
+ const s = simple(token);
219
+ if (s)
220
+ slots.push(s);
221
+ continue;
222
+ }
223
+ const members = [];
224
+ for (const m of parts) {
225
+ if (!m)
226
+ error("an empty member in a group", token);
227
+ else {
228
+ const s = simple(m);
229
+ if (s)
230
+ members.push(s);
231
+ }
232
+ }
233
+ slots.push({ kind: "group", members });
234
+ }
235
+ cells.push({ kind: "slots", meter, slots });
236
+ }
237
+ const failed = diagnostics.some((d) => d.severity === "error");
238
+ return {
239
+ bars: failed ? null : { kind: "bars", line, opens, closes, cells, repeat },
240
+ diagnostics,
241
+ };
242
+ }
@@ -0,0 +1,14 @@
1
+ import type { ChartDiagnostic, Directives, Meter } from "./types.js";
2
+ export declare const DIRECTIVE_NAMES: readonly ["key", "time", "tempo", "feel"];
3
+ /** `n/d` with n from 1 to 32 and d in 2, 4, 8, 16. */
4
+ export declare function parseMeter(text: string): Meter | null;
5
+ /** Beats per bar: compound meters (6/8, 9/8, 12/8) count dotted quarters. */
6
+ export declare function beatsOf(m: Meter): number;
7
+ /**
8
+ * A directive line: one or more `name: value` parts separated by commas.
9
+ * Returns null when the line does not start with a directive name and a colon.
10
+ */
11
+ export declare function parseDirectiveLine(text: string, line: number): {
12
+ set: Directives;
13
+ diagnostics: ChartDiagnostic[];
14
+ } | null;
@@ -0,0 +1,108 @@
1
+ export const DIRECTIVE_NAMES = ["key", "time", "tempo", "feel"];
2
+ const MODES = [
3
+ "major",
4
+ "minor",
5
+ "ionian",
6
+ "dorian",
7
+ "phrygian",
8
+ "lydian",
9
+ "mixolydian",
10
+ "aeolian",
11
+ "locrian",
12
+ ];
13
+ const FEELS = ["straight", "swing", "shuffle", "swing 16"];
14
+ /** `n/d` with n from 1 to 32 and d in 2, 4, 8, 16. */
15
+ export function parseMeter(text) {
16
+ const m = /^(\d{1,2})\/(\d{1,2})$/.exec(text.trim());
17
+ if (!m)
18
+ return null;
19
+ const n = Number(m[1]);
20
+ const d = Number(m[2]);
21
+ if (n < 1 || n > 32 || ![2, 4, 8, 16].includes(d))
22
+ return null;
23
+ return { n, d };
24
+ }
25
+ /** Beats per bar: compound meters (6/8, 9/8, 12/8) count dotted quarters. */
26
+ export function beatsOf(m) {
27
+ return m.d === 8 && [6, 9, 12].includes(m.n) ? m.n / 3 : m.n;
28
+ }
29
+ function parseKey(text) {
30
+ const m = /^([A-G])([#b♯♭]?)(m|\s+([A-Za-z]+))?$/.exec(text);
31
+ if (!m)
32
+ return null;
33
+ const tonic = `${m[1]}${(m[2] ?? "").replace("♯", "#").replace("♭", "b")}`;
34
+ if (m[3] === "m")
35
+ return { tonic, mode: "minor" };
36
+ if (m[4] === undefined)
37
+ return { tonic, mode: "major" };
38
+ const mode = m[4].toLowerCase();
39
+ return MODES.includes(mode) ? { tonic, mode } : null;
40
+ }
41
+ function parseTempo(text) {
42
+ const m = /^(\d+(?:\.\d+)?)(?:\s*bpm)?$/i.exec(text);
43
+ const n = m ? Number(m[1]) : 0;
44
+ return n >= 1 && n <= 999 ? n : null;
45
+ }
46
+ function parseFeel(text) {
47
+ const lower = text.toLowerCase();
48
+ return FEELS.find((f) => f === lower) ?? null;
49
+ }
50
+ /**
51
+ * A directive line: one or more `name: value` parts separated by commas.
52
+ * Returns null when the line does not start with a directive name and a colon.
53
+ */
54
+ export function parseDirectiveLine(text, line) {
55
+ const head = /^(\w+)\s*:/.exec(text.trim());
56
+ if (!head || !DIRECTIVE_NAMES.includes(head[1]?.toLowerCase()))
57
+ return null;
58
+ const set = {};
59
+ const seen = new Set();
60
+ const diagnostics = [];
61
+ const error = (message, token) => diagnostics.push({ line, severity: "error", message, token });
62
+ for (const part of text
63
+ .split(",")
64
+ .map((p) => p.trim())
65
+ .filter(Boolean)) {
66
+ const m = /^(\w+)\s*:\s*(.*)$/.exec(part);
67
+ const name = m?.[1]?.toLowerCase();
68
+ const value = m?.[2]?.trim() ?? "";
69
+ if (!m || !name || !DIRECTIVE_NAMES.includes(name)) {
70
+ error("unknown directive (key, time, tempo, feel)", part);
71
+ continue;
72
+ }
73
+ if (seen.has(name)) {
74
+ error(`${name} is given twice on this line`, name);
75
+ continue;
76
+ }
77
+ seen.add(name);
78
+ if (name === "key") {
79
+ const key = parseKey(value);
80
+ if (key)
81
+ set.key = key;
82
+ else
83
+ error("key must be a root with optional m or a mode", value);
84
+ }
85
+ else if (name === "time") {
86
+ const time = parseMeter(value);
87
+ if (time)
88
+ set.time = time;
89
+ else
90
+ error("time must be n/d with d of 2, 4, 8 or 16", value);
91
+ }
92
+ else if (name === "tempo") {
93
+ const tempo = parseTempo(value);
94
+ if (tempo)
95
+ set.tempo = tempo;
96
+ else
97
+ error("tempo must be beats per minute, from 1 to 999", value);
98
+ }
99
+ else {
100
+ const feel = parseFeel(value);
101
+ if (feel)
102
+ set.feel = feel;
103
+ else
104
+ error("feel must be straight, swing, shuffle or swing 16", value);
105
+ }
106
+ }
107
+ return { set, diagnostics };
108
+ }
@@ -0,0 +1,7 @@
1
+ import type { ChartDiagnostic, Line } from "./types.js";
2
+ /** Classify every line of a chart: title, sections, directives, bar lines and text. */
3
+ export declare function readDocument(text: string): {
4
+ title: string | null;
5
+ lines: Line[];
6
+ diagnostics: ChartDiagnostic[];
7
+ };
@@ -0,0 +1,116 @@
1
+ import { parseChord } from "../chords/parse.js";
2
+ import { misplacedRepeat, parseBarLine, readRepeat, repeatTail } from "./barLine.js";
3
+ import { parseDirectiveLine } from "./directives.js";
4
+ const NEAR_DIRECTIVES = {
5
+ meter: "time",
6
+ signature: "time",
7
+ bpm: "tempo",
8
+ groove: "feel",
9
+ };
10
+ function readHeading(text, line, diagnostics) {
11
+ let rest = text.trim();
12
+ const elided = /(->|→)$/.test(rest);
13
+ if (elided)
14
+ rest = rest.replace(/(->|→)$/, "").trim();
15
+ let repeat = null;
16
+ const tail = repeatTail(rest, true);
17
+ if (tail) {
18
+ repeat = readRepeat(tail.count, line, diagnostics);
19
+ rest = tail.rest.trim();
20
+ }
21
+ const typo = /\s(\S+)$/.exec(rest);
22
+ const meant = typo?.[1] ? misplacedRepeat(typo[1]) : null;
23
+ if (typo && meant)
24
+ diagnostics.push({
25
+ line,
26
+ severity: "warning",
27
+ message: "a section repeat is written x N",
28
+ token: typo[1] ?? "",
29
+ suggestion: `## ${rest.slice(0, typo.index)} ${meant}`,
30
+ });
31
+ if (/->|→/.test(rest))
32
+ diagnostics.push({
33
+ line,
34
+ severity: "error",
35
+ message: "-> goes at the end of a replay heading",
36
+ token: "->",
37
+ });
38
+ if (!rest)
39
+ diagnostics.push({
40
+ line,
41
+ severity: "error",
42
+ message: "a section heading needs a name",
43
+ token: text,
44
+ });
45
+ return { kind: "section", line, name: rest, repeat, elided };
46
+ }
47
+ /** A warning when a text line looks like an older chart format. */
48
+ function oldFormat(text, line) {
49
+ const warn = (message, suggestion) => ({
50
+ line,
51
+ severity: "warning",
52
+ message,
53
+ token: text,
54
+ suggestion,
55
+ });
56
+ const label = /^\[([^\]]+)\]$/.exec(text) ?? /^([A-Za-z][\w ]*):$/.exec(text);
57
+ if (label?.[1])
58
+ return warn("a section label; barmark headings start with ##", `## ${label[1].trim()}`);
59
+ const near = /^(\w+)\s*:\s*(.*)$/.exec(text);
60
+ const name = near?.[1] ? NEAR_DIRECTIVES[near[1].toLowerCase()] : undefined;
61
+ if (near && name)
62
+ return warn(`not a directive; did you mean ${name}:?`, `${name}: ${near[2]}`);
63
+ const words = text.split(/\s+/);
64
+ if (words.length >= 2 && words.every((w) => parseChord(w).ok))
65
+ return warn("chords outside a bar line are text", `| ${words.join(" | ")} |`);
66
+ return null;
67
+ }
68
+ /** Classify every line of a chart: title, sections, directives, bar lines and text. */
69
+ export function readDocument(text) {
70
+ const lines = [];
71
+ const diagnostics = [];
72
+ let title = null;
73
+ const physical = text.replace(/^/, "").split(/\r?\n/);
74
+ physical.forEach((raw, i) => {
75
+ const line = i + 1;
76
+ const t = raw.trim();
77
+ if (!t || t.startsWith("```"))
78
+ return;
79
+ if (t.startsWith("|")) {
80
+ const r = parseBarLine(t, line);
81
+ diagnostics.push(...r.diagnostics);
82
+ lines.push(r.bars ?? { kind: "invalid", line, text: t });
83
+ return;
84
+ }
85
+ if (t.startsWith("# ")) {
86
+ if (title === null) {
87
+ title = t.slice(2).trim();
88
+ lines.push({ kind: "title", line, text: title });
89
+ return;
90
+ }
91
+ diagnostics.push({
92
+ line,
93
+ severity: "warning",
94
+ message: "a chart has one title; this is text",
95
+ token: t,
96
+ });
97
+ lines.push({ kind: "text", line, text: t });
98
+ return;
99
+ }
100
+ if (t === "##" || t.startsWith("## ")) {
101
+ lines.push(readHeading(t.slice(2), line, diagnostics));
102
+ return;
103
+ }
104
+ const directive = parseDirectiveLine(t, line);
105
+ if (directive) {
106
+ diagnostics.push(...directive.diagnostics);
107
+ lines.push({ kind: "directive", line, set: directive.set });
108
+ return;
109
+ }
110
+ const old = oldFormat(t, line);
111
+ if (old)
112
+ diagnostics.push(old);
113
+ lines.push({ kind: "text", line, text: t });
114
+ });
115
+ return { title, lines, diagnostics };
116
+ }