@barmark/score 0.1.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.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,90 @@ package uses [semantic versioning](https://semver.org/).
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.2.0] - 2026-11-09
10
+
11
+ ### Added
12
+
13
+ - **Limits on what a score may cost, exported.** `EngraveOptions.maxCost`
14
+ and `maxXmlLength`, `scoreCost`, `MAX_SCORE_COST` and `MAX_XML_LENGTH`
15
+ (`engraveChart`), and `createEngine`'s options `grace`, `loadDeadline`
16
+ and `deadline` with their defaults `SUPERSEDED_GRACE_MS`,
17
+ `LOAD_DEADLINE_MS` and `JOB_DEADLINE_MS`, and the `EngineOptions`,
18
+ `Ready` and `WorkerMessage` types. What they bound is under Fixed.
19
+
20
+ ### Changed
21
+
22
+ - **Requires `barmark` 0.22.0, `@barmark/render` 0.18.0 and
23
+ `@barmark/musicxml` 0.8.0**, whose minor releases a caret range would
24
+ not reach. Grid and Score now number a pickup alike: bar 0, with the
25
+ first full bar 1.
26
+
27
+ ### Fixed
28
+
29
+ - **A score too large to draw is refused, not attempted.** A short chart
30
+ with repeats can play thousands of bars, and writing a crowded one out
31
+ took gigabytes of MusicXML (and a phone's tab). The export now stops
32
+ writing at `MAX_XML_LENGTH` (50,000,000 characters, `@barmark/musicxml`'s
33
+ new `maxLength`), and before it, as a cheap early refusal, `engraveChart`
34
+ estimates the score's size (`scoreCost`: every played bar's measure in
35
+ every declared part, tacet ones too, each slot, pitch, chord degree,
36
+ syllable and words with the length of its escaped text, and each bar's
37
+ heading, in one pass) and refuses more than `MAX_SCORE_COST`
38
+ (50,000,000) unexported. Either way the reason is "The score is too
39
+ large to draw", so the element shows its note. `EngraveOptions.maxCost`
40
+ and `maxXmlLength` set them. Needs the `@barmark/musicxml` release that
41
+ adds `maxLength`.
42
+
43
+ - **A slow score no longer holds up every later one.** The worker takes
44
+ one job at a time; a request its element has since replaced is never
45
+ sent, and one already engraving is cut off (the worker is terminated and
46
+ a fresh one takes the requests still waiting) once it has engraved for
47
+ `SUPERSEDED_GRACE_MS` (3 s), so a normal job still finishes and keeps
48
+ the loaded Verovio. A job still loading Verovio is never cut for this.
49
+ Loading Verovio has `LOAD_DEADLINE_MS` (60 s, for a 7 MB download on a
50
+ slow line) and engraving `JOB_DEADLINE_MS` (20 s, from the worker's new
51
+ `Ready` message); past either the job is cut off and its request rejects
52
+ with "The score engine failed", so the element shows its note. A worker
53
+ that crashes fails only the job it was on; the requests still waiting
54
+ run on a fresh one. All three are `createEngine` options (`grace`,
55
+ `loadDeadline`, `deadline`). A fresh worker loads the Verovio the first
56
+ one loaded (its `Ready` says which), so the first `verovio-url` that
57
+ loads still wins for the page.
58
+
59
+ ### Technical
60
+
61
+ - **The README gives Verovio's copyright and source**, and how to build with
62
+ another Verovio (LGPL-3.0).
63
+
64
+ ## [0.1.1] - 2026-11-09
65
+
66
+ Requires `@barmark/musicxml` 0.7.2.
67
+
68
+ ### Fixed
69
+
70
+ - **A chord symbol is drawn as the chart spells it.** Verovio 6.4 appends
71
+ every `<degree>` to the kind text, `print-object="no"` or not, so
72
+ `D7sus4` was drawn `D7sus4(7)` and `G5(7)` as `G5(7)(no3)`. The score
73
+ now drops a degree that is not printed before Verovio reads the
74
+ MusicXML (with `@barmark/musicxml`'s next release, which hides a degree
75
+ its kind text already spells). `Engraved.xml` is the export unchanged.
76
+ The pass is linear (a single `indexOf` scan, no backtracking regex), so a
77
+ hostile MusicXML given to `engraveXml` cannot stall it.
78
+ - **The Grid / Score switch follows the element's `theme`.** It sits
79
+ outside the grid's themed `.bm-chart`, and render's `:host{all:initial}`
80
+ reset its colour and font, so on a dark page it was black text in the
81
+ browser's serif. It now takes render's ink and rule for `theme="dark"`,
82
+ for `auto` (or no theme) under a dark colour scheme, and light ones
83
+ otherwise and in print, honouring `--barmark-ink` and `--barmark-rule`,
84
+ in render's label font (`--barmark-label-font`). A page no longer has to
85
+ colour the host itself.
86
+ - **Chord accidentals and the tempo's note draw in Chromium.** Verovio
87
+ declares its Leipzig font (the ♯, ♭ and ♩) inside the score's SVG, in the
88
+ shadow root, where Chromium never registers a font face, so `C♯m7` drew
89
+ as `C m7`. The element now copies that face, once per document, into a
90
+ `<style data-barmark-score-font>` in the head. A page that copied it
91
+ itself can drop the copy.
92
+
9
93
  ## [0.1.0] - 2026-11-08
10
94
 
11
95
  First release.
@@ -62,5 +146,7 @@ First release.
62
146
  needs no config; Vite 7 needs `optimizeDeps.exclude` and
63
147
  `worker.format: "es"`.
64
148
 
65
- [Unreleased]: https://github.com/kevinpeckham/barmark/compare/score-v0.1.0...HEAD
149
+ [Unreleased]: https://github.com/kevinpeckham/barmark/compare/score-v0.2.0...HEAD
150
+ [0.2.0]: https://github.com/kevinpeckham/barmark/compare/score-v0.1.1...score-v0.2.0
151
+ [0.1.1]: https://github.com/kevinpeckham/barmark/compare/score-v0.1.0...score-v0.1.1
66
152
  [0.1.0]: https://github.com/kevinpeckham/barmark/releases/tag/score-v0.1.0
package/README.md CHANGED
@@ -94,8 +94,12 @@ worker, so a later or different URL is not loaded.
94
94
  ### When the score can't be drawn
95
95
 
96
96
  If Verovio fails to load, or rejects the MusicXML, or the chart will not
97
- export, the grid stays and a note by the switch says "The score couldn't
98
- be drawn". The reason goes to the console.
97
+ export or is too large to draw (see "Engraving directly"), or Verovio
98
+ takes over 60 seconds to load or 20 seconds to engrave, the grid stays and
99
+ a note by the switch says "The score couldn't be drawn". The reason goes
100
+ to the console. A score an element no longer wants (its chart or width
101
+ changed) is dropped, and cut off after three seconds if the worker is
102
+ already engraving it.
99
103
 
100
104
  ## On the server
101
105
 
@@ -125,19 +129,36 @@ if (result.ok) document.body.innerHTML = result.svg;
125
129
  else console.warn(result.reason);
126
130
  ```
127
131
 
132
+ A score is refused with the reason "The score is too large to draw" when
133
+ its MusicXML would pass 50,000,000 characters (`MAX_XML_LENGTH`): the
134
+ export stops writing there. A short chart with repeats can play thousands
135
+ of bars, and writing them all out could take gigabytes. Before exporting,
136
+ `scoreCost` estimates the MusicXML's bytes in one pass over the play order
137
+ (every played bar's measure in every declared part, a tacet part's rests
138
+ too, each slot, pitch, chord degree, syllable and words with the length of
139
+ its text, and each bar's heading), and a chart over 50,000,000
140
+ (`MAX_SCORE_COST`) is refused without exporting. A long lead sheet costs
141
+ about half a million. Pass `maxXmlLength` or `maxCost` to set either.
142
+
128
143
  The SVG is cleaned with an allow-list (`cleanSvg`) before it is returned;
129
144
  `scorePane` and `scoreStyles` wrap it so it follows the grid's light and
130
- dark palette.
145
+ dark palette. `engraveChart` and `engraveXml` drop a chord `<degree>`
146
+ marked `print-object="no"` before Verovio reads the MusicXML, as Verovio
147
+ 6.4 prints every degree after the chord's text (`D7sus4(7)`); `result.xml`
148
+ is the export unchanged.
131
149
 
132
150
  ## Licence
133
151
 
134
152
  This package is MIT. It uses [Verovio](https://github.com/rism-digital/verovio),
135
153
  which is LGPL-3.0-only, as an ordinary npm dependency, loaded unchanged at
136
154
  run time; its code is never copied into this package. barmark's own code
137
- stays MIT. Verovio's licence text is
155
+ stays MIT. Verovio © Laurent Pugin and others; its licence text is
138
156
  [COPYING.LESSER](https://github.com/rism-digital/verovio/blob/develop/COPYING.LESSER).
139
157
 
140
158
  A site that bundles the worker ships Verovio inside its bundle. Keeping
141
159
  Verovio a separate file (through `verovio-url`, or the bundler's own
142
- chunk) and keeping its notice is the easy way to meet the LGPL. This is
143
- not legal advice.
160
+ chunk) and keeping its notice is the easy way to meet the LGPL. If it is
161
+ bundled into one file with the worker instead (Vite 8 does this), credit it
162
+ with its copyright and licence, host or link the LGPL and GPL texts, and
163
+ link your site's source so a visitor can rebuild it with another Verovio;
164
+ barmark.dev does all three in its footer. This is not legal advice.
package/dist/element.js CHANGED
@@ -9,7 +9,7 @@
9
9
  import { FONT_FAMILY, fontFaceCss, renderChartUnwrapped, } from "@barmark/render";
10
10
  import { chartSource, inlineChartText, optionsFromAttributes, } from "@barmark/render/element";
11
11
  import { parseChart } from "barmark";
12
- import { scorePane } from "./markup.js";
12
+ import { isLeipzigFace, scorePane } from "./markup.js";
13
13
  import { decodeCarried, gridError, scoreShell } from "./shell.js";
14
14
  import { viewOf } from "./switch.js";
15
15
  let testEngine = null;
@@ -47,6 +47,24 @@ function addFont(doc) {
47
47
  font.setAttribute("data-barmark-font", FONT_FAMILY);
48
48
  doc.head.append(font);
49
49
  }
50
+ /**
51
+ * Verovio's Leipzig face (the ♯, ♭ and ♩ of chord symbols and tempo marks), once per
52
+ * document. Verovio declares it in a `<style>` inside the score's SVG, in the shadow
53
+ * root, where Chromium never registers a font face, so "C♯m7" drew as "C m7". The
54
+ * copy is the face `cleanSvg` already let through, checked again here.
55
+ */
56
+ function addScoreFont(doc, pane) {
57
+ if (doc.querySelector("style[data-barmark-score-font]") !== null)
58
+ return;
59
+ const css = [...pane.querySelectorAll("style")]
60
+ .map((s) => s.textContent ?? "")
61
+ .find(isLeipzigFace);
62
+ if (!css)
63
+ return;
64
+ const font = Object.assign(doc.createElement("style"), { textContent: css });
65
+ font.setAttribute("data-barmark-score-font", "Leipzig");
66
+ doc.head.append(font);
67
+ }
50
68
  const load = (src) => fetch(src).then((r) => r.ok ? r.text() : Promise.reject(new Error(`${r.status} ${r.statusText}`.trim())));
51
69
  /** Text set on the element before it was defined is an own property; it is taken off and returned. */
52
70
  function takeEarlyText(el) {
@@ -358,6 +376,7 @@ function defineElement() {
358
376
  if (this.#revealed?.svg !== svg || this.#revealed.theme !== theme) {
359
377
  try {
360
378
  pane.innerHTML = scorePane(svg, theme, label);
379
+ addScoreFont(this.ownerDocument, pane);
361
380
  }
362
381
  catch (e) {
363
382
  return this.#fail(messageOf(e));
package/dist/engine.d.ts CHANGED
@@ -18,6 +18,19 @@ export type Reply = {
18
18
  };
19
19
  /** An `EngraveReply` is a reply a page may show. */
20
20
  export type EngraveReply = Reply;
21
+ /**
22
+ * What the worker says before it engraves job `id`: its Verovio is loaded,
23
+ * and from where (no `verovioUrl`: the package's own), so the engine can
24
+ * start the job's deadline and give a replacement worker the same Verovio.
25
+ */
26
+ export type Ready = {
27
+ id: number;
28
+ loaded: {
29
+ verovioUrl?: string;
30
+ };
31
+ };
32
+ /** Every message a worker sends: a job's `Ready`, then its `Reply`. */
33
+ export type WorkerMessage = Reply | Ready;
21
34
  /**
22
35
  * The part of a `Worker` the engine uses, so a test can pass a fake. It is
23
36
  * driven by the `onmessage` and `onerror` properties (a real `Worker`
@@ -26,18 +39,42 @@ export type EngraveReply = Reply;
26
39
  export interface WorkerLike {
27
40
  postMessage(request: Request): void;
28
41
  terminate(): void;
29
- onmessage: ((e: MessageEvent<Reply>) => void) | null;
42
+ onmessage: ((e: MessageEvent<WorkerMessage>) => void) | null;
30
43
  onerror: ((e: ErrorEvent) => void) | null;
31
44
  }
32
45
  export type Engine = {
33
46
  /**
34
47
  * Engrave `text` for `width`. Per `key` (the element) only the newest
35
48
  * request resolves with a reply; an older one resolves `null`. Rejects
36
- * with "The score engine failed" if the worker crashes.
49
+ * with "The score engine failed" if the worker crashes on it, or its
50
+ * Verovio load or its engraving runs past its deadline.
37
51
  */
38
52
  engrave(key: object, text: string, width: number, verovioUrl?: string): Promise<EngraveReply | null>;
39
53
  };
40
- /** An engine over one worker made on first use; a crashed worker is replaced on the next call. */
41
- export declare function createEngine(makeWorker: () => WorkerLike): Engine;
54
+ /** How long one job may engrave, from its worker's Verovio being ready, before the worker is cut off and the request rejects. */
55
+ export declare const JOB_DEADLINE_MS = 20000;
56
+ /** How long a worker may take to load Verovio for a job (a 7 MB download and compile on a slow line) before it is cut off. */
57
+ export declare const LOAD_DEADLINE_MS = 60000;
58
+ /**
59
+ * How long a job no one waits for any more (a newer request from its
60
+ * element superseded it) may engrave before its worker is cut off. Most
61
+ * jobs finish well within it, even on a slow device, and keeping the
62
+ * worker keeps its loaded Verovio. A job still loading Verovio is never
63
+ * cut for this: the load serves the next job.
64
+ */
65
+ export declare const SUPERSEDED_GRACE_MS = 3000;
66
+ export type EngineOptions = {
67
+ deadline?: number;
68
+ loadDeadline?: number;
69
+ grace?: number;
70
+ };
71
+ /**
72
+ * An engine over one worker made on first use, given one job at a time. A
73
+ * job whose worker crashes, or whose Verovio load or engraving runs past
74
+ * its deadline, rejects; one superseded and past its grace is dropped.
75
+ * Either way the worker is terminated and a fresh one (loading the
76
+ * Verovio the first one loaded) takes the requests still waiting.
77
+ */
78
+ export declare function createEngine(makeWorker: () => WorkerLike, options?: EngineOptions): Engine;
42
79
  /** The page's single shared engine, over one real module `Worker` made on first use. */
43
80
  export declare function engine(): Engine;
package/dist/engine.js CHANGED
@@ -1,47 +1,133 @@
1
- /** An engine over one worker made on first use; a crashed worker is replaced on the next call. */
2
- export function createEngine(makeWorker) {
1
+ /** How long one job may engrave, from its worker's Verovio being ready, before the worker is cut off and the request rejects. */
2
+ export const JOB_DEADLINE_MS = 20_000;
3
+ /** How long a worker may take to load Verovio for a job (a 7 MB download and compile on a slow line) before it is cut off. */
4
+ export const LOAD_DEADLINE_MS = 60_000;
5
+ /**
6
+ * How long a job no one waits for any more (a newer request from its
7
+ * element superseded it) may engrave before its worker is cut off. Most
8
+ * jobs finish well within it, even on a slow device, and keeping the
9
+ * worker keeps its loaded Verovio. A job still loading Verovio is never
10
+ * cut for this: the load serves the next job.
11
+ */
12
+ export const SUPERSEDED_GRACE_MS = 3_000;
13
+ const FAILED = "The score engine failed";
14
+ const isReady = (m) => !("ok" in m);
15
+ const clear = (job) => {
16
+ for (const t of job.timers)
17
+ clearTimeout(t);
18
+ job.timers = [];
19
+ };
20
+ /**
21
+ * An engine over one worker made on first use, given one job at a time. A
22
+ * job whose worker crashes, or whose Verovio load or engraving runs past
23
+ * its deadline, rejects; one superseded and past its grace is dropped.
24
+ * Either way the worker is terminated and a fresh one (loading the
25
+ * Verovio the first one loaded) takes the requests still waiting.
26
+ */
27
+ export function createEngine(makeWorker, options = {}) {
28
+ const deadline = options.deadline ?? JOB_DEADLINE_MS;
29
+ const loadDeadline = options.loadDeadline ?? LOAD_DEADLINE_MS;
30
+ const grace = options.grace ?? SUPERSEDED_GRACE_MS;
3
31
  let worker = null;
32
+ let running = null;
33
+ let loaded;
4
34
  let nextId = 0;
35
+ const waiting = [];
5
36
  const pending = new Map();
6
37
  const newest = new WeakMap();
7
- const fail = (w) => {
8
- if (worker !== w)
38
+ const settle = (id) => {
39
+ const p = pending.get(id);
40
+ pending.delete(id);
41
+ return p;
42
+ };
43
+ /** Cuts off the job `id` if the worker is still on it (rejecting it for `reason`, if given), and moves on to the next. */
44
+ const cut = (id, reason) => {
45
+ if (running?.id !== id)
9
46
  return;
47
+ clear(running);
48
+ running = null;
49
+ const w = worker;
10
50
  worker = null;
11
- w.terminate();
12
- const all = [...pending.values()];
13
- pending.clear();
14
- for (const p of all)
15
- p.reject(new Error("The score engine failed"));
51
+ w?.terminate();
52
+ if (reason !== null)
53
+ settle(id)?.reject(new Error(reason));
54
+ next();
55
+ };
56
+ const overdue = (id, what) => () => cut(id, `${FAILED}: ${what} took too long`);
57
+ /** Verovio is ready: the job's engraving deadline and its grace start now. */
58
+ const onReady = (job, ready) => {
59
+ loaded ??= ready.loaded;
60
+ clear(job);
61
+ job.timers = [
62
+ setTimeout(overdue(job.id, "engraving"), deadline),
63
+ setTimeout(() => {
64
+ job.graceOver = true;
65
+ if (job.superseded)
66
+ cut(job.id, null);
67
+ }, grace),
68
+ ];
69
+ };
70
+ const onReply = (job, reply) => {
71
+ clear(job);
72
+ running = null;
73
+ settle(reply.id)?.resolve(reply);
74
+ next();
16
75
  };
17
76
  const start = () => {
18
77
  if (worker)
19
78
  return worker;
20
79
  const w = makeWorker();
21
- w.onmessage = (e) => {
22
- const p = pending.get(e.data.id);
23
- if (!p)
80
+ w.onmessage = ({ data }) => {
81
+ const job = running;
82
+ if (worker !== w || job?.id !== data.id)
24
83
  return;
25
- pending.delete(e.data.id);
26
- p.resolve(newest.get(p.key) === e.data.id ? e.data : null);
84
+ if (isReady(data))
85
+ onReady(job, data);
86
+ else
87
+ onReply(job, data);
88
+ };
89
+ w.onerror = () => {
90
+ if (worker === w && running)
91
+ cut(running.id, FAILED);
27
92
  };
28
- w.onerror = () => fail(w);
29
93
  worker = w;
30
94
  return w;
31
95
  };
96
+ /** Gives the worker the next job, if it is free: the Verovio it loaded first, whatever the request asks. */
97
+ const next = () => {
98
+ const request = running ? undefined : waiting.shift();
99
+ if (!request)
100
+ return;
101
+ const { verovioUrl, ...rest } = request;
102
+ const url = loaded ? loaded.verovioUrl : verovioUrl;
103
+ const id = rest.id;
104
+ running = { id, superseded: false, graceOver: false, timers: [] };
105
+ running.timers = [setTimeout(overdue(id, "loading Verovio"), loadDeadline)];
106
+ start().postMessage(url === undefined ? rest : { ...rest, verovioUrl: url });
107
+ };
108
+ /** No one waits for `id` any more: drop it if it waits its turn, cut it off past its grace if it runs. */
109
+ const supersede = (id) => {
110
+ settle(id)?.resolve(null);
111
+ const at = waiting.findIndex((r) => r.id === id);
112
+ if (at >= 0)
113
+ waiting.splice(at, 1);
114
+ if (running?.id !== id)
115
+ return;
116
+ running.superseded = true;
117
+ if (running.graceOver)
118
+ cut(id, null);
119
+ };
32
120
  return {
33
121
  engrave(key, text, width, verovioUrl) {
34
- const w = start();
35
122
  const id = ++nextId;
36
123
  const before = newest.get(key);
37
- if (before !== undefined) {
38
- pending.get(before)?.resolve(null);
39
- pending.delete(before);
40
- }
41
124
  newest.set(key, id);
42
125
  return new Promise((resolve, reject) => {
43
- pending.set(id, { key, resolve, reject });
44
- w.postMessage(verovioUrl === undefined ? { id, text, width } : { id, text, width, verovioUrl });
126
+ pending.set(id, { resolve, reject });
127
+ if (before !== undefined)
128
+ supersede(before);
129
+ waiting.push(verovioUrl === undefined ? { id, text, width } : { id, text, width, verovioUrl });
130
+ next();
45
131
  });
46
132
  },
47
133
  };
package/dist/engrave.d.ts CHANGED
@@ -1,11 +1,35 @@
1
- import type { ChartDiagnostic } from "barmark";
1
+ import { type ChartDiagnostic, type ChartParse } from "barmark";
2
2
  import type { VerovioToolkit } from "verovio/esm";
3
3
  export type EngraveOptions = {
4
4
  /** The width available, in CSS pixels; below 320 it is 320. */
5
5
  width: number;
6
6
  /** Verovio's scale (default 40). */
7
7
  scale?: number;
8
+ /** The most the score may cost (`scoreCost`, about the bytes of MusicXML it writes); default `MAX_SCORE_COST`. */
9
+ maxCost?: number;
10
+ /** The longest MusicXML engraved, in characters: the export stops writing past it; default `MAX_XML_LENGTH`. */
11
+ maxXmlLength?: number;
8
12
  };
13
+ /**
14
+ * The most a score may cost (`scoreCost`, about the bytes of MusicXML it
15
+ * writes) before it is refused, unexported: a short chart with repeats can
16
+ * play thousands of bars, and writing each out could take gigabytes. A
17
+ * long lead sheet costs about half a megabyte.
18
+ */
19
+ export declare const MAX_SCORE_COST = 50000000;
20
+ /** The longest MusicXML handed to Verovio, in characters: the export stops writing past it (`maxLength`). */
21
+ export declare const MAX_XML_LENGTH = 50000000;
22
+ /**
23
+ * About how many bytes of MusicXML a score of the chart writes: every
24
+ * played bar's measure in every declared part (tacet ones too), each
25
+ * slot, pitch, degree, syllable and words, with the length of its text,
26
+ * and its heading. One pass over the play order, cheap enough to refuse a
27
+ * chart before exporting it. It is an early gate, not the bound: it
28
+ * leaves out what is rarely large (a part's silent lines, text lines), and
29
+ * the export's own `maxLength` budget, which `engraveChart` sets, is what
30
+ * keeps the MusicXML within `MAX_XML_LENGTH`.
31
+ */
32
+ export declare function scoreCost(parse: ChartParse): number;
9
33
  export type Engraved = {
10
34
  ok: true;
11
35
  svg: string;
@@ -26,10 +50,20 @@ export declare const LAYOUT: {
26
50
  readonly header: "auto";
27
51
  readonly justifyVertically: false;
28
52
  };
53
+ /**
54
+ * The MusicXML as Verovio should read it. Verovio 6.4 appends every chord <degree> to the
55
+ * kind text, `print-object="no"` or not, so a degree the text already spells is drawn twice
56
+ * (`D7sus4(7)`); a degree that is not printed is dropped, which changes nothing it draws.
57
+ */
58
+ export declare function forVerovio(xml: string): string;
29
59
  /** MusicXML laid out for a width, every page as SVG in a `bms-score-page` div. Throws on unreadable XML. */
30
60
  export declare function engraveXml(vrv: VerovioToolkit, xml: string, options: EngraveOptions): {
31
61
  svg: string;
32
62
  pages: number;
33
63
  };
34
- /** A chart as a full score, or why it cannot be one. */
64
+ /**
65
+ * A chart as a full score, or why it cannot be one. A chart that would
66
+ * cost more than `maxCost` is refused before it is exported, and the
67
+ * export stops writing MusicXML longer than `maxXmlLength`.
68
+ */
35
69
  export declare function engraveChart(vrv: VerovioToolkit, text: string, options: EngraveOptions): Engraved;
package/dist/engrave.js CHANGED
@@ -1,5 +1,73 @@
1
1
  import { exportMusicXml } from "@barmark/musicxml";
2
+ import { parseChart, } from "barmark";
2
3
  import { cleanSvg } from "./markup.js";
4
+ /**
5
+ * The most a score may cost (`scoreCost`, about the bytes of MusicXML it
6
+ * writes) before it is refused, unexported: a short chart with repeats can
7
+ * play thousands of bars, and writing each out could take gigabytes. A
8
+ * long lead sheet costs about half a megabyte.
9
+ */
10
+ export const MAX_SCORE_COST = 50_000_000;
11
+ /** The longest MusicXML handed to Verovio, in characters: the export stops writing past it (`maxLength`). */
12
+ export const MAX_XML_LENGTH = 50_000_000;
13
+ const TOO_LARGE = "The score is too large to draw";
14
+ // What the export writes for each thing, beyond its text, in bytes, from measuring it
15
+ // (see the calibration test in tests/engrave.test.ts): a part's measure (a rest when tacet), a
16
+ // line's voice in it, a note or slash, each pitch of a note set or chord, each degree of a
17
+ // chord symbol, a syllable, words, and a bar's heading or mark.
18
+ const COST = {
19
+ measure: 600,
20
+ line: 200,
21
+ slot: 450,
22
+ pitch: 250,
23
+ degree: 150,
24
+ syllable: 200,
25
+ words: 400,
26
+ heading: 300,
27
+ };
28
+ /** Text as the export escapes it: `&<>"'` take up to six bytes each. */
29
+ const escaped = (text) => text.length + 5 * (text.match(/[&<>"']/g)?.length ?? 0);
30
+ function chordCost(c) {
31
+ if (!c)
32
+ return 0;
33
+ return escaped(c.source) + c.pitches.length * COST.pitch + c.intervals.length * COST.degree;
34
+ }
35
+ /** A note or slash, and its chord or notes; its syllable is the bar's (`lyricsCost`). */
36
+ const memberCost = (m) => m.kind === "chord" ? COST.slot + chordCost(m.chord) + chordCost(m.voicing) : COST.slot;
37
+ const slotCost = (s) => s.kind === "group" ? s.members.reduce((n, m) => n + memberCost(m), 0) : memberCost(s);
38
+ const wordsCost = (words) => (words ?? []).reduce((n, w) => n + COST.words + escaped(w.text), 0);
39
+ const lineCost = (l) => COST.line + l.slots.reduce((n, s) => n + slotCost(s), 0) + wordsCost(l.words);
40
+ /** A part's share of a bar: its measure, then each line's notes, or its own. */
41
+ const partCost = (p) => COST.measure +
42
+ (p === null ? 0 : p.lines ? p.lines.reduce((n, l) => n + lineCost(l), 0) : lineCost(p));
43
+ /** A syllable and its text; one on no note of the singing line is a lyric staff's slash too. */
44
+ const syllableCost = ({ syllable, note }) => COST.syllable +
45
+ (syllable.kind === "sung" ? escaped(syllable.parts.join("")) : 0) +
46
+ (note ? 0 : COST.slot);
47
+ const lyricsCost = (bar) => (bar.lyrics ?? []).reduce((n, l) => n + l.syllables.reduce((m, s) => m + syllableCost(s), 0), 0);
48
+ /** One played bar: every declared part's measure (a tacet one's rest too), its notes and words, the sung syllables (a lyric staff's measure with them), and its heading. */
49
+ function barCost(bar, parts) {
50
+ const played = bar.parts
51
+ ? bar.parts.reduce((n, p) => n + partCost(p), 0) + (parts - bar.parts.length) * COST.measure
52
+ : partCost(bar);
53
+ const sung = bar.lyrics?.length ? COST.measure + lyricsCost(bar) : 0;
54
+ const heading = COST.heading + escaped(bar.section ?? "") + escaped(bar.rehearsal ?? "");
55
+ return played + sung + heading;
56
+ }
57
+ /**
58
+ * About how many bytes of MusicXML a score of the chart writes: every
59
+ * played bar's measure in every declared part (tacet ones too), each
60
+ * slot, pitch, degree, syllable and words, with the length of its text,
61
+ * and its heading. One pass over the play order, cheap enough to refuse a
62
+ * chart before exporting it. It is an early gate, not the bound: it
63
+ * leaves out what is rarely large (a part's silent lines, text lines), and
64
+ * the export's own `maxLength` budget, which `engraveChart` sets, is what
65
+ * keeps the MusicXML within `MAX_XML_LENGTH`.
66
+ */
67
+ export function scoreCost(parse) {
68
+ const parts = Math.max(1, parse.parts.length);
69
+ return parse.bars.reduce((n, bar) => n + barCost(bar, parts), 0);
70
+ }
3
71
  /** Verovio's options for a score, all but `pageWidth` and `scale`. */
4
72
  export const LAYOUT = {
5
73
  pageHeight: 60000,
@@ -12,6 +80,31 @@ export const LAYOUT = {
12
80
  };
13
81
  const DEFAULT_SCALE = 40;
14
82
  const MIN_WIDTH = 320;
83
+ const HIDDEN_DEGREE = '<degree print-object="no">';
84
+ const DEGREE_END = "</degree>";
85
+ /**
86
+ * The MusicXML as Verovio should read it. Verovio 6.4 appends every chord <degree> to the
87
+ * kind text, `print-object="no"` or not, so a degree the text already spells is drawn twice
88
+ * (`D7sus4(7)`); a degree that is not printed is dropped, which changes nothing it draws.
89
+ */
90
+ export function forVerovio(xml) {
91
+ // One pass with indexOf, never a backtracking regex: an opener with no closer ends the
92
+ // search, so a hostile file of openers costs linear time, not a rescan per opener.
93
+ const parts = [];
94
+ let from = 0;
95
+ for (;;) {
96
+ const open = xml.indexOf(HIDDEN_DEGREE, from);
97
+ if (open < 0)
98
+ break;
99
+ const close = xml.indexOf(DEGREE_END, open + HIDDEN_DEGREE.length);
100
+ if (close < 0)
101
+ break;
102
+ parts.push(xml.slice(from, open));
103
+ from = close + DEGREE_END.length;
104
+ }
105
+ parts.push(xml.slice(from));
106
+ return parts.join("");
107
+ }
15
108
  /** MusicXML laid out for a width, every page as SVG in a `bms-score-page` div. Throws on unreadable XML. */
16
109
  export function engraveXml(vrv, xml, options) {
17
110
  const scale = options.scale ?? DEFAULT_SCALE;
@@ -21,7 +114,7 @@ export function engraveXml(vrv, xml, options) {
21
114
  // Verovio's page width is in its own units at scale 100.
22
115
  pageWidth: Math.round((Math.max(MIN_WIDTH, options.width) * 100) / scale),
23
116
  });
24
- if (!vrv.loadData(xml))
117
+ if (!vrv.loadData(forVerovio(xml)))
25
118
  throw new Error("Verovio could not read the score");
26
119
  const pages = vrv.getPageCount();
27
120
  if (pages < 1)
@@ -38,9 +131,18 @@ function refusal(diagnostics) {
38
131
  // A diagnostic about the whole chart has line 0: there is no line to name.
39
132
  return first.line > 0 ? `Line ${first.line}: ${first.message}` : first.message;
40
133
  }
41
- /** A chart as a full score, or why it cannot be one. */
134
+ /**
135
+ * A chart as a full score, or why it cannot be one. A chart that would
136
+ * cost more than `maxCost` is refused before it is exported, and the
137
+ * export stops writing MusicXML longer than `maxXmlLength`.
138
+ */
42
139
  export function engraveChart(vrv, text, options) {
43
- const exported = exportMusicXml(text);
140
+ if (scoreCost(parseChart(text)) > (options.maxCost ?? MAX_SCORE_COST))
141
+ return { ok: false, reason: TOO_LARGE, diagnostics: [] };
142
+ // The export's own budget is the bound: it stops writing at the limit.
143
+ const exported = exportMusicXml(text, { maxLength: options.maxXmlLength ?? MAX_XML_LENGTH });
144
+ if (!exported.ok && exported.tooLarge)
145
+ return { ok: false, reason: TOO_LARGE, diagnostics: [] };
44
146
  if (!exported.ok)
45
147
  return { ok: false, reason: refusal(exported.diagnostics), diagnostics: exported.diagnostics };
46
148
  try {
package/dist/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- export { createEngine, type Engine, type EngraveReply, engine, type Reply, type Request, type WorkerLike, } from "./engine.js";
2
- export { type Engraved, type EngraveOptions, engraveChart, engraveXml, LAYOUT } from "./engrave.js";
1
+ export { createEngine, type Engine, type EngineOptions, type EngraveReply, engine, JOB_DEADLINE_MS, LOAD_DEADLINE_MS, type Ready, type Reply, type Request, SUPERSEDED_GRACE_MS, type WorkerLike, type WorkerMessage, } from "./engine.js";
2
+ export { type Engraved, type EngraveOptions, engraveChart, engraveXml, LAYOUT, MAX_SCORE_COST, MAX_XML_LENGTH, scoreCost, } from "./engrave.js";
3
3
  export { cleanSvg, type ScoreTheme, scorePane, scoreStyles } from "./markup.js";
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
- export { createEngine, engine, } from "./engine.js";
2
- export { engraveChart, engraveXml, LAYOUT } from "./engrave.js";
1
+ export { createEngine, engine, JOB_DEADLINE_MS, LOAD_DEADLINE_MS, SUPERSEDED_GRACE_MS, } from "./engine.js";
2
+ export { engraveChart, engraveXml, LAYOUT, MAX_SCORE_COST, MAX_XML_LENGTH, scoreCost, } from "./engrave.js";
3
3
  export { cleanSvg, scorePane, scoreStyles } from "./markup.js";
package/dist/markup.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  export type ScoreTheme = "auto" | "light" | "dark";
2
+ /** Whether a stylesheet is Verovio's embedded Leipzig face, exactly (and nothing else). */
3
+ export declare const isLeipzigFace: (css: string) => boolean;
2
4
  /**
3
5
  * Verovio's SVG reduced to what Verovio emits: only the listed elements and
4
6
  * attributes survive, an unlisted element goes with its content, links keep
package/dist/markup.js CHANGED
@@ -46,8 +46,10 @@ const STYLE_ID = /^#([A-Za-z0-9]+) g\.ending,/;
46
46
  const STYLE_TEMPLATE = "#@ g.ending, #@ g.fing, #@ g.reh, #@ g.tempo {font-weight:bold;}#@ g.dir, #@ g.dynam, #@ g.mNum {font-style:italic;}#@ g.label {font-weight:normal;}#@ ellipse, #@ path, #@ polygon, #@ polyline, #@ rect {stroke:currentColor}#@ g.cursor {fill:dodgerblue; color:dodgerblue;}#@ g.cursor.chord {fill:limegreen; color:limegreen;}#@ g.placeholder {visibility:hidden}";
47
47
  /** The one embedded font Verovio adds for some scores: Leipzig as a base64 woff2, nothing else. */
48
48
  const FONT_FACE = /^@font-face \{\s*font-family: 'Leipzig';\s*src: url\(data:application\/font-woff2;charset=utf-8;base64,[A-Za-z0-9+/=]+\) format\('woff2'\);\s*font-weight: normal;\s*font-style: normal;\s*\}$/;
49
+ /** Whether a stylesheet is Verovio's embedded Leipzig face, exactly (and nothing else). */
50
+ export const isLeipzigFace = (css) => FONT_FACE.test(css);
49
51
  function isVerovioStyle(css) {
50
- if (FONT_FACE.test(css))
52
+ if (isLeipzigFace(css))
51
53
  return true;
52
54
  const id = STYLE_ID.exec(css)?.[1];
53
55
  return id !== undefined && css === STYLE_TEMPLATE.replaceAll("@", id);
package/dist/switch.d.ts CHANGED
@@ -3,5 +3,16 @@ export type ScoreView = "grid" | "score";
3
3
  export declare const viewOf: (value: unknown) => ScoreView;
4
4
  /** The Grid / Score switch: a radio group of two buttons, the current view checked. */
5
5
  export declare function switchHtml(view: ScoreView): string;
6
- /** The switch's own look, in render's palette variables. */
7
- export declare const switchStyles = ".bms-switch{display:inline-flex;margin:0 0 .5rem;border:1px solid var(--bm-rule,currentColor);border-radius:.4rem;overflow:hidden}\n.bms-switch button{font:inherit;color:var(--bm-ink,inherit);background:transparent;border:0;padding:.25rem .75rem;cursor:pointer}\n.bms-switch button[aria-checked=\"true\"]{font-weight:bold;text-decoration:underline}\n.bms-switch button:focus-visible{outline:2px solid currentColor;outline-offset:-2px}\n.bms-switch button[aria-disabled=\"true\"]{opacity:.5;cursor:not-allowed}\n.bms-note{margin:0 0 .5rem;font-size:.875em;color:var(--bm-ink,inherit)}";
6
+ /**
7
+ * The switch's ink and rule: @barmark/render's palettes (its `PALETTES`, which it does not
8
+ * export; tests/switch.test.ts holds the two equal), with its `--barmark-ink` and
9
+ * `--barmark-rule` overrides. The switch sits outside render's `.bm-chart`, whose
10
+ * `data-theme` sets the palette, and render's `:host{all:initial}` resets its colour and
11
+ * font, so it keys the same choice off the element's own `theme` attribute.
12
+ */
13
+ export declare const SWITCH_PALETTES: Record<"light" | "dark", {
14
+ ink: string;
15
+ rule: string;
16
+ }>;
17
+ /** The switch's own look, in its theme's colours and render's label font. */
18
+ export declare const switchStyles: string;
package/dist/switch.js CHANGED
@@ -5,10 +5,28 @@ export function switchHtml(view) {
5
5
  const radio = (value, label) => `<button type="button" role="radio" data-view="${value}" aria-checked="${view === value}"${view === value ? "" : ' tabindex="-1"'}>${label}</button>`;
6
6
  return `<div class="bms-switch" role="radiogroup" aria-label="View">${radio("grid", "Grid")}${radio("score", "Score")}</div>`;
7
7
  }
8
- /** The switch's own look, in render's palette variables. */
9
- export const switchStyles = `.bms-switch{display:inline-flex;margin:0 0 .5rem;border:1px solid var(--bm-rule,currentColor);border-radius:.4rem;overflow:hidden}
10
- .bms-switch button{font:inherit;color:var(--bm-ink,inherit);background:transparent;border:0;padding:.25rem .75rem;cursor:pointer}
8
+ /**
9
+ * The switch's ink and rule: @barmark/render's palettes (its `PALETTES`, which it does not
10
+ * export; tests/switch.test.ts holds the two equal), with its `--barmark-ink` and
11
+ * `--barmark-rule` overrides. The switch sits outside render's `.bm-chart`, whose
12
+ * `data-theme` sets the palette, and render's `:host{all:initial}` resets its colour and
13
+ * font, so it keys the same choice off the element's own `theme` attribute.
14
+ */
15
+ export const SWITCH_PALETTES = {
16
+ light: { ink: "#1d1d1f", rule: "#4a4a4a" },
17
+ dark: { ink: "#ece8e0", rule: "#8f897f" },
18
+ };
19
+ const colours = ({ ink, rule }) => `--bms-ink:var(--barmark-ink,${ink});--bms-rule:var(--barmark-rule,${rule});`;
20
+ const AUTO = ':host(:not([theme="light"]):not([theme="dark"]))';
21
+ /** The switch's own look, in its theme's colours and render's label font. */
22
+ export const switchStyles = `:host{${colours(SWITCH_PALETTES.light)}}
23
+ :host([theme="dark"]){${colours(SWITCH_PALETTES.dark)}}
24
+ @media (prefers-color-scheme:dark){${AUTO}{${colours(SWITCH_PALETTES.dark)}}}
25
+ @media print{:host,:host([theme="dark"]),${AUTO}{${colours(SWITCH_PALETTES.light)}}}
26
+ .bms-switch,.bms-note{font-family:var(--barmark-label-font,system-ui,-apple-system,"Segoe UI",sans-serif)}
27
+ .bms-switch{display:inline-flex;margin:0 0 .5rem;border:1px solid var(--bms-rule);border-radius:.4rem;overflow:hidden}
28
+ .bms-switch button{font:inherit;color:var(--bms-ink);background:transparent;border:0;padding:.25rem .75rem;cursor:pointer}
11
29
  .bms-switch button[aria-checked="true"]{font-weight:bold;text-decoration:underline}
12
30
  .bms-switch button:focus-visible{outline:2px solid currentColor;outline-offset:-2px}
13
31
  .bms-switch button[aria-disabled="true"]{opacity:.5;cursor:not-allowed}
14
- .bms-note{margin:0 0 .5rem;font-size:.875em;color:var(--bm-ink,inherit)}`;
32
+ .bms-note{margin:0 0 .5rem;font-size:.875em;color:var(--bms-ink)}`;
package/dist/worker.d.ts CHANGED
@@ -1,8 +1,26 @@
1
1
  import { VerovioToolkit } from "verovio/esm";
2
- import type { Reply, Request } from "./engine.js";
2
+ import type { Ready, Reply, Request } from "./engine.js";
3
3
  type Toolkit = VerovioToolkit;
4
4
  /** Run `load` once and keep its result; a load that fails is forgotten, so the next call tries again. */
5
5
  export declare function loadOnce<A, T>(load: (arg: A) => Promise<T>): (arg: A) => Promise<T>;
6
+ /**
7
+ * A worker's one Verovio toolkit, loaded on first use and reused, and
8
+ * where it came from once loaded (no `verovioUrl`: the package's own), so
9
+ * the engine can give a replacement worker the same. The first load that
10
+ * succeeds wins for the worker's life: later URLs are ignored.
11
+ */
12
+ export declare function toolkitLoader<T>(load: (verovioUrl: string | undefined) => Promise<T>): {
13
+ ready: (arg: string | undefined) => Promise<T>;
14
+ loaded: () => {
15
+ verovioUrl?: string;
16
+ } | undefined;
17
+ };
18
+ /**
19
+ * The toolkit for `request`, saying it is `Ready` (and where it came
20
+ * from) once loaded, before the job is engraved: the engine starts the
21
+ * job's deadline then, so a slow download is not counted against it.
22
+ */
23
+ export declare function withReady<T>(loader: ReturnType<typeof toolkitLoader<T>>, request: Request, post: (ready: Ready) => void): () => Promise<T>;
6
24
  /** Answer one request. Never throws: a failure is a reply with its reason. */
7
25
  export declare function handle(request: Request, loaded: () => Promise<Toolkit>): Promise<Reply>;
8
26
  export {};
package/dist/worker.js CHANGED
@@ -15,12 +15,25 @@ export function loadOnce(load) {
15
15
  };
16
16
  }
17
17
  /**
18
- * The page's one Verovio toolkit, loaded on first use and reused. By
19
- * default the package's own `verovio/wasm`; when a request carries
20
- * `verovioUrl` that module is imported instead. The first request whose
21
- * load succeeds wins for the worker's life: later URLs are ignored.
18
+ * A worker's one Verovio toolkit, loaded on first use and reused, and
19
+ * where it came from once loaded (no `verovioUrl`: the package's own), so
20
+ * the engine can give a replacement worker the same. The first load that
21
+ * succeeds wins for the worker's life: later URLs are ignored.
22
22
  */
23
- const ready = loadOnce(async (verovioUrl) => {
23
+ export function toolkitLoader(load) {
24
+ let loaded;
25
+ const ready = loadOnce(async (verovioUrl) => {
26
+ const toolkit = await load(verovioUrl);
27
+ loaded = verovioUrl === undefined ? {} : { verovioUrl };
28
+ return toolkit;
29
+ });
30
+ return { ready, loaded: () => loaded };
31
+ }
32
+ /**
33
+ * By default the package's own `verovio/wasm`; when a request carries
34
+ * `verovioUrl` that module is imported instead.
35
+ */
36
+ const toolkit = toolkitLoader(async (verovioUrl) => {
24
37
  const m = verovioUrl
25
38
  ? await import(/* @vite-ignore */ verovioUrl)
26
39
  : await import("verovio/wasm");
@@ -28,6 +41,18 @@ const ready = loadOnce(async (verovioUrl) => {
28
41
  enableLog(LOG_OFF, module);
29
42
  return new VerovioToolkit(module);
30
43
  });
44
+ /**
45
+ * The toolkit for `request`, saying it is `Ready` (and where it came
46
+ * from) once loaded, before the job is engraved: the engine starts the
47
+ * job's deadline then, so a slow download is not counted against it.
48
+ */
49
+ export function withReady(loader, request, post) {
50
+ return async () => {
51
+ const toolkit = await loader.ready(request.verovioUrl);
52
+ post({ id: request.id, loaded: loader.loaded() ?? {} });
53
+ return toolkit;
54
+ };
55
+ }
31
56
  /** Answer one request. Never throws: a failure is a reply with its reason. */
32
57
  export async function handle(request, loaded) {
33
58
  const { id, text, width } = request;
@@ -46,7 +71,6 @@ const scope = globalThis;
46
71
  if (typeof scope.WorkerGlobalScope === "function" &&
47
72
  globalThis instanceof scope.WorkerGlobalScope) {
48
73
  scope.onmessage = async (e) => {
49
- const { verovioUrl } = e.data;
50
- scope.postMessage(await handle(e.data, () => ready(verovioUrl)));
74
+ scope.postMessage(await handle(e.data, withReady(toolkit, e.data, (r) => scope.postMessage(r))));
51
75
  };
52
76
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@barmark/score",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Show a barmark chord chart as a full engraved score: MusicXML from @barmark/musicxml, engraved by Verovio (LGPL-3.0, a dependency loaded unchanged).",
5
5
  "type": "module",
6
6
  "exports": {
@@ -49,9 +49,9 @@
49
49
  "url": "https://github.com/kevinpeckham/barmark/issues"
50
50
  },
51
51
  "dependencies": {
52
- "@barmark/musicxml": "^0.7.1",
53
- "@barmark/render": "^0.17.1",
54
- "barmark": "^0.21.0",
52
+ "@barmark/musicxml": "^0.8.0",
53
+ "@barmark/render": "^0.18.0",
54
+ "barmark": "^0.22.0",
55
55
  "verovio": "^6.4.1"
56
56
  },
57
57
  "scripts": {