@freedome/client 0.0.0-stage → 1.0.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.
@@ -0,0 +1,1622 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/testing.ts
21
+ var testing_exports = {};
22
+ __export(testing_exports, {
23
+ FakeDomeServer: () => FakeDomeServer,
24
+ createFakeTransport: () => createFakeTransport
25
+ });
26
+ module.exports = __toCommonJS(testing_exports);
27
+ var import_protocol3 = require("@freedome/protocol");
28
+
29
+ // src/endpoint.ts
30
+ var FreedomeEndpoint = class _FreedomeEndpoint {
31
+ constructor(baseUrl, opts = {}) {
32
+ this.opts = opts;
33
+ const u = new URL(String(baseUrl));
34
+ this.baseUrl = `${u.protocol}//${u.host}`;
35
+ }
36
+ opts;
37
+ baseUrl;
38
+ /** `host[:port]`, `http(s)://…` or a `freedome://pair?…` link (default port 8080 / 443). */
39
+ static parse(text) {
40
+ const t = text.trim();
41
+ if (t.startsWith("freedome://")) return PairingLink.parse(t).endpoint;
42
+ const u = new URL(t.includes("://") ? t : `http://${t}`);
43
+ if (u.protocol !== "http:" && u.protocol !== "https:")
44
+ throw new TypeError(`unsupported scheme "${u.protocol}"`);
45
+ if (!u.hostname) throw new TypeError("no host");
46
+ if (!u.port) u.port = u.protocol === "https:" ? "443" : "8080";
47
+ return new _FreedomeEndpoint(u);
48
+ }
49
+ get id() {
50
+ return this.opts.id;
51
+ }
52
+ get tlsFingerprint() {
53
+ return this.opts.tlsFingerprint;
54
+ }
55
+ get pairingCode() {
56
+ return this.opts.pairingCode;
57
+ }
58
+ /** `<base>/api/v1`. */
59
+ get apiBase() {
60
+ return `${this.baseUrl}/api/v1`;
61
+ }
62
+ /** WebSocket base (`ws://` / `wss://`). */
63
+ get wsBase() {
64
+ return this.baseUrl.replace(/^http/, "ws");
65
+ }
66
+ /** Key of the stored tokens / caches (server instance id once known). */
67
+ get storageKey() {
68
+ return this.opts.id ?? this.baseUrl;
69
+ }
70
+ withId(id) {
71
+ return new _FreedomeEndpoint(this.baseUrl, { ...this.opts, id });
72
+ }
73
+ toString() {
74
+ return `FreedomeEndpoint(${this.baseUrl}${this.opts.id ? `, id: ${this.opts.id}` : ""})`;
75
+ }
76
+ };
77
+ var HOST = /^(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*|\[[0-9A-Fa-f:.]+\]|[0-9A-Fa-f:]+:[0-9A-Fa-f:.]*)$/;
78
+ var PairingLink = class _PairingLink {
79
+ constructor(host, port = 8080, opts = {}) {
80
+ this.host = host;
81
+ this.port = port;
82
+ this.opts = opts;
83
+ }
84
+ host;
85
+ port;
86
+ opts;
87
+ static parse(text) {
88
+ let u;
89
+ try {
90
+ u = new URL(text.trim());
91
+ } catch {
92
+ throw new TypeError("not a pairing link");
93
+ }
94
+ if (u.protocol !== "freedome:" || u.hostname !== "pair" && u.host !== "pair")
95
+ throw new TypeError("not a freedome://pair link");
96
+ const q = u.searchParams;
97
+ const host = q.get("host");
98
+ if (!host || !HOST.test(host)) throw new TypeError("pairing link: bad or missing host");
99
+ const portText = q.get("port");
100
+ const port = portText === null ? 8080 : Number(portText);
101
+ if (!Number.isInteger(port) || port < 1 || port > 65535)
102
+ throw new TypeError("pairing link: bad port");
103
+ const id = q.get("id");
104
+ if (id !== null && !/^[A-Za-z0-9._-]{1,64}$/.test(id))
105
+ throw new TypeError("pairing link: bad id");
106
+ const code = q.get("code");
107
+ if (code !== null && !/^[0-9]{6}$/.test(code))
108
+ throw new TypeError("pairing link: code must be 6 digits");
109
+ const fp = q.get("fp");
110
+ if (fp !== null && !/^(?:[0-9A-Fa-f]{2}:?){8,32}$/.test(fp))
111
+ throw new TypeError("pairing link: fp must be \u2265 16 hex digits");
112
+ const name = q.get("name");
113
+ if (name !== null && name.length > 128) throw new TypeError("pairing link: name too long");
114
+ return new _PairingLink(host, port, {
115
+ ...id !== null ? { id } : {},
116
+ ...code !== null ? { code } : {},
117
+ ...fp !== null ? { fingerprint: fp } : {},
118
+ tls: q.get("tls") === "1" || fp !== null,
119
+ ...name !== null ? { name } : {}
120
+ });
121
+ }
122
+ static tryParse(text) {
123
+ try {
124
+ return _PairingLink.parse(text);
125
+ } catch {
126
+ return null;
127
+ }
128
+ }
129
+ get endpoint() {
130
+ const h = this.host.includes(":") && !this.host.startsWith("[") ? `[${this.host}]` : this.host;
131
+ return new FreedomeEndpoint(`${this.opts.tls ? "https" : "http"}://${h}:${this.port}`, {
132
+ ...this.opts.id ? { id: this.opts.id } : {},
133
+ ...this.opts.name ? { name: this.opts.name } : {},
134
+ ...this.opts.fingerprint ? { tlsFingerprint: this.opts.fingerprint } : {},
135
+ ...this.opts.code ? { pairingCode: this.opts.code } : {}
136
+ });
137
+ }
138
+ toString() {
139
+ const q = new URLSearchParams({ host: this.host, port: String(this.port) });
140
+ if (this.opts.id) q.set("id", this.opts.id);
141
+ if (this.opts.code) q.set("code", this.opts.code);
142
+ if (this.opts.fingerprint) q.set("fp", this.opts.fingerprint);
143
+ else if (this.opts.tls) q.set("tls", "1");
144
+ if (this.opts.name) q.set("name", this.opts.name);
145
+ return `freedome://pair?${q.toString()}`;
146
+ }
147
+ };
148
+
149
+ // src/errors.ts
150
+ var FreedomeError = class extends Error {
151
+ code;
152
+ problem;
153
+ constructor(message, opts = {}) {
154
+ super(message, opts.cause === void 0 ? void 0 : { cause: opts.cause });
155
+ this.name = new.target.name;
156
+ this.code = opts.code;
157
+ this.problem = opts.problem;
158
+ }
159
+ };
160
+ var NetworkError = class extends FreedomeError {
161
+ };
162
+
163
+ // src/ids.ts
164
+ var lastMs = 0;
165
+ var seq = 0;
166
+ function randomBytes(n) {
167
+ const b = new Uint8Array(n);
168
+ globalThis.crypto.getRandomValues(b);
169
+ return b;
170
+ }
171
+ function uuidV7(now = Date.now()) {
172
+ if (now === lastMs) seq = seq + 1 & 4095;
173
+ else {
174
+ lastMs = now;
175
+ seq = randomBytes(2).reduce((a, x) => a << 8 | x, 0) & 2047;
176
+ }
177
+ const b = randomBytes(16);
178
+ let t = now;
179
+ for (let i = 5; i >= 0; i--) {
180
+ b[i] = t % 256;
181
+ t = Math.floor(t / 256);
182
+ }
183
+ b[6] = 112 | seq >> 8 & 15;
184
+ b[7] = seq & 255;
185
+ b[8] = 128 | b[8] & 63;
186
+ const h = Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
187
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
188
+ }
189
+
190
+ // src/sha256.ts
191
+ var K = new Uint32Array([
192
+ 1116352408,
193
+ 1899447441,
194
+ 3049323471,
195
+ 3921009573,
196
+ 961987163,
197
+ 1508970993,
198
+ 2453635748,
199
+ 2870763221,
200
+ 3624381080,
201
+ 310598401,
202
+ 607225278,
203
+ 1426881987,
204
+ 1925078388,
205
+ 2162078206,
206
+ 2614888103,
207
+ 3248222580,
208
+ 3835390401,
209
+ 4022224774,
210
+ 264347078,
211
+ 604807628,
212
+ 770255983,
213
+ 1249150122,
214
+ 1555081692,
215
+ 1996064986,
216
+ 2554220882,
217
+ 2821834349,
218
+ 2952996808,
219
+ 3210313671,
220
+ 3336571891,
221
+ 3584528711,
222
+ 113926993,
223
+ 338241895,
224
+ 666307205,
225
+ 773529912,
226
+ 1294757372,
227
+ 1396182291,
228
+ 1695183700,
229
+ 1986661051,
230
+ 2177026350,
231
+ 2456956037,
232
+ 2730485921,
233
+ 2820302411,
234
+ 3259730800,
235
+ 3345764771,
236
+ 3516065817,
237
+ 3600352804,
238
+ 4094571909,
239
+ 275423344,
240
+ 430227734,
241
+ 506948616,
242
+ 659060556,
243
+ 883997877,
244
+ 958139571,
245
+ 1322822218,
246
+ 1537002063,
247
+ 1747873779,
248
+ 1955562222,
249
+ 2024104815,
250
+ 2227730452,
251
+ 2361852424,
252
+ 2428436474,
253
+ 2756734187,
254
+ 3204031479,
255
+ 3329325298
256
+ ]);
257
+ var Sha256 = class {
258
+ h = new Uint32Array([
259
+ 1779033703,
260
+ 3144134277,
261
+ 1013904242,
262
+ 2773480762,
263
+ 1359893119,
264
+ 2600822924,
265
+ 528734635,
266
+ 1541459225
267
+ ]);
268
+ buf = new Uint8Array(64);
269
+ w = new Uint32Array(64);
270
+ bufLen = 0;
271
+ total = 0;
272
+ finished = false;
273
+ update(data) {
274
+ if (this.finished) throw new Error("sha256: already finished");
275
+ let i = 0;
276
+ this.total += data.length;
277
+ if (this.bufLen) {
278
+ const n = Math.min(64 - this.bufLen, data.length);
279
+ this.buf.set(data.subarray(0, n), this.bufLen);
280
+ this.bufLen += n;
281
+ i = n;
282
+ if (this.bufLen === 64) {
283
+ this.block(this.buf, 0);
284
+ this.bufLen = 0;
285
+ }
286
+ }
287
+ for (; i + 64 <= data.length; i += 64) this.block(data, i);
288
+ if (i < data.length) {
289
+ this.buf.set(data.subarray(i), 0);
290
+ this.bufLen = data.length - i;
291
+ }
292
+ return this;
293
+ }
294
+ digest() {
295
+ if (!this.finished) {
296
+ const bits = this.total * 8;
297
+ const pad = new Uint8Array((this.bufLen < 56 ? 56 : 120) - this.bufLen + 8);
298
+ pad[0] = 128;
299
+ const dv2 = new DataView(pad.buffer);
300
+ dv2.setUint32(pad.length - 8, Math.floor(bits / 2 ** 32));
301
+ dv2.setUint32(pad.length - 4, bits >>> 0);
302
+ const t = this.total;
303
+ this.update(pad);
304
+ this.total = t;
305
+ this.finished = true;
306
+ }
307
+ const out = new Uint8Array(32);
308
+ const dv = new DataView(out.buffer);
309
+ for (let j = 0; j < 8; j++) dv.setUint32(j * 4, this.h[j]);
310
+ return out;
311
+ }
312
+ hex() {
313
+ return Array.from(this.digest(), (b) => b.toString(16).padStart(2, "0")).join("");
314
+ }
315
+ block(d, o) {
316
+ const w = this.w;
317
+ for (let j = 0; j < 16; j++)
318
+ w[j] = d[o + j * 4] << 24 | d[o + j * 4 + 1] << 16 | d[o + j * 4 + 2] << 8 | d[o + j * 4 + 3];
319
+ for (let j = 16; j < 64; j++) {
320
+ const a2 = w[j - 15];
321
+ const b2 = w[j - 2];
322
+ const s0 = (a2 >>> 7 | a2 << 25) ^ (a2 >>> 18 | a2 << 14) ^ a2 >>> 3;
323
+ const s1 = (b2 >>> 17 | b2 << 15) ^ (b2 >>> 19 | b2 << 13) ^ b2 >>> 10;
324
+ w[j] = w[j - 16] + s0 + w[j - 7] + s1 | 0;
325
+ }
326
+ let [a, b, c, dd, e, f, g, h] = this.h;
327
+ for (let j = 0; j < 64; j++) {
328
+ const S1 = (e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7);
329
+ const ch = e & f ^ ~e & g;
330
+ const t1 = h + S1 + ch + K[j] + w[j] | 0;
331
+ const S0 = (a >>> 2 | a << 30) ^ (a >>> 13 | a << 19) ^ (a >>> 22 | a << 10);
332
+ const maj = a & b ^ a & c ^ b & c;
333
+ const t2 = S0 + maj | 0;
334
+ h = g;
335
+ g = f;
336
+ f = e;
337
+ e = dd + t1 | 0;
338
+ dd = c;
339
+ c = b;
340
+ b = a;
341
+ a = t1 + t2 | 0;
342
+ }
343
+ const H = this.h;
344
+ H[0] = H[0] + a | 0;
345
+ H[1] = H[1] + b | 0;
346
+ H[2] = H[2] + c | 0;
347
+ H[3] = H[3] + dd | 0;
348
+ H[4] = H[4] + e | 0;
349
+ H[5] = H[5] + f | 0;
350
+ H[6] = H[6] + g | 0;
351
+ H[7] = H[7] + h | 0;
352
+ }
353
+ };
354
+ var sha256Hex = (data) => new Sha256().update(data).hex();
355
+
356
+ // src/testing/fake-audio.ts
357
+ var import_protocol = require("@freedome/protocol");
358
+
359
+ // src/transport.ts
360
+ var FreedomeResponse = class _FreedomeResponse {
361
+ constructor(status, headers = {}, body = new Uint8Array(0)) {
362
+ this.status = status;
363
+ this.headers = headers;
364
+ this.body = body;
365
+ }
366
+ status;
367
+ headers;
368
+ body;
369
+ get ok() {
370
+ return this.status >= 200 && this.status < 300;
371
+ }
372
+ get text() {
373
+ return new TextDecoder().decode(this.body);
374
+ }
375
+ /** Parsed JSON body (`undefined` when empty). */
376
+ get json() {
377
+ if (this.body.length === 0) return void 0;
378
+ return JSON.parse(this.text);
379
+ }
380
+ static json(status, value, headers = {}) {
381
+ return new _FreedomeResponse(
382
+ status,
383
+ { "content-type": "application/json", ...headers },
384
+ new TextEncoder().encode(JSON.stringify(value))
385
+ );
386
+ }
387
+ };
388
+
389
+ // src/testing/fake-audio.ts
390
+ var ENDED = /* @__PURE__ */ new Set(["finished", "stopped", "failed"]);
391
+ var FakeAudio = class {
392
+ constructor(publish, problem2) {
393
+ this.publish = publish;
394
+ this.problem = problem2;
395
+ this.zones.set("front", {
396
+ id: "front",
397
+ name: "Front",
398
+ speakers: ["s1", "s2"],
399
+ gainDb: 0,
400
+ delayMs: 0,
401
+ eq: [],
402
+ mute: false,
403
+ revision: 1
404
+ });
405
+ this.devices.set("spk-1", {
406
+ id: "spk-1",
407
+ kind: "speaker",
408
+ name: "Speaker 1",
409
+ state: { online: true, gainDb: 0, mute: false }
410
+ });
411
+ this.devices.set("qrd-1", {
412
+ id: "qrd-1",
413
+ kind: "qrd",
414
+ name: "QRD hub",
415
+ state: { online: true }
416
+ });
417
+ this.presets.set("calm-7", {
418
+ id: "calm-7",
419
+ kind: "session",
420
+ revision: 1,
421
+ title: { en: "Calm 7" },
422
+ document: {
423
+ format: "ananta-session",
424
+ formatVersion: "1.0.0",
425
+ id: "calm-7",
426
+ title: { en: "Calm 7" },
427
+ items: [{ programme: { id: "tone-432" } }]
428
+ },
429
+ updatedAt: (0, import_protocol.rfc3339Millis)()
430
+ });
431
+ }
432
+ publish;
433
+ problem;
434
+ state = {
435
+ venueId: "default",
436
+ mode: "combined",
437
+ masterGainDb: 0,
438
+ mute: false,
439
+ engines: { anantasound: { status: "up" }, anantadigital: { status: "up" } },
440
+ layoutRevision: 1,
441
+ revision: 1
442
+ };
443
+ layout = {
444
+ body: {
445
+ ambisonics: { order: 3 },
446
+ speakers: [
447
+ { id: "s1", position: { azimuth: -30, elevation: 0, distance: 5 } },
448
+ { id: "s2", position: { azimuth: 30, elevation: 0, distance: 5 } },
449
+ { id: "s3", position: { azimuth: 0, elevation: 90, distance: 5 } }
450
+ ]
451
+ },
452
+ revision: 1
453
+ };
454
+ zones = /* @__PURE__ */ new Map();
455
+ devices = /* @__PURE__ */ new Map();
456
+ presets = /* @__PURE__ */ new Map();
457
+ sessions = /* @__PURE__ */ new Map();
458
+ generator = { running: false };
459
+ /** Last position per source id. */
460
+ sources = /* @__PURE__ */ new Map();
461
+ /** Test hook: publishes `audio.levels` (`{meter id: dBFS}`) on `venues/{v}/audio/levels`. */
462
+ emitLevels(levels) {
463
+ this.publish("audio/levels", "audio.levels", { resource: { levels } });
464
+ }
465
+ /** Test hook: advances session [id] to [positionSec] (and optionally a new [status]); publishes the state. */
466
+ advanceSession(id, positionSec, status) {
467
+ const s = this.sessions.get(id);
468
+ if (!s) throw new Error(`fake: no audio session ${id}`);
469
+ s.position = positionSec;
470
+ if (status) {
471
+ s.status = status;
472
+ if (ENDED.has(status)) s.endedAt = (0, import_protocol.rfc3339Millis)();
473
+ }
474
+ this.publishSession(s);
475
+ return s;
476
+ }
477
+ bumpState() {
478
+ this.state = { ...this.state, revision: this.state.revision + 1 };
479
+ this.publish("audio", "audio.state", { resource: this.state, revision: this.state.revision });
480
+ }
481
+ publishZone(z) {
482
+ this.publish(`audio/zones/${z.id}`, "zone.state", { resource: z, revision: z.revision });
483
+ }
484
+ publishSession(s) {
485
+ this.publish(`audio/sessions/${s.id}`, "audioSession.state", { resource: s });
486
+ }
487
+ publishGenerator() {
488
+ this.publish("audio/generator", "generator.state", { resource: this.generator });
489
+ }
490
+ page(items) {
491
+ return FreedomeResponse.json(200, { items, nextCursor: null });
492
+ }
493
+ /** Serves audio operation [op]; undefined = not an audio operation. */
494
+ handle(op, p, body, h, q) {
495
+ const json = (s, v, hd = {}) => FreedomeResponse.json(s, v, hd);
496
+ const etag = (rev) => ({ etag: `"r${rev}"` });
497
+ const noContent = () => new FreedomeResponse(204);
498
+ switch (op) {
499
+ case "getAudio":
500
+ return json(200, { ...this.state, venueId: p.venueId });
501
+ case "patchAudio":
502
+ for (const k of ["mode", "masterGainDb", "mute"])
503
+ if (body?.[k] !== void 0) this.state[k] = body[k];
504
+ this.bumpState();
505
+ return json(200, { ...this.state, venueId: p.venueId });
506
+ case "getSpeakerLayout":
507
+ return json(200, this.layout.body, etag(this.layout.revision));
508
+ case "putSpeakerLayout": {
509
+ if (!h["if-match"]) return this.problem(428, "precondition-required", "If-Match required");
510
+ if (h["if-match"] !== `"r${this.layout.revision}"`)
511
+ return this.problem(412, "precondition-failed", `revision is ${this.layout.revision}`);
512
+ this.layout = { body, revision: this.layout.revision + 1 };
513
+ this.state.layoutRevision = this.layout.revision;
514
+ this.publish("audio/layout", "audio.layout", {
515
+ resource: body,
516
+ revision: this.layout.revision
517
+ });
518
+ this.bumpState();
519
+ return json(200, body, etag(this.layout.revision));
520
+ }
521
+ case "listAudioZones":
522
+ return this.page([...this.zones.values()]);
523
+ case "getAudioZone": {
524
+ const z = this.zones.get(p.zoneId);
525
+ return z ? json(200, z, etag(z.revision)) : this.problem(404, "not-found", "zone");
526
+ }
527
+ case "putAudioZone": {
528
+ const z = this.zones.get(p.zoneId);
529
+ if (!z) {
530
+ if (h["if-match"]) return this.problem(412, "precondition-failed", "zone does not exist");
531
+ const n2 = { id: p.zoneId, gainDb: 0, mute: false, ...body, revision: 1 };
532
+ this.zones.set(p.zoneId, n2);
533
+ this.publishZone(n2);
534
+ return json(201, n2, etag(1));
535
+ }
536
+ if (h["if-none-match"] === "*")
537
+ return this.problem(412, "precondition-failed", `zone ${p.zoneId} exists`);
538
+ if (h["if-match"] && h["if-match"] !== `"r${z.revision}"`)
539
+ return this.problem(412, "precondition-failed", `revision is ${z.revision}`);
540
+ const n = { id: p.zoneId, gainDb: 0, mute: false, ...body, revision: z.revision + 1 };
541
+ this.zones.set(p.zoneId, n);
542
+ this.publishZone(n);
543
+ return json(200, n, etag(n.revision));
544
+ }
545
+ case "patchAudioZone": {
546
+ const z = this.zones.get(p.zoneId);
547
+ if (!z) return this.problem(404, "not-found", "zone");
548
+ if (!body || !Object.keys(body).length)
549
+ return this.problem(422, "validation", "empty patch");
550
+ Object.assign(z, body, { revision: z.revision + 1 });
551
+ this.publish(`audio/zones/${z.id}`, "zone.state", {
552
+ patch: { ...body, revision: z.revision },
553
+ revision: z.revision
554
+ });
555
+ return json(200, z, etag(z.revision));
556
+ }
557
+ case "deleteAudioZone": {
558
+ const z = this.zones.get(p.zoneId);
559
+ if (!z) return this.problem(404, "not-found", "zone");
560
+ if (!h["if-match"]) return this.problem(428, "precondition-required", "If-Match required");
561
+ if (h["if-match"] !== `"r${z.revision}"`)
562
+ return this.problem(412, "precondition-failed", `revision is ${z.revision}`);
563
+ this.zones.delete(p.zoneId);
564
+ this.publish(`audio/zones/${z.id}`, "zone.deleted", { resource: { id: z.id } });
565
+ return noContent();
566
+ }
567
+ case "listAudioDevices":
568
+ return this.page([...this.devices.values()].filter((d) => !q.kind || d.kind === q.kind));
569
+ case "getAudioDevice": {
570
+ const d = this.devices.get(p.deviceId);
571
+ return d ? json(200, d) : this.problem(404, "not-found", "device");
572
+ }
573
+ case "patchAudioDevice": {
574
+ const d = this.devices.get(p.deviceId);
575
+ if (!d) return this.problem(404, "not-found", "device");
576
+ if (body?.name !== void 0) d.name = body.name;
577
+ if (body?.config !== void 0) d.config = { ...d.config ?? {}, ...body.config };
578
+ const st = {};
579
+ if (body?.gainDb !== void 0) st.gainDb = body.gainDb;
580
+ if (body?.mute !== void 0) st.mute = body.mute;
581
+ d.state = { ...d.state, ...st };
582
+ this.publish(`audio/devices/${d.id}`, "audioDevice.state", { resource: d });
583
+ return json(200, d);
584
+ }
585
+ case "testAudioDevice": {
586
+ const d = this.devices.get(p.deviceId);
587
+ if (!d) return this.problem(404, "not-found", "device");
588
+ return json(200, {
589
+ deviceId: d.id,
590
+ ok: d.state?.online !== false,
591
+ latencyMs: 4,
592
+ detail: `${body?.kind ?? "ping"} ok`
593
+ });
594
+ }
595
+ case "listAudioPresets":
596
+ return this.page(
597
+ [...this.presets.values()].filter((x) => !q.kind || x.kind === q.kind).map(({ document: _d, ...summary }) => summary)
598
+ );
599
+ case "getAudioPreset": {
600
+ const x = this.presets.get(p.presetId);
601
+ return x ? json(200, x, etag(x.revision)) : this.problem(404, "not-found", "preset");
602
+ }
603
+ case "putAudioPreset": {
604
+ const x = this.presets.get(p.presetId);
605
+ if (x && h["if-none-match"] === "*")
606
+ return this.problem(412, "precondition-failed", `preset ${p.presetId} exists`);
607
+ if (h["if-match"] && (!x || h["if-match"] !== `"r${x.revision}"`))
608
+ return this.problem(412, "precondition-failed", `revision is ${x?.revision ?? 0}`);
609
+ if (!body?.kind || !body?.document)
610
+ return this.problem(422, "validation", "kind and document are required");
611
+ const n = {
612
+ id: p.presetId,
613
+ kind: body.kind,
614
+ revision: (x?.revision ?? 0) + 1,
615
+ document: body.document,
616
+ ...body.document?.title ? { title: body.document.title } : {},
617
+ updatedAt: (0, import_protocol.rfc3339Millis)()
618
+ };
619
+ this.presets.set(p.presetId, n);
620
+ return json(x ? 200 : 201, n, etag(n.revision));
621
+ }
622
+ case "deleteAudioPreset": {
623
+ const x = this.presets.get(p.presetId);
624
+ if (!x) return this.problem(404, "not-found", "preset");
625
+ if (h["if-match"] && h["if-match"] !== `"r${x.revision}"`)
626
+ return this.problem(412, "precondition-failed", `revision is ${x.revision}`);
627
+ this.presets.delete(p.presetId);
628
+ return noContent();
629
+ }
630
+ case "listAudioSessions":
631
+ return this.page([...this.sessions.values()]);
632
+ case "startAudioSession": {
633
+ if (!this.presets.has(body?.presetId))
634
+ return this.problem(404, "not-found", `preset ${body?.presetId}`);
635
+ const s = {
636
+ id: uuidV7(),
637
+ venueId: p.venueId,
638
+ presetId: body.presetId,
639
+ status: "running",
640
+ engines: ["anantadigital"],
641
+ position: 0,
642
+ itemIndex: 0,
643
+ ...body.targets ? { targets: body.targets } : {},
644
+ startedAt: body.at ?? (0, import_protocol.rfc3339Millis)()
645
+ };
646
+ this.sessions.set(s.id, s);
647
+ this.publishSession(s);
648
+ return json(201, s, { location: `/api/v1/venues/${p.venueId}/audio/sessions/${s.id}` });
649
+ }
650
+ case "getAudioSession": {
651
+ const s = this.sessions.get(p.sessionId);
652
+ return s ? json(200, s) : this.problem(404, "not-found", "session");
653
+ }
654
+ case "stopAudioSession": {
655
+ const s = this.sessions.get(p.sessionId);
656
+ if (!s) return this.problem(404, "not-found", "session");
657
+ if (!ENDED.has(s.status)) {
658
+ s.status = "stopped";
659
+ s.endedAt = (0, import_protocol.rfc3339Millis)();
660
+ this.publishSession(s);
661
+ }
662
+ return noContent();
663
+ }
664
+ case "getGenerator":
665
+ return json(200, this.generator);
666
+ case "setGenerator":
667
+ if (!body?.signal) return this.problem(422, "validation", "signal is required");
668
+ this.generator = {
669
+ running: true,
670
+ settings: body,
671
+ startedAt: this.generator.running ? this.generator.startedAt : (0, import_protocol.rfc3339Millis)()
672
+ };
673
+ this.publishGenerator();
674
+ return json(200, this.generator);
675
+ case "stopGenerator":
676
+ this.generator = { running: false };
677
+ this.publishGenerator();
678
+ return noContent();
679
+ case "setSourcePosition":
680
+ if (typeof body?.azimuth !== "number" || typeof body?.elevation !== "number")
681
+ return this.problem(422, "validation", "azimuth and elevation are required");
682
+ this.sources.set(p.sourceId, body);
683
+ return noContent();
684
+ default:
685
+ return void 0;
686
+ }
687
+ }
688
+ };
689
+
690
+ // src/testing/fake-audio-reactive.ts
691
+ var import_protocol2 = require("@freedome/protocol");
692
+ var FakeAudioReactive = class {
693
+ constructor(publishVenue, publish, problem2) {
694
+ this.publishVenue = publishVenue;
695
+ this.publish = publish;
696
+ this.problem = problem2;
697
+ }
698
+ publishVenue;
699
+ publish;
700
+ problem;
701
+ analysis = { venueId: "default", enabled: false, status: "disabled", inputs: [] };
702
+ enabled = true;
703
+ activeSceneId = null;
704
+ intensity = 1;
705
+ scenes = /* @__PURE__ */ new Map();
706
+ textureSources = /* @__PURE__ */ new Map();
707
+ gateways = /* @__PURE__ */ new Map();
708
+ /** The driver takes `config` at run time (the media server's 422 on `/config` otherwise). */
709
+ runtimeSettings = true;
710
+ /** The Resolume machine answers. */
711
+ reachable = true;
712
+ /** Test hook: one running `resolume` gateway and the scene `vocal-aura` reading input `vocal`. */
713
+ seed() {
714
+ this.gateways.set("resolume", {
715
+ id: "resolume",
716
+ direction: "outbound",
717
+ protocol: "resolume",
718
+ vendor: "Resolume",
719
+ enabled: true,
720
+ status: "up",
721
+ revision: 1,
722
+ config: { host: "192.168.1.50", oscPort: 7e3, restPort: 8080, ws: true }
723
+ });
724
+ this.scenes.set("vocal-aura", {
725
+ id: "vocal-aura",
726
+ title: { en: "Vocal aura" },
727
+ revision: 1,
728
+ mappings: [],
729
+ updatedAt: (0, import_protocol2.rfc3339Millis)()
730
+ });
731
+ this.analysis = { ...this.analysis, inputs: [{ id: "vocal" }] };
732
+ }
733
+ /** Test hook: publishes an analysis frame of [inputId]. */
734
+ publishFrame(inputId, frame = {}) {
735
+ this.publishVenue(`audio/analysis/${inputId}`, "audio.analysis", {
736
+ resource: { inputId, ...frame }
737
+ });
738
+ }
739
+ /** Test hook: publishes a detected attack of [inputId]. */
740
+ publishOnset(inputId, onset = {}) {
741
+ this.publishVenue(`audio/onsets/${inputId}`, "audio.onset", {
742
+ resource: { inputId, ...onset }
743
+ });
744
+ }
745
+ /** Test hook: adds or changes a sender and publishes the change. */
746
+ setTextureSource(s) {
747
+ this.textureSources.set(s.id, s);
748
+ this.publishVenue(`texture-sources/${s.id}`, "textureSource.state", { resource: s });
749
+ }
750
+ state() {
751
+ return {
752
+ venueId: "default",
753
+ enabled: this.enabled,
754
+ status: this.enabled ? "running" : "disabled",
755
+ activeSceneId: this.activeSceneId,
756
+ intensity: this.intensity
757
+ };
758
+ }
759
+ publishState() {
760
+ this.publishVenue("audio/reactive", "audioReactive.state", { resource: this.state() });
761
+ }
762
+ /** Serves operation [op]; undefined = not one of these. */
763
+ handle(op, p, body, h) {
764
+ const json = (s, v, hd = {}) => FreedomeResponse.json(s, v, hd);
765
+ const etag = (rev) => ({ etag: `"r${rev}"` });
766
+ const page = (items) => json(200, { items, nextCursor: null });
767
+ switch (op) {
768
+ case "getAudioAnalysis":
769
+ return json(200, this.analysis);
770
+ case "setAudioAnalysis":
771
+ this.analysis = {
772
+ ...this.analysis,
773
+ enabled: body.enabled,
774
+ status: body.enabled ? "running" : "disabled",
775
+ inputs: body.inputs ?? []
776
+ };
777
+ this.publishVenue("audio/analysis", "audioAnalysis.state", { resource: this.analysis });
778
+ return json(200, this.analysis);
779
+ case "getAudioReactive":
780
+ return json(200, this.state());
781
+ case "patchAudioReactive": {
782
+ if (typeof body.activeSceneId === "string" && !this.scenes.has(body.activeSceneId))
783
+ return this.problem(422, "validation-failed", `no scene ${body.activeSceneId}`);
784
+ if ("activeSceneId" in body) this.activeSceneId = body.activeSceneId;
785
+ if (typeof body.enabled === "boolean") this.enabled = body.enabled;
786
+ if (typeof body.intensity === "number") this.intensity = body.intensity;
787
+ this.publishState();
788
+ return json(200, this.state());
789
+ }
790
+ case "listAudioReactiveScenes":
791
+ return page([...this.scenes.values()]);
792
+ case "getAudioReactiveScene": {
793
+ const s = this.scenes.get(p.sceneId);
794
+ return s ? json(200, s, etag(s.revision)) : this.problem(404, "not-found", "scene");
795
+ }
796
+ case "putAudioReactiveScene": {
797
+ const cur = this.scenes.get(p.sceneId);
798
+ if (h["if-none-match"] === "*" && cur)
799
+ return this.problem(412, "precondition-failed", "the scene exists");
800
+ if (h["if-match"] && h["if-match"] !== `"r${cur?.revision}"`)
801
+ return this.problem(412, "precondition-failed", `revision is ${cur?.revision}`);
802
+ const s = {
803
+ ...body,
804
+ id: p.sceneId,
805
+ revision: (cur?.revision ?? 0) + 1,
806
+ updatedAt: (0, import_protocol2.rfc3339Millis)()
807
+ };
808
+ this.scenes.set(p.sceneId, s);
809
+ this.publishVenue("audio/reactive/scenes", "audioReactiveScene.updated", { resource: s });
810
+ return json(cur ? 200 : 201, s, etag(s.revision));
811
+ }
812
+ case "deleteAudioReactiveScene": {
813
+ const s = this.scenes.get(p.sceneId);
814
+ if (!s) return this.problem(404, "not-found", "scene");
815
+ if (h["if-match"] !== `"r${s.revision}"`)
816
+ return this.problem(412, "precondition-failed", `revision is ${s.revision}`);
817
+ if (this.activeSceneId === p.sceneId)
818
+ return this.problem(409, "conflict", "the scene is active");
819
+ this.scenes.delete(p.sceneId);
820
+ return new FreedomeResponse(204);
821
+ }
822
+ case "listTextureSources":
823
+ return page([...this.textureSources.values()]);
824
+ case "listGateways":
825
+ return page([...this.gateways.values()]);
826
+ case "getGateway": {
827
+ const g = this.gateways.get(p.gatewayId);
828
+ return g ? json(200, g, etag(g.revision)) : this.problem(404, "not-found", "gateway");
829
+ }
830
+ case "patchGateway": {
831
+ const g = this.gateways.get(p.gatewayId);
832
+ if (!g) return this.problem(404, "not-found", "gateway");
833
+ if (h["if-match"] && h["if-match"] !== `"r${g.revision}"`)
834
+ return this.problem(412, "precondition-failed", `revision is ${g.revision}`);
835
+ if (body.config && !this.runtimeSettings)
836
+ return this.problem(422, "validation-failed", "config is not a run-time setting");
837
+ const enabled = body.enabled ?? g.enabled;
838
+ const next = {
839
+ ...g,
840
+ enabled,
841
+ status: enabled ? "up" : "disabled",
842
+ config: { ...g.config, ...body.config },
843
+ revision: g.revision + 1
844
+ };
845
+ this.gateways.set(g.id, next);
846
+ this.publish(`gateways/${g.id}`, "gateway.state", { resource: next });
847
+ return json(200, next, etag(next.revision));
848
+ }
849
+ case "testGateway": {
850
+ const g = this.gateways.get(p.gatewayId);
851
+ if (!g) return this.problem(404, "not-found", "gateway");
852
+ return json(200, {
853
+ ok: g.enabled && this.reachable,
854
+ ...g.enabled && this.reachable ? { latencyMs: 3, remoteVersion: "7.22.0" } : {}
855
+ });
856
+ }
857
+ default:
858
+ return void 0;
859
+ }
860
+ }
861
+ };
862
+
863
+ // src/testing.ts
864
+ var ROLE_SCOPES = {
865
+ guest: ["info:read", "events:subscribe", "playback:read", "content:read"],
866
+ operator: [
867
+ "info:read",
868
+ "events:subscribe",
869
+ "playback:read",
870
+ "content:read",
871
+ "playback:control",
872
+ "apps:publish",
873
+ "content:write",
874
+ "audio:control",
875
+ "displays:control"
876
+ ],
877
+ admin: [
878
+ "info:read",
879
+ "events:subscribe",
880
+ "playback:read",
881
+ "content:read",
882
+ "playback:control",
883
+ "apps:publish",
884
+ "content:write",
885
+ "audio:control",
886
+ "displays:control",
887
+ "calibration:run",
888
+ "audio:calibrate",
889
+ "venues:write",
890
+ "gateways:manage",
891
+ "system:read",
892
+ "users:manage",
893
+ "keys:manage"
894
+ ]
895
+ };
896
+ var problem = (status, code, detail, extra = {}) => FreedomeResponse.json(
897
+ status,
898
+ {
899
+ type: `https://freedome.nativemind.us/problems/${code}`,
900
+ title: code,
901
+ status,
902
+ code,
903
+ detail,
904
+ ...extra
905
+ },
906
+ { "content-type": "application/problem+json" }
907
+ );
908
+ var FakeDomeServer = class {
909
+ endpoint = new FreedomeEndpoint("http://fake-dome.local:8080");
910
+ /** Every REST request received (WS calls included as operationId-only records). */
911
+ requests = [];
912
+ instanceId = uuidV7();
913
+ /** Users (password = username). */
914
+ users = /* @__PURE__ */ new Map([
915
+ ["admin", "admin"],
916
+ ["operator", "operator"]
917
+ ]);
918
+ /** Accepted API keys → role. */
919
+ apiKeys = /* @__PURE__ */ new Map();
920
+ networkDown = false;
921
+ realtimeAvailable = true;
922
+ accessTtlSec = 900;
923
+ seq = 0;
924
+ history = [];
925
+ sessions = /* @__PURE__ */ new Map();
926
+ refreshTokens = /* @__PURE__ */ new Map();
927
+ failures = /* @__PURE__ */ new Map();
928
+ sockets = /* @__PURE__ */ new Set();
929
+ venues = /* @__PURE__ */ new Map();
930
+ activeVenue = "";
931
+ shows = /* @__PURE__ */ new Map();
932
+ assets = /* @__PURE__ */ new Map();
933
+ assetBytes = /* @__PURE__ */ new Map();
934
+ uploads = /* @__PURE__ */ new Map();
935
+ jobs = /* @__PURE__ */ new Map();
936
+ player = {
937
+ id: "main",
938
+ status: "idle",
939
+ position: 0,
940
+ rate: 1,
941
+ volume: 1,
942
+ opacity: 1,
943
+ loop: false,
944
+ revision: 0
945
+ };
946
+ output = { brightness: 1, volume: 1, blackout: false, rotation: 0, lighting: false };
947
+ /** Live app payloads per app (cleared by `clearAppPayloads`). */
948
+ appPayloads = /* @__PURE__ */ new Map();
949
+ /** Pairing requests by id. */
950
+ pairings = /* @__PURE__ */ new Map();
951
+ /** Approve every pairing request at once (role = requested role or operator). */
952
+ autoApprovePairings = false;
953
+ /** Calibration jobs by id. */
954
+ calibrationJobs = /* @__PURE__ */ new Map();
955
+ /** Audio model + hooks (`emitLevels`, `advanceSession`). */
956
+ audio = new FakeAudio(
957
+ (t, kind, data) => {
958
+ for (const v of /* @__PURE__ */ new Set(["default", this.activeVenue]))
959
+ this.publish(`venues/${v}/${t}`, kind, data);
960
+ },
961
+ (status, code, detail) => problem(status, code, detail)
962
+ );
963
+ /** Live analysis, AudioReactive scenes, texture sources and gateways (`seed`, `publishFrame`). */
964
+ audioReactive = new FakeAudioReactive(
965
+ (t, kind, data) => {
966
+ for (const v of /* @__PURE__ */ new Set(["default", this.activeVenue]))
967
+ this.publish(`venues/${v}/${t}`, kind, data);
968
+ },
969
+ (t, kind, data) => this.publish(t, kind, data),
970
+ (status, code, detail) => problem(status, code, detail)
971
+ );
972
+ constructor() {
973
+ const id = "0192f3a4-5b6c-7d8e-9f01-0000000000d4";
974
+ this.addVenue({
975
+ meta: { id, title: { en: "Fake venue" } },
976
+ dome: { mode: "classical", shape: "hemisphere", radius: 5 },
977
+ displays: [
978
+ {
979
+ id: "p1",
980
+ type: "projector",
981
+ resolution: [1920, 1080],
982
+ output: { host: "node-1", connector: "HDMI-1" }
983
+ }
984
+ ]
985
+ });
986
+ this.activeVenue = id;
987
+ }
988
+ addVenue(body) {
989
+ this.venues.set(body.meta.id, { body, revision: 1 });
990
+ if (!this.activeVenue) this.activeVenue = body.meta.id;
991
+ }
992
+ addShow(body) {
993
+ this.shows.set(body.meta.id, { body, revision: 1 });
994
+ }
995
+ /** The next call of [operationId] answers [status] ([times] times). */
996
+ failNext(operationId, status = 503, times = 1) {
997
+ this.failures.set(operationId, { status, times });
998
+ }
999
+ /** Closes every realtime session (the client reconnects with resume). */
1000
+ dropRealtime(code = 1006) {
1001
+ for (const s of [...this.sockets]) s.serverClose(code, "dropped");
1002
+ }
1003
+ /** Simulates a server restart: new instance id, seq space restarts, sessions survive (persistent tokens). */
1004
+ restart() {
1005
+ this.instanceId = uuidV7();
1006
+ this.seq = 0;
1007
+ this.history.length = 0;
1008
+ this.dropRealtime(1012);
1009
+ }
1010
+ /** Approves (or denies) pairing [pairingId] as an administrator would on the dome; returns the pairing. */
1011
+ approvePairing(pairingId, o = {}) {
1012
+ const x = this.pairings.get(pairingId);
1013
+ if (!x) throw new Error(`fake: no pairing ${pairingId}`);
1014
+ if (x.status !== "pending") return x;
1015
+ if (o.approve === false) x.status = "denied";
1016
+ else {
1017
+ const role = o.role ?? x.requestedRole ?? "operator";
1018
+ x.status = "approved";
1019
+ x.role = role;
1020
+ x.tokens = this.issue(x.deviceName, role);
1021
+ }
1022
+ return x;
1023
+ }
1024
+ /** Invalidates every access token (refresh tokens stay valid). */
1025
+ expireTokens() {
1026
+ this.sessions.clear();
1027
+ }
1028
+ /** Publishes an event on [topic]. */
1029
+ publish(topic, kind, data) {
1030
+ const e = {
1031
+ type: "event",
1032
+ id: uuidV7(),
1033
+ ts: (0, import_protocol3.rfc3339Millis)(),
1034
+ topic,
1035
+ data: { seq: ++this.seq, kind, ...data }
1036
+ };
1037
+ this.history.push(e);
1038
+ if (this.history.length > 1e3) this.history.shift();
1039
+ for (const s of this.sockets) s.deliver(e);
1040
+ }
1041
+ get transports() {
1042
+ const connector = async (_e, path, protocols) => {
1043
+ if (this.networkDown || !this.realtimeAvailable)
1044
+ throw new NetworkError("fake: realtime unavailable");
1045
+ if (path !== "/api/v1/ws" || !protocols.includes("freedome.v1"))
1046
+ throw new NetworkError(`fake: no socket at ${path}`);
1047
+ const s = new FakeSocketSession(this);
1048
+ this.sockets.add(s);
1049
+ return s.client;
1050
+ };
1051
+ return { rest: () => new FakeTransport(this), sockets: connector };
1052
+ }
1053
+ /** @internal */
1054
+ forget(s) {
1055
+ this.sockets.delete(s);
1056
+ }
1057
+ /** @internal Events after [since] matching any filter. */
1058
+ replay(since) {
1059
+ return this.history.filter((e) => e.data.seq > since);
1060
+ }
1061
+ /** @internal */
1062
+ get lastSeq() {
1063
+ return this.seq;
1064
+ }
1065
+ /** @internal Bearer → session. */
1066
+ principal(auth) {
1067
+ if (!auth?.startsWith("Bearer ")) return void 0;
1068
+ const t = auth.slice(7);
1069
+ const role = this.apiKeys.get(t);
1070
+ if (role) return { token: t, refresh: "", user: "api-key", role };
1071
+ return this.sessions.get(t);
1072
+ }
1073
+ issue(user, role) {
1074
+ const s = { token: `at_${uuidV7()}`, refresh: `rt_${uuidV7()}`, user, role };
1075
+ this.sessions.set(s.token, s);
1076
+ this.refreshTokens.set(s.refresh, s);
1077
+ return {
1078
+ accessToken: s.token,
1079
+ tokenType: "Bearer",
1080
+ expiresIn: this.accessTtlSec,
1081
+ refreshToken: s.refresh,
1082
+ scopes: ROLE_SCOPES[role] ?? [],
1083
+ principal: { kind: "user", subject: user, name: user, role, scopes: ROLE_SCOPES[role] ?? [] }
1084
+ };
1085
+ }
1086
+ venueId(v) {
1087
+ return v === "default" ? this.activeVenue : v;
1088
+ }
1089
+ etag(rev) {
1090
+ return { etag: `"r${rev}"` };
1091
+ }
1092
+ publishPlayer() {
1093
+ this.player = { ...this.player, revision: this.player.revision + 1 };
1094
+ for (const v of ["default", this.activeVenue])
1095
+ this.publish(`venues/${v}/players/main`, "player.state", {
1096
+ resource: this.player,
1097
+ revision: this.player.revision
1098
+ });
1099
+ }
1100
+ /** Handles one request (REST or a WS `call`). */
1101
+ async handle(r) {
1102
+ this.requests.push(r);
1103
+ if (this.networkDown) throw new NetworkError("fake: network down");
1104
+ let op;
1105
+ let p = {};
1106
+ for (const o of Object.values(import_protocol3.Operations)) {
1107
+ const m = (0, import_protocol3.matchOperation)(o, r.method, r.path);
1108
+ if (m) {
1109
+ op = o;
1110
+ p = m;
1111
+ break;
1112
+ }
1113
+ }
1114
+ if (!op) return problem(404, "not-found", `no route ${r.method} ${r.path}`);
1115
+ const f = this.failures.get(op.id);
1116
+ if (f) {
1117
+ if (--f.times <= 0) this.failures.delete(op.id);
1118
+ return problem(
1119
+ f.status,
1120
+ f.status === 429 ? "rate-limited" : "internal",
1121
+ `injected ${f.status}`,
1122
+ {}
1123
+ );
1124
+ }
1125
+ const who = this.principal(r.headers.authorization);
1126
+ if (op.scope !== "anon") {
1127
+ if (!who) return problem(401, "unauthenticated", "sign in first");
1128
+ if (op.scope !== "any" && !(ROLE_SCOPES[who.role] ?? []).includes(op.scope))
1129
+ return problem(403, "forbidden", `needs ${op.scope}`);
1130
+ }
1131
+ const body = r.body?.length && (r.headers["content-type"] ?? "").includes("json") ? JSON.parse(new TextDecoder().decode(r.body)) : void 0;
1132
+ const json = (s, v, h = {}) => FreedomeResponse.json(s, v, h);
1133
+ switch (op.id) {
1134
+ case "getInfo":
1135
+ return json(200, {
1136
+ name: "Fake dome",
1137
+ instanceId: this.instanceId,
1138
+ apiVersions: ["v1"],
1139
+ version: "1.0.0-rc.1",
1140
+ capabilities: { realtime: ["ws"], audio: true },
1141
+ transports: { ws: true, graphql: false, socketIo: false }
1142
+ });
1143
+ case "createSession": {
1144
+ if (this.users.get(body?.username) !== body?.password)
1145
+ return problem(401, "unauthenticated", "wrong username or password");
1146
+ return json(
1147
+ 201,
1148
+ this.issue(body.username, body.username === "admin" ? "admin" : "operator")
1149
+ );
1150
+ }
1151
+ case "refreshSession": {
1152
+ const s = this.refreshTokens.get(body?.refreshToken);
1153
+ if (!s) return problem(401, "unauthenticated", "refresh token invalid");
1154
+ this.refreshTokens.delete(body.refreshToken);
1155
+ return json(200, this.issue(s.user, s.role));
1156
+ }
1157
+ case "deleteSession":
1158
+ if (who) this.sessions.delete(who.token);
1159
+ return new FreedomeResponse(204);
1160
+ case "getMe":
1161
+ return json(200, {
1162
+ kind: who.user === "api-key" ? "apiKey" : "user",
1163
+ subject: who.user,
1164
+ name: who.user,
1165
+ role: who.role,
1166
+ scopes: ROLE_SCOPES[who.role] ?? []
1167
+ });
1168
+ case "listEvents":
1169
+ return json(200, { items: [], nextCursor: null, lastSeq: this.seq });
1170
+ case "listVenues":
1171
+ return json(200, {
1172
+ items: [...this.venues.entries()].map(([id, v]) => ({
1173
+ id,
1174
+ revision: v.revision,
1175
+ ...v.body
1176
+ })),
1177
+ nextCursor: null
1178
+ });
1179
+ case "getVenue": {
1180
+ const id = this.venueId(p.venueId);
1181
+ const v = this.venues.get(id);
1182
+ if (!v) return problem(404, "not-found", `venue ${id}`);
1183
+ return json(200, { id, revision: v.revision, ...v.body }, this.etag(v.revision));
1184
+ }
1185
+ case "putVenue": {
1186
+ const id = this.venueId(p.venueId);
1187
+ const v = this.venues.get(id);
1188
+ if (!v) {
1189
+ if (r.headers["if-none-match"] !== "*")
1190
+ return problem(428, "precondition-required", "create needs If-None-Match: *");
1191
+ this.venues.set(id, { body, revision: 1 });
1192
+ return json(201, { id, revision: 1, ...body }, this.etag(1));
1193
+ }
1194
+ if (r.headers["if-none-match"] === "*")
1195
+ return problem(412, "precondition-failed", `venue ${id} exists`);
1196
+ if (!r.headers["if-match"])
1197
+ return problem(428, "precondition-required", "If-Match required");
1198
+ if (r.headers["if-match"] !== `"r${v.revision}"`)
1199
+ return problem(412, "precondition-failed", `revision is ${v.revision}`);
1200
+ v.body = body;
1201
+ v.revision++;
1202
+ this.publish(`venues/${id}`, "venue.updated", {
1203
+ resource: { id, revision: v.revision, ...body },
1204
+ revision: v.revision
1205
+ });
1206
+ return json(200, { id, revision: v.revision, ...body }, this.etag(v.revision));
1207
+ }
1208
+ case "getPlayer":
1209
+ return json(200, this.player);
1210
+ case "play":
1211
+ this.player = {
1212
+ ...this.player,
1213
+ status: "playing",
1214
+ ...body?.showId ? { showId: body.showId } : {},
1215
+ ...body?.assetId ? { assetId: body.assetId } : {},
1216
+ position: body?.position ?? 0
1217
+ };
1218
+ this.publishPlayer();
1219
+ return json(200, this.player);
1220
+ case "pause":
1221
+ case "resume":
1222
+ case "stop":
1223
+ case "next":
1224
+ case "previous":
1225
+ this.player = {
1226
+ ...this.player,
1227
+ status: { pause: "paused", resume: "playing", stop: "stopped" }[op.id] ?? this.player.status
1228
+ };
1229
+ this.publishPlayer();
1230
+ return json(200, this.player);
1231
+ case "seek":
1232
+ this.player = { ...this.player, position: body?.position ?? 0 };
1233
+ this.publishPlayer();
1234
+ return json(200, this.player);
1235
+ case "patchPlayer":
1236
+ this.player = { ...this.player, ...body };
1237
+ this.publishPlayer();
1238
+ return json(200, this.player);
1239
+ case "getOutput":
1240
+ return json(200, this.output);
1241
+ case "patchOutput":
1242
+ this.output = { ...this.output, ...body };
1243
+ this.publish("venues/default/output", "output.changed", { resource: this.output });
1244
+ return json(200, this.output);
1245
+ case "publishAppPayload": {
1246
+ this.publish(`apps/${p.app}`, "app.payload", { resource: { app: p.app, ...body } });
1247
+ const created = {
1248
+ id: uuidV7(),
1249
+ app: p.app,
1250
+ ...body,
1251
+ expiresAt: (0, import_protocol3.rfc3339Millis)(new Date(Date.now() + (body?.ttlSec ?? 3600) * 1e3))
1252
+ };
1253
+ this.appPayloads.set(p.app, [...this.appPayloads.get(p.app) ?? [], created]);
1254
+ return json(201, created);
1255
+ }
1256
+ case "clearAppPayloads":
1257
+ this.appPayloads.delete(p.app);
1258
+ this.publish(`apps/${p.app}`, "app.cleared", { resource: { app: p.app } });
1259
+ return new FreedomeResponse(204);
1260
+ case "createPairing": {
1261
+ if (!body?.app || !body?.deviceName)
1262
+ return problem(422, "validation", "app and deviceName are required");
1263
+ const id = uuidV7();
1264
+ const code = String(1e5 + Math.floor(Math.random() * 9e5));
1265
+ const x = {
1266
+ pairingId: id,
1267
+ status: "pending",
1268
+ code,
1269
+ qr: `freedome://pair?host=fake-dome.local&code=${code}`,
1270
+ app: body.app,
1271
+ deviceName: body.deviceName,
1272
+ ...body.requestedRole ? { requestedRole: body.requestedRole } : {},
1273
+ expiresAt: (0, import_protocol3.rfc3339Millis)(new Date(Date.now() + 3e5))
1274
+ };
1275
+ this.pairings.set(id, x);
1276
+ if (this.autoApprovePairings) this.approvePairing(id);
1277
+ const { requestedRole: _r, ...out } = this.pairings.get(id);
1278
+ return json(201, out);
1279
+ }
1280
+ case "getPairing": {
1281
+ const x = this.pairings.get(p.pairingId);
1282
+ if (!x) return problem(404, "not-found", "pairing");
1283
+ const { requestedRole: _r, ...out } = x;
1284
+ return json(200, out);
1285
+ }
1286
+ case "listPairings":
1287
+ return json(200, {
1288
+ items: [...this.pairings.values()].map(({ tokens: _t, requestedRole: _r, ...x }) => x),
1289
+ nextCursor: null
1290
+ });
1291
+ case "approvePairing": {
1292
+ if (!this.pairings.has(p.pairingId)) return problem(404, "not-found", "pairing");
1293
+ const {
1294
+ tokens: _t,
1295
+ requestedRole: _r,
1296
+ ...x
1297
+ } = this.approvePairing(p.pairingId, {
1298
+ approve: body?.approve !== false,
1299
+ ...body?.role ? { role: body.role } : {}
1300
+ });
1301
+ return json(200, x);
1302
+ }
1303
+ case "startCalibrationJob": {
1304
+ const id = uuidV7();
1305
+ const now = (0, import_protocol3.rfc3339Millis)();
1306
+ const j = {
1307
+ id,
1308
+ venueId: p.venueId,
1309
+ kind: body?.kind,
1310
+ status: "running",
1311
+ progress: 0,
1312
+ ...body?.speakers ? { speakers: body.speakers } : {},
1313
+ ...body?.displays ? { displays: body.displays } : {},
1314
+ ...body?.options ? { options: body.options } : {},
1315
+ result: null,
1316
+ createdAt: now,
1317
+ updatedAt: now
1318
+ };
1319
+ this.calibrationJobs.set(id, j);
1320
+ return json(202, j, { location: `/api/v1/venues/${p.venueId}/calibration/jobs/${id}` });
1321
+ }
1322
+ case "getCalibrationJob": {
1323
+ const j = this.calibrationJobs.get(p.jobId);
1324
+ return j ? json(200, j) : problem(404, "not-found", "calibration job");
1325
+ }
1326
+ case "listShows":
1327
+ return json(200, {
1328
+ items: [...this.shows.entries()].map(([id, s]) => ({
1329
+ id,
1330
+ revision: s.revision,
1331
+ meta: s.body.meta
1332
+ })),
1333
+ nextCursor: null
1334
+ });
1335
+ case "getShow": {
1336
+ const s = this.shows.get(p.showId);
1337
+ if (!s) return problem(404, "not-found", "show");
1338
+ return json(
1339
+ 200,
1340
+ { id: p.showId, revision: s.revision, status: "ready", ...s.body },
1341
+ this.etag(s.revision)
1342
+ );
1343
+ }
1344
+ case "putShow": {
1345
+ const id = p.showId;
1346
+ const s = this.shows.get(id);
1347
+ if (!s) {
1348
+ if (r.headers["if-none-match"] !== "*")
1349
+ return problem(428, "precondition-required", "create needs If-None-Match: *");
1350
+ this.shows.set(id, { body, revision: 1 });
1351
+ return json(201, { id, revision: 1, status: "ready", ...body }, this.etag(1));
1352
+ }
1353
+ if (r.headers["if-none-match"] === "*")
1354
+ return problem(412, "precondition-failed", `show ${id} exists`);
1355
+ if (r.headers["if-match"] !== `"r${s.revision}"`)
1356
+ return problem(412, "precondition-failed", `revision is ${s.revision}`);
1357
+ s.body = body;
1358
+ s.revision++;
1359
+ this.publish(`shows/${id}`, "show.updated", {
1360
+ resource: { id, revision: s.revision, ...body },
1361
+ revision: s.revision
1362
+ });
1363
+ return json(
1364
+ 200,
1365
+ { id, revision: s.revision, status: "ready", ...body },
1366
+ this.etag(s.revision)
1367
+ );
1368
+ }
1369
+ case "createUpload": {
1370
+ const id = uuidV7();
1371
+ const meta = {};
1372
+ for (const kv of (r.headers["upload-metadata"] ?? "").split(",").filter(Boolean)) {
1373
+ const [k, v] = kv.trim().split(" ");
1374
+ meta[k] = v ? new TextDecoder().decode(Uint8Array.from(atob(v), (c) => c.charCodeAt(0))) : "";
1375
+ }
1376
+ this.uploads.set(id, {
1377
+ length: Number(r.headers["upload-length"]),
1378
+ data: [],
1379
+ offset: 0,
1380
+ meta,
1381
+ status: "uploading"
1382
+ });
1383
+ return new FreedomeResponse(201, {
1384
+ location: `/api/v1/uploads/${id}`,
1385
+ "upload-offset": "0",
1386
+ "tus-resumable": "1.0.0"
1387
+ });
1388
+ }
1389
+ case "getUploadOffset": {
1390
+ const u = this.uploads.get(p.uploadId);
1391
+ if (!u) return problem(404, "not-found", "upload");
1392
+ return new FreedomeResponse(200, {
1393
+ "upload-offset": String(u.offset),
1394
+ "upload-length": String(u.length),
1395
+ "tus-resumable": "1.0.0"
1396
+ });
1397
+ }
1398
+ case "appendUpload": {
1399
+ const u = this.uploads.get(p.uploadId);
1400
+ if (!u) return problem(404, "not-found", "upload");
1401
+ if (Number(r.headers["upload-offset"]) !== u.offset)
1402
+ return problem(409, "conflict", `offset is ${u.offset}`);
1403
+ const chunk = r.body ?? new Uint8Array(0);
1404
+ u.data.push(chunk.slice());
1405
+ u.offset += chunk.length;
1406
+ if (u.offset >= u.length) u.status = "complete";
1407
+ return new FreedomeResponse(204, {
1408
+ "upload-offset": String(u.offset),
1409
+ "tus-resumable": "1.0.0"
1410
+ });
1411
+ }
1412
+ case "deleteUpload":
1413
+ this.uploads.delete(p.uploadId);
1414
+ return new FreedomeResponse(204, { "tus-resumable": "1.0.0" });
1415
+ case "createAsset": {
1416
+ const u = this.uploads.get(body?.uploadId);
1417
+ if (!u || u.status !== "complete")
1418
+ return problem(422, "validation-failed", "/uploadId: no completed upload", {
1419
+ errors: [{ pointer: "/uploadId", detail: "no completed upload" }]
1420
+ });
1421
+ const bytes = new Uint8Array(u.length);
1422
+ let o = 0;
1423
+ for (const c of u.data) {
1424
+ bytes.set(c, o);
1425
+ o += c.length;
1426
+ }
1427
+ const sha = sha256Hex(bytes);
1428
+ if (u.meta.sha256 && u.meta.sha256 !== sha)
1429
+ return problem(422, "upload-checksum-mismatch", "sha256 differs");
1430
+ const id = body.id ?? uuidV7();
1431
+ const a = {
1432
+ id,
1433
+ revision: 1,
1434
+ name: body.name ?? u.meta.filename,
1435
+ type: body.type ?? "other",
1436
+ status: "ready",
1437
+ size: bytes.length,
1438
+ sha256: sha,
1439
+ tags: body.tags ?? [],
1440
+ createdAt: (0, import_protocol3.rfc3339Millis)()
1441
+ };
1442
+ this.assets.set(id, a);
1443
+ this.assetBytes.set(id, bytes);
1444
+ this.publish(`assets/${id}`, "asset.ready", { resource: a });
1445
+ return json(201, a);
1446
+ }
1447
+ case "getAsset": {
1448
+ const a = this.assets.get(p.assetId);
1449
+ return a ? json(200, a, this.etag(a.revision)) : problem(404, "not-found", "asset");
1450
+ }
1451
+ case "listAssets":
1452
+ return json(200, { items: [...this.assets.values()], nextCursor: null });
1453
+ case "getJob": {
1454
+ const j = this.jobs.get(p.jobId);
1455
+ return j ? json(200, j) : problem(404, "not-found", "job");
1456
+ }
1457
+ default: {
1458
+ const a = op.tags.includes("audio") ? this.audio.handle(op.id, p, body, r.headers, r.query ?? {}) : void 0;
1459
+ if (a) return a;
1460
+ const reactive = this.audioReactive.handle(op.id, p, body, r.headers);
1461
+ if (reactive) return reactive;
1462
+ return problem(
1463
+ 501,
1464
+ "internal",
1465
+ `${op.id} is not implemented by the in-memory fake \u2014 use the freedome/fake-dome image`
1466
+ );
1467
+ }
1468
+ }
1469
+ }
1470
+ };
1471
+ var FakeTransport = class {
1472
+ constructor(s) {
1473
+ this.s = s;
1474
+ }
1475
+ s;
1476
+ closed = false;
1477
+ async send(r) {
1478
+ if (this.closed) throw new NetworkError("transport closed");
1479
+ return this.s.handle(r);
1480
+ }
1481
+ async close() {
1482
+ this.closed = true;
1483
+ }
1484
+ };
1485
+ var FakeSocketSession = class {
1486
+ constructor(server) {
1487
+ this.server = server;
1488
+ this.client = {
1489
+ protocol: "freedome.v1",
1490
+ send: (t) => queueMicrotask(() => void this.receive(t)),
1491
+ listen: (m, c) => {
1492
+ this.onMessage = m;
1493
+ this.onClose = c;
1494
+ },
1495
+ close: (code, reason) => this.serverClose(code ?? 1e3, reason)
1496
+ };
1497
+ }
1498
+ server;
1499
+ onMessage;
1500
+ onClose;
1501
+ filters = [];
1502
+ token;
1503
+ open = true;
1504
+ client;
1505
+ out(m) {
1506
+ if (!this.open) return;
1507
+ const t = JSON.stringify(m);
1508
+ queueMicrotask(() => this.onMessage?.(t));
1509
+ }
1510
+ serverClose(code, reason) {
1511
+ if (!this.open) return;
1512
+ this.open = false;
1513
+ this.server.forget(this);
1514
+ queueMicrotask(() => this.onClose?.(code, reason));
1515
+ }
1516
+ deliver(e) {
1517
+ if (this.filters.some((f) => matches(f, e.topic))) this.out(e);
1518
+ }
1519
+ reply(m, type, data) {
1520
+ this.out({ type, id: uuidV7(), ts: (0, import_protocol3.rfc3339Millis)(), replyTo: m.id, data });
1521
+ }
1522
+ async receive(text) {
1523
+ if (!this.open) return;
1524
+ const m = JSON.parse(text);
1525
+ switch (m.type) {
1526
+ case "hello": {
1527
+ this.token = m.data?.token;
1528
+ if (this.token && !this.server.principal(`Bearer ${this.token}`)) {
1529
+ this.out({
1530
+ type: "bye",
1531
+ id: uuidV7(),
1532
+ ts: (0, import_protocol3.rfc3339Millis)(),
1533
+ data: { reason: "unauthenticated", code: 4401 }
1534
+ });
1535
+ this.serverClose(4401, "unauthenticated");
1536
+ return;
1537
+ }
1538
+ this.reply(m, "welcome", {
1539
+ server: { instanceId: this.server.instanceId, version: "1.0.0-rc.1" },
1540
+ heartbeatSec: 20,
1541
+ maxMessageBytes: 1048576
1542
+ });
1543
+ const since = m.data?.resume?.sinceSeq;
1544
+ if (typeof since === "number") this.pendingResume = since;
1545
+ return;
1546
+ }
1547
+ case "subscribe": {
1548
+ const topics = m.data?.topics ?? [];
1549
+ this.filters.push(...topics);
1550
+ this.reply(m, "result", { status: 200, body: { topics } });
1551
+ const since = m.data?.sinceSeq ?? this.pendingResume;
1552
+ if (typeof since === "number") {
1553
+ for (const e of this.server.replay(since))
1554
+ if (topics.some((f) => matches(f, e.topic))) this.out(e);
1555
+ }
1556
+ return;
1557
+ }
1558
+ case "unsubscribe":
1559
+ this.filters = this.filters.filter((f) => !(m.data?.topics ?? []).includes(f));
1560
+ this.reply(m, "result", { status: 200 });
1561
+ return;
1562
+ case "ping":
1563
+ this.reply(m, "pong", {});
1564
+ return;
1565
+ case "call": {
1566
+ const op = import_protocol3.Operations[m.data?.op];
1567
+ if (!op) {
1568
+ this.reply(m, "error", {
1569
+ type: "about:blank",
1570
+ title: "not-found",
1571
+ status: 404,
1572
+ code: "not-found",
1573
+ detail: `unknown op ${m.data?.op}`
1574
+ });
1575
+ return;
1576
+ }
1577
+ const path = op.path.replace(
1578
+ /\{([^}]+)\}/g,
1579
+ (_, n) => encodeURIComponent(m.data.params?.[n] ?? "")
1580
+ );
1581
+ const res = await this.server.handle({
1582
+ method: op.method,
1583
+ path,
1584
+ headers: {
1585
+ ...this.token ? { authorization: `Bearer ${this.token}` } : {},
1586
+ ...m.data.ifMatch ? { "if-match": m.data.ifMatch } : {},
1587
+ "content-type": "application/json"
1588
+ },
1589
+ ...m.data.body !== void 0 ? { body: new TextEncoder().encode(JSON.stringify(m.data.body)) } : {},
1590
+ operationId: op.id
1591
+ });
1592
+ if (res.ok)
1593
+ this.reply(m, "result", {
1594
+ status: res.status,
1595
+ ...res.body.length ? { body: res.json } : {},
1596
+ ...res.headers.etag ? { etag: res.headers.etag } : {}
1597
+ });
1598
+ else this.reply(m, "error", res.json);
1599
+ return;
1600
+ }
1601
+ }
1602
+ }
1603
+ pendingResume;
1604
+ };
1605
+ function matches(filter, topic) {
1606
+ if (filter === "#") return true;
1607
+ const f = filter.split("/");
1608
+ const t = topic.split("/");
1609
+ for (let i = 0; i < f.length; i++) {
1610
+ if (f[i] === "#") return true;
1611
+ if (i >= t.length || f[i] !== "+" && f[i] !== t[i]) return false;
1612
+ }
1613
+ return f.length === t.length;
1614
+ }
1615
+ function createFakeTransport() {
1616
+ return new FakeDomeServer();
1617
+ }
1618
+ // Annotate the CommonJS export names for ESM import in node:
1619
+ 0 && (module.exports = {
1620
+ FakeDomeServer,
1621
+ createFakeTransport
1622
+ });