@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.
package/dist/index.cjs ADDED
@@ -0,0 +1,4753 @@
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/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ ApiCaller: () => ApiCaller,
24
+ AudioReactiveRepository: () => AudioReactiveRepository,
25
+ AudioRepository: () => AudioRepository,
26
+ BackoffPolicy: () => BackoffPolicy,
27
+ BlobContentSource: () => BlobContentSource,
28
+ BytesContentSource: () => BytesContentSource,
29
+ CALIBRATION_FILE_TYPES: () => CALIBRATION_FILE_TYPES,
30
+ CalibrationRepository: () => CalibrationRepository,
31
+ ClientsRepository: () => ClientsRepository,
32
+ CompositeDiscovery: () => CompositeDiscovery,
33
+ ConflictError: () => ConflictError,
34
+ ContentRepository: () => ContentRepository,
35
+ Credentials: () => Credentials,
36
+ DEFAULT_OFFLINE_POLICY: () => DEFAULT_OFFLINE_POLICY,
37
+ DomeTopics: () => import_protocol21.DomeTopics,
38
+ Emitter: () => Emitter,
39
+ EngineRepository: () => EngineRepository,
40
+ EventHub: () => EventHub,
41
+ EventKinds: () => import_protocol21.EventKinds,
42
+ FREEDOME_CLIENT_VERSION: () => FREEDOME_CLIENT_VERSION,
43
+ FetchTransport: () => FetchTransport,
44
+ ForbiddenError: () => ForbiddenError,
45
+ FreedomeClient: () => FreedomeClient,
46
+ FreedomeEndpoint: () => FreedomeEndpoint,
47
+ FreedomeError: () => FreedomeError,
48
+ FreedomeResponse: () => FreedomeResponse,
49
+ GRAPHQL_EVENTS_SUBSCRIPTION: () => GRAPHQL_EVENTS_SUBSCRIPTION,
50
+ GRAPHQL_OPERATION: () => GRAPHQL_OPERATION,
51
+ GRAPHQL_WS_SUBPROTOCOL: () => GRAPHQL_WS_SUBPROTOCOL,
52
+ GatewaysRepository: () => GatewaysRepository,
53
+ GeneratorSession: () => GeneratorSession,
54
+ GraphqlClient: () => GraphqlClient,
55
+ GraphqlWsChannel: () => GraphqlWsChannel,
56
+ InMemoryCacheStore: () => InMemoryCacheStore,
57
+ InMemoryOutboxStore: () => InMemoryOutboxStore,
58
+ InMemoryTokenStore: () => InMemoryTokenStore,
59
+ IncompatibleServerError: () => IncompatibleServerError,
60
+ MAX_UPLOAD_CHUNK: () => MAX_UPLOAD_CHUNK,
61
+ NO_SESSION: () => NO_SESSION,
62
+ NetworkError: () => NetworkError,
63
+ NotFoundError: () => NotFoundError,
64
+ OfflineError: () => OfflineError,
65
+ Operations: () => import_protocol21.Operations,
66
+ OscRepository: () => OscRepository,
67
+ PACKAGE_NAME: () => PACKAGE_NAME,
68
+ PairingLink: () => PairingLink,
69
+ PayloadTooLargeError: () => PayloadTooLargeError,
70
+ PlayTargets: () => PlayTargets,
71
+ PlaybackRepository: () => PlaybackRepository,
72
+ PlayerHandle: () => PlayerHandle,
73
+ QueuedForReplayError: () => QueuedForReplayError,
74
+ RateLimitedError: () => RateLimitedError,
75
+ RepositoryContext: () => RepositoryContext,
76
+ RequestTimeoutError: () => RequestTimeoutError,
77
+ ServerError: () => ServerError,
78
+ Sha256: () => Sha256,
79
+ ShowParts: () => ShowParts,
80
+ SocketIoChannel: () => SocketIoChannel,
81
+ StaticDiscovery: () => StaticDiscovery,
82
+ TlsPinMismatchError: () => TlsPinMismatchError,
83
+ UnauthorizedError: () => UnauthorizedError,
84
+ UnsupportedCapabilityError: () => UnsupportedCapabilityError,
85
+ UnsupportedFormatError: () => UnsupportedFormatError,
86
+ UploadTask: () => UploadTask,
87
+ ValidationError: () => ValidationError,
88
+ VenuesRepository: () => VenuesRepository,
89
+ WsChannel: () => WsChannel,
90
+ audioSessionEnded: () => audioSessionEnded,
91
+ base64: () => base64,
92
+ can: () => can,
93
+ defaultTransports: () => defaultTransports,
94
+ errorFromProblem: () => errorFromProblem,
95
+ isAuthFailure: () => isAuthFailure,
96
+ isUnreachable: () => isUnreachable,
97
+ multipart: () => multipart,
98
+ nextValue: () => nextValue,
99
+ oscArg: () => oscArg,
100
+ probe: () => probe,
101
+ readAllPages: () => readAllPages,
102
+ readPage: () => readPage,
103
+ requestUrl: () => requestUrl,
104
+ scopesOfRole: () => scopesOfRole,
105
+ sessionFromPrincipal: () => sessionFromPrincipal,
106
+ sessionFromTokens: () => sessionFromTokens,
107
+ sha256Hex: () => sha256Hex,
108
+ storedTokensOf: () => storedTokensOf,
109
+ uuidV7: () => uuidV7,
110
+ webSocketConnector: () => webSocketConnector
111
+ });
112
+ module.exports = __toCommonJS(index_exports);
113
+
114
+ // src/api.ts
115
+ var import_protocol = require("@freedome/protocol");
116
+
117
+ // src/errors.ts
118
+ var FreedomeError = class extends Error {
119
+ code;
120
+ problem;
121
+ constructor(message, opts = {}) {
122
+ super(message, opts.cause === void 0 ? void 0 : { cause: opts.cause });
123
+ this.name = new.target.name;
124
+ this.code = opts.code;
125
+ this.problem = opts.problem;
126
+ }
127
+ };
128
+ var NetworkError = class extends FreedomeError {
129
+ };
130
+ var RequestTimeoutError = class extends FreedomeError {
131
+ constructor(message, timeoutMs) {
132
+ super(message, { code: "timeout" });
133
+ this.timeoutMs = timeoutMs;
134
+ }
135
+ timeoutMs;
136
+ };
137
+ var OfflineError = class extends FreedomeError {
138
+ constructor(message) {
139
+ super(message, { code: "offline" });
140
+ }
141
+ };
142
+ var UnauthorizedError = class extends FreedomeError {
143
+ constructor(message, problem) {
144
+ super(message, { code: "unauthenticated", ...problem ? { problem } : {} });
145
+ }
146
+ };
147
+ var ForbiddenError = class extends FreedomeError {
148
+ constructor(message, scope, problem) {
149
+ super(message, { code: "forbidden", ...problem ? { problem } : {} });
150
+ this.scope = scope;
151
+ }
152
+ scope;
153
+ };
154
+ var NotFoundError = class extends FreedomeError {
155
+ constructor(message, problem) {
156
+ super(message, { code: "not-found", ...problem ? { problem } : {} });
157
+ }
158
+ };
159
+ var ConflictError = class extends FreedomeError {
160
+ constructor(message, opts = {}) {
161
+ super(message, { ...opts, code: opts.code ?? "conflict" });
162
+ this.latest = opts.latest;
163
+ }
164
+ latest;
165
+ };
166
+ var ValidationError = class extends FreedomeError {
167
+ constructor(pointer, reason, opts = {}) {
168
+ super(`${pointer}: ${reason}`, { ...opts, code: opts.code ?? "validation-failed" });
169
+ this.pointer = pointer;
170
+ this.reason = reason;
171
+ this.issues = opts.issues?.length ? opts.issues : [{ pointer, detail: reason }];
172
+ }
173
+ pointer;
174
+ reason;
175
+ issues;
176
+ };
177
+ var UnsupportedFormatError = class extends FreedomeError {
178
+ constructor(message, problem) {
179
+ super(message, { code: "unsupported-format", ...problem ? { problem } : {} });
180
+ }
181
+ };
182
+ var PayloadTooLargeError = class extends FreedomeError {
183
+ constructor(message, problem) {
184
+ super(message, { code: "payload-too-large", ...problem ? { problem } : {} });
185
+ }
186
+ };
187
+ var IncompatibleServerError = class extends FreedomeError {
188
+ constructor(message, serverVersions = [], supported = []) {
189
+ super(message, { code: "engine-incompatible" });
190
+ this.serverVersions = serverVersions;
191
+ this.supported = supported;
192
+ }
193
+ serverVersions;
194
+ supported;
195
+ };
196
+ var RateLimitedError = class extends FreedomeError {
197
+ constructor(message, retryAfterMs, problem) {
198
+ super(message, { code: "rate-limited", ...problem ? { problem } : {} });
199
+ this.retryAfterMs = retryAfterMs;
200
+ }
201
+ retryAfterMs;
202
+ };
203
+ var ServerError = class extends FreedomeError {
204
+ constructor(message, opts = {}) {
205
+ super(message, opts);
206
+ this.status = opts.status;
207
+ this.traceId = opts.traceId;
208
+ }
209
+ status;
210
+ traceId;
211
+ };
212
+ var UnsupportedCapabilityError = class extends FreedomeError {
213
+ };
214
+ var TlsPinMismatchError = class extends FreedomeError {
215
+ constructor(message, expected, actual) {
216
+ super(message, { code: "tls-pin-mismatch" });
217
+ this.expected = expected;
218
+ this.actual = actual;
219
+ }
220
+ expected;
221
+ actual;
222
+ };
223
+ var QueuedForReplayError = class extends FreedomeError {
224
+ constructor(message, entryId) {
225
+ super(message, { code: "queued" });
226
+ this.entryId = entryId;
227
+ }
228
+ entryId;
229
+ };
230
+ function errorFromProblem(status, problem, context, retryAfter) {
231
+ const detail = problem?.detail ?? problem?.title ?? `HTTP ${status}`;
232
+ const msg = `${context}: ${detail}`;
233
+ const code = problem?.code;
234
+ switch (status) {
235
+ case 400:
236
+ case 422: {
237
+ const errs = problem?.errors ?? [];
238
+ return new ValidationError(errs[0]?.pointer ?? "/", errs[0]?.detail ?? detail, {
239
+ issues: errs.map((e) => ({ pointer: e.pointer, detail: e.detail })),
240
+ code: code ?? "validation-failed",
241
+ ...problem ? { problem } : {}
242
+ });
243
+ }
244
+ case 401:
245
+ return new UnauthorizedError(msg, problem);
246
+ case 403:
247
+ return new ForbiddenError(msg, /\b([a-z]+:[a-z]+)\b/.exec(detail)?.[1], problem);
248
+ case 404:
249
+ return new NotFoundError(msg, problem);
250
+ case 409:
251
+ return new ConflictError(msg, { code: code ?? "conflict", ...problem ? { problem } : {} });
252
+ case 412:
253
+ return new ConflictError(msg, {
254
+ code: code ?? "precondition-failed",
255
+ ...problem ? { problem } : {}
256
+ });
257
+ case 413:
258
+ return new PayloadTooLargeError(msg, problem);
259
+ case 415:
260
+ return new UnsupportedFormatError(msg, problem);
261
+ case 429: {
262
+ const ra = Number.parseInt(retryAfter ?? "", 10);
263
+ return new RateLimitedError(msg, Number.isFinite(ra) ? ra * 1e3 : void 0, problem);
264
+ }
265
+ default:
266
+ return new ServerError(msg, {
267
+ code: code ?? (status >= 500 ? "internal" : `http-${status}`),
268
+ status,
269
+ ...problem?.traceId ? { traceId: problem.traceId } : {},
270
+ ...problem ? { problem } : {}
271
+ });
272
+ }
273
+ }
274
+ var isUnreachable = (e) => e instanceof NetworkError || e instanceof RequestTimeoutError || e instanceof OfflineError;
275
+
276
+ // src/ids.ts
277
+ var lastMs = 0;
278
+ var seq = 0;
279
+ function randomBytes(n) {
280
+ const b = new Uint8Array(n);
281
+ globalThis.crypto.getRandomValues(b);
282
+ return b;
283
+ }
284
+ function uuidV7(now = Date.now()) {
285
+ if (now === lastMs) seq = seq + 1 & 4095;
286
+ else {
287
+ lastMs = now;
288
+ seq = randomBytes(2).reduce((a, x) => a << 8 | x, 0) & 2047;
289
+ }
290
+ const b = randomBytes(16);
291
+ let t = now;
292
+ for (let i = 5; i >= 0; i--) {
293
+ b[i] = t % 256;
294
+ t = Math.floor(t / 256);
295
+ }
296
+ b[6] = 112 | seq >> 8 & 15;
297
+ b[7] = seq & 255;
298
+ b[8] = 128 | b[8] & 63;
299
+ const h = Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
300
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
301
+ }
302
+
303
+ // src/transport.ts
304
+ var FreedomeResponse = class _FreedomeResponse {
305
+ constructor(status, headers = {}, body = new Uint8Array(0)) {
306
+ this.status = status;
307
+ this.headers = headers;
308
+ this.body = body;
309
+ }
310
+ status;
311
+ headers;
312
+ body;
313
+ get ok() {
314
+ return this.status >= 200 && this.status < 300;
315
+ }
316
+ get text() {
317
+ return new TextDecoder().decode(this.body);
318
+ }
319
+ /** Parsed JSON body (`undefined` when empty). */
320
+ get json() {
321
+ if (this.body.length === 0) return void 0;
322
+ return JSON.parse(this.text);
323
+ }
324
+ static json(status, value, headers = {}) {
325
+ return new _FreedomeResponse(
326
+ status,
327
+ { "content-type": "application/json", ...headers },
328
+ new TextEncoder().encode(JSON.stringify(value))
329
+ );
330
+ }
331
+ };
332
+ function requestUrl(endpoint, r) {
333
+ const base = r.rootRelative ? endpoint.baseUrl : endpoint.apiBase;
334
+ const q = r.query && Object.keys(r.query).length ? `?${new URLSearchParams(r.query).toString()}` : "";
335
+ return `${base}${r.path}${q}`;
336
+ }
337
+ var FetchTransport = class {
338
+ constructor(endpoint, fetchImpl = globalThis.fetch.bind(globalThis)) {
339
+ this.endpoint = endpoint;
340
+ this.fetchImpl = fetchImpl;
341
+ }
342
+ endpoint;
343
+ fetchImpl;
344
+ controllers = /* @__PURE__ */ new Set();
345
+ async send(r, timeoutMs) {
346
+ const ac = new AbortController();
347
+ this.controllers.add(ac);
348
+ let timedOut = false;
349
+ const timer = setTimeout(() => {
350
+ timedOut = true;
351
+ ac.abort();
352
+ }, timeoutMs);
353
+ try {
354
+ const res = await this.fetchImpl(requestUrl(this.endpoint, r), {
355
+ method: r.method,
356
+ headers: r.headers,
357
+ ...r.body ? { body: r.body } : {},
358
+ signal: ac.signal
359
+ });
360
+ const body = new Uint8Array(await res.arrayBuffer());
361
+ const headers = {};
362
+ res.headers.forEach((v, k) => headers[k.toLowerCase()] = v);
363
+ return new FreedomeResponse(res.status, headers, body);
364
+ } catch (e) {
365
+ if (timedOut)
366
+ throw new RequestTimeoutError(
367
+ `${r.method} ${r.path}: no answer within ${timeoutMs} ms`,
368
+ timeoutMs
369
+ );
370
+ throw new NetworkError(`${r.method} ${r.path}: ${e?.message ?? e}`, { cause: e });
371
+ } finally {
372
+ clearTimeout(timer);
373
+ this.controllers.delete(ac);
374
+ }
375
+ }
376
+ async close() {
377
+ for (const c of this.controllers) c.abort();
378
+ this.controllers.clear();
379
+ }
380
+ };
381
+
382
+ // src/api.ts
383
+ var enc = new TextEncoder();
384
+ var clean = (o) => {
385
+ const out = {};
386
+ for (const [k, v] of Object.entries(o ?? {})) if (v !== void 0) out[k] = v;
387
+ return out;
388
+ };
389
+ var ApiCaller = class _ApiCaller {
390
+ constructor(transport, userAgent, timeoutMs, logger) {
391
+ this.transport = transport;
392
+ this.userAgent = userAgent;
393
+ this.timeoutMs = timeoutMs;
394
+ this.logger = logger;
395
+ }
396
+ transport;
397
+ userAgent;
398
+ timeoutMs;
399
+ logger;
400
+ /** `Bearer …` of the session. */
401
+ authorization;
402
+ onUnauthorized;
403
+ realtime;
404
+ isOffline;
405
+ onTransportFailure;
406
+ /** Operations served at the server root (unversioned). */
407
+ static unversionedOps = /* @__PURE__ */ new Set(["getHealth", "getReady", "getMetrics"]);
408
+ /** Live-control operations: fail fast while offline (never queued). */
409
+ static liveOps = /* @__PURE__ */ new Set([
410
+ "play",
411
+ "pause",
412
+ "resume",
413
+ "stop",
414
+ "next",
415
+ "previous",
416
+ "seek",
417
+ "patchPlayer",
418
+ "patchOutput",
419
+ "setParameter",
420
+ "fireCue",
421
+ "setActiveShow",
422
+ "setTestPattern",
423
+ "identifyDisplay",
424
+ "setDisplayPower",
425
+ "submitCalibrationCapture",
426
+ "applyCalibrationJob",
427
+ "startCalibrationJob",
428
+ "sendOsc",
429
+ "publishAppPayload",
430
+ "clearAppPayloads",
431
+ "patchAudio",
432
+ "setGenerator",
433
+ "stopGenerator",
434
+ "patchAudioZone",
435
+ "startAudioSession",
436
+ "stopAudioSession",
437
+ "setSourcePosition"
438
+ ]);
439
+ async call(op, o = {}) {
440
+ if (_ApiCaller.liveOps.has(op.id) && this.isOffline?.()) {
441
+ throw new OfflineError(
442
+ `${op.id}: the media server is not reachable (live control is never queued)`
443
+ );
444
+ }
445
+ const rt = o.preferRealtime && !o.bytes ? this.realtime?.() : void 0;
446
+ if (rt?.supportsCalls) return this.viaRealtime(rt, op, o);
447
+ const payload = o.bytes ?? (o.body === void 0 ? void 0 : enc.encode(JSON.stringify(o.body)));
448
+ const headers = {
449
+ accept: "application/json, application/problem+json",
450
+ "x-freedome-client": this.userAgent,
451
+ ...payload ? {
452
+ "content-type": o.contentType ?? (op.method === "PATCH" ? "application/merge-patch+json" : "application/json")
453
+ } : {},
454
+ ...op.method === "POST" ? { "idempotency-key": o.idempotencyKey ?? uuidV7() } : {},
455
+ ...clean(o.headers)
456
+ };
457
+ const path = (0, import_protocol.expandPath)(op, o.params ?? {});
458
+ const once = () => this.transport.send(
459
+ {
460
+ method: op.method,
461
+ path,
462
+ query: clean(o.query),
463
+ headers: {
464
+ ...headers,
465
+ ...o.authenticated !== false && this.authorization ? { authorization: this.authorization } : {}
466
+ },
467
+ body: payload,
468
+ operationId: op.id,
469
+ rootRelative: _ApiCaller.unversionedOps.has(op.id)
470
+ },
471
+ o.timeoutMs ?? this.timeoutMs
472
+ );
473
+ this.logger?.({ level: "debug", message: `\u2192 ${op.method} ${path} (${op.id})` });
474
+ let res;
475
+ try {
476
+ res = await once();
477
+ } catch (e) {
478
+ if (e instanceof NetworkError || e instanceof RequestTimeoutError)
479
+ this.onTransportFailure?.(e);
480
+ throw e;
481
+ }
482
+ if (res.status === 401 && o.authenticated !== false && this.onUnauthorized) {
483
+ this.logger?.({ level: "info", message: `${op.id}: 401 \u2014 refreshing credentials` });
484
+ if (await this.onUnauthorized()) res = await once();
485
+ }
486
+ this.logger?.({ level: "debug", message: `\u2190 ${res.status} ${op.id}` });
487
+ if (!res.ok) throw _ApiCaller.errorOf(op, res);
488
+ return res;
489
+ }
490
+ async viaRealtime(rt, op, o) {
491
+ this.logger?.({ level: "debug", message: `\u21E2 realtime call ${op.id}` });
492
+ try {
493
+ const r = await rt.call(op.id, {
494
+ params: o.params ?? {},
495
+ body: o.body,
496
+ ...o.headers?.["if-match"] ? { ifMatch: o.headers["if-match"] } : {},
497
+ timeoutMs: o.timeoutMs ?? this.timeoutMs
498
+ });
499
+ if (r.status >= 400) {
500
+ throw _ApiCaller.errorOf(op, FreedomeResponse.json(r.status, r.body));
501
+ }
502
+ return r.body === void 0 || r.body === null ? new FreedomeResponse(r.status, r.etag ? { etag: r.etag } : {}) : FreedomeResponse.json(r.status, r.body, r.etag ? { etag: r.etag } : {});
503
+ } catch (e) {
504
+ if (e instanceof NetworkError || e instanceof UnsupportedCapabilityError) {
505
+ return this.call(op, { ...o, preferRealtime: false });
506
+ }
507
+ throw e;
508
+ }
509
+ }
510
+ /** JSON object body of [op]. */
511
+ async json(op, o = {}) {
512
+ return _ApiCaller.decodeBody(op, await this.call(op, o));
513
+ }
514
+ /** Decodes a JSON object body; a non-object → ServerError(internal). */
515
+ static decodeBody(op, res) {
516
+ let j;
517
+ try {
518
+ j = res.json;
519
+ } catch (e) {
520
+ throw new ServerError(`${op.id}: response is not JSON (${e.message})`, {
521
+ code: "internal",
522
+ status: res.status
523
+ });
524
+ }
525
+ if (typeof j !== "object" || j === null || Array.isArray(j)) {
526
+ throw new ServerError(`${op.id}: response is not a JSON object`, {
527
+ code: "internal",
528
+ status: res.status
529
+ });
530
+ }
531
+ return j;
532
+ }
533
+ /** Maps an error response of [op]. */
534
+ static errorOf(op, res) {
535
+ let p;
536
+ try {
537
+ const j = res.json;
538
+ if (j && typeof j.code === "string" && typeof j.title === "string")
539
+ p = { type: "about:blank", ...j };
540
+ } catch {
541
+ p = void 0;
542
+ }
543
+ return errorFromProblem(res.status, p, op.id, res.headers["retry-after"]);
544
+ }
545
+ };
546
+ async function readPage(api, op, o = {}) {
547
+ const page = await api.json(op, {
548
+ ...o,
549
+ query: {
550
+ ...o.query,
551
+ limit: o.limit === void 0 ? void 0 : String(o.limit),
552
+ cursor: o.cursor
553
+ }
554
+ });
555
+ if (!Array.isArray(page.items))
556
+ throw new ServerError(`${op.id}: page without items`, { code: "internal" });
557
+ return {
558
+ items: page.items,
559
+ nextCursor: typeof page.nextCursor === "string" && page.nextCursor ? page.nextCursor : null
560
+ };
561
+ }
562
+ async function readAllPages(api, op, o = {}) {
563
+ const out = [];
564
+ let cursor;
565
+ do {
566
+ const p = await readPage(api, op, { ...o, limit: o.limit ?? 200, cursor });
567
+ out.push(...p.items);
568
+ cursor = p.nextCursor ?? void 0;
569
+ } while (cursor);
570
+ return out;
571
+ }
572
+
573
+ // src/auth.ts
574
+ var import_protocol2 = require("@freedome/protocol");
575
+ var Credentials = {
576
+ guest: () => ({ kind: "guest" }),
577
+ password: (username, password) => ({
578
+ kind: "password",
579
+ username,
580
+ password
581
+ }),
582
+ apiKey: (key) => ({ kind: "apiKey", key }),
583
+ pairing: (o) => ({ kind: "pairing", ...o }),
584
+ cloud: (token) => ({
585
+ kind: "cloud",
586
+ token: typeof token === "string" ? () => Promise.resolve(token) : token
587
+ })
588
+ };
589
+ var InMemoryTokenStore = class {
590
+ m = /* @__PURE__ */ new Map();
591
+ async read(k) {
592
+ return this.m.get(k);
593
+ }
594
+ async write(k, t) {
595
+ this.m.set(k, t);
596
+ }
597
+ async delete(k) {
598
+ this.m.delete(k);
599
+ }
600
+ };
601
+ var NO_SESSION = { role: "none", scopes: /* @__PURE__ */ new Set() };
602
+ var ROLES = ["guest", "operator", "admin", "superadmin"];
603
+ var scopesOfRole = (role) => new Set(import_protocol2.RoleScopes[role] ?? []);
604
+ var can = (session, scope) => session.scopes.has(scope);
605
+ function roleOf(scopes) {
606
+ if (!scopes) return "guest";
607
+ for (const r of ROLES) {
608
+ const s = scopesOfRole(r);
609
+ if (scopes.every((x) => s.has(x))) return r;
610
+ }
611
+ return "superadmin";
612
+ }
613
+ function sessionFromTokens(t, user) {
614
+ const tt = t;
615
+ const p = tt.principal;
616
+ const role = p?.role ?? roleOf(tt.scopes);
617
+ const scopes = tt.scopes ?? p?.scopes;
618
+ const name = p?.name ?? user;
619
+ return {
620
+ role,
621
+ scopes: scopes ? new Set(scopes) : scopesOfRole(role),
622
+ ...typeof tt.expiresIn === "number" ? { expiresAt: new Date(Date.now() + tt.expiresIn * 1e3).toISOString() } : {},
623
+ ...name ? { user: name } : {}
624
+ };
625
+ }
626
+ function sessionFromPrincipal(p) {
627
+ const x = p;
628
+ const user = x.name ?? x.subject;
629
+ return {
630
+ role: x.role,
631
+ scopes: new Set(x.scopes),
632
+ ...x.expiresAt ? { expiresAt: x.expiresAt } : {},
633
+ ...user ? { user } : {}
634
+ };
635
+ }
636
+ function storedTokensOf(t) {
637
+ const tt = t;
638
+ return {
639
+ accessToken: tt.accessToken,
640
+ ...tt.refreshToken ? { refreshToken: tt.refreshToken } : {},
641
+ ...typeof tt.expiresIn === "number" ? { expiresAt: new Date(Date.now() + tt.expiresIn * 1e3).toISOString() } : {}
642
+ };
643
+ }
644
+
645
+ // src/backoff.ts
646
+ var BackoffPolicy = class {
647
+ constructor(initialMs = 500, maxMs = 3e4, factor = 2, jitter = true) {
648
+ this.initialMs = initialMs;
649
+ this.maxMs = maxMs;
650
+ this.factor = factor;
651
+ this.jitter = jitter;
652
+ }
653
+ initialMs;
654
+ maxMs;
655
+ factor;
656
+ jitter;
657
+ /** Upper bound of attempt [n] (0-based). */
658
+ cap(n) {
659
+ const ms = this.initialMs * this.factor ** n;
660
+ return Number.isFinite(ms) && ms < this.maxMs ? Math.round(ms) : this.maxMs;
661
+ }
662
+ /** Delay of attempt [n]: uniform in [0, cap] with jitter, else cap. */
663
+ delay(n, random = Math.random) {
664
+ const c = this.cap(n);
665
+ return this.jitter ? Math.round(random() * c) : c;
666
+ }
667
+ };
668
+
669
+ // src/client.ts
670
+ var import_protocol19 = require("@freedome/protocol");
671
+
672
+ // src/context.ts
673
+ var import_protocol3 = require("@freedome/protocol");
674
+
675
+ // src/emitter.ts
676
+ var Emitter = class {
677
+ listeners = /* @__PURE__ */ new Set();
678
+ closedFlag = false;
679
+ on(fn) {
680
+ this.listeners.add(fn);
681
+ return () => this.listeners.delete(fn);
682
+ }
683
+ emit(v) {
684
+ if (this.closedFlag) return;
685
+ for (const l of [...this.listeners]) l(v);
686
+ }
687
+ get size() {
688
+ return this.listeners.size;
689
+ }
690
+ close() {
691
+ this.closedFlag = true;
692
+ this.listeners.clear();
693
+ }
694
+ };
695
+ function nextValue(e, pred = () => true, timeoutMs = 5e3) {
696
+ return new Promise((resolve, reject) => {
697
+ const t = setTimeout(() => {
698
+ off();
699
+ reject(new Error(`no value within ${timeoutMs} ms`));
700
+ }, timeoutMs);
701
+ const off = e.on((v) => {
702
+ if (!pred(v)) return;
703
+ clearTimeout(t);
704
+ off();
705
+ resolve(v);
706
+ });
707
+ });
708
+ }
709
+
710
+ // src/context.ts
711
+ var RepositoryContext = class {
712
+ constructor(api, hub, cache, outbox, offline, isOffline, cacheScope, realtimeUp, positionHz, onEngineHealth, logger) {
713
+ this.api = api;
714
+ this.hub = hub;
715
+ this.cache = cache;
716
+ this.outbox = outbox;
717
+ this.offline = offline;
718
+ this.isOffline = isOffline;
719
+ this.cacheScope = cacheScope;
720
+ this.realtimeUp = realtimeUp;
721
+ this.positionHz = positionHz;
722
+ this.onEngineHealth = onEngineHealth;
723
+ this.logger = logger;
724
+ }
725
+ api;
726
+ hub;
727
+ cache;
728
+ outbox;
729
+ offline;
730
+ isOffline;
731
+ cacheScope;
732
+ realtimeUp;
733
+ positionHz;
734
+ onEngineHealth;
735
+ logger;
736
+ outboxOutcomes = new Emitter();
737
+ log(level, message, error) {
738
+ this.logger?.({ level, message, ...error === void 0 ? {} : { error } });
739
+ }
740
+ /** Read through the cache: fresh when reachable, `stale` copy when not (02f §7.4). */
741
+ async cachedRead(name, read, stale) {
742
+ const key = `${this.cacheScope()}/${name}`;
743
+ if (this.isOffline() && this.offline.staleReads) {
744
+ const c = await this.cache.read(key);
745
+ if (c) return stale(c.json, new Date(c.asOf));
746
+ throw new OfflineError(`${name}: offline and nothing cached`);
747
+ }
748
+ try {
749
+ const [value, json] = await read();
750
+ await this.cache.write(key, { json, asOf: (/* @__PURE__ */ new Date()).toISOString() });
751
+ return value;
752
+ } catch (e) {
753
+ if (!this.offline.staleReads || !isUnreachable(e)) throw e;
754
+ const c = await this.cache.read(key);
755
+ if (!c) throw e;
756
+ this.log("info", `${name} served from cache`);
757
+ return stale(c.json, new Date(c.asOf));
758
+ }
759
+ }
760
+ /** Idempotent write; queued in the outbox when unreachable (QueuedForReplayError). */
761
+ async idempotentWrite(op, o = {}) {
762
+ const ob = this.outbox;
763
+ const canQueue = ob !== void 0 && this.offline.queueWrites;
764
+ const queue = async () => {
765
+ const e = {
766
+ id: uuidV7(),
767
+ scope: this.cacheScope(),
768
+ operationId: op.id,
769
+ params: o.params ?? {},
770
+ headers: o.headers ?? {},
771
+ ...o.body !== void 0 ? { body: o.body } : {},
772
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
773
+ };
774
+ await ob.add(e);
775
+ throw new QueuedForReplayError(`${op.id} queued for replay after reconnect`, e.id);
776
+ };
777
+ if (this.isOffline() && canQueue) return queue();
778
+ try {
779
+ return await this.api.call(op, o);
780
+ } catch (e) {
781
+ if (canQueue && isUnreachable(e)) return queue();
782
+ throw e;
783
+ }
784
+ }
785
+ /** Replays the outbox in order; conflicts carry the latest server version (`latestOf`). */
786
+ async replayOutbox(latestOf) {
787
+ const ob = this.outbox;
788
+ if (!ob) return;
789
+ for (const e of await ob.list(this.cacheScope())) {
790
+ const op = import_protocol3.Operations[e.operationId];
791
+ if (!op) {
792
+ await ob.remove(e.id);
793
+ this.outboxOutcomes.emit({
794
+ entry: e,
795
+ error: new UnsupportedCapabilityError(`unknown operation ${e.operationId}`)
796
+ });
797
+ continue;
798
+ }
799
+ try {
800
+ const res = await this.api.call(op, {
801
+ params: e.params,
802
+ headers: e.headers,
803
+ body: e.body,
804
+ idempotencyKey: e.id
805
+ });
806
+ await ob.remove(e.id);
807
+ this.outboxOutcomes.emit({
808
+ entry: e,
809
+ status: res.status,
810
+ body: res.body.length ? res.json : void 0
811
+ });
812
+ } catch (err) {
813
+ if (isUnreachable(err)) return;
814
+ await ob.remove(e.id);
815
+ let error = err;
816
+ if (err instanceof ConflictError && latestOf) {
817
+ let latest;
818
+ try {
819
+ latest = await latestOf(e);
820
+ } catch {
821
+ latest = void 0;
822
+ }
823
+ error = new ConflictError(err.message, {
824
+ latest,
825
+ ...err.problem ? { problem: err.problem } : {},
826
+ ...err.code ? { code: err.code } : {}
827
+ });
828
+ }
829
+ this.outboxOutcomes.emit({ entry: e, error });
830
+ }
831
+ }
832
+ }
833
+ /**
834
+ * Watches a resource: initial read, then `resource` / `patch` events of [topic] (merge-patched), re-read after
835
+ * resync, polling every [intervalMs] while realtime is down. Returns the stop function.
836
+ */
837
+ watchResource(topic, fetch, obs, o = {}) {
838
+ let last;
839
+ let emitted = false;
840
+ let busy = false;
841
+ let again = false;
842
+ let stopped = false;
843
+ const emit = (v) => {
844
+ if (stopped) return;
845
+ if (emitted && JSON.stringify(v) === JSON.stringify(last)) return;
846
+ last = v;
847
+ emitted = true;
848
+ obs.next(v);
849
+ if (o.isFinal?.(v)) stop();
850
+ };
851
+ const read = async () => {
852
+ if (stopped) return;
853
+ if (busy) {
854
+ again = true;
855
+ return;
856
+ }
857
+ busy = true;
858
+ try {
859
+ emit(await fetch());
860
+ } catch (e) {
861
+ if (!stopped) obs.error?.(e);
862
+ } finally {
863
+ busy = false;
864
+ }
865
+ if (again) {
866
+ again = false;
867
+ await read();
868
+ }
869
+ };
870
+ const offEvents = this.hub.on([topic], (e) => {
871
+ if (o.kinds?.size && !o.kinds.has(e.kind)) return;
872
+ if (e.resource && typeof e.resource === "object") emit(e.resource);
873
+ else if (e.patch && emitted) emit((0, import_protocol3.jsonMergePatch)(last, e.patch));
874
+ });
875
+ const offSnap = this.hub.onSnapshot(topic, read);
876
+ void read();
877
+ const poll = setInterval(() => {
878
+ if (!this.realtimeUp()) void read();
879
+ }, o.intervalMs ?? 2e3);
880
+ poll.unref?.();
881
+ const stop = () => {
882
+ if (stopped) return;
883
+ stopped = true;
884
+ clearInterval(poll);
885
+ offSnap();
886
+ offEvents();
887
+ };
888
+ return stop;
889
+ }
890
+ close() {
891
+ this.outboxOutcomes.close();
892
+ }
893
+ };
894
+
895
+ // src/graphql.ts
896
+ var GRAPHQL_OPERATION = {
897
+ id: "graphql",
898
+ method: "POST",
899
+ path: "/graphql",
900
+ scope: "any",
901
+ tags: [],
902
+ params: [],
903
+ requestContentTypes: ["application/json"]
904
+ };
905
+ var GraphqlClient = class {
906
+ constructor(api) {
907
+ this.api = api;
908
+ }
909
+ api;
910
+ async query(document, variables = {}, operationName) {
911
+ const res = await this.api.call(GRAPHQL_OPERATION, {
912
+ body: {
913
+ query: document,
914
+ ...Object.keys(variables).length ? { variables } : {},
915
+ ...operationName ? { operationName } : {}
916
+ }
917
+ });
918
+ const j = res.json;
919
+ if (!j || typeof j !== "object")
920
+ throw new ServerError("graphql: response is not an object", { code: "internal" });
921
+ const first = j.errors?.[0];
922
+ if (first) {
923
+ const p = first.extensions?.problem;
924
+ if (p && typeof p === "object")
925
+ throw ApiCaller.errorOf(GRAPHQL_OPERATION, FreedomeResponse.json(p.status ?? 500, p));
926
+ throw new ServerError(`graphql: ${first.message ?? JSON.stringify(first)}`, {
927
+ code: "graphql"
928
+ });
929
+ }
930
+ return j.data ?? {};
931
+ }
932
+ };
933
+
934
+ // src/hub.ts
935
+ var import_protocol4 = require("@freedome/protocol");
936
+ var EventHub = class {
937
+ /** Resolves when the server acknowledged [filters]; `false` = no live channel, so nothing was acknowledged. */
938
+ onSubscribe;
939
+ onUnsubscribe;
940
+ refs = /* @__PURE__ */ new Map();
941
+ listeners = /* @__PURE__ */ new Set();
942
+ snapshots = /* @__PURE__ */ new Set();
943
+ last;
944
+ epoch;
945
+ /** Last seen `seq` (resume point). */
946
+ get lastSeq() {
947
+ return this.last;
948
+ }
949
+ /** Active filters. */
950
+ get filters() {
951
+ return [...this.refs.keys()];
952
+ }
953
+ /** Listens to events matching any of [filters]. */
954
+ on(filters, fn) {
955
+ const l = { filters: new Set(filters), fn };
956
+ this.listeners.add(l);
957
+ this.retain(l.filters);
958
+ let done = false;
959
+ return () => {
960
+ if (done) return;
961
+ done = true;
962
+ this.listeners.delete(l);
963
+ this.release(l.filters);
964
+ };
965
+ }
966
+ /** Registers a re-read for topics overlapping [filter] (after resync / restart / reconnect). */
967
+ onSnapshot(filter, fn) {
968
+ const e = { filter, fn };
969
+ this.snapshots.add(e);
970
+ return () => this.snapshots.delete(e);
971
+ }
972
+ retain(filters) {
973
+ const add = [];
974
+ for (const f of filters) {
975
+ const n = (this.refs.get(f) ?? 0) + 1;
976
+ this.refs.set(f, n);
977
+ if (n === 1) add.push(f);
978
+ }
979
+ if (!add.length) return;
980
+ void this.onSubscribe?.(add).then(
981
+ (acknowledged) => acknowledged === false ? void 0 : this.snapshot(add),
982
+ () => void 0
983
+ );
984
+ }
985
+ release(filters) {
986
+ const drop = [];
987
+ for (const f of filters) {
988
+ const n = (this.refs.get(f) ?? 1) - 1;
989
+ if (n <= 0) {
990
+ this.refs.delete(f);
991
+ drop.push(f);
992
+ } else this.refs.set(f, n);
993
+ }
994
+ if (drop.length) void this.onUnsubscribe?.(drop).catch(() => void 0);
995
+ }
996
+ /** Delivers an event (drops duplicates of a resume; a lower seq = server restart → snapshot everything). */
997
+ dispatch(e) {
998
+ const last = this.last;
999
+ if (last !== void 0 && e.seq < last) {
1000
+ this.last = e.seq;
1001
+ void this.snapshot(["#"]);
1002
+ } else if (last === void 0 || e.seq > last) {
1003
+ this.last = e.seq;
1004
+ } else return;
1005
+ for (const l of [...this.listeners]) {
1006
+ for (const f of l.filters) {
1007
+ if ((0, import_protocol4.topicMatches)(f, e.topic)) {
1008
+ l.fn(e);
1009
+ break;
1010
+ }
1011
+ }
1012
+ }
1013
+ }
1014
+ /** Seeds the resume point (from `GET /events` lastSeq) when none is known. */
1015
+ seed(lastSeq) {
1016
+ this.last ??= lastSeq;
1017
+ }
1018
+ /** Records the server instance; a different one → the seq space restarted. */
1019
+ newEpoch(serverId) {
1020
+ if (!serverId) return false;
1021
+ const changed = this.epoch !== void 0 && this.epoch !== serverId;
1022
+ this.epoch = serverId;
1023
+ if (changed) this.last = void 0;
1024
+ return changed;
1025
+ }
1026
+ /** Runs the snapshot handlers overlapping [topics]. */
1027
+ async snapshot(topics) {
1028
+ const ts = [...topics];
1029
+ const run = /* @__PURE__ */ new Set();
1030
+ for (const s of this.snapshots)
1031
+ if (ts.some((t) => t === "#" || overlap(s.filter, t))) run.add(s.fn);
1032
+ for (const fn of run) {
1033
+ try {
1034
+ await fn();
1035
+ } catch {
1036
+ }
1037
+ }
1038
+ }
1039
+ close() {
1040
+ this.listeners.clear();
1041
+ this.refs.clear();
1042
+ this.snapshots.clear();
1043
+ }
1044
+ };
1045
+ function overlap(a, b) {
1046
+ const x = a.split("/");
1047
+ const y = b.split("/");
1048
+ for (let i = 0; i < x.length && i < y.length; i++) {
1049
+ if (x[i] === "#" || y[i] === "#") return true;
1050
+ if (x[i] !== "+" && y[i] !== "+" && x[i] !== y[i]) return false;
1051
+ }
1052
+ return x.length === y.length;
1053
+ }
1054
+
1055
+ // src/offline.ts
1056
+ var DEFAULT_OFFLINE_POLICY = {
1057
+ staleReads: true,
1058
+ queueWrites: true,
1059
+ failAfterAttempts: 3
1060
+ };
1061
+ var InMemoryCacheStore = class {
1062
+ m = /* @__PURE__ */ new Map();
1063
+ async read(k) {
1064
+ return this.m.get(k);
1065
+ }
1066
+ async write(k, v) {
1067
+ this.m.set(k, v);
1068
+ }
1069
+ async delete(k) {
1070
+ this.m.delete(k);
1071
+ }
1072
+ };
1073
+ var InMemoryOutboxStore = class {
1074
+ q = [];
1075
+ async add(e) {
1076
+ this.q.push(e);
1077
+ }
1078
+ async list(scope) {
1079
+ return this.q.filter((e) => e.scope === scope);
1080
+ }
1081
+ async remove(id) {
1082
+ this.q = this.q.filter((e) => e.id !== id);
1083
+ }
1084
+ };
1085
+
1086
+ // src/realtime/channel.ts
1087
+ var isAuthFailure = (c) => c.code === 4401 || c.code === 4403;
1088
+
1089
+ // src/realtime/graphql-ws.ts
1090
+ var import_protocol5 = require("@freedome/protocol");
1091
+ var GRAPHQL_WS_SUBPROTOCOL = "graphql-transport-ws";
1092
+ var GRAPHQL_EVENTS_SUBSCRIPTION = "subscription Events($topics: [String!]!, $sinceSeq: Int) { events(topics: $topics, sinceSeq: $sinceSeq) { seq topic kind ts data } }";
1093
+ var GraphqlWsChannel = class _GraphqlWsChannel {
1094
+ constructor(socket, heartbeatMs, logger) {
1095
+ this.socket = socket;
1096
+ this.heartbeatMs = heartbeatMs;
1097
+ this.logger = logger;
1098
+ this.closed = new Promise((r) => this.resolveClosed = r);
1099
+ this.ack = new Promise((res, rej) => {
1100
+ this.ackResolve = res;
1101
+ this.ackReject = rej;
1102
+ });
1103
+ this.ack.catch(() => void 0);
1104
+ socket.listen(
1105
+ (t) => this.onFrame(t),
1106
+ (c, r) => this.onDone(c, r)
1107
+ );
1108
+ }
1109
+ socket;
1110
+ heartbeatMs;
1111
+ logger;
1112
+ kind = "graphqlWs";
1113
+ supportsCalls = false;
1114
+ welcome = void 0;
1115
+ events = new Emitter();
1116
+ resyncs = new Emitter();
1117
+ closed;
1118
+ resolveClosed;
1119
+ ackResolve;
1120
+ ackReject;
1121
+ ack;
1122
+ ops = /* @__PURE__ */ new Map();
1123
+ hb;
1124
+ lastSeen = Date.now();
1125
+ closing = false;
1126
+ acked = false;
1127
+ done = false;
1128
+ static async open(socket, hello, opts = {}) {
1129
+ const ch = new _GraphqlWsChannel(socket, opts.heartbeatMs ?? 15e3, opts.logger);
1130
+ ch.send({
1131
+ type: "connection_init",
1132
+ payload: {
1133
+ app: hello.app,
1134
+ ...hello.appVersion ? { appVersion: hello.appVersion } : {},
1135
+ ...hello.sdk ? { sdk: hello.sdk } : {},
1136
+ ...hello.token ? { token: hello.token } : {}
1137
+ }
1138
+ });
1139
+ const timeoutMs = opts.timeoutMs ?? 1e4;
1140
+ let timer;
1141
+ try {
1142
+ await Promise.race([
1143
+ ch.ack,
1144
+ new Promise((_, rej) => {
1145
+ timer = setTimeout(
1146
+ () => rej(new NetworkError(`graphql-ws: no connection_ack within ${timeoutMs} ms`)),
1147
+ timeoutMs
1148
+ );
1149
+ })
1150
+ ]);
1151
+ } catch (e) {
1152
+ await ch.close();
1153
+ throw e;
1154
+ } finally {
1155
+ clearTimeout(timer);
1156
+ }
1157
+ ch.startHeartbeat();
1158
+ return ch;
1159
+ }
1160
+ send(m) {
1161
+ this.socket.send(JSON.stringify(m));
1162
+ }
1163
+ onFrame(frame) {
1164
+ this.lastSeen = Date.now();
1165
+ let j;
1166
+ try {
1167
+ j = JSON.parse(frame);
1168
+ } catch {
1169
+ return;
1170
+ }
1171
+ switch (j.type) {
1172
+ case "connection_ack":
1173
+ this.acked = true;
1174
+ this.ackResolve();
1175
+ return;
1176
+ case "ping":
1177
+ this.send({ type: "pong" });
1178
+ return;
1179
+ case "next": {
1180
+ const payload = j.payload;
1181
+ const ev = payload?.data?.events;
1182
+ if (ev && typeof ev.seq === "number" && typeof ev.topic === "string" && typeof ev.kind === "string") {
1183
+ const data = {
1184
+ ...ev.data ?? {},
1185
+ seq: ev.seq,
1186
+ kind: ev.kind
1187
+ };
1188
+ const e = {
1189
+ id: uuidV7(),
1190
+ topic: ev.topic,
1191
+ seq: ev.seq,
1192
+ kind: ev.kind,
1193
+ ts: String(ev.ts ?? ""),
1194
+ data
1195
+ };
1196
+ if ("resource" in data) e.resource = data.resource;
1197
+ if (typeof data.patch === "object" && data.patch !== null)
1198
+ e.patch = data.patch;
1199
+ if (typeof data.revision === "number") e.revision = data.revision;
1200
+ this.events.emit(e);
1201
+ } else if (ev) {
1202
+ this.logger?.({ level: "warning", message: "graphql-ws: malformed event" });
1203
+ }
1204
+ if (payload?.errors?.length) this.onErrors(j.id, payload.errors);
1205
+ return;
1206
+ }
1207
+ case "error":
1208
+ this.onErrors(j.id, j.payload ?? []);
1209
+ return;
1210
+ case "complete": {
1211
+ const topics = this.ops.get(j.id);
1212
+ this.ops.delete(j.id);
1213
+ if (topics && !this.closing) this.resyncs.emit({ topics, reason: "complete" });
1214
+ return;
1215
+ }
1216
+ }
1217
+ }
1218
+ onErrors(id, errors) {
1219
+ const first = errors[0];
1220
+ const code = first?.extensions?.problem?.code;
1221
+ this.logger?.({
1222
+ level: "warning",
1223
+ message: `graphql-ws: subscription ${id} error ${code ?? JSON.stringify(first)}`
1224
+ });
1225
+ if (code === "resync" || code === "gap-too-old")
1226
+ this.resyncs.emit({ topics: this.ops.get(id) ?? ["#"], reason: code });
1227
+ }
1228
+ onDone(code, reason) {
1229
+ if (this.done) return;
1230
+ this.done = true;
1231
+ if (this.hb) clearInterval(this.hb);
1232
+ if (!this.acked) {
1233
+ this.ackReject(
1234
+ code === 4401 || code === 4403 ? new UnauthorizedError(`graphql-ws: ${reason ?? "unauthorized"}`) : new NetworkError(`graphql-ws closed during handshake (${code ?? "network"})`)
1235
+ );
1236
+ }
1237
+ this.resolveClosed({ code, reason, byServer: !this.closing });
1238
+ this.events.close();
1239
+ this.resyncs.close();
1240
+ }
1241
+ startHeartbeat() {
1242
+ this.lastSeen = Date.now();
1243
+ this.hb = setInterval(() => {
1244
+ if (Date.now() - this.lastSeen >= this.heartbeatMs * 2) {
1245
+ void this.close(import_protocol5.WsCloseCodes.heartbeatTimeout, "heartbeat timeout");
1246
+ return;
1247
+ }
1248
+ this.send({ type: "ping" });
1249
+ }, this.heartbeatMs);
1250
+ this.hb.unref?.();
1251
+ }
1252
+ async subscribe(topics, o = {}) {
1253
+ if (this.done) throw new NetworkError("graphql-ws session closed");
1254
+ const id = uuidV7();
1255
+ this.ops.set(id, topics);
1256
+ this.send({
1257
+ id,
1258
+ type: "subscribe",
1259
+ payload: {
1260
+ query: GRAPHQL_EVENTS_SUBSCRIPTION,
1261
+ variables: { topics, ...o.sinceSeq !== void 0 ? { sinceSeq: o.sinceSeq } : {} }
1262
+ }
1263
+ });
1264
+ return { topics };
1265
+ }
1266
+ async unsubscribe(topics) {
1267
+ for (const [id, t] of [...this.ops]) {
1268
+ if (t.every((x) => topics.includes(x))) {
1269
+ this.ops.delete(id);
1270
+ this.send({ id, type: "complete" });
1271
+ }
1272
+ }
1273
+ }
1274
+ call(op) {
1275
+ return Promise.reject(
1276
+ new UnsupportedCapabilityError(
1277
+ `graphql-ws carries no REST calls (${op}) \u2014 the client uses REST`
1278
+ )
1279
+ );
1280
+ }
1281
+ async close(code, reason) {
1282
+ if (this.closing) return;
1283
+ this.closing = true;
1284
+ if (this.hb) clearInterval(this.hb);
1285
+ try {
1286
+ this.socket.close(code ?? 1e3, reason);
1287
+ } catch {
1288
+ }
1289
+ this.onDone(code ?? 1e3, reason);
1290
+ }
1291
+ };
1292
+
1293
+ // src/realtime/socket.ts
1294
+ function webSocketConnector(impl) {
1295
+ return (endpoint, path, protocols, timeoutMs) => new Promise((resolve, reject) => {
1296
+ const Ctor = impl ?? globalThis.WebSocket;
1297
+ if (!Ctor) {
1298
+ reject(
1299
+ new NetworkError(
1300
+ "no WebSocket implementation (Node < 22: use createNodeTransports from @freedome/client/node)"
1301
+ )
1302
+ );
1303
+ return;
1304
+ }
1305
+ let ws;
1306
+ try {
1307
+ ws = new Ctor(`${endpoint.wsBase}${path}`, protocols);
1308
+ } catch (e) {
1309
+ reject(new NetworkError(`websocket: ${e.message}`, { cause: e }));
1310
+ return;
1311
+ }
1312
+ let settled = false;
1313
+ const timer = setTimeout(() => {
1314
+ if (settled) return;
1315
+ settled = true;
1316
+ try {
1317
+ ws.close();
1318
+ } catch {
1319
+ }
1320
+ reject(
1321
+ new RequestTimeoutError(`websocket ${path}: not open within ${timeoutMs} ms`, timeoutMs)
1322
+ );
1323
+ }, timeoutMs);
1324
+ let onMsg;
1325
+ let onClose;
1326
+ const buffered = [];
1327
+ ws.onmessage = (ev) => {
1328
+ const t = typeof ev.data === "string" ? ev.data : new TextDecoder().decode(ev.data);
1329
+ if (onMsg) onMsg(t);
1330
+ else buffered.push(t);
1331
+ };
1332
+ ws.onclose = (ev) => {
1333
+ clearTimeout(timer);
1334
+ if (!settled) {
1335
+ settled = true;
1336
+ reject(
1337
+ ev.code === 4401 || ev.code === 4403 ? new UnauthorizedError(`websocket ${path}: ${ev.reason || "unauthorized"}`) : new NetworkError(
1338
+ `websocket ${path} closed during handshake (${ev.code ?? "network"})`
1339
+ )
1340
+ );
1341
+ return;
1342
+ }
1343
+ onClose?.(ev.code, ev.reason || void 0);
1344
+ };
1345
+ ws.onerror = () => {
1346
+ };
1347
+ ws.onopen = () => {
1348
+ clearTimeout(timer);
1349
+ if (settled) return;
1350
+ settled = true;
1351
+ resolve({
1352
+ protocol: ws.protocol,
1353
+ send: (t) => ws.send(t),
1354
+ close: (code, reason) => ws.close(code ?? 1e3, reason),
1355
+ listen(m, c) {
1356
+ onMsg = m;
1357
+ onClose = c;
1358
+ for (const t of buffered.splice(0)) m(t);
1359
+ }
1360
+ });
1361
+ };
1362
+ });
1363
+ }
1364
+
1365
+ // src/realtime/socketio.ts
1366
+ var import_protocol6 = require("@freedome/protocol");
1367
+ var import_socket = require("socket.io-client");
1368
+
1369
+ // src/realtime/problem-error.ts
1370
+ function realtimeError(data, context) {
1371
+ const p = typeof data === "object" && data !== null ? { type: "about:blank", ...data } : { type: "about:blank" };
1372
+ return errorFromProblem(typeof p.status === "number" ? p.status : 500, p, context);
1373
+ }
1374
+
1375
+ // src/realtime/socketio.ts
1376
+ var SocketIoChannel = class _SocketIoChannel {
1377
+ constructor(socket, timeoutMs, logger) {
1378
+ this.socket = socket;
1379
+ this.timeoutMs = timeoutMs;
1380
+ this.logger = logger;
1381
+ this.closed = new Promise((r) => this.resolveClosed = r);
1382
+ }
1383
+ socket;
1384
+ timeoutMs;
1385
+ logger;
1386
+ kind = "socketIo";
1387
+ supportsCalls = true;
1388
+ welcome = void 0;
1389
+ events = new Emitter();
1390
+ resyncs = new Emitter();
1391
+ closed;
1392
+ resolveClosed;
1393
+ closing = false;
1394
+ done = false;
1395
+ static open(endpoint, hello, opts = {}) {
1396
+ const timeoutMs = opts.timeoutMs ?? 1e4;
1397
+ const s = (0, import_socket.io)(`${endpoint.baseUrl}/v1`, {
1398
+ path: "/socket.io/",
1399
+ transports: ["websocket"],
1400
+ auth: {
1401
+ app: hello.app,
1402
+ ...hello.appVersion ? { appVersion: hello.appVersion } : {},
1403
+ ...hello.sdk ? { sdk: hello.sdk } : {},
1404
+ ...hello.token ? { token: hello.token } : {}
1405
+ },
1406
+ autoConnect: false,
1407
+ forceNew: true,
1408
+ reconnection: false,
1409
+ timeout: timeoutMs
1410
+ });
1411
+ const ch = new _SocketIoChannel(s, timeoutMs, opts.logger);
1412
+ s.on("disconnect", (reason) => ch.finish(void 0, reason));
1413
+ s.on("event", (data) => {
1414
+ try {
1415
+ ch.events.emit((0, import_protocol6.eventFromMessage)((0, import_protocol6.parseWsMessage)(data)));
1416
+ } catch (e) {
1417
+ ch.logger?.({
1418
+ level: "warning",
1419
+ message: `socket.io: malformed event (${e.message})`
1420
+ });
1421
+ }
1422
+ });
1423
+ s.on("resync", (data) => {
1424
+ if (Array.isArray(data?.topics))
1425
+ ch.resyncs.emit({ topics: data.topics, reason: String(data.reason ?? "gap") });
1426
+ });
1427
+ return new Promise((resolve, reject) => {
1428
+ const timer = setTimeout(() => {
1429
+ s.disconnect();
1430
+ reject(new NetworkError(`socket.io: no connect within ${timeoutMs} ms`));
1431
+ }, timeoutMs);
1432
+ s.once("connect", () => {
1433
+ clearTimeout(timer);
1434
+ resolve(ch);
1435
+ });
1436
+ s.once("connect_error", (e) => {
1437
+ clearTimeout(timer);
1438
+ s.disconnect();
1439
+ reject(
1440
+ String(e?.message).includes("unauthenticated") ? new UnauthorizedError(`socket.io: ${e.message}`) : new NetworkError(`socket.io connect failed: ${e?.message ?? e}`, { cause: e })
1441
+ );
1442
+ });
1443
+ s.connect();
1444
+ });
1445
+ }
1446
+ finish(code, reason) {
1447
+ if (this.done) return;
1448
+ this.done = true;
1449
+ this.resolveClosed({ code, reason, byServer: !this.closing });
1450
+ this.events.close();
1451
+ this.resyncs.close();
1452
+ }
1453
+ emitAck(event, data, timeoutMs) {
1454
+ if (this.done) return Promise.reject(new NetworkError("socket.io session closed"));
1455
+ const t = timeoutMs ?? this.timeoutMs;
1456
+ return new Promise((resolve, reject) => {
1457
+ const timer = setTimeout(
1458
+ () => reject(new RequestTimeoutError(`socket.io ${event}: no ack within ${t} ms`, t)),
1459
+ t
1460
+ );
1461
+ this.socket.emit(event, data, (...args) => {
1462
+ clearTimeout(timer);
1463
+ const [err, result] = args.length === 1 && Array.isArray(args[0]) ? args[0] : args;
1464
+ if (err !== null && err !== void 0) reject(realtimeError(err, `socket.io ${event}`));
1465
+ else resolve(result);
1466
+ });
1467
+ });
1468
+ }
1469
+ async subscribe(topics, o = {}) {
1470
+ const r = await this.emitAck("subscribe", {
1471
+ topics,
1472
+ ...o.sinceSeq !== void 0 ? { sinceSeq: o.sinceSeq } : {},
1473
+ ...o.positionHz !== void 0 ? { options: { positionHz: o.positionHz } } : {}
1474
+ });
1475
+ return typeof r === "object" && r !== null ? r : { topics };
1476
+ }
1477
+ async unsubscribe(topics) {
1478
+ await this.emitAck("unsubscribe", { topics });
1479
+ }
1480
+ async call(op, o) {
1481
+ const r = await this.emitAck(
1482
+ "call",
1483
+ {
1484
+ op,
1485
+ ...o.params && Object.keys(o.params).length ? { params: o.params } : {},
1486
+ ...o.body !== void 0 ? { body: o.body } : {},
1487
+ ...o.ifMatch ? { ifMatch: o.ifMatch } : {},
1488
+ ...o.id ? { id: o.id } : {}
1489
+ },
1490
+ o.timeoutMs
1491
+ );
1492
+ return { status: r?.status ?? 200, body: r?.body, ...r?.etag ? { etag: r.etag } : {} };
1493
+ }
1494
+ async close() {
1495
+ if (this.closing) return;
1496
+ this.closing = true;
1497
+ this.socket.disconnect();
1498
+ this.finish(1e3, "closed by client");
1499
+ }
1500
+ };
1501
+
1502
+ // src/realtime/ws.ts
1503
+ var import_protocol7 = require("@freedome/protocol");
1504
+ var WsChannel = class _WsChannel {
1505
+ constructor(socket, heartbeatMs, timeoutMs, logger) {
1506
+ this.socket = socket;
1507
+ this.heartbeatMs = heartbeatMs;
1508
+ this.timeoutMs = timeoutMs;
1509
+ this.logger = logger;
1510
+ this.closed = new Promise((r) => this.resolveClosed = r);
1511
+ socket.listen(
1512
+ (t) => this.onFrame(t),
1513
+ (code, reason) => this.onDone(code, reason)
1514
+ );
1515
+ }
1516
+ socket;
1517
+ heartbeatMs;
1518
+ timeoutMs;
1519
+ logger;
1520
+ kind = "ws";
1521
+ supportsCalls = true;
1522
+ events = new Emitter();
1523
+ resyncs = new Emitter();
1524
+ closed;
1525
+ welcome;
1526
+ resolveClosed;
1527
+ pending = /* @__PURE__ */ new Map();
1528
+ hb;
1529
+ lastSeen = Date.now();
1530
+ closing = false;
1531
+ done = false;
1532
+ bye;
1533
+ /** Sends `hello`, waits for `welcome`, starts the heartbeat. */
1534
+ static async open(socket, hello, opts = {}) {
1535
+ const ch = new _WsChannel(
1536
+ socket,
1537
+ opts.heartbeatMs ?? 15e3,
1538
+ opts.timeoutMs ?? 1e4,
1539
+ opts.logger
1540
+ );
1541
+ const id = uuidV7();
1542
+ const reply = ch.expect(id, ch.timeoutMs);
1543
+ ch.sendMsg(
1544
+ import_protocol7.MessageTypes.hello,
1545
+ {
1546
+ app: hello.app,
1547
+ ...hello.appVersion ? { appVersion: hello.appVersion } : {},
1548
+ ...hello.sdk ? { sdk: hello.sdk } : {},
1549
+ ...hello.token ? { token: hello.token } : {},
1550
+ ...hello.sinceSeq !== void 0 ? { resume: { sinceSeq: hello.sinceSeq } } : {}
1551
+ },
1552
+ { id }
1553
+ );
1554
+ let m;
1555
+ try {
1556
+ m = await reply;
1557
+ } catch (e) {
1558
+ await ch.close();
1559
+ throw e;
1560
+ }
1561
+ if (m.type !== import_protocol7.MessageTypes.welcome) {
1562
+ await ch.close();
1563
+ throw new NetworkError(`expected welcome, got ${m.type}`);
1564
+ }
1565
+ if (typeof m.data !== "object" || m.data === null) {
1566
+ await ch.close();
1567
+ throw new ServerError("welcome does not match the contract", { code: "internal" });
1568
+ }
1569
+ const d = m.data;
1570
+ const server = d.server ?? {};
1571
+ ch.welcome = {
1572
+ ...d,
1573
+ ...typeof server.instanceId === "string" ? { instanceId: server.instanceId } : {},
1574
+ ...typeof d.heartbeatSec === "number" ? { heartbeatSec: d.heartbeatSec } : {}
1575
+ };
1576
+ ch.startHeartbeat();
1577
+ return ch;
1578
+ }
1579
+ log(level, message) {
1580
+ this.logger?.({ level, message: `ws: ${message}` });
1581
+ }
1582
+ onFrame(frame) {
1583
+ this.lastSeen = Date.now();
1584
+ let m;
1585
+ try {
1586
+ m = (0, import_protocol7.parseWsMessage)(JSON.parse(frame));
1587
+ } catch (e) {
1588
+ this.log("warning", `dropping malformed frame (${e.message})`);
1589
+ return;
1590
+ }
1591
+ switch (m.type) {
1592
+ case import_protocol7.MessageTypes.event:
1593
+ try {
1594
+ this.events.emit((0, import_protocol7.eventFromMessage)(m));
1595
+ } catch (e) {
1596
+ this.log("warning", `malformed event (${e.message})`);
1597
+ }
1598
+ return;
1599
+ case import_protocol7.MessageTypes.resync: {
1600
+ const d = m.data;
1601
+ if (Array.isArray(d?.topics))
1602
+ this.resyncs.emit({ topics: d.topics, reason: String(d.reason ?? "gap") });
1603
+ return;
1604
+ }
1605
+ case import_protocol7.MessageTypes.ping:
1606
+ this.sendMsg(import_protocol7.MessageTypes.pong, {}, { replyTo: m.id });
1607
+ return;
1608
+ case import_protocol7.MessageTypes.bye: {
1609
+ const d = m.data ?? {};
1610
+ this.bye = d;
1611
+ this.log("info", `server says bye: ${d.reason ?? ""}`);
1612
+ return;
1613
+ }
1614
+ default: {
1615
+ const p = m.replyTo ? this.pending.get(m.replyTo) : void 0;
1616
+ if (p) {
1617
+ this.pending.delete(m.replyTo);
1618
+ clearTimeout(p.timer);
1619
+ if (m.type === import_protocol7.MessageTypes.error) p.reject(realtimeError(m.data, "realtime"));
1620
+ else p.resolve(m);
1621
+ } else if (m.type === import_protocol7.MessageTypes.error) {
1622
+ this.log("warning", `unsolicited error: ${JSON.stringify(m.data)}`);
1623
+ }
1624
+ }
1625
+ }
1626
+ }
1627
+ onDone(code, reason) {
1628
+ if (this.done) return;
1629
+ this.done = true;
1630
+ if (this.hb) clearInterval(this.hb);
1631
+ const rec = {
1632
+ code: this.bye?.code ?? code ?? (this.bye ? 1e3 : void 0),
1633
+ reason: this.bye?.reason ?? reason,
1634
+ byServer: !this.closing
1635
+ };
1636
+ const auth = rec.code === import_protocol7.WsCloseCodes.unauthenticated || rec.code === import_protocol7.WsCloseCodes.forbidden;
1637
+ for (const p of this.pending.values()) {
1638
+ clearTimeout(p.timer);
1639
+ p.reject(
1640
+ auth ? new UnauthorizedError(`realtime session closed: ${rec.reason ?? ""}`) : new NetworkError(
1641
+ `realtime session closed (${rec.code ?? "network"}${rec.reason ? ` ${rec.reason}` : ""})`
1642
+ )
1643
+ );
1644
+ }
1645
+ this.pending.clear();
1646
+ this.resolveClosed(rec);
1647
+ this.events.close();
1648
+ this.resyncs.close();
1649
+ }
1650
+ startHeartbeat() {
1651
+ let every = this.heartbeatMs;
1652
+ const s = this.welcome?.heartbeatSec;
1653
+ if (typeof s === "number" && s > 0 && s * 1e3 < every) every = s * 1e3;
1654
+ this.lastSeen = Date.now();
1655
+ this.hb = setInterval(() => {
1656
+ if (Date.now() - this.lastSeen >= every * 2) {
1657
+ this.log("warning", "two heartbeats missed \u2014 closing");
1658
+ void this.close(import_protocol7.WsCloseCodes.heartbeatTimeout, "heartbeat timeout");
1659
+ return;
1660
+ }
1661
+ this.sendMsg(import_protocol7.MessageTypes.ping, {});
1662
+ }, every);
1663
+ this.hb.unref?.();
1664
+ }
1665
+ sendMsg(type, data, o = {}) {
1666
+ const m = {
1667
+ type,
1668
+ id: o.id ?? uuidV7(),
1669
+ ts: (0, import_protocol7.rfc3339Millis)(),
1670
+ ...o.topic ? { topic: o.topic } : {},
1671
+ ...o.replyTo ? { replyTo: o.replyTo } : {},
1672
+ data
1673
+ };
1674
+ this.socket.send(JSON.stringify(m));
1675
+ }
1676
+ expect(id, timeoutMs) {
1677
+ return new Promise((resolve, reject) => {
1678
+ const timer = setTimeout(() => {
1679
+ this.pending.delete(id);
1680
+ reject(new RequestTimeoutError(`realtime: no reply within ${timeoutMs} ms`, timeoutMs));
1681
+ }, timeoutMs);
1682
+ this.pending.set(id, { resolve, reject, timer });
1683
+ });
1684
+ }
1685
+ request(type, data, id, timeoutMs) {
1686
+ if (this.done) return Promise.reject(new NetworkError("realtime session closed"));
1687
+ const mid = id ?? uuidV7();
1688
+ const f = this.expect(mid, timeoutMs ?? this.timeoutMs);
1689
+ this.sendMsg(type, data, { id: mid });
1690
+ return f;
1691
+ }
1692
+ async subscribe(topics, o = {}) {
1693
+ const m = await this.request(import_protocol7.MessageTypes.subscribe, {
1694
+ topics,
1695
+ ...o.sinceSeq !== void 0 ? { sinceSeq: o.sinceSeq } : {},
1696
+ ...o.positionHz !== void 0 ? { options: { positionHz: o.positionHz } } : {}
1697
+ });
1698
+ const body = m.data?.body;
1699
+ return typeof body === "object" && body !== null ? body : { topics };
1700
+ }
1701
+ async unsubscribe(topics) {
1702
+ await this.request(import_protocol7.MessageTypes.unsubscribe, { topics });
1703
+ }
1704
+ async call(op, o) {
1705
+ const m = await this.request(
1706
+ import_protocol7.MessageTypes.call,
1707
+ {
1708
+ op,
1709
+ ...o.params && Object.keys(o.params).length ? { params: o.params } : {},
1710
+ ...o.body !== void 0 ? { body: o.body } : {},
1711
+ ...o.ifMatch ? { ifMatch: o.ifMatch } : {}
1712
+ },
1713
+ o.id,
1714
+ o.timeoutMs
1715
+ );
1716
+ const d = m.data ?? {};
1717
+ return { status: d.status ?? 200, body: d.body, ...d.etag ? { etag: d.etag } : {} };
1718
+ }
1719
+ async close(code, reason) {
1720
+ if (this.closing) return;
1721
+ this.closing = true;
1722
+ if (this.hb) clearInterval(this.hb);
1723
+ try {
1724
+ this.socket.close(code ?? 1e3, reason);
1725
+ } catch {
1726
+ }
1727
+ this.onDone(code ?? 1e3, reason);
1728
+ }
1729
+ };
1730
+
1731
+ // src/repositories/audio-reactive.ts
1732
+ var import_protocol8 = require("@freedome/protocol");
1733
+ var AudioReactiveRepository = class _AudioReactiveRepository {
1734
+ constructor(c, venueId = "default") {
1735
+ this.c = c;
1736
+ this.venueId = venueId;
1737
+ }
1738
+ c;
1739
+ venueId;
1740
+ venues = /* @__PURE__ */ new Map();
1741
+ get v() {
1742
+ return { venueId: this.venueId };
1743
+ }
1744
+ /** The same repository for another venue. */
1745
+ venue(id) {
1746
+ if (id === this.venueId) return this;
1747
+ let r = this.venues.get(id);
1748
+ if (!r) {
1749
+ r = new _AudioReactiveRepository(this.c, id);
1750
+ this.venues.set(id, r);
1751
+ }
1752
+ return r;
1753
+ }
1754
+ // ---- analysis ----
1755
+ /** Analysed inputs and whether the audio engine runs them. */
1756
+ analysis() {
1757
+ return this.c.api.json(import_protocol8.Operations.getAudioAnalysis, { params: this.v });
1758
+ }
1759
+ /**
1760
+ * Replaces the inputs and starts or stops the analysis (scope `audio:control`; live control, never queued offline).
1761
+ * 503 `engine-unavailable` when the audio engine cannot be reached.
1762
+ */
1763
+ setAnalysis(settings) {
1764
+ return this.c.api.json(import_protocol8.Operations.setAudioAnalysis, {
1765
+ params: this.v,
1766
+ body: settings
1767
+ });
1768
+ }
1769
+ /** Follows the analysis state (polled every [intervalMs] only while realtime is down). */
1770
+ analysisStates(obs, o = {}) {
1771
+ return this.c.watchResource(
1772
+ import_protocol8.DomeTopics.audioAnalysis(this.venueId),
1773
+ () => this.analysis(),
1774
+ obs,
1775
+ { intervalMs: o.intervalMs ?? 2e3, kinds: /* @__PURE__ */ new Set([import_protocol8.EventKinds.audioAnalysisState]) }
1776
+ );
1777
+ }
1778
+ /**
1779
+ * Analysis frames of [inputId], or of every input (server default 15 Hz). Events only: nothing arrives while realtime
1780
+ * is down, and the ring buffer does not keep frames, so a gap is not replayed.
1781
+ */
1782
+ frames(fn, o = {}) {
1783
+ return this.decoded(
1784
+ o.inputId === void 0 ? `${import_protocol8.DomeTopics.audioAnalysis(this.venueId)}/+` : import_protocol8.DomeTopics.audioAnalysisInput(o.inputId, this.venueId),
1785
+ import_protocol8.EventKinds.audioAnalysis,
1786
+ fn
1787
+ );
1788
+ }
1789
+ /** Detected attacks of [inputId], or of every input. */
1790
+ onsets(fn, o = {}) {
1791
+ return this.decoded(
1792
+ o.inputId === void 0 ? `${import_protocol8.DomeTopics.audio(this.venueId)}/onsets/+` : import_protocol8.DomeTopics.audioOnsets(o.inputId, this.venueId),
1793
+ import_protocol8.EventKinds.audioOnset,
1794
+ fn
1795
+ );
1796
+ }
1797
+ // ---- AudioReactive service ----
1798
+ /** Active scene, master intensity, service status. */
1799
+ get() {
1800
+ return this.c.api.json(import_protocol8.Operations.getAudioReactive, { params: this.v });
1801
+ }
1802
+ /** Follows the state (polled every [intervalMs] only while realtime is down). */
1803
+ states(obs, o = {}) {
1804
+ return this.c.watchResource(import_protocol8.DomeTopics.audioReactive(this.venueId), () => this.get(), obs, {
1805
+ intervalMs: o.intervalMs ?? 2e3,
1806
+ kinds: /* @__PURE__ */ new Set([import_protocol8.EventKinds.audioReactiveState])
1807
+ });
1808
+ }
1809
+ /**
1810
+ * Selects a scene, enables the service or sets the intensity (scope `playback:control`; next frame). `activeSceneId:
1811
+ * null` stops the running scene. 422 for an unknown scene or one whose gateway or input does not exist.
1812
+ */
1813
+ update(o) {
1814
+ return this.c.api.json(import_protocol8.Operations.patchAudioReactive, {
1815
+ params: this.v,
1816
+ body: o
1817
+ });
1818
+ }
1819
+ // ---- scenes ----
1820
+ /** Scenes stored for this venue. */
1821
+ scenes() {
1822
+ return readAllPages(this.c.api, import_protocol8.Operations.listAudioReactiveScenes, {
1823
+ params: this.v
1824
+ });
1825
+ }
1826
+ /** One scene with its ETag. */
1827
+ async scene(sceneId) {
1828
+ const res = await this.c.api.call(import_protocol8.Operations.getAudioReactiveScene, {
1829
+ params: { ...this.v, sceneId }
1830
+ });
1831
+ return {
1832
+ value: ApiCaller.decodeBody(import_protocol8.Operations.getAudioReactiveScene, res),
1833
+ etag: res.headers.etag
1834
+ };
1835
+ }
1836
+ /**
1837
+ * Stores a scene (scope `content:write`): with [ifMatch] it replaces that revision, without it the scene must be
1838
+ * new (`If-None-Match: *`).
1839
+ */
1840
+ async saveScene(sceneId, input, o = {}) {
1841
+ const res = await this.c.api.call(import_protocol8.Operations.putAudioReactiveScene, {
1842
+ params: { ...this.v, sceneId },
1843
+ body: input,
1844
+ headers: o.ifMatch === void 0 ? { "if-none-match": "*" } : { "if-match": o.ifMatch }
1845
+ });
1846
+ return {
1847
+ value: ApiCaller.decodeBody(import_protocol8.Operations.putAudioReactiveScene, res),
1848
+ etag: res.headers.etag
1849
+ };
1850
+ }
1851
+ /** Removes a scene ([ifMatch] read when absent). 409 while it is active. */
1852
+ async deleteScene(sceneId, o = {}) {
1853
+ const etag = o.ifMatch ?? (await this.scene(sceneId)).etag;
1854
+ await this.c.api.call(import_protocol8.Operations.deleteAudioReactiveScene, {
1855
+ params: { ...this.v, sceneId },
1856
+ headers: { "if-match": etag }
1857
+ });
1858
+ }
1859
+ // ---- texture sources ----
1860
+ /** Senders the engines of this venue can see. To show one, register a `stream` asset with the matching `src`. */
1861
+ textureSources() {
1862
+ return readAllPages(this.c.api, import_protocol8.Operations.listTextureSources, {
1863
+ params: this.v
1864
+ });
1865
+ }
1866
+ /** Changes of any texture source of this venue (events only). */
1867
+ textureSourceChanges(fn) {
1868
+ return this.decoded(
1869
+ `${import_protocol8.DomeTopics.venue(this.venueId)}/texture-sources/+`,
1870
+ import_protocol8.EventKinds.textureSourceState,
1871
+ fn
1872
+ );
1873
+ }
1874
+ /** `resource` of the [kind] events of [filter]; events without one are skipped. */
1875
+ decoded(filter, kind, fn) {
1876
+ return this.c.hub.on([filter], (e) => {
1877
+ if (e.kind === kind && e.resource && typeof e.resource === "object") fn(e.resource);
1878
+ });
1879
+ }
1880
+ };
1881
+
1882
+ // src/repositories/audio.ts
1883
+ var import_protocol9 = require("@freedome/protocol");
1884
+ var ENDED = /* @__PURE__ */ new Set(["finished", "stopped", "failed"]);
1885
+ function audioSessionEnded(status) {
1886
+ return ENDED.has(String(status));
1887
+ }
1888
+ var AudioRepository = class _AudioRepository {
1889
+ constructor(c, venueId = "default") {
1890
+ this.c = c;
1891
+ this.venueId = venueId;
1892
+ }
1893
+ c;
1894
+ venueId;
1895
+ venues = /* @__PURE__ */ new Map();
1896
+ /** @internal */
1897
+ get ctx() {
1898
+ return this.c;
1899
+ }
1900
+ get v() {
1901
+ return { venueId: this.venueId };
1902
+ }
1903
+ /** The same repository for another venue. */
1904
+ venue(id) {
1905
+ if (id === this.venueId) return this;
1906
+ let r = this.venues.get(id);
1907
+ if (!r) {
1908
+ r = new _AudioRepository(this.c, id);
1909
+ this.venues.set(id, r);
1910
+ }
1911
+ return r;
1912
+ }
1913
+ // ---- state ----
1914
+ /** Mode, master gain / mute, engine status. */
1915
+ get() {
1916
+ return this.c.api.json(import_protocol9.Operations.getAudio, { params: this.v });
1917
+ }
1918
+ /**
1919
+ * Follows the audio state: `audio.state` events of `venues/{v}/audio`, re-read after resync, polled every
1920
+ * [intervalMs] only while realtime is down. Returns the stop function.
1921
+ */
1922
+ state(obs, o = {}) {
1923
+ return this.c.watchResource(import_protocol9.DomeTopics.audio(this.venueId), () => this.get(), obs, {
1924
+ intervalMs: o.intervalMs ?? 2e3,
1925
+ kinds: /* @__PURE__ */ new Set([import_protocol9.EventKinds.audioState])
1926
+ });
1927
+ }
1928
+ /** Changes mode / master gain / mute (live control, scope `audio:control`; never queued offline). */
1929
+ setMaster(o) {
1930
+ const body = {};
1931
+ if (o.masterGainDb !== void 0) body.masterGainDb = o.masterGainDb;
1932
+ if (o.mute !== void 0) body.mute = o.mute;
1933
+ if (o.mode !== void 0) body.mode = o.mode;
1934
+ return this.c.api.json(import_protocol9.Operations.patchAudio, {
1935
+ params: this.v,
1936
+ body,
1937
+ preferRealtime: true
1938
+ });
1939
+ }
1940
+ /**
1941
+ * Meters (`audio.levels` of `venues/{v}/audio/levels`, server rate ≤ 10 Hz), decimated here to at most [maxHz]:
1942
+ * intermediate values are dropped, the latest one is always delivered at the end of the window.
1943
+ */
1944
+ levels(fn, o = {}) {
1945
+ const windowMs = 1e3 / Math.max(1e-3, o.maxHz ?? 10);
1946
+ let lastSent;
1947
+ let pending;
1948
+ let timer;
1949
+ let stopped = false;
1950
+ const flush = () => {
1951
+ timer = void 0;
1952
+ const p = pending;
1953
+ if (!p || stopped) return;
1954
+ pending = void 0;
1955
+ lastSent = Date.now();
1956
+ fn(p);
1957
+ };
1958
+ const off = this.c.hub.on([import_protocol9.DomeTopics.audioLevels(this.venueId)], (e) => {
1959
+ if (e.kind !== import_protocol9.EventKinds.audioLevels) return;
1960
+ const l = e.resource?.levels;
1961
+ if (!l || typeof l !== "object") return;
1962
+ const next = {};
1963
+ for (const [k, x] of Object.entries(l))
1964
+ if (typeof x === "number") next[k] = x;
1965
+ pending = next;
1966
+ const since = lastSent === void 0 ? windowMs : Date.now() - lastSent;
1967
+ if (since >= windowMs) {
1968
+ if (timer) clearTimeout(timer);
1969
+ flush();
1970
+ } else timer ??= setTimeout(flush, windowMs - since);
1971
+ });
1972
+ return () => {
1973
+ if (stopped) return;
1974
+ stopped = true;
1975
+ if (timer) clearTimeout(timer);
1976
+ off();
1977
+ };
1978
+ }
1979
+ // ---- layout ----
1980
+ /** Speaker layout with its ETag. */
1981
+ async layout() {
1982
+ const res = await this.c.api.call(import_protocol9.Operations.getSpeakerLayout, { params: this.v });
1983
+ return {
1984
+ value: ApiCaller.decodeBody(import_protocol9.Operations.getSpeakerLayout, res),
1985
+ etag: res.headers.etag
1986
+ };
1987
+ }
1988
+ /** Replaces the speaker layout (scope `venues:write`; [ifMatch] = ETag of [layout], read when absent). */
1989
+ async saveLayout(layout, o = {}) {
1990
+ const etag = o.ifMatch ?? (await this.layout()).etag;
1991
+ const res = await this.c.api.call(import_protocol9.Operations.putSpeakerLayout, {
1992
+ params: this.v,
1993
+ body: layout,
1994
+ headers: { "if-match": etag }
1995
+ });
1996
+ return {
1997
+ value: ApiCaller.decodeBody(import_protocol9.Operations.putSpeakerLayout, res),
1998
+ etag: res.headers.etag
1999
+ };
2000
+ }
2001
+ // ---- zones ----
2002
+ /** Zones of the venue. */
2003
+ zones() {
2004
+ return readAllPages(this.c.api, import_protocol9.Operations.listAudioZones, { params: this.v });
2005
+ }
2006
+ /** One zone. */
2007
+ zone(zoneId) {
2008
+ return this.c.api.json(import_protocol9.Operations.getAudioZone, {
2009
+ params: { ...this.v, zoneId }
2010
+ });
2011
+ }
2012
+ /** Zone gain in dB (live control). */
2013
+ setZoneGain(zoneId, db) {
2014
+ return this.patchZone(zoneId, { gainDb: db });
2015
+ }
2016
+ /** Mutes / unmutes a zone (live control). */
2017
+ setMute(zoneId, muted) {
2018
+ return this.patchZone(zoneId, { mute: muted });
2019
+ }
2020
+ /** Merge-patches a zone (gain, delay, EQ, mute, speakers; live control). */
2021
+ patchZone(zoneId, patch) {
2022
+ return this.c.api.json(import_protocol9.Operations.patchAudioZone, {
2023
+ params: { ...this.v, zoneId },
2024
+ body: patch,
2025
+ preferRealtime: true
2026
+ });
2027
+ }
2028
+ /** Creates ([ifMatch] absent → `If-None-Match: *`) or replaces a zone. */
2029
+ saveZone(zoneId, body, o = {}) {
2030
+ return this.c.api.json(import_protocol9.Operations.putAudioZone, {
2031
+ params: { ...this.v, zoneId },
2032
+ body,
2033
+ headers: o.ifMatch ? { "if-match": o.ifMatch } : { "if-none-match": "*" }
2034
+ });
2035
+ }
2036
+ /** Deletes a zone ([ifMatch] = `"r<revision>"`, read when absent). */
2037
+ async deleteZone(zoneId, o = {}) {
2038
+ const etag = o.ifMatch ?? `"r${(await this.zone(zoneId)).revision}"`;
2039
+ await this.c.api.call(import_protocol9.Operations.deleteAudioZone, {
2040
+ params: { ...this.v, zoneId },
2041
+ headers: { "if-match": etag }
2042
+ });
2043
+ }
2044
+ /** Follows a zone (`zone.state` merge patches applied); stops after `zone.deleted` (`obs.deleted` is called). */
2045
+ zoneState(zoneId, obs, o = {}) {
2046
+ const topic = import_protocol9.DomeTopics.audioZone(zoneId, this.venueId);
2047
+ const stop = this.c.watchResource(topic, () => this.zone(zoneId), obs, {
2048
+ intervalMs: o.intervalMs ?? 2e3,
2049
+ kinds: /* @__PURE__ */ new Set([import_protocol9.EventKinds.zoneState])
2050
+ });
2051
+ const offDeleted = this.c.hub.on([topic], (e) => {
2052
+ if (e.kind !== import_protocol9.EventKinds.zoneDeleted) return;
2053
+ done();
2054
+ obs.deleted?.();
2055
+ });
2056
+ const done = () => {
2057
+ stop();
2058
+ offDeleted();
2059
+ };
2060
+ return done;
2061
+ }
2062
+ // ---- devices ----
2063
+ /** Audio devices (speakers, amps, microphones, QRD hubs, Patefon units …), optionally of one [kind]. */
2064
+ async devices(o = {}) {
2065
+ const all = await readAllPages(this.c.api, import_protocol9.Operations.listAudioDevices, {
2066
+ params: this.v,
2067
+ query: { kind: o.kind }
2068
+ });
2069
+ return o.kind === void 0 ? all : all.filter((d) => d.kind === o.kind);
2070
+ }
2071
+ /** One device. */
2072
+ device(deviceId) {
2073
+ return this.c.api.json(import_protocol9.Operations.getAudioDevice, {
2074
+ params: { ...this.v, deviceId }
2075
+ });
2076
+ }
2077
+ /** Operator gain / mute / name / config of a device. */
2078
+ patchDevice(deviceId, patch) {
2079
+ return this.c.api.json(import_protocol9.Operations.patchAudioDevice, {
2080
+ params: { ...this.v, deviceId },
2081
+ body: patch
2082
+ });
2083
+ }
2084
+ /** Ping / tone / self-test / strike of a device. */
2085
+ testDevice(deviceId, test = { kind: "ping" }) {
2086
+ return this.c.api.json(import_protocol9.Operations.testAudioDevice, {
2087
+ params: { ...this.v, deviceId },
2088
+ body: test
2089
+ });
2090
+ }
2091
+ /** Follows a device (`audioDevice.state`, telemetry patches ≤ 1 Hz). */
2092
+ deviceState(deviceId, obs, o = {}) {
2093
+ return this.c.watchResource(
2094
+ import_protocol9.DomeTopics.audioDevice(deviceId, this.venueId),
2095
+ () => this.device(deviceId),
2096
+ obs,
2097
+ { intervalMs: o.intervalMs ?? 2e3, kinds: /* @__PURE__ */ new Set([import_protocol9.EventKinds.audioDeviceState]) }
2098
+ );
2099
+ }
2100
+ // ---- presets ----
2101
+ /** Installed presets (summaries). */
2102
+ presets() {
2103
+ return readAllPages(this.c.api, import_protocol9.Operations.listAudioPresets, {
2104
+ params: this.v
2105
+ });
2106
+ }
2107
+ /** One preset with its document and ETag. */
2108
+ async preset(presetId) {
2109
+ const res = await this.c.api.call(import_protocol9.Operations.getAudioPreset, {
2110
+ params: { ...this.v, presetId }
2111
+ });
2112
+ return {
2113
+ value: ApiCaller.decodeBody(import_protocol9.Operations.getAudioPreset, res),
2114
+ etag: res.headers.etag
2115
+ };
2116
+ }
2117
+ /**
2118
+ * Installs / replaces an ananta/1.0 programme, pattern or session document (scope `content:write`). Without
2119
+ * [ifMatch] an existing preset is overwritten (last writer wins).
2120
+ */
2121
+ async savePreset(presetId, input, o = {}) {
2122
+ const res = await this.c.api.call(import_protocol9.Operations.putAudioPreset, {
2123
+ params: { ...this.v, presetId },
2124
+ body: input,
2125
+ headers: { "if-match": o.ifMatch }
2126
+ });
2127
+ return {
2128
+ value: ApiCaller.decodeBody(import_protocol9.Operations.putAudioPreset, res),
2129
+ etag: res.headers.etag
2130
+ };
2131
+ }
2132
+ /** Removes a preset ([ifMatch] read when absent). */
2133
+ async deletePreset(presetId, o = {}) {
2134
+ const etag = o.ifMatch ?? (await this.preset(presetId)).etag;
2135
+ await this.c.api.call(import_protocol9.Operations.deleteAudioPreset, {
2136
+ params: { ...this.v, presetId },
2137
+ headers: { "if-match": etag }
2138
+ });
2139
+ }
2140
+ // ---- sessions ----
2141
+ /** Runs an installed preset (live control). */
2142
+ startSession(s) {
2143
+ const body = { presetId: s.presetId };
2144
+ if (s.gainDb !== void 0) body.gainDb = s.gainDb;
2145
+ if (s.targets !== void 0) body.targets = s.targets;
2146
+ if (s.at !== void 0) body.at = s.at instanceof Date ? (0, import_protocol9.rfc3339Millis)(s.at) : s.at;
2147
+ if (s.loop !== void 0) body.loop = s.loop;
2148
+ return this.c.api.json(import_protocol9.Operations.startAudioSession, {
2149
+ params: this.v,
2150
+ body,
2151
+ preferRealtime: true
2152
+ });
2153
+ }
2154
+ /** Sessions of the venue. */
2155
+ sessions() {
2156
+ return readAllPages(this.c.api, import_protocol9.Operations.listAudioSessions, {
2157
+ params: this.v
2158
+ });
2159
+ }
2160
+ /** One session. */
2161
+ session(sessionId) {
2162
+ return this.c.api.json(import_protocol9.Operations.getAudioSession, {
2163
+ params: { ...this.v, sessionId }
2164
+ });
2165
+ }
2166
+ /** Follows a session until it ends (`finished` / `stopped` / `failed`), then stops by itself. */
2167
+ sessionState(sessionId, obs, o = {}) {
2168
+ return this.c.watchResource(
2169
+ import_protocol9.DomeTopics.audioSession(sessionId, this.venueId),
2170
+ () => this.session(sessionId),
2171
+ obs,
2172
+ {
2173
+ intervalMs: o.intervalMs ?? 1e3,
2174
+ kinds: /* @__PURE__ */ new Set([import_protocol9.EventKinds.audioSessionState]),
2175
+ isFinal: (s) => audioSessionEnded(s.status)
2176
+ }
2177
+ );
2178
+ }
2179
+ /** Stops a session (live control). */
2180
+ async stopSession(sessionId) {
2181
+ await this.c.api.call(import_protocol9.Operations.stopAudioSession, {
2182
+ params: { ...this.v, sessionId },
2183
+ preferRealtime: true
2184
+ });
2185
+ }
2186
+ // ---- generator / sources ----
2187
+ /** The venue's test / MULTI generator (backs the dome sound engine). Close it when done. */
2188
+ generator() {
2189
+ return new GeneratorSession(this);
2190
+ }
2191
+ /** Moves interactive source [sourceId] (spherical, listener at the dome centre; live control). */
2192
+ async setSourcePosition(sourceId, position) {
2193
+ await this.c.api.call(import_protocol9.Operations.setSourcePosition, {
2194
+ params: { ...this.v, sourceId },
2195
+ body: position,
2196
+ preferRealtime: true
2197
+ });
2198
+ }
2199
+ };
2200
+ var GeneratorSession = class {
2201
+ constructor(r) {
2202
+ this.r = r;
2203
+ const topic = import_protocol9.DomeTopics.audioGenerator(r.venueId);
2204
+ this.offEvents = r.ctx.hub.on([topic], (e) => {
2205
+ if (e.kind !== import_protocol9.EventKinds.generatorState) return;
2206
+ if (e.resource && typeof e.resource === "object") this.push(e.resource);
2207
+ else if (e.patch && this.value)
2208
+ this.push((0, import_protocol9.jsonMergePatch)(this.value, e.patch));
2209
+ });
2210
+ this.offSnapshot = r.ctx.hub.onSnapshot(topic, () => this.refreshQuietly());
2211
+ }
2212
+ r;
2213
+ /** State changes. */
2214
+ states = new Emitter();
2215
+ value;
2216
+ offEvents;
2217
+ offSnapshot;
2218
+ poll;
2219
+ closed = false;
2220
+ get v() {
2221
+ return { venueId: this.r.venueId };
2222
+ }
2223
+ /** Latest known state (undefined before the first read / event). */
2224
+ get last() {
2225
+ return this.value;
2226
+ }
2227
+ push(s) {
2228
+ if (this.closed) return;
2229
+ const same = this.value !== void 0 && JSON.stringify(this.value) === JSON.stringify(s);
2230
+ this.value = s;
2231
+ if (!same) this.states.emit(s);
2232
+ }
2233
+ /**
2234
+ * Watches the state (replays the latest; reads once when unknown). Polls every [pollMs] only while realtime is
2235
+ * down. Returns the unsubscribe function.
2236
+ */
2237
+ watch(fn, o = {}) {
2238
+ const off = this.states.on(fn);
2239
+ if (!this.poll && !this.closed) {
2240
+ this.poll = setInterval(() => {
2241
+ if (!this.r.ctx.realtimeUp()) void this.refreshQuietly();
2242
+ }, o.pollMs ?? 2e3);
2243
+ this.poll.unref?.();
2244
+ }
2245
+ if (this.value) fn(this.value);
2246
+ else void this.refreshQuietly();
2247
+ return off;
2248
+ }
2249
+ /** Reads the state over REST. */
2250
+ async get() {
2251
+ const s = await this.r.ctx.api.json(import_protocol9.Operations.getGenerator, {
2252
+ params: this.v
2253
+ });
2254
+ this.push(s);
2255
+ return s;
2256
+ }
2257
+ /** Starts the generator or replaces its settings (live control, scope `audio:control`). */
2258
+ async start(settings) {
2259
+ const s = await this.r.ctx.api.json(import_protocol9.Operations.setGenerator, {
2260
+ params: this.v,
2261
+ body: settings,
2262
+ preferRealtime: true
2263
+ });
2264
+ this.push(s);
2265
+ return s;
2266
+ }
2267
+ /** Stops the generator (live control). */
2268
+ async stop() {
2269
+ await this.r.ctx.api.call(import_protocol9.Operations.stopGenerator, { params: this.v, preferRealtime: true });
2270
+ this.push({ running: false });
2271
+ }
2272
+ async refreshQuietly() {
2273
+ if (this.closed) return;
2274
+ try {
2275
+ await this.get();
2276
+ } catch (e) {
2277
+ this.r.ctx.log("warning", "generator: read failed", e);
2278
+ }
2279
+ }
2280
+ /** Stops following the generator (does not stop it). */
2281
+ close() {
2282
+ if (this.closed) return;
2283
+ this.closed = true;
2284
+ if (this.poll) clearInterval(this.poll);
2285
+ this.offSnapshot();
2286
+ this.offEvents();
2287
+ this.states.close();
2288
+ }
2289
+ };
2290
+
2291
+ // src/repositories/calibration.ts
2292
+ var import_protocol10 = require("@freedome/protocol");
2293
+ var TERMINAL = /* @__PURE__ */ new Set(["succeeded", "failed", "cancelled"]);
2294
+ function multipart(parts) {
2295
+ const boundary = `freedome-${Math.random().toString(16).slice(2)}${Date.now().toString(16)}`;
2296
+ const enc2 = new TextEncoder();
2297
+ const chunks = [];
2298
+ for (const p of parts) {
2299
+ if ("value" in p) {
2300
+ chunks.push(
2301
+ enc2.encode(
2302
+ `--${boundary}\r
2303
+ Content-Disposition: form-data; name="${p.name}"\r
2304
+ \r
2305
+ ${p.value}\r
2306
+ `
2307
+ )
2308
+ );
2309
+ } else {
2310
+ chunks.push(
2311
+ enc2.encode(
2312
+ `--${boundary}\r
2313
+ Content-Disposition: form-data; name="${p.name}"; filename="${p.fileName}"\r
2314
+ Content-Type: ${p.contentType}\r
2315
+ \r
2316
+ `
2317
+ ),
2318
+ p.bytes,
2319
+ enc2.encode("\r\n")
2320
+ );
2321
+ }
2322
+ }
2323
+ chunks.push(enc2.encode(`--${boundary}--\r
2324
+ `));
2325
+ const out = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0));
2326
+ let o = 0;
2327
+ for (const c of chunks) {
2328
+ out.set(c, o);
2329
+ o += c.length;
2330
+ }
2331
+ return [`multipart/form-data; boundary=${boundary}`, out];
2332
+ }
2333
+ var CalibrationRepository = class {
2334
+ constructor(c) {
2335
+ this.c = c;
2336
+ }
2337
+ c;
2338
+ start(request, venueId = "default") {
2339
+ return this.c.api.json(import_protocol10.Operations.startCalibrationJob, { params: { venueId }, body: request });
2340
+ }
2341
+ /**
2342
+ * Audio room calibration (speakers play → microphones capture → the solver proposes delay / gain / EQ per speaker):
2343
+ * job kind `audio-room`, scope `audio:calibrate`.
2344
+ */
2345
+ startAudioRoom(o = {}) {
2346
+ return this.start(
2347
+ {
2348
+ kind: "audio-room",
2349
+ ...o.speakers ? { speakers: o.speakers } : {},
2350
+ ...o.options ? { options: o.options } : {}
2351
+ },
2352
+ o.venueId ?? "default"
2353
+ );
2354
+ }
2355
+ get(jobId, venueId = "default") {
2356
+ return this.c.api.json(import_protocol10.Operations.getCalibrationJob, { params: { venueId, jobId } });
2357
+ }
2358
+ /** Follows a job until it is terminal. */
2359
+ progress(jobId, obs, venueId = "default", intervalMs = 500) {
2360
+ return this.c.watchResource(
2361
+ import_protocol10.DomeTopics.calibrationJob(jobId, venueId),
2362
+ () => this.get(jobId, venueId),
2363
+ obs,
2364
+ {
2365
+ intervalMs,
2366
+ isFinal: (j) => TERMINAL.has(String(j.status))
2367
+ }
2368
+ );
2369
+ }
2370
+ /** Submits a camera frame (≤ 32 MB, multipart). */
2371
+ async submitCapture(jobId, frame, venueId = "default") {
2372
+ if (frame.bytes.length > 32 * 1024 * 1024)
2373
+ throw new PayloadTooLargeError("capture frames are limited to 32 MB");
2374
+ const [type, body] = multipart([
2375
+ {
2376
+ name: "image",
2377
+ fileName: frame.fileName ?? "capture.jpg",
2378
+ contentType: frame.contentType ?? "image/jpeg",
2379
+ bytes: frame.bytes
2380
+ },
2381
+ ...frame.stepId ? [{ name: "stepId", value: frame.stepId }] : []
2382
+ ]);
2383
+ return this.c.api.json(import_protocol10.Operations.submitCalibrationCapture, {
2384
+ params: { venueId, jobId },
2385
+ bytes: body,
2386
+ contentType: type,
2387
+ timeoutMs: 6e4
2388
+ });
2389
+ }
2390
+ cancel(jobId, venueId = "default") {
2391
+ return this.c.api.json(import_protocol10.Operations.cancelCalibrationJob, { params: { venueId, jobId } });
2392
+ }
2393
+ /** Writes the job result into the venue calibration. */
2394
+ apply(jobId, venueId = "default") {
2395
+ return this.c.api.json(import_protocol10.Operations.applyCalibrationJob, { params: { venueId, jobId } });
2396
+ }
2397
+ /** The venue's calibration block. */
2398
+ results(venueId = "default") {
2399
+ return this.c.api.json(import_protocol10.Operations.getCalibration, { params: { venueId } });
2400
+ }
2401
+ /** Calibration jobs of the venue. */
2402
+ async jobs(venueId = "default") {
2403
+ const p = await this.c.api.json(import_protocol10.Operations.listCalibrationJobs, {
2404
+ params: { venueId }
2405
+ });
2406
+ return p.items;
2407
+ }
2408
+ };
2409
+
2410
+ // src/repositories/clients.ts
2411
+ var import_protocol11 = require("@freedome/protocol");
2412
+ var ClientsRepository = class {
2413
+ constructor(c) {
2414
+ this.c = c;
2415
+ }
2416
+ c;
2417
+ register(registration) {
2418
+ return this.c.api.json(import_protocol11.Operations.registerClient, { body: registration });
2419
+ }
2420
+ list() {
2421
+ return readAllPages(this.c.api, import_protocol11.Operations.listClients);
2422
+ }
2423
+ async telemetry(clientId, batch) {
2424
+ await this.c.api.call(import_protocol11.Operations.postClientTelemetry, { params: { clientId }, body: batch });
2425
+ }
2426
+ async unregister(clientId) {
2427
+ await this.c.api.call(import_protocol11.Operations.unregisterClient, { params: { clientId } });
2428
+ }
2429
+ /** Commands the dome sends to this device (`clients/{id}/commands`). */
2430
+ commands(clientId, fn) {
2431
+ return this.c.hub.on([import_protocol11.DomeTopics.clientCommands(clientId)], (e) => {
2432
+ const r = e.resource ?? {};
2433
+ if (typeof r.command === "string") fn(r.command, r.args);
2434
+ });
2435
+ }
2436
+ };
2437
+
2438
+ // src/repositories/content.ts
2439
+ var import_protocol13 = require("@freedome/protocol");
2440
+
2441
+ // src/repositories/upload.ts
2442
+ var import_protocol12 = require("@freedome/protocol");
2443
+
2444
+ // src/sha256.ts
2445
+ var K = new Uint32Array([
2446
+ 1116352408,
2447
+ 1899447441,
2448
+ 3049323471,
2449
+ 3921009573,
2450
+ 961987163,
2451
+ 1508970993,
2452
+ 2453635748,
2453
+ 2870763221,
2454
+ 3624381080,
2455
+ 310598401,
2456
+ 607225278,
2457
+ 1426881987,
2458
+ 1925078388,
2459
+ 2162078206,
2460
+ 2614888103,
2461
+ 3248222580,
2462
+ 3835390401,
2463
+ 4022224774,
2464
+ 264347078,
2465
+ 604807628,
2466
+ 770255983,
2467
+ 1249150122,
2468
+ 1555081692,
2469
+ 1996064986,
2470
+ 2554220882,
2471
+ 2821834349,
2472
+ 2952996808,
2473
+ 3210313671,
2474
+ 3336571891,
2475
+ 3584528711,
2476
+ 113926993,
2477
+ 338241895,
2478
+ 666307205,
2479
+ 773529912,
2480
+ 1294757372,
2481
+ 1396182291,
2482
+ 1695183700,
2483
+ 1986661051,
2484
+ 2177026350,
2485
+ 2456956037,
2486
+ 2730485921,
2487
+ 2820302411,
2488
+ 3259730800,
2489
+ 3345764771,
2490
+ 3516065817,
2491
+ 3600352804,
2492
+ 4094571909,
2493
+ 275423344,
2494
+ 430227734,
2495
+ 506948616,
2496
+ 659060556,
2497
+ 883997877,
2498
+ 958139571,
2499
+ 1322822218,
2500
+ 1537002063,
2501
+ 1747873779,
2502
+ 1955562222,
2503
+ 2024104815,
2504
+ 2227730452,
2505
+ 2361852424,
2506
+ 2428436474,
2507
+ 2756734187,
2508
+ 3204031479,
2509
+ 3329325298
2510
+ ]);
2511
+ var Sha256 = class {
2512
+ h = new Uint32Array([
2513
+ 1779033703,
2514
+ 3144134277,
2515
+ 1013904242,
2516
+ 2773480762,
2517
+ 1359893119,
2518
+ 2600822924,
2519
+ 528734635,
2520
+ 1541459225
2521
+ ]);
2522
+ buf = new Uint8Array(64);
2523
+ w = new Uint32Array(64);
2524
+ bufLen = 0;
2525
+ total = 0;
2526
+ finished = false;
2527
+ update(data) {
2528
+ if (this.finished) throw new Error("sha256: already finished");
2529
+ let i = 0;
2530
+ this.total += data.length;
2531
+ if (this.bufLen) {
2532
+ const n = Math.min(64 - this.bufLen, data.length);
2533
+ this.buf.set(data.subarray(0, n), this.bufLen);
2534
+ this.bufLen += n;
2535
+ i = n;
2536
+ if (this.bufLen === 64) {
2537
+ this.block(this.buf, 0);
2538
+ this.bufLen = 0;
2539
+ }
2540
+ }
2541
+ for (; i + 64 <= data.length; i += 64) this.block(data, i);
2542
+ if (i < data.length) {
2543
+ this.buf.set(data.subarray(i), 0);
2544
+ this.bufLen = data.length - i;
2545
+ }
2546
+ return this;
2547
+ }
2548
+ digest() {
2549
+ if (!this.finished) {
2550
+ const bits = this.total * 8;
2551
+ const pad = new Uint8Array((this.bufLen < 56 ? 56 : 120) - this.bufLen + 8);
2552
+ pad[0] = 128;
2553
+ const dv2 = new DataView(pad.buffer);
2554
+ dv2.setUint32(pad.length - 8, Math.floor(bits / 2 ** 32));
2555
+ dv2.setUint32(pad.length - 4, bits >>> 0);
2556
+ const t = this.total;
2557
+ this.update(pad);
2558
+ this.total = t;
2559
+ this.finished = true;
2560
+ }
2561
+ const out = new Uint8Array(32);
2562
+ const dv = new DataView(out.buffer);
2563
+ for (let j = 0; j < 8; j++) dv.setUint32(j * 4, this.h[j]);
2564
+ return out;
2565
+ }
2566
+ hex() {
2567
+ return Array.from(this.digest(), (b) => b.toString(16).padStart(2, "0")).join("");
2568
+ }
2569
+ block(d, o) {
2570
+ const w = this.w;
2571
+ for (let j = 0; j < 16; j++)
2572
+ w[j] = d[o + j * 4] << 24 | d[o + j * 4 + 1] << 16 | d[o + j * 4 + 2] << 8 | d[o + j * 4 + 3];
2573
+ for (let j = 16; j < 64; j++) {
2574
+ const a2 = w[j - 15];
2575
+ const b2 = w[j - 2];
2576
+ const s0 = (a2 >>> 7 | a2 << 25) ^ (a2 >>> 18 | a2 << 14) ^ a2 >>> 3;
2577
+ const s1 = (b2 >>> 17 | b2 << 15) ^ (b2 >>> 19 | b2 << 13) ^ b2 >>> 10;
2578
+ w[j] = w[j - 16] + s0 + w[j - 7] + s1 | 0;
2579
+ }
2580
+ let [a, b, c, dd, e, f, g, h] = this.h;
2581
+ for (let j = 0; j < 64; j++) {
2582
+ const S1 = (e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7);
2583
+ const ch = e & f ^ ~e & g;
2584
+ const t1 = h + S1 + ch + K[j] + w[j] | 0;
2585
+ const S0 = (a >>> 2 | a << 30) ^ (a >>> 13 | a << 19) ^ (a >>> 22 | a << 10);
2586
+ const maj = a & b ^ a & c ^ b & c;
2587
+ const t2 = S0 + maj | 0;
2588
+ h = g;
2589
+ g = f;
2590
+ f = e;
2591
+ e = dd + t1 | 0;
2592
+ dd = c;
2593
+ c = b;
2594
+ b = a;
2595
+ a = t1 + t2 | 0;
2596
+ }
2597
+ const H = this.h;
2598
+ H[0] = H[0] + a | 0;
2599
+ H[1] = H[1] + b | 0;
2600
+ H[2] = H[2] + c | 0;
2601
+ H[3] = H[3] + dd | 0;
2602
+ H[4] = H[4] + e | 0;
2603
+ H[5] = H[5] + f | 0;
2604
+ H[6] = H[6] + g | 0;
2605
+ H[7] = H[7] + h | 0;
2606
+ }
2607
+ };
2608
+ var sha256Hex = (data) => new Sha256().update(data).hex();
2609
+ function base64(bytes) {
2610
+ const abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2611
+ let s = "";
2612
+ for (let i = 0; i < bytes.length; i += 3) {
2613
+ const n = bytes[i] << 16 | (bytes[i + 1] ?? 0) << 8 | (bytes[i + 2] ?? 0);
2614
+ s += abc[n >> 18 & 63] + abc[n >> 12 & 63] + (i + 1 < bytes.length ? abc[n >> 6 & 63] : "=") + (i + 2 < bytes.length ? abc[n & 63] : "=");
2615
+ }
2616
+ return s;
2617
+ }
2618
+
2619
+ // src/repositories/upload.ts
2620
+ var MAX_UPLOAD_CHUNK = 95 * 1024 * 1024;
2621
+ var BytesContentSource = class {
2622
+ constructor(bytes, name, contentType) {
2623
+ this.bytes = bytes;
2624
+ this.name = name;
2625
+ this.contentType = contentType;
2626
+ }
2627
+ bytes;
2628
+ name;
2629
+ contentType;
2630
+ get length() {
2631
+ return this.bytes.length;
2632
+ }
2633
+ async read(start, end) {
2634
+ return this.bytes.subarray(start, end);
2635
+ }
2636
+ };
2637
+ var BlobContentSource = class {
2638
+ constructor(blob, name = blob.name ?? "upload", contentType = blob.type || void 0) {
2639
+ this.blob = blob;
2640
+ this.name = name;
2641
+ this.contentType = contentType;
2642
+ }
2643
+ blob;
2644
+ name;
2645
+ contentType;
2646
+ get length() {
2647
+ return this.blob.size;
2648
+ }
2649
+ async read(start, end) {
2650
+ return new Uint8Array(await this.blob.slice(start, end).arrayBuffer());
2651
+ }
2652
+ };
2653
+ var b64 = (s) => base64(new TextEncoder().encode(s));
2654
+ var UploadTask = class {
2655
+ constructor(c, source, o = {}) {
2656
+ this.c = c;
2657
+ this.source = source;
2658
+ this.o = o;
2659
+ this.chunkSize = o.chunkSize ?? 8 * 1024 * 1024;
2660
+ if (this.chunkSize <= 0 || this.chunkSize > MAX_UPLOAD_CHUNK)
2661
+ throw new RangeError(`chunkSize 1..${MAX_UPLOAD_CHUNK}`);
2662
+ this.uploadIdValue = o.uploadId;
2663
+ this.sha = o.sha256;
2664
+ this.done = new Promise((res, rej) => {
2665
+ this.resolveDone = res;
2666
+ this.rejectDone = rej;
2667
+ });
2668
+ this.done.catch(() => void 0);
2669
+ }
2670
+ c;
2671
+ source;
2672
+ o;
2673
+ progress = new Emitter();
2674
+ done;
2675
+ resolveDone;
2676
+ rejectDone;
2677
+ finished = false;
2678
+ uploadIdValue;
2679
+ sha;
2680
+ offset = 0;
2681
+ stateValue = "pending";
2682
+ paused = false;
2683
+ running = false;
2684
+ wake;
2685
+ resumeRequested = false;
2686
+ chunkSize;
2687
+ get uploadId() {
2688
+ return this.uploadIdValue;
2689
+ }
2690
+ get sha256() {
2691
+ return this.sha;
2692
+ }
2693
+ get sent() {
2694
+ return this.offset;
2695
+ }
2696
+ get state() {
2697
+ return this.stateValue;
2698
+ }
2699
+ set(s) {
2700
+ this.stateValue = s;
2701
+ this.progress.emit({ state: s, sent: this.offset, total: this.source.length });
2702
+ }
2703
+ start() {
2704
+ if (!this.running && !this.finished) void this.run();
2705
+ return this.done;
2706
+ }
2707
+ pause() {
2708
+ this.paused = true;
2709
+ }
2710
+ resume() {
2711
+ this.paused = false;
2712
+ const w = this.wake;
2713
+ this.wake = void 0;
2714
+ if (w) w();
2715
+ else this.resumeRequested = this.running;
2716
+ if (!this.running && !this.finished) void this.run();
2717
+ }
2718
+ /** Terminates the upload on the server (tus DELETE) and rejects `done`. */
2719
+ async cancel() {
2720
+ this.paused = true;
2721
+ const id = this.uploadIdValue;
2722
+ if (id) {
2723
+ try {
2724
+ await this.c.api.call(import_protocol12.Operations.deleteUpload, {
2725
+ params: { uploadId: id },
2726
+ headers: { "tus-resumable": "1.0.0" }
2727
+ });
2728
+ } catch (e) {
2729
+ this.c.log("warning", `upload ${id}: terminate failed`, e);
2730
+ }
2731
+ }
2732
+ this.set("cancelled");
2733
+ this.fail(new ServerError("upload cancelled", { code: "cancelled" }));
2734
+ const w = this.wake;
2735
+ this.wake = void 0;
2736
+ w?.();
2737
+ this.progress.close();
2738
+ }
2739
+ fail(e) {
2740
+ if (this.finished) return;
2741
+ this.finished = true;
2742
+ this.rejectDone(e);
2743
+ }
2744
+ waitForResume() {
2745
+ if (this.resumeRequested) {
2746
+ this.resumeRequested = false;
2747
+ return Promise.resolve();
2748
+ }
2749
+ this.set("paused");
2750
+ return new Promise((r) => this.wake = r);
2751
+ }
2752
+ async run() {
2753
+ this.running = true;
2754
+ try {
2755
+ while (!this.finished) {
2756
+ try {
2757
+ await this.step();
2758
+ return;
2759
+ } catch (e) {
2760
+ if (isUnreachable(e)) {
2761
+ this.c.log("info", `upload paused (${e.message})`);
2762
+ await this.waitForResume();
2763
+ continue;
2764
+ }
2765
+ this.set("failed");
2766
+ this.fail(e);
2767
+ return;
2768
+ }
2769
+ }
2770
+ } finally {
2771
+ this.running = false;
2772
+ }
2773
+ }
2774
+ async step() {
2775
+ const total = this.source.length;
2776
+ if (!this.sha) {
2777
+ this.set("hashing");
2778
+ const h = new Sha256();
2779
+ for (let p = 0; p < total; p += this.chunkSize)
2780
+ h.update(await this.source.read(p, Math.min(total, p + this.chunkSize)));
2781
+ this.sha = h.hex();
2782
+ }
2783
+ const api = this.c.api;
2784
+ if (!this.uploadIdValue) {
2785
+ const res = await api.call(import_protocol12.Operations.createUpload, {
2786
+ headers: {
2787
+ "tus-resumable": "1.0.0",
2788
+ "upload-length": String(total),
2789
+ "upload-metadata": this.metadata()
2790
+ }
2791
+ });
2792
+ const loc = res.headers.location;
2793
+ const id = loc ? loc.split("?")[0].split("/").filter(Boolean).at(-1) : res.body.length ? res.json?.id : void 0;
2794
+ if (!id) throw new ServerError("createUpload: no Location / id", { code: "internal" });
2795
+ this.uploadIdValue = id;
2796
+ this.offset = Number.parseInt(res.headers["upload-offset"] ?? "0", 10) || 0;
2797
+ } else {
2798
+ this.offset = await this.headOffset();
2799
+ }
2800
+ this.set("uploading");
2801
+ while (this.offset < total) {
2802
+ if (this.paused) {
2803
+ await this.waitForResume();
2804
+ if (this.finished) return;
2805
+ this.offset = await this.headOffset();
2806
+ this.set("uploading");
2807
+ continue;
2808
+ }
2809
+ const end = Math.min(total, this.offset + this.chunkSize);
2810
+ const chunk = await this.source.read(this.offset, end);
2811
+ let res;
2812
+ try {
2813
+ res = await api.call(import_protocol12.Operations.appendUpload, {
2814
+ params: { uploadId: this.uploadIdValue },
2815
+ bytes: chunk,
2816
+ contentType: "application/offset+octet-stream",
2817
+ headers: {
2818
+ "tus-resumable": "1.0.0",
2819
+ "upload-offset": String(this.offset),
2820
+ "upload-checksum": `sha256 ${base64(new Sha256().update(chunk).digest())}`
2821
+ }
2822
+ });
2823
+ } catch (e) {
2824
+ if (e instanceof ConflictError) {
2825
+ this.offset = await this.headOffset();
2826
+ continue;
2827
+ }
2828
+ throw e;
2829
+ }
2830
+ this.offset = Number.parseInt(res.headers["upload-offset"] ?? "", 10) || this.offset + chunk.length;
2831
+ this.set("uploading");
2832
+ }
2833
+ this.set("completing");
2834
+ let asset;
2835
+ if ((this.o.purpose ?? "asset") === "asset") {
2836
+ const req = {
2837
+ ...this.o.asset,
2838
+ uploadId: this.uploadIdValue,
2839
+ name: this.o.asset?.name ?? this.source.name
2840
+ };
2841
+ asset = await api.json(import_protocol12.Operations.createAsset, { body: req });
2842
+ }
2843
+ this.set("done");
2844
+ if (!this.finished) {
2845
+ this.finished = true;
2846
+ this.resolveDone({
2847
+ uploadId: this.uploadIdValue,
2848
+ sha256: this.sha,
2849
+ ...asset ? { asset } : {}
2850
+ });
2851
+ }
2852
+ this.progress.close();
2853
+ }
2854
+ async headOffset() {
2855
+ const res = await this.c.api.call(import_protocol12.Operations.getUploadOffset, {
2856
+ params: { uploadId: this.uploadIdValue },
2857
+ headers: { "tus-resumable": "1.0.0" }
2858
+ });
2859
+ const o = Number.parseInt(res.headers["upload-offset"] ?? "", 10);
2860
+ if (!Number.isFinite(o))
2861
+ throw new ServerError("HEAD upload: no Upload-Offset", { code: "internal" });
2862
+ return o;
2863
+ }
2864
+ metadata() {
2865
+ const parts = [`filename ${b64(this.source.name)}`];
2866
+ if (this.source.contentType) parts.push(`contentType ${b64(this.source.contentType)}`);
2867
+ parts.push(`sha256 ${b64(this.sha)}`, `purpose ${b64(this.o.purpose ?? "asset")}`);
2868
+ const assetId = this.o.asset?.id;
2869
+ if (assetId) parts.push(`assetId ${b64(assetId)}`);
2870
+ return parts.join(",");
2871
+ }
2872
+ };
2873
+
2874
+ // src/repositories/content.ts
2875
+ var ContentRepository = class {
2876
+ constructor(c) {
2877
+ this.c = c;
2878
+ this.parts = new ShowParts(c);
2879
+ c.hub.onSnapshot("#", async () => {
2880
+ for (const t of this.tasks) if (t.state === "paused") t.resume();
2881
+ });
2882
+ }
2883
+ c;
2884
+ tasks = /* @__PURE__ */ new Set();
2885
+ parts;
2886
+ /** One page of assets (first pages cache-backed). */
2887
+ list(query = {}, cursor) {
2888
+ const q = { type: query.type, tag: query.tag, q: query.q, status: query.status };
2889
+ const read = () => readPage(this.c.api, import_protocol13.Operations.listAssets, {
2890
+ query: q,
2891
+ cursor,
2892
+ limit: query.limit
2893
+ });
2894
+ if (cursor) return read();
2895
+ const key = `assets?${Object.entries(q).filter(([, v]) => v !== void 0).map(([k, v]) => `${k}=${v}`).join("&")}`;
2896
+ return this.c.cachedRead(
2897
+ key,
2898
+ async () => {
2899
+ const p = await read();
2900
+ return [p, p];
2901
+ },
2902
+ (json, asOf) => ({ ...json, stale: true, asOf })
2903
+ );
2904
+ }
2905
+ get(assetId) {
2906
+ return this.c.api.json(import_protocol13.Operations.getAsset, { params: { assetId } });
2907
+ }
2908
+ /** Starts a resumable upload creating an asset (await `task.done`). */
2909
+ upload(source, o = {}) {
2910
+ const src = source instanceof Uint8Array ? new BytesContentSource(source, o.name ?? "upload") : source;
2911
+ return this.track(
2912
+ new UploadTask(this.c, src, {
2913
+ purpose: "asset",
2914
+ ...o.asset ? { asset: o.asset } : {},
2915
+ ...o.chunkSize ? { chunkSize: o.chunkSize } : {}
2916
+ })
2917
+ );
2918
+ }
2919
+ /** Continues a persisted upload (same [source]). */
2920
+ resumeUpload(uploadId, source, o = {}) {
2921
+ return this.track(
2922
+ new UploadTask(this.c, source, { uploadId, purpose: o.purpose ?? "asset", ...o })
2923
+ );
2924
+ }
2925
+ /** Uploads for another purpose (import / restore / capture), no asset. */
2926
+ uploadFor(purpose, source) {
2927
+ return this.track(new UploadTask(this.c, source, { purpose }));
2928
+ }
2929
+ track(t) {
2930
+ this.tasks.add(t);
2931
+ void t.done.then(
2932
+ () => this.tasks.delete(t),
2933
+ () => this.tasks.delete(t)
2934
+ );
2935
+ void t.start();
2936
+ return t;
2937
+ }
2938
+ /** Uploads in progress. */
2939
+ get uploads() {
2940
+ return [...this.tasks];
2941
+ }
2942
+ /** Uploads [source] and runs an import job; returns the finished job (rejects when it failed). */
2943
+ async importFile(source, format, o = {}) {
2944
+ const up = await this.uploadFor("import", source).done;
2945
+ const job = await this.c.api.json(import_protocol13.Operations.startImport, {
2946
+ body: {
2947
+ uploadId: up.uploadId,
2948
+ format,
2949
+ ...o.target ? { target: o.target } : {}
2950
+ }
2951
+ });
2952
+ return this.waitJob(job, { timeoutMs: o.timeoutMs ?? 6e5 });
2953
+ }
2954
+ /** Imports `.dome` bytes (kind show / bundle) and returns the created show. */
2955
+ async publishShow(dome, name = "show.dome") {
2956
+ const job = await this.importFile(
2957
+ new BytesContentSource(dome, name, "application/vnd.nativemind.freedome.dome+zip"),
2958
+ "dome"
2959
+ );
2960
+ const showId = job.result?.showId;
2961
+ if (!showId)
2962
+ throw new ServerError(`import job ${job.id} finished without a showId`, {
2963
+ code: "job-failed"
2964
+ });
2965
+ return (await this.getShow(showId)).value;
2966
+ }
2967
+ /** Polls a job until terminal; failed / cancelled reject. */
2968
+ async waitJob(job, o = {}) {
2969
+ const deadline = Date.now() + (o.timeoutMs ?? 6e5);
2970
+ let j = job;
2971
+ for (; ; ) {
2972
+ if (j.status === "succeeded") return j;
2973
+ if (j.status === "failed" || j.status === "cancelled") {
2974
+ throw new ServerError(`job ${j.id} ${j.status}: ${j.problem?.detail ?? j.message ?? ""}`, {
2975
+ code: j.problem?.code ?? "job-failed"
2976
+ });
2977
+ }
2978
+ if (Date.now() > deadline)
2979
+ throw new RequestTimeoutError(`job ${j.id} not finished in time`, o.timeoutMs);
2980
+ await new Promise((r) => setTimeout(r, o.pollMs ?? 500));
2981
+ j = await this.c.api.json(import_protocol13.Operations.getJob, { params: { jobId: j.id } });
2982
+ }
2983
+ }
2984
+ /** Merge-patches an asset (ETag read first when not given). */
2985
+ async patch(assetId, patch, ifMatch) {
2986
+ const etag = ifMatch ?? `"r${(await this.get(assetId)).revision}"`;
2987
+ return this.c.api.json(import_protocol13.Operations.patchAsset, {
2988
+ params: { assetId },
2989
+ body: patch,
2990
+ headers: { "if-match": etag }
2991
+ });
2992
+ }
2993
+ /** Deletes an asset (409 while referenced unless [force]). */
2994
+ async delete(assetId, o = {}) {
2995
+ const etag = o.ifMatch ?? `"r${(await this.get(assetId)).revision}"`;
2996
+ await this.c.api.call(import_protocol13.Operations.deleteAsset, {
2997
+ params: { assetId },
2998
+ query: o.force ? { force: "true" } : {},
2999
+ headers: { "if-match": etag }
3000
+ });
3001
+ }
3002
+ async thumbnail(assetId, size) {
3003
+ return (await this.c.api.call(import_protocol13.Operations.getAssetThumbnail, {
3004
+ params: { assetId },
3005
+ query: { size: size?.toString() }
3006
+ })).body;
3007
+ }
3008
+ async download(assetId) {
3009
+ return (await this.c.api.call(import_protocol13.Operations.downloadAsset, { params: { assetId }, timeoutMs: 18e5 })).body;
3010
+ }
3011
+ storage() {
3012
+ return this.c.api.json(import_protocol13.Operations.getStorageStats);
3013
+ }
3014
+ /** Changes of the content store. */
3015
+ changes(fn) {
3016
+ return this.c.hub.on(["assets/+"], (e) => {
3017
+ const p = e.patch?.progress;
3018
+ fn({
3019
+ kind: e.kind,
3020
+ assetId: e.topic.split("/").at(-1),
3021
+ ...e.resource && typeof e.resource === "object" ? { asset: e.resource } : {},
3022
+ ...typeof p === "number" ? { progress: p } : {}
3023
+ });
3024
+ });
3025
+ }
3026
+ listShows(o = {}) {
3027
+ return readPage(this.c.api, import_protocol13.Operations.listShows, {
3028
+ query: { q: o.q },
3029
+ cursor: o.cursor,
3030
+ limit: o.limit
3031
+ });
3032
+ }
3033
+ async getShow(showId) {
3034
+ const res = await this.c.api.call(import_protocol13.Operations.getShow, { params: { showId } });
3035
+ return {
3036
+ value: ApiCaller.decodeBody(import_protocol13.Operations.getShow, res),
3037
+ etag: res.headers.etag
3038
+ };
3039
+ }
3040
+ async createShow(body) {
3041
+ const res = await this.c.api.call(import_protocol13.Operations.createShow, { body });
3042
+ return {
3043
+ value: ApiCaller.decodeBody(import_protocol13.Operations.createShow, res),
3044
+ etag: res.headers.etag
3045
+ };
3046
+ }
3047
+ /** Replaces a show (`ifMatch`; without: create with If-None-Match: *). Queued in the outbox while offline. */
3048
+ async saveShow(showId, body, ifMatch) {
3049
+ const res = await this.c.idempotentWrite(import_protocol13.Operations.putShow, {
3050
+ params: { showId },
3051
+ body,
3052
+ headers: ifMatch ? { "if-match": ifMatch } : { "if-none-match": "*" }
3053
+ });
3054
+ return {
3055
+ value: ApiCaller.decodeBody(import_protocol13.Operations.putShow, res),
3056
+ etag: res.headers.etag
3057
+ };
3058
+ }
3059
+ async patchShow(showId, patch, ifMatch) {
3060
+ const etag = ifMatch ?? (await this.getShow(showId)).etag;
3061
+ const res = await this.c.api.call(import_protocol13.Operations.patchShow, {
3062
+ params: { showId },
3063
+ body: patch,
3064
+ headers: { "if-match": etag }
3065
+ });
3066
+ return {
3067
+ value: ApiCaller.decodeBody(import_protocol13.Operations.patchShow, res),
3068
+ etag: res.headers.etag
3069
+ };
3070
+ }
3071
+ async deleteShow(showId, ifMatch) {
3072
+ await this.c.api.call(import_protocol13.Operations.deleteShow, {
3073
+ params: { showId },
3074
+ headers: { "if-match": ifMatch }
3075
+ });
3076
+ }
3077
+ /** Exports a show as `.dome` bytes. */
3078
+ async exportShow(showId, embedAssets = false) {
3079
+ return (await this.c.api.call(import_protocol13.Operations.exportShow, {
3080
+ params: { showId },
3081
+ query: embedAssets ? { embedAssets: "true" } : {},
3082
+ timeoutMs: 18e5
3083
+ })).body;
3084
+ }
3085
+ /** tus capabilities. */
3086
+ async uploadCapabilities() {
3087
+ const res = await this.c.api.call(import_protocol13.Operations.getUploadCapabilities);
3088
+ const list = (h) => (res.headers[h] ?? "").split(",").map((x) => x.trim()).filter(Boolean);
3089
+ const max = Number.parseInt(res.headers["tus-max-size"] ?? "", 10);
3090
+ return {
3091
+ version: list("tus-version"),
3092
+ extensions: list("tus-extension"),
3093
+ ...Number.isFinite(max) ? { maxSize: max } : {},
3094
+ ...res.headers["tus-checksum-algorithm"] ? { checksumAlgorithms: list("tus-checksum-algorithm") } : {}
3095
+ };
3096
+ }
3097
+ uploadStatus(uploadId) {
3098
+ return this.c.api.json(import_protocol13.Operations.getUpload, { params: { uploadId } });
3099
+ }
3100
+ /** Watch hook used by apps showing one asset. */
3101
+ watchAsset(assetId, fn) {
3102
+ return this.c.watchResource(import_protocol13.DomeTopics.asset(assetId), () => this.get(assetId), { next: fn });
3103
+ }
3104
+ };
3105
+ var ShowParts = class {
3106
+ constructor(c) {
3107
+ this.c = c;
3108
+ }
3109
+ c;
3110
+ async etag(showId, ifMatch) {
3111
+ return ifMatch ?? (await this.c.api.call(import_protocol13.Operations.getShow, { params: { showId } })).headers.etag;
3112
+ }
3113
+ get(part, showId, itemId) {
3114
+ return this.c.api.json(import_protocol13.Operations[`get${part}`], { params: { showId, itemId } });
3115
+ }
3116
+ async put(part, showId, item, ifMatch) {
3117
+ return this.c.api.json(import_protocol13.Operations[`put${part}`], {
3118
+ params: { showId, itemId: item.id },
3119
+ body: item,
3120
+ headers: { "if-match": await this.etag(showId, ifMatch) }
3121
+ });
3122
+ }
3123
+ async delete(part, showId, itemId, ifMatch) {
3124
+ await this.c.api.call(import_protocol13.Operations[`delete${part}`], {
3125
+ params: { showId, itemId },
3126
+ headers: { "if-match": await this.etag(showId, ifMatch) }
3127
+ });
3128
+ }
3129
+ matrix(showId) {
3130
+ return this.c.api.json(import_protocol13.Operations.getMatrix, { params: { showId } });
3131
+ }
3132
+ async putMatrix(showId, matrix, ifMatch) {
3133
+ return this.c.api.json(import_protocol13.Operations.putMatrix, {
3134
+ params: { showId },
3135
+ body: matrix,
3136
+ headers: { "if-match": await this.etag(showId, ifMatch) }
3137
+ });
3138
+ }
3139
+ };
3140
+
3141
+ // src/repositories/engine.ts
3142
+ var import_protocol14 = require("@freedome/protocol");
3143
+ var EngineRepository = class {
3144
+ constructor(c) {
3145
+ this.c = c;
3146
+ }
3147
+ c;
3148
+ /** Every engine (visual, audio, …; `name@node` on multi-node installations). */
3149
+ engines() {
3150
+ return readAllPages(this.c.api, import_protocol14.Operations.listEngines);
3151
+ }
3152
+ /** Displays of a venue. */
3153
+ outputs(venueId = "default") {
3154
+ return readAllPages(this.c.api, import_protocol14.Operations.listDisplays, {
3155
+ params: { venueId }
3156
+ });
3157
+ }
3158
+ /** One display. */
3159
+ display(displayId, venueId = "default") {
3160
+ return this.c.api.json(import_protocol14.Operations.getDisplay, {
3161
+ params: { venueId, displayId }
3162
+ });
3163
+ }
3164
+ /** Shows a test pattern on a display. */
3165
+ showTestPattern(displayId, pattern, venueId = "default") {
3166
+ return this.c.api.json(import_protocol14.Operations.setTestPattern, {
3167
+ params: { venueId, displayId },
3168
+ body: pattern,
3169
+ preferRealtime: true
3170
+ });
3171
+ }
3172
+ /** Clears the test pattern. */
3173
+ clearTestPattern(displayId, venueId = "default") {
3174
+ return this.showTestPattern(
3175
+ displayId,
3176
+ { kind: "off" },
3177
+ venueId
3178
+ );
3179
+ }
3180
+ /** Flashes the id overlay. */
3181
+ async identify(displayId, durationMs, venueId = "default") {
3182
+ await this.c.api.call(import_protocol14.Operations.identifyDisplay, {
3183
+ params: { venueId, displayId },
3184
+ body: durationMs === void 0 ? {} : { durationS: durationMs / 1e3 }
3185
+ });
3186
+ }
3187
+ /** Power / shutter (what `state.capabilities` lists). */
3188
+ setPower(displayId, request, venueId = "default") {
3189
+ return this.c.api.json(import_protocol14.Operations.setDisplayPower, {
3190
+ params: { venueId, displayId },
3191
+ body: request
3192
+ });
3193
+ }
3194
+ /** Status of engine [name]. */
3195
+ async engineStatus(name = "visual") {
3196
+ const s = await this.c.api.json(import_protocol14.Operations.getEngine, { params: { name } });
3197
+ if (name === "visual") this.c.onEngineHealth?.(String(s.status));
3198
+ return s;
3199
+ }
3200
+ /** Watches an engine (feeds the `degraded` state for the visual engine). */
3201
+ status(obs, name = "visual", intervalMs = 2e3) {
3202
+ return this.c.watchResource(
3203
+ import_protocol14.DomeTopics.engine(name),
3204
+ () => this.engineStatus(name),
3205
+ {
3206
+ next: (s) => {
3207
+ if (name === "visual")
3208
+ this.c.onEngineHealth?.(String(s.status));
3209
+ obs.next(s);
3210
+ },
3211
+ ...obs.error ? { error: obs.error } : {}
3212
+ },
3213
+ { intervalMs, kinds: /* @__PURE__ */ new Set([import_protocol14.EventKinds.engineStatus]) }
3214
+ );
3215
+ }
3216
+ };
3217
+
3218
+ // src/repositories/gateways.ts
3219
+ var import_protocol15 = require("@freedome/protocol");
3220
+ var GatewaysRepository = class {
3221
+ constructor(c) {
3222
+ this.c = c;
3223
+ }
3224
+ c;
3225
+ /** Every gateway. */
3226
+ list() {
3227
+ return readAllPages(this.c.api, import_protocol15.Operations.listGateways, {});
3228
+ }
3229
+ /** One gateway with its ETag. */
3230
+ async get(gatewayId) {
3231
+ const res = await this.c.api.call(import_protocol15.Operations.getGateway, { params: { gatewayId } });
3232
+ return {
3233
+ value: ApiCaller.decodeBody(import_protocol15.Operations.getGateway, res),
3234
+ etag: res.headers.etag
3235
+ };
3236
+ }
3237
+ /**
3238
+ * Merge-patches a gateway ([ifMatch] read when absent). The server validates `config` for the gateway's protocol
3239
+ * and answers 422 when it refuses it.
3240
+ */
3241
+ async patch(gatewayId, patch, o = {}) {
3242
+ const etag = o.ifMatch ?? (await this.get(gatewayId)).etag;
3243
+ const res = await this.c.api.call(import_protocol15.Operations.patchGateway, {
3244
+ params: { gatewayId },
3245
+ body: patch,
3246
+ headers: { "if-match": etag }
3247
+ });
3248
+ return {
3249
+ value: ApiCaller.decodeBody(import_protocol15.Operations.patchGateway, res),
3250
+ etag: res.headers.etag
3251
+ };
3252
+ }
3253
+ /** Runs the gateway's connectivity test. */
3254
+ test(gatewayId) {
3255
+ return this.c.api.json(import_protocol15.Operations.testGateway, { params: { gatewayId } });
3256
+ }
3257
+ };
3258
+
3259
+ // src/repositories/osc.ts
3260
+ var import_protocol16 = require("@freedome/protocol");
3261
+ function oscArg(a) {
3262
+ if (a !== null && typeof a === "object" && "type" in a && !(a instanceof Uint8Array) && !(a instanceof Date))
3263
+ return a;
3264
+ if (a === null || a === void 0) return { type: "N" };
3265
+ if (typeof a === "boolean") return { type: a ? "T" : "F" };
3266
+ if (typeof a === "number")
3267
+ return Number.isInteger(a) && Math.abs(a) <= 2147483647 ? { type: "i", value: a } : { type: "f", value: a };
3268
+ if (typeof a === "bigint") return { type: "h", value: a.toString() };
3269
+ if (typeof a === "string") return { type: "s", value: a };
3270
+ if (a instanceof Uint8Array) {
3271
+ let s = "";
3272
+ for (const b of a) s += String.fromCharCode(b);
3273
+ return { type: "b", value: btoa(s) };
3274
+ }
3275
+ if (a instanceof Date) return { type: "t", value: a.toISOString() };
3276
+ throw new TypeError(`unsupported OSC argument ${typeof a}`);
3277
+ }
3278
+ var OscRepository = class {
3279
+ constructor(c) {
3280
+ this.c = c;
3281
+ }
3282
+ c;
3283
+ /** Sends [address] [args] to the configured OSC [target] (gateway / target id). */
3284
+ async send(address, args, target) {
3285
+ if (!address.startsWith("/")) throw new TypeError("OSC address must start with /");
3286
+ const body = { target, address, args: args.map(oscArg) };
3287
+ await this.c.api.call(import_protocol16.Operations.sendOsc, { body, preferRealtime: true });
3288
+ }
3289
+ /** OSC traffic of gateways (`gateway.message` events). */
3290
+ messages(fn, gatewayId = "+") {
3291
+ return this.c.hub.on(
3292
+ [gatewayId === "+" ? "gateways/+" : import_protocol16.DomeTopics.gateway(gatewayId)],
3293
+ (e) => {
3294
+ const r = e.resource ?? e.data;
3295
+ if (typeof r?.address === "string")
3296
+ fn({ address: r.address, args: r.args ?? [], target: e.topic.split("/")[1] ?? "" });
3297
+ }
3298
+ );
3299
+ }
3300
+ };
3301
+
3302
+ // src/repositories/playback.ts
3303
+ var import_protocol17 = require("@freedome/protocol");
3304
+ var PlayTargets = {
3305
+ show: (showId, o = {}) => ({
3306
+ kind: "show",
3307
+ showId,
3308
+ ...o
3309
+ }),
3310
+ playlist: (playlistId, o = {}) => ({
3311
+ kind: "playlist",
3312
+ playlistId,
3313
+ ...o
3314
+ }),
3315
+ asset: (assetId) => ({ kind: "asset", assetId }),
3316
+ app: (app, payload) => ({ kind: "app", app, payload }),
3317
+ current: () => ({ kind: "current" })
3318
+ };
3319
+ var Fader = class {
3320
+ constructor(send) {
3321
+ this.send = send;
3322
+ }
3323
+ send;
3324
+ busy = false;
3325
+ pending;
3326
+ waiters = [];
3327
+ set(body) {
3328
+ return new Promise((resolve, reject) => {
3329
+ this.waiters.push({ resolve, reject });
3330
+ this.pending = { body };
3331
+ if (!this.busy) void this.pump();
3332
+ });
3333
+ }
3334
+ async pump() {
3335
+ this.busy = true;
3336
+ try {
3337
+ while (this.pending) {
3338
+ const { body } = this.pending;
3339
+ this.pending = void 0;
3340
+ const waiters = this.waiters;
3341
+ this.waiters = [];
3342
+ try {
3343
+ const r = await this.send(body);
3344
+ if (!this.pending) for (const w of waiters) w.resolve(r);
3345
+ else this.waiters.unshift(...waiters);
3346
+ } catch (e) {
3347
+ if (e instanceof RateLimitedError) {
3348
+ await new Promise((r) => setTimeout(r, e.retryAfterMs ?? 250));
3349
+ this.pending ??= { body };
3350
+ this.waiters.unshift(...waiters);
3351
+ } else if (this.pending) {
3352
+ this.waiters.unshift(...waiters);
3353
+ } else for (const w of waiters) w.reject(e);
3354
+ }
3355
+ }
3356
+ } finally {
3357
+ this.busy = false;
3358
+ }
3359
+ }
3360
+ };
3361
+ var PlayerHandle = class {
3362
+ constructor(c, venueId, playerId) {
3363
+ this.c = c;
3364
+ this.venueId = venueId;
3365
+ this.playerId = playerId;
3366
+ }
3367
+ c;
3368
+ venueId;
3369
+ playerId;
3370
+ states = new Emitter();
3371
+ last;
3372
+ listeners = 0;
3373
+ offEvents;
3374
+ offSnapshot;
3375
+ faders = /* @__PURE__ */ new Map();
3376
+ get params() {
3377
+ return { venueId: this.venueId, playerId: this.playerId };
3378
+ }
3379
+ /** Latest known state. */
3380
+ get value() {
3381
+ return this.last;
3382
+ }
3383
+ push(s) {
3384
+ this.last = s;
3385
+ this.states.emit(s);
3386
+ }
3387
+ /** Follows the player's state (subscribes while at least one watcher). */
3388
+ watch(fn) {
3389
+ const off = this.states.on(fn);
3390
+ if (this.listeners++ === 0) {
3391
+ const topic = import_protocol17.DomeTopics.player(this.playerId, this.venueId);
3392
+ this.offEvents = this.c.hub.on([topic], (e) => {
3393
+ if (e.kind === import_protocol17.EventKinds.playerState || e.kind === import_protocol17.EventKinds.playerError) {
3394
+ if (e.resource && typeof e.resource === "object")
3395
+ this.push({ state: e.resource });
3396
+ } else if (e.kind === import_protocol17.EventKinds.playerPosition && e.patch && this.last) {
3397
+ this.push({ state: (0, import_protocol17.jsonMergePatch)(this.last.state, e.patch) });
3398
+ }
3399
+ });
3400
+ this.offSnapshot = this.c.hub.onSnapshot(topic, async () => {
3401
+ await this.refresh();
3402
+ });
3403
+ if (!this.last)
3404
+ void this.refresh().catch(
3405
+ (e) => this.c.log("warning", `player ${this.playerId}: initial read failed`, e)
3406
+ );
3407
+ }
3408
+ if (this.last) fn(this.last);
3409
+ let done = false;
3410
+ return () => {
3411
+ if (done) return;
3412
+ done = true;
3413
+ off();
3414
+ if (--this.listeners === 0) {
3415
+ this.offEvents?.();
3416
+ this.offSnapshot?.();
3417
+ }
3418
+ };
3419
+ }
3420
+ /** Re-reads the state (cache-backed). */
3421
+ async refresh() {
3422
+ const snap = await this.c.cachedRead(
3423
+ `players/${this.venueId}/${this.playerId}`,
3424
+ async () => {
3425
+ const s = await this.c.api.json(import_protocol17.Operations.getPlayer, { params: this.params });
3426
+ return [{ state: s }, s];
3427
+ },
3428
+ (json, asOf) => ({ state: json, stale: true, asOf })
3429
+ );
3430
+ this.push(snap);
3431
+ return snap;
3432
+ }
3433
+ async command(op, body) {
3434
+ const res = await this.c.api.call(op, {
3435
+ params: this.params,
3436
+ ...body === void 0 ? {} : { body },
3437
+ preferRealtime: true
3438
+ });
3439
+ const j = res.body.length ? res.json : void 0;
3440
+ if (j && typeof j === "object" && "status" in j && !("kind" in j && "progress" in j)) {
3441
+ this.push({ state: j });
3442
+ return j;
3443
+ }
3444
+ return void 0;
3445
+ }
3446
+ fader(key, body, send) {
3447
+ let f = this.faders.get(key);
3448
+ if (!f) {
3449
+ f = new Fader(send);
3450
+ this.faders.set(key, f);
3451
+ }
3452
+ return f.set(body);
3453
+ }
3454
+ /** Plays [target] (optionally from [positionMs], at server time [at] for multi-node sync). */
3455
+ async play(target, o = {}) {
3456
+ if (target.kind === "app") {
3457
+ await this.c.api.call(import_protocol17.Operations.publishAppPayload, {
3458
+ params: { app: target.app },
3459
+ body: target.payload,
3460
+ preferRealtime: true
3461
+ });
3462
+ return void 0;
3463
+ }
3464
+ const req = {};
3465
+ if (target.kind === "show") {
3466
+ req.showId = target.showId;
3467
+ if (target.playlistId) req.playlistId = target.playlistId;
3468
+ if (target.itemIndex !== void 0) req.itemIndex = target.itemIndex;
3469
+ } else if (target.kind === "playlist") {
3470
+ req.playlistId = target.playlistId;
3471
+ if (target.showId) req.showId = target.showId;
3472
+ if (target.itemIndex !== void 0) req.itemIndex = target.itemIndex;
3473
+ } else if (target.kind === "asset") req.assetId = target.assetId;
3474
+ if (o.positionMs !== void 0) req.position = o.positionMs / 1e3;
3475
+ if (o.at) req.at = (0, import_protocol17.rfc3339Millis)(o.at);
3476
+ return this.command(import_protocol17.Operations.play, req);
3477
+ }
3478
+ pause() {
3479
+ return this.command(import_protocol17.Operations.pause);
3480
+ }
3481
+ resume() {
3482
+ return this.command(import_protocol17.Operations.resume);
3483
+ }
3484
+ stop() {
3485
+ return this.command(import_protocol17.Operations.stop);
3486
+ }
3487
+ next() {
3488
+ return this.command(import_protocol17.Operations.next);
3489
+ }
3490
+ previous() {
3491
+ return this.command(import_protocol17.Operations.previous);
3492
+ }
3493
+ /** Seeks (coalesced while scrubbing). */
3494
+ seek(positionMs) {
3495
+ return this.fader(
3496
+ "seek",
3497
+ { position: positionMs / 1e3 },
3498
+ (b) => this.command(import_protocol17.Operations.seek, b)
3499
+ );
3500
+ }
3501
+ seekToMarker(marker) {
3502
+ return this.command(import_protocol17.Operations.seek, { marker });
3503
+ }
3504
+ patch(body) {
3505
+ return this.fader(
3506
+ `patch:${Object.keys(body).join(",")}`,
3507
+ body,
3508
+ (b) => this.command(import_protocol17.Operations.patchPlayer, b)
3509
+ );
3510
+ }
3511
+ /** Player volume 0..1 (fader). */
3512
+ setVolume(v) {
3513
+ return this.patch({ volume: unit(v) });
3514
+ }
3515
+ setOpacity(v) {
3516
+ return this.patch({ opacity: unit(v) });
3517
+ }
3518
+ setRate(rate) {
3519
+ return this.patch({ rate });
3520
+ }
3521
+ setLoop(loop) {
3522
+ return this.patch({ loop });
3523
+ }
3524
+ dispose() {
3525
+ this.offEvents?.();
3526
+ this.offSnapshot?.();
3527
+ this.states.close();
3528
+ }
3529
+ };
3530
+ var unit = (v) => Number.isNaN(v) ? 0 : Math.min(1, Math.max(0, v));
3531
+ var PlaybackRepository = class {
3532
+ constructor(c) {
3533
+ this.c = c;
3534
+ }
3535
+ c;
3536
+ players = /* @__PURE__ */ new Map();
3537
+ outputFaders = /* @__PURE__ */ new Map();
3538
+ /** Handle of a player (`main` of the active venue by default). */
3539
+ player(venueId = "default", playerId = "main") {
3540
+ const k = `${venueId}/${playerId}`;
3541
+ let p = this.players.get(k);
3542
+ if (!p) {
3543
+ p = new PlayerHandle(this.c, venueId, playerId);
3544
+ this.players.set(k, p);
3545
+ }
3546
+ return p;
3547
+ }
3548
+ get main() {
3549
+ return this.player();
3550
+ }
3551
+ get value() {
3552
+ return this.main.value;
3553
+ }
3554
+ watch(fn) {
3555
+ return this.main.watch(fn);
3556
+ }
3557
+ list(venueId = "default") {
3558
+ return readAllPages(this.c.api, import_protocol17.Operations.listPlayers, { params: { venueId } });
3559
+ }
3560
+ play(target, o = {}) {
3561
+ return this.main.play(target, o);
3562
+ }
3563
+ pause() {
3564
+ return this.main.pause();
3565
+ }
3566
+ resume() {
3567
+ return this.main.resume();
3568
+ }
3569
+ stop() {
3570
+ return this.main.stop();
3571
+ }
3572
+ seek(positionMs) {
3573
+ return this.main.seek(positionMs);
3574
+ }
3575
+ next() {
3576
+ return this.main.next();
3577
+ }
3578
+ previous() {
3579
+ return this.main.previous();
3580
+ }
3581
+ /** Fires cue [cueId] of the active show (or of [showId]). */
3582
+ async cue(cueId, o = {}) {
3583
+ await this.c.api.call(import_protocol17.Operations.fireCue, {
3584
+ params: { venueId: o.venueId ?? "default", cueId },
3585
+ body: o.showId ? { showId: o.showId } : {},
3586
+ preferRealtime: true
3587
+ });
3588
+ }
3589
+ /** Loads a show onto the venue. */
3590
+ async setActiveShow(showId, o = {}) {
3591
+ await this.c.api.call(import_protocol17.Operations.setActiveShow, {
3592
+ params: { venueId: o.venueId ?? "default" },
3593
+ body: { showId, autoplay: o.autoplay ?? false }
3594
+ });
3595
+ }
3596
+ activeShow(venueId = "default") {
3597
+ return this.c.api.json(import_protocol17.Operations.getActiveShow, { params: { venueId } });
3598
+ }
3599
+ parameters(venueId = "default") {
3600
+ return readAllPages(this.c.api, import_protocol17.Operations.listParameters, {
3601
+ params: { venueId }
3602
+ });
3603
+ }
3604
+ parameter(path, venueId = "default") {
3605
+ return this.c.api.json(import_protocol17.Operations.getParameter, { params: { venueId, path } });
3606
+ }
3607
+ /** Sets a parameter (fader; coalesced). */
3608
+ async setParameter(path, value, venueId = "default") {
3609
+ const k = `param:${venueId}:${path}`;
3610
+ let f = this.outputFaders.get(k);
3611
+ if (!f) {
3612
+ f = new Fader(async (b) => {
3613
+ await this.c.api.call(import_protocol17.Operations.setParameter, {
3614
+ params: { venueId, path },
3615
+ body: b,
3616
+ preferRealtime: true
3617
+ });
3618
+ return void 0;
3619
+ });
3620
+ this.outputFaders.set(k, f);
3621
+ }
3622
+ await f.set({ value });
3623
+ }
3624
+ /** Removes every payload an app published. */
3625
+ async clearAppPayloads(app) {
3626
+ await this.c.api.call(import_protocol17.Operations.clearAppPayloads, { params: { app }, preferRealtime: true });
3627
+ }
3628
+ /** Master output of a venue. */
3629
+ readOutput(venueId = "default") {
3630
+ return this.c.cachedRead(
3631
+ `output/${venueId}`,
3632
+ async () => {
3633
+ const o = await this.c.api.json(import_protocol17.Operations.getOutput, { params: { venueId } });
3634
+ return [o, o];
3635
+ },
3636
+ (json) => json
3637
+ );
3638
+ }
3639
+ /** Follows the master output (`output.changed` events / patches). */
3640
+ watchOutput(fn, venueId = "default") {
3641
+ let last;
3642
+ const off = this.c.hub.on([import_protocol17.DomeTopics.output(venueId)], (e) => {
3643
+ if (e.resource && typeof e.resource === "object") last = e.resource;
3644
+ else if (e.patch && last) last = (0, import_protocol17.jsonMergePatch)(last, e.patch);
3645
+ else return;
3646
+ fn(last);
3647
+ });
3648
+ void this.readOutput(venueId).then(
3649
+ (o) => {
3650
+ last ??= o;
3651
+ fn(o);
3652
+ },
3653
+ () => void 0
3654
+ );
3655
+ return off;
3656
+ }
3657
+ patchOutput(p, venueId) {
3658
+ const k = `output:${venueId}:${Object.keys(p).join(",")}`;
3659
+ let f = this.outputFaders.get(k);
3660
+ if (!f) {
3661
+ f = new Fader(
3662
+ (b) => this.c.api.json(import_protocol17.Operations.patchOutput, {
3663
+ params: { venueId },
3664
+ body: b,
3665
+ preferRealtime: true
3666
+ })
3667
+ );
3668
+ this.outputFaders.set(k, f);
3669
+ }
3670
+ return f.set(p);
3671
+ }
3672
+ /** Master volume 0..1. */
3673
+ setVolume(v, venueId = "default") {
3674
+ return this.patchOutput({ volume: unit(v) }, venueId);
3675
+ }
3676
+ /** Master brightness 0..1. */
3677
+ setBrightness(v, venueId = "default") {
3678
+ return this.patchOutput({ brightness: unit(v) }, venueId);
3679
+ }
3680
+ setBlackout(on, venueId = "default") {
3681
+ return this.patchOutput({ blackout: on }, venueId);
3682
+ }
3683
+ /** Dome rotation in degrees. */
3684
+ setRotation(degrees, venueId = "default") {
3685
+ return this.patchOutput({ rotation: degrees }, venueId);
3686
+ }
3687
+ dispose() {
3688
+ for (const p of this.players.values()) p.dispose();
3689
+ }
3690
+ };
3691
+
3692
+ // src/repositories/venues.ts
3693
+ var import_protocol18 = require("@freedome/protocol");
3694
+ var CALIBRATION_FILE_TYPES = {
3695
+ warp: "application/vnd.nativemind.freedome.fdmesh",
3696
+ blend: "image/png",
3697
+ colour: "text/plain"
3698
+ };
3699
+ var VenuesRepository = class {
3700
+ constructor(c) {
3701
+ this.c = c;
3702
+ }
3703
+ c;
3704
+ get api() {
3705
+ return this.c.api;
3706
+ }
3707
+ /** All venues (cache-backed: `stale` while offline). */
3708
+ async list() {
3709
+ return this.c.cachedRead(
3710
+ "venues",
3711
+ async () => {
3712
+ const l = await readAllPages(this.api, import_protocol18.Operations.listVenues);
3713
+ return [{ value: l, etag: void 0 }, l];
3714
+ },
3715
+ (json, asOf) => ({ value: json, etag: void 0, stale: true, asOf })
3716
+ );
3717
+ }
3718
+ /** One venue with its ETag (`default` = the active venue). */
3719
+ async get(venueId = "default") {
3720
+ const res = await this.api.call(import_protocol18.Operations.getVenue, { params: { venueId } });
3721
+ return { value: ApiCaller.decodeBody(import_protocol18.Operations.getVenue, res), etag: res.headers.etag };
3722
+ }
3723
+ /** The venue the server runs now. */
3724
+ async current() {
3725
+ return (await this.get("default")).value;
3726
+ }
3727
+ /** Creates a venue (`POST /venues`; id = `meta.id`). */
3728
+ async create(body) {
3729
+ const res = await this.api.call(import_protocol18.Operations.createVenue, { body });
3730
+ return {
3731
+ value: ApiCaller.decodeBody(import_protocol18.Operations.createVenue, res),
3732
+ etag: res.headers.etag
3733
+ };
3734
+ }
3735
+ /** Replaces a venue (`ifMatch` = ETag; without it: create with If-None-Match: *). 409 / 412 → ConflictError with `latest`. */
3736
+ async save(venueId, body, ifMatch) {
3737
+ try {
3738
+ const res = await this.api.call(import_protocol18.Operations.putVenue, {
3739
+ params: { venueId },
3740
+ body,
3741
+ headers: ifMatch ? { "if-match": ifMatch } : { "if-none-match": "*" }
3742
+ });
3743
+ return {
3744
+ value: ApiCaller.decodeBody(import_protocol18.Operations.putVenue, res),
3745
+ etag: res.headers.etag
3746
+ };
3747
+ } catch (e) {
3748
+ if (!(e instanceof ConflictError)) throw e;
3749
+ let latest;
3750
+ try {
3751
+ latest = await this.get(venueId);
3752
+ } catch (x) {
3753
+ if (!(x instanceof FreedomeError)) throw x;
3754
+ }
3755
+ throw new ConflictError(e.message, {
3756
+ latest,
3757
+ ...e.problem ? { problem: e.problem } : {},
3758
+ ...e.code ? { code: e.code } : {}
3759
+ });
3760
+ }
3761
+ }
3762
+ /** Merge-patches a venue (reads the ETag when not given). */
3763
+ async patch(venueId, patch, ifMatch) {
3764
+ const etag = ifMatch ?? (await this.get(venueId)).etag;
3765
+ const res = await this.api.call(import_protocol18.Operations.patchVenue, {
3766
+ params: { venueId },
3767
+ body: patch,
3768
+ headers: { "if-match": etag }
3769
+ });
3770
+ return {
3771
+ value: ApiCaller.decodeBody(import_protocol18.Operations.patchVenue, res),
3772
+ etag: res.headers.etag
3773
+ };
3774
+ }
3775
+ /** Watches a venue (events, resync re-read, polling while realtime is down). */
3776
+ watch(venueId, obs, intervalMs = 5e3) {
3777
+ return this.c.watchResource(
3778
+ import_protocol18.DomeTopics.venue(venueId),
3779
+ async () => (await this.get(venueId)).value,
3780
+ obs,
3781
+ {
3782
+ intervalMs,
3783
+ kinds: /* @__PURE__ */ new Set([import_protocol18.EventKinds.venueUpdated])
3784
+ }
3785
+ );
3786
+ }
3787
+ /** Exports the venue as `.dome` bytes. */
3788
+ async export(venueId = "default") {
3789
+ const res = await this.api.call(import_protocol18.Operations.exportVenue, {
3790
+ params: { venueId },
3791
+ headers: { accept: "application/vnd.nativemind.freedome.dome+zip, application/problem+json" },
3792
+ timeoutMs: 3e5
3793
+ });
3794
+ return res.body;
3795
+ }
3796
+ /** Calibration block with the venue ETag. */
3797
+ async calibration(venueId = "default") {
3798
+ const res = await this.api.call(import_protocol18.Operations.getCalibration, { params: { venueId } });
3799
+ return {
3800
+ value: ApiCaller.decodeBody(import_protocol18.Operations.getCalibration, res),
3801
+ etag: res.headers.etag
3802
+ };
3803
+ }
3804
+ /** Bytes of a calibration sidecar. */
3805
+ async calibrationFile(venueId, displayId, file) {
3806
+ return (await this.api.call(import_protocol18.Operations.getCalibrationFile, {
3807
+ params: { venueId, displayId, file },
3808
+ headers: { accept: "*/*" }
3809
+ })).body;
3810
+ }
3811
+ /** Uploads a calibration sidecar (If-Match = venue ETag, read when not given). */
3812
+ async putCalibrationFile(venueId, displayId, file, bytes, ifMatch) {
3813
+ const etag = ifMatch ?? (await this.calibration(venueId)).etag;
3814
+ const res = await this.api.call(import_protocol18.Operations.putCalibrationFile, {
3815
+ params: { venueId, displayId, file },
3816
+ bytes,
3817
+ contentType: CALIBRATION_FILE_TYPES[file],
3818
+ headers: { "if-match": etag }
3819
+ });
3820
+ return {
3821
+ value: ApiCaller.decodeBody(import_protocol18.Operations.putCalibrationFile, res),
3822
+ etag: res.headers.etag
3823
+ };
3824
+ }
3825
+ };
3826
+
3827
+ // src/client.ts
3828
+ var FREEDOME_CLIENT_VERSION = "1.0.0-rc.1";
3829
+ function defaultTransports() {
3830
+ return { rest: (e) => new FetchTransport(e), sockets: webSocketConnector() };
3831
+ }
3832
+ var FreedomeClient = class {
3833
+ credentials;
3834
+ options;
3835
+ tokenStore;
3836
+ cache;
3837
+ outbox;
3838
+ logger;
3839
+ venues;
3840
+ engine;
3841
+ calibration;
3842
+ playback;
3843
+ content;
3844
+ osc;
3845
+ clients;
3846
+ audio;
3847
+ audioReactive;
3848
+ gateways;
3849
+ graphql;
3850
+ /** Connection state changes. */
3851
+ states = new Emitter();
3852
+ /** Session changes. */
3853
+ sessions = new Emitter();
3854
+ transports;
3855
+ api;
3856
+ hub = new EventHub();
3857
+ ctx;
3858
+ random;
3859
+ customConnector;
3860
+ endpointValue;
3861
+ serverInfo;
3862
+ sessionValue = NO_SESSION;
3863
+ stateValue = "idle";
3864
+ reason;
3865
+ refreshing;
3866
+ channel;
3867
+ offChannel = [];
3868
+ retry;
3869
+ background;
3870
+ attempt = 0;
3871
+ suspended = false;
3872
+ engineDegraded = false;
3873
+ connecting = false;
3874
+ constructor(init) {
3875
+ const o = init.options ?? {};
3876
+ this.options = {
3877
+ realtime: o.realtime ?? "ws",
3878
+ requestTimeoutMs: o.requestTimeoutMs ?? 1e4,
3879
+ heartbeatMs: o.heartbeatMs ?? 15e3,
3880
+ reconnect: o.reconnect ?? new BackoffPolicy(),
3881
+ offline: { ...DEFAULT_OFFLINE_POLICY, ...o.offline },
3882
+ appName: o.appName ?? "app",
3883
+ appVersion: o.appVersion ?? "0",
3884
+ pairingPollIntervalMs: o.pairingPollIntervalMs ?? 1e3,
3885
+ backgroundGraceMs: o.backgroundGraceMs ?? 3e4,
3886
+ ...o.positionHz !== void 0 ? { positionHz: o.positionHz } : {}
3887
+ };
3888
+ this.endpointValue = init.endpoint;
3889
+ this.credentials = init.credentials ?? { kind: "guest" };
3890
+ this.tokenStore = init.tokenStore ?? new InMemoryTokenStore();
3891
+ this.cache = init.cache ?? new InMemoryCacheStore();
3892
+ this.outbox = init.outbox;
3893
+ this.logger = init.logger;
3894
+ this.transports = init.transports ?? defaultTransports();
3895
+ this.customConnector = init.realtimeConnector;
3896
+ this.random = init.random ?? Math.random;
3897
+ this.api = new ApiCaller(
3898
+ this.transports.rest(init.endpoint),
3899
+ this.userAgent,
3900
+ this.options.requestTimeoutMs,
3901
+ init.logger
3902
+ );
3903
+ this.api.onUnauthorized = () => this.refresh();
3904
+ this.api.realtime = () => this.channel;
3905
+ this.api.isOffline = () => this.stateValue === "offline";
3906
+ this.api.onTransportFailure = () => this.onTransportFailure();
3907
+ this.hub.onSubscribe = (f) => this.subscribeFilters(f);
3908
+ this.hub.onUnsubscribe = async (f) => {
3909
+ await this.channel?.unsubscribe(f);
3910
+ };
3911
+ this.ctx = new RepositoryContext(
3912
+ this.api,
3913
+ this.hub,
3914
+ this.cache,
3915
+ this.outbox,
3916
+ this.options.offline,
3917
+ () => this.stateValue === "offline",
3918
+ () => this.endpointValue.storageKey,
3919
+ () => this.channel !== void 0,
3920
+ this.options.positionHz,
3921
+ (s) => this.onEngineHealth(s),
3922
+ init.logger
3923
+ );
3924
+ this.graphql = new GraphqlClient(this.api);
3925
+ this.venues = new VenuesRepository(this.ctx);
3926
+ this.engine = new EngineRepository(this.ctx);
3927
+ this.calibration = new CalibrationRepository(this.ctx);
3928
+ this.playback = new PlaybackRepository(this.ctx);
3929
+ this.content = new ContentRepository(this.ctx);
3930
+ this.osc = new OscRepository(this.ctx);
3931
+ this.clients = new ClientsRepository(this.ctx);
3932
+ this.audio = new AudioRepository(this.ctx);
3933
+ this.audioReactive = new AudioReactiveRepository(this.ctx);
3934
+ this.gateways = new GatewaysRepository(this.ctx);
3935
+ }
3936
+ get userAgent() {
3937
+ return `${this.options.appName}/${this.options.appVersion} @freedome/client/${FREEDOME_CLIENT_VERSION}`;
3938
+ }
3939
+ get endpoint() {
3940
+ return this.endpointValue;
3941
+ }
3942
+ get server() {
3943
+ return this.serverInfo;
3944
+ }
3945
+ get state() {
3946
+ return this.stateValue;
3947
+ }
3948
+ /** Reason of `degraded` / `offline` / `reconnecting`. */
3949
+ get stateReason() {
3950
+ return this.reason;
3951
+ }
3952
+ get session() {
3953
+ return this.sessionValue;
3954
+ }
3955
+ /** Transport of the open realtime channel. */
3956
+ get realtimeTransport() {
3957
+ return this.channel?.kind;
3958
+ }
3959
+ /** Replay results of queued writes. */
3960
+ get outboxOutcomes() {
3961
+ return this.ctx.outboxOutcomes;
3962
+ }
3963
+ /** Whether the server advertises [capability] (`transport.ws`, `audio`, dotted paths into `capabilities`). */
3964
+ supports(capability) {
3965
+ const info = this.serverInfo;
3966
+ if (!info) return false;
3967
+ const transport = capability.startsWith("transport.");
3968
+ let node = transport ? info.transports : info.capabilities;
3969
+ for (const seg of (transport ? capability.slice(10) : capability).split(".")) {
3970
+ if (Array.isArray(node)) return node.includes(seg);
3971
+ if (typeof node === "object" && node !== null) node = node[seg];
3972
+ else return false;
3973
+ }
3974
+ if (node === void 0 || node === null || node === false) return false;
3975
+ if (Array.isArray(node)) return node.length > 0;
3976
+ if (typeof node === "object") return Object.keys(node).length > 0;
3977
+ return true;
3978
+ }
3979
+ /** Events matching [filters] (`+` / `#` wildcards); subscribes while listened to. */
3980
+ on(filters, fn) {
3981
+ return this.hub.on(typeof filters === "string" ? [filters] : filters, fn);
3982
+ }
3983
+ /** Raw contract call (escape hatch for operations without a repository method). */
3984
+ send(op, o = {}) {
3985
+ return this.api.call(op, o);
3986
+ }
3987
+ /** Raw call returning parsed JSON. */
3988
+ async request(op, o = {}) {
3989
+ const res = await this.api.call(op, {
3990
+ ...o,
3991
+ headers: { ...o.headers, ...o.ifMatch ? { "if-match": o.ifMatch } : {} }
3992
+ });
3993
+ return res.body.length ? res.json : void 0;
3994
+ }
3995
+ set(s, reason) {
3996
+ this.reason = s === "degraded" || s === "offline" || s === "reconnecting" ? reason ?? this.reason : void 0;
3997
+ if (this.stateValue === s) return;
3998
+ this.stateValue = s;
3999
+ this.states.emit(s);
4000
+ this.log("info", `state \u2192 ${s}${reason ? ` (${reason})` : ""}`);
4001
+ }
4002
+ setSession(s) {
4003
+ this.sessionValue = s;
4004
+ this.sessions.emit(s);
4005
+ }
4006
+ log(level, message, error) {
4007
+ this.logger?.({ level, message, ...error === void 0 ? {} : { error } });
4008
+ }
4009
+ /** Negotiates, authenticates and starts realtime. */
4010
+ async open() {
4011
+ if (this.stateValue === "closed") throw new Error("client is closed");
4012
+ await this.negotiate();
4013
+ this.set("authenticating");
4014
+ try {
4015
+ await this.authenticate();
4016
+ } catch (e) {
4017
+ if (e instanceof UnauthorizedError || e instanceof ForbiddenError) this.set("unauthorized");
4018
+ else if (e instanceof NetworkError) this.set("offline", "server not reachable");
4019
+ throw e;
4020
+ }
4021
+ await this.startRealtime(true);
4022
+ }
4023
+ async negotiate() {
4024
+ this.set("negotiating");
4025
+ let info;
4026
+ try {
4027
+ info = await this.api.json(import_protocol19.Operations.getInfo, { authenticated: false });
4028
+ } catch (e) {
4029
+ if (e instanceof NetworkError) {
4030
+ this.set("offline", "server not reachable");
4031
+ throw e;
4032
+ }
4033
+ if (e instanceof RequestTimeoutError) {
4034
+ this.set("offline", "server not answering");
4035
+ throw e;
4036
+ }
4037
+ this.set("incompatible");
4038
+ throw new IncompatibleServerError(
4039
+ `no Freedome API v1 at ${this.endpointValue.apiBase} (${e.message})`,
4040
+ [],
4041
+ import_protocol19.ProtocolVersions.apiMajors
4042
+ );
4043
+ }
4044
+ const versions = (info.apiVersions ?? []).map(String);
4045
+ const majors = versions.map((v) => Number.parseInt(v.replace(/^v/, ""), 10));
4046
+ if (!majors.some((m) => import_protocol19.ProtocolVersions.apiMajors.includes(m))) {
4047
+ this.set("incompatible");
4048
+ throw new IncompatibleServerError(
4049
+ `server speaks ${versions.join(", ")}, this client v${import_protocol19.ProtocolVersions.apiMajors.join(", v")}`,
4050
+ versions,
4051
+ import_protocol19.ProtocolVersions.apiMajors
4052
+ );
4053
+ }
4054
+ this.serverInfo = info;
4055
+ const id = info.instanceId;
4056
+ if (!this.endpointValue.id && id) this.endpointValue = this.endpointValue.withId(id);
4057
+ return info;
4058
+ }
4059
+ async authenticate() {
4060
+ const key = this.endpointValue.storageKey;
4061
+ const c = this.credentials;
4062
+ const client = { app: this.options.appName, appVersion: this.options.appVersion };
4063
+ switch (c.kind) {
4064
+ case "guest":
4065
+ this.api.authorization = void 0;
4066
+ this.setSession({ role: "guest", scopes: scopesOfRole("guest") });
4067
+ return;
4068
+ case "apiKey":
4069
+ this.api.authorization = `Bearer ${c.key}`;
4070
+ this.setSession(sessionFromPrincipal(await this.api.json(import_protocol19.Operations.getMe)));
4071
+ return;
4072
+ case "password": {
4073
+ const stored = await this.tokenStore.read(key);
4074
+ if (stored && await this.tryStored(stored)) return;
4075
+ const t = await this.api.json(import_protocol19.Operations.createSession, {
4076
+ body: { username: c.username, password: c.password, client },
4077
+ authenticated: false
4078
+ });
4079
+ await this.adopt(t, c.username);
4080
+ return;
4081
+ }
4082
+ case "pairing": {
4083
+ const stored = await this.tokenStore.read(key);
4084
+ if (stored && await this.tryStored(stored)) return;
4085
+ await this.pair(c);
4086
+ return;
4087
+ }
4088
+ case "cloud": {
4089
+ const stored = await this.tokenStore.read(key);
4090
+ if (stored && await this.tryStored(stored)) return;
4091
+ const t = await this.api.json(import_protocol19.Operations.exchangeCloudToken, {
4092
+ body: { subjectToken: await c.token(), client },
4093
+ authenticated: false
4094
+ });
4095
+ await this.adopt(t);
4096
+ return;
4097
+ }
4098
+ }
4099
+ }
4100
+ async tryStored(t) {
4101
+ this.api.authorization = `Bearer ${t.accessToken}`;
4102
+ try {
4103
+ this.setSession(sessionFromPrincipal(await this.api.json(import_protocol19.Operations.getMe)));
4104
+ return true;
4105
+ } catch (e) {
4106
+ if (!(e instanceof UnauthorizedError)) throw e;
4107
+ await this.tokenStore.delete(this.endpointValue.storageKey);
4108
+ this.api.authorization = void 0;
4109
+ return false;
4110
+ }
4111
+ }
4112
+ async adopt(t, user) {
4113
+ this.api.authorization = `Bearer ${t.accessToken}`;
4114
+ await this.tokenStore.write(this.endpointValue.storageKey, storedTokensOf(t));
4115
+ this.setSession(sessionFromTokens(t, user ?? this.sessionValue.user));
4116
+ }
4117
+ async pair(p) {
4118
+ let pairing = await this.api.json(import_protocol19.Operations.createPairing, {
4119
+ body: {
4120
+ app: p.app,
4121
+ deviceName: p.deviceName,
4122
+ ...p.requestedRole ? { requestedRole: p.requestedRole } : {}
4123
+ },
4124
+ authenticated: false
4125
+ });
4126
+ const pr = () => pairing;
4127
+ const linkCode = p.code ?? this.endpointValue.pairingCode;
4128
+ const code = pr().code;
4129
+ if (code) {
4130
+ if (linkCode && linkCode !== code)
4131
+ this.log(
4132
+ "warning",
4133
+ `pairing code from the link differs from the server's \u2014 approve ${code} on the dome`
4134
+ );
4135
+ if (pr().status !== "approved") p.onCode?.(code);
4136
+ }
4137
+ const deadline = Date.now() + (p.timeoutMs ?? 12e4);
4138
+ while (!["approved", "denied", "expired", "revoked"].includes(pr().status)) {
4139
+ if (Date.now() > deadline) throw new UnauthorizedError("pairing was not approved in time");
4140
+ await new Promise((r) => setTimeout(r, this.options.pairingPollIntervalMs));
4141
+ pairing = await this.api.json(import_protocol19.Operations.getPairing, {
4142
+ params: { pairingId: pr().pairingId },
4143
+ authenticated: false
4144
+ });
4145
+ }
4146
+ const tokens = pr().tokens;
4147
+ if (pr().status !== "approved" || !tokens)
4148
+ throw new UnauthorizedError(`pairing ${pr().status}`);
4149
+ await this.adopt(tokens, p.deviceName);
4150
+ }
4151
+ refresh() {
4152
+ this.refreshing ??= (async () => {
4153
+ try {
4154
+ if (this.credentials.kind === "apiKey" || this.credentials.kind === "guest") return false;
4155
+ const stored = await this.tokenStore.read(this.endpointValue.storageKey);
4156
+ const rt = stored?.refreshToken;
4157
+ if (!rt) return await this.reauthenticate();
4158
+ try {
4159
+ const t = await this.api.json(import_protocol19.Operations.refreshSession, {
4160
+ body: { refreshToken: rt },
4161
+ authenticated: false
4162
+ });
4163
+ await this.adopt(t);
4164
+ return true;
4165
+ } catch (e) {
4166
+ if (!(e instanceof UnauthorizedError)) throw e;
4167
+ this.log("warning", "refresh rejected", e);
4168
+ await this.tokenStore.delete(this.endpointValue.storageKey);
4169
+ return await this.reauthenticate();
4170
+ }
4171
+ } finally {
4172
+ this.refreshing = void 0;
4173
+ }
4174
+ })();
4175
+ return this.refreshing;
4176
+ }
4177
+ async reauthenticate() {
4178
+ if (this.credentials.kind === "cloud") {
4179
+ try {
4180
+ this.api.authorization = void 0;
4181
+ await this.authenticate();
4182
+ return true;
4183
+ } catch (e) {
4184
+ this.log("warning", "cloud re-authentication failed", e);
4185
+ }
4186
+ }
4187
+ this.api.authorization = void 0;
4188
+ this.setSession(NO_SESSION);
4189
+ this.set("unauthorized");
4190
+ await this.dropRealtime();
4191
+ return false;
4192
+ }
4193
+ /** Ends the session on the server and locally. */
4194
+ async logout() {
4195
+ if (this.api.authorization && this.credentials.kind !== "apiKey") {
4196
+ try {
4197
+ await this.api.call(import_protocol19.Operations.deleteSession);
4198
+ } catch (e) {
4199
+ this.log("warning", "logout", e);
4200
+ }
4201
+ }
4202
+ await this.tokenStore.delete(this.endpointValue.storageKey);
4203
+ this.api.authorization = void 0;
4204
+ this.setSession(NO_SESSION);
4205
+ if (this.retry) clearTimeout(this.retry);
4206
+ await this.dropRealtime();
4207
+ this.set("unauthorized");
4208
+ }
4209
+ get token() {
4210
+ const a = this.api.authorization;
4211
+ return a?.startsWith("Bearer ") ? a.slice(7) : void 0;
4212
+ }
4213
+ connector() {
4214
+ if (this.customConnector) return this.customConnector;
4215
+ const kind = this.options.realtime;
4216
+ if (kind === "none") return void 0;
4217
+ const log = this.logger ? { logger: this.logger } : {};
4218
+ if (kind === "socketIo") {
4219
+ return (_k, hello, o) => SocketIoChannel.open(this.endpointValue, hello, { timeoutMs: o.timeoutMs, ...log });
4220
+ }
4221
+ const sockets = this.transports.sockets;
4222
+ if (!sockets) return void 0;
4223
+ return async (k, hello, o) => {
4224
+ if (k === "graphqlWs") {
4225
+ const s2 = await sockets(
4226
+ this.endpointValue,
4227
+ "/api/v1/graphql",
4228
+ [GRAPHQL_WS_SUBPROTOCOL],
4229
+ o.timeoutMs
4230
+ );
4231
+ return GraphqlWsChannel.open(s2, hello, { ...o, ...log });
4232
+ }
4233
+ const s = await sockets(this.endpointValue, "/api/v1/ws", [import_protocol19.WS_SUBPROTOCOL], o.timeoutMs);
4234
+ return WsChannel.open(s, hello, { ...o, ...log });
4235
+ };
4236
+ }
4237
+ async startRealtime(initial = false) {
4238
+ const connect = this.connector();
4239
+ if (!connect) {
4240
+ const none = this.options.realtime === "none";
4241
+ this.set(
4242
+ none ? "online" : "degraded",
4243
+ none ? void 0 : `realtime transport ${this.options.realtime} not available`
4244
+ );
4245
+ void this.replayOutbox();
4246
+ return;
4247
+ }
4248
+ if (this.connecting) return;
4249
+ this.connecting = true;
4250
+ try {
4251
+ if (!initial) this.set("resyncing");
4252
+ let ch;
4253
+ try {
4254
+ const token = this.token;
4255
+ const since = this.hub.lastSeq;
4256
+ ch = await connect(
4257
+ this.options.realtime,
4258
+ {
4259
+ app: this.options.appName,
4260
+ appVersion: this.options.appVersion,
4261
+ sdk: `@freedome/client/${FREEDOME_CLIENT_VERSION}`,
4262
+ ...token ? { token } : {},
4263
+ ...since !== void 0 ? { sinceSeq: since } : {}
4264
+ },
4265
+ { timeoutMs: this.options.requestTimeoutMs, heartbeatMs: this.options.heartbeatMs }
4266
+ );
4267
+ } catch (e) {
4268
+ if (e instanceof UnauthorizedError) {
4269
+ if (await this.refresh()) {
4270
+ this.connecting = false;
4271
+ return await this.startRealtime(initial);
4272
+ }
4273
+ return;
4274
+ }
4275
+ if (e instanceof FreedomeError) {
4276
+ this.log("warning", "realtime connect failed", e);
4277
+ this.set("degraded", `realtime unavailable: ${e.message}`);
4278
+ this.scheduleReconnect();
4279
+ return;
4280
+ }
4281
+ throw e;
4282
+ }
4283
+ if (this.stateValue === "closed") {
4284
+ await ch.close();
4285
+ return;
4286
+ }
4287
+ this.channel = ch;
4288
+ this.attempt = 0;
4289
+ const epochChanged = this.hub.newEpoch(
4290
+ ch.welcome?.instanceId ?? this.serverInfo?.instanceId
4291
+ );
4292
+ this.offChannel = [
4293
+ ch.events.on((e) => this.hub.dispatch(e)),
4294
+ ch.resyncs.on((r) => {
4295
+ this.log("info", `resync ${r.reason}: ${r.topics.join(",")}`);
4296
+ void this.hub.snapshot(r.topics);
4297
+ })
4298
+ ];
4299
+ void ch.closed.then((c) => this.onRealtimeClosed(ch, c));
4300
+ const filters = this.hub.filters;
4301
+ if (filters.length) {
4302
+ try {
4303
+ const since = this.hub.lastSeq;
4304
+ await ch.subscribe(filters, {
4305
+ ...since !== void 0 ? { sinceSeq: since } : {},
4306
+ ...this.options.positionHz !== void 0 ? { positionHz: this.options.positionHz } : {}
4307
+ });
4308
+ } catch (e) {
4309
+ this.log("warning", "re-subscribe failed", e);
4310
+ }
4311
+ await this.seedSeq(filters);
4312
+ }
4313
+ if (!initial || epochChanged) await this.hub.snapshot(["#"]);
4314
+ if (this.stateValue !== "closed" && this.channel === ch) {
4315
+ this.set(
4316
+ this.engineDegraded ? "degraded" : "online",
4317
+ this.engineDegraded ? "engine degraded" : void 0
4318
+ );
4319
+ void this.replayOutbox();
4320
+ }
4321
+ } finally {
4322
+ this.connecting = false;
4323
+ }
4324
+ }
4325
+ async replayOutbox() {
4326
+ if (!this.outbox) return;
4327
+ await this.ctx.replayOutbox(async (e) => {
4328
+ const op = import_protocol19.Operations[e.operationId];
4329
+ if (!op || op.method !== "PUT" && op.method !== "PATCH") return void 0;
4330
+ const get = Object.values(import_protocol19.Operations).find(
4331
+ (o) => o.method === "GET" && o.path === op.path
4332
+ );
4333
+ if (!get) return void 0;
4334
+ const res = await this.api.call(get, { params: e.params });
4335
+ return { value: res.json, etag: res.headers.etag };
4336
+ });
4337
+ }
4338
+ async subscribeFilters(filters) {
4339
+ const ch = this.channel;
4340
+ if (!ch) return false;
4341
+ await ch.subscribe(
4342
+ filters,
4343
+ this.options.positionHz !== void 0 ? { positionHz: this.options.positionHz } : {}
4344
+ );
4345
+ await this.seedSeq(filters);
4346
+ return true;
4347
+ }
4348
+ async seedSeq(filters) {
4349
+ if (this.hub.lastSeq !== void 0) return;
4350
+ try {
4351
+ const page = await this.api.json(import_protocol19.Operations.listEvents, {
4352
+ query: { topics: filters.join(","), limit: "1" }
4353
+ });
4354
+ if (typeof page.lastSeq === "number") this.hub.seed(page.lastSeq);
4355
+ } catch (e) {
4356
+ this.log("debug", `no resume point (${e.code ?? e})`);
4357
+ }
4358
+ }
4359
+ async dropRealtime() {
4360
+ const ch = this.channel;
4361
+ this.channel = void 0;
4362
+ for (const off of this.offChannel) off();
4363
+ this.offChannel = [];
4364
+ await ch?.close();
4365
+ }
4366
+ onRealtimeClosed(ch, c) {
4367
+ if (this.channel !== ch) return;
4368
+ this.channel = void 0;
4369
+ for (const off of this.offChannel) off();
4370
+ this.offChannel = [];
4371
+ if (this.stateValue === "closed" || this.suspended) return;
4372
+ this.log("warning", `realtime lost: ${c.code ?? ""} ${c.reason ?? ""}`);
4373
+ if (isAuthFailure(c)) {
4374
+ void this.refresh().then((ok) => {
4375
+ if (ok) this.scheduleReconnect(true);
4376
+ else if (this.stateValue !== "unauthorized" && this.stateValue !== "closed") {
4377
+ this.api.authorization = void 0;
4378
+ this.setSession(NO_SESSION);
4379
+ this.set("unauthorized", c.reason);
4380
+ }
4381
+ });
4382
+ return;
4383
+ }
4384
+ this.set("reconnecting", c.reason);
4385
+ this.scheduleReconnect();
4386
+ }
4387
+ onTransportFailure() {
4388
+ if (this.stateValue === "online" || this.stateValue === "degraded")
4389
+ this.scheduleReconnect(this.channel === void 0);
4390
+ }
4391
+ onEngineHealth(status) {
4392
+ const degraded = status !== "up";
4393
+ if (degraded === this.engineDegraded) return;
4394
+ this.engineDegraded = degraded;
4395
+ if (this.stateValue === "online" && degraded) this.set("degraded", `engine ${status}`);
4396
+ else if (this.stateValue === "degraded" && !degraded && this.channel) this.set("online");
4397
+ }
4398
+ scheduleReconnect(immediate = false) {
4399
+ if (this.stateValue === "closed" || this.suspended) return;
4400
+ if (this.retry) clearTimeout(this.retry);
4401
+ const delay = immediate ? 0 : this.options.reconnect.delay(this.attempt, this.random);
4402
+ this.retry = setTimeout(() => void this.reconnect(), delay);
4403
+ }
4404
+ async reconnect() {
4405
+ if (this.stateValue === "closed" || this.suspended || this.connecting) return;
4406
+ if (this.channel && this.stateValue === "online") return;
4407
+ this.attempt++;
4408
+ try {
4409
+ const info = await this.negotiate();
4410
+ if (this.hub.newEpoch(info.instanceId))
4411
+ this.log("info", "server instance changed \u2014 full resync");
4412
+ } catch (e) {
4413
+ if (e instanceof IncompatibleServerError) return;
4414
+ this.set(
4415
+ this.attempt >= this.options.offline.failAfterAttempts ? "offline" : "reconnecting",
4416
+ e.message
4417
+ );
4418
+ this.scheduleReconnect();
4419
+ return;
4420
+ }
4421
+ await this.startRealtime();
4422
+ }
4423
+ /** The OS reports connectivity: reconnect now. */
4424
+ networkAvailable() {
4425
+ this.attempt = 0;
4426
+ if (this.stateValue !== "online" && this.stateValue !== "idle") this.scheduleReconnect(true);
4427
+ }
4428
+ /** The OS reports no network: go offline (reads served from cache). */
4429
+ networkLost() {
4430
+ if (this.stateValue === "closed" || this.stateValue === "idle") return;
4431
+ void this.dropRealtime();
4432
+ this.set("offline", "no network");
4433
+ this.scheduleReconnect();
4434
+ }
4435
+ /** App moved to the background: realtime is suspended after the grace period. */
4436
+ enterBackground() {
4437
+ if (this.background) clearTimeout(this.background);
4438
+ this.background = setTimeout(() => {
4439
+ this.suspended = true;
4440
+ if (this.retry) clearTimeout(this.retry);
4441
+ void this.dropRealtime();
4442
+ this.log("info", "background: realtime suspended");
4443
+ }, this.options.backgroundGraceMs);
4444
+ }
4445
+ /** App back in the foreground. */
4446
+ resume() {
4447
+ if (this.background) clearTimeout(this.background);
4448
+ const was = this.suspended;
4449
+ this.suspended = false;
4450
+ this.attempt = 0;
4451
+ if (was || !this.channel) this.scheduleReconnect(true);
4452
+ }
4453
+ /** Closes everything (terminal). */
4454
+ async close() {
4455
+ if (this.stateValue === "closed") return;
4456
+ this.set("closed");
4457
+ if (this.retry) clearTimeout(this.retry);
4458
+ if (this.background) clearTimeout(this.background);
4459
+ await this.dropRealtime();
4460
+ this.playback.dispose();
4461
+ this.hub.close();
4462
+ this.ctx.close();
4463
+ await this.api.transport.close();
4464
+ this.states.close();
4465
+ this.sessions.close();
4466
+ }
4467
+ };
4468
+
4469
+ // src/discovery.ts
4470
+ var import_protocol20 = require("@freedome/protocol");
4471
+
4472
+ // src/endpoint.ts
4473
+ var FreedomeEndpoint = class _FreedomeEndpoint {
4474
+ constructor(baseUrl, opts = {}) {
4475
+ this.opts = opts;
4476
+ const u = new URL(String(baseUrl));
4477
+ this.baseUrl = `${u.protocol}//${u.host}`;
4478
+ }
4479
+ opts;
4480
+ baseUrl;
4481
+ /** `host[:port]`, `http(s)://…` or a `freedome://pair?…` link (default port 8080 / 443). */
4482
+ static parse(text) {
4483
+ const t = text.trim();
4484
+ if (t.startsWith("freedome://")) return PairingLink.parse(t).endpoint;
4485
+ const u = new URL(t.includes("://") ? t : `http://${t}`);
4486
+ if (u.protocol !== "http:" && u.protocol !== "https:")
4487
+ throw new TypeError(`unsupported scheme "${u.protocol}"`);
4488
+ if (!u.hostname) throw new TypeError("no host");
4489
+ if (!u.port) u.port = u.protocol === "https:" ? "443" : "8080";
4490
+ return new _FreedomeEndpoint(u);
4491
+ }
4492
+ get id() {
4493
+ return this.opts.id;
4494
+ }
4495
+ get tlsFingerprint() {
4496
+ return this.opts.tlsFingerprint;
4497
+ }
4498
+ get pairingCode() {
4499
+ return this.opts.pairingCode;
4500
+ }
4501
+ /** `<base>/api/v1`. */
4502
+ get apiBase() {
4503
+ return `${this.baseUrl}/api/v1`;
4504
+ }
4505
+ /** WebSocket base (`ws://` / `wss://`). */
4506
+ get wsBase() {
4507
+ return this.baseUrl.replace(/^http/, "ws");
4508
+ }
4509
+ /** Key of the stored tokens / caches (server instance id once known). */
4510
+ get storageKey() {
4511
+ return this.opts.id ?? this.baseUrl;
4512
+ }
4513
+ withId(id) {
4514
+ return new _FreedomeEndpoint(this.baseUrl, { ...this.opts, id });
4515
+ }
4516
+ toString() {
4517
+ return `FreedomeEndpoint(${this.baseUrl}${this.opts.id ? `, id: ${this.opts.id}` : ""})`;
4518
+ }
4519
+ };
4520
+ 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:.]*)$/;
4521
+ var PairingLink = class _PairingLink {
4522
+ constructor(host, port = 8080, opts = {}) {
4523
+ this.host = host;
4524
+ this.port = port;
4525
+ this.opts = opts;
4526
+ }
4527
+ host;
4528
+ port;
4529
+ opts;
4530
+ static parse(text) {
4531
+ let u;
4532
+ try {
4533
+ u = new URL(text.trim());
4534
+ } catch {
4535
+ throw new TypeError("not a pairing link");
4536
+ }
4537
+ if (u.protocol !== "freedome:" || u.hostname !== "pair" && u.host !== "pair")
4538
+ throw new TypeError("not a freedome://pair link");
4539
+ const q = u.searchParams;
4540
+ const host = q.get("host");
4541
+ if (!host || !HOST.test(host)) throw new TypeError("pairing link: bad or missing host");
4542
+ const portText = q.get("port");
4543
+ const port = portText === null ? 8080 : Number(portText);
4544
+ if (!Number.isInteger(port) || port < 1 || port > 65535)
4545
+ throw new TypeError("pairing link: bad port");
4546
+ const id = q.get("id");
4547
+ if (id !== null && !/^[A-Za-z0-9._-]{1,64}$/.test(id))
4548
+ throw new TypeError("pairing link: bad id");
4549
+ const code = q.get("code");
4550
+ if (code !== null && !/^[0-9]{6}$/.test(code))
4551
+ throw new TypeError("pairing link: code must be 6 digits");
4552
+ const fp = q.get("fp");
4553
+ if (fp !== null && !/^(?:[0-9A-Fa-f]{2}:?){8,32}$/.test(fp))
4554
+ throw new TypeError("pairing link: fp must be \u2265 16 hex digits");
4555
+ const name = q.get("name");
4556
+ if (name !== null && name.length > 128) throw new TypeError("pairing link: name too long");
4557
+ return new _PairingLink(host, port, {
4558
+ ...id !== null ? { id } : {},
4559
+ ...code !== null ? { code } : {},
4560
+ ...fp !== null ? { fingerprint: fp } : {},
4561
+ tls: q.get("tls") === "1" || fp !== null,
4562
+ ...name !== null ? { name } : {}
4563
+ });
4564
+ }
4565
+ static tryParse(text) {
4566
+ try {
4567
+ return _PairingLink.parse(text);
4568
+ } catch {
4569
+ return null;
4570
+ }
4571
+ }
4572
+ get endpoint() {
4573
+ const h = this.host.includes(":") && !this.host.startsWith("[") ? `[${this.host}]` : this.host;
4574
+ return new FreedomeEndpoint(`${this.opts.tls ? "https" : "http"}://${h}:${this.port}`, {
4575
+ ...this.opts.id ? { id: this.opts.id } : {},
4576
+ ...this.opts.name ? { name: this.opts.name } : {},
4577
+ ...this.opts.fingerprint ? { tlsFingerprint: this.opts.fingerprint } : {},
4578
+ ...this.opts.code ? { pairingCode: this.opts.code } : {}
4579
+ });
4580
+ }
4581
+ toString() {
4582
+ const q = new URLSearchParams({ host: this.host, port: String(this.port) });
4583
+ if (this.opts.id) q.set("id", this.opts.id);
4584
+ if (this.opts.code) q.set("code", this.opts.code);
4585
+ if (this.opts.fingerprint) q.set("fp", this.opts.fingerprint);
4586
+ else if (this.opts.tls) q.set("tls", "1");
4587
+ if (this.opts.name) q.set("name", this.opts.name);
4588
+ return `freedome://pair?${q.toString()}`;
4589
+ }
4590
+ };
4591
+
4592
+ // src/discovery.ts
4593
+ async function probe(endpoint, timeoutMs = 2e3) {
4594
+ const t = new FetchTransport(endpoint);
4595
+ try {
4596
+ const res = await t.send(
4597
+ {
4598
+ method: import_protocol20.Operations.getInfo.method,
4599
+ path: import_protocol20.Operations.getInfo.path,
4600
+ headers: { accept: "application/json" }
4601
+ },
4602
+ timeoutMs
4603
+ );
4604
+ return res.ok ? res.json : void 0;
4605
+ } catch {
4606
+ return void 0;
4607
+ } finally {
4608
+ await t.close();
4609
+ }
4610
+ }
4611
+ var StaticDiscovery = class {
4612
+ constructor(addresses, verify = true) {
4613
+ this.addresses = addresses;
4614
+ this.verify = verify;
4615
+ }
4616
+ addresses;
4617
+ verify;
4618
+ async scan(timeoutMs = 2e3) {
4619
+ const out = [];
4620
+ await Promise.all(
4621
+ this.addresses.map(async (a) => {
4622
+ const endpoint = typeof a === "string" ? FreedomeEndpoint.parse(a) : a;
4623
+ if (!this.verify) {
4624
+ out.push({ endpoint, source: "static" });
4625
+ return;
4626
+ }
4627
+ const info = await probe(endpoint, timeoutMs);
4628
+ if (info) {
4629
+ const id = info.instanceId;
4630
+ const name = info.name;
4631
+ out.push({
4632
+ endpoint: id ? endpoint.withId(id) : endpoint,
4633
+ source: "static",
4634
+ info,
4635
+ ...name ? { name } : {}
4636
+ });
4637
+ }
4638
+ })
4639
+ );
4640
+ return out;
4641
+ }
4642
+ };
4643
+ var CompositeDiscovery = class {
4644
+ constructor(sources) {
4645
+ this.sources = sources;
4646
+ }
4647
+ sources;
4648
+ async scan(timeoutMs = 2e3) {
4649
+ const all = (await Promise.all(this.sources.map((s) => s.scan(timeoutMs).catch(() => [])))).flat();
4650
+ const seen = /* @__PURE__ */ new Set();
4651
+ return all.filter((d) => {
4652
+ const k = d.endpoint.id ?? d.endpoint.baseUrl;
4653
+ if (seen.has(k)) return false;
4654
+ seen.add(k);
4655
+ return true;
4656
+ });
4657
+ }
4658
+ };
4659
+
4660
+ // src/index.ts
4661
+ var import_protocol21 = require("@freedome/protocol");
4662
+ var PACKAGE_NAME = "@freedome/client";
4663
+ // Annotate the CommonJS export names for ESM import in node:
4664
+ 0 && (module.exports = {
4665
+ ApiCaller,
4666
+ AudioReactiveRepository,
4667
+ AudioRepository,
4668
+ BackoffPolicy,
4669
+ BlobContentSource,
4670
+ BytesContentSource,
4671
+ CALIBRATION_FILE_TYPES,
4672
+ CalibrationRepository,
4673
+ ClientsRepository,
4674
+ CompositeDiscovery,
4675
+ ConflictError,
4676
+ ContentRepository,
4677
+ Credentials,
4678
+ DEFAULT_OFFLINE_POLICY,
4679
+ DomeTopics,
4680
+ Emitter,
4681
+ EngineRepository,
4682
+ EventHub,
4683
+ EventKinds,
4684
+ FREEDOME_CLIENT_VERSION,
4685
+ FetchTransport,
4686
+ ForbiddenError,
4687
+ FreedomeClient,
4688
+ FreedomeEndpoint,
4689
+ FreedomeError,
4690
+ FreedomeResponse,
4691
+ GRAPHQL_EVENTS_SUBSCRIPTION,
4692
+ GRAPHQL_OPERATION,
4693
+ GRAPHQL_WS_SUBPROTOCOL,
4694
+ GatewaysRepository,
4695
+ GeneratorSession,
4696
+ GraphqlClient,
4697
+ GraphqlWsChannel,
4698
+ InMemoryCacheStore,
4699
+ InMemoryOutboxStore,
4700
+ InMemoryTokenStore,
4701
+ IncompatibleServerError,
4702
+ MAX_UPLOAD_CHUNK,
4703
+ NO_SESSION,
4704
+ NetworkError,
4705
+ NotFoundError,
4706
+ OfflineError,
4707
+ Operations,
4708
+ OscRepository,
4709
+ PACKAGE_NAME,
4710
+ PairingLink,
4711
+ PayloadTooLargeError,
4712
+ PlayTargets,
4713
+ PlaybackRepository,
4714
+ PlayerHandle,
4715
+ QueuedForReplayError,
4716
+ RateLimitedError,
4717
+ RepositoryContext,
4718
+ RequestTimeoutError,
4719
+ ServerError,
4720
+ Sha256,
4721
+ ShowParts,
4722
+ SocketIoChannel,
4723
+ StaticDiscovery,
4724
+ TlsPinMismatchError,
4725
+ UnauthorizedError,
4726
+ UnsupportedCapabilityError,
4727
+ UnsupportedFormatError,
4728
+ UploadTask,
4729
+ ValidationError,
4730
+ VenuesRepository,
4731
+ WsChannel,
4732
+ audioSessionEnded,
4733
+ base64,
4734
+ can,
4735
+ defaultTransports,
4736
+ errorFromProblem,
4737
+ isAuthFailure,
4738
+ isUnreachable,
4739
+ multipart,
4740
+ nextValue,
4741
+ oscArg,
4742
+ probe,
4743
+ readAllPages,
4744
+ readPage,
4745
+ requestUrl,
4746
+ scopesOfRole,
4747
+ sessionFromPrincipal,
4748
+ sessionFromTokens,
4749
+ sha256Hex,
4750
+ storedTokensOf,
4751
+ uuidV7,
4752
+ webSocketConnector
4753
+ });