@gusto/baerly-storage 0.6.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.
Files changed (218) hide show
  1. package/README.md +47 -124
  2. package/dist/API.md +161 -512
  3. package/dist/CHANGELOG.md +1137 -378
  4. package/dist/RECIPES.md +398 -80
  5. package/dist/THIRD-PARTY-LICENSES.txt +5 -26
  6. package/dist/{app-config-DyiFK3_k.d.ts → app-config-C6qW7m8S.d.ts} +119 -111
  7. package/dist/app-config.d.ts +31 -1
  8. package/dist/app-config.js +1 -2
  9. package/dist/app-config.js.map +1 -1
  10. package/dist/auth.d.ts +33 -28
  11. package/dist/auth.js +549 -985
  12. package/dist/auth.js.map +1 -1
  13. package/dist/baerly.js +130 -138
  14. package/dist/baerly.js.map +1 -1
  15. package/dist/baerly.spec.json +97 -22
  16. package/dist/capacity-warning-header-BlVopyiI.js +16 -0
  17. package/dist/capacity-warning-header-BlVopyiI.js.map +1 -0
  18. package/dist/{client-ypCm3zjt.d.ts → client-CHQTXpef.d.ts} +121 -36
  19. package/dist/client-react.d.ts +67 -20
  20. package/dist/client-react.js +240 -54
  21. package/dist/client-react.js.map +1 -1
  22. package/dist/client.d.ts +5 -4
  23. package/dist/client.js +51 -16
  24. package/dist/client.js.map +1 -1
  25. package/dist/{cloudflare-wrVYf4bb.js → cloudflare-CKHYXccw.js} +61 -82
  26. package/dist/cloudflare-CKHYXccw.js.map +1 -0
  27. package/dist/cloudflare.d.ts +106 -71
  28. package/dist/cloudflare.js +334 -271
  29. package/dist/cloudflare.js.map +1 -1
  30. package/dist/code-resolution-CL_7L0wS.js +22 -0
  31. package/dist/code-resolution-CL_7L0wS.js.map +1 -0
  32. package/dist/collection-api-DbyhLAY8.d.ts +1001 -0
  33. package/dist/config-DEzInG6M.js +4035 -0
  34. package/dist/config-DEzInG6M.js.map +1 -0
  35. package/dist/constants-D3GSH3tc.js +469 -0
  36. package/dist/constants-D3GSH3tc.js.map +1 -0
  37. package/dist/{context-DRZ3tZ5l.js → context-rlpSnHFA.js} +17 -17
  38. package/dist/context-rlpSnHFA.js.map +1 -0
  39. package/dist/cost-B52llVDx.js +330 -0
  40. package/dist/cost-B52llVDx.js.map +1 -0
  41. package/dist/{current-json-C6nhPOm1.js → current-json-CC6lE4Aj.js} +115 -32
  42. package/dist/current-json-CC6lE4Aj.js.map +1 -0
  43. package/dist/db-plFUNTSF.d.ts +130 -0
  44. package/dist/db-read-seams-BSs0m1z1.js +3261 -0
  45. package/dist/db-read-seams-BSs0m1z1.js.map +1 -0
  46. package/dist/{deploy-Di_Q01qx.js → deploy-Obj4nE-Z.js} +10 -14
  47. package/dist/deploy-Obj4nE-Z.js.map +1 -0
  48. package/dist/{dev-banner-CWHIk8tH.d.ts → dev-banner-B5AUHmu1.d.ts} +1 -4
  49. package/dist/dev-landing-BI5UdmOb.d.ts +32 -0
  50. package/dist/dev-landing-CD-si4dW.js +50 -0
  51. package/dist/dev-landing-CD-si4dW.js.map +1 -0
  52. package/dist/dev-vite.d.ts +9 -14
  53. package/dist/dev-vite.js +11 -10
  54. package/dist/dev-vite.js.map +1 -1
  55. package/dist/dev.d.ts +3 -2
  56. package/dist/dev.js +2 -1
  57. package/dist/doctor-BA0i-YAN.js +270 -0
  58. package/dist/doctor-BA0i-YAN.js.map +1 -0
  59. package/dist/dump-D1vX8ozg.js +133 -0
  60. package/dist/dump-D1vX8ozg.js.map +1 -0
  61. package/dist/errors-7Rk1HGCE.js +160 -0
  62. package/dist/errors-7Rk1HGCE.js.map +1 -0
  63. package/dist/{validate-DtljsCh1.js → export-BVL2EvYE.js} +409 -19
  64. package/dist/export-BVL2EvYE.js.map +1 -0
  65. package/dist/fsck-BWkPgov4.js +145 -0
  66. package/dist/fsck-BWkPgov4.js.map +1 -0
  67. package/dist/{gcs-admin-Bx6xSNJj.d.ts → gcs-admin-Dso1HWQj.d.ts} +18 -14
  68. package/dist/gcs.d.ts +19 -7
  69. package/dist/gcs.js +1 -2
  70. package/dist/{goog4-signer-Z7KnJ1su.js → goog4-signer-CeLIABoE.js} +102 -92
  71. package/dist/goog4-signer-CeLIABoE.js.map +1 -0
  72. package/dist/{http-7zT29K3P.js → http-Z5rZyYMX.js} +898 -271
  73. package/dist/http-Z5rZyYMX.js.map +1 -0
  74. package/dist/http-transport-DNUM8kU-.js +1299 -0
  75. package/dist/http-transport-DNUM8kU-.js.map +1 -0
  76. package/dist/http.d.ts +366 -294
  77. package/dist/http.js +2 -2
  78. package/dist/index-JJrIu1pO.d.ts +135 -0
  79. package/dist/index-LEgHN0qJ.d.ts +50 -0
  80. package/dist/{index-DP3ClvcA.d.ts → index-RiEYj8t0.d.ts} +291 -78
  81. package/dist/index.d.ts +27 -6
  82. package/dist/index.js +3 -5
  83. package/dist/inspect-BTsVYZKd.js +196 -0
  84. package/dist/inspect-BTsVYZKd.js.map +1 -0
  85. package/dist/{key-Di6yyxFu.js → key-C4FPZ9Io.js} +3 -4
  86. package/dist/{key-Di6yyxFu.js.map → key-C4FPZ9Io.js.map} +1 -1
  87. package/dist/ledger-Dj_bGgo0.js +192 -0
  88. package/dist/ledger-Dj_bGgo0.js.map +1 -0
  89. package/dist/legacy-names-DgZBtgOh.js +47 -0
  90. package/dist/legacy-names-DgZBtgOh.js.map +1 -0
  91. package/dist/log-C9W15Dfo.d.ts +94 -0
  92. package/dist/log-tail-DWJbneBF.js +142 -0
  93. package/dist/log-tail-DWJbneBF.js.map +1 -0
  94. package/dist/log-walk-C-vA-WGJ.js +111 -0
  95. package/dist/log-walk-C-vA-WGJ.js.map +1 -0
  96. package/dist/maintenance-Dd-Yakqj.js +1709 -0
  97. package/dist/maintenance-Dd-Yakqj.js.map +1 -0
  98. package/dist/maintenance-DevB6z4e.js +2237 -0
  99. package/dist/maintenance-DevB6z4e.js.map +1 -0
  100. package/dist/maintenance.d.ts +100 -3
  101. package/dist/maintenance.js +1 -3
  102. package/dist/node.d.ts +119 -92
  103. package/dist/node.js +3 -3
  104. package/dist/{observability-Ch-VQJyE.js → observability-C-ISCCLE.js} +1247 -326
  105. package/dist/observability-C-ISCCLE.js.map +1 -0
  106. package/dist/observability.d.ts +27 -3
  107. package/dist/observability.js +3 -3
  108. package/dist/path-segment-DBXG26PW.js +363 -0
  109. package/dist/path-segment-DBXG26PW.js.map +1 -0
  110. package/dist/{plan-C4qgiXSg.js → plan-BvQbaNMe.js} +19 -11
  111. package/dist/plan-BvQbaNMe.js.map +1 -0
  112. package/dist/request-CRWiTrza.js +272 -0
  113. package/dist/request-CRWiTrza.js.map +1 -0
  114. package/dist/restore-U6Im8V1V.js +1467 -0
  115. package/dist/restore-U6Im8V1V.js.map +1 -0
  116. package/dist/retry-OBtLB2GC.js +126 -0
  117. package/dist/retry-OBtLB2GC.js.map +1 -0
  118. package/dist/rolldown-runtime-D3KUYPsf.js +12 -0
  119. package/dist/{runtime-spec--LykAdl1.js → runtime-spec-B5mg3pHF.js} +189 -28
  120. package/dist/runtime-spec-B5mg3pHF.js.map +1 -0
  121. package/dist/{s3-http-DD5gDc7t.d.ts → s3-http-DBC_wiCL.d.ts} +14 -8
  122. package/dist/s3.d.ts +20 -7
  123. package/dist/s3.js +4 -5
  124. package/dist/s3.js.map +1 -1
  125. package/dist/{sha256-CqcKTjw9.js → sha256-4FfGQNPw.js} +9 -9
  126. package/dist/sha256-4FfGQNPw.js.map +1 -0
  127. package/dist/{shared-secret-DgEicd3x.js → shared-secret-Vkur-8r0.js} +27 -15
  128. package/dist/shared-secret-Vkur-8r0.js.map +1 -0
  129. package/dist/{aws4fetch.esm-CXE5ZbAa.js → sigv4-sign-5IUflUD_.js} +143 -96
  130. package/dist/sigv4-sign-5IUflUD_.js.map +1 -0
  131. package/dist/snapshot-CknzkDM0.js +148 -0
  132. package/dist/snapshot-CknzkDM0.js.map +1 -0
  133. package/dist/{src-BMFfDUI2.js → src-Actga-bO.js} +949 -363
  134. package/dist/src-Actga-bO.js.map +1 -0
  135. package/dist/src-D0MQfvOp.js +812 -0
  136. package/dist/src-D0MQfvOp.js.map +1 -0
  137. package/dist/src-Dr9uo3dc.js +501 -0
  138. package/dist/src-Dr9uo3dc.js.map +1 -0
  139. package/dist/{subcommand-BV68pqwJ.js → subcommand-BLoF66dG.js} +89 -16
  140. package/dist/subcommand-BLoF66dG.js.map +1 -0
  141. package/dist/{time-DUqvFMHq.js → time-DRxTP9iv.js} +15 -34
  142. package/dist/time-DRxTP9iv.js.map +1 -0
  143. package/dist/types-suVbsEWS.d.ts +116 -0
  144. package/dist/{usage-BMZR8o6U.js → usage-CPzVhrQr.js} +40 -45
  145. package/dist/usage-CPzVhrQr.js.map +1 -0
  146. package/dist/uuid-BuT_c404.js +333 -0
  147. package/dist/uuid-BuT_c404.js.map +1 -0
  148. package/dist/verifier-Bmlmndzo.d.ts +95 -0
  149. package/dist/{wire-izfGZDvr.js → wire-DndvKU-K.js} +2 -3
  150. package/dist/wire-DndvKU-K.js.map +1 -0
  151. package/package.json +90 -69
  152. package/dist/aws4fetch.esm-CXE5ZbAa.js.map +0 -1
  153. package/dist/bytes-BXdamO3L.js +0 -11
  154. package/dist/bytes-BXdamO3L.js.map +0 -1
  155. package/dist/cloudflare-wrVYf4bb.js.map +0 -1
  156. package/dist/config-B6nTy8e2.js +0 -3095
  157. package/dist/config-B6nTy8e2.js.map +0 -1
  158. package/dist/constants-CfeMWQWk.js +0 -222
  159. package/dist/constants-CfeMWQWk.js.map +0 -1
  160. package/dist/context-DRZ3tZ5l.js.map +0 -1
  161. package/dist/cost-_SE_SVgZ.js +0 -203
  162. package/dist/cost-_SE_SVgZ.js.map +0 -1
  163. package/dist/current-json-C6nhPOm1.js.map +0 -1
  164. package/dist/db-DjjthkTi.d.ts +0 -254
  165. package/dist/deploy-Di_Q01qx.js.map +0 -1
  166. package/dist/doctor-RWVRpvat.js +0 -102
  167. package/dist/doctor-RWVRpvat.js.map +0 -1
  168. package/dist/dump-m2vEYDNY.js +0 -94
  169. package/dist/dump-m2vEYDNY.js.map +0 -1
  170. package/dist/errors-Dfa3p78c.js +0 -78
  171. package/dist/errors-Dfa3p78c.js.map +0 -1
  172. package/dist/export-DenKwEQu.js +0 -401
  173. package/dist/export-DenKwEQu.js.map +0 -1
  174. package/dist/fsck-2Vq-7-e2.js +0 -279
  175. package/dist/fsck-2Vq-7-e2.js.map +0 -1
  176. package/dist/goog4-signer-Z7KnJ1su.js.map +0 -1
  177. package/dist/http-7zT29K3P.js.map +0 -1
  178. package/dist/http-transport-BTgVCY5r.js +0 -1250
  179. package/dist/http-transport-BTgVCY5r.js.map +0 -1
  180. package/dist/index-BHz92Acj.d.ts +0 -162
  181. package/dist/index-CEZKQsKt.d.ts +0 -1113
  182. package/dist/index-uE-w2dgj.d.ts +0 -115
  183. package/dist/indexes-Dn9hbGQG.d.ts +0 -22
  184. package/dist/inspect-BpYbH1DM.js +0 -133
  185. package/dist/inspect-BpYbH1DM.js.map +0 -1
  186. package/dist/log-tail-QWU4wlu-.js +0 -514
  187. package/dist/log-tail-QWU4wlu-.js.map +0 -1
  188. package/dist/maintenance-BGHGt2Yg.d.ts +0 -537
  189. package/dist/maintenance-DULFcpd1.js +0 -2144
  190. package/dist/maintenance-DULFcpd1.js.map +0 -1
  191. package/dist/maintenance-fEi-UZ2o.js +0 -1412
  192. package/dist/maintenance-fEi-UZ2o.js.map +0 -1
  193. package/dist/normalize-rjnZLwS4.js +0 -133
  194. package/dist/normalize-rjnZLwS4.js.map +0 -1
  195. package/dist/observability-Ch-VQJyE.js.map +0 -1
  196. package/dist/plan-C4qgiXSg.js.map +0 -1
  197. package/dist/query-C43r-6ib.js +0 -1773
  198. package/dist/query-C43r-6ib.js.map +0 -1
  199. package/dist/rebuild-index-BH1dc1p6.js +0 -81
  200. package/dist/rebuild-index-BH1dc1p6.js.map +0 -1
  201. package/dist/request-u0M51mhJ.js +0 -72
  202. package/dist/request-u0M51mhJ.js.map +0 -1
  203. package/dist/restore-D0VYWzfP.js +0 -778
  204. package/dist/restore-D0VYWzfP.js.map +0 -1
  205. package/dist/rolldown-runtime-EAsCxrDo.js +0 -14
  206. package/dist/runtime-spec--LykAdl1.js.map +0 -1
  207. package/dist/sha256-CqcKTjw9.js.map +0 -1
  208. package/dist/shared-secret-DgEicd3x.js.map +0 -1
  209. package/dist/src-BMFfDUI2.js.map +0 -1
  210. package/dist/src-DYZ4H1aF.js +0 -392
  211. package/dist/src-DYZ4H1aF.js.map +0 -1
  212. package/dist/src-DvbTEya2.js +0 -536
  213. package/dist/src-DvbTEya2.js.map +0 -1
  214. package/dist/subcommand-BV68pqwJ.js.map +0 -1
  215. package/dist/time-DUqvFMHq.js.map +0 -1
  216. package/dist/usage-BMZR8o6U.js.map +0 -1
  217. package/dist/validate-DtljsCh1.js.map +0 -1
  218. package/dist/wire-izfGZDvr.js.map +0 -1
@@ -1,7 +1,7 @@
1
- import { t as BaerlyError } from "./errors-Dfa3p78c.js";
2
- import { r as getClientContext, t as request } from "./request-u0M51mhJ.js";
1
+ import { t as BaerlyError } from "./errors-7Rk1HGCE.js";
2
+ import { a as getClientContext, n as MAINTENANCE_PENDING_CLIENT_MAX_WAIT_MILLIS, o as withSignal, t as request } from "./request-CRWiTrza.js";
3
3
  import { createContext, createElement, useCallback, useContext, useEffect, useMemo, useReducer, useRef, useState, useSyncExternalStore } from "react";
4
- //#region packages/client/src/react/provider.ts
4
+ // packages/client/src/react/provider.ts
5
5
  const ClientContext = createContext(void 0);
6
6
  /**
7
7
  * Provides a {@link BaerlyClient} to every Baerly React hook below it.
@@ -49,8 +49,7 @@ const useBaerlyClient = () => {
49
49
  if (client === void 0) throw new Error("useBaerlyClient (and every Baerly React hook) must be used inside <BaerlyProvider>. Wrap your app: <BaerlyProvider client={client}>…</BaerlyProvider>.");
50
50
  return client;
51
51
  };
52
- //#endregion
53
- //#region packages/client/src/react/use-mutation.ts
52
+ // packages/client/src/react/use-mutation.ts
54
53
  /**
55
54
  * Imperative mutation hook. `mutate(callback)` runs the callback
56
55
  * against the real `BaerlyClient` and resolves to whatever the
@@ -94,7 +93,7 @@ const useMutation = () => {
94
93
  try {
95
94
  return await callback(client);
96
95
  } catch (error) {
97
- const be = error instanceof BaerlyError ? error : new BaerlyError("MutationFailed", error instanceof Error ? error.message : String(error), error);
96
+ const be = error instanceof BaerlyError ? error : new BaerlyError("MutationFailed", error instanceof Error ? error.message : String(error), { cause: error });
98
97
  if (mountedRef.current) setLastError(be);
99
98
  throw be;
100
99
  } finally {
@@ -106,8 +105,7 @@ const useMutation = () => {
106
105
  error: lastError
107
106
  }), [isPending, lastError])];
108
107
  };
109
- //#endregion
110
- //#region packages/client/src/react/stable-key.ts
108
+ // packages/client/src/react/stable-key.ts
111
109
  /**
112
110
  * Deterministic JSON serialization with sorted object keys. `useQuery`
113
111
  * feeds its `[chainShape, deps]` tuple into this to compute the
@@ -133,8 +131,7 @@ const compareStrings = (a, b) => {
133
131
  if (a > b) return 1;
134
132
  return 0;
135
133
  };
136
- //#endregion
137
- //#region packages/client/src/poll-since-once.ts
134
+ // packages/client/src/poll-since-once.ts
138
135
  /**
139
136
  * One round-trip of `GET /v1/since?collection=…&cursor=…`. The single
140
137
  * place that talks to `/v1/since` in this package — the React
@@ -156,14 +153,53 @@ const pollSinceOnce = async (ctx, name, cursor, signal) => {
156
153
  const params = new URLSearchParams();
157
154
  params.set("collection", name);
158
155
  params.set("cursor", cursor);
159
- return request(ctx, {
156
+ const response = await request(ctx, {
160
157
  method: "GET",
161
158
  path: `/v1/since?${params.toString()}`,
162
- signal
159
+ signal,
160
+ retry: false
163
161
  });
162
+ if (typeof response !== "object" || response === null || !("events" in response) || !Array.isArray(response.events) || !("next_cursor" in response) || typeof response.next_cursor !== "string") throw new BaerlyError("InvalidResponse", "Response to GET /v1/since must contain an events array and string next_cursor");
163
+ return response;
164
164
  };
165
- //#endregion
166
- //#region packages/client/src/react/subscription-pool.ts
165
+ /**
166
+ * Maximum upper bound, in milliseconds, for the React client's
167
+ * `/v1/since` retry delay. The equal-jitter calculation never returns
168
+ * a delay above this cap.
169
+ *
170
+ * @see ./subscription-pool.ts
171
+ */
172
+ const SUBSCRIPTION_RETRY_MAX_MILLIS = 1e4;
173
+ /**
174
+ * Equal-jitter backoff delay for the `attempt`-th consecutive
175
+ * retriable `/v1/since` failure, counting from zero.
176
+ *
177
+ * The upper bound doubles per attempt from
178
+ * {@link SUBSCRIPTION_RETRY_INITIAL_MILLIS} and saturates at
179
+ * {@link SUBSCRIPTION_RETRY_MAX_MILLIS}; the returned delay is drawn
180
+ * uniformly from the top half of that bound. Half the bound is fixed
181
+ * so a wedged table still backs off monotonically, and half is random
182
+ * so a fleet of clients that lost the same server does not re-converge
183
+ * into a synchronised retry wave.
184
+ */
185
+ const retryDelay = (attempt) => {
186
+ const upperBound = Math.min(SUBSCRIPTION_RETRY_MAX_MILLIS, 250 * 2 ** attempt);
187
+ return Math.floor(upperBound / 2 + Math.random() * (upperBound / 2));
188
+ };
189
+ /**
190
+ * The wait, in milliseconds, before re-polling after `error` on the
191
+ * `attempt`-th consecutive retriable failure: {@link retryDelay}, or the
192
+ * server's hint when `error` is `MaintenancePending` and asks for longer.
193
+ * The hint (`error.retryAfter`, which already folds in the `Retry-After`
194
+ * header) is clamped to `MAINTENANCE_PENDING_CLIENT_MAX_WAIT_MILLIS`: the
195
+ * poll never gives up, so a hostile hint must not park it.
196
+ */
197
+ const pollRetryDelay = (attempt, error) => {
198
+ const backoff = retryDelay(attempt);
199
+ if (!(error instanceof BaerlyError) || error.code !== "MaintenancePending" || error.retryAfter === void 0) return backoff;
200
+ return Math.max(backoff, Math.min(error.retryAfter * 1e3, MAINTENANCE_PENDING_CLIENT_MAX_WAIT_MILLIS));
201
+ };
202
+ // packages/client/src/react/subscription-pool.ts
167
203
  const LOADING_SNAPSHOT = Object.freeze({
168
204
  status: "loading",
169
205
  data: void 0,
@@ -173,6 +209,22 @@ const toError = (raw) => {
173
209
  if (raw instanceof BaerlyError || raw instanceof Error) return raw;
174
210
  return new BaerlyError("Internal", String(raw));
175
211
  };
212
+ const isAbortError = (raw) => typeof raw === "object" && raw !== null && "name" in raw && raw.name === "AbortError";
213
+ const waitForRetry = async (delay, signal) => {
214
+ if (signal.aborted) return;
215
+ const cleanup = [];
216
+ const timeout = new Promise((resolve) => {
217
+ const timer = setTimeout(resolve, delay);
218
+ cleanup.push(() => clearTimeout(timer));
219
+ });
220
+ const aborted = new Promise((resolve) => {
221
+ const onAbort = () => resolve();
222
+ signal.addEventListener("abort", onAbort, { once: true });
223
+ cleanup.push(() => signal.removeEventListener("abort", onAbort));
224
+ });
225
+ await Promise.race([timeout, aborted]);
226
+ for (const dispose of cleanup) dispose();
227
+ };
176
228
  const poolByClient = /* @__PURE__ */ new WeakMap();
177
229
  /** Returns the (lazily-created) pool for `client`. */
178
230
  const poolFor = (client) => {
@@ -192,14 +244,32 @@ const createPool = (client) => {
192
244
  if (subs === void 0) return;
193
245
  for (const notify of subs) notify();
194
246
  };
247
+ const terminalErrorFor = (entry) => {
248
+ for (const table of entry.chainTables) {
249
+ const error = tablePolls.get(table)?.terminalError;
250
+ if (error !== void 0) return error;
251
+ }
252
+ };
195
253
  const dispatchFetch = (signature, fetcher) => {
196
254
  const entry = cache.get(signature);
197
255
  if (entry === void 0) return;
256
+ const terminalError = terminalErrorFor(entry);
257
+ if (terminalError !== void 0) {
258
+ if (entry.snapshot.status !== "error" || entry.snapshot.error !== terminalError) {
259
+ entry.snapshot = {
260
+ status: "error",
261
+ data: entry.snapshot.data,
262
+ error: terminalError
263
+ };
264
+ notifyAll(signature);
265
+ }
266
+ return;
267
+ }
198
268
  if (entry.inFlight !== void 0) entry.inFlight.abort();
199
269
  const controller = new AbortController();
200
270
  entry.inFlight = controller;
201
271
  const prevSnapshot = entry.snapshot;
202
- entry.snapshot = entry.snapshot.status === "ok" || entry.snapshot.status === "refreshing" ? {
272
+ entry.snapshot = entry.hasSuccessfulData ? {
203
273
  status: "refreshing",
204
274
  data: entry.snapshot.data,
205
275
  error: void 0
@@ -207,7 +277,7 @@ const createPool = (client) => {
207
277
  if (entry.snapshot !== prevSnapshot) notifyAll(signature);
208
278
  (async () => {
209
279
  try {
210
- const data = await fetcher();
280
+ const data = await fetcher(controller.signal);
211
281
  if (controller.signal.aborted) return;
212
282
  const live = cache.get(signature);
213
283
  if (live === void 0 || live.inFlight !== controller) return;
@@ -216,6 +286,7 @@ const createPool = (client) => {
216
286
  data,
217
287
  error: void 0
218
288
  };
289
+ live.hasSuccessfulData = true;
219
290
  live.inFlight = void 0;
220
291
  notifyAll(signature);
221
292
  } catch (error) {
@@ -233,42 +304,93 @@ const createPool = (client) => {
233
304
  }
234
305
  })();
235
306
  };
236
- const invalidateForTable = (table) => {
307
+ const invalidateForTable = (table, skipSignature, dispatchedSignatures) => {
237
308
  for (const [signature, entry] of cache) {
238
- if (!entry.chainTables.has(table)) continue;
309
+ if (!entry.chainTables.has(table) || signature === skipSignature || dispatchedSignatures?.has(signature)) continue;
239
310
  const subs = subscribersBySignature.get(signature);
240
311
  if (subs === void 0 || subs.size === 0) continue;
241
312
  const fetcher = signatureFetchers.get(signature);
242
- if (fetcher !== void 0) dispatchFetch(signature, fetcher);
313
+ if (fetcher !== void 0) {
314
+ dispatchedSignatures?.add(signature);
315
+ dispatchFetch(signature, fetcher);
316
+ }
317
+ }
318
+ };
319
+ const failForTable = (table, error) => {
320
+ for (const [signature, entry] of cache) {
321
+ if (!entry.chainTables.has(table)) continue;
322
+ const subs = subscribersBySignature.get(signature);
323
+ if (subs === void 0 || subs.size === 0) continue;
324
+ entry.inFlight?.abort();
325
+ entry.inFlight = void 0;
326
+ entry.snapshot = {
327
+ status: "error",
328
+ data: entry.snapshot.data,
329
+ error
330
+ };
331
+ notifyAll(signature);
243
332
  }
244
333
  };
245
334
  /** Per-signature fetcher; last writer wins (all fetchers for a signature are equivalent). */
246
335
  const signatureFetchers = /* @__PURE__ */ new Map();
247
- const startTablePoll = (table) => {
336
+ const startTablePoll = (table, initialRefcount = 1) => {
248
337
  if (tablePolls.has(table)) return;
249
338
  const controller = new AbortController();
250
339
  const poll = {
251
- refcount: 1,
340
+ refcount: initialRefcount,
252
341
  controller,
253
- cursor: ""
342
+ cursor: "",
343
+ terminalError: void 0
254
344
  };
255
345
  tablePolls.set(table, poll);
256
346
  const ctx = getClientContext(client);
257
347
  (async () => {
258
- while (!controller.signal.aborted) try {
259
- const res = await pollSinceOnce(ctx, table, poll.cursor, controller.signal);
260
- if (controller.signal.aborted) return;
261
- if (res.events.length > 0 || res.next_cursor !== poll.cursor) {
262
- poll.cursor = res.next_cursor;
263
- if (res.events.length > 0) invalidateForTable(table);
348
+ let retryAttempt = 0;
349
+ let deadCursorRecoveryPending = false;
350
+ while (!controller.signal.aborted) {
351
+ const requestCursor = poll.cursor;
352
+ try {
353
+ const res = await pollSinceOnce(ctx, table, requestCursor, controller.signal);
354
+ if (controller.signal.aborted) return;
355
+ if (res.events.length > 0 || res.next_cursor !== poll.cursor) {
356
+ poll.cursor = res.next_cursor;
357
+ if (res.events.length > 0) invalidateForTable(table);
358
+ }
359
+ if (!deadCursorRecoveryPending || requestCursor !== "" || res.next_cursor === "") {
360
+ retryAttempt = 0;
361
+ deadCursorRecoveryPending = false;
362
+ }
363
+ } catch (error) {
364
+ if (controller.signal.aborted) return;
365
+ if (isAbortError(error)) return;
366
+ let recoveredDeadCursor = false;
367
+ if (error instanceof BaerlyError && error.code === "CursorExpired" && poll.cursor !== "") {
368
+ poll.cursor = "";
369
+ deadCursorRecoveryPending = true;
370
+ invalidateForTable(table);
371
+ recoveredDeadCursor = true;
372
+ }
373
+ if (!recoveredDeadCursor && error instanceof BaerlyError && !error.retriable) {
374
+ poll.terminalError = error;
375
+ failForTable(table, error);
376
+ return;
377
+ }
378
+ const delay = pollRetryDelay(retryAttempt, error);
379
+ retryAttempt += 1;
380
+ await waitForRetry(delay, controller.signal);
264
381
  }
265
- } catch (error) {
266
- if (controller.signal.aborted) return;
267
- if (error instanceof DOMException && error.name === "AbortError") return;
268
- await new Promise((r) => setTimeout(r, 1e3));
269
382
  }
270
383
  })();
271
384
  };
385
+ const restartTerminalPoll = (table) => {
386
+ const poll = tablePolls.get(table);
387
+ if (poll?.terminalError === void 0) return false;
388
+ const refcount = poll.refcount;
389
+ poll.controller.abort();
390
+ tablePolls.delete(table);
391
+ startTablePoll(table, refcount);
392
+ return true;
393
+ };
272
394
  const stopTablePoll = (table) => {
273
395
  const poll = tablePolls.get(table);
274
396
  if (poll === void 0) return;
@@ -287,12 +409,23 @@ const createPool = (client) => {
287
409
  getSnapshot(signature) {
288
410
  return cache.get(signature)?.snapshot ?? LOADING_SNAPSHOT;
289
411
  },
412
+ refetch(signature) {
413
+ const entry = cache.get(signature);
414
+ const fetcher = signatureFetchers.get(signature);
415
+ if (entry === void 0 || fetcher === void 0) return;
416
+ const revived = [];
417
+ for (const table of entry.chainTables) if (restartTerminalPoll(table)) revived.push(table);
418
+ dispatchFetch(signature, fetcher);
419
+ const dispatchedSignatures = /* @__PURE__ */ new Set();
420
+ for (const table of revived) invalidateForTable(table, signature, dispatchedSignatures);
421
+ },
290
422
  attach(signature, tables, chainTables, fetcher, notify) {
291
423
  let entry = cache.get(signature);
292
424
  const isFirstSubscriber = entry === void 0;
293
425
  if (entry === void 0) {
294
426
  entry = {
295
427
  snapshot: LOADING_SNAPSHOT,
428
+ hasSuccessfulData: false,
296
429
  chainTables,
297
430
  inFlight: void 0
298
431
  };
@@ -326,8 +459,7 @@ const createPool = (client) => {
326
459
  }
327
460
  };
328
461
  };
329
- //#endregion
330
- //#region packages/client/src/react/use-query.ts
462
+ // packages/client/src/react/use-query.ts
331
463
  const SKIP = Symbol("baerly.useQuery.skip");
332
464
  const SKIPPED_SNAPSHOT = Object.freeze({
333
465
  status: "skipped",
@@ -441,10 +573,10 @@ const discover = (callback) => {
441
573
  };
442
574
  };
443
575
  /**
444
- * Reactive read against a `baerly` server. The callback receives a
576
+ * Read against a `baerly` server, live by default. The callback receives a
445
577
  * type-compatible `BaerlyClient` proxy that records which collections it
446
- * touches; the hook subscribes to those collections and re-runs the
447
- * callback against the real client when any of them mutate.
578
+ * touches; in live mode, the hook subscribes to those collections and
579
+ * re-runs the callback against the real client when any of them mutate.
448
580
  *
449
581
  * Re-runs also fire whenever the `deps` array changes between
450
582
  * renders (shallow `stableKey` compare). Closure variables read
@@ -456,6 +588,12 @@ const discover = (callback) => {
456
588
  * `{ status: "skipped" }` and registers no subscription — use it
457
589
  * for deferred / conditional reads.
458
590
  *
591
+ * Pass `{ live: false }` as the third argument to perform the initial
592
+ * read and dependency-driven re-reads without opening `/v1/since`.
593
+ * Every result state includes a stable `refetch()` function for an
594
+ * explicit refresh; successful data remains available while that
595
+ * refresh is running and if it fails.
596
+ *
459
597
  * @example
460
598
  * ```tsx
461
599
  * // Single read
@@ -471,6 +609,14 @@ const discover = (callback) => {
471
609
  * );
472
610
  * if (list.status === "skipped") return null;
473
611
  *
612
+ * // Non-live read with an explicit refresh
613
+ * const report = useQuery(
614
+ * (c) => c.collection("notes").all(),
615
+ * [],
616
+ * { live: false },
617
+ * );
618
+ * <button onClick={report.refetch}>Refresh</button>;
619
+ *
474
620
  * // Dependent read (parent → child)
475
621
  * const parent = useQuery((c) => c.collection("notes").get(id), [id]);
476
622
  * const replies = useQuery(
@@ -481,16 +627,21 @@ const discover = (callback) => {
481
627
  * );
482
628
  * ```
483
629
  */
484
- const useQueryImpl = (callback, deps) => {
630
+ const useQueryImpl = (callback, deps, options) => {
485
631
  const client = useBaerlyClient();
486
632
  const pool = poolFor(client);
633
+ const live = options?.live !== false;
487
634
  const callbackRef = useRef(callback);
488
635
  callbackRef.current = callback;
489
636
  const [, forceUpdate] = useReducer((c) => c + 1, 0);
490
637
  const asyncErrorRef = useRef(void 0);
491
638
  const discovery = discover(callbackRef.current);
492
639
  const depsKey = stableKey([deps ?? []]);
493
- const signatureBase = discovery.kind === "ok" ? stableKey([discovery.chainShape, deps ?? []]) : `__non_ok__${discovery.kind}__${depsKey}`;
640
+ const signatureBase = discovery.kind === "ok" ? stableKey([
641
+ discovery.chainShape,
642
+ deps ?? [],
643
+ live
644
+ ]) : `__non_ok__${discovery.kind}__${depsKey}__${String(live)}`;
494
645
  const lastSignatureRef = useRef("");
495
646
  if (lastSignatureRef.current !== signatureBase) {
496
647
  lastSignatureRef.current = signatureBase;
@@ -507,8 +658,8 @@ const useQueryImpl = (callback, deps) => {
507
658
  }
508
659
  const collectionsJoin = discovery.kind === "ok" ? discovery.collections.join("\0") : "__non_ok__";
509
660
  const fetcherRef = useRef(() => Promise.resolve(void 0));
510
- fetcherRef.current = () => {
511
- const out = callbackRef.current(client);
661
+ fetcherRef.current = (signal) => {
662
+ const out = callbackRef.current(withSignal(client, signal));
512
663
  if (out === SKIP) return Promise.resolve(void 0);
513
664
  return out;
514
665
  };
@@ -517,18 +668,33 @@ const useQueryImpl = (callback, deps) => {
517
668
  const discoveryErrorRef = useRef(void 0);
518
669
  discoveryKindRef.current = discovery.kind;
519
670
  if (discovery.kind === "ok") {
520
- chainCollectionsRef.current = new Set(discovery.collections);
671
+ chainCollectionsRef.current = live ? new Set(discovery.collections) : /* @__PURE__ */ new Set();
521
672
  discoveryErrorRef.current = void 0;
522
673
  } else if (discovery.kind === "error") discoveryErrorRef.current = discovery.error;
523
674
  else discoveryErrorRef.current = void 0;
524
675
  const subscribe = useCallback((notify) => {
525
676
  if (discovery.kind !== "ok") return () => {};
526
- return pool.attach(signatureBase, discovery.collections, chainCollectionsRef.current, () => fetcherRef.current(), notify);
677
+ return pool.attach(signatureBase, live ? discovery.collections : [], chainCollectionsRef.current, (signal) => fetcherRef.current(signal), notify);
527
678
  }, [
528
679
  pool,
529
680
  signatureBase,
530
681
  collectionsJoin
531
682
  ]);
683
+ const refetchTargetRef = useRef({
684
+ kind: discovery.kind,
685
+ pool,
686
+ signature: signatureBase
687
+ });
688
+ refetchTargetRef.current = {
689
+ kind: discovery.kind,
690
+ pool,
691
+ signature: signatureBase
692
+ };
693
+ const refetch = useCallback(() => {
694
+ const target = refetchTargetRef.current;
695
+ if (target.kind === "ok") target.pool.refetch(target.signature);
696
+ else forceUpdate();
697
+ }, []);
532
698
  const errorSnapshotRef = useRef(void 0);
533
699
  const snapshotForError = (err) => {
534
700
  if (errorSnapshotRef.current?.error === err) return errorSnapshotRef.current.snapshot;
@@ -543,22 +709,35 @@ const useQueryImpl = (callback, deps) => {
543
709
  };
544
710
  return snapshot;
545
711
  };
712
+ const decoratedSnapshotRef = useRef(void 0);
713
+ const withRefetch = (base) => {
714
+ if (decoratedSnapshotRef.current?.base === base) return decoratedSnapshotRef.current.snapshot;
715
+ const snapshot = {
716
+ ...base,
717
+ refetch
718
+ };
719
+ decoratedSnapshotRef.current = {
720
+ base,
721
+ snapshot
722
+ };
723
+ return snapshot;
724
+ };
546
725
  const getSnapshot = useCallback(() => {
547
- if (asyncErrorRef.current) return snapshotForError(asyncErrorRef.current);
548
- if (discoveryKindRef.current === "skip") return SKIPPED_SNAPSHOT;
549
- if (discoveryKindRef.current === "error") return snapshotForError(discoveryErrorRef.current ?? new BaerlyError("Internal", "unknown discovery error"));
550
- return pool.getSnapshot(signatureBase);
726
+ if (asyncErrorRef.current) return withRefetch(snapshotForError(asyncErrorRef.current));
727
+ if (discoveryKindRef.current === "skip") return withRefetch(SKIPPED_SNAPSHOT);
728
+ if (discoveryKindRef.current === "error") return withRefetch(snapshotForError(discoveryErrorRef.current ?? new BaerlyError("Internal", "unknown discovery error")));
729
+ return withRefetch(pool.getSnapshot(signatureBase));
551
730
  }, [pool, signatureBase]);
552
731
  return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
553
732
  };
554
733
  /**
555
- * Reactive read hook. See {@link useQueryImpl} JSDoc for usage.
734
+ * Read hook, live by default. See {@link useQueryImpl} JSDoc for usage.
556
735
  * The `.skip` property is the sentinel that short-circuits the hook
557
- * into `status: "skipped"`.
736
+ * into `status: "skipped"`; `{ live: false }` disables `/v1/since`
737
+ * while retaining initial reads, dependency re-runs, and `refetch()`.
558
738
  */
559
739
  const useQuery = Object.assign(useQueryImpl, { skip: SKIP });
560
- //#endregion
561
- //#region packages/client/src/react/create-react.ts
740
+ // packages/client/src/react/create-react.ts
562
741
  /**
563
742
  * Build the typed React surface for one `baerly.config.ts`. Call it
564
743
  * once at module scope and export the result; every hook is bound to
@@ -583,11 +762,19 @@ const useQuery = Object.assign(useQueryImpl, { skip: SKIP });
583
762
  * import { useQuery } from "./client.ts";
584
763
  * const notes = useQuery((c) => c.collection("notes").all(), []);
585
764
  * // ^? UseQueryResult<Note[]> — no cast
765
+ *
766
+ * const report = useQuery(
767
+ * (c) => c.collection("notes").all(),
768
+ * [],
769
+ * { live: false },
770
+ * );
771
+ * // report.refetch() re-runs the read without enabling live updates.
586
772
  * ```
587
773
  *
588
774
  * Omit the type parameter (`createBaerlyReact()`) for an unbound app;
589
- * collection names widen to `string` and rows to `DocumentData`,
590
- * matching the in-process `Db.collection` fallback.
775
+ * collection names widen to `string` and rows to
776
+ * `DocumentData & { _id: string }`, matching the in-process
777
+ * `Db.collection` fallback.
591
778
  */
592
779
  const createBaerlyReact = () => ({
593
780
  BaerlyProvider,
@@ -595,7 +782,6 @@ const createBaerlyReact = () => ({
595
782
  useMutation,
596
783
  useBaerlyClient
597
784
  });
598
- //#endregion
599
785
  export { createBaerlyReact };
600
786
 
601
787
  //# sourceMappingURL=client-react.js.map