@econ-v1/app-sdk 7.7.5 → 7.7.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -7
- package/dist/replica/collection.d.ts +11 -3
- package/dist/replica/digest.d.ts +11 -8
- package/dist/replica/ledger.d.ts +30 -7
- package/dist/replica.d.ts +4 -3
- package/dist/replica.js +9 -9
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -180,8 +180,11 @@ const conversations = replica.collection("message.conversations.pull", {
|
|
|
180
180
|
reconcile still reflects the write) and reconciles the whole `list()` 50 ms after
|
|
181
181
|
the last call of a burst, then announces once. `touch(row)` / `remove(key)` record
|
|
182
182
|
one row at a write site. `reset()` starts a new epoch (at most one a minute; a held
|
|
183
|
-
back one is owed and never dropped). `list()` and `get()`
|
|
184
|
-
|
|
183
|
+
back one is owed and never dropped). `list()` and `get()` read the same database and
|
|
184
|
+
must not call the replica. A list's rows are read, checked and hashed before the
|
|
185
|
+
ledger's transaction is opened (`get()` runs inside it). For a list of more than a
|
|
186
|
+
few hundred kilobytes that changes often, hand over the rows that changed
|
|
187
|
+
(`touch` / `remove`, and `get`): a whole list costs its whole size each time.
|
|
185
188
|
- **The pull**: `handle()` answers `{"e","v","s","l","a"?}` and rejects with a
|
|
186
189
|
`ReplicaError` whose message starts with a stable prefix, the same as the Rust
|
|
187
190
|
crate's: `replica_schema_unsupported:`, `replica_request_invalid:`,
|
|
@@ -207,11 +210,12 @@ const conversations = replica.collection("message.conversations.pull", {
|
|
|
207
210
|
`MemoryLedger` keeps the ledger in process memory (every device takes one full copy
|
|
208
211
|
after each start). `CollectionLedger` is the ledger underneath, for apps that drive
|
|
209
212
|
it directly.
|
|
210
|
-
- **Digest**:
|
|
211
|
-
`[value, ord, part]
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
213
|
+
- **Digest**: SHA-256 (the runtime's own, from `node:crypto`, which burger-build maps)
|
|
214
|
+
of the canonical JSON of `[value, ord, part]`, its first 128 bits after `s1.`. It
|
|
215
|
+
never leaves the app's ledger. A ledger an older helper wrote (FNV-1a 64) takes one
|
|
216
|
+
version per row at its first reconcile, and devices read those rows again once. The
|
|
217
|
+
Rust crate's digest is written differently: keep one collection's ledger to one of
|
|
218
|
+
the two helpers, to the other every row would look changed.
|
|
215
219
|
|
|
216
220
|
- **Numbers** are where the bytes can differ from the Rust crate's for the same JSON
|
|
217
221
|
value: JavaScript has only doubles, and a number is written as `JSON.stringify`
|
|
@@ -80,6 +80,13 @@ export declare class CollectionLedger {
|
|
|
80
80
|
* told whether that happened.
|
|
81
81
|
*/
|
|
82
82
|
private withRecord;
|
|
83
|
+
/**
|
|
84
|
+
* `work` done before the transaction, for the part that is long (see
|
|
85
|
+
* `ledger.checkRows`). A failure is thrown from inside one, as it was when the work
|
|
86
|
+
* was done there: what the transaction opens is given back, so a refusal leaves a
|
|
87
|
+
* ledger as the Rust helper's refusal does.
|
|
88
|
+
*/
|
|
89
|
+
private before;
|
|
83
90
|
/** The committed record when a read can stand for a write; `null` sends the caller to the write path. */
|
|
84
91
|
private readSettled;
|
|
85
92
|
/** Creates the ledger's tables if they do not exist. Idempotent; call it on every start. */
|
|
@@ -106,9 +113,10 @@ export declare class CollectionLedger {
|
|
|
106
113
|
head(): Head;
|
|
107
114
|
/**
|
|
108
115
|
* Answers one pull. `load` returns the app's current rows: every row for
|
|
109
|
-
* `null`, else the rows of the given keys (keys with no row are left out).
|
|
110
|
-
*
|
|
111
|
-
*
|
|
116
|
+
* `null`, else the rows of the given keys (keys with no row are left out). Those
|
|
117
|
+
* of keys are read inside the ledger's write transaction, every row before it
|
|
118
|
+
* (inside it when another connection wrote this ledger meanwhile). It must not
|
|
119
|
+
* call this collection again.
|
|
112
120
|
*/
|
|
113
121
|
answer(request: PullRequest, load: (keys: readonly string[] | null) => readonly ReplicaRow[]): Answered;
|
|
114
122
|
/**
|
package/dist/replica/digest.d.ts
CHANGED
|
@@ -7,12 +7,11 @@
|
|
|
7
7
|
* same value (numbers aside: JavaScript has only doubles, see the README), and
|
|
8
8
|
* its UTF-8 length is the value's encoded size.
|
|
9
9
|
*
|
|
10
|
-
* The digest is
|
|
11
|
-
* `[value, ord, part]
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
* Nothing here imports a platform module.
|
|
10
|
+
* The digest is SHA-256 (the runtime's own, first 128 bits) of the canonical JSON
|
|
11
|
+
* of `[value, ord, part]`. A list is hashed on an app's one thread, and Burger's
|
|
12
|
+
* JavaScript has no JIT: a hash or a canonical writer in JavaScript costs a node
|
|
13
|
+
* seconds for a list of a megabyte. `node:crypto` is what Bun and Burger both have
|
|
14
|
+
* (burger-build maps it). The digest never leaves the app's own ledger.
|
|
16
15
|
*/
|
|
17
16
|
/**
|
|
18
17
|
* Orders two strings by their UTF-8 bytes (SQLite's BINARY collation, Rust's
|
|
@@ -54,6 +53,8 @@ export declare class NotJsonError extends Error {
|
|
|
54
53
|
* nested past {@link MAX_VALUE_DEPTH}.
|
|
55
54
|
*/
|
|
56
55
|
export declare function canonicalJson(value: unknown): string;
|
|
56
|
+
/** The canonical JSON, written key by key: the reference {@link canonicalJson} answers for, and what it falls back to. */
|
|
57
|
+
export declare function canonicalJsonByHand(value: unknown): string;
|
|
57
58
|
/** FNV-1a 64 of the UTF-8 bytes of `text`, as 16 hex characters. */
|
|
58
59
|
export declare function fnv1a64(text: string): string;
|
|
59
60
|
/** The parts of a row the digest covers. */
|
|
@@ -64,8 +65,10 @@ export interface DigestInput {
|
|
|
64
65
|
}
|
|
65
66
|
/**
|
|
66
67
|
* The ledger digest of a row — what changes when its value, order or group
|
|
67
|
-
* does — and its value's canonical (encoded) size in bytes
|
|
68
|
-
*
|
|
68
|
+
* does — and its value's canonical (encoded) size in bytes. Throws
|
|
69
|
+
* {@link NotJsonError} when the value is not JSON. The prefix tells the digest
|
|
70
|
+
* from the one older helpers wrote (FNV-1a 64 and a length), which no row equals:
|
|
71
|
+
* after an upgrade each row takes one version, and devices read it again once.
|
|
69
72
|
*/
|
|
70
73
|
export declare function digestAndValueBytes(row: DigestInput): {
|
|
71
74
|
digest: string;
|
package/dist/replica/ledger.d.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The ledger's rules (Phase 3 spec, sections 4.2, 4.6, 4.7 and 5.1), written
|
|
3
|
-
* against {@link LedgerTx} and nothing else.
|
|
4
|
-
*
|
|
3
|
+
* against {@link LedgerTx} and nothing else. The Rust helper's `ledger.rs` in
|
|
4
|
+
* TypeScript: the same plan, the same cut, the same rotation rules. One thing is
|
|
5
|
+
* done elsewhere: rows are checked before the transaction (see {@link checkRows}).
|
|
5
6
|
*/
|
|
6
7
|
import type { CollectionRecord, LedgerTx } from "./store.js";
|
|
7
8
|
import { type PullReply, type PullRequest, type ReplicaRow, type Row } from "./wire.js";
|
|
@@ -46,6 +47,18 @@ export interface Head {
|
|
|
46
47
|
}
|
|
47
48
|
export declare function headOf(record: CollectionRecord): Head;
|
|
48
49
|
export declare function sameHead(a: Head, b: Head): boolean;
|
|
50
|
+
/** A row that passed {@link checkRow}, with the digest it returned. */
|
|
51
|
+
export interface CheckedRow {
|
|
52
|
+
row: Row;
|
|
53
|
+
digest: string;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Every row of a list, checked. Done before the ledger's transaction is opened:
|
|
57
|
+
* it is the long part, and Burger can cut an app's callback off in the middle of it,
|
|
58
|
+
* which runs no `catch` or `finally`, so a transaction left open would hold back, and
|
|
59
|
+
* at the process's end lose, every later write of the app.
|
|
60
|
+
*/
|
|
61
|
+
export declare function checkRows(rows: readonly Row[]): CheckedRow[];
|
|
49
62
|
/** Checks a row against the contract's limits and returns its digest. */
|
|
50
63
|
export declare function checkRow(row: Row): string;
|
|
51
64
|
/** The collection's record, created (new epoch, version 0, dirty) when the ledger has none. */
|
|
@@ -73,14 +86,24 @@ export declare function rotateNow(tx: LedgerTx, spec: Spec, record: CollectionRe
|
|
|
73
86
|
/**
|
|
74
87
|
* Whole-list mode: `rows` is every current row. A new key or a changed digest
|
|
75
88
|
* gets the next version; a ledger key missing from `rows` becomes a tombstone at
|
|
76
|
-
* the next version.
|
|
89
|
+
* the next version. The rows were all checked before anything is written.
|
|
77
90
|
*/
|
|
78
|
-
export declare function reconcile(tx: LedgerTx, spec: Spec, record: CollectionRecord, rows: readonly
|
|
79
|
-
export declare function touch(tx: LedgerTx, spec: Spec, record: CollectionRecord, row:
|
|
91
|
+
export declare function reconcile(tx: LedgerTx, spec: Spec, record: CollectionRecord, rows: readonly CheckedRow[]): void;
|
|
92
|
+
export declare function touch(tx: LedgerTx, spec: Spec, record: CollectionRecord, { row, digest }: CheckedRow): void;
|
|
80
93
|
export declare function remove(tx: LedgerTx, spec: Spec, record: CollectionRecord, key: string): void;
|
|
81
94
|
/** Loads the app's current rows: all of them for `null`, else those of the given keys. */
|
|
82
95
|
export type Load = (keys: readonly string[] | null) => readonly ReplicaRow[];
|
|
83
96
|
/** Refuses a request for a schema this collection does not serve, or outside the contract. */
|
|
84
97
|
export declare function checkRequest(spec: Spec, request: PullRequest): void;
|
|
85
|
-
/**
|
|
86
|
-
|
|
98
|
+
/**
|
|
99
|
+
* Every current row, checked, for a pull that will reconcile first: read and checked
|
|
100
|
+
* before the ledger's transaction, as {@link checkRows} says.
|
|
101
|
+
*/
|
|
102
|
+
export declare function currentRows(load: Load): CheckedRow[];
|
|
103
|
+
/**
|
|
104
|
+
* Answers one pull (section 4.2). `record` is the collection's current record; the
|
|
105
|
+
* caller writes it back. `current` is what {@link currentRows} read when the record
|
|
106
|
+
* was dirty before the transaction; `null` when it was not, or another writer moved the
|
|
107
|
+
* record since: a dirty one then reads them here.
|
|
108
|
+
*/
|
|
109
|
+
export declare function answer(tx: LedgerTx, spec: Spec, record: CollectionRecord, request: PullRequest, load: Load, current: readonly CheckedRow[] | null): PullReply;
|
package/dist/replica.d.ts
CHANGED
|
@@ -26,8 +26,9 @@
|
|
|
26
26
|
* // at a write site: conversations.changed();
|
|
27
27
|
* ```
|
|
28
28
|
*
|
|
29
|
-
*
|
|
30
|
-
*
|
|
29
|
+
* It runs on the database object the app already holds, `bun:sqlite`'s or Burger's
|
|
30
|
+
* `burger:sqlite`, and imports one platform module, `node:crypto` (for `createHash`),
|
|
31
|
+
* which Bun has and burger-build maps to `burger:crypto`.
|
|
31
32
|
*/
|
|
32
33
|
import { CollectionLedger, type ReplicaInvoke } from "./replica/collection.js";
|
|
33
34
|
import { type Head, type Horizon, type ReplicaEnvironment } from "./replica/ledger.js";
|
|
@@ -55,7 +56,7 @@ export interface ReplicaProvidedCapability {
|
|
|
55
56
|
export interface CollectionOptions {
|
|
56
57
|
/** The `N`s of the `.vN` names this app serves; default `[1]`. */
|
|
57
58
|
schemas?: readonly number[];
|
|
58
|
-
/** Every current row.
|
|
59
|
+
/** Every current row. Read before the ledger's transaction is opened; it must not call the replica. */
|
|
59
60
|
list: () => readonly ReplicaRow[];
|
|
60
61
|
/**
|
|
61
62
|
* The rows of the given keys (a key with no row is left out), for large lists;
|
package/dist/replica.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var O={config:"replica_config_invalid:",row:"replica_row_invalid:",request:"replica_request_invalid:",schema:"replica_schema_unsupported:",load:"replica_load_failed:",store:"replica_store_failed:"};function yn(e){return typeof e==="string"?Array.from(e).slice(0,64).join(""):""}class s extends Error{kind;reason;key;constructor(e,n,t,r){super(n);this.name="ReplicaError",this.kind=e,this.reason=t,this.key=r}static config(e){return new s("config",`${O.config} ${e}`,e)}static row(e,n){let t=yn(e);return new s("row",`${O.row} row '${t}': ${n}`,n,t)}static request(e){return new s("request",`${O.request} ${e}`,e)}static schema(e,n){let t=`schema ${n} is not served by ${e}`;return new s("schema",`${O.schema} ${t}`,t)}static load(e){return new s("load",`${O.load} ${e}`,e)}static store(e){return new s("store",`${O.store} ${e}`,e)}}function w(e){if(e instanceof Error)return e.message;if(typeof e==="string")return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function T(e,n){if(e===n)return 0;let t=Math.min(e.length,n.length);for(let r=0;r<t;r+=1){let o=e.charCodeAt(r),i=n.charCodeAt(r);if(o===i)continue;if(o>=55296)o+=o>=57344?-2048:8192;if(i>=55296)i+=i>=57344?-2048:8192;return o<i?-1:1}return e.length<n.length?-1:e.length>n.length?1:0}function _(e){let n=0;for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r<128)n+=1;else if(r<2048)n+=2;else if(r>=55296&&r<=56319&&re(e.charCodeAt(t+1)))n+=4,t+=1;else n+=3}return n}function re(e){return e>=56320&&e<=57343}function U(e){for(let n=0;n<e.length;n+=1){let t=e.charCodeAt(n);if(t<55296||t>57343)continue;if(t<=56319&&re(e.charCodeAt(n+1))){n+=1;continue}return!0}return!1}var oe=128;function ie(e){let n=[{level:1,value:e}];for(let t=n.pop();t!==void 0;t=n.pop()){if(typeof t.value!=="object"||t.value===null)continue;if(t.level>=oe)return!1;for(let r of Array.isArray(t.value)?t.value:Object.values(t.value))n.push({level:t.level+1,value:r})}return!0}var se="value nests 128 or more containers; at most 127 are allowed (the node's JSON limit)";class k extends Error{}function mn(e){let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function _e(e,n){if(U(e))throw new k(`${n} holds a lone surrogate`);return JSON.stringify(e)}function te(e,n,t){switch(typeof e){case"string":return _e(e,n);case"number":if(!Number.isFinite(e))throw new k(`${n} is ${String(e)}, not a JSON number`);return JSON.stringify(e);case"boolean":return e?"true":"false";case"object":{if(e===null)return"null";if(t+1>=oe)throw new k(se);if(Array.isArray(e)){let i=[];for(let a=0;a<e.length;a+=1){let u=e[a];if(u===void 0)throw new k(`${n}[${a}] is undefined`);i.push(te(u,`${n}[${a}]`,t+1))}return`[${i.join(",")}]`}if(!mn(e))throw new k(`${n} is not a plain object`);let r=Object.keys(e).filter((i)=>e[i]!==void 0).sort(T),o=[];for(let i of r)o.push(`${_e(i,`${n} key`)}:${te(e[i],`${n}.${i}`,t+1)}`);return`{${o.join(",")}}`}default:throw new k(`${n} is ${e===void 0?"undefined":`a ${typeof e}`}, not JSON`)}}function Y(e){return te(e,"value",0)}class ae{h0=8997;h1=33826;h2=40164;h3=52210;bytes=0;byte(e){this.h0^=e;let n=this.h0*435,t=this.h1*435,r=this.h2*435+(this.h0<<8),o=this.h3*435+(this.h1<<8);t+=n>>>16,this.h0=n&65535,r+=t>>>16,this.h1=t&65535,this.h3=o+(r>>>16)&65535,this.h2=r&65535}update(e){for(let n=0;n<e.length;n+=1){let t=e.charCodeAt(n);if(t>=55296&&t<=56319&&re(e.charCodeAt(n+1)))t=65536+(t-55296<<10)+(e.charCodeAt(n+1)-56320),n+=1;else if(t>=55296&&t<=57343)t=65533;if(t<128)this.byte(t),this.bytes+=1;else if(t<2048)this.byte(192|t>>6),this.byte(128|t&63),this.bytes+=2;else if(t<65536)this.byte(224|t>>12),this.byte(128|t>>6&63),this.byte(128|t&63),this.bytes+=3;else this.byte(240|t>>18),this.byte(128|t>>12&63),this.byte(128|t>>6&63),this.byte(128|t&63),this.bytes+=4}return this}hex(){return[this.h3,this.h2,this.h1,this.h0].map((e)=>e.toString(16).padStart(4,"0")).join("")}}function wn(e){return new ae().update(e).hex()}function ce(e){let n=Y(e.value),t=new ae().update("[").update(n),r=t.bytes-1;return t.update(`,${e.ord},`).update(JSON.stringify(e.part)).update("]"),{digest:`${t.hex()}.${t.bytes}`,valueBytes:r}}function Rn(e){return ce(e).digest}var Me=256,ue=65536,C=Number.MAX_SAFE_INTEGER,de=128,Jn=16,he=500,fe=262144,Zn=64,Qn=786432,et="core.replica.sync",Ne="core.replica.announce",nt="replica_schema_unsupported:";function F(e){if(typeof e!=="object"||e===null)throw s.row("",`a row must be an object {key, value, ord?, part?}, not ${e===null?"null":typeof e}`);let n=e.key;if(typeof n!=="string")throw s.row("",`key must be a string, not ${n===null?"null":typeof n}`);return{key:n,value:e.value,ord:e.ord??0,part:e.part??""}}function tt(e){return{epoch:"",version:0,schema:e,limit:he}}function pe(e){return Math.min(e.limit,he)}function Ce(e){if(e.epoch!==""&&!ge(e.epoch))return'e must be "" or 1-16 characters of [a-z0-9]';if(e.version>C)return"v must be at most 2^53 - 1";if(e.limit===0)return"l must be at least 1";if(e.resume!==void 0){let n=G(e.resume);if(n!==null)return`a ${n}`;if(e.epoch==="")return"a resumes a full copy and needs that copy's e"}return null}function rt(e){if(e.kind==="full-copy"&&e.head!==void 0)return Math.max(e.version,e.head);return e.version}function ot(e){if(e.kind==="changes")return e.more;if(e.kind==="full-copy")return e.next!==void 0;return!1}function it(e,n){let t={epoch:e.epoch,version:e.version,schema:e.schema,limit:n};if(e.resume!==void 0)t.resume=e.resume;return t}var vn=["unknown","schema","unavailable","busy"];function st(e){switch(e.kind){case"nothing-new":return{kind:"nothing-new"};case"changes":return{kind:"changes",version:e.version,upserts:e.upserts,deletes:e.deletes,more:e.more};case"full-copy":{let n={kind:"full-copy",epoch:e.epoch,version:e.version,rows:e.rows};if(e.next!==void 0)n.next=e.next;return n}}}function ge(e){return/^[a-z0-9]{1,16}$/.test(e)}var bn=/[\u0000-\u001f\u007f-\u009f]/;function G(e){if(typeof e!=="string")return"key must be a string";if(e.length===0)return"key must not be empty";let n=_(e);if(n>Me)return`key is ${n} bytes; at most ${Me} are allowed`;if(bn.test(e))return"key must not contain control characters";if(U(e))return"key must not contain a lone surrogate";return null}function p(e){return JSON.stringify(e)}function b(e){if(!Number.isSafeInteger(e))throw s.store(`${e} is not an integer within 2^53 - 1`);return String(e)}function En(e){try{return Y(e.value)}catch(n){if(n instanceof k)throw s.row(e.key,n.message);throw n}}function Pe(e){let n=`[${p(e.key)},${En(e)}`;if(e.part!=="")return`${n},${b(e.ord)},${p(e.part)}]`;if(e.ord!==0)return`${n},${b(e.ord)}]`;return`${n}]`}function ye(e){return _(Pe(e))+1}function Ie(e){return _(p(e))+1}function De(e){return`[${e.map(Pe).join(",")}]`}function xn(e){return`[${e.map(p).join(",")}]`}function at(e){let n=e.resume===void 0?"":`,"a":${p(e.resume)}`;return`{"e":${p(e.epoch)},"v":${b(e.version)},"s":${b(e.schema)},"l":${b(e.limit)}${n}}`}function He(e,n,t,r){return`"v":${b(e)},"u":${De(n)},"x":${xn(t)}${r?',"m":1':""}`}function Ue(e,n,t,r){return`"e":${p(e)},"v":${b(n)},"f":1,"u":${De(t)}${r===void 0?"":`,"n":${p(r)}`}`}function K(e){switch(e.kind){case"nothing-new":return`{"e":${p(e.epoch)},"v":${b(e.version)}}`;case"changes":return`{"e":${p(e.epoch)},${He(e.version,e.upserts,e.deletes,e.more)}}`;case"full-copy":{let n=e.head===void 0?"":`,"h":${b(e.head)}`;return`{${Ue(e.epoch,e.version,e.rows,e.next)}${n}}`}}}function kn(e){let n=e.resume===void 0?"":`,${p(e.resume)}`;return`[${p(e.capability)},${b(e.schema)},${p(e.epoch)},${b(e.version)}${n}]`}function ct(e){let n=e.origin===void 0?"":`,"origin":${p(e.origin)}`;return`{"c":[${e.entries.map(kn).join(",")}]${n}}`}function An(e){switch(e.kind){case"nothing-new":return"0";case"changes":return`{${He(e.version,e.upserts,e.deletes,e.more)}}`;case"full-copy":return`{${Ue(e.epoch,e.version,e.rows,e.next)}}`;case"error":return`{"err":${p(e.code)}}`}}function lt(e){return`{"r":[${e.answers.map(An).join(",")}]}`}function Fe(e){return`{"c":${p(e.capability)},"e":${p(e.epoch)},"v":${b(e.version)}}`}function ut(e){return e==="ok"?'{"ok":true}':'{"rotate":true}'}function dt(e){return`{"h":[${e.heads.map((t)=>`[${p(t.capability)},${p(t.epoch)},${b(t.version)}]`).join(",")}]}`}function g(e){return s.request(e)}function qe(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function M(e,n){if(!qe(e))throw g(`${n} must be an object`);return e}function R(e,n){let t=e[n];return t===null?void 0:t}function x(e,n,t){let r=R(e,n);if(r===void 0)throw g(`${t}: missing field \`${n}\``);return r}function y(e,n){if(typeof e!=="string")throw g(`${n} must be a string`);return e}function A(e,n,t=C){if(typeof e!=="number"||!Number.isInteger(e)||e<0||e>t){let r=t===C?"from 0 to 2^53 - 1":t===Number.MAX_VALUE?"of at least 0":`from 0 to ${t}`;throw g(`${n} must be an integer ${r}`)}return e}var le=4294967295;function z(e,n){let t=R(e,n);if(t===void 0)return!1;if(A(t,n,255)!==1)throw g(`${n} must be 1 when present, got ${JSON.stringify(t)}`);return!0}function Tn(e){if(!Array.isArray(e)||e.length<2||e.length>4)throw g("a row entry is [key, value, ord?, part?]");let n=e,t=y(n[0],"a row's key"),r=n[2];if(r!==void 0&&(typeof r!=="number"||!Number.isInteger(r)))throw g("a row's ord must be an integer");let o=n[3]===void 0?"":y(n[3],"a row's part");return{key:t,value:n[1],ord:typeof r==="number"?r:0,part:o}}function W(e,n){if(e===void 0)return[];if(!Array.isArray(e))throw g(`${n} must be an array of row entries`);return e.map(Tn)}function Be(e,n){if(e===void 0)return[];if(!Array.isArray(e))throw g(`${n} must be an array of keys`);return e.map((t)=>y(t,`an entry of ${n}`))}function J(e){let n=M(e,"a pull request"),t=R(n,"l"),r={epoch:y(x(n,"e","a pull request"),"e"),version:A(x(n,"v","a pull request"),"v",Number.MAX_VALUE),schema:A(x(n,"s","a pull request"),"s",le),limit:t===void 0?he:A(t,"l",le)},o=R(n,"a");if(o!==void 0)r.resume=y(o,"a");return r}function ht(e){let n=M(e,"a pull reply"),t=A(x(n,"v","a pull reply"),"v"),r=R(n,"e");if(r===void 0)throw g("a pull reply: missing field `e`");let o=y(r,"e"),i=R(n,"u"),a=R(n,"x");if(z(n,"f")){let u={kind:"full-copy",epoch:o,version:t,rows:W(i,"u")},d=R(n,"n");if(d!==void 0)u.next=y(d,"n");let l=R(n,"h");if(l!==void 0)u.head=A(l,"h");return u}if(i!==void 0||a!==void 0)return{kind:"changes",epoch:o,version:t,upserts:W(i,"u"),deletes:Be(a,"x"),more:z(n,"m")};return{kind:"nothing-new",epoch:o,version:t}}function Ln(e){if(!Array.isArray(e)||e.length<4||e.length>5)throw g("a sync entry is [capability, schema, epoch, version, resume?]");let n=e,t={capability:y(n[0],"a sync entry's capability"),schema:A(n[1],"a sync entry's schema",le),epoch:y(n[2],"a sync entry's epoch"),version:A(n[3],"a sync entry's version")};if(n.length===5)t.resume=y(n[4],"a sync entry's resume key");return t}function ft(e){let n=M(e,"a sync request"),t=x(n,"c","a sync request");if(!Array.isArray(t))throw g("c must be an array of sync entries");let r={entries:t.map(Ln)},o=R(n,"origin");if(o!==void 0)r.origin=y(o,"origin");return r}function Sn(e){if(e===0)return{kind:"nothing-new"};if(!qe(e))throw g("a sync answer is 0, a changes object, a full copy or an error");if("err"in e){let t=vn.find((r)=>r===e.err);if(t===void 0)throw g("err must be a known error code");return{kind:"error",code:t}}let n=A(x(e,"v","a sync answer"),"v");if(z(e,"f")){let t={kind:"full-copy",epoch:y(x(e,"e","a sync answer"),"e"),version:n,rows:W(R(e,"u"),"u")},r=R(e,"n");if(r!==void 0)t.next=y(r,"n");return t}return{kind:"changes",version:n,upserts:W(R(e,"u"),"u"),deletes:Be(R(e,"x"),"x"),more:z(e,"m")}}function pt(e){let n=x(M(e,"a sync reply"),"r","a sync reply");if(!Array.isArray(n))throw g("r must be an array of answers");return{answers:n.map(Sn)}}function gt(e){let n=M(e,"an announce");return{capability:y(x(n,"c","an announce"),"c"),epoch:y(x(n,"e","an announce"),"e"),version:A(x(n,"v","an announce"),"v")}}function Xe(e){let n=M(e,"an announce reply"),t=(i)=>{let a=R(n,i);if(a===void 0)return!1;if(typeof a!=="boolean")throw g(`${i} must be a boolean`);return a},r=t("rotate"),o=t("ok");if(r)return"rotate";if(o)return"ok";throw g('an announce reply is {"ok":true} or {"rotate":true}')}function yt(e){let n=x(M(e,"replica.heads data"),"h","replica.heads data");if(!Array.isArray(n))throw g("h must be an array of heads");return{heads:n.map((t)=>{if(!Array.isArray(t)||t.length!==3)throw g("a pushed head is [capability, epoch, version]");let r=t;return{capability:y(r[0],"a head's capability"),epoch:y(r[1],"a head's epoch"),version:A(r[2],"a head's version")}})}}var Ve=2592000000,Ye=5000,ze=60000,me={maxAgeMs:Ve,maxCount:Ye};function L(e){return{epoch:e.epoch,version:e.version}}function q(e,n){return e.epoch===n.epoch&&e.version===n.version}function we(e){let n=G(e.key);if(n!==null)throw s.row(e.key,n);if(!ie(e.value))throw s.row(e.key,se);let t,r;try{({digest:t,valueBytes:r}=ce(e))}catch(i){if(i instanceof k)throw s.row(e.key,i.message);throw i}if(r>ue)throw s.row(e.key,`value is ${r} bytes encoded; at most ${ue} are allowed`);if(!Number.isInteger(e.ord)||Math.abs(e.ord)>C)throw s.row(e.key,"ord must be within \xB1(2^53 - 1)");if(typeof e.part!=="string")throw s.row(e.key,"part must be a string");let o=_(e.part);if(o>de)throw s.row(e.key,`part is ${o} bytes; at most ${de} are allowed`);if(U(e.part))throw s.row(e.key,"part must not contain a lone surrogate");return t}function We(e,n){for(let t=0;t<4;t+=1){let r=e.env.newEpoch();if(!ge(r))throw s.store("the environment produced an epoch outside [a-z0-9]{1,16}");if(r!==n)return r}throw s.store("the environment keeps producing the current epoch")}function Z(e,n,t){if(t.rotateOwed)D(e,n,t);if(t.version>=C)throw s.store(`version of ${t.epoch} would pass 2^53 - 1`);return t.version+=1,t.version}function Ge(e,n){let t=e.record(n.name);if(t!==null)return t;let r={epoch:We(n,null),version:0,floor:0,dirty:!0,rotatedAt:n.env.nowMs(),reconciledAt:0,rotateOwed:!1};return e.putRecord(n.name,r),r}function Re(e,n){let t=e.env.nowMs();return n.rotatedAt===0||t<n.rotatedAt||t-n.rotatedAt>=ze}function ve(e,n,t){if(Re(n,t))return D(e,n,t),!0;return t.rotateOwed=!0,!1}function Ke(e,n,t,r){if(r||t.rotateOwed&&Re(n,t))return D(e,n,t),!0;return!1}function Je(e,n){return!(n.rotateOwed&&Re(e,n))}function D(e,n,t){let r=n.env.nowMs(),o=0;for(let i of e.entries(n.name)){if(i.deleted){e.deleteEntry(n.name,i.key);continue}o+=1,e.putEntry(n.name,{...i,version:o,changedAt:r})}t.epoch=We(n,t.epoch),t.version=o,t.floor=0,t.rotatedAt=r,t.rotateOwed=!1}function Ze(e,n,t,r,o,i){let a=e.entry(n.name,r.key);if(a!==null&&!a.deleted&&a.digest===o)return!1;let u=Z(e,n,t);return e.putEntry(n.name,{key:r.key,digest:o,version:u,deleted:!1,changedAt:i}),!0}function Qe(e,n,t,r,o){let i=e.entry(n.name,r);if(i===null||i.deleted)return!1;let a=Z(e,n,t);return e.putEntry(n.name,{key:r,digest:i.digest,version:a,deleted:!0,changedAt:o}),!0}function be(e,n,t,r){let o=e.pruneTombstones(n.name,Math.max(0,r-n.horizon.maxAgeMs),n.horizon.maxCount);if(o.highest!==null)t.floor=Math.max(t.floor,o.highest);if(o.overKeep)ve(e,n,t)}function Ee(e,n,t,r){let o=n.env.nowMs(),i=r.map((c)=>({row:c,digest:we(c)}));i.sort((c,h)=>T(c.row.key,h.row.key));for(let c=1;c<i.length;c+=1){let h=i[c-1],f=i[c];if(h!==void 0&&f!==void 0&&h.row.key===f.row.key)throw s.row(h.row.key,"the key appears twice in the list")}let a=e.entries(n.name),u=[],d=[],l=0;for(let c of i){while(l<a.length&&T(P(a,l).key,c.row.key)<0){let f=P(a,l);if(!f.deleted)d.push(f);l+=1}let h=!1;if(l<a.length&&P(a,l).key===c.row.key){let f=P(a,l);h=!f.deleted&&f.digest===c.digest,l+=1}if(!h)u.push(c)}for(;l<a.length;l+=1){let c=P(a,l);if(!c.deleted)d.push(c)}for(let{row:c,digest:h}of u){let f=Z(e,n,t);e.putEntry(n.name,{key:c.key,digest:h,version:f,deleted:!1,changedAt:o})}for(let c of d){let h=Z(e,n,t);e.putEntry(n.name,{key:c.key,digest:c.digest,version:h,deleted:!0,changedAt:o})}be(e,n,t,o),t.dirty=!1,t.reconciledAt=o}function P(e,n){let t=e[n];if(t===void 0)throw s.store("ledger index out of range");return t}function en(e,n,t,r){let o=we(r),i=n.env.nowMs();Ze(e,n,t,r,o,i),be(e,n,t,i)}function nn(e,n,t,r){let o=G(r);if(o!==null)throw s.row(r,o);let i=n.env.nowMs();Qe(e,n,t,r,i),be(e,n,t,i)}function I(e,n,t,r,o){return{kind:"full-copy",version:r,entries:e.liveAfter(n.name,t,o)}}function $n(e,n,t,r){let o=pe(r)+1;if(r.epoch!==t.epoch)return I(e,n,null,t.version,o);if(r.version>t.version)return D(e,n,t),I(e,n,null,t.version,o);if(r.resume!==void 0){if(r.version>=t.floor)return I(e,n,r.resume,r.version,o);return I(e,n,null,t.version,o)}if(r.version<t.floor)return I(e,n,null,t.version,o);if(r.version===t.version)return{kind:"nothing-new"};return{kind:"changes",entries:e.changesAfter(n.name,r.version,o)}}function On(e,n,t,r,o){let i=n.env.nowMs(),a=!1;for(let u of r){if(u.deleted)continue;let d=o.get(u.key);if(d===void 0)a=Qe(e,n,t,u.key,i)||a;else{let l=we(d);if(l!==u.digest)a=Ze(e,n,t,d,l,i)||a}}return a}function xe(e,n){if(!e.schemas.includes(n.schema))throw s.schema(e.name,n.schema);let t=Ce(n);if(t!==null)throw s.request(t)}function je(e,n){let t;try{t=e(n)}catch(r){throw s.load(w(r))}return t.map(F)}function tn(e,n,t,r,o){if(xe(n,r),t.dirty)Ee(e,n,t,je(o,null));let i=pe(r),a=!1,u=0;for(;;){let d=a?I(e,n,null,t.version,i+1):$n(e,n,t,r);if(d.kind==="nothing-new")return{kind:"nothing-new",epoch:t.epoch,version:t.version};let l=d.entries.slice(0,i),c=l.filter((E)=>!E.deleted).map((E)=>E.key),h=new Map;if(c.length>0){let E=new Set(c);for(let N of je(o,c))if(E.has(N.key))h.set(N.key,N)}if(u<2&&On(e,n,t,l,h)){u+=1;continue}let f=_n(t,r,d,i,h);if(f!==null)return f;if(a)throw s.store("a full copy could not be built");a=!0}}function _n(e,n,t,r,o){if(t.kind==="changes"){let c=[],h=0,f=!1;for(let m of t.entries){if(c.length===r){f=!0;break}let H=o.get(m.key),Oe=m.deleted?Ie(m.key):H!==void 0?ye(H):0;if(c.length>0&&h+Oe>fe){f=!0;break}h+=Oe,c.push(m)}let E;if(f){let m=0;while(m<c.length&&c[m]?.version===n.version+m+1)m+=1;if(m===0)return null;c.length=m,E=n.version+m}else E=e.version;let N=[],$e=[];for(let m of c){if(m.deleted){$e.push(m.key);continue}let H=o.get(m.key);if(H!==void 0)N.push(H)}return{kind:"changes",epoch:e.epoch,version:E,upserts:N,deletes:$e,more:f}}let i=[],a=0,u=null,d=!1;for(let c=0;c<t.entries.length;c+=1){let h=P(t.entries,c);if(c===r){d=!0;break}let f=o.get(h.key);if(f===void 0){u=h.key;continue}let E=ye(f);if(c>0&&a+E>fe){d=!0;break}i.push(f),a+=E,u=h.key}let l={kind:"full-copy",epoch:e.epoch,version:t.version,rows:i};if(d&&u!==null)l.next=u;if(e.version>t.version)l.head=e.version;return l}function sn(e,n,t){if(e.readRecord!==void 0)return e.readRecord(n,t);let r=null;return e.write(n,(o)=>{r=o.record(t)}),r}function Nn(e){let n=new Map;for(let[t,r]of e.entries)n.set(t,{...r});return{record:e.record===null?null:{...e.record},entries:n}}function rn(e){let n=new Map;for(let[t,r]of e)n.set(t,Nn(r));return n}function on(e){if(e===void 0)return[];return[...e.entries.values()].sort((n,t)=>T(n.key,t.key))}class an{prefix;tables;undo=[];saved=new Set;constructor(e,n){this.prefix=e;this.tables=n}rollback(){for(let e=this.undo.length-1;e>=0;e-=1)this.undo[e]?.()}name(e){return`${this.prefix}\x00${e}`}get(e){return this.tables.get(this.name(e))}getMut(e){let n=this.name(e),t=this.tables.get(n);if(t===void 0)t={record:null,entries:new Map},this.tables.set(n,t),this.undo.push(()=>this.tables.delete(n));return t}saveRecord(e){let n=this.getMut(e),t=`r\x00${this.name(e)}`;if(!this.saved.has(t)){this.saved.add(t);let r=n.record;this.undo.push(()=>{n.record=r})}return n}saveEntry(e,n,t){let r=`e\x00${this.name(n)}\x00${t}`;if(this.saved.has(r))return;this.saved.add(r);let o=e.entries.get(t);this.undo.push(()=>{if(o===void 0)e.entries.delete(t);else e.entries.set(t,o)})}record(e){let n=this.get(e)?.record;return n?{...n}:null}putRecord(e,n){this.saveRecord(e).record={...n}}entry(e,n){let t=this.get(e)?.entries.get(n);return t?{...t}:null}entries(e){return on(this.get(e)).map((n)=>({...n}))}putEntry(e,n){let t=this.getMut(e);this.saveEntry(t,e,n.key),t.entries.set(n.key,{...n})}deleteEntry(e,n){let t=this.getMut(e);this.saveEntry(t,e,n),t.entries.delete(n)}changesAfter(e,n,t){let r=this.get(e);if(r===void 0)return[];return[...r.entries.values()].filter((o)=>o.version>n).sort((o,i)=>o.version-i.version).slice(0,t).map((o)=>({...o}))}liveAfter(e,n,t){return on(this.get(e)).filter((r)=>!r.deleted&&(n===null||T(r.key,n)>0)).slice(0,t).map((r)=>({...r}))}pruneTombstones(e,n,t){let r=this.getMut(e),o=r.entries,i=[...o.values()].filter((l)=>l.deleted).sort((l,c)=>l.version-c.version||l.changedAt-c.changedAt||T(l.key,c.key)),a=Math.max(0,i.length-t),u=null,d=0;return i.forEach((l,c)=>{if(c<a||l.changedAt<n)this.saveEntry(r,e,l.key),o.delete(l.key),u=u===null?l.version:Math.max(u,l.version);else d+=1}),{highest:u,overKeep:d>t}}}class ke{tables=new Map;ensure(){}write(e,n){let t=new an(e,this.tables);try{n(t)}catch(r){throw t.rollback(),r}}readRecord(e,n){let t=this.tables.get(`${e}\x00${n}`)?.record;return t?{...t}:null}clone(){let e=new ke;return e.tables=rn(this.tables),e}restoreFrom(e){this.tables=rn(e.tables)}}var dn={nowMs:()=>Date.now(),newEpoch:Cn},cn="abcdefghijklmnopqrstuvwxyz0123456789",ln=0;function Cn(){let e=new Uint8Array(8),n=globalThis.crypto;if(n?.getRandomValues!==void 0)n.getRandomValues(e);else{ln+=1;let r=Date.now()+ln;for(let o=0;o<e.length;o+=1)e[o]=Math.floor(Math.random()*256)^r>>>o%4*8&255}let t="";for(let r of e)t+=cn.charAt(r%cn.length);return t}var Pn=16,In=/^[a-z][a-z0-9_-]*$/,Dn=/^(?:[A-Za-z_][A-Za-z0-9_]{0,47})?$/;class Q{store;name;tablePrefix;schemas;spec;announceFailing=!1;handedOutMarks=[];constructor(e,n,t={}){this.store=e;this.name=n,this.tablePrefix=t.tablePrefix??"",this.schemas=[...t.schemas??[1]],this.spec={name:n,schemas:this.schemas,env:t.env??dn,horizon:t.horizon??me}}check(){let e=this.name.split(".");if(e.length<3||e[e.length-1]!=="pull"||!e.every((n)=>In.test(n)))throw s.config(`'${this.name}' is not a pull capability '<app>.<collection>.pull'`);if(this.name.startsWith("core."))throw s.config(`'${this.name}' is in the reserved 'core.' namespace`);if(!Dn.test(this.tablePrefix))throw s.config(`table prefix '${this.tablePrefix}' must be [A-Za-z_][A-Za-z0-9_]{0,47} or empty`);if(!(this.spec.horizon.maxCount>=1))throw s.config("the tombstone horizon must keep at least one tombstone");if(!this.schemas.every((n)=>Number.isInteger(n)&&n>=0&&n<=4294967295))throw s.config("schemas must be integers from 0 to 4294967295")}handedOut(e){return this.handedOutMarks.find(([n])=>n===e)?.[1]}noteHandedOut(e,n){let t=this.handedOutMarks.findIndex(([o])=>o===e),r=n;if(t>=0){let[o]=this.handedOutMarks.splice(t,1);if(o!==void 0)r=Math.max(o[1],n)}this.handedOutMarks.unshift([e,r]),this.handedOutMarks.length=Math.min(this.handedOutMarks.length,Pn)}wentBack(e){let n=this.handedOut(e.epoch);return n!==void 0&&n>e.version}withRecord(e){this.check();let n=null;if(this.store.write(this.tablePrefix,(t)=>{let r=Ge(t,this.spec),o={...r},i=Ke(t,this.spec,r,this.wentBack(r)),a=e(t,r,i);if(!Hn(r,o))t.putRecord(this.spec.name,r);n={value:a}}),n===null)throw s.store("the store did not run the ledger work");return n.value}readSettled(){this.check();let e=sn(this.store,this.tablePrefix,this.name);if(e===null||this.wentBack(e)||!Je(this.spec,e))return null;return e}ensure(){this.check(),this.store.ensure(this.tablePrefix)}reconcile(e){let n=e.map(F);return this.withRecord((t,r)=>{let o=L(r);return Ee(t,this.spec,r,n),q(L(r),o)?null:r.version})}touch(e){let n=F(e);return this.withRecord((t,r)=>(en(t,this.spec,r,n),r.version))}remove(e){return this.withRecord((n,t)=>(nn(n,this.spec,t,e),t.version))}markDirty(){this.withRecord((e,n)=>{n.dirty=!0})}reset(){return this.withRecord((e,n,t)=>{let r=t||ve(e,this.spec,n);return n.dirty=!0,r})}head(){let e=this.readSettled();if(e!==null)return L(e);return this.withRecord((n,t)=>L(t))}answer(e,n){if(xe(this.spec,e),e.resume===void 0){let o=this.readSettled();if(o!==null&&!o.dirty&&o.epoch===e.epoch&&o.version===e.version)return this.noteHandedOut(o.epoch,o.version),{reply:{kind:"nothing-new",epoch:o.epoch,version:o.version},headMoved:!1}}let{answered:t,head:r}=this.withRecord((o,i,a)=>{let u=L(i),d=tn(o,this.spec,i,e,n),l=L(i);return{answered:{reply:d,headMoved:a||!q(l,u)},head:l}});return this.noteHandedOut(r.epoch,r.version),t}pull(e,n){return JSON.parse(K(this.answer(J(e),n).reply))}async announce(e){try{let n=await this.announceInner(e);return this.announceFailing=!1,n}catch(n){let t=!this.announceFailing;return this.announceFailing=!0,{kind:"failed",error:w(n),first:t}}}async announceInner(e){let n=this.head();if(await un(this.name,n,e)==="ok")return this.noteHandedOut(n.epoch,n.version),{kind:"accepted",head:n};this.noteHandedOut(n.epoch,n.version+1);let t=this.withRecord((r,o,i)=>{if(!i&&o.epoch===n.epoch)D(r,this.spec,o);return L(o)});if(await un(this.name,t,e)==="ok")return this.noteHandedOut(t.epoch,t.version),{kind:"rotated",head:t};return{kind:"rotation-deferred",head:t}}description(){return`Replicated collection served by @econ-v1/app-sdk/replica (Phase 3 contract). Request {"e":<epoch held, "" for none>,"v":<version held>,"s":<schema>,"l":<row limit, at most 500>,"a":<resume key, optional>}. Reply {"e","v"} when nothing is new; {"e","v","u":[[key,value,ord?,part?]...],"x":[key...],"m":1?} with the changes since v; or {"e","v","f":1,"u":[...],"n":<next key>?}, a full copy in key order. Schemas served: ${this.schemas.join(", ")}. Called by the node (core.replica.sync), not by devices.`}}function Hn(e,n){return e.epoch===n.epoch&&e.version===n.version&&e.floor===n.floor&&e.dirty===n.dirty&&e.rotatedAt===n.rotatedAt&&e.reconciledAt===n.reconciledAt&&e.rotateOwed===n.rotateOwed}async function un(e,n,t){let r=JSON.parse(Fe({capability:e,epoch:n.epoch,version:n.version})),o=await t(Ne,r);try{return Xe(o)}catch(i){throw Error(`unexpected announce reply: ${w(i)}`)}}var ee=2;function Ae(e){return{meta:`${e}replica_meta`,collections:`${e}replica_collections`,rows:`${e}replica_rows`}}function Un(e,n){e.exec(`CREATE TABLE IF NOT EXISTS ${n.collections} (
|
|
2
|
+
var N={config:"replica_config_invalid:",row:"replica_row_invalid:",request:"replica_request_invalid:",schema:"replica_schema_unsupported:",load:"replica_load_failed:",store:"replica_store_failed:"};function xn(e){return typeof e==="string"?Array.from(e).slice(0,64).join(""):""}class c extends Error{kind;reason;key;constructor(e,n,t,r){super(n);this.name="ReplicaError",this.kind=e,this.reason=t,this.key=r}static config(e){return new c("config",`${N.config} ${e}`,e)}static row(e,n){let t=xn(e);return new c("row",`${N.row} row '${t}': ${n}`,n,t)}static request(e){return new c("request",`${N.request} ${e}`,e)}static schema(e,n){let t=`schema ${n} is not served by ${e}`;return new c("schema",`${N.schema} ${t}`,t)}static load(e){return new c("load",`${N.load} ${e}`,e)}static store(e){return new c("store",`${N.store} ${e}`,e)}}function w(e){if(e instanceof Error)return e.message;if(typeof e==="string")return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}import{createHash as kn}from"crypto";function L(e,n){if(e===n)return 0;let t=Math.min(e.length,n.length);for(let r=0;r<t;r+=1){let o=e.charCodeAt(r),i=n.charCodeAt(r);if(o===i)continue;if(o>=55296)o+=o>=57344?-2048:8192;if(i>=55296)i+=i>=57344?-2048:8192;return o<i?-1:1}return e.length<n.length?-1:e.length>n.length?1:0}var An=new TextEncoder;function O(e){if(e.length>128)return An.encode(e).length;let n=0;for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r<128)n+=1;else if(r<2048)n+=2;else if(r>=55296&&r<=56319&&le(e.charCodeAt(t+1)))n+=4,t+=1;else n+=3}return n}function le(e){return e>=56320&&e<=57343}function q(e){for(let n=0;n<e.length;n+=1){let t=e.charCodeAt(n);if(t<55296||t>57343)continue;if(t<=56319&&le(e.charCodeAt(n+1))){n+=1;continue}return!0}return!1}var G=128;function Tn(e){let n=[{level:1,value:e}];for(let t=n.pop();t!==void 0;t=n.pop()){if(typeof t.value!=="object"||t.value===null)continue;if(t.level>=G)return!1;for(let r of Array.isArray(t.value)?t.value:Object.values(t.value))n.push({level:t.level+1,value:r})}return!0}var Ln="value nests 128 or more containers; at most 127 are allowed (the node's JSON limit)";class k extends Error{}function Ie(e){let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Ce(e,n){if(q(e))throw new k(`${n} holds a lone surrogate`);return JSON.stringify(e)}function ce(e,n,t){switch(typeof e){case"string":return Ce(e,n);case"number":if(!Number.isFinite(e))throw new k(`${n} is ${String(e)}, not a JSON number`);return JSON.stringify(e);case"boolean":return e?"true":"false";case"object":{if(e===null)return"null";if(t+1>=G)throw new k(Ln);if(Array.isArray(e)){let i=[];for(let s=0;s<e.length;s+=1){let l=e[s];if(l===void 0)throw new k(`${n}[${s}] is undefined`);i.push(ce(l,`${n}[${s}]`,t+1))}return`[${i.join(",")}]`}if(!Ie(e))throw new k(`${n} is not a plain object`);let r=Object.keys(e).filter((i)=>e[i]!==void 0).sort(L),o=[];for(let i of r)o.push(`${Ce(i,`${n} key`)}:${ce(e[i],`${n}.${i}`,t+1)}`);return`{${o.join(",")}}`}default:throw new k(`${n} is ${e===void 0?"undefined":`a ${typeof e}`}, not JSON`)}}var x=Symbol("unusual"),Sn=/^(?:0|[1-9][0-9]*)$/,$n=/[\ud800-\uffff]/,W=new Map,On=64,_n=8;function Pe(e){if(e.some((n)=>n==="__proto__"||Sn.test(n)||$n.test(n)))return null;return e.sort()}function Mn(e){if(e.length<=_n)return Pe(e);let n=JSON.stringify(e),t=W.get(n);if(t===void 0){if(t=Pe(e),W.size>=On)W.clear();W.set(n,t)}return t}function ae(e,n){switch(typeof e){case"string":case"boolean":return e;case"number":return Number.isFinite(e)?e:x;case"object":break;default:return x}if(e===null)return null;if(n+1>=G)return x;if(Array.isArray(e)){let o=[];for(let i=0;i<e.length;i+=1){let s=e[i]===void 0?x:ae(e[i],n+1);if(s===x)return x;o.push(s)}return o}if(!Ie(e))return x;let t=Mn(Object.keys(e));if(t===null)return x;let r={};for(let o of t){let i=e[o];if(i===void 0)continue;if(i===null||typeof i==="string"){r[o]=i;continue}let s=ae(i,n+1);if(s===x)return x;r[o]=s}return r}function K(e){let n=ae(e,0);if(n!==x){let t=JSON.stringify(n);if(!t.includes("\\ud"))return t}return Nn(e)}function Nn(e){return ce(e,"value",0)}class De{h0=8997;h1=33826;h2=40164;h3=52210;bytes=0;byte(e){this.h0^=e;let n=this.h0*435,t=this.h1*435,r=this.h2*435+(this.h0<<8),o=this.h3*435+(this.h1<<8);t+=n>>>16,this.h0=n&65535,r+=t>>>16,this.h1=t&65535,this.h3=o+(r>>>16)&65535,this.h2=r&65535}update(e){for(let n=0;n<e.length;n+=1){let t=e.charCodeAt(n);if(t>=55296&&t<=56319&&le(e.charCodeAt(n+1)))t=65536+(t-55296<<10)+(e.charCodeAt(n+1)-56320),n+=1;else if(t>=55296&&t<=57343)t=65533;if(t<128)this.byte(t),this.bytes+=1;else if(t<2048)this.byte(192|t>>6),this.byte(128|t&63),this.bytes+=2;else if(t<65536)this.byte(224|t>>12),this.byte(128|t>>6&63),this.byte(128|t&63),this.bytes+=3;else this.byte(240|t>>18),this.byte(128|t>>12&63),this.byte(128|t>>6&63),this.byte(128|t&63),this.bytes+=4}return this}hex(){return[this.h3,this.h2,this.h1,this.h0].map((e)=>e.toString(16).padStart(4,"0")).join("")}}function Cn(e){return new De().update(e).hex()}function ue(e){let n=K(e.value),t=`[${n},${e.ord},${JSON.stringify(e.part)}]`;return{digest:`s1.${kn("sha256").update(t).digest("hex").slice(0,32)}`,valueBytes:O(n)}}function Pn(e){return ue(e).digest}var He=256,he=65536,I=Number.MAX_SAFE_INTEGER,fe=128,ft=16,pe=500,ge=262144,pt=64,gt=786432,yt="core.replica.sync",Ue="core.replica.announce",mt="replica_schema_unsupported:";function B(e){if(typeof e!=="object"||e===null)throw c.row("",`a row must be an object {key, value, ord?, part?}, not ${e===null?"null":typeof e}`);let n=e.key;if(typeof n!=="string")throw c.row("",`key must be a string, not ${n===null?"null":typeof n}`);return{key:n,value:e.value,ord:e.ord??0,part:e.part??""}}function wt(e){return{epoch:"",version:0,schema:e,limit:pe}}function ye(e){return Math.min(e.limit,pe)}function Fe(e){if(e.epoch!==""&&!me(e.epoch))return'e must be "" or 1-16 characters of [a-z0-9]';if(e.version>I)return"v must be at most 2^53 - 1";if(e.limit===0)return"l must be at least 1";if(e.resume!==void 0){let n=Q(e.resume);if(n!==null)return`a ${n}`;if(e.epoch==="")return"a resumes a full copy and needs that copy's e"}return null}function Rt(e){if(e.kind==="full-copy"&&e.head!==void 0)return Math.max(e.version,e.head);return e.version}function vt(e){if(e.kind==="changes")return e.more;if(e.kind==="full-copy")return e.next!==void 0;return!1}function bt(e,n){let t={epoch:e.epoch,version:e.version,schema:e.schema,limit:n};if(e.resume!==void 0)t.resume=e.resume;return t}var In=["unknown","schema","unavailable","busy"];function Et(e){switch(e.kind){case"nothing-new":return{kind:"nothing-new"};case"changes":return{kind:"changes",version:e.version,upserts:e.upserts,deletes:e.deletes,more:e.more};case"full-copy":{let n={kind:"full-copy",epoch:e.epoch,version:e.version,rows:e.rows};if(e.next!==void 0)n.next=e.next;return n}}}function me(e){return/^[a-z0-9]{1,16}$/.test(e)}var Dn=/[\u0000-\u001f\u007f-\u009f]/;function Q(e){if(typeof e!=="string")return"key must be a string";if(e.length===0)return"key must not be empty";let n=O(e);if(n>He)return`key is ${n} bytes; at most ${He} are allowed`;if(Dn.test(e))return"key must not contain control characters";if(q(e))return"key must not contain a lone surrogate";return null}function p(e){return JSON.stringify(e)}function b(e){if(!Number.isSafeInteger(e))throw c.store(`${e} is not an integer within 2^53 - 1`);return String(e)}function Hn(e){try{return K(e.value)}catch(n){if(n instanceof k)throw c.row(e.key,n.message);throw n}}var qe=new WeakMap;function Be(e){let n=qe.get(e);if(n!==void 0)return n;let t=`[${p(e.key)},${Hn(e)}`;if(e.part!=="")return`${t},${b(e.ord)},${p(e.part)}]`;if(e.ord!==0)return`${t},${b(e.ord)}]`;return`${t}]`}function we(e){let n=Be(e);return qe.set(e,n),O(n)+1}function Xe(e){return O(p(e))+1}function je(e){return`[${e.map(Be).join(",")}]`}function Un(e){return`[${e.map(p).join(",")}]`}function xt(e){let n=e.resume===void 0?"":`,"a":${p(e.resume)}`;return`{"e":${p(e.epoch)},"v":${b(e.version)},"s":${b(e.schema)},"l":${b(e.limit)}${n}}`}function Ye(e,n,t,r){return`"v":${b(e)},"u":${je(n)},"x":${Un(t)}${r?',"m":1':""}`}function ze(e,n,t,r){return`"e":${p(e)},"v":${b(n)},"f":1,"u":${je(t)}${r===void 0?"":`,"n":${p(r)}`}`}function ee(e){switch(e.kind){case"nothing-new":return`{"e":${p(e.epoch)},"v":${b(e.version)}}`;case"changes":return`{"e":${p(e.epoch)},${Ye(e.version,e.upserts,e.deletes,e.more)}}`;case"full-copy":{let n=e.head===void 0?"":`,"h":${b(e.head)}`;return`{${ze(e.epoch,e.version,e.rows,e.next)}${n}}`}}}function Fn(e){let n=e.resume===void 0?"":`,${p(e.resume)}`;return`[${p(e.capability)},${b(e.schema)},${p(e.epoch)},${b(e.version)}${n}]`}function kt(e){let n=e.origin===void 0?"":`,"origin":${p(e.origin)}`;return`{"c":[${e.entries.map(Fn).join(",")}]${n}}`}function qn(e){switch(e.kind){case"nothing-new":return"0";case"changes":return`{${Ye(e.version,e.upserts,e.deletes,e.more)}}`;case"full-copy":return`{${ze(e.epoch,e.version,e.rows,e.next)}}`;case"error":return`{"err":${p(e.code)}}`}}function At(e){return`{"r":[${e.answers.map(qn).join(",")}]}`}function Ve(e){return`{"c":${p(e.capability)},"e":${p(e.epoch)},"v":${b(e.version)}}`}function Tt(e){return e==="ok"?'{"ok":true}':'{"rotate":true}'}function Lt(e){return`{"h":[${e.heads.map((t)=>`[${p(t.capability)},${p(t.epoch)},${b(t.version)}]`).join(",")}]}`}function g(e){return c.request(e)}function We(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function C(e,n){if(!We(e))throw g(`${n} must be an object`);return e}function R(e,n){let t=e[n];return t===null?void 0:t}function E(e,n,t){let r=R(e,n);if(r===void 0)throw g(`${t}: missing field \`${n}\``);return r}function y(e,n){if(typeof e!=="string")throw g(`${n} must be a string`);return e}function A(e,n,t=I){if(typeof e!=="number"||!Number.isInteger(e)||e<0||e>t){let r=t===I?"from 0 to 2^53 - 1":t===Number.MAX_VALUE?"of at least 0":`from 0 to ${t}`;throw g(`${n} must be an integer ${r}`)}return e}var de=4294967295;function J(e,n){let t=R(e,n);if(t===void 0)return!1;if(A(t,n,255)!==1)throw g(`${n} must be 1 when present, got ${JSON.stringify(t)}`);return!0}function Bn(e){if(!Array.isArray(e)||e.length<2||e.length>4)throw g("a row entry is [key, value, ord?, part?]");let n=e,t=y(n[0],"a row's key"),r=n[2];if(r!==void 0&&(typeof r!=="number"||!Number.isInteger(r)))throw g("a row's ord must be an integer");let o=n[3]===void 0?"":y(n[3],"a row's part");return{key:t,value:n[1],ord:typeof r==="number"?r:0,part:o}}function Z(e,n){if(e===void 0)return[];if(!Array.isArray(e))throw g(`${n} must be an array of row entries`);return e.map(Bn)}function Ge(e,n){if(e===void 0)return[];if(!Array.isArray(e))throw g(`${n} must be an array of keys`);return e.map((t)=>y(t,`an entry of ${n}`))}function ne(e){let n=C(e,"a pull request"),t=R(n,"l"),r={epoch:y(E(n,"e","a pull request"),"e"),version:A(E(n,"v","a pull request"),"v",Number.MAX_VALUE),schema:A(E(n,"s","a pull request"),"s",de),limit:t===void 0?pe:A(t,"l",de)},o=R(n,"a");if(o!==void 0)r.resume=y(o,"a");return r}function St(e){let n=C(e,"a pull reply"),t=A(E(n,"v","a pull reply"),"v"),r=R(n,"e");if(r===void 0)throw g("a pull reply: missing field `e`");let o=y(r,"e"),i=R(n,"u"),s=R(n,"x");if(J(n,"f")){let l={kind:"full-copy",epoch:o,version:t,rows:Z(i,"u")},d=R(n,"n");if(d!==void 0)l.next=y(d,"n");let u=R(n,"h");if(u!==void 0)l.head=A(u,"h");return l}if(i!==void 0||s!==void 0)return{kind:"changes",epoch:o,version:t,upserts:Z(i,"u"),deletes:Ge(s,"x"),more:J(n,"m")};return{kind:"nothing-new",epoch:o,version:t}}function Xn(e){if(!Array.isArray(e)||e.length<4||e.length>5)throw g("a sync entry is [capability, schema, epoch, version, resume?]");let n=e,t={capability:y(n[0],"a sync entry's capability"),schema:A(n[1],"a sync entry's schema",de),epoch:y(n[2],"a sync entry's epoch"),version:A(n[3],"a sync entry's version")};if(n.length===5)t.resume=y(n[4],"a sync entry's resume key");return t}function $t(e){let n=C(e,"a sync request"),t=E(n,"c","a sync request");if(!Array.isArray(t))throw g("c must be an array of sync entries");let r={entries:t.map(Xn)},o=R(n,"origin");if(o!==void 0)r.origin=y(o,"origin");return r}function jn(e){if(e===0)return{kind:"nothing-new"};if(!We(e))throw g("a sync answer is 0, a changes object, a full copy or an error");if("err"in e){let t=In.find((r)=>r===e.err);if(t===void 0)throw g("err must be a known error code");return{kind:"error",code:t}}let n=A(E(e,"v","a sync answer"),"v");if(J(e,"f")){let t={kind:"full-copy",epoch:y(E(e,"e","a sync answer"),"e"),version:n,rows:Z(R(e,"u"),"u")},r=R(e,"n");if(r!==void 0)t.next=y(r,"n");return t}return{kind:"changes",version:n,upserts:Z(R(e,"u"),"u"),deletes:Ge(R(e,"x"),"x"),more:J(e,"m")}}function Ot(e){let n=E(C(e,"a sync reply"),"r","a sync reply");if(!Array.isArray(n))throw g("r must be an array of answers");return{answers:n.map(jn)}}function _t(e){let n=C(e,"an announce");return{capability:y(E(n,"c","an announce"),"c"),epoch:y(E(n,"e","an announce"),"e"),version:A(E(n,"v","an announce"),"v")}}function Ke(e){let n=C(e,"an announce reply"),t=(i)=>{let s=R(n,i);if(s===void 0)return!1;if(typeof s!=="boolean")throw g(`${i} must be a boolean`);return s},r=t("rotate"),o=t("ok");if(r)return"rotate";if(o)return"ok";throw g('an announce reply is {"ok":true} or {"rotate":true}')}function Mt(e){let n=E(C(e,"replica.heads data"),"h","replica.heads data");if(!Array.isArray(n))throw g("h must be an array of heads");return{heads:n.map((t)=>{if(!Array.isArray(t)||t.length!==3)throw g("a pushed head is [capability, epoch, version]");let r=t;return{capability:y(r[0],"a head's capability"),epoch:y(r[1],"a head's epoch"),version:A(r[2],"a head's version")}})}}var Je=2592000000,Ze=5000,Qe=60000,Re={maxAgeMs:Je,maxCount:Ze};function _(e){return{epoch:e.epoch,version:e.version}}function X(e,n){return e.epoch===n.epoch&&e.version===n.version}function ve(e){return e.map((n)=>({row:n,digest:re(n)}))}function re(e){let n=Q(e.key);if(n!==null)throw c.row(e.key,n);let t,r;try{({digest:t,valueBytes:r}=ue(e))}catch(i){if(i instanceof k)throw c.row(e.key,i.message);throw i}if(r>he)throw c.row(e.key,`value is ${r} bytes encoded; at most ${he} are allowed`);if(!Number.isInteger(e.ord)||Math.abs(e.ord)>I)throw c.row(e.key,"ord must be within \xB1(2^53 - 1)");if(typeof e.part!=="string")throw c.row(e.key,"part must be a string");let o=O(e.part);if(o>fe)throw c.row(e.key,`part is ${o} bytes; at most ${fe} are allowed`);if(q(e.part))throw c.row(e.key,"part must not contain a lone surrogate");return t}function en(e,n){for(let t=0;t<4;t+=1){let r=e.env.newEpoch();if(!me(r))throw c.store("the environment produced an epoch outside [a-z0-9]{1,16}");if(r!==n)return r}throw c.store("the environment keeps producing the current epoch")}function te(e,n,t){if(t.rotateOwed)U(e,n,t);if(t.version>=I)throw c.store(`version of ${t.epoch} would pass 2^53 - 1`);return t.version+=1,t.version}function nn(e,n){let t=e.record(n.name);if(t!==null)return t;let r={epoch:en(n,null),version:0,floor:0,dirty:!0,rotatedAt:n.env.nowMs(),reconciledAt:0,rotateOwed:!1};return e.putRecord(n.name,r),r}function be(e,n){let t=e.env.nowMs();return n.rotatedAt===0||t<n.rotatedAt||t-n.rotatedAt>=Qe}function Ee(e,n,t){if(be(n,t))return U(e,n,t),!0;return t.rotateOwed=!0,!1}function tn(e,n,t,r){if(r||t.rotateOwed&&be(n,t))return U(e,n,t),!0;return!1}function rn(e,n){return!(n.rotateOwed&&be(e,n))}function U(e,n,t){let r=n.env.nowMs(),o=0;for(let i of e.entries(n.name)){if(i.deleted){e.deleteEntry(n.name,i.key);continue}o+=1,e.putEntry(n.name,{...i,version:o,changedAt:r})}t.epoch=en(n,t.epoch),t.version=o,t.floor=0,t.rotatedAt=r,t.rotateOwed=!1}function on(e,n,t,r,o,i){let s=e.entry(n.name,r.key);if(s!==null&&!s.deleted&&s.digest===o)return!1;let l=te(e,n,t);return e.putEntry(n.name,{key:r.key,digest:o,version:l,deleted:!1,changedAt:i}),!0}function sn(e,n,t,r,o){let i=e.entry(n.name,r);if(i===null||i.deleted)return!1;let s=te(e,n,t);return e.putEntry(n.name,{key:r,digest:i.digest,version:s,deleted:!0,changedAt:o}),!0}function xe(e,n,t,r){let o=e.pruneTombstones(n.name,Math.max(0,r-n.horizon.maxAgeMs),n.horizon.maxCount);if(o.highest!==null)t.floor=Math.max(t.floor,o.highest);if(o.overKeep)Ee(e,n,t)}function ke(e,n,t,r){let o=n.env.nowMs(),i=[...r];i.sort((a,f)=>L(a.row.key,f.row.key));for(let a=1;a<i.length;a+=1){let f=i[a-1],h=i[a];if(f!==void 0&&h!==void 0&&f.row.key===h.row.key)throw c.row(f.row.key,"the key appears twice in the list")}let s=e.entries(n.name),l=[],d=[],u=0;for(let a of i){while(u<s.length&&L(D(s,u).key,a.row.key)<0){let h=D(s,u);if(!h.deleted)d.push(h);u+=1}let f=!1;if(u<s.length&&D(s,u).key===a.row.key){let h=D(s,u);f=!h.deleted&&h.digest===a.digest,u+=1}if(!f)l.push(a)}for(;u<s.length;u+=1){let a=D(s,u);if(!a.deleted)d.push(a)}for(let{row:a,digest:f}of l){let h=te(e,n,t);e.putEntry(n.name,{key:a.key,digest:f,version:h,deleted:!1,changedAt:o})}for(let a of d){let f=te(e,n,t);e.putEntry(n.name,{key:a.key,digest:a.digest,version:f,deleted:!0,changedAt:o})}xe(e,n,t,o),t.dirty=!1,t.reconciledAt=o}function D(e,n){let t=e[n];if(t===void 0)throw c.store("ledger index out of range");return t}function cn(e,n,t,{row:r,digest:o}){let i=n.env.nowMs();on(e,n,t,r,o,i),xe(e,n,t,i)}function an(e,n,t,r){let o=Q(r);if(o!==null)throw c.row(r,o);let i=n.env.nowMs();sn(e,n,t,r,i),xe(e,n,t,i)}function H(e,n,t,r,o){return{kind:"full-copy",version:r,entries:e.liveAfter(n.name,t,o)}}function Yn(e,n,t,r){let o=ye(r)+1;if(r.epoch!==t.epoch)return H(e,n,null,t.version,o);if(r.version>t.version)return U(e,n,t),H(e,n,null,t.version,o);if(r.resume!==void 0){if(r.version>=t.floor)return H(e,n,r.resume,r.version,o);return H(e,n,null,t.version,o)}if(r.version<t.floor)return H(e,n,null,t.version,o);if(r.version===t.version)return{kind:"nothing-new"};return{kind:"changes",entries:e.changesAfter(n.name,r.version,o)}}function zn(e,n,t,r,o){let i=n.env.nowMs(),s=!1;for(let l of r){if(l.deleted)continue;let d=o.get(l.key);if(d===void 0)s=sn(e,n,t,l.key,i)||s;else{let u=re(d);if(u!==l.digest)s=on(e,n,t,d,u,i)||s}}return s}function Ae(e,n){if(!e.schemas.includes(n.schema))throw c.schema(e.name,n.schema);let t=Fe(n);if(t!==null)throw c.request(t)}function ln(e,n){let t;try{t=e(n)}catch(r){throw c.load(w(r))}return t.map(B)}function Te(e){return ve(ln(e,null))}function un(e,n,t,r,o,i){if(Ae(n,r),t.dirty)ke(e,n,t,i??Te(o));let s=ye(r),l=!1,d=0;for(;;){let u=l?H(e,n,null,t.version,s+1):Yn(e,n,t,r);if(u.kind==="nothing-new")return{kind:"nothing-new",epoch:t.epoch,version:t.version};let a=u.entries.slice(0,s),f=a.filter((S)=>!S.deleted).map((S)=>S.key),h=new Map;if(f.length>0){let S=new Set(f);for(let P of ln(o,f))if(S.has(P.key))h.set(P.key,P)}if(d<2&&zn(e,n,t,a,h)){d+=1;continue}let T=Vn(t,r,u,s,h);if(T!==null)return T;if(l)throw c.store("a full copy could not be built");l=!0}}function Vn(e,n,t,r,o){if(t.kind==="changes"){let a=[],f=0,h=!1;for(let m of t.entries){if(a.length===r){h=!0;break}let F=o.get(m.key),Ne=m.deleted?Xe(m.key):F!==void 0?we(F):0;if(a.length>0&&f+Ne>ge){h=!0;break}f+=Ne,a.push(m)}let T;if(h){let m=0;while(m<a.length&&a[m]?.version===n.version+m+1)m+=1;if(m===0)return null;a.length=m,T=n.version+m}else T=e.version;let S=[],P=[];for(let m of a){if(m.deleted){P.push(m.key);continue}let F=o.get(m.key);if(F!==void 0)S.push(F)}return{kind:"changes",epoch:e.epoch,version:T,upserts:S,deletes:P,more:h}}let i=[],s=0,l=null,d=!1;for(let a=0;a<t.entries.length;a+=1){let f=D(t.entries,a);if(a===r){d=!0;break}let h=o.get(f.key);if(h===void 0){l=f.key;continue}let T=we(h);if(a>0&&s+T>ge){d=!0;break}i.push(h),s+=T,l=f.key}let u={kind:"full-copy",epoch:e.epoch,version:t.version,rows:i};if(d&&l!==null)u.next=l;if(e.version>t.version)u.head=e.version;return u}function Le(e,n,t){if(e.readRecord!==void 0)return e.readRecord(n,t);let r=null;return e.write(n,(o)=>{r=o.record(t)}),r}function Gn(e){let n=new Map;for(let[t,r]of e.entries)n.set(t,{...r});return{record:e.record===null?null:{...e.record},entries:n}}function dn(e){let n=new Map;for(let[t,r]of e)n.set(t,Gn(r));return n}function hn(e){if(e===void 0)return[];return[...e.entries.values()].sort((n,t)=>L(n.key,t.key))}class fn{prefix;tables;undo=[];saved=new Set;constructor(e,n){this.prefix=e;this.tables=n}rollback(){for(let e=this.undo.length-1;e>=0;e-=1)this.undo[e]?.()}name(e){return`${this.prefix}\x00${e}`}get(e){return this.tables.get(this.name(e))}getMut(e){let n=this.name(e),t=this.tables.get(n);if(t===void 0)t={record:null,entries:new Map},this.tables.set(n,t),this.undo.push(()=>this.tables.delete(n));return t}saveRecord(e){let n=this.getMut(e),t=`r\x00${this.name(e)}`;if(!this.saved.has(t)){this.saved.add(t);let r=n.record;this.undo.push(()=>{n.record=r})}return n}saveEntry(e,n,t){let r=`e\x00${this.name(n)}\x00${t}`;if(this.saved.has(r))return;this.saved.add(r);let o=e.entries.get(t);this.undo.push(()=>{if(o===void 0)e.entries.delete(t);else e.entries.set(t,o)})}record(e){let n=this.get(e)?.record;return n?{...n}:null}putRecord(e,n){this.saveRecord(e).record={...n}}entry(e,n){let t=this.get(e)?.entries.get(n);return t?{...t}:null}entries(e){return hn(this.get(e)).map((n)=>({...n}))}putEntry(e,n){let t=this.getMut(e);this.saveEntry(t,e,n.key),t.entries.set(n.key,{...n})}deleteEntry(e,n){let t=this.getMut(e);this.saveEntry(t,e,n),t.entries.delete(n)}changesAfter(e,n,t){let r=this.get(e);if(r===void 0)return[];return[...r.entries.values()].filter((o)=>o.version>n).sort((o,i)=>o.version-i.version).slice(0,t).map((o)=>({...o}))}liveAfter(e,n,t){return hn(this.get(e)).filter((r)=>!r.deleted&&(n===null||L(r.key,n)>0)).slice(0,t).map((r)=>({...r}))}pruneTombstones(e,n,t){let r=this.getMut(e),o=r.entries,i=[...o.values()].filter((u)=>u.deleted).sort((u,a)=>u.version-a.version||u.changedAt-a.changedAt||L(u.key,a.key)),s=Math.max(0,i.length-t),l=null,d=0;return i.forEach((u,a)=>{if(a<s||u.changedAt<n)this.saveEntry(r,e,u.key),o.delete(u.key),l=l===null?u.version:Math.max(l,u.version);else d+=1}),{highest:l,overKeep:d>t}}}class Se{tables=new Map;ensure(){}write(e,n){let t=new fn(e,this.tables);try{n(t)}catch(r){throw t.rollback(),r}}readRecord(e,n){let t=this.tables.get(`${e}\x00${n}`)?.record;return t?{...t}:null}clone(){let e=new Se;return e.tables=dn(this.tables),e}restoreFrom(e){this.tables=dn(e.tables)}}var wn={nowMs:()=>Date.now(),newEpoch:Kn},pn="abcdefghijklmnopqrstuvwxyz0123456789",gn=0;function Kn(){let e=new Uint8Array(8),n=globalThis.crypto;if(n?.getRandomValues!==void 0)n.getRandomValues(e);else{gn+=1;let r=Date.now()+gn;for(let o=0;o<e.length;o+=1)e[o]=Math.floor(Math.random()*256)^r>>>o%4*8&255}let t="";for(let r of e)t+=pn.charAt(r%pn.length);return t}var Jn=16,Zn=/^[a-z][a-z0-9_-]*$/,Qn=/^(?:[A-Za-z_][A-Za-z0-9_]{0,47})?$/;class oe{store;name;tablePrefix;schemas;spec;announceFailing=!1;handedOutMarks=[];constructor(e,n,t={}){this.store=e;this.name=n,this.tablePrefix=t.tablePrefix??"",this.schemas=[...t.schemas??[1]],this.spec={name:n,schemas:this.schemas,env:t.env??wn,horizon:t.horizon??Re}}check(){let e=this.name.split(".");if(e.length<3||e[e.length-1]!=="pull"||!e.every((n)=>Zn.test(n)))throw c.config(`'${this.name}' is not a pull capability '<app>.<collection>.pull'`);if(this.name.startsWith("core."))throw c.config(`'${this.name}' is in the reserved 'core.' namespace`);if(!Qn.test(this.tablePrefix))throw c.config(`table prefix '${this.tablePrefix}' must be [A-Za-z_][A-Za-z0-9_]{0,47} or empty`);if(!(this.spec.horizon.maxCount>=1))throw c.config("the tombstone horizon must keep at least one tombstone");if(!this.schemas.every((n)=>Number.isInteger(n)&&n>=0&&n<=4294967295))throw c.config("schemas must be integers from 0 to 4294967295")}handedOut(e){return this.handedOutMarks.find(([n])=>n===e)?.[1]}noteHandedOut(e,n){let t=this.handedOutMarks.findIndex(([o])=>o===e),r=n;if(t>=0){let[o]=this.handedOutMarks.splice(t,1);if(o!==void 0)r=Math.max(o[1],n)}this.handedOutMarks.unshift([e,r]),this.handedOutMarks.length=Math.min(this.handedOutMarks.length,Jn)}wentBack(e){let n=this.handedOut(e.epoch);return n!==void 0&&n>e.version}withRecord(e){this.check();let n=null;if(this.store.write(this.tablePrefix,(t)=>{let r=nn(t,this.spec),o={...r},i=tn(t,this.spec,r,this.wentBack(r)),s=e(t,r,i);if(!yn(r,o))t.putRecord(this.spec.name,r);n={value:s}}),n===null)throw c.store("the store did not run the ledger work");return n.value}before(e){try{return e()}catch(n){return this.withRecord(()=>{throw n})}}readSettled(){this.check();let e=Le(this.store,this.tablePrefix,this.name);if(e===null||this.wentBack(e)||!rn(this.spec,e))return null;return e}ensure(){this.check(),this.store.ensure(this.tablePrefix)}reconcile(e){let n=e.map(B),t=this.before(()=>ve(n));return this.withRecord((r,o)=>{let i=_(o);return ke(r,this.spec,o,t),X(_(o),i)?null:o.version})}touch(e){let n=B(e),t=this.before(()=>({row:n,digest:re(n)}));return this.withRecord((r,o)=>(cn(r,this.spec,o,t),o.version))}remove(e){return this.withRecord((n,t)=>(an(n,this.spec,t,e),t.version))}markDirty(){this.withRecord((e,n)=>{n.dirty=!0})}reset(){return this.withRecord((e,n,t)=>{let r=t||Ee(e,this.spec,n);return n.dirty=!0,r})}head(){let e=this.readSettled();if(e!==null)return _(e);return this.withRecord((n,t)=>_(t))}answer(e,n){if(Ae(this.spec,e),e.resume===void 0){let s=this.readSettled();if(s!==null&&!s.dirty&&s.epoch===e.epoch&&s.version===e.version)return this.noteHandedOut(s.epoch,s.version),{reply:{kind:"nothing-new",epoch:s.epoch,version:s.version},headMoved:!1}}let t=Le(this.store,this.tablePrefix,this.name),r=t===null||t.dirty?this.before(()=>Te(n)):null,{answered:o,head:i}=this.withRecord((s,l,d)=>{let u=_(l),a=t===null?l.version===0:yn(l,t),f=un(s,this.spec,l,e,n,a?r:null),h=_(l);return{answered:{reply:f,headMoved:d||!X(h,u)},head:h}});return this.noteHandedOut(i.epoch,i.version),o}pull(e,n){return JSON.parse(ee(this.answer(ne(e),n).reply))}async announce(e){try{let n=await this.announceInner(e);return this.announceFailing=!1,n}catch(n){let t=!this.announceFailing;return this.announceFailing=!0,{kind:"failed",error:w(n),first:t}}}async announceInner(e){let n=this.head();if(await mn(this.name,n,e)==="ok")return this.noteHandedOut(n.epoch,n.version),{kind:"accepted",head:n};this.noteHandedOut(n.epoch,n.version+1);let t=this.withRecord((r,o,i)=>{if(!i&&o.epoch===n.epoch)U(r,this.spec,o);return _(o)});if(await mn(this.name,t,e)==="ok")return this.noteHandedOut(t.epoch,t.version),{kind:"rotated",head:t};return{kind:"rotation-deferred",head:t}}description(){return`Replicated collection served by @econ-v1/app-sdk/replica (Phase 3 contract). Request {"e":<epoch held, "" for none>,"v":<version held>,"s":<schema>,"l":<row limit, at most 500>,"a":<resume key, optional>}. Reply {"e","v"} when nothing is new; {"e","v","u":[[key,value,ord?,part?]...],"x":[key...],"m":1?} with the changes since v; or {"e","v","f":1,"u":[...],"n":<next key>?}, a full copy in key order. Schemas served: ${this.schemas.join(", ")}. Called by the node (core.replica.sync), not by devices.`}}function yn(e,n){return e.epoch===n.epoch&&e.version===n.version&&e.floor===n.floor&&e.dirty===n.dirty&&e.rotatedAt===n.rotatedAt&&e.reconciledAt===n.reconciledAt&&e.rotateOwed===n.rotateOwed}async function mn(e,n,t){let r=JSON.parse(Ve({capability:e,epoch:n.epoch,version:n.version})),o=await t(Ue,r);try{return Ke(o)}catch(i){throw Error(`unexpected announce reply: ${w(i)}`)}}var ie=2;function $e(e){return{meta:`${e}replica_meta`,collections:`${e}replica_collections`,rows:`${e}replica_rows`}}function et(e,n){e.exec(`CREATE TABLE IF NOT EXISTS ${n.collections} (
|
|
3
3
|
name TEXT PRIMARY KEY NOT NULL,
|
|
4
4
|
epoch TEXT NOT NULL,
|
|
5
5
|
version INTEGER NOT NULL DEFAULT 0,
|
|
@@ -15,17 +15,17 @@ var O={config:"replica_config_invalid:",row:"replica_row_invalid:",request:"repl
|
|
|
15
15
|
deleted INTEGER NOT NULL DEFAULT 0,
|
|
16
16
|
changed_at INTEGER NOT NULL,
|
|
17
17
|
PRIMARY KEY (collection, row_key)
|
|
18
|
-
)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_${n.rows}_version ON ${n.rows} (collection, version)`)}function
|
|
18
|
+
)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_${n.rows}_version ON ${n.rows} (collection, version)`)}function nt(e,n){e.exec(`ALTER TABLE ${n.collections} ADD COLUMN rotate_owed INTEGER NOT NULL DEFAULT 0`),e.exec(`CREATE INDEX IF NOT EXISTS idx_${n.rows}_tombstone_version ON ${n.rows} (collection, version)
|
|
19
19
|
WHERE deleted = 1`),e.exec(`CREATE INDEX IF NOT EXISTS idx_${n.rows}_tombstone_age ON ${n.rows} (collection, changed_at)
|
|
20
|
-
WHERE deleted = 1`)}var
|
|
20
|
+
WHERE deleted = 1`)}var tt=[nt];function V(e,n){if(typeof e==="number"&&Number.isSafeInteger(e))return e;if(typeof e==="bigint"&&e>=0n&&e<=BigInt(Number.MAX_SAFE_INTEGER))return Number(e);throw c.store(`${n} in the replica ledger is not an integer within 2^53 - 1: ${String(e)}`)}function M(e,n){let t=V(e,n);if(t<0)throw c.store(`negative ${t} in the replica ledger`);return t}function _e(e,n){if(typeof e!=="string")throw c.store(`${n} in the replica ledger is not text`);return e}function v(e,n){if(typeof e!=="object"||e===null)throw c.store("the replica ledger returned a non-row");return e[n]}var Rn="epoch, version, floor, dirty, rotated_at, reconciled_at, rotate_owed",j="row_key, digest, version, deleted, changed_at";function rt(e){return{epoch:_e(v(e,"epoch"),"an epoch"),version:M(v(e,"version"),"a version"),floor:M(v(e,"floor"),"a floor"),dirty:V(v(e,"dirty"),"dirty")!==0,rotatedAt:M(v(e,"rotated_at"),"rotated_at"),reconciledAt:M(v(e,"reconciled_at"),"reconciled_at"),rotateOwed:V(v(e,"rotate_owed"),"rotate_owed")!==0}}function Y(e){return{key:_e(v(e,"row_key"),"a row key"),digest:_e(v(e,"digest"),"a digest"),version:M(v(e,"version"),"a version"),deleted:V(v(e,"deleted"),"deleted")!==0,changedAt:M(v(e,"changed_at"),"changed_at")}}function Oe(e){try{return e()}catch(n){if(n instanceof c)throw n;throw c.store(w(n))}}class vn{store;t;constructor(e,n){this.store=e;this.t=n}q(e){return this.store.statement(e)}record(e){return this.store.readRecordIn(this.t,e)}putRecord(e,n){this.q(`INSERT INTO ${this.t.collections} (name, ${Rn})
|
|
21
21
|
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)
|
|
22
22
|
ON CONFLICT(name) DO UPDATE SET epoch = excluded.epoch, version = excluded.version,
|
|
23
23
|
floor = excluded.floor, dirty = excluded.dirty, rotated_at = excluded.rotated_at,
|
|
24
|
-
reconciled_at = excluded.reconciled_at, rotate_owed = excluded.rotate_owed`).run(e,n.epoch,n.version,n.floor,n.dirty?1:0,n.rotatedAt,n.reconciledAt,n.rotateOwed?1:0)}entry(e,n){let t=this.q(`SELECT ${
|
|
24
|
+
reconciled_at = excluded.reconciled_at, rotate_owed = excluded.rotate_owed`).run(e,n.epoch,n.version,n.floor,n.dirty?1:0,n.rotatedAt,n.reconciledAt,n.rotateOwed?1:0)}entry(e,n){let t=this.q(`SELECT ${j} FROM ${this.t.rows} WHERE collection = ?1 AND row_key = ?2`).get(e,n);return t===null||t===void 0?null:Y(t)}entries(e){return this.q(`SELECT ${j} FROM ${this.t.rows} WHERE collection = ?1 ORDER BY row_key`).all(e).map(Y)}putEntry(e,n){this.q(`INSERT INTO ${this.t.rows} (collection, row_key, digest, version, deleted, changed_at)
|
|
25
25
|
VALUES (?1, ?2, ?3, ?4, ?5, ?6)
|
|
26
26
|
ON CONFLICT(collection, row_key) DO UPDATE SET digest = excluded.digest,
|
|
27
|
-
version = excluded.version, deleted = excluded.deleted, changed_at = excluded.changed_at`).run(e,n.key,n.digest,n.version,n.deleted?1:0,n.changedAt)}deleteEntry(e,n){this.q(`DELETE FROM ${this.t.rows} WHERE collection = ?1 AND row_key = ?2`).run(e,n)}changesAfter(e,n,t){return this.q(`SELECT ${
|
|
28
|
-
ORDER BY version LIMIT ?3`).all(e,n,t).map(
|
|
29
|
-
ORDER BY row_key LIMIT ?2`).all(e,t).map(
|
|
30
|
-
AND row_key > ?2 ORDER BY row_key LIMIT ?3`).all(e,n,t).map(
|
|
31
|
-
ON CONFLICT(key) DO UPDATE SET value = excluded.value`).run(t),this.statements.clear()}write(e,n){let t
|
|
27
|
+
version = excluded.version, deleted = excluded.deleted, changed_at = excluded.changed_at`).run(e,n.key,n.digest,n.version,n.deleted?1:0,n.changedAt)}deleteEntry(e,n){this.q(`DELETE FROM ${this.t.rows} WHERE collection = ?1 AND row_key = ?2`).run(e,n)}changesAfter(e,n,t){return this.q(`SELECT ${j} FROM ${this.t.rows} WHERE collection = ?1 AND version > ?2
|
|
28
|
+
ORDER BY version LIMIT ?3`).all(e,n,t).map(Y)}liveAfter(e,n,t){if(n===null)return this.q(`SELECT ${j} FROM ${this.t.rows} WHERE collection = ?1 AND deleted = 0
|
|
29
|
+
ORDER BY row_key LIMIT ?2`).all(e,t).map(Y);return this.q(`SELECT ${j} FROM ${this.t.rows} WHERE collection = ?1 AND deleted = 0
|
|
30
|
+
AND row_key > ?2 ORDER BY row_key LIMIT ?3`).all(e,n,t).map(Y)}pruneTombstones(e,n,t){let r=this.t.rows,o=this.q(`SELECT MAX(version) AS highest FROM ${r} WHERE collection = ?1 AND deleted = 1 AND changed_at < ?2`).get(e,n),i=v(o,"highest"),s=i===null||i===void 0?null:M(i,"a version");if(s!==null)this.q(`DELETE FROM ${r} WHERE collection = ?1 AND deleted = 1 AND changed_at < ?2`).run(e,n);let l=this.q(`SELECT version FROM ${r} WHERE collection = ?1 AND deleted = 1 ORDER BY version DESC LIMIT 1 OFFSET ?2`).get(e,t),d=l===null||l===void 0?null:M(v(l,"version"),"a version");if(d!==null)this.q(`DELETE FROM ${r} WHERE collection = ?1 AND deleted = 1 AND version <= ?2`).run(e,d);return{highest:s===null?d:d===null?s:Math.max(s,d),overKeep:!1}}}var z="node_app_replica";class se{db;statements=new Map;constructor(e){this.db=e}statement(e){let n=this.statements.get(e);if(n===void 0)n=this.db.query(e),this.statements.set(e,n);return n}inTransaction(e){let n=this.begin(),t;try{t=e(),this.db.exec(n?`RELEASE ${z}`:"COMMIT")}catch(r){try{if(this.db.exec(n?`ROLLBACK TO ${z}`:"ROLLBACK"),n)this.db.exec(`RELEASE ${z}`)}catch{}if(r instanceof c)throw r;throw c.store(w(r))}return t}begin(){if(this.db.inTransaction===!0)return Oe(()=>this.db.exec(`SAVEPOINT ${z}`)),!0;try{return this.db.exec("BEGIN IMMEDIATE"),!1}catch(e){if(this.db.inTransaction===void 0&&this.insideAppTransaction())return Oe(()=>this.db.exec(`SAVEPOINT ${z}`)),!0;throw c.store(w(e))}}insideAppTransaction(){try{this.db.exec("BEGIN DEFERRED")}catch{return!0}try{this.db.exec("ROLLBACK")}catch{}return!1}ensure(e){let n=$e(e);this.inTransaction(()=>this.bringUp(n))}bringUp(e){this.db.exec(`CREATE TABLE IF NOT EXISTS ${e.meta} (key TEXT PRIMARY KEY NOT NULL, value INTEGER NOT NULL)`);let n=this.db.query(`SELECT value FROM ${e.meta} WHERE key = 'layout'`).get(),t;if(n!==null&&n!==void 0)t=V(v(n,"value"),"the layout");else if(this.db.query("SELECT 1 AS found FROM sqlite_master WHERE type = 'table' AND name = ?1").get(e.collections))t=1;else et(this.db,e),t=1;if(t<1||t>ie)throw c.store(`the replica ledger's layout is ${t}; this helper knows layouts 1 to ${ie}`);while(t<ie){let r=tt[t-1];if(r===void 0)throw c.store(`no upgrade from layout ${t}`);r(this.db,e),t+=1}this.db.query(`INSERT INTO ${e.meta} (key, value) VALUES ('layout', ?1)
|
|
31
|
+
ON CONFLICT(key) DO UPDATE SET value = excluded.value`).run(t),this.statements.clear()}write(e,n){let t=$e(e);this.inTransaction(()=>n(new vn(this,t)))}readRecordIn(e,n){let t=this.statement(`SELECT ${Rn} FROM ${e.collections} WHERE name = ?1`).get(n);return t===null||t===void 0?null:rt(t)}readRecord(e,n){return Oe(()=>this.readRecordIn($e(e),n))}}function ot(e){return typeof e.write==="function"&&typeof e.ensure==="function"}var bn=0;function Jt(e,n=5000){return async(t,r)=>{bn+=1;let o=`replica-${Date.now().toString(36)}-${bn.toString(36)}`,i=await e({id:o,capability:t,payload:r},n);if(!i.success)throw Error(w(i.payload));return i.payload}}var it=2000,st=60000;class Me{firstMs;maxMs;job;timer=null;delay;stopped=!1;constructor(e,n,t){this.firstMs=e;this.maxMs=n;this.job=t;this.delay=e}failed(){if(this.stopped||this.timer!==null)return;this.timer=setTimeout(()=>{this.timer=null,this.job()},this.delay),this.delay=Math.min(this.delay*2,this.maxMs)}succeeded(){this.cancel(),this.delay=this.firstMs}pending(){return this.timer!==null}cancel(){if(this.timer!==null)clearTimeout(this.timer);this.timer=null}stop(){this.stopped=!0,this.cancel()}}class En{ledger;options;invoke;warn;coalesceMs;name;timer=null;announcing=null;announceAgain=!1;announced=null;reconcileFailing=!1;reconcileRetry;announceRetry;constructor(e,n,t,r,o,i){this.ledger=e;this.options=n;this.invoke=t;this.warn=r;this.coalesceMs=o;this.name=e.name,this.reconcileRetry=new Me(i.firstMs,i.maxMs,()=>this.reconcileNow()),this.announceRetry=new Me(i.firstMs,i.maxMs,()=>void this.announce())}load(e){if(e===null)return this.options.list();if(this.options.get!==void 0)return this.options.get(e);let n=new Set(e);return this.options.list().filter((t)=>n.has(t.key))}changed(){try{this.ledger.markDirty()}catch(e){this.warn(`replica: ${this.name}: ${w(e)}`)}if(this.timer!==null)return;this.timer=setTimeout(()=>{this.timer=null,this.reconcileNow()},this.coalesceMs)}reconcileNow(){try{this.ledger.reconcile(this.options.list())}catch(e){if(!this.reconcileFailing)this.warn(`replica: reconciling ${this.name} failed (retrying with backoff): ${w(e)}`);this.reconcileFailing=!0,this.reconcileRetry.failed();return}this.reconcileFailing=!1,this.reconcileRetry.succeeded(),this.afterWrite()}touch(e){this.ledger.touch(e),this.afterWrite()}remove(e){this.ledger.remove(e),this.afterWrite()}reset(){this.ledger.reset(),this.afterWrite(),this.changed()}head(){return this.ledger.head()}afterWrite(){let e;try{e=this.ledger.head()}catch(n){this.warn(`replica: ${this.name}: ${w(n)}`),this.announceRetry.failed();return}if(this.announced===null||!X(e,this.announced))this.announce()}announce(){if(this.announceAgain=!0,this.announcing===null)this.announcing=this.runAnnounces();return this.announcing}async runAnnounces(){try{await Promise.resolve();while(this.announceAgain){this.announceAgain=!1;try{this.note(await this.ledger.announce(this.invoke))}catch(e){this.warn(`replica: announcing ${this.name} failed: ${w(e)}`),this.announceRetry.failed()}}}finally{this.announcing=null}}note(e){switch(e.kind){case"accepted":case"rotated":this.announced=e.head,this.announceRetry.succeeded();return;case"rotation-deferred":this.announced=null,this.announceRetry.failed();return;case"failed":if(e.first)this.warn(`replica: announcing ${this.name} failed (retrying with backoff; until an announce lands the node answers "nothing new" from the head it remembers, so devices do not see the change; an older node has no core.replica.announce): ${e.error}`);this.announceRetry.failed();return}}retrying(){return this.reconcileRetry.pending()||this.announceRetry.pending()}async flush(){if(this.timer!==null)clearTimeout(this.timer),this.timer=null,this.reconcileNow();while(this.announcing!==null)await this.announcing}stop(){if(this.timer!==null)clearTimeout(this.timer);this.timer=null,this.reconcileRetry.stop(),this.announceRetry.stop()}}class ct{invoke;options;store;collections=new Map;tablePrefix;warn;constructor(e,n,t={}){this.invoke=n;this.options=t;this.store=ot(e)?e:new se(e),this.tablePrefix=t.tablePrefix??"",this.warn=t.warn??((r)=>console.warn(r))}collection(e,n){if(this.collections.has(e))throw c.config(`'${e}' is declared twice`);let t={tablePrefix:this.tablePrefix,schemas:n.schemas??[1],...this.options.env===void 0?{}:{env:this.options.env},...this.options.horizon===void 0?{}:{horizon:this.options.horizon}},r=new oe(this.store,e,t);r.ensure();let o={firstMs:this.options.retry?.firstMs??it,maxMs:this.options.retry?.maxMs??st},i=new En(r,n,this.invoke,this.warn,this.options.coalesceMs??50,o);return this.collections.set(e,i),i}provides(){return[...this.collections.values()].map((e)=>({name:e.name,description:e.ledger.description()}))}handles(e){return this.collections.has(e)}handle(e,n){try{let t=this.collections.get(e);if(t===void 0)throw c.request(`${e} is not a replicated collection of this app`);let r=t.ledger.answer(ne(n),(o)=>t.load(o));if(r.headMoved)t.announce();return Promise.resolve(JSON.parse(ee(r.reply)))}catch(t){return Promise.reject(t instanceof Error?t:Error(w(t)))}}async start(){await Promise.all([...this.collections.values()].map((e)=>e.announce()))}async flush(){await Promise.all([...this.collections.values()].map((e)=>e.flush()))}retrying(){return[...this.collections.values()].some((e)=>e.retrying())}stop(){for(let e of this.collections.values())e.stop()}}export{Ue as ANNOUNCE_CAPABILITY,oe as CollectionLedger,Re as DEFAULT_HORIZON,ie as LEDGER_LAYOUT,ft as MAX_EPOCH_CHARS,He as MAX_KEY_BYTES,fe as MAX_PART_BYTES,ge as MAX_REPLY_ROW_BYTES,pe as MAX_ROWS_PER_REPLY,I as MAX_SAFE_INTEGER,pt as MAX_SYNC_ENTRIES,gt as MAX_SYNC_REPLY_BYTES,he as MAX_VALUE_BYTES,G as MAX_VALUE_DEPTH,Se as MemoryLedger,N as REPLICA_ERROR_PREFIXES,Qe as ROTATION_MIN_INTERVAL_MS,ct as Replica,c as ReplicaError,mt as SCHEMA_UNSUPPORTED_PREFIX,yt as SYNC_CAPABILITY,se as SqliteLedgerStore,Je as TOMBSTONE_MAX_AGE_MS,Ze as TOMBSTONE_MAX_COUNT,K as canonicalJson,Hn as canonicalValue,L as compareUtf8,_t as decodeAnnounce,Ke as decodeAnnounceReply,Mt as decodeHeadsData,St as decodePullReply,ne as decodePullRequest,Bn as decodeRow,jn as decodeSyncAnswer,Xn as decodeSyncEntry,Ot as decodeSyncReply,$t as decodeSyncRequest,ye as effectiveLimit,Ve as encodeAnnounce,Tt as encodeAnnounceReply,Lt as encodeHeadsData,ee as encodePullReply,xt as encodePullRequest,Be as encodeRow,qn as encodeSyncAnswer,Fn as encodeSyncEntry,At as encodeSyncReply,kt as encodeSyncRequest,Xe as encodedDeleteBytes,we as encodedRowBytes,Cn as fnv1a64,Rt as handedOut,Jt as hostInvoke,wt as initialPullRequest,me as isEpoch,vt as isTruncated,Tn as isWithinValueDepth,Q as keyProblem,bt as pullRequestOf,Fe as pullRequestProblem,Pn as rowDigest,Et as syncAnswerOf,wn as systemEnvironment,B as toRow,O as utf8Length};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@econ-v1/app-sdk",
|
|
3
|
-
"version": "7.7.
|
|
3
|
+
"version": "7.7.7",
|
|
4
4
|
"description": "TypeScript SDK for building Node mini-app plugins (Bun runtime) on the Lightning-powered marketplace daemon",
|
|
5
5
|
"license": "MIT OR Apache-2.0",
|
|
6
6
|
"author": "Node contributors",
|