@openbone/player 0.0.0-stage → 0.3.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/dist/audio.js ADDED
@@ -0,0 +1,394 @@
1
+ import { busGain } from "@openbone/core";
2
+ const isAbsolute = (src) => /^(data:|https?:|blob:|\/)/.test(src);
3
+ /**
4
+ * Plays the runtime's AudioCommands with the Web Audio API: resolves and decodes assets (cached per URL),
5
+ * routes each sound through its bus into the master, applies fades, and follows the document's mix
6
+ * (call `syncMix()` after changing bus/master values). Browsers block audio until a user gesture, so the
7
+ * context is resumed by the first pointer/key event (see `unlock`); one-shots requested before that are skipped.
8
+ */
9
+ export class WebAudioBackend {
10
+ doc;
11
+ opts;
12
+ ctx;
13
+ master = null;
14
+ buses = new Map();
15
+ buffers = new Map();
16
+ voices = new Map();
17
+ hostMuted = false;
18
+ unbind = null;
19
+ constructor(doc, opts = {}) {
20
+ this.doc = doc;
21
+ this.opts = opts;
22
+ this.ctx = opts.context ?? null;
23
+ }
24
+ /** True once the browser lets the context play. */
25
+ get unlocked() {
26
+ return this.ctx?.state === "running";
27
+ }
28
+ get muted() {
29
+ return this.hostMuted;
30
+ }
31
+ /** Mute everything (independent of the document's own mute). */
32
+ setMuted(m) {
33
+ this.hostMuted = m;
34
+ this.syncMix();
35
+ }
36
+ setDocument(doc) {
37
+ this.doc = doc;
38
+ this.syncMix();
39
+ }
40
+ setBaseUrl(url) {
41
+ this.opts.baseUrl = url;
42
+ }
43
+ /** Create (if needed) and resume the context now. Call it from a user gesture (a click) so the browser allows sound. */
44
+ activate() {
45
+ const ctx = this.context();
46
+ if (ctx && ctx.state !== "running")
47
+ void ctx.resume();
48
+ return ctx;
49
+ }
50
+ context() {
51
+ if (this.ctx)
52
+ return this.ctx;
53
+ const Ctor = globalThis.AudioContext ?? globalThis.webkitAudioContext;
54
+ if (!Ctor)
55
+ return null;
56
+ this.ctx = new Ctor();
57
+ return this.ctx;
58
+ }
59
+ masterNode(ctx) {
60
+ if (!this.master) {
61
+ this.master = ctx.createGain();
62
+ this.master.connect(ctx.destination);
63
+ this.syncMix();
64
+ }
65
+ return this.master;
66
+ }
67
+ busNode(ctx, busId) {
68
+ const master = this.masterNode(ctx);
69
+ if (!busId || !this.doc.audio?.buses.some((b) => b.id === busId))
70
+ return master;
71
+ let g = this.buses.get(busId);
72
+ if (!g) {
73
+ g = ctx.createGain();
74
+ g.connect(master);
75
+ this.buses.set(busId, g);
76
+ this.syncMix();
77
+ }
78
+ return g;
79
+ }
80
+ /** Mutes set while playing by "mix" commands (mute buttons): bus id, "" = master. They win over the document. */
81
+ mixMutes = new Map();
82
+ isMuted(busId) {
83
+ const key = busId ?? "";
84
+ if (this.mixMutes.has(key))
85
+ return this.mixMutes.get(key);
86
+ const a = this.doc.audio;
87
+ return busId === null ? !!a?.muted : !!a?.buses.find((b) => b.id === busId)?.muted;
88
+ }
89
+ /** Apply the document's master/bus volumes and mutes (and the host mute, and mute buttons) to the graph. */
90
+ syncMix() {
91
+ const ctx = this.ctx;
92
+ if (!ctx)
93
+ return;
94
+ const a = this.doc.audio;
95
+ const t = ctx.currentTime;
96
+ if (this.master)
97
+ this.master.gain.setTargetAtTime(this.hostMuted || this.isMuted(null) ? 0 : (a?.master ?? 1), t, 0.015);
98
+ for (const [id, g] of this.buses) {
99
+ const bus = a?.buses.find((b) => b.id === id);
100
+ g.gain.setTargetAtTime(bus ? (this.isMuted(id) ? 0 : bus.volume) : 1, t, 0.015);
101
+ }
102
+ }
103
+ /** Effective gain a sound on `busId` gets from the mix right now (master x bus, 0 when muted). */
104
+ busGain(busId) {
105
+ if (this.hostMuted || this.isMuted(null) || (busId !== null && this.isMuted(busId)))
106
+ return 0;
107
+ return busGain(this.doc, busId);
108
+ }
109
+ url(asset) {
110
+ if (this.opts.resolveUrl)
111
+ return this.opts.resolveUrl(asset);
112
+ return isAbsolute(asset.src) ? asset.src : (this.opts.baseUrl ?? "") + asset.src;
113
+ }
114
+ /** Fetch and decode an asset (cached by URL). */
115
+ load(asset) {
116
+ const url = this.url(asset);
117
+ let p = this.buffers.get(url);
118
+ if (!p) {
119
+ const ctx = this.context();
120
+ if (!ctx)
121
+ return Promise.resolve(null);
122
+ p = fetch(url)
123
+ .then((r) => {
124
+ if (!r.ok)
125
+ throw new Error(`${r.status}`);
126
+ return r.arrayBuffer();
127
+ })
128
+ .then((buf) => ctx.decodeAudioData(buf))
129
+ .catch((e) => {
130
+ this.opts.onLog?.(`could not load audio "${asset.name}": ${e.message}`);
131
+ this.buffers.delete(url);
132
+ return null;
133
+ });
134
+ this.buffers.set(url, p);
135
+ }
136
+ return p;
137
+ }
138
+ /** Start decoding every asset in the document. */
139
+ preload() {
140
+ return Promise.all((this.doc.audio?.assets ?? []).map((a) => this.load(a)));
141
+ }
142
+ /** Resume the context on the first user gesture on `target` (default: window). Safe to call more than once. */
143
+ unlock(target = globalThis) {
144
+ if (this.unbind || !target?.addEventListener)
145
+ return;
146
+ const evs = ["pointerdown", "keydown", "touchend"];
147
+ const go = () => {
148
+ const ctx = this.context();
149
+ if (!ctx)
150
+ return;
151
+ void ctx.resume().then(() => {
152
+ if (ctx.state === "running") {
153
+ this.opts.onLog?.("audio unlocked");
154
+ this.unbind?.();
155
+ }
156
+ });
157
+ };
158
+ for (const e of evs)
159
+ target.addEventListener(e, go, { capture: true });
160
+ this.unbind = () => {
161
+ for (const e of evs)
162
+ target.removeEventListener(e, go, { capture: true });
163
+ this.unbind = () => { };
164
+ };
165
+ }
166
+ /** Handle one runtime command. Pass this to `instance.on("audio", ...)`. */
167
+ handle = (cmd) => {
168
+ switch (cmd.type) {
169
+ case "play":
170
+ return this.play(cmd);
171
+ case "stop":
172
+ return this.stop(cmd.id, cmd.fade, cmd);
173
+ case "fade": {
174
+ const v = this.voices.get(cmd.id);
175
+ if (!v || !this.ctx)
176
+ return;
177
+ const t = this.ctx.currentTime;
178
+ v.gain.gain.cancelScheduledValues(t);
179
+ v.gain.gain.setValueAtTime(v.gain.gain.value, t);
180
+ v.gain.gain.linearRampToValueAtTime(cmd.volume, t + Math.max(0.005, cmd.duration));
181
+ this.opts.onLog?.(`fade ${cmd.id} → ${cmd.volume} over ${cmd.duration}s`, cmd);
182
+ return;
183
+ }
184
+ case "mix": {
185
+ this.mixMutes.set(cmd.bus ?? "", cmd.muted);
186
+ // Make sure the bus node exists so the mute applies to sounds started later too.
187
+ const ctx = this.ctx;
188
+ if (ctx && cmd.bus)
189
+ this.busNode(ctx, cmd.bus);
190
+ this.syncMix();
191
+ const name = cmd.bus === null ? "master" : (this.doc.audio?.buses.find((b) => b.id === cmd.bus)?.name ?? cmd.bus);
192
+ this.opts.onLog?.(`${cmd.muted ? "mute" : "unmute"} ${name}`, cmd);
193
+ return;
194
+ }
195
+ }
196
+ };
197
+ play(cmd) {
198
+ const asset = this.doc.audio?.assets.find((a) => a.id === cmd.asset);
199
+ const ctx = this.context();
200
+ const name = this.doc.audio?.sounds.find((s) => s.id === cmd.sound)?.name ?? asset?.name ?? cmd.sound;
201
+ if (!asset || !ctx) {
202
+ this.opts.onLog?.(`play ${name} skipped (${asset ? "no Web Audio" : "asset missing"})`, cmd);
203
+ return;
204
+ }
205
+ // One-shots before the first gesture would all burst out at unlock time: drop them. Loops start late.
206
+ if (ctx.state !== "running" && !cmd.loop) {
207
+ this.opts.onLog?.(`play ${name} skipped (audio locked until a click or key press)`, cmd);
208
+ return;
209
+ }
210
+ const gain = ctx.createGain();
211
+ gain.connect(this.busNode(ctx, cmd.bus));
212
+ const voice = { gain, source: null, stopped: false, rate: cmd.rate, loop: cmd.loop, startedAt: 0, offset: 0, paused: this.pausedAll ? 0 : null };
213
+ this.voices.set(cmd.id, voice);
214
+ this.opts.onLog?.(`play ${name} [${cmd.id}]${cmd.loop ? " loop" : ""} vol ${round(cmd.volume)} × bus ${round(this.busGain(cmd.bus))} rate ${cmd.rate} (${cmd.source})`, cmd);
215
+ void this.load(asset).then((buffer) => {
216
+ if (!buffer || voice.stopped) {
217
+ this.voices.delete(cmd.id);
218
+ gain.disconnect();
219
+ return;
220
+ }
221
+ voice.buffer = buffer;
222
+ const t = ctx.currentTime;
223
+ if (cmd.fadeIn > 0) {
224
+ gain.gain.setValueAtTime(0, t);
225
+ gain.gain.linearRampToValueAtTime(cmd.volume, t + cmd.fadeIn);
226
+ }
227
+ else
228
+ gain.gain.setValueAtTime(cmd.volume, t);
229
+ // Started while everything is paused: it waits at the beginning for resumeAll().
230
+ if (voice.paused === null)
231
+ this.startSource(cmd.id, voice, 0);
232
+ });
233
+ }
234
+ /** (Re)start a voice's buffer from `offset` seconds into the file, at the sound's rate × the backend's speed. */
235
+ startSource(id, voice, offset) {
236
+ const ctx = this.ctx;
237
+ if (!ctx || !voice.buffer)
238
+ return;
239
+ const src = ctx.createBufferSource();
240
+ src.buffer = voice.buffer;
241
+ src.loop = voice.loop;
242
+ src.playbackRate.value = voice.rate * this.speed;
243
+ src.connect(voice.gain);
244
+ src.onended = () => {
245
+ if (voice.source !== src)
246
+ return;
247
+ if (this.voices.get(id) === voice)
248
+ this.voices.delete(id);
249
+ voice.gain.disconnect();
250
+ };
251
+ voice.source = src;
252
+ voice.startedAt = ctx.currentTime;
253
+ voice.offset = offset;
254
+ voice.paused = null;
255
+ src.start(ctx.currentTime, Math.max(0, offset));
256
+ }
257
+ /** Where a voice is in its file now (seconds). */
258
+ position(v) {
259
+ if (v.paused !== null)
260
+ return v.paused;
261
+ const ctx = this.ctx;
262
+ if (!ctx || !v.buffer)
263
+ return 0;
264
+ const p = v.offset + (ctx.currentTime - v.startedAt) * v.rate * this.speed;
265
+ return v.loop ? p % v.buffer.duration : p;
266
+ }
267
+ speed = 1;
268
+ pausedAll = false;
269
+ /**
270
+ * Playback speed for everything this backend plays (sounds already playing change too), like a player's speed
271
+ * control: 2 plays twice as fast and an octave higher.
272
+ */
273
+ setSpeed(speed) {
274
+ const ctx = this.ctx;
275
+ for (const v of this.voices.values()) {
276
+ if (!v.source || !ctx)
277
+ continue;
278
+ // Keep the position continuous: restart the clock from here at the new rate.
279
+ v.offset = this.position(v);
280
+ v.startedAt = ctx.currentTime;
281
+ v.source.playbackRate.value = v.rate * speed;
282
+ }
283
+ this.speed = Math.max(0.05, speed);
284
+ }
285
+ /** Pause every voice where it is (resumeAll continues them from there). */
286
+ pauseAll() {
287
+ this.pausedAll = true;
288
+ for (const v of this.voices.values()) {
289
+ if (!v.source)
290
+ continue;
291
+ v.paused = this.position(v);
292
+ const src = v.source;
293
+ v.source = null;
294
+ try {
295
+ src.stop();
296
+ }
297
+ catch {
298
+ /* already stopped */
299
+ }
300
+ src.disconnect();
301
+ }
302
+ }
303
+ /** Continue every paused voice from where it was paused. */
304
+ resumeAll() {
305
+ this.pausedAll = false;
306
+ for (const [id, v] of [...this.voices]) {
307
+ if (v.paused === null || v.source)
308
+ continue;
309
+ if (!v.buffer) {
310
+ v.paused = null; // still loading: it starts when it arrives
311
+ continue;
312
+ }
313
+ if (!v.loop && v.paused >= v.buffer.duration - 0.005) {
314
+ this.voices.delete(id);
315
+ v.gain.disconnect();
316
+ continue;
317
+ }
318
+ this.startSource(id, v, v.paused);
319
+ }
320
+ }
321
+ /**
322
+ * A short grain of a sound at `offset` seconds into its file, for scrubbing a timeline: fades in and out over a few
323
+ * milliseconds so dragging sounds like a tape head rather than clicks.
324
+ */
325
+ scrub(assetId, offset, o = {}) {
326
+ const asset = this.doc.audio?.assets.find((a) => a.id === assetId);
327
+ const ctx = this.context();
328
+ if (!asset || !ctx || ctx.state !== "running")
329
+ return;
330
+ void this.load(asset).then((buffer) => {
331
+ if (!buffer || offset < 0 || offset >= buffer.duration)
332
+ return;
333
+ const dur = Math.min(o.duration ?? 0.09, buffer.duration - offset);
334
+ const g = ctx.createGain();
335
+ g.connect(this.busNode(ctx, o.bus ?? null));
336
+ const src = ctx.createBufferSource();
337
+ src.buffer = buffer;
338
+ src.playbackRate.value = (o.rate ?? 1) * this.speed;
339
+ src.connect(g);
340
+ const t = ctx.currentTime;
341
+ const v = o.volume ?? 1;
342
+ g.gain.setValueAtTime(0, t);
343
+ g.gain.linearRampToValueAtTime(v, t + 0.006);
344
+ g.gain.setValueAtTime(v, t + Math.max(0.007, dur - 0.012));
345
+ g.gain.linearRampToValueAtTime(0, t + dur);
346
+ src.onended = () => g.disconnect();
347
+ src.start(t, offset, dur + 0.01);
348
+ });
349
+ }
350
+ stop(id, fade, cmd) {
351
+ const v = this.voices.get(id);
352
+ if (!v)
353
+ return;
354
+ v.stopped = true;
355
+ this.voices.delete(id);
356
+ this.opts.onLog?.(`stop [${id}]${fade > 0 ? ` fade ${fade}s` : ""}`, cmd);
357
+ const ctx = this.ctx;
358
+ if (!ctx || !v.source) {
359
+ v.gain.disconnect();
360
+ return;
361
+ }
362
+ const t = ctx.currentTime;
363
+ v.gain.gain.cancelScheduledValues(t);
364
+ v.gain.gain.setValueAtTime(v.gain.gain.value, t);
365
+ if (fade > 0)
366
+ v.gain.gain.linearRampToValueAtTime(0, t + fade);
367
+ try {
368
+ v.source.stop(t + Math.max(0, fade));
369
+ }
370
+ catch {
371
+ /* already stopped */
372
+ }
373
+ }
374
+ /** Stop every voice (optionally fading). */
375
+ stopAll(fade = 0) {
376
+ for (const id of [...this.voices.keys()])
377
+ this.stop(id, fade);
378
+ }
379
+ /** Number of voices currently playing or loading. */
380
+ get activeVoices() {
381
+ return this.voices.size;
382
+ }
383
+ dispose() {
384
+ this.stopAll();
385
+ this.unbind?.();
386
+ if (!this.opts.context)
387
+ void this.ctx?.close();
388
+ this.ctx = null;
389
+ this.master = null;
390
+ this.buses.clear();
391
+ this.buffers.clear();
392
+ }
393
+ }
394
+ const round = (n) => Math.round(n * 100) / 100;
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Host bridge for embedding the player in a native WebView (Flutter, Android, iOS) or an iframe.
3
+ *
4
+ * Host → page: call `OpenBone.receive(json)` (or `OpenBone.setInput(...)` etc. directly) with a {@link BridgeCommand}.
5
+ * Page → host: JSON strings of {@link BridgeMessage}, posted to whichever channel exists:
6
+ * - `window.OpenBoneHost.postMessage(str)` Flutter `JavaScriptChannel` / Android `addJavascriptInterface`
7
+ * - `window.webkit.messageHandlers.openbone.postMessage(str)` iOS WKWebView
8
+ * - `window.parent.postMessage(obj, "*")` iframes (object, not string), when embedded
9
+ * - a `openbone-message` DOM event on `window` (detail = object), always
10
+ */
11
+ export declare const BRIDGE_VERSION = 1;
12
+ export type BridgeCommand = {
13
+ type: "setInput";
14
+ name: string;
15
+ value: boolean | number | string;
16
+ } | {
17
+ type: "fire";
18
+ name: string;
19
+ } | {
20
+ type: "play";
21
+ animation?: string;
22
+ loop?: boolean;
23
+ } | {
24
+ type: "pause";
25
+ } | {
26
+ type: "setSkin";
27
+ name: string | null;
28
+ } | {
29
+ type: "useStateMachine";
30
+ name?: string;
31
+ } | {
32
+ type: "getInputs";
33
+ };
34
+ export interface BridgeInputInfo {
35
+ name: string;
36
+ type: "bool" | "number" | "trigger" | "string";
37
+ value: boolean | number | string | null;
38
+ }
39
+ export type BridgeMessage = {
40
+ type: "ready";
41
+ animations: string[];
42
+ stateMachines: string[];
43
+ inputs: BridgeInputInfo[];
44
+ skins: string[];
45
+ width: number;
46
+ height: number;
47
+ } | {
48
+ type: "event";
49
+ name: string;
50
+ int?: number;
51
+ float?: number;
52
+ string?: string;
53
+ time?: number;
54
+ } | {
55
+ type: "stateChange";
56
+ layer: string;
57
+ from: string | null;
58
+ to: string;
59
+ } | {
60
+ type: "inputs";
61
+ inputs: BridgeInputInfo[];
62
+ } | {
63
+ type: "error";
64
+ message: string;
65
+ };
66
+ /** Wire format of a page → host message: the message plus a source tag and protocol version. */
67
+ export type BridgeEnvelope = BridgeMessage & {
68
+ source: "openbone";
69
+ v: number;
70
+ };
71
+ export declare function encodeMessage(m: BridgeMessage): string;
72
+ /** Parse a host message string (for hosts written in JS, and tests). Returns null for anything that is not ours. */
73
+ export declare function decodeMessage(s: string): BridgeEnvelope | null;
74
+ /** Validate a command from the host (a JSON string or an object). Throws with a readable message when it is wrong. */
75
+ export declare function parseCommand(input: string | unknown): BridgeCommand;
76
+ /** What the bridge needs from a player (structural, so tests can pass a fake). */
77
+ export interface BridgePlayer {
78
+ setInput(name: string, value: boolean | number | string): void;
79
+ fire(name: string): void;
80
+ play(): void;
81
+ pause(): void;
82
+ playAnimation(name: string, loop?: boolean): void;
83
+ setSkin(name: string | null): void;
84
+ useStateMachine?(name?: string): void;
85
+ inputs(): BridgeInputInfo[];
86
+ }
87
+ /** Run a validated command against a player. Returns a reply message for queries. */
88
+ export declare function applyCommand(p: BridgePlayer, c: BridgeCommand): BridgeMessage | null;
89
+ type PostTarget = {
90
+ postMessage(s: string): void;
91
+ };
92
+ interface HostWindow {
93
+ OpenBoneHost?: PostTarget;
94
+ webkit?: {
95
+ messageHandlers?: {
96
+ openbone?: PostTarget;
97
+ };
98
+ };
99
+ parent?: {
100
+ postMessage(m: unknown, origin: string): void;
101
+ } | null;
102
+ dispatchEvent?(e: Event): boolean;
103
+ }
104
+ /** Send a message to every host channel present on `w` (see the module comment). */
105
+ export declare function postToHost(m: BridgeMessage, w?: HostWindow): string;
106
+ export {};
package/dist/bridge.js ADDED
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Host bridge for embedding the player in a native WebView (Flutter, Android, iOS) or an iframe.
3
+ *
4
+ * Host → page: call `OpenBone.receive(json)` (or `OpenBone.setInput(...)` etc. directly) with a {@link BridgeCommand}.
5
+ * Page → host: JSON strings of {@link BridgeMessage}, posted to whichever channel exists:
6
+ * - `window.OpenBoneHost.postMessage(str)` Flutter `JavaScriptChannel` / Android `addJavascriptInterface`
7
+ * - `window.webkit.messageHandlers.openbone.postMessage(str)` iOS WKWebView
8
+ * - `window.parent.postMessage(obj, "*")` iframes (object, not string), when embedded
9
+ * - a `openbone-message` DOM event on `window` (detail = object), always
10
+ */
11
+ export const BRIDGE_VERSION = 1;
12
+ export function encodeMessage(m) {
13
+ return JSON.stringify({ source: "openbone", v: BRIDGE_VERSION, ...m });
14
+ }
15
+ /** Parse a host message string (for hosts written in JS, and tests). Returns null for anything that is not ours. */
16
+ export function decodeMessage(s) {
17
+ try {
18
+ const m = JSON.parse(s);
19
+ return m && m.source === "openbone" && typeof m.type === "string" ? m : null;
20
+ }
21
+ catch {
22
+ return null;
23
+ }
24
+ }
25
+ /** Validate a command from the host (a JSON string or an object). Throws with a readable message when it is wrong. */
26
+ export function parseCommand(input) {
27
+ const c = (typeof input === "string" ? JSON.parse(input) : input);
28
+ if (!c || typeof c !== "object" || typeof c.type !== "string")
29
+ throw new Error("OpenBone bridge: a command needs a string `type`");
30
+ const str = (k) => {
31
+ if (typeof c[k] !== "string" || !c[k])
32
+ throw new Error(`OpenBone bridge: "${c.type}" needs a string \`${k}\``);
33
+ return c[k];
34
+ };
35
+ switch (c.type) {
36
+ case "setInput": {
37
+ const v = c.value;
38
+ if (typeof v !== "boolean" && typeof v !== "string" && !(typeof v === "number" && Number.isFinite(v)))
39
+ throw new Error('OpenBone bridge: "setInput" needs a boolean, number or string `value`');
40
+ return { type: "setInput", name: str("name"), value: v };
41
+ }
42
+ case "fire":
43
+ return { type: "fire", name: str("name") };
44
+ case "play":
45
+ return {
46
+ type: "play",
47
+ ...(typeof c.animation === "string" ? { animation: c.animation } : {}),
48
+ ...(typeof c.loop === "boolean" ? { loop: c.loop } : {}),
49
+ };
50
+ case "pause":
51
+ case "getInputs":
52
+ return { type: c.type };
53
+ case "setSkin":
54
+ return { type: "setSkin", name: typeof c.name === "string" && c.name ? c.name : null };
55
+ case "useStateMachine":
56
+ return { type: "useStateMachine", ...(typeof c.name === "string" ? { name: c.name } : {}) };
57
+ default:
58
+ throw new Error(`OpenBone bridge: unknown command "${String(c.type)}"`);
59
+ }
60
+ }
61
+ /** Run a validated command against a player. Returns a reply message for queries. */
62
+ export function applyCommand(p, c) {
63
+ switch (c.type) {
64
+ case "setInput":
65
+ p.setInput(c.name, c.value);
66
+ return null;
67
+ case "fire":
68
+ p.fire(c.name);
69
+ return null;
70
+ case "play":
71
+ if (c.animation)
72
+ p.playAnimation(c.animation, c.loop ?? true);
73
+ p.play();
74
+ return null;
75
+ case "pause":
76
+ p.pause();
77
+ return null;
78
+ case "setSkin":
79
+ p.setSkin(c.name);
80
+ return null;
81
+ case "useStateMachine":
82
+ p.useStateMachine?.(c.name);
83
+ return null;
84
+ case "getInputs":
85
+ return { type: "inputs", inputs: p.inputs() };
86
+ }
87
+ }
88
+ /** Send a message to every host channel present on `w` (see the module comment). */
89
+ export function postToHost(m, w = globalThis) {
90
+ const s = encodeMessage(m);
91
+ try {
92
+ w.OpenBoneHost?.postMessage(s);
93
+ }
94
+ catch {
95
+ /* host channel gone */
96
+ }
97
+ try {
98
+ w.webkit?.messageHandlers?.openbone?.postMessage(s);
99
+ }
100
+ catch {
101
+ /* host channel gone */
102
+ }
103
+ if (w.parent && w.parent !== w)
104
+ w.parent.postMessage(JSON.parse(s), "*");
105
+ if (w.dispatchEvent && typeof CustomEvent !== "undefined")
106
+ w.dispatchEvent(new CustomEvent("openbone-message", { detail: JSON.parse(s) }));
107
+ return s;
108
+ }
@@ -0,0 +1,33 @@
1
+ export declare const BUNDLE_ENTRY: string;
2
+ /** Folder whose changes invalidate the bundle (player, runtime, renderers, core, scripting sources). */
3
+ export declare const BUNDLE_SOURCES: string;
4
+ export declare function quickJsWasmPath(): string;
5
+ /** Build the bundle and return its source. */
6
+ export declare function buildPlayerBundle(opts?: {
7
+ minify?: boolean;
8
+ }): Promise<string>;
9
+ export type WebBundleFormat = "iife" | "esm";
10
+ export interface WebBundleOptions {
11
+ /** "iife": classic `<script src>` exposing `window.OpenBone`; "esm": an ES module with named exports. */
12
+ format?: WebBundleFormat;
13
+ minify?: boolean;
14
+ /**
15
+ * Script sandbox: true inlines QuickJS (one file, +0.7 MB); "lazy" loads `openbone-scripts.js` + `quickjs.wasm`
16
+ * from next to the player only when an animation has scripts (see buildScriptsAddon); false leaves it out.
17
+ */
18
+ scripts?: boolean | "lazy";
19
+ }
20
+ /**
21
+ * Build the web player library (`<openbone-player>` + `OpenBone.Player`) for websites: classic script or ES module,
22
+ * minified or readable, with or without the script sandbox. Returns the source.
23
+ */
24
+ export declare function buildWebBundle(opts?: WebBundleOptions): Promise<string>;
25
+ /**
26
+ * `openbone-scripts.js`: the QuickJS sandbox add-on loaded by "lazy" web players (classic script, any page).
27
+ * Ship it with `quickjs.wasm` (quickJsWasmBytes) next to the player.
28
+ */
29
+ export declare function buildScriptsAddon(opts?: {
30
+ minify?: boolean;
31
+ }): Promise<string>;
32
+ /** The QuickJS .wasm the sandbox add-on fetches. */
33
+ export declare function quickJsWasmBytes(): Uint8Array;