@orpc/shared 2.0.0-beta.4 → 2.0.0-beta.40

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,5 +1,5 @@
1
- import { AbortError, AsyncIteratorClass, isTypescriptObject, getOrBind } from '@standardserver/shared';
2
- export { AbortError, AsyncIteratorClass, SequentialIdGenerator, getOrBind, isAsyncIteratorObject, isTypescriptObject, parseEmptyableJSON, sleep, stringifyJSON, toArray } from '@standardserver/shared';
1
+ import { safeDecodeURIComponent, safeEncodeURIComponent, AbortError, AsyncIteratorClass, getOrBind, isTypescriptObject, isAsyncIteratorObject } from '@standard-server/shared';
2
+ export { AbortError, AsyncIteratorClass, SequentialIdGenerator, getOrBind, isAsyncIteratorObject, isTypescriptObject, parseEmptyableJSON, safeDecodeURIComponent, safeEncodeURIComponent, sequential, sleep, stringifyJSON, toArray } from '@standard-server/shared';
3
3
 
4
4
  function resolveMaybeOptionalOptions(rest) {
5
5
  return rest[0] ?? {};
@@ -16,24 +16,44 @@ async function loadBytes(source) {
16
16
  }
17
17
  return new Uint8Array(await source.arrayBuffer());
18
18
  }
19
- async function toStringOrBytes(source) {
19
+ function toStringOrBytes(source) {
20
20
  if (typeof source === "string") {
21
21
  return source;
22
22
  }
23
23
  if (source instanceof ArrayBuffer) {
24
24
  return new Uint8Array(source);
25
25
  }
26
- if (source instanceof Blob) {
27
- return loadBytes(source);
28
- }
29
26
  if (Array.isArray(source)) {
30
- return loadBytes(new Blob(source));
27
+ return concatBytes(source);
31
28
  }
32
29
  if (source instanceof Uint8Array) {
33
30
  return source;
34
31
  }
35
32
  return new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
36
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
+ }
37
57
 
38
58
  function isDeepEqual(a, b) {
39
59
  return isDeepEqualInternal(a, b, /* @__PURE__ */ new WeakMap());
@@ -91,6 +111,11 @@ function isAbortError(error) {
91
111
  return error instanceof Error && error.name.includes("Abort");
92
112
  }
93
113
 
114
+ const AsyncGeneratorFunction = Object.getPrototypeOf(async function* () {
115
+ }).constructor;
116
+ function isAsyncGeneratorFunction(value) {
117
+ return value instanceof AsyncGeneratorFunction;
118
+ }
94
119
  function once(fn) {
95
120
  let cached;
96
121
  return () => {
@@ -117,23 +142,15 @@ function tryOrUndefined(fn) {
117
142
  }
118
143
  }
119
144
 
120
- function tryDecodeURIComponent(value) {
121
- try {
122
- return decodeURIComponent(value);
123
- } catch {
124
- return value;
125
- }
126
- }
127
-
128
145
  function pathToHttpPath(path) {
129
- return `/${path.map(encodeURIComponent).join("/")}`;
146
+ return `/${path.map(safeEncodeURIComponent).join("/")}`;
130
147
  }
131
148
  function normalizeHttpPath(path) {
132
149
  const paths = path.split("/");
133
150
  if (paths.at(0) === "") {
134
151
  paths.shift();
135
152
  }
136
- return pathToHttpPath(paths.map(tryDecodeURIComponent));
153
+ return pathToHttpPath(paths.map(safeDecodeURIComponent));
137
154
  }
138
155
  function mergeHttpPath(a, b) {
139
156
  return `${a.endsWith("/") ? a.slice(0, -1) : a}${b}`;
@@ -156,167 +173,51 @@ function matchesHttpPath(url, path) {
156
173
  }
157
174
  return charAfterPrefix === void 0 || charAfterPrefix === "?" || charAfterPrefix === "#";
158
175
  }
159
-
160
- function compareSequentialIds(a, b) {
161
- if (a.length !== b.length) {
162
- return a.length - b.length;
163
- }
164
- return a < b ? -1 : a > b ? 1 : 0;
165
- }
166
-
167
- function onStart(callback) {
168
- return async (options, ...rest) => {
169
- await callback(options, ...rest);
170
- return await options.next();
171
- };
172
- }
173
- function onSuccess(callback) {
174
- return async (options, ...rest) => {
175
- const result = await options.next();
176
- await callback(result, options, ...rest);
177
- return result;
178
- };
179
- }
180
- function onError(callback) {
181
- return async (options, ...rest) => {
182
- try {
183
- return await options.next();
184
- } catch (error) {
185
- await callback(error, options, ...rest);
186
- throw error;
187
- }
188
- };
189
- }
190
- function onFinish(callback) {
191
- let state;
192
- return async (options, ...rest) => {
193
- try {
194
- const result = await options.next();
195
- state = [null, result, true];
196
- return result;
197
- } catch (error) {
198
- state = [error, void 0, false];
199
- throw error;
200
- } finally {
201
- await callback(state, options, ...rest);
202
- }
203
- };
204
- }
205
- function intercept(interceptors, options, main) {
206
- if (!interceptors?.length) {
207
- return main(options);
208
- }
209
- const next = (options2, index) => {
210
- const interceptor = interceptors[index];
211
- if (!interceptor) {
212
- return main(options2);
176
+ const ACCEPT_ENCODING_QUALITY_REGEX = /^\s*q=([\d.]+)\s*$/i;
177
+ function parseAcceptEncodingQualities(header) {
178
+ const qualities = /* @__PURE__ */ new Map();
179
+ for (const part of header?.split(",") ?? []) {
180
+ const [rawCoding, ...params] = part.split(";");
181
+ const coding = rawCoding.trim().toLowerCase();
182
+ if (coding === "") {
183
+ continue;
213
184
  }
214
- return interceptor({
215
- ...options2,
216
- next: (newOptions = options2) => next(newOptions, index + 1)
217
- });
218
- };
219
- return next(options, 0);
220
- }
221
-
222
- const SPAN_ERROR_STATUS = 2;
223
- const OPENTELEMETRY_CONFIG_SYMBOL = Symbol.for("ORPC_OPENTELEMETRY_CONFIG");
224
- function setOpenTelemetryConfig(config) {
225
- globalThis[OPENTELEMETRY_CONFIG_SYMBOL] = config;
226
- }
227
- function getOpenTelemetryConfig() {
228
- return globalThis[OPENTELEMETRY_CONFIG_SYMBOL];
229
- }
230
- function startSpan(options) {
231
- const tracer = getOpenTelemetryConfig()?.tracer;
232
- if (!tracer) {
233
- return void 0;
234
- }
235
- const { name, context, ...spanOptions } = typeof options === "string" ? { name: options } : options;
236
- return tracer.startSpan(name, spanOptions, context);
237
- }
238
- function recordSpanError(span, error) {
239
- if (!span) {
240
- return;
241
- }
242
- const exception = toOtelException(error);
243
- span.recordException(exception);
244
- if (!isAbortError(error)) {
245
- span.setStatus({
246
- code: SPAN_ERROR_STATUS,
247
- message: exception.message
248
- });
249
- }
250
- }
251
- function setSpanAttributeIfDefined(span, key, value) {
252
- if (!span || value === void 0) {
253
- return;
185
+ const quality = params.map((param) => ACCEPT_ENCODING_QUALITY_REGEX.exec(param)?.[1]).find((value) => value !== void 0);
186
+ qualities.set(coding, quality === void 0 ? 1 : Number(quality));
254
187
  }
255
- span.setAttribute(key, value);
188
+ return qualities;
256
189
  }
257
- function toOtelException(error) {
258
- if (error instanceof Error) {
259
- const exception = {
260
- message: error.message,
261
- name: error.name,
262
- stack: error.stack
263
- };
264
- if ("code" in error && (typeof error.code === "string" || typeof error.code === "number")) {
265
- exception.code = error.code;
266
- }
267
- return exception;
190
+ function varyByAcceptEncoding(vary) {
191
+ if (vary === void 0) {
192
+ return "accept-encoding";
268
193
  }
269
- return { message: String(error) };
194
+ const fields = vary.split(",").map((field) => field.trim().toLowerCase());
195
+ return fields.includes("accept-encoding") || fields.includes("*") ? vary : `${vary}, accept-encoding`;
270
196
  }
271
- function toSpanAttributeValue(data) {
272
- if (data === void 0) {
273
- return "undefined";
274
- }
275
- try {
276
- return JSON.stringify(data, (_, value) => {
277
- if (typeof value === "bigint") {
278
- return value.toString();
279
- }
280
- if (value instanceof Map || value instanceof Set) {
281
- return Array.from(value);
282
- }
283
- return value;
284
- });
285
- } catch {
286
- return String(data);
197
+ const CACHE_CONTROL_NO_TRANSFORM_REGEX = /(?:^|,)\s*no-transform\s*(?:,|$)/i;
198
+ function isNoTransformCacheControl(cacheControl) {
199
+ if (cacheControl === void 0) {
200
+ return false;
287
201
  }
202
+ return CACHE_CONTROL_NO_TRANSFORM_REGEX.test(cacheControl);
288
203
  }
289
- async function runWithSpan(options, fn) {
290
- const tracer = getOpenTelemetryConfig()?.tracer;
291
- if (!tracer) {
292
- return fn();
293
- }
294
- if (typeof options === "string") {
295
- options = { name: options };
204
+ 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;
205
+ const MAX_COMPRESSIBLE_CONTENT_TYPE_LENGTH = 1024;
206
+ function isCompressibleContentType(contentType) {
207
+ if (contentType === null || contentType === void 0) {
208
+ return false;
296
209
  }
297
- const callback = async (span) => {
298
- try {
299
- return await fn(span);
300
- } catch (e) {
301
- recordSpanError(span, e);
302
- throw e;
303
- } finally {
304
- span.end();
305
- }
306
- };
307
- if (options.context) {
308
- return tracer.startActiveSpan(options.name, options, options.context, callback);
309
- } else {
310
- return tracer.startActiveSpan(options.name, options, callback);
210
+ if (contentType.length > MAX_COMPRESSIBLE_CONTENT_TYPE_LENGTH) {
211
+ return false;
311
212
  }
213
+ return COMPRESSIBLE_CONTENT_TYPE_REGEX.test(contentType);
312
214
  }
313
- async function runInSpanContext(span, fn) {
314
- const otelConfig = getOpenTelemetryConfig();
315
- if (!span || !otelConfig) {
316
- return fn();
215
+
216
+ function compareSequentialIds(a, b) {
217
+ if (a.length !== b.length) {
218
+ return a.length - b.length;
317
219
  }
318
- const ctx = otelConfig.trace.setSpan(otelConfig.context.active(), span);
319
- return otelConfig.context.with(ctx, fn);
220
+ return a < b ? -1 : a > b ? 1 : 0;
320
221
  }
321
222
 
322
223
  class AsyncIdQueue {
@@ -393,6 +294,93 @@ class AsyncIdQueue {
393
294
  }
394
295
  }
395
296
 
297
+ const TRACER_SYMBOL = Symbol.for("ORPC_TRACER");
298
+ function setTracer(tracer) {
299
+ globalThis[TRACER_SYMBOL] = tracer;
300
+ }
301
+ function getTracer() {
302
+ return globalThis[TRACER_SYMBOL];
303
+ }
304
+ function startSpan(options) {
305
+ const tracer = getTracer();
306
+ if (!tracer) {
307
+ return void 0;
308
+ }
309
+ if (typeof options === "string") {
310
+ return tracer.startSpan(options);
311
+ }
312
+ return tracer.startSpan(options.name, options.parent);
313
+ }
314
+ function recordSpanError(span, error) {
315
+ if (!span) {
316
+ return;
317
+ }
318
+ span.recordException(isAbortError(error) ? "info" : "error", toTracingException(error));
319
+ }
320
+ function setSpanAttributeIfDefined(span, key, value) {
321
+ if (!span || value === void 0) {
322
+ return;
323
+ }
324
+ span.setAttribute(key, value);
325
+ }
326
+ function toTracingException(error) {
327
+ if (error instanceof Error) {
328
+ const exception = {
329
+ message: error.message,
330
+ name: error.name,
331
+ stack: error.stack
332
+ };
333
+ if ("code" in error && (typeof error.code === "string" || typeof error.code === "number")) {
334
+ exception.code = error.code;
335
+ }
336
+ return exception;
337
+ }
338
+ return { message: String(error) };
339
+ }
340
+ function toSpanAttributeValue(data) {
341
+ if (data === void 0) {
342
+ return "undefined";
343
+ }
344
+ try {
345
+ return JSON.stringify(data, (_, value) => {
346
+ if (typeof value === "bigint") {
347
+ return value.toString();
348
+ }
349
+ if (value instanceof Map || value instanceof Set) {
350
+ return Array.from(value);
351
+ }
352
+ return value;
353
+ });
354
+ } catch {
355
+ return String(data);
356
+ }
357
+ }
358
+ async function runWithSpan(options, fn) {
359
+ const tracer = getTracer();
360
+ if (!tracer) {
361
+ return fn();
362
+ }
363
+ const name = typeof options === "string" ? options : options.name;
364
+ const parent = typeof options === "string" ? void 0 : options.parent;
365
+ return tracer.startActiveSpan(name, parent, async (span) => {
366
+ try {
367
+ return await fn(span);
368
+ } catch (e) {
369
+ recordSpanError(span, e);
370
+ throw e;
371
+ } finally {
372
+ span.end();
373
+ }
374
+ });
375
+ }
376
+ function runInSpanContext(span, fn) {
377
+ const tracer = getTracer();
378
+ if (!span || !tracer) {
379
+ return fn();
380
+ }
381
+ return tracer.withActiveSpan(span, fn);
382
+ }
383
+
396
384
  function wrapAsyncIterator(iterator, { runWith, mapResult, mapError, onError, onFinish }) {
397
385
  runWith ??= (run) => run();
398
386
  let isDone;
@@ -491,6 +479,52 @@ function replicateAsyncIterator(source, count) {
491
479
  });
492
480
  return replicated;
493
481
  }
482
+ function consumeAsyncIterator(iterator, options) {
483
+ void (async () => {
484
+ let onFinishState;
485
+ try {
486
+ const resolvedIterator = await iterator;
487
+ while (true) {
488
+ const { done, value } = await resolvedIterator.next();
489
+ if (done) {
490
+ const realValue = value;
491
+ onFinishState = [null, realValue, true];
492
+ options.onSuccess?.(realValue);
493
+ break;
494
+ }
495
+ options.onEvent(value);
496
+ }
497
+ } catch (error) {
498
+ onFinishState = [error, void 0, false];
499
+ options.onError?.(error);
500
+ } finally {
501
+ options.onFinish?.(onFinishState);
502
+ }
503
+ })();
504
+ return async () => {
505
+ await (await iterator)?.return?.();
506
+ };
507
+ }
508
+
509
+ function value(value2, ...args) {
510
+ if (typeof value2 === "function") {
511
+ return value2(...args);
512
+ }
513
+ return value2;
514
+ }
515
+
516
+ function override(target, partial) {
517
+ const proxy = new Proxy(typeof target === "function" ? partial : target, {
518
+ get(_, prop) {
519
+ const targetValue = prop in partial ? partial : value(target);
520
+ return getOrBind(targetValue, prop);
521
+ },
522
+ has(_, prop) {
523
+ return Reflect.has(partial, prop) || Reflect.has(value(target), prop);
524
+ }
525
+ });
526
+ return proxy;
527
+ }
494
528
 
495
529
  function findDeepMatches(check, payload, segments = [], maps = [], values = []) {
496
530
  if (check(payload)) {
@@ -501,7 +535,7 @@ function findDeepMatches(check, payload, segments = [], maps = [], values = [])
501
535
  findDeepMatches(check, v, [...segments, i], maps, values);
502
536
  });
503
537
  } else if (isPlainObject(payload)) {
504
- for (const key in payload) {
538
+ for (const key of Object.keys(payload)) {
505
539
  findDeepMatches(check, payload[key], [...segments, key], maps, values);
506
540
  }
507
541
  }
@@ -513,6 +547,18 @@ function getConstructor(value) {
513
547
  }
514
548
  return Object.getPrototypeOf(value)?.constructor;
515
549
  }
550
+ function* getConstructors(value) {
551
+ if (!isTypescriptObject(value)) {
552
+ return;
553
+ }
554
+ let proto = Object.getPrototypeOf(value);
555
+ while (proto != null) {
556
+ if (proto.constructor) {
557
+ yield proto.constructor;
558
+ }
559
+ proto = Object.getPrototypeOf(proto);
560
+ }
561
+ }
516
562
  function isPlainObject(value) {
517
563
  if (!value || typeof value !== "object") {
518
564
  return false;
@@ -520,13 +566,16 @@ function isPlainObject(value) {
520
566
  const proto = Object.getPrototypeOf(value);
521
567
  return proto === Object.prototype || !proto || !proto.constructor;
522
568
  }
569
+ function getOwn(object, key) {
570
+ return Object.hasOwn(object, key) ? object[key] : void 0;
571
+ }
523
572
  function get(object, path) {
524
573
  let current = object;
525
574
  for (const key of path) {
526
575
  if (!isTypescriptObject(current)) {
527
576
  return void 0;
528
577
  }
529
- current = current[key];
578
+ current = getOwn(current, key);
530
579
  }
531
580
  return current;
532
581
  }
@@ -534,37 +583,102 @@ function set(root, path, value) {
534
583
  let current = root;
535
584
  for (let i = 0; i < path.length - 1; i++) {
536
585
  const key = path[i];
537
- const next = current[key];
586
+ const next = getOwn(current, key);
538
587
  if (!isTypescriptObject(next)) {
539
- current[key] = {};
588
+ const child = {};
589
+ setOwn(current, key, child);
590
+ current = child;
591
+ } else {
592
+ current = next;
540
593
  }
541
- current = current[key];
542
594
  }
543
- current[path.at(-1)] = value;
595
+ setOwn(current, path.at(-1), value);
544
596
  }
545
- function omit(obj, keys) {
546
- const result = { ...obj };
547
- for (const key of keys) {
597
+ function setOwn(object, key, value) {
598
+ if (key === "__proto__") {
599
+ Object.defineProperty(object, key, {
600
+ value,
601
+ writable: true,
602
+ enumerable: true,
603
+ configurable: true
604
+ });
605
+ } else {
606
+ object[key] = value;
607
+ }
608
+ }
609
+ function mergeTwoLevels(first, second) {
610
+ if (!isPlainObject(first) || !isPlainObject(second)) {
611
+ return second;
612
+ }
613
+ const result = { ...first, ...second };
614
+ for (const key of Object.keys(second)) {
615
+ if (!Object.hasOwn(first, key)) {
616
+ continue;
617
+ }
618
+ const firstValue = first[key];
619
+ const secondValue = second[key];
620
+ if (isPlainObject(firstValue) && isPlainObject(secondValue)) {
621
+ result[key] = { ...firstValue, ...secondValue };
622
+ }
623
+ }
624
+ return result;
625
+ }
626
+ function omit(obj, keys) {
627
+ const result = { ...obj };
628
+ for (const key of keys) {
548
629
  delete result[key];
549
630
  }
550
631
  return result;
551
632
  }
552
633
  function clone(value) {
634
+ return cloneWithVisited(value, /* @__PURE__ */ new WeakMap());
635
+ }
636
+ function cloneWithVisited(value, visited) {
553
637
  if (Array.isArray(value)) {
554
- return value.map(clone);
638
+ const existing = visited.get(value);
639
+ if (existing) {
640
+ return existing;
641
+ }
642
+ const result = [];
643
+ visited.set(value, result);
644
+ for (const item of value) {
645
+ result.push(cloneWithVisited(item, visited));
646
+ }
647
+ return result;
555
648
  }
556
649
  if (isPlainObject(value)) {
650
+ const existing = visited.get(value);
651
+ if (existing) {
652
+ return existing;
653
+ }
557
654
  const result = {};
558
- for (const key in value) {
559
- result[key] = clone(value[key]);
655
+ visited.set(value, result);
656
+ for (const key of Object.keys(value)) {
657
+ setOwn(result, key, cloneWithVisited(value[key], visited));
560
658
  }
561
659
  for (const sym of Object.getOwnPropertySymbols(value)) {
562
- result[sym] = clone(value[sym]);
660
+ setOwn(result, sym, cloneWithVisited(value[sym], visited));
563
661
  }
564
662
  return result;
565
663
  }
566
664
  return value;
567
665
  }
666
+ function copyOnWrite(parent, key, original) {
667
+ const value = parent[key];
668
+ if (value !== original) {
669
+ return value;
670
+ }
671
+ let copy;
672
+ if (Array.isArray(value)) {
673
+ copy = value.slice();
674
+ } else if (isPlainObject(value)) {
675
+ copy = { ...value };
676
+ } else {
677
+ return value;
678
+ }
679
+ setOwn(parent, key, copy);
680
+ return copy;
681
+ }
568
682
  function isPropertyKey(value) {
569
683
  const type = typeof value;
570
684
  return type === "string" || type === "number" || type === "symbol";
@@ -576,7 +690,8 @@ const NullProtoObj = /* @__PURE__ */ (() => {
576
690
  Object.freeze(e.prototype);
577
691
  return e;
578
692
  })();
579
- function bindMethods(obj) {
693
+ function bindMethods(obj, options = {}) {
694
+ const unbound = new Set(options.unbound);
580
695
  const methods = new NullProtoObj();
581
696
  let current = obj;
582
697
  while (current && current !== Object.prototype) {
@@ -584,18 +699,18 @@ function bindMethods(obj) {
584
699
  if (key === "constructor" || key in methods) {
585
700
  continue;
586
701
  }
587
- const val = obj[key];
702
+ const val = getOrBind(obj, key, { bind: !unbound.has(key) });
588
703
  if (typeof val === "function") {
589
- methods[key] = val.bind(obj);
704
+ methods[key] = val;
590
705
  }
591
706
  }
592
707
  for (const sym of Object.getOwnPropertySymbols(current)) {
593
708
  if (sym in methods) {
594
709
  continue;
595
710
  }
596
- const val = obj[sym];
711
+ const val = getOrBind(obj, sym, { bind: !unbound.has(sym) });
597
712
  if (typeof val === "function") {
598
- methods[sym] = val.bind(obj);
713
+ methods[sym] = val;
599
714
  }
600
715
  }
601
716
  current = Object.getPrototypeOf(current);
@@ -603,84 +718,6 @@ function bindMethods(obj) {
603
718
  return methods;
604
719
  }
605
720
 
606
- function sortPlugins(plugins) {
607
- const pluginCount = plugins.length;
608
- const pluginIdToIndices = /* @__PURE__ */ new Map();
609
- for (let i = 0; i < pluginCount; i++) {
610
- const plugin = plugins[i];
611
- const indices = pluginIdToIndices.get(plugin.name);
612
- if (indices === void 0) {
613
- pluginIdToIndices.set(plugin.name, [i]);
614
- } else {
615
- indices.push(i);
616
- }
617
- }
618
- const graph = Array.from(
619
- { length: pluginCount },
620
- () => /* @__PURE__ */ new Set()
621
- );
622
- for (let i = 0; i < pluginCount; i++) {
623
- const plugin = plugins[i];
624
- const beforeList = plugin.before;
625
- if (beforeList !== void 0) {
626
- for (const beforeId of beforeList) {
627
- const beforeIndices = pluginIdToIndices.get(beforeId);
628
- if (beforeIndices === void 0)
629
- continue;
630
- for (const beforeIndex of beforeIndices) {
631
- const beforeGraph = graph[beforeIndex];
632
- if (beforeGraph !== void 0) {
633
- beforeGraph.add(i);
634
- }
635
- }
636
- }
637
- }
638
- const afterList = plugin.after;
639
- if (afterList !== void 0) {
640
- const currentGraph = graph[i];
641
- if (currentGraph !== void 0) {
642
- for (const afterId of afterList) {
643
- const afterIndices = pluginIdToIndices.get(afterId);
644
- if (afterIndices === void 0)
645
- continue;
646
- for (const afterIndex of afterIndices) {
647
- currentGraph.add(afterIndex);
648
- }
649
- }
650
- }
651
- }
652
- }
653
- const sorted = [];
654
- const visiting = /* @__PURE__ */ new Set();
655
- const visited = /* @__PURE__ */ new Set();
656
- function visit(index) {
657
- if (visited.has(index))
658
- return;
659
- if (visiting.has(index)) {
660
- const plugin2 = plugins[index];
661
- const pluginId = plugin2 !== void 0 ? plugin2.name : "unknown";
662
- throw new Error(`Circular dependency detected involving plugin "${pluginId}"`);
663
- }
664
- visiting.add(index);
665
- const deps = graph[index];
666
- if (deps !== void 0) {
667
- for (const depIndex of deps) {
668
- visit(depIndex);
669
- }
670
- }
671
- visiting.delete(index);
672
- visited.add(index);
673
- const plugin = plugins[index];
674
- if (plugin !== void 0) {
675
- sorted.push(plugin);
676
- }
677
- }
678
- for (let i = 0; i < pluginCount; i++) {
679
- visit(i);
680
- }
681
- return sorted;
682
- }
683
-
684
721
  function promiseWithResolvers() {
685
722
  const result = {};
686
723
  result.promise = new Promise((resolve, reject) => {
@@ -690,69 +727,6 @@ function promiseWithResolvers() {
690
727
  return result;
691
728
  }
692
729
 
693
- function value(value2, ...args) {
694
- if (typeof value2 === "function") {
695
- return value2(...args);
696
- }
697
- return value2;
698
- }
699
-
700
- function override(target, partial) {
701
- const proxy = new Proxy(typeof target === "function" ? partial : target, {
702
- get(_, prop) {
703
- const targetValue = prop in partial ? partial : value(target);
704
- return getOrBind(targetValue, prop);
705
- },
706
- has(_, prop) {
707
- return Reflect.has(partial, prop) || Reflect.has(value(target), prop);
708
- }
709
- });
710
- return proxy;
711
- }
712
-
713
- function allAbortSignal(signals) {
714
- const realSignals = signals.filter((signal) => signal !== void 0);
715
- if (realSignals.length === 0 || realSignals.length !== signals.length) {
716
- return void 0;
717
- }
718
- const controller = new AbortController();
719
- const abortIfAllAborted = () => {
720
- if (realSignals.every((signal) => signal.aborted)) {
721
- controller.abort();
722
- }
723
- };
724
- abortIfAllAborted();
725
- for (const signal of realSignals) {
726
- signal.addEventListener("abort", () => {
727
- abortIfAllAborted();
728
- }, {
729
- once: true,
730
- signal: controller.signal
731
- });
732
- }
733
- return controller.signal;
734
- }
735
- async function runWithSignal(signal, fn) {
736
- if (!signal) {
737
- return fn();
738
- }
739
- signal.throwIfAborted();
740
- const { promise, reject, resolve } = promiseWithResolvers();
741
- let abortListener;
742
- signal.addEventListener("abort", abortListener = () => {
743
- reject(signal.reason);
744
- abortListener = void 0;
745
- });
746
- try {
747
- fn().then(resolve, reject);
748
- return await promise;
749
- } finally {
750
- if (abortListener) {
751
- signal.removeEventListener("abort", abortListener);
752
- }
753
- }
754
- }
755
-
756
730
  function replicateReadableStream(stream, count) {
757
731
  if (count <= 0) {
758
732
  return [];
@@ -823,7 +797,7 @@ function traceReadableStream(options, stream) {
823
797
  }
824
798
  });
825
799
  }
826
- function streamToAsyncIteratorClass(stream, { signal } = {}) {
800
+ function streamToAsyncIteratorObject(stream, { signal } = {}) {
827
801
  const reader = stream.getReader();
828
802
  let cancelledBySignal = false;
829
803
  return new AsyncIteratorClass(
@@ -889,4 +863,208 @@ function asyncIteratorToUnproxiedDataStream(iterator) {
889
863
  });
890
864
  }
891
865
 
892
- export { AsyncIdQueue, NullProtoObj, ORPC_NAME, allAbortSignal, asyncIteratorToStream, asyncIteratorToUnproxiedDataStream, bindMethods, clone, compareSequentialIds, defer, findDeepMatches, get, getConstructor, getOpenTelemetryConfig, intercept, isAbortError, isDeepEqual, isPlainObject, isPropertyKey, loadBytes, matchesHttpPath, matchesHttpPathPrefix, mergeHttpPath, normalizeHttpPath, omit, onError, onFinish, onStart, onSuccess, once, override, pathToHttpPath, promiseWithResolvers, recordSpanError, replicateAsyncIterator, replicateReadableStream, resolveMaybeOptionalOptions, runInSpanContext, runWithSignal, runWithSpan, set, setOpenTelemetryConfig, setSpanAttributeIfDefined, sortPlugins, splitInHalf, startSpan, streamToAsyncIteratorClass, toOtelException, toSpanAttributeValue, toStringOrBytes, traceAsyncIterator, traceReadableStream, tryDecodeURIComponent, tryOrUndefined, value, wrapAsyncIterator, wrapReadableStream };
866
+ function onStart(callback) {
867
+ return async (options, ...rest) => {
868
+ await callback(options, ...rest);
869
+ return await options.next();
870
+ };
871
+ }
872
+ function onSuccess(callback) {
873
+ return async (options, ...rest) => {
874
+ const result = await options.next();
875
+ await callback(result, options, ...rest);
876
+ return result;
877
+ };
878
+ }
879
+ function onError(callback) {
880
+ return async (options, ...rest) => {
881
+ try {
882
+ return await options.next();
883
+ } catch (error) {
884
+ await callback(error, options, ...rest);
885
+ throw error;
886
+ }
887
+ };
888
+ }
889
+ function onFinish(callback) {
890
+ let state;
891
+ return async (options, ...rest) => {
892
+ try {
893
+ const result = await options.next();
894
+ state = [null, result, true];
895
+ return result;
896
+ } catch (error) {
897
+ state = [error, void 0, false];
898
+ throw error;
899
+ } finally {
900
+ await callback(state, options, ...rest);
901
+ }
902
+ };
903
+ }
904
+ function onAsyncIteratorObjectError(callback) {
905
+ return async (options, ...rest) => {
906
+ const output = await options.next();
907
+ if (!isAsyncIteratorObject(output)) {
908
+ return output;
909
+ }
910
+ return override(output, wrapAsyncIterator(output, {
911
+ onError: (error) => callback(error, options, ...rest)
912
+ }));
913
+ };
914
+ }
915
+ function onReadableStreamError(callback) {
916
+ return async (options, ...rest) => {
917
+ const output = await options.next();
918
+ if (!(output instanceof ReadableStream)) {
919
+ return output;
920
+ }
921
+ return override(output, wrapReadableStream(output, {
922
+ onError: (error) => callback(error, options, ...rest)
923
+ }));
924
+ };
925
+ }
926
+ function intercept(interceptors, options, main) {
927
+ if (!interceptors?.length) {
928
+ return main(options);
929
+ }
930
+ const next = (options2, index) => {
931
+ const interceptor = interceptors[index];
932
+ if (!interceptor) {
933
+ return main(options2);
934
+ }
935
+ return interceptor({
936
+ ...options2,
937
+ next: (newOptions = options2) => next(newOptions, index + 1)
938
+ });
939
+ };
940
+ return next(options, 0);
941
+ }
942
+
943
+ function sortPlugins(plugins) {
944
+ const pluginCount = plugins.length;
945
+ const pluginIdToIndices = /* @__PURE__ */ new Map();
946
+ for (let i = 0; i < pluginCount; i++) {
947
+ const plugin = plugins[i];
948
+ const indices = pluginIdToIndices.get(plugin.name);
949
+ if (indices === void 0) {
950
+ pluginIdToIndices.set(plugin.name, [i]);
951
+ } else {
952
+ indices.push(i);
953
+ }
954
+ }
955
+ const dependencies = Array.from({ length: pluginCount }, () => []);
956
+ for (let i = 0; i < pluginCount; i++) {
957
+ const plugin = plugins[i];
958
+ if (plugin.before !== void 0) {
959
+ for (const beforeId of plugin.before) {
960
+ const beforeIndices = pluginIdToIndices.get(beforeId);
961
+ if (beforeIndices !== void 0) {
962
+ for (const beforeIndex of beforeIndices) {
963
+ dependencies[beforeIndex].push(i);
964
+ }
965
+ }
966
+ }
967
+ }
968
+ if (plugin.after !== void 0) {
969
+ for (const afterId of plugin.after) {
970
+ const afterIndices = pluginIdToIndices.get(afterId);
971
+ if (afterIndices !== void 0) {
972
+ for (const afterIndex of afterIndices) {
973
+ dependencies[i].push(afterIndex);
974
+ }
975
+ }
976
+ }
977
+ }
978
+ }
979
+ const sorted = [];
980
+ const placed = /* @__PURE__ */ new Set();
981
+ while (sorted.length < pluginCount) {
982
+ const next = plugins.findIndex((_, i) => !placed.has(i) && dependencies[i].every((dependency) => placed.has(dependency)));
983
+ if (next === -1) {
984
+ throw new Error(`Circular dependency detected involving plugin "${findCyclicPlugin(plugins, dependencies, placed).name}"`);
985
+ }
986
+ placed.add(next);
987
+ sorted.push(plugins[next]);
988
+ }
989
+ return sorted;
990
+ }
991
+ function findCyclicPlugin(plugins, dependencies, placed) {
992
+ const seen = /* @__PURE__ */ new Set();
993
+ let current = plugins.findIndex((_, i) => !placed.has(i));
994
+ while (!seen.has(current)) {
995
+ seen.add(current);
996
+ current = dependencies[current].find((dependency) => !placed.has(dependency));
997
+ }
998
+ return plugins[current];
999
+ }
1000
+
1001
+ function allAbortSignal(signals) {
1002
+ const realSignals = signals.filter((signal) => signal !== void 0);
1003
+ if (realSignals.length === 0 || realSignals.length !== signals.length) {
1004
+ return void 0;
1005
+ }
1006
+ const controller = new AbortController();
1007
+ const abortIfAllAborted = () => {
1008
+ if (realSignals.every((signal) => signal.aborted)) {
1009
+ controller.abort();
1010
+ }
1011
+ };
1012
+ abortIfAllAborted();
1013
+ for (const signal of realSignals) {
1014
+ signal.addEventListener("abort", () => {
1015
+ abortIfAllAborted();
1016
+ }, {
1017
+ once: true,
1018
+ signal: controller.signal
1019
+ });
1020
+ }
1021
+ return controller.signal;
1022
+ }
1023
+ function anyAbortSignal(signals) {
1024
+ const realSignals = signals.filter((signal) => signal !== void 0);
1025
+ if (realSignals.length === 0) {
1026
+ return void 0;
1027
+ }
1028
+ if (realSignals.length === 1) {
1029
+ return realSignals[0];
1030
+ }
1031
+ if (typeof AbortSignal !== "undefined" && typeof AbortSignal.any === "function") {
1032
+ return AbortSignal.any(realSignals);
1033
+ }
1034
+ const controller = new AbortController();
1035
+ for (const signal of realSignals) {
1036
+ if (signal.aborted) {
1037
+ controller.abort(signal.reason);
1038
+ break;
1039
+ }
1040
+ signal.addEventListener("abort", () => {
1041
+ controller.abort(signal.reason);
1042
+ }, {
1043
+ once: true,
1044
+ signal: controller.signal
1045
+ });
1046
+ }
1047
+ return controller.signal;
1048
+ }
1049
+ async function runWithSignal(signal, fn) {
1050
+ if (!signal) {
1051
+ return fn();
1052
+ }
1053
+ signal.throwIfAborted();
1054
+ const { promise, reject, resolve } = promiseWithResolvers();
1055
+ let abortListener;
1056
+ signal.addEventListener("abort", abortListener = () => {
1057
+ reject(signal.reason);
1058
+ abortListener = void 0;
1059
+ });
1060
+ try {
1061
+ fn().then(resolve, reject);
1062
+ return await promise;
1063
+ } finally {
1064
+ if (abortListener) {
1065
+ signal.removeEventListener("abort", abortListener);
1066
+ }
1067
+ }
1068
+ }
1069
+
1070
+ export { AsyncIdQueue, NullProtoObj, ORPC_NAME, allAbortSignal, anyAbortSignal, asyncIteratorToStream, asyncIteratorToUnproxiedDataStream, bindMethods, clone, compareSequentialIds, consumeAsyncIterator, copyOnWrite, defer, findDeepMatches, get, getConstructor, getConstructors, getOwn, getTracer, intercept, isAbortError, isAsyncGeneratorFunction, isCompressibleContentType, isDeepEqual, isNoTransformCacheControl, isPlainObject, isPropertyKey, loadBytes, matchesHttpPath, matchesHttpPathPrefix, mergeHttpPath, mergeTwoLevels, normalizeHttpPath, omit, onAsyncIteratorObjectError, onError, onFinish, onReadableStreamError, onStart, onSuccess, once, override, parseAcceptEncodingQualities, pathToHttpPath, promiseWithResolvers, recordSpanError, replicateAsyncIterator, replicateReadableStream, resolveMaybeOptionalOptions, runInSpanContext, runWithSignal, runWithSpan, set, setOwn, setSpanAttributeIfDefined, setTracer, sortPlugins, splitInHalf, startSpan, streamToAsyncIteratorObject, toSpanAttributeValue, toStringOrBytes, toTracingException, traceAsyncIterator, traceReadableStream, tryOrUndefined, value, varyByAcceptEncoding, wrapAsyncIterator, wrapReadableStream };