@lunora/replica 1.0.0-alpha.8 → 1.0.0-alpha.81
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.md +214 -0
- package/README.md +55 -10
- package/dist/adapters/better-sqlite3.d.mts +1 -1
- package/dist/adapters/better-sqlite3.d.ts +1 -1
- package/dist/adapters/better-sqlite3.mjs +1 -29
- package/dist/adapters/sqlite-wasm.d.mts +3 -9
- package/dist/adapters/sqlite-wasm.d.ts +3 -9
- package/dist/adapters/sqlite-wasm.mjs +1 -44
- package/dist/adapters/sqljs.d.mts +1 -1
- package/dist/adapters/sqljs.d.ts +1 -1
- package/dist/adapters/sqljs.mjs +1 -55
- package/dist/index.d.mts +156 -57
- package/dist/index.d.ts +156 -57
- package/dist/index.mjs +1 -20
- package/dist/packem_shared/EventEmitter-uo75adUL.mjs +1 -0
- package/dist/packem_shared/EventLog-B1-yhArT.mjs +1 -0
- package/dist/packem_shared/EventLogDO-BgUx2GGL.mjs +1 -0
- package/dist/packem_shared/EventLogDOClient-DWerZ3_n.mjs +1 -0
- package/dist/packem_shared/EventSource-BC0hKJSA.mjs +1 -0
- package/dist/packem_shared/EventsSync-B3wzXm-b.mjs +1 -0
- package/dist/packem_shared/InMemorySnapshotStore-C4taIG5K.mjs +1 -0
- package/dist/packem_shared/LocalMirror-DP6flo3R.mjs +4 -0
- package/dist/packem_shared/MaterializerRuntime-DdszLF-h.mjs +1 -0
- package/dist/packem_shared/SubscriptionManager-AhPw3lFc.mjs +1 -0
- package/dist/packem_shared/applyDiff-BaUgblCl.mjs +1 -0
- package/dist/packem_shared/applyDiffToDb-DiSnjR45.mjs +1 -0
- package/dist/packem_shared/classifyChanges-BBc0-770.mjs +1 -0
- package/dist/packem_shared/defineEvents-DHo-VK7G.mjs +1 -0
- package/dist/packem_shared/eventsContext-Dxow9Y7S.mjs +1 -0
- package/dist/packem_shared/fnv1a-BNN96GYb.mjs +1 -0
- package/dist/packem_shared/isClientSeq-D2Xm0_lj.mjs +1 -0
- package/dist/packem_shared/{local-mirror.d-DTavX_y0.d.mts → local-mirror.d-CHCqFAg9.d.mts} +31 -14
- package/dist/packem_shared/{local-mirror.d-CyGOpUES.d.ts → local-mirror.d-CvNV3_gk.d.ts} +31 -14
- package/dist/packem_shared/subscribeToMirror-Cv24WiWj.mjs +1 -0
- package/dist/packem_shared/{types.d-CkMkSwLJ.d.mts → types.d-BuLTPLaQ.d.mts} +0 -2
- package/dist/packem_shared/{types.d-CkMkSwLJ.d.ts → types.d-BuLTPLaQ.d.ts} +0 -2
- package/dist/packem_shared/wire-key-CU8KEXPo.mjs +1 -0
- package/dist/react.d.mts +39 -29
- package/dist/react.d.ts +39 -29
- package/dist/react.mjs +1 -15
- package/package.json +1 -1
- package/dist/packem_shared/EventEmitter-CMZfct03.mjs +0 -92
- package/dist/packem_shared/EventLog-CnK-3Wge.mjs +0 -264
- package/dist/packem_shared/EventLogDO-DqlsVx0H.mjs +0 -381
- package/dist/packem_shared/EventLogDOClient-F4FO8Si4.mjs +0 -92
- package/dist/packem_shared/EventSource-D5yO9_aI.mjs +0 -221
- package/dist/packem_shared/EventsSync-BP36tC9O.mjs +0 -123
- package/dist/packem_shared/InMemorySnapshotStore-BHVAD-Bp.mjs +0 -24
- package/dist/packem_shared/LocalMirror-a-5jEqFN.mjs +0 -219
- package/dist/packem_shared/MaterializerRuntime-BoIrsMYB.mjs +0 -224
- package/dist/packem_shared/SubscriptionManager-C5xbw0pg.mjs +0 -75
- package/dist/packem_shared/applyDiff-98tKzmiW.mjs +0 -67
- package/dist/packem_shared/applyDiffToDb-DQ1xZp5J.mjs +0 -58
- package/dist/packem_shared/classifyChanges-RcqLBpLs.mjs +0 -41
- package/dist/packem_shared/defineEvents-DiBkPTh_.mjs +0 -28
- package/dist/packem_shared/eventsContext-Bk_p48hj.mjs +0 -6
- package/dist/packem_shared/isClientSeq-C46BkzqJ.mjs +0 -5
- package/dist/packem_shared/subscribeToMirror-CiaM-nQ7.mjs +0 -45
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { S as SqliteAdapter } from "./types.d-
|
|
1
|
+
import { S as SqliteAdapter } from "./types.d-BuLTPLaQ.js";
|
|
2
2
|
/**
|
|
3
3
|
* Row-level change kind within a TableDiff.
|
|
4
4
|
*
|
|
@@ -140,7 +140,7 @@ declare const isClientSeq: (seq: Seq) => seq is ClientSeq;
|
|
|
140
140
|
*
|
|
141
141
|
* ```ts
|
|
142
142
|
* const event = events.chat.messageSent({ channelId: "c1", text: "hello" });
|
|
143
|
-
* // event: InputEvent
|
|
143
|
+
* // event: InputEvent<"chat.messageSent", { channelId: string; text: string }>
|
|
144
144
|
* ```
|
|
145
145
|
* @experimental
|
|
146
146
|
*/
|
|
@@ -381,15 +381,18 @@ interface LocalMirrorOptions {
|
|
|
381
381
|
/** Platform-specific SQLite adapter. */
|
|
382
382
|
readonly db: SqliteAdapter;
|
|
383
383
|
/**
|
|
384
|
-
* Cap the mirror's internal {@link EventLog} to this many entries
|
|
385
|
-
*
|
|
386
|
-
*
|
|
384
|
+
* Cap the mirror's internal {@link EventLog} to this many entries.
|
|
385
|
+
* Every applied diff is recorded in the log, so an uncapped log grows by
|
|
386
|
+
* one entry (holding every changed row) per diff for the life of the
|
|
387
|
+
* mirror — a leak by construction on a long-lived client.
|
|
387
388
|
*
|
|
388
|
-
*
|
|
389
|
-
*
|
|
390
|
-
*
|
|
391
|
-
*
|
|
392
|
-
* a
|
|
389
|
+
* Defaults to {@link DEFAULT_MAX_EVENT_LOG_ENTRIES}. On overflow the
|
|
390
|
+
* OLDEST entries are dropped; nothing in the mirror replays its own log,
|
|
391
|
+
* so a drop loses nothing the mirror needs. A consumer that does replay
|
|
392
|
+
* it (`eventLog.getSince(watermark)` from another tab / service worker)
|
|
393
|
+
* detects a gap when the first returned entry's `seq` is above its
|
|
394
|
+
* watermark, and should re-seed from the mirror's rows (`query`) instead
|
|
395
|
+
* of applying the partial window.
|
|
393
396
|
*/
|
|
394
397
|
readonly maxEventLogEntries?: number;
|
|
395
398
|
/**
|
|
@@ -420,7 +423,7 @@ interface LocalMirrorOptions {
|
|
|
420
423
|
* mirror.applyDiff(someDiff);
|
|
421
424
|
*
|
|
422
425
|
* // Query locally:
|
|
423
|
-
* const rows = mirror.query
|
|
426
|
+
* const rows = mirror.query<{ id: string; name: string }>(
|
|
424
427
|
* "SELECT id, name FROM users WHERE name LIKE ?",
|
|
425
428
|
* ["alice%"],
|
|
426
429
|
* );
|
|
@@ -504,8 +507,17 @@ declare class LocalMirror {
|
|
|
504
507
|
*/
|
|
505
508
|
query<T = Record<string, unknown>>(sql: string, params?: ReadonlyArray<unknown>): T[];
|
|
506
509
|
/**
|
|
507
|
-
* Delete every row from
|
|
508
|
-
* and schema). Useful when re-syncing from scratch.
|
|
510
|
+
* Delete every row from every data table in the adapter's database
|
|
511
|
+
* (preserves the event log and schema). Useful when re-syncing from scratch.
|
|
512
|
+
*
|
|
513
|
+
* **The mirror owns its database.** The sweep is `sqlite_master` minus the
|
|
514
|
+
* reserved prefixes, NOT {@link LocalMirror.mirroredTables} — a table this
|
|
515
|
+
* mirror never registered is cleared too, and `#reconcileSchemaVersion`
|
|
516
|
+
* DROPs on the same list. It cannot be narrowed to the registered set: that
|
|
517
|
+
* runs from the constructor, before any `applyDiff` has re-registered the
|
|
518
|
+
* tables a previous session persisted, and those are exactly the
|
|
519
|
+
* stale-schema tables it exists to drop. So hand the adapter a database
|
|
520
|
+
* dedicated to the mirror, never one that also holds your own tables.
|
|
509
521
|
*
|
|
510
522
|
* Notifies `onChange` subscribers and bumps {@link LocalMirror.version}
|
|
511
523
|
* (REPLICA-09) even though nothing is appended to the event log — a
|
|
@@ -519,9 +531,14 @@ declare class LocalMirror {
|
|
|
519
531
|
close(): void;
|
|
520
532
|
/**
|
|
521
533
|
* Register a table schema so the mirror can create the table on
|
|
522
|
-
* first use.
|
|
534
|
+
* first use. Merges into any definition already registered for `name`
|
|
535
|
+
* (from the constructor's `tables` or an earlier call), so a helper that
|
|
536
|
+
* registers `{}` just to make the table known does not erase a
|
|
537
|
+
* user-supplied `primaryKey`.
|
|
523
538
|
*/
|
|
524
539
|
registerTable(name: string, definition: MirrorTableDef): void;
|
|
540
|
+
/** The primary-key column of a mirrored table (`"id"` unless registered otherwise). */
|
|
541
|
+
primaryKeyOf(table: string): string;
|
|
525
542
|
/**
|
|
526
543
|
* Return the list of mirrored table names.
|
|
527
544
|
*/
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{s as w}from"./wire-key-CU8KEXPo.mjs";const h=e=>`fn_${e.replaceAll(/[/:.]/g,"_")}`,m=e=>Array.isArray(e)?e:e!==null&&typeof e=="object"?[e]:[],M=(e,c,a,y,b)=>{const i=h(a.__lunoraRef);c.registerTable(i,{});const u=c.primaryKeyOf(i);let p=new Map;return e.subscribe(a,y,d=>{const r=new Map,f=new Map,o=[];for(const t of m(d)){const n=t,s=n[u];if(typeof s!="string"&&typeof s!="number"&&typeof s!="bigint"){o.push({type:"insert",data:n});continue}const l=String(s),g=w(n);r.set(l,g),f.set(l,n)}for(const[t,n]of r)p.get(t)!==n&&o.push({data:f.get(t),type:"insert"});for(const t of p.keys())r.has(t)||o.push({type:"delete",id:t});o.length>0&&c.applyDiff({table:i,changes:o,timestamp:Date.now()}),p=r},{shardKey:b})};export{M as subscribeToMirror};
|
|
@@ -11,8 +11,6 @@ interface SqliteAdapter {
|
|
|
11
11
|
close: () => void;
|
|
12
12
|
/** Execute a SQL statement (with optional bound params). */
|
|
13
13
|
exec: (sql: string, params?: ReadonlyArray<unknown>) => void;
|
|
14
|
-
/** Return the id of the last inserted row. */
|
|
15
|
-
lastInsertRowId: () => number;
|
|
16
14
|
/**
|
|
17
15
|
* Execute a SQL statement and return the result rows.
|
|
18
16
|
* Columns can be accessed by index or by name.
|
|
@@ -11,8 +11,6 @@ interface SqliteAdapter {
|
|
|
11
11
|
close: () => void;
|
|
12
12
|
/** Execute a SQL statement (with optional bound params). */
|
|
13
13
|
exec: (sql: string, params?: ReadonlyArray<unknown>) => void;
|
|
14
|
-
/** Return the id of the last inserted row. */
|
|
15
|
-
lastInsertRowId: () => number;
|
|
16
14
|
/**
|
|
17
15
|
* Execute a SQL statement and return the result rows.
|
|
18
16
|
* Columns can be accessed by index or by name.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const d=/["\\\u0000-\u001F\uD800-\uDFFF]/,p=r=>d.test(r)?JSON.stringify(r):`"${r}"`,b=r=>{if(r===void 0)return"null";if(typeof r=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key — pass it as a string, or use stableWireKey");if(typeof r=="number"){if(Number.isNaN(r))return"nan";if(r===1/0)return"inf";if(r===-1/0)return"-inf";if(Object.is(r,-0))return"-0"}if(typeof r=="string")return p(r);if(r===null||typeof r!="object")return JSON.stringify(r);if(Array.isArray(r)){let n="[";for(let i=0;i<r.length;i++)i>0&&(n+=","),n+=b(r[i]);return n+"]"}const e=Object.getPrototypeOf(r);if(e!==null&&e!==Object.prototype){const n=r.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${n} in a stable JSON cache key — only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}const y=r,s=Object.keys(y).sort();let f="{",t=!0;for(const n of s){const i=y[n];i!==void 0&&(t?t=!1:f+=",",f+=p(n),f+=":",f+=b(i))}return f+"}"},u=r=>{let e="";for(let s=0;s<r.length;s+=32768)e+=String.fromCharCode(...r.subarray(s,s+32768));return btoa(e)},o="$lunora.wire$";const g="__proto__",m=r=>{if(r===null||typeof r!="object")return!1;const e=Object.getPrototypeOf(r);return e===null||e===Object.prototype},c=(r,e=0)=>{if(e>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(r===void 0)return[o,"undefined"];if(r===null)return null;const y=typeof r;if(y==="bigint")return[o,"bigint",r.toString()];if(y==="number"){const t=r;return Number.isNaN(t)?[o,"nan"]:t===1/0?[o,"inf"]:t===-1/0?[o,"-inf"]:t}if(y!=="object")return r;if(r instanceof Date)return[o,"date",c(r.getTime(),e+1)];if(r instanceof Error){const t=r,n={};for(const a of Object.keys(t))t[a]!==void 0&&(n[a]=c(t[a],e+1));const i=[o,"error",t.name,t.message,n];return t.cause!==void 0&&i.push(c(t.cause,e+1)),i}if(r instanceof URL)return[o,"url",r.href];if(r instanceof Map)return[o,"map",[...r.entries()].map(([t,n])=>[c(t,e+1),c(n,e+1)])];if(r instanceof Set)return[o,"set",[...r].map(t=>c(t,e+1))];if(r instanceof ArrayBuffer)return[o,"bytes",u(new Uint8Array(r)),"ArrayBuffer"];if(ArrayBuffer.isView(r)){const t=r,n=t.constructor.name,i=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);return n==="Uint8Array"?[o,"bytes",u(i)]:[o,"bytes",u(i),n]}if(Array.isArray(r)){const t=r.map(n=>c(n,e+1));return t.length>0&&t[0]===o?[o,"arr",t]:t}if(!m(r)){const t=r.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${t} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const s=r,f={};for(const t of Object.keys(s)){const n=s[t];if(n===void 0)continue;const i=c(n,e+1);t===g?Object.defineProperty(f,t,{configurable:!0,enumerable:!0,value:i,writable:!0}):f[t]=i}return f},w=r=>b(c(r));export{w as s};
|
package/dist/react.d.mts
CHANGED
|
@@ -1,26 +1,36 @@
|
|
|
1
|
-
import { L as LocalMirror } from "./packem_shared/local-mirror.d-
|
|
2
|
-
import "./packem_shared/types.d-
|
|
1
|
+
import { L as LocalMirror } from "./packem_shared/local-mirror.d-CHCqFAg9.mjs";
|
|
2
|
+
import "./packem_shared/types.d-BuLTPLaQ.mjs";
|
|
3
3
|
/**
|
|
4
|
-
*
|
|
4
|
+
* Result of {@link useLocalQuery} — a discriminated union so callers get a
|
|
5
|
+
* typed error instead of a swallowed `undefined`.
|
|
5
6
|
* @experimental
|
|
6
7
|
*/
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
* argument.
|
|
15
|
-
*/
|
|
16
|
-
shardKey?: string;
|
|
17
|
-
}
|
|
8
|
+
type LocalQueryResult<T> = {
|
|
9
|
+
readonly data: T[];
|
|
10
|
+
readonly error?: undefined;
|
|
11
|
+
} | {
|
|
12
|
+
readonly data?: undefined;
|
|
13
|
+
readonly error: Error;
|
|
14
|
+
};
|
|
18
15
|
/**
|
|
19
16
|
* React hook that subscribes to a local SQLite query and returns
|
|
20
17
|
* live-updating results whenever the mirror applies a diff.
|
|
21
18
|
*
|
|
22
|
-
* Uses `useSyncExternalStore`
|
|
23
|
-
*
|
|
19
|
+
* Uses `useSyncExternalStore` with `getSnapshot` reading {@link LocalMirror.version}
|
|
20
|
+
* — a plain number, unconditionally `Object.is`-stable across calls with no
|
|
21
|
+
* mutation in between. The actual query runs in a `useMemo` keyed on
|
|
22
|
+
* `[mirror, version, sql, stableParamsKey(params)]`, so it only re-executes
|
|
23
|
+
* when the mirror actually advances (or `sql`/`params` change) — not on
|
|
24
|
+
* every unrelated re-render.
|
|
25
|
+
*
|
|
26
|
+
* This intentionally does NOT cache query results inside {@link LocalMirror}
|
|
27
|
+
* itself: an LRU-capped cache in the mirror core evicts still-mounted hooks'
|
|
28
|
+
* entries once more than the cap's worth of distinct live queries are open
|
|
29
|
+
* on one mirror, which makes `getSnapshot` return a fresh (non-identical)
|
|
30
|
+
* object on the next read — `useSyncExternalStore` then force-re-renders,
|
|
31
|
+
* re-inserts, evicts another entry, and so on without bound. Keying the
|
|
32
|
+
* external-store snapshot on the version primitive instead of a cached
|
|
33
|
+
* query result has no such cap, so it can't loop.
|
|
24
34
|
*
|
|
25
35
|
* The hook works with React 18+ concurrent features, Suspense, and
|
|
26
36
|
* server-side rendering. During SSR the same value is returned as on
|
|
@@ -32,28 +42,28 @@ interface UseLocalQueryOptions {
|
|
|
32
42
|
* engine without rewriting).
|
|
33
43
|
* @param params Optional positional bound parameters matching `?`
|
|
34
44
|
* placeholders in `sql`.
|
|
35
|
-
* @
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
*
|
|
41
|
-
*
|
|
42
|
-
* **Error handling**: The hook catches SQL errors internally and returns
|
|
43
|
-
* `undefined`. Use a try-catch around `mirror.query(...)` directly if you
|
|
44
|
-
* need finer-grained error diagnostics.
|
|
45
|
+
* @returns `{ data }` with the result rows typed via the generic parameter
|
|
46
|
+
* `T`, or `{ error }` when the query fails (e.g. malformed SQL, or the
|
|
47
|
+
* target table doesn't exist yet because no matching diff has been applied
|
|
48
|
+
* — that specific case surfaces as a "no such table" `Error`). Never
|
|
49
|
+
* collapses a failure to `undefined` — check `error` explicitly rather than
|
|
50
|
+
* treating a missing `data` as "still loading".
|
|
45
51
|
* @example
|
|
46
52
|
* ```tsx
|
|
47
53
|
* import { useLocalQuery } from "@lunora/replica/react";
|
|
48
54
|
* import { mirror } from "./mirror";
|
|
49
55
|
*
|
|
50
56
|
* function UserList() {
|
|
51
|
-
* const users = useLocalQuery<{ id: string; name: string }>(
|
|
57
|
+
* const { data: users, error } = useLocalQuery<{ id: string; name: string }>(
|
|
52
58
|
* mirror,
|
|
53
59
|
* "SELECT id, name FROM fn_todos_list WHERE name LIKE ?",
|
|
54
60
|
* ["%alice%"],
|
|
55
61
|
* );
|
|
56
62
|
*
|
|
63
|
+
* if (error) {
|
|
64
|
+
* return <p>Query failed: {error.message}</p>;
|
|
65
|
+
* }
|
|
66
|
+
*
|
|
57
67
|
* if (users === undefined) {
|
|
58
68
|
* return <p>Waiting for data…</p>;
|
|
59
69
|
* }
|
|
@@ -63,5 +73,5 @@ interface UseLocalQueryOptions {
|
|
|
63
73
|
* ```
|
|
64
74
|
* @experimental
|
|
65
75
|
*/
|
|
66
|
-
declare const useLocalQuery: <T = Record<string, unknown>>(mirror: LocalMirror, sql: string, params?: ReadonlyArray<unknown
|
|
67
|
-
export {
|
|
76
|
+
declare const useLocalQuery: <T = Record<string, unknown>>(mirror: LocalMirror, sql: string, params?: ReadonlyArray<unknown>) => LocalQueryResult<T>;
|
|
77
|
+
export { type LocalQueryResult, useLocalQuery };
|
package/dist/react.d.ts
CHANGED
|
@@ -1,26 +1,36 @@
|
|
|
1
|
-
import { L as LocalMirror } from "./packem_shared/local-mirror.d-
|
|
2
|
-
import "./packem_shared/types.d-
|
|
1
|
+
import { L as LocalMirror } from "./packem_shared/local-mirror.d-CvNV3_gk.js";
|
|
2
|
+
import "./packem_shared/types.d-BuLTPLaQ.js";
|
|
3
3
|
/**
|
|
4
|
-
*
|
|
4
|
+
* Result of {@link useLocalQuery} — a discriminated union so callers get a
|
|
5
|
+
* typed error instead of a swallowed `undefined`.
|
|
5
6
|
* @experimental
|
|
6
7
|
*/
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
* argument.
|
|
15
|
-
*/
|
|
16
|
-
shardKey?: string;
|
|
17
|
-
}
|
|
8
|
+
type LocalQueryResult<T> = {
|
|
9
|
+
readonly data: T[];
|
|
10
|
+
readonly error?: undefined;
|
|
11
|
+
} | {
|
|
12
|
+
readonly data?: undefined;
|
|
13
|
+
readonly error: Error;
|
|
14
|
+
};
|
|
18
15
|
/**
|
|
19
16
|
* React hook that subscribes to a local SQLite query and returns
|
|
20
17
|
* live-updating results whenever the mirror applies a diff.
|
|
21
18
|
*
|
|
22
|
-
* Uses `useSyncExternalStore`
|
|
23
|
-
*
|
|
19
|
+
* Uses `useSyncExternalStore` with `getSnapshot` reading {@link LocalMirror.version}
|
|
20
|
+
* — a plain number, unconditionally `Object.is`-stable across calls with no
|
|
21
|
+
* mutation in between. The actual query runs in a `useMemo` keyed on
|
|
22
|
+
* `[mirror, version, sql, stableParamsKey(params)]`, so it only re-executes
|
|
23
|
+
* when the mirror actually advances (or `sql`/`params` change) — not on
|
|
24
|
+
* every unrelated re-render.
|
|
25
|
+
*
|
|
26
|
+
* This intentionally does NOT cache query results inside {@link LocalMirror}
|
|
27
|
+
* itself: an LRU-capped cache in the mirror core evicts still-mounted hooks'
|
|
28
|
+
* entries once more than the cap's worth of distinct live queries are open
|
|
29
|
+
* on one mirror, which makes `getSnapshot` return a fresh (non-identical)
|
|
30
|
+
* object on the next read — `useSyncExternalStore` then force-re-renders,
|
|
31
|
+
* re-inserts, evicts another entry, and so on without bound. Keying the
|
|
32
|
+
* external-store snapshot on the version primitive instead of a cached
|
|
33
|
+
* query result has no such cap, so it can't loop.
|
|
24
34
|
*
|
|
25
35
|
* The hook works with React 18+ concurrent features, Suspense, and
|
|
26
36
|
* server-side rendering. During SSR the same value is returned as on
|
|
@@ -32,28 +42,28 @@ interface UseLocalQueryOptions {
|
|
|
32
42
|
* engine without rewriting).
|
|
33
43
|
* @param params Optional positional bound parameters matching `?`
|
|
34
44
|
* placeholders in `sql`.
|
|
35
|
-
* @
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
*
|
|
41
|
-
*
|
|
42
|
-
* **Error handling**: The hook catches SQL errors internally and returns
|
|
43
|
-
* `undefined`. Use a try-catch around `mirror.query(...)` directly if you
|
|
44
|
-
* need finer-grained error diagnostics.
|
|
45
|
+
* @returns `{ data }` with the result rows typed via the generic parameter
|
|
46
|
+
* `T`, or `{ error }` when the query fails (e.g. malformed SQL, or the
|
|
47
|
+
* target table doesn't exist yet because no matching diff has been applied
|
|
48
|
+
* — that specific case surfaces as a "no such table" `Error`). Never
|
|
49
|
+
* collapses a failure to `undefined` — check `error` explicitly rather than
|
|
50
|
+
* treating a missing `data` as "still loading".
|
|
45
51
|
* @example
|
|
46
52
|
* ```tsx
|
|
47
53
|
* import { useLocalQuery } from "@lunora/replica/react";
|
|
48
54
|
* import { mirror } from "./mirror";
|
|
49
55
|
*
|
|
50
56
|
* function UserList() {
|
|
51
|
-
* const users = useLocalQuery<{ id: string; name: string }>(
|
|
57
|
+
* const { data: users, error } = useLocalQuery<{ id: string; name: string }>(
|
|
52
58
|
* mirror,
|
|
53
59
|
* "SELECT id, name FROM fn_todos_list WHERE name LIKE ?",
|
|
54
60
|
* ["%alice%"],
|
|
55
61
|
* );
|
|
56
62
|
*
|
|
63
|
+
* if (error) {
|
|
64
|
+
* return <p>Query failed: {error.message}</p>;
|
|
65
|
+
* }
|
|
66
|
+
*
|
|
57
67
|
* if (users === undefined) {
|
|
58
68
|
* return <p>Waiting for data…</p>;
|
|
59
69
|
* }
|
|
@@ -63,5 +73,5 @@ interface UseLocalQueryOptions {
|
|
|
63
73
|
* ```
|
|
64
74
|
* @experimental
|
|
65
75
|
*/
|
|
66
|
-
declare const useLocalQuery: <T = Record<string, unknown>>(mirror: LocalMirror, sql: string, params?: ReadonlyArray<unknown
|
|
67
|
-
export {
|
|
76
|
+
declare const useLocalQuery: <T = Record<string, unknown>>(mirror: LocalMirror, sql: string, params?: ReadonlyArray<unknown>) => LocalQueryResult<T>;
|
|
77
|
+
export { type LocalQueryResult, useLocalQuery };
|
package/dist/react.mjs
CHANGED
|
@@ -1,15 +1 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
const useLocalQuery = (mirror, sql, params, _options) => {
|
|
4
|
-
const subscribe = (onStoreChange) => mirror.onChange(onStoreChange);
|
|
5
|
-
const getSnapshot = () => mirror.version;
|
|
6
|
-
const getServerSnapshot = () => mirror.version;
|
|
7
|
-
useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
|
|
8
|
-
try {
|
|
9
|
-
return mirror.query(sql, params);
|
|
10
|
-
} catch {
|
|
11
|
-
return void 0;
|
|
12
|
-
}
|
|
13
|
-
};
|
|
14
|
-
|
|
15
|
-
export { useLocalQuery };
|
|
1
|
+
import{useSyncExternalStore as y,useMemo as i}from"react";const u=t=>JSON.stringify(t??[],(r,e)=>typeof e=="bigint"?`${e.toString()}n`:e),S=(t,r,e)=>{const s=n=>t.onChange(n),o=()=>t.version,c=y(s,o,o),a=u(e);return i(()=>{try{return{data:t.query(r,e)}}catch(n){return{error:n instanceof Error?n:new Error(String(n))}}},[t,c,r,a])};export{S as useLocalQuery};
|
package/package.json
CHANGED
|
@@ -1,92 +0,0 @@
|
|
|
1
|
-
class EventEmitter {
|
|
2
|
-
#listeners = /* @__PURE__ */ new Map();
|
|
3
|
-
#wildcardListeners = /* @__PURE__ */ new Set();
|
|
4
|
-
// ── Registration ──────────────────────────────────────────────────
|
|
5
|
-
/**
|
|
6
|
-
* Register a handler for a specific event type.
|
|
7
|
-
* @returns An unsubscribe function (equivalent to calling {@link off}).
|
|
8
|
-
*/
|
|
9
|
-
on(event, handler) {
|
|
10
|
-
let set = this.#listeners.get(event);
|
|
11
|
-
if (!set) {
|
|
12
|
-
set = /* @__PURE__ */ new Set();
|
|
13
|
-
this.#listeners.set(event, set);
|
|
14
|
-
}
|
|
15
|
-
set.add(handler);
|
|
16
|
-
return () => {
|
|
17
|
-
this.off(event, handler);
|
|
18
|
-
};
|
|
19
|
-
}
|
|
20
|
-
/**
|
|
21
|
-
* Remove a previously registered handler.
|
|
22
|
-
*/
|
|
23
|
-
off(event, handler) {
|
|
24
|
-
this.#listeners.get(event)?.delete(handler);
|
|
25
|
-
}
|
|
26
|
-
/**
|
|
27
|
-
* Register a wildcard handler that fires for **every** event type.
|
|
28
|
-
* @returns An unsubscribe function.
|
|
29
|
-
*/
|
|
30
|
-
onAny(handler) {
|
|
31
|
-
this.#wildcardListeners.add(handler);
|
|
32
|
-
return () => {
|
|
33
|
-
this.#wildcardListeners.delete(handler);
|
|
34
|
-
};
|
|
35
|
-
}
|
|
36
|
-
/**
|
|
37
|
-
* Remove a wildcard handler.
|
|
38
|
-
*/
|
|
39
|
-
offAny(handler) {
|
|
40
|
-
this.#wildcardListeners.delete(handler);
|
|
41
|
-
}
|
|
42
|
-
// ── Emission ──────────────────────────────────────────────────────
|
|
43
|
-
/**
|
|
44
|
-
* Emit an event. All registered handlers (typed + wildcard) are invoked
|
|
45
|
-
* synchronously. Exceptions from handlers are caught and silently
|
|
46
|
-
* swallowed — they **must not** break the emitter loop.
|
|
47
|
-
* @returns `true` if at least one handler was called.
|
|
48
|
-
*/
|
|
49
|
-
emit(event, payload) {
|
|
50
|
-
let called = false;
|
|
51
|
-
const typed = this.#listeners.get(event);
|
|
52
|
-
if (typed) {
|
|
53
|
-
for (const handler of typed) {
|
|
54
|
-
try {
|
|
55
|
-
handler(payload);
|
|
56
|
-
called = true;
|
|
57
|
-
} catch {
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
for (const handler of this.#wildcardListeners) {
|
|
62
|
-
try {
|
|
63
|
-
handler(event, payload);
|
|
64
|
-
called = true;
|
|
65
|
-
} catch {
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
return called;
|
|
69
|
-
}
|
|
70
|
-
// ── Introspection ─────────────────────────────────────────────────
|
|
71
|
-
/**
|
|
72
|
-
* Return `true` when at least one listener is registered for `event`.
|
|
73
|
-
*/
|
|
74
|
-
hasListeners(event) {
|
|
75
|
-
return (this.#listeners.get(event)?.size ?? 0) > 0 || this.#wildcardListeners.size > 0;
|
|
76
|
-
}
|
|
77
|
-
/**
|
|
78
|
-
* Return the number of typed listeners for a specific event.
|
|
79
|
-
*/
|
|
80
|
-
listenerCount(event) {
|
|
81
|
-
return this.#listeners.get(event)?.size ?? 0;
|
|
82
|
-
}
|
|
83
|
-
/**
|
|
84
|
-
* Remove all listeners.
|
|
85
|
-
*/
|
|
86
|
-
clear() {
|
|
87
|
-
this.#listeners.clear();
|
|
88
|
-
this.#wildcardListeners.clear();
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
export { EventEmitter };
|