@zeeuw/riff 0.0.0-stage → 0.1.0-beta.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 (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +46 -2
  3. package/data/registry-data.js +3 -0
  4. package/data/signatures.js +3 -0
  5. package/docs/clean-room.md +450 -0
  6. package/package.json +69 -4
  7. package/src/audio/clock.js +383 -0
  8. package/src/audio/engine.js +678 -0
  9. package/src/audio/index.js +394 -0
  10. package/src/audio/offline.js +73 -0
  11. package/src/audio/params.js +397 -0
  12. package/src/audio/samples.js +274 -0
  13. package/src/audio/unlock.js +70 -0
  14. package/src/audio/voices.js +44 -0
  15. package/src/combinators.js +150 -0
  16. package/src/compat.js +16 -0
  17. package/src/constructors.js +236 -0
  18. package/src/controls.js +199 -0
  19. package/src/draw.js +252 -0
  20. package/src/euclid.js +57 -0
  21. package/src/evaluate.js +251 -0
  22. package/src/extras/check.js +678 -0
  23. package/src/extras/describe.js +433 -0
  24. package/src/extras/editor.js +369 -0
  25. package/src/extras/index.js +10 -0
  26. package/src/fraction.js +300 -0
  27. package/src/hap.js +64 -0
  28. package/src/helpers.js +68 -0
  29. package/src/index.js +74 -0
  30. package/src/mini/index.js +36 -0
  31. package/src/mini/parser.js +400 -0
  32. package/src/ops.js +293 -0
  33. package/src/outline.js +175 -0
  34. package/src/pattern.js +365 -0
  35. package/src/random.js +344 -0
  36. package/src/register.js +83 -0
  37. package/src/registry.js +52 -0
  38. package/src/samples.js +14 -0
  39. package/src/sampling.js +123 -0
  40. package/src/scope.js +77 -0
  41. package/src/signals.js +76 -0
  42. package/src/stepwise.js +150 -0
  43. package/src/structure.js +636 -0
  44. package/src/time.js +70 -0
  45. package/src/tonal.js +583 -0
  46. package/src/transforms.js +125 -0
  47. package/src/transpile.js +394 -0
  48. package/src/util.js +80 -0
  49. package/src/visuals.js +216 -0
@@ -0,0 +1,369 @@
1
+ // CodeMirror 6 editor extensions (plan 5.3, spec/integration.md §7-8).
2
+ //
3
+ // RIFF imports nothing from CodeMirror (docs/decisions.md, 2026-11-18): the
4
+ // host passes its own modules in.
5
+ //
6
+ // const ed = createEditorExtensions(
7
+ // { EditorView, StateField, StateEffect, Decoration, WidgetType },
8
+ // { repl, lint: { linter } /* optional @codemirror/lint */ },
9
+ // );
10
+ // new EditorView({ extensions: [basicSetup, ...ed.extensions], parent });
11
+ // // after each evaluation (descriptors from repl.state.widgets):
12
+ // ed.updateSliderWidgets(view, widgets, { offset });
13
+ // ed.updateWidgets(view, widgets, { offset });
14
+ // // in the draw loop:
15
+ // ed.highlight(view, haps, now, { offset });
16
+ //
17
+ // Positions: widget descriptors, hap locations and slider ids are in the
18
+ // coordinates of the code that was evaluated; `offset` is the length of any
19
+ // wrapper the host put in front of the editor text, and RIFF subtracts it.
20
+ // Pure helpers (hapRanges, diagnosticRange, formatSliderValue, sliderId) are
21
+ // exported for hosts and tests.
22
+
23
+ import { check as riffCheck } from './check.js';
24
+ import { repl as defaultRepl } from '../evaluate.js';
25
+ import { addScope } from '../scope.js';
26
+
27
+ // --- pure helpers ---
28
+
29
+ const num = (x) => (x == null ? NaN : Number(x));
30
+
31
+ // A hap sounds at `time` when whole.begin <= time < whole.end (part when the
32
+ // hap has no whole), spec/integration.md §7.
33
+ export function isActiveHap(hap, time) {
34
+ const span = hap?.whole ?? hap?.part;
35
+ if (!span) return false;
36
+ const b = num(span.begin), e = num(span.end);
37
+ return b <= time && time < e;
38
+ }
39
+
40
+ // hapRanges(haps, time, { offset, length, all }) -> [{ from, to }]
41
+ // Editor ranges of the mini-notation locations of the haps sounding at
42
+ // `time` (all haps when `time` is null). Locations may be { start, end } or
43
+ // [start, end]. Ranges are shifted by -offset, clamped to [0, length],
44
+ // empty ones dropped, de-duplicated and sorted.
45
+ export function hapRanges(haps, time, opts = {}) {
46
+ const offset = opts.offset ?? 0;
47
+ const length = opts.length ?? Infinity;
48
+ const seen = new Set();
49
+ const out = [];
50
+ for (const hap of haps ?? []) {
51
+ if (time != null && !isActiveHap(hap, time)) continue;
52
+ for (const loc of hap?.context?.locations ?? []) {
53
+ let s, e;
54
+ if (Array.isArray(loc)) [s, e] = loc;
55
+ else if (loc && typeof loc === 'object') ({ start: s, end: e } = loc);
56
+ s = Math.max(0, Math.min(length, num(s) - offset));
57
+ e = Math.max(0, Math.min(length, num(e) - offset));
58
+ if (!(e > s)) continue;
59
+ const key = `${s}:${e}`;
60
+ if (seen.has(key)) continue;
61
+ seen.add(key);
62
+ out.push({ from: s, to: e });
63
+ }
64
+ }
65
+ return out.sort((a, b) => a.from - b.from || a.to - b.to);
66
+ }
67
+
68
+ export const sliderId = (from) => `slider_${from}`;
69
+
70
+ const decimalsOf = (x) => {
71
+ const s = String(x);
72
+ if (/e-(\d+)/.test(s)) return Number(s.match(/e-(\d+)/)[1]);
73
+ const i = s.indexOf('.');
74
+ return i < 0 ? 0 : s.length - i - 1;
75
+ };
76
+
77
+ // formatSliderValue(value, step) -> string written into the document.
78
+ // With a step: rounded to the step's decimals. Without: at most 3 decimals,
79
+ // trailing zeros dropped.
80
+ export function formatSliderValue(value, step) {
81
+ const v = Number(value);
82
+ if (!Number.isFinite(v)) return '0';
83
+ if (step != null && Number(step) > 0) return v.toFixed(decimalsOf(step));
84
+ const s = v.toFixed(3).replace(/\.?0+$/, '');
85
+ return s === '-0' ? '0' : s;
86
+ }
87
+
88
+ // diagnosticRange(doc, d) -> { from, to }: a check() diagnostic (1-based line
89
+ // and column, endColumn exclusive) as document offsets; never empty when the
90
+ // document is not.
91
+ export function diagnosticRange(doc, d) {
92
+ const len = doc.length;
93
+ const lines = doc.lines ?? Infinity;
94
+ const pos = (line, col) => {
95
+ const l = doc.line(Math.max(1, Math.min(lines, line || 1)));
96
+ return Math.max(l.from, Math.min(l.to, l.from + (col || 1) - 1));
97
+ };
98
+ let from = pos(d.line, d.column);
99
+ let to = pos(d.endLine ?? d.line, d.endColumn ?? d.column);
100
+ if (to < from) [from, to] = [to, from];
101
+ if (to === from) {
102
+ if (to < len) to += 1;
103
+ else if (from > 0) from -= 1;
104
+ }
105
+ return { from, to };
106
+ }
107
+
108
+ // --- extensions ---
109
+
110
+ const need = (cm, names) => {
111
+ const miss = names.filter((n) => !cm?.[n]);
112
+ if (miss.length) throw new TypeError(`createEditorExtensions: missing CodeMirror module(s) ${miss.join(', ')}`);
113
+ };
114
+
115
+ const sameRanges = (a, b) => a.length === b.length && a.every((r, i) => r.from === b[i].from && r.to === b[i].to);
116
+
117
+ // createEditorExtensions(cm, options) -> editor API (see the file header).
118
+ // cm: { EditorView, StateField, StateEffect, Decoration, WidgetType }.
119
+ // options.repl: the REPL whose sliders move (default: RIFF's default repl);
120
+ // options.setSliderValue(id, value): overrides repl.setSliderValue;
121
+ // options.onSliderChange(id, value): called after each drag step;
122
+ // options.lint: the @codemirror/lint module ({ linter }); without it the lint
123
+ // extension draws marks itself; options.lint === false: no lint extension;
124
+ // options.lintDelay (500 ms); options.check (RIFF check);
125
+ // options.checkOptions: object or () => object passed to check();
126
+ // options.createWidgetDOM(id, type, document) -> element for block widgets;
127
+ // options.theme (true): add a small base theme when EditorView.baseTheme exists.
128
+ export function createEditorExtensions(cm, options = {}) {
129
+ need(cm, ['EditorView', 'StateField', 'StateEffect', 'Decoration', 'WidgetType']);
130
+ const { EditorView, StateField, StateEffect, Decoration, WidgetType } = cm;
131
+ const setDeco = (ranges) => (ranges.length ? Decoration.set(ranges, true) : Decoration.none);
132
+ const mapRange = (changes, r) => {
133
+ const from = changes.mapPos(r.from, 1), to = changes.mapPos(r.to, -1);
134
+ return to > from ? { ...r, from, to } : null;
135
+ };
136
+ const mapAll = (tr, list) => (tr.docChanged ? list.map((r) => mapRange(tr.changes, r)).filter(Boolean) : list);
137
+
138
+ // -- active-hap highlighting --
139
+ const highlightEffect = StateEffect.define();
140
+ const activeMark = Decoration.mark({ class: options.highlightClass ?? 'riff-active' });
141
+ const highlightField = StateField.define({
142
+ create: () => ({ ranges: [], deco: Decoration.none }),
143
+ update(value, tr) {
144
+ let ranges = mapAll(tr, value.ranges);
145
+ for (const e of tr.effects) if (e.is(highlightEffect)) ranges = e.value;
146
+ if (ranges === value.ranges) return value;
147
+ return { ranges, deco: setDeco(ranges.map((r) => activeMark.range(r.from, r.to))) };
148
+ },
149
+ provide: (f) => EditorView.decorations.from(f, (v) => v.deco),
150
+ });
151
+ function setHighlights(view, ranges) {
152
+ const len = view.state.doc.length;
153
+ const clean = hapRanges([{ whole: null, part: null, context: { locations: ranges.map((r) => [r.from, r.to]) } }], null, { length: len });
154
+ if (sameRanges(clean, view.state.field(highlightField).ranges)) return false;
155
+ view.dispatch({ effects: highlightEffect.of(clean) });
156
+ return true;
157
+ }
158
+ const highlight = (view, haps, time, opts = {}) =>
159
+ setHighlights(view, hapRanges(haps, time, { offset: opts.offset, length: view.state.doc.length }));
160
+ const clearHighlights = (view) => setHighlights(view, []);
161
+
162
+ // -- sliders --
163
+ const setSliders = StateEffect.define();
164
+ const moveSlider = StateEffect.define();
165
+ const setValue = options.setSliderValue
166
+ ?? ((id, v) => (options.repl ?? defaultRepl).setSliderValue(id, v));
167
+
168
+ class SliderWidget extends WidgetType {
169
+ constructor(rec) { super(); this.rec = rec; }
170
+ eq(other) {
171
+ // Value changes keep the DOM, so a drag survives the document rewrite.
172
+ const a = this.rec, b = other.rec;
173
+ return a.id === b.id && a.min === b.min && a.max === b.max && a.step === b.step;
174
+ }
175
+ toDOM(view) {
176
+ const doc = view?.dom?.ownerDocument ?? globalThis.document;
177
+ const input = doc.createElement('input');
178
+ const { min, max, step, value } = this.rec;
179
+ Object.assign(input, { type: 'range', min: String(min), max: String(max), step: step == null ? 'any' : String(step), value: String(value) });
180
+ input.className = 'riff-slider';
181
+ input.setAttribute?.('aria-label', this.rec.id);
182
+ input.addEventListener('input', () => moveTo(view, this.rec.id, Number(input.value)));
183
+ return input;
184
+ }
185
+ ignoreEvent() { return true; }
186
+ }
187
+
188
+ // moveTo(view, id, value): what a drag step does. Sets the running value
189
+ // (no re-evaluation) and rewrites the number literal in the document.
190
+ function moveTo(view, id, value) {
191
+ const rec = view.state.field(sliderField).list.find((r) => r.id === id);
192
+ if (!rec) return false;
193
+ const v = Math.max(Math.min(rec.min, rec.max), Math.min(Math.max(rec.min, rec.max), Number(value)));
194
+ setValue(id, v);
195
+ const text = formatSliderValue(v, rec.step);
196
+ view.dispatch({
197
+ changes: { from: rec.from, to: rec.to, insert: text },
198
+ effects: moveSlider.of({ id, value: v, from: rec.from, to: rec.from + text.length }),
199
+ userEvent: 'input.riff-slider',
200
+ });
201
+ options.onSliderChange?.(id, v);
202
+ return true;
203
+ }
204
+
205
+ const sliderDeco = (list) => setDeco(list.map((r) => Decoration.widget({ widget: new SliderWidget(r), side: -1 }).range(r.from)));
206
+ const sliderField = StateField.define({
207
+ create: () => ({ list: [], deco: Decoration.none }),
208
+ update(value, tr) {
209
+ let list = mapAll(tr, value.list);
210
+ for (const e of tr.effects) {
211
+ if (e.is(setSliders)) list = e.value;
212
+ else if (e.is(moveSlider)) {
213
+ // The drag replaced the whole literal, which mapping collapses: take
214
+ // the record from before the change, with its new range and value.
215
+ const old = value.list.find((r) => r.id === e.value.id);
216
+ if (old) list = [...list.filter((r) => r.id !== old.id), { ...old, ...e.value }].sort((a, b) => a.from - b.from);
217
+ }
218
+ }
219
+ if (list === value.list) return value;
220
+ return { list, deco: sliderDeco(list) };
221
+ },
222
+ provide: (f) => EditorView.decorations.from(f, (v) => v.deco),
223
+ });
224
+
225
+ // updateSliderWidgets(view, descriptors, { offset }): one control per slider
226
+ // descriptor with a literal value; non-slider descriptors are ignored.
227
+ function updateSliderWidgets(view, widgets, opts = {}) {
228
+ const offset = opts.offset ?? 0;
229
+ const len = view.state.doc.length;
230
+ const list = [];
231
+ for (const d of widgets ?? []) {
232
+ if (d?.type !== 'slider' || d.value == null || d.value === '') continue;
233
+ const from = d.from - offset, to = d.to - offset;
234
+ if (!(from >= 0 && to > from && to <= len)) continue;
235
+ const min = d.min ?? 0, max = d.max ?? 1;
236
+ list.push({ id: d.id ?? sliderId(d.from), from, to, value: Number(d.value), min, max, step: d.step ?? null });
237
+ }
238
+ view.dispatch({ effects: setSliders.of(list) });
239
+ return list;
240
+ }
241
+
242
+ // -- block widgets (._pianoroll etc.) --
243
+ const setBlocks = StateEffect.define();
244
+ class BlockWidget extends WidgetType {
245
+ constructor(rec) { super(); this.rec = rec; }
246
+ eq(other) { return other.rec.id === this.rec.id && other.rec.type === this.rec.type; }
247
+ toDOM(view) {
248
+ const doc = view?.dom?.ownerDocument ?? globalThis.document;
249
+ if (options.createWidgetDOM) return options.createWidgetDOM(this.rec.id, this.rec.type, doc);
250
+ const box = doc.createElement('div');
251
+ box.className = `riff-widget riff-widget-${this.rec.type.replace(/^_/, '')}`;
252
+ const canvas = doc.createElement('canvas');
253
+ canvas.id = this.rec.id;
254
+ box.appendChild(canvas);
255
+ return box;
256
+ }
257
+ ignoreEvent() { return true; }
258
+ }
259
+ const blockDeco = (list, doc) => setDeco(list.map((r) =>
260
+ Decoration.widget({ widget: new BlockWidget(r), block: true, side: 1 }).range(doc.lineAt(Math.min(r.to, doc.length)).to)));
261
+ const blockField = StateField.define({
262
+ create: () => ({ list: [], deco: Decoration.none }),
263
+ update(value, tr) {
264
+ let list = tr.docChanged
265
+ ? value.list.map((r) => ({ ...r, to: tr.changes.mapPos(r.to, -1) }))
266
+ : value.list;
267
+ for (const e of tr.effects) if (e.is(setBlocks)) list = e.value;
268
+ if (list === value.list) return value;
269
+ return { list, deco: blockDeco(list, tr.newDoc ?? tr.state.doc) };
270
+ },
271
+ provide: (f) => EditorView.decorations.from(f, (v) => v.deco),
272
+ });
273
+
274
+ // updateWidgets(view, descriptors, { offset }): a block below the line of
275
+ // each block-widget descriptor, keyed `_widget_<type>_<index>`; widgets
276
+ // missing from the list are removed; sliders are ignored.
277
+ function updateWidgets(view, widgets, opts = {}) {
278
+ const offset = opts.offset ?? 0;
279
+ const len = view.state.doc.length;
280
+ const list = [];
281
+ for (const d of widgets ?? []) {
282
+ if (!d || d.type === 'slider' || d.to == null || !d.type) continue;
283
+ const to = Math.max(0, Math.min(len, d.to - offset));
284
+ list.push({ id: d.id ?? `_widget_${d.type}_${d.index ?? 0}`, type: d.type, index: d.index ?? 0, to });
285
+ }
286
+ view.dispatch({ effects: setBlocks.of(list) });
287
+ return list;
288
+ }
289
+
290
+ // -- lint (RIFF check) --
291
+ const check = options.check ?? riffCheck;
292
+ const checkOpts = () => (typeof options.checkOptions === 'function' ? options.checkOptions() : options.checkOptions ?? {});
293
+ const lintDelay = options.lintDelay ?? 500;
294
+ async function diagnostics(doc) {
295
+ const ds = await check(doc.toString(), checkOpts());
296
+ return ds.map((d) => ({
297
+ ...diagnosticRange(doc, d),
298
+ severity: d.severity,
299
+ message: d.hint ? `${d.message} (${d.hint})` : d.message,
300
+ source: `riff:${d.code}`,
301
+ }));
302
+ }
303
+
304
+ const setDiags = StateEffect.define();
305
+ const diagField = StateField.define({
306
+ create: () => ({ list: [], deco: Decoration.none }),
307
+ update(value, tr) {
308
+ let list = mapAll(tr, value.list);
309
+ for (const e of tr.effects) if (e.is(setDiags)) list = e.value;
310
+ if (list === value.list) return value;
311
+ return {
312
+ list,
313
+ deco: setDeco(list.map((d) => Decoration.mark({
314
+ class: `riff-diag riff-diag-${d.severity}`, attributes: { title: d.message },
315
+ }).range(d.from, d.to))),
316
+ };
317
+ },
318
+ provide: (f) => EditorView.decorations.from(f, (v) => v.deco),
319
+ });
320
+
321
+ // runLint(view) -> Promise<diagnostics>: checks now; the fallback marks are
322
+ // set only when the document did not change meanwhile.
323
+ async function runLint(view) {
324
+ const doc = view.state.doc;
325
+ const list = await diagnostics(doc);
326
+ if (!options.lint && view.state.doc === doc) view.dispatch({ effects: setDiags.of(list) });
327
+ return list;
328
+ }
329
+
330
+ let lintExtension = [];
331
+ if (options.lint && typeof options.lint.linter === 'function') {
332
+ lintExtension = [options.lint.linter((view) => diagnostics(view.state.doc), { delay: lintDelay })];
333
+ } else if (options.lint !== false) {
334
+ const timers = new WeakMap();
335
+ const schedule = (view) => {
336
+ clearTimeout(timers.get(view));
337
+ timers.set(view, setTimeout(() => { timers.delete(view); runLint(view).catch(() => {}); }, lintDelay));
338
+ };
339
+ lintExtension = [diagField, EditorView.updateListener.of((u) => { if (u.docChanged) schedule(u.view); })];
340
+ }
341
+
342
+ const theme = options.theme !== false && EditorView.baseTheme
343
+ ? [EditorView.baseTheme({
344
+ '.riff-active': { outline: '1px solid currentColor', borderRadius: '2px' },
345
+ '.riff-slider': { width: '6em', margin: '0 0.3em', verticalAlign: 'middle' },
346
+ '.riff-widget canvas': { width: '100%', height: '80px', display: 'block' },
347
+ '.riff-diag-error': { textDecoration: 'underline wavy #e55' },
348
+ '.riff-diag-warning': { textDecoration: 'underline wavy #e9a23b' },
349
+ '.riff-diag-info': { textDecoration: 'underline dotted #5a9' },
350
+ })]
351
+ : [];
352
+
353
+ const highlightExtension = highlightField;
354
+ const sliderPlugin = sliderField;
355
+ const widgetPlugin = [blockField];
356
+
357
+ return {
358
+ extensions: [highlightExtension, sliderPlugin, ...widgetPlugin, ...lintExtension, ...theme],
359
+ highlightExtension, sliderPlugin, widgetPlugin, lintExtension,
360
+ highlight, setHighlights, clearHighlights,
361
+ updateSliderWidgets, moveSlider: moveTo,
362
+ updateWidgets,
363
+ runLint, diagnostics,
364
+ fields: { highlight: highlightField, sliders: sliderField, widgets: blockField, diagnostics: diagField },
365
+ };
366
+ }
367
+
368
+ // Names for user code (src/scope.js).
369
+ addScope({ createEditorExtensions, diagnosticRange, formatSliderValue, hapRanges, isActiveHap, sliderId });
@@ -0,0 +1,10 @@
1
+ // RIFF developer extras (B1, docs/decisions.md): the code checker, describe()
2
+ // and the CodeMirror editor helpers. Optional: the engine (src/index.js)
3
+ // never imports this folder, so a host loads it only when it needs the tools:
4
+ //
5
+ // import { check, describe, createEditorExtensions } from '@zeeuw/riff/extras';
6
+ //
7
+ // Loading it also adds these names to the evaluation scope (src/scope.js).
8
+ export { check, suggestName, CONTROL_RANGES, DENSITY_LIMIT } from './check.js';
9
+ export { describe } from './describe.js';
10
+ export { createEditorExtensions, hapRanges, isActiveHap, formatSliderValue, diagnosticRange, sliderId } from './editor.js';
@@ -0,0 +1,300 @@
1
+ // Exact rational time (spec/time.md section 1). A Fraction is n/d, d > 0,
2
+ // reduced, sign carried by n. Instances are immutable.
3
+ //
4
+ // Representation (plan 8.7): the parts live in `_n`/`_d`, as plain JS numbers
5
+ // when both are safe integers (the common case: small powers of 2 and 3) and as
6
+ // BigInts otherwise. The representation is canonical (a value that fits is
7
+ // always stored as numbers), so equality is a field comparison. Number
8
+ // arithmetic is exact as long as every intermediate is a safe integer; each
9
+ // fast path checks that and falls back to BigInt when it is not. The public
10
+ // `n` and `d` are getters that always return BigInts.
11
+
12
+ // JS number -> Fraction (the float conversion is costly). Two generations:
13
+ // when the young map fills it becomes the old one, so floats that keep coming
14
+ // back survive while one-off values (signals) age out.
15
+ let cache = new Map();
16
+ let oldCache = new Map();
17
+ const CACHE_MAX = 4096;
18
+ const MAX = Number.MAX_SAFE_INTEGER;
19
+ const BMAX = BigInt(MAX);
20
+ const safe = Number.isSafeInteger;
21
+ // Range check for a sum or product of safe integers: such a result is always an
22
+ // integer (a double this large has no fraction), so only its size can fail.
23
+ const ok = (x) => x <= MAX && x >= -MAX;
24
+
25
+ function gcd(a, b) { // numbers, a >= 0, b > 0
26
+ while (b !== 0) { const t = a % b; a = b; b = t; }
27
+ return a;
28
+ }
29
+
30
+ function bgcd(a, b) {
31
+ if (a < 0n) a = -a;
32
+ if (b < 0n) b = -b;
33
+ while (b !== 0n) { const t = a % b; a = b; b = t; }
34
+ return a;
35
+ }
36
+
37
+ // Floor division for BigInt (BigInt `/` truncates toward zero).
38
+ function floorDiv(n, d) {
39
+ const q = n / d;
40
+ return (n % d !== 0n && (n < 0n) !== (d < 0n)) ? q - 1n : q;
41
+ }
42
+
43
+ // floor(n / d) for safe integers, d > 0; exact (no float division rounding).
44
+ function floorNum(n, d) {
45
+ const r = n % d;
46
+ const q = (n - r) / d;
47
+ return r < 0 ? q - 1 : q;
48
+ }
49
+
50
+ // Reduced number parts -> Fraction (n may be -0 or unsafe-free; d > 0).
51
+ function small(n, d) { return new Fraction(n === 0 ? 0 : n, d); }
52
+
53
+ // Unreduced safe-integer parts, d > 0 -> reduced Fraction.
54
+ function reduceNum(n, d) {
55
+ if (n === 0) return new Fraction(0, 1);
56
+ if (d === 1) return new Fraction(n, 1);
57
+ const g = gcd(n < 0 ? -n : n, d);
58
+ return g === 1 ? new Fraction(n, d) : new Fraction(n / g, d / g);
59
+ }
60
+
61
+ // BigInt parts, any sign, d !== 0 -> reduced, canonical Fraction.
62
+ function reduceBig(n, d) {
63
+ if (d === 0n) throw new RangeError('fraction with zero denominator');
64
+ if (d < 0n) { n = -n; d = -d; }
65
+ if (d !== 1n) {
66
+ const g = bgcd(n, d);
67
+ if (g !== 1n) { n /= g; d /= g; }
68
+ }
69
+ return new Fraction(n, d);
70
+ }
71
+
72
+ const big = (x) => (typeof x === 'bigint' ? x : BigInt(x));
73
+
74
+ export class Fraction {
75
+ // Trusted constructor: callers pass an already reduced n/d with d > 0, as
76
+ // numbers or BigInts (BigInts that fit are stored as numbers).
77
+ constructor(n, d = 1n) {
78
+ if (typeof n === 'number' && typeof d === 'number') {
79
+ this._n = n;
80
+ this._d = d;
81
+ } else {
82
+ n = big(n); d = big(d);
83
+ if (n <= BMAX && n >= -BMAX && d <= BMAX) { this._n = Number(n); this._d = Number(d); } else { this._n = n; this._d = d; }
84
+ }
85
+ }
86
+
87
+ get n() { return typeof this._n === 'number' ? BigInt(this._n) : this._n; }
88
+ get d() { return typeof this._d === 'number' ? BigInt(this._d) : this._d; }
89
+
90
+ // Normalising constructor (numbers or BigInts).
91
+ static of(n, d = 1n) {
92
+ if (typeof n === 'number' && typeof d === 'number' && safe(n) && safe(d) && d !== 0) {
93
+ return d < 0 ? reduceNum(-n, -d) : reduceNum(n, d);
94
+ }
95
+ return reduceBig(big(n), big(d));
96
+ }
97
+
98
+ // -1, 0 or 1 (the sign of the value).
99
+ sign() { const n = this._n; return n > 0 ? 1 : n < 0 ? -1 : 0; }
100
+
101
+ add(o) {
102
+ if (!(o instanceof Fraction)) o = fraction(o);
103
+ const a = this._n, b = this._d, c = o._n, e = o._d;
104
+ if (typeof a === 'number' && typeof c === 'number') {
105
+ if (b === e) {
106
+ const n = a + c;
107
+ if (ok(n)) return b === 1 ? new Fraction(n, 1) : reduceNum(n, b);
108
+ } else if (b === 1) { // integer + n/d is already reduced
109
+ const n = a * e + c;
110
+ if (ok(n)) return new Fraction(n, e);
111
+ } else if (e === 1) {
112
+ const n = a + c * b;
113
+ if (ok(n)) return new Fraction(n, b);
114
+ } else {
115
+ const p = a * e, q = c * b, d = b * e;
116
+ if (ok(p) && ok(q) && ok(d)) { const n = p + q; if (ok(n)) return reduceNum(n, d); }
117
+ }
118
+ }
119
+ return reduceBig(big(a) * big(e) + big(c) * big(b), big(b) * big(e));
120
+ }
121
+
122
+ sub(o) {
123
+ if (!(o instanceof Fraction)) o = fraction(o);
124
+ const a = this._n, b = this._d, c = o._n, e = o._d;
125
+ if (typeof a === 'number' && typeof c === 'number') {
126
+ if (b === e) {
127
+ const n = a - c;
128
+ if (ok(n)) return b === 1 ? new Fraction(n, 1) : reduceNum(n, b);
129
+ } else if (b === 1) { // integer - n/d is already reduced
130
+ const n = a * e - c;
131
+ if (ok(n)) return new Fraction(n, e);
132
+ } else if (e === 1) {
133
+ const n = a - c * b;
134
+ if (ok(n)) return new Fraction(n, b);
135
+ } else {
136
+ const p = a * e, q = c * b, d = b * e;
137
+ if (ok(p) && ok(q) && ok(d)) { const n = p - q; if (ok(n)) return reduceNum(n, d); }
138
+ }
139
+ }
140
+ return reduceBig(big(a) * big(e) - big(c) * big(b), big(b) * big(e));
141
+ }
142
+
143
+ mul(o) {
144
+ if (!(o instanceof Fraction)) o = fraction(o);
145
+ const a = this._n, b = this._d, c = o._n, e = o._d;
146
+ if (typeof a === 'number' && typeof c === 'number') {
147
+ const n = a * c, d = b * e;
148
+ if (ok(n) && ok(d)) return d === 1 ? small(n, 1) : reduceNum(n, d);
149
+ }
150
+ return reduceBig(big(a) * big(c), big(b) * big(e));
151
+ }
152
+
153
+ div(o) {
154
+ if (!(o instanceof Fraction)) o = fraction(o);
155
+ const a = this._n, b = this._d, c = o._n, e = o._d;
156
+ if (c === 0 || c === 0n) throw new RangeError('division of time by zero');
157
+ if (typeof a === 'number' && typeof c === 'number') {
158
+ let n = a * e, d = b * c;
159
+ if (ok(n) && ok(d)) {
160
+ if (d < 0) { n = -n; d = -d; }
161
+ return reduceNum(n, d);
162
+ }
163
+ }
164
+ return reduceBig(big(a) * big(e), big(b) * big(c));
165
+ }
166
+
167
+ neg() { const n = this._n; return new Fraction(n === 0 ? 0 : -n, this._d); }
168
+ abs() { return this.sign() < 0 ? this.neg() : this; }
169
+
170
+ // -1, 0 or 1.
171
+ compare(o) {
172
+ if (!(o instanceof Fraction)) o = fraction(o);
173
+ const a = this._n, b = this._d, c = o._n, e = o._d;
174
+ if (typeof a === 'number' && typeof c === 'number') {
175
+ if (b === e) return a < c ? -1 : a > c ? 1 : 0;
176
+ const x = a * e, y = c * b;
177
+ if (safe(x) && safe(y)) return x < y ? -1 : x > y ? 1 : 0;
178
+ }
179
+ const x = big(a) * big(e), y = big(c) * big(b);
180
+ return x < y ? -1 : x > y ? 1 : 0;
181
+ }
182
+
183
+ eq(o) { if (!(o instanceof Fraction)) o = fraction(o); return this._n === o._n && this._d === o._d; }
184
+ lt(o) { return this.compare(o) < 0; }
185
+ lte(o) { return this.compare(o) <= 0; }
186
+ gt(o) { return this.compare(o) > 0; }
187
+ gte(o) { return this.compare(o) >= 0; }
188
+ min(o) { if (!(o instanceof Fraction)) o = fraction(o); return this.compare(o) <= 0 ? this : o; }
189
+ max(o) { if (!(o instanceof Fraction)) o = fraction(o); return this.compare(o) >= 0 ? this : o; }
190
+
191
+ floor() {
192
+ const d = this._d;
193
+ if (d === 1) return this;
194
+ if (typeof d === 'number') return new Fraction(floorNum(this._n, d), 1);
195
+ return d === 1n ? this : new Fraction(floorDiv(this._n, d), 1n);
196
+ }
197
+ ceil() {
198
+ const d = this._d;
199
+ if (d === 1 || d === 1n) return this;
200
+ if (typeof d === 'number') { const f = floorNum(this._n, d) + 1; return new Fraction(f === 0 ? 0 : f, 1); }
201
+ return new Fraction(floorDiv(this._n, d) + 1n, 1n);
202
+ }
203
+ // Start of the cycle that contains this time.
204
+ sam() { return this.floor(); }
205
+ // Start of the next cycle.
206
+ nextSam() {
207
+ const d = this._d;
208
+ if (typeof d === 'number') {
209
+ const f = (d === 1 ? this._n : floorNum(this._n, d)) + 1;
210
+ if (safe(f)) return new Fraction(f === 0 ? 0 : f, 1);
211
+ }
212
+ return new Fraction(floorDiv(big(this._n), big(d)) + 1n, 1n);
213
+ }
214
+ // Position inside the cycle, in [0, 1).
215
+ cyclePos() { return this.sub(this.sam()); }
216
+
217
+ isZero() { return this._n === 0 || this._n === 0n; }
218
+ isInteger() { return this._d === 1 || this._d === 1n; }
219
+ toNumber() {
220
+ const n = this._n, d = this._d;
221
+ if (typeof n === 'number') return d === 1 ? n : n / d;
222
+ return d === 1n ? Number(n) : Number(n) / Number(d);
223
+ }
224
+ valueOf() { return this.toNumber(); }
225
+ // Fixture serialisation: always "n/d", reduced ("0/1", "-1/4").
226
+ toString() { return `${this._n}/${this._d}`; }
227
+ toJSON() { return this.toString(); }
228
+ }
229
+
230
+ const N = 10_000_000;
231
+
232
+ // Shared instances for small integers (immutable, so sharing is safe).
233
+ const INT_LO = -256, INT_HI = 4096;
234
+ const INTS = Array.from({ length: INT_HI - INT_LO }, (_, i) => new Fraction(i + INT_LO === 0 ? 0 : i + INT_LO, 1));
235
+
236
+ // JS number -> exact fraction, the literal procedure of spec/time.md 1.1.
237
+ function fromNumber(x) {
238
+ if ((x | 0) === x && x >= INT_LO && x < INT_HI) return INTS[x - INT_LO];
239
+ if (!Number.isFinite(x)) throw new RangeError(`cannot turn ${x} into time`);
240
+ if (Number.isInteger(x)) {
241
+ if (x >= INT_LO && x < INT_HI) return INTS[x - INT_LO];
242
+ return safe(x) ? new Fraction(x, 1) : new Fraction(BigInt(x), 1n);
243
+ }
244
+ let hit = cache.get(x);
245
+ if (hit) return hit;
246
+ hit = oldCache.get(x);
247
+ if (hit) { cache.set(x, hit); return hit; }
248
+ const sign = x < 0 ? -1n : 1n;
249
+ let p = Math.abs(x);
250
+ let z = 1n;
251
+ if (p >= 1) {
252
+ const k = Math.floor(1 + Math.log10(p));
253
+ z = 10n ** BigInt(k);
254
+ p = p / 10 ** k;
255
+ }
256
+ let A = 0, B = 1, C = 1, D = 1;
257
+ let rn, rd;
258
+ while (B <= N && D <= N) {
259
+ const M = (A + C) / (B + D);
260
+ if (p === M) {
261
+ if (B + D <= N) { rn = A + C; rd = B + D; } else if (D > B) { rn = C; rd = D; } else { rn = A; rd = B; }
262
+ break;
263
+ }
264
+ if (p > M) { A += C; B += D; } else { C += A; D += B; }
265
+ }
266
+ if (rn === undefined) { if (B > N) { rn = C; rd = D; } else { rn = A; rd = B; } }
267
+ const f = Fraction.of(sign * BigInt(rn) * z, BigInt(rd));
268
+ if (cache.size >= CACHE_MAX) { oldCache = cache; cache = new Map(); }
269
+ cache.set(x, f);
270
+ return f;
271
+ }
272
+
273
+ function fromString(s) {
274
+ const t = s.trim();
275
+ let m = /^(-?\d+)\s*\/\s*(-?\d+)$/.exec(t);
276
+ if (m) return Fraction.of(BigInt(m[1]), BigInt(m[2]));
277
+ m = /^(-?)(\d*)(?:\.(\d*))?(?:e([+-]?\d+))?$/i.exec(t);
278
+ if (m && (m[2] || m[3])) {
279
+ const frac = m[3] ?? '';
280
+ let n = BigInt((m[2] || '0') + frac);
281
+ let d = 10n ** BigInt(frac.length);
282
+ const e = Number(m[4] ?? 0);
283
+ if (e > 0) n *= 10n ** BigInt(e); else if (e < 0) d *= 10n ** BigInt(-e);
284
+ return Fraction.of(m[1] ? -n : n, d);
285
+ }
286
+ throw new RangeError(`cannot turn "${s}" into time`);
287
+ }
288
+
289
+ // Anything time-like -> Fraction: Fraction, number, bigint, "n/d" or decimal string.
290
+ export function fraction(x) {
291
+ if (x instanceof Fraction) return x;
292
+ if (typeof x === 'number') return fromNumber(x);
293
+ if (typeof x === 'bigint') return new Fraction(x, 1n);
294
+ if (typeof x === 'string') return fromString(x);
295
+ if (x && typeof x === 'object' && typeof x.n === 'bigint' && typeof x.d === 'bigint') return Fraction.of(x.n, x.d);
296
+ throw new TypeError(`cannot turn ${String(x)} into time`);
297
+ }
298
+
299
+ export const ZERO = new Fraction(0, 1);
300
+ export const ONE = new Fraction(1, 1);