@lunora/db 1.0.0-alpha.3 → 1.0.0-alpha.30
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 +6 -0
- package/README.md +12 -0
- package/dist/collections/index.d.mts +5 -0
- package/dist/collections/index.d.ts +5 -0
- package/dist/collections/index.mjs +1 -0
- package/dist/index.d.mts +75 -135
- package/dist/index.d.ts +75 -135
- package/dist/index.mjs +1 -6
- package/dist/mutators/index.d.mts +5 -0
- package/dist/mutators/index.d.ts +5 -0
- package/dist/mutators/index.mjs +1 -0
- package/dist/packem_shared/CHECKPOINT_FALLBACK_MS-CtPxAU9J.mjs +1 -0
- package/dist/packem_shared/DIRECT_TRANSACTION_METADATA_KEY-Cvm6vs5S.mjs +1 -0
- package/dist/packem_shared/OUTBOX_MUTATION_FN_NAME-CebgkYw2.mjs +1 -0
- package/dist/packem_shared/applyPlanToCollections-C29s6OoX.mjs +1 -0
- package/dist/packem_shared/collection-options.d-C03Rjjxn.d.mts +337 -0
- package/dist/packem_shared/collection-options.d-C03Rjjxn.d.ts +337 -0
- package/dist/packem_shared/define-collections.d-Ds-5C0M9.d.ts +166 -0
- package/dist/packem_shared/define-collections.d-Y9AaX0yt.d.mts +166 -0
- package/dist/packem_shared/define-mutators.d-DqkWcDks.d.ts +148 -0
- package/dist/packem_shared/define-mutators.d-tPb72T4I.d.mts +148 -0
- package/dist/packem_shared/defineCollections-CnFdW1Ff.mjs +1 -0
- package/package.json +11 -2
- package/dist/packem_shared/createOptimisticOnlineDetector-CRulWqZ7.mjs +0 -65
- package/dist/packem_shared/defineCollections-BAmslSrF.mjs +0 -109
package/LICENSE.md
CHANGED
|
@@ -103,3 +103,9 @@ Unless required by applicable law or agreed to in writing, software distributed
|
|
|
103
103
|
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
|
|
104
104
|
CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
|
105
105
|
specific language governing permissions and limitations under the License.
|
|
106
|
+
|
|
107
|
+
<!-- DEPENDENCIES -->
|
|
108
|
+
<!-- /DEPENDENCIES -->
|
|
109
|
+
|
|
110
|
+
<!-- TYPE_DEPENDENCIES -->
|
|
111
|
+
<!-- /TYPE_DEPENDENCIES -->
|
package/README.md
CHANGED
|
@@ -85,6 +85,18 @@ export const createCollections = (client: LunoraClient) =>
|
|
|
85
85
|
|
|
86
86
|
> `vis generate lunora-collections` scaffolds this from your `schema.ts` + functions.
|
|
87
87
|
|
|
88
|
+
### Local-first sync engine
|
|
89
|
+
|
|
90
|
+
Beyond whole-table collections, the `@lunora/db/collections` and
|
|
91
|
+
`@lunora/db/mutators` subpaths expose the local-first sync engine:
|
|
92
|
+
`lunoraCollectionOptions({ shape })` syncs a **partial replication shape** (only
|
|
93
|
+
the rows a client needs, scoped by a server-resolved predicate) over the poke
|
|
94
|
+
diff protocol, and `defineMutator` + `bindMutators` run **optimistic custom
|
|
95
|
+
mutators** (a local body first, a server-authoritative impl second, rebased on
|
|
96
|
+
every sync tick). The framework adapters add a `useMutator` / `createMutator` /
|
|
97
|
+
`mutator` hook over a bound handle. See the
|
|
98
|
+
**[local-first guide](https://lunora.sh/docs/concepts/local-first)**.
|
|
99
|
+
|
|
88
100
|
> This README covers the basics. For the full API, options, and guides, see the **[documentation](https://lunora.sh/docs/addons/db)**.
|
|
89
101
|
|
|
90
102
|
## Related
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { type C as CheckpointRegistry, type L as LunoraCollectionConfig, type a as LunoraCollectionOptions, c as createCheckpointRegistry, l as lunoraCollectionOptions } from "../packem_shared/collection-options.d-C03Rjjxn.mjs";
|
|
2
|
+
export { type C as CollectionDef, type I as InsertBinding, type L as LunoraDb, d as defineCollections } from "../packem_shared/define-collections.d-Y9AaX0yt.mjs";
|
|
3
|
+
import '@lunora/client';
|
|
4
|
+
import '@tanstack/db';
|
|
5
|
+
import '@tanstack/offline-transactions';
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { type C as CheckpointRegistry, type L as LunoraCollectionConfig, type a as LunoraCollectionOptions, c as createCheckpointRegistry, l as lunoraCollectionOptions } from "../packem_shared/collection-options.d-C03Rjjxn.js";
|
|
2
|
+
export { type C as CollectionDef, type I as InsertBinding, type L as LunoraDb, d as defineCollections } from "../packem_shared/define-collections.d-Ds-5C0M9.js";
|
|
3
|
+
import '@lunora/client';
|
|
4
|
+
import '@tanstack/db';
|
|
5
|
+
import '@tanstack/offline-transactions';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createCheckpointRegistry as t,lunoraCollectionOptions as r}from"../packem_shared/CHECKPOINT_FALLBACK_MS-CtPxAU9J.mjs";import{defineCollections as n}from"../packem_shared/defineCollections-CnFdW1Ff.mjs";export{t as createCheckpointRegistry,n as defineCollections,r as lunoraCollectionOptions};
|
package/dist/index.d.mts
CHANGED
|
@@ -1,142 +1,82 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
type
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
interface
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
} | {
|
|
16
|
-
key: string;
|
|
17
|
-
type: "delete";
|
|
18
|
-
}) => void;
|
|
1
|
+
import { Collection } from '@tanstack/db';
|
|
2
|
+
import { R as Row } from "./packem_shared/collection-options.d-C03Rjjxn.mjs";
|
|
3
|
+
export { b as CHECKPOINT_FALLBACK_MS, type d as CheckpointFallbackEvent, type C as CheckpointRegistry, type e as CheckpointRegistryOptions, type f as CheckpointRegistryStats, type g as CheckpointWatermark, type E as ExecutorOutboxSinkOptions, type L as LunoraCollectionConfig, type a as LunoraCollectionOptions, O as OUTBOX_MUTATION_FN_NAME, type h as OutboxExecutor, type i as OutboxMutationMetadata, type S as SyncWriter, c as createCheckpointRegistry, j as createExecutorOutboxSink, k as createOptimisticOnlineDetector, m as getShardCheckpoints, l as lunoraCollectionOptions, n as makeDiffEmit, r as releaseShardCheckpoints, o as runOutboxMutation, s as shardCheckpointStats, t as toMap } from "./packem_shared/collection-options.d-C03Rjjxn.mjs";
|
|
4
|
+
export { type C as CollectionDef, type D as DefineCollectionsOptions, type I as InsertBinding, type L as LunoraDb, type W as WriteRejectedEvent, d as defineCollections } from "./packem_shared/define-collections.d-Y9AaX0yt.mjs";
|
|
5
|
+
export { type B as BindMutatorsContext, type a as BoundMutators, type C as ClientMutatorContext, type b as ClientMutatorDef, D as DIRECT_TRANSACTION_METADATA_KEY, type M as MutatorReference, c as bindMutators, d as defineMutator } from "./packem_shared/define-mutators.d-tPb72T4I.mjs";
|
|
6
|
+
import '@lunora/client';
|
|
7
|
+
import '@tanstack/offline-transactions';
|
|
8
|
+
/** One row to insert. `_id` may be pre-minted client-side so the optimistic row keys match the persisted one. */
|
|
9
|
+
interface PlanInsert {
|
|
10
|
+
/** Row body. Include `_id` to key the row yourself (the server honors it as the `clientId`). */
|
|
11
|
+
row: Record<string, unknown> & {
|
|
12
|
+
_id?: string;
|
|
13
|
+
};
|
|
14
|
+
table: string;
|
|
19
15
|
}
|
|
20
|
-
/**
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
* scope change never churns the synced view out from under a pending optimistic
|
|
26
|
-
* row. The last-synced base is tracked in `synced`.
|
|
27
|
-
*
|
|
28
|
-
* Change detection compares rows by `JSON.stringify`, which is key-order
|
|
29
|
-
* sensitive — safe here because `synced` only ever holds server snapshots, whose
|
|
30
|
-
* column order is stable across reconnects (same query projection). A sync source
|
|
31
|
-
* with unstable key ordering would need a structural compare instead.
|
|
32
|
-
*/
|
|
33
|
-
declare const makeDiffEmit: <T extends object>(synced: Map<string, T>, writer: SyncWriter<T>) => (next: Map<string, T>) => void;
|
|
34
|
-
/**
|
|
35
|
-
* Run a Lunora mutation under the outbox's retry policy.
|
|
36
|
-
*
|
|
37
|
-
* The retryable/permanent split keys on whether the failure carries a server
|
|
38
|
-
* application error `code` (set by `@lunora/client`'s rpc when the server returns
|
|
39
|
-
* a `{ error: { code, … } }` envelope — validation, conflict, etc.). A coded
|
|
40
|
-
* error is a definite verdict: surface it as a `NonRetriableError` so the executor
|
|
41
|
-
* stops and TanStack DB rolls the optimistic insert back. Everything without a
|
|
42
|
-
* code is transient — a `fetch` network failure (`TypeError`) or an HTTP/infra
|
|
43
|
-
* blip the rpc surfaces as a code-less `Error` (a 5xx gateway page, a non-JSON
|
|
44
|
-
* body) — so it's rethrown as-is and the durable outbox replays it. Keying on
|
|
45
|
-
* `error instanceof TypeError` alone would wrongly drop the latter.
|
|
46
|
-
*/
|
|
47
|
-
declare const runOutboxMutation: (mutate: () => Promise<unknown>) => Promise<void>;
|
|
48
|
-
/**
|
|
49
|
-
* An "always attempt" online detector. We deliberately don't trust
|
|
50
|
-
* `navigator.onLine`: some environments (and Playwright's `setOffline` under
|
|
51
|
-
* Firefox) leave it stuck, which would freeze the outbox. Instead the executor
|
|
52
|
-
* always tries the send and {@link runOutboxMutation}'s transient-error retry
|
|
53
|
-
* handles real offline; the periodic tick nudges the executor to drain the outbox
|
|
54
|
-
* so a queued write replays promptly once connectivity returns.
|
|
55
|
-
*
|
|
56
|
-
* `isOnline` is therefore intentionally always `true` — it gates the executor's
|
|
57
|
-
* attempts, not a UI signal. A consumer that wants to show real connectivity
|
|
58
|
-
* should read `navigator.onLine` itself, separately from this detector.
|
|
59
|
-
*/
|
|
60
|
-
declare const createOptimisticOnlineDetector: () => OnlineDetector;
|
|
61
|
-
/** Element type of an array (the row type a `list` query returns). */
|
|
62
|
-
type Element<T> = T extends ReadonlyArray<infer E> ? E : never;
|
|
63
|
-
/** `true` for the `any` type, `false` otherwise. */
|
|
64
|
-
type IsAny<T> = 0 extends 1 & T ? true : false;
|
|
65
|
-
/**
|
|
66
|
-
* The row type a `list` query syncs. For `TList = any` (the heterogeneous-map
|
|
67
|
-
* constraint) it resolves to the permissive {@link Row}, not `never` — otherwise
|
|
68
|
-
* the constraint would force every `optimistic` to return `never`. For a concrete
|
|
69
|
-
* `FunctionReference` it's the element type of the query's array return.
|
|
70
|
-
*/
|
|
71
|
-
type RowOfList<TList> = IsAny<TList> extends true ? Row : TList extends FunctionReference<infer _K, infer _A, infer R> ? Element<R> & Row : never;
|
|
72
|
-
/** Maps a write through the durable outbox: optimistic insert + a retried mutation. */
|
|
73
|
-
interface InsertBinding<TRow extends Row, TInput> {
|
|
74
|
-
/** The Lunora mutation that persists the row. */
|
|
75
|
-
mutation: FunctionReference;
|
|
76
|
-
/** Build the optimistic row to insert from the action input + the generated client id. */
|
|
77
|
-
optimistic: (input: TInput, id: string) => TRow;
|
|
78
|
-
/** Build the mutation args from the persisted optimistic row (forward `_id` as the `clientId`). */
|
|
79
|
-
toArgs: (row: TRow) => Record<string, unknown>;
|
|
16
|
+
/** One row to patch, by id. */
|
|
17
|
+
interface PlanPatch {
|
|
18
|
+
fields: Record<string, unknown>;
|
|
19
|
+
id: string;
|
|
20
|
+
table: string;
|
|
80
21
|
}
|
|
81
|
-
/**
|
|
82
|
-
interface
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
/** Optional write binding — present iff this collection is written through the outbox. */
|
|
86
|
-
insert?: InsertBinding<RowOfList<TList>, TInput>;
|
|
87
|
-
/** The Lunora query that lists the rows (the sync source). */
|
|
88
|
-
list: TList;
|
|
89
|
-
/**
|
|
90
|
-
* Notified when the underlying `list` subscription errors (e.g. the server
|
|
91
|
-
* rejects it). Without this the error would be swallowed and the collection
|
|
92
|
-
* could hang in `loading`; the binding always moves the collection out of
|
|
93
|
-
* `loading` on error, and forwards the error here if supplied.
|
|
94
|
-
*/
|
|
95
|
-
onError?: (error: SubscriptionError) => void;
|
|
96
|
-
/** A field that scopes the list (e.g. a shard key); makes the collection re-pointable via `scope`. */
|
|
97
|
-
scopeBy?: string;
|
|
22
|
+
/** One row to delete, by id. */
|
|
23
|
+
interface PlanDelete {
|
|
24
|
+
id: string;
|
|
25
|
+
table: string;
|
|
98
26
|
}
|
|
99
|
-
type AnyDef = CollectionDef<any, any>;
|
|
100
27
|
/**
|
|
101
|
-
*
|
|
102
|
-
*
|
|
103
|
-
*
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
28
|
+
* A change plan: what a mutator intends to write.
|
|
29
|
+
*
|
|
30
|
+
* Applied in a fixed order — **deletes, then patches, then inserts** — by both
|
|
31
|
+
* appliers. The order is part of the contract, not an implementation detail: a plan
|
|
32
|
+
* that deletes a row and inserts its replacement under the same natural key only
|
|
33
|
+
* behaves the same on both sides if both sides agree which happens first.
|
|
34
|
+
*/
|
|
35
|
+
interface ChangePlan {
|
|
36
|
+
deletes?: ReadonlyArray<PlanDelete>;
|
|
37
|
+
inserts?: ReadonlyArray<PlanInsert>;
|
|
38
|
+
patches?: ReadonlyArray<PlanPatch>;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* The `ctx.db` methods {@link applyPlanToDb} needs — structural, so any writer
|
|
42
|
+
* satisfies it.
|
|
43
|
+
*
|
|
44
|
+
* The `never` parameter positions are deliberate, not laziness. `ctx.db.delete` is
|
|
45
|
+
* `<T extends string>(id: Id<T>) => …` over the **branded** `Id<T>`, and under
|
|
46
|
+
* `strictFunctionTypes` a parameter is contravariant — so declaring `id: string` here
|
|
47
|
+
* would make the real `ctx.db` un-assignable to `PlanWriter` (`string` is not
|
|
48
|
+
* assignable to `string & { __table }`), and every caller would need a cast at the
|
|
49
|
+
* call site instead. `never` accepts any branded id, which keeps `applyPlanToDb(ctx.db,
|
|
50
|
+
* plan)` cast-free for the caller and confines the two `as never` casts to this module.
|
|
51
|
+
*
|
|
52
|
+
* The trade-off is real: argument checking inside `applyPlanToDb` is erased, so a plan
|
|
53
|
+
* naming a table the schema doesn't have is a runtime error. Use `ctx.db.asId(table,
|
|
54
|
+
* id)` when building the plan to catch a malformed id at the boundary.
|
|
55
|
+
*/
|
|
56
|
+
interface PlanWriter {
|
|
57
|
+
delete: (id: never) => Promise<void>;
|
|
58
|
+
insert: (tableName: never, document: Record<string, unknown>, options?: {
|
|
59
|
+
clientId?: string;
|
|
60
|
+
}) => Promise<unknown>;
|
|
61
|
+
patch: (id: never, patch: Record<string, unknown>) => Promise<void>;
|
|
129
62
|
}
|
|
130
63
|
/**
|
|
131
|
-
*
|
|
132
|
-
*
|
|
133
|
-
*
|
|
134
|
-
*
|
|
135
|
-
*
|
|
136
|
-
*
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
64
|
+
* Apply `plan` to a map of TanStack collections — the client (optimistic) half.
|
|
65
|
+
*
|
|
66
|
+
* A plan naming a table with no wired collection is **skipped, not an error**: an app
|
|
67
|
+
* legitimately syncs a subset of the tables its mutators write (a server-only audit
|
|
68
|
+
* row has no client collection), and throwing would make the optimistic body fail on
|
|
69
|
+
* a write the server handles fine.
|
|
70
|
+
*/
|
|
71
|
+
declare const applyPlanToCollections: (collections: Record<string, Collection<Row, string>>, plan: ChangePlan) => void;
|
|
72
|
+
/**
|
|
73
|
+
* Apply `plan` to a `ctx.db` writer — the server (authoritative) half.
|
|
74
|
+
*
|
|
75
|
+
* Sequential by design: the shard's SQLite is single-threaded and a mutation runs
|
|
76
|
+
* inside one BEGIN/COMMIT span, so ordering is observable and a mid-plan failure
|
|
77
|
+
* rolls the whole plan back. An insert carrying an `_id` forwards it as `clientId`,
|
|
78
|
+
* which is how a client-minted key becomes the persisted primary key.
|
|
79
|
+
*/
|
|
80
|
+
declare const applyPlanToDb: (db: PlanWriter, plan: ChangePlan) => Promise<void>;
|
|
141
81
|
declare const VERSION = "0.0.0";
|
|
142
|
-
export { type
|
|
82
|
+
export { type ChangePlan, type PlanDelete, type PlanInsert, type PlanPatch, type PlanWriter, type Row, VERSION, applyPlanToCollections, applyPlanToDb };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,142 +1,82 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
type
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
interface
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
} | {
|
|
16
|
-
key: string;
|
|
17
|
-
type: "delete";
|
|
18
|
-
}) => void;
|
|
1
|
+
import { Collection } from '@tanstack/db';
|
|
2
|
+
import { R as Row } from "./packem_shared/collection-options.d-C03Rjjxn.js";
|
|
3
|
+
export { b as CHECKPOINT_FALLBACK_MS, type d as CheckpointFallbackEvent, type C as CheckpointRegistry, type e as CheckpointRegistryOptions, type f as CheckpointRegistryStats, type g as CheckpointWatermark, type E as ExecutorOutboxSinkOptions, type L as LunoraCollectionConfig, type a as LunoraCollectionOptions, O as OUTBOX_MUTATION_FN_NAME, type h as OutboxExecutor, type i as OutboxMutationMetadata, type S as SyncWriter, c as createCheckpointRegistry, j as createExecutorOutboxSink, k as createOptimisticOnlineDetector, m as getShardCheckpoints, l as lunoraCollectionOptions, n as makeDiffEmit, r as releaseShardCheckpoints, o as runOutboxMutation, s as shardCheckpointStats, t as toMap } from "./packem_shared/collection-options.d-C03Rjjxn.js";
|
|
4
|
+
export { type C as CollectionDef, type D as DefineCollectionsOptions, type I as InsertBinding, type L as LunoraDb, type W as WriteRejectedEvent, d as defineCollections } from "./packem_shared/define-collections.d-Ds-5C0M9.js";
|
|
5
|
+
export { type B as BindMutatorsContext, type a as BoundMutators, type C as ClientMutatorContext, type b as ClientMutatorDef, D as DIRECT_TRANSACTION_METADATA_KEY, type M as MutatorReference, c as bindMutators, d as defineMutator } from "./packem_shared/define-mutators.d-DqkWcDks.js";
|
|
6
|
+
import '@lunora/client';
|
|
7
|
+
import '@tanstack/offline-transactions';
|
|
8
|
+
/** One row to insert. `_id` may be pre-minted client-side so the optimistic row keys match the persisted one. */
|
|
9
|
+
interface PlanInsert {
|
|
10
|
+
/** Row body. Include `_id` to key the row yourself (the server honors it as the `clientId`). */
|
|
11
|
+
row: Record<string, unknown> & {
|
|
12
|
+
_id?: string;
|
|
13
|
+
};
|
|
14
|
+
table: string;
|
|
19
15
|
}
|
|
20
|
-
/**
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
* scope change never churns the synced view out from under a pending optimistic
|
|
26
|
-
* row. The last-synced base is tracked in `synced`.
|
|
27
|
-
*
|
|
28
|
-
* Change detection compares rows by `JSON.stringify`, which is key-order
|
|
29
|
-
* sensitive — safe here because `synced` only ever holds server snapshots, whose
|
|
30
|
-
* column order is stable across reconnects (same query projection). A sync source
|
|
31
|
-
* with unstable key ordering would need a structural compare instead.
|
|
32
|
-
*/
|
|
33
|
-
declare const makeDiffEmit: <T extends object>(synced: Map<string, T>, writer: SyncWriter<T>) => (next: Map<string, T>) => void;
|
|
34
|
-
/**
|
|
35
|
-
* Run a Lunora mutation under the outbox's retry policy.
|
|
36
|
-
*
|
|
37
|
-
* The retryable/permanent split keys on whether the failure carries a server
|
|
38
|
-
* application error `code` (set by `@lunora/client`'s rpc when the server returns
|
|
39
|
-
* a `{ error: { code, … } }` envelope — validation, conflict, etc.). A coded
|
|
40
|
-
* error is a definite verdict: surface it as a `NonRetriableError` so the executor
|
|
41
|
-
* stops and TanStack DB rolls the optimistic insert back. Everything without a
|
|
42
|
-
* code is transient — a `fetch` network failure (`TypeError`) or an HTTP/infra
|
|
43
|
-
* blip the rpc surfaces as a code-less `Error` (a 5xx gateway page, a non-JSON
|
|
44
|
-
* body) — so it's rethrown as-is and the durable outbox replays it. Keying on
|
|
45
|
-
* `error instanceof TypeError` alone would wrongly drop the latter.
|
|
46
|
-
*/
|
|
47
|
-
declare const runOutboxMutation: (mutate: () => Promise<unknown>) => Promise<void>;
|
|
48
|
-
/**
|
|
49
|
-
* An "always attempt" online detector. We deliberately don't trust
|
|
50
|
-
* `navigator.onLine`: some environments (and Playwright's `setOffline` under
|
|
51
|
-
* Firefox) leave it stuck, which would freeze the outbox. Instead the executor
|
|
52
|
-
* always tries the send and {@link runOutboxMutation}'s transient-error retry
|
|
53
|
-
* handles real offline; the periodic tick nudges the executor to drain the outbox
|
|
54
|
-
* so a queued write replays promptly once connectivity returns.
|
|
55
|
-
*
|
|
56
|
-
* `isOnline` is therefore intentionally always `true` — it gates the executor's
|
|
57
|
-
* attempts, not a UI signal. A consumer that wants to show real connectivity
|
|
58
|
-
* should read `navigator.onLine` itself, separately from this detector.
|
|
59
|
-
*/
|
|
60
|
-
declare const createOptimisticOnlineDetector: () => OnlineDetector;
|
|
61
|
-
/** Element type of an array (the row type a `list` query returns). */
|
|
62
|
-
type Element<T> = T extends ReadonlyArray<infer E> ? E : never;
|
|
63
|
-
/** `true` for the `any` type, `false` otherwise. */
|
|
64
|
-
type IsAny<T> = 0 extends 1 & T ? true : false;
|
|
65
|
-
/**
|
|
66
|
-
* The row type a `list` query syncs. For `TList = any` (the heterogeneous-map
|
|
67
|
-
* constraint) it resolves to the permissive {@link Row}, not `never` — otherwise
|
|
68
|
-
* the constraint would force every `optimistic` to return `never`. For a concrete
|
|
69
|
-
* `FunctionReference` it's the element type of the query's array return.
|
|
70
|
-
*/
|
|
71
|
-
type RowOfList<TList> = IsAny<TList> extends true ? Row : TList extends FunctionReference<infer _K, infer _A, infer R> ? Element<R> & Row : never;
|
|
72
|
-
/** Maps a write through the durable outbox: optimistic insert + a retried mutation. */
|
|
73
|
-
interface InsertBinding<TRow extends Row, TInput> {
|
|
74
|
-
/** The Lunora mutation that persists the row. */
|
|
75
|
-
mutation: FunctionReference;
|
|
76
|
-
/** Build the optimistic row to insert from the action input + the generated client id. */
|
|
77
|
-
optimistic: (input: TInput, id: string) => TRow;
|
|
78
|
-
/** Build the mutation args from the persisted optimistic row (forward `_id` as the `clientId`). */
|
|
79
|
-
toArgs: (row: TRow) => Record<string, unknown>;
|
|
16
|
+
/** One row to patch, by id. */
|
|
17
|
+
interface PlanPatch {
|
|
18
|
+
fields: Record<string, unknown>;
|
|
19
|
+
id: string;
|
|
20
|
+
table: string;
|
|
80
21
|
}
|
|
81
|
-
/**
|
|
82
|
-
interface
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
/** Optional write binding — present iff this collection is written through the outbox. */
|
|
86
|
-
insert?: InsertBinding<RowOfList<TList>, TInput>;
|
|
87
|
-
/** The Lunora query that lists the rows (the sync source). */
|
|
88
|
-
list: TList;
|
|
89
|
-
/**
|
|
90
|
-
* Notified when the underlying `list` subscription errors (e.g. the server
|
|
91
|
-
* rejects it). Without this the error would be swallowed and the collection
|
|
92
|
-
* could hang in `loading`; the binding always moves the collection out of
|
|
93
|
-
* `loading` on error, and forwards the error here if supplied.
|
|
94
|
-
*/
|
|
95
|
-
onError?: (error: SubscriptionError) => void;
|
|
96
|
-
/** A field that scopes the list (e.g. a shard key); makes the collection re-pointable via `scope`. */
|
|
97
|
-
scopeBy?: string;
|
|
22
|
+
/** One row to delete, by id. */
|
|
23
|
+
interface PlanDelete {
|
|
24
|
+
id: string;
|
|
25
|
+
table: string;
|
|
98
26
|
}
|
|
99
|
-
type AnyDef = CollectionDef<any, any>;
|
|
100
27
|
/**
|
|
101
|
-
*
|
|
102
|
-
*
|
|
103
|
-
*
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
28
|
+
* A change plan: what a mutator intends to write.
|
|
29
|
+
*
|
|
30
|
+
* Applied in a fixed order — **deletes, then patches, then inserts** — by both
|
|
31
|
+
* appliers. The order is part of the contract, not an implementation detail: a plan
|
|
32
|
+
* that deletes a row and inserts its replacement under the same natural key only
|
|
33
|
+
* behaves the same on both sides if both sides agree which happens first.
|
|
34
|
+
*/
|
|
35
|
+
interface ChangePlan {
|
|
36
|
+
deletes?: ReadonlyArray<PlanDelete>;
|
|
37
|
+
inserts?: ReadonlyArray<PlanInsert>;
|
|
38
|
+
patches?: ReadonlyArray<PlanPatch>;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* The `ctx.db` methods {@link applyPlanToDb} needs — structural, so any writer
|
|
42
|
+
* satisfies it.
|
|
43
|
+
*
|
|
44
|
+
* The `never` parameter positions are deliberate, not laziness. `ctx.db.delete` is
|
|
45
|
+
* `<T extends string>(id: Id<T>) => …` over the **branded** `Id<T>`, and under
|
|
46
|
+
* `strictFunctionTypes` a parameter is contravariant — so declaring `id: string` here
|
|
47
|
+
* would make the real `ctx.db` un-assignable to `PlanWriter` (`string` is not
|
|
48
|
+
* assignable to `string & { __table }`), and every caller would need a cast at the
|
|
49
|
+
* call site instead. `never` accepts any branded id, which keeps `applyPlanToDb(ctx.db,
|
|
50
|
+
* plan)` cast-free for the caller and confines the two `as never` casts to this module.
|
|
51
|
+
*
|
|
52
|
+
* The trade-off is real: argument checking inside `applyPlanToDb` is erased, so a plan
|
|
53
|
+
* naming a table the schema doesn't have is a runtime error. Use `ctx.db.asId(table,
|
|
54
|
+
* id)` when building the plan to catch a malformed id at the boundary.
|
|
55
|
+
*/
|
|
56
|
+
interface PlanWriter {
|
|
57
|
+
delete: (id: never) => Promise<void>;
|
|
58
|
+
insert: (tableName: never, document: Record<string, unknown>, options?: {
|
|
59
|
+
clientId?: string;
|
|
60
|
+
}) => Promise<unknown>;
|
|
61
|
+
patch: (id: never, patch: Record<string, unknown>) => Promise<void>;
|
|
129
62
|
}
|
|
130
63
|
/**
|
|
131
|
-
*
|
|
132
|
-
*
|
|
133
|
-
*
|
|
134
|
-
*
|
|
135
|
-
*
|
|
136
|
-
*
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
64
|
+
* Apply `plan` to a map of TanStack collections — the client (optimistic) half.
|
|
65
|
+
*
|
|
66
|
+
* A plan naming a table with no wired collection is **skipped, not an error**: an app
|
|
67
|
+
* legitimately syncs a subset of the tables its mutators write (a server-only audit
|
|
68
|
+
* row has no client collection), and throwing would make the optimistic body fail on
|
|
69
|
+
* a write the server handles fine.
|
|
70
|
+
*/
|
|
71
|
+
declare const applyPlanToCollections: (collections: Record<string, Collection<Row, string>>, plan: ChangePlan) => void;
|
|
72
|
+
/**
|
|
73
|
+
* Apply `plan` to a `ctx.db` writer — the server (authoritative) half.
|
|
74
|
+
*
|
|
75
|
+
* Sequential by design: the shard's SQLite is single-threaded and a mutation runs
|
|
76
|
+
* inside one BEGIN/COMMIT span, so ordering is observable and a mid-plan failure
|
|
77
|
+
* rolls the whole plan back. An insert carrying an `_id` forwards it as `clientId`,
|
|
78
|
+
* which is how a client-minted key becomes the persisted primary key.
|
|
79
|
+
*/
|
|
80
|
+
declare const applyPlanToDb: (db: PlanWriter, plan: ChangePlan) => Promise<void>;
|
|
141
81
|
declare const VERSION = "0.0.0";
|
|
142
|
-
export { type
|
|
82
|
+
export { type ChangePlan, type PlanDelete, type PlanInsert, type PlanPatch, type PlanWriter, type Row, VERSION, applyPlanToCollections, applyPlanToDb };
|
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1 @@
|
|
|
1
|
-
|
|
2
|
-
export { createOptimisticOnlineDetector, makeDiffEmit, runOutboxMutation, toMap } from './packem_shared/createOptimisticOnlineDetector-CRulWqZ7.mjs';
|
|
3
|
-
|
|
4
|
-
const VERSION = "0.0.0";
|
|
5
|
-
|
|
6
|
-
export { VERSION };
|
|
1
|
+
import{applyPlanToCollections as r,applyPlanToDb as i}from"./packem_shared/applyPlanToCollections-C29s6OoX.mjs";import{CHECKPOINT_FALLBACK_MS as a,createCheckpointRegistry as p,getShardCheckpoints as c,lunoraCollectionOptions as l,releaseShardCheckpoints as s,shardCheckpointStats as C}from"./packem_shared/CHECKPOINT_FALLBACK_MS-CtPxAU9J.mjs";import{defineCollections as T}from"./packem_shared/defineCollections-CnFdW1Ff.mjs";import{DIRECT_TRANSACTION_METADATA_KEY as x,bindMutators as A,defineMutator as m}from"./packem_shared/DIRECT_TRANSACTION_METADATA_KEY-Cvm6vs5S.mjs";import{OUTBOX_MUTATION_FN_NAME as E,createExecutorOutboxSink as M,createOptimisticOnlineDetector as _,makeDiffEmit as h,runOutboxMutation as N,toMap as S}from"./packem_shared/OUTBOX_MUTATION_FN_NAME-CebgkYw2.mjs";const t="0.0.0";export{a as CHECKPOINT_FALLBACK_MS,x as DIRECT_TRANSACTION_METADATA_KEY,E as OUTBOX_MUTATION_FN_NAME,t as VERSION,r as applyPlanToCollections,i as applyPlanToDb,A as bindMutators,p as createCheckpointRegistry,M as createExecutorOutboxSink,_ as createOptimisticOnlineDetector,T as defineCollections,m as defineMutator,c as getShardCheckpoints,l as lunoraCollectionOptions,h as makeDiffEmit,s as releaseShardCheckpoints,N as runOutboxMutation,C as shardCheckpointStats,S as toMap};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { type B as BindMutatorsContext, type a as BoundMutators, type C as ClientMutatorContext, type b as ClientMutatorDef, c as bindMutators, d as defineMutator } from "../packem_shared/define-mutators.d-tPb72T4I.mjs";
|
|
2
|
+
import '@lunora/client';
|
|
3
|
+
import '@tanstack/db';
|
|
4
|
+
import "../packem_shared/collection-options.d-C03Rjjxn.mjs";
|
|
5
|
+
import '@tanstack/offline-transactions';
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { type B as BindMutatorsContext, type a as BoundMutators, type C as ClientMutatorContext, type b as ClientMutatorDef, c as bindMutators, d as defineMutator } from "../packem_shared/define-mutators.d-DqkWcDks.js";
|
|
2
|
+
import '@lunora/client';
|
|
3
|
+
import '@tanstack/db';
|
|
4
|
+
import "../packem_shared/collection-options.d-C03Rjjxn.js";
|
|
5
|
+
import '@tanstack/offline-transactions';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{bindMutators as r,defineMutator as e}from"../packem_shared/DIRECT_TRANSACTION_METADATA_KEY-Cvm6vs5S.mjs";export{r as bindMutators,e as defineMutator};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as y}from"@lunora/errors";import{BTreeIndex as w}from"@tanstack/db";import{toMap as b,makeDiffEmit as C}from"./OUTBOX_MUTATION_FN_NAME-CebgkYw2.mjs";const v=()=>{let e=Number.NEGATIVE_INFINITY;const a=[];return{advance:n=>{if(!(n<=e)){e=n;for(let o=a.length-1;o>=0;o-=1){const r=a[o];r&&r.threshold<=e&&(r.resolve(),a.splice(o,1))}}},await:n=>n<=e?Promise.resolve():new Promise(o=>{a.push({resolve:o,threshold:n})}),passed:n=>n<=e,waiting:()=>a.length}},M=3e3;let I=!1;const N=e=>{I||(I=!0,console.warn(`[@lunora/db] released an optimistic overlay via the ${String(e.waitedMs)}ms checkpoint fallback: the server confirmed ${e.kind} ${String(e.watermark)} but no sync frame ever echoed it. A dropped shape poke or \`settled\` frame is the usual cause — inspect the subscription rather than raising \`fallbackMs\`. (Reported once per process.)`))},S=(e={})=>{const a=e.fallbackMs??M,n=e.onFallback??N,o=v(),r=v();let s=0;const c=new Set,h=(i,t)=>{for(const d of c)d.kind===i&&d.threshold<=t&&(clearTimeout(d.handle),c.delete(d))},l=(i,t)=>{if(a<=0)return;const d=i==="checkpoint"?o:r;if(d.passed(t))return;for(const u of c)if(u.kind===i&&u.threshold>=t)return;const p={handle:setTimeout(()=>{if(c.delete(p),!d.passed(t)){s+=1,d.advance(t);try{n({kind:i,waitedMs:a,watermark:t})}catch{}}},a),kind:i,threshold:t};c.add(p)};return{acknowledge:({checkpoint:i,mutationId:t})=>{i!==void 0&&l("checkpoint",i),t!==void 0&&l("mutationId",t)},awaitCheckpoint:i=>o.await(i),awaitMutationId:i=>r.await(i),resolve:({checkpoint:i,mutationId:t})=>{i!==void 0&&(o.advance(i),h("checkpoint",i)),t!==void 0&&(r.advance(t),h("mutationId",t))},stats:()=>({fallbacks:s,pendingCheckpointWaiters:o.waiting(),pendingMutationWaiters:r.waiting()})}},m=new WeakMap,T=(e,a,n)=>{let o=m.get(e);o||(o=new Map,m.set(e,o));const r=a??"",s=o.get(r);if(s)return s;const c=S(n);return o.set(r,c),c},g=new WeakSet,E=e=>{g.add(e)},R=e=>g.has(e),x=e=>{const a=m.get(e);if(a){for(const n of a.values())n.resolve({checkpoint:Number.POSITIVE_INFINITY,mutationId:Number.POSITIVE_INFINITY});m.delete(e)}},F=e=>{const a=m.get(e),n={};if(a)for(const[o,r]of a)n[o]=r.stats();return n},O=e=>{if(e.list===void 0==(e.shape===void 0))throw new y("INTERNAL","lunoraCollectionOptions: pass exactly one of `list` or `shape`");const a=e.getKey??(t=>t._id),n=e.checkpoints??T(e.client,e.shape?.shardKey??e.shardKey);E(n);const o=new Map;let r,s,c,h;const l=(t,d)=>{const p=k=>{r?.(b(k,a)),d?.(),e.shape===void 0&&n.resolve({mutationId:e.client.confirmedMutationWatermark(e.shardKey)})},u=k=>c?.(k),f=k=>{n.resolve(k)};return e.shape!==void 0?e.client.subscribeShape({args:t,name:e.shape.name},p,{onCheckpoint:f,onError:u,shardKey:e.shape.shardKey}):e.client.subscribe(e.list,t,p,{onCheckpoint:f,onError:u,shardKey:e.shardKey})},i={autoIndex:"eager",defaultIndexType:w,getKey:a,id:e.id??e.list?.__lunoraRef??`shape:${e.shape?.name??""}`,...e.load==="eager"?{startSync:!0}:{},sync:{sync:t=>(r=C(o,t),c=d=>{t.markReady(),e.onError?.(d)},e.scopeBy===void 0?s=l(e.shape?.args??{},()=>{t.markReady()}):(t.markReady(),h!==void 0&&(s=l(h,void 0))),()=>{r=void 0,c=void 0,s?.(),s=void 0,o.clear()})}};return{checkpoints:n,config:i,scope:t=>{e.scopeBy!==void 0&&(h=t,s?.(),s=void 0,r?.(new Map),t!==void 0&&r!==void 0&&(s=l(t,void 0)))}}};export{M as CHECKPOINT_FALLBACK_MS,S as createCheckpointRegistry,T as getShardCheckpoints,R as hasCheckpointsAttached,O as lunoraCollectionOptions,E as markCheckpointsAttached,x as releaseShardCheckpoints,F as shardCheckpointStats};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as l}from"@lunora/errors";import{createTransaction as y}from"@tanstack/db";import{getShardCheckpoints as R,hasCheckpointsAttached as M}from"./CHECKPOINT_FALLBACK_MS-CtPxAU9J.mjs";import{runOutboxMutation as _}from"./OUTBOX_MUTATION_FN_NAME-CebgkYw2.mjs";const w="__tanstack_db_direct",A="defineMutator: `serverRef` must be a generated mutator reference (api.mutators.*) or a 'namespace:fn' string",g=e=>{const t=typeof e=="string"?e:e?.__lunoraRef;if(typeof t!="string"||t.length===0)throw new l("INTERNAL",A);return t},E=e=>({__lunoraClientMutator:!0,apply:e.apply,serverRef:g(e.serverRef)}),I=(e,t,m)=>{let c=0;const p=()=>(c=Math.max(c,e.confirmedMutationWatermark(t.shardKey))+1,c);let u=Promise.resolve();const d=(r,o)=>{const a=u.then(async()=>{for(let s=0;;s+=1){const n=p(),{applied:i}=await e.callMutator(r,o,{clientSeq:n,shardKey:t.shardKey});if(i)return n;if(s>=32)throw new l("INTERNAL",`lunora: custom mutator "${r}" could not claim a fresh client sequence after ${String(32)} attempts`)}});return u=a.then(()=>{},()=>{}),a},h=()=>{if(t.checkpoints===!1)return;if(t.checkpoints)return t.checkpoints;const r=R(e,t.shardKey);return M(r)?r:void 0},f={};for(const[r,o]of Object.entries(m))f[r]=a=>{const s=y({autoCommit:!0,metadata:{[w]:!0,serverRef:o.serverRef},mutationFn:async()=>{let n=0;await _(async()=>{n=await d(o.serverRef,a)});const i=h();i&&(i.acknowledge({mutationId:n}),await i.awaitMutationId(n))}});return s.mutate(()=>{o.apply({collections:t.collections},a)}),s};return f};export{w as DIRECT_TRANSACTION_METADATA_KEY,I as bindMutators,E as defineMutator};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createCollection as f,safeRandomUUID as m}from"@tanstack/db";import{NonRetriableError as y}from"@tanstack/offline-transactions";const p=1e3,d="__lunora_outbox__",l=new WeakMap,w=()=>f({getKey:e=>e._id,id:`${d}:${m()}`,startSync:!0,sync:{sync:e=>(e.markReady(),()=>{})}}),x=(e,t)=>{l.set(e,t)};let u=!1;const g=(e,t={})=>{const r=t.maxItems??1e3,n=t.mutationFnName??d;return{enqueue(o){if(e.getPendingCount()>=r){const c=new Error("offline outbox is full");return c.code="OFFLINE_QUEUE_OVERFLOW",Promise.reject(c)}const i={args:o.args,clientId:o.clientId,functionPath:o.functionPath,idempotencyKey:o.idempotencyKey,identity:o.identity,mutationId:o.mutationId,shardKey:o.shardKey},a=l.get(e);!a&&!u&&(u=!0,console.warn("[@lunora/db] createExecutorOutboxSink: no outbox carrier is registered for this executor. On a TanStack OfflineExecutor a zero-mutation transaction is silently dropped, so offline writes may be lost — wire the sink to the executor returned by defineCollections()."));const s=e.createOfflineTransaction({autoCommit:!1,idempotencyKey:o.idempotencyKey,metadata:i,mutationFnName:n});return s.mutate(()=>{a?.insert({_id:o.idempotencyKey})}),s.commit?.().catch(()=>{}),Promise.resolve()}}},h=(e,t)=>{const r=new Map;for(const n of e)r.set(t(n),n);return r},E=(e,t)=>r=>{t.begin();const n=new Map;for(const[o,i]of r){const a=JSON.stringify(i);n.set(o,a),e.has(o)?e.get(o)!==a&&t.write({type:"update",value:i}):t.write({type:"insert",value:i})}for(const o of e.keys())r.has(o)||t.write({key:o,type:"delete"});t.commit(),e.clear();for(const[o,i]of n)e.set(o,i)},_=async e=>{try{await e()}catch(t){if(typeof t.code=="string"){const r=new y(t instanceof Error?t.message:String(t));throw r.code=t.code,r}throw t}},I=()=>{const e=new Set;return{dispose:()=>{for(const t of e)clearInterval(t);e.clear()},isOnline:()=>!0,notifyOnline:()=>{},subscribe:t=>{const r=setInterval(t,p);return e.add(r),()=>{clearInterval(r),e.delete(r)}}}};export{d as OUTBOX_MUTATION_FN_NAME,g as createExecutorOutboxSink,I as createOptimisticOnlineDetector,w as createOutboxCarrier,E as makeDiffEmit,x as registerOutboxCarrier,_ as runOutboxMutation,h as toMap};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const l=t=>({deletes:t.deletes??[],inserts:t.inserts??[],patches:t.patches??[]}),r=(t,o)=>{const{deletes:n,inserts:i,patches:a}=l(o);for(const e of n)t[e.table]?.delete(e.id);for(const e of a){const s=t[e.table];s&&s.update(e.id,c=>{Object.assign(c,e.fields)})}for(const e of i){const s=t[e.table];if(s){if(typeof e.row._id!="string")throw new TypeError(`applyPlanToCollections: insert into "${e.table}" needs an "_id" — mint it client-side so the optimistic row keys match the persisted one`);s.insert(e.row)}}},d=async(t,o)=>{const{deletes:n,inserts:i,patches:a}=l(o);for(const e of n)await t.delete(e.id);for(const e of a)await t.patch(e.id,e.fields);for(const e of i){const{_id:s,...c}=e.row;await t.insert(e.table,c,...typeof s=="string"?[{clientId:s}]:[])}};export{r as applyPlanToCollections,d as applyPlanToDb};
|