@orpc/shared 1.14.10 → 1.14.11

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.mjs CHANGED
@@ -1,33 +1,114 @@
1
- export { group, guard, mapEntries, mapValues, omit, retry, sleep } from 'radash';
1
+ import { AbortError, AsyncIteratorClass, getOrBind, isTypescriptObject, isAsyncIteratorObject } from '@standardserver/shared';
2
+ export { AbortError, AsyncIteratorClass, SequentialIdGenerator, getOrBind, isAsyncIteratorObject, isTypescriptObject, parseEmptyableJSON, sequential, sleep, stringifyJSON, toArray } from '@standardserver/shared';
2
3
 
3
4
  function resolveMaybeOptionalOptions(rest) {
4
5
  return rest[0] ?? {};
5
6
  }
6
7
 
7
- function toArray(value) {
8
- return Array.isArray(value) ? value : value === void 0 || value === null ? [] : [value];
9
- }
10
8
  function splitInHalf(arr) {
11
9
  const half = Math.ceil(arr.length / 2);
12
10
  return [arr.slice(0, half), arr.slice(half)];
13
11
  }
14
12
 
15
- function readAsBuffer(source) {
13
+ async function loadBytes(source) {
16
14
  if (typeof source.bytes === "function") {
17
15
  return source.bytes();
18
16
  }
19
- return source.arrayBuffer();
17
+ return new Uint8Array(await source.arrayBuffer());
18
+ }
19
+ function toStringOrBytes(source) {
20
+ if (typeof source === "string") {
21
+ return source;
22
+ }
23
+ if (source instanceof ArrayBuffer) {
24
+ return new Uint8Array(source);
25
+ }
26
+ if (Array.isArray(source)) {
27
+ return concatBytes(source);
28
+ }
29
+ if (source instanceof Uint8Array) {
30
+ return source;
31
+ }
32
+ return new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
33
+ }
34
+ function toBytes(item) {
35
+ if (typeof item === "string") {
36
+ return new TextEncoder().encode(item);
37
+ }
38
+ if (item instanceof ArrayBuffer) {
39
+ return new Uint8Array(item);
40
+ }
41
+ if (item instanceof Uint8Array) {
42
+ return item;
43
+ }
44
+ return new Uint8Array(item.buffer, item.byteOffset, item.byteLength);
45
+ }
46
+ function concatBytes(items) {
47
+ const chunks = items.map(toBytes);
48
+ const totalLength = chunks.reduce((sum, chunk) => sum + chunk.byteLength, 0);
49
+ const result = new Uint8Array(totalLength);
50
+ let offset = 0;
51
+ for (const chunk of chunks) {
52
+ result.set(chunk, offset);
53
+ offset += chunk.byteLength;
54
+ }
55
+ return result;
56
+ }
57
+
58
+ function isDeepEqual(a, b) {
59
+ return isDeepEqualInternal(a, b, /* @__PURE__ */ new WeakMap());
60
+ }
61
+ function isDeepEqualInternal(a, b, visited) {
62
+ if (Object.is(a, b)) {
63
+ return true;
64
+ }
65
+ if (typeof a !== typeof b) {
66
+ return false;
67
+ }
68
+ if (a === null || typeof a !== "object") {
69
+ return false;
70
+ }
71
+ if (b === null || typeof b !== "object") {
72
+ return false;
73
+ }
74
+ const isArray = Array.isArray(a);
75
+ if (isArray !== Array.isArray(b)) {
76
+ return false;
77
+ }
78
+ if (isArray && a.length !== b.length) {
79
+ return false;
80
+ }
81
+ const aRecord = a;
82
+ const bRecord = b;
83
+ const visitedMatches = visited.get(a);
84
+ if (visitedMatches?.has(b)) {
85
+ return true;
86
+ }
87
+ if (visitedMatches) {
88
+ visitedMatches.add(b);
89
+ } else {
90
+ visited.set(a, new WeakSet([b]));
91
+ }
92
+ const aKeys = Object.keys(aRecord).filter((k) => aRecord[k] !== void 0);
93
+ const bKeys = Object.keys(bRecord).filter((k) => bRecord[k] !== void 0);
94
+ if (aKeys.length !== bKeys.length) {
95
+ return false;
96
+ }
97
+ for (const key of aKeys) {
98
+ if (!Object.hasOwn(bRecord, key)) {
99
+ return false;
100
+ }
101
+ if (!isDeepEqualInternal(aRecord[key], bRecord[key], visited)) {
102
+ return false;
103
+ }
104
+ }
105
+ return true;
20
106
  }
21
107
 
22
108
  const ORPC_NAME = "orpc";
23
- const ORPC_SHARED_PACKAGE_NAME = "@orpc/shared";
24
- const ORPC_SHARED_PACKAGE_VERSION = "1.14.10";
25
109
 
26
- class AbortError extends Error {
27
- constructor(...rest) {
28
- super(...rest);
29
- this.name = "AbortError";
30
- }
110
+ function isAbortError(error) {
111
+ return error instanceof Error && error.name.includes("Abort");
31
112
  }
32
113
 
33
114
  function once(fn) {
@@ -41,15 +122,6 @@ function once(fn) {
41
122
  return result;
42
123
  };
43
124
  }
44
- function sequential(fn) {
45
- let lastOperationPromise = Promise.resolve();
46
- return (...args) => {
47
- return lastOperationPromise = lastOperationPromise.catch(() => {
48
- }).then(() => {
49
- return fn(...args);
50
- });
51
- };
52
- }
53
125
  function defer(callback) {
54
126
  if (typeof setTimeout === "function") {
55
127
  setTimeout(callback, 0);
@@ -57,33 +129,102 @@ function defer(callback) {
57
129
  Promise.resolve().then(() => Promise.resolve().then(() => Promise.resolve().then(callback)));
58
130
  }
59
131
  }
132
+ function tryOrUndefined(fn) {
133
+ try {
134
+ return fn();
135
+ } catch {
136
+ return void 0;
137
+ }
138
+ }
139
+
140
+ function tryDecodeURIComponent(value) {
141
+ try {
142
+ return decodeURIComponent(value);
143
+ } catch {
144
+ return value;
145
+ }
146
+ }
147
+
148
+ function pathToHttpPath(path) {
149
+ return `/${path.map(encodeURIComponent).join("/")}`;
150
+ }
151
+ function normalizeHttpPath(path) {
152
+ const paths = path.split("/");
153
+ if (paths.at(0) === "") {
154
+ paths.shift();
155
+ }
156
+ return pathToHttpPath(paths.map(tryDecodeURIComponent));
157
+ }
158
+ function mergeHttpPath(a, b) {
159
+ return `${a.endsWith("/") ? a.slice(0, -1) : a}${b}`;
160
+ }
161
+ function matchesHttpPathPrefix(url, prefix) {
162
+ if (!url.startsWith(prefix)) {
163
+ return false;
164
+ }
165
+ const charAfterPrefix = url[prefix.length];
166
+ return charAfterPrefix === "/" || charAfterPrefix === "?" || charAfterPrefix === "#" || charAfterPrefix === void 0 || prefix[prefix.length - 1] === "/";
167
+ }
168
+ function matchesHttpPath(url, path) {
169
+ const pathWithoutEndSlash = path.endsWith("/") ? path.slice(0, path.length - 1) : path;
170
+ if (!url.startsWith(pathWithoutEndSlash)) {
171
+ return false;
172
+ }
173
+ let charAfterPrefix = url[pathWithoutEndSlash.length];
174
+ if (charAfterPrefix === "/") {
175
+ charAfterPrefix = url[pathWithoutEndSlash.length + 1];
176
+ }
177
+ return charAfterPrefix === void 0 || charAfterPrefix === "?" || charAfterPrefix === "#";
178
+ }
179
+ const COMPRESSIBLE_CONTENT_TYPE_REGEX = /^\s*(?:text\/(?!event-stream(?:[;\s]|$))[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i;
180
+ const MAX_COMPRESSIBLE_CONTENT_TYPE_LENGTH = 1024;
181
+ function isCompressibleContentType(contentType) {
182
+ if (contentType === null || contentType === void 0) {
183
+ return false;
184
+ }
185
+ if (contentType.length > MAX_COMPRESSIBLE_CONTENT_TYPE_LENGTH) {
186
+ return false;
187
+ }
188
+ return COMPRESSIBLE_CONTENT_TYPE_REGEX.test(contentType);
189
+ }
190
+
191
+ function compareSequentialIds(a, b) {
192
+ if (a.length !== b.length) {
193
+ return a.length - b.length;
194
+ }
195
+ return a < b ? -1 : a > b ? 1 : 0;
196
+ }
60
197
 
61
198
  const SPAN_ERROR_STATUS = 2;
62
- const GLOBAL_OTEL_CONFIG_KEY = `__${ORPC_SHARED_PACKAGE_NAME}@${ORPC_SHARED_PACKAGE_VERSION}/otel/config__`;
63
- function setGlobalOtelConfig(config) {
64
- globalThis[GLOBAL_OTEL_CONFIG_KEY] = config;
199
+ const OPENTELEMETRY_CONFIG_SYMBOL = Symbol.for("ORPC_OPENTELEMETRY_CONFIG");
200
+ function setOpenTelemetryConfig(config) {
201
+ globalThis[OPENTELEMETRY_CONFIG_SYMBOL] = config;
65
202
  }
66
- function getGlobalOtelConfig() {
67
- return globalThis[GLOBAL_OTEL_CONFIG_KEY];
203
+ function getOpenTelemetryConfig() {
204
+ return globalThis[OPENTELEMETRY_CONFIG_SYMBOL];
68
205
  }
69
- function startSpan(name, options = {}, context) {
70
- const tracer = getGlobalOtelConfig()?.tracer;
71
- return tracer?.startSpan(name, options, context);
206
+ function startSpan(options) {
207
+ const tracer = getOpenTelemetryConfig()?.tracer;
208
+ if (!tracer) {
209
+ return void 0;
210
+ }
211
+ const { name, context, ...spanOptions } = typeof options === "string" ? { name: options } : options;
212
+ return tracer.startSpan(name, spanOptions, context);
72
213
  }
73
- function setSpanError(span, error, options = {}) {
214
+ function recordSpanError(span, error) {
74
215
  if (!span) {
75
216
  return;
76
217
  }
77
218
  const exception = toOtelException(error);
78
219
  span.recordException(exception);
79
- if (!options.signal?.aborted || options.signal.reason !== error) {
220
+ if (!isAbortError(error)) {
80
221
  span.setStatus({
81
222
  code: SPAN_ERROR_STATUS,
82
223
  message: exception.message
83
224
  });
84
225
  }
85
226
  }
86
- function setSpanAttribute(span, key, value) {
227
+ function setSpanAttributeIfDefined(span, key, value) {
87
228
  if (!span || value === void 0) {
88
229
  return;
89
230
  }
@@ -121,29 +262,32 @@ function toSpanAttributeValue(data) {
121
262
  return String(data);
122
263
  }
123
264
  }
124
- async function runWithSpan({ name, context, ...options }, fn) {
125
- const tracer = getGlobalOtelConfig()?.tracer;
265
+ async function runWithSpan(options, fn) {
266
+ const tracer = getOpenTelemetryConfig()?.tracer;
126
267
  if (!tracer) {
127
268
  return fn();
128
269
  }
270
+ if (typeof options === "string") {
271
+ options = { name: options };
272
+ }
129
273
  const callback = async (span) => {
130
274
  try {
131
275
  return await fn(span);
132
276
  } catch (e) {
133
- setSpanError(span, e, options);
277
+ recordSpanError(span, e);
134
278
  throw e;
135
279
  } finally {
136
280
  span.end();
137
281
  }
138
282
  };
139
- if (context) {
140
- return tracer.startActiveSpan(name, options, context, callback);
283
+ if (options.context) {
284
+ return tracer.startActiveSpan(options.name, options, options.context, callback);
141
285
  } else {
142
- return tracer.startActiveSpan(name, options, callback);
286
+ return tracer.startActiveSpan(options.name, options, callback);
143
287
  }
144
288
  }
145
289
  async function runInSpanContext(span, fn) {
146
- const otelConfig = getGlobalOtelConfig();
290
+ const otelConfig = getOpenTelemetryConfig();
147
291
  if (!span || !otelConfig) {
148
292
  return fn();
149
293
  }
@@ -155,15 +299,9 @@ class AsyncIdQueue {
155
299
  openIds = /* @__PURE__ */ new Set();
156
300
  queues = /* @__PURE__ */ new Map();
157
301
  waiters = /* @__PURE__ */ new Map();
158
- get length() {
302
+ get size() {
159
303
  return this.openIds.size;
160
304
  }
161
- get waiterIds() {
162
- return Array.from(this.waiters.keys());
163
- }
164
- hasBufferedItems(id) {
165
- return Boolean(this.queues.get(id)?.length);
166
- }
167
305
  open(id) {
168
306
  this.openIds.add(id);
169
307
  }
@@ -231,74 +369,54 @@ class AsyncIdQueue {
231
369
  }
232
370
  }
233
371
 
234
- function isAsyncIteratorObject(maybe) {
235
- if (!maybe || typeof maybe !== "object") {
236
- return false;
237
- }
238
- return "next" in maybe && typeof maybe.next === "function" && Symbol.asyncIterator in maybe && typeof maybe[Symbol.asyncIterator] === "function";
239
- }
240
- const fallbackAsyncDisposeSymbol = Symbol.for("asyncDispose");
241
- const asyncDisposeSymbol = Symbol.asyncDispose ?? fallbackAsyncDisposeSymbol;
242
- class AsyncIteratorClass {
243
- #isDone = false;
244
- #isExecuteComplete = false;
245
- #cleanup;
246
- #next;
247
- constructor(next, cleanup) {
248
- this.#cleanup = cleanup;
249
- this.#next = sequential(async () => {
250
- if (this.#isDone) {
251
- return { done: true, value: void 0 };
252
- }
372
+ function wrapAsyncIterator(iterator, { runWith, mapResult, mapError, onError, onFinish }) {
373
+ runWith ??= (run) => run();
374
+ let isDone;
375
+ return new AsyncIteratorClass(async () => {
376
+ try {
377
+ let result;
253
378
  try {
254
- const result = await next();
255
- if (result.done) {
256
- this.#isDone = true;
257
- }
258
- return result;
259
- } catch (err) {
260
- this.#isDone = true;
261
- throw err;
262
- } finally {
263
- if (this.#isDone && !this.#isExecuteComplete) {
264
- this.#isExecuteComplete = true;
265
- await this.#cleanup("next");
266
- }
379
+ result = await runWith(() => iterator.next());
380
+ isDone = result.done;
381
+ } catch (error) {
382
+ isDone = true;
383
+ throw error;
267
384
  }
268
- });
269
- }
270
- next() {
271
- return this.#next();
272
- }
273
- async return(value) {
274
- this.#isDone = true;
275
- if (!this.#isExecuteComplete) {
276
- this.#isExecuteComplete = true;
277
- await this.#cleanup("return");
385
+ return mapResult ? await mapResult(result) : result;
386
+ } catch (error) {
387
+ await onError?.(error);
388
+ throw mapError ? await mapError(error) : error;
278
389
  }
279
- return { done: true, value };
280
- }
281
- async throw(err) {
282
- this.#isDone = true;
283
- if (!this.#isExecuteComplete) {
284
- this.#isExecuteComplete = true;
285
- await this.#cleanup("throw");
390
+ }, async (_state) => {
391
+ try {
392
+ if (!isDone) {
393
+ try {
394
+ await runWith(async () => iterator.return?.());
395
+ } catch (error) {
396
+ await onError?.(error);
397
+ throw error;
398
+ }
399
+ }
400
+ } finally {
401
+ await onFinish?.();
286
402
  }
287
- throw err;
288
- }
289
- /**
290
- * asyncDispose symbol only available in esnext, we should fallback to Symbol.for('asyncDispose')
291
- */
292
- async [asyncDisposeSymbol]() {
293
- this.#isDone = true;
294
- if (!this.#isExecuteComplete) {
295
- this.#isExecuteComplete = true;
296
- await this.#cleanup("dispose");
403
+ });
404
+ }
405
+ function traceAsyncIterator(options, iterator) {
406
+ const getSpan = once(() => startSpan(options));
407
+ return wrapAsyncIterator(iterator, {
408
+ runWith: (run) => runInSpanContext(getSpan(), run),
409
+ mapResult(result) {
410
+ getSpan()?.addEvent(result.done ? "completed" : "yielded");
411
+ return result;
412
+ },
413
+ onError(error) {
414
+ recordSpanError(getSpan(), error);
415
+ },
416
+ onFinish() {
417
+ getSpan()?.end();
297
418
  }
298
- }
299
- [Symbol.asyncIterator]() {
300
- return this;
301
- }
419
+ });
302
420
  }
303
421
  function replicateAsyncIterator(source, count) {
304
422
  const queue = new AsyncIdQueue();
@@ -338,9 +456,9 @@ function replicateAsyncIterator(source, count) {
338
456
  }
339
457
  throw item.error;
340
458
  },
341
- async (reason) => {
342
- queue.close({ id });
343
- if (reason !== "next" && !queue.length && !isSourceFinished) {
459
+ async ({ kind, error }) => {
460
+ queue.close({ id, reason: error });
461
+ if (kind === "cancelled" && !queue.size && !isSourceFinished) {
344
462
  isSourceFinished = true;
345
463
  await source?.return?.();
346
464
  }
@@ -349,194 +467,51 @@ function replicateAsyncIterator(source, count) {
349
467
  });
350
468
  return replicated;
351
469
  }
352
- function asyncIteratorWithSpan({ name, ...options }, iterator) {
353
- let span;
354
- return new AsyncIteratorClass(
355
- async () => {
356
- span ??= startSpan(name);
357
- try {
358
- const result = await runInSpanContext(span, () => iterator.next());
359
- span?.addEvent(result.done ? "completed" : "yielded");
360
- return result;
361
- } catch (err) {
362
- setSpanError(span, err, options);
363
- throw err;
364
- }
365
- },
366
- async (reason) => {
367
- try {
368
- if (reason !== "next") {
369
- await runInSpanContext(span, () => iterator.return?.());
370
- }
371
- } catch (err) {
372
- setSpanError(span, err, options);
373
- throw err;
374
- } finally {
375
- span?.end();
376
- }
377
- }
378
- );
379
- }
380
-
381
- class EventPublisher {
382
- #listenersMap = /* @__PURE__ */ new Map();
383
- #maxBufferedEvents;
384
- constructor(options = {}) {
385
- this.#maxBufferedEvents = options.maxBufferedEvents ?? 100;
386
- }
387
- get size() {
388
- return this.#listenersMap.size;
389
- }
390
- /**
391
- * Emits an event and delivers the payload to all subscribed listeners.
392
- */
393
- publish(event, payload) {
394
- const listeners = this.#listenersMap.get(event);
395
- if (!listeners) {
396
- return;
397
- }
398
- for (const listener of listeners) {
399
- listener(payload);
400
- }
401
- }
402
- subscribe(event, listenerOrOptions) {
403
- if (typeof listenerOrOptions === "function") {
404
- let listeners = this.#listenersMap.get(event);
405
- if (!listeners) {
406
- this.#listenersMap.set(event, listeners = []);
407
- }
408
- listeners.push(listenerOrOptions);
409
- return once(() => {
410
- listeners.splice(listeners.indexOf(listenerOrOptions), 1);
411
- if (listeners.length === 0) {
412
- this.#listenersMap.delete(event);
413
- }
414
- });
415
- }
416
- const signal = listenerOrOptions?.signal;
417
- const maxBufferedEvents = listenerOrOptions?.maxBufferedEvents ?? this.#maxBufferedEvents;
418
- signal?.throwIfAborted();
419
- const bufferedEvents = [];
420
- const pullResolvers = [];
421
- const unsubscribe = this.subscribe(event, (payload) => {
422
- const resolver = pullResolvers.shift();
423
- if (resolver) {
424
- resolver[0]({ done: false, value: payload });
425
- } else {
426
- bufferedEvents.push(payload);
427
- if (bufferedEvents.length > maxBufferedEvents) {
428
- bufferedEvents.shift();
470
+ function consumeAsyncIterator(iterator, options) {
471
+ void (async () => {
472
+ let onFinishState;
473
+ try {
474
+ const resolvedIterator = await iterator;
475
+ while (true) {
476
+ const { done, value } = await resolvedIterator.next();
477
+ if (done) {
478
+ const realValue = value;
479
+ onFinishState = [null, realValue, true];
480
+ options.onSuccess?.(realValue);
481
+ break;
429
482
  }
483
+ options.onEvent(value);
430
484
  }
431
- });
432
- const abortListener = (event2) => {
433
- unsubscribe();
434
- pullResolvers.forEach((resolver) => resolver[1](event2.target.reason));
435
- pullResolvers.length = 0;
436
- bufferedEvents.length = 0;
437
- };
438
- signal?.addEventListener("abort", abortListener, { once: true });
439
- return new AsyncIteratorClass(async () => {
440
- if (signal?.aborted) {
441
- throw signal.reason;
442
- }
443
- if (bufferedEvents.length > 0) {
444
- return { done: false, value: bufferedEvents.shift() };
445
- }
446
- return new Promise((resolve, reject) => {
447
- pullResolvers.push([resolve, reject]);
448
- });
449
- }, async () => {
450
- unsubscribe();
451
- signal?.removeEventListener("abort", abortListener);
452
- pullResolvers.forEach((resolver) => resolver[0]({ done: true, value: void 0 }));
453
- pullResolvers.length = 0;
454
- bufferedEvents.length = 0;
455
- });
456
- }
457
- }
458
-
459
- class SequentialIdGenerator {
460
- index = BigInt(1);
461
- generate() {
462
- const id = this.index.toString(36);
463
- this.index++;
464
- return id;
465
- }
466
- }
467
- function compareSequentialIds(a, b) {
468
- if (a.length !== b.length) {
469
- return a.length - b.length;
470
- }
471
- return a < b ? -1 : a > b ? 1 : 0;
472
- }
473
-
474
- function onStart(callback) {
475
- return async (options, ...rest) => {
476
- await callback(options, ...rest);
477
- return await options.next();
478
- };
479
- }
480
- function onSuccess(callback) {
481
- return async (options, ...rest) => {
482
- const result = await options.next();
483
- await callback(result, options, ...rest);
484
- return result;
485
- };
486
- }
487
- function onError(callback) {
488
- return async (options, ...rest) => {
489
- try {
490
- return await options.next();
491
485
  } catch (error) {
492
- await callback(error, options, ...rest);
493
- throw error;
494
- }
495
- };
496
- }
497
- function onFinish(callback) {
498
- let state;
499
- return async (options, ...rest) => {
500
- try {
501
- const result = await options.next();
502
- state = [null, result, true];
503
- return result;
504
- } catch (error) {
505
- state = [error, void 0, false];
506
- throw error;
486
+ onFinishState = [error, void 0, false];
487
+ options.onError?.(error);
507
488
  } finally {
508
- await callback(state, options, ...rest);
489
+ options.onFinish?.(onFinishState);
509
490
  }
491
+ })();
492
+ return async () => {
493
+ await (await iterator)?.return?.();
510
494
  };
511
495
  }
512
- function intercept(interceptors, options, main) {
513
- const next = (options2, index) => {
514
- const interceptor = interceptors[index];
515
- if (!interceptor) {
516
- return main(options2);
517
- }
518
- return interceptor({
519
- ...options2,
520
- next: (newOptions = options2) => next(newOptions, index + 1)
521
- });
522
- };
523
- return next(options, 0);
524
- }
525
496
 
526
- function parseEmptyableJSON(text) {
527
- if (!text) {
528
- return void 0;
497
+ function value(value2, ...args) {
498
+ if (typeof value2 === "function") {
499
+ return value2(...args);
529
500
  }
530
- return JSON.parse(text);
531
- }
532
- function stringifyJSON(value) {
533
- return JSON.stringify(value);
501
+ return value2;
534
502
  }
535
503
 
536
- function logError(error) {
537
- if (typeof console === "object" && typeof console.error === "function") {
538
- console.error(error);
539
- }
504
+ function override(target, partial) {
505
+ const proxy = new Proxy(typeof target === "function" ? partial : target, {
506
+ get(_, prop) {
507
+ const targetValue = prop in partial ? partial : value(target);
508
+ return getOrBind(targetValue, prop);
509
+ },
510
+ has(_, prop) {
511
+ return Reflect.has(partial, prop) || Reflect.has(value(target), prop);
512
+ }
513
+ });
514
+ return proxy;
540
515
  }
541
516
 
542
517
  function findDeepMatches(check, payload, segments = [], maps = [], values = []) {
@@ -547,7 +522,7 @@ function findDeepMatches(check, payload, segments = [], maps = [], values = [])
547
522
  payload.forEach((v, i) => {
548
523
  findDeepMatches(check, v, [...segments, i], maps, values);
549
524
  });
550
- } else if (isObject(payload)) {
525
+ } else if (isPlainObject(payload)) {
551
526
  for (const key in payload) {
552
527
  findDeepMatches(check, payload[key], [...segments, key], maps, values);
553
528
  }
@@ -560,21 +535,47 @@ function getConstructor(value) {
560
535
  }
561
536
  return Object.getPrototypeOf(value)?.constructor;
562
537
  }
563
- function isObject(value) {
538
+ function isPlainObject(value) {
564
539
  if (!value || typeof value !== "object") {
565
540
  return false;
566
541
  }
567
542
  const proto = Object.getPrototypeOf(value);
568
543
  return proto === Object.prototype || !proto || !proto.constructor;
569
544
  }
570
- function isTypescriptObject(value) {
571
- return !!value && (typeof value === "object" || typeof value === "function");
545
+ function get(object, path) {
546
+ let current = object;
547
+ for (const key of path) {
548
+ if (!isTypescriptObject(current) || !Object.hasOwn(current, key)) {
549
+ return void 0;
550
+ }
551
+ current = current[key];
552
+ }
553
+ return current;
554
+ }
555
+ function set(root, path, value) {
556
+ let current = root;
557
+ for (let i = 0; i < path.length - 1; i++) {
558
+ const key = path[i];
559
+ const next = current[key];
560
+ if (!isTypescriptObject(next)) {
561
+ current[key] = {};
562
+ }
563
+ current = current[key];
564
+ }
565
+ current[path.at(-1)] = value;
566
+ }
567
+ function omit(obj, keys) {
568
+ const result = { ...obj };
569
+ for (const key of keys) {
570
+ delete result[key];
571
+ }
572
+ return result;
572
573
  }
573
574
  function clone(value) {
574
575
  if (Array.isArray(value)) {
575
576
  return value.map(clone);
576
577
  }
577
- if (isObject(value)) {
578
+ if (isPlainObject(value)) {
578
579
  const result = {};
579
580
  for (const key in value) {
580
581
  result[key] = clone(value[key]);
@@ -586,16 +587,6 @@ function clone(value) {
586
587
  }
587
588
  return value;
588
589
  }
589
- function get(object, path) {
590
- let current = object;
591
- for (const key of path) {
592
- if (!isTypescriptObject(current)) {
593
- return void 0;
594
- }
595
- current = current[key];
596
- }
597
- return current;
598
- }
599
590
  function isPropertyKey(value) {
600
591
  const type = typeof value;
601
592
  return type === "string" || type === "number" || type === "symbol";
@@ -607,70 +598,143 @@ const NullProtoObj = /* @__PURE__ */ (() => {
607
598
  Object.freeze(e.prototype);
608
599
  return e;
609
600
  })();
610
-
611
- function value(value2, ...args) {
612
- if (typeof value2 === "function") {
613
- return value2(...args);
601
+ function bindMethods(obj) {
602
+ const methods = new NullProtoObj();
603
+ let current = obj;
604
+ while (current && current !== Object.prototype) {
605
+ for (const key of Object.getOwnPropertyNames(current)) {
606
+ if (key === "constructor" || key in methods) {
607
+ continue;
608
+ }
609
+ const val = obj[key];
610
+ if (typeof val === "function") {
611
+ methods[key] = val.bind(obj);
612
+ }
613
+ }
614
+ for (const sym of Object.getOwnPropertySymbols(current)) {
615
+ if (sym in methods) {
616
+ continue;
617
+ }
618
+ const val = obj[sym];
619
+ if (typeof val === "function") {
620
+ methods[sym] = val.bind(obj);
621
+ }
622
+ }
623
+ current = Object.getPrototypeOf(current);
614
624
  }
615
- return value2;
625
+ return methods;
616
626
  }
617
- function fallback(value2, fallback2) {
618
- return value2 === void 0 ? fallback2 : value2;
627
+
628
+ function promiseWithResolvers() {
629
+ const result = {};
630
+ result.promise = new Promise((resolve, reject) => {
631
+ result.resolve = resolve;
632
+ result.reject = reject;
633
+ });
634
+ return result;
619
635
  }
620
636
 
621
- function preventNativeAwait(target) {
622
- return new Proxy(target, {
623
- get(target2, prop, receiver) {
624
- const value2 = Reflect.get(target2, prop, receiver);
625
- if (prop !== "then" || typeof value2 !== "function") {
626
- return value2;
637
+ function replicateReadableStream(stream, count) {
638
+ if (count <= 0) {
639
+ return [];
640
+ }
641
+ const replicated = [];
642
+ let pending = stream;
643
+ for (let index = 0; index < count - 1; index++) {
644
+ const [replica, remainder] = pending.tee();
645
+ replicated.push(replica);
646
+ pending = remainder;
647
+ }
648
+ replicated.push(pending);
649
+ return replicated;
650
+ }
651
+ function wrapReadableStream(stream, { runWith, mapResult, mapError, onError, onFinish }) {
652
+ runWith ??= (run) => run();
653
+ const reader = once(() => stream.getReader());
654
+ const finish = once(async () => onFinish?.());
655
+ return new ReadableStream({
656
+ async pull(controller) {
657
+ let result;
658
+ try {
659
+ const readResult = await runWith(() => reader().read());
660
+ result = mapResult ? await mapResult(readResult) : readResult;
661
+ } catch (error) {
662
+ try {
663
+ await onError?.(error);
664
+ controller.error(mapError ? await mapError(error) : error);
665
+ } finally {
666
+ await finish();
667
+ }
668
+ return;
627
669
  }
628
- return new Proxy(value2, {
629
- apply(targetFn, thisArg, args) {
630
- if (args.length !== 2 || args.some((arg) => !isNativeFunction(arg))) {
631
- return Reflect.apply(targetFn, thisArg, args);
632
- }
633
- let shouldOmit = true;
634
- args[0].call(thisArg, preventNativeAwait(new Proxy(target2, {
635
- get: (target3, prop2, receiver2) => {
636
- if (shouldOmit && prop2 === "then") {
637
- shouldOmit = false;
638
- return void 0;
639
- }
640
- return Reflect.get(target3, prop2, receiver2);
641
- }
642
- })));
670
+ if (result.done) {
671
+ controller.close();
672
+ await finish();
673
+ } else {
674
+ controller.enqueue(result.value);
675
+ }
676
+ },
677
+ async cancel(reason) {
678
+ try {
679
+ try {
680
+ await runWith(() => reader().cancel(reason));
681
+ } catch (error) {
682
+ await onError?.(error);
683
+ throw error;
643
684
  }
644
- });
685
+ } finally {
686
+ await finish();
687
+ }
645
688
  }
646
689
  });
647
690
  }
648
- const NATIVE_FUNCTION_REGEX = /^\s*function\s*\(\)\s*\{\s*\[native code\]\s*\}\s*$/;
649
- function isNativeFunction(fn) {
650
- return typeof fn === "function" && NATIVE_FUNCTION_REGEX.test(fn.toString());
651
- }
652
- function overlayProxy(target, partial) {
653
- const proxy = new Proxy(typeof target === "function" ? partial : target, {
654
- get(_, prop) {
655
- const targetValue = prop in partial ? partial : value(target);
656
- const v = Reflect.get(targetValue, prop);
657
- return typeof v === "function" ? v.bind(targetValue) : v;
691
+ function traceReadableStream(options, stream) {
692
+ const getSpan = once(() => startSpan(options));
693
+ return wrapReadableStream(stream, {
694
+ runWith: (run) => runInSpanContext(getSpan(), run),
695
+ mapResult(result) {
696
+ getSpan()?.addEvent(result.done ? "closed" : "enqueued");
697
+ return result;
658
698
  },
659
- has(_, prop) {
660
- return Reflect.has(partial, prop) || Reflect.has(value(target), prop);
699
+ onError(error) {
700
+ recordSpanError(getSpan(), error);
701
+ },
702
+ onFinish() {
703
+ getSpan()?.end();
661
704
  }
662
705
  });
663
- return proxy;
664
706
  }
665
-
666
- function streamToAsyncIteratorClass(stream) {
707
+ function streamToAsyncIteratorObject(stream, { signal } = {}) {
667
708
  const reader = stream.getReader();
709
+ let cancelledBySignal = false;
668
710
  return new AsyncIteratorClass(
669
711
  async () => {
670
- return reader.read();
712
+ if (signal?.aborted) {
713
+ cancelledBySignal = true;
714
+ throw signal.reason;
715
+ }
716
+ if (!signal) {
717
+ return reader.read();
718
+ }
719
+ const { promise, reject } = promiseWithResolvers();
720
+ const onAbort = () => reject(signal.reason);
721
+ signal.addEventListener("abort", onAbort, { once: true });
722
+ try {
723
+ return await Promise.race([
724
+ reader.read(),
725
+ promise.catch(async (reason) => {
726
+ cancelledBySignal = true;
727
+ throw reason;
728
+ })
729
+ ]);
730
+ } finally {
731
+ signal.removeEventListener("abort", onAbort);
732
+ }
671
733
  },
672
- async () => {
673
- await reader.cancel();
734
+ async ({ kind, error }) => {
735
+ if (kind === "cancelled" || kind === "error" && cancelledBySignal) {
736
+ await reader.cancel(error);
737
+ }
674
738
  }
675
739
  );
676
740
  }
@@ -696,7 +760,7 @@ function asyncIteratorToUnproxiedDataStream(iterator) {
696
760
  if (done) {
697
761
  controller.close();
698
762
  } else {
699
- const unproxied = isObject(value) ? { ...value } : Array.isArray(value) ? value.map((i) => i) : value;
763
+ const unproxied = isPlainObject(value) ? { ...value } : Array.isArray(value) ? value.map((i) => i) : value;
700
764
  controller.enqueue(unproxied);
701
765
  }
702
766
  },
@@ -706,12 +770,228 @@ function asyncIteratorToUnproxiedDataStream(iterator) {
706
770
  });
707
771
  }
708
772
 
709
- function tryDecodeURIComponent(value) {
773
+ function onStart(callback) {
774
+ return async (options, ...rest) => {
775
+ await callback(options, ...rest);
776
+ return await options.next();
777
+ };
778
+ }
779
+ function onSuccess(callback) {
780
+ return async (options, ...rest) => {
781
+ const result = await options.next();
782
+ await callback(result, options, ...rest);
783
+ return result;
784
+ };
785
+ }
786
+ function onError(callback) {
787
+ return async (options, ...rest) => {
788
+ try {
789
+ return await options.next();
790
+ } catch (error) {
791
+ await callback(error, options, ...rest);
792
+ throw error;
793
+ }
794
+ };
795
+ }
796
+ function onFinish(callback) {
797
+ let state;
798
+ return async (options, ...rest) => {
799
+ try {
800
+ const result = await options.next();
801
+ state = [null, result, true];
802
+ return result;
803
+ } catch (error) {
804
+ state = [error, void 0, false];
805
+ throw error;
806
+ } finally {
807
+ await callback(state, options, ...rest);
808
+ }
809
+ };
810
+ }
811
+ function onAsyncIteratorObjectError(callback) {
812
+ return async (options, ...rest) => {
813
+ const output = await options.next();
814
+ if (!isAsyncIteratorObject(output)) {
815
+ return output;
816
+ }
817
+ return override(output, wrapAsyncIterator(output, {
818
+ onError: (error) => callback(error, options, ...rest)
819
+ }));
820
+ };
821
+ }
822
+ function onReadableStreamError(callback) {
823
+ return async (options, ...rest) => {
824
+ const output = await options.next();
825
+ if (!(output instanceof ReadableStream)) {
826
+ return output;
827
+ }
828
+ return override(output, wrapReadableStream(output, {
829
+ onError: (error) => callback(error, options, ...rest)
830
+ }));
831
+ };
832
+ }
833
+ function intercept(interceptors, options, main) {
834
+ if (!interceptors?.length) {
835
+ return main(options);
836
+ }
837
+ const next = (options2, index) => {
838
+ const interceptor = interceptors[index];
839
+ if (!interceptor) {
840
+ return main(options2);
841
+ }
842
+ return interceptor({
843
+ ...options2,
844
+ next: (newOptions = options2) => next(newOptions, index + 1)
845
+ });
846
+ };
847
+ return next(options, 0);
848
+ }
849
+
850
+ function sortPlugins(plugins) {
851
+ const pluginCount = plugins.length;
852
+ const pluginIdToIndices = /* @__PURE__ */ new Map();
853
+ for (let i = 0; i < pluginCount; i++) {
854
+ const plugin = plugins[i];
855
+ const indices = pluginIdToIndices.get(plugin.name);
856
+ if (indices === void 0) {
857
+ pluginIdToIndices.set(plugin.name, [i]);
858
+ } else {
859
+ indices.push(i);
860
+ }
861
+ }
862
+ const graph = Array.from(
863
+ { length: pluginCount },
864
+ () => /* @__PURE__ */ new Set()
865
+ );
866
+ for (let i = 0; i < pluginCount; i++) {
867
+ const plugin = plugins[i];
868
+ const beforeList = plugin.before;
869
+ if (beforeList !== void 0) {
870
+ for (const beforeId of beforeList) {
871
+ const beforeIndices = pluginIdToIndices.get(beforeId);
872
+ if (beforeIndices === void 0)
873
+ continue;
874
+ for (const beforeIndex of beforeIndices) {
875
+ const beforeGraph = graph[beforeIndex];
876
+ if (beforeGraph !== void 0) {
877
+ beforeGraph.add(i);
878
+ }
879
+ }
880
+ }
881
+ }
882
+ const afterList = plugin.after;
883
+ if (afterList !== void 0) {
884
+ const currentGraph = graph[i];
885
+ if (currentGraph !== void 0) {
886
+ for (const afterId of afterList) {
887
+ const afterIndices = pluginIdToIndices.get(afterId);
888
+ if (afterIndices === void 0)
889
+ continue;
890
+ for (const afterIndex of afterIndices) {
891
+ currentGraph.add(afterIndex);
892
+ }
893
+ }
894
+ }
895
+ }
896
+ }
897
+ const sorted = [];
898
+ const visiting = /* @__PURE__ */ new Set();
899
+ const visited = /* @__PURE__ */ new Set();
900
+ function visit(index) {
901
+ if (visited.has(index))
902
+ return;
903
+ if (visiting.has(index)) {
904
+ const plugin2 = plugins[index];
905
+ const pluginId = plugin2 !== void 0 ? plugin2.name : "unknown";
906
+ throw new Error(`Circular dependency detected involving plugin "${pluginId}"`);
907
+ }
908
+ visiting.add(index);
909
+ const deps = graph[index];
910
+ if (deps !== void 0) {
911
+ for (const depIndex of deps) {
912
+ visit(depIndex);
913
+ }
914
+ }
915
+ visiting.delete(index);
916
+ visited.add(index);
917
+ const plugin = plugins[index];
918
+ if (plugin !== void 0) {
919
+ sorted.push(plugin);
920
+ }
921
+ }
922
+ for (let i = 0; i < pluginCount; i++) {
923
+ visit(i);
924
+ }
925
+ return sorted;
926
+ }
927
+
928
+ function allAbortSignal(signals) {
929
+ const realSignals = signals.filter((signal) => signal !== void 0);
930
+ if (realSignals.length === 0 || realSignals.length !== signals.length) {
931
+ return void 0;
932
+ }
933
+ const controller = new AbortController();
934
+ const abortIfAllAborted = () => {
935
+ if (realSignals.every((signal) => signal.aborted)) {
936
+ controller.abort();
937
+ }
938
+ };
939
+ abortIfAllAborted();
940
+ for (const signal of realSignals) {
941
+ signal.addEventListener("abort", () => {
942
+ abortIfAllAborted();
943
+ }, {
944
+ once: true,
945
+ signal: controller.signal
946
+ });
947
+ }
948
+ return controller.signal;
949
+ }
950
+ function anyAbortSignal(signals) {
951
+ const realSignals = signals.filter((signal) => signal !== void 0);
952
+ if (realSignals.length === 0) {
953
+ return void 0;
954
+ }
955
+ if (realSignals.length === 1) {
956
+ return realSignals[0];
957
+ }
958
+ if (typeof AbortSignal.any === "function") {
959
+ return AbortSignal.any(realSignals);
960
+ }
961
+ const controller = new AbortController();
962
+ for (const signal of realSignals) {
963
+ if (signal.aborted) {
964
+ controller.abort(signal.reason);
965
+ break;
966
+ }
967
+ signal.addEventListener("abort", () => {
968
+ controller.abort(signal.reason);
969
+ }, {
970
+ once: true,
971
+ signal: controller.signal
972
+ });
973
+ }
974
+ return controller.signal;
975
+ }
976
+ async function runWithSignal(signal, fn) {
977
+ if (!signal) {
978
+ return fn();
979
+ }
980
+ signal.throwIfAborted();
981
+ const { promise, reject, resolve } = promiseWithResolvers();
982
+ let abortListener;
983
+ signal.addEventListener("abort", abortListener = () => {
984
+ reject(signal.reason);
985
+ abortListener = void 0;
986
+ });
710
987
  try {
711
- return decodeURIComponent(value);
712
- } catch {
713
- return value;
988
+ fn().then(resolve, reject);
989
+ return await promise;
990
+ } finally {
991
+ if (abortListener) {
992
+ signal.removeEventListener("abort", abortListener);
993
+ }
714
994
  }
715
995
  }
716
996
 
717
- export { AbortError, AsyncIdQueue, AsyncIteratorClass, EventPublisher, NullProtoObj, ORPC_NAME, ORPC_SHARED_PACKAGE_NAME, ORPC_SHARED_PACKAGE_VERSION, SequentialIdGenerator, asyncIteratorToStream, asyncIteratorToUnproxiedDataStream, asyncIteratorWithSpan, clone, compareSequentialIds, defer, fallback, findDeepMatches, get, getConstructor, getGlobalOtelConfig, intercept, isAsyncIteratorObject, isObject, isPropertyKey, isTypescriptObject, logError, onError, onFinish, onStart, onSuccess, once, overlayProxy, parseEmptyableJSON, preventNativeAwait, readAsBuffer, replicateAsyncIterator, resolveMaybeOptionalOptions, runInSpanContext, runWithSpan, sequential, setGlobalOtelConfig, setSpanAttribute, setSpanError, splitInHalf, startSpan, streamToAsyncIteratorClass, stringifyJSON, toArray, toOtelException, toSpanAttributeValue, tryDecodeURIComponent, value };
997
+ export { AsyncIdQueue, NullProtoObj, ORPC_NAME, allAbortSignal, anyAbortSignal, asyncIteratorToStream, asyncIteratorToUnproxiedDataStream, bindMethods, clone, compareSequentialIds, consumeAsyncIterator, defer, findDeepMatches, get, getConstructor, getOpenTelemetryConfig, intercept, isAbortError, isCompressibleContentType, isDeepEqual, isPlainObject, isPropertyKey, loadBytes, matchesHttpPath, matchesHttpPathPrefix, mergeHttpPath, normalizeHttpPath, omit, onAsyncIteratorObjectError, onError, onFinish, onReadableStreamError, onStart, onSuccess, once, override, pathToHttpPath, promiseWithResolvers, recordSpanError, replicateAsyncIterator, replicateReadableStream, resolveMaybeOptionalOptions, runInSpanContext, runWithSignal, runWithSpan, set, setOpenTelemetryConfig, setSpanAttributeIfDefined, sortPlugins, splitInHalf, startSpan, streamToAsyncIteratorObject, toOtelException, toSpanAttributeValue, toStringOrBytes, traceAsyncIterator, traceReadableStream, tryDecodeURIComponent, tryOrUndefined, value, wrapAsyncIterator, wrapReadableStream };