@gusto/baerly-storage 0.1.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 +97 -0
- package/dist/API.md +850 -0
- package/dist/app-config-Cb5dO2s9.d.ts +480 -0
- package/dist/app-config.d.ts +2 -0
- package/dist/app-config.js +8 -0
- package/dist/app-config.js.map +1 -0
- package/dist/auth.d.ts +237 -0
- package/dist/auth.js +1335 -0
- package/dist/auth.js.map +1 -0
- package/dist/baerly.js +761 -0
- package/dist/baerly.js.map +1 -0
- package/dist/bucket-uri-BrDEYvzy.js +4922 -0
- package/dist/bucket-uri-BrDEYvzy.js.map +1 -0
- package/dist/chunk-EAsCxrDo.js +14 -0
- package/dist/client-BLf3Ae5s.d.ts +233 -0
- package/dist/client-react.d.ts +131 -0
- package/dist/client-react.js +559 -0
- package/dist/client-react.js.map +1 -0
- package/dist/client.d.ts +4 -0
- package/dist/client.js +160 -0
- package/dist/client.js.map +1 -0
- package/dist/cloudflare-CINJPKCW.js +911 -0
- package/dist/cloudflare-CINJPKCW.js.map +1 -0
- package/dist/cloudflare.d.ts +211 -0
- package/dist/cloudflare.js +445 -0
- package/dist/cloudflare.js.map +1 -0
- package/dist/config-Bsg8wgwo.js +198 -0
- package/dist/config-Bsg8wgwo.js.map +1 -0
- package/dist/context-Oj7ffwD-.js +187 -0
- package/dist/context-Oj7ffwD-.js.map +1 -0
- package/dist/cost-B1WiZxlf.js +203 -0
- package/dist/cost-B1WiZxlf.js.map +1 -0
- package/dist/current-json-BkatBzF7.js +252 -0
- package/dist/current-json-BkatBzF7.js.map +1 -0
- package/dist/db-D62JguBc.d.ts +336 -0
- package/dist/deploy-BB-wqbhf.js +83 -0
- package/dist/deploy-BB-wqbhf.js.map +1 -0
- package/dist/dev-banner-CWHIk8tH.d.ts +26 -0
- package/dist/dev-vite.d.ts +146 -0
- package/dist/dev-vite.js +223 -0
- package/dist/dev-vite.js.map +1 -0
- package/dist/dev.d.ts +3 -0
- package/dist/dev.js +2 -0
- package/dist/doctor-B8h9GCN9.js +331 -0
- package/dist/doctor-B8h9GCN9.js.map +1 -0
- package/dist/dump-BHo_sIMZ.js +116 -0
- package/dist/dump-BHo_sIMZ.js.map +1 -0
- package/dist/errors-DOdL95kK.js +58 -0
- package/dist/errors-DOdL95kK.js.map +1 -0
- package/dist/export-Dz2PZKSR.js +423 -0
- package/dist/export-Dz2PZKSR.js.map +1 -0
- package/dist/fsck-DEz9lyCy.js +293 -0
- package/dist/fsck-DEz9lyCy.js.map +1 -0
- package/dist/http-CjUO1Bec.js +1756 -0
- package/dist/http-CjUO1Bec.js.map +1 -0
- package/dist/http.d.ts +1619 -0
- package/dist/http.js +2 -0
- package/dist/index-BGC-ENnj.d.ts +1065 -0
- package/dist/index-BYv0hb8M.d.ts +1457 -0
- package/dist/index-BquQkhJi.d.ts +112 -0
- package/dist/index-COsQ-Mlz.d.ts +146 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +6 -0
- package/dist/indexes-BXn7a06a.js +297 -0
- package/dist/indexes-BXn7a06a.js.map +1 -0
- package/dist/indexes-DwOXkn1Y.d.ts +22 -0
- package/dist/inspect-x02aFWnh.js +149 -0
- package/dist/inspect-x02aFWnh.js.map +1 -0
- package/dist/log-walk-DIru96UT.js +260 -0
- package/dist/log-walk-DIru96UT.js.map +1 -0
- package/dist/maintenance-Bn6ul9aV.js +758 -0
- package/dist/maintenance-Bn6ul9aV.js.map +1 -0
- package/dist/maintenance.d.ts +323 -0
- package/dist/maintenance.js +2 -0
- package/dist/node.d.ts +422 -0
- package/dist/node.js +2 -0
- package/dist/normalize-XWY25_sG.js +133 -0
- package/dist/normalize-XWY25_sG.js.map +1 -0
- package/dist/observability-2IDYRuZK.js +2333 -0
- package/dist/observability-2IDYRuZK.js.map +1 -0
- package/dist/observability.d.ts +3 -0
- package/dist/observability.js +3 -0
- package/dist/plan-Cs17VqjU.js +224 -0
- package/dist/plan-Cs17VqjU.js.map +1 -0
- package/dist/query-DcSbFLJt.js +1880 -0
- package/dist/query-DcSbFLJt.js.map +1 -0
- package/dist/rebuild-index-C5gTXryd.js +119 -0
- package/dist/rebuild-index-C5gTXryd.js.map +1 -0
- package/dist/rebuild-index-DwXM0WfA.js +104 -0
- package/dist/rebuild-index-DwXM0WfA.js.map +1 -0
- package/dist/request-BEF_OvMh.js +72 -0
- package/dist/request-BEF_OvMh.js.map +1 -0
- package/dist/restore-CbKVMMpm.js +847 -0
- package/dist/restore-CbKVMMpm.js.map +1 -0
- package/dist/shared-secret-BJdSwpgw.js +71 -0
- package/dist/shared-secret-BJdSwpgw.js.map +1 -0
- package/dist/snapshot-D7C4_FSl.js +71 -0
- package/dist/snapshot-D7C4_FSl.js.map +1 -0
- package/dist/snapshot-z_N9hpTe.js +917 -0
- package/dist/snapshot-z_N9hpTe.js.map +1 -0
- package/dist/src-Chafbw8r.js +522 -0
- package/dist/src-Chafbw8r.js.map +1 -0
- package/dist/src-DyET_VPP.js +6199 -0
- package/dist/src-DyET_VPP.js.map +1 -0
- package/dist/src-n0Te1r98.js +352 -0
- package/dist/src-n0Te1r98.js.map +1 -0
- package/dist/subcommand-BWs6K7zb.js +110 -0
- package/dist/subcommand-BWs6K7zb.js.map +1 -0
- package/dist/usage-RVUQMLop.js +339 -0
- package/dist/usage-RVUQMLop.js.map +1 -0
- package/dist/validate-DhH1lO8I.js +377 -0
- package/dist/validate-DhH1lO8I.js.map +1 -0
- package/dist/wire-izfGZDvr.js +7 -0
- package/dist/wire-izfGZDvr.js.map +1 -0
- package/package.json +189 -0
|
@@ -0,0 +1,559 @@
|
|
|
1
|
+
import { t as BaerlyError } from "./errors-DOdL95kK.js";
|
|
2
|
+
import { r as getClientContext, t as request } from "./request-BEF_OvMh.js";
|
|
3
|
+
import { createContext, createElement, useCallback, useContext, useEffect, useMemo, useReducer, useRef, useState, useSyncExternalStore } from "react";
|
|
4
|
+
//#region packages/client/src/react/provider.ts
|
|
5
|
+
const ClientContext = createContext(void 0);
|
|
6
|
+
/**
|
|
7
|
+
* Provides a {@link BaerlyClient} to every Baerly React hook below it.
|
|
8
|
+
* Wrap your app once near the root; the hooks read the client from
|
|
9
|
+
* this context and have no `client` argument.
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* ```tsx
|
|
13
|
+
* import { createBaerlyClient } from "@gusto/baerly-storage/client";
|
|
14
|
+
* import { BaerlyProvider } from "@gusto/baerly-storage/client/react";
|
|
15
|
+
*
|
|
16
|
+
* const client = createBaerlyClient({ baseUrl: "/api" });
|
|
17
|
+
*
|
|
18
|
+
* <BaerlyProvider client={client}>
|
|
19
|
+
* <App />
|
|
20
|
+
* </BaerlyProvider>
|
|
21
|
+
* ```
|
|
22
|
+
*/
|
|
23
|
+
const BaerlyProvider = ({ client, children }) => createElement(ClientContext.Provider, { value: client }, children);
|
|
24
|
+
/**
|
|
25
|
+
* Returns the {@link BaerlyClient} provided by the nearest
|
|
26
|
+
* {@link BaerlyProvider}. Throws a clear error if called outside a
|
|
27
|
+
* provider — every hook in this package uses it, so a missing
|
|
28
|
+
* provider surfaces here first.
|
|
29
|
+
*
|
|
30
|
+
* Use this directly when you need imperative access — e.g. inside an
|
|
31
|
+
* event handler that performs a one-shot read or a custom long-poll.
|
|
32
|
+
* For declarative reads and mutations, prefer the typed hooks.
|
|
33
|
+
*
|
|
34
|
+
* @example
|
|
35
|
+
* ```tsx
|
|
36
|
+
* const client = useBaerlyClient<MyConfig>();
|
|
37
|
+
* const onExport = async () => {
|
|
38
|
+
* const rows = await client.collection("tickets").all();
|
|
39
|
+
* download(rows);
|
|
40
|
+
* };
|
|
41
|
+
* ```
|
|
42
|
+
*/
|
|
43
|
+
const useBaerlyClient = () => {
|
|
44
|
+
const client = useContext(ClientContext);
|
|
45
|
+
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>.");
|
|
46
|
+
return client;
|
|
47
|
+
};
|
|
48
|
+
//#endregion
|
|
49
|
+
//#region packages/client/src/react/stable-key.ts
|
|
50
|
+
/**
|
|
51
|
+
* Deterministic JSON serialization with sorted object keys. `useQuery`
|
|
52
|
+
* feeds its `[chainShape, deps]` tuple into this to compute the
|
|
53
|
+
* read-signature that keys the subscription-pool's result cache.
|
|
54
|
+
* Sorting keys means `{ a: 1, b: 2 }` and `{ b: 2, a: 1 }` stringify
|
|
55
|
+
* identically, which `JSON.stringify` alone does not guarantee (it
|
|
56
|
+
* preserves insertion order).
|
|
57
|
+
*
|
|
58
|
+
* Inputs are caller-declared `deps` plus the deterministic chain
|
|
59
|
+
* shape — no `undefined`, no functions, no circular references — so
|
|
60
|
+
* a recursive walk terminates and the output is well-defined. Arrays
|
|
61
|
+
* are serialized positionally.
|
|
62
|
+
*
|
|
63
|
+
* @internal
|
|
64
|
+
*/
|
|
65
|
+
const stableKey = (value) => {
|
|
66
|
+
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
|
67
|
+
if (Array.isArray(value)) return `[${value.map(stableKey).join(",")}]`;
|
|
68
|
+
return `{${Object.entries(value).toSorted(([a], [b]) => compareStrings(a, b)).map(([k, v]) => `${JSON.stringify(k)}:${stableKey(v)}`).join(",")}}`;
|
|
69
|
+
};
|
|
70
|
+
const compareStrings = (a, b) => {
|
|
71
|
+
if (a < b) return -1;
|
|
72
|
+
if (a > b) return 1;
|
|
73
|
+
return 0;
|
|
74
|
+
};
|
|
75
|
+
//#endregion
|
|
76
|
+
//#region packages/client/src/poll-since-once.ts
|
|
77
|
+
/**
|
|
78
|
+
* One round-trip of `GET /v1/since?collection=…&cursor=…`. The single
|
|
79
|
+
* place that talks to `/v1/since` in this package — the React
|
|
80
|
+
* `subscription-pool` is its only first-party consumer.
|
|
81
|
+
*
|
|
82
|
+
* Long-poll semantics live server-side: the call resolves once the
|
|
83
|
+
* server's budget elapses (`{ events: [], next_cursor: <same> }`) or
|
|
84
|
+
* one or more events arrive. Callers are expected to loop over this
|
|
85
|
+
* helper, threading `next_cursor` through.
|
|
86
|
+
*
|
|
87
|
+
* `cursor === ""` means "start at `log_seq_start`" (the wire
|
|
88
|
+
* protocol); pass the previously returned `next_cursor` to resume.
|
|
89
|
+
*
|
|
90
|
+
* `signal` cancels the underlying fetch via the standard
|
|
91
|
+
* `AbortController` plumbing; the rejection propagates as
|
|
92
|
+
* `AbortError`.
|
|
93
|
+
*/
|
|
94
|
+
const pollSinceOnce = async (ctx, name, cursor, signal) => {
|
|
95
|
+
const params = new URLSearchParams();
|
|
96
|
+
params.set("collection", name);
|
|
97
|
+
params.set("cursor", cursor);
|
|
98
|
+
return request(ctx, {
|
|
99
|
+
method: "GET",
|
|
100
|
+
path: `/v1/since?${params.toString()}`,
|
|
101
|
+
signal
|
|
102
|
+
});
|
|
103
|
+
};
|
|
104
|
+
//#endregion
|
|
105
|
+
//#region packages/client/src/react/subscription-pool.ts
|
|
106
|
+
const LOADING_SNAPSHOT = Object.freeze({
|
|
107
|
+
status: "loading",
|
|
108
|
+
data: void 0,
|
|
109
|
+
error: void 0
|
|
110
|
+
});
|
|
111
|
+
const toError = (raw) => {
|
|
112
|
+
if (raw instanceof BaerlyError || raw instanceof Error) return raw;
|
|
113
|
+
return new BaerlyError("Internal", String(raw));
|
|
114
|
+
};
|
|
115
|
+
const poolByClient = /* @__PURE__ */ new WeakMap();
|
|
116
|
+
/** Returns the (lazily-created) pool for `client`. */
|
|
117
|
+
const poolFor = (client) => {
|
|
118
|
+
let pool = poolByClient.get(client);
|
|
119
|
+
if (pool === void 0) {
|
|
120
|
+
pool = createPool(client);
|
|
121
|
+
poolByClient.set(client, pool);
|
|
122
|
+
}
|
|
123
|
+
return pool;
|
|
124
|
+
};
|
|
125
|
+
const createPool = (client) => {
|
|
126
|
+
const cache = /* @__PURE__ */ new Map();
|
|
127
|
+
const subscribersBySignature = /* @__PURE__ */ new Map();
|
|
128
|
+
const tablePolls = /* @__PURE__ */ new Map();
|
|
129
|
+
const notifyAll = (signature) => {
|
|
130
|
+
const subs = subscribersBySignature.get(signature);
|
|
131
|
+
if (subs === void 0) return;
|
|
132
|
+
for (const notify of subs) notify();
|
|
133
|
+
};
|
|
134
|
+
const dispatchFetch = (signature, fetcher) => {
|
|
135
|
+
const entry = cache.get(signature);
|
|
136
|
+
if (entry === void 0) return;
|
|
137
|
+
if (entry.inFlight !== void 0) entry.inFlight.abort();
|
|
138
|
+
const controller = new AbortController();
|
|
139
|
+
entry.inFlight = controller;
|
|
140
|
+
const prevSnapshot = entry.snapshot;
|
|
141
|
+
entry.snapshot = entry.snapshot.status === "ok" || entry.snapshot.status === "refreshing" ? {
|
|
142
|
+
status: "refreshing",
|
|
143
|
+
data: entry.snapshot.data,
|
|
144
|
+
error: void 0
|
|
145
|
+
} : LOADING_SNAPSHOT;
|
|
146
|
+
if (entry.snapshot !== prevSnapshot) notifyAll(signature);
|
|
147
|
+
(async () => {
|
|
148
|
+
try {
|
|
149
|
+
const data = await fetcher();
|
|
150
|
+
if (controller.signal.aborted) return;
|
|
151
|
+
const live = cache.get(signature);
|
|
152
|
+
if (live === void 0 || live.inFlight !== controller) return;
|
|
153
|
+
live.snapshot = {
|
|
154
|
+
status: "ok",
|
|
155
|
+
data,
|
|
156
|
+
error: void 0
|
|
157
|
+
};
|
|
158
|
+
live.inFlight = void 0;
|
|
159
|
+
notifyAll(signature);
|
|
160
|
+
} catch (error) {
|
|
161
|
+
if (controller.signal.aborted) return;
|
|
162
|
+
const live = cache.get(signature);
|
|
163
|
+
if (live === void 0 || live.inFlight !== controller) return;
|
|
164
|
+
const wrapped = toError(error);
|
|
165
|
+
live.snapshot = {
|
|
166
|
+
status: "error",
|
|
167
|
+
data: live.snapshot.data,
|
|
168
|
+
error: wrapped
|
|
169
|
+
};
|
|
170
|
+
live.inFlight = void 0;
|
|
171
|
+
notifyAll(signature);
|
|
172
|
+
}
|
|
173
|
+
})();
|
|
174
|
+
};
|
|
175
|
+
const invalidateForTable = (table) => {
|
|
176
|
+
for (const [signature, entry] of cache) {
|
|
177
|
+
if (!entry.chainTables.has(table)) continue;
|
|
178
|
+
const subs = subscribersBySignature.get(signature);
|
|
179
|
+
if (subs === void 0 || subs.size === 0) continue;
|
|
180
|
+
const fetcher = signatureFetchers.get(signature);
|
|
181
|
+
if (fetcher !== void 0) dispatchFetch(signature, fetcher);
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
/** Per-signature fetcher; last writer wins (all fetchers for a signature are equivalent). */
|
|
185
|
+
const signatureFetchers = /* @__PURE__ */ new Map();
|
|
186
|
+
const startTablePoll = (table) => {
|
|
187
|
+
if (tablePolls.has(table)) return;
|
|
188
|
+
const controller = new AbortController();
|
|
189
|
+
const poll = {
|
|
190
|
+
refcount: 1,
|
|
191
|
+
controller,
|
|
192
|
+
cursor: ""
|
|
193
|
+
};
|
|
194
|
+
tablePolls.set(table, poll);
|
|
195
|
+
const ctx = getClientContext(client);
|
|
196
|
+
(async () => {
|
|
197
|
+
while (!controller.signal.aborted) try {
|
|
198
|
+
const res = await pollSinceOnce(ctx, table, poll.cursor, controller.signal);
|
|
199
|
+
if (controller.signal.aborted) return;
|
|
200
|
+
if (res.events.length > 0 || res.next_cursor !== poll.cursor) {
|
|
201
|
+
poll.cursor = res.next_cursor;
|
|
202
|
+
if (res.events.length > 0) invalidateForTable(table);
|
|
203
|
+
}
|
|
204
|
+
} catch (error) {
|
|
205
|
+
if (controller.signal.aborted) return;
|
|
206
|
+
if (error instanceof DOMException && error.name === "AbortError") return;
|
|
207
|
+
await new Promise((r) => setTimeout(r, 1e3));
|
|
208
|
+
}
|
|
209
|
+
})();
|
|
210
|
+
};
|
|
211
|
+
const stopTablePoll = (table) => {
|
|
212
|
+
const poll = tablePolls.get(table);
|
|
213
|
+
if (poll === void 0) return;
|
|
214
|
+
poll.refcount--;
|
|
215
|
+
if (poll.refcount === 0) {
|
|
216
|
+
poll.controller.abort();
|
|
217
|
+
tablePolls.delete(table);
|
|
218
|
+
}
|
|
219
|
+
};
|
|
220
|
+
const incrementTablePoll = (table) => {
|
|
221
|
+
const poll = tablePolls.get(table);
|
|
222
|
+
if (poll === void 0) startTablePoll(table);
|
|
223
|
+
else poll.refcount++;
|
|
224
|
+
};
|
|
225
|
+
return {
|
|
226
|
+
getSnapshot(signature) {
|
|
227
|
+
return cache.get(signature)?.snapshot ?? LOADING_SNAPSHOT;
|
|
228
|
+
},
|
|
229
|
+
attach(signature, tables, chainTables, fetcher, notify) {
|
|
230
|
+
let entry = cache.get(signature);
|
|
231
|
+
const isFirstSubscriber = entry === void 0;
|
|
232
|
+
if (entry === void 0) {
|
|
233
|
+
entry = {
|
|
234
|
+
snapshot: LOADING_SNAPSHOT,
|
|
235
|
+
chainTables,
|
|
236
|
+
inFlight: void 0
|
|
237
|
+
};
|
|
238
|
+
cache.set(signature, entry);
|
|
239
|
+
}
|
|
240
|
+
signatureFetchers.set(signature, fetcher);
|
|
241
|
+
let subs = subscribersBySignature.get(signature);
|
|
242
|
+
if (subs === void 0) {
|
|
243
|
+
subs = /* @__PURE__ */ new Set();
|
|
244
|
+
subscribersBySignature.set(signature, subs);
|
|
245
|
+
}
|
|
246
|
+
subs.add(notify);
|
|
247
|
+
for (const table of tables) incrementTablePoll(table);
|
|
248
|
+
if (isFirstSubscriber) dispatchFetch(signature, fetcher);
|
|
249
|
+
return () => {
|
|
250
|
+
const liveSubs = subscribersBySignature.get(signature);
|
|
251
|
+
if (liveSubs !== void 0) {
|
|
252
|
+
liveSubs.delete(notify);
|
|
253
|
+
if (liveSubs.size === 0) {
|
|
254
|
+
subscribersBySignature.delete(signature);
|
|
255
|
+
const liveEntry = cache.get(signature);
|
|
256
|
+
if (liveEntry !== void 0) {
|
|
257
|
+
liveEntry.inFlight?.abort();
|
|
258
|
+
cache.delete(signature);
|
|
259
|
+
}
|
|
260
|
+
signatureFetchers.delete(signature);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
for (const table of tables) stopTablePoll(table);
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
};
|
|
267
|
+
};
|
|
268
|
+
//#endregion
|
|
269
|
+
//#region packages/client/src/react/use-query.ts
|
|
270
|
+
const SKIP = Symbol("baerly.useQuery.skip");
|
|
271
|
+
const SKIPPED_SNAPSHOT = Object.freeze({
|
|
272
|
+
status: "skipped",
|
|
273
|
+
data: void 0,
|
|
274
|
+
error: void 0
|
|
275
|
+
});
|
|
276
|
+
const WRITE_METHODS = new Set([
|
|
277
|
+
"insert",
|
|
278
|
+
"update",
|
|
279
|
+
"replace",
|
|
280
|
+
"delete"
|
|
281
|
+
]);
|
|
282
|
+
const awaitedError = (prop) => new BaerlyError("UseQueryAwaitedRecorder", `useQuery callbacks must not dereference the result of an awaited recorder terminal — property access (${String(prop)}) on the awaited value throws. The recorder is for the synchronous prefix of the callback only. For compound reads, use Promise.all (parallel) or compose two useQuery calls with useQuery.skip (dependent). See the lint rule baerly/no-await-in-use-query for the edit-time check.`);
|
|
283
|
+
/**
|
|
284
|
+
* Sentinel handed back when a recorder terminal is awaited. Every
|
|
285
|
+
* own-property access throws `BaerlyError("UseQueryAwaitedRecorder")`;
|
|
286
|
+
* `Symbol.*` accesses (which the JS engine uses internally —
|
|
287
|
+
* Symbol.toPrimitive, Symbol.iterator, etc.) return undefined so the
|
|
288
|
+
* sentinel can flow through engine-side coercions without spurious
|
|
289
|
+
* throws. The single shared instance avoids per-render allocation.
|
|
290
|
+
*/
|
|
291
|
+
const SENTINEL_SAFE_PROPS = new Set([
|
|
292
|
+
"then",
|
|
293
|
+
"catch",
|
|
294
|
+
"finally"
|
|
295
|
+
]);
|
|
296
|
+
const AWAITED_SENTINEL = new Proxy(Object.create(null), { get(_target, prop) {
|
|
297
|
+
if (typeof prop === "symbol" || SENTINEL_SAFE_PROPS.has(prop)) return;
|
|
298
|
+
throw awaitedError(prop);
|
|
299
|
+
} });
|
|
300
|
+
const TERMINAL_RESULT = Promise.resolve(AWAITED_SENTINEL);
|
|
301
|
+
const makeTerminal = () => TERMINAL_RESULT;
|
|
302
|
+
const makeQuery = (state) => {
|
|
303
|
+
const query = {};
|
|
304
|
+
for (const modifier of [
|
|
305
|
+
"where",
|
|
306
|
+
"order",
|
|
307
|
+
"limit"
|
|
308
|
+
]) query[modifier] = () => {
|
|
309
|
+
state.chain.push(modifier);
|
|
310
|
+
return query;
|
|
311
|
+
};
|
|
312
|
+
for (const terminal of [
|
|
313
|
+
"first",
|
|
314
|
+
"all",
|
|
315
|
+
"count"
|
|
316
|
+
]) query[terminal] = () => {
|
|
317
|
+
state.chain.push(terminal);
|
|
318
|
+
return makeTerminal();
|
|
319
|
+
};
|
|
320
|
+
return query;
|
|
321
|
+
};
|
|
322
|
+
const makeCollection = (name, state) => {
|
|
323
|
+
state.collectionsRead.add(name);
|
|
324
|
+
state.chain.push(`collection:${name}`);
|
|
325
|
+
const collection = { name };
|
|
326
|
+
for (const modifier of [
|
|
327
|
+
"where",
|
|
328
|
+
"order",
|
|
329
|
+
"limit"
|
|
330
|
+
]) collection[modifier] = () => {
|
|
331
|
+
state.chain.push(modifier);
|
|
332
|
+
return makeQuery(state);
|
|
333
|
+
};
|
|
334
|
+
for (const terminal of [
|
|
335
|
+
"first",
|
|
336
|
+
"all",
|
|
337
|
+
"count",
|
|
338
|
+
"get"
|
|
339
|
+
]) collection[terminal] = () => {
|
|
340
|
+
state.chain.push(terminal);
|
|
341
|
+
return makeTerminal();
|
|
342
|
+
};
|
|
343
|
+
for (const write of WRITE_METHODS) collection[write] = () => {
|
|
344
|
+
throw new BaerlyError("UnexpectedWriteInQuery", `useQuery callbacks must not write to the database. .${write}() was called on collection "${name}". Use useMutation() instead.`);
|
|
345
|
+
};
|
|
346
|
+
return collection;
|
|
347
|
+
};
|
|
348
|
+
const createRecorder = () => {
|
|
349
|
+
const state = {
|
|
350
|
+
collectionsRead: /* @__PURE__ */ new Set(),
|
|
351
|
+
chain: []
|
|
352
|
+
};
|
|
353
|
+
return {
|
|
354
|
+
client: {
|
|
355
|
+
collection: (name) => makeCollection(name, state),
|
|
356
|
+
healthz: () => {
|
|
357
|
+
throw new BaerlyError("UnexpectedWriteInQuery", "useQuery callbacks must not call client.healthz(); use useMutation() or the bare client.");
|
|
358
|
+
}
|
|
359
|
+
},
|
|
360
|
+
state
|
|
361
|
+
};
|
|
362
|
+
};
|
|
363
|
+
const discover = (callback) => {
|
|
364
|
+
const { client: recorder, state } = createRecorder();
|
|
365
|
+
let callbackResult;
|
|
366
|
+
try {
|
|
367
|
+
callbackResult = callback(recorder);
|
|
368
|
+
} catch (error) {
|
|
369
|
+
return {
|
|
370
|
+
kind: "error",
|
|
371
|
+
error: error instanceof Error ? error : new BaerlyError("Internal", String(error))
|
|
372
|
+
};
|
|
373
|
+
}
|
|
374
|
+
if (callbackResult === SKIP) return { kind: "skip" };
|
|
375
|
+
return {
|
|
376
|
+
kind: "ok",
|
|
377
|
+
collections: [...state.collectionsRead].toSorted(),
|
|
378
|
+
chainShape: stableKey(state.chain),
|
|
379
|
+
callbackResult
|
|
380
|
+
};
|
|
381
|
+
};
|
|
382
|
+
/**
|
|
383
|
+
* Reactive read against a `baerly` server. The callback receives a
|
|
384
|
+
* type-compatible `BaerlyClient` proxy that records which collections it
|
|
385
|
+
* touches; the hook subscribes to those collections and re-runs the
|
|
386
|
+
* callback against the real client when any of them mutate.
|
|
387
|
+
*
|
|
388
|
+
* Re-runs also fire whenever the `deps` array changes between
|
|
389
|
+
* renders (shallow `stableKey` compare). Closure variables read
|
|
390
|
+
* inside the callback must be listed in `deps` — the companion
|
|
391
|
+
* `baerly/exhaustive-deps-use-query` lint rule flags missing
|
|
392
|
+
* entries.
|
|
393
|
+
*
|
|
394
|
+
* Returning {@link useQuery.skip} from the callback yields
|
|
395
|
+
* `{ status: "skipped" }` and registers no subscription — use it
|
|
396
|
+
* for deferred / conditional reads.
|
|
397
|
+
*
|
|
398
|
+
* @example
|
|
399
|
+
* ```tsx
|
|
400
|
+
* // Single read
|
|
401
|
+
* const note = useQuery((c) => c.collection("notes").get(id), [id]);
|
|
402
|
+
* if (note.status === "loading") return <Spinner/>;
|
|
403
|
+
* if (note.status === "error") return <Err e={note.error}/>;
|
|
404
|
+
* return <pre>{note.data?.body}</pre>; // typed Note | undefined
|
|
405
|
+
*
|
|
406
|
+
* // Deferred read
|
|
407
|
+
* const list = useQuery(
|
|
408
|
+
* (c) => userId ? c.collection("notes").where({ authorId: userId }).all() : useQuery.skip,
|
|
409
|
+
* [userId],
|
|
410
|
+
* );
|
|
411
|
+
* if (list.status === "skipped") return null;
|
|
412
|
+
*
|
|
413
|
+
* // Dependent read (parent → child)
|
|
414
|
+
* const parent = useQuery((c) => c.collection("notes").get(id), [id]);
|
|
415
|
+
* const replies = useQuery(
|
|
416
|
+
* (c) => parent.status === "ok"
|
|
417
|
+
* ? c.collection("comments").where({ noteId: parent.data._id }).all()
|
|
418
|
+
* : useQuery.skip,
|
|
419
|
+
* [parent.status === "ok" ? parent.data._id : undefined],
|
|
420
|
+
* );
|
|
421
|
+
* ```
|
|
422
|
+
*/
|
|
423
|
+
const useQueryImpl = (callback, deps) => {
|
|
424
|
+
const client = useBaerlyClient();
|
|
425
|
+
const pool = poolFor(client);
|
|
426
|
+
const callbackRef = useRef(callback);
|
|
427
|
+
callbackRef.current = callback;
|
|
428
|
+
const [, forceUpdate] = useReducer((c) => c + 1, 0);
|
|
429
|
+
const asyncErrorRef = useRef(void 0);
|
|
430
|
+
const discovery = discover(callbackRef.current);
|
|
431
|
+
const depsKey = stableKey([deps ?? []]);
|
|
432
|
+
const signatureBase = discovery.kind === "ok" ? stableKey([discovery.chainShape, deps ?? []]) : `__non_ok__${discovery.kind}__${depsKey}`;
|
|
433
|
+
const lastSignatureRef = useRef("");
|
|
434
|
+
if (lastSignatureRef.current !== signatureBase) {
|
|
435
|
+
lastSignatureRef.current = signatureBase;
|
|
436
|
+
asyncErrorRef.current = void 0;
|
|
437
|
+
}
|
|
438
|
+
if (discovery.kind === "ok") {
|
|
439
|
+
const result = discovery.callbackResult;
|
|
440
|
+
if (result !== null && typeof result === "object" && typeof result.then === "function") Promise.resolve(result).then(() => {}, (error) => {
|
|
441
|
+
if (error instanceof BaerlyError && error.code === "UseQueryAwaitedRecorder" && asyncErrorRef.current === void 0) {
|
|
442
|
+
asyncErrorRef.current = error;
|
|
443
|
+
forceUpdate();
|
|
444
|
+
}
|
|
445
|
+
});
|
|
446
|
+
}
|
|
447
|
+
const collectionsJoin = discovery.kind === "ok" ? discovery.collections.join("\0") : "__non_ok__";
|
|
448
|
+
const fetcherRef = useRef(() => Promise.resolve(void 0));
|
|
449
|
+
fetcherRef.current = () => {
|
|
450
|
+
const out = callbackRef.current(client);
|
|
451
|
+
if (out === SKIP) return Promise.resolve(void 0);
|
|
452
|
+
return out;
|
|
453
|
+
};
|
|
454
|
+
const chainCollectionsRef = useRef(/* @__PURE__ */ new Set());
|
|
455
|
+
const discoveryKindRef = useRef("ok");
|
|
456
|
+
const discoveryErrorRef = useRef(void 0);
|
|
457
|
+
discoveryKindRef.current = discovery.kind;
|
|
458
|
+
if (discovery.kind === "ok") {
|
|
459
|
+
chainCollectionsRef.current = new Set(discovery.collections);
|
|
460
|
+
discoveryErrorRef.current = void 0;
|
|
461
|
+
} else if (discovery.kind === "error") discoveryErrorRef.current = discovery.error;
|
|
462
|
+
else discoveryErrorRef.current = void 0;
|
|
463
|
+
const subscribe = useCallback((notify) => {
|
|
464
|
+
if (discovery.kind !== "ok") return () => {};
|
|
465
|
+
return pool.attach(signatureBase, discovery.collections, chainCollectionsRef.current, () => fetcherRef.current(), notify);
|
|
466
|
+
}, [
|
|
467
|
+
pool,
|
|
468
|
+
signatureBase,
|
|
469
|
+
collectionsJoin
|
|
470
|
+
]);
|
|
471
|
+
const errorSnapshotRef = useRef(void 0);
|
|
472
|
+
const snapshotForError = (err) => {
|
|
473
|
+
if (errorSnapshotRef.current?.error === err) return errorSnapshotRef.current.snapshot;
|
|
474
|
+
const snapshot = {
|
|
475
|
+
status: "error",
|
|
476
|
+
data: void 0,
|
|
477
|
+
error: err
|
|
478
|
+
};
|
|
479
|
+
errorSnapshotRef.current = {
|
|
480
|
+
error: err,
|
|
481
|
+
snapshot
|
|
482
|
+
};
|
|
483
|
+
return snapshot;
|
|
484
|
+
};
|
|
485
|
+
const getSnapshot = useCallback(() => {
|
|
486
|
+
if (asyncErrorRef.current) return snapshotForError(asyncErrorRef.current);
|
|
487
|
+
if (discoveryKindRef.current === "skip") return SKIPPED_SNAPSHOT;
|
|
488
|
+
if (discoveryKindRef.current === "error") return snapshotForError(discoveryErrorRef.current ?? new BaerlyError("Internal", "unknown discovery error"));
|
|
489
|
+
return pool.getSnapshot(signatureBase);
|
|
490
|
+
}, [pool, signatureBase]);
|
|
491
|
+
return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
|
|
492
|
+
};
|
|
493
|
+
/**
|
|
494
|
+
* Reactive read hook. See {@link useQueryImpl} JSDoc for usage.
|
|
495
|
+
* The `.skip` property is the sentinel that short-circuits the hook
|
|
496
|
+
* into `status: "skipped"`.
|
|
497
|
+
*/
|
|
498
|
+
const useQuery = Object.assign(useQueryImpl, { skip: SKIP });
|
|
499
|
+
//#endregion
|
|
500
|
+
//#region packages/client/src/react/use-mutation.ts
|
|
501
|
+
/**
|
|
502
|
+
* Imperative mutation hook. `mutate(callback)` runs the callback
|
|
503
|
+
* against the real `BaerlyClient` and resolves to whatever the
|
|
504
|
+
* callback returns; `state` carries `isPending` (refcounted across
|
|
505
|
+
* concurrent submits — `true` until every in-flight call settles)
|
|
506
|
+
* and `error` (last-wins; the most recent rejection until the next
|
|
507
|
+
* successful call clears it).
|
|
508
|
+
*
|
|
509
|
+
* Errors are normalised to {@link BaerlyError}: a non-`BaerlyError`
|
|
510
|
+
* throwable from the callback is wrapped under
|
|
511
|
+
* `code: "MutationFailed"` with the original on `.cause`.
|
|
512
|
+
*
|
|
513
|
+
* @example
|
|
514
|
+
* ```tsx
|
|
515
|
+
* const [mutate, { isPending, error }] = useMutation();
|
|
516
|
+
* <button
|
|
517
|
+
* disabled={isPending}
|
|
518
|
+
* onClick={() => mutate((client) => client.collection("notes").insert({ body }))}
|
|
519
|
+
* >
|
|
520
|
+
* {isPending ? "Saving…" : "Save"}
|
|
521
|
+
* </button>
|
|
522
|
+
* {error ? <p>{error.message}</p> : null}
|
|
523
|
+
* ```
|
|
524
|
+
*/
|
|
525
|
+
const useMutation = () => {
|
|
526
|
+
const client = useBaerlyClient();
|
|
527
|
+
const inFlightRef = useRef(0);
|
|
528
|
+
const mountedRef = useRef(true);
|
|
529
|
+
const [isPending, setIsPending] = useState(false);
|
|
530
|
+
const [lastError, setLastError] = useState(void 0);
|
|
531
|
+
useEffect(() => () => {
|
|
532
|
+
mountedRef.current = false;
|
|
533
|
+
}, []);
|
|
534
|
+
return [useCallback(async (callback) => {
|
|
535
|
+
const wasIdle = inFlightRef.current === 0;
|
|
536
|
+
inFlightRef.current += 1;
|
|
537
|
+
if (wasIdle && mountedRef.current) {
|
|
538
|
+
setIsPending(true);
|
|
539
|
+
setLastError(void 0);
|
|
540
|
+
}
|
|
541
|
+
try {
|
|
542
|
+
return await callback(client);
|
|
543
|
+
} catch (error) {
|
|
544
|
+
const be = error instanceof BaerlyError ? error : new BaerlyError("MutationFailed", error instanceof Error ? error.message : String(error), error);
|
|
545
|
+
if (mountedRef.current) setLastError(be);
|
|
546
|
+
throw be;
|
|
547
|
+
} finally {
|
|
548
|
+
inFlightRef.current -= 1;
|
|
549
|
+
if (inFlightRef.current === 0 && mountedRef.current) setIsPending(false);
|
|
550
|
+
}
|
|
551
|
+
}, [client]), useMemo(() => ({
|
|
552
|
+
isPending,
|
|
553
|
+
error: lastError
|
|
554
|
+
}), [isPending, lastError])];
|
|
555
|
+
};
|
|
556
|
+
//#endregion
|
|
557
|
+
export { BaerlyProvider, useBaerlyClient, useMutation, useQuery };
|
|
558
|
+
|
|
559
|
+
//# sourceMappingURL=client-react.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client-react.js","names":[],"sources":["../packages/client/src/react/provider.ts","../packages/client/src/react/stable-key.ts","../packages/client/src/poll-since-once.ts","../packages/client/src/react/subscription-pool.ts","../packages/client/src/react/use-query.ts","../packages/client/src/react/use-mutation.ts"],"sourcesContent":["import { createContext, createElement, useContext, type ReactNode } from \"react\";\nimport type { BaerlyConfig, UnboundConfig } from \"@baerly/protocol\";\nimport type { BaerlyClient } from \"../client.ts\";\n\nconst ClientContext = createContext<BaerlyClient | undefined>(undefined);\n\nexport interface BaerlyProviderProps {\n readonly client: BaerlyClient;\n readonly children?: ReactNode;\n}\n\n/**\n * Provides a {@link BaerlyClient} to every Baerly React hook below it.\n * Wrap your app once near the root; the hooks read the client from\n * this context and have no `client` argument.\n *\n * @example\n * ```tsx\n * import { createBaerlyClient } from \"@gusto/baerly-storage/client\";\n * import { BaerlyProvider } from \"@gusto/baerly-storage/client/react\";\n *\n * const client = createBaerlyClient({ baseUrl: \"/api\" });\n *\n * <BaerlyProvider client={client}>\n * <App />\n * </BaerlyProvider>\n * ```\n */\nexport const BaerlyProvider = ({ client, children }: BaerlyProviderProps): React.JSX.Element =>\n createElement(ClientContext.Provider, { value: client }, children);\n\n/**\n * Returns the {@link BaerlyClient} provided by the nearest\n * {@link BaerlyProvider}. Throws a clear error if called outside a\n * provider — every hook in this package uses it, so a missing\n * provider surfaces here first.\n *\n * Use this directly when you need imperative access — e.g. inside an\n * event handler that performs a one-shot read or a custom long-poll.\n * For declarative reads and mutations, prefer the typed hooks.\n *\n * @example\n * ```tsx\n * const client = useBaerlyClient<MyConfig>();\n * const onExport = async () => {\n * const rows = await client.collection(\"tickets\").all();\n * download(rows);\n * };\n * ```\n */\nexport const useBaerlyClient = <\n TConfig extends BaerlyConfig = UnboundConfig,\n>(): BaerlyClient<TConfig> => {\n const client = useContext(ClientContext);\n if (client === undefined) {\n throw new Error(\n \"useBaerlyClient (and every Baerly React hook) must be used inside <BaerlyProvider>. \" +\n \"Wrap your app: <BaerlyProvider client={client}>…</BaerlyProvider>.\",\n );\n }\n return client as BaerlyClient<TConfig>;\n};\n","/**\n * Deterministic JSON serialization with sorted object keys. `useQuery`\n * feeds its `[chainShape, deps]` tuple into this to compute the\n * read-signature that keys the subscription-pool's result cache.\n * Sorting keys means `{ a: 1, b: 2 }` and `{ b: 2, a: 1 }` stringify\n * identically, which `JSON.stringify` alone does not guarantee (it\n * preserves insertion order).\n *\n * Inputs are caller-declared `deps` plus the deterministic chain\n * shape — no `undefined`, no functions, no circular references — so\n * a recursive walk terminates and the output is well-defined. Arrays\n * are serialized positionally.\n *\n * @internal\n */\nexport const stableKey = (value: unknown): string => {\n if (value === null || typeof value !== \"object\") {\n return JSON.stringify(value);\n }\n if (Array.isArray(value)) {\n return `[${value.map(stableKey).join(\",\")}]`;\n }\n const entries = Object.entries(value as Record<string, unknown>).toSorted(([a], [b]) =>\n compareStrings(a, b),\n );\n return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableKey(v)}`).join(\",\")}}`;\n};\n\n// Lex compare for object-key ordering. `localeCompare` is locale-aware\n// and would re-order BMP code points; we need byte-stable output so the\n// `useEffect` deps key is identical across machines.\nconst compareStrings = (a: string, b: string): number => {\n if (a < b) {\n return -1;\n }\n if (a > b) {\n return 1;\n }\n return 0;\n};\n","import type { SinceResponse } from \"./contract.ts\";\nimport { type RequestContext, request } from \"./request.ts\";\n\n/**\n * One round-trip of `GET /v1/since?collection=…&cursor=…`. The single\n * place that talks to `/v1/since` in this package — the React\n * `subscription-pool` is its only first-party consumer.\n *\n * Long-poll semantics live server-side: the call resolves once the\n * server's budget elapses (`{ events: [], next_cursor: <same> }`) or\n * one or more events arrive. Callers are expected to loop over this\n * helper, threading `next_cursor` through.\n *\n * `cursor === \"\"` means \"start at `log_seq_start`\" (the wire\n * protocol); pass the previously returned `next_cursor` to resume.\n *\n * `signal` cancels the underlying fetch via the standard\n * `AbortController` plumbing; the rejection propagates as\n * `AbortError`.\n */\nexport const pollSinceOnce = async (\n ctx: RequestContext,\n name: string,\n cursor: string,\n signal: AbortSignal | undefined,\n): Promise<SinceResponse> => {\n const params = new URLSearchParams();\n params.set(\"collection\", name);\n params.set(\"cursor\", cursor);\n return request<SinceResponse>(ctx, {\n method: \"GET\",\n path: `/v1/since?${params.toString()}`,\n signal,\n });\n};\n","import { BaerlyError } from \"@baerly/protocol\";\nimport type { BaerlyClient } from \"../client.ts\";\nimport { getClientContext } from \"../internal/context.ts\";\nimport { pollSinceOnce } from \"../poll-since-once.ts\";\n\n/**\n * Discriminated snapshot a hook hands back from `getSnapshot`. The\n * `useQuery` types narrow this further (data: T vs data: undefined);\n * the pool stores it generically so the cache can be a single\n * `Map<signature, CachedSnapshot>`.\n */\nexport interface CachedSnapshot {\n readonly status: \"loading\" | \"refreshing\" | \"ok\" | \"error\";\n readonly data: unknown;\n readonly error: Error | undefined;\n}\n\nexport const LOADING_SNAPSHOT: CachedSnapshot = Object.freeze({\n status: \"loading\",\n data: undefined,\n error: undefined,\n});\n\nconst toError = (raw: unknown): Error => {\n if (raw instanceof BaerlyError || raw instanceof Error) {\n return raw;\n }\n return new BaerlyError(\"Internal\", String(raw));\n};\n\ninterface CacheEntry {\n snapshot: CachedSnapshot;\n /** Tables this signature's chain references — used for invalidation. */\n readonly chainTables: ReadonlySet<string>;\n /** Aborts the in-flight read for this signature, if any. */\n inFlight: AbortController | undefined;\n}\n\ninterface TablePoll {\n refcount: number;\n controller: AbortController;\n cursor: string;\n}\n\ninterface SubscriptionPool {\n /** Register a subscriber. Returns an unsubscribe. */\n attach(\n signature: string,\n tables: ReadonlyArray<string>,\n chainTables: ReadonlySet<string>,\n fetcher: () => Promise<unknown>,\n notify: () => void,\n ): () => void;\n /** Read the cached snapshot for `signature` (or the canonical loading sentinel). */\n getSnapshot(signature: string): CachedSnapshot;\n}\n\nconst poolByClient = new WeakMap<BaerlyClient, SubscriptionPool>();\n\n/** Returns the (lazily-created) pool for `client`. */\nexport const poolFor = (client: BaerlyClient): SubscriptionPool => {\n let pool = poolByClient.get(client);\n if (pool === undefined) {\n pool = createPool(client);\n poolByClient.set(client, pool);\n }\n return pool;\n};\n\nconst createPool = (client: BaerlyClient): SubscriptionPool => {\n const cache = new Map<string, CacheEntry>();\n const subscribersBySignature = new Map<string, Set<() => void>>();\n const tablePolls = new Map<string, TablePoll>();\n\n const notifyAll = (signature: string): void => {\n const subs = subscribersBySignature.get(signature);\n if (subs === undefined) {\n return;\n }\n for (const notify of subs) {\n notify();\n }\n };\n\n const dispatchFetch = (signature: string, fetcher: () => Promise<unknown>): void => {\n const entry = cache.get(signature);\n if (entry === undefined) {\n return;\n }\n if (entry.inFlight !== undefined) {\n entry.inFlight.abort();\n }\n const controller = new AbortController();\n entry.inFlight = controller;\n const prevSnapshot = entry.snapshot;\n const hadData = entry.snapshot.status === \"ok\" || entry.snapshot.status === \"refreshing\";\n entry.snapshot = hadData\n ? { status: \"refreshing\", data: entry.snapshot.data, error: undefined }\n : LOADING_SNAPSHOT;\n if (entry.snapshot !== prevSnapshot) {\n notifyAll(signature);\n }\n void (async () => {\n try {\n const data = await fetcher();\n if (controller.signal.aborted) {\n return;\n }\n const live = cache.get(signature);\n if (live === undefined || live.inFlight !== controller) {\n return;\n }\n live.snapshot = { status: \"ok\", data, error: undefined };\n live.inFlight = undefined;\n notifyAll(signature);\n } catch (error) {\n if (controller.signal.aborted) {\n return;\n }\n const live = cache.get(signature);\n if (live === undefined || live.inFlight !== controller) {\n return;\n }\n const wrapped = toError(error);\n live.snapshot = {\n status: \"error\",\n data: live.snapshot.data,\n error: wrapped,\n };\n live.inFlight = undefined;\n notifyAll(signature);\n }\n })();\n };\n\n const invalidateForTable = (table: string): void => {\n for (const [signature, entry] of cache) {\n if (!entry.chainTables.has(table)) {\n continue;\n }\n const subs = subscribersBySignature.get(signature);\n if (subs === undefined || subs.size === 0) {\n continue;\n }\n // Any subscriber's fetcher is fine — they all produce the\n // same call against the real client for this signature\n // (signature is hashed on chain shape + deps).\n const fetcher = signatureFetchers.get(signature);\n if (fetcher !== undefined) {\n dispatchFetch(signature, fetcher);\n }\n }\n };\n\n /** Per-signature fetcher; last writer wins (all fetchers for a signature are equivalent). */\n const signatureFetchers = new Map<string, () => Promise<unknown>>();\n\n const startTablePoll = (table: string): void => {\n if (tablePolls.has(table)) {\n return;\n }\n const controller = new AbortController();\n const poll: TablePoll = { refcount: 1, controller, cursor: \"\" };\n tablePolls.set(table, poll);\n const ctx = getClientContext(client);\n void (async () => {\n while (!controller.signal.aborted) {\n try {\n const res = await pollSinceOnce(ctx, table, poll.cursor, controller.signal);\n if (controller.signal.aborted) {\n return;\n }\n if (res.events.length > 0 || res.next_cursor !== poll.cursor) {\n poll.cursor = res.next_cursor;\n if (res.events.length > 0) {\n invalidateForTable(table);\n }\n }\n } catch (error) {\n if (controller.signal.aborted) {\n return;\n }\n if (error instanceof DOMException && error.name === \"AbortError\") {\n return;\n }\n // 1-second backoff on error to avoid hot-spinning on a\n // persistent failure; downstream subscribers' next fetch\n // sees the same error if it doesn't clear.\n await new Promise((r) => setTimeout(r, 1000));\n }\n }\n })();\n };\n\n const stopTablePoll = (table: string): void => {\n const poll = tablePolls.get(table);\n if (poll === undefined) {\n return;\n }\n poll.refcount--;\n if (poll.refcount === 0) {\n poll.controller.abort();\n tablePolls.delete(table);\n }\n };\n\n const incrementTablePoll = (table: string): void => {\n const poll = tablePolls.get(table);\n if (poll === undefined) {\n startTablePoll(table);\n } else {\n poll.refcount++;\n }\n };\n\n return {\n getSnapshot(signature: string): CachedSnapshot {\n return cache.get(signature)?.snapshot ?? LOADING_SNAPSHOT;\n },\n attach(signature, tables, chainTables, fetcher, notify) {\n let entry = cache.get(signature);\n const isFirstSubscriber = entry === undefined;\n if (entry === undefined) {\n entry = {\n snapshot: LOADING_SNAPSHOT,\n chainTables,\n inFlight: undefined,\n };\n cache.set(signature, entry);\n }\n signatureFetchers.set(signature, fetcher);\n let subs = subscribersBySignature.get(signature);\n if (subs === undefined) {\n subs = new Set();\n subscribersBySignature.set(signature, subs);\n }\n subs.add(notify);\n for (const table of tables) {\n incrementTablePoll(table);\n }\n if (isFirstSubscriber) {\n dispatchFetch(signature, fetcher);\n } else {\n // Cache already has data (or in-flight). The new subscriber\n // gets the existing snapshot via getSnapshot; no extra fetch.\n }\n return () => {\n const liveSubs = subscribersBySignature.get(signature);\n if (liveSubs !== undefined) {\n liveSubs.delete(notify);\n if (liveSubs.size === 0) {\n subscribersBySignature.delete(signature);\n const liveEntry = cache.get(signature);\n if (liveEntry !== undefined) {\n liveEntry.inFlight?.abort();\n cache.delete(signature);\n }\n signatureFetchers.delete(signature);\n }\n }\n for (const table of tables) {\n stopTablePoll(table);\n }\n };\n },\n };\n};\n","import { type BaerlyConfig, BaerlyError, type UnboundConfig } from \"@baerly/protocol\";\nimport { useCallback, useReducer, useRef, useSyncExternalStore } from \"react\";\nimport type { BaerlyClient } from \"../client.ts\";\nimport { useBaerlyClient } from \"./provider.ts\";\nimport { stableKey } from \"./stable-key.ts\";\nimport { LOADING_SNAPSHOT, poolFor } from \"./subscription-pool.ts\";\n\nconst SKIP: unique symbol = Symbol(\"baerly.useQuery.skip\");\n\n/**\n * Result handed back by {@link useQuery}. Discriminate on `status` —\n * narrowing into `\"ok\"` / `\"refreshing\"` gives `data: T`; narrowing\n * into `\"loading\"` / `\"skipped\"` gives `data: undefined`; narrowing\n * into `\"error\"` gives `data: T | undefined` (the prior successful\n * read survives across errors so the UI can keep rendering).\n */\nexport type UseQueryResult<T> =\n | { readonly status: \"loading\"; readonly data: undefined; readonly error: undefined }\n | { readonly status: \"refreshing\"; readonly data: T; readonly error: undefined }\n | { readonly status: \"ok\"; readonly data: T; readonly error: undefined }\n | { readonly status: \"skipped\"; readonly data: undefined; readonly error: undefined }\n | { readonly status: \"error\"; readonly data: T | undefined; readonly error: Error };\n\nconst SKIPPED_SNAPSHOT: UseQueryResult<never> = Object.freeze({\n status: \"skipped\",\n data: undefined,\n error: undefined,\n});\n\ninterface RecorderState {\n readonly collectionsRead: Set<string>;\n readonly chain: Array<string>;\n}\n\nconst WRITE_METHODS = new Set([\"insert\", \"update\", \"replace\", \"delete\"]);\n\nconst awaitedError = (prop: string | symbol): BaerlyError =>\n new BaerlyError(\n \"UseQueryAwaitedRecorder\",\n `useQuery callbacks must not dereference the result of an awaited recorder terminal — property access (${String(prop)}) on the awaited value throws. The recorder is for the synchronous prefix of the callback only. For compound reads, use Promise.all (parallel) or compose two useQuery calls with useQuery.skip (dependent). See the lint rule baerly/no-await-in-use-query for the edit-time check.`,\n );\n\n/**\n * Sentinel handed back when a recorder terminal is awaited. Every\n * own-property access throws `BaerlyError(\"UseQueryAwaitedRecorder\")`;\n * `Symbol.*` accesses (which the JS engine uses internally —\n * Symbol.toPrimitive, Symbol.iterator, etc.) return undefined so the\n * sentinel can flow through engine-side coercions without spurious\n * throws. The single shared instance avoids per-render allocation.\n */\nconst SENTINEL_SAFE_PROPS = new Set<string | symbol>([\n // The JS engine probes `.then` to test whether a value is a\n // thenable while resolving Promises. Returning undefined makes the\n // sentinel look like a non-thenable so awaiting it yields the\n // sentinel itself (not a chained Promise) — and our error fires on\n // the next, user-visible property access.\n \"then\",\n // `.catch` and `.finally` are sometimes probed similarly.\n \"catch\",\n \"finally\",\n // `Symbol.toStringTag` etc. are probed by `String()` and JSON\n // serialization. The generic `typeof prop === \"symbol\"` branch\n // already covers these; keep them here for explicit reference.\n]);\n\nconst AWAITED_SENTINEL: unknown = new Proxy(\n Object.create(null) as Record<string | symbol, unknown>,\n {\n get(_target, prop) {\n if (typeof prop === \"symbol\" || SENTINEL_SAFE_PROPS.has(prop)) {\n return undefined;\n }\n throw awaitedError(prop);\n },\n },\n);\n\nconst TERMINAL_RESULT: Promise<unknown> = Promise.resolve(AWAITED_SENTINEL);\n\nconst makeTerminal = (): Promise<unknown> => TERMINAL_RESULT;\n\nconst makeQuery = (state: RecorderState): unknown => {\n const query: Record<string, unknown> = {};\n for (const modifier of [\"where\", \"order\", \"limit\"]) {\n query[modifier] = (): unknown => {\n state.chain.push(modifier);\n return query;\n };\n }\n for (const terminal of [\"first\", \"all\", \"count\"]) {\n query[terminal] = (): unknown => {\n state.chain.push(terminal);\n return makeTerminal();\n };\n }\n return query;\n};\n\nconst makeCollection = (name: string, state: RecorderState): unknown => {\n state.collectionsRead.add(name);\n state.chain.push(`collection:${name}`);\n const collection: Record<string, unknown> = {\n name,\n };\n for (const modifier of [\"where\", \"order\", \"limit\"]) {\n collection[modifier] = (): unknown => {\n state.chain.push(modifier);\n return makeQuery(state);\n };\n }\n for (const terminal of [\"first\", \"all\", \"count\", \"get\"]) {\n collection[terminal] = (): unknown => {\n state.chain.push(terminal);\n return makeTerminal();\n };\n }\n for (const write of WRITE_METHODS) {\n collection[write] = (): never => {\n throw new BaerlyError(\n \"UnexpectedWriteInQuery\",\n `useQuery callbacks must not write to the database. .${write}() was called on collection \"${name}\". Use useMutation() instead.`,\n );\n };\n }\n return collection;\n};\n\nconst createRecorder = (): { client: unknown; state: RecorderState } => {\n const state: RecorderState = {\n collectionsRead: new Set(),\n chain: [],\n };\n const recorder = {\n collection: (name: string): unknown => makeCollection(name, state),\n healthz: (): never => {\n throw new BaerlyError(\n \"UnexpectedWriteInQuery\",\n \"useQuery callbacks must not call client.healthz(); use useMutation() or the bare client.\",\n );\n },\n };\n return { client: recorder, state };\n};\n\ninterface DiscoveryOk {\n readonly kind: \"ok\";\n readonly collections: ReadonlyArray<string>;\n readonly chainShape: string;\n readonly callbackResult: unknown;\n}\ninterface DiscoverySkip {\n readonly kind: \"skip\";\n}\ninterface DiscoveryError {\n readonly kind: \"error\";\n readonly error: Error;\n}\ntype DiscoveryResult = DiscoveryOk | DiscoverySkip | DiscoveryError;\n\nconst discover = (\n callback: (client: BaerlyClient) => Promise<unknown> | typeof SKIP,\n): DiscoveryResult => {\n const { client: recorder, state } = createRecorder();\n let callbackResult: unknown;\n try {\n callbackResult = callback(recorder as BaerlyClient);\n } catch (error) {\n return {\n kind: \"error\",\n error: error instanceof Error ? error : new BaerlyError(\"Internal\", String(error)),\n };\n }\n if (callbackResult === SKIP) {\n return { kind: \"skip\" };\n }\n return {\n kind: \"ok\",\n collections: [...state.collectionsRead].toSorted(),\n chainShape: stableKey(state.chain),\n callbackResult,\n };\n};\n\n/**\n * Reactive read against a `baerly` server. The callback receives a\n * type-compatible `BaerlyClient` proxy that records which collections it\n * touches; the hook subscribes to those collections and re-runs the\n * callback against the real client when any of them mutate.\n *\n * Re-runs also fire whenever the `deps` array changes between\n * renders (shallow `stableKey` compare). Closure variables read\n * inside the callback must be listed in `deps` — the companion\n * `baerly/exhaustive-deps-use-query` lint rule flags missing\n * entries.\n *\n * Returning {@link useQuery.skip} from the callback yields\n * `{ status: \"skipped\" }` and registers no subscription — use it\n * for deferred / conditional reads.\n *\n * @example\n * ```tsx\n * // Single read\n * const note = useQuery((c) => c.collection(\"notes\").get(id), [id]);\n * if (note.status === \"loading\") return <Spinner/>;\n * if (note.status === \"error\") return <Err e={note.error}/>;\n * return <pre>{note.data?.body}</pre>; // typed Note | undefined\n *\n * // Deferred read\n * const list = useQuery(\n * (c) => userId ? c.collection(\"notes\").where({ authorId: userId }).all() : useQuery.skip,\n * [userId],\n * );\n * if (list.status === \"skipped\") return null;\n *\n * // Dependent read (parent → child)\n * const parent = useQuery((c) => c.collection(\"notes\").get(id), [id]);\n * const replies = useQuery(\n * (c) => parent.status === \"ok\"\n * ? c.collection(\"comments\").where({ noteId: parent.data._id }).all()\n * : useQuery.skip,\n * [parent.status === \"ok\" ? parent.data._id : undefined],\n * );\n * ```\n */\nconst useQueryImpl = <T, TConfig extends BaerlyConfig = UnboundConfig>(\n callback: (client: BaerlyClient<TConfig>) => Promise<T> | typeof SKIP,\n deps?: ReadonlyArray<unknown>,\n): UseQueryResult<T> => {\n const client = useBaerlyClient<TConfig>();\n const pool = poolFor(client as unknown as BaerlyClient);\n\n const callbackRef = useRef(callback);\n callbackRef.current = callback;\n\n // Force-update for async-error capture (see below). Used to push\n // a microtask-deferred recorder-await rejection back into a sync\n // render.\n const [, forceUpdate] = useReducer((c: number) => c + 1, 0);\n const asyncErrorRef = useRef<BaerlyError | undefined>(undefined);\n\n // Recorder pass. Cheap — no I/O.\n const discovery = discover(\n callbackRef.current as (client: BaerlyClient) => Promise<unknown> | typeof SKIP,\n );\n\n // The signature inputs that need to be stable across the same\n // logical query: chain shape + caller-declared deps.\n const depsKey = stableKey([deps ?? []]);\n const signatureBase =\n discovery.kind === \"ok\"\n ? stableKey([discovery.chainShape, deps ?? []])\n : `__non_ok__${discovery.kind}__${depsKey}`;\n\n // Reset the captured async error if the signature changed (the\n // user is on a different query now — give them a fresh chance).\n const lastSignatureRef = useRef<string>(\"\");\n if (lastSignatureRef.current !== signatureBase) {\n lastSignatureRef.current = signatureBase;\n asyncErrorRef.current = undefined;\n }\n\n // Attach an async-error handler to the callback's returned value\n // so that any microtask-deferred rejection from sentinel access\n // (sequential-await pattern) flows back into render via\n // forceUpdate. Wrap in `Promise.resolve(...)` so a bare recorder\n // terminal (Promise<sentinel>) is observed too — the resolved\n // value carries no `.catch`. Always attach (even if asyncErrorRef\n // is already set) so the per-render discovery invocation's\n // rejection is observed and doesn't surface as an unhandled\n // rejection from vitest or the host runtime.\n if (discovery.kind === \"ok\") {\n const result = discovery.callbackResult;\n if (\n result !== null &&\n typeof result === \"object\" &&\n typeof (result as { then?: unknown }).then === \"function\"\n ) {\n Promise.resolve(result as PromiseLike<unknown>).then(\n () => {\n /* discovery success — value discarded */\n },\n (error: unknown) => {\n if (\n error instanceof BaerlyError &&\n error.code === \"UseQueryAwaitedRecorder\" &&\n asyncErrorRef.current === undefined\n ) {\n asyncErrorRef.current = error;\n forceUpdate();\n }\n // Any other rejection is silently swallowed here — the\n // pool's real-client fetch path is the canonical surface\n // for non-recorder errors.\n },\n );\n }\n }\n\n // Subscription channel — stable per (client, collectionsRead.join(\" \")).\n // Pool's getSnapshot returns the current cached entry for this\n // signature; React polls it on subscribe + on every notify.\n const collectionsJoin =\n discovery.kind === \"ok\" ? discovery.collections.join(\"\\x00\") : \"__non_ok__\";\n\n const fetcherRef = useRef<() => Promise<unknown>>(() => Promise.resolve(undefined));\n fetcherRef.current = (): Promise<unknown> => {\n const out = callbackRef.current(client) as Promise<unknown> | typeof SKIP;\n if (out === SKIP) {\n return Promise.resolve(undefined);\n }\n return out as Promise<unknown>;\n };\n\n const chainCollectionsRef = useRef<ReadonlySet<string>>(new Set());\n const discoveryKindRef = useRef<DiscoveryResult[\"kind\"]>(\"ok\");\n const discoveryErrorRef = useRef<Error | undefined>(undefined);\n discoveryKindRef.current = discovery.kind;\n if (discovery.kind === \"ok\") {\n chainCollectionsRef.current = new Set(discovery.collections);\n discoveryErrorRef.current = undefined;\n } else if (discovery.kind === \"error\") {\n discoveryErrorRef.current = discovery.error;\n } else {\n discoveryErrorRef.current = undefined;\n }\n\n const subscribe = useCallback(\n (notify: () => void): (() => void) => {\n if (discovery.kind !== \"ok\") {\n return () => {};\n }\n return pool.attach(\n signatureBase,\n discovery.collections,\n chainCollectionsRef.current,\n () => fetcherRef.current(),\n notify,\n );\n },\n // The signature/collections determine the subscription; React\n // re-subscribes when either changes.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [pool, signatureBase, collectionsJoin],\n );\n\n // Stable per-error snapshot cache so repeated getSnapshot polls\n // within a single render return the same reference. React's\n // useSyncExternalStore detects identity changes; constructing a\n // fresh error literal each call drives an infinite re-render.\n const errorSnapshotRef = useRef<\n | {\n error: Error;\n snapshot: UseQueryResult<unknown>;\n }\n | undefined\n >(undefined);\n const snapshotForError = (err: Error): UseQueryResult<T> => {\n if (errorSnapshotRef.current?.error === err) {\n return errorSnapshotRef.current.snapshot as UseQueryResult<T>;\n }\n const snapshot = {\n status: \"error\" as const,\n data: undefined,\n error: err,\n } satisfies UseQueryResult<unknown>;\n errorSnapshotRef.current = { error: err, snapshot };\n return snapshot as UseQueryResult<T>;\n };\n\n const getSnapshot = useCallback((): UseQueryResult<T> => {\n if (asyncErrorRef.current) {\n return snapshotForError(asyncErrorRef.current);\n }\n if (discoveryKindRef.current === \"skip\") {\n return SKIPPED_SNAPSHOT as UseQueryResult<T>;\n }\n if (discoveryKindRef.current === \"error\") {\n return snapshotForError(\n discoveryErrorRef.current ?? new BaerlyError(\"Internal\", \"unknown discovery error\"),\n );\n }\n return pool.getSnapshot(signatureBase) as UseQueryResult<T>;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [pool, signatureBase]);\n\n // discoveryKindRef + discoveryErrorRef carry the latest discovery\n // state into getSnapshot without making it a useCallback dep\n // (avoids re-creating the snapshot callback every render).\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n};\n\n/**\n * Reactive read hook. See {@link useQueryImpl} JSDoc for usage.\n * The `.skip` property is the sentinel that short-circuits the hook\n * into `status: \"skipped\"`.\n */\nexport const useQuery: {\n <T, TConfig extends BaerlyConfig = UnboundConfig>(\n callback: (client: BaerlyClient<TConfig>) => Promise<T> | typeof SKIP,\n deps?: ReadonlyArray<unknown>,\n ): UseQueryResult<T>;\n readonly skip: typeof SKIP;\n} = Object.assign(useQueryImpl, { skip: SKIP }) as {\n <T, TConfig extends BaerlyConfig = UnboundConfig>(\n callback: (client: BaerlyClient<TConfig>) => Promise<T> | typeof SKIP,\n deps?: ReadonlyArray<unknown>,\n ): UseQueryResult<T>;\n readonly skip: typeof SKIP;\n};\n\n// Quiet `LOADING_SNAPSHOT` as a value-import — referenced by\n// generated type for the `loading` branch only; bundled alongside\n// `subscription-pool.ts`.\nvoid LOADING_SNAPSHOT;\n","import { type BaerlyConfig, BaerlyError, type UnboundConfig } from \"@baerly/protocol\";\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport type { BaerlyClient } from \"../client.ts\";\nimport { useBaerlyClient } from \"./provider.ts\";\n\n/**\n * Tuple returned by {@link useMutation}. Positionally mirrors React\n * 19's `useActionState`: `[mutate, state]`. `mutate` is stable across\n * renders; `state` is a fresh object only when `isPending` or\n * `error` actually flips.\n */\nexport type UseMutationTuple<TConfig extends BaerlyConfig = UnboundConfig> = readonly [\n mutate: <T>(callback: (client: BaerlyClient<TConfig>) => Promise<T>) => Promise<T>,\n state: { readonly isPending: boolean; readonly error: BaerlyError | undefined },\n];\n\n/**\n * Imperative mutation hook. `mutate(callback)` runs the callback\n * against the real `BaerlyClient` and resolves to whatever the\n * callback returns; `state` carries `isPending` (refcounted across\n * concurrent submits — `true` until every in-flight call settles)\n * and `error` (last-wins; the most recent rejection until the next\n * successful call clears it).\n *\n * Errors are normalised to {@link BaerlyError}: a non-`BaerlyError`\n * throwable from the callback is wrapped under\n * `code: \"MutationFailed\"` with the original on `.cause`.\n *\n * @example\n * ```tsx\n * const [mutate, { isPending, error }] = useMutation();\n * <button\n * disabled={isPending}\n * onClick={() => mutate((client) => client.collection(\"notes\").insert({ body }))}\n * >\n * {isPending ? \"Saving…\" : \"Save\"}\n * </button>\n * {error ? <p>{error.message}</p> : null}\n * ```\n */\nexport const useMutation = <\n TConfig extends BaerlyConfig = UnboundConfig,\n>(): UseMutationTuple<TConfig> => {\n const client = useBaerlyClient<TConfig>();\n const inFlightRef = useRef<number>(0);\n const mountedRef = useRef<boolean>(true);\n const [isPending, setIsPending] = useState<boolean>(false);\n const [lastError, setLastError] = useState<BaerlyError | undefined>(undefined);\n\n useEffect(\n () => () => {\n mountedRef.current = false;\n },\n [],\n );\n\n const mutate = useCallback(\n async <T>(callback: (c: BaerlyClient<TConfig>) => Promise<T>): Promise<T> => {\n const wasIdle = inFlightRef.current === 0;\n inFlightRef.current += 1;\n if (wasIdle && mountedRef.current) {\n setIsPending(true);\n setLastError(undefined);\n }\n try {\n const result = await callback(client);\n return result;\n } catch (error) {\n const be =\n error instanceof BaerlyError\n ? error\n : new BaerlyError(\n \"MutationFailed\",\n error instanceof Error ? error.message : String(error),\n error,\n );\n if (mountedRef.current) {\n setLastError(be);\n }\n throw be;\n } finally {\n inFlightRef.current -= 1;\n if (inFlightRef.current === 0 && mountedRef.current) {\n setIsPending(false);\n }\n }\n },\n [client],\n );\n\n const state = useMemo(() => ({ isPending, error: lastError }), [isPending, lastError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MAAM,UAAU,YAAY,YAAY;EACxC,YAAY,WAAW;EACvB,IAAI,WAAW,WAAW,SAAS;GACjC,aAAa,IAAI;GACjB,aAAa,KAAA,CAAS;EACxB;EACA,IAAI;GAEF,OAAO,MADc,SAAS,MAAM;EAEtC,SAAS,OAAO;GACd,MAAM,KACJ,iBAAiB,cACb,QACA,IAAI,YACF,kBACA,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GACrD,KACF;GACN,IAAI,WAAW,SACb,aAAa,EAAE;GAEjB,MAAM;EACR,UAAU;GACR,YAAY,WAAW;GACvB,IAAI,YAAY,YAAY,KAAK,WAAW,SAC1C,aAAa,KAAK;EAEtB;CACF,GACA,CAAC,MAAM,CAKI,GAFC,eAAe;EAAE;EAAW,OAAO;CAAU,IAAI,CAAC,WAAW,SAAS,CAEhE,CAAC;AACvB"}
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { f as DocumentData } from "./app-config-Cb5dO2s9.js";
|
|
2
|
+
import { l as OrderSpec, n as LogEntry, o as BaerlyError, s as BaerlyErrorCode, u as Predicate } from "./index-BGC-ENnj.js";
|
|
3
|
+
import { a as TerminalOptions, i as ClientQuery, n as BaerlyClientOptions, o as createBaerlyClient, r as ClientCollection, s as Fetcher, t as BaerlyClient } from "./client-BLf3Ae5s.js";
|
|
4
|
+
export { type BaerlyClient, type BaerlyClientOptions, BaerlyError, type BaerlyErrorCode, type ClientCollection, type ClientQuery, type DocumentData, type Fetcher, type LogEntry, type OrderSpec, type Predicate, type TerminalOptions, createBaerlyClient };
|