@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,70 @@
1
+ // Mobile audio unlock (plan 8.10). iOS and Android start Web Audio only from
2
+ // code that runs synchronously inside a user gesture, so everything here is
3
+ // synchronous up to the returned promise: resume() is called, a one-sample
4
+ // silent buffer is started, and on iOS the media session is switched to
5
+ // "playback" so the ring/silent switch does not mute Web Audio.
6
+
7
+ let mediaEl = null;
8
+
9
+ // A short silent 8-bit mono WAV as a data URI (no file to serve).
10
+ export function silentWavUri(samples = 800, rate = 8000) {
11
+ const b = new Uint8Array(44 + samples);
12
+ const v = new DataView(b.buffer);
13
+ const str = (o, s) => { for (let i = 0; i < s.length; i++) b[o + i] = s.charCodeAt(i); };
14
+ str(0, 'RIFF'); v.setUint32(4, 36 + samples, true); str(8, 'WAVE');
15
+ str(12, 'fmt '); v.setUint32(16, 16, true); v.setUint16(20, 1, true); v.setUint16(22, 1, true);
16
+ v.setUint32(24, rate, true); v.setUint32(28, rate, true); v.setUint16(32, 1, true); v.setUint16(34, 8, true);
17
+ str(36, 'data'); v.setUint32(40, samples, true);
18
+ b.fill(128, 44);
19
+ let s = '';
20
+ for (const x of b) s += String.fromCharCode(x);
21
+ return `data:audio/wav;base64,${btoa(s)}`;
22
+ }
23
+
24
+ function looksLikeIOS(nav) {
25
+ if (!nav) return false;
26
+ return /iPad|iPhone|iPod/.test(nav.userAgent ?? '') || (nav.platform === 'MacIntel' && nav.maxTouchPoints > 1);
27
+ }
28
+
29
+ // iOS mute switch: Safari 16.4+ has navigator.audioSession; older iOS needs a
30
+ // playing (silent, looping) HTML media element. htmlAudio: 'auto' (iOS only),
31
+ // true (always), false (never).
32
+ function playbackSession(htmlAudio) {
33
+ const nav = globalThis.navigator;
34
+ if (nav?.audioSession) {
35
+ try { nav.audioSession.type = 'playback'; } catch { /* read-only on some builds */ }
36
+ if (htmlAudio !== true) return;
37
+ }
38
+ if (htmlAudio === false || (htmlAudio === 'auto' && !looksLikeIOS(nav))) return;
39
+ const A = globalThis.Audio;
40
+ if (typeof A !== 'function') return;
41
+ if (!mediaEl) {
42
+ mediaEl = new A();
43
+ mediaEl.loop = true;
44
+ mediaEl.preload = 'auto';
45
+ mediaEl.setAttribute?.('playsinline', '');
46
+ mediaEl.setAttribute?.('x-webkit-airplay', 'deny');
47
+ mediaEl.src = silentWavUri();
48
+ }
49
+ try { Promise.resolve(mediaEl.play?.()).catch(() => {}); } catch { /* no media playback */ }
50
+ }
51
+
52
+ // unlockContext(ctx, { log, htmlAudio }) → Promise<state>. Call it as the
53
+ // first statement of a pointerdown/touchend/click/keydown handler.
54
+ export function unlockContext(ctx, { log = () => {}, htmlAudio = 'auto' } = {}) {
55
+ let p = null;
56
+ if (ctx.state !== 'running' && ctx.state !== 'closed' && typeof ctx.resume === 'function') {
57
+ try { p = Promise.resolve(ctx.resume()); } catch (e) { p = Promise.reject(e); }
58
+ }
59
+ try {
60
+ const src = ctx.createBufferSource();
61
+ src.buffer = ctx.createBuffer(1, 1, ctx.sampleRate || 44100);
62
+ src.connect(ctx.destination);
63
+ src.start(0);
64
+ } catch { /* a context without buffers still resumes */ }
65
+ playbackSession(htmlAudio);
66
+ return (p ?? Promise.resolve()).then(() => ctx.state, (e) => {
67
+ log(`[riff] could not start audio: ${e?.message ?? e}`);
68
+ return ctx.state;
69
+ });
70
+ }
@@ -0,0 +1,44 @@
1
+ // Voice bookkeeping: polyphony cap with oldest-voice stealing
2
+ // (docs/improvements.md 2) and cut groups. Pure; the engine calls stop().
3
+ export class VoicePool {
4
+ constructor(maxVoices = 128) {
5
+ const n = Number(maxVoices);
6
+ this.max = Number.isFinite(n) && n >= 1 ? Math.floor(n) : 128;
7
+ this.voices = [];
8
+ this.cuts = new Map();
9
+ this.nextId = 1;
10
+ }
11
+
12
+ get size() { return this.voices.length; }
13
+
14
+ // Adds a voice ({ start, cut?, stop(at) }); returns the voices it displaced
15
+ // (same cut group, then the oldest over the cap). They are already removed.
16
+ add(voice) {
17
+ voice.id = this.nextId++;
18
+ const out = [];
19
+ if (voice.cut !== undefined && voice.cut !== null) {
20
+ const prev = this.cuts.get(voice.cut);
21
+ if (prev && this.voices.includes(prev)) { this.remove(prev); out.push(prev); }
22
+ this.cuts.set(voice.cut, voice);
23
+ }
24
+ // Keep start order (voices may be added slightly out of order).
25
+ let i = this.voices.length;
26
+ while (i > 0 && this.voices[i - 1].start > voice.start) i--;
27
+ this.voices.splice(i, 0, voice);
28
+ while (this.voices.length > this.max) out.push(this.removeAt(0));
29
+ return out;
30
+ }
31
+
32
+ remove(voice) {
33
+ const i = this.voices.indexOf(voice);
34
+ if (i >= 0) this.removeAt(i);
35
+ }
36
+
37
+ removeAt(i) {
38
+ const [v] = this.voices.splice(i, 1);
39
+ if (v.cut !== undefined && this.cuts.get(v.cut) === v) this.cuts.delete(v.cut);
40
+ return v;
41
+ }
42
+
43
+ clear() { const all = this.voices; this.voices = []; this.cuts.clear(); return all; }
44
+ }
@@ -0,0 +1,150 @@
1
+ // Tier 1 combinators (plan 2.6): superimpose, layer, off, echo, echoWith,
2
+ // jux, when, whenmod (RIFF extension), inside/outside, swingBy/swing.
3
+ // Each follows its spec in spec/functions/ (whenmod: spec/integration.md 12).
4
+ import { fraction } from './fraction.js';
5
+ import { TimeSpan } from './time.js';
6
+ import { Pattern, reify, silence } from './pattern.js';
7
+ import { register } from './register.js';
8
+ import { stack, seq } from './constructors.js';
9
+ import { isTrue, rev, fast } from './transforms.js';
10
+ import { isRecord } from './util.js';
11
+ import { alias } from './register.js';
12
+
13
+
14
+ // stack(pat, f1(pat), f2(pat), ...) (spec/functions/superimpose.md).
15
+ export const superimpose = register('superimpose', (pat, ...fs) => stack(pat, ...fs.map((f) => f(pat))), { patternArgs: 0 });
16
+
17
+ // stack(f1(pat), f2(pat), ...): the original is not included.
18
+ export const layer = register('layer', (pat, ...fs) => stack(...fs.map((f) => f(pat))), { patternArgs: 0 });
19
+
20
+ // stack(pat, f(pat.late(t))) (spec/functions/off.md).
21
+ export const off = register('off', (pat, t, f) => stack(pat, f(pat.late(t))), { patternArgs: 1 });
22
+
23
+ // count copies late by i*time; gain set to feedback^i (spec/functions/echo.md).
24
+ export const echo = register('echo', (pat, count, time, feedback) => {
25
+ const copies = [];
26
+ for (let i = 0; i < Number(count); i++) copies.push(pat.late(fraction(time).mul(i)).gain(Number(feedback) ** i));
27
+ return copies.length ? stack(...copies) : silence;
28
+ }, { patternArgs: 3 });
29
+
30
+ // count copies late by i*time, each passed through f exactly once (1.2.5).
31
+ export const echoWith = register('echoWith', (pat, count, time, f) => {
32
+ const copies = [];
33
+ for (let i = 0; i < Number(count); i++) copies.push(f(pat.late(fraction(time).mul(i))));
34
+ return copies.length ? stack(...copies) : silence;
35
+ }, { patternArgs: 2, aliases: ['echowith'] });
36
+
37
+ // stack(L, R): pan p - 1/2 on pat, p + 1/2 on f(pat); p defaults to 1/2.
38
+ const panBy = (pat, d) => pat.fmap((v) => (isRecord(v) ? { ...v, pan: (v.pan ?? 0.5) + d } : { value: v, pan: 0.5 + d }));
39
+ export const jux = register('jux', (pat, f) => stack(panBy(pat, -0.5), panBy(f(pat), 0.5)), { patternArgs: 0 });
40
+
41
+ // Width w: pan p - w/2 on pat, p + w/2 on f(pat), in doubles in that order
42
+ // (spec/functions/juxBy.md).
43
+ const panSub = (pat, d) => pat.fmap((v) => (isRecord(v) ? { ...v, pan: (v.pan ?? 0.5) - d } : { value: v, pan: 0.5 - d }));
44
+ export const juxBy = register('juxBy', (pat, w, f) => {
45
+ const d = Number(w) / 2;
46
+ return stack(panSub(pat, d), panBy(f(pat), d));
47
+ }, { patternArgs: 1, aliases: ['juxby'], curry: 2 });
48
+ export const juxby = juxBy;
49
+
50
+ // fast(r) plus speed multiplied by r (spec/functions/hurry.md).
51
+ export const hurry = register('hurry', (pat, r) => {
52
+ const x = Number(r);
53
+ return fast(r, pat.fmap((v) => (isRecord(v) ? { ...v, speed: v.speed === undefined ? x : v.speed * x } : { value: v, speed: x })));
54
+ }, { memo: true, curry: 1 });
55
+
56
+ // n must be a whole number >= 1: the oracle throws this RangeError otherwise.
57
+ function cycleCount(n) {
58
+ const k = Number(n);
59
+ if (!Number.isInteger(k) || k < 1) throw new RangeError('Invalid array length');
60
+ return k;
61
+ }
62
+
63
+ // Per cycle, f(pat) where pick(cycle, n) holds, else pat (spec/functions/every.md).
64
+ const cycleChooser = (pick) => (pat, n, f) => {
65
+ const fp = f(pat);
66
+ return new Pattern((state) => {
67
+ const k = cycleCount(n);
68
+ const out = [];
69
+ for (const span of state.span.spanCycles()) {
70
+ const c = span.begin.sam().toNumber();
71
+ for (const h of (pick(((c % k) + k) % k, k) ? fp : pat).query(state.setSpan(span))) out.push(h);
72
+ }
73
+ return out;
74
+ }, pat._steps);
75
+ };
76
+ export const firstOf = register('firstOf', cycleChooser((m) => m === 0), { patternArgs: 1, curry: 2 });
77
+ export const every = register('every', cycleChooser((m) => m === 0), { patternArgs: 1, curry: 2 });
78
+ export const lastOf = register('lastOf', cycleChooser((m, k) => m === k - 1), { patternArgs: 1, curry: 2 });
79
+
80
+ // Odd cycles mirrored: lastOf(2, rev) (spec/functions/palindrome.md).
81
+ export const palindrome = register('palindrome', (pat) => lastOf(2, rev, pat), { patternArgs: 0 });
82
+
83
+ // Each cycle cut into n windows; f(pat) plays window w(c), pat the others.
84
+ // Every window edge cuts haps (spec/functions/chunk.md).
85
+ const chunker = (back) => (pat, n, f) => {
86
+ const fp = f(pat);
87
+ return new Pattern((state) => {
88
+ const k = cycleCount(n);
89
+ const out = [];
90
+ for (const span of state.span.spanCycles()) {
91
+ const cyc = span.begin.sam();
92
+ const c = cyc.toNumber();
93
+ const m = ((c % k) + k) % k;
94
+ const w = back ? (k - m) % k : m;
95
+ for (let j = 0; j < k; j++) {
96
+ const win = new TimeSpan(cyc.add(fraction(j).div(k)), cyc.add(fraction(j + 1).div(k))).intersect(span);
97
+ if (!win || (win.begin.eq(win.end) && !span.begin.eq(span.end))) continue;
98
+ for (const h of (j === w ? fp : pat).query(state.setSpan(win))) out.push(h);
99
+ }
100
+ }
101
+ return out;
102
+ }, pat._steps);
103
+ };
104
+ export const chunk = register('chunk', chunker(false), { patternArgs: 1, curry: 2 });
105
+ export const chunkBack = register('chunkBack', chunker(true), { patternArgs: 1, aliases: ['chunkback'], curry: 2 });
106
+ export const chunkback = chunkBack;
107
+
108
+ // Where the boolean pattern is true, f(pat), else pat; cut to its haps.
109
+ export const when = register('when', (pat, bools, f) => {
110
+ const fp = f(pat);
111
+ return reify(bools).fmap((b) => (isTrue(b) ? fp : pat)).innerJoin();
112
+ }, { patternArgs: 0 });
113
+
114
+ // RIFF extension (Strudel 1.2.5 has none): f(pat) in cycles with c mod a >= b.
115
+ export const whenmod = register('whenmod', (pat, a, b, f) => {
116
+ const fp = f(pat);
117
+ a = Number(a); b = Number(b);
118
+ return new Pattern((state) => {
119
+ const out = [];
120
+ for (const span of state.span.spanCycles()) {
121
+ const c = Number(span.begin.sam().n);
122
+ const use = (((c % a) + a) % a) >= b ? fp : pat;
123
+ out.push(...use.query(state.setSpan(span)));
124
+ }
125
+ return out;
126
+ });
127
+ }, { patternArgs: 2 });
128
+
129
+ // f applied with time stretched by n (inside) or compressed by n (outside).
130
+ export const inside = register('inside', (pat, n, f) => f(pat.slow(n)).fast(n), { patternArgs: 1 });
131
+ export const outside = register('outside', (pat, n, f) => f(pat.fast(n)).slow(n), { patternArgs: 1 });
132
+
133
+ // Second half of each 1/n slot delayed by x/(2n) (spec/functions/swing.md).
134
+ export const swingBy = register('swingBy', (pat, x, n) =>
135
+ pat.inside(n, (p) => p.late(seq(0, fraction(x).div(2)))), { patternArgs: 2 });
136
+ export const swing = register('swing', (pat, n) => pat.swingBy(fraction(1).div(3), n), { patternArgs: 1 });
137
+
138
+ // --- moved here from the Tier 2/3 batch modules (audit 6) ---------------------
139
+
140
+ // Tier 3 alias (spec/functions/tier3-aliases.md): the target's own function.
141
+ export const stutWith = alias('stutWith', 'echoWith');
142
+
143
+ // Tier 3 alias (spec/functions/tier3-aliases.md): the target's own function.
144
+ export const stutwith = alias('stutwith', 'echoWith');
145
+
146
+ // Tier 3 alias (spec/functions/tier3-aliases.md): the target's own function.
147
+ export const slowchunk = alias('slowchunk', 'chunk');
148
+
149
+ // Tier 3 alias (spec/functions/tier3-aliases.md): the target's own function.
150
+ export const slowChunk = alias('slowChunk', 'chunk');
package/src/compat.js ADDED
@@ -0,0 +1,16 @@
1
+ // Plan 8.12 (RIFF extension): the compatibility mode. 'strudel' (default)
2
+ // keeps every output identical to Strudel 1.2.5 (vision L1). 'riff' turns on
3
+ // fixes that change output only where Strudel errors or stays silent:
4
+ // chord-symbol aliases (docs/improvements.md 22) and note names in
5
+ // `n().scale()` keeping the other controls (item 11). Global, like setSeed.
6
+ let mode = 'strudel';
7
+ const MODES = { strudel: 'strudel', default: 'strudel', riff: 'riff' };
8
+
9
+ export function setCompat(m = 'strudel') {
10
+ const next = MODES[m];
11
+ if (!next) throw new TypeError(`setCompat: unknown mode ${JSON.stringify(m)} (use 'strudel' or 'riff')`);
12
+ mode = next;
13
+ return mode;
14
+ }
15
+ export const getCompat = () => mode;
16
+ export const riffCompat = () => mode === 'riff';
@@ -0,0 +1,236 @@
1
+ // Pattern constructors: stack, cat/slowcat, fastcat/seq, timecat, polymeter
2
+ // (plan 2.2). pure, silence and signal live in pattern.js because reify needs them.
3
+ import { Fraction, fraction, ONE } from './fraction.js';
4
+ import { TimeSpan } from './time.js';
5
+ import { Hap } from './hap.js';
6
+ import { Pattern, reify, silence, setSequenceBuilder } from './pattern.js';
7
+ import { register, registerFree } from './register.js';
8
+
9
+ // Speed up by a constant factor (spec/time.md 5.1); f <= 0 is silence.
10
+ export function fastBy(pat, f) {
11
+ f = fraction(f);
12
+ if (f.sign() <= 0) return silence;
13
+ if (f.eq(1)) return pat;
14
+ // fastBy(fastBy(p, a), b) is fastBy(p, a * b): one time map, not two (plan 8.7).
15
+ const steps = pat._steps;
16
+ const inner = pat._fastOf;
17
+ if (inner !== undefined) {
18
+ f = f.mul(inner.f);
19
+ pat = inner.pat;
20
+ if (f.eq(1)) return new Pattern(pat.query, steps);
21
+ }
22
+ const back = (t) => t.div(f);
23
+ const out = new Pattern((state) => {
24
+ const s = state.span;
25
+ const haps = pat.query(state.setSpan(new TimeSpan(s.begin.mul(f), s.end.mul(f))));
26
+ const res = new Array(haps.length);
27
+ for (let i = 0; i < haps.length; i++) res[i] = haps[i].withTime(back);
28
+ return res;
29
+ }, steps);
30
+ out._fastOf = { pat, f };
31
+ return out;
32
+ }
33
+
34
+ // Shift by a constant amount (spec/time.md 5.3).
35
+ export function shiftBy(pat, t) {
36
+ t = fraction(t);
37
+ if (t.n === 0n) return pat;
38
+ return new Pattern((state) => pat.query(state.withSpan((s) => s.withTime((x) => x.sub(t))))
39
+ .map((h) => h.withTime((x) => x.add(t))), pat._steps);
40
+ }
41
+
42
+ // shiftBy(pat, t).query(state) without building the pattern (t not zero).
43
+ function shiftedQuery(pat, t, state) {
44
+ const span = state.span;
45
+ const haps = pat.query(state.setSpan(new TimeSpan(span.begin.sub(t), span.end.sub(t))));
46
+ const back = (x) => x.add(t);
47
+ const out = new Array(haps.length); // the child's array may be shared: copy
48
+ for (let i = 0; i < haps.length; i++) out[i] = haps[i].withTime(back);
49
+ return out;
50
+ }
51
+
52
+ function sameSteps(pats) {
53
+ const s = pats[0]?._steps;
54
+ return s !== undefined && pats.every((p) => p._steps !== undefined && fraction(p._steps).eq(s)) ? s : undefined;
55
+ }
56
+
57
+ // All layers at once, layer by layer (spec/functions/stack.md).
58
+ // The members of each stack, so the scheduler can query top-level layers one
59
+ // by one and keep the healthy ones playing when one throws (plan 8.3).
60
+ export const stackMembers = new WeakMap();
61
+
62
+ export function stack(...items) {
63
+ const pats = items.map(reify);
64
+ if (pats.length === 0) return silence;
65
+ if (pats.length === 1) return pats[0];
66
+ const out = new Pattern((state) => {
67
+ const haps = [];
68
+ for (const p of pats) for (const h of p.query(state)) haps.push(h);
69
+ return haps;
70
+ }, sameSteps(pats));
71
+ stackMembers.set(out, pats);
72
+ return out;
73
+ }
74
+
75
+ // One item per cycle; each item's own time advances only while it plays
76
+ // (spec/functions/slowcat.md).
77
+ export function slowcat(...items) {
78
+ const pats = items.map(reify);
79
+ if (pats.length === 0) return silence;
80
+ if (pats.length === 1) return pats[0];
81
+ const n = pats.length;
82
+ return new Pattern((state) => {
83
+ const out = [];
84
+ for (const span of state.span.spanCycles()) {
85
+ const c = span.begin.sam().toNumber(); // an integer; exact while safe
86
+ const i = ((c % n) + n) % n;
87
+ const k = (c - i) / n; // floor(c / n)
88
+ const pat = pats[i];
89
+ if (c === k) { for (const h of pat.query(state.setSpan(span))) out.push(h); continue; }
90
+ const off = Number.isSafeInteger(c) ? new Fraction(c - k, 1) : (() => {
91
+ const cb = span.begin.sam().n, nb = BigInt(n), ib = ((cb % nb) + nb) % nb;
92
+ return new Fraction(cb - (cb - ib) / nb, 1n);
93
+ })();
94
+ for (const h of shiftedQuery(pat, off, state.setSpan(span))) out.push(h);
95
+ }
96
+ return out;
97
+ }, sameSteps(pats));
98
+ }
99
+
100
+ // All items squeezed into one cycle, in time order (spec/time.md 7.4).
101
+ export function fastcat(...items) {
102
+ const pats = items.map(reify);
103
+ if (pats.length === 0) return silence;
104
+ if (pats.length === 1) return pats[0];
105
+ const n = pats.length;
106
+ const general = fastBy(slowcat(...pats), n); // the definition; used past safe integers
107
+ const fn = fraction(n);
108
+ // fastBy(slowcat(...), n) in one pass (plan 8.7): slowcat cycle C plays item
109
+ // C mod n shifted by C - floor(C / n); each hap time maps back as (t + off) / n.
110
+ return new Pattern((state) => {
111
+ const s = state.span;
112
+ const scaled = new TimeSpan(s.begin.mul(fn), s.end.mul(fn));
113
+ const cycles = scaled.spanCycles();
114
+ const out = [];
115
+ for (const span of cycles) {
116
+ const c = span.begin.sam().toNumber();
117
+ if (!Number.isSafeInteger(c) || !Number.isSafeInteger(c * n)) return general.query(state);
118
+ const i = ((c % n) + n) % n;
119
+ const off = c - (c - i) / n;
120
+ const pat = pats[i];
121
+ if (off === 0) {
122
+ for (const h of pat.query(state.setSpan(span))) out.push(h.withTime((t) => t.div(fn)));
123
+ continue;
124
+ }
125
+ const offF = fraction(off);
126
+ const back = (t) => t.add(offF).div(fn);
127
+ for (const h of pat.query(state.setSpan(new TimeSpan(span.begin.sub(offF), span.end.sub(offF))))) out.push(h.withTime(back));
128
+ }
129
+ return out;
130
+ }, n);
131
+ }
132
+
133
+ // Weighted sequence: [weight, pattern] pairs (a bare pattern weighs its step
134
+ // count, or 1). Each child is queried per cycle in its slot (spec/time.md 5.5);
135
+ // haps come grouped by child, then by cycle (the mini-notation order, 7.2).
136
+ export function timecat(...items) {
137
+ const kids = [];
138
+ let total = new Fraction(0n, 1n);
139
+ for (const it of items) {
140
+ const [w, p] = Array.isArray(it) && it.length === 2 && !Array.isArray(it[0]) ? [fraction(it[0]), reify(it[1])] : [null, reify(it)];
141
+ const weight = w ?? fraction(p._steps ?? 1);
142
+ if (weight.n <= 0n) continue;
143
+ kids.push({ pat: p, begin: total, weight });
144
+ total = total.add(weight);
145
+ }
146
+ if (kids.length === 0) return silence;
147
+ for (const k of kids) { k.sb = k.begin.div(total); k.len = k.weight.div(total); k.se = k.sb.add(k.len); k.inv = ONE.div(k.len); }
148
+ // One constant child fills the cycle: it answers like itself.
149
+ if (kids.length === 1 && kids[0].pat._pure) {
150
+ const out = new Pattern(kids[0].pat.query, total);
151
+ out._pure = kids[0].pat._pure;
152
+ return out;
153
+ }
154
+ const bounds = [kids[0].sb, ...kids.map((k) => k.se)];
155
+ return new Pattern((state) => {
156
+ const out = [];
157
+ const cycles = state.span.spanCycles();
158
+ const sams = cycles.map((s) => s.begin.sam());
159
+ // Slot edges per cycle: kid i spans [edge i, edge i+1) (kids are contiguous).
160
+ const edges = sams.map((cyc) => bounds.map((b) => cyc.add(b)));
161
+ const fulls = cycles.map((s, j) => s.begin.eq(sams[j]) && s.end.eq(s.begin.nextSam()));
162
+ for (let ki = 0; ki < kids.length; ki++) {
163
+ const kid = kids[ki];
164
+ if (kid.pat === silence) continue; // a rest: nothing to query
165
+ for (let j = 0; j < cycles.length; j++) {
166
+ const span = cycles[j];
167
+ const cyc = sams[j];
168
+ const slot = new TimeSpan(edges[j][ki], edges[j][ki + 1]);
169
+ const q = fulls[j] ? slot : span.intersect(slot); // a whole-cycle query holds every slot
170
+ if (!q) continue;
171
+ // A constant child (pure value, fixed context) has one hap whose
172
+ // whole is the slot and whose part is the query (plan 8.7).
173
+ const pure = kid.pat._pure;
174
+ if (pure) { out.push(new Hap(slot, q, pure.value, pure.context)); continue; }
175
+ // Affine maps, offsets once per slot: x -> x / len + (cyc - begin / len)
176
+ // and back t -> t * len + (begin - cyc * len).
177
+ const inOff = cyc.sub(slot.begin.mul(kid.inv));
178
+ const outOff = slot.begin.sub(cyc.mul(kid.len));
179
+ const toChild = (x) => x.mul(kid.inv).add(inOff);
180
+ const toParent = (t) => t.mul(kid.len).add(outOff);
181
+ for (const h of kid.pat.query(state.setSpan(q.withTime(toChild)))) out.push(h.withTime(toParent));
182
+ }
183
+ }
184
+ return out;
185
+ }, total);
186
+ }
187
+
188
+ // Free polymeter()/pm(): layers aligned to the least common multiple of their
189
+ // step counts (spec/functions/polymeter.md); a layer without a step count is
190
+ // stacked as it is. Mini `{}` keeps the first-layer rule in the mini parser.
191
+ const bgcd = (a, b) => (b === 0n ? a : bgcd(b, a % b));
192
+ // lcm of two positive fractions: lcm(numerators) / gcd(denominators).
193
+ function lcmSteps(a, b) {
194
+ const n = (a.n / bgcd(a.n, b.n)) * b.n;
195
+ return fraction(n).div(fraction(bgcd(a.d, b.d)));
196
+ }
197
+ export function polymeter(...items) {
198
+ const pats = items.map(reify);
199
+ if (pats.length === 0) return silence;
200
+ const known = pats.filter((p) => p._steps !== undefined).map((p) => fraction(p._steps)).filter((s) => s.sign() > 0);
201
+ if (known.length === 0) return stack(...pats);
202
+ const steps = known.reduce(lcmSteps);
203
+ const layers = [];
204
+ for (const p of pats) {
205
+ if (p._steps === undefined) { layers.push(p); continue; }
206
+ const s = fraction(p._steps);
207
+ if (s.sign() <= 0) continue;
208
+ layers.push(fastBy(p, steps.div(s)));
209
+ }
210
+ return stack(...layers).withSteps(steps);
211
+ }
212
+
213
+ setSequenceBuilder((items) => fastcat(...items));
214
+
215
+ export const cat = slowcat;
216
+ export const seq = fastcat;
217
+ export const sequence = fastcat;
218
+ export const polyrhythm = stack;
219
+ export const pr = stack;
220
+ export const timeCat = timecat;
221
+ export const stepcat = timecat;
222
+ export const s_cat = timecat;
223
+ export const pm = polymeter;
224
+
225
+ registerFree('stack', stack, ['polyrhythm', 'pr']);
226
+ registerFree('slowcat', slowcat, ['cat']);
227
+ registerFree('fastcat', fastcat, ['seq', 'sequence']);
228
+ registerFree('timecat', timecat, ['timeCat', 'stepcat', 's_cat']);
229
+ registerFree('polymeter', polymeter, ['pm']);
230
+
231
+ // Methods: the pattern is the first item.
232
+ const methods = { stack, slowcat, cat: slowcat, fastcat, seq: fastcat, sequence: fastcat };
233
+ for (const [name, f] of Object.entries(methods)) {
234
+ register(name, (pat, ...others) => f(pat, ...others), { patternArgs: 0, free: false });
235
+ }
236
+