@gusto/baerly-storage 0.1.2 → 0.3.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/LICENSE +202 -0
- package/NOTICE +29 -0
- package/README.md +108 -44
- package/dist/API.md +192 -121
- package/dist/CHANGELOG.md +144 -0
- package/dist/THIRD-PARTY-LICENSES.txt +312 -0
- package/dist/{app-config-C0Bbw_Z6.d.ts → app-config-BIzyAKzy.d.ts} +14 -2
- package/dist/app-config.d.ts +1 -1
- package/dist/auth.d.ts +1 -1
- package/dist/auth.js +288 -288
- package/dist/auth.js.map +1 -1
- package/dist/baerly.js +10 -10
- package/dist/baerly.js.map +1 -1
- package/dist/bytes-BXdamO3L.js.map +1 -1
- package/dist/{client-DYZfoZb9.d.ts → client-BJXF3XJA.d.ts} +10 -10
- package/dist/client-react.d.ts +76 -85
- package/dist/client-react.js +95 -53
- package/dist/client-react.js.map +1 -1
- package/dist/client.d.ts +3 -3
- package/dist/client.js.map +1 -1
- package/dist/{cloudflare-CINJPKCW.js → cloudflare-Cn2ibODt.js} +178 -2
- package/dist/cloudflare-Cn2ibODt.js.map +1 -0
- package/dist/cloudflare.d.ts +4 -4
- package/dist/cloudflare.js +10 -11
- package/dist/cloudflare.js.map +1 -1
- package/dist/{subcommand-DZcHcsYp.js → config-CGyBopy3.js} +643 -439
- package/dist/config-CGyBopy3.js.map +1 -0
- package/dist/context-DRZ3tZ5l.js.map +1 -1
- package/dist/{cost-CQt1YRkA.js → cost-BZ_MDBmn.js} +6 -4
- package/dist/cost-BZ_MDBmn.js.map +1 -0
- package/dist/{current-json-C-EyJqs0.js → current-json-DsN7FNY1.js} +47 -13
- package/dist/current-json-DsN7FNY1.js.map +1 -0
- package/dist/{db-BM3y2JQw.d.ts → db-CCT6tDfY.d.ts} +26 -108
- package/dist/{deploy-CrAbfgCq.js → deploy-BKKyGlSJ.js} +11 -4
- package/dist/deploy-BKKyGlSJ.js.map +1 -0
- package/dist/dev-vite.d.ts +5 -5
- package/dist/dev-vite.js +5 -5
- package/dist/dev-vite.js.map +1 -1
- package/dist/dev.d.ts +1 -1
- package/dist/dev.js +1 -1
- package/dist/{doctor-Db-hzPmE.js → doctor-BVU4GNXN.js} +13 -132
- package/dist/doctor-BVU4GNXN.js.map +1 -0
- package/dist/{dump-BYA55NLP.js → dump-DPEAKub6.js} +5 -3
- package/dist/dump-DPEAKub6.js.map +1 -0
- package/dist/errors-DOdL95kK.js.map +1 -1
- package/dist/{export-Bhbz90-z.js → export-BcuCLFFe.js} +6 -4
- package/dist/{export-Bhbz90-z.js.map → export-BcuCLFFe.js.map} +1 -1
- package/dist/{fsck-CPPZWt9p.js → fsck-RXgLOaJG.js} +23 -11
- package/dist/fsck-RXgLOaJG.js.map +1 -0
- package/dist/{http-Cw8p6y5b.js → http-Bd4byR4n.js} +45 -61
- package/dist/http-Bd4byR4n.js.map +1 -0
- package/dist/http.d.ts +15 -15
- package/dist/http.js +1 -1
- package/dist/{index-cUY-36AN.d.ts → index-BDceQQi-.d.ts} +20 -4
- package/dist/{index-C3JAH1Yo.d.ts → index-Cmsxx-ZN.d.ts} +9 -9
- package/dist/{index-DSvwEUeF.d.ts → index-DW7GT6M2.d.ts} +50 -42
- package/dist/{index-DwDTWPSU.d.ts → index-DnBGSeuU.d.ts} +10 -7
- package/dist/index.d.ts +6 -6
- package/dist/index.js +4 -4
- package/dist/{indexes-DAu2AkTW.d.ts → indexes-Cx7uMXm0.d.ts} +2 -2
- package/dist/{inspect-Bdbzvi-_.js → inspect-DhI49PSi.js} +16 -8
- package/dist/inspect-DhI49PSi.js.map +1 -0
- package/dist/{snapshot-SS8USDUF.js → log-tail-DXeDkWEp.js} +154 -83
- package/dist/log-tail-DXeDkWEp.js.map +1 -0
- package/dist/{maintenance-BRrThz8V.d.ts → maintenance-BkhUr72A.d.ts} +91 -26
- package/dist/{maintenance-ClzBC1Vv.js → maintenance-CWBQpZ2y.js} +368 -161
- package/dist/maintenance-CWBQpZ2y.js.map +1 -0
- package/dist/{maintenance-BvOv6BMM.js → maintenance-C_KSkVjd.js} +204 -82
- package/dist/maintenance-C_KSkVjd.js.map +1 -0
- package/dist/maintenance.d.ts +3 -2
- package/dist/maintenance.js +3 -2
- package/dist/node.d.ts +13 -8
- package/dist/node.js +1 -1
- package/dist/normalize-XWY25_sG.js.map +1 -1
- package/dist/{observability-CpOiEN0k.js → observability-BYd-RzEx.js} +63 -55
- package/dist/observability-BYd-RzEx.js.map +1 -0
- package/dist/observability.d.ts +3 -3
- package/dist/observability.js +1 -1
- package/dist/{plan-DOTl21vq.js → plan-DIu_B6fy.js} +7 -4
- package/dist/plan-DIu_B6fy.js.map +1 -0
- package/dist/{query-BmiQy328.js → query-sQNO5vU_.js} +1071 -1099
- package/dist/query-sQNO5vU_.js.map +1 -0
- package/dist/{rebuild-index-DC_nR6wP.js → rebuild-index-DP4CqSSs.js} +5 -4
- package/dist/rebuild-index-DP4CqSSs.js.map +1 -0
- package/dist/{restore-C6IcmLeA.js → restore-DpQYef6r.js} +362 -328
- package/dist/restore-DpQYef6r.js.map +1 -0
- package/dist/shared-secret-BJdSwpgw.js.map +1 -1
- package/dist/{src-QQ7jDeL2.js → src-CWpkSbvJ.js} +40 -20
- package/dist/src-CWpkSbvJ.js.map +1 -0
- package/dist/{src-DU1sCMlr.js → src-D24wDpzR.js} +269 -258
- package/dist/src-D24wDpzR.js.map +1 -0
- package/dist/{src-zhEAmmF7.js → src-Db4-qVtM.js} +36 -96
- package/dist/src-Db4-qVtM.js.map +1 -0
- package/dist/subcommand-CP9NY2J4.js +159 -0
- package/dist/subcommand-CP9NY2J4.js.map +1 -0
- package/dist/{usage-CLjirdD-.js → usage-CTfDq9HR.js} +3 -3
- package/dist/{usage-CLjirdD-.js.map → usage-CTfDq9HR.js.map} +1 -1
- package/dist/{validate-DCq_0DIn.js → validate-DtljsCh1.js} +51 -51
- package/dist/{validate-DCq_0DIn.js.map → validate-DtljsCh1.js.map} +1 -1
- package/package.json +42 -31
- package/dist/cloudflare-CINJPKCW.js.map +0 -1
- package/dist/config-DVfDGyw1.js +0 -278
- package/dist/config-DVfDGyw1.js.map +0 -1
- package/dist/cost-CQt1YRkA.js.map +0 -1
- package/dist/current-json-C-EyJqs0.js.map +0 -1
- package/dist/deploy-CrAbfgCq.js.map +0 -1
- package/dist/doctor-Db-hzPmE.js.map +0 -1
- package/dist/dump-BYA55NLP.js.map +0 -1
- package/dist/fsck-CPPZWt9p.js.map +0 -1
- package/dist/http-Cw8p6y5b.js.map +0 -1
- package/dist/inspect-Bdbzvi-_.js.map +0 -1
- package/dist/maintenance-BvOv6BMM.js.map +0 -1
- package/dist/maintenance-ClzBC1Vv.js.map +0 -1
- package/dist/observability-CpOiEN0k.js.map +0 -1
- package/dist/plan-DOTl21vq.js.map +0 -1
- package/dist/query-BmiQy328.js.map +0 -1
- package/dist/rebuild-index-DC_nR6wP.js.map +0 -1
- package/dist/restore-C6IcmLeA.js.map +0 -1
- package/dist/snapshot-SS8USDUF.js.map +0 -1
- package/dist/src-DU1sCMlr.js.map +0 -1
- package/dist/src-QQ7jDeL2.js.map +0 -1
- package/dist/src-zhEAmmF7.js.map +0 -1
- package/dist/subcommand-DZcHcsYp.js.map +0 -1
package/dist/client-react.js
CHANGED
|
@@ -8,12 +8,16 @@ const ClientContext = createContext(void 0);
|
|
|
8
8
|
* Wrap your app once near the root; the hooks read the client from
|
|
9
9
|
* this context and have no `client` argument.
|
|
10
10
|
*
|
|
11
|
+
* Obtained from {@link createBaerlyReact}, not imported directly:
|
|
12
|
+
*
|
|
11
13
|
* @example
|
|
12
14
|
* ```tsx
|
|
13
15
|
* import { createBaerlyClient } from "@gusto/baerly-storage/client";
|
|
14
|
-
* import {
|
|
16
|
+
* import { createBaerlyReact } from "@gusto/baerly-storage/client/react";
|
|
17
|
+
* import config from "./baerly.config.ts";
|
|
15
18
|
*
|
|
16
|
-
* const client = createBaerlyClient({ baseUrl: "/api" });
|
|
19
|
+
* const client = createBaerlyClient({ baseUrl: "/api", config });
|
|
20
|
+
* const { BaerlyProvider } = createBaerlyReact<typeof config>();
|
|
17
21
|
*
|
|
18
22
|
* <BaerlyProvider client={client}>
|
|
19
23
|
* <App />
|
|
@@ -46,6 +50,63 @@ const useBaerlyClient = () => {
|
|
|
46
50
|
return client;
|
|
47
51
|
};
|
|
48
52
|
//#endregion
|
|
53
|
+
//#region packages/client/src/react/use-mutation.ts
|
|
54
|
+
/**
|
|
55
|
+
* Imperative mutation hook. `mutate(callback)` runs the callback
|
|
56
|
+
* against the real `BaerlyClient` and resolves to whatever the
|
|
57
|
+
* callback returns; `state` carries `isPending` (refcounted across
|
|
58
|
+
* concurrent submits — `true` until every in-flight call settles)
|
|
59
|
+
* and `error` (last-wins; the most recent rejection until the next
|
|
60
|
+
* successful call clears it).
|
|
61
|
+
*
|
|
62
|
+
* Errors are normalised to {@link BaerlyError}: a non-`BaerlyError`
|
|
63
|
+
* throwable from the callback is wrapped under
|
|
64
|
+
* `code: "MutationFailed"` with the original on `.cause`.
|
|
65
|
+
*
|
|
66
|
+
* @example
|
|
67
|
+
* ```tsx
|
|
68
|
+
* const [mutate, { isPending, error }] = useMutation();
|
|
69
|
+
* <button
|
|
70
|
+
* disabled={isPending}
|
|
71
|
+
* onClick={() => mutate((client) => client.collection("notes").insert({ body }))}
|
|
72
|
+
* >
|
|
73
|
+
* {isPending ? "Saving…" : "Save"}
|
|
74
|
+
* </button>
|
|
75
|
+
* {error ? <p>{error.message}</p> : null}
|
|
76
|
+
* ```
|
|
77
|
+
*/
|
|
78
|
+
const useMutation = () => {
|
|
79
|
+
const client = useBaerlyClient();
|
|
80
|
+
const inFlightRef = useRef(0);
|
|
81
|
+
const mountedRef = useRef(true);
|
|
82
|
+
const [isPending, setIsPending] = useState(false);
|
|
83
|
+
const [lastError, setLastError] = useState(void 0);
|
|
84
|
+
useEffect(() => () => {
|
|
85
|
+
mountedRef.current = false;
|
|
86
|
+
}, []);
|
|
87
|
+
return [useCallback(async (callback) => {
|
|
88
|
+
const wasIdle = inFlightRef.current === 0;
|
|
89
|
+
inFlightRef.current += 1;
|
|
90
|
+
if (wasIdle && mountedRef.current) {
|
|
91
|
+
setIsPending(true);
|
|
92
|
+
setLastError(void 0);
|
|
93
|
+
}
|
|
94
|
+
try {
|
|
95
|
+
return await callback(client);
|
|
96
|
+
} catch (error) {
|
|
97
|
+
const be = error instanceof BaerlyError ? error : new BaerlyError("MutationFailed", error instanceof Error ? error.message : String(error), error);
|
|
98
|
+
if (mountedRef.current) setLastError(be);
|
|
99
|
+
throw be;
|
|
100
|
+
} finally {
|
|
101
|
+
inFlightRef.current -= 1;
|
|
102
|
+
if (inFlightRef.current === 0 && mountedRef.current) setIsPending(false);
|
|
103
|
+
}
|
|
104
|
+
}, [client]), useMemo(() => ({
|
|
105
|
+
isPending,
|
|
106
|
+
error: lastError
|
|
107
|
+
}), [isPending, lastError])];
|
|
108
|
+
};
|
|
109
|
+
//#endregion
|
|
49
110
|
//#region packages/client/src/react/stable-key.ts
|
|
50
111
|
/**
|
|
51
112
|
* Deterministic JSON serialization with sorted object keys. `useQuery`
|
|
@@ -497,63 +558,44 @@ const useQueryImpl = (callback, deps) => {
|
|
|
497
558
|
*/
|
|
498
559
|
const useQuery = Object.assign(useQueryImpl, { skip: SKIP });
|
|
499
560
|
//#endregion
|
|
500
|
-
//#region packages/client/src/react/
|
|
561
|
+
//#region packages/client/src/react/create-react.ts
|
|
501
562
|
/**
|
|
502
|
-
*
|
|
503
|
-
*
|
|
504
|
-
*
|
|
505
|
-
*
|
|
506
|
-
*
|
|
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`.
|
|
563
|
+
* Build the typed React surface for one `baerly.config.ts`. Call it
|
|
564
|
+
* once at module scope and export the result; every hook is bound to
|
|
565
|
+
* the config so collection names autocomplete and row types infer
|
|
566
|
+
* end-to-end. This is the only React entry point — there are no
|
|
567
|
+
* loose, unbound hooks to import by mistake.
|
|
512
568
|
*
|
|
513
569
|
* @example
|
|
570
|
+
* ```ts
|
|
571
|
+
* // src/web/client.ts
|
|
572
|
+
* import { createBaerlyClient } from "@gusto/baerly-storage/client";
|
|
573
|
+
* import { createBaerlyReact } from "@gusto/baerly-storage/client/react";
|
|
574
|
+
* import config from "../../baerly.config.ts";
|
|
575
|
+
*
|
|
576
|
+
* export const client = createBaerlyClient({ baseUrl: "", config });
|
|
577
|
+
* export const { BaerlyProvider, useQuery, useMutation } =
|
|
578
|
+
* createBaerlyReact<typeof config>();
|
|
579
|
+
* ```
|
|
580
|
+
*
|
|
514
581
|
* ```tsx
|
|
515
|
-
*
|
|
516
|
-
*
|
|
517
|
-
*
|
|
518
|
-
*
|
|
519
|
-
* >
|
|
520
|
-
* {isPending ? "Saving…" : "Save"}
|
|
521
|
-
* </button>
|
|
522
|
-
* {error ? <p>{error.message}</p> : null}
|
|
582
|
+
* // any component
|
|
583
|
+
* import { useQuery } from "./client.ts";
|
|
584
|
+
* const notes = useQuery((c) => c.collection("notes").all(), []);
|
|
585
|
+
* // ^? UseQueryResult<Note[]> — no cast
|
|
523
586
|
* ```
|
|
587
|
+
*
|
|
588
|
+
* 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.
|
|
524
591
|
*/
|
|
525
|
-
const
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
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
|
-
};
|
|
592
|
+
const createBaerlyReact = () => ({
|
|
593
|
+
BaerlyProvider,
|
|
594
|
+
useQuery,
|
|
595
|
+
useMutation,
|
|
596
|
+
useBaerlyClient
|
|
597
|
+
});
|
|
556
598
|
//#endregion
|
|
557
|
-
export {
|
|
599
|
+
export { createBaerlyReact };
|
|
558
600
|
|
|
559
601
|
//# sourceMappingURL=client-react.js.map
|
package/dist/client-react.js.map
CHANGED
|
@@ -1 +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]);\n\n return [mutate, state] as const;\n};\n"],"mappings":";;;;AAIA,MAAM,gBAAgB,cAAwC,KAAA,CAAS;;;;;;;;;;;;;;;;;;AAwBvE,MAAa,kBAAkB,EAAE,QAAQ,eACvC,cAAc,cAAc,UAAU,EAAE,OAAO,OAAO,GAAG,QAAQ;;;;;;;;;;;;;;;;;;;;AAqBnE,MAAa,wBAEiB;CAC5B,MAAM,SAAS,WAAW,aAAa;CACvC,IAAI,WAAW,KAAA,GACb,MAAM,IAAI,MACR,wJAEF;CAEF,OAAO;AACT;;;;;;;;;;;;;;;;;;AC9CA,MAAa,aAAa,UAA2B;CACnD,IAAI,UAAU,QAAQ,OAAO,UAAU,UACrC,OAAO,KAAK,UAAU,KAA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C,eAAe;EAAE;EAAW,OAAO;CAAU,IAAI,CAAC,WAAW,SAAS,CAEhE,CAAC;AACvB"}
|
|
1
|
+
{"version":3,"file":"client-react.js","names":[],"sources":["../packages/client/src/react/provider.ts","../packages/client/src/react/use-mutation.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/create-react.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 * Obtained from {@link createBaerlyReact}, not imported directly:\n *\n * @example\n * ```tsx\n * import { createBaerlyClient } from \"@gusto/baerly-storage/client\";\n * import { createBaerlyReact } from \"@gusto/baerly-storage/client/react\";\n * import config from \"./baerly.config.ts\";\n *\n * const client = createBaerlyClient({ baseUrl: \"/api\", config });\n * const { BaerlyProvider } = createBaerlyReact<typeof config>();\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","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]);\n\n return [mutate, state] as const;\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, UnboundConfig } from \"@baerly/protocol\";\nimport type { ReactNode } from \"react\";\nimport type { BaerlyClient } from \"../client.ts\";\nimport { BaerlyProvider, useBaerlyClient } from \"./provider.ts\";\nimport { useMutation, type UseMutationTuple } from \"./use-mutation.ts\";\nimport { useQuery, type UseQueryResult } from \"./use-query.ts\";\n\n/**\n * Props for the config-bound `BaerlyProvider` returned by\n * {@link createBaerlyReact}. `client` is typed `BaerlyClient<TConfig>`\n * to document the intended binding; the hooks carry `TConfig`\n * themselves, so row inference holds regardless of the client value's\n * own inferred type.\n */\nexport interface BaerlyProviderProps<TConfig extends BaerlyConfig> {\n readonly client: BaerlyClient<TConfig>;\n readonly children?: ReactNode;\n}\n\n/**\n * The config-bound React surface returned by {@link createBaerlyReact}.\n * Every hook is pinned to `TConfig`, so `c.collection(\"notes\")` inside\n * a `useQuery` / `useMutation` callback infers the real row type — no\n * `as Promise<Note[]>` cast.\n */\nexport interface BaerlyReact<TConfig extends BaerlyConfig> {\n /** Wrap your app once; provides the bound client to every hook below it. */\n readonly BaerlyProvider: (props: BaerlyProviderProps<TConfig>) => React.JSX.Element;\n /**\n * Reactive read. The callback receives `BaerlyClient<TConfig>`, so\n * the chain is fully typed. `useQuery.skip` short-circuits to\n * `{ status: \"skipped\" }`.\n */\n readonly useQuery: {\n <T>(\n callback: (client: BaerlyClient<TConfig>) => Promise<T> | symbol,\n deps?: ReadonlyArray<unknown>,\n ): UseQueryResult<T>;\n /**\n * Sentinel — return it from the callback to defer the read\n * (`{ status: \"skipped\" }`, no subscription). Typed `symbol` (not\n * the impl's `unique symbol`) so the bound surface stays nameable\n * across the package boundary; identity-compared at runtime.\n */\n readonly skip: symbol;\n };\n /** Imperative mutation hook → `[mutate, { isPending, error }]`. */\n readonly useMutation: () => UseMutationTuple<TConfig>;\n /** Escape hatch — the raw bound {@link BaerlyClient} for imperative use. */\n readonly useBaerlyClient: () => BaerlyClient<TConfig>;\n}\n\n/**\n * Build the typed React surface for one `baerly.config.ts`. Call it\n * once at module scope and export the result; every hook is bound to\n * the config so collection names autocomplete and row types infer\n * end-to-end. This is the only React entry point — there are no\n * loose, unbound hooks to import by mistake.\n *\n * @example\n * ```ts\n * // src/web/client.ts\n * import { createBaerlyClient } from \"@gusto/baerly-storage/client\";\n * import { createBaerlyReact } from \"@gusto/baerly-storage/client/react\";\n * import config from \"../../baerly.config.ts\";\n *\n * export const client = createBaerlyClient({ baseUrl: \"\", config });\n * export const { BaerlyProvider, useQuery, useMutation } =\n * createBaerlyReact<typeof config>();\n * ```\n *\n * ```tsx\n * // any component\n * import { useQuery } from \"./client.ts\";\n * const notes = useQuery((c) => c.collection(\"notes\").all(), []);\n * // ^? UseQueryResult<Note[]> — no cast\n * ```\n *\n * Omit the type parameter (`createBaerlyReact()`) for an unbound app;\n * collection names widen to `string` and rows to `DocumentData`,\n * matching the in-process `Db.collection` fallback.\n */\nexport const createBaerlyReact = <\n TConfig extends BaerlyConfig = UnboundConfig,\n>(): BaerlyReact<TConfig> => ({\n // Identical runtime implementations — the generic is erased, so the\n // factory only re-pins each hook's type to `TConfig`. The\n // recorder-proxy in `useQuery` is structurally typed as\n // `BaerlyClient`, so binding a narrower config is a no-op at runtime.\n BaerlyProvider: BaerlyProvider as BaerlyReact<TConfig>[\"BaerlyProvider\"],\n useQuery: useQuery as unknown as BaerlyReact<TConfig>[\"useQuery\"],\n useMutation: useMutation as BaerlyReact<TConfig>[\"useMutation\"],\n useBaerlyClient: useBaerlyClient as BaerlyReact<TConfig>[\"useBaerlyClient\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IAAI,iBAAiB,SAAS,UAAU,KACtC,OAAO,iBAAiB,QAAQ;EAElC,MAAM,WAAW;GACf,QAAQ;GACR,MAAM,KAAA;GACN,OAAO;EACT;EACA,iBAAiB,UAAU;GAAE,OAAO;GAAK;EAAS;EAClD,OAAO;CACT;CAEA,MAAM,cAAc,kBAAqC;EACvD,IAAI,cAAc,SAChB,OAAO,iBAAiB,cAAc,OAAO;EAE/C,IAAI,iBAAiB,YAAY,QAC/B,OAAO;EAET,IAAI,iBAAiB,YAAY,SAC/B,OAAO,iBACL,kBAAkB,WAAW,IAAI,YAAY,YAAY,yBAAyB,CACpF;EAEF,OAAO,KAAK,YAAY,aAAa;CAEvC,GAAG,CAAC,MAAM,aAAa,CAAC;CAKxB,OAAO,qBAAqB,WAAW,aAAa,WAAW;AACjE;;;;;;AAOA,MAAa,WAMT,OAAO,OAAO,cAAc,EAAE,MAAM,KAAK,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AChU9C,MAAa,2BAEiB;CAKZ;CACN;CACG;CACI;AACnB"}
|
package/dist/client.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { f as DocumentData } from "./app-config-
|
|
2
|
-
import { l as OrderSpec, n as LogEntry, o as BaerlyError, s as BaerlyErrorCode, u as Predicate } from "./index-
|
|
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-
|
|
1
|
+
import { f as DocumentData } from "./app-config-BIzyAKzy.js";
|
|
2
|
+
import { l as OrderSpec, n as LogEntry, o as BaerlyError, s as BaerlyErrorCode, u as Predicate } from "./index-DW7GT6M2.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-BJXF3XJA.js";
|
|
4
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 };
|
package/dist/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","names":[],"sources":["../packages/client/src/client.ts"],"sourcesContent":["/* eslint-disable no-underscore-dangle -- `_id` and `_meta` are the\n locked wire-shape field names (see `packages/protocol/src/collection-api.ts`\n and `packages/server/src/contract.ts`); we mirror them verbatim\n so the typed client stays structurally compatible. */\n\nimport {\n type BaerlyConfig,\n BaerlyError,\n type CollectionNames,\n type DocumentData,\n EMPTY_PREDICATE_WIRE,\n normalizePredicateArg,\n type OrderSpec,\n type PredicateArg,\n type PredicateWire,\n type RowOf,\n type UnboundConfig,\n} from \"@baerly/protocol\";\nimport { CLIENT_CONTEXT } from \"./internal/context.ts\";\nimport { type Fetcher, type RequestContext, request } from \"./request.ts\";\n\n/**\n * Public options for {@link createBaerlyClient}.\n *\n * @example\n * ```ts\n * const client = createBaerlyClient({\n * baseUrl: \"https://api.example.com\",\n * headers: { Authorization: \"Bearer <token>\" },\n * });\n * ```\n */\nexport interface BaerlyClientOptions<TConfig extends BaerlyConfig = UnboundConfig> {\n /**\n * Required. The deployed `baerly` server URL — e.g.\n * `https://acme.example.com`. No trailing slash.\n */\n readonly baseUrl: string;\n /**\n * Optional. Defaults to `globalThis.fetch`. Wrap your own to add\n * logging, retries, tracing, or auth-refresh — the entire client\n * routes every request through this one function. This is the\n * `link` middleware story (tRPC) and the `interceptor` story\n * (axios) without new API surface.\n *\n * @example\n * ```ts\n * // Log every request + response.\n * const withLogging: Fetcher = async (req) => {\n * const t0 = performance.now();\n * const res = await globalThis.fetch(req);\n * console.log(`${req.method} ${req.url} → ${res.status} (${Math.round(performance.now() - t0)}ms)`);\n * return res;\n * };\n *\n * // Retry idempotent reads on 5xx (max 3 total attempts, 100ms backoff).\n * const withRetry = (next: Fetcher): Fetcher => async (req) => {\n * for (let i = 0; i < 2; i++) {\n * const res = await next(req.clone());\n * if (res.ok || res.status < 500 || req.method !== \"GET\") return res;\n * await new Promise((r) => setTimeout(r, 100 * (i + 1)));\n * }\n * return next(req);\n * };\n *\n * const client = createBaerlyClient({\n * baseUrl: \"https://api.example.com\",\n * fetch: withRetry(withLogging),\n * });\n * ```\n *\n * See `dist/API.md` → \"Recipe — wrapping the client `fetch`\"\n * for `onSuccess` / `onError` helpers and a composition pattern.\n */\n readonly fetch?: Fetcher;\n /**\n * Optional. Forwarded on every request. Typically\n * `{ Authorization: \"Bearer <token>\" }`. For credential refresh\n * (fresh JWT per call, 401-driven re-issue, etc.) wrap\n * {@link BaerlyClientOptions.fetch} instead — see the retry +\n * logging examples above.\n */\n readonly headers?: Headers | Record<string, string>;\n /**\n * Optional. **Type-only** — the runtime client does not read this\n * field; it exists so `client.collection(name)` can narrow `name` to\n * declared collection names and infer the row type from\n * `collections[name].schema`. Bind the type via the generic\n * parameter using `import type` so the server-side storage\n * adapter and secrets in `baerly.config.ts` do not enter the\n * browser bundle:\n *\n * ```ts\n * import type config from \"./baerly.config.ts\";\n * const client = createBaerlyClient<typeof config>({ baseUrl });\n * await client.collection(\"tickets\").first(); // Promise<Ticket | undefined>\n * ```\n *\n * Skip the type parameter to fall back to the per-call generic\n * `client.collection(\"tickets\")` form.\n */\n readonly config?: TConfig;\n}\n\n/**\n * Trailing-options bag accepted by every terminal. Today this is\n * only `signal`, so the type is split out for readability rather\n * than forcing every call site to ascribe `{ signal?: AbortSignal }`.\n * When other per-call options land (timeout, idempotency key, etc.)\n * they belong here.\n */\nexport interface TerminalOptions {\n /**\n * Cancels this specific request. React effect cleanup is the\n * canonical caller:\n *\n * ```ts\n * useEffect(() => {\n * const ac = new AbortController();\n * client.collection(\"tickets\").where(p).all({ signal: ac.signal }).then(setRows);\n * return () => ac.abort();\n * }, [predicateKey]);\n * ```\n */\n readonly signal?: AbortSignal;\n}\n\n/**\n * Client-side mirror of `Collection<T>` from `@baerly/protocol`. Cheap\n * handle; constructs no I/O. Same method names as the in-process\n * `Collection<T>`, but every terminal also accepts a trailing\n * {@link TerminalOptions} bag carrying `{ signal }`.\n *\n * By-id mutation verbs (`update`, `replace`, `delete`) live here;\n * predicate-aware bulk mutation has no HTTP route today and is\n * intentionally absent from {@link ClientQuery}.\n *\n * @template T — document shape. `_id` is always present on rows\n * returned from the server.\n */\nexport interface ClientCollection<T extends DocumentData = DocumentData> {\n readonly name: string;\n /** First document in the whole collection or `undefined`. */\n first(opts?: TerminalOptions): Promise<T | undefined>;\n /** Every document in the whole collection. Pair with `.where(...).limit(n)` on large collections. */\n all(opts?: TerminalOptions): Promise<T[]>;\n /** Count every row in the collection (equivalent to `.where({}).count()`). */\n count(opts?: TerminalOptions): Promise<number>;\n /** Fetch one document by primary key. Returns `undefined` when the id is unknown. */\n get(id: string, opts?: TerminalOptions): Promise<T | undefined>;\n /**\n * Filter rows. Two shapes:\n *\n * - **Object literal** — equality only.\n * - **Callback DSL** — `q => q.eq(...).gt(...).in(...)` for the\n * operator vocabulary.\n *\n * Chained calls AND-merge across shapes.\n */\n where(predicate: PredicateArg<T>): ClientQuery<T>;\n /** Order modifier; last call wins. */\n order(spec: OrderSpec<T>): ClientQuery<T>;\n /** Limit modifier; last call wins. */\n limit(n: number): ClientQuery<T>;\n /** Insert a new document. Returns the server-assigned `_id`. */\n insert(doc: Partial<T> & DocumentData, opts?: TerminalOptions): Promise<{ readonly _id: string }>;\n /** JSON-merge-patch applied to one row by primary key. */\n update(\n id: string,\n patch: Partial<T>,\n opts?: TerminalOptions,\n ): Promise<{ readonly modified: number }>;\n /** Whole-document replace on one row by primary key. */\n replace(id: string, doc: T, opts?: TerminalOptions): Promise<void>;\n /** Delete one row by primary key. Returns `{ deleted: 0 }` on 404 (not an error). */\n delete(id: string, opts?: TerminalOptions): Promise<{ readonly deleted: number }>;\n}\n\n/**\n * Client-side mirror of `Query<T>` from `@baerly/protocol`. See\n * {@link ClientCollection} for the method-shape contract.\n *\n * Read-only over HTTP: by-id mutation lives on {@link ClientCollection}\n * directly. Predicate-aware bulk mutation is server-only — the HTTP\n * surface has no route for it.\n */\nexport interface ClientQuery<T extends DocumentData = DocumentData> {\n where(predicate: PredicateArg<T>): ClientQuery<T>;\n order(spec: OrderSpec<T>): ClientQuery<T>;\n limit(n: number): ClientQuery<T>;\n /** First match or `undefined`. Issues `GET /v1/c/:collection?...&limit=1`. */\n first(opts?: TerminalOptions): Promise<T | undefined>;\n /** Every matching document. Pair with `.limit(n)` on large collections. */\n all(opts?: TerminalOptions): Promise<T[]>;\n /** Count matching rows. Issues `GET /v1/count?collection=&where=`; server returns a scalar. */\n count(opts?: TerminalOptions): Promise<number>;\n}\n\n/**\n * Returned by {@link createBaerlyClient}. The typed entry point.\n *\n * `BaerlyClient` does NOT expose a `transaction(...)` method:\n * the server has no HTTP route for atomic batch commit today (see\n * `packages/server/src/http/router.ts`). Issuing N HTTP requests\n * from the client would silently break the single-CAS invariant.\n * If you need atomic multi-row mutation today, expose a business-\n * level RPC on the server that calls `db.transaction(...)` in-\n * process.\n *\n * @example\n * ```ts\n * const client = createBaerlyClient({ baseUrl: \"https://api.example.com\" });\n * const { _id } = await client.collection(\"tickets\").insert({ title: \"hi\" });\n * const row = await client.collection(\"tickets\").get(_id);\n * ```\n */\nexport interface BaerlyClient<TConfig extends BaerlyConfig = UnboundConfig> {\n /**\n * Typed collection handle. Cheap; constructs no I/O.\n *\n * When `TConfig` is bound (via `options.config`) and `name` is one\n * of the declared collection names, the row type is inferred from\n * `TConfig[\"collections\"][name][\"schema\"]`. Otherwise the row type\n * defaults to `DocumentData` and the call accepts any string name —\n * matching the in-process `Db.collection` shape.\n */\n collection<N extends CollectionNames<TConfig>>(\n name: N,\n ): ClientCollection<RowOf<TConfig, N> & DocumentData>;\n}\n\n/**\n * Construct a typed HTTP client over the locked `/v1/...` routes.\n * Returns a {@link BaerlyClient} with the same surface as the\n * in-process `Db.collection(...)` API.\n *\n * @example\n * ```ts\n * const client = createBaerlyClient({\n * baseUrl: \"https://api.example.com\",\n * headers: { Authorization: \"Bearer <token>\" },\n * });\n * ```\n */\nexport const createBaerlyClient = <TConfig extends BaerlyConfig = UnboundConfig>(\n options: BaerlyClientOptions<TConfig>,\n): BaerlyClient<TConfig> => {\n const ctx: RequestContext = {\n baseUrl: options.baseUrl,\n fetch: options.fetch ?? ((req) => globalThis.fetch(req)),\n headers: new Headers(options.headers ?? {}),\n };\n const client = {\n [CLIENT_CONTEXT]: ctx,\n collection<T extends DocumentData = DocumentData>(name: string): ClientCollection<T> {\n return makeClientCollection<T>(ctx, name);\n },\n };\n return client as BaerlyClient<TConfig>;\n};\n\n/** Query-state carried across the chainable modifiers. */\ninterface QueryState {\n readonly wire: PredicateWire;\n readonly order: OrderSpec<DocumentData> | undefined;\n readonly limit: number | undefined;\n}\n\nconst emptyState: QueryState = {\n wire: EMPTY_PREDICATE_WIRE,\n order: undefined,\n limit: undefined,\n};\n\nconst makeClientCollection = <T extends DocumentData>(\n ctx: RequestContext,\n name: string,\n): ClientCollection<T> => {\n const collectionForQuery = makeClientQuery<T>(ctx, name, emptyState);\n const idPath = (id: string): string =>\n `/v1/c/${encodeURIComponent(name)}/${encodeURIComponent(id)}`;\n return {\n name,\n where: (predicate) => collectionForQuery.where(predicate),\n order: (spec) => collectionForQuery.order(spec),\n limit: (n) => collectionForQuery.limit(n),\n first: (opts) => collectionForQuery.first(opts),\n all: (opts) => collectionForQuery.all(opts),\n count: (opts) => collectionForQuery.count(opts),\n async get(id, opts): Promise<T | undefined> {\n try {\n return await request<T>(ctx, {\n method: \"GET\",\n path: idPath(id),\n signal: opts?.signal,\n });\n } catch (error) {\n // 404 on GET → unknown id. Mirrors `Db.collection().get(id)` which\n // resolves `undefined` rather than throwing.\n if (error instanceof BaerlyError && error.code === \"NotFound\") {\n return undefined;\n }\n throw error;\n }\n },\n async insert(doc, opts): Promise<{ readonly _id: string }> {\n return request<{ _id: string }>(ctx, {\n method: \"POST\",\n path: `/v1/c/${encodeURIComponent(name)}`,\n body: { doc },\n signal: opts?.signal,\n });\n },\n async update(id, patch, opts): Promise<{ readonly modified: number }> {\n return request<{ modified: number }>(ctx, {\n method: \"PATCH\",\n path: idPath(id),\n body: { patch },\n signal: opts?.signal,\n });\n },\n async replace(id, doc, opts): Promise<void> {\n // PUT = whole-document overwrite. NOT PATCH — PATCH would be\n // RFC 7386 merge-patch and silently retain omitted fields from\n // the prior doc.\n await request<{ modified: number }>(ctx, {\n method: \"PUT\",\n path: idPath(id),\n body: { doc },\n signal: opts?.signal,\n });\n },\n async delete(id, opts): Promise<{ readonly deleted: number }> {\n try {\n await request<undefined>(ctx, {\n method: \"DELETE\",\n path: idPath(id),\n signal: opts?.signal,\n });\n return { deleted: 1 };\n } catch (error) {\n // 404 on DELETE → \"no row matched\". Mirrors `Query.delete()`\n // which returns `{ deleted: 0 }` rather than throwing.\n if (error instanceof BaerlyError && error.code === \"NotFound\") {\n return { deleted: 0 };\n }\n throw error;\n }\n },\n };\n};\n\nconst makeClientQuery = <T extends DocumentData>(\n ctx: RequestContext,\n collectionName: string,\n state: QueryState,\n): ClientQuery<T> => {\n const listParams = (): URLSearchParams => {\n const params = new URLSearchParams();\n if (state.wire.clauses.length > 0) {\n params.set(\"where\", JSON.stringify(state.wire));\n }\n if (state.order !== undefined && Object.keys(state.order).length > 0) {\n params.set(\"order\", JSON.stringify(state.order));\n }\n if (state.limit !== undefined) {\n params.set(\"limit\", String(state.limit));\n }\n return params;\n };\n\n const listPath = (override?: { limit?: number }): string => {\n const params = listParams();\n if (override?.limit !== undefined) {\n params.set(\"limit\", String(override.limit));\n }\n const qs = params.toString();\n return `/v1/c/${encodeURIComponent(collectionName)}${qs.length > 0 ? `?${qs}` : \"\"}`;\n };\n\n return {\n where: (predicate): ClientQuery<T> => {\n // Normalise the incoming arg (object or callback) to a wire and\n // concatenate clauses with any prior wire. The server's\n // `parseWhereParam` runs `validateWire` on arrival, so empty\n // `in` / conflicting `eq` / unsatisfiable interval surface as\n // a 400 `InvalidConfig` / `UnsatisfiablePredicate` from the\n // HTTP layer — no client-side merger needed. Skipping the\n // satisfiability check here keeps the SPA bundle out of the\n // wire-merger / per-field-fold code path.\n const incoming = normalizePredicateArg<T>(predicate);\n const merged: PredicateWire =\n state.wire.clauses.length === 0\n ? incoming\n : { clauses: [...state.wire.clauses, ...incoming.clauses] };\n return makeClientQuery<T>(ctx, collectionName, { ...state, wire: merged });\n },\n order: (spec): ClientQuery<T> =>\n makeClientQuery<T>(ctx, collectionName, {\n ...state,\n order: spec as OrderSpec<DocumentData>,\n }),\n limit: (n): ClientQuery<T> => makeClientQuery<T>(ctx, collectionName, { ...state, limit: n }),\n\n async first(opts): Promise<T | undefined> {\n // Mirrors `Db.first()` which sets `limit: 1` on its underlying\n // list call; override the query-state limit for this terminal\n // only (chained `.limit(n).first()` semantics: `first` wins).\n const data = await request<ReadonlyArray<T>>(ctx, {\n method: \"GET\",\n path: listPath({ limit: 1 }),\n signal: opts?.signal,\n });\n return data[0];\n },\n async all(opts): Promise<T[]> {\n const data = await request<ReadonlyArray<T>>(ctx, {\n method: \"GET\",\n path: listPath(),\n signal: opts?.signal,\n });\n return [...data];\n },\n async count(opts): Promise<number> {\n const params = new URLSearchParams();\n params.set(\"collection\", collectionName);\n if (state.wire.clauses.length > 0) {\n params.set(\"where\", JSON.stringify(state.wire));\n }\n const { count } = await request<{ count: number }>(ctx, {\n method: \"GET\",\n path: `/v1/count?${params.toString()}`,\n signal: opts?.signal,\n });\n return count;\n },\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAoPA,MAAa,sBACX,YAC0B;CAC1B,MAAM,MAAsB;EAC1B,SAAS,QAAQ;EACjB,OAAO,QAAQ,WAAW,QAAQ,WAAW,MAAM,GAAG;EACtD,SAAS,IAAI,QAAQ,QAAQ,WAAW,CAAC,CAAC;CAC5C;CAOA,OAAO;GALJ,iBAAiB;EAClB,WAAkD,MAAmC;GACnF,OAAO,qBAAwB,KAAK,IAAI;EAC1C;CA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,gBAAmB,KAAK,gBAAgB;GAAE,GAAG;GAAO,OAAO;EAAE,CAAC;EAE5F,MAAM,MAAM,MAA8B;GASxC,QAAO,MALY,QAA0B,KAAK;IAChD,QAAQ;IACR,MAAM,SAAS,EAAE,OAAO,EAAE,CAAC;IAC3B,QAAQ,MAAM;GAChB,CAAC,GACW;EACd;EACA,MAAM,IAAI,MAAoB;GAM5B,OAAO,CAAC,GAAG,MALQ,QAA0B,KAAK;IAChD,QAAQ;IACR,MAAM,SAAS;IACf,QAAQ,MAAM;GAChB,CAAC,CACc;EACjB;EACA,MAAM,MAAM,MAAuB;GACjC,MAAM,SAAS,IAAI,gBAAgB;GACnC,OAAO,IAAI,cAAc,cAAc;GACvC,IAAI,MAAM,KAAK,QAAQ,SAAS,GAC9B,OAAO,IAAI,SAAS,KAAK,UAAU,MAAM,IAAI,CAAC;GAEhD,MAAM,EAAE,UAAU,MAAM,QAA2B,KAAK;IACtD,QAAQ;IACR,MAAM,aAAa,OAAO,SAAS;IACnC,QAAQ,MAAM;GAChB,CAAC;GACD,OAAO;EACT;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"client.js","names":[],"sources":["../packages/client/src/client.ts"],"sourcesContent":["/* eslint-disable no-underscore-dangle -- `_id` and `_meta` are the\n locked wire-shape field names (see `packages/protocol/src/collection-api.ts`\n and `packages/server/src/contract.ts`); we mirror them verbatim\n so the typed client stays structurally compatible. */\n\nimport {\n type BaerlyConfig,\n BaerlyError,\n type CollectionNames,\n type DocumentData,\n EMPTY_PREDICATE_WIRE,\n normalizePredicateArg,\n type OrderSpec,\n type PredicateArg,\n type PredicateWire,\n type RowOf,\n type UnboundConfig,\n} from \"@baerly/protocol\";\nimport { CLIENT_CONTEXT } from \"./internal/context.ts\";\nimport { type Fetcher, type RequestContext, request } from \"./request.ts\";\n\n/**\n * Public options for {@link createBaerlyClient}.\n *\n * @example\n * ```ts\n * const client = createBaerlyClient({\n * baseUrl: \"https://api.example.com\",\n * headers: { Authorization: \"Bearer <token>\" },\n * });\n * ```\n */\nexport interface BaerlyClientOptions<TConfig extends BaerlyConfig = UnboundConfig> {\n /**\n * Required. The deployed `baerly` server URL — e.g.\n * `https://acme.example.com`. No trailing slash.\n */\n readonly baseUrl: string;\n /**\n * Optional. Defaults to `globalThis.fetch`. Wrap your own to add\n * logging, retries, tracing, or auth-refresh — the entire client\n * routes every request through this one function. This is the\n * `link` middleware story (tRPC) and the `interceptor` story\n * (axios) without new API surface.\n *\n * @example\n * ```ts\n * // Log every request + response.\n * const withLogging: Fetcher = async (req) => {\n * const t0 = performance.now();\n * const res = await globalThis.fetch(req);\n * console.log(`${req.method} ${req.url} → ${res.status} (${Math.round(performance.now() - t0)}ms)`);\n * return res;\n * };\n *\n * // Retry idempotent reads on 5xx (max 3 total attempts, 100ms backoff).\n * const withRetry = (next: Fetcher): Fetcher => async (req) => {\n * for (let i = 0; i < 2; i++) {\n * const res = await next(req.clone());\n * if (res.ok || res.status < 500 || req.method !== \"GET\") return res;\n * await new Promise((r) => setTimeout(r, 100 * (i + 1)));\n * }\n * return next(req);\n * };\n *\n * const client = createBaerlyClient({\n * baseUrl: \"https://api.example.com\",\n * fetch: withRetry(withLogging),\n * });\n * ```\n *\n * See `dist/API.md` → \"Recipe — wrapping the client `fetch`\"\n * for `onSuccess` / `onError` helpers and a composition pattern.\n */\n readonly fetch?: Fetcher;\n /**\n * Optional. Forwarded on every request. Typically\n * `{ Authorization: \"Bearer <token>\" }`. For credential refresh\n * (fresh JWT per call, 401-driven re-issue, etc.) wrap\n * {@link BaerlyClientOptions.fetch} instead — see the retry +\n * logging examples above.\n */\n readonly headers?: Headers | Record<string, string>;\n /**\n * Optional. **Type-only** — the runtime client does not read this\n * field; it exists so `client.collection(name)` can narrow `name` to\n * declared collection names and infer the row type from\n * `collections[name].schema`. Bind the type via the generic\n * parameter using `import type` so the server-side storage\n * adapter and secrets in `baerly.config.ts` do not enter the\n * browser bundle:\n *\n * ```ts\n * import type config from \"./baerly.config.ts\";\n * const client = createBaerlyClient<typeof config>({ baseUrl });\n * await client.collection(\"tickets\").first(); // Promise<Ticket | undefined>\n * ```\n *\n * Skip the type parameter to fall back to the per-call generic\n * `client.collection(\"tickets\")` form.\n */\n readonly config?: TConfig;\n}\n\n/**\n * Trailing-options bag accepted by every terminal. Today this is\n * only `signal`, so the type is split out for readability rather\n * than forcing every call site to ascribe `{ signal?: AbortSignal }`.\n * When other per-call options land (timeout, idempotency key, etc.)\n * they belong here.\n */\nexport interface TerminalOptions {\n /**\n * Cancels this specific request. React effect cleanup is the\n * canonical caller:\n *\n * ```ts\n * useEffect(() => {\n * const ac = new AbortController();\n * client.collection(\"tickets\").where(p).all({ signal: ac.signal }).then(setRows);\n * return () => ac.abort();\n * }, [predicateKey]);\n * ```\n */\n readonly signal?: AbortSignal;\n}\n\n/**\n * Client-side mirror of `Collection<T>` from `@baerly/protocol`. Cheap\n * handle; constructs no I/O. Same method names as the in-process\n * `Collection<T>`, but every terminal also accepts a trailing\n * {@link TerminalOptions} bag carrying `{ signal }`.\n *\n * By-id mutation verbs (`update`, `replace`, `delete`) live here;\n * predicate-aware bulk mutation has no HTTP route today and is\n * intentionally absent from {@link ClientQuery}.\n *\n * @template T — document shape. `_id` is always present on rows\n * returned from the server.\n */\nexport interface ClientCollection<T extends DocumentData = DocumentData> {\n readonly name: string;\n /** First document in the whole collection or `undefined`. */\n first(opts?: TerminalOptions): Promise<T | undefined>;\n /** Every document in the whole collection. Pair with `.where(...).limit(n)` on large collections. */\n all(opts?: TerminalOptions): Promise<T[]>;\n /** Count every row in the collection (equivalent to `.where({}).count()`). */\n count(opts?: TerminalOptions): Promise<number>;\n /** Fetch one document by primary key. Returns `undefined` when the id is unknown. */\n get(id: string, opts?: TerminalOptions): Promise<T | undefined>;\n /**\n * Filter rows. Two shapes:\n *\n * - **Object literal** — equality only.\n * - **Callback DSL** — `q => q.eq(...).gt(...).in(...)` for the\n * operator vocabulary.\n *\n * Chained calls AND-merge across shapes.\n */\n where(predicate: PredicateArg<T>): ClientQuery<T>;\n /** Order modifier; last call wins. */\n order(spec: OrderSpec<T>): ClientQuery<T>;\n /** Limit modifier; last call wins. */\n limit(n: number): ClientQuery<T>;\n /** Insert a new document. Returns the server-assigned `_id`. */\n insert(doc: Partial<T> & DocumentData, opts?: TerminalOptions): Promise<{ readonly _id: string }>;\n /** JSON-merge-patch applied to one row by primary key. */\n update(\n id: string,\n patch: Partial<T>,\n opts?: TerminalOptions,\n ): Promise<{ readonly modified: number }>;\n /** Whole-document replace on one row by primary key. */\n replace(id: string, doc: T, opts?: TerminalOptions): Promise<void>;\n /** Delete one row by primary key. Returns `{ deleted: 0 }` on 404 (not an error). */\n delete(id: string, opts?: TerminalOptions): Promise<{ readonly deleted: number }>;\n}\n\n/**\n * Client-side mirror of `Query<T>` from `@baerly/protocol`. See\n * {@link ClientCollection} for the method-shape contract.\n *\n * Read-only over HTTP: by-id mutation lives on {@link ClientCollection}\n * directly. Predicate-aware bulk mutation is server-only — the HTTP\n * surface has no route for it.\n */\nexport interface ClientQuery<T extends DocumentData = DocumentData> {\n where(predicate: PredicateArg<T>): ClientQuery<T>;\n order(spec: OrderSpec<T>): ClientQuery<T>;\n limit(n: number): ClientQuery<T>;\n /** First match or `undefined`. Issues `GET /v1/c/:collection?...&limit=1`. */\n first(opts?: TerminalOptions): Promise<T | undefined>;\n /** Every matching document. Pair with `.limit(n)` on large collections. */\n all(opts?: TerminalOptions): Promise<T[]>;\n /** Count matching rows. Issues `GET /v1/count?collection=&where=`; server returns a scalar. */\n count(opts?: TerminalOptions): Promise<number>;\n}\n\n/**\n * Returned by {@link createBaerlyClient}. The typed entry point.\n *\n * `BaerlyClient` is read + single-write RPC: reads and by-id\n * mutations (`insert` / `update` / `replace` / `delete`), one\n * document per call. There is no multi-document atomic write — the\n * document is the atomic unit, and the server exposes no batch route.\n * If you need to fan a write across several documents server-side,\n * expose a business-level RPC on the server that drives\n * `db.collection(...)` in-process.\n *\n * @example\n * ```ts\n * const client = createBaerlyClient({ baseUrl: \"https://api.example.com\" });\n * const { _id } = await client.collection(\"tickets\").insert({ title: \"hi\" });\n * const row = await client.collection(\"tickets\").get(_id);\n * ```\n */\nexport interface BaerlyClient<TConfig extends BaerlyConfig = UnboundConfig> {\n /**\n * Typed collection handle. Cheap; constructs no I/O.\n *\n * When `TConfig` is bound (via `options.config`) and `name` is one\n * of the declared collection names, the row type is inferred from\n * `TConfig[\"collections\"][name][\"schema\"]`. Otherwise the row type\n * defaults to `DocumentData` and the call accepts any string name —\n * matching the in-process `Db.collection` shape.\n */\n collection<N extends CollectionNames<TConfig>>(\n name: N,\n ): ClientCollection<RowOf<TConfig, N> & DocumentData>;\n}\n\n/**\n * Construct a typed HTTP client over the locked `/v1/...` routes.\n * Returns a {@link BaerlyClient} with the same surface as the\n * in-process `Db.collection(...)` API.\n *\n * @example\n * ```ts\n * const client = createBaerlyClient({\n * baseUrl: \"https://api.example.com\",\n * headers: { Authorization: \"Bearer <token>\" },\n * });\n * ```\n */\nexport const createBaerlyClient = <TConfig extends BaerlyConfig = UnboundConfig>(\n options: BaerlyClientOptions<TConfig>,\n): BaerlyClient<TConfig> => {\n const ctx: RequestContext = {\n baseUrl: options.baseUrl,\n fetch: options.fetch ?? ((req) => globalThis.fetch(req)),\n headers: new Headers(options.headers ?? {}),\n };\n const client = {\n [CLIENT_CONTEXT]: ctx,\n collection<T extends DocumentData = DocumentData>(name: string): ClientCollection<T> {\n return makeClientCollection<T>(ctx, name);\n },\n };\n return client as BaerlyClient<TConfig>;\n};\n\n/** Query-state carried across the chainable modifiers. */\ninterface QueryState {\n readonly wire: PredicateWire;\n readonly order: OrderSpec<DocumentData> | undefined;\n readonly limit: number | undefined;\n}\n\nconst emptyState: QueryState = {\n wire: EMPTY_PREDICATE_WIRE,\n order: undefined,\n limit: undefined,\n};\n\nconst makeClientCollection = <T extends DocumentData>(\n ctx: RequestContext,\n name: string,\n): ClientCollection<T> => {\n const collectionForQuery = makeClientQuery<T>(ctx, name, emptyState);\n const idPath = (id: string): string =>\n `/v1/c/${encodeURIComponent(name)}/${encodeURIComponent(id)}`;\n return {\n name,\n where: (predicate) => collectionForQuery.where(predicate),\n order: (spec) => collectionForQuery.order(spec),\n limit: (n) => collectionForQuery.limit(n),\n first: (opts) => collectionForQuery.first(opts),\n all: (opts) => collectionForQuery.all(opts),\n count: (opts) => collectionForQuery.count(opts),\n async get(id, opts): Promise<T | undefined> {\n try {\n return await request<T>(ctx, {\n method: \"GET\",\n path: idPath(id),\n signal: opts?.signal,\n });\n } catch (error) {\n // 404 on GET → unknown id. Mirrors `Db.collection().get(id)` which\n // resolves `undefined` rather than throwing.\n if (error instanceof BaerlyError && error.code === \"NotFound\") {\n return undefined;\n }\n throw error;\n }\n },\n async insert(doc, opts): Promise<{ readonly _id: string }> {\n return request<{ _id: string }>(ctx, {\n method: \"POST\",\n path: `/v1/c/${encodeURIComponent(name)}`,\n body: { doc },\n signal: opts?.signal,\n });\n },\n async update(id, patch, opts): Promise<{ readonly modified: number }> {\n return request<{ modified: number }>(ctx, {\n method: \"PATCH\",\n path: idPath(id),\n body: { patch },\n signal: opts?.signal,\n });\n },\n async replace(id, doc, opts): Promise<void> {\n // PUT = whole-document overwrite. NOT PATCH — PATCH would be\n // RFC 7386 merge-patch and silently retain omitted fields from\n // the prior doc.\n await request<{ modified: number }>(ctx, {\n method: \"PUT\",\n path: idPath(id),\n body: { doc },\n signal: opts?.signal,\n });\n },\n async delete(id, opts): Promise<{ readonly deleted: number }> {\n try {\n await request<undefined>(ctx, {\n method: \"DELETE\",\n path: idPath(id),\n signal: opts?.signal,\n });\n return { deleted: 1 };\n } catch (error) {\n // 404 on DELETE → \"no row matched\". Mirrors `Query.delete()`\n // which returns `{ deleted: 0 }` rather than throwing.\n if (error instanceof BaerlyError && error.code === \"NotFound\") {\n return { deleted: 0 };\n }\n throw error;\n }\n },\n };\n};\n\nconst makeClientQuery = <T extends DocumentData>(\n ctx: RequestContext,\n collectionName: string,\n state: QueryState,\n): ClientQuery<T> => {\n const listParams = (): URLSearchParams => {\n const params = new URLSearchParams();\n if (state.wire.clauses.length > 0) {\n params.set(\"where\", JSON.stringify(state.wire));\n }\n if (state.order !== undefined && Object.keys(state.order).length > 0) {\n params.set(\"order\", JSON.stringify(state.order));\n }\n if (state.limit !== undefined) {\n params.set(\"limit\", String(state.limit));\n }\n return params;\n };\n\n const listPath = (override?: { limit?: number }): string => {\n const params = listParams();\n if (override?.limit !== undefined) {\n params.set(\"limit\", String(override.limit));\n }\n const qs = params.toString();\n return `/v1/c/${encodeURIComponent(collectionName)}${qs.length > 0 ? `?${qs}` : \"\"}`;\n };\n\n return {\n where: (predicate): ClientQuery<T> => {\n // Normalise the incoming arg (object or callback) to a wire and\n // concatenate clauses with any prior wire. The server's\n // `parseWhereParam` runs `validateWire` on arrival, so empty\n // `in` / conflicting `eq` / unsatisfiable interval surface as\n // a 400 `InvalidConfig` / `UnsatisfiablePredicate` from the\n // HTTP layer — no client-side merger needed. Skipping the\n // satisfiability check here keeps the SPA bundle out of the\n // wire-merger / per-field-fold code path.\n const incoming = normalizePredicateArg<T>(predicate);\n const merged: PredicateWire =\n state.wire.clauses.length === 0\n ? incoming\n : { clauses: [...state.wire.clauses, ...incoming.clauses] };\n return makeClientQuery<T>(ctx, collectionName, { ...state, wire: merged });\n },\n order: (spec): ClientQuery<T> =>\n makeClientQuery<T>(ctx, collectionName, {\n ...state,\n order: spec as OrderSpec<DocumentData>,\n }),\n limit: (n): ClientQuery<T> => makeClientQuery<T>(ctx, collectionName, { ...state, limit: n }),\n\n async first(opts): Promise<T | undefined> {\n // Mirrors `Db.first()` which sets `limit: 1` on its underlying\n // list call; override the query-state limit for this terminal\n // only (chained `.limit(n).first()` semantics: `first` wins).\n const data = await request<ReadonlyArray<T>>(ctx, {\n method: \"GET\",\n path: listPath({ limit: 1 }),\n signal: opts?.signal,\n });\n return data[0];\n },\n async all(opts): Promise<T[]> {\n const data = await request<ReadonlyArray<T>>(ctx, {\n method: \"GET\",\n path: listPath(),\n signal: opts?.signal,\n });\n return [...data];\n },\n async count(opts): Promise<number> {\n const params = new URLSearchParams();\n params.set(\"collection\", collectionName);\n if (state.wire.clauses.length > 0) {\n params.set(\"where\", JSON.stringify(state.wire));\n }\n const { count } = await request<{ count: number }>(ctx, {\n method: \"GET\",\n path: `/v1/count?${params.toString()}`,\n signal: opts?.signal,\n });\n return count;\n },\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAoPA,MAAa,sBACX,YAC0B;CAC1B,MAAM,MAAsB;EAC1B,SAAS,QAAQ;EACjB,OAAO,QAAQ,WAAW,QAAQ,WAAW,MAAM,GAAG;EACtD,SAAS,IAAI,QAAQ,QAAQ,WAAW,CAAC,CAAC;CAC5C;CAOA,OAAO;GALJ,iBAAiB;EAClB,WAAkD,MAAmC;GACnF,OAAO,qBAAwB,KAAK,IAAI;EAC1C;CAEU;AACd;AASA,MAAM,aAAyB;CAC7B,MAAM;CACN,OAAO,KAAA;CACP,OAAO,KAAA;AACT;AAEA,MAAM,wBACJ,KACA,SACwB;CACxB,MAAM,qBAAqB,gBAAmB,KAAK,MAAM,UAAU;CACnE,MAAM,UAAU,OACd,SAAS,mBAAmB,IAAI,EAAE,GAAG,mBAAmB,EAAE;CAC5D,OAAO;EACL;EACA,QAAQ,cAAc,mBAAmB,MAAM,SAAS;EACxD,QAAQ,SAAS,mBAAmB,MAAM,IAAI;EAC9C,QAAQ,MAAM,mBAAmB,MAAM,CAAC;EACxC,QAAQ,SAAS,mBAAmB,MAAM,IAAI;EAC9C,MAAM,SAAS,mBAAmB,IAAI,IAAI;EAC1C,QAAQ,SAAS,mBAAmB,MAAM,IAAI;EAC9C,MAAM,IAAI,IAAI,MAA8B;GAC1C,IAAI;IACF,OAAO,MAAM,QAAW,KAAK;KAC3B,QAAQ;KACR,MAAM,OAAO,EAAE;KACf,QAAQ,MAAM;IAChB,CAAC;GACH,SAAS,OAAO;IAGd,IAAI,iBAAiB,eAAe,MAAM,SAAS,YACjD;IAEF,M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