@gusto/baerly-storage 0.5.0 → 0.7.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/README.md +47 -124
- package/dist/API.md +161 -511
- package/dist/CHANGELOG.md +1148 -307
- package/dist/RECIPES.md +398 -80
- package/dist/THIRD-PARTY-LICENSES.txt +5 -26
- package/dist/{app-config-DyiFK3_k.d.ts → app-config-C6qW7m8S.d.ts} +119 -111
- package/dist/app-config.d.ts +31 -1
- package/dist/app-config.js +1 -2
- package/dist/app-config.js.map +1 -1
- package/dist/auth.d.ts +33 -28
- package/dist/auth.js +549 -985
- package/dist/auth.js.map +1 -1
- package/dist/baerly.js +130 -138
- package/dist/baerly.js.map +1 -1
- package/dist/baerly.spec.json +97 -22
- package/dist/capacity-warning-header-BlVopyiI.js +16 -0
- package/dist/capacity-warning-header-BlVopyiI.js.map +1 -0
- package/dist/{client-Fe8CwB73.d.ts → client-CHQTXpef.d.ts} +121 -36
- package/dist/client-react.d.ts +67 -20
- package/dist/client-react.js +240 -54
- package/dist/client-react.js.map +1 -1
- package/dist/client.d.ts +5 -4
- package/dist/client.js +51 -16
- package/dist/client.js.map +1 -1
- package/dist/{cloudflare-DzKBrUlg.js → cloudflare-CKHYXccw.js} +504 -124
- package/dist/cloudflare-CKHYXccw.js.map +1 -0
- package/dist/cloudflare.d.ts +106 -71
- package/dist/cloudflare.js +334 -271
- package/dist/cloudflare.js.map +1 -1
- package/dist/code-resolution-CL_7L0wS.js +22 -0
- package/dist/code-resolution-CL_7L0wS.js.map +1 -0
- package/dist/collection-api-DbyhLAY8.d.ts +1001 -0
- package/dist/config-DEzInG6M.js +4035 -0
- package/dist/config-DEzInG6M.js.map +1 -0
- package/dist/constants-D3GSH3tc.js +469 -0
- package/dist/constants-D3GSH3tc.js.map +1 -0
- package/dist/{context-DRZ3tZ5l.js → context-rlpSnHFA.js} +17 -17
- package/dist/context-rlpSnHFA.js.map +1 -0
- package/dist/cost-B52llVDx.js +330 -0
- package/dist/cost-B52llVDx.js.map +1 -0
- package/dist/{current-json-C6nhPOm1.js → current-json-CC6lE4Aj.js} +115 -32
- package/dist/current-json-CC6lE4Aj.js.map +1 -0
- package/dist/db-plFUNTSF.d.ts +130 -0
- package/dist/db-read-seams-BSs0m1z1.js +3261 -0
- package/dist/db-read-seams-BSs0m1z1.js.map +1 -0
- package/dist/{deploy-DonTr-CV.js → deploy-Obj4nE-Z.js} +12 -16
- package/dist/deploy-Obj4nE-Z.js.map +1 -0
- package/dist/{dev-banner-CWHIk8tH.d.ts → dev-banner-B5AUHmu1.d.ts} +1 -4
- package/dist/dev-landing-BI5UdmOb.d.ts +32 -0
- package/dist/dev-landing-CD-si4dW.js +50 -0
- package/dist/dev-landing-CD-si4dW.js.map +1 -0
- package/dist/dev-vite.d.ts +38 -39
- package/dist/dev-vite.js +67 -36
- package/dist/dev-vite.js.map +1 -1
- package/dist/dev.d.ts +3 -2
- package/dist/dev.js +2 -1
- package/dist/doctor-BA0i-YAN.js +270 -0
- package/dist/doctor-BA0i-YAN.js.map +1 -0
- package/dist/dump-D1vX8ozg.js +133 -0
- package/dist/dump-D1vX8ozg.js.map +1 -0
- package/dist/errors-7Rk1HGCE.js +160 -0
- package/dist/errors-7Rk1HGCE.js.map +1 -0
- package/dist/{validate-DtljsCh1.js → export-BVL2EvYE.js} +409 -19
- package/dist/export-BVL2EvYE.js.map +1 -0
- package/dist/fsck-BWkPgov4.js +145 -0
- package/dist/fsck-BWkPgov4.js.map +1 -0
- package/dist/gcs-admin-Dso1HWQj.d.ts +127 -0
- package/dist/gcs.d.ts +30 -0
- package/dist/gcs.js +1 -0
- package/dist/goog4-signer-CeLIABoE.js +331 -0
- package/dist/goog4-signer-CeLIABoE.js.map +1 -0
- package/dist/{http-DGd5tbNs.js → http-Z5rZyYMX.js} +898 -271
- package/dist/http-Z5rZyYMX.js.map +1 -0
- package/dist/http-transport-DNUM8kU-.js +1299 -0
- package/dist/http-transport-DNUM8kU-.js.map +1 -0
- package/dist/http.d.ts +366 -294
- package/dist/http.js +2 -2
- package/dist/index-JJrIu1pO.d.ts +135 -0
- package/dist/index-LEgHN0qJ.d.ts +50 -0
- package/dist/{index-CuA9Mi3K.d.ts → index-RiEYj8t0.d.ts} +291 -78
- package/dist/index.d.ts +27 -6
- package/dist/index.js +3 -5
- package/dist/inspect-BTsVYZKd.js +196 -0
- package/dist/inspect-BTsVYZKd.js.map +1 -0
- package/dist/{key-Di6yyxFu.js → key-C4FPZ9Io.js} +3 -4
- package/dist/{key-Di6yyxFu.js.map → key-C4FPZ9Io.js.map} +1 -1
- package/dist/ledger-Dj_bGgo0.js +192 -0
- package/dist/ledger-Dj_bGgo0.js.map +1 -0
- package/dist/legacy-names-DgZBtgOh.js +47 -0
- package/dist/legacy-names-DgZBtgOh.js.map +1 -0
- package/dist/log-C9W15Dfo.d.ts +94 -0
- package/dist/log-tail-DWJbneBF.js +142 -0
- package/dist/log-tail-DWJbneBF.js.map +1 -0
- package/dist/log-walk-C-vA-WGJ.js +111 -0
- package/dist/log-walk-C-vA-WGJ.js.map +1 -0
- package/dist/maintenance-Dd-Yakqj.js +1709 -0
- package/dist/maintenance-Dd-Yakqj.js.map +1 -0
- package/dist/maintenance-DevB6z4e.js +2237 -0
- package/dist/maintenance-DevB6z4e.js.map +1 -0
- package/dist/maintenance.d.ts +100 -3
- package/dist/maintenance.js +1 -3
- package/dist/node.d.ts +130 -142
- package/dist/node.js +4 -3
- package/dist/{observability-BmflLCdF.js → observability-C-ISCCLE.js} +1275 -332
- package/dist/observability-C-ISCCLE.js.map +1 -0
- package/dist/observability.d.ts +27 -3
- package/dist/observability.js +3 -3
- package/dist/path-segment-DBXG26PW.js +363 -0
- package/dist/path-segment-DBXG26PW.js.map +1 -0
- package/dist/{plan-a7PJHBCy.js → plan-BvQbaNMe.js} +19 -11
- package/dist/plan-BvQbaNMe.js.map +1 -0
- package/dist/request-CRWiTrza.js +272 -0
- package/dist/request-CRWiTrza.js.map +1 -0
- package/dist/restore-U6Im8V1V.js +1467 -0
- package/dist/restore-U6Im8V1V.js.map +1 -0
- package/dist/retry-OBtLB2GC.js +126 -0
- package/dist/retry-OBtLB2GC.js.map +1 -0
- package/dist/rolldown-runtime-D3KUYPsf.js +12 -0
- package/dist/{runtime-spec-Dsw2-n8S.js → runtime-spec-B5mg3pHF.js} +189 -28
- package/dist/runtime-spec-B5mg3pHF.js.map +1 -0
- package/dist/{s3-http-B-z8th6O.d.ts → s3-http-DBC_wiCL.d.ts} +18 -10
- package/dist/s3.d.ts +20 -7
- package/dist/s3.js +4 -5
- package/dist/s3.js.map +1 -1
- package/dist/sha256-4FfGQNPw.js +22 -0
- package/dist/sha256-4FfGQNPw.js.map +1 -0
- package/dist/{shared-secret-DgEicd3x.js → shared-secret-Vkur-8r0.js} +27 -15
- package/dist/shared-secret-Vkur-8r0.js.map +1 -0
- package/dist/sigv4-sign-5IUflUD_.js +507 -0
- package/dist/sigv4-sign-5IUflUD_.js.map +1 -0
- package/dist/snapshot-CknzkDM0.js +148 -0
- package/dist/snapshot-CknzkDM0.js.map +1 -0
- package/dist/{src-BL_JoPTn.js → src-Actga-bO.js} +1004 -378
- package/dist/src-Actga-bO.js.map +1 -0
- package/dist/src-D0MQfvOp.js +812 -0
- package/dist/src-D0MQfvOp.js.map +1 -0
- package/dist/src-Dr9uo3dc.js +501 -0
- package/dist/src-Dr9uo3dc.js.map +1 -0
- package/dist/{subcommand-DoDA-K7d.js → subcommand-BLoF66dG.js} +89 -16
- package/dist/subcommand-BLoF66dG.js.map +1 -0
- package/dist/{time-DUqvFMHq.js → time-DRxTP9iv.js} +15 -34
- package/dist/time-DRxTP9iv.js.map +1 -0
- package/dist/types-suVbsEWS.d.ts +116 -0
- package/dist/{usage-DBV1eQHC.js → usage-CPzVhrQr.js} +40 -45
- package/dist/usage-CPzVhrQr.js.map +1 -0
- package/dist/uuid-BuT_c404.js +333 -0
- package/dist/uuid-BuT_c404.js.map +1 -0
- package/dist/verifier-Bmlmndzo.d.ts +95 -0
- package/dist/{wire-izfGZDvr.js → wire-DndvKU-K.js} +2 -3
- package/dist/wire-DndvKU-K.js.map +1 -0
- package/package.json +96 -69
- package/dist/aws4fetch.esm-p7eEzLCs.js +0 -1702
- package/dist/aws4fetch.esm-p7eEzLCs.js.map +0 -1
- package/dist/bytes-BXdamO3L.js +0 -11
- package/dist/bytes-BXdamO3L.js.map +0 -1
- package/dist/cloudflare-DzKBrUlg.js.map +0 -1
- package/dist/config-1tv0-Yzm.js +0 -2693
- package/dist/config-1tv0-Yzm.js.map +0 -1
- package/dist/constants-CfeMWQWk.js +0 -222
- package/dist/constants-CfeMWQWk.js.map +0 -1
- package/dist/context-DRZ3tZ5l.js.map +0 -1
- package/dist/cost-DSMIVqzL.js +0 -203
- package/dist/cost-DSMIVqzL.js.map +0 -1
- package/dist/current-json-C6nhPOm1.js.map +0 -1
- package/dist/db-DsPkOVEH.d.ts +0 -254
- package/dist/deploy-DonTr-CV.js.map +0 -1
- package/dist/doctor-DSIyCDg_.js +0 -346
- package/dist/doctor-DSIyCDg_.js.map +0 -1
- package/dist/dump-Bh5k26VQ.js +0 -94
- package/dist/dump-Bh5k26VQ.js.map +0 -1
- package/dist/errors-Dfa3p78c.js +0 -78
- package/dist/errors-Dfa3p78c.js.map +0 -1
- package/dist/export-DtF5tDIM.js +0 -401
- package/dist/export-DtF5tDIM.js.map +0 -1
- package/dist/fsck-D_djMO5D.js +0 -279
- package/dist/fsck-D_djMO5D.js.map +0 -1
- package/dist/http-DGd5tbNs.js.map +0 -1
- package/dist/index-0rZcMBwy.d.ts +0 -115
- package/dist/index-BNRh23K9.d.ts +0 -162
- package/dist/index-BYk9oCNf.d.ts +0 -1112
- package/dist/indexes-Dn9hbGQG.d.ts +0 -22
- package/dist/inspect-6WZ-pC7-.js +0 -133
- package/dist/inspect-6WZ-pC7-.js.map +0 -1
- package/dist/log-tail-D98U1JBo.js +0 -522
- package/dist/log-tail-D98U1JBo.js.map +0 -1
- package/dist/maintenance-B4Dki6Ig.js +0 -2157
- package/dist/maintenance-B4Dki6Ig.js.map +0 -1
- package/dist/maintenance-B_e0T99L.d.ts +0 -537
- package/dist/maintenance-C7coQp4c.js +0 -1418
- package/dist/maintenance-C7coQp4c.js.map +0 -1
- package/dist/normalize-rjnZLwS4.js +0 -133
- package/dist/normalize-rjnZLwS4.js.map +0 -1
- package/dist/observability-BmflLCdF.js.map +0 -1
- package/dist/plan-a7PJHBCy.js.map +0 -1
- package/dist/query-rAtXNQQB.js +0 -1773
- package/dist/query-rAtXNQQB.js.map +0 -1
- package/dist/rebuild-index-BVzQSZlm.js +0 -81
- package/dist/rebuild-index-BVzQSZlm.js.map +0 -1
- package/dist/request-u0M51mhJ.js +0 -72
- package/dist/request-u0M51mhJ.js.map +0 -1
- package/dist/restore-R-4rbciV.js +0 -778
- package/dist/restore-R-4rbciV.js.map +0 -1
- package/dist/rolldown-runtime-EAsCxrDo.js +0 -14
- package/dist/runtime-spec-Dsw2-n8S.js.map +0 -1
- package/dist/shared-secret-DgEicd3x.js.map +0 -1
- package/dist/src-BL_JoPTn.js.map +0 -1
- package/dist/src-CYHFDrKz.js +0 -536
- package/dist/src-CYHFDrKz.js.map +0 -1
- package/dist/src-DYZ4H1aF.js +0 -392
- package/dist/src-DYZ4H1aF.js.map +0 -1
- package/dist/subcommand-DoDA-K7d.js.map +0 -1
- package/dist/time-DUqvFMHq.js.map +0 -1
- package/dist/usage-DBV1eQHC.js.map +0 -1
- package/dist/validate-DtljsCh1.js.map +0 -1
- package/dist/wire-izfGZDvr.js.map +0 -1
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
import { t as CAPACITY_WARNING_HEADER } from "./capacity-warning-header-BlVopyiI.js";
|
|
2
|
+
import { n as isBaerlyErrorCode, t as BaerlyError } from "./errors-7Rk1HGCE.js";
|
|
3
|
+
// packages/client/src/internal/context.ts
|
|
4
|
+
/**
|
|
5
|
+
* Symbol-keyed slot on every `BaerlyClient` carrying the internal
|
|
6
|
+
* `RequestContext`. Lets internals (e.g. the React
|
|
7
|
+
* `subscription-pool`) reach the same fetcher / headers resolution
|
|
8
|
+
* the typed API uses, without widening the public `BaerlyClient`
|
|
9
|
+
* surface.
|
|
10
|
+
*
|
|
11
|
+
* Symbol is module-scoped — users cannot import it from package
|
|
12
|
+
* internals, so the slot is invisible outside this package.
|
|
13
|
+
*/
|
|
14
|
+
const CLIENT_CONTEXT = Symbol("baerly.client.context");
|
|
15
|
+
/**
|
|
16
|
+
* Returns the internal `RequestContext` stashed on `client` by
|
|
17
|
+
* `createBaerlyClient`. Throws if called with a client not produced
|
|
18
|
+
* by `createBaerlyClient` (e.g. a test stub) — that is the right
|
|
19
|
+
* signal for callers, who in production have no other way to obtain
|
|
20
|
+
* a `BaerlyClient` instance.
|
|
21
|
+
*/
|
|
22
|
+
const getClientContext = (client) => {
|
|
23
|
+
const ctx = client[CLIENT_CONTEXT];
|
|
24
|
+
if (ctx === void 0) throw new Error("getClientContext: client was not produced by createBaerlyClient (missing internal context slot)");
|
|
25
|
+
return ctx;
|
|
26
|
+
};
|
|
27
|
+
/** Slot holding the factory behind {@link withSignal}. */
|
|
28
|
+
const CLIENT_SCOPE = Symbol("baerly.client.scope");
|
|
29
|
+
/**
|
|
30
|
+
* A view of `client` whose every request is also cancelled by `signal`.
|
|
31
|
+
* The React subscription pool runs a query's callback against this view
|
|
32
|
+
* so superseding or unmounting the query aborts its in-flight GET and
|
|
33
|
+
* any retry wait, without the callback threading a signal itself.
|
|
34
|
+
*/
|
|
35
|
+
const withSignal = (client, signal) => client[CLIENT_SCOPE](signal);
|
|
36
|
+
/**
|
|
37
|
+
* Upper bound, in milliseconds, on one jittered backoff, and the
|
|
38
|
+
* ceiling on a server `Retry-After` the client will wait out. A hint
|
|
39
|
+
* above it is not honoured by clamping (the retry would arrive early
|
|
40
|
+
* and likely fail again); the GET fails as it would without retry, so
|
|
41
|
+
* a hostile or misconfigured proxy cannot park a caller.
|
|
42
|
+
*/
|
|
43
|
+
const REQUEST_RETRY_MAX_DELAY_MILLIS = 1e4;
|
|
44
|
+
/**
|
|
45
|
+
* Longest wait, in milliseconds, the client honours for one
|
|
46
|
+
* `MaintenancePending` retry hint (`Retry-After`, or `error.retryAfter`).
|
|
47
|
+
* As with {@link REQUEST_RETRY_MAX_DELAY_MILLIS}, a larger hint ends the
|
|
48
|
+
* retries rather than being clamped, so a hostile or misconfigured server
|
|
49
|
+
* cannot park a caller. The React subscription pool, which never gives
|
|
50
|
+
* up, clamps its wait to this instead.
|
|
51
|
+
*/
|
|
52
|
+
const MAINTENANCE_PENDING_CLIENT_MAX_WAIT_MILLIS = 1e4;
|
|
53
|
+
/**
|
|
54
|
+
* Parse a `Retry-After` header (RFC 9110 §10.2.3: delta-seconds or an
|
|
55
|
+
* HTTP-date) into milliseconds to wait. `undefined` when absent or
|
|
56
|
+
* unparseable; a past date or `0` is `0`.
|
|
57
|
+
*/
|
|
58
|
+
const parseRetryAfterMillis = (value, now = Date.now()) => {
|
|
59
|
+
const text = value?.trim();
|
|
60
|
+
if (text === void 0 || text === "") return;
|
|
61
|
+
if (/^\d+$/.test(text)) return Number(text) * 1e3;
|
|
62
|
+
const at = /[a-z]/i.test(text) ? Date.parse(text) : NaN;
|
|
63
|
+
return Number.isNaN(at) ? void 0 : Math.max(0, at - now);
|
|
64
|
+
};
|
|
65
|
+
/**
|
|
66
|
+
* Sleep `ms`, rejecting with `signal.reason` the moment `signal` aborts.
|
|
67
|
+
* Local rather than `@baerly/protocol`'s `delay`: importing that pulls
|
|
68
|
+
* `time.ts` and its key-encoding closure into the browser client bundle.
|
|
69
|
+
*/
|
|
70
|
+
const sleep = (ms, signal) => new Promise((resolve, reject) => {
|
|
71
|
+
if (signal?.aborted === true) {
|
|
72
|
+
reject(signal.reason);
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
const timer = setTimeout(() => {
|
|
76
|
+
signal?.removeEventListener("abort", onAbort);
|
|
77
|
+
resolve();
|
|
78
|
+
}, ms);
|
|
79
|
+
const onAbort = () => {
|
|
80
|
+
clearTimeout(timer);
|
|
81
|
+
reject(signal?.reason);
|
|
82
|
+
};
|
|
83
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
84
|
+
});
|
|
85
|
+
/** Jittered exponential wait before retry `retryIndex` (0-based). */
|
|
86
|
+
const backoffMillis = (retryIndex) => Math.random() * Math.min(REQUEST_RETRY_MAX_DELAY_MILLIS, 250 * 2 ** retryIndex);
|
|
87
|
+
// packages/client/src/request.ts
|
|
88
|
+
/**
|
|
89
|
+
* Hand a successful response's capacity warning to `ctx.onWarning`. The
|
|
90
|
+
* callback is the app's code: whatever it throws, or an async callback's
|
|
91
|
+
* rejection, is swallowed, so it can never fail a committed write.
|
|
92
|
+
*/
|
|
93
|
+
const reportWarning = (ctx, opts, res) => {
|
|
94
|
+
const message = res.headers.get(CAPACITY_WARNING_HEADER);
|
|
95
|
+
if (ctx.onWarning === void 0 || !message) return;
|
|
96
|
+
try {
|
|
97
|
+
Promise.resolve(ctx.onWarning({
|
|
98
|
+
code: "CapacityWarning",
|
|
99
|
+
message,
|
|
100
|
+
method: opts.method,
|
|
101
|
+
path: opts.path
|
|
102
|
+
})).catch(() => {});
|
|
103
|
+
} catch {}
|
|
104
|
+
};
|
|
105
|
+
const parseSuccessfulJson = async (res, opts) => {
|
|
106
|
+
try {
|
|
107
|
+
return await res.json();
|
|
108
|
+
} catch (error) {
|
|
109
|
+
throw new BaerlyError("InvalidResponse", `Response to ${opts.method} ${opts.path} was not valid JSON`, {
|
|
110
|
+
cause: error,
|
|
111
|
+
status: res.status
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
const isAbortError = (error) => typeof error === "object" && error !== null && error.name === "AbortError";
|
|
116
|
+
/**
|
|
117
|
+
* Decode a non-ok response into the error `request` throws, plus whether
|
|
118
|
+
* the server itself produced it (`enveloped`).
|
|
119
|
+
*
|
|
120
|
+
* No envelope means the response came from something between the
|
|
121
|
+
* caller and the server — a load balancer, CDN, rate limiter, or
|
|
122
|
+
* service mesh — so the server's own failure class is unavailable and
|
|
123
|
+
* we infer one from the status. 5xx, 408 Request Timeout and 429 Too
|
|
124
|
+
* Many Requests are transient conditions that clear on their own, and
|
|
125
|
+
* `NetworkError` is the only synthesized code whose `retriable` says
|
|
126
|
+
* so. `Internal` does not: the React subscription pool treats a
|
|
127
|
+
* non-retriable error as permanently terminal, so labelling a
|
|
128
|
+
* rolling-deploy 502 or an edge 429 `Internal` would park every live
|
|
129
|
+
* query on a dead poll until the user remounted. Any other 4xx without
|
|
130
|
+
* an envelope is a caller or routing fault that retrying cannot clear,
|
|
131
|
+
* so it stays `Internal`.
|
|
132
|
+
*
|
|
133
|
+
* A code this build doesn't know (minted by a newer server, or
|
|
134
|
+
* `Conflict` from an older one) gets the same status-derived code, so
|
|
135
|
+
* a newer server's 503 backpressure keeps a subscription reconnecting
|
|
136
|
+
* and `code` never holds a string outside `BaerlyErrorCode`. Only the
|
|
137
|
+
* message carries over: `resolution`, `issues` and `_id` belong to the
|
|
138
|
+
* undecoded code and would contradict the synthesized one, so the
|
|
139
|
+
* whole wire error rides on `cause` instead.
|
|
140
|
+
*
|
|
141
|
+
* A `MaintenancePending` error's `retryAfter` is the longer of the
|
|
142
|
+
* envelope's `retryAfter` and the `Retry-After` header (`hintMillis`), in
|
|
143
|
+
* seconds, so a caller that sees only the error (the React subscription
|
|
144
|
+
* pool) still honours the header.
|
|
145
|
+
*/
|
|
146
|
+
const decodeFailure = async (res, hintMillis) => {
|
|
147
|
+
let envelope;
|
|
148
|
+
try {
|
|
149
|
+
envelope = await res.json();
|
|
150
|
+
} catch {}
|
|
151
|
+
const wire = envelope?.error;
|
|
152
|
+
const wireCode = wire?.code;
|
|
153
|
+
if (wire !== void 0 && isBaerlyErrorCode(wireCode)) {
|
|
154
|
+
const wireAfter = wire.retryAfter;
|
|
155
|
+
const hints = [...typeof wireAfter === "number" && wireAfter >= 0 ? [wireAfter] : [], ...hintMillis === void 0 ? [] : [hintMillis / 1e3]];
|
|
156
|
+
return {
|
|
157
|
+
enveloped: true,
|
|
158
|
+
error: new BaerlyError(wireCode, wire.message ?? `HTTP ${res.status}`, {
|
|
159
|
+
issues: wire.issues,
|
|
160
|
+
status: res.status,
|
|
161
|
+
resolution: wire.resolution,
|
|
162
|
+
_id: wire._id,
|
|
163
|
+
retryAfter: wireCode === "MaintenancePending" && hints.length > 0 ? Math.max(...hints) : void 0
|
|
164
|
+
})
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
const transient = res.status >= 500 || res.status === 408 || res.status === 429;
|
|
168
|
+
return {
|
|
169
|
+
enveloped: typeof wire === "object" && wire !== null && !Array.isArray(wire) && typeof wireCode === "string",
|
|
170
|
+
error: new BaerlyError(transient ? "NetworkError" : "Internal", wire?.message ?? `HTTP ${res.status}`, {
|
|
171
|
+
cause: wire,
|
|
172
|
+
status: res.status
|
|
173
|
+
})
|
|
174
|
+
};
|
|
175
|
+
};
|
|
176
|
+
/**
|
|
177
|
+
* Issue one HTTP request and unwrap the response per the locked
|
|
178
|
+
* status-code policy in `packages/server/src/contract.ts:73-89`:
|
|
179
|
+
*
|
|
180
|
+
* - 204 → `undefined as T` (DELETE success — no body).
|
|
181
|
+
* - 201 → raw parsed body as T (POST insert success — body `{ _id }`).
|
|
182
|
+
* - 4xx / 5xx → parse `HttpErrorEnvelope` and throw
|
|
183
|
+
* {@link BaerlyError} with `status` set to the wire HTTP code.
|
|
184
|
+
* Bodies that carry no envelope (a proxy or CDN answering for the
|
|
185
|
+
* server) still get a structured throw, with the code synthesized
|
|
186
|
+
* from the status: `NetworkError` for 5xx, `Internal` for 4xx. An
|
|
187
|
+
* envelope whose code this build doesn't know is treated the same way.
|
|
188
|
+
* - 200 on non-`GET` (PATCH, future mutations) → raw parsed body
|
|
189
|
+
* as T (e.g. `{ modified }`).
|
|
190
|
+
* - 200 on `GET /v1/since` → raw `SinceResponse` as T (no `data` unwrap).
|
|
191
|
+
* - 200 on any other `GET` → `HttpOkEnvelope<T>.data`.
|
|
192
|
+
*
|
|
193
|
+
* A successful response carrying `Baerly-Capacity-Warning` is first
|
|
194
|
+
* reported to `ctx.onWarning` (see {@link BaerlyWarning}).
|
|
195
|
+
*
|
|
196
|
+
* Two failure classes are retried, each up to its attempt cap, after a
|
|
197
|
+
* wait of the server's `Retry-After` or else a jittered backoff. A hint
|
|
198
|
+
* above the class's ceiling ends the retries instead of being clamped.
|
|
199
|
+
* An abort stops at once, and the final failure is thrown unchanged.
|
|
200
|
+
* `retry: false` disables both.
|
|
201
|
+
*
|
|
202
|
+
* - **Transport, `GET` and minted inserts** (`REQUEST_RETRY_MAX_ATTEMPTS`):
|
|
203
|
+
* a thrown `fetch` or an envelope-less 5xx, 408 or 429. A minted insert
|
|
204
|
+
* (`mintedInsert`) is resent with the same serialized body, so a commit
|
|
205
|
+
* the failure hid replays as `201 { _id }` (E2) instead of adding a row.
|
|
206
|
+
* Every other non-`GET` (caller-`_id` insert, update, replace, delete) is
|
|
207
|
+
* sent once for these (E3). An enveloped `NetworkError` is never
|
|
208
|
+
* retried: the server adapter already retried it. No other enveloped
|
|
209
|
+
* code is retried, bar `MaintenancePending` below.
|
|
210
|
+
* - **`MaintenancePending`, every verb**
|
|
211
|
+
* (`MAINTENANCE_PENDING_CLIENT_MAX_ATTEMPTS`): the server's backpressure
|
|
212
|
+
* code, waited out for `error.retryAfter`. The server refuses with it
|
|
213
|
+
* only before the write's `log/<seq>` create, so nothing committed, and
|
|
214
|
+
* each client write is one row, so the resend cannot apply anything
|
|
215
|
+
* twice. The resend carries the same serialized body, so an auto-ID
|
|
216
|
+
* insert keeps its minted `_id` and `mintedId`: even if the first
|
|
217
|
+
* attempt had committed, the resend would replay its `201`, never add a
|
|
218
|
+
* row. A caller-chosen `_id` gets `AlreadyExists` in that case, also
|
|
219
|
+
* never a second row. `update` is an RFC 7386 merge patch, which is
|
|
220
|
+
* idempotent on the row it lands on; `replace` and `delete` are
|
|
221
|
+
* idempotent outright.
|
|
222
|
+
*
|
|
223
|
+
* The two classes share one attempt counter, so a request that sees both
|
|
224
|
+
* makes at most `max(REQUEST_RETRY_MAX_ATTEMPTS,
|
|
225
|
+
* MAINTENANCE_PENDING_CLIENT_MAX_ATTEMPTS)` attempts, not their product.
|
|
226
|
+
*/
|
|
227
|
+
const request = async (ctx, opts) => {
|
|
228
|
+
const headers = new Headers(ctx.headers);
|
|
229
|
+
if (opts.body !== void 0) headers.set("content-type", "application/json");
|
|
230
|
+
const body = opts.body === void 0 ? void 0 : JSON.stringify(opts.body);
|
|
231
|
+
const signal = opts.signal !== void 0 && ctx.signal !== void 0 ? AbortSignal.any([opts.signal, ctx.signal]) : opts.signal ?? ctx.signal;
|
|
232
|
+
const retry = opts.retry !== false;
|
|
233
|
+
const transportAttempts = (opts.method === "GET" || opts.mintedInsert === true) && retry ? 3 : 1;
|
|
234
|
+
const pendingAttempts = retry ? 3 : 1;
|
|
235
|
+
for (let attempt = 1;; attempt++) {
|
|
236
|
+
let res;
|
|
237
|
+
try {
|
|
238
|
+
res = await ctx.fetch(new Request(`${ctx.baseUrl}${opts.path}`, {
|
|
239
|
+
method: opts.method,
|
|
240
|
+
headers,
|
|
241
|
+
body,
|
|
242
|
+
signal
|
|
243
|
+
}));
|
|
244
|
+
} catch (error) {
|
|
245
|
+
if (attempt >= transportAttempts || signal?.aborted === true || isAbortError(error)) throw error;
|
|
246
|
+
await sleep(backoffMillis(attempt - 1), signal);
|
|
247
|
+
continue;
|
|
248
|
+
}
|
|
249
|
+
if (res.ok) reportWarning(ctx, opts, res);
|
|
250
|
+
if (res.status === 204) return;
|
|
251
|
+
if (res.status === 201) return await parseSuccessfulJson(res, opts);
|
|
252
|
+
if (!res.ok) {
|
|
253
|
+
const hintMillis = parseRetryAfterMillis(res.headers.get("retry-after"));
|
|
254
|
+
const { error, enveloped } = await decodeFailure(res, hintMillis);
|
|
255
|
+
const pending = enveloped && error.code === "MaintenancePending";
|
|
256
|
+
if (!(pending ? attempt < pendingAttempts : !enveloped && error.code === "NetworkError" && attempt < transportAttempts)) throw error;
|
|
257
|
+
const pendingMillis = error.retryAfter === void 0 ? void 0 : error.retryAfter * 1e3;
|
|
258
|
+
const waitMillis = pending ? pendingMillis : hintMillis;
|
|
259
|
+
if (waitMillis !== void 0 && waitMillis > (pending ? 1e4 : 1e4)) throw error;
|
|
260
|
+
await sleep(waitMillis ?? backoffMillis(attempt - 1), signal);
|
|
261
|
+
continue;
|
|
262
|
+
}
|
|
263
|
+
const parsed = await parseSuccessfulJson(res, opts);
|
|
264
|
+
if (opts.method !== "GET") return parsed;
|
|
265
|
+
if (opts.path.startsWith("/v1/since")) return parsed;
|
|
266
|
+
if (typeof parsed !== "object" || parsed === null || !("data" in parsed)) throw new BaerlyError("InvalidResponse", `Response to ${opts.method} ${opts.path} missing 'data' field`, { status: res.status });
|
|
267
|
+
return parsed.data;
|
|
268
|
+
}
|
|
269
|
+
};
|
|
270
|
+
export { getClientContext as a, CLIENT_SCOPE as i, MAINTENANCE_PENDING_CLIENT_MAX_WAIT_MILLIS as n, withSignal as o, CLIENT_CONTEXT as r, request as t };
|
|
271
|
+
|
|
272
|
+
//# sourceMappingURL=request-CRWiTrza.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"request-CRWiTrza.js","names":[],"sources":["../packages/client/src/internal/context.ts","../packages/client/src/request-retry.ts","../packages/client/src/request.ts"],"sourcesContent":["import type { BaerlyClient } from \"../client.ts\";\nimport type { RequestContext } from \"../request.ts\";\n\n/**\n * Symbol-keyed slot on every `BaerlyClient` carrying the internal\n * `RequestContext`. Lets internals (e.g. the React\n * `subscription-pool`) reach the same fetcher / headers resolution\n * the typed API uses, without widening the public `BaerlyClient`\n * surface.\n *\n * Symbol is module-scoped — users cannot import it from package\n * internals, so the slot is invisible outside this package.\n */\nexport const CLIENT_CONTEXT: unique symbol = Symbol(\"baerly.client.context\");\n\ninterface ClientWithContext {\n readonly [CLIENT_CONTEXT]: RequestContext;\n}\n\n/**\n * Returns the internal `RequestContext` stashed on `client` by\n * `createBaerlyClient`. Throws if called with a client not produced\n * by `createBaerlyClient` (e.g. a test stub) — that is the right\n * signal for callers, who in production have no other way to obtain\n * a `BaerlyClient` instance.\n */\nexport const getClientContext = (client: BaerlyClient): RequestContext => {\n const ctx = (client as unknown as Partial<ClientWithContext>)[CLIENT_CONTEXT];\n if (ctx === undefined) {\n throw new Error(\n \"getClientContext: client was not produced by createBaerlyClient (missing internal context slot)\",\n );\n }\n return ctx;\n};\n\n/** Slot holding the factory behind {@link withSignal}. */\nexport const CLIENT_SCOPE: unique symbol = Symbol(\"baerly.client.scope\");\n\n/**\n * A view of `client` whose every request is also cancelled by `signal`.\n * The React subscription pool runs a query's callback against this view\n * so superseding or unmounting the query aborts its in-flight GET and\n * any retry wait, without the callback threading a signal itself.\n */\nexport const withSignal = <C extends BaerlyClient<never>>(client: C, signal: AbortSignal): C =>\n (client as unknown as { [CLIENT_SCOPE]: (signal: AbortSignal) => C })[CLIENT_SCOPE](signal);\n","/**\n * Total attempts (first try included) the client makes for one GET\n * before surfacing the last failure. Matches the 3-attempt cap the\n * storage adapters use (`STORAGE_RETRY_MAX_ATTEMPTS` in\n * `@baerly/protocol`; AWS SDK standard mode and the Google SRE book\n * both cap at 3). Client-side retry tuning, not a wire-protocol value,\n * so it lives here rather than in `@baerly/protocol`'s `constants.ts`\n * (same reasoning as `subscription-retry.ts`).\n *\n * @see ./request.ts\n */\nexport const REQUEST_RETRY_MAX_ATTEMPTS: number = 3;\n\n/**\n * Full-jitter backoff base, in milliseconds: retry `n` (0-based) waits\n * `random() * min(REQUEST_RETRY_MAX_DELAY_MILLIS, base * 2^n)`. Larger\n * than the storage adapters' 50 ms transient base because the failure\n * here came from a proxy or the network in front of the server, where\n * an early resend mostly adds load to something already struggling.\n */\nexport const REQUEST_RETRY_BASE_MILLIS: number = 250;\n\n/**\n * Upper bound, in milliseconds, on one jittered backoff, and the\n * ceiling on a server `Retry-After` the client will wait out. A hint\n * above it is not honoured by clamping (the retry would arrive early\n * and likely fail again); the GET fails as it would without retry, so\n * a hostile or misconfigured proxy cannot park a caller.\n */\nexport const REQUEST_RETRY_MAX_DELAY_MILLIS: number = 10_000;\n\n/**\n * Total attempts (first try included) the client makes for one request\n * answered with an enveloped `MaintenancePending` before it surfaces that\n * error (main-7 slice 3, S6b), on every verb. Every refused write has\n * already dispatched one bounded fold, so the third attempt lands behind\n * two fold passes; a backlog that needs more keeps draining on the\n * caller's later writes. The same 3-attempt cap as\n * {@link REQUEST_RETRY_MAX_ATTEMPTS} and `STORAGE_RETRY_MAX_ATTEMPTS`, so\n * the client has one retry budget, not one per failure class.\n *\n * Lives here rather than in `@baerly/protocol`'s `constants.ts`, like the\n * values above: importing that module adds its whole chunk (~17 KB raw,\n * ~0.7 KB min-gz) to the browser client for two numbers. The server's\n * hint is `MAINTENANCE_PENDING_RETRY_AFTER_SECONDS` there.\n */\nexport const MAINTENANCE_PENDING_CLIENT_MAX_ATTEMPTS: number = 3;\n\n/**\n * Longest wait, in milliseconds, the client honours for one\n * `MaintenancePending` retry hint (`Retry-After`, or `error.retryAfter`).\n * As with {@link REQUEST_RETRY_MAX_DELAY_MILLIS}, a larger hint ends the\n * retries rather than being clamped, so a hostile or misconfigured server\n * cannot park a caller. The React subscription pool, which never gives\n * up, clamps its wait to this instead.\n */\nexport const MAINTENANCE_PENDING_CLIENT_MAX_WAIT_MILLIS: number = 10_000;\n\n/**\n * Parse a `Retry-After` header (RFC 9110 §10.2.3: delta-seconds or an\n * HTTP-date) into milliseconds to wait. `undefined` when absent or\n * unparseable; a past date or `0` is `0`.\n */\nexport const parseRetryAfterMillis = (\n value: string | null,\n now: number = Date.now(),\n): number | undefined => {\n const text = value?.trim();\n if (text === undefined || text === \"\") {\n return undefined;\n }\n if (/^\\d+$/.test(text)) {\n return Number(text) * 1000;\n }\n // An HTTP-date always names its day and month; `Date.parse` alone\n // would accept junk like \"1.5\" or \"-1\" as a year-2001 date.\n const at = /[a-z]/i.test(text) ? Date.parse(text) : Number.NaN;\n return Number.isNaN(at) ? undefined : Math.max(0, at - now);\n};\n\n/**\n * Sleep `ms`, rejecting with `signal.reason` the moment `signal` aborts.\n * Local rather than `@baerly/protocol`'s `delay`: importing that pulls\n * `time.ts` and its key-encoding closure into the browser client bundle.\n */\nexport const sleep = (ms: number, signal: AbortSignal | undefined): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n if (signal?.aborted === true) {\n reject(signal.reason);\n return;\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n const onAbort = (): void => {\n clearTimeout(timer);\n reject(signal?.reason);\n };\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n\n/** Jittered exponential wait before retry `retryIndex` (0-based). */\nexport const backoffMillis = (retryIndex: number): number =>\n Math.random() *\n Math.min(REQUEST_RETRY_MAX_DELAY_MILLIS, REQUEST_RETRY_BASE_MILLIS * 2 ** retryIndex);\n","import { BaerlyError, CAPACITY_WARNING_HEADER, isBaerlyErrorCode } from \"@baerly/protocol\";\nimport type { HttpErrorEnvelope, HttpOkEnvelope } from \"./contract.ts\";\nimport {\n backoffMillis,\n MAINTENANCE_PENDING_CLIENT_MAX_ATTEMPTS,\n MAINTENANCE_PENDING_CLIENT_MAX_WAIT_MILLIS,\n parseRetryAfterMillis,\n REQUEST_RETRY_MAX_ATTEMPTS,\n REQUEST_RETRY_MAX_DELAY_MILLIS,\n sleep,\n} from \"./request-retry.ts\";\n\n/**\n * Pluggable fetch implementation. Defaults to `globalThis.fetch`;\n * tests override with a {@link MockFetch}.\n */\nexport type Fetcher = (req: Request) => Promise<Response>;\n\n/**\n * A warning the server attached to a successful response, passed to\n * `BaerlyClientOptions.onWarning`. The request itself succeeded and its\n * result is unchanged.\n *\n * `code` is the kind of warning. `\"CapacityWarning\"` (the\n * `Baerly-Capacity-Warning` response header) means the write was\n * committed but left its collection at 90% or more of what the host can\n * hold, so inserts and growing updates will soon be refused with\n * `CapacityExceeded`; `message` is the server's text, naming the state\n * and the app-side remedy.\n */\nexport interface BaerlyWarning {\n readonly code: \"CapacityWarning\";\n /** The server's warning text, verbatim. */\n readonly message: string;\n /** The request that drew the warning. */\n readonly method: RequestOptions[\"method\"];\n /** The request path, e.g. `/v1/c/tickets`. */\n readonly path: string;\n}\n\nexport interface RequestOptions {\n readonly method: \"GET\" | \"POST\" | \"PATCH\" | \"PUT\" | \"DELETE\";\n readonly path: string;\n readonly body?: unknown;\n readonly signal?: AbortSignal;\n /** `false` makes the request single-attempt, for callers that own their own retry loop. */\n readonly retry?: false;\n /**\n * Marks a `POST` insert whose `_id` the SDK minted and sent as `mintedId`\n * (E2). Only such a request may be resent after a transport failure: if the\n * first attempt had committed, the server replays its `201 { _id }`.\n */\n readonly mintedInsert?: true;\n}\n\n/**\n * Internal carrier passed to every {@link request} call. Built once\n * by `createBaerlyClient` from `BaerlyClientOptions`.\n *\n * `headers` is the shared template; callers MUST clone before\n * mutating (each request adds `content-type`).\n */\nexport interface RequestContext {\n readonly baseUrl: string;\n readonly fetch: Fetcher;\n readonly headers: Headers;\n /**\n * Aborts every request made through this context, alongside any\n * per-call `signal`. Set only on the scoped client a `useQuery`\n * fetch runs against.\n */\n readonly signal?: AbortSignal;\n /** `BaerlyClientOptions.onWarning`, called once per warned response. */\n readonly onWarning?: (warning: BaerlyWarning) => void;\n}\n\n/**\n * Hand a successful response's capacity warning to `ctx.onWarning`. The\n * callback is the app's code: whatever it throws, or an async callback's\n * rejection, is swallowed, so it can never fail a committed write.\n */\nconst reportWarning = (ctx: RequestContext, opts: RequestOptions, res: Response): void => {\n const message = res.headers.get(CAPACITY_WARNING_HEADER);\n if (ctx.onWarning === undefined || !message) {\n return;\n }\n try {\n Promise.resolve(\n ctx.onWarning({ code: \"CapacityWarning\", message, method: opts.method, path: opts.path }),\n ).catch(() => {});\n } catch {\n // The callback threw synchronously; the request still succeeds.\n }\n};\n\nconst parseSuccessfulJson = async (\n res: Response,\n opts: Pick<RequestOptions, \"method\" | \"path\">,\n): Promise<unknown> => {\n try {\n return await res.json();\n } catch (error) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `Response to ${opts.method} ${opts.path} was not valid JSON`,\n { cause: error, status: res.status },\n );\n }\n};\n\nconst isAbortError = (error: unknown): boolean =>\n typeof error === \"object\" &&\n error !== null &&\n (error as { name?: unknown }).name === \"AbortError\";\n\n/**\n * Decode a non-ok response into the error `request` throws, plus whether\n * the server itself produced it (`enveloped`).\n *\n * No envelope means the response came from something between the\n * caller and the server — a load balancer, CDN, rate limiter, or\n * service mesh — so the server's own failure class is unavailable and\n * we infer one from the status. 5xx, 408 Request Timeout and 429 Too\n * Many Requests are transient conditions that clear on their own, and\n * `NetworkError` is the only synthesized code whose `retriable` says\n * so. `Internal` does not: the React subscription pool treats a\n * non-retriable error as permanently terminal, so labelling a\n * rolling-deploy 502 or an edge 429 `Internal` would park every live\n * query on a dead poll until the user remounted. Any other 4xx without\n * an envelope is a caller or routing fault that retrying cannot clear,\n * so it stays `Internal`.\n *\n * A code this build doesn't know (minted by a newer server, or\n * `Conflict` from an older one) gets the same status-derived code, so\n * a newer server's 503 backpressure keeps a subscription reconnecting\n * and `code` never holds a string outside `BaerlyErrorCode`. Only the\n * message carries over: `resolution`, `issues` and `_id` belong to the\n * undecoded code and would contradict the synthesized one, so the\n * whole wire error rides on `cause` instead.\n *\n * A `MaintenancePending` error's `retryAfter` is the longer of the\n * envelope's `retryAfter` and the `Retry-After` header (`hintMillis`), in\n * seconds, so a caller that sees only the error (the React subscription\n * pool) still honours the header.\n */\nconst decodeFailure = async (\n res: Response,\n hintMillis: number | undefined,\n): Promise<{ readonly error: BaerlyError; readonly enveloped: boolean }> => {\n let envelope: HttpErrorEnvelope | undefined;\n try {\n envelope = (await res.json()) as HttpErrorEnvelope;\n } catch {\n // Non-JSON body (e.g. an upstream proxy 502). Fall through to\n // the synthesized code below so consumers still get a\n // structured throw.\n }\n const wire = envelope?.error;\n const wireCode = wire?.code;\n if (wire !== undefined && isBaerlyErrorCode(wireCode)) {\n const wireAfter = wire.retryAfter;\n const hints = [\n ...(typeof wireAfter === \"number\" && wireAfter >= 0 ? [wireAfter] : []),\n ...(hintMillis === undefined ? [] : [hintMillis / 1000]),\n ];\n return {\n enveloped: true,\n error: new BaerlyError(wireCode, wire.message ?? `HTTP ${res.status}`, {\n issues: wire.issues,\n status: res.status,\n resolution: wire.resolution,\n _id: wire._id,\n retryAfter:\n wireCode === \"MaintenancePending\" && hints.length > 0 ? Math.max(...hints) : undefined,\n }),\n };\n }\n const transient = res.status >= 500 || res.status === 408 || res.status === 429;\n return {\n enveloped:\n typeof wire === \"object\" &&\n wire !== null &&\n !Array.isArray(wire) &&\n typeof wireCode === \"string\",\n error: new BaerlyError(\n transient ? \"NetworkError\" : \"Internal\",\n wire?.message ?? `HTTP ${res.status}`,\n { cause: wire, status: res.status },\n ),\n };\n};\n\n/**\n * Issue one HTTP request and unwrap the response per the locked\n * status-code policy in `packages/server/src/contract.ts:73-89`:\n *\n * - 204 → `undefined as T` (DELETE success — no body).\n * - 201 → raw parsed body as T (POST insert success — body `{ _id }`).\n * - 4xx / 5xx → parse `HttpErrorEnvelope` and throw\n * {@link BaerlyError} with `status` set to the wire HTTP code.\n * Bodies that carry no envelope (a proxy or CDN answering for the\n * server) still get a structured throw, with the code synthesized\n * from the status: `NetworkError` for 5xx, `Internal` for 4xx. An\n * envelope whose code this build doesn't know is treated the same way.\n * - 200 on non-`GET` (PATCH, future mutations) → raw parsed body\n * as T (e.g. `{ modified }`).\n * - 200 on `GET /v1/since` → raw `SinceResponse` as T (no `data` unwrap).\n * - 200 on any other `GET` → `HttpOkEnvelope<T>.data`.\n *\n * A successful response carrying `Baerly-Capacity-Warning` is first\n * reported to `ctx.onWarning` (see {@link BaerlyWarning}).\n *\n * Two failure classes are retried, each up to its attempt cap, after a\n * wait of the server's `Retry-After` or else a jittered backoff. A hint\n * above the class's ceiling ends the retries instead of being clamped.\n * An abort stops at once, and the final failure is thrown unchanged.\n * `retry: false` disables both.\n *\n * - **Transport, `GET` and minted inserts** (`REQUEST_RETRY_MAX_ATTEMPTS`):\n * a thrown `fetch` or an envelope-less 5xx, 408 or 429. A minted insert\n * (`mintedInsert`) is resent with the same serialized body, so a commit\n * the failure hid replays as `201 { _id }` (E2) instead of adding a row.\n * Every other non-`GET` (caller-`_id` insert, update, replace, delete) is\n * sent once for these (E3). An enveloped `NetworkError` is never\n * retried: the server adapter already retried it. No other enveloped\n * code is retried, bar `MaintenancePending` below.\n * - **`MaintenancePending`, every verb**\n * (`MAINTENANCE_PENDING_CLIENT_MAX_ATTEMPTS`): the server's backpressure\n * code, waited out for `error.retryAfter`. The server refuses with it\n * only before the write's `log/<seq>` create, so nothing committed, and\n * each client write is one row, so the resend cannot apply anything\n * twice. The resend carries the same serialized body, so an auto-ID\n * insert keeps its minted `_id` and `mintedId`: even if the first\n * attempt had committed, the resend would replay its `201`, never add a\n * row. A caller-chosen `_id` gets `AlreadyExists` in that case, also\n * never a second row. `update` is an RFC 7386 merge patch, which is\n * idempotent on the row it lands on; `replace` and `delete` are\n * idempotent outright.\n *\n * The two classes share one attempt counter, so a request that sees both\n * makes at most `max(REQUEST_RETRY_MAX_ATTEMPTS,\n * MAINTENANCE_PENDING_CLIENT_MAX_ATTEMPTS)` attempts, not their product.\n */\nexport const request = async <T>(ctx: RequestContext, opts: RequestOptions): Promise<T> => {\n const headers = new Headers(ctx.headers);\n if (opts.body !== undefined) {\n headers.set(\"content-type\", \"application/json\");\n }\n const body = opts.body === undefined ? undefined : JSON.stringify(opts.body);\n const signal =\n opts.signal !== undefined && ctx.signal !== undefined\n ? AbortSignal.any([opts.signal, ctx.signal])\n : (opts.signal ?? ctx.signal);\n const retry = opts.retry !== false;\n const transportAttempts =\n (opts.method === \"GET\" || opts.mintedInsert === true) && retry ? REQUEST_RETRY_MAX_ATTEMPTS : 1;\n const pendingAttempts = retry ? MAINTENANCE_PENDING_CLIENT_MAX_ATTEMPTS : 1;\n\n for (let attempt = 1; ; attempt++) {\n let res: Response;\n try {\n // A fresh `Request` per attempt: a `Request` is single-use.\n res = await ctx.fetch(\n new Request(`${ctx.baseUrl}${opts.path}`, {\n method: opts.method,\n headers,\n body,\n signal,\n }),\n );\n } catch (error) {\n if (attempt >= transportAttempts || signal?.aborted === true || isAbortError(error)) {\n throw error;\n }\n await sleep(backoffMillis(attempt - 1), signal);\n continue;\n }\n\n if (res.ok) {\n reportWarning(ctx, opts, res);\n }\n\n // 204 No Content — never a body; cast the \"no value\" to T. The\n // only caller (`delete`) types T = undefined so this is safe.\n if (res.status === 204) {\n return undefined as T;\n }\n\n // 201 Created — body is `{ _id }`, not `HttpOkEnvelope`. The only\n // caller (`insert`) types T = `{ _id }` so we return the parsed\n // body raw.\n if (res.status === 201) {\n return (await parseSuccessfulJson(res, opts)) as T;\n }\n\n // 4xx / 5xx — `HttpErrorEnvelope`. Parse + throw, or retry.\n if (!res.ok) {\n const hintMillis = parseRetryAfterMillis(res.headers.get(\"retry-after\"));\n const { error, enveloped } = await decodeFailure(res, hintMillis);\n const pending = enveloped && error.code === \"MaintenancePending\";\n const retriable = pending\n ? attempt < pendingAttempts\n : !enveloped && error.code === \"NetworkError\" && attempt < transportAttempts;\n if (!retriable) {\n throw error;\n }\n // A pending error's `retryAfter` already folds in the header.\n const pendingMillis = error.retryAfter === undefined ? undefined : error.retryAfter * 1000;\n const waitMillis = pending ? pendingMillis : hintMillis;\n const ceiling = pending\n ? MAINTENANCE_PENDING_CLIENT_MAX_WAIT_MILLIS\n : REQUEST_RETRY_MAX_DELAY_MILLIS;\n if (waitMillis !== undefined && waitMillis > ceiling) {\n throw error;\n }\n await sleep(waitMillis ?? backoffMillis(attempt - 1), signal);\n continue;\n }\n\n // 200 — only GET reads ship `HttpOkEnvelope<T>`. PATCH (and any\n // future non-GET mutation that hits 200) ships its body raw. GET\n // /v1/since also ships raw (`SinceResponse`).\n const parsed = await parseSuccessfulJson(res, opts);\n if (opts.method !== \"GET\") {\n return parsed as T;\n }\n if (opts.path.startsWith(\"/v1/since\")) {\n return parsed as T;\n }\n if (typeof parsed !== \"object\" || parsed === null || !(\"data\" in parsed)) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `Response to ${opts.method} ${opts.path} missing 'data' field`,\n { status: res.status },\n );\n }\n return (parsed as HttpOkEnvelope<T>).data;\n }\n};\n"],"mappings":";;;;;;;;;;;;;AAaA,MAAa,iBAAgC,OAAO,uBAAuB;;;;;;;;AAa3E,MAAa,oBAAoB,WAAyC;CACxE,MAAM,MAAO,OAAiD;CAC9D,IAAI,QAAQ,KAAA,GACV,MAAM,IAAI,MACR,iGACF;CAEF,OAAO;AACT;;AAGA,MAAa,eAA8B,OAAO,qBAAqB;;;;;;;AAQvE,MAAa,cAA6C,QAAW,WAClE,OAAqE,aAAa,CAAC,MAAM;;;;;;;;ACjB5F,MAAa,iCAAyC;;;;;;;;;AA2BtD,MAAa,6CAAqD;;;;;;AAOlE,MAAa,yBACX,OACA,MAAc,KAAK,IAAI,MACA;CACvB,MAAM,OAAO,OAAO,KAAK;CACzB,IAAI,SAAS,KAAA,KAAa,SAAS,IACjC;CAEF,IAAI,QAAQ,KAAK,IAAI,GACnB,OAAO,OAAO,IAAI,IAAI;CAIxB,MAAM,KAAK,SAAS,KAAK,IAAI,IAAI,KAAK,MAAM,IAAI,IAAI;CACpD,OAAO,OAAO,MAAM,EAAE,IAAI,KAAA,IAAY,KAAK,IAAI,GAAG,KAAK,GAAG;AAC5D;;;;;;AAOA,MAAa,SAAS,IAAY,WAChC,IAAI,SAAe,SAAS,WAAW;CACrC,IAAI,QAAQ,YAAY,MAAM;EAC5B,OAAO,OAAO,MAAM;EACpB;CACF;CACA,MAAM,QAAQ,iBAAiB;EAC7B,QAAQ,oBAAoB,SAAS,OAAO;EAC5C,QAAQ;CACV,GAAG,EAAE;CACL,MAAM,gBAAsB;EAC1B,aAAa,KAAK;EAClB,OAAO,QAAQ,MAAM;CACvB;CACA,QAAQ,iBAA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