@barmark/score 0.1.1 → 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,61 @@ 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
+
9
64
  ## [0.1.1] - 2026-11-09
10
65
 
11
66
  Requires `@barmark/musicxml` 0.7.2.
@@ -91,6 +146,7 @@ First release.
91
146
  needs no config; Vite 7 needs `optimizeDeps.exclude` and
92
147
  `worker.format: "es"`.
93
148
 
94
- [Unreleased]: https://github.com/kevinpeckham/barmark/compare/score-v0.1.1...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
95
151
  [0.1.1]: https://github.com/kevinpeckham/barmark/compare/score-v0.1.0...score-v0.1.1
96
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,6 +129,17 @@ 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
145
  dark palette. `engraveChart` and `engraveXml` drop a chord `<degree>`
@@ -137,10 +152,13 @@ is the export unchanged.
137
152
  This package is MIT. It uses [Verovio](https://github.com/rism-digital/verovio),
138
153
  which is LGPL-3.0-only, as an ordinary npm dependency, loaded unchanged at
139
154
  run time; its code is never copied into this package. barmark's own code
140
- stays MIT. Verovio's licence text is
155
+ stays MIT. Verovio © Laurent Pugin and others; its licence text is
141
156
  [COPYING.LESSER](https://github.com/rism-digital/verovio/blob/develop/COPYING.LESSER).
142
157
 
143
158
  A site that bundles the worker ships Verovio inside its bundle. Keeping
144
159
  Verovio a separate file (through `verovio-url`, or the bundler's own
145
- chunk) and keeping its notice is the easy way to meet the LGPL. This is
146
- 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/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;
@@ -37,5 +61,9 @@ export declare function engraveXml(vrv: VerovioToolkit, xml: string, options: En
37
61
  svg: string;
38
62
  pages: number;
39
63
  };
40
- /** 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
+ */
41
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,
@@ -63,9 +131,18 @@ function refusal(diagnostics) {
63
131
  // A diagnostic about the whole chart has line 0: there is no line to name.
64
132
  return first.line > 0 ? `Line ${first.line}: ${first.message}` : first.message;
65
133
  }
66
- /** 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
+ */
67
139
  export function engraveChart(vrv, text, options) {
68
- 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: [] };
69
146
  if (!exported.ok)
70
147
  return { ok: false, reason: refusal(exported.diagnostics), diagnostics: exported.diagnostics };
71
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/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.1",
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.2",
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": {