kiteline 0.2.0 → 0.3.1

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.
Files changed (43) hide show
  1. package/README.md +2 -2
  2. package/dist/auth-CYNu-f_h.mjs +104 -0
  3. package/dist/{banner-CXnDgf5p.mjs → banner-C1Jj4n4W.mjs} +44 -42
  4. package/dist/cli.mjs +30 -10
  5. package/dist/client.BPI7fHX3-CSey2FaL.mjs +1437 -0
  6. package/dist/control-BEq2N-wP.mjs +101 -0
  7. package/dist/control-BpOGsRCZ.mjs +1 -0
  8. package/dist/devices-command-Bubh46v1.mjs +76 -0
  9. package/dist/{package-CbMOnF6R.mjs → package-CsnKrm9M.mjs} +1 -1
  10. package/dist/pair-command-DHeG-ZsP.mjs +120 -0
  11. package/dist/{service-BCgNAv2Z.mjs → service-CsyQPw0G.mjs} +16 -22
  12. package/dist/{src-DSH8d4ZM.mjs → src-C1LEhxeO.mjs} +1054 -1420
  13. package/dist/web/assets/MagnifyingGlass.es-DUOewsuL.js +1 -0
  14. package/dist/web/assets/Plus.es-wuLJIFEO.js +1 -0
  15. package/dist/web/assets/composer-3-vKn_3C.js +1 -0
  16. package/dist/web/assets/copy-button-CSWEBRJT.js +1 -0
  17. package/dist/web/assets/format-DYOlz7Mf.js +9 -0
  18. package/dist/web/assets/index-BRaZDA7B.css +1 -0
  19. package/dist/web/assets/index-DA4jO1yh.js +11 -0
  20. package/dist/web/assets/lazy/{core-CuC-kkU7.js → core-B6TDb-vl.js} +1 -1
  21. package/dist/web/assets/new-BGVIKCzl.js +1 -0
  22. package/dist/web/assets/{prefs-D6OSXuFe.js → prefs-DzSTtEbH.js} +1 -1
  23. package/dist/web/assets/routes-DpVY3ZGq.js +1 -0
  24. package/dist/web/assets/s._sessionId-zegjksnG.js +45 -0
  25. package/dist/web/assets/settings-Dvc2znbn.js +1 -0
  26. package/dist/web/assets/status-D-preq93.js +1 -0
  27. package/dist/web/index.html +3 -3
  28. package/dist/web/sw.js +1 -1
  29. package/package.json +1 -1
  30. package/dist/auth-YhkfTv6K.mjs +0 -60
  31. package/dist/show-pairing-CTd0UfS1.mjs +0 -30
  32. package/dist/show-pairing-Zurbk9wK.mjs +0 -1
  33. package/dist/web/assets/IconBase.es-h0cGkmPy.js +0 -9
  34. package/dist/web/assets/MagnifyingGlass.es-CpSmmHxy.js +0 -1
  35. package/dist/web/assets/composer-WnPpY669.js +0 -1
  36. package/dist/web/assets/copy-button-DBETbWKF.js +0 -1
  37. package/dist/web/assets/index-CA73h-Vn.css +0 -1
  38. package/dist/web/assets/index-CTAi3HIp.js +0 -11
  39. package/dist/web/assets/new-D_XEbYrm.js +0 -1
  40. package/dist/web/assets/routes-Csbxwlji.js +0 -1
  41. package/dist/web/assets/s._sessionId-BlR4dPFc.js +0 -45
  42. package/dist/web/assets/settings-DRpTnWMo.js +0 -1
  43. package/dist/web/assets/status-C7fEa4v1.js +0 -1
@@ -0,0 +1,1437 @@
1
+ // ../../node_modules/.pnpm/@orpc+shared@1.16.1_@opentelemetry+api@1.10.0/node_modules/@orpc/shared/dist/index.mjs
2
+ function resolveMaybeOptionalOptions(rest) {
3
+ return rest[0] ?? {};
4
+ }
5
+ function toArray(value) {
6
+ return Array.isArray(value) ? value : value === void 0 || value === null ? [] : [value];
7
+ }
8
+ const DEFAULT_MAX_BIGINT_DIGITS = 4300;
9
+ const BIGINT_PATTERN = /^-?(?:0|[1-9]\d*)$/;
10
+ function parseBigIntString(value, maxDigits) {
11
+ if ((value.startsWith("-") ? value.length - 1 : value.length) > maxDigits || !BIGINT_PATTERN.test(value)) return;
12
+ return BigInt(value);
13
+ }
14
+ const ORPC_NAME = "orpc";
15
+ const ORPC_SHARED_PACKAGE_NAME = "@orpc/shared";
16
+ const ORPC_SHARED_PACKAGE_VERSION = "1.16.1";
17
+ var AbortError = class extends Error {
18
+ constructor(...rest) {
19
+ super(...rest);
20
+ this.name = "AbortError";
21
+ }
22
+ };
23
+ function once(fn) {
24
+ let cached;
25
+ return () => {
26
+ if (cached) return cached.result;
27
+ const result = fn();
28
+ cached = { result };
29
+ return result;
30
+ };
31
+ }
32
+ function sequential(fn) {
33
+ let lastOperationPromise = Promise.resolve();
34
+ return (...args) => {
35
+ return lastOperationPromise = lastOperationPromise.catch(() => {}).then(() => {
36
+ return fn(...args);
37
+ });
38
+ };
39
+ }
40
+ const SPAN_ERROR_STATUS = 2;
41
+ const GLOBAL_OTEL_CONFIG_KEY = `__${ORPC_SHARED_PACKAGE_NAME}@${ORPC_SHARED_PACKAGE_VERSION}/otel/config__`;
42
+ function getGlobalOtelConfig() {
43
+ return globalThis[GLOBAL_OTEL_CONFIG_KEY];
44
+ }
45
+ function startSpan(name, options = {}, context) {
46
+ return (getGlobalOtelConfig()?.tracer)?.startSpan(name, options, context);
47
+ }
48
+ function setSpanError(span, error, options = {}) {
49
+ if (!span) return;
50
+ const exception = toOtelException(error);
51
+ span.recordException(exception);
52
+ if (!options.signal?.aborted || options.signal.reason !== error) span.setStatus({
53
+ code: SPAN_ERROR_STATUS,
54
+ message: exception.message
55
+ });
56
+ }
57
+ function toOtelException(error) {
58
+ if (error instanceof Error) {
59
+ const exception = {
60
+ message: error.message,
61
+ name: error.name,
62
+ stack: error.stack
63
+ };
64
+ if ("code" in error && (typeof error.code === "string" || typeof error.code === "number")) exception.code = error.code;
65
+ return exception;
66
+ }
67
+ return { message: String(error) };
68
+ }
69
+ async function runWithSpan({ name, context, ...options }, fn) {
70
+ const tracer = getGlobalOtelConfig()?.tracer;
71
+ if (!tracer) return fn();
72
+ const callback = async (span) => {
73
+ try {
74
+ return await fn(span);
75
+ } catch (e) {
76
+ setSpanError(span, e, options);
77
+ throw e;
78
+ } finally {
79
+ span.end();
80
+ }
81
+ };
82
+ if (context) return tracer.startActiveSpan(name, options, context, callback);
83
+ else return tracer.startActiveSpan(name, options, callback);
84
+ }
85
+ async function runInSpanContext(span, fn) {
86
+ const otelConfig = getGlobalOtelConfig();
87
+ if (!span || !otelConfig) return fn();
88
+ const ctx = otelConfig.trace.setSpan(otelConfig.context.active(), span);
89
+ return otelConfig.context.with(ctx, fn);
90
+ }
91
+ function isAsyncIteratorObject(maybe) {
92
+ if (!maybe || typeof maybe !== "object") return false;
93
+ return "next" in maybe && typeof maybe.next === "function" && Symbol.asyncIterator in maybe && typeof maybe[Symbol.asyncIterator] === "function";
94
+ }
95
+ const asyncDisposeSymbol = Symbol.asyncDispose ?? Symbol.for("asyncDispose");
96
+ var AsyncIteratorClass = class {
97
+ #isDone = false;
98
+ #isExecuteComplete = false;
99
+ #cleanup;
100
+ #next;
101
+ constructor(next, cleanup) {
102
+ this.#cleanup = cleanup;
103
+ this.#next = sequential(async () => {
104
+ if (this.#isDone) return {
105
+ done: true,
106
+ value: void 0
107
+ };
108
+ try {
109
+ const result = await next();
110
+ if (result.done) this.#isDone = true;
111
+ return result;
112
+ } catch (err) {
113
+ this.#isDone = true;
114
+ throw err;
115
+ } finally {
116
+ if (this.#isDone && !this.#isExecuteComplete) {
117
+ this.#isExecuteComplete = true;
118
+ await this.#cleanup("next");
119
+ }
120
+ }
121
+ });
122
+ }
123
+ next() {
124
+ return this.#next();
125
+ }
126
+ async return(value) {
127
+ this.#isDone = true;
128
+ if (!this.#isExecuteComplete) {
129
+ this.#isExecuteComplete = true;
130
+ await this.#cleanup("return");
131
+ }
132
+ return {
133
+ done: true,
134
+ value
135
+ };
136
+ }
137
+ async throw(err) {
138
+ this.#isDone = true;
139
+ if (!this.#isExecuteComplete) {
140
+ this.#isExecuteComplete = true;
141
+ await this.#cleanup("throw");
142
+ }
143
+ throw err;
144
+ }
145
+ /**
146
+ * asyncDispose symbol only available in esnext, we should fallback to Symbol.for('asyncDispose')
147
+ */
148
+ async [asyncDisposeSymbol]() {
149
+ this.#isDone = true;
150
+ if (!this.#isExecuteComplete) {
151
+ this.#isExecuteComplete = true;
152
+ await this.#cleanup("dispose");
153
+ }
154
+ }
155
+ [Symbol.asyncIterator]() {
156
+ return this;
157
+ }
158
+ };
159
+ function asyncIteratorWithSpan({ name, ...options }, iterator) {
160
+ let span;
161
+ return new AsyncIteratorClass(async () => {
162
+ span ??= startSpan(name);
163
+ try {
164
+ const result = await runInSpanContext(span, () => iterator.next());
165
+ span?.addEvent(result.done ? "completed" : "yielded");
166
+ return result;
167
+ } catch (err) {
168
+ setSpanError(span, err, options);
169
+ throw err;
170
+ }
171
+ }, async (reason) => {
172
+ try {
173
+ if (reason !== "next") await runInSpanContext(span, () => iterator.return?.());
174
+ } catch (err) {
175
+ setSpanError(span, err, options);
176
+ throw err;
177
+ } finally {
178
+ span?.end();
179
+ }
180
+ });
181
+ }
182
+ function onError(callback) {
183
+ return async (options, ...rest) => {
184
+ try {
185
+ return await options.next();
186
+ } catch (error) {
187
+ await callback(error, options, ...rest);
188
+ throw error;
189
+ }
190
+ };
191
+ }
192
+ function intercept(interceptors, options, main) {
193
+ const next = (options2, index) => {
194
+ const interceptor = interceptors[index];
195
+ if (!interceptor) return main(options2);
196
+ return interceptor({
197
+ ...options2,
198
+ next: (newOptions = options2) => next(newOptions, index + 1)
199
+ });
200
+ };
201
+ return next(options, 0);
202
+ }
203
+ function parseEmptyableJSON(text) {
204
+ if (!text) return;
205
+ return JSON.parse(text);
206
+ }
207
+ function stringifyJSON(value) {
208
+ return JSON.stringify(value);
209
+ }
210
+ function getConstructor(value) {
211
+ if (!isTypescriptObject(value)) return null;
212
+ return Object.getPrototypeOf(value)?.constructor;
213
+ }
214
+ function isObject(value) {
215
+ if (!value || typeof value !== "object") return false;
216
+ const proto = Object.getPrototypeOf(value);
217
+ return proto === Object.prototype || !proto || !proto.constructor;
218
+ }
219
+ function isTypescriptObject(value) {
220
+ return !!value && (typeof value === "object" || typeof value === "function");
221
+ }
222
+ function setOwn(object, key, value) {
223
+ if (key === "__proto__") Object.defineProperty(object, key, {
224
+ value,
225
+ writable: true,
226
+ enumerable: true,
227
+ configurable: true
228
+ });
229
+ else object[key] = value;
230
+ }
231
+ function copyOnWrite(parent, key, original) {
232
+ const value = parent[key];
233
+ if (value !== original) return value;
234
+ let copy;
235
+ if (Array.isArray(value)) copy = value.slice();
236
+ else if (isObject(value)) copy = { ...value };
237
+ else return value;
238
+ setOwn(parent, key, copy);
239
+ return copy;
240
+ }
241
+ const NullProtoObj = /* @__PURE__ */ (() => {
242
+ const e = function() {};
243
+ e.prototype = /* @__PURE__ */ Object.create(null);
244
+ Object.freeze(e.prototype);
245
+ return e;
246
+ })();
247
+ function value(value2, ...args) {
248
+ if (typeof value2 === "function") return value2(...args);
249
+ return value2;
250
+ }
251
+ function preventNativeAwait(target) {
252
+ return new Proxy(target, { get(target2, prop, receiver) {
253
+ const value2 = Reflect.get(target2, prop, receiver);
254
+ if (prop !== "then" || typeof value2 !== "function") return value2;
255
+ return new Proxy(value2, { apply(targetFn, thisArg, args) {
256
+ if (args.length !== 2 || args.some((arg) => !isNativeFunction(arg))) return Reflect.apply(targetFn, thisArg, args);
257
+ let shouldOmit = true;
258
+ args[0].call(thisArg, preventNativeAwait(new Proxy(target2, { get: (target3, prop2, receiver2) => {
259
+ if (shouldOmit && prop2 === "then") {
260
+ shouldOmit = false;
261
+ return;
262
+ }
263
+ return Reflect.get(target3, prop2, receiver2);
264
+ } })));
265
+ } });
266
+ } });
267
+ }
268
+ const NATIVE_FUNCTION_REGEX = /^\s*function\s*\(\)\s*\{\s*\[native code\]\s*\}\s*$/;
269
+ function isNativeFunction(fn) {
270
+ return typeof fn === "function" && NATIVE_FUNCTION_REGEX.test(fn.toString());
271
+ }
272
+ function overlayProxy(target, partial) {
273
+ return new Proxy(typeof target === "function" ? partial : target, {
274
+ get(_, prop) {
275
+ const targetValue = prop in partial ? partial : value(target);
276
+ const v = Reflect.get(targetValue, prop);
277
+ return typeof v === "function" ? v.bind(targetValue) : v;
278
+ },
279
+ has(_, prop) {
280
+ return Reflect.has(partial, prop) || Reflect.has(value(target), prop);
281
+ }
282
+ });
283
+ }
284
+ const REGEXP_FLAGS = /^[dgimsuvy]*$/;
285
+ function isValidRegExpFlags(flags) {
286
+ return REGEXP_FLAGS.test(flags) && new Set(flags).size === flags.length && !(flags.includes("u") && flags.includes("v"));
287
+ }
288
+ function createLazyRegExp(pattern, flags) {
289
+ let compiled;
290
+ let lastIndex = 0;
291
+ const compile = () => {
292
+ if (compiled === void 0) {
293
+ compiled = new RegExp(pattern, flags);
294
+ compiled.lastIndex = lastIndex;
295
+ }
296
+ return compiled;
297
+ };
298
+ return new Proxy(Object.create(RegExp.prototype), {
299
+ get(_, prop) {
300
+ if (prop === Symbol.toStringTag) return "RegExp";
301
+ if (compiled === void 0) {
302
+ if (prop === "lastIndex") return lastIndex;
303
+ if (!(prop in RegExp.prototype)) return;
304
+ }
305
+ const target = compile();
306
+ const value = Reflect.get(target, prop, target);
307
+ return typeof value === "function" && prop !== "constructor" ? value.bind(target) : value;
308
+ },
309
+ set(_, prop, value) {
310
+ if (compiled === void 0 && prop === "lastIndex") {
311
+ lastIndex = value;
312
+ return true;
313
+ }
314
+ const target = compile();
315
+ return Reflect.set(target, prop, value, target);
316
+ },
317
+ has(_, prop) {
318
+ if (compiled === void 0) return prop === "lastIndex" || prop in RegExp.prototype;
319
+ return Reflect.has(compiled, prop);
320
+ }
321
+ });
322
+ }
323
+ function tryDecodeURIComponent(value) {
324
+ try {
325
+ return decodeURIComponent(value);
326
+ } catch {
327
+ return value;
328
+ }
329
+ }
330
+ // ../../node_modules/.pnpm/@orpc+client@1.16.1_@opentelemetry+api@1.10.0/node_modules/@orpc/client/dist/shared/client.D_0j2fRr.mjs
331
+ const ORPC_CLIENT_PACKAGE_NAME = "@orpc/client";
332
+ const ORPC_CLIENT_PACKAGE_VERSION = "1.16.1";
333
+ const RECURSIVE_CLIENT_UNWRAP_KEYS = /* @__PURE__ */ new Set([
334
+ "bind",
335
+ "valueOf",
336
+ "toString",
337
+ "toJSON"
338
+ ]);
339
+ const COMMON_ORPC_ERROR_DEFS = {
340
+ BAD_REQUEST: {
341
+ status: 400,
342
+ message: "Bad Request"
343
+ },
344
+ UNAUTHORIZED: {
345
+ status: 401,
346
+ message: "Unauthorized"
347
+ },
348
+ FORBIDDEN: {
349
+ status: 403,
350
+ message: "Forbidden"
351
+ },
352
+ NOT_FOUND: {
353
+ status: 404,
354
+ message: "Not Found"
355
+ },
356
+ METHOD_NOT_SUPPORTED: {
357
+ status: 405,
358
+ message: "Method Not Supported"
359
+ },
360
+ NOT_ACCEPTABLE: {
361
+ status: 406,
362
+ message: "Not Acceptable"
363
+ },
364
+ TIMEOUT: {
365
+ status: 408,
366
+ message: "Request Timeout"
367
+ },
368
+ CONFLICT: {
369
+ status: 409,
370
+ message: "Conflict"
371
+ },
372
+ PRECONDITION_FAILED: {
373
+ status: 412,
374
+ message: "Precondition Failed"
375
+ },
376
+ PAYLOAD_TOO_LARGE: {
377
+ status: 413,
378
+ message: "Payload Too Large"
379
+ },
380
+ UNSUPPORTED_MEDIA_TYPE: {
381
+ status: 415,
382
+ message: "Unsupported Media Type"
383
+ },
384
+ UNPROCESSABLE_CONTENT: {
385
+ status: 422,
386
+ message: "Unprocessable Content"
387
+ },
388
+ TOO_MANY_REQUESTS: {
389
+ status: 429,
390
+ message: "Too Many Requests"
391
+ },
392
+ CLIENT_CLOSED_REQUEST: {
393
+ status: 499,
394
+ message: "Client Closed Request"
395
+ },
396
+ INTERNAL_SERVER_ERROR: {
397
+ status: 500,
398
+ message: "Internal Server Error"
399
+ },
400
+ NOT_IMPLEMENTED: {
401
+ status: 501,
402
+ message: "Not Implemented"
403
+ },
404
+ BAD_GATEWAY: {
405
+ status: 502,
406
+ message: "Bad Gateway"
407
+ },
408
+ SERVICE_UNAVAILABLE: {
409
+ status: 503,
410
+ message: "Service Unavailable"
411
+ },
412
+ GATEWAY_TIMEOUT: {
413
+ status: 504,
414
+ message: "Gateway Timeout"
415
+ }
416
+ };
417
+ function fallbackORPCErrorStatus(code, status) {
418
+ return status ?? COMMON_ORPC_ERROR_DEFS[code]?.status ?? 500;
419
+ }
420
+ function fallbackORPCErrorMessage(code, message) {
421
+ return message || COMMON_ORPC_ERROR_DEFS[code]?.message || code;
422
+ }
423
+ let globalORPCErrorConstructors;
424
+ var ORPCError = class ORPCError extends Error {
425
+ defined;
426
+ code;
427
+ status;
428
+ data;
429
+ static {
430
+ const GLOBAL_ORPC_ERROR_CONSTRUCTORS_SYMBOL = Symbol.for(`__${ORPC_CLIENT_PACKAGE_NAME}@${ORPC_CLIENT_PACKAGE_VERSION}/error/ORPC_ERROR_CONSTRUCTORS__`);
431
+ globalThis[GLOBAL_ORPC_ERROR_CONSTRUCTORS_SYMBOL] ??= /* @__PURE__ */ new WeakSet();
432
+ globalORPCErrorConstructors = globalThis[GLOBAL_ORPC_ERROR_CONSTRUCTORS_SYMBOL];
433
+ globalORPCErrorConstructors.add(ORPCError);
434
+ }
435
+ constructor(code, ...rest) {
436
+ const options = resolveMaybeOptionalOptions(rest);
437
+ if (options.status !== void 0 && !isORPCErrorStatus(options.status)) throw new Error("[ORPCError] Invalid error status code.");
438
+ const message = fallbackORPCErrorMessage(code, options.message);
439
+ super(message, options);
440
+ this.code = code;
441
+ this.status = fallbackORPCErrorStatus(code, options.status);
442
+ this.defined = options.defined ?? false;
443
+ this.data = options.data;
444
+ }
445
+ toJSON() {
446
+ return {
447
+ defined: this.defined,
448
+ code: this.code,
449
+ status: this.status,
450
+ message: this.message,
451
+ data: this.data
452
+ };
453
+ }
454
+ /**
455
+ * Workaround for Next.js where different contexts use separate
456
+ * dependency graphs, causing multiple ORPCError constructors existing and breaking
457
+ * `instanceof` checks across contexts.
458
+ *
459
+ * This is particularly problematic with "Optimized SSR", where orpc-client
460
+ * executes in one context but is invoked from another. When an error is thrown
461
+ * in the execution context, `instanceof ORPCError` checks fail in the
462
+ * invocation context due to separate class constructors.
463
+ *
464
+ * @todo Remove this and related code if Next.js resolves the multiple dependency graph issue.
465
+ */
466
+ static [Symbol.hasInstance](instance) {
467
+ if (globalORPCErrorConstructors.has(this)) {
468
+ const constructor = getConstructor(instance);
469
+ if (constructor && globalORPCErrorConstructors.has(constructor)) return true;
470
+ }
471
+ return super[Symbol.hasInstance](instance);
472
+ }
473
+ };
474
+ function toORPCError(error) {
475
+ return error instanceof ORPCError ? error : new ORPCError("INTERNAL_SERVER_ERROR", {
476
+ message: "Internal server error",
477
+ cause: error
478
+ });
479
+ }
480
+ function isORPCErrorStatus(status) {
481
+ return status < 200 || status >= 400;
482
+ }
483
+ function isORPCErrorJson(json) {
484
+ if (!isObject(json)) return false;
485
+ const validKeys = [
486
+ "defined",
487
+ "code",
488
+ "status",
489
+ "message",
490
+ "data"
491
+ ];
492
+ if (Object.keys(json).some((k) => !validKeys.includes(k))) return false;
493
+ return "defined" in json && typeof json.defined === "boolean" && "code" in json && typeof json.code === "string" && "status" in json && typeof json.status === "number" && isORPCErrorStatus(json.status) && "message" in json && typeof json.message === "string";
494
+ }
495
+ function createORPCErrorFromJson(json, options = {}) {
496
+ return new ORPCError(json.code, {
497
+ ...options,
498
+ ...json
499
+ });
500
+ }
501
+ // ../../node_modules/.pnpm/@orpc+standard-server@1.16.1_@opentelemetry+api@1.10.0/node_modules/@orpc/standard-server/dist/index.mjs
502
+ var EventEncoderError = class extends TypeError {};
503
+ var EventDecoderError = class extends TypeError {};
504
+ var ErrorEvent = class extends Error {
505
+ data;
506
+ constructor(options) {
507
+ super(options?.message ?? "An error event was received", options);
508
+ this.data = options?.data;
509
+ }
510
+ };
511
+ const LINE_ENDING_REGEX$1 = /\r\n|\r(?!\n)|\n/;
512
+ const MESSAGE_DELIMITER_REGEX = /(?:\r\n|\r(?!\n)|\n){2}/;
513
+ const MESSAGE_DELIMITER_GLOBAL_REGEX = /(?:\r\n|\r(?!\n)|\n){2}/g;
514
+ const CR = 13;
515
+ const LF = 10;
516
+ const SPACE = 32;
517
+ function decodeEventMessage(encoded) {
518
+ const message = {
519
+ data: void 0,
520
+ event: void 0,
521
+ id: void 0,
522
+ retry: void 0,
523
+ comments: []
524
+ };
525
+ for (const line of encoded.split(LINE_ENDING_REGEX$1)) {
526
+ if (line === "") continue;
527
+ const index = line.indexOf(":");
528
+ const value = index === -1 ? "" : line.slice(line.charCodeAt(index + 1) === SPACE ? index + 2 : index + 1);
529
+ if (index === 0) {
530
+ message.comments.push(value);
531
+ continue;
532
+ }
533
+ switch (index === -1 ? line : line.slice(0, index)) {
534
+ case "data":
535
+ message.data = message.data === void 0 ? value : `${message.data}
536
+ ${value}`;
537
+ break;
538
+ case "event":
539
+ message.event = value;
540
+ break;
541
+ case "id":
542
+ message.id = value;
543
+ break;
544
+ case "retry": {
545
+ const maybeInteger = Number.parseInt(value, 10);
546
+ if (maybeInteger >= 0 && maybeInteger.toString() === value) message.retry = maybeInteger;
547
+ break;
548
+ }
549
+ }
550
+ }
551
+ return message;
552
+ }
553
+ var EventDecoder = class {
554
+ constructor(options = {}) {
555
+ this.options = options;
556
+ }
557
+ pending = [];
558
+ tail = "";
559
+ discardLeadingLF = false;
560
+ feed(chunk) {
561
+ if (chunk === "") return;
562
+ if (this.discardLeadingLF) {
563
+ this.discardLeadingLF = false;
564
+ if (chunk.charCodeAt(0) === LF) {
565
+ chunk = chunk.slice(1);
566
+ if (chunk === "") return;
567
+ }
568
+ }
569
+ const scan = this.tail + chunk;
570
+ if (!MESSAGE_DELIMITER_REGEX.test(scan)) {
571
+ this.pending.push(chunk);
572
+ this.tail = scan.slice(-3);
573
+ return;
574
+ }
575
+ this.pending.push(chunk);
576
+ const buffered = this.pending.length === 1 ? chunk : this.pending.join("");
577
+ const offset = buffered.length - scan.length;
578
+ const parts = [];
579
+ let start = 0;
580
+ for (const match of scan.matchAll(MESSAGE_DELIMITER_GLOBAL_REGEX)) {
581
+ parts.push(buffered.slice(start, offset + match.index));
582
+ start = offset + match.index + match[0].length;
583
+ }
584
+ const incomplete = buffered.slice(start);
585
+ this.pending.length = 0;
586
+ this.tail = incomplete.slice(-3);
587
+ if (incomplete === "") this.discardLeadingLF = chunk.charCodeAt(chunk.length - 1) === CR;
588
+ else this.pending.push(incomplete);
589
+ for (const encoded of parts) {
590
+ const message = decodeEventMessage(encoded);
591
+ if (this.options.onEvent) this.options.onEvent(message);
592
+ }
593
+ }
594
+ end() {
595
+ if (this.pending.length !== 0) throw new EventDecoderError("Event Iterator ended before complete");
596
+ }
597
+ };
598
+ var EventDecoderStream = class extends TransformStream {
599
+ constructor() {
600
+ let decoder;
601
+ super({
602
+ start(controller) {
603
+ decoder = new EventDecoder({ onEvent: (event) => {
604
+ controller.enqueue(event);
605
+ } });
606
+ },
607
+ transform(chunk) {
608
+ decoder.feed(chunk);
609
+ },
610
+ flush() {
611
+ decoder.end();
612
+ }
613
+ });
614
+ }
615
+ };
616
+ const LINE_ENDING_REGEX = /\r\n|[\n\r]/;
617
+ const LINE_ENDING_GLOBAL_REGEX = /\r\n|[\n\r]/g;
618
+ function containsLineBreak(value) {
619
+ return LINE_ENDING_REGEX.test(value);
620
+ }
621
+ function assertEventId(id) {
622
+ if (containsLineBreak(id)) throw new EventEncoderError("Event's id must not contain a carriage return or newline character");
623
+ }
624
+ function assertEventName(event) {
625
+ if (containsLineBreak(event)) throw new EventEncoderError("Event's event must not contain a carriage return or newline character");
626
+ }
627
+ function assertEventRetry(retry) {
628
+ if (!Number.isInteger(retry) || retry < 0) throw new EventEncoderError("Event's retry must be a integer and >= 0");
629
+ }
630
+ function assertEventComment(comment) {
631
+ if (containsLineBreak(comment)) throw new EventEncoderError("Event's comment must not contain a carriage return or newline character");
632
+ }
633
+ function encodeEventData(data) {
634
+ if (data === void 0) return "";
635
+ return `data: ${data.replace(LINE_ENDING_GLOBAL_REGEX, "\ndata: ")}
636
+ `;
637
+ }
638
+ function encodeEventComments(comments) {
639
+ let output = "";
640
+ for (const comment of comments ?? []) {
641
+ assertEventComment(comment);
642
+ output += `: ${comment}
643
+ `;
644
+ }
645
+ return output;
646
+ }
647
+ function encodeEventMessage(message) {
648
+ let output = "";
649
+ output += encodeEventComments(message.comments);
650
+ if (message.event !== void 0) {
651
+ assertEventName(message.event);
652
+ output += `event: ${message.event}
653
+ `;
654
+ }
655
+ if (message.retry !== void 0) {
656
+ assertEventRetry(message.retry);
657
+ output += `retry: ${message.retry}
658
+ `;
659
+ }
660
+ if (message.id !== void 0) {
661
+ assertEventId(message.id);
662
+ output += `id: ${message.id}
663
+ `;
664
+ }
665
+ output += encodeEventData(message.data);
666
+ output += "\n";
667
+ return output;
668
+ }
669
+ const EVENT_SOURCE_META_SYMBOL = Symbol("ORPC_EVENT_SOURCE_META");
670
+ function withEventMeta(container, meta) {
671
+ if (meta.id === void 0 && meta.retry === void 0 && !meta.comments?.length) return container;
672
+ if (meta.id !== void 0) assertEventId(meta.id);
673
+ if (meta.retry !== void 0) assertEventRetry(meta.retry);
674
+ if (meta.comments !== void 0) for (const comment of meta.comments) assertEventComment(comment);
675
+ return new Proxy(container, { get(target, prop, receiver) {
676
+ if (prop === EVENT_SOURCE_META_SYMBOL) return meta;
677
+ return Reflect.get(target, prop, receiver);
678
+ } });
679
+ }
680
+ function getEventMeta(container) {
681
+ return isTypescriptObject(container) ? Reflect.get(container, EVENT_SOURCE_META_SYMBOL) : void 0;
682
+ }
683
+ var HibernationEventIterator = class extends AsyncIteratorClass {
684
+ /**
685
+ * this property is not transferred to the client, so it should be optional for type safety
686
+ */
687
+ hibernationCallback;
688
+ constructor(hibernationCallback) {
689
+ super(async () => {
690
+ throw new Error("Cannot iterate over hibernating iterator directly");
691
+ }, async (reason) => {
692
+ if (reason !== "next") throw new Error("Cannot cleanup hibernating iterator directly");
693
+ });
694
+ this.hibernationCallback = hibernationCallback;
695
+ }
696
+ };
697
+ function generateContentDisposition(filename, disposition = "inline") {
698
+ return `${disposition}; filename="${filename.replace(/[^\x20-\x7E]/g, "_").replace(/"/g, "\\\"")}"; filename*=utf-8''${encodeURIComponent(filename).replace(/['()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%(7C|60|5E)/g, (str, hex) => String.fromCharCode(Number.parseInt(hex, 16)))}`;
699
+ }
700
+ function getFilenameFromContentDisposition(contentDisposition) {
701
+ const encodedFilenameStarMatch = contentDisposition.match(/filename\*=(UTF-8'')?([^;]*)/i);
702
+ if (encodedFilenameStarMatch && typeof encodedFilenameStarMatch[2] === "string") return tryDecodeURIComponent(encodedFilenameStarMatch[2]);
703
+ const encodedFilenameMatch = contentDisposition.match(/filename="((?:\\"|[^"])*)"/i);
704
+ if (encodedFilenameMatch && typeof encodedFilenameMatch[1] === "string") return encodedFilenameMatch[1].replace(/\\"/g, "\"");
705
+ }
706
+ function mergeStandardHeaders(a, b) {
707
+ const merged = { ...a };
708
+ for (const key in b) if (Array.isArray(b[key])) merged[key] = [...toArray(merged[key]), ...b[key]];
709
+ else if (b[key] !== void 0) {
710
+ if (Array.isArray(merged[key])) merged[key] = [...merged[key], b[key]];
711
+ else if (merged[key] !== void 0) merged[key] = [merged[key], b[key]];
712
+ else merged[key] = b[key];
713
+ }
714
+ return merged;
715
+ }
716
+ function flattenHeader(header) {
717
+ if (typeof header === "string" || header === void 0) return header;
718
+ if (header.length === 0) return;
719
+ return header.join(", ");
720
+ }
721
+ // ../../node_modules/.pnpm/@orpc+client@1.16.1_@opentelemetry+api@1.10.0/node_modules/@orpc/client/dist/shared/client.BLtwTQUg.mjs
722
+ function mapEventIterator(iterator, maps) {
723
+ const mapError = async (error) => {
724
+ let mappedError = await maps.error(error);
725
+ if (mappedError !== error) {
726
+ const meta = getEventMeta(error);
727
+ if (meta && isTypescriptObject(mappedError)) mappedError = withEventMeta(mappedError, meta);
728
+ }
729
+ return mappedError;
730
+ };
731
+ return new AsyncIteratorClass(async () => {
732
+ const { done, value } = await (async () => {
733
+ try {
734
+ return await iterator.next();
735
+ } catch (error) {
736
+ throw await mapError(error);
737
+ }
738
+ })();
739
+ let mappedValue = await maps.value(value, done);
740
+ if (mappedValue !== value) {
741
+ const meta = getEventMeta(value);
742
+ if (meta && isTypescriptObject(mappedValue)) mappedValue = withEventMeta(mappedValue, meta);
743
+ }
744
+ return {
745
+ done,
746
+ value: mappedValue
747
+ };
748
+ }, async () => {
749
+ try {
750
+ await iterator.return?.();
751
+ } catch (error) {
752
+ throw await mapError(error);
753
+ }
754
+ });
755
+ }
756
+ // ../../node_modules/.pnpm/@orpc+standard-server-fetch@1.16.1_@opentelemetry+api@1.10.0/node_modules/@orpc/standard-server-fetch/dist/index.mjs
757
+ function toEventIterator(stream, options = {}) {
758
+ const reader = (stream?.pipeThrough(new TextDecoderStream()).pipeThrough(new EventDecoderStream()))?.getReader();
759
+ let span;
760
+ let isCancelled = false;
761
+ return new AsyncIteratorClass(async () => {
762
+ span ??= startSpan("consume_event_iterator_stream");
763
+ try {
764
+ while (true) {
765
+ if (reader === void 0) return {
766
+ done: true,
767
+ value: void 0
768
+ };
769
+ const { done, value } = await runInSpanContext(span, () => reader.read());
770
+ if (done) {
771
+ if (isCancelled) throw new AbortError("Stream was cancelled");
772
+ return {
773
+ done: true,
774
+ value: void 0
775
+ };
776
+ }
777
+ switch (value.event ?? (value.data !== void 0 ? "message" : void 0)) {
778
+ case "message": {
779
+ let message = parseEmptyableJSON(value.data);
780
+ if (isTypescriptObject(message)) message = withEventMeta(message, value);
781
+ span?.addEvent("message");
782
+ return {
783
+ done: false,
784
+ value: message
785
+ };
786
+ }
787
+ case "error": {
788
+ let error = new ErrorEvent({ data: parseEmptyableJSON(value.data) });
789
+ error = withEventMeta(error, value);
790
+ span?.addEvent("error");
791
+ throw error;
792
+ }
793
+ case "done":
794
+ case "close": {
795
+ let done2 = parseEmptyableJSON(value.data);
796
+ if (isTypescriptObject(done2)) done2 = withEventMeta(done2, value);
797
+ span?.addEvent("done");
798
+ return {
799
+ done: true,
800
+ value: done2
801
+ };
802
+ }
803
+ default: span?.addEvent("maybe_keepalive");
804
+ }
805
+ }
806
+ } catch (e) {
807
+ if (!(e instanceof ErrorEvent)) setSpanError(span, e, options);
808
+ throw e;
809
+ }
810
+ }, async (reason) => {
811
+ try {
812
+ if (reason !== "next") {
813
+ isCancelled = true;
814
+ span?.addEvent("cancelled");
815
+ }
816
+ await runInSpanContext(span, () => reader?.cancel());
817
+ } catch (e) {
818
+ setSpanError(span, e, options);
819
+ throw e;
820
+ } finally {
821
+ span?.end();
822
+ }
823
+ });
824
+ }
825
+ function toEventStream(iterator, options = {}) {
826
+ const keepAliveEnabled = options.eventIteratorKeepAliveEnabled ?? true;
827
+ const keepAliveInterval = options.eventIteratorKeepAliveInterval ?? 5e3;
828
+ const keepAliveComment = options.eventIteratorKeepAliveComment ?? "";
829
+ const initialCommentEnabled = options.eventIteratorInitialCommentEnabled ?? true;
830
+ const initialComment = options.eventIteratorInitialComment ?? "";
831
+ let cancelled = false;
832
+ let timeout;
833
+ let span;
834
+ return new ReadableStream({
835
+ start(controller) {
836
+ span = startSpan("stream_event_iterator");
837
+ if (initialCommentEnabled) controller.enqueue(encodeEventMessage({ comments: [initialComment] }));
838
+ },
839
+ async pull(controller) {
840
+ try {
841
+ if (keepAliveEnabled) timeout = setInterval(() => {
842
+ controller.enqueue(encodeEventMessage({ comments: [keepAliveComment] }));
843
+ span?.addEvent("keepalive");
844
+ }, keepAliveInterval);
845
+ const value = await runInSpanContext(span, () => iterator.next());
846
+ clearInterval(timeout);
847
+ if (cancelled) return;
848
+ const meta = getEventMeta(value.value);
849
+ if (!value.done || value.value !== void 0 || meta !== void 0) {
850
+ const event = value.done ? "done" : "message";
851
+ controller.enqueue(encodeEventMessage({
852
+ ...meta,
853
+ event,
854
+ data: stringifyJSON(value.value)
855
+ }));
856
+ span?.addEvent(event);
857
+ }
858
+ if (value.done) {
859
+ controller.close();
860
+ span?.end();
861
+ }
862
+ } catch (err) {
863
+ clearInterval(timeout);
864
+ if (cancelled) return;
865
+ if (err instanceof ErrorEvent) {
866
+ controller.enqueue(encodeEventMessage({
867
+ ...getEventMeta(err),
868
+ event: "error",
869
+ data: stringifyJSON(err.data)
870
+ }));
871
+ span?.addEvent("error");
872
+ controller.close();
873
+ } else {
874
+ setSpanError(span, err);
875
+ controller.error(err);
876
+ }
877
+ span?.end();
878
+ }
879
+ },
880
+ async cancel() {
881
+ try {
882
+ cancelled = true;
883
+ clearInterval(timeout);
884
+ span?.addEvent("cancelled");
885
+ await runInSpanContext(span, () => iterator.return?.());
886
+ } catch (e) {
887
+ setSpanError(span, e);
888
+ throw e;
889
+ } finally {
890
+ span?.end();
891
+ }
892
+ }
893
+ }).pipeThrough(new TextEncoderStream());
894
+ }
895
+ function toStandardBody(re, options = {}) {
896
+ return runWithSpan({
897
+ name: "parse_standard_body",
898
+ signal: options.signal
899
+ }, async () => {
900
+ const contentDisposition = re.headers.get("content-disposition");
901
+ if (typeof contentDisposition === "string") {
902
+ const fileName = getFilenameFromContentDisposition(contentDisposition) ?? "blob";
903
+ const blob2 = await re.blob();
904
+ return new File([blob2], fileName, { type: blob2.type });
905
+ }
906
+ const contentType = re.headers.get("content-type");
907
+ if (!contentType || contentType.startsWith("application/json")) return parseEmptyableJSON(await re.text());
908
+ if (contentType.startsWith("multipart/form-data")) return await re.formData();
909
+ if (contentType.startsWith("application/x-www-form-urlencoded")) {
910
+ const text = await re.text();
911
+ return new URLSearchParams(text);
912
+ }
913
+ if (contentType.startsWith("text/event-stream")) return toEventIterator(re.body, options);
914
+ if (contentType.startsWith("text/plain")) return await re.text();
915
+ const blob = await re.blob();
916
+ return new File([blob], "blob", { type: blob.type });
917
+ });
918
+ }
919
+ function toFetchBody(body, headers, options = {}) {
920
+ if (body instanceof ReadableStream) return body;
921
+ const currentContentDisposition = headers.get("content-disposition");
922
+ headers.delete("content-type");
923
+ headers.delete("content-disposition");
924
+ if (body === void 0) return;
925
+ if (body instanceof Blob) {
926
+ headers.set("content-type", body.type);
927
+ headers.set("content-length", body.size.toString());
928
+ headers.set("content-disposition", currentContentDisposition ?? generateContentDisposition(body instanceof File ? body.name : "blob"));
929
+ return body;
930
+ }
931
+ if (body instanceof FormData) return body;
932
+ if (body instanceof URLSearchParams) return body;
933
+ if (isAsyncIteratorObject(body)) {
934
+ headers.set("content-type", "text/event-stream");
935
+ return toEventStream(body, options);
936
+ }
937
+ headers.set("content-type", "application/json");
938
+ return stringifyJSON(body);
939
+ }
940
+ function toStandardHeaders$1(headers, standardHeaders = {}) {
941
+ headers.forEach((value, key) => {
942
+ if (Array.isArray(standardHeaders[key])) standardHeaders[key].push(value);
943
+ else if (standardHeaders[key] !== void 0) standardHeaders[key] = [standardHeaders[key], value];
944
+ else standardHeaders[key] = value;
945
+ });
946
+ return standardHeaders;
947
+ }
948
+ function toFetchHeaders(headers, fetchHeaders = new Headers()) {
949
+ for (const [key, value] of Object.entries(headers)) if (Array.isArray(value)) for (const v of value) fetchHeaders.append(key, v);
950
+ else if (value !== void 0) fetchHeaders.append(key, value);
951
+ return fetchHeaders;
952
+ }
953
+ function toStandardLazyRequest(request) {
954
+ return {
955
+ url: new URL(request.url),
956
+ signal: request.signal,
957
+ method: request.method,
958
+ body: once(() => toStandardBody(request, { signal: request.signal })),
959
+ get headers() {
960
+ const headers = toStandardHeaders$1(request.headers);
961
+ Object.defineProperty(this, "headers", {
962
+ value: headers,
963
+ writable: true
964
+ });
965
+ return headers;
966
+ },
967
+ set headers(value) {
968
+ Object.defineProperty(this, "headers", {
969
+ value,
970
+ writable: true
971
+ });
972
+ }
973
+ };
974
+ }
975
+ function toFetchRequest(request, options = {}) {
976
+ const headers = toFetchHeaders(request.headers);
977
+ const body = toFetchBody(request.body, headers, options);
978
+ return new Request(request.url, {
979
+ signal: request.signal,
980
+ method: request.method,
981
+ headers,
982
+ body
983
+ });
984
+ }
985
+ function toFetchResponse(response, options = {}) {
986
+ const headers = toFetchHeaders(response.headers);
987
+ const body = toFetchBody(response.body, headers, options);
988
+ return new Response(body, {
989
+ headers,
990
+ status: response.status
991
+ });
992
+ }
993
+ function toStandardLazyResponse(response, options = {}) {
994
+ return {
995
+ body: once(() => toStandardBody(response, options)),
996
+ status: response.status,
997
+ get headers() {
998
+ const headers = toStandardHeaders$1(response.headers);
999
+ Object.defineProperty(this, "headers", {
1000
+ value: headers,
1001
+ writable: true
1002
+ });
1003
+ return headers;
1004
+ },
1005
+ set headers(value) {
1006
+ Object.defineProperty(this, "headers", {
1007
+ value,
1008
+ writable: true
1009
+ });
1010
+ }
1011
+ };
1012
+ }
1013
+ // ../../node_modules/.pnpm/@orpc+client@1.16.1_@opentelemetry+api@1.10.0/node_modules/@orpc/client/dist/shared/client.BPI7fHX3.mjs
1014
+ var CompositeStandardLinkPlugin = class {
1015
+ plugins;
1016
+ constructor(plugins = []) {
1017
+ this.plugins = [...plugins].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
1018
+ }
1019
+ init(options) {
1020
+ for (const plugin of this.plugins) plugin.init?.(options);
1021
+ }
1022
+ };
1023
+ var StandardLink = class {
1024
+ constructor(codec, sender, options = {}) {
1025
+ this.codec = codec;
1026
+ this.sender = sender;
1027
+ new CompositeStandardLinkPlugin(options.plugins).init(options);
1028
+ this.interceptors = toArray(options.interceptors);
1029
+ this.clientInterceptors = toArray(options.clientInterceptors);
1030
+ }
1031
+ interceptors;
1032
+ clientInterceptors;
1033
+ call(path, input, options) {
1034
+ return runWithSpan({
1035
+ name: `${ORPC_NAME}.${path.join("/")}`,
1036
+ signal: options.signal
1037
+ }, (span) => {
1038
+ span?.setAttribute("rpc.system", ORPC_NAME);
1039
+ span?.setAttribute("rpc.method", path.join("."));
1040
+ if (isAsyncIteratorObject(input)) input = asyncIteratorWithSpan({
1041
+ name: "consume_event_iterator_input",
1042
+ signal: options.signal
1043
+ }, input);
1044
+ return intercept(this.interceptors, {
1045
+ ...options,
1046
+ path,
1047
+ input
1048
+ }, async ({ path: path2, input: input2, ...options2 }) => {
1049
+ const otelConfig = getGlobalOtelConfig();
1050
+ let otelContext;
1051
+ const currentSpan = otelConfig?.trace.getActiveSpan() ?? span;
1052
+ if (currentSpan && otelConfig) otelContext = otelConfig?.trace.setSpan(otelConfig.context.active(), currentSpan);
1053
+ const request = await runWithSpan({
1054
+ name: "encode_request",
1055
+ context: otelContext
1056
+ }, () => this.codec.encode(path2, input2, options2));
1057
+ const response = await intercept(this.clientInterceptors, {
1058
+ ...options2,
1059
+ input: input2,
1060
+ path: path2,
1061
+ request
1062
+ }, ({ input: input3, path: path3, request: request2, ...options3 }) => {
1063
+ return runWithSpan({
1064
+ name: "send_request",
1065
+ signal: options3.signal,
1066
+ context: otelContext
1067
+ }, () => this.sender.call(request2, options3, path3, input3));
1068
+ });
1069
+ const output = await runWithSpan({
1070
+ name: "decode_response",
1071
+ context: otelContext
1072
+ }, () => this.codec.decode(response, options2, path2, input2));
1073
+ if (isAsyncIteratorObject(output)) return asyncIteratorWithSpan({
1074
+ name: "consume_event_iterator_output",
1075
+ signal: options2.signal
1076
+ }, output);
1077
+ return output;
1078
+ });
1079
+ });
1080
+ }
1081
+ };
1082
+ const STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES = {
1083
+ BIGINT: 0,
1084
+ DATE: 1,
1085
+ NAN: 2,
1086
+ UNDEFINED: 3,
1087
+ URL: 4,
1088
+ REGEXP: 5,
1089
+ SET: 6,
1090
+ MAP: 7
1091
+ };
1092
+ const BUILT_IN_TYPES = new Set(Object.values(STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES));
1093
+ const SERIALIZED_REGEXP_FORMAT = /^\/(.*)\/([a-z]*)$/;
1094
+ function invalidSerializedData(detail) {
1095
+ return /* @__PURE__ */ new TypeError(`Invalid RPC serialized data: ${detail}`);
1096
+ }
1097
+ function invalidSerializedType(type, name, expected) {
1098
+ return invalidSerializedData(`type ${type} (${name}) expects ${expected}.`);
1099
+ }
1100
+ var StandardRPCJsonSerializer = class {
1101
+ customSerializers;
1102
+ constructor(options = {}) {
1103
+ this.customSerializers = options.customJsonSerializers ?? [];
1104
+ if (this.customSerializers.length !== new Set(this.customSerializers.map((custom) => custom.type)).size) throw new Error("Custom serializer type must be unique.");
1105
+ }
1106
+ serialize(data, segments = [], meta = [], maps = [], blobs = []) {
1107
+ for (const custom of this.customSerializers) if (custom.condition(data)) {
1108
+ const result = this.serialize(custom.serialize(data), segments, meta, maps, blobs);
1109
+ meta.push([custom.type, ...segments]);
1110
+ return result;
1111
+ }
1112
+ if (data instanceof Blob) {
1113
+ maps.push(segments);
1114
+ blobs.push(data);
1115
+ return [
1116
+ data,
1117
+ meta,
1118
+ maps,
1119
+ blobs
1120
+ ];
1121
+ }
1122
+ if (typeof data === "bigint") {
1123
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.BIGINT, ...segments]);
1124
+ return [
1125
+ data.toString(),
1126
+ meta,
1127
+ maps,
1128
+ blobs
1129
+ ];
1130
+ }
1131
+ if (data instanceof Date) {
1132
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.DATE, ...segments]);
1133
+ if (Number.isNaN(data.getTime())) return [
1134
+ null,
1135
+ meta,
1136
+ maps,
1137
+ blobs
1138
+ ];
1139
+ return [
1140
+ data.toISOString(),
1141
+ meta,
1142
+ maps,
1143
+ blobs
1144
+ ];
1145
+ }
1146
+ if (Number.isNaN(data)) {
1147
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.NAN, ...segments]);
1148
+ return [
1149
+ null,
1150
+ meta,
1151
+ maps,
1152
+ blobs
1153
+ ];
1154
+ }
1155
+ if (data instanceof URL) {
1156
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.URL, ...segments]);
1157
+ return [
1158
+ data.toString(),
1159
+ meta,
1160
+ maps,
1161
+ blobs
1162
+ ];
1163
+ }
1164
+ if (data instanceof RegExp) {
1165
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.REGEXP, ...segments]);
1166
+ return [
1167
+ data.toString(),
1168
+ meta,
1169
+ maps,
1170
+ blobs
1171
+ ];
1172
+ }
1173
+ if (data instanceof Set) {
1174
+ const result = this.serialize(Array.from(data), segments, meta, maps, blobs);
1175
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.SET, ...segments]);
1176
+ return result;
1177
+ }
1178
+ if (data instanceof Map) {
1179
+ const result = this.serialize(Array.from(data.entries()), segments, meta, maps, blobs);
1180
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.MAP, ...segments]);
1181
+ return result;
1182
+ }
1183
+ if (Array.isArray(data)) return [
1184
+ data.map((v, i) => {
1185
+ if (v === void 0) {
1186
+ meta.push([
1187
+ STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.UNDEFINED,
1188
+ ...segments,
1189
+ i
1190
+ ]);
1191
+ return null;
1192
+ }
1193
+ return this.serialize(v, [...segments, i], meta, maps, blobs)[0];
1194
+ }),
1195
+ meta,
1196
+ maps,
1197
+ blobs
1198
+ ];
1199
+ if (isObject(data)) {
1200
+ const json = {};
1201
+ for (const k in data) {
1202
+ if (k === "toJSON" && typeof data[k] === "function") continue;
1203
+ json[k] = this.serialize(data[k], [...segments, k], meta, maps, blobs)[0];
1204
+ }
1205
+ return [
1206
+ json,
1207
+ meta,
1208
+ maps,
1209
+ blobs
1210
+ ];
1211
+ }
1212
+ return [
1213
+ data,
1214
+ meta,
1215
+ maps,
1216
+ blobs
1217
+ ];
1218
+ }
1219
+ deserialize(json, meta, maps, getBlob) {
1220
+ const ref = { data: json };
1221
+ const input = { data: json };
1222
+ if (maps && getBlob) maps.forEach((segments, i) => {
1223
+ const blob = getBlob(i);
1224
+ if (!(blob instanceof Blob)) throw invalidSerializedData(`blob ${i} is not a Blob.`);
1225
+ let original = input;
1226
+ let currentRef = ref;
1227
+ let preSegment = "data";
1228
+ segments.forEach((segment) => {
1229
+ original = original[preSegment];
1230
+ currentRef = copyOnWrite(currentRef, preSegment, original);
1231
+ preSegment = segment;
1232
+ if (!Object.hasOwn(currentRef, preSegment)) throw invalidSerializedData(`segment "${preSegment}" does not exist.`);
1233
+ });
1234
+ currentRef[preSegment] = blob;
1235
+ });
1236
+ for (const item of meta) {
1237
+ const type = item[0];
1238
+ const custom = this.customSerializers.find((custom2) => custom2.type === type);
1239
+ if (custom === void 0 && !BUILT_IN_TYPES.has(type)) continue;
1240
+ let original = input;
1241
+ let currentRef = ref;
1242
+ let preSegment = "data";
1243
+ for (let i = 1; i < item.length; i++) {
1244
+ original = original[preSegment];
1245
+ currentRef = copyOnWrite(currentRef, preSegment, original);
1246
+ preSegment = item[i];
1247
+ if (!Object.hasOwn(currentRef, preSegment)) throw invalidSerializedData(`segment "${preSegment}" does not exist.`);
1248
+ }
1249
+ if (custom !== void 0) {
1250
+ currentRef[preSegment] = custom.deserialize(currentRef[preSegment]);
1251
+ continue;
1252
+ }
1253
+ const serialized = currentRef[preSegment];
1254
+ switch (type) {
1255
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.BIGINT: {
1256
+ if (typeof serialized !== "string") throw invalidSerializedType(type, "bigint", "a string");
1257
+ const value = parseBigIntString(serialized, DEFAULT_MAX_BIGINT_DIGITS);
1258
+ if (value === void 0) throw invalidSerializedType(type, "bigint", `a decimal integer string of at most ${DEFAULT_MAX_BIGINT_DIGITS} digits`);
1259
+ currentRef[preSegment] = value;
1260
+ break;
1261
+ }
1262
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.DATE:
1263
+ if (typeof serialized !== "string" && serialized !== null) throw invalidSerializedType(type, "date", "a string or null");
1264
+ currentRef[preSegment] = new Date(serialized ?? NaN);
1265
+ break;
1266
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.NAN:
1267
+ if (serialized !== null) throw invalidSerializedType(type, "nan", "null");
1268
+ currentRef[preSegment] = NaN;
1269
+ break;
1270
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.UNDEFINED:
1271
+ if (serialized !== null) throw invalidSerializedType(type, "undefined", "null");
1272
+ currentRef[preSegment] = void 0;
1273
+ break;
1274
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.URL:
1275
+ if (typeof serialized !== "string") throw invalidSerializedType(type, "url", "a string");
1276
+ currentRef[preSegment] = new URL(serialized);
1277
+ break;
1278
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.REGEXP: {
1279
+ if (typeof serialized !== "string") throw invalidSerializedType(type, "regexp", "a string");
1280
+ const match = serialized.match(SERIALIZED_REGEXP_FORMAT);
1281
+ if (match === null || !isValidRegExpFlags(match[2])) throw invalidSerializedData(`type ${type} (regexp) expects a "/pattern/flags" string.`);
1282
+ currentRef[preSegment] = createLazyRegExp(match[1], match[2]);
1283
+ break;
1284
+ }
1285
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.SET:
1286
+ if (!Array.isArray(serialized)) throw invalidSerializedType(type, "set", "an array");
1287
+ currentRef[preSegment] = new Set(serialized);
1288
+ break;
1289
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.MAP:
1290
+ if (!Array.isArray(serialized)) throw invalidSerializedType(type, "map", "an array");
1291
+ currentRef[preSegment] = new Map(serialized);
1292
+ }
1293
+ }
1294
+ return ref.data;
1295
+ }
1296
+ };
1297
+ function toHttpPath(path) {
1298
+ return `/${path.map(encodeURIComponent).join("/")}`;
1299
+ }
1300
+ function toStandardHeaders(headers) {
1301
+ if (typeof headers.forEach === "function") return toStandardHeaders$1(headers);
1302
+ return headers;
1303
+ }
1304
+ function getMalformedResponseErrorCode(status) {
1305
+ return Object.entries(COMMON_ORPC_ERROR_DEFS).find(([, def]) => def.status === status)?.[0] ?? "MALFORMED_ORPC_ERROR_RESPONSE";
1306
+ }
1307
+ var StandardRPCLinkCodec = class {
1308
+ constructor(serializer, options) {
1309
+ this.serializer = serializer;
1310
+ this.baseUrl = options.url;
1311
+ this.maxUrlLength = options.maxUrlLength ?? 2083;
1312
+ this.fallbackMethod = options.fallbackMethod ?? "POST";
1313
+ this.expectedMethod = options.method ?? this.fallbackMethod;
1314
+ this.headers = options.headers ?? {};
1315
+ }
1316
+ baseUrl;
1317
+ maxUrlLength;
1318
+ fallbackMethod;
1319
+ expectedMethod;
1320
+ headers;
1321
+ async encode(path, input, options) {
1322
+ let headers = toStandardHeaders(await value(this.headers, options, path, input));
1323
+ if (options.lastEventId !== void 0) headers = mergeStandardHeaders(headers, { "last-event-id": options.lastEventId });
1324
+ const expectedMethod = await value(this.expectedMethod, options, path, input);
1325
+ const baseUrl = await value(this.baseUrl, options, path, input);
1326
+ const url = new URL(baseUrl);
1327
+ url.pathname = `${url.pathname.replace(/\/$/, "")}${toHttpPath(path)}`;
1328
+ const serialized = this.serializer.serialize(input);
1329
+ if (expectedMethod === "GET" && !(serialized instanceof FormData) && !isAsyncIteratorObject(serialized)) {
1330
+ const maxUrlLength = await value(this.maxUrlLength, options, path, input);
1331
+ const getUrl = new URL(url);
1332
+ getUrl.searchParams.append("data", stringifyJSON(serialized));
1333
+ if (getUrl.toString().length <= maxUrlLength) return {
1334
+ body: void 0,
1335
+ method: expectedMethod,
1336
+ headers,
1337
+ url: getUrl,
1338
+ signal: options.signal
1339
+ };
1340
+ }
1341
+ return {
1342
+ url,
1343
+ method: expectedMethod === "GET" ? this.fallbackMethod : expectedMethod,
1344
+ headers,
1345
+ body: serialized,
1346
+ signal: options.signal
1347
+ };
1348
+ }
1349
+ async decode(response) {
1350
+ const isOk = !isORPCErrorStatus(response.status);
1351
+ const deserialized = await (async () => {
1352
+ let isBodyOk = false;
1353
+ try {
1354
+ const body = await response.body();
1355
+ isBodyOk = true;
1356
+ return this.serializer.deserialize(body);
1357
+ } catch (error) {
1358
+ if (!isBodyOk) throw new Error("Cannot parse response body, please check the response body and content-type.", { cause: error });
1359
+ throw new Error("Invalid RPC response format.", { cause: error });
1360
+ }
1361
+ })();
1362
+ if (!isOk) {
1363
+ if (isORPCErrorJson(deserialized)) throw createORPCErrorFromJson(deserialized);
1364
+ throw new ORPCError(getMalformedResponseErrorCode(response.status), {
1365
+ status: response.status,
1366
+ data: {
1367
+ ...response,
1368
+ body: deserialized
1369
+ }
1370
+ });
1371
+ }
1372
+ return deserialized;
1373
+ }
1374
+ };
1375
+ var StandardRPCSerializer = class {
1376
+ constructor(jsonSerializer) {
1377
+ this.jsonSerializer = jsonSerializer;
1378
+ }
1379
+ serialize(data) {
1380
+ if (isAsyncIteratorObject(data)) return mapEventIterator(data, {
1381
+ value: async (value) => this.#serialize(value, false),
1382
+ error: async (e) => {
1383
+ return new ErrorEvent({
1384
+ data: this.#serialize(toORPCError(e).toJSON(), false),
1385
+ cause: e
1386
+ });
1387
+ }
1388
+ });
1389
+ return this.#serialize(data, true);
1390
+ }
1391
+ #serialize(data, enableFormData) {
1392
+ const [json, meta_, maps, blobs] = this.jsonSerializer.serialize(data);
1393
+ const meta = meta_.length === 0 ? void 0 : meta_;
1394
+ if (!enableFormData || blobs.length === 0) return {
1395
+ json,
1396
+ meta
1397
+ };
1398
+ const form = new FormData();
1399
+ form.set("data", stringifyJSON({
1400
+ json,
1401
+ meta,
1402
+ maps
1403
+ }));
1404
+ blobs.forEach((blob, i) => {
1405
+ form.set(i.toString(), blob);
1406
+ });
1407
+ return form;
1408
+ }
1409
+ deserialize(data) {
1410
+ if (isAsyncIteratorObject(data)) return mapEventIterator(data, {
1411
+ value: async (value) => this.#deserialize(value),
1412
+ error: async (e) => {
1413
+ if (!(e instanceof ErrorEvent)) return e;
1414
+ const deserialized = this.#deserialize(e.data);
1415
+ if (isORPCErrorJson(deserialized)) return createORPCErrorFromJson(deserialized, { cause: e });
1416
+ return new ErrorEvent({
1417
+ data: deserialized,
1418
+ cause: e
1419
+ });
1420
+ }
1421
+ });
1422
+ return this.#deserialize(data);
1423
+ }
1424
+ #deserialize(data) {
1425
+ if (data === void 0) return;
1426
+ if (!(data instanceof FormData)) return this.jsonSerializer.deserialize(data.json, data.meta ?? []);
1427
+ const serialized = JSON.parse(data.get("data"));
1428
+ return this.jsonSerializer.deserialize(serialized.json, serialized.meta ?? [], serialized.maps, (i) => data.get(i.toString()));
1429
+ }
1430
+ };
1431
+ var StandardRPCLink = class extends StandardLink {
1432
+ constructor(linkClient, options) {
1433
+ const linkCodec = new StandardRPCLinkCodec(new StandardRPCSerializer(new StandardRPCJsonSerializer(options)), options);
1434
+ super(linkCodec, linkClient, options);
1435
+ }
1436
+ };
1437
+ export { runWithSpan as A, isObject as C, parseEmptyableJSON as D, overlayProxy as E, toArray as M, value as N, preventNativeAwait as O, isAsyncIteratorObject as S, onError as T, toORPCError as _, toHttpPath as a, asyncIteratorWithSpan as b, toStandardLazyRequest as c, HibernationEventIterator as d, flattenHeader as f, isORPCErrorStatus as g, fallbackORPCErrorStatus as h, StandardRPCSerializer as i, setSpanError as j, resolveMaybeOptionalOptions as k, toStandardLazyResponse as l, RECURSIVE_CLIENT_UNWRAP_KEYS as m, StandardRPCJsonSerializer as n, toFetchRequest as o, ORPCError as p, StandardRPCLink as r, toFetchResponse as s, CompositeStandardLinkPlugin as t, mapEventIterator as u, NullProtoObj as v, isTypescriptObject as w, intercept as x, ORPC_NAME as y };