@webmusic/kernel 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +435 -0
- package/dist/audio-context.cjs +10 -0
- package/dist/audio-context.cjs.map +1 -0
- package/dist/audio-context.d.cts +13 -0
- package/dist/audio-context.d.ts +13 -0
- package/dist/audio-context.js +10 -0
- package/dist/audio-context.js.map +1 -0
- package/dist/build-receipt.json +7 -0
- package/dist/chunk-3INDOVUC.cjs +134 -0
- package/dist/chunk-3INDOVUC.cjs.map +1 -0
- package/dist/chunk-53YD73OY.js +162 -0
- package/dist/chunk-53YD73OY.js.map +1 -0
- package/dist/chunk-7ZTZZ5PN.cjs +25 -0
- package/dist/chunk-7ZTZZ5PN.cjs.map +1 -0
- package/dist/chunk-BR63OD53.cjs +1 -0
- package/dist/chunk-BR63OD53.cjs.map +1 -0
- package/dist/chunk-C3YWUZW3.cjs +57 -0
- package/dist/chunk-C3YWUZW3.cjs.map +1 -0
- package/dist/chunk-FJLY3RWZ.js +134 -0
- package/dist/chunk-FJLY3RWZ.js.map +1 -0
- package/dist/chunk-GO4N5T27.js +94 -0
- package/dist/chunk-GO4N5T27.js.map +1 -0
- package/dist/chunk-HOKRTYPV.js +199 -0
- package/dist/chunk-HOKRTYPV.js.map +1 -0
- package/dist/chunk-HY2YIL75.js +16 -0
- package/dist/chunk-HY2YIL75.js.map +1 -0
- package/dist/chunk-HZQX4J2J.cjs +199 -0
- package/dist/chunk-HZQX4J2J.cjs.map +1 -0
- package/dist/chunk-ILKEVUJ3.js +57 -0
- package/dist/chunk-ILKEVUJ3.js.map +1 -0
- package/dist/chunk-JNXB74G3.cjs +987 -0
- package/dist/chunk-JNXB74G3.cjs.map +1 -0
- package/dist/chunk-N6KU2HYA.js +25 -0
- package/dist/chunk-N6KU2HYA.js.map +1 -0
- package/dist/chunk-PXG64RU4.js +25 -0
- package/dist/chunk-PXG64RU4.js.map +1 -0
- package/dist/chunk-SM5YPDDI.cjs +162 -0
- package/dist/chunk-SM5YPDDI.cjs.map +1 -0
- package/dist/chunk-TEM2I2NN.js +1 -0
- package/dist/chunk-TEM2I2NN.js.map +1 -0
- package/dist/chunk-UMTPJ76S.cjs +94 -0
- package/dist/chunk-UMTPJ76S.cjs.map +1 -0
- package/dist/chunk-VVZX7DQ6.cjs +254 -0
- package/dist/chunk-VVZX7DQ6.cjs.map +1 -0
- package/dist/chunk-VY6WWZSW.cjs +16 -0
- package/dist/chunk-VY6WWZSW.cjs.map +1 -0
- package/dist/chunk-WNFGDB7B.js +254 -0
- package/dist/chunk-WNFGDB7B.js.map +1 -0
- package/dist/chunk-XBJBY4J5.js +987 -0
- package/dist/chunk-XBJBY4J5.js.map +1 -0
- package/dist/chunk-ZMU72HJS.cjs +25 -0
- package/dist/chunk-ZMU72HJS.cjs.map +1 -0
- package/dist/effect.cjs +2 -0
- package/dist/effect.cjs.map +1 -0
- package/dist/effect.d.cts +19 -0
- package/dist/effect.d.ts +19 -0
- package/dist/effect.js +2 -0
- package/dist/effect.js.map +1 -0
- package/dist/elements.cjs +24 -0
- package/dist/elements.cjs.map +1 -0
- package/dist/elements.d.cts +76 -0
- package/dist/elements.d.ts +76 -0
- package/dist/elements.js +24 -0
- package/dist/elements.js.map +1 -0
- package/dist/events.cjs +8 -0
- package/dist/events.cjs.map +1 -0
- package/dist/events.d.cts +36 -0
- package/dist/events.d.ts +36 -0
- package/dist/events.js +8 -0
- package/dist/events.js.map +1 -0
- package/dist/index.cjs +77 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +10 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +77 -0
- package/dist/index.js.map +1 -0
- package/dist/meter.cjs +12 -0
- package/dist/meter.cjs.map +1 -0
- package/dist/meter.d.cts +76 -0
- package/dist/meter.d.ts +76 -0
- package/dist/meter.js +12 -0
- package/dist/meter.js.map +1 -0
- package/dist/player.cjs +16 -0
- package/dist/player.cjs.map +1 -0
- package/dist/player.d.cts +49 -0
- package/dist/player.d.ts +49 -0
- package/dist/player.js +16 -0
- package/dist/player.js.map +1 -0
- package/dist/sync.cjs +12 -0
- package/dist/sync.cjs.map +1 -0
- package/dist/sync.d.cts +304 -0
- package/dist/sync.d.ts +304 -0
- package/dist/sync.js +12 -0
- package/dist/sync.js.map +1 -0
- package/dist/tick.cjs +10 -0
- package/dist/tick.cjs.map +1 -0
- package/dist/tick.d.cts +48 -0
- package/dist/tick.d.ts +48 -0
- package/dist/tick.js +10 -0
- package/dist/tick.js.map +1 -0
- package/dist/transport.cjs +8 -0
- package/dist/transport.cjs.map +1 -0
- package/dist/transport.d.cts +114 -0
- package/dist/transport.d.ts +114 -0
- package/dist/transport.js +8 -0
- package/dist/transport.js.map +1 -0
- package/dist/worker.cjs +10 -0
- package/dist/worker.cjs.map +1 -0
- package/dist/worker.d.cts +49 -0
- package/dist/worker.d.ts +49 -0
- package/dist/worker.js +10 -0
- package/dist/worker.js.map +1 -0
- package/package.json +164 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 WebScore Contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,435 @@
|
|
|
1
|
+
# @webmusic/kernel
|
|
2
|
+
|
|
3
|
+
The domain-neutral contracts and runtime utilities used by `@webmusic/score`
|
|
4
|
+
and custom WebMusic integrations. It knows nothing about scores or clips —
|
|
5
|
+
no `Note`, no `Score`, no `AudioClip`, no `BeatGrid`.
|
|
6
|
+
|
|
7
|
+
```text
|
|
8
|
+
@webmusic/score ── required peer ──→ @webmusic/kernel
|
|
9
|
+
↑
|
|
10
|
+
custom players, effects and timelines ────┘
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Zero dependencies, zero peer dependencies, ESM + CJS, `sideEffects: false`,
|
|
14
|
+
one subpath export per module. Score declares it as a required
|
|
15
|
+
peer so applications select a compatible shared implementation. UI does not depend
|
|
16
|
+
on Kernel. Package resolution does not allocate shared runtime objects: a shared
|
|
17
|
+
Kernel package, an AudioContext and a session TransportClock are three distinct
|
|
18
|
+
things. See the [session-clock design boundary](https://github.com/koperative-lab/WebMusic/blob/main/platform/shared-clock-injection.md).
|
|
19
|
+
|
|
20
|
+
The first-release packages are Kernel, UI and Score. Audio and Bridge continue
|
|
21
|
+
on the [`dev` branch](https://github.com/mrsteamedbun/WebMusic/tree/dev);
|
|
22
|
+
the cross-domain examples below describe those shared contracts.
|
|
23
|
+
|
|
24
|
+
## Install and use
|
|
25
|
+
|
|
26
|
+
```sh
|
|
27
|
+
npm install @webmusic/kernel
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Node.js 22 or later is supported. Import a subpath for the capability you need;
|
|
31
|
+
the root re-exports all ten modules. CommonJS uses the same paths with `require()`.
|
|
32
|
+
Importing the package creates no context, worker, timer or custom-element
|
|
33
|
+
registration. Browser operations still require their corresponding Web APIs.
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
import {TransportClock} from '@webmusic/kernel/transport';
|
|
37
|
+
|
|
38
|
+
const clock = new TransportClock();
|
|
39
|
+
clock.start(0, 4); // Reference time 0, content position 4.
|
|
40
|
+
clock.setRate(2, 1); // Position remains 5 at reference time 1.
|
|
41
|
+
console.log(clock.positionAt(2)); // 7
|
|
42
|
+
clock.pause(2); // Position now holds at 7.
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
The clock allocates no resource and needs no disposal. In contrast, owners of
|
|
46
|
+
tick sources, transport groups and analyser taps must call their `dispose()`.
|
|
47
|
+
TypeScript declarations for browser contracts use DOM types; pure `/events`
|
|
48
|
+
and `/transport` imports also work with an ES-only TypeScript `lib`.
|
|
49
|
+
|
|
50
|
+
## What qualifies as kernel code
|
|
51
|
+
|
|
52
|
+
The admission rule, enforced by review against the ledger in
|
|
53
|
+
[`platform/README.md`](https://github.com/koperative-lab/WebMusic/blob/main/platform/README.md):
|
|
54
|
+
|
|
55
|
+
> Code qualifies for the kernel only if **two drifting copies of it already
|
|
56
|
+
> exist**, or it is a **contract both domains must implement**.
|
|
57
|
+
|
|
58
|
+
Review new work against existing modules before adding another shared mechanism.
|
|
59
|
+
The ledger records the extraction boundary, including the role-contract basis for
|
|
60
|
+
`kernel/sync`. Keep an extraction's justification and retained domain policies in that ledger.
|
|
61
|
+
|
|
62
|
+
The counterpart rule matters as much: **policy that legitimately differs
|
|
63
|
+
between the families stays with the families.** The kernel carries the
|
|
64
|
+
`AudioContext` constructor lookup but not ownership, liveness validation or
|
|
65
|
+
close-on-dispose; the `Effect` shape but not chain/insert helpers, whose
|
|
66
|
+
dispose and rollback semantics differ by design; the `WorkerLike` surface and
|
|
67
|
+
request correlation but not protocol versioning, cancellation or restart
|
|
68
|
+
policy. Pulling those in would not remove duplication — it would force one
|
|
69
|
+
family's semantics onto the other.
|
|
70
|
+
|
|
71
|
+
## Module map
|
|
72
|
+
|
|
73
|
+
| Entry | Contract |
|
|
74
|
+
|---|---|
|
|
75
|
+
| `@webmusic/kernel/events` | Hardened typed `EventEmitter` |
|
|
76
|
+
| `@webmusic/kernel/element` | `WebMusicElement` connected-lifetime cleanup plus SSR-safe attribute and registration helpers |
|
|
77
|
+
| `@webmusic/kernel/worker` | `WorkerLike`, `RequestTracker` correlation plumbing, `dedicatedWorkerScope()` |
|
|
78
|
+
| `@webmusic/kernel/audio-context` | SSR-safe AudioContext construction |
|
|
79
|
+
| `@webmusic/kernel/player` | `PlayerLike` playback control contract, capability tiers + guards |
|
|
80
|
+
| `@webmusic/kernel/effect` | `Effect`/`EffectNodes` over `BaseAudioContext` |
|
|
81
|
+
| `@webmusic/kernel/meter` | `AnalyserMeter` tap, RMS/peak with peak hold, `aggregateSpectrumBars` |
|
|
82
|
+
| `@webmusic/kernel/transport` | `TransportClock` affine anchor math + `TimelineMapping` |
|
|
83
|
+
| `@webmusic/kernel/tick` | Throttling-resistant tick delivery for lookahead schedulers |
|
|
84
|
+
| `@webmusic/kernel/sync` | `TransportGroup` master/follower choreography + `MirrorClockMaster` |
|
|
85
|
+
|
|
86
|
+
Internally the kernel is almost entirely flat: every module is a leaf except
|
|
87
|
+
`sync`, which composes `transport` and `tick`.
|
|
88
|
+
|
|
89
|
+
```text
|
|
90
|
+
transport ──┐
|
|
91
|
+
├──→ sync events element worker
|
|
92
|
+
tick ───────┘ audio-context player effect meter
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
That shape is intentional. A module that imports a sibling has taken a
|
|
96
|
+
position on how the sibling is used; nine independent leaves let a consumer
|
|
97
|
+
adopt the parts it needs — and let a third party implement the contracts
|
|
98
|
+
without inheriting the machinery.
|
|
99
|
+
|
|
100
|
+
## Design principles
|
|
101
|
+
|
|
102
|
+
These recur across the modules and explain most of the local decisions.
|
|
103
|
+
|
|
104
|
+
**Player, effect and mapping contracts are structural.** Consumers satisfy these
|
|
105
|
+
interfaces by shape without inheriting a shared domain base class. The optional
|
|
106
|
+
`WebMusicElement` lifecycle base serves a separate browser composition concern. `AudioClipPlayer`
|
|
107
|
+
and `ScorePlayer` satisfy `PlayerLike` without either knowing the other
|
|
108
|
+
exists; an `Effect` crosses families because it has `createAudioNodes`. Two
|
|
109
|
+
consequences are load-bearing: contract members use method-shorthand syntax
|
|
110
|
+
so that method bivariance lets a typed-emitter `on<K extends keyof E>(…)`
|
|
111
|
+
satisfy the loose `on(event: string, …)` (arrow-property signatures would
|
|
112
|
+
reject every typed-emitter implementer under `strictFunctionTypes`), and
|
|
113
|
+
families pin their conformance in type-only `*-contract.ts` modules so drift
|
|
114
|
+
fails at the definition site rather than at some distant call.
|
|
115
|
+
|
|
116
|
+
**Optional capability, named and guarded.** `PlayerLike`'s optional members
|
|
117
|
+
are the lowest common denominator both families can always promise. Each
|
|
118
|
+
optional capability is *named* by an interface — `TimedPlayerLike`,
|
|
119
|
+
`StatefulPlayerLike`, `RateControlledPlayerLike`, `VolumeControlledPlayerLike`,
|
|
120
|
+
`DisposablePlayerLike` — and feature-tested through an exported `is*Player()`
|
|
121
|
+
guard. Implementers advertise a capability by making its members
|
|
122
|
+
non-optional; consumers narrow once with a guard instead of poking optional
|
|
123
|
+
members everywhere, and a failed guard means "absent", never "error".
|
|
124
|
+
|
|
125
|
+
**Purity, with time injected.** `TransportClock` never reads a clock unless
|
|
126
|
+
one is handed to it; every mutator takes the current reference time
|
|
127
|
+
explicitly. `TransportGroup` takes `now()` as a constructor argument and is
|
|
128
|
+
Web-Audio-free. `RequestTracker` is bookkeeping with no worker attached.
|
|
129
|
+
`aggregateSpectrumBars` is a pure function beside the live meter. This is what
|
|
130
|
+
makes the timing core testable against a counter and reusable against
|
|
131
|
+
`AudioContext.currentTime`, `performance.now()/1000`, or an offline render.
|
|
132
|
+
|
|
133
|
+
**Numbers in, numbers out — units are the consumer's.** The clock is
|
|
134
|
+
unit-agnostic: it maps a monotonic reference axis onto a position axis and
|
|
135
|
+
takes no view on whether positions are media seconds, nominal seconds or
|
|
136
|
+
samples. Clamping to a duration is domain policy. Loop is out of scope
|
|
137
|
+
(a consumer can wrap with `seekTo(loopStart, t)`, or maintain a separately mapped
|
|
138
|
+
local loop phase). The kernel's job is to be the one place the affine math is
|
|
139
|
+
correct, not to decide what the axis means.
|
|
140
|
+
|
|
141
|
+
**SSR-safe at import.** `HTMLElementBase` resolves to `HTMLElement` where it
|
|
142
|
+
exists and a plain class elsewhere, so an element module can be imported in
|
|
143
|
+
Node without a `ReferenceError`; `defineOnce` is a no-op outside a browser;
|
|
144
|
+
`getAudioContextConstructor()` returns `undefined` rather than throwing;
|
|
145
|
+
`dedicatedWorkerScope()` returns `undefined` outside a real dedicated worker,
|
|
146
|
+
so a worker runtime's registration is inert when the same module is imported
|
|
147
|
+
from Node, SSR or the main thread. Importing any entry has no side effects.
|
|
148
|
+
|
|
149
|
+
**Degrade transparently, never silently.** The tick source falls back from a
|
|
150
|
+
worker to a main-thread interval when `Worker`/`Blob`/`URL` are missing, when
|
|
151
|
+
CSP rejects the blob worker synchronously, and when the worker fails
|
|
152
|
+
asynchronously after construction — same surface either way, with
|
|
153
|
+
`workerBacked` telling the truth about which path is live. What the kernel
|
|
154
|
+
avoids is the failure mode where a component reports success and then does
|
|
155
|
+
nothing.
|
|
156
|
+
|
|
157
|
+
## The clock spine
|
|
158
|
+
|
|
159
|
+
`transport` + `tick` + `sync` are the part of the kernel the rest of the
|
|
160
|
+
project's alignment rests on. They are three separate concerns: what time
|
|
161
|
+
*is*, how work gets *woken up*, and how several transports *agree*.
|
|
162
|
+
|
|
163
|
+
### TransportClock — one affine anchor
|
|
164
|
+
|
|
165
|
+
```text
|
|
166
|
+
position(t) = paused ? originPosition
|
|
167
|
+
: originPosition + (t - originTime) * rate
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
Four numbers (`originTime`, `originPosition`, `rate`, `paused`) and a handful
|
|
171
|
+
of transitions that all preserve position continuity:
|
|
172
|
+
|
|
173
|
+
- `start(t, position?)` anchors and unpauses; re-anchoring while playing is
|
|
174
|
+
idempotent for the position at `t`.
|
|
175
|
+
- `pause(t)` folds elapsed time into `originPosition`.
|
|
176
|
+
- `seekTo(position, t)` re-anchors while preserving the paused/playing state.
|
|
177
|
+
- `setRate(r, t)` re-anchors at `t` first so the position is continuous
|
|
178
|
+
across the slope change. `r` must be finite and `> 0`.
|
|
179
|
+
|
|
180
|
+
Every anchor mutator rejects non-finite input. A `NaN` reference time or
|
|
181
|
+
position would otherwise flow into the anchor and poison every later
|
|
182
|
+
`positionAt` read with no error at the source — the kind of corruption that
|
|
183
|
+
surfaces three layers away from its cause.
|
|
184
|
+
|
|
185
|
+
`timeAt` is the inverse, and it throws rather than inventing an answer where
|
|
186
|
+
none exists: while paused, no reference time maps to a position at all.
|
|
187
|
+
|
|
188
|
+
### Scheduled starts and the pre-roll hold
|
|
189
|
+
|
|
190
|
+
`startAt(t, position)` arms a *scheduled* start: the clock is unpaused, but
|
|
191
|
+
the position holds at `position` until `t` arrives — the clock-side mirror of
|
|
192
|
+
a sample-accurate `source.start(when)`, which sounds nothing before `when`.
|
|
193
|
+
The hold is what lets a follower join a master at an instant that has not
|
|
194
|
+
happened yet.
|
|
195
|
+
|
|
196
|
+
Transitions during the pre-roll keep the armed origin: `setRate` changes the
|
|
197
|
+
slope after `t` without collapsing the hold (naively re-anchoring at `t` here
|
|
198
|
+
is the engine bug this mode exists to prevent), `seekTo` re-arms the held
|
|
199
|
+
position, and `pause` cancels the pending start. `timeAt` refuses positions
|
|
200
|
+
below the armed origin, because a holding clock never passes through them —
|
|
201
|
+
extrapolating backwards would hand a follower a confident, schedulable, wrong
|
|
202
|
+
answer.
|
|
203
|
+
|
|
204
|
+
### TransportClockReader — sharing without ownership
|
|
205
|
+
|
|
206
|
+
```ts
|
|
207
|
+
type TransportClockReader = Pick<TransportClock,
|
|
208
|
+
'state' | 'rate' | 'paused' | 'holding' | 'positionAt' | 'timeAt'>;
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
The reader is what a transport *owner* exposes to consumers: a sync group,
|
|
212
|
+
a view, a follower can anchor against its affine map without estimating that map
|
|
213
|
+
from sampled positions. The reader exposes no mutator in its TypeScript surface;
|
|
214
|
+
it is not an immutable snapshot or a runtime access-control boundary. It also
|
|
215
|
+
provides no anchor-change notification. Exact mapping reads do not confer audio
|
|
216
|
+
scheduling precision on a backend, timer or UI callback.
|
|
217
|
+
|
|
218
|
+
The accepted architecture is one timeline authority per session, with independent
|
|
219
|
+
sessions. Today's `TransportGroup` supplies a master-based authority while each
|
|
220
|
+
engine retains its private clock. Same-instance injection and invalidation of
|
|
221
|
+
already committed audio are not implemented by this reader.
|
|
222
|
+
|
|
223
|
+
### TimelineMapping — the musical-axis seam
|
|
224
|
+
|
|
225
|
+
`TransportClock` is affine, so it cannot express tempo curves, and it should
|
|
226
|
+
not try. `TimelineMapping` is the two-function seam where a musical axis
|
|
227
|
+
(quarters, beats — the consumer names the unit) meets media seconds:
|
|
228
|
+
|
|
229
|
+
```ts
|
|
230
|
+
interface TimelineMapping {
|
|
231
|
+
positionToSeconds(position: number): number;
|
|
232
|
+
secondsToPosition(seconds: number): number;
|
|
233
|
+
}
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
Implementations should be total over the reals and monotonic non-decreasing;
|
|
237
|
+
they may clamp negatives and may quantize, so round-trips are approximate by
|
|
238
|
+
the mapping's own policy. Both families ship an adapter (`timeMapMapping`
|
|
239
|
+
over score's `TimeMap`, `beatGridMapping` over audio's `BeatGrid`), which is
|
|
240
|
+
what makes the two musical axes interoperable through seconds.
|
|
241
|
+
|
|
242
|
+
### TickSource — keeping schedulers fed
|
|
243
|
+
|
|
244
|
+
The tick source uses an inline Blob worker to reduce reliance on main-thread
|
|
245
|
+
intervals under background throttling. It posts a bare tick on an interval and
|
|
246
|
+
needs no separate asset. This is a wakeup mechanism, not a real-time guarantee:
|
|
247
|
+
worker suspension, delivery to the main thread and browser lifecycle policy can
|
|
248
|
+
still delay scheduling. Environments without `Worker`/`Blob`/`URL`, or with a CSP
|
|
249
|
+
that forbids blob workers, fall back to a main-thread interval.
|
|
250
|
+
|
|
251
|
+
The surface is deliberately tiny: `start(onTick)` / `stop()` / `dispose()`,
|
|
252
|
+
plus `running` and `workerBacked`. It delivers ticks; it holds no opinion
|
|
253
|
+
about what the tick does.
|
|
254
|
+
|
|
255
|
+
### TransportGroup — master, followers, and the join dance
|
|
256
|
+
|
|
257
|
+
`sync` is the choreography the score↔audio bridge proved out, hoisted once
|
|
258
|
+
its class body turned out to reference only kernel types. One **master** whose
|
|
259
|
+
clock is the group's timeline, N **followers** that join it, all positions on
|
|
260
|
+
the master's axis against one shared reference clock.
|
|
261
|
+
|
|
262
|
+
```text
|
|
263
|
+
master.clock (TransportClockReader) ← the timeline, read never written
|
|
264
|
+
│
|
|
265
|
+
├─ join: when = armed origin if it is still ahead, else now + leadIn
|
|
266
|
+
│ follower.setRate(clock.rate * positionScale)
|
|
267
|
+
│ follower.seek(localPhase(offset + clock.positionAt(when) * positionScale))
|
|
268
|
+
│ follower.play(when) ← sample-accurate on a real engine
|
|
269
|
+
│
|
|
270
|
+
├─ drift: every driftCheckIntervalMs, compare each follower against
|
|
271
|
+
│ mapped local phase; re-join past master-unit tolerance
|
|
272
|
+
│
|
|
273
|
+
└─ loop: every tick, wrap at the boundary through the same join dance
|
|
274
|
+
```
|
|
275
|
+
|
|
276
|
+
The role contracts encode the design:
|
|
277
|
+
|
|
278
|
+
- The master **must** expose a `TransportClockReader`. There is no clockless
|
|
279
|
+
code path inside the group — a transport without a clock is wrapped in
|
|
280
|
+
`MirrorClockMaster` instead, so the fallback exists once as an adapter
|
|
281
|
+
rather than as a second branch through every method.
|
|
282
|
+
- Scheduled-start support is **observed, not declared**. The group proposes
|
|
283
|
+
`now + leadIn` to `master.play(when)`; a master that can arm does, and the
|
|
284
|
+
group notices through `clock.holding`. A master that ignores the proposal
|
|
285
|
+
starts immediately and followers join a lead-in later. No capability flag
|
|
286
|
+
to keep honest.
|
|
287
|
+
- `master.seekPosition` may resolve with the transport left *paused*, which
|
|
288
|
+
the group reads as a failed resume: it pauses the followers, settles into
|
|
289
|
+
the paused state, and reports it — rather than leaving a master stalled
|
|
290
|
+
while followers play on.
|
|
291
|
+
- `master.reconcile(now)` is the optional hook an adapter uses to say the
|
|
292
|
+
master stopped on its own (`'stalled'`), which the group handles exactly
|
|
293
|
+
like an observed stop.
|
|
294
|
+
- Followers honor future `play(when)` for scheduled alignment, carry an `offsetSeconds`,
|
|
295
|
+
and may expose their own clock — when they do, drift is read from the clock
|
|
296
|
+
instead of sampled.
|
|
297
|
+
|
|
298
|
+
A join aligns the **slope before the intercept**: it hands the follower the
|
|
299
|
+
clock's current rate and only then seeks and schedules. Seeking alone would
|
|
300
|
+
leave a rate mismatch intact, so the drift just corrected starts growing back
|
|
301
|
+
immediately — the same reasoning that makes `MirrorClockMaster` re-learn a
|
|
302
|
+
rate rather than only a position.
|
|
303
|
+
|
|
304
|
+
Two safeguards keep corrections from becoming pathologies. Drift checks hold
|
|
305
|
+
off until a scheduled join's origin has passed, because a follower parked at
|
|
306
|
+
its offset through a pre-roll is not drifting. And after
|
|
307
|
+
`MAX_CONSECUTIVE_DRIFT_JOINS` (3) corrections that fail to bring a follower
|
|
308
|
+
into tolerance, the group stops re-joining it and reports instead — each
|
|
309
|
+
correction restarts a follower audibly, so a mismatch corrections cannot fix
|
|
310
|
+
must not stutter forever. Any explicit command re-arms the corrections.
|
|
311
|
+
|
|
312
|
+
The same group now exposes a revisioned command protocol: `dispatch(command)`
|
|
313
|
+
returns an observable `TransportCommit`, `snapshot` reads one coherent state, and
|
|
314
|
+
`subscribe(listener)` delivers the initial state before following invalidation,
|
|
315
|
+
settlement, background reconciliation and errors. Existing controls remain
|
|
316
|
+
migration surfaces. Strict dispatch checks observable failures and distinguishes
|
|
317
|
+
superseded commands; the engines cancel and re-arm through their existing methods,
|
|
318
|
+
retaining their private clocks. See the complete
|
|
319
|
+
[command contract](https://github.com/koperative-lab/WebMusic/blob/main/apps/doc/webmusic/src/content/docs/kernel/api.mdx).
|
|
320
|
+
|
|
321
|
+
`FollowerOptions.positionScale` adds a positive constant local-axis scale to the
|
|
322
|
+
offset, applied to both positions and rates. Optional `loop` metadata maps into
|
|
323
|
+
an already configured native loop; followers can retain independent periods while
|
|
324
|
+
the master continues. Drift compares local phase and reports master-axis seconds.
|
|
325
|
+
The group does not configure native loops, consume nonlinear mappings or perform
|
|
326
|
+
audio warping. Group-level loop re-entry still waits for a delivered watcher tick.
|
|
327
|
+
|
|
328
|
+
### MirrorClockMaster — the sampled fallback, once
|
|
329
|
+
|
|
330
|
+
A transport with no readable clock is adapted into the required-clock role by
|
|
331
|
+
dead-reckoning a mirror `TransportClock` across the command surface and
|
|
332
|
+
reconciling it against the transport's actual position on every drift check:
|
|
333
|
+
|
|
334
|
+
- two identical position samples while the mirror advanced past tolerance
|
|
335
|
+
mean the transport stopped on its own (ended, clamped, paused out of band):
|
|
336
|
+
pause the mirror and report `'stalled'`;
|
|
337
|
+
- a moving transport that diverged re-anchors the mirror — **slope as well as
|
|
338
|
+
intercept**. Correcting only the position leaves a transport that refused or
|
|
339
|
+
clamped the shared rate drifting away again before the next check, which is
|
|
340
|
+
precisely how a rate mismatch turns into an endless correction loop.
|
|
341
|
+
|
|
342
|
+
## Error and lifetime policy
|
|
343
|
+
|
|
344
|
+
**Two delivery modes, chosen by the owner.** `emit` propagates a listener's
|
|
345
|
+
exception to the caller — the historic behavior, and the right one for code
|
|
346
|
+
that wants to know. `emitSafely` isolates subscribers, reports synchronous
|
|
347
|
+
throws and rejected promises through an observer, and swallows the observer's
|
|
348
|
+
own failures: a diagnostic hook must never become a second path out of a
|
|
349
|
+
scheduler callback. Both snapshot their subscribers at dispatch start, so a
|
|
350
|
+
listener registered mid-dispatch is not delivered the in-flight event (with
|
|
351
|
+
live-set iteration, the ordinary self-rearming `once` idiom is an infinite
|
|
352
|
+
loop). `once` also stays single-fire when a listener recursively dispatches the
|
|
353
|
+
same event before the outer subscriber snapshot reaches it.
|
|
354
|
+
|
|
355
|
+
**Generations bound every asynchronous lifetime.** `WebMusicElement` gives
|
|
356
|
+
each connected lifetime a fresh cleanup scope, so a cleanup returned by an
|
|
357
|
+
`onMount` that synchronously disconnected and reconnected is released against
|
|
358
|
+
the lifetime it belonged to rather than attached to the new one; cleanups run
|
|
359
|
+
once, in reverse order, and failures are collected and routed through
|
|
360
|
+
`onLifecycleError` instead of aborting the rest. `TransportGroup` applies the
|
|
361
|
+
same discipline to commands: a FIFO serializes them, a generation counter
|
|
362
|
+
invalidates superseded work, and a recorded intent (`playing`/`paused`/
|
|
363
|
+
`stopped`) is re-applied when an older async command settles late — so a
|
|
364
|
+
`pause()` issued during an in-flight `play()` stays authoritative.
|
|
365
|
+
|
|
366
|
+
**Fire-and-forget work gets an observer.** Drift and rate re-joins, loop
|
|
367
|
+
wraps and stop reconciliation run behind the command queue with no caller
|
|
368
|
+
promise to reject; on failure they settle the group into a paused state.
|
|
369
|
+
`onOperationError(operation, error)` is how that settlement becomes visible
|
|
370
|
+
rather than silent.
|
|
371
|
+
|
|
372
|
+
## What the kernel deliberately does not do
|
|
373
|
+
|
|
374
|
+
Recorded so the boundaries are visible rather than discovered:
|
|
375
|
+
|
|
376
|
+
- **No non-positive running rate.** `rate` must be finite and `> 0`.
|
|
377
|
+
Reverse playback is not represented by a negative rate. Pause holds position;
|
|
378
|
+
applications can implement scrubbing through explicit seeks.
|
|
379
|
+
- **No mutable-clock injection.** `TransportClock` remains pure time math with
|
|
380
|
+
no event surface. `TransportGroup` now publishes command invalidation and
|
|
381
|
+
settlement, but each engine still owns its clock; direct mutations outside
|
|
382
|
+
the group are not automatically versioned. See
|
|
383
|
+
[`platform/shared-clock-injection.md`](https://github.com/koperative-lab/WebMusic/blob/main/platform/shared-clock-injection.md).
|
|
384
|
+
- **No nonlinear mapped alignment.** `TimelineMapping` is published and both
|
|
385
|
+
families ship adapters. The group consumes constant offset/scale and optional
|
|
386
|
+
native-loop phase, not nonlinear rubato or audio-warp mappings.
|
|
387
|
+
- **No shared tick.** `TickSource` is single-callback by contract, so each
|
|
388
|
+
consumer owns a worker; several transports in one page mean several
|
|
389
|
+
workers.
|
|
390
|
+
- **No loop inside the clock.** Wrapping is `seekTo(loopStart, t)` at the
|
|
391
|
+
consumer, where the domain's boundary policy lives. Group loops currently
|
|
392
|
+
detect boundaries on ticks and do not promise sample-accurate wrap.
|
|
393
|
+
|
|
394
|
+
## Using the kernel from outside
|
|
395
|
+
|
|
396
|
+
Third parties implementing a WebMusic-compatible player, effect, or timeline
|
|
397
|
+
mapping should depend on this package and implement the structural contracts.
|
|
398
|
+
For players, implement the `PlayerLike` base plus whichever capability tiers
|
|
399
|
+
you can honestly advertise (`TimedPlayerLike`, `StatefulPlayerLike`,
|
|
400
|
+
`RateControlledPlayerLike`, `VolumeControlledPlayerLike`,
|
|
401
|
+
`DisposablePlayerLike`); consumers discover capabilities through the
|
|
402
|
+
exported `is*Player()` guards, never by poking optional members.
|
|
403
|
+
|
|
404
|
+
To take part in synchronized playback, implement `SyncFollowerTransport`
|
|
405
|
+
(honor `play(when)` sample-accurately) or `SyncMasterTransport` (expose a
|
|
406
|
+
`TransportClockReader`; wrap a clockless transport in `MirrorClockMaster`).
|
|
407
|
+
|
|
408
|
+
## Gates
|
|
409
|
+
|
|
410
|
+
The multi-entry build explicitly enables code splitting for both module formats.
|
|
411
|
+
This keeps root/subpath re-exports identical within ESM and within CommonJS,
|
|
412
|
+
including the `TransportClock` created by `MirrorClockMaster`. ESM and CommonJS
|
|
413
|
+
remain separate module instances; cross-format constructor identity is not promised.
|
|
414
|
+
|
|
415
|
+
The kernel is a first-class checked package: its policy declares zero
|
|
416
|
+
workspace dependencies, so any domain import inside `platform/kernel` fails
|
|
417
|
+
the architecture gate. Public entries are verified against the export map,
|
|
418
|
+
and the whole repository runs `npm run check`. The current command graph is in
|
|
419
|
+
[root package.json](https://github.com/koperative-lab/WebMusic/blob/main/package.json); development instructions are in
|
|
420
|
+
[CONTRIBUTING.md](https://github.com/koperative-lab/WebMusic/blob/main/CONTRIBUTING.md). The executable architecture sources
|
|
421
|
+
include [package-policy.mjs](https://github.com/koperative-lab/WebMusic/blob/main/scripts/package-policy.mjs),
|
|
422
|
+
[element-composition-policy.mjs](https://github.com/koperative-lab/WebMusic/blob/main/scripts/element-composition-policy.mjs) and
|
|
423
|
+
[check-architecture.mjs](https://github.com/koperative-lab/WebMusic/blob/main/scripts/check-architecture.mjs), each with a distinct
|
|
424
|
+
scope. Check the exported contracts and relevant behavioral tests when changing them.
|
|
425
|
+
|
|
426
|
+
The extraction ledger — what moved here, from where, what it replaced, and
|
|
427
|
+
what deliberately stayed per-family — lives in
|
|
428
|
+
[`platform/README.md`](https://github.com/koperative-lab/WebMusic/blob/main/platform/README.md).
|
|
429
|
+
|
|
430
|
+
## License
|
|
431
|
+
|
|
432
|
+
MIT
|
|
433
|
+
|
|
434
|
+
For source contributions and release verification, see the
|
|
435
|
+
[contribution guide](https://github.com/koperative-lab/WebMusic/blob/main/CONTRIBUTING.md).
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
var _chunkVY6WWZSWcjs = require('./chunk-VY6WWZSW.cjs');
|
|
5
|
+
require('./chunk-7ZTZZ5PN.cjs');
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
exports.createWebAudioContext = _chunkVY6WWZSWcjs.createWebAudioContext; exports.getAudioContextConstructor = _chunkVY6WWZSWcjs.getAudioContextConstructor;
|
|
10
|
+
//# sourceMappingURL=audio-context.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/Users/mamingchen/GitHub/public/WebMusic/platform/kernel/dist/audio-context.cjs"],"names":[],"mappings":"AAAA;AACE;AACA;AACF,wDAA6B;AAC7B,gCAA6B;AAC7B;AACE;AACA;AACF,2JAAC","file":"/Users/mamingchen/GitHub/public/WebMusic/platform/kernel/dist/audio-context.cjs"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The runtime AudioContext constructor (standard, else legacy
|
|
3
|
+
* `webkitAudioContext`); `undefined` when Web Audio is absent (SSR / Node).
|
|
4
|
+
*/
|
|
5
|
+
declare function getAudioContextConstructor(): (typeof AudioContext) | undefined;
|
|
6
|
+
/**
|
|
7
|
+
* Construct an AudioContext, throwing `missingMessage` when Web Audio is
|
|
8
|
+
* unavailable. Calls the constructor with no argument when `options` is
|
|
9
|
+
* omitted, preserving `arguments.length`-sensitive test fakes.
|
|
10
|
+
*/
|
|
11
|
+
declare function createWebAudioContext(missingMessage: string, options?: AudioContextOptions): AudioContext;
|
|
12
|
+
|
|
13
|
+
export { createWebAudioContext, getAudioContextConstructor };
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The runtime AudioContext constructor (standard, else legacy
|
|
3
|
+
* `webkitAudioContext`); `undefined` when Web Audio is absent (SSR / Node).
|
|
4
|
+
*/
|
|
5
|
+
declare function getAudioContextConstructor(): (typeof AudioContext) | undefined;
|
|
6
|
+
/**
|
|
7
|
+
* Construct an AudioContext, throwing `missingMessage` when Web Audio is
|
|
8
|
+
* unavailable. Calls the constructor with no argument when `options` is
|
|
9
|
+
* omitted, preserving `arguments.length`-sensitive test fakes.
|
|
10
|
+
*/
|
|
11
|
+
declare function createWebAudioContext(missingMessage: string, options?: AudioContextOptions): AudioContext;
|
|
12
|
+
|
|
13
|
+
export { createWebAudioContext, getAudioContextConstructor };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/tick.ts
|
|
2
|
+
var MAX_TIMER_DELAY_MS = 2147483647;
|
|
3
|
+
var WORKER_SOURCE = `
|
|
4
|
+
let id = null;
|
|
5
|
+
onmessage = (event) => {
|
|
6
|
+
const data = event.data;
|
|
7
|
+
if (data && data.type === 'start') {
|
|
8
|
+
clearInterval(id);
|
|
9
|
+
id = setInterval(() => postMessage(0), data.intervalMs);
|
|
10
|
+
} else if (data && data.type === 'stop') {
|
|
11
|
+
clearInterval(id);
|
|
12
|
+
id = null;
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
`;
|
|
16
|
+
function defaultWorkerFactory() {
|
|
17
|
+
if (typeof Worker === "undefined" || typeof Blob === "undefined" || typeof URL === "undefined") {
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
let url;
|
|
21
|
+
try {
|
|
22
|
+
url = URL.createObjectURL(new Blob([WORKER_SOURCE], { type: "text/javascript" }));
|
|
23
|
+
return new Worker(url);
|
|
24
|
+
} catch (e) {
|
|
25
|
+
return null;
|
|
26
|
+
} finally {
|
|
27
|
+
if (url !== void 0) {
|
|
28
|
+
try {
|
|
29
|
+
URL.revokeObjectURL(url);
|
|
30
|
+
} catch (e2) {
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
function createTickSource(options = {}) {
|
|
36
|
+
const intervalMs = _nullishCoalesce(options.intervalMs, () => ( 25));
|
|
37
|
+
if (!Number.isSafeInteger(intervalMs) || intervalMs < 1 || intervalMs > MAX_TIMER_DELAY_MS) {
|
|
38
|
+
throw new RangeError(
|
|
39
|
+
`TickSource intervalMs must be a positive safe integer no greater than ${MAX_TIMER_DELAY_MS}, got ${intervalMs}.`
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
const worker = (_nullishCoalesce(options.createWorker, () => ( defaultWorkerFactory)))();
|
|
43
|
+
let activeWorker = worker;
|
|
44
|
+
let callback = null;
|
|
45
|
+
let running = false;
|
|
46
|
+
let disposed = false;
|
|
47
|
+
let fallbackId = null;
|
|
48
|
+
const startFallbackInterval = () => {
|
|
49
|
+
_nullishCoalesce(fallbackId, () => ( (fallbackId = setInterval(() => {
|
|
50
|
+
if (running) _optionalChain([callback, 'optionalCall', _ => _()]);
|
|
51
|
+
}, intervalMs))));
|
|
52
|
+
};
|
|
53
|
+
const fallBackFromWorker = () => {
|
|
54
|
+
if (activeWorker === null || disposed) return;
|
|
55
|
+
const failedWorker = activeWorker;
|
|
56
|
+
activeWorker = null;
|
|
57
|
+
try {
|
|
58
|
+
failedWorker.terminate();
|
|
59
|
+
} catch (e3) {
|
|
60
|
+
}
|
|
61
|
+
if (running) startFallbackInterval();
|
|
62
|
+
};
|
|
63
|
+
if (worker) {
|
|
64
|
+
worker.addEventListener("message", () => {
|
|
65
|
+
if (activeWorker === worker && running) _optionalChain([callback, 'optionalCall', _2 => _2()]);
|
|
66
|
+
});
|
|
67
|
+
worker.addEventListener("error", () => {
|
|
68
|
+
fallBackFromWorker();
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
return {
|
|
72
|
+
get running() {
|
|
73
|
+
return running;
|
|
74
|
+
},
|
|
75
|
+
get workerBacked() {
|
|
76
|
+
return activeWorker !== null;
|
|
77
|
+
},
|
|
78
|
+
start(onTick) {
|
|
79
|
+
if (disposed) throw new Error("TickSource has been disposed.");
|
|
80
|
+
callback = onTick;
|
|
81
|
+
if (running) return;
|
|
82
|
+
running = true;
|
|
83
|
+
if (activeWorker) {
|
|
84
|
+
try {
|
|
85
|
+
activeWorker.postMessage({ type: "start", intervalMs });
|
|
86
|
+
} catch (e4) {
|
|
87
|
+
fallBackFromWorker();
|
|
88
|
+
}
|
|
89
|
+
} else {
|
|
90
|
+
startFallbackInterval();
|
|
91
|
+
}
|
|
92
|
+
},
|
|
93
|
+
stop() {
|
|
94
|
+
if (!running) return;
|
|
95
|
+
running = false;
|
|
96
|
+
if (activeWorker) {
|
|
97
|
+
try {
|
|
98
|
+
activeWorker.postMessage({ type: "stop" });
|
|
99
|
+
} catch (error) {
|
|
100
|
+
if (disposed) throw error;
|
|
101
|
+
fallBackFromWorker();
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
if (fallbackId !== null) {
|
|
105
|
+
clearInterval(fallbackId);
|
|
106
|
+
fallbackId = null;
|
|
107
|
+
}
|
|
108
|
+
},
|
|
109
|
+
dispose() {
|
|
110
|
+
if (disposed) return;
|
|
111
|
+
disposed = true;
|
|
112
|
+
const errors = [];
|
|
113
|
+
try {
|
|
114
|
+
this.stop();
|
|
115
|
+
} catch (error) {
|
|
116
|
+
errors.push(error);
|
|
117
|
+
}
|
|
118
|
+
callback = null;
|
|
119
|
+
try {
|
|
120
|
+
_optionalChain([activeWorker, 'optionalAccess', _3 => _3.terminate, 'call', _4 => _4()]);
|
|
121
|
+
} catch (error) {
|
|
122
|
+
errors.push(error);
|
|
123
|
+
}
|
|
124
|
+
activeWorker = null;
|
|
125
|
+
if (errors.length > 0) throw errors[0];
|
|
126
|
+
}
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
exports.MAX_TIMER_DELAY_MS = MAX_TIMER_DELAY_MS; exports.createTickSource = createTickSource;
|
|
134
|
+
//# sourceMappingURL=chunk-3INDOVUC.cjs.map
|