@voltro/client 0.89.2 → 0.90.0

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/runtime.d.ts CHANGED
@@ -413,6 +413,17 @@ export declare interface ClientTraceEvent {
413
413
 
414
414
  declare type ClientTraceListener = (event: ClientTraceEvent) => void;
415
415
 
416
+ /** A traced call whose server answered with a failure its descriptor declares (a typed refusal the
417
+ * caller can handle, `kind: 'handler'`), not a defect or a transport loss. The dev trace bridge
418
+ * logs that trace's errored spans as a refusal instead of surfacing them as errors. */
419
+ export declare interface ClientTraceRefusal {
420
+ readonly traceId: string;
421
+ /** RPC tag (e.g. `'social.request'`). */
422
+ readonly tag: string;
423
+ }
424
+
425
+ declare type ClientTraceRefusalListener = (event: ClientTraceRefusal) => void;
426
+
416
427
  /** One physical socket attempt inside one runtime, including in-place retries. */
417
428
  declare interface ConnectionAttempt {
418
429
  readonly open: () => ConnectionLease | undefined;
@@ -431,7 +442,6 @@ declare interface ConnectionLease {
431
442
  * deliberately not an input: outgoing and replacement runtimes share health.
432
443
  */
433
444
  declare class ConnectionScope {
434
- #private;
435
445
  readonly getSnapshot: () => ConnectionLease | undefined;
436
446
  readonly subscribe: (listener: () => void) => (() => void);
437
447
  begin(): ConnectionAttempt;
@@ -605,6 +615,8 @@ export declare const publishClientError: (event: ClientErrorEvent) => void;
605
615
  /** Publish a started client trace. Cheap + sync; safe on the hot path. */
606
616
  export declare const publishClientTrace: (event: ClientTraceEvent) => void;
607
617
 
618
+ export declare const publishClientTraceRefusal: (event: ClientTraceRefusal) => void;
619
+
608
620
  /** `queryOnce`'s shape, declared here so this module stays free of it. */
609
621
  declare type QueryOnce = (handleRef: {
610
622
  readonly current: {
@@ -628,7 +640,6 @@ export declare const recordClientDiagnostic: (api: string, kind: ClientDiagnosti
628
640
  * retain the complete sequence.
629
641
  */
630
642
  export declare class RecoveryCoordinator {
631
- #private;
632
643
  constructor(apiName: string, options?: RecoveryOptions, scheduler?: Partial<RecoveryScheduler>);
633
644
  get options(): ResolvedRecoveryOptions;
634
645
  /** Ends on login/logout, tenant change or API disposal, not ordinary reconnect. */
@@ -795,7 +806,6 @@ export declare interface RpcError {
795
806
  }
796
807
 
797
808
  export declare class RpcErrorBus {
798
- #private;
799
809
  /** Subscribe. Returns an unsubscribe function. */
800
810
  on(listener: RpcErrorListener): () => void;
801
811
  /** Emit. Pipeline code (useMutation / subscriptionCache) calls this. */
@@ -966,40 +976,14 @@ export declare const subscribeClientDiagnostics: (listener: () => void) => (() =
966
976
  /** Subscribe to client errors. Returns an unsubscribe fn. */
967
977
  export declare const subscribeClientErrors: (listener: ClientErrorListener) => (() => void);
968
978
 
979
+ /** Subscribe to declared refusals of traced calls. Returns an unsubscribe fn. */
980
+ export declare const subscribeClientTraceRefusals: (listener: ClientTraceRefusalListener) => () => void;
981
+
969
982
  /** Subscribe to started client traces. Returns an unsubscribe fn. */
970
983
  export declare const subscribeClientTraces: (listener: ClientTraceListener) => () => void;
971
984
 
972
985
  export declare class SubscriptionCache {
973
- private readonly entries;
974
- private readonly entriesByTable;
975
- private readonly entriesByTag;
976
- private readonly entriesByMutation;
977
- private readonly patchMemberships;
978
- private readonly entryOrder;
979
- private orderedMemberships;
980
- private nextEntryOrder;
981
- /** Standing optimistic intents, by mutation id — see `autoApply`. */
982
- private readonly intents;
983
- private readonly tableRows;
984
- private readonly anyListeners;
985
- private readonly tableListeners;
986
- private readonly refreshing;
987
- /**
988
- * Same-subject runtime replacement. A mutation may settle against the cache
989
- * it started on after React has already switched to the replacement cache.
990
- * Keep this link one-way so staging and settlement follow the visible data
991
- * without retaining an old cache from the new runtime.
992
- */
993
- private successor;
994
- private readonly inactiveTtlMs;
995
- private readonly onChangeHook;
996
- private readonly errorBus;
997
- private readonly mirror;
998
- private readonly mergeCell;
999
- private readonly apiName;
1000
- private readonly recoveryStuckMs;
1001
986
  constructor(options?: SubscriptionCacheOptions);
1002
- private diagnose;
1003
987
  /**
1004
988
  * Register a subscriber. The cache forks the underlying fiber on the
1005
989
  * first subscriber and re-uses it for the rest. Returns the snapshot
@@ -1063,31 +1047,6 @@ export declare class SubscriptionCache {
1063
1047
  * resolve briefly exposes a stale base before the server delta lands.
1064
1048
  */
1065
1049
  confirmByMutation(mutationId: string): void;
1066
- /**
1067
- * The confirmed-patch window expired: a committed write never got its
1068
- * superseding server event. Re-issue the affected subscriptions instead of
1069
- * discarding the write's preview.
1070
- *
1071
- * Three things are load-bearing, and each was a way to reintroduce the bug:
1072
- *
1073
- * - **The patch is KEPT across the resync.** `refreshAll` already
1074
- * establishes that shape ("the new base snapshot will land on top of
1075
- * them"). Clearing it here would be the revert again, wearing a longer
1076
- * word.
1077
- * - **A stub entry — no `fetch`, no `runtime` — is left ALONE.** There is
1078
- * nothing to re-issue, and the only other option is to show a base the
1079
- * client knows is stale. Keeping the patch is the honest state.
1080
- * - **It is LOUD.** The reporter found the jump only by reading minified
1081
- * source, because in the UI it is indistinguishable from "the server did
1082
- * not save it" — and that is the false trail they followed first. This
1083
- * goes to the error bus, so it reaches `voltro logs` rather than only a
1084
- * console nobody has open.
1085
- *
1086
- * No second timer is armed: this runs once per mutation, from the one
1087
- * `confirmByMutation` scheduled it, so a server that never echoes cannot put
1088
- * the client into a resync loop.
1089
- */
1090
- private resyncUnechoedMutation;
1091
1050
  /**
1092
1051
  * Auto-derive optimistic patches from a mutation's declared target(s).
1093
1052
  * Iterates every cache entry whose `source` table matches a target's
@@ -1111,10 +1070,6 @@ export declare class SubscriptionCache {
1111
1070
  * {@link SubscriptionCache.autoApply}). Carried to a same-subject
1112
1071
  * replacement cache, so a stager can tell "already staged" from "new". */
1113
1072
  hasIntent(mutationId: string): boolean;
1114
- private applyIntent;
1115
- private applyStandingIntents;
1116
- /** Drop a specific patch by id. */
1117
- private revertPatch;
1118
1073
  /**
1119
1074
  * Read the current snapshot for a key WITHOUT subscribing. If the
1120
1075
  * entry doesn't exist, returns the "empty" snapshot (data=undefined,
@@ -1161,40 +1116,6 @@ export declare class SubscriptionCache {
1161
1116
  * patches. Coalesce refreshes until that request answers or fails; never
1162
1117
  * interrupt an initial read merely because another refresh was requested. */
1163
1118
  refresh(key: ReadonlyArray<unknown>): boolean;
1164
- /* Excluded from this release type: resumeTransportFailures */
1165
- /**
1166
- * The stall watchdog for one re-issued entry: `recoveryStuckMs` after the
1167
- * re-issue with neither snapshot nor delta, the entry is reported stuck and
1168
- * its subscribers are notified.
1169
- *
1170
- * That is a finding only if the watchdog itself ran on time. A browser
1171
- * throttles timers in a hidden tab — to a one-second grid, then a one-minute
1172
- * grid — so a timer there fires whenever the tab next wakes, and it used to
1173
- * report the interval it was ARMED with as the interval waited. A delivery
1174
- * queued behind the same throttling then arrived a moment after the warning
1175
- * and the invalidation, under the same attempt: the watchdog had measured
1176
- * its own delay and called it a stall.
1177
- *
1178
- * So the watchdog compares its due time with its fire time. Late beyond the
1179
- * tolerance, or firing in a hidden tab, it does not judge: it records ONE
1180
- * `recovery-timer-late` for the attempt (with how late, and whether hidden)
1181
- * and re-arms. The first on-time fire in a visible tab decides — which gives
1182
- * a delivery `recoveryStuckMs` of unthrottled time once the tab is looked at
1183
- * again, and reports a real stall within that.
1184
- */
1185
- private armRecoveryWatchdog;
1186
- /**
1187
- * Re-issue ONE entry's subscription: interrupt the fiber, reset the base,
1188
- * re-fork through the saved `fetch`.
1189
- *
1190
- * Extracted so `refreshAll` and the confirmed-patch resync cannot disagree
1191
- * about it — and the thing they must agree on is that **optimistic patches
1192
- * survive**. For a re-auth they belong to in-flight mutations; for the resync
1193
- * they describe a write the server has already committed. Dropping them here
1194
- * would be a revert with a longer name, which is the defect the resync exists
1195
- * to remove.
1196
- */
1197
- private reissue;
1198
1119
  /**
1199
1120
  * Seed this (fresh) cache with the last-known-good rows held by the cache it
1200
1121
  * REPLACES, so a transport rebuild degrades to STALE DATA rather than to
@@ -1234,21 +1155,6 @@ export declare class SubscriptionCache {
1234
1155
  * Returns the number of entries seeded (diagnostics / tests).
1235
1156
  */
1236
1157
  seedStaleFrom(previous: SubscriptionCache): number;
1237
- private create;
1238
- private createStub;
1239
- private freshState;
1240
- private startFiber;
1241
- private sourceTables;
1242
- private addIndex;
1243
- private removeIndex;
1244
- private orderedEntries;
1245
- private indexSource;
1246
- private appendPatch;
1247
- private replacePatches;
1248
- private indexPatches;
1249
- private registerEntry;
1250
- private unindexEntry;
1251
- private invalidate;
1252
1158
  /**
1253
1159
  * Every row of `table` this cache holds — the client's local replica of the
1254
1160
  * table: the union of the rows of every entry sourced on that table ALONE
@@ -1262,12 +1168,6 @@ export declare class SubscriptionCache {
1262
1168
  subscribeTable(table: string, listener: () => void): () => void;
1263
1169
  /** Call `listener` after any entry changed. Returns the unsubscribe. */
1264
1170
  subscribeAny(listener: () => void): () => void;
1265
- private getSnapshot;
1266
- private unsubscribe;
1267
- /** Start (or restart) the inactive-TTL countdown for `entry`: unless
1268
- * something subscribes first, interrupt its fiber and drop it. Shared by
1269
- * the last-subscriber-out path and by `seedStaleFrom`'s unclaimed seeds. */
1270
- private scheduleEviction;
1271
1171
  }
1272
1172
 
1273
1173
  export declare interface SubscriptionCacheOptions {
package/dist/runtime.js CHANGED
@@ -1,16 +1,16 @@
1
- import { publishClientTrace as e, subscribeClientTraces as t } from "./traceBus.js";
2
- import { rememberRpcErrorKind as n, rpcErrorKind as r } from "./rpcErrorKind.js";
3
- import { clearClientDiagnostics as i, clientDiagnosticsSnapshot as a, recordClientDiagnostic as o, subscribeClientDiagnostics as s } from "./clientDiagnostics.js";
4
- import { stableKey as c } from "./stableKey.js";
5
- import { LoadingSubscriptionCache as l, SubscriptionCache as u, supersedesConfirmedPatches as d } from "./subscriptionCache.js";
6
- import { publishClientError as f, reportClientError as p, subscribeClientErrors as m } from "./clientErrorBus.js";
7
- import { RpcErrorBus as h } from "./rpcErrorBus.js";
8
- import { apiConnectivity as g } from "./apiConnectivity.js";
9
- import { INITIAL_RECOVERY_SNAPSHOT as _, RecoveryCoordinator as v, recoveryCoordinatorFor as y, resolveRecoveryOptions as b } from "./recoveryCoordinator.js";
10
- import { resolveByTag as x } from "./tagWalk.js";
11
- import { buildApiRuntime as S, makeProtocolOpenRecovery as C } from "./apiRuntime.js";
12
- import { startApiSupervisor as w } from "./apiSupervisor.js";
13
- import { runRpcPromise as T } from "./runRpc.js";
14
- import { isUnauthenticated as E, wireAuthRefresh as D } from "./authRefresh.js";
15
- import { DEFAULT_SERVICE_CALL_TIMEOUT_MS as O, makeServiceClient as k, serviceApi as A } from "./serviceClient.js";
16
- export { O as DEFAULT_SERVICE_CALL_TIMEOUT_MS, _ as INITIAL_RECOVERY_SNAPSHOT, l as LoadingSubscriptionCache, v as RecoveryCoordinator, h as RpcErrorBus, u as SubscriptionCache, g as apiConnectivity, S as buildApiRuntime, i as clearClientDiagnostics, a as clientDiagnosticsSnapshot, E as isUnauthenticated, C as makeProtocolOpenRecovery, k as makeServiceClient, f as publishClientError, e as publishClientTrace, o as recordClientDiagnostic, y as recoveryCoordinatorFor, n as rememberRpcErrorKind, p as reportClientError, x as resolveByTag, b as resolveRecoveryOptions, r as rpcErrorKind, T as runRpcPromise, A as serviceApi, c as stableKey, w as startApiSupervisor, s as subscribeClientDiagnostics, m as subscribeClientErrors, t as subscribeClientTraces, d as supersedesConfirmedPatches, D as wireAuthRefresh };
1
+ import { publishClientTrace as e, publishClientTraceRefusal as t, subscribeClientTraceRefusals as n, subscribeClientTraces as r } from "./traceBus.js";
2
+ import { rememberRpcErrorKind as i, rpcErrorKind as a } from "./rpcErrorKind.js";
3
+ import { clearClientDiagnostics as o, clientDiagnosticsSnapshot as s, recordClientDiagnostic as c, subscribeClientDiagnostics as l } from "./clientDiagnostics.js";
4
+ import { stableKey as u } from "./stableKey.js";
5
+ import { LoadingSubscriptionCache as d, SubscriptionCache as f, supersedesConfirmedPatches as p } from "./subscriptionCache.js";
6
+ import { publishClientError as m, reportClientError as h, subscribeClientErrors as g } from "./clientErrorBus.js";
7
+ import { RpcErrorBus as _ } from "./rpcErrorBus.js";
8
+ import { apiConnectivity as v } from "./apiConnectivity.js";
9
+ import { INITIAL_RECOVERY_SNAPSHOT as y, RecoveryCoordinator as b, recoveryCoordinatorFor as x, resolveRecoveryOptions as S } from "./recoveryCoordinator.js";
10
+ import { resolveByTag as C } from "./tagWalk.js";
11
+ import { buildApiRuntime as w, makeProtocolOpenRecovery as T } from "./apiRuntime.js";
12
+ import { startApiSupervisor as E } from "./apiSupervisor.js";
13
+ import { runRpcPromise as D } from "./runRpc.js";
14
+ import { isUnauthenticated as O, wireAuthRefresh as k } from "./authRefresh.js";
15
+ import { DEFAULT_SERVICE_CALL_TIMEOUT_MS as A, makeServiceClient as j, serviceApi as M } from "./serviceClient.js";
16
+ export { A as DEFAULT_SERVICE_CALL_TIMEOUT_MS, y as INITIAL_RECOVERY_SNAPSHOT, d as LoadingSubscriptionCache, b as RecoveryCoordinator, _ as RpcErrorBus, f as SubscriptionCache, v as apiConnectivity, w as buildApiRuntime, o as clearClientDiagnostics, s as clientDiagnosticsSnapshot, O as isUnauthenticated, T as makeProtocolOpenRecovery, j as makeServiceClient, m as publishClientError, e as publishClientTrace, t as publishClientTraceRefusal, c as recordClientDiagnostic, x as recoveryCoordinatorFor, i as rememberRpcErrorKind, h as reportClientError, C as resolveByTag, S as resolveRecoveryOptions, a as rpcErrorKind, D as runRpcPromise, M as serviceApi, u as stableKey, E as startApiSupervisor, l as subscribeClientDiagnostics, g as subscribeClientErrors, n as subscribeClientTraceRefusals, r as subscribeClientTraces, p as supersedesConfirmedPatches, k as wireAuthRefresh };
package/dist/traceBus.js CHANGED
@@ -5,5 +5,11 @@ var e = /* @__PURE__ */ new Set(), t = (t) => {
5
5
  } catch {}
6
6
  }, n = (t) => (e.add(t), () => {
7
7
  e.delete(t);
8
+ }), r = /* @__PURE__ */ new Set(), i = (e) => {
9
+ for (let t of r) try {
10
+ t(e);
11
+ } catch {}
12
+ }, a = (e) => (r.add(e), () => {
13
+ r.delete(e);
8
14
  });
9
- export { t as publishClientTrace, n as subscribeClientTraces };
15
+ export { t as publishClientTrace, i as publishClientTraceRefusal, a as subscribeClientTraceRefusals, n as subscribeClientTraces };
@@ -0,0 +1,7 @@
1
+ // src/unknownRpcTag.ts
2
+ var e = /* @__PURE__ */ new Set(), t = (t, n, r, i) => {
3
+ if (process.env.NODE_ENV === "production" || Object.hasOwn(i, r) || Object.keys(i).length === 0) return;
4
+ let a = n + "\0" + r;
5
+ e.has(a) || (e.add(a), console.error(`[@voltro/client] ${t}('${n}', '${r}'): '${r}' is not in the client group of api '${n}', so every call fails before it reaches the server. Check the spelling; for a plugin route, the plugin must list it in \`rpcClientDescriptors\` so the codegen puts it into the client group.`));
6
+ };
7
+ export { t as reportUnknownRpcTag };
@@ -0,0 +1,83 @@
1
+ // src/uploadBytes.ts
2
+ var e = () => new DOMException("upload aborted", "AbortError"), t = (t) => new Promise((n, r) => {
3
+ if (t.signal.aborted) {
4
+ r(e());
5
+ return;
6
+ }
7
+ let i = new XMLHttpRequest(), a = !1, o = (e) => {
8
+ a || (a = !0, t.signal.removeEventListener("abort", s), i.onload = null, i.onerror = null, i.onabort = null, i.upload.onprogress = null, e());
9
+ }, s = () => {
10
+ a || (i.abort(), o(() => r(e())));
11
+ };
12
+ try {
13
+ i.open(t.method, t.url), t.contentType !== void 0 && i.setRequestHeader("content-type", t.contentType), i.upload.onprogress = (e) => {
14
+ !a && !t.signal.aborted && e.lengthComputable && t.onProgress(e.loaded / e.total);
15
+ }, i.onload = () => o(() => {
16
+ try {
17
+ if (i.status < 200 || i.status >= 300) throw Error(`${t.failure} (${i.status}): ${i.responseText || i.statusText}`.trim());
18
+ n(t.decode(i));
19
+ } catch (e) {
20
+ r(e);
21
+ }
22
+ }), i.onerror = () => o(() => r(Error(t.network))), i.onabort = () => o(() => r(e())), t.signal.addEventListener("abort", s, { once: !0 }), t.signal.aborted ? s() : i.send(t.body);
23
+ } catch (e) {
24
+ o(() => r(e));
25
+ }
26
+ }), n = (e, n, r, i) => t({
27
+ method: "PUT",
28
+ url: e,
29
+ body: n,
30
+ onProgress: r,
31
+ signal: i,
32
+ failure: "multipart part failed",
33
+ network: "multipart part: network error",
34
+ decode: (e) => {
35
+ let t = e.getResponseHeader("ETag") ?? e.getResponseHeader("etag");
36
+ if (!t) throw Error("multipart part: response carried no ETag (the bucket CORS must expose the ETag header)");
37
+ return t;
38
+ }
39
+ }), r = (e, n, r, i, a, o) => t({
40
+ method: "POST",
41
+ url: e,
42
+ contentType: n,
43
+ body: r,
44
+ onProgress: i,
45
+ signal: a,
46
+ failure: "resumable chunk failed",
47
+ network: "resumable chunk: network error",
48
+ decode: (e) => {
49
+ if (!o) return null;
50
+ try {
51
+ return JSON.parse(e.responseText);
52
+ } catch {
53
+ throw Error("resumable upload: malformed final response");
54
+ }
55
+ }
56
+ }), i = (e, n, r, i, a) => t({
57
+ method: "PUT",
58
+ url: e,
59
+ contentType: n,
60
+ body: r,
61
+ onProgress: i,
62
+ signal: a,
63
+ failure: "direct upload failed",
64
+ network: "direct upload: network error",
65
+ decode: () => void 0
66
+ }), a = (e, n, r, i, a) => t({
67
+ method: "POST",
68
+ url: e,
69
+ contentType: n,
70
+ body: r,
71
+ onProgress: i,
72
+ signal: a,
73
+ failure: "storage upload failed",
74
+ network: "storage upload: network error",
75
+ decode: (e) => {
76
+ try {
77
+ return JSON.parse(e.responseText);
78
+ } catch {
79
+ throw Error("storage upload: malformed response");
80
+ }
81
+ }
82
+ });
83
+ export { a as postBytes, r as postChunk, i as putBytesRaw, n as putPart };
@@ -0,0 +1,153 @@
1
+ import { rpcErrorKind as e } from "./rpcErrorKind.js";
2
+ import { useFrameworkApi as t } from "./runtimeContext.js";
3
+ import { resolveByTag as n } from "./tagWalk.js";
4
+ import { deferRpcMethod as r, runRpcPromise as i } from "./runRpc.js";
5
+ import { ConnectionPrerequisiteInvalidated as a } from "./connectionPrerequisite.js";
6
+ import { awaitReadyApi as o, bindResolvedRpcInvocationOwner as s } from "./awaitResolvedApi.js";
7
+ import { useRpcInvocationOwner as c } from "./useRpcInvocationOwner.js";
8
+ import { waitForInvocation as l } from "./invocationWait.js";
9
+ import { useRpcCaller as u } from "./useRpcCaller.js";
10
+ import { createUploadProgress as d } from "./uploadProgress.js";
11
+ import { useCallback as f, useEffect as p, useMemo as m, useRef as h, useState as g } from "react";
12
+ // src/uploadClient.ts
13
+ var _ = () => new DOMException("upload aborted", "AbortError"), v = (e, t, n) => {
14
+ if (!Number.isSafeInteger(e) || e < t) throw RangeError(`useUpload: ${n} must be a finite integer >= ${t}.`);
15
+ return e;
16
+ }, y = (y) => {
17
+ let b = t(y), x = h(b);
18
+ x.current = b;
19
+ let { owner: S, current: C, assertCurrent: w } = c(x, y, "storage.upload"), T = u(y), E = m(() => ({
20
+ epoch: 0,
21
+ batches: /* @__PURE__ */ new Set(),
22
+ count: 0,
23
+ settledProgress: 0,
24
+ failed: !1,
25
+ error: void 0
26
+ }), [S]), [D, O] = g(() => ({
27
+ owner: S,
28
+ epoch: 0,
29
+ status: "idle",
30
+ progress: 0,
31
+ error: void 0
32
+ }));
33
+ p(() => () => {
34
+ for (let e of E.batches) e.controller.abort();
35
+ E.batches.clear(), E.count = 0, E.settledProgress = 0, E.failed = !1, E.error = void 0, O((e) => e.owner === S ? {
36
+ owner: S,
37
+ epoch: E.epoch,
38
+ status: "idle",
39
+ progress: 0,
40
+ error: void 0
41
+ } : e);
42
+ }, [E, S]);
43
+ let k = f(() => {
44
+ if (!C()) return;
45
+ let e = [...E.batches], t = e.length > 0, n = E.count ? (E.settledProgress + e.reduce((e, t) => e + t.progress * t.count, 0)) / E.count : 0;
46
+ O({
47
+ owner: S,
48
+ epoch: E.epoch,
49
+ status: t ? "uploading" : E.failed ? "error" : "success",
50
+ progress: n,
51
+ error: E.error
52
+ });
53
+ }, [
54
+ C,
55
+ E,
56
+ S
57
+ ]), A = f(() => {
58
+ if (C()) for (let e of E.batches) e.finished || e.controller.abort();
59
+ }, [C, E]), j = f(() => {
60
+ if (C()) {
61
+ E.epoch++;
62
+ for (let e of E.batches) e.controller.abort();
63
+ E.batches.clear(), E.count = 0, E.settledProgress = 0, E.failed = !1, E.error = void 0, O({
64
+ owner: S,
65
+ epoch: E.epoch,
66
+ status: "idle",
67
+ progress: 0,
68
+ error: void 0
69
+ });
70
+ }
71
+ }, [
72
+ C,
73
+ E,
74
+ S
75
+ ]), M = f(async (t, c, u) => {
76
+ w();
77
+ let f = v(c.retries ?? 1, 0, "retries"), p = v(c.concurrency ?? 3, 1, "concurrency");
78
+ if (!t.length) return [];
79
+ if (t.length > 1 && c.operationId !== void 0) throw Error("useUpload: one operationId identifies one file; upload files with separate operation identities.");
80
+ E.batches.size || (E.count = 0, E.settledProgress = 0, E.failed = !1, E.error = void 0);
81
+ let m = {
82
+ controller: new AbortController(),
83
+ epoch: E.epoch,
84
+ count: t.length,
85
+ progress: 0,
86
+ finished: !1
87
+ };
88
+ E.batches.add(m), E.count += t.length, k();
89
+ let h, g = x.current.inspectBaseUrl, b = x.current.errorBus, D = () => m.controller.abort(), O = () => {
90
+ h !== S.subject && (h?.removeEventListener("abort", D), h = S.subject, h.addEventListener("abort", D, { once: !0 })), h.aborted && D();
91
+ }, A = () => {
92
+ if (w(), m.epoch !== E.epoch || m.controller.signal.aborted) throw _();
93
+ }, j = () => C() && m.epoch === E.epoch && E.batches.has(m), M = (e) => l(e, m.controller.signal, A), N = {
94
+ signal: m.controller.signal,
95
+ assertCurrent: A,
96
+ cleanup: (e, t) => T.call(e, t),
97
+ url: (e) => /^https?:\/\//.test(e) ? e : `${g}${e}`,
98
+ rpc: async (e, t) => {
99
+ A();
100
+ let a = await o(x, y, e, m.controller.signal);
101
+ s(S, a), O(), A(), g = a.inspectBaseUrl, b = a.errorBus;
102
+ let c = r(() => (A(), n(a.client, e)(t))), l = await M(i(a.runtime, c));
103
+ return A(), l;
104
+ }
105
+ };
106
+ O();
107
+ let P = d(t.length), F = Array(t.length), I = 0, L = async () => {
108
+ for (;;) {
109
+ A();
110
+ let e = I++;
111
+ if (e >= t.length) return;
112
+ F[e] = await u(t[e], {
113
+ ...c,
114
+ retries: f
115
+ }, N, (t) => {
116
+ !j() || m.finished || m.controller.signal.aborted || (m.progress = P(e, Number.isFinite(t) ? Math.min(1, Math.max(0, t)) : 0), k());
117
+ }), A(), m.progress = P(e, 1), k();
118
+ }
119
+ };
120
+ try {
121
+ return A(), await M(Promise.all(Array.from({ length: Math.min(p, t.length) }, () => L()))), A(), m.progress = 1, m.finished = !0, E.settledProgress += m.count, E.batches.delete(m), k(), F;
122
+ } catch (t) {
123
+ let n = C() ? m.epoch !== E.epoch || m.controller.signal.aborted ? _() : t : new a("inactive"), r = j();
124
+ throw m.controller.abort(), m.finished = !0, E.batches.delete(m), r && (E.settledProgress += m.progress * m.count, E.failed = !0, E.error = n, k(), n instanceof DOMException && n.name === "AbortError" || b.emit({
125
+ source: "action",
126
+ tag: c.mintTag ?? "storage.mintUploadTicket",
127
+ error: n,
128
+ kind: e(n, "unknown"),
129
+ outcome: e(n, "unknown") === "transport" ? "unknown" : "not-applicable"
130
+ })), n;
131
+ } finally {
132
+ h?.removeEventListener("abort", D);
133
+ }
134
+ }, [
135
+ y,
136
+ w,
137
+ T,
138
+ C,
139
+ E,
140
+ S,
141
+ k
142
+ ]), N = D.owner === S && D.epoch === E.epoch ? D : void 0;
143
+ return {
144
+ execute: M,
145
+ assertCurrent: w,
146
+ cancel: A,
147
+ reset: j,
148
+ status: N?.status ?? "idle",
149
+ progress: N?.progress ?? 0,
150
+ error: N?.error
151
+ };
152
+ };
153
+ export { y as useUploadClient };