@orpc/shared 1.14.11 → 1.14.12

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,114 +1,33 @@
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';
1
+ export { group, guard, mapEntries, mapValues, omit, retry, sleep } from 'radash';
3
2
 
4
3
  function resolveMaybeOptionalOptions(rest) {
5
4
  return rest[0] ?? {};
6
5
  }
7
6
 
7
+ function toArray(value) {
8
+ return Array.isArray(value) ? value : value === void 0 || value === null ? [] : [value];
9
+ }
8
10
  function splitInHalf(arr) {
9
11
  const half = Math.ceil(arr.length / 2);
10
12
  return [arr.slice(0, half), arr.slice(half)];
11
13
  }
12
14
 
13
- async function loadBytes(source) {
15
+ function readAsBuffer(source) {
14
16
  if (typeof source.bytes === "function") {
15
17
  return source.bytes();
16
18
  }
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;
19
+ return source.arrayBuffer();
106
20
  }
107
21
 
108
22
  const ORPC_NAME = "orpc";
23
+ const ORPC_SHARED_PACKAGE_NAME = "@orpc/shared";
24
+ const ORPC_SHARED_PACKAGE_VERSION = "1.14.12";
109
25
 
110
- function isAbortError(error) {
111
- return error instanceof Error && error.name.includes("Abort");
26
+ class AbortError extends Error {
27
+ constructor(...rest) {
28
+ super(...rest);
29
+ this.name = "AbortError";
30
+ }
112
31
  }
113
32
 
114
33
  function once(fn) {
@@ -122,6 +41,15 @@ function once(fn) {
122
41
  return result;
123
42
  };
124
43
  }
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
+ }
125
53
  function defer(callback) {
126
54
  if (typeof setTimeout === "function") {
127
55
  setTimeout(callback, 0);
@@ -129,102 +57,33 @@ function defer(callback) {
129
57
  Promise.resolve().then(() => Promise.resolve().then(() => Promise.resolve().then(callback)));
130
58
  }
131
59
  }
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
- }
197
60
 
198
61
  const SPAN_ERROR_STATUS = 2;
199
- const OPENTELEMETRY_CONFIG_SYMBOL = Symbol.for("ORPC_OPENTELEMETRY_CONFIG");
200
- function setOpenTelemetryConfig(config) {
201
- globalThis[OPENTELEMETRY_CONFIG_SYMBOL] = config;
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;
202
65
  }
203
- function getOpenTelemetryConfig() {
204
- return globalThis[OPENTELEMETRY_CONFIG_SYMBOL];
66
+ function getGlobalOtelConfig() {
67
+ return globalThis[GLOBAL_OTEL_CONFIG_KEY];
205
68
  }
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);
69
+ function startSpan(name, options = {}, context) {
70
+ const tracer = getGlobalOtelConfig()?.tracer;
71
+ return tracer?.startSpan(name, options, context);
213
72
  }
214
- function recordSpanError(span, error) {
73
+ function setSpanError(span, error, options = {}) {
215
74
  if (!span) {
216
75
  return;
217
76
  }
218
77
  const exception = toOtelException(error);
219
78
  span.recordException(exception);
220
- if (!isAbortError(error)) {
79
+ if (!options.signal?.aborted || options.signal.reason !== error) {
221
80
  span.setStatus({
222
81
  code: SPAN_ERROR_STATUS,
223
82
  message: exception.message
224
83
  });
225
84
  }
226
85
  }
227
- function setSpanAttributeIfDefined(span, key, value) {
86
+ function setSpanAttribute(span, key, value) {
228
87
  if (!span || value === void 0) {
229
88
  return;
230
89
  }
@@ -262,32 +121,29 @@ function toSpanAttributeValue(data) {
262
121
  return String(data);
263
122
  }
264
123
  }
265
- async function runWithSpan(options, fn) {
266
- const tracer = getOpenTelemetryConfig()?.tracer;
124
+ async function runWithSpan({ name, context, ...options }, fn) {
125
+ const tracer = getGlobalOtelConfig()?.tracer;
267
126
  if (!tracer) {
268
127
  return fn();
269
128
  }
270
- if (typeof options === "string") {
271
- options = { name: options };
272
- }
273
129
  const callback = async (span) => {
274
130
  try {
275
131
  return await fn(span);
276
132
  } catch (e) {
277
- recordSpanError(span, e);
133
+ setSpanError(span, e, options);
278
134
  throw e;
279
135
  } finally {
280
136
  span.end();
281
137
  }
282
138
  };
283
- if (options.context) {
284
- return tracer.startActiveSpan(options.name, options, options.context, callback);
139
+ if (context) {
140
+ return tracer.startActiveSpan(name, options, context, callback);
285
141
  } else {
286
- return tracer.startActiveSpan(options.name, options, callback);
142
+ return tracer.startActiveSpan(name, options, callback);
287
143
  }
288
144
  }
289
145
  async function runInSpanContext(span, fn) {
290
- const otelConfig = getOpenTelemetryConfig();
146
+ const otelConfig = getGlobalOtelConfig();
291
147
  if (!span || !otelConfig) {
292
148
  return fn();
293
149
  }
@@ -299,9 +155,15 @@ class AsyncIdQueue {
299
155
  openIds = /* @__PURE__ */ new Set();
300
156
  queues = /* @__PURE__ */ new Map();
301
157
  waiters = /* @__PURE__ */ new Map();
302
- get size() {
158
+ get length() {
303
159
  return this.openIds.size;
304
160
  }
161
+ get waiterIds() {
162
+ return Array.from(this.waiters.keys());
163
+ }
164
+ hasBufferedItems(id) {
165
+ return Boolean(this.queues.get(id)?.length);
166
+ }
305
167
  open(id) {
306
168
  this.openIds.add(id);
307
169
  }
@@ -369,54 +231,74 @@ class AsyncIdQueue {
369
231
  }
370
232
  }
371
233
 
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;
378
- try {
379
- result = await runWith(() => iterator.next());
380
- isDone = result.done;
381
- } catch (error) {
382
- isDone = true;
383
- throw error;
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 };
384
252
  }
385
- return mapResult ? await mapResult(result) : result;
386
- } catch (error) {
387
- await onError?.(error);
388
- throw mapError ? await mapError(error) : error;
389
- }
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;
253
+ 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");
398
266
  }
399
267
  }
400
- } finally {
401
- await onFinish?.();
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");
402
278
  }
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();
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");
418
286
  }
419
- });
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");
297
+ }
298
+ }
299
+ [Symbol.asyncIterator]() {
300
+ return this;
301
+ }
420
302
  }
421
303
  function replicateAsyncIterator(source, count) {
422
304
  const queue = new AsyncIdQueue();
@@ -456,9 +338,9 @@ function replicateAsyncIterator(source, count) {
456
338
  }
457
339
  throw item.error;
458
340
  },
459
- async ({ kind, error }) => {
460
- queue.close({ id, reason: error });
461
- if (kind === "cancelled" && !queue.size && !isSourceFinished) {
341
+ async (reason) => {
342
+ queue.close({ id });
343
+ if (reason !== "next" && !queue.length && !isSourceFinished) {
462
344
  isSourceFinished = true;
463
345
  await source?.return?.();
464
346
  }
@@ -467,51 +349,194 @@ function replicateAsyncIterator(source, count) {
467
349
  });
468
350
  return replicated;
469
351
  }
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;
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?.());
482
370
  }
483
- options.onEvent(value);
371
+ } catch (err) {
372
+ setSpanError(span, err, options);
373
+ throw err;
374
+ } finally {
375
+ span?.end();
484
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();
429
+ }
430
+ }
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();
485
491
  } catch (error) {
486
- onFinishState = [error, void 0, false];
487
- options.onError?.(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;
488
507
  } finally {
489
- options.onFinish?.(onFinishState);
508
+ await callback(state, options, ...rest);
490
509
  }
491
- })();
492
- return async () => {
493
- await (await iterator)?.return?.();
494
510
  };
495
511
  }
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
+ }
496
525
 
497
- function value(value2, ...args) {
498
- if (typeof value2 === "function") {
499
- return value2(...args);
526
+ function parseEmptyableJSON(text) {
527
+ if (!text) {
528
+ return void 0;
500
529
  }
501
- return value2;
530
+ return JSON.parse(text);
531
+ }
532
+ function stringifyJSON(value) {
533
+ return JSON.stringify(value);
502
534
  }
503
535
 
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;
536
+ function logError(error) {
537
+ if (typeof console === "object" && typeof console.error === "function") {
538
+ console.error(error);
539
+ }
515
540
  }
516
541
 
517
542
  function findDeepMatches(check, payload, segments = [], maps = [], values = []) {
@@ -522,7 +547,7 @@ function findDeepMatches(check, payload, segments = [], maps = [], values = [])
522
547
  payload.forEach((v, i) => {
523
548
  findDeepMatches(check, v, [...segments, i], maps, values);
524
549
  });
525
- } else if (isPlainObject(payload)) {
550
+ } else if (isObject(payload)) {
526
551
  for (const key in payload) {
527
552
  findDeepMatches(check, payload[key], [...segments, key], maps, values);
528
553
  }
@@ -535,47 +560,21 @@ function getConstructor(value) {
535
560
  }
536
561
  return Object.getPrototypeOf(value)?.constructor;
537
562
  }
538
- function isPlainObject(value) {
563
+ function isObject(value) {
539
564
  if (!value || typeof value !== "object") {
540
565
  return false;
541
566
  }
542
567
  const proto = Object.getPrototypeOf(value);
543
568
  return proto === Object.prototype || !proto || !proto.constructor;
544
569
  }
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;
570
+ function isTypescriptObject(value) {
571
+ return !!value && (typeof value === "object" || typeof value === "function");
573
572
  }
574
573
  function clone(value) {
575
574
  if (Array.isArray(value)) {
576
575
  return value.map(clone);
577
576
  }
578
- if (isPlainObject(value)) {
577
+ if (isObject(value)) {
579
578
  const result = {};
580
579
  for (const key in value) {
581
580
  result[key] = clone(value[key]);
@@ -587,6 +586,16 @@ function clone(value) {
587
586
  }
588
587
  return value;
589
588
  }
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
+ }
590
599
  function isPropertyKey(value) {
591
600
  const type = typeof value;
592
601
  return type === "string" || type === "number" || type === "symbol";
@@ -598,143 +607,70 @@ const NullProtoObj = /* @__PURE__ */ (() => {
598
607
  Object.freeze(e.prototype);
599
608
  return e;
600
609
  })();
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);
610
+
611
+ function value(value2, ...args) {
612
+ if (typeof value2 === "function") {
613
+ return value2(...args);
624
614
  }
625
- return methods;
615
+ return value2;
626
616
  }
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;
617
+ function fallback(value2, fallback2) {
618
+ return value2 === void 0 ? fallback2 : value2;
635
619
  }
636
620
 
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;
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;
669
627
  }
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;
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
+ })));
684
643
  }
685
- } finally {
686
- await finish();
687
- }
644
+ });
688
645
  }
689
646
  });
690
647
  }
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;
698
- },
699
- onError(error) {
700
- recordSpanError(getSpan(), error);
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;
701
658
  },
702
- onFinish() {
703
- getSpan()?.end();
659
+ has(_, prop) {
660
+ return Reflect.has(partial, prop) || Reflect.has(value(target), prop);
704
661
  }
705
662
  });
663
+ return proxy;
706
664
  }
707
- function streamToAsyncIteratorObject(stream, { signal } = {}) {
665
+
666
+ function streamToAsyncIteratorClass(stream) {
708
667
  const reader = stream.getReader();
709
- let cancelledBySignal = false;
710
668
  return new AsyncIteratorClass(
711
669
  async () => {
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
- }
670
+ return reader.read();
733
671
  },
734
- async ({ kind, error }) => {
735
- if (kind === "cancelled" || kind === "error" && cancelledBySignal) {
736
- await reader.cancel(error);
737
- }
672
+ async () => {
673
+ await reader.cancel();
738
674
  }
739
675
  );
740
676
  }
@@ -760,7 +696,7 @@ function asyncIteratorToUnproxiedDataStream(iterator) {
760
696
  if (done) {
761
697
  controller.close();
762
698
  } else {
763
- const unproxied = isPlainObject(value) ? { ...value } : Array.isArray(value) ? value.map((i) => i) : value;
699
+ const unproxied = isObject(value) ? { ...value } : Array.isArray(value) ? value.map((i) => i) : value;
764
700
  controller.enqueue(unproxied);
765
701
  }
766
702
  },
@@ -770,228 +706,12 @@ function asyncIteratorToUnproxiedDataStream(iterator) {
770
706
  });
771
707
  }
772
708
 
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
- });
709
+ function tryDecodeURIComponent(value) {
987
710
  try {
988
- fn().then(resolve, reject);
989
- return await promise;
990
- } finally {
991
- if (abortListener) {
992
- signal.removeEventListener("abort", abortListener);
993
- }
711
+ return decodeURIComponent(value);
712
+ } catch {
713
+ return value;
994
714
  }
995
715
  }
996
716
 
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 };
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 };