@camstack/sdk 0.1.35 → 0.1.37

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.js CHANGED
@@ -1,2104 +1,1347 @@
1
- var __defProp = Object.defineProperty;
2
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
-
4
- // node_modules/@trpc/client/dist/objectSpread2-BvkFp-_Y.mjs
5
- var __create = Object.create;
6
- var __defProp2 = Object.defineProperty;
7
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
8
- var __getOwnPropNames = Object.getOwnPropertyNames;
9
- var __getProtoOf = Object.getPrototypeOf;
10
- var __hasOwnProp = Object.prototype.hasOwnProperty;
11
- var __commonJS = /* @__PURE__ */ __name((cb, mod) => function() {
12
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
13
- }, "__commonJS");
14
- var __copyProps = /* @__PURE__ */ __name((to, from, except, desc) => {
15
- if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
16
- key = keys[i];
17
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp2(to, key, {
18
- get: ((k) => from[k]).bind(null, key),
19
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
20
- });
1
+ import { createWSClient, createTRPCClient, wsLink, httpLink } from "@trpc/client";
2
+ import { createSystemProxy, SystemMirror } from "@camstack/types";
3
+ class DoubleIndexedKV {
4
+ constructor() {
5
+ this.keyToValue = /* @__PURE__ */ new Map();
6
+ this.valueToKey = /* @__PURE__ */ new Map();
21
7
  }
22
- return to;
23
- }, "__copyProps");
24
- var __toESM = /* @__PURE__ */ __name((mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", {
25
- value: mod,
26
- enumerable: true
27
- }) : target, mod)), "__toESM");
28
- var require_typeof = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/typeof.js"(exports, module) {
29
- function _typeof$2(o) {
30
- "@babel/helpers - typeof";
31
- return module.exports = _typeof$2 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$1) {
32
- return typeof o$1;
33
- } : function(o$1) {
34
- return o$1 && "function" == typeof Symbol && o$1.constructor === Symbol && o$1 !== Symbol.prototype ? "symbol" : typeof o$1;
35
- }, module.exports.__esModule = true, module.exports["default"] = module.exports, _typeof$2(o);
36
- }
37
- __name(_typeof$2, "_typeof$2");
38
- module.exports = _typeof$2, module.exports.__esModule = true, module.exports["default"] = module.exports;
39
- } });
40
- var require_toPrimitive = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/toPrimitive.js"(exports, module) {
41
- var _typeof$1 = require_typeof()["default"];
42
- function toPrimitive$1(t, r) {
43
- if ("object" != _typeof$1(t) || !t) return t;
44
- var e = t[Symbol.toPrimitive];
45
- if (void 0 !== e) {
46
- var i = e.call(t, r || "default");
47
- if ("object" != _typeof$1(i)) return i;
48
- throw new TypeError("@@toPrimitive must return a primitive value.");
49
- }
50
- return ("string" === r ? String : Number)(t);
51
- }
52
- __name(toPrimitive$1, "toPrimitive$1");
53
- module.exports = toPrimitive$1, module.exports.__esModule = true, module.exports["default"] = module.exports;
54
- } });
55
- var require_toPropertyKey = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/toPropertyKey.js"(exports, module) {
56
- var _typeof = require_typeof()["default"];
57
- var toPrimitive = require_toPrimitive();
58
- function toPropertyKey$1(t) {
59
- var i = toPrimitive(t, "string");
60
- return "symbol" == _typeof(i) ? i : i + "";
61
- }
62
- __name(toPropertyKey$1, "toPropertyKey$1");
63
- module.exports = toPropertyKey$1, module.exports.__esModule = true, module.exports["default"] = module.exports;
64
- } });
65
- var require_defineProperty = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/defineProperty.js"(exports, module) {
66
- var toPropertyKey = require_toPropertyKey();
67
- function _defineProperty(e, r, t) {
68
- return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
69
- value: t,
70
- enumerable: true,
71
- configurable: true,
72
- writable: true
73
- }) : e[r] = t, e;
74
- }
75
- __name(_defineProperty, "_defineProperty");
76
- module.exports = _defineProperty, module.exports.__esModule = true, module.exports["default"] = module.exports;
77
- } });
78
- var require_objectSpread2 = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/objectSpread2.js"(exports, module) {
79
- var defineProperty = require_defineProperty();
80
- function ownKeys(e, r) {
81
- var t = Object.keys(e);
82
- if (Object.getOwnPropertySymbols) {
83
- var o = Object.getOwnPropertySymbols(e);
84
- r && (o = o.filter(function(r$1) {
85
- return Object.getOwnPropertyDescriptor(e, r$1).enumerable;
86
- })), t.push.apply(t, o);
87
- }
88
- return t;
89
- }
90
- __name(ownKeys, "ownKeys");
91
- function _objectSpread2(e) {
92
- for (var r = 1; r < arguments.length; r++) {
93
- var t = null != arguments[r] ? arguments[r] : {};
94
- r % 2 ? ownKeys(Object(t), true).forEach(function(r$1) {
95
- defineProperty(e, r$1, t[r$1]);
96
- }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r$1) {
97
- Object.defineProperty(e, r$1, Object.getOwnPropertyDescriptor(t, r$1));
98
- });
99
- }
100
- return e;
8
+ set(key, value) {
9
+ this.keyToValue.set(key, value);
10
+ this.valueToKey.set(value, key);
11
+ }
12
+ getByKey(key) {
13
+ return this.keyToValue.get(key);
14
+ }
15
+ getByValue(value) {
16
+ return this.valueToKey.get(value);
17
+ }
18
+ clear() {
19
+ this.keyToValue.clear();
20
+ this.valueToKey.clear();
101
21
  }
102
- __name(_objectSpread2, "_objectSpread2");
103
- module.exports = _objectSpread2, module.exports.__esModule = true, module.exports["default"] = module.exports;
104
- } });
105
-
106
- // node_modules/@trpc/server/dist/observable-UMO3vUa_.mjs
107
- function observable(subscribe) {
108
- const self = {
109
- subscribe(observer) {
110
- let teardownRef = null;
111
- let isDone = false;
112
- let unsubscribed = false;
113
- let teardownImmediately = false;
114
- function unsubscribe() {
115
- if (teardownRef === null) {
116
- teardownImmediately = true;
117
- return;
118
- }
119
- if (unsubscribed) return;
120
- unsubscribed = true;
121
- if (typeof teardownRef === "function") teardownRef();
122
- else if (teardownRef) teardownRef.unsubscribe();
123
- }
124
- __name(unsubscribe, "unsubscribe");
125
- teardownRef = subscribe({
126
- next(value) {
127
- var _observer$next;
128
- if (isDone) return;
129
- (_observer$next = observer.next) === null || _observer$next === void 0 || _observer$next.call(observer, value);
130
- },
131
- error(err) {
132
- var _observer$error;
133
- if (isDone) return;
134
- isDone = true;
135
- (_observer$error = observer.error) === null || _observer$error === void 0 || _observer$error.call(observer, err);
136
- unsubscribe();
137
- },
138
- complete() {
139
- var _observer$complete;
140
- if (isDone) return;
141
- isDone = true;
142
- (_observer$complete = observer.complete) === null || _observer$complete === void 0 || _observer$complete.call(observer);
143
- unsubscribe();
144
- }
145
- });
146
- if (teardownImmediately) unsubscribe();
147
- return { unsubscribe };
148
- },
149
- pipe(...operations) {
150
- return operations.reduce(pipeReducer, self);
151
- }
152
- };
153
- return self;
154
- }
155
- __name(observable, "observable");
156
- function pipeReducer(prev, fn) {
157
- return fn(prev);
158
22
  }
159
- __name(pipeReducer, "pipeReducer");
160
- function observableToPromise(observable$1) {
161
- const ac = new AbortController();
162
- const promise = new Promise((resolve, reject) => {
163
- let isDone = false;
164
- function onDone() {
165
- if (isDone) return;
166
- isDone = true;
167
- obs$.unsubscribe();
23
+ class Registry {
24
+ constructor(generateIdentifier) {
25
+ this.generateIdentifier = generateIdentifier;
26
+ this.kv = new DoubleIndexedKV();
27
+ }
28
+ register(value, identifier) {
29
+ if (this.kv.getByValue(value)) {
30
+ return;
168
31
  }
169
- __name(onDone, "onDone");
170
- ac.signal.addEventListener("abort", () => {
171
- reject(ac.signal.reason);
172
- });
173
- const obs$ = observable$1.subscribe({
174
- next(data) {
175
- isDone = true;
176
- resolve(data);
177
- onDone();
178
- },
179
- error(data) {
180
- reject(data);
181
- },
182
- complete() {
183
- ac.abort();
184
- onDone();
185
- }
186
- });
187
- });
188
- return promise;
189
- }
190
- __name(observableToPromise, "observableToPromise");
191
-
192
- // node_modules/@trpc/server/dist/observable-CUiPknO-.mjs
193
- function share(_opts) {
194
- return (source) => {
195
- let refCount = 0;
196
- let subscription = null;
197
- const observers = [];
198
- function startIfNeeded() {
199
- if (subscription) return;
200
- subscription = source.subscribe({
201
- next(value) {
202
- for (const observer of observers) {
203
- var _observer$next;
204
- (_observer$next = observer.next) === null || _observer$next === void 0 || _observer$next.call(observer, value);
205
- }
206
- },
207
- error(error) {
208
- for (const observer of observers) {
209
- var _observer$error;
210
- (_observer$error = observer.error) === null || _observer$error === void 0 || _observer$error.call(observer, error);
211
- }
212
- },
213
- complete() {
214
- for (const observer of observers) {
215
- var _observer$complete;
216
- (_observer$complete = observer.complete) === null || _observer$complete === void 0 || _observer$complete.call(observer);
217
- }
218
- }
219
- });
32
+ if (!identifier) {
33
+ identifier = this.generateIdentifier(value);
220
34
  }
221
- __name(startIfNeeded, "startIfNeeded");
222
- function resetIfNeeded() {
223
- if (refCount === 0 && subscription) {
224
- const _sub = subscription;
225
- subscription = null;
226
- _sub.unsubscribe();
35
+ this.kv.set(identifier, value);
36
+ }
37
+ clear() {
38
+ this.kv.clear();
39
+ }
40
+ getIdentifier(value) {
41
+ return this.kv.getByValue(value);
42
+ }
43
+ getValue(identifier) {
44
+ return this.kv.getByKey(identifier);
45
+ }
46
+ }
47
+ class ClassRegistry extends Registry {
48
+ constructor() {
49
+ super((c) => c.name);
50
+ this.classToAllowedProps = /* @__PURE__ */ new Map();
51
+ }
52
+ register(value, options) {
53
+ if (typeof options === "object") {
54
+ if (options.allowProps) {
55
+ this.classToAllowedProps.set(value, options.allowProps);
227
56
  }
57
+ super.register(value, options.identifier);
58
+ } else {
59
+ super.register(value, options);
228
60
  }
229
- __name(resetIfNeeded, "resetIfNeeded");
230
- return observable((subscriber) => {
231
- refCount++;
232
- observers.push(subscriber);
233
- startIfNeeded();
234
- return { unsubscribe() {
235
- refCount--;
236
- resetIfNeeded();
237
- const index = observers.findIndex((v) => v === subscriber);
238
- if (index > -1) observers.splice(index, 1);
239
- } };
240
- });
241
- };
242
- }
243
- __name(share, "share");
244
- function behaviorSubject(initialValue) {
245
- let value = initialValue;
246
- const observerList = [];
247
- const addObserver = /* @__PURE__ */ __name((observer) => {
248
- if (value !== void 0) observer.next(value);
249
- observerList.push(observer);
250
- }, "addObserver");
251
- const removeObserver = /* @__PURE__ */ __name((observer) => {
252
- observerList.splice(observerList.indexOf(observer), 1);
253
- }, "removeObserver");
254
- const obs = observable((observer) => {
255
- addObserver(observer);
256
- return () => {
257
- removeObserver(observer);
258
- };
259
- });
260
- obs.next = (nextValue) => {
261
- if (value === nextValue) return;
262
- value = nextValue;
263
- for (const observer of observerList) observer.next(nextValue);
264
- };
265
- obs.get = () => value;
266
- return obs;
61
+ }
62
+ getAllowedProps(value) {
63
+ return this.classToAllowedProps.get(value);
64
+ }
267
65
  }
268
- __name(behaviorSubject, "behaviorSubject");
269
-
270
- // node_modules/@trpc/client/dist/splitLink-B7Cuf2c_.mjs
271
- function createChain(opts) {
272
- return observable((observer) => {
273
- function execute(index = 0, op = opts.op) {
274
- const next = opts.links[index];
275
- if (!next) throw new Error("No more links to execute - did you forget to add an ending link?");
276
- const subscription = next({
277
- op,
278
- next(nextOp) {
279
- const nextObserver = execute(index + 1, nextOp);
280
- return nextObserver;
281
- }
282
- });
283
- return subscription;
66
+ function valuesOfObj(record) {
67
+ if ("values" in Object) {
68
+ return Object.values(record);
69
+ }
70
+ const values = [];
71
+ for (const key in record) {
72
+ if (record.hasOwnProperty(key)) {
73
+ values.push(record[key]);
284
74
  }
285
- __name(execute, "execute");
286
- const obs$ = execute();
287
- return obs$.subscribe(observer);
288
- });
75
+ }
76
+ return values;
289
77
  }
290
- __name(createChain, "createChain");
291
-
292
- // node_modules/@trpc/server/dist/codes-DagpWZLc.mjs
293
- function isObject(value) {
294
- return !!value && !Array.isArray(value) && typeof value === "object";
78
+ function find(record, predicate) {
79
+ const values = valuesOfObj(record);
80
+ if ("find" in values) {
81
+ return values.find(predicate);
82
+ }
83
+ const valuesNotNever = values;
84
+ for (let i = 0; i < valuesNotNever.length; i++) {
85
+ const value = valuesNotNever[i];
86
+ if (predicate(value)) {
87
+ return value;
88
+ }
89
+ }
90
+ return void 0;
295
91
  }
296
- __name(isObject, "isObject");
297
- function emptyObject() {
298
- return /* @__PURE__ */ Object.create(null);
92
+ function forEach(record, run) {
93
+ Object.entries(record).forEach(([key, value]) => run(value, key));
299
94
  }
300
- __name(emptyObject, "emptyObject");
301
- var run = /* @__PURE__ */ __name((fn) => fn(), "run");
302
- function sleep(ms = 0) {
303
- return new Promise((res) => setTimeout(res, ms));
95
+ function includes(arr, value) {
96
+ return arr.indexOf(value) !== -1;
304
97
  }
305
- __name(sleep, "sleep");
306
- var TRPC_ERROR_CODES_BY_KEY = {
307
- PARSE_ERROR: -32700,
308
- BAD_REQUEST: -32600,
309
- INTERNAL_SERVER_ERROR: -32603,
310
- NOT_IMPLEMENTED: -32603,
311
- BAD_GATEWAY: -32603,
312
- SERVICE_UNAVAILABLE: -32603,
313
- GATEWAY_TIMEOUT: -32603,
314
- UNAUTHORIZED: -32001,
315
- PAYMENT_REQUIRED: -32002,
316
- FORBIDDEN: -32003,
317
- NOT_FOUND: -32004,
318
- METHOD_NOT_SUPPORTED: -32005,
319
- TIMEOUT: -32008,
320
- CONFLICT: -32009,
321
- PRECONDITION_FAILED: -32012,
322
- PAYLOAD_TOO_LARGE: -32013,
323
- UNSUPPORTED_MEDIA_TYPE: -32015,
324
- UNPROCESSABLE_CONTENT: -32022,
325
- PRECONDITION_REQUIRED: -32028,
326
- TOO_MANY_REQUESTS: -32029,
327
- CLIENT_CLOSED_REQUEST: -32099
328
- };
329
- var retryableRpcCodes = [
330
- TRPC_ERROR_CODES_BY_KEY.BAD_GATEWAY,
331
- TRPC_ERROR_CODES_BY_KEY.SERVICE_UNAVAILABLE,
332
- TRPC_ERROR_CODES_BY_KEY.GATEWAY_TIMEOUT,
333
- TRPC_ERROR_CODES_BY_KEY.INTERNAL_SERVER_ERROR
334
- ];
335
-
336
- // node_modules/@trpc/server/dist/getErrorShape-vC8mUXJD.mjs
337
- var __create2 = Object.create;
338
- var __defProp3 = Object.defineProperty;
339
- var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
340
- var __getOwnPropNames2 = Object.getOwnPropertyNames;
341
- var __getProtoOf2 = Object.getPrototypeOf;
342
- var __hasOwnProp2 = Object.prototype.hasOwnProperty;
343
- var __commonJS2 = /* @__PURE__ */ __name((cb, mod) => function() {
344
- return mod || (0, cb[__getOwnPropNames2(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
345
- }, "__commonJS");
346
- var __copyProps2 = /* @__PURE__ */ __name((to, from, except, desc) => {
347
- if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames2(from), i = 0, n = keys.length, key; i < n; i++) {
348
- key = keys[i];
349
- if (!__hasOwnProp2.call(to, key) && key !== except) __defProp3(to, key, {
350
- get: ((k) => from[k]).bind(null, key),
351
- enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable
352
- });
353
- }
354
- return to;
355
- }, "__copyProps");
356
- var __toESM2 = /* @__PURE__ */ __name((mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2(isNodeMode || !mod || !mod.__esModule ? __defProp3(target, "default", {
357
- value: mod,
358
- enumerable: true
359
- }) : target, mod)), "__toESM");
360
- var noop = /* @__PURE__ */ __name(() => {
361
- }, "noop");
362
- var freezeIfAvailable = /* @__PURE__ */ __name((obj) => {
363
- if (Object.freeze) Object.freeze(obj);
364
- }, "freezeIfAvailable");
365
- function createInnerProxy(callback, path, memo) {
366
- var _memo$cacheKey;
367
- const cacheKey = path.join(".");
368
- (_memo$cacheKey = memo[cacheKey]) !== null && _memo$cacheKey !== void 0 || (memo[cacheKey] = new Proxy(noop, {
369
- get(_obj, key) {
370
- if (typeof key !== "string" || key === "then") return void 0;
371
- return createInnerProxy(callback, [...path, key], memo);
372
- },
373
- apply(_1, _2, args) {
374
- const lastOfPath = path[path.length - 1];
375
- let opts = {
376
- args,
377
- path
378
- };
379
- if (lastOfPath === "call") opts = {
380
- args: args.length >= 2 ? [args[1]] : [],
381
- path: path.slice(0, -1)
382
- };
383
- else if (lastOfPath === "apply") opts = {
384
- args: args.length >= 2 ? args[1] : [],
385
- path: path.slice(0, -1)
386
- };
387
- freezeIfAvailable(opts.args);
388
- freezeIfAvailable(opts.path);
389
- return callback(opts);
390
- }
391
- }));
392
- return memo[cacheKey];
393
- }
394
- __name(createInnerProxy, "createInnerProxy");
395
- var createRecursiveProxy = /* @__PURE__ */ __name((callback) => createInnerProxy(callback, [], emptyObject()), "createRecursiveProxy");
396
- var createFlatProxy = /* @__PURE__ */ __name((callback) => {
397
- return new Proxy(noop, { get(_obj, name) {
398
- if (name === "then") return void 0;
399
- return callback(name);
400
- } });
401
- }, "createFlatProxy");
402
- var require_typeof2 = __commonJS2({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/typeof.js"(exports, module) {
403
- function _typeof$2(o) {
404
- "@babel/helpers - typeof";
405
- return module.exports = _typeof$2 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$1) {
406
- return typeof o$1;
407
- } : function(o$1) {
408
- return o$1 && "function" == typeof Symbol && o$1.constructor === Symbol && o$1 !== Symbol.prototype ? "symbol" : typeof o$1;
409
- }, module.exports.__esModule = true, module.exports["default"] = module.exports, _typeof$2(o);
410
- }
411
- __name(_typeof$2, "_typeof$2");
412
- module.exports = _typeof$2, module.exports.__esModule = true, module.exports["default"] = module.exports;
413
- } });
414
- var require_toPrimitive2 = __commonJS2({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/toPrimitive.js"(exports, module) {
415
- var _typeof$1 = require_typeof2()["default"];
416
- function toPrimitive$1(t, r) {
417
- if ("object" != _typeof$1(t) || !t) return t;
418
- var e = t[Symbol.toPrimitive];
419
- if (void 0 !== e) {
420
- var i = e.call(t, r || "default");
421
- if ("object" != _typeof$1(i)) return i;
422
- throw new TypeError("@@toPrimitive must return a primitive value.");
423
- }
424
- return ("string" === r ? String : Number)(t);
425
- }
426
- __name(toPrimitive$1, "toPrimitive$1");
427
- module.exports = toPrimitive$1, module.exports.__esModule = true, module.exports["default"] = module.exports;
428
- } });
429
- var require_toPropertyKey2 = __commonJS2({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/toPropertyKey.js"(exports, module) {
430
- var _typeof = require_typeof2()["default"];
431
- var toPrimitive = require_toPrimitive2();
432
- function toPropertyKey$1(t) {
433
- var i = toPrimitive(t, "string");
434
- return "symbol" == _typeof(i) ? i : i + "";
435
- }
436
- __name(toPropertyKey$1, "toPropertyKey$1");
437
- module.exports = toPropertyKey$1, module.exports.__esModule = true, module.exports["default"] = module.exports;
438
- } });
439
- var require_defineProperty2 = __commonJS2({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/defineProperty.js"(exports, module) {
440
- var toPropertyKey = require_toPropertyKey2();
441
- function _defineProperty(e, r, t) {
442
- return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
443
- value: t,
444
- enumerable: true,
445
- configurable: true,
446
- writable: true
447
- }) : e[r] = t, e;
448
- }
449
- __name(_defineProperty, "_defineProperty");
450
- module.exports = _defineProperty, module.exports.__esModule = true, module.exports["default"] = module.exports;
451
- } });
452
- var require_objectSpread22 = __commonJS2({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/objectSpread2.js"(exports, module) {
453
- var defineProperty = require_defineProperty2();
454
- function ownKeys(e, r) {
455
- var t = Object.keys(e);
456
- if (Object.getOwnPropertySymbols) {
457
- var o = Object.getOwnPropertySymbols(e);
458
- r && (o = o.filter(function(r$1) {
459
- return Object.getOwnPropertyDescriptor(e, r$1).enumerable;
460
- })), t.push.apply(t, o);
461
- }
462
- return t;
463
- }
464
- __name(ownKeys, "ownKeys");
465
- function _objectSpread2(e) {
466
- for (var r = 1; r < arguments.length; r++) {
467
- var t = null != arguments[r] ? arguments[r] : {};
468
- r % 2 ? ownKeys(Object(t), true).forEach(function(r$1) {
469
- defineProperty(e, r$1, t[r$1]);
470
- }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r$1) {
471
- Object.defineProperty(e, r$1, Object.getOwnPropertyDescriptor(t, r$1));
472
- });
98
+ function findArr(record, predicate) {
99
+ for (let i = 0; i < record.length; i++) {
100
+ const value = record[i];
101
+ if (predicate(value)) {
102
+ return value;
473
103
  }
474
- return e;
475
104
  }
476
- __name(_objectSpread2, "_objectSpread2");
477
- module.exports = _objectSpread2, module.exports.__esModule = true, module.exports["default"] = module.exports;
478
- } });
479
- var import_objectSpread2 = __toESM2(require_objectSpread22(), 1);
480
-
481
- // node_modules/@trpc/server/dist/tracked-DiE3uR1B.mjs
482
- var import_defineProperty = __toESM2(require_defineProperty2(), 1);
483
- var import_objectSpread2$1 = __toESM2(require_objectSpread22(), 1);
484
- function transformResultInner(response, transformer) {
485
- if ("error" in response) {
486
- const error = transformer.deserialize(response.error);
487
- return {
488
- ok: false,
489
- error: (0, import_objectSpread2$1.default)((0, import_objectSpread2$1.default)({}, response), {}, { error })
490
- };
491
- }
492
- const result = (0, import_objectSpread2$1.default)((0, import_objectSpread2$1.default)({}, response.result), (!response.result.type || response.result.type === "data") && {
493
- type: "data",
494
- data: transformer.deserialize(response.result.data)
495
- });
496
- return {
497
- ok: true,
498
- result
499
- };
105
+ return void 0;
500
106
  }
501
- __name(transformResultInner, "transformResultInner");
502
- var TransformResultError = class extends Error {
503
- static {
504
- __name(this, "TransformResultError");
505
- }
107
+ class CustomTransformerRegistry {
506
108
  constructor() {
507
- super("Unable to transform response from server");
109
+ this.transfomers = {};
508
110
  }
509
- };
510
- function transformResult(response, transformer) {
511
- let result;
512
- try {
513
- result = transformResultInner(response, transformer);
514
- } catch (_unused) {
515
- throw new TransformResultError();
111
+ register(transformer) {
112
+ this.transfomers[transformer.name] = transformer;
113
+ }
114
+ findApplicable(v) {
115
+ return find(this.transfomers, (transformer) => transformer.isApplicable(v));
116
+ }
117
+ findByName(name) {
118
+ return this.transfomers[name];
516
119
  }
517
- if (!result.ok && (!isObject(result.error.error) || typeof result.error.error["code"] !== "number")) throw new TransformResultError();
518
- if (result.ok && !isObject(result.result)) throw new TransformResultError();
519
- return result;
520
- }
521
- __name(transformResult, "transformResult");
522
- var import_objectSpread22 = __toESM2(require_objectSpread22(), 1);
523
-
524
- // node_modules/@trpc/client/dist/TRPCClientError-apv8gw59.mjs
525
- var import_defineProperty2 = __toESM(require_defineProperty(), 1);
526
- var import_objectSpread23 = __toESM(require_objectSpread2(), 1);
527
- function isTRPCClientError(cause) {
528
- return cause instanceof TRPCClientError;
529
- }
530
- __name(isTRPCClientError, "isTRPCClientError");
531
- function isTRPCErrorResponse(obj) {
532
- return isObject(obj) && isObject(obj["error"]) && typeof obj["error"]["code"] === "number" && typeof obj["error"]["message"] === "string";
533
- }
534
- __name(isTRPCErrorResponse, "isTRPCErrorResponse");
535
- function getMessageFromUnknownError(err, fallback) {
536
- if (typeof err === "string") return err;
537
- if (isObject(err) && typeof err["message"] === "string") return err["message"];
538
- return fallback;
539
120
  }
540
- __name(getMessageFromUnknownError, "getMessageFromUnknownError");
541
- var TRPCClientError = class TRPCClientError2 extends Error {
542
- static {
543
- __name(this, "TRPCClientError");
544
- }
545
- constructor(message, opts) {
546
- var _opts$result, _opts$result2;
547
- const cause = opts === null || opts === void 0 ? void 0 : opts.cause;
548
- super(message, { cause });
549
- (0, import_defineProperty2.default)(this, "cause", void 0);
550
- (0, import_defineProperty2.default)(this, "shape", void 0);
551
- (0, import_defineProperty2.default)(this, "data", void 0);
552
- (0, import_defineProperty2.default)(this, "meta", void 0);
553
- this.meta = opts === null || opts === void 0 ? void 0 : opts.meta;
554
- this.cause = cause;
555
- this.shape = opts === null || opts === void 0 || (_opts$result = opts.result) === null || _opts$result === void 0 ? void 0 : _opts$result.error;
556
- this.data = opts === null || opts === void 0 || (_opts$result2 = opts.result) === null || _opts$result2 === void 0 ? void 0 : _opts$result2.error.data;
557
- this.name = "TRPCClientError";
558
- Object.setPrototypeOf(this, TRPCClientError2.prototype);
559
- }
560
- static from(_cause, opts = {}) {
561
- const cause = _cause;
562
- if (isTRPCClientError(cause)) {
563
- if (opts.meta) cause.meta = (0, import_objectSpread23.default)((0, import_objectSpread23.default)({}, cause.meta), opts.meta);
564
- return cause;
121
+ const getType$1 = (payload) => Object.prototype.toString.call(payload).slice(8, -1);
122
+ const isUndefined = (payload) => typeof payload === "undefined";
123
+ const isNull = (payload) => payload === null;
124
+ const isPlainObject$1 = (payload) => {
125
+ if (typeof payload !== "object" || payload === null)
126
+ return false;
127
+ if (payload === Object.prototype)
128
+ return false;
129
+ if (Object.getPrototypeOf(payload) === null)
130
+ return true;
131
+ return Object.getPrototypeOf(payload) === Object.prototype;
132
+ };
133
+ const isEmptyObject = (payload) => isPlainObject$1(payload) && Object.keys(payload).length === 0;
134
+ const isArray$1 = (payload) => Array.isArray(payload);
135
+ const isString = (payload) => typeof payload === "string";
136
+ const isNumber = (payload) => typeof payload === "number" && !isNaN(payload);
137
+ const isBoolean = (payload) => typeof payload === "boolean";
138
+ const isRegExp = (payload) => payload instanceof RegExp;
139
+ const isMap = (payload) => payload instanceof Map;
140
+ const isSet = (payload) => payload instanceof Set;
141
+ const isSymbol = (payload) => getType$1(payload) === "Symbol";
142
+ const isDate = (payload) => payload instanceof Date && !isNaN(payload.valueOf());
143
+ const isError = (payload) => payload instanceof Error;
144
+ const isNaNValue = (payload) => typeof payload === "number" && isNaN(payload);
145
+ const isPrimitive = (payload) => isBoolean(payload) || isNull(payload) || isUndefined(payload) || isNumber(payload) || isString(payload) || isSymbol(payload);
146
+ const isBigint = (payload) => typeof payload === "bigint";
147
+ const isInfinite = (payload) => payload === Infinity || payload === -Infinity;
148
+ const isTypedArray = (payload) => ArrayBuffer.isView(payload) && !(payload instanceof DataView);
149
+ const isURL = (payload) => payload instanceof URL;
150
+ const escapeKey = (key) => key.replace(/\\/g, "\\\\").replace(/\./g, "\\.");
151
+ const stringifyPath = (path) => path.map(String).map(escapeKey).join(".");
152
+ const parsePath = (string, legacyPaths) => {
153
+ const result = [];
154
+ let segment = "";
155
+ for (let i = 0; i < string.length; i++) {
156
+ let char = string.charAt(i);
157
+ if (!legacyPaths && char === "\\") {
158
+ const escaped = string.charAt(i + 1);
159
+ if (escaped === "\\") {
160
+ segment += "\\";
161
+ i++;
162
+ continue;
163
+ } else if (escaped !== ".") {
164
+ throw Error("invalid path");
165
+ }
166
+ }
167
+ const isEscapedDot = char === "\\" && string.charAt(i + 1) === ".";
168
+ if (isEscapedDot) {
169
+ segment += ".";
170
+ i++;
171
+ continue;
172
+ }
173
+ const isEndOfSegment = char === ".";
174
+ if (isEndOfSegment) {
175
+ result.push(segment);
176
+ segment = "";
177
+ continue;
565
178
  }
566
- if (isTRPCErrorResponse(cause)) return new TRPCClientError2(cause.error.message, (0, import_objectSpread23.default)((0, import_objectSpread23.default)({}, opts), {}, {
567
- result: cause,
568
- cause: opts.cause
569
- }));
570
- return new TRPCClientError2(getMessageFromUnknownError(cause, "Unknown error"), (0, import_objectSpread23.default)((0, import_objectSpread23.default)({}, opts), {}, { cause }));
179
+ segment += char;
571
180
  }
181
+ const lastSegment = segment;
182
+ result.push(lastSegment);
183
+ return result;
572
184
  };
573
-
574
- // node_modules/@trpc/client/dist/unstable-internals-Bg7n9BBj.mjs
575
- function getTransformer(transformer) {
576
- const _transformer = transformer;
577
- if (!_transformer) return {
578
- input: {
579
- serialize: /* @__PURE__ */ __name((data) => data, "serialize"),
580
- deserialize: /* @__PURE__ */ __name((data) => data, "deserialize")
581
- },
582
- output: {
583
- serialize: /* @__PURE__ */ __name((data) => data, "serialize"),
584
- deserialize: /* @__PURE__ */ __name((data) => data, "deserialize")
585
- }
586
- };
587
- if ("input" in _transformer) return _transformer;
185
+ function simpleTransformation(isApplicable, annotation, transform, untransform) {
588
186
  return {
589
- input: _transformer,
590
- output: _transformer
187
+ isApplicable,
188
+ annotation,
189
+ transform,
190
+ untransform
591
191
  };
592
192
  }
593
- __name(getTransformer, "getTransformer");
594
-
595
- // node_modules/@trpc/client/dist/httpUtils-BNq9QC3d.mjs
596
- var isFunction2 = /* @__PURE__ */ __name((fn) => typeof fn === "function", "isFunction");
597
- function getFetch(customFetchImpl) {
598
- if (customFetchImpl) return customFetchImpl;
599
- if (typeof window !== "undefined" && isFunction2(window.fetch)) return window.fetch;
600
- if (typeof globalThis !== "undefined" && isFunction2(globalThis.fetch)) return globalThis.fetch;
601
- throw new Error("No fetch implementation found");
602
- }
603
- __name(getFetch, "getFetch");
604
- var import_objectSpread24 = __toESM(require_objectSpread2());
605
- function resolveHTTPLinkOptions(opts) {
193
+ const simpleRules = [
194
+ simpleTransformation(isUndefined, "undefined", () => null, () => void 0),
195
+ simpleTransformation(isBigint, "bigint", (v) => v.toString(), (v) => {
196
+ if (typeof BigInt !== "undefined") {
197
+ return BigInt(v);
198
+ }
199
+ console.error("Please add a BigInt polyfill.");
200
+ return v;
201
+ }),
202
+ simpleTransformation(isDate, "Date", (v) => v.toISOString(), (v) => new Date(v)),
203
+ simpleTransformation(isError, "Error", (v, superJson) => {
204
+ const baseError = {
205
+ name: v.name,
206
+ message: v.message
207
+ };
208
+ if ("cause" in v) {
209
+ baseError.cause = v.cause;
210
+ }
211
+ superJson.allowedErrorProps.forEach((prop) => {
212
+ baseError[prop] = v[prop];
213
+ });
214
+ return baseError;
215
+ }, (v, superJson) => {
216
+ const e = new Error(v.message, { cause: v.cause });
217
+ e.name = v.name;
218
+ e.stack = v.stack;
219
+ superJson.allowedErrorProps.forEach((prop) => {
220
+ e[prop] = v[prop];
221
+ });
222
+ return e;
223
+ }),
224
+ simpleTransformation(isRegExp, "regexp", (v) => "" + v, (regex) => {
225
+ const body = regex.slice(1, regex.lastIndexOf("/"));
226
+ const flags = regex.slice(regex.lastIndexOf("/") + 1);
227
+ return new RegExp(body, flags);
228
+ }),
229
+ simpleTransformation(
230
+ isSet,
231
+ "set",
232
+ // (sets only exist in es6+)
233
+ // eslint-disable-next-line es5/no-es6-methods
234
+ (v) => [...v.values()],
235
+ (v) => new Set(v)
236
+ ),
237
+ simpleTransformation(isMap, "map", (v) => [...v.entries()], (v) => new Map(v)),
238
+ simpleTransformation((v) => isNaNValue(v) || isInfinite(v), "number", (v) => {
239
+ if (isNaNValue(v)) {
240
+ return "NaN";
241
+ }
242
+ if (v > 0) {
243
+ return "Infinity";
244
+ } else {
245
+ return "-Infinity";
246
+ }
247
+ }, Number),
248
+ simpleTransformation((v) => v === 0 && 1 / v === -Infinity, "number", () => {
249
+ return "-0";
250
+ }, Number),
251
+ simpleTransformation(isURL, "URL", (v) => v.toString(), (v) => new URL(v))
252
+ ];
253
+ function compositeTransformation(isApplicable, annotation, transform, untransform) {
606
254
  return {
607
- url: opts.url.toString(),
608
- fetch: opts.fetch,
609
- transformer: getTransformer(opts.transformer),
610
- methodOverride: opts.methodOverride
255
+ isApplicable,
256
+ annotation,
257
+ transform,
258
+ untransform
611
259
  };
612
260
  }
613
- __name(resolveHTTPLinkOptions, "resolveHTTPLinkOptions");
614
- function arrayToDict(array) {
615
- const dict = {};
616
- for (let index = 0; index < array.length; index++) {
617
- const element = array[index];
618
- dict[index] = element;
619
- }
620
- return dict;
261
+ const symbolRule = compositeTransformation((s, superJson) => {
262
+ if (isSymbol(s)) {
263
+ const isRegistered = !!superJson.symbolRegistry.getIdentifier(s);
264
+ return isRegistered;
265
+ }
266
+ return false;
267
+ }, (s, superJson) => {
268
+ const identifier = superJson.symbolRegistry.getIdentifier(s);
269
+ return ["symbol", identifier];
270
+ }, (v) => v.description, (_, a, superJson) => {
271
+ const value = superJson.symbolRegistry.getValue(a[1]);
272
+ if (!value) {
273
+ throw new Error("Trying to deserialize unknown symbol");
274
+ }
275
+ return value;
276
+ });
277
+ const constructorToName = [
278
+ Int8Array,
279
+ Uint8Array,
280
+ Int16Array,
281
+ Uint16Array,
282
+ Int32Array,
283
+ Uint32Array,
284
+ Float32Array,
285
+ Float64Array,
286
+ Uint8ClampedArray
287
+ ].reduce((obj, ctor) => {
288
+ obj[ctor.name] = ctor;
289
+ return obj;
290
+ }, {});
291
+ const typedArrayRule = compositeTransformation(isTypedArray, (v) => ["typed-array", v.constructor.name], (v) => [...v], (v, a) => {
292
+ const ctor = constructorToName[a[1]];
293
+ if (!ctor) {
294
+ throw new Error("Trying to deserialize unknown typed array");
295
+ }
296
+ return new ctor(v);
297
+ });
298
+ function isInstanceOfRegisteredClass(potentialClass, superJson) {
299
+ if (potentialClass?.constructor) {
300
+ const isRegistered = !!superJson.classRegistry.getIdentifier(potentialClass.constructor);
301
+ return isRegistered;
302
+ }
303
+ return false;
621
304
  }
622
- __name(arrayToDict, "arrayToDict");
623
- var METHOD = {
624
- query: "GET",
625
- mutation: "POST",
626
- subscription: "PATCH"
627
- };
628
- function getInput(opts) {
629
- return "input" in opts ? opts.transformer.input.serialize(opts.input) : arrayToDict(opts.inputs.map((_input) => opts.transformer.input.serialize(_input)));
630
- }
631
- __name(getInput, "getInput");
632
- var getUrl = /* @__PURE__ */ __name((opts) => {
633
- const parts = opts.url.split("?");
634
- const base = parts[0].replace(/\/$/, "");
635
- let url = base + "/" + opts.path;
636
- const queryParts = [];
637
- if (parts[1]) queryParts.push(parts[1]);
638
- if ("inputs" in opts) queryParts.push("batch=1");
639
- if (opts.type === "query" || opts.type === "subscription") {
640
- const input = getInput(opts);
641
- if (input !== void 0 && opts.methodOverride !== "POST") queryParts.push(`input=${encodeURIComponent(JSON.stringify(input))}`);
642
- }
643
- if (queryParts.length) url += "?" + queryParts.join("&");
644
- return url;
645
- }, "getUrl");
646
- var getBody = /* @__PURE__ */ __name((opts) => {
647
- if (opts.type === "query" && opts.methodOverride !== "POST") return void 0;
648
- const input = getInput(opts);
649
- return input !== void 0 ? JSON.stringify(input) : void 0;
650
- }, "getBody");
651
- var jsonHttpRequester = /* @__PURE__ */ __name((opts) => {
652
- return httpRequest((0, import_objectSpread24.default)((0, import_objectSpread24.default)({}, opts), {}, {
653
- contentTypeHeader: "application/json",
654
- getUrl,
655
- getBody
656
- }));
657
- }, "jsonHttpRequester");
658
- var AbortError = class extends Error {
659
- static {
660
- __name(this, "AbortError");
305
+ const classRule = compositeTransformation(isInstanceOfRegisteredClass, (clazz, superJson) => {
306
+ const identifier = superJson.classRegistry.getIdentifier(clazz.constructor);
307
+ return ["class", identifier];
308
+ }, (clazz, superJson) => {
309
+ const allowedProps = superJson.classRegistry.getAllowedProps(clazz.constructor);
310
+ if (!allowedProps) {
311
+ return { ...clazz };
312
+ }
313
+ const result = {};
314
+ allowedProps.forEach((prop) => {
315
+ result[prop] = clazz[prop];
316
+ });
317
+ return result;
318
+ }, (v, a, superJson) => {
319
+ const clazz = superJson.classRegistry.getValue(a[1]);
320
+ if (!clazz) {
321
+ throw new Error(`Trying to deserialize unknown class '${a[1]}' - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564`);
322
+ }
323
+ return Object.assign(Object.create(clazz.prototype), v);
324
+ });
325
+ const customRule = compositeTransformation((value, superJson) => {
326
+ return !!superJson.customTransformerRegistry.findApplicable(value);
327
+ }, (value, superJson) => {
328
+ const transformer = superJson.customTransformerRegistry.findApplicable(value);
329
+ return ["custom", transformer.name];
330
+ }, (value, superJson) => {
331
+ const transformer = superJson.customTransformerRegistry.findApplicable(value);
332
+ return transformer.serialize(value);
333
+ }, (v, a, superJson) => {
334
+ const transformer = superJson.customTransformerRegistry.findByName(a[1]);
335
+ if (!transformer) {
336
+ throw new Error("Trying to deserialize unknown custom value");
337
+ }
338
+ return transformer.deserialize(v);
339
+ });
340
+ const compositeRules = [classRule, symbolRule, customRule, typedArrayRule];
341
+ const transformValue = (value, superJson) => {
342
+ const applicableCompositeRule = findArr(compositeRules, (rule) => rule.isApplicable(value, superJson));
343
+ if (applicableCompositeRule) {
344
+ return {
345
+ value: applicableCompositeRule.transform(value, superJson),
346
+ type: applicableCompositeRule.annotation(value, superJson)
347
+ };
661
348
  }
662
- constructor() {
663
- const name = "AbortError";
664
- super(name);
665
- this.name = name;
666
- this.message = name;
349
+ const applicableSimpleRule = findArr(simpleRules, (rule) => rule.isApplicable(value, superJson));
350
+ if (applicableSimpleRule) {
351
+ return {
352
+ value: applicableSimpleRule.transform(value, superJson),
353
+ type: applicableSimpleRule.annotation
354
+ };
667
355
  }
356
+ return void 0;
668
357
  };
669
- var throwIfAborted = /* @__PURE__ */ __name((signal) => {
670
- var _signal$throwIfAborte;
671
- if (!(signal === null || signal === void 0 ? void 0 : signal.aborted)) return;
672
- (_signal$throwIfAborte = signal.throwIfAborted) === null || _signal$throwIfAborte === void 0 || _signal$throwIfAborte.call(signal);
673
- if (typeof DOMException !== "undefined") throw new DOMException("AbortError", "AbortError");
674
- throw new AbortError();
675
- }, "throwIfAborted");
676
- async function fetchHTTPResponse(opts) {
677
- var _opts$methodOverride, _opts$trpcAcceptHeade;
678
- throwIfAborted(opts.signal);
679
- const url = opts.getUrl(opts);
680
- const body = opts.getBody(opts);
681
- const method = (_opts$methodOverride = opts.methodOverride) !== null && _opts$methodOverride !== void 0 ? _opts$methodOverride : METHOD[opts.type];
682
- const resolvedHeaders = await (async () => {
683
- const heads = await opts.headers();
684
- if (Symbol.iterator in heads) return Object.fromEntries(heads);
685
- return heads;
686
- })();
687
- const headers = (0, import_objectSpread24.default)((0, import_objectSpread24.default)((0, import_objectSpread24.default)({}, opts.contentTypeHeader && method !== "GET" ? { "content-type": opts.contentTypeHeader } : {}), opts.trpcAcceptHeader ? { [(_opts$trpcAcceptHeade = opts.trpcAcceptHeaderKey) !== null && _opts$trpcAcceptHeade !== void 0 ? _opts$trpcAcceptHeade : "trpc-accept"]: opts.trpcAcceptHeader } : void 0), resolvedHeaders);
688
- return getFetch(opts.fetch)(url, {
689
- method,
690
- signal: opts.signal,
691
- body,
692
- headers
693
- });
694
- }
695
- __name(fetchHTTPResponse, "fetchHTTPResponse");
696
- async function httpRequest(opts) {
697
- const meta = {};
698
- const res = await fetchHTTPResponse(opts);
699
- meta.response = res;
700
- const json = await res.json();
701
- meta.responseJSON = json;
702
- return {
703
- json,
704
- meta
705
- };
706
- }
707
- __name(httpRequest, "httpRequest");
708
-
709
- // node_modules/@trpc/client/dist/httpLink-oiU8eqFi.mjs
710
- function isOctetType(input) {
711
- return input instanceof Uint8Array || input instanceof Blob;
712
- }
713
- __name(isOctetType, "isOctetType");
714
- function isFormData(input) {
715
- return input instanceof FormData;
716
- }
717
- __name(isFormData, "isFormData");
718
- var import_objectSpread25 = __toESM(require_objectSpread2(), 1);
719
- var universalRequester = /* @__PURE__ */ __name((opts) => {
720
- if ("input" in opts) {
721
- const { input } = opts;
722
- if (isFormData(input)) {
723
- if (opts.type !== "mutation" && opts.methodOverride !== "POST") throw new Error("FormData is only supported for mutations");
724
- return httpRequest((0, import_objectSpread25.default)((0, import_objectSpread25.default)({}, opts), {}, {
725
- contentTypeHeader: void 0,
726
- getUrl,
727
- getBody: /* @__PURE__ */ __name(() => input, "getBody")
728
- }));
358
+ const simpleRulesByAnnotation = {};
359
+ simpleRules.forEach((rule) => {
360
+ simpleRulesByAnnotation[rule.annotation] = rule;
361
+ });
362
+ const untransformValue = (json, type, superJson) => {
363
+ if (isArray$1(type)) {
364
+ switch (type[0]) {
365
+ case "symbol":
366
+ return symbolRule.untransform(json, type, superJson);
367
+ case "class":
368
+ return classRule.untransform(json, type, superJson);
369
+ case "custom":
370
+ return customRule.untransform(json, type, superJson);
371
+ case "typed-array":
372
+ return typedArrayRule.untransform(json, type, superJson);
373
+ default:
374
+ throw new Error("Unknown transformation: " + type);
729
375
  }
730
- if (isOctetType(input)) {
731
- if (opts.type !== "mutation" && opts.methodOverride !== "POST") throw new Error("Octet type input is only supported for mutations");
732
- return httpRequest((0, import_objectSpread25.default)((0, import_objectSpread25.default)({}, opts), {}, {
733
- contentTypeHeader: "application/octet-stream",
734
- getUrl,
735
- getBody: /* @__PURE__ */ __name(() => input, "getBody")
736
- }));
376
+ } else {
377
+ const transformation = simpleRulesByAnnotation[type];
378
+ if (!transformation) {
379
+ throw new Error("Unknown transformation: " + type);
737
380
  }
381
+ return transformation.untransform(json, superJson);
738
382
  }
739
- return jsonHttpRequester(opts);
740
- }, "universalRequester");
741
- function httpLink(opts) {
742
- const resolvedOpts = resolveHTTPLinkOptions(opts);
743
- return () => {
744
- return (operationOpts) => {
745
- const { op } = operationOpts;
746
- return observable((observer) => {
747
- const { path, input, type } = op;
748
- if (type === "subscription") throw new Error("Subscriptions are unsupported by `httpLink` - use `httpSubscriptionLink` or `wsLink`");
749
- const request = universalRequester((0, import_objectSpread25.default)((0, import_objectSpread25.default)({}, resolvedOpts), {}, {
750
- type,
751
- path,
752
- input,
753
- signal: op.signal,
754
- headers() {
755
- if (!opts.headers) return {};
756
- if (typeof opts.headers === "function") return opts.headers({ op });
757
- return opts.headers;
758
- }
759
- }));
760
- let meta = void 0;
761
- request.then((res) => {
762
- meta = res.meta;
763
- const transformed = transformResult(res.json, resolvedOpts.transformer.output);
764
- if (!transformed.ok) {
765
- observer.error(TRPCClientError.from(transformed.error, { meta }));
766
- return;
767
- }
768
- observer.next({
769
- context: res.meta,
770
- result: transformed.result
771
- });
772
- observer.complete();
773
- }).catch((cause) => {
774
- observer.error(TRPCClientError.from(cause, { meta }));
775
- });
776
- return () => {
777
- };
778
- });
779
- };
780
- };
781
- }
782
- __name(httpLink, "httpLink");
783
-
784
- // node_modules/@trpc/client/dist/httpBatchLink-CaWjh1oW.mjs
785
- var import_objectSpread26 = __toESM(require_objectSpread2(), 1);
786
-
787
- // node_modules/@trpc/client/dist/loggerLink-ineCN1PO.mjs
788
- var import_objectSpread27 = __toESM(require_objectSpread2(), 1);
789
-
790
- // node_modules/@trpc/client/dist/wsLink-DSf4KOdW.mjs
791
- var jsonEncoder = {
792
- encode: /* @__PURE__ */ __name((data) => JSON.stringify(data), "encode"),
793
- decode: /* @__PURE__ */ __name((data) => {
794
- if (typeof data !== "string") throw new Error("jsonEncoder received binary data. JSON uses text frames. Use a binary encoder for binary data.");
795
- return JSON.parse(data);
796
- }, "decode")
797
383
  };
798
- var lazyDefaults = {
799
- enabled: false,
800
- closeMs: 0
384
+ const getNthKey = (value, n) => {
385
+ if (n > value.size)
386
+ throw new Error("index out of bounds");
387
+ const keys = value.keys();
388
+ while (n > 0) {
389
+ keys.next();
390
+ n--;
391
+ }
392
+ return keys.next().value;
801
393
  };
802
- var keepAliveDefaults = {
803
- enabled: false,
804
- pongTimeoutMs: 1e3,
805
- intervalMs: 5e3
806
- };
807
- var exponentialBackoff = /* @__PURE__ */ __name((attemptIndex) => {
808
- return attemptIndex === 0 ? 0 : Math.min(1e3 * 2 ** attemptIndex, 3e4);
809
- }, "exponentialBackoff");
810
- var resultOf = /* @__PURE__ */ __name((value, ...args) => {
811
- return typeof value === "function" ? value(...args) : value;
812
- }, "resultOf");
813
- var import_defineProperty$3 = __toESM(require_defineProperty(), 1);
814
- var TRPCWebSocketClosedError = class TRPCWebSocketClosedError2 extends Error {
815
- static {
816
- __name(this, "TRPCWebSocketClosedError");
817
- }
818
- constructor(opts) {
819
- super(opts.message, { cause: opts.cause });
820
- this.name = "TRPCWebSocketClosedError";
821
- Object.setPrototypeOf(this, TRPCWebSocketClosedError2.prototype);
822
- }
823
- };
824
- var ResettableTimeout = class {
825
- static {
826
- __name(this, "ResettableTimeout");
394
+ function validatePath(path) {
395
+ if (includes(path, "__proto__")) {
396
+ throw new Error("__proto__ is not allowed as a property");
827
397
  }
828
- constructor(onTimeout, timeoutMs) {
829
- this.onTimeout = onTimeout;
830
- this.timeoutMs = timeoutMs;
831
- (0, import_defineProperty$3.default)(this, "timeout", void 0);
398
+ if (includes(path, "prototype")) {
399
+ throw new Error("prototype is not allowed as a property");
832
400
  }
833
- /**
834
- * Resets the current timeout, restarting it with the same duration.
835
- * Does nothing if no timeout is active.
836
- */
837
- reset() {
838
- if (!this.timeout) return;
839
- clearTimeout(this.timeout);
840
- this.timeout = setTimeout(this.onTimeout, this.timeoutMs);
841
- }
842
- start() {
843
- clearTimeout(this.timeout);
844
- this.timeout = setTimeout(this.onTimeout, this.timeoutMs);
845
- }
846
- stop() {
847
- clearTimeout(this.timeout);
848
- this.timeout = void 0;
401
+ if (includes(path, "constructor")) {
402
+ throw new Error("constructor is not allowed as a property");
849
403
  }
850
- };
851
- function withResolvers() {
852
- let resolve;
853
- let reject;
854
- const promise = new Promise((res, rej) => {
855
- resolve = res;
856
- reject = rej;
857
- });
858
- return {
859
- promise,
860
- resolve,
861
- reject
862
- };
863
- }
864
- __name(withResolvers, "withResolvers");
865
- async function prepareUrl(urlOptions) {
866
- const url = await resultOf(urlOptions.url);
867
- if (!urlOptions.connectionParams) return url;
868
- const prefix = url.includes("?") ? "&" : "?";
869
- const connectionParams = `${prefix}connectionParams=1`;
870
- return url + connectionParams;
871
- }
872
- __name(prepareUrl, "prepareUrl");
873
- async function buildConnectionMessage(connectionParams, encoder) {
874
- const message = {
875
- method: "connectionParams",
876
- data: await resultOf(connectionParams)
877
- };
878
- return encoder.encode(message);
879
404
  }
880
- __name(buildConnectionMessage, "buildConnectionMessage");
881
- var import_defineProperty$2 = __toESM(require_defineProperty(), 1);
882
- var RequestManager = class {
883
- static {
884
- __name(this, "RequestManager");
885
- }
886
- constructor() {
887
- (0, import_defineProperty$2.default)(this, "outgoingRequests", new Array());
888
- (0, import_defineProperty$2.default)(this, "pendingRequests", {});
889
- }
890
- /**
891
- * Registers a new request by adding it to the outgoing queue and setting up
892
- * callbacks for lifecycle events such as completion or error.
893
- *
894
- * @param message - The outgoing message to be sent.
895
- * @param callbacks - Callback functions to observe the request's state.
896
- * @returns A cleanup function to manually remove the request.
897
- */
898
- register(message, callbacks) {
899
- const { promise: end, resolve } = withResolvers();
900
- this.outgoingRequests.push({
901
- id: String(message.id),
902
- message,
903
- end,
904
- callbacks: {
905
- next: callbacks.next,
906
- complete: /* @__PURE__ */ __name(() => {
907
- callbacks.complete();
908
- resolve();
909
- }, "complete"),
910
- error: /* @__PURE__ */ __name((e) => {
911
- callbacks.error(e);
912
- resolve();
913
- }, "error")
405
+ const getDeep = (object, path) => {
406
+ validatePath(path);
407
+ for (let i = 0; i < path.length; i++) {
408
+ const key = path[i];
409
+ if (isSet(object)) {
410
+ object = getNthKey(object, +key);
411
+ } else if (isMap(object)) {
412
+ const row = +key;
413
+ const type = +path[++i] === 0 ? "key" : "value";
414
+ const keyOfRow = getNthKey(object, row);
415
+ switch (type) {
416
+ case "key":
417
+ object = keyOfRow;
418
+ break;
419
+ case "value":
420
+ object = object.get(keyOfRow);
421
+ break;
914
422
  }
915
- });
916
- return () => {
917
- this.delete(message.id);
918
- callbacks.complete();
919
- resolve();
920
- };
921
- }
922
- /**
923
- * Deletes a request from both the outgoing and pending collections, if it exists.
924
- */
925
- delete(messageId) {
926
- if (messageId === null) return;
927
- this.outgoingRequests = this.outgoingRequests.filter(({ id }) => id !== String(messageId));
928
- delete this.pendingRequests[String(messageId)];
929
- }
930
- /**
931
- * Moves all outgoing requests to the pending state and clears the outgoing queue.
932
- *
933
- * The caller is expected to handle the actual sending of the requests
934
- * (e.g., sending them over the network) after this method is called.
935
- *
936
- * @returns The list of requests that were transitioned to the pending state.
937
- */
938
- flush() {
939
- const requests = this.outgoingRequests;
940
- this.outgoingRequests = [];
941
- for (const request of requests) this.pendingRequests[request.id] = request;
942
- return requests;
943
- }
944
- /**
945
- * Retrieves all currently pending requests, which are in flight awaiting responses
946
- * or handling ongoing subscriptions.
947
- */
948
- getPendingRequests() {
949
- return Object.values(this.pendingRequests);
950
- }
951
- /**
952
- * Retrieves a specific pending request by its message ID.
953
- */
954
- getPendingRequest(messageId) {
955
- if (messageId === null) return null;
956
- return this.pendingRequests[String(messageId)];
957
- }
958
- /**
959
- * Retrieves all outgoing requests, which are waiting to be sent.
960
- */
961
- getOutgoingRequests() {
962
- return this.outgoingRequests;
963
- }
964
- /**
965
- * Retrieves all requests, both outgoing and pending, with their respective states.
966
- *
967
- * @returns An array of all requests with their state ("outgoing" or "pending").
968
- */
969
- getRequests() {
970
- return [...this.getOutgoingRequests().map((request) => ({
971
- state: "outgoing",
972
- message: request.message,
973
- end: request.end,
974
- callbacks: request.callbacks
975
- })), ...this.getPendingRequests().map((request) => ({
976
- state: "pending",
977
- message: request.message,
978
- end: request.end,
979
- callbacks: request.callbacks
980
- }))];
981
- }
982
- /**
983
- * Checks if there are any pending requests, including ongoing subscriptions.
984
- */
985
- hasPendingRequests() {
986
- return this.getPendingRequests().length > 0;
987
- }
988
- /**
989
- * Checks if there are any pending subscriptions
990
- */
991
- hasPendingSubscriptions() {
992
- return this.getPendingRequests().some((request) => request.message.method === "subscription");
993
- }
994
- /**
995
- * Checks if there are any outgoing requests waiting to be sent.
996
- */
997
- hasOutgoingRequests() {
998
- return this.outgoingRequests.length > 0;
999
- }
1000
- };
1001
- var import_defineProperty$1 = __toESM(require_defineProperty(), 1);
1002
- function asyncWsOpen(ws) {
1003
- const { promise, resolve, reject } = withResolvers();
1004
- ws.addEventListener("open", () => {
1005
- ws.removeEventListener("error", reject);
1006
- resolve();
1007
- });
1008
- ws.addEventListener("error", reject);
1009
- return promise;
1010
- }
1011
- __name(asyncWsOpen, "asyncWsOpen");
1012
- function setupPingInterval(ws, { intervalMs, pongTimeoutMs }) {
1013
- let pingTimeout;
1014
- let pongTimeout;
1015
- function start() {
1016
- pingTimeout = setTimeout(() => {
1017
- ws.send("PING");
1018
- pongTimeout = setTimeout(() => {
1019
- ws.close();
1020
- }, pongTimeoutMs);
1021
- }, intervalMs);
1022
- }
1023
- __name(start, "start");
1024
- function reset() {
1025
- clearTimeout(pingTimeout);
1026
- start();
1027
- }
1028
- __name(reset, "reset");
1029
- function pong() {
1030
- clearTimeout(pongTimeout);
1031
- reset();
1032
- }
1033
- __name(pong, "pong");
1034
- ws.addEventListener("open", start);
1035
- ws.addEventListener("message", ({ data }) => {
1036
- clearTimeout(pingTimeout);
1037
- start();
1038
- if (data === "PONG") pong();
1039
- });
1040
- ws.addEventListener("close", () => {
1041
- clearTimeout(pingTimeout);
1042
- clearTimeout(pongTimeout);
1043
- });
1044
- }
1045
- __name(setupPingInterval, "setupPingInterval");
1046
- var WsConnection = class WsConnection2 {
1047
- static {
1048
- __name(this, "WsConnection");
1049
- }
1050
- constructor(opts) {
1051
- var _opts$WebSocketPonyfi;
1052
- (0, import_defineProperty$1.default)(this, "id", ++WsConnection2.connectCount);
1053
- (0, import_defineProperty$1.default)(this, "WebSocketPonyfill", void 0);
1054
- (0, import_defineProperty$1.default)(this, "urlOptions", void 0);
1055
- (0, import_defineProperty$1.default)(this, "keepAliveOpts", void 0);
1056
- (0, import_defineProperty$1.default)(this, "encoder", void 0);
1057
- (0, import_defineProperty$1.default)(this, "wsObservable", behaviorSubject(null));
1058
- (0, import_defineProperty$1.default)(this, "openPromise", null);
1059
- this.WebSocketPonyfill = (_opts$WebSocketPonyfi = opts.WebSocketPonyfill) !== null && _opts$WebSocketPonyfi !== void 0 ? _opts$WebSocketPonyfi : WebSocket;
1060
- if (!this.WebSocketPonyfill) throw new Error("No WebSocket implementation found - you probably don't want to use this on the server, but if you do you need to pass a `WebSocket`-ponyfill");
1061
- this.urlOptions = opts.urlOptions;
1062
- this.keepAliveOpts = opts.keepAlive;
1063
- this.encoder = opts.encoder;
1064
- }
1065
- get ws() {
1066
- return this.wsObservable.get();
1067
- }
1068
- set ws(ws) {
1069
- this.wsObservable.next(ws);
1070
- }
1071
- /**
1072
- * Checks if the WebSocket connection is open and ready to communicate.
1073
- */
1074
- isOpen() {
1075
- return !!this.ws && this.ws.readyState === this.WebSocketPonyfill.OPEN && !this.openPromise;
1076
- }
1077
- /**
1078
- * Checks if the WebSocket connection is closed or in the process of closing.
1079
- */
1080
- isClosed() {
1081
- return !!this.ws && (this.ws.readyState === this.WebSocketPonyfill.CLOSING || this.ws.readyState === this.WebSocketPonyfill.CLOSED);
1082
- }
1083
- async open() {
1084
- var _this = this;
1085
- if (_this.openPromise) return _this.openPromise;
1086
- _this.id = ++WsConnection2.connectCount;
1087
- const wsPromise = prepareUrl(_this.urlOptions).then((url) => new _this.WebSocketPonyfill(url));
1088
- _this.openPromise = wsPromise.then(async (ws) => {
1089
- _this.ws = ws;
1090
- ws.binaryType = "arraybuffer";
1091
- ws.addEventListener("message", function({ data }) {
1092
- if (data === "PING") this.send("PONG");
1093
- });
1094
- if (_this.keepAliveOpts.enabled) setupPingInterval(ws, _this.keepAliveOpts);
1095
- ws.addEventListener("close", () => {
1096
- if (_this.ws === ws) _this.ws = null;
1097
- });
1098
- await asyncWsOpen(ws);
1099
- if (_this.urlOptions.connectionParams) ws.send(await buildConnectionMessage(_this.urlOptions.connectionParams, _this.encoder));
1100
- });
1101
- try {
1102
- await _this.openPromise;
1103
- } finally {
1104
- _this.openPromise = null;
1105
- }
1106
- }
1107
- /**
1108
- * Closes the WebSocket connection gracefully.
1109
- * Waits for any ongoing open operation to complete before closing.
1110
- */
1111
- async close() {
1112
- var _this2 = this;
1113
- try {
1114
- await _this2.openPromise;
1115
- } finally {
1116
- var _this$ws;
1117
- (_this$ws = _this2.ws) === null || _this$ws === void 0 || _this$ws.close();
423
+ } else {
424
+ object = object[key];
1118
425
  }
1119
426
  }
427
+ return object;
1120
428
  };
1121
- (0, import_defineProperty$1.default)(WsConnection, "connectCount", 0);
1122
- function backwardCompatibility(connection) {
1123
- if (connection.isOpen()) return {
1124
- id: connection.id,
1125
- state: "open",
1126
- ws: connection.ws
1127
- };
1128
- if (connection.isClosed()) return {
1129
- id: connection.id,
1130
- state: "closed",
1131
- ws: connection.ws
1132
- };
1133
- if (!connection.ws) return null;
1134
- return {
1135
- id: connection.id,
1136
- state: "connecting",
1137
- ws: connection.ws
1138
- };
1139
- }
1140
- __name(backwardCompatibility, "backwardCompatibility");
1141
- var import_defineProperty3 = __toESM(require_defineProperty(), 1);
1142
- var import_objectSpread28 = __toESM(require_objectSpread2(), 1);
1143
- var WsClient = class {
1144
- static {
1145
- __name(this, "WsClient");
1146
- }
1147
- constructor(opts) {
1148
- var _opts$experimental_en, _opts$retryDelayMs;
1149
- (0, import_defineProperty3.default)(this, "connectionState", void 0);
1150
- (0, import_defineProperty3.default)(this, "allowReconnect", false);
1151
- (0, import_defineProperty3.default)(this, "requestManager", new RequestManager());
1152
- (0, import_defineProperty3.default)(this, "activeConnection", void 0);
1153
- (0, import_defineProperty3.default)(this, "reconnectRetryDelay", void 0);
1154
- (0, import_defineProperty3.default)(this, "inactivityTimeout", void 0);
1155
- (0, import_defineProperty3.default)(this, "callbacks", void 0);
1156
- (0, import_defineProperty3.default)(this, "lazyMode", void 0);
1157
- (0, import_defineProperty3.default)(this, "encoder", void 0);
1158
- (0, import_defineProperty3.default)(this, "reconnecting", null);
1159
- this.encoder = (_opts$experimental_en = opts.experimental_encoder) !== null && _opts$experimental_en !== void 0 ? _opts$experimental_en : jsonEncoder;
1160
- this.callbacks = {
1161
- onOpen: opts.onOpen,
1162
- onClose: opts.onClose,
1163
- onError: opts.onError
1164
- };
1165
- const lazyOptions = (0, import_objectSpread28.default)((0, import_objectSpread28.default)({}, lazyDefaults), opts.lazy);
1166
- this.inactivityTimeout = new ResettableTimeout(() => {
1167
- if (this.requestManager.hasOutgoingRequests() || this.requestManager.hasPendingRequests()) {
1168
- this.inactivityTimeout.reset();
1169
- return;
429
+ const setDeep = (object, path, mapper) => {
430
+ validatePath(path);
431
+ if (path.length === 0) {
432
+ return mapper(object);
433
+ }
434
+ let parent = object;
435
+ for (let i = 0; i < path.length - 1; i++) {
436
+ const key = path[i];
437
+ if (isArray$1(parent)) {
438
+ const index = +key;
439
+ parent = parent[index];
440
+ } else if (isPlainObject$1(parent)) {
441
+ parent = parent[key];
442
+ } else if (isSet(parent)) {
443
+ const row = +key;
444
+ parent = getNthKey(parent, row);
445
+ } else if (isMap(parent)) {
446
+ const isEnd = i === path.length - 2;
447
+ if (isEnd) {
448
+ break;
449
+ }
450
+ const row = +key;
451
+ const type = +path[++i] === 0 ? "key" : "value";
452
+ const keyOfRow = getNthKey(parent, row);
453
+ switch (type) {
454
+ case "key":
455
+ parent = keyOfRow;
456
+ break;
457
+ case "value":
458
+ parent = parent.get(keyOfRow);
459
+ break;
1170
460
  }
1171
- this.close().catch(() => null);
1172
- }, lazyOptions.closeMs);
1173
- this.activeConnection = new WsConnection({
1174
- WebSocketPonyfill: opts.WebSocket,
1175
- urlOptions: opts,
1176
- keepAlive: (0, import_objectSpread28.default)((0, import_objectSpread28.default)({}, keepAliveDefaults), opts.keepAlive),
1177
- encoder: this.encoder
1178
- });
1179
- this.activeConnection.wsObservable.subscribe({ next: /* @__PURE__ */ __name((ws) => {
1180
- if (!ws) return;
1181
- this.setupWebSocketListeners(ws);
1182
- }, "next") });
1183
- this.reconnectRetryDelay = (_opts$retryDelayMs = opts.retryDelayMs) !== null && _opts$retryDelayMs !== void 0 ? _opts$retryDelayMs : exponentialBackoff;
1184
- this.lazyMode = lazyOptions.enabled;
1185
- this.connectionState = behaviorSubject({
1186
- type: "state",
1187
- state: lazyOptions.enabled ? "idle" : "connecting",
1188
- error: null
1189
- });
1190
- if (!this.lazyMode) this.open().catch(() => null);
1191
- }
1192
- /**
1193
- * Opens the WebSocket connection. Handles reconnection attempts and updates
1194
- * the connection state accordingly.
1195
- */
1196
- async open() {
1197
- var _this = this;
1198
- _this.allowReconnect = true;
1199
- if (_this.connectionState.get().state === "idle") _this.connectionState.next({
1200
- type: "state",
1201
- state: "connecting",
1202
- error: null
1203
- });
1204
- try {
1205
- await _this.activeConnection.open();
1206
- } catch (error) {
1207
- _this.reconnect(new TRPCWebSocketClosedError({
1208
- message: "Initialization error",
1209
- cause: error
1210
- }));
1211
- return _this.reconnecting;
1212
461
  }
1213
462
  }
1214
- /**
1215
- * Closes the WebSocket connection and stops managing requests.
1216
- * Ensures all outgoing and pending requests are properly finalized.
1217
- */
1218
- async close() {
1219
- var _this2 = this;
1220
- _this2.allowReconnect = false;
1221
- _this2.inactivityTimeout.stop();
1222
- const requestsToAwait = [];
1223
- for (const request of _this2.requestManager.getRequests()) if (request.message.method === "subscription") request.callbacks.complete();
1224
- else if (request.state === "outgoing") request.callbacks.error(TRPCClientError.from(new TRPCWebSocketClosedError({ message: "Closed before connection was established" })));
1225
- else requestsToAwait.push(request.end);
1226
- await Promise.all(requestsToAwait).catch(() => null);
1227
- await _this2.activeConnection.close().catch(() => null);
1228
- _this2.connectionState.next({
1229
- type: "state",
1230
- state: "idle",
1231
- error: null
1232
- });
1233
- }
1234
- /**
1235
- * Method to request the server.
1236
- * Handles data transformation, batching of requests, and subscription lifecycle.
1237
- *
1238
- * @param op - The operation details including id, type, path, input and signal
1239
- * @param transformer - Data transformer for serializing requests and deserializing responses
1240
- * @param lastEventId - Optional ID of the last received event for subscriptions
1241
- *
1242
- * @returns An observable that emits operation results and handles cleanup
1243
- */
1244
- request({ op: { id, type, path, input, signal }, transformer, lastEventId }) {
1245
- return observable((observer) => {
1246
- const abort = this.batchSend({
1247
- id,
1248
- method: type,
1249
- params: {
1250
- input: transformer.input.serialize(input),
1251
- path,
1252
- lastEventId
1253
- }
1254
- }, (0, import_objectSpread28.default)((0, import_objectSpread28.default)({}, observer), {}, { next(event) {
1255
- const transformed = transformResult(event, transformer.output);
1256
- if (!transformed.ok) {
1257
- observer.error(TRPCClientError.from(transformed.error));
1258
- return;
1259
- }
1260
- observer.next({ result: transformed.result });
1261
- } }));
1262
- return () => {
1263
- abort();
1264
- if (type === "subscription" && this.activeConnection.isOpen()) this.send({
1265
- id,
1266
- method: "subscription.stop"
1267
- });
1268
- signal === null || signal === void 0 || signal.removeEventListener("abort", abort);
1269
- };
1270
- });
1271
- }
1272
- get connection() {
1273
- return backwardCompatibility(this.activeConnection);
463
+ const lastKey = path[path.length - 1];
464
+ if (isArray$1(parent)) {
465
+ parent[+lastKey] = mapper(parent[+lastKey]);
466
+ } else if (isPlainObject$1(parent)) {
467
+ parent[lastKey] = mapper(parent[lastKey]);
468
+ }
469
+ if (isSet(parent)) {
470
+ const oldValue = getNthKey(parent, +lastKey);
471
+ const newValue = mapper(oldValue);
472
+ if (oldValue !== newValue) {
473
+ parent.delete(oldValue);
474
+ parent.add(newValue);
475
+ }
1274
476
  }
1275
- reconnect(closedError) {
1276
- var _this3 = this;
1277
- this.connectionState.next({
1278
- type: "state",
1279
- state: "connecting",
1280
- error: TRPCClientError.from(closedError)
1281
- });
1282
- if (this.reconnecting) return;
1283
- const tryReconnect = /* @__PURE__ */ __name(async (attemptIndex) => {
1284
- try {
1285
- await sleep(_this3.reconnectRetryDelay(attemptIndex));
1286
- if (_this3.allowReconnect) {
1287
- await _this3.activeConnection.close();
1288
- await _this3.activeConnection.open();
1289
- if (_this3.requestManager.hasPendingRequests()) _this3.send(_this3.requestManager.getPendingRequests().map(({ message }) => message));
477
+ if (isMap(parent)) {
478
+ const row = +path[path.length - 2];
479
+ const keyToRow = getNthKey(parent, row);
480
+ const type = +lastKey === 0 ? "key" : "value";
481
+ switch (type) {
482
+ case "key": {
483
+ const newKey = mapper(keyToRow);
484
+ parent.set(newKey, parent.get(keyToRow));
485
+ if (newKey !== keyToRow) {
486
+ parent.delete(keyToRow);
1290
487
  }
1291
- _this3.reconnecting = null;
1292
- } catch (_unused) {
1293
- await tryReconnect(attemptIndex + 1);
488
+ break;
1294
489
  }
1295
- }, "tryReconnect");
1296
- this.reconnecting = tryReconnect(0);
1297
- }
1298
- setupWebSocketListeners(ws) {
1299
- var _this4 = this;
1300
- const handleCloseOrError = /* @__PURE__ */ __name((cause) => {
1301
- const reqs = this.requestManager.getPendingRequests();
1302
- for (const { message, callbacks } of reqs) {
1303
- if (message.method === "subscription") continue;
1304
- callbacks.error(TRPCClientError.from(cause !== null && cause !== void 0 ? cause : new TRPCWebSocketClosedError({
1305
- message: "WebSocket closed",
1306
- cause
1307
- })));
1308
- this.requestManager.delete(message.id);
490
+ case "value": {
491
+ parent.set(keyToRow, mapper(parent.get(keyToRow)));
492
+ break;
1309
493
  }
1310
- }, "handleCloseOrError");
1311
- ws.addEventListener("open", () => {
1312
- run(async () => {
1313
- var _this$callbacks$onOpe, _this$callbacks;
1314
- if (_this4.lazyMode) _this4.inactivityTimeout.start();
1315
- (_this$callbacks$onOpe = (_this$callbacks = _this4.callbacks).onOpen) === null || _this$callbacks$onOpe === void 0 || _this$callbacks$onOpe.call(_this$callbacks);
1316
- _this4.connectionState.next({
1317
- type: "state",
1318
- state: "pending",
1319
- error: null
1320
- });
1321
- }).catch((error) => {
1322
- ws.close(3e3);
1323
- handleCloseOrError(error);
1324
- });
1325
- });
1326
- ws.addEventListener("message", ({ data }) => {
1327
- this.inactivityTimeout.reset();
1328
- if (["PING", "PONG"].includes(data)) return;
1329
- const incomingMessage = this.encoder.decode(data);
1330
- if ("method" in incomingMessage) {
1331
- this.handleIncomingRequest(incomingMessage);
1332
- return;
1333
- }
1334
- this.handleResponseMessage(incomingMessage);
1335
- });
1336
- ws.addEventListener("close", (event) => {
1337
- var _this$callbacks$onClo, _this$callbacks2;
1338
- handleCloseOrError(event);
1339
- (_this$callbacks$onClo = (_this$callbacks2 = this.callbacks).onClose) === null || _this$callbacks$onClo === void 0 || _this$callbacks$onClo.call(_this$callbacks2, event);
1340
- if (!this.lazyMode || this.requestManager.hasPendingSubscriptions()) this.reconnect(new TRPCWebSocketClosedError({
1341
- message: "WebSocket closed",
1342
- cause: event
1343
- }));
1344
- });
1345
- ws.addEventListener("error", (event) => {
1346
- var _this$callbacks$onErr, _this$callbacks3;
1347
- handleCloseOrError(event);
1348
- (_this$callbacks$onErr = (_this$callbacks3 = this.callbacks).onError) === null || _this$callbacks$onErr === void 0 || _this$callbacks$onErr.call(_this$callbacks3, event);
1349
- this.reconnect(new TRPCWebSocketClosedError({
1350
- message: "WebSocket closed",
1351
- cause: event
1352
- }));
1353
- });
1354
- }
1355
- handleResponseMessage(message) {
1356
- const request = this.requestManager.getPendingRequest(message.id);
1357
- if (!request) return;
1358
- request.callbacks.next(message);
1359
- let completed = true;
1360
- if ("result" in message && request.message.method === "subscription") {
1361
- if (message.result.type === "data") request.message.params.lastEventId = message.result.id;
1362
- if (message.result.type !== "stopped") completed = false;
1363
494
  }
1364
- if (completed) {
1365
- request.callbacks.complete();
1366
- this.requestManager.delete(message.id);
1367
- }
1368
- }
1369
- handleIncomingRequest(message) {
1370
- if (message.method === "reconnect") this.reconnect(new TRPCWebSocketClosedError({ message: "Server requested reconnect" }));
1371
495
  }
1372
- /**
1373
- * Sends a message or batch of messages directly to the server.
1374
- */
1375
- send(messageOrMessages) {
1376
- if (!this.activeConnection.isOpen()) throw new Error("Active connection is not open");
1377
- const messages = messageOrMessages instanceof Array ? messageOrMessages : [messageOrMessages];
1378
- this.activeConnection.ws.send(this.encoder.encode(messages.length === 1 ? messages[0] : messages));
1379
- }
1380
- /**
1381
- * Groups requests for batch sending.
1382
- *
1383
- * @returns A function to abort the batched request.
1384
- */
1385
- batchSend(message, callbacks) {
1386
- var _this5 = this;
1387
- this.inactivityTimeout.reset();
1388
- run(async () => {
1389
- if (!_this5.activeConnection.isOpen()) await _this5.open();
1390
- await sleep(0);
1391
- if (!_this5.requestManager.hasOutgoingRequests()) return;
1392
- _this5.send(_this5.requestManager.flush().map(({ message: message$1 }) => message$1));
1393
- }).catch((err) => {
1394
- this.requestManager.delete(message.id);
1395
- callbacks.error(TRPCClientError.from(err));
496
+ return object;
497
+ };
498
+ const enableLegacyPaths = (version) => version < 1;
499
+ function traverse(tree, walker2, version, origin = []) {
500
+ if (!tree) {
501
+ return;
502
+ }
503
+ const legacyPaths = enableLegacyPaths(version);
504
+ if (!isArray$1(tree)) {
505
+ forEach(tree, (subtree, key) => traverse(subtree, walker2, version, [
506
+ ...origin,
507
+ ...parsePath(key, legacyPaths)
508
+ ]));
509
+ return;
510
+ }
511
+ const [nodeValue, children] = tree;
512
+ if (children) {
513
+ forEach(children, (child, key) => {
514
+ traverse(child, walker2, version, [
515
+ ...origin,
516
+ ...parsePath(key, legacyPaths)
517
+ ]);
1396
518
  });
1397
- return this.requestManager.register(message, callbacks);
1398
519
  }
1399
- };
1400
- function createWSClient(opts) {
1401
- return new WsClient(opts);
520
+ walker2(nodeValue, origin);
1402
521
  }
1403
- __name(createWSClient, "createWSClient");
1404
- function wsLink(opts) {
1405
- const { client } = opts;
1406
- const transformer = getTransformer(opts.transformer);
1407
- return () => {
1408
- return ({ op }) => {
1409
- return observable((observer) => {
1410
- const connStateSubscription = op.type === "subscription" ? client.connectionState.subscribe({ next(result) {
1411
- observer.next({
1412
- result,
1413
- context: op.context
1414
- });
1415
- } }) : null;
1416
- const requestSubscription = client.request({
1417
- op,
1418
- transformer
1419
- }).subscribe(observer);
1420
- return () => {
1421
- requestSubscription.unsubscribe();
1422
- connStateSubscription === null || connStateSubscription === void 0 || connStateSubscription.unsubscribe();
1423
- };
1424
- });
1425
- };
1426
- };
522
+ function applyValueAnnotations(plain, annotations, version, superJson) {
523
+ traverse(annotations, (type, path) => {
524
+ plain = setDeep(plain, path, (v) => untransformValue(v, type, superJson));
525
+ }, version);
526
+ return plain;
1427
527
  }
1428
- __name(wsLink, "wsLink");
1429
-
1430
- // node_modules/@trpc/client/dist/index.mjs
1431
- var import_defineProperty4 = __toESM(require_defineProperty(), 1);
1432
- var import_objectSpread2$4 = __toESM(require_objectSpread2(), 1);
1433
- var TRPCUntypedClient = class {
1434
- static {
1435
- __name(this, "TRPCUntypedClient");
1436
- }
1437
- constructor(opts) {
1438
- (0, import_defineProperty4.default)(this, "links", void 0);
1439
- (0, import_defineProperty4.default)(this, "runtime", void 0);
1440
- (0, import_defineProperty4.default)(this, "requestId", void 0);
1441
- this.requestId = 0;
1442
- this.runtime = {};
1443
- this.links = opts.links.map((link) => link(this.runtime));
1444
- }
1445
- $request(opts) {
1446
- var _opts$context;
1447
- const chain$ = createChain({
1448
- links: this.links,
1449
- op: (0, import_objectSpread2$4.default)((0, import_objectSpread2$4.default)({}, opts), {}, {
1450
- context: (_opts$context = opts.context) !== null && _opts$context !== void 0 ? _opts$context : {},
1451
- id: ++this.requestId
1452
- })
528
+ function applyReferentialEqualityAnnotations(plain, annotations, version) {
529
+ const legacyPaths = enableLegacyPaths(version);
530
+ function apply(identicalPaths, path) {
531
+ const object = getDeep(plain, parsePath(path, legacyPaths));
532
+ identicalPaths.map((path2) => parsePath(path2, legacyPaths)).forEach((identicalObjectPath) => {
533
+ plain = setDeep(plain, identicalObjectPath, () => object);
1453
534
  });
1454
- return chain$.pipe(share());
1455
535
  }
1456
- async requestAsPromise(opts) {
1457
- var _this = this;
1458
- try {
1459
- const req$ = _this.$request(opts);
1460
- const envelope = await observableToPromise(req$);
1461
- const data = envelope.result.data;
1462
- return data;
1463
- } catch (err) {
1464
- throw TRPCClientError.from(err);
1465
- }
1466
- }
1467
- query(path, input, opts) {
1468
- return this.requestAsPromise({
1469
- type: "query",
1470
- path,
1471
- input,
1472
- context: opts === null || opts === void 0 ? void 0 : opts.context,
1473
- signal: opts === null || opts === void 0 ? void 0 : opts.signal
1474
- });
1475
- }
1476
- mutation(path, input, opts) {
1477
- return this.requestAsPromise({
1478
- type: "mutation",
1479
- path,
1480
- input,
1481
- context: opts === null || opts === void 0 ? void 0 : opts.context,
1482
- signal: opts === null || opts === void 0 ? void 0 : opts.signal
1483
- });
1484
- }
1485
- subscription(path, input, opts) {
1486
- const observable$ = this.$request({
1487
- type: "subscription",
1488
- path,
1489
- input,
1490
- context: opts.context,
1491
- signal: opts.signal
1492
- });
1493
- return observable$.subscribe({
1494
- next(envelope) {
1495
- switch (envelope.result.type) {
1496
- case "state": {
1497
- var _opts$onConnectionSta;
1498
- (_opts$onConnectionSta = opts.onConnectionStateChange) === null || _opts$onConnectionSta === void 0 || _opts$onConnectionSta.call(opts, envelope.result);
1499
- break;
1500
- }
1501
- case "started": {
1502
- var _opts$onStarted;
1503
- (_opts$onStarted = opts.onStarted) === null || _opts$onStarted === void 0 || _opts$onStarted.call(opts, { context: envelope.context });
1504
- break;
1505
- }
1506
- case "stopped": {
1507
- var _opts$onStopped;
1508
- (_opts$onStopped = opts.onStopped) === null || _opts$onStopped === void 0 || _opts$onStopped.call(opts);
1509
- break;
1510
- }
1511
- case "data":
1512
- case void 0: {
1513
- var _opts$onData;
1514
- (_opts$onData = opts.onData) === null || _opts$onData === void 0 || _opts$onData.call(opts, envelope.result.data);
1515
- break;
1516
- }
1517
- }
1518
- },
1519
- error(err) {
1520
- var _opts$onError;
1521
- (_opts$onError = opts.onError) === null || _opts$onError === void 0 || _opts$onError.call(opts, err);
1522
- },
1523
- complete() {
1524
- var _opts$onComplete;
1525
- (_opts$onComplete = opts.onComplete) === null || _opts$onComplete === void 0 || _opts$onComplete.call(opts);
1526
- }
536
+ if (isArray$1(annotations)) {
537
+ const [root, other] = annotations;
538
+ root.forEach((identicalPath) => {
539
+ plain = setDeep(plain, parsePath(identicalPath, legacyPaths), () => plain);
1527
540
  });
541
+ if (other) {
542
+ forEach(other, apply);
543
+ }
544
+ } else {
545
+ forEach(annotations, apply);
1528
546
  }
1529
- };
1530
- var untypedClientSymbol = /* @__PURE__ */ Symbol.for("trpc_untypedClient");
1531
- var clientCallTypeMap = {
1532
- query: "query",
1533
- mutate: "mutation",
1534
- subscribe: "subscription"
1535
- };
1536
- var clientCallTypeToProcedureType = /* @__PURE__ */ __name((clientCallType) => {
1537
- return clientCallTypeMap[clientCallType];
1538
- }, "clientCallTypeToProcedureType");
1539
- function createTRPCClientProxy(client) {
1540
- const proxy = createRecursiveProxy(({ path, args }) => {
1541
- const pathCopy = [...path];
1542
- const procedureType = clientCallTypeToProcedureType(pathCopy.pop());
1543
- const fullPath = pathCopy.join(".");
1544
- return client[procedureType](fullPath, ...args);
1545
- });
1546
- return createFlatProxy((key) => {
1547
- if (key === untypedClientSymbol) return client;
1548
- return proxy[key];
1549
- });
547
+ return plain;
1550
548
  }
1551
- __name(createTRPCClientProxy, "createTRPCClientProxy");
1552
- function createTRPCClient(opts) {
1553
- const client = new TRPCUntypedClient(opts);
1554
- const proxy = createTRPCClientProxy(client);
1555
- return proxy;
549
+ const isDeep = (object, superJson) => isPlainObject$1(object) || isArray$1(object) || isMap(object) || isSet(object) || isError(object) || isInstanceOfRegisteredClass(object, superJson);
550
+ function addIdentity(object, path, identities) {
551
+ const existingSet = identities.get(object);
552
+ if (existingSet) {
553
+ existingSet.push(path);
554
+ } else {
555
+ identities.set(object, [path]);
556
+ }
1556
557
  }
1557
- __name(createTRPCClient, "createTRPCClient");
1558
- var import_objectSpread2$3 = __toESM(require_objectSpread2(), 1);
1559
- var import_objectSpread2$2 = __toESM(require_objectSpread2(), 1);
1560
- var require_asyncIterator = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/asyncIterator.js"(exports, module) {
1561
- function _asyncIterator$1(r) {
1562
- var n, t, o, e = 2;
1563
- for ("undefined" != typeof Symbol && (t = Symbol.asyncIterator, o = Symbol.iterator); e--; ) {
1564
- if (t && null != (n = r[t])) return n.call(r);
1565
- if (o && null != (n = r[o])) return new AsyncFromSyncIterator(n.call(r));
1566
- t = "@@asyncIterator", o = "@@iterator";
558
+ function generateReferentialEqualityAnnotations(identitites, dedupe) {
559
+ const result = {};
560
+ let rootEqualityPaths = void 0;
561
+ identitites.forEach((paths) => {
562
+ if (paths.length <= 1) {
563
+ return;
1567
564
  }
1568
- throw new TypeError("Object is not async iterable");
1569
- }
1570
- __name(_asyncIterator$1, "_asyncIterator$1");
1571
- function AsyncFromSyncIterator(r) {
1572
- function AsyncFromSyncIteratorContinuation(r$1) {
1573
- if (Object(r$1) !== r$1) return Promise.reject(new TypeError(r$1 + " is not an object."));
1574
- var n = r$1.done;
1575
- return Promise.resolve(r$1.value).then(function(r$2) {
1576
- return {
1577
- value: r$2,
1578
- done: n
1579
- };
1580
- });
565
+ if (!dedupe) {
566
+ paths = paths.map((path) => path.map(String)).sort((a, b) => a.length - b.length);
1581
567
  }
1582
- __name(AsyncFromSyncIteratorContinuation, "AsyncFromSyncIteratorContinuation");
1583
- return AsyncFromSyncIterator = /* @__PURE__ */ __name(function AsyncFromSyncIterator$1(r$1) {
1584
- this.s = r$1, this.n = r$1.next;
1585
- }, "AsyncFromSyncIterator$1"), AsyncFromSyncIterator.prototype = {
1586
- s: null,
1587
- n: null,
1588
- next: /* @__PURE__ */ __name(function next() {
1589
- return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments));
1590
- }, "next"),
1591
- "return": /* @__PURE__ */ __name(function _return(r$1) {
1592
- var n = this.s["return"];
1593
- return void 0 === n ? Promise.resolve({
1594
- value: r$1,
1595
- done: true
1596
- }) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments));
1597
- }, "_return"),
1598
- "throw": /* @__PURE__ */ __name(function _throw(r$1) {
1599
- var n = this.s["return"];
1600
- return void 0 === n ? Promise.reject(r$1) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments));
1601
- }, "_throw")
1602
- }, new AsyncFromSyncIterator(r);
1603
- }
1604
- __name(AsyncFromSyncIterator, "AsyncFromSyncIterator");
1605
- module.exports = _asyncIterator$1, module.exports.__esModule = true, module.exports["default"] = module.exports;
1606
- } });
1607
- var import_asyncIterator = __toESM(require_asyncIterator(), 1);
1608
- var import_objectSpread2$12 = __toESM(require_objectSpread2(), 1);
1609
- var require_usingCtx = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/usingCtx.js"(exports, module) {
1610
- function _usingCtx() {
1611
- var r = "function" == typeof SuppressedError ? SuppressedError : function(r$1, e$1) {
1612
- var n$1 = Error();
1613
- return n$1.name = "SuppressedError", n$1.error = r$1, n$1.suppressed = e$1, n$1;
1614
- }, e = {}, n = [];
1615
- function using(r$1, e$1) {
1616
- if (null != e$1) {
1617
- if (Object(e$1) !== e$1) throw new TypeError("using declarations can only be used with objects, functions, null, or undefined.");
1618
- if (r$1) var o = e$1[Symbol.asyncDispose || Symbol["for"]("Symbol.asyncDispose")];
1619
- if (void 0 === o && (o = e$1[Symbol.dispose || Symbol["for"]("Symbol.dispose")], r$1)) var t = o;
1620
- if ("function" != typeof o) throw new TypeError("Object is not disposable.");
1621
- t && (o = /* @__PURE__ */ __name(function o$1() {
1622
- try {
1623
- t.call(e$1);
1624
- } catch (r$2) {
1625
- return Promise.reject(r$2);
1626
- }
1627
- }, "o$1")), n.push({
1628
- v: e$1,
1629
- d: o,
1630
- a: r$1
1631
- });
1632
- } else r$1 && n.push({
1633
- d: e$1,
1634
- a: r$1
1635
- });
1636
- return e$1;
568
+ const [representativePath, ...identicalPaths] = paths;
569
+ if (representativePath.length === 0) {
570
+ rootEqualityPaths = identicalPaths.map(stringifyPath);
571
+ } else {
572
+ result[stringifyPath(representativePath)] = identicalPaths.map(stringifyPath);
1637
573
  }
1638
- __name(using, "using");
1639
- return {
1640
- e,
1641
- u: using.bind(null, false),
1642
- a: using.bind(null, true),
1643
- d: /* @__PURE__ */ __name(function d() {
1644
- var o, t = this.e, s = 0;
1645
- function next() {
1646
- for (; o = n.pop(); ) try {
1647
- if (!o.a && 1 === s) return s = 0, n.push(o), Promise.resolve().then(next);
1648
- if (o.d) {
1649
- var r$1 = o.d.call(o.v);
1650
- if (o.a) return s |= 2, Promise.resolve(r$1).then(next, err);
1651
- } else s |= 1;
1652
- } catch (r$2) {
1653
- return err(r$2);
1654
- }
1655
- if (1 === s) return t !== e ? Promise.reject(t) : Promise.resolve();
1656
- if (t !== e) throw t;
1657
- }
1658
- __name(next, "next");
1659
- function err(n$1) {
1660
- return t = t !== e ? new r(n$1, t) : n$1, next();
1661
- }
1662
- __name(err, "err");
1663
- return next();
1664
- }, "d")
574
+ });
575
+ if (rootEqualityPaths) {
576
+ if (isEmptyObject(result)) {
577
+ return [rootEqualityPaths];
578
+ } else {
579
+ return [rootEqualityPaths, result];
580
+ }
581
+ } else {
582
+ return isEmptyObject(result) ? void 0 : result;
583
+ }
584
+ }
585
+ const walker = (object, identities, superJson, dedupe, path = [], objectsInThisPath = [], seenObjects = /* @__PURE__ */ new Map()) => {
586
+ const primitive = isPrimitive(object);
587
+ if (!primitive) {
588
+ addIdentity(object, path, identities);
589
+ const seen = seenObjects.get(object);
590
+ if (seen) {
591
+ return dedupe ? {
592
+ transformedValue: null
593
+ } : seen;
594
+ }
595
+ }
596
+ if (!isDeep(object, superJson)) {
597
+ const transformed2 = transformValue(object, superJson);
598
+ const result2 = transformed2 ? {
599
+ transformedValue: transformed2.value,
600
+ annotations: [transformed2.type]
601
+ } : {
602
+ transformedValue: object
1665
603
  };
604
+ if (!primitive) {
605
+ seenObjects.set(object, result2);
606
+ }
607
+ return result2;
1666
608
  }
1667
- __name(_usingCtx, "_usingCtx");
1668
- module.exports = _usingCtx, module.exports.__esModule = true, module.exports["default"] = module.exports;
1669
- } });
1670
- var require_OverloadYield = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/OverloadYield.js"(exports, module) {
1671
- function _OverloadYield(e, d) {
1672
- this.v = e, this.k = d;
1673
- }
1674
- __name(_OverloadYield, "_OverloadYield");
1675
- module.exports = _OverloadYield, module.exports.__esModule = true, module.exports["default"] = module.exports;
1676
- } });
1677
- var require_awaitAsyncGenerator = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/awaitAsyncGenerator.js"(exports, module) {
1678
- var OverloadYield$1 = require_OverloadYield();
1679
- function _awaitAsyncGenerator$1(e) {
1680
- return new OverloadYield$1(e, 0);
1681
- }
1682
- __name(_awaitAsyncGenerator$1, "_awaitAsyncGenerator$1");
1683
- module.exports = _awaitAsyncGenerator$1, module.exports.__esModule = true, module.exports["default"] = module.exports;
1684
- } });
1685
- var require_wrapAsyncGenerator = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/wrapAsyncGenerator.js"(exports, module) {
1686
- var OverloadYield = require_OverloadYield();
1687
- function _wrapAsyncGenerator$1(e) {
1688
- return function() {
1689
- return new AsyncGenerator(e.apply(this, arguments));
609
+ if (includes(objectsInThisPath, object)) {
610
+ return {
611
+ transformedValue: null
1690
612
  };
1691
613
  }
1692
- __name(_wrapAsyncGenerator$1, "_wrapAsyncGenerator$1");
1693
- function AsyncGenerator(e) {
1694
- var r, t;
1695
- function resume(r$1, t$1) {
1696
- try {
1697
- var n = e[r$1](t$1), o = n.value, u = o instanceof OverloadYield;
1698
- Promise.resolve(u ? o.v : o).then(function(t$2) {
1699
- if (u) {
1700
- var i = "return" === r$1 ? "return" : "next";
1701
- if (!o.k || t$2.done) return resume(i, t$2);
1702
- t$2 = e[i](t$2).value;
1703
- }
1704
- settle(n.done ? "return" : "normal", t$2);
1705
- }, function(e$1) {
1706
- resume("throw", e$1);
1707
- });
1708
- } catch (e$1) {
1709
- settle("throw", e$1);
1710
- }
614
+ const transformationResult = transformValue(object, superJson);
615
+ const transformed = transformationResult?.value ?? object;
616
+ const transformedValue = isArray$1(transformed) ? [] : {};
617
+ const innerAnnotations = {};
618
+ forEach(transformed, (value, index) => {
619
+ if (index === "__proto__" || index === "constructor" || index === "prototype") {
620
+ throw new Error(`Detected property ${index}. This is a prototype pollution risk, please remove it from your object.`);
1711
621
  }
1712
- __name(resume, "resume");
1713
- function settle(e$1, n) {
1714
- switch (e$1) {
1715
- case "return":
1716
- r.resolve({
1717
- value: n,
1718
- done: true
1719
- });
1720
- break;
1721
- case "throw":
1722
- r.reject(n);
1723
- break;
1724
- default:
1725
- r.resolve({
1726
- value: n,
1727
- done: false
1728
- });
1729
- }
1730
- (r = r.next) ? resume(r.key, r.arg) : t = null;
1731
- }
1732
- __name(settle, "settle");
1733
- this._invoke = function(e$1, n) {
1734
- return new Promise(function(o, u) {
1735
- var i = {
1736
- key: e$1,
1737
- arg: n,
1738
- resolve: o,
1739
- reject: u,
1740
- next: null
1741
- };
1742
- t ? t = t.next = i : (r = t = i, resume(e$1, n));
622
+ const recursiveResult = walker(value, identities, superJson, dedupe, [...path, index], [...objectsInThisPath, object], seenObjects);
623
+ transformedValue[index] = recursiveResult.transformedValue;
624
+ if (isArray$1(recursiveResult.annotations)) {
625
+ innerAnnotations[escapeKey(index)] = recursiveResult.annotations;
626
+ } else if (isPlainObject$1(recursiveResult.annotations)) {
627
+ forEach(recursiveResult.annotations, (tree, key) => {
628
+ innerAnnotations[escapeKey(index) + "." + key] = tree;
1743
629
  });
1744
- }, "function" != typeof e["return"] && (this["return"] = void 0);
1745
- }
1746
- __name(AsyncGenerator, "AsyncGenerator");
1747
- AsyncGenerator.prototype["function" == typeof Symbol && Symbol.asyncIterator || "@@asyncIterator"] = function() {
1748
- return this;
1749
- }, AsyncGenerator.prototype.next = function(e) {
1750
- return this._invoke("next", e);
1751
- }, AsyncGenerator.prototype["throw"] = function(e) {
1752
- return this._invoke("throw", e);
1753
- }, AsyncGenerator.prototype["return"] = function(e) {
1754
- return this._invoke("return", e);
630
+ }
631
+ });
632
+ const result = isEmptyObject(innerAnnotations) ? {
633
+ transformedValue,
634
+ annotations: !!transformationResult ? [transformationResult.type] : void 0
635
+ } : {
636
+ transformedValue,
637
+ annotations: !!transformationResult ? [transformationResult.type, innerAnnotations] : innerAnnotations
1755
638
  };
1756
- module.exports = _wrapAsyncGenerator$1, module.exports.__esModule = true, module.exports["default"] = module.exports;
1757
- } });
1758
- var import_usingCtx = __toESM(require_usingCtx(), 1);
1759
- var import_awaitAsyncGenerator = __toESM(require_awaitAsyncGenerator(), 1);
1760
- var import_wrapAsyncGenerator = __toESM(require_wrapAsyncGenerator(), 1);
1761
- var import_objectSpread29 = __toESM(require_objectSpread2(), 1);
1762
-
1763
- // src/backend-client.ts
1764
- import superjson from "superjson";
1765
- var BackendClient = class {
1766
- static {
1767
- __name(this, "BackendClient");
1768
- }
1769
- /** Raw tRPC client — for advanced usage / direct path access */
1770
- trpc;
1771
- serverUrl;
1772
- token;
1773
- wsClient = null;
1774
- constructor(config) {
1775
- this.serverUrl = config.serverUrl.replace(/\/+$/, "");
1776
- this.token = config.token;
1777
- const isBrowser = typeof window !== "undefined";
1778
- const useWs = config.useWebSocket ?? isBrowser;
1779
- const headers = /* @__PURE__ */ __name(() => {
1780
- const h = {};
1781
- if (this.token) {
1782
- h["Authorization"] = `Bearer ${this.token}`;
1783
- }
1784
- return h;
1785
- }, "headers");
1786
- if (useWs) {
1787
- const wsUrl = this.serverUrl.replace(/^http/, "ws") + "/trpc";
1788
- this.wsClient = createWSClient({
1789
- url: wsUrl,
1790
- connectionParams: /* @__PURE__ */ __name(() => ({
1791
- token: this.token
1792
- }), "connectionParams"),
1793
- retryDelayMs: /* @__PURE__ */ __name(() => 2e3, "retryDelayMs")
1794
- });
1795
- this.trpc = createTRPCClient({
1796
- links: [
1797
- wsLink({
1798
- client: this.wsClient,
1799
- transformer: superjson
1800
- })
1801
- ]
1802
- });
1803
- } else {
1804
- this.trpc = createTRPCClient({
1805
- links: [
1806
- httpLink({
1807
- url: `${this.serverUrl}/trpc`,
1808
- headers,
1809
- transformer: superjson
1810
- })
1811
- ]
1812
- });
639
+ if (!primitive) {
640
+ seenObjects.set(object, result);
641
+ }
642
+ return result;
643
+ };
644
+ function getType(payload) {
645
+ return Object.prototype.toString.call(payload).slice(8, -1);
646
+ }
647
+ function isArray(payload) {
648
+ return getType(payload) === "Array";
649
+ }
650
+ function isPlainObject(payload) {
651
+ if (getType(payload) !== "Object")
652
+ return false;
653
+ const prototype = Object.getPrototypeOf(payload);
654
+ return !!prototype && prototype.constructor === Object && prototype === Object.prototype;
655
+ }
656
+ function assignProp(carry, key, newVal, originalObject, includeNonenumerable) {
657
+ const propType = {}.propertyIsEnumerable.call(originalObject, key) ? "enumerable" : "nonenumerable";
658
+ if (propType === "enumerable")
659
+ carry[key] = newVal;
660
+ if (includeNonenumerable && propType === "nonenumerable") {
661
+ Object.defineProperty(carry, key, {
662
+ value: newVal,
663
+ enumerable: false,
664
+ writable: true,
665
+ configurable: true
666
+ });
667
+ }
668
+ }
669
+ function copy(target, options = {}) {
670
+ if (isArray(target)) {
671
+ return target.map((item) => copy(item, options));
672
+ }
673
+ if (!isPlainObject(target)) {
674
+ return target;
675
+ }
676
+ const props = Object.getOwnPropertyNames(target);
677
+ const symbols = Object.getOwnPropertySymbols(target);
678
+ return [...props, ...symbols].reduce((carry, key) => {
679
+ if (key === "__proto__")
680
+ return carry;
681
+ if (isArray(options.props) && !options.props.includes(key)) {
682
+ return carry;
683
+ }
684
+ const val = target[key];
685
+ const newVal = copy(val, options);
686
+ assignProp(carry, key, newVal, target, options.nonenumerable);
687
+ return carry;
688
+ }, {});
689
+ }
690
+ class SuperJSON {
691
+ /**
692
+ * @param dedupeReferentialEqualities If true, SuperJSON will make sure only one instance of referentially equal objects are serialized and the rest are replaced with `null`.
693
+ */
694
+ constructor({ dedupe = false } = {}) {
695
+ this.classRegistry = new ClassRegistry();
696
+ this.symbolRegistry = new Registry((s) => s.description ?? "");
697
+ this.customTransformerRegistry = new CustomTransformerRegistry();
698
+ this.allowedErrorProps = [];
699
+ this.dedupe = dedupe;
700
+ }
701
+ serialize(object) {
702
+ const identities = /* @__PURE__ */ new Map();
703
+ const output = walker(object, identities, this, this.dedupe);
704
+ const res = {
705
+ json: output.transformedValue
706
+ };
707
+ if (output.annotations) {
708
+ res.meta = {
709
+ ...res.meta,
710
+ values: output.annotations
711
+ };
712
+ }
713
+ const equalityAnnotations = generateReferentialEqualityAnnotations(identities, this.dedupe);
714
+ if (equalityAnnotations) {
715
+ res.meta = {
716
+ ...res.meta,
717
+ referentialEqualities: equalityAnnotations
718
+ };
719
+ }
720
+ if (res.meta)
721
+ res.meta.v = 1;
722
+ return res;
723
+ }
724
+ deserialize(payload, options) {
725
+ const { json, meta } = payload;
726
+ let result = options?.inPlace ? json : copy(json);
727
+ if (meta?.values) {
728
+ result = applyValueAnnotations(result, meta.values, meta.v ?? 0, this);
1813
729
  }
730
+ if (meta?.referentialEqualities) {
731
+ result = applyReferentialEqualityAnnotations(result, meta.referentialEqualities, meta.v ?? 0);
732
+ }
733
+ return result;
1814
734
  }
1815
- /** Update the auth token (e.g. after login) */
1816
- setToken(token) {
1817
- this.token = token;
735
+ stringify(object) {
736
+ return JSON.stringify(this.serialize(object));
1818
737
  }
1819
- /** Close the WebSocket connection (if using WS transport) */
1820
- close() {
1821
- this.wsClient?.close();
738
+ parse(string) {
739
+ return this.deserialize(JSON.parse(string), { inPlace: true });
1822
740
  }
1823
- // ─── Auth ──────────────────────────────────────────────────────────
1824
- async login(username, password) {
1825
- return this.trpc.auth.login.mutate({
1826
- username,
1827
- password
741
+ registerClass(v, options) {
742
+ this.classRegistry.register(v, options);
743
+ }
744
+ registerSymbol(v, identifier) {
745
+ this.symbolRegistry.register(v, identifier);
746
+ }
747
+ registerCustom(transformer, name) {
748
+ this.customTransformerRegistry.register({
749
+ name,
750
+ ...transformer
1828
751
  });
1829
752
  }
1830
- async getMe() {
1831
- return this.trpc.auth.me.query();
753
+ allowErrorProps(...props) {
754
+ this.allowedErrorProps.push(...props);
1832
755
  }
1833
- async logout() {
1834
- return this.trpc.auth.logout.mutate();
756
+ }
757
+ SuperJSON.defaultInstance = new SuperJSON();
758
+ SuperJSON.serialize = SuperJSON.defaultInstance.serialize.bind(SuperJSON.defaultInstance);
759
+ SuperJSON.deserialize = SuperJSON.defaultInstance.deserialize.bind(SuperJSON.defaultInstance);
760
+ SuperJSON.stringify = SuperJSON.defaultInstance.stringify.bind(SuperJSON.defaultInstance);
761
+ SuperJSON.parse = SuperJSON.defaultInstance.parse.bind(SuperJSON.defaultInstance);
762
+ SuperJSON.registerClass = SuperJSON.defaultInstance.registerClass.bind(SuperJSON.defaultInstance);
763
+ SuperJSON.registerSymbol = SuperJSON.defaultInstance.registerSymbol.bind(SuperJSON.defaultInstance);
764
+ SuperJSON.registerCustom = SuperJSON.defaultInstance.registerCustom.bind(SuperJSON.defaultInstance);
765
+ SuperJSON.allowErrorProps = SuperJSON.defaultInstance.allowErrorProps.bind(SuperJSON.defaultInstance);
766
+ SuperJSON.serialize;
767
+ SuperJSON.deserialize;
768
+ SuperJSON.stringify;
769
+ SuperJSON.parse;
770
+ SuperJSON.registerClass;
771
+ SuperJSON.registerCustom;
772
+ SuperJSON.registerSymbol;
773
+ SuperJSON.allowErrorProps;
774
+ const WS_KEEP_ALIVE_INTERVAL_MS = 1e4;
775
+ const WS_KEEP_ALIVE_PONG_TIMEOUT_MS = 3e3;
776
+ const WS_RECONNECT_RETRY_DELAY_MS = 2e3;
777
+ const WS_RECONNECT_MAX_RETRY_DELAY_MS = 3e4;
778
+ class System {
779
+ /** Active server base URL. Mutable via `switchServerUrl()` so the
780
+ * endpoint-race helper can pivot the transport onto a LAN candidate
781
+ * after the initial public-URL bootstrap. */
782
+ _serverUrl;
783
+ useWs;
784
+ baseRetryMs;
785
+ maxRetryMs;
786
+ onConnectionChange;
787
+ token;
788
+ _trpcClient;
789
+ _wsClient = null;
790
+ // Mirror — owns binding cache + state mirror + lifecycle listeners.
791
+ // Lazily initialised on `init()`. Subsequent `reconnect()` disposes
792
+ // the old mirror and rebuilds against the new tRPC client.
793
+ mirror = null;
794
+ mirrorInit = null;
795
+ // Transport-readiness probe state. `connected` flips true the first
796
+ // time `auth.me` succeeds against the current tRPC client; resets
797
+ // on every `reconnect()` / `close()` so the next consumer waits for
798
+ // a fresh handshake before issuing queries.
799
+ connected = false;
800
+ connectedPromise = null;
801
+ // System-cap namespaces — populated in the constructor from
802
+ // `createSystemProxy(api)`. Each namespace is a `Pick<InferProvider<typeof cap>, …>`
803
+ // shape generated by `scripts/generate-system-proxy.ts`.
804
+ _systemProxy;
805
+ // Connection-version + listener bookkeeping for the admin UI's
806
+ // reconnect watchdog.
807
+ _connectionVersion = 0;
808
+ connectionListeners = /* @__PURE__ */ new Set();
809
+ constructor(config) {
810
+ this._serverUrl = config.serverUrl.replace(/\/+$/, "");
811
+ this.token = config.token;
812
+ const isBrowser = typeof window !== "undefined";
813
+ this.useWs = config.useWebSocket ?? isBrowser;
814
+ this.onConnectionChange = config.onConnectionChange;
815
+ this.baseRetryMs = config.retryDelayMs ?? WS_RECONNECT_RETRY_DELAY_MS;
816
+ this.maxRetryMs = config.maxRetryDelayMs ?? WS_RECONNECT_MAX_RETRY_DELAY_MS;
817
+ this._trpcClient = this.buildTrpcClient();
818
+ this._systemProxy = createSystemProxy(this._trpcClient);
1835
819
  }
1836
- // ─── System ────────────────────────────────────────────────────────
1837
- async getSystemInfo() {
1838
- return this.trpc.system.info.query();
820
+ // ── Connection state ─────────────────────────────────────────────
821
+ /** Active server base URL (no trailing slash). */
822
+ get serverUrl() {
823
+ return this._serverUrl;
1839
824
  }
1840
- async getFeatureFlags() {
1841
- return this.trpc.system.featureFlags.query();
825
+ get connectionVersion() {
826
+ return this._connectionVersion;
1842
827
  }
1843
- // ─── Providers ─────────────────────────────────────────────────────
1844
- async listProviders() {
1845
- return this.trpc.providers.list.query();
828
+ /**
829
+ * Subscribe to connection-state transitions. Called with `('connected'
830
+ * | 'disconnected' | 'connecting', version)` whenever the SDK opens,
831
+ * closes, or starts a manual reconnect. Listener errors are swallowed
832
+ * so a misbehaving consumer cannot break the SDK's event loop.
833
+ */
834
+ subscribeConnectionEvents(cb) {
835
+ this.connectionListeners.add(cb);
836
+ return () => {
837
+ this.connectionListeners.delete(cb);
838
+ };
1846
839
  }
1847
- async getProvider(providerId) {
1848
- return this.trpc.providers.get.query({
1849
- id: providerId
1850
- });
840
+ emitConnectionEvent(state) {
841
+ try {
842
+ this.onConnectionChange?.(state);
843
+ } catch {
844
+ }
845
+ for (const l of this.connectionListeners) {
846
+ try {
847
+ l(state, this._connectionVersion);
848
+ } catch {
849
+ }
850
+ }
1851
851
  }
1852
- async startProvider(providerId) {
1853
- return this.trpc.providers.start.mutate({
1854
- id: providerId
1855
- });
852
+ // ── Lifecycle ────────────────────────────────────────────────────
853
+ /**
854
+ * Wait until the underlying tRPC transport is connected AND the
855
+ * server has responded to a cheap auth round-trip (`auth.me`). This
856
+ * is the canonical "ready to issue queries" gate.
857
+ *
858
+ * Why a probe, not just `ws.readyState === OPEN`?
859
+ * The WS handshake completes asynchronously: tRPC's `wsLink`
860
+ * queues outgoing messages and only flushes them after `open()`
861
+ * resolves (post `connectionParams` send). On the server, the
862
+ * tRPC context is created lazily once the connectionParams
863
+ * message is received. A query fired between WS-open and
864
+ * connection-params-processed is technically queued by tRPC, but
865
+ * the auth context for that query is only resolved once the
866
+ * handshake message is decoded server-side. A probe round-trip is
867
+ * the safest way to confirm both sides have agreed on the auth
868
+ * identity before the React tree starts firing parallel queries
869
+ * (which can otherwise land before any addon-side service
870
+ * discovery has settled, returning empty results that get cached).
871
+ *
872
+ * Idempotent — concurrent callers await the same in-flight Promise.
873
+ * Bounded by `timeoutMs` (default 15s) — beyond which a
874
+ * `Error('System.awaitConnected: probe timed out after Xms')` is
875
+ * thrown so the host can render a clear error state instead of
876
+ * hanging on a bricked socket.
877
+ */
878
+ async awaitConnected(timeoutMs) {
879
+ if (this.connected) return;
880
+ if (this.connectedPromise) return this.connectedPromise;
881
+ const effectiveTimeoutMs = timeoutMs ?? 15e3;
882
+ this.connectedPromise = (async () => {
883
+ const probe = this._trpcClient.auth.me.query();
884
+ if (!Number.isFinite(effectiveTimeoutMs)) {
885
+ await probe;
886
+ } else {
887
+ await new Promise((resolve, reject) => {
888
+ const timer = setTimeout(
889
+ () => reject(new Error(`System.awaitConnected: probe timed out after ${effectiveTimeoutMs}ms`)),
890
+ effectiveTimeoutMs
891
+ );
892
+ probe.then(
893
+ () => {
894
+ clearTimeout(timer);
895
+ resolve();
896
+ },
897
+ (err) => {
898
+ clearTimeout(timer);
899
+ reject(err instanceof Error ? err : new Error(String(err)));
900
+ }
901
+ );
902
+ });
903
+ }
904
+ this.connected = true;
905
+ })();
906
+ try {
907
+ await this.connectedPromise;
908
+ } finally {
909
+ this.connectedPromise = null;
910
+ }
1856
911
  }
1857
- async stopProvider(providerId) {
1858
- return this.trpc.providers.stop.mutate({
1859
- id: providerId
912
+ /**
913
+ * Warm-boot the device mirror. Awaits the transport probe first
914
+ * (`awaitConnected`) so the three mirror round-trips
915
+ * (`getAllBindings` + `getAllSnapshots` + `listAll`) cannot race
916
+ * against the WS auth handshake. Subsequent `getDevice(id)` calls
917
+ * are sync; live `device.*` event subscriptions keep the caches
918
+ * fresh.
919
+ *
920
+ * Idempotent — concurrent callers await the same in-flight Promise.
921
+ */
922
+ async init(timeoutMs) {
923
+ if (this.mirror?.isReady()) return;
924
+ if (this.mirrorInit) return this.mirrorInit;
925
+ const m = new SystemMirror(this._trpcClient);
926
+ this.mirror = m;
927
+ this.mirrorInit = (async () => {
928
+ await this.awaitConnected(timeoutMs);
929
+ await m.init(timeoutMs);
930
+ })().finally(() => {
931
+ this.mirrorInit = null;
1860
932
  });
933
+ return this.mirrorInit;
1861
934
  }
1862
- async listProviderTypes() {
1863
- return this.trpc.providerConfig.getAvailableTypes.query();
935
+ /** Promise that resolves once `init()` has completed. */
936
+ async awaitReady() {
937
+ if (this.mirror?.isReady()) return;
938
+ if (this.mirrorInit) return this.mirrorInit;
939
+ return this.init();
1864
940
  }
1865
- // ─── Devices ───────────────────────────────────────────────────────
1866
- async listDevices() {
1867
- return this.trpc.devices.list.query();
941
+ /** True after `init()` resolves. */
942
+ isReady() {
943
+ return this.mirror?.isReady() ?? false;
1868
944
  }
1869
- async getDevice(deviceId) {
1870
- return this.trpc.devices.get.query({
1871
- id: deviceId
1872
- });
945
+ /** True after the transport probe has succeeded at least once. */
946
+ isConnected() {
947
+ return this.connected;
1873
948
  }
1874
- async discoverDevices(providerId) {
1875
- return this.trpc.devices.discoverDevices.query({
1876
- providerId
1877
- });
1878
- }
1879
- async adoptDevice(providerId, externalId) {
1880
- return this.trpc.devices.adoptDevice.mutate({
1881
- providerId,
1882
- externalId
1883
- });
949
+ /**
950
+ * Force a fresh WebSocket handshake. Tears down the wsClient + tRPC
951
+ * client + mirror (the mirror captures the tRPC reference at
952
+ * construction time and would otherwise dispatch through a closed
953
+ * client) and rebuilds them. No-op for HTTP transport.
954
+ */
955
+ reconnect() {
956
+ if (!this.useWs) return;
957
+ this.emitConnectionEvent("connecting");
958
+ this._wsClient?.close();
959
+ this.disposeMirror();
960
+ this.connected = false;
961
+ this.connectedPromise = null;
962
+ this._trpcClient = this.buildTrpcClient();
963
+ this._systemProxy = createSystemProxy(this._trpcClient);
1884
964
  }
1885
- async createDevice(providerId, config) {
1886
- return this.trpc.devices.createDevice.mutate({
1887
- providerId,
1888
- config
1889
- });
965
+ /**
966
+ * Pivot the underlying tRPC transport onto a different base URL.
967
+ * Used by the endpoint-race flow: the SDK opens against the public
968
+ * URL the operator provided, calls `localNetwork.getConnectionEndpoints`
969
+ * to discover LAN candidates, races them, and (when a faster one wins)
970
+ * calls `switchServerUrl(winner)` to migrate every subsequent query
971
+ * onto the LAN path without losing auth state.
972
+ *
973
+ * Keeps the auth token. Tears down the WS + mirror and rebuilds them
974
+ * against the new URL — same machinery as `reconnect()` but with a
975
+ * different target.
976
+ */
977
+ switchServerUrl(nextUrl) {
978
+ const normalized = nextUrl.replace(/\/+$/, "");
979
+ if (normalized === this._serverUrl) return;
980
+ this._serverUrl = normalized;
981
+ this.reconnect();
1890
982
  }
1891
- /** Returns the URL path for a static asset served by an addon. */
1892
- getAddonAssetUrl(addonId, assetPath) {
1893
- return `/api/addon-assets/${addonId}/${assetPath}`;
983
+ /**
984
+ * Race the candidate base URLs reported by the hub's `local-network`
985
+ * cap, pick the fastest one that responds, and (if it's different
986
+ * from the current URL) pivot the transport onto it.
987
+ *
988
+ * Flow:
989
+ * 1. Query `localNetwork.getConnectionEndpoints({ port })` over the
990
+ * already-authenticated tRPC channel — the cap is auth-gated,
991
+ * so the LAN IPs never leak to anonymous callers.
992
+ * 2. For each candidate, fire a HEAD on `{baseUrl}/trpc/health`
993
+ * with a short timeout (default 1500ms). The first 2xx wins.
994
+ * 3. If the winner differs from `this.serverUrl`, call
995
+ * `switchServerUrl(winner)` and return it. Otherwise return
996
+ * the current URL unchanged.
997
+ *
998
+ * Bounded — if every candidate times out we keep the current URL.
999
+ * Idempotent — safe to call on every connect / reconnect / network
1000
+ * change event.
1001
+ */
1002
+ async raceConnectionEndpoints(options) {
1003
+ const timeoutMs = options?.perCandidateTimeoutMs ?? 1500;
1004
+ const url = (() => {
1005
+ try {
1006
+ return new URL(this._serverUrl);
1007
+ } catch {
1008
+ return null;
1009
+ }
1010
+ })();
1011
+ const port = url?.port ? Number(url.port) : url?.protocol === "https:" ? 443 : 80;
1012
+ const scheme = url?.protocol === "https:" ? "https" : "http";
1013
+ const proxy = this._trpcClient;
1014
+ const cap = proxy.localNetwork?.getConnectionEndpoints;
1015
+ if (!cap) {
1016
+ return { winner: this._serverUrl, switched: false };
1017
+ }
1018
+ let endpoints = [];
1019
+ try {
1020
+ const res = await cap.query({ port, ipv4Only: options?.ipv4Only, scheme });
1021
+ endpoints = res.endpoints;
1022
+ } catch {
1023
+ return { winner: this._serverUrl, switched: false };
1024
+ }
1025
+ if (endpoints.length === 0) {
1026
+ return { winner: this._serverUrl, switched: false };
1027
+ }
1028
+ const winner = await raceFastestEndpoint(endpoints.map((e) => e.baseUrl), timeoutMs);
1029
+ if (!winner || winner === this._serverUrl) {
1030
+ return { winner: winner ?? this._serverUrl, switched: false };
1031
+ }
1032
+ this.switchServerUrl(winner);
1033
+ return { winner, switched: true };
1894
1034
  }
1895
- // ─── Addons ────────────────────────────────────────────────────────
1896
- async listAddons() {
1897
- return this.trpc.addons.list.query();
1035
+ /** Tear down WS connection + mirror. The instance is unusable afterwards. */
1036
+ close() {
1037
+ this.disposeMirror();
1038
+ this.connected = false;
1039
+ this.connectedPromise = null;
1040
+ this._wsClient?.close();
1898
1041
  }
1899
- async getAddonConfigSchema(addonId) {
1900
- return this.trpc.addons.getConfigSchema.query({
1901
- addonId
1902
- });
1042
+ disposeMirror() {
1043
+ this.mirror?.dispose();
1044
+ this.mirror = null;
1045
+ this.mirrorInit = null;
1903
1046
  }
1904
- async getAddonConfig(addonId) {
1905
- return this.trpc.addons.getConfig.query({
1906
- addonId
1907
- });
1047
+ // ── Auth ──────────────────────────────────────────────────────────
1048
+ async login(username, password) {
1049
+ const result = await this._trpcClient.auth.login.mutate({ username, password });
1050
+ if (typeof result === "object" && result !== null && "token" in result) {
1051
+ const token = result.token;
1052
+ if (typeof token === "string") this.setToken(token);
1053
+ }
1054
+ return result;
1908
1055
  }
1909
- async updateAddonConfig(addonId, config) {
1910
- return this.trpc.addons.updateConfig.mutate({
1911
- addonId,
1912
- config
1913
- });
1056
+ async logout() {
1057
+ await this._trpcClient.auth.logout.mutate();
1914
1058
  }
1915
- async getAddonLogs(addonId, options) {
1916
- return this.trpc.addons.getLogs.query({
1917
- addonId,
1918
- ...options
1919
- });
1059
+ async getMe() {
1060
+ const me = await this._trpcClient.auth.me.query();
1061
+ return me;
1920
1062
  }
1921
- // ─── Known Faces ───────────────────────────────────────────────────
1922
- async listKnownFaces() {
1923
- return this.trpc.knownFaces.list.query();
1063
+ /** Update the auth token (e.g. after login or token refresh). */
1064
+ setToken(token) {
1065
+ this.token = token;
1924
1066
  }
1925
- async registerFace(label, cropBase64, group) {
1926
- return this.trpc.knownFaces.register.mutate({
1927
- label,
1928
- cropBase64,
1929
- group
1930
- });
1067
+ // ── Devices ──────────────────────────────────────────────────────
1068
+ /**
1069
+ * Synchronous snapshot of every device matching the optional filters.
1070
+ * Backed by the `SystemMirror` warm-boot cache — call `init()` first
1071
+ * (or `awaitReady()`) before invoking. Returns an empty array if the
1072
+ * mirror has not yet been booted.
1073
+ *
1074
+ * Each returned proxy has `binding` populated from the mirror's
1075
+ * binding cache (Phase 5 dedup), so consumers no longer need to
1076
+ * make a separate `deviceManager.getBindings` round-trip.
1077
+ */
1078
+ listDevices(filters) {
1079
+ if (!this.mirror) return [];
1080
+ const proxies = filters ? this.mirror.query(filters) : this.mirror.getAllDevices();
1081
+ return proxies.map((p) => this.attachBinding(p));
1931
1082
  }
1932
- // ─── Pipeline ──────────────────────────────────────────────────────
1933
- async listPipelines() {
1934
- return this.trpc.bridgePipeline.listAddons.query();
1083
+ /**
1084
+ * Sync lookup by numeric id. `null` if the mirror has not been booted
1085
+ * or the device is unknown.
1086
+ */
1087
+ getDevice(deviceId) {
1088
+ const proxy = this.mirror?.getDeviceById(deviceId) ?? null;
1089
+ return proxy ? this.attachBinding(proxy) : null;
1090
+ }
1091
+ /** Sync lookup by display name (exact match). */
1092
+ getDeviceByName(name) {
1093
+ const proxy = this.mirror?.getDeviceByName(name) ?? null;
1094
+ return proxy ? this.attachBinding(proxy) : null;
1095
+ }
1096
+ /** Sync lookup by stableId. */
1097
+ getDeviceByStableId(stableId) {
1098
+ const proxy = this.mirror?.getDeviceByStableId(stableId) ?? null;
1099
+ return proxy ? this.attachBinding(proxy) : null;
1935
1100
  }
1936
- async getPipelineStatus(deviceId) {
1937
- return this.trpc.bridgePipeline.getPipeline.query({
1938
- deviceId
1939
- });
1101
+ /**
1102
+ * Resolve when a device with `deviceId` becomes available. Resolves
1103
+ * immediately if already known; rejects with a timeout error
1104
+ * otherwise (default 30s).
1105
+ */
1106
+ async waitForDevice(deviceId, timeoutMs) {
1107
+ if (!this.mirror) await this.init();
1108
+ const proxy = await this.mirror.waitForDevice(deviceId, timeoutMs ?? 3e4);
1109
+ return this.attachBinding(proxy);
1110
+ }
1111
+ /** Subscribe to `device.registered` events. */
1112
+ onDeviceAdded(cb) {
1113
+ if (!this.mirror) {
1114
+ throw new Error("System.onDeviceAdded: call init() before subscribing");
1115
+ }
1116
+ return this.mirror.onDeviceAdded(cb);
1940
1117
  }
1941
- // ─── Agents ────────────────────────────────────────────────────────
1942
- async listAgents() {
1943
- return this.trpc.agents.listAgents.query();
1118
+ /** Subscribe to `device.unregistered` events. */
1119
+ onDeviceRemoved(cb) {
1120
+ if (!this.mirror) {
1121
+ throw new Error("System.onDeviceRemoved: call init() before subscribing");
1122
+ }
1123
+ return this.mirror.onDeviceRemoved(cb);
1944
1124
  }
1945
- async dispatchTask(agentId, task) {
1946
- return this.trpc.agents.dispatchTask.mutate({
1947
- capability: agentId,
1948
- input: task
1949
- });
1125
+ /**
1126
+ * Patch the proxy's `binding` field from the mirror's cache. The
1127
+ * generated `createDeviceProxy()` already sets `binding` to the
1128
+ * binding it was constructed with — this is a defensive overwrite
1129
+ * that uses the latest cached entry in case a `binding-changed`
1130
+ * event landed between proxy creation and access.
1131
+ */
1132
+ attachBinding(proxy) {
1133
+ const binding = this.lookupBinding(proxy.deviceId);
1134
+ if (binding === proxy.binding) return proxy;
1135
+ const writable = proxy;
1136
+ writable.binding = binding;
1137
+ return proxy;
1950
1138
  }
1951
- async getProcessTree() {
1952
- return this.trpc.agent.processTree.query();
1139
+ /** Fetch the latest cached binding from the mirror, or `null`. */
1140
+ lookupBinding(deviceId) {
1141
+ if (!this.mirror) return null;
1142
+ const proxy = this.mirror.getDeviceById(deviceId);
1143
+ return proxy?.binding ?? null;
1953
1144
  }
1954
- // ─── Bridge Pipeline ───────────────────────────────────────────────
1955
- async bridgeListAddons() {
1956
- return this.trpc.bridgePipeline.listAddons.query();
1145
+ // ── System caps ──────────────────────────────────────────────────
1146
+ //
1147
+ // One getter per `scope: 'system'` capability. The actual surface
1148
+ // comes from `createSystemProxy(api)` (codegen). Adding a new
1149
+ // system cap regenerates the proxy and the new namespace surfaces
1150
+ // automatically via `system.<newCap>.<method>(input)`.
1151
+ get addonPages() {
1152
+ return this._systemProxy.addonPages;
1957
1153
  }
1958
- async bridgeGetPipeline(deviceId) {
1959
- return this.trpc.bridgePipeline.getPipeline.query({
1960
- deviceId
1961
- });
1154
+ get addonSettings() {
1155
+ return this._systemProxy.addonSettings;
1962
1156
  }
1963
- async bridgeSetPipeline(deviceId, config) {
1964
- return this.trpc.bridgePipeline.setPipeline.mutate({
1965
- deviceId,
1966
- config
1967
- });
1157
+ get alerts() {
1158
+ return this._systemProxy.alerts;
1968
1159
  }
1969
- async bridgeValidatePipeline(config) {
1970
- return this.trpc.bridgePipeline.validatePipeline.query(config);
1160
+ get audioAnalyzer() {
1161
+ return this._systemProxy.audioAnalyzer;
1971
1162
  }
1972
- async bridgeGetAddonConfig(addonId) {
1973
- return this.trpc.bridgePipeline.getAddonConfig.query({
1974
- addonId
1975
- });
1163
+ get audioCodec() {
1164
+ return this._systemProxy.audioCodec;
1976
1165
  }
1977
- async bridgeSetAddonConfig(addonId, config) {
1978
- return this.trpc.bridgePipeline.setAddonConfig.mutate({
1979
- addonId,
1980
- config
1981
- });
1166
+ get backup() {
1167
+ return this._systemProxy.backup;
1982
1168
  }
1983
- // ─── Addon Packages ────────────────────────────────────────────────
1984
- async bridgeListPackages() {
1985
- return this.trpc.addons.listPackages.query();
1169
+ get decoder() {
1170
+ return this._systemProxy.decoder;
1986
1171
  }
1987
- async bridgeListAddonsPackages() {
1988
- return this.trpc.addons.list.query();
1172
+ get deviceManager() {
1173
+ return this._systemProxy.deviceManager;
1989
1174
  }
1990
- async bridgeInstallPackage(packageName, version) {
1991
- return this.trpc.addons.installPackage.mutate({
1992
- packageName,
1993
- version
1994
- });
1175
+ get deviceProvider() {
1176
+ return this._systemProxy.deviceProvider;
1995
1177
  }
1996
- async bridgeUninstallPackage(packageName) {
1997
- return this.trpc.addons.uninstallPackage.mutate({
1998
- packageName
1999
- });
1178
+ get deviceState() {
1179
+ return this._systemProxy.deviceState;
2000
1180
  }
2001
- // ─── Recording ─────────────────────────────────────────────────────
2002
- async getRecordingConfig(deviceId) {
2003
- return this.trpc.recording.getConfig.query({
2004
- deviceId
2005
- });
1181
+ get metricsProvider() {
1182
+ return this._systemProxy.metricsProvider;
2006
1183
  }
2007
- async getRecordingPolicy(deviceId) {
2008
- return this.trpc.recording.getPolicy.query({
2009
- deviceId
2010
- });
1184
+ get notificationOutput() {
1185
+ return this._systemProxy.notificationOutput;
2011
1186
  }
2012
- async getRecordingPolicyStatus(deviceId) {
2013
- return this.trpc.recording.getPolicyStatus.query({
2014
- deviceId
2015
- });
1187
+ get pipelineExecutor() {
1188
+ return this._systemProxy.pipelineExecutor;
2016
1189
  }
2017
- async getRecordingSegments(deviceId, streamId, startTime, endTime) {
2018
- return this.trpc.recording.getSegments.query({
2019
- deviceId,
2020
- streamId,
2021
- startTime,
2022
- endTime
2023
- });
1190
+ get pipelineOrchestrator() {
1191
+ return this._systemProxy.pipelineOrchestrator;
2024
1192
  }
2025
- // ─── Events ────────────────────────────────────────────────────────
2026
- async getEvents(deviceId, options) {
2027
- return this.trpc.events.query.query({
2028
- deviceId,
2029
- ...options
2030
- });
1193
+ get pipelineRunner() {
1194
+ return this._systemProxy.pipelineRunner;
2031
1195
  }
2032
- // ─── Logs ──────────────────────────────────────────────────────────
2033
- async getLogs(options) {
2034
- return this.trpc.logs.query.query(options ?? {});
1196
+ get platformProbe() {
1197
+ return this._systemProxy.platformProbe;
2035
1198
  }
2036
- // ─── REPL ──────────────────────────────────────────────────────────
2037
- async replEval(code, scope) {
2038
- return this.trpc.repl.execute.mutate({
2039
- code,
2040
- scope: scope ?? {
2041
- type: "system"
2042
- }
2043
- });
1199
+ get recordingEngine() {
1200
+ return this._systemProxy.recordingEngine;
2044
1201
  }
2045
- // ─── Users ─────────────────────────────────────────────────────────
2046
- async listUsers() {
2047
- return this.trpc.users.list.query();
1202
+ get settingsStore() {
1203
+ return this._systemProxy.settingsStore;
2048
1204
  }
2049
- async createUser(username, password, role) {
2050
- return this.trpc.users.create.mutate({
2051
- username,
2052
- password,
2053
- role
2054
- });
1205
+ get storage() {
1206
+ return this._systemProxy.storage;
2055
1207
  }
2056
- // ─── Session Tracker ───────────────────────────────────────────────
2057
- async getTrackingSessions(deviceId) {
2058
- return this.trpc.session.getActiveTracks.query({
2059
- deviceId
2060
- });
1208
+ get streamBroker() {
1209
+ return this._systemProxy.streamBroker;
2061
1210
  }
2062
- // ─── Processes ─────────────────────────────────────────────────────
2063
- async listProcesses() {
2064
- return this.trpc.processes.listProcesses.query();
1211
+ get turnProvider() {
1212
+ return this._systemProxy.turnProvider;
2065
1213
  }
2066
- async enableProvider(providerId) {
2067
- return this.trpc.processes.enableProvider.mutate({
2068
- id: providerId
2069
- });
1214
+ get userManagement() {
1215
+ return this._systemProxy.userManagement;
2070
1216
  }
2071
- async disableProvider(providerId) {
2072
- return this.trpc.processes.disableProvider.mutate({
2073
- id: providerId
2074
- });
1217
+ // ── Live events ──────────────────────────────────────────────────
1218
+ /**
1219
+ * Subscribe to a single event category. Returns an unsubscribe
1220
+ * handle. Errors thrown by the listener are swallowed so a single
1221
+ * misbehaving consumer cannot tear down the WS subscription.
1222
+ *
1223
+ * Categories should be values from the `EventCategory` enum
1224
+ * (`@camstack/types`) — passing a raw string works for forward-compat
1225
+ * but loses type safety. The SDK forwards the value verbatim to the
1226
+ * server's `live.onEvent` subscription.
1227
+ */
1228
+ subscribeEvent(category, cb) {
1229
+ const sub = this._trpcClient.live.onEvent.subscribe(
1230
+ { category },
1231
+ {
1232
+ onData: (event) => {
1233
+ try {
1234
+ cb(event);
1235
+ } catch {
1236
+ }
1237
+ }
1238
+ }
1239
+ );
1240
+ return () => {
1241
+ try {
1242
+ sub.unsubscribe();
1243
+ } catch {
1244
+ }
1245
+ };
2075
1246
  }
2076
- // ─── Settings ──────────────────────────────────────────────────────
2077
- /** Fetch the UI schema for a single section, or all sections if omitted. */
2078
- async getSettingsSchema(section) {
2079
- return this.trpc.settings.getSchema.query({
2080
- section
2081
- });
1247
+ // ── Escape hatches ───────────────────────────────────────────────
1248
+ //
1249
+ // Kept public so the ui-library `<TrpcProvider>` can seed React
1250
+ // Query with the same WebSocket connection during Phase 2. Phase 4
1251
+ // is expected to revisit whether either field can be hidden.
1252
+ /** Direct tRPC client. Read once per call; rebuilt on `reconnect()`. */
1253
+ get trpcClient() {
1254
+ return this._trpcClient;
2082
1255
  }
2083
- async getSettings(section) {
2084
- return this.trpc.settings.get.query({
2085
- section
1256
+ /**
1257
+ * Underlying WSClient (or `null` for HTTP transport). Used by
1258
+ * advanced consumers that need direct access to the WebSocket
1259
+ * (e.g. for keep-alive metrics). Rebuilt on `reconnect()`.
1260
+ */
1261
+ get wsClient() {
1262
+ return this._wsClient;
1263
+ }
1264
+ // ── Internals ────────────────────────────────────────────────────
1265
+ buildTrpcClient() {
1266
+ const headers = () => {
1267
+ const h = {};
1268
+ if (this.token) h["Authorization"] = `Bearer ${this.token}`;
1269
+ return h;
1270
+ };
1271
+ if (this.useWs) {
1272
+ const wsUrl = this._serverUrl.replace(/^http/, "ws") + "/trpc";
1273
+ const baseRetryMs = this.baseRetryMs;
1274
+ const maxRetryMs = this.maxRetryMs;
1275
+ this._wsClient = createWSClient({
1276
+ url: wsUrl,
1277
+ connectionParams: () => ({ token: this.token }),
1278
+ retryDelayMs: (attemptIndex) => Math.min(baseRetryMs * Math.pow(2, attemptIndex), maxRetryMs),
1279
+ keepAlive: {
1280
+ enabled: true,
1281
+ intervalMs: WS_KEEP_ALIVE_INTERVAL_MS,
1282
+ pongTimeoutMs: WS_KEEP_ALIVE_PONG_TIMEOUT_MS
1283
+ },
1284
+ onOpen: () => {
1285
+ this._connectionVersion += 1;
1286
+ this.emitConnectionEvent("connected");
1287
+ },
1288
+ onClose: () => {
1289
+ this.emitConnectionEvent("disconnected");
1290
+ }
1291
+ });
1292
+ return createTRPCClient({
1293
+ links: [wsLink({ client: this._wsClient, transformer: SuperJSON })]
1294
+ });
1295
+ }
1296
+ this._wsClient = null;
1297
+ return createTRPCClient({
1298
+ links: [httpLink({ url: `${this._serverUrl}/trpc`, headers, transformer: SuperJSON })]
2086
1299
  });
2087
1300
  }
2088
- async updateSettings(section, data) {
2089
- return this.trpc.settings.update.mutate({
2090
- section,
2091
- data
2092
- });
1301
+ }
1302
+ function createSystem(config) {
1303
+ return new System(config);
1304
+ }
1305
+ async function raceFastestEndpoint(candidates, timeoutMs) {
1306
+ if (candidates.length === 0) return null;
1307
+ if (typeof fetch !== "function") return candidates[0] ?? null;
1308
+ const pageIsHttps = typeof window !== "undefined" && typeof window.location !== "undefined" && window.location.protocol === "https:";
1309
+ const reachable = pageIsHttps ? candidates.filter((u) => u.toLowerCase().startsWith("https://")) : candidates;
1310
+ if (reachable.length === 0) return null;
1311
+ const controllers = reachable.map(() => new AbortController());
1312
+ const probes = reachable.map(async (baseUrl, i) => {
1313
+ const ctrl = controllers[i];
1314
+ const timer = setTimeout(() => ctrl.abort(), timeoutMs);
1315
+ try {
1316
+ const res = await fetch(`${baseUrl.replace(/\/+$/, "")}/trpc/health`, {
1317
+ method: "GET",
1318
+ signal: ctrl.signal,
1319
+ // Cross-origin probes from a browser sandbox are fine — the
1320
+ // /trpc/health response is open-CORS by the Fastify default.
1321
+ // No credentials needed (this is a transport-quality probe,
1322
+ // not an auth round-trip).
1323
+ credentials: "omit"
1324
+ });
1325
+ if (!res.ok) throw new Error(`${res.status}`);
1326
+ return baseUrl;
1327
+ } finally {
1328
+ clearTimeout(timer);
1329
+ }
1330
+ });
1331
+ try {
1332
+ const winner = await Promise.any(probes);
1333
+ for (const c of controllers) {
1334
+ try {
1335
+ c.abort();
1336
+ } catch {
1337
+ }
1338
+ }
1339
+ return winner;
1340
+ } catch {
1341
+ return null;
2093
1342
  }
2094
- };
2095
- function createBackendClient(config) {
2096
- return new BackendClient(config);
2097
1343
  }
2098
- __name(createBackendClient, "createBackendClient");
2099
-
2100
- // src/detection.ts
2101
- var DetectionClass = /* @__PURE__ */ (function(DetectionClass2) {
1344
+ var DetectionClass = /* @__PURE__ */ ((DetectionClass2) => {
2102
1345
  DetectionClass2["Motion"] = "motion";
2103
1346
  DetectionClass2["Person"] = "person";
2104
1347
  DetectionClass2["Vehicle"] = "vehicle";
@@ -2110,8 +1353,8 @@ var DetectionClass = /* @__PURE__ */ (function(DetectionClass2) {
2110
1353
  DetectionClass2["Doorbell"] = "doorbell";
2111
1354
  DetectionClass2["Sensor"] = "sensor";
2112
1355
  return DetectionClass2;
2113
- })({});
2114
- var animalClasses = [
1356
+ })(DetectionClass || {});
1357
+ const animalClasses = [
2115
1358
  "animal",
2116
1359
  "dog_cat",
2117
1360
  "dog",
@@ -2139,7 +1382,7 @@ var animalClasses = [
2139
1382
  "turtle",
2140
1383
  "lizard"
2141
1384
  ];
2142
- var personClasses = [
1385
+ const personClasses = [
2143
1386
  "person",
2144
1387
  "people",
2145
1388
  "pedestrian",
@@ -2153,7 +1396,7 @@ var personClasses = [
2153
1396
  "head",
2154
1397
  "body"
2155
1398
  ];
2156
- var vehicleClasses = [
1399
+ const vehicleClasses = [
2157
1400
  "vehicle",
2158
1401
  "car",
2159
1402
  "truck",
@@ -2172,7 +1415,7 @@ var vehicleClasses = [
2172
1415
  "ship",
2173
1416
  "helicopter"
2174
1417
  ];
2175
- var faceClasses = [
1418
+ const faceClasses = [
2176
1419
  "face",
2177
1420
  "eyes",
2178
1421
  "nose",
@@ -2200,7 +1443,7 @@ var faceClasses = [
2200
1443
  "facial_landmark",
2201
1444
  "facial_keypoint"
2202
1445
  ];
2203
- var licensePlateClasses = [
1446
+ const licensePlateClasses = [
2204
1447
  "plate",
2205
1448
  "license_plate",
2206
1449
  "front_plate",
@@ -2224,19 +1467,13 @@ var licensePlateClasses = [
2224
1467
  "obscured_plate",
2225
1468
  "dirty_plate"
2226
1469
  ];
2227
- var motionClasses = [
2228
- "motion",
2229
- "movement",
2230
- "other"
2231
- ];
2232
- var packageClasses = [
2233
- "package",
2234
- "packet"
2235
- ];
2236
- var audioClasses = [
1470
+ const motionClasses = ["motion", "movement", "other"];
1471
+ const packageClasses = ["package", "packet"];
1472
+ const audioClasses = [
2237
1473
  "audio"
1474
+ /* Audio */
2238
1475
  ];
2239
- var audioLabelClasses = [
1476
+ const audioLabelClasses = [
2240
1477
  "speech",
2241
1478
  "scream",
2242
1479
  "babbling",
@@ -2297,11 +1534,8 @@ var audioLabelClasses = [
2297
1534
  "dog",
2298
1535
  "dogs"
2299
1536
  ];
2300
- var doorbellClasses = [
2301
- "doorbell",
2302
- "ring"
2303
- ];
2304
- var sensorLabelClasses = [
1537
+ const doorbellClasses = ["doorbell", "ring"];
1538
+ const sensorLabelClasses = [
2305
1539
  "lock",
2306
1540
  "binary",
2307
1541
  "flood",
@@ -2312,92 +1546,113 @@ var sensorLabelClasses = [
2312
1546
  "flooded",
2313
1547
  "entry_open"
2314
1548
  ];
2315
- var detectionClassesDefaultMap = {
1549
+ const detectionClassesDefaultMap = {
2316
1550
  ...animalClasses.reduce((tot, curr) => ({
2317
1551
  ...tot,
2318
1552
  [curr]: "animal"
1553
+ /* Animal */
2319
1554
  }), {}),
2320
1555
  ...personClasses.reduce((tot, curr) => ({
2321
1556
  ...tot,
2322
1557
  [curr]: "person"
1558
+ /* Person */
2323
1559
  }), {}),
2324
1560
  ...vehicleClasses.reduce((tot, curr) => ({
2325
1561
  ...tot,
2326
1562
  [curr]: "vehicle"
1563
+ /* Vehicle */
2327
1564
  }), {}),
2328
1565
  ...motionClasses.reduce((tot, curr) => ({
2329
1566
  ...tot,
2330
1567
  [curr]: "motion"
1568
+ /* Motion */
2331
1569
  }), {}),
2332
1570
  ...packageClasses.reduce((tot, curr) => ({
2333
1571
  ...tot,
2334
1572
  [curr]: "package"
1573
+ /* Package */
2335
1574
  }), {}),
2336
1575
  ...faceClasses.reduce((tot, curr) => ({
2337
1576
  ...tot,
2338
1577
  [curr]: "face"
1578
+ /* Face */
2339
1579
  }), {}),
2340
1580
  ...licensePlateClasses.reduce((tot, curr) => ({
2341
1581
  ...tot,
2342
1582
  [curr]: "plate"
1583
+ /* Plate */
2343
1584
  }), {}),
2344
1585
  ...audioClasses.reduce((tot, curr) => ({
2345
1586
  ...tot,
2346
1587
  [curr]: "audio"
1588
+ /* Audio */
2347
1589
  }), {}),
2348
1590
  ...audioLabelClasses.reduce((tot, curr) => ({
2349
1591
  ...tot,
2350
1592
  [curr]: "audio"
1593
+ /* Audio */
2351
1594
  }), {}),
2352
1595
  ...doorbellClasses.reduce((tot, curr) => ({
2353
1596
  ...tot,
2354
1597
  [curr]: "doorbell"
1598
+ /* Doorbell */
2355
1599
  }), {}),
2356
1600
  ...sensorLabelClasses.reduce((tot, curr) => ({
2357
1601
  ...tot,
2358
1602
  [curr]: "sensor"
1603
+ /* Sensor */
2359
1604
  }), {})
2360
1605
  };
2361
- var isFaceClassname = /* @__PURE__ */ __name((c) => faceClasses.includes(c), "isFaceClassname");
2362
- var isPlateClassname = /* @__PURE__ */ __name((c) => licensePlateClasses.includes(c), "isPlateClassname");
2363
- var isAnimalClassname = /* @__PURE__ */ __name((c) => animalClasses.includes(c), "isAnimalClassname");
2364
- var isPersonClassname = /* @__PURE__ */ __name((c) => personClasses.includes(c), "isPersonClassname");
2365
- var isVehicleClassname = /* @__PURE__ */ __name((c) => vehicleClasses.includes(c), "isVehicleClassname");
2366
- var isMotionClassname = /* @__PURE__ */ __name((c) => motionClasses.includes(c), "isMotionClassname");
2367
- var isDoorbellClassname = /* @__PURE__ */ __name((c) => doorbellClasses.includes(c), "isDoorbellClassname");
2368
- var isPackageClassname = /* @__PURE__ */ __name((c) => packageClasses.includes(c), "isPackageClassname");
2369
- var isAudioClassname = /* @__PURE__ */ __name((c) => audioClasses.includes(c) || audioLabelClasses.includes(c), "isAudioClassname");
2370
- var isSensorLabelClassname = /* @__PURE__ */ __name((c) => sensorLabelClasses.includes(c), "isSensorLabelClassname");
2371
- var isLabelDetection = /* @__PURE__ */ __name((c) => isFaceClassname(c) || isPlateClassname(c), "isLabelDetection");
2372
- var getParentClass = /* @__PURE__ */ __name((className) => detectionClassesDefaultMap[className], "getParentClass");
2373
- var getParentDetectionClass = /* @__PURE__ */ __name((det) => {
1606
+ const isFaceClassname = (c) => faceClasses.includes(c);
1607
+ const isPlateClassname = (c) => licensePlateClasses.includes(c);
1608
+ const isAnimalClassname = (c) => animalClasses.includes(c);
1609
+ const isPersonClassname = (c) => personClasses.includes(c);
1610
+ const isVehicleClassname = (c) => vehicleClasses.includes(c);
1611
+ const isMotionClassname = (c) => motionClasses.includes(c);
1612
+ const isDoorbellClassname = (c) => doorbellClasses.includes(c);
1613
+ const isPackageClassname = (c) => packageClasses.includes(c);
1614
+ const isAudioClassname = (c) => audioClasses.includes(c) || audioLabelClasses.includes(c);
1615
+ const isSensorLabelClassname = (c) => sensorLabelClasses.includes(c);
1616
+ const isLabelDetection = (c) => isFaceClassname(c) || isPlateClassname(c);
1617
+ const getParentClass = (className) => detectionClassesDefaultMap[className];
1618
+ const getParentDetectionClass = (det) => {
2374
1619
  const { className } = det;
2375
1620
  const baseMap = {
2376
- ["face"]: "person",
2377
- ["plate"]: "vehicle"
1621
+ [
1622
+ "face"
1623
+ /* Face */
1624
+ ]: "person",
1625
+ [
1626
+ "plate"
1627
+ /* Plate */
1628
+ ]: "vehicle"
1629
+ /* Vehicle */
2378
1630
  };
2379
1631
  const parentGroup = detectionClassesDefaultMap[className];
2380
1632
  if (parentGroup && parentGroup !== className) return parentGroup;
2381
1633
  return baseMap[className];
2382
- }, "getParentDetectionClass");
2383
- var defaultDetectionClasses = Object.values(DetectionClass);
2384
- var DEFAULT_ENABLED_CLASSES = defaultDetectionClasses.filter((c) => c !== "motion");
2385
- var TIMELINE_PRESET_CRITICAL = [
1634
+ };
1635
+ const defaultDetectionClasses = Object.values(DetectionClass);
1636
+ const DEFAULT_ENABLED_CLASSES = defaultDetectionClasses.filter(
1637
+ (c) => c !== "motion"
1638
+ /* Motion */
1639
+ );
1640
+ const TIMELINE_PRESET_CRITICAL = [
2386
1641
  "person",
2387
1642
  "doorbell",
2388
1643
  "package"
1644
+ /* Package */
2389
1645
  ];
2390
- var TIMELINE_PRESET_IMPORTANT = [
1646
+ const TIMELINE_PRESET_IMPORTANT = [
2391
1647
  ...TIMELINE_PRESET_CRITICAL,
2392
1648
  "vehicle",
2393
1649
  "animal",
2394
1650
  "audio",
2395
1651
  "face",
2396
1652
  "plate"
1653
+ /* Plate */
2397
1654
  ];
2398
- var TIMELINE_PRESET_ALL = [
2399
- ...DEFAULT_ENABLED_CLASSES
2400
- ];
1655
+ const TIMELINE_PRESET_ALL = [...DEFAULT_ENABLED_CLASSES];
2401
1656
  function getClassesForTimelinePreset(preset, customClasses) {
2402
1657
  switch (preset) {
2403
1658
  case "critical":
@@ -2412,10 +1667,7 @@ function getClassesForTimelinePreset(preset, customClasses) {
2412
1667
  return DEFAULT_ENABLED_CLASSES;
2413
1668
  }
2414
1669
  }
2415
- __name(getClassesForTimelinePreset, "getClassesForTimelinePreset");
2416
-
2417
- // src/devices.ts
2418
- var RAW_TO_CANONICAL = {
1670
+ const RAW_TO_CANONICAL = {
2419
1671
  // Scrypted PascalCase
2420
1672
  Light: "light",
2421
1673
  Switch: "switch",
@@ -2446,7 +1698,7 @@ var RAW_TO_CANONICAL = {
2446
1698
  media_player: "media_player",
2447
1699
  script: "script"
2448
1700
  };
2449
- var HA_DOMAIN_TYPE_MAP = {
1701
+ const HA_DOMAIN_TYPE_MAP = {
2450
1702
  light: "light",
2451
1703
  switch: "switch",
2452
1704
  input_boolean: "switch",
@@ -2474,7 +1726,7 @@ var HA_DOMAIN_TYPE_MAP = {
2474
1726
  weather: "weather",
2475
1727
  water_heater: "climate"
2476
1728
  };
2477
- var SCRYPTED_TYPE_TO_CANONICAL = {
1729
+ const SCRYPTED_TYPE_TO_CANONICAL = {
2478
1730
  Light: "light",
2479
1731
  Switch: "switch",
2480
1732
  WindowCovering: "cover",
@@ -2498,8 +1750,7 @@ function getCanonicalDeviceType(rawType) {
2498
1750
  const lower = rawType.toLowerCase();
2499
1751
  return RAW_TO_CANONICAL[lower] ?? null;
2500
1752
  }
2501
- __name(getCanonicalDeviceType, "getCanonicalDeviceType");
2502
- var ELIGIBLE_SCRYPTED_DEVICE_TYPES = [
1753
+ const ELIGIBLE_SCRYPTED_DEVICE_TYPES = [
2503
1754
  "Entry",
2504
1755
  "Light",
2505
1756
  "Switch",
@@ -2512,8 +1763,8 @@ var ELIGIBLE_SCRYPTED_DEVICE_TYPES = [
2512
1763
  "Select",
2513
1764
  "Program"
2514
1765
  ];
2515
- var ELIGIBLE_SCRYPTED_DEVICE_TYPES_SET = new Set(ELIGIBLE_SCRYPTED_DEVICE_TYPES);
2516
- var ELIGIBLE_HA_DOMAINS = [
1766
+ const ELIGIBLE_SCRYPTED_DEVICE_TYPES_SET = new Set(ELIGIBLE_SCRYPTED_DEVICE_TYPES);
1767
+ const ELIGIBLE_HA_DOMAINS = [
2517
1768
  "light",
2518
1769
  "switch",
2519
1770
  "input_boolean",
@@ -2528,179 +1779,109 @@ var ELIGIBLE_HA_DOMAINS = [
2528
1779
  "media_player",
2529
1780
  "script"
2530
1781
  ];
2531
- var ELIGIBLE_HA_DOMAINS_SET = new Set(ELIGIBLE_HA_DOMAINS);
2532
-
2533
- // src/features.ts
2534
- var FEATURE_MATRIX = [
1782
+ const ELIGIBLE_HA_DOMAINS_SET = new Set(ELIGIBLE_HA_DOMAINS);
1783
+ const FEATURE_MATRIX = [
2535
1784
  {
2536
1785
  id: "liveStream",
2537
1786
  label: "Live Stream",
2538
- sources: {
2539
- frigate: true,
2540
- scrypted: true,
2541
- rtsp: true
2542
- },
1787
+ sources: { frigate: true, scrypted: true, rtsp: true },
2543
1788
  adapterMethod: "getLiveStream"
2544
1789
  },
2545
1790
  {
2546
1791
  id: "multiResolution",
2547
1792
  label: "Multi-Resolution",
2548
- sources: {
2549
- frigate: true,
2550
- scrypted: true,
2551
- rtsp: false
2552
- },
1793
+ sources: { frigate: true, scrypted: true, rtsp: false },
2553
1794
  adapterMethod: "getResolutions"
2554
1795
  },
2555
1796
  {
2556
1797
  id: "motion",
2557
1798
  label: "Motion Detection",
2558
- sources: {
2559
- frigate: false,
2560
- scrypted: true,
2561
- rtsp: false
2562
- },
1799
+ sources: { frigate: false, scrypted: true, rtsp: false },
2563
1800
  adapterMethod: "getMotion"
2564
1801
  },
2565
1802
  {
2566
1803
  id: "objectDetection",
2567
1804
  label: "Object Detection",
2568
- sources: {
2569
- frigate: false,
2570
- scrypted: true,
2571
- rtsp: false
2572
- },
1805
+ sources: { frigate: false, scrypted: true, rtsp: false },
2573
1806
  adapterMethod: "getObjectDetections"
2574
1807
  },
2575
1808
  {
2576
1809
  id: "audioVolume",
2577
1810
  label: "Audio Level",
2578
- sources: {
2579
- frigate: false,
2580
- scrypted: true,
2581
- rtsp: false
2582
- },
1811
+ sources: { frigate: false, scrypted: true, rtsp: false },
2583
1812
  adapterMethod: "getAudioVolume"
2584
1813
  },
2585
1814
  {
2586
1815
  id: "audioVolumes",
2587
1816
  label: "Audio Volumes (dBFS)",
2588
- sources: {
2589
- frigate: false,
2590
- scrypted: true,
2591
- rtsp: false
2592
- },
1817
+ sources: { frigate: false, scrypted: true, rtsp: false },
2593
1818
  adapterMethod: "getAudioVolumes"
2594
1819
  },
2595
1820
  {
2596
1821
  id: "ptz",
2597
1822
  label: "PTZ Control",
2598
- sources: {
2599
- frigate: false,
2600
- scrypted: true,
2601
- rtsp: false
2602
- },
1823
+ sources: { frigate: false, scrypted: true, rtsp: false },
2603
1824
  adapterMethod: "getPTZ"
2604
1825
  },
2605
1826
  {
2606
1827
  id: "intercom",
2607
1828
  label: "Intercom (Mic)",
2608
- sources: {
2609
- frigate: false,
2610
- scrypted: true,
2611
- rtsp: false
2612
- },
1829
+ sources: { frigate: false, scrypted: true, rtsp: false },
2613
1830
  adapterMethod: "getIntercomSupport"
2614
1831
  },
2615
1832
  {
2616
1833
  id: "deviceStatus",
2617
1834
  label: "Device Status",
2618
- sources: {
2619
- frigate: false,
2620
- scrypted: true,
2621
- rtsp: false
2622
- },
1835
+ sources: { frigate: false, scrypted: true, rtsp: false },
2623
1836
  adapterMethod: "getStatus"
2624
1837
  },
2625
1838
  {
2626
1839
  id: "timeline",
2627
1840
  label: "Detection Timeline",
2628
- sources: {
2629
- frigate: true,
2630
- scrypted: true,
2631
- rtsp: false
2632
- },
1841
+ sources: { frigate: true, scrypted: true, rtsp: false },
2633
1842
  adapterMethod: "getCameraDayData"
2634
1843
  },
2635
1844
  {
2636
1845
  id: "clusteredTimeline",
2637
1846
  label: "Clustered Timeline",
2638
- sources: {
2639
- frigate: true,
2640
- scrypted: true,
2641
- rtsp: false
2642
- },
1847
+ sources: { frigate: true, scrypted: true, rtsp: false },
2643
1848
  requiresBackend: true,
2644
1849
  adapterMethod: "getClusteredDayData"
2645
1850
  },
2646
1851
  {
2647
1852
  id: "detectionClasses",
2648
1853
  label: "Detection Classes",
2649
- sources: {
2650
- frigate: true,
2651
- scrypted: true,
2652
- rtsp: false
2653
- },
1854
+ sources: { frigate: true, scrypted: true, rtsp: false },
2654
1855
  adapterMethod: "getDetectionClasses"
2655
1856
  },
2656
1857
  {
2657
1858
  id: "videoClips",
2658
1859
  label: "Video Clips",
2659
- sources: {
2660
- frigate: true,
2661
- scrypted: true,
2662
- rtsp: false
2663
- },
1860
+ sources: { frigate: true, scrypted: true, rtsp: false },
2664
1861
  adapterMethod: "getVideoClips"
2665
1862
  },
2666
1863
  {
2667
1864
  id: "nvrPlayback",
2668
1865
  label: "NVR Playback",
2669
- sources: {
2670
- frigate: true,
2671
- scrypted: true,
2672
- rtsp: false
2673
- },
1866
+ sources: { frigate: true, scrypted: true, rtsp: false },
2674
1867
  adapterMethod: "getNvrPlaybackSupported"
2675
1868
  },
2676
1869
  {
2677
1870
  id: "nvrScrub",
2678
1871
  label: "NVR Scrub/Seek",
2679
- sources: {
2680
- frigate: false,
2681
- scrypted: true,
2682
- rtsp: false
2683
- },
1872
+ sources: { frigate: false, scrypted: true, rtsp: false },
2684
1873
  adapterMethod: "seekRecordingStream"
2685
1874
  },
2686
1875
  {
2687
1876
  id: "recordingThumbnail",
2688
1877
  label: "Recording Thumbnails",
2689
- sources: {
2690
- frigate: true,
2691
- scrypted: true,
2692
- rtsp: false
2693
- },
1878
+ sources: { frigate: true, scrypted: true, rtsp: false },
2694
1879
  adapterMethod: "getRecordingStreamThumbnail"
2695
1880
  },
2696
1881
  {
2697
1882
  id: "nvrSeekToLive",
2698
1883
  label: "Seek to Live",
2699
- sources: {
2700
- frigate: false,
2701
- scrypted: true,
2702
- rtsp: false
2703
- },
1884
+ sources: { frigate: false, scrypted: true, rtsp: false },
2704
1885
  adapterMethod: "seekNvrToLive"
2705
1886
  }
2706
1887
  ];
@@ -2711,17 +1892,12 @@ function isFeatureAvailable(featureId, source, platform) {
2711
1892
  if (entry.platforms && entry.platforms[platform] === false) return false;
2712
1893
  return true;
2713
1894
  }
2714
- __name(isFeatureAvailable, "isFeatureAvailable");
2715
1895
  function getSourceFeatures(source) {
2716
1896
  return FEATURE_MATRIX.filter((f) => f.sources[source]);
2717
1897
  }
2718
- __name(getSourceFeatures, "getSourceFeatures");
2719
1898
  function getBackendRequiredFeatures() {
2720
1899
  return FEATURE_MATRIX.filter((f) => f.requiresBackend);
2721
1900
  }
2722
- __name(getBackendRequiredFeatures, "getBackendRequiredFeatures");
2723
-
2724
- // src/adaptive-stream.ts
2725
1901
  function selectOptimalStream(streams, constraints, defaultTransport) {
2726
1902
  if (streams.length === 0) return null;
2727
1903
  const viewportPixels = constraints.viewportWidth * constraints.viewportHeight * (constraints.pixelRatio ?? 1);
@@ -2762,38 +1938,26 @@ function selectOptimalStream(streams, constraints, defaultTransport) {
2762
1938
  if (bw < 5 && s.metadata.codec.includes("265")) score += 10;
2763
1939
  if (bw >= 10 && s.metadata.codec.includes("264")) score += 5;
2764
1940
  }
2765
- return {
2766
- ...s,
2767
- score,
2768
- targetTier
2769
- };
1941
+ return { ...s, score, targetTier };
2770
1942
  });
2771
1943
  scored.sort((a, b) => b.score - a.score);
2772
1944
  const best = scored[0];
2773
- const tierNames = {
2774
- high: "main",
2775
- medium: "sub",
2776
- low: "ext"
2777
- };
2778
1945
  return {
2779
1946
  streamName: best.streamName,
2780
1947
  profile: best.profile,
2781
1948
  transport: best.transport,
2782
1949
  label: best.label,
2783
1950
  metadata: best.metadata,
2784
- reason: `${best.targetTier} quality \u2192 ${best.profile}/${best.transport} (score: ${best.score})`
1951
+ reason: `${best.targetTier} quality ${best.profile}/${best.transport} (score: ${best.score})`
2785
1952
  };
2786
1953
  }
2787
- __name(selectOptimalStream, "selectOptimalStream");
2788
1954
  function getNextEvalInterval(constraints, wasSwitch) {
2789
1955
  if (wasSwitch) return 10;
2790
1956
  if (constraints.isCellular) return 15;
2791
1957
  if ((constraints.packetLoss ?? 0) > 0.02) return 15;
2792
1958
  return 30;
2793
1959
  }
2794
- __name(getNextEvalInterval, "getNextEvalInterval");
2795
1960
  export {
2796
- BackendClient,
2797
1961
  DEFAULT_ENABLED_CLASSES,
2798
1962
  DetectionClass,
2799
1963
  ELIGIBLE_HA_DOMAINS,
@@ -2804,13 +1968,14 @@ export {
2804
1968
  HA_DOMAIN_TYPE_MAP,
2805
1969
  RAW_TO_CANONICAL,
2806
1970
  SCRYPTED_TYPE_TO_CANONICAL,
1971
+ System,
2807
1972
  TIMELINE_PRESET_ALL,
2808
1973
  TIMELINE_PRESET_CRITICAL,
2809
1974
  TIMELINE_PRESET_IMPORTANT,
2810
1975
  animalClasses,
2811
1976
  audioClasses,
2812
1977
  audioLabelClasses,
2813
- createBackendClient,
1978
+ createSystem,
2814
1979
  defaultDetectionClasses,
2815
1980
  detectionClassesDefaultMap,
2816
1981
  doorbellClasses,
@@ -2838,13 +2003,9 @@ export {
2838
2003
  motionClasses,
2839
2004
  packageClasses,
2840
2005
  personClasses,
2006
+ raceFastestEndpoint,
2841
2007
  selectOptimalStream,
2842
2008
  sensorLabelClasses,
2843
2009
  vehicleClasses
2844
2010
  };
2845
- /*! Bundled license information:
2846
-
2847
- @trpc/client/dist/httpLink-oiU8eqFi.mjs:
2848
- (* istanbul ignore if -- @preserve *)
2849
- */
2850
- //# sourceMappingURL=index.js.map
2011
+ //# sourceMappingURL=index.js.map