@loro-dev/flock-sqlite 0.7.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +60 -0
- package/dist/index.cjs +4 -4
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.mts +47 -7
- package/dist/index.d.ts +47 -7
- package/dist/index.mjs +4 -4
- package/dist/index.mjs.map +1 -1
- package/package.json +4 -4
- package/src/event-batcher.ts +189 -0
- package/src/index.ts +375 -203
- package/src/lru.ts +74 -0
- package/src/multi-tab-env.ts +79 -0
- package/src/multi-tab.ts +107 -0
- package/src/types.ts +5 -0
- package/src/write-coordinator.ts +468 -0
package/dist/index.d.mts
CHANGED
|
@@ -85,6 +85,7 @@ type ScanRow = {
|
|
|
85
85
|
type EventPayload = ExportPayload;
|
|
86
86
|
type Event = {
|
|
87
87
|
key: KeyPart[];
|
|
88
|
+
clock: EntryClock;
|
|
88
89
|
value?: Value;
|
|
89
90
|
metadata?: MetadataMap;
|
|
90
91
|
payload: EventPayload;
|
|
@@ -93,6 +94,7 @@ type EventBatch = {
|
|
|
93
94
|
source: string;
|
|
94
95
|
events: Event[];
|
|
95
96
|
};
|
|
97
|
+
type FlockSQLiteRole = "host" | "participant" | "unknown";
|
|
96
98
|
type ExportOptions = {
|
|
97
99
|
from?: VersionVector$1;
|
|
98
100
|
hooks?: ExportHooks;
|
|
@@ -117,6 +119,26 @@ type PutWithMetaOptions = {
|
|
|
117
119
|
hooks?: PutHooks;
|
|
118
120
|
};
|
|
119
121
|
type EventListener = (batch: EventBatch) => void;
|
|
122
|
+
type RoleChangeListener = (role: FlockSQLiteRole) => void;
|
|
123
|
+
//#endregion
|
|
124
|
+
//#region src/multi-tab-env.d.ts
|
|
125
|
+
type FlockTransport = {
|
|
126
|
+
postMessage(message: unknown): void;
|
|
127
|
+
subscribe(onMessage: (message: unknown) => void): () => void;
|
|
128
|
+
close?: () => void;
|
|
129
|
+
};
|
|
130
|
+
type FlockTransportFactory = (name: string) => FlockTransport | undefined;
|
|
131
|
+
type FlockRoleProvider = {
|
|
132
|
+
getRole(): FlockSQLiteRole;
|
|
133
|
+
subscribeRoleChange?: (listener: (role: FlockSQLiteRole) => void) => () => void;
|
|
134
|
+
};
|
|
135
|
+
type TimeoutHandle = unknown;
|
|
136
|
+
type FlockRuntime = {
|
|
137
|
+
now(): number;
|
|
138
|
+
setTimeout(fn: () => void, ms: number): TimeoutHandle;
|
|
139
|
+
clearTimeout(handle: TimeoutHandle): void;
|
|
140
|
+
randomUUID(): string;
|
|
141
|
+
};
|
|
120
142
|
//#endregion
|
|
121
143
|
//#region src/index.d.ts
|
|
122
144
|
interface VersionVector extends VersionVector$1 {}
|
|
@@ -127,6 +149,16 @@ type FlockSQLiteOptions = {
|
|
|
127
149
|
peerId?: string;
|
|
128
150
|
connection?: UniStoreConnection;
|
|
129
151
|
tablePrefix?: string;
|
|
152
|
+
/**
|
|
153
|
+
* Advanced: Inject multi-tab environment dependencies.
|
|
154
|
+
* Defaults to BroadcastChannel + UniSQLite role + real timers when available.
|
|
155
|
+
*/
|
|
156
|
+
multiTab?: {
|
|
157
|
+
transportFactory?: FlockTransportFactory;
|
|
158
|
+
roleProvider?: FlockRoleProvider;
|
|
159
|
+
runtime?: FlockRuntime;
|
|
160
|
+
tabId?: string;
|
|
161
|
+
};
|
|
130
162
|
};
|
|
131
163
|
declare class FlockSQLite {
|
|
132
164
|
private db;
|
|
@@ -135,23 +167,29 @@ declare class FlockSQLite {
|
|
|
135
167
|
private maxHlc;
|
|
136
168
|
private listeners;
|
|
137
169
|
private tables;
|
|
138
|
-
|
|
139
|
-
private
|
|
140
|
-
|
|
141
|
-
private
|
|
170
|
+
private readonly runtime;
|
|
171
|
+
private readonly eventBatcher;
|
|
172
|
+
private readonly coordinator;
|
|
173
|
+
private readonly seenCommitIds;
|
|
174
|
+
private closed;
|
|
142
175
|
private constructor();
|
|
143
176
|
static open(options: FlockSQLiteOptions): Promise<FlockSQLite>;
|
|
144
177
|
static fromJson(options: FlockSQLiteOptions & {
|
|
145
178
|
bundle: ExportBundle;
|
|
146
179
|
}): Promise<FlockSQLite>;
|
|
147
180
|
close(): Promise<void>;
|
|
181
|
+
getRole(): FlockSQLiteRole;
|
|
182
|
+
isHost(): boolean;
|
|
183
|
+
subscribeRoleChange(listener: RoleChangeListener): () => void;
|
|
184
|
+
private dispatchWriteRequest;
|
|
185
|
+
private applyCommit;
|
|
186
|
+
private executeWriteRequest;
|
|
148
187
|
private static ensureSchema;
|
|
149
188
|
private static resolvePeerId;
|
|
150
189
|
private static loadVersionState;
|
|
151
190
|
private bumpVersion;
|
|
152
191
|
private allocateClock;
|
|
153
192
|
private applyOperation;
|
|
154
|
-
private resetDebounceTimer;
|
|
155
193
|
private emitEvents;
|
|
156
194
|
put(key: KeyPart[], value: Value, now?: number): Promise<void>;
|
|
157
195
|
putWithMeta(key: KeyPart[], value: Value, options?: PutWithMetaOptions): Promise<void>;
|
|
@@ -173,6 +211,7 @@ declare class FlockSQLite {
|
|
|
173
211
|
forceDelete(key: KeyPart[], now?: number): Promise<void>;
|
|
174
212
|
set(key: KeyPart[], value: Value, now?: number): Promise<void>;
|
|
175
213
|
setPeerId(peerId: string): Promise<void>;
|
|
214
|
+
private setPeerIdInternal;
|
|
176
215
|
get(key: KeyPart[]): Promise<Value | undefined>;
|
|
177
216
|
/**
|
|
178
217
|
* Returns the full entry payload (data, metadata, and clock) for a key.
|
|
@@ -185,6 +224,7 @@ declare class FlockSQLite {
|
|
|
185
224
|
getEntry(key: KeyPart[]): Promise<EntryInfo | undefined>;
|
|
186
225
|
getMvr(key: KeyPart[]): Promise<Value[]>;
|
|
187
226
|
putMvr(key: KeyPart[], value: Value, now?: number): Promise<void>;
|
|
227
|
+
private putMvrInternal;
|
|
188
228
|
private buildScanBounds;
|
|
189
229
|
scan(options?: ScanOptions): Promise<ScanRow[]>;
|
|
190
230
|
/**
|
|
@@ -210,7 +250,7 @@ declare class FlockSQLite {
|
|
|
210
250
|
exportJson(from: VersionVector): Promise<ExportBundle>;
|
|
211
251
|
exportJson(from: VersionVector, pruneTombstonesBefore: number): Promise<ExportBundle>;
|
|
212
252
|
exportJson(options: ExportOptions): Promise<ExportBundle>;
|
|
213
|
-
private
|
|
253
|
+
private importBundleInternal;
|
|
214
254
|
importJson(bundle: ExportBundle): Promise<ImportReport>;
|
|
215
255
|
importJson(options: ImportOptions): Promise<ImportReport>;
|
|
216
256
|
importJsonStr(json: string): Promise<ImportReport>;
|
|
@@ -293,5 +333,5 @@ declare class FlockSQLite {
|
|
|
293
333
|
isAutoDebounceActive(): boolean;
|
|
294
334
|
}
|
|
295
335
|
//#endregion
|
|
296
|
-
export { type EntryInfo, type Event, type EventBatch, type EventListener, type ExportBundle, type ExportHooks, type ExportOptions, type ExportPayload, type ExportRecord, FlockSQLite as Flock, FlockSQLite, FlockSQLiteOptions, type ImportHooks, type ImportOptions, type ImportReport, type KeyPart, type MetadataMap, type PutHooks, type PutWithMetaOptions, type ScanBound, type ScanOptions, type ScanRow, type Value, VersionVector, type VersionVectorEntry, decodeVersionVector, encodeVersionVector };
|
|
336
|
+
export { type EntryInfo, type Event, type EventBatch, type EventListener, type ExportBundle, type ExportHooks, type ExportOptions, type ExportPayload, type ExportRecord, FlockSQLite as Flock, FlockSQLite, type FlockRoleProvider, type FlockRuntime, FlockSQLiteOptions, type FlockSQLiteRole, type FlockTransport, type FlockTransportFactory, type ImportHooks, type ImportOptions, type ImportReport, type KeyPart, type MetadataMap, type PutHooks, type PutWithMetaOptions, type RoleChangeListener, type ScanBound, type ScanOptions, type ScanRow, type TimeoutHandle, type Value, VersionVector, type VersionVectorEntry, decodeVersionVector, encodeVersionVector };
|
|
297
337
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.d.ts
CHANGED
|
@@ -85,6 +85,7 @@ type ScanRow = {
|
|
|
85
85
|
type EventPayload = ExportPayload;
|
|
86
86
|
type Event = {
|
|
87
87
|
key: KeyPart[];
|
|
88
|
+
clock: EntryClock;
|
|
88
89
|
value?: Value;
|
|
89
90
|
metadata?: MetadataMap;
|
|
90
91
|
payload: EventPayload;
|
|
@@ -93,6 +94,7 @@ type EventBatch = {
|
|
|
93
94
|
source: string;
|
|
94
95
|
events: Event[];
|
|
95
96
|
};
|
|
97
|
+
type FlockSQLiteRole = "host" | "participant" | "unknown";
|
|
96
98
|
type ExportOptions = {
|
|
97
99
|
from?: VersionVector$1;
|
|
98
100
|
hooks?: ExportHooks;
|
|
@@ -117,6 +119,26 @@ type PutWithMetaOptions = {
|
|
|
117
119
|
hooks?: PutHooks;
|
|
118
120
|
};
|
|
119
121
|
type EventListener = (batch: EventBatch) => void;
|
|
122
|
+
type RoleChangeListener = (role: FlockSQLiteRole) => void;
|
|
123
|
+
//#endregion
|
|
124
|
+
//#region src/multi-tab-env.d.ts
|
|
125
|
+
type FlockTransport = {
|
|
126
|
+
postMessage(message: unknown): void;
|
|
127
|
+
subscribe(onMessage: (message: unknown) => void): () => void;
|
|
128
|
+
close?: () => void;
|
|
129
|
+
};
|
|
130
|
+
type FlockTransportFactory = (name: string) => FlockTransport | undefined;
|
|
131
|
+
type FlockRoleProvider = {
|
|
132
|
+
getRole(): FlockSQLiteRole;
|
|
133
|
+
subscribeRoleChange?: (listener: (role: FlockSQLiteRole) => void) => () => void;
|
|
134
|
+
};
|
|
135
|
+
type TimeoutHandle = unknown;
|
|
136
|
+
type FlockRuntime = {
|
|
137
|
+
now(): number;
|
|
138
|
+
setTimeout(fn: () => void, ms: number): TimeoutHandle;
|
|
139
|
+
clearTimeout(handle: TimeoutHandle): void;
|
|
140
|
+
randomUUID(): string;
|
|
141
|
+
};
|
|
120
142
|
//#endregion
|
|
121
143
|
//#region src/index.d.ts
|
|
122
144
|
interface VersionVector extends VersionVector$1 {}
|
|
@@ -127,6 +149,16 @@ type FlockSQLiteOptions = {
|
|
|
127
149
|
peerId?: string;
|
|
128
150
|
connection?: UniStoreConnection;
|
|
129
151
|
tablePrefix?: string;
|
|
152
|
+
/**
|
|
153
|
+
* Advanced: Inject multi-tab environment dependencies.
|
|
154
|
+
* Defaults to BroadcastChannel + UniSQLite role + real timers when available.
|
|
155
|
+
*/
|
|
156
|
+
multiTab?: {
|
|
157
|
+
transportFactory?: FlockTransportFactory;
|
|
158
|
+
roleProvider?: FlockRoleProvider;
|
|
159
|
+
runtime?: FlockRuntime;
|
|
160
|
+
tabId?: string;
|
|
161
|
+
};
|
|
130
162
|
};
|
|
131
163
|
declare class FlockSQLite {
|
|
132
164
|
private db;
|
|
@@ -135,23 +167,29 @@ declare class FlockSQLite {
|
|
|
135
167
|
private maxHlc;
|
|
136
168
|
private listeners;
|
|
137
169
|
private tables;
|
|
138
|
-
|
|
139
|
-
private
|
|
140
|
-
|
|
141
|
-
private
|
|
170
|
+
private readonly runtime;
|
|
171
|
+
private readonly eventBatcher;
|
|
172
|
+
private readonly coordinator;
|
|
173
|
+
private readonly seenCommitIds;
|
|
174
|
+
private closed;
|
|
142
175
|
private constructor();
|
|
143
176
|
static open(options: FlockSQLiteOptions): Promise<FlockSQLite>;
|
|
144
177
|
static fromJson(options: FlockSQLiteOptions & {
|
|
145
178
|
bundle: ExportBundle;
|
|
146
179
|
}): Promise<FlockSQLite>;
|
|
147
180
|
close(): Promise<void>;
|
|
181
|
+
getRole(): FlockSQLiteRole;
|
|
182
|
+
isHost(): boolean;
|
|
183
|
+
subscribeRoleChange(listener: RoleChangeListener): () => void;
|
|
184
|
+
private dispatchWriteRequest;
|
|
185
|
+
private applyCommit;
|
|
186
|
+
private executeWriteRequest;
|
|
148
187
|
private static ensureSchema;
|
|
149
188
|
private static resolvePeerId;
|
|
150
189
|
private static loadVersionState;
|
|
151
190
|
private bumpVersion;
|
|
152
191
|
private allocateClock;
|
|
153
192
|
private applyOperation;
|
|
154
|
-
private resetDebounceTimer;
|
|
155
193
|
private emitEvents;
|
|
156
194
|
put(key: KeyPart[], value: Value, now?: number): Promise<void>;
|
|
157
195
|
putWithMeta(key: KeyPart[], value: Value, options?: PutWithMetaOptions): Promise<void>;
|
|
@@ -173,6 +211,7 @@ declare class FlockSQLite {
|
|
|
173
211
|
forceDelete(key: KeyPart[], now?: number): Promise<void>;
|
|
174
212
|
set(key: KeyPart[], value: Value, now?: number): Promise<void>;
|
|
175
213
|
setPeerId(peerId: string): Promise<void>;
|
|
214
|
+
private setPeerIdInternal;
|
|
176
215
|
get(key: KeyPart[]): Promise<Value | undefined>;
|
|
177
216
|
/**
|
|
178
217
|
* Returns the full entry payload (data, metadata, and clock) for a key.
|
|
@@ -185,6 +224,7 @@ declare class FlockSQLite {
|
|
|
185
224
|
getEntry(key: KeyPart[]): Promise<EntryInfo | undefined>;
|
|
186
225
|
getMvr(key: KeyPart[]): Promise<Value[]>;
|
|
187
226
|
putMvr(key: KeyPart[], value: Value, now?: number): Promise<void>;
|
|
227
|
+
private putMvrInternal;
|
|
188
228
|
private buildScanBounds;
|
|
189
229
|
scan(options?: ScanOptions): Promise<ScanRow[]>;
|
|
190
230
|
/**
|
|
@@ -210,7 +250,7 @@ declare class FlockSQLite {
|
|
|
210
250
|
exportJson(from: VersionVector): Promise<ExportBundle>;
|
|
211
251
|
exportJson(from: VersionVector, pruneTombstonesBefore: number): Promise<ExportBundle>;
|
|
212
252
|
exportJson(options: ExportOptions): Promise<ExportBundle>;
|
|
213
|
-
private
|
|
253
|
+
private importBundleInternal;
|
|
214
254
|
importJson(bundle: ExportBundle): Promise<ImportReport>;
|
|
215
255
|
importJson(options: ImportOptions): Promise<ImportReport>;
|
|
216
256
|
importJsonStr(json: string): Promise<ImportReport>;
|
|
@@ -293,5 +333,5 @@ declare class FlockSQLite {
|
|
|
293
333
|
isAutoDebounceActive(): boolean;
|
|
294
334
|
}
|
|
295
335
|
//#endregion
|
|
296
|
-
export { type EntryInfo, type Event, type EventBatch, type EventListener, type ExportBundle, type ExportHooks, type ExportOptions, type ExportPayload, type ExportRecord, FlockSQLite as Flock, FlockSQLite, FlockSQLiteOptions, type ImportHooks, type ImportOptions, type ImportReport, type KeyPart, type MetadataMap, type PutHooks, type PutWithMetaOptions, type ScanBound, type ScanOptions, type ScanRow, type Value, VersionVector, type VersionVectorEntry, decodeVersionVector, encodeVersionVector };
|
|
336
|
+
export { type EntryInfo, type Event, type EventBatch, type EventListener, type ExportBundle, type ExportHooks, type ExportOptions, type ExportPayload, type ExportRecord, FlockSQLite as Flock, FlockSQLite, type FlockRoleProvider, type FlockRuntime, FlockSQLiteOptions, type FlockSQLiteRole, type FlockTransport, type FlockTransportFactory, type ImportHooks, type ImportOptions, type ImportReport, type KeyPart, type MetadataMap, type PutHooks, type PutWithMetaOptions, type RoleChangeListener, type ScanBound, type ScanOptions, type ScanRow, type TimeoutHandle, type Value, VersionVector, type VersionVectorEntry, decodeVersionVector, encodeVersionVector };
|
|
297
337
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{openStore as e}from"@loro-dev/unisqlite";const t=new TextEncoder;function n(e){return Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}function r(e){let t=BigInt(e),n=[];do{let e=Number(t&127n);t>>=7n,t!==0n&&(e|=128),n.push(e)}while(t!==0n);return new Uint8Array(n)}function i(e){let t=BigInt(e),n=[],r=!0;for(;r;){let e=Number(t&127n);t>>=7n;let i=(e&64)!=0;t===0n&&!i||t===-1n&&i?r=!1:e|=128,n.push(e)}return new Uint8Array(n)}async function a(e){let t=typeof crypto<`u`?crypto:void 0;if(t?.subtle){let n=new ArrayBuffer(e.byteLength);new Uint8Array(n).set(e);let r=await t.subtle.digest(`SHA-256`,n);return new Uint8Array(r)}try{let{createHash:t}=await import(`crypto`),n=t(`sha256`);return n.update(e),new Uint8Array(n.digest())}catch{throw Error(`No crypto implementation available for digest`)}}var o=class{chunks=[];writeTag(e){this.chunks.push(e&255)}writeBool(e){this.chunks.push(e?1:0)}writeBytes(e){this.writeLen(e.length);for(let t=0;t<e.length;t+=1)this.chunks.push(e[t])}writeRawBytes(e){for(let t=0;t<e.length;t+=1)this.chunks.push(e[t])}writeLen(e){this.writeRawBytes(r(e))}writeI64(e){this.writeRawBytes(i(e))}writeF64(e){let t=new DataView(new ArrayBuffer(8));t.setFloat64(0,e,!1);let n=new Uint8Array(t.buffer);this.writeRawBytes(n)}writeString(e){this.writeBytes(t.encode(e))}writeJson(e){if(e===null){this.writeTag(32);return}if(typeof e==`boolean`){this.writeTag(33),this.writeBool(e);return}if(typeof e==`number`){this.writeTag(34),this.writeF64(e);return}if(typeof e==`string`){this.writeTag(35),this.writeString(e);return}if(Array.isArray(e)){this.writeTag(36),this.writeLen(e.length);for(let t of e)this.writeJson(t);return}if(e&&typeof e==`object`){let t=Object.entries(e).sort(([e],[t])=>e<t?-1:e>t?1:0);this.writeTag(37),this.writeLen(t.length);for(let[e,n]of t)this.writeString(e),this.writeJson(n);return}throw TypeError(`Unsupported JSON value in digest`)}writeRawValue(e){if(this.writeTag(16),e.data===void 0?this.writeBool(!1):(this.writeBool(!0),this.writeJson(e.data)),this.writeTag(18),!e.metadata||typeof e.metadata!=`object`)this.writeBool(!1);else{let t=Object.entries(e.metadata).sort(([e],[t])=>e<t?-1:e>t?1:0);this.writeBool(!0),this.writeLen(t.length);for(let[e,n]of t)this.writeString(e),this.writeJson(n)}this.writeTag(17),this.writeF64(e.clock.physicalTime),this.writeI64(Math.trunc(e.clock.logicalCounter)),this.writeBytes(t.encode(e.clock.peerId))}async finish(){return a(new Uint8Array(this.chunks))}};function s(e){if(e)try{let t=JSON.parse(e);return!t||typeof t!=`object`||Array.isArray(t)?void 0:t}catch{return}}function c(e){if(e!=null)return JSON.parse(e)}async function l(e){let t=c(e.data);if(t===void 0)return null;let n=s(e.metadata),r=new o;return r.writeBytes(e.key),r.writeRawValue({data:t,metadata:n,clock:{physicalTime:Number(e.physical),logicalCounter:Number(e.logical),peerId:String(e.peer)}}),r.finish()}async function u(e){let t=new Uint8Array(32);for(let n of e){let e=await l(n);if(e)for(let n=0;n<t.length;n+=1)t[n]^=e[n]}return n(t)}const ee={hi:2146959360,lo:1};var te=class extends Error{};function d(){throw new te}const ne=(e,t)=>e<t?-1:e>t?1:0,re=(e,t)=>e===t,f=e=>BigInt(e.hi)*4294967296n+BigInt(e.lo>>>0),ie=e=>-e,ae=(e,t)=>e+t,oe=(e,t)=>e*t,se=(e,t)=>e/t,ce=(e,t)=>e%t,le=(e,t)=>e>>BigInt(t),ue=e=>Number(BigInt.asUintN(32,e))|0,de=e=>Number(BigInt.asIntN(32,e));function p(e,t){if(t<0||t>=e.length)throw Error(`Index out of bounds`)}const fe=(e,t)=>e.toString(t);function pe(e,t){let n=new Uint8Array(e);return t!==0&&n.fill(t),n}const m=(e,t)=>{e.push(t)},me={$tag:0};function he(e){this._0=e}he.prototype.$tag=1;function ge(e){this._0=e}ge.prototype.$tag=2;function _e(e){this._0=e}_e.prototype.$tag=3;function ve(e){this._0=e}ve.prototype.$tag=4;const ye=function e(t){let n=e._view;return n===void 0&&(n=e._view=new DataView(new ArrayBuffer(8))),n.setUint32(0,t.hi),n.setUint32(4,t.lo),n.getFloat64(0)},be=function e(t){let n=e._view;return n===void 0&&(n=e._view=new DataView(new ArrayBuffer(8))),n.setFloat64(0,t),{hi:n.getInt32(0),lo:n.getInt32(4)}},xe=e=>e.hi*4294967296+(e.lo>>>0),Se=e=>{if(isNaN(e))return{hi:0,lo:0};if(e>=0x8000000000000000)return{hi:2147483647,lo:4294967295};if(e<=-0x8000000000000000)return{hi:-2147483648,lo:0};let t=!1;e<0&&(t=!0,e=-e);let n=1/4294967296*e|0,r=e>>>0;return t&&(r===0?n=~n+1:(n=~n,r=~r+1)),{hi:n,lo:r}},Ce=new Uint8Array,h={hi:0,lo:255},we={hi:0,lo:0},Te={hi:-1,lo:-1},g={hi:-2147483648,lo:0};function Ee(e){this._0=e}Ee.prototype.$tag=0;function De(e){this._0=e}De.prototype.$tag=1;function Oe(e){this._0=e}Oe.prototype.$tag=2;const _={$tag:1},ke={$tag:0},Ae={hi:0,lo:1},je={hi:0,lo:256};function v(e){this._0=e}v.prototype.$tag=0;function y(e){this._0=e}y.prototype.$tag=1;function Me(e){this._0=e}Me.prototype.$tag=0;function Ne(e){this._0=e}Ne.prototype.$tag=1;function Pe(e){this._0=e}Pe.prototype.$tag=0;function Fe(e){this._0=e}Fe.prototype.$tag=1;function Ie(e){this._0=e}Ie.prototype.$tag=2;function Le(e){this._0=e}Le.prototype.$tag=3;const Re={$tag:4},ze={$tag:5};function Be(e){this._0=e}Be.prototype.$tag=0;function Ve(e){this._0=e}Ve.prototype.$tag=1;function He(e){this._0=e}He.prototype.$tag=0;function Ue(e){this._0=e}Ue.prototype.$tag=1;function We(e){this._0=e}We.prototype.$tag=2;const Ge={$tag:3},Ke={$tag:4},qe=Rt(ee);function Je(e){return d()}function Ye(e){return d()}function Xe(e){return d()}function b(e){d()}function Ze(e){return d()}function Qe(e){return Lt(e)}function $e(e,t){if(e.end-e.start|0){let n=e.buf[e.start],r=e.buf,i=1+e.start|0,a={buf:r,start:i,end:e.end},o=E(n),s=o.end-o.start|0,c=a.end-a.start|0,l=0;for(;;){let e=l;if(e<c){let n=r[i+e|0],a=s,o=E(n);s=a+((o.end-o.start|0)+(t.end-t.start|0)|0)|0,l=e+1|0;continue}else break}s<<=1;let u=ht(s);if(O(u,o.str,o.start,o.end-o.start|0),bt(t.str,0,t.start,t.end)){let e=a.end-a.start|0,t=0;for(;;){let n=t;if(n<e){let e=r[i+n|0],a=E(e);O(u,a.str,a.start,a.end-a.start|0),t=n+1|0;continue}else break}}else{let e=a.end-a.start|0,n=0;for(;;){let a=n;if(a<e){let e=r[i+a|0],o=E(e);O(u,t.str,t.start,t.end-t.start|0),O(u,o.str,o.start,o.end-o.start|0),n=a+1|0;continue}else break}}return u.val}else return``}function et(e,t){t(t=>(Dt(e,t),1))}function tt(e,t){return $e({buf:e,start:0,end:e.length},t)}function nt(e,t){return ne(e,t)}function rt(e,t){return re(e,t)}function it(e){return ie(e)}function at(e,t){return ae(e,t)}function ot(e,t){return oe(e,t)}function st(e,t){return se(e,t)}function ct(e,t){return ce(e,t)}function lt(e,t){return t<0&&b(`negative shift count`),le(e,t)}function ut(e){let t=ue(lt(e,32)),n=ue(e);return qt(Jt(Qe(t),32),Qe(n))}function x(e,t){if(t>=0&&t<(e.end-e.start|0)){let n=e.bytes,r=e.start+t|0;return p(n,r),n[r]}else return Xe(`index out of bounds: the len is from 0 to ${D(e.end-e.start|0)} but the index is ${D(t)}`)}function S(e,t,n){let r=e.length,i;if(n===void 0)i=r;else{let e=n;i=e<0?r+e|0:e}let a=t<0?r+t|0:t;return a>=0&&a<=i&&i<=r?{bytes:e,start:a,end:i}:Ye(`Invalid index for View`)}function C(e,t,n){let r=e.end-e.start|0,i;if(n===void 0)i=r;else{let e=n;i=e<0?r+e|0:e}let a=t<0?r+t|0:t;return a>=0&&a<=i&&i<=r?{bytes:e.bytes,start:e.start+a|0,end:(e.start+a|0)+(i-a|0)|0}:Ye(`Invalid index for View`)}function dt(e){return t=>{let n=e.end-e.start|0,r=0;for(;;){let i=r;if(i<n){if(t(x(e,i))!==1)return 0;r=i+1|0;continue}else return 1}}}function ft(e){let t={val:0},n=e.end-e.start|0;return()=>{if(t.val<n){let n=t.val,r=e.bytes,i=e.start+n|0;p(r,i);let a=r[i];return t.val=t.val+1|0,a}else return-1}}function w(e){return tn(e.end-e.start|0,t=>an(e,t))}function pt(e){let t=At(e);return w({buf:t,start:0,end:t.length})}function T(e){return Lt(e)}function E(e){return{str:e,start:0,end:e.length}}function mt(e,t,n,r,i){if(e===n&&t<r){let a=0;for(;;){let o=a;if(o<i){let i=t+o|0,s=r+o|0;p(n,s),p(e,i),e[i]=n[s],a=o+1|0;continue}else return}}else{let a=i-1|0;for(;;){let i=a;if(i>=0){let o=t+i|0,s=r+i|0;p(n,s),p(e,o),e[o]=n[s],a=i-1|0;continue}else return}}}function ht(e){return{val:``}}function gt(e,t){let n=e;n.val=`${n.val}${String.fromCodePoint(t)}`}function _t(e,t){let n=e;n.val=`${n.val}${t}`}function vt(e,t){return nt(e,t)>0}function D(e){let t=ht(0);return Mt(e,{self:t,method_0:_t,method_1:O,method_2:gt}),t.val}function yt(e,t){return fe(e,t)}function bt(e,t,n,r){let i;i=r===void 0?e.length:r;let a=n,o=0;for(;;){let n=a,r=o;if(n<i&&r<t){let t=e.charCodeAt(n);if(55296<=t&&t<=56319&&(n+1|0)<i){let t=n+1|0,i=e.charCodeAt(t);if(56320<=i&&i<=57343){a=n+2|0,o=r+1|0;continue}else b(`invalid surrogate pair`)}a=n+1|0,o=r+1|0;continue}else return r===t&&n===i}}function xt(e,t,n){let r=e.length,i;return i=n===void 0?r:n,t>=0&&t<=i&&i<=r?e.substring(t,i):d()}function O(e,t,n,r){let i=e;i.val=`${i.val}${xt(t,n,n+r|0)}`}function St(e){return[]}function Ct(e){return[]}function wt(e){return[]}function Tt(e,t){m(e,t)}function Et(e,t){m(e,t)}function k(e,t){m(e,t)}function A(e,t){m(e,t)}function Dt(e,t){m(e,t)}function Ot(e){return String.fromCodePoint(e)}function kt(e,t){let n={val:me};e(e=>(t(e),1));let r=n.val;switch(r.$tag){case 0:return;case 1:r._0;return;case 2:return r._0;case 3:d();return;default:d();return}}function At(e){let t=[];return kt(e,e=>{k(t,e)}),t}function jt(e){return e()}function Mt(e,t){t.method_0(t.self,yt(e,10))}function Nt(e){return t=>{let n=e.length,r=0;for(;;){let i=r;if(i<n){let n=e[i];if(t(n)!==1)return 0;r=i+1|0;continue}else return 1}}}function Pt(e,t,n){let r=e.length,i;if(n===void 0)i=r;else{let e=n;i=e<0?r+e|0:e}let a=t<0?r+t|0:t;return a>=0&&a<=i&&i<=r?{buf:e,start:a,end:i}:Ze(`View index out of bounds`)}function Ft(e){return{hi:0,lo:e}}function It(e){return Ft(e)}function Lt(e){return It(e)}function Rt(e){return ye(e)}function zt(e){return{hi:e>>31&-1,lo:e|0}}function Bt(e){return zt(e)}function Vt(e){return e.lo}function j(e){return Vt(e)&255}function Ht(e,t){return{hi:e.hi&t.hi,lo:e.lo&t.lo}}function Ut(e,t){return{hi:e.hi|t.hi,lo:e.lo|t.lo}}function Wt(e,t){return{hi:e.hi^t.hi,lo:e.lo^t.lo}}function Gt(e,t){let n=t&63;if(n===0)return e;if(n<32){let t=e.hi,r=e.lo,i=t,a=r;return{hi:i<<n|a>>>(32-n|0)|0,lo:a<<n}}else return{hi:e.lo<<(n-32|0),lo:0}}function Kt(e,t){let n=t&63;return n===0?e:n<32?{hi:e.hi>>>n|0,lo:e.lo>>>n|e.hi<<(32-n|0)}:{hi:0,lo:e.hi>>>(n-32|0)|0}}function qt(e,t){return Ut(e,t)}function Jt(e,t){return Gt(e,t)}function Yt(e){return xe(e)}function Xt(e){return Yt(e)}function Zt(e){return ye(e)}function Qt(e){return be(e)}function $t(e,t){let n=e,r=t;return n.hi===r.hi&&n.lo===r.lo}function M(e,t){return Ht(e,t)}function N(e,t){return Ut(e,t)}function P(e,t){return Wt(e,t)}function F(e,t){return Gt(e,t)}function I(e,t){return Kt(e,t)}function en(e){return Se(e)}function tn(e,t){if(e<=0)return Ce;let n=pe(e,t(0)),r=1;for(;;){let i=r;if(i<e){p(n,i),n[i]=t(i),r=i+1|0;continue}else break}return n}function nn(e){console.log(e)}function rn(e,t,n,r,i){let a=(t+i|0)-1|0,o=(r+i|0)-1|0,s=e.length,c=n.length;if(i>=0&&t>=0&&a<s&&r>=0&&o<c){mt(e,t,n,r,i);return}else{d();return}}function an(e,t){if(t>=0&&t<(e.end-e.start|0)){let n=e.buf,r=e.start+t|0;return p(n,r),n[r]}else return Xe(`index out of bounds: the len is from 0 to ${D(e.end-e.start|0)} but the index is ${D(t)}`)}function on(e){let t=e.length,n=Array(t),r=0;for(;;){let i=r;if(i<t){n[i]=e[(t-i|0)-1|0],r=i+1|0;continue}else break}return n}function sn(e,t){let n=e.data.length<=0?1:e.data.length,r,i=n;for(;;){let e=i;if(e>=t){r=e;break}i=Math.imul(e,2)|0}if(r!==e.data.length){let t=pe(r,0);mt(t,0,e.data,0,e.len),e.data=t;return}else return}function L(e,t){sn(e,e.len+1|0);let n=e.data,r=e.len;p(n,r),n[r]=t,e.len=e.len+1|0}function R(e){return w(Pt(e.data,0,e.len))}function z(e){return{data:pe(e<1?1:e,0),len:0}}function cn(e,t){let n=t.length;sn(e,e.len+n|0),rn(e.data,e.len,t,0,n),e.len=e.len+n|0}function ln(e){switch(e){case 0:return`40`;case 1:return`41`;case 2:return`42`;case 3:return`43`;case 4:return`44`;case 5:return`45`;case 6:return`46`;case 7:return`47`;default:return`49`}}function un(e){switch(e){case 0:return`30`;case 1:return`31`;case 2:return`32`;case 3:return`33`;case 4:return`34`;case 5:return`35`;case 6:return`36`;case 7:return`37`;default:return`39`}}function dn(e){let t=[],n=e.color;n===void 0||A(t,un(n));let r=e.bg_color;r===void 0||A(t,ln(r));let i=e.formats,a=i.length,o=0;for(;;){let e=o;if(e<a){switch(i[e]){case 0:A(t,`1`);break;case 1:A(t,`4`);break;case 2:A(t,`5`);break;case 3:A(t,`7`);break;case 4:A(t,`8`);break;case 5:A(t,`9`);break;default:A(t,`3`)}o=e+1|0;continue}else break}return t.length>0?`[${tt(t,{str:`;`,start:0,end:1})}m${e.str}[0m`:e.str}function fn(e){return{str:e,bg_color:void 0,color:void 0,formats:[]}}function pn(e){return{str:e.str,bg_color:e.bg_color,color:1,formats:e.formats}}function mn(e){return{str:e.str,bg_color:e.bg_color,color:3,formats:e.formats}}function hn(e){return{str:e.str,bg_color:e.bg_color,color:4,formats:e.formats}}function gn(e){let t=e.str,n=e.bg_color,r=e.color,i=[];return Dt(i,0),et(i,Nt(e.formats)),{str:t,bg_color:n,color:r,formats:i}}function _n(e,t){let n=`${dn(pn(gn(fn(`Panic: `))))}${dn(mn(fn(e)))} at ${dn(hn(fn(t)))}`;nn(n),b(n)}function vn(e){let t=wt(0),n=0;for(;n<e.length;){let r=n;p(e,r);let i=e.charCodeAt(r);if(i>=55296&&i<=56319&&(n+1|0)<e.length){let r=n+1|0;p(e,r);let a=e.charCodeAt(r);if(a>=56320&&a<=57343){let e=(65536+(i-55296<<10)|0)+(a-56320|0)|0;k(t,(240|e>>18)&255),k(t,(128|e>>12&63)&255),k(t,(128|e>>6&63)&255),k(t,(128|e&63)&255),n=n+1|0}else k(t,(224|i>>12)&255),k(t,(128|i>>6&63)&255),k(t,(128|i&63)&255)}else i<128?k(t,i&255):i<2048?(k(t,(192|i>>6)&255),k(t,(128|i&63)&255)):(k(t,(224|i>>12)&255),k(t,(128|i>>6&63)&255),k(t,(128|i&63)&255));n=n+1|0}return w({buf:t,start:0,end:t.length})}function yn(e){return{bytes:vn(e)}}function bn(e){let t=0;for(;t<(e.end-e.start|0);){let n=x(e,t);if(!(n&128))t=t+1|0;else if((n&224)==192){if((t+1|0)>=(e.end-e.start|0)||(x(e,t+1|0)&192)!=128)return!1;t=t+2|0}else if((n&240)==224){if((t+2|0)>=(e.end-e.start|0))return!1;let n=x(e,t+1|0),r=x(e,t+2|0),i;if(i=(n&192)==128?(r&192)!=128:!0,i)return!1;t=t+3|0}else if((n&248)==240){if((t+3|0)>=(e.end-e.start|0))return!1;let n=x(e,t+1|0),r=x(e,t+2|0),i=x(e,t+3|0),a;if((n&192)!=128)a=!0;else{let e;e=(r&192)==128?(i&192)!=128:!0,a=e}if(a)return!1;t=t+4|0}else return!1}return!0}function xn(e){if(bn(C(e,0,void 0)))return{bytes:pt(dt(e))}}function Sn(e){let t=0,n=``;for(;t<e.length;){let r=t;p(e,r);let i=e[r],a;if(!(i&128))a=i;else if((i&224)==192){if((t+1|0)>=e.length)return;let n=t+1|0;p(e,n);let r=e[n];if((r&192)!=128)return;t=t+1|0,a=(i&31)<<6|r&63}else if((i&240)==224){if((t+2|0)>=e.length)return;let n=t+1|0;p(e,n);let r=e[n],o=t+2|0;p(e,o);let s=e[o],c;if(c=(r&192)==128?(s&192)!=128:!0,c)return;t=t+2|0,a=(i&15)<<12|(r&63)<<6|s&63}else if((i&248)==240){if((t+3|0)>=e.length)return;let n=t+1|0;p(e,n);let r=e[n],o=t+2|0;p(e,o);let s=e[o],c=t+3|0;p(e,c);let l=e[c],u;if((r&192)!=128)u=!0;else{let e;e=(s&192)==128?(l&192)!=128:!0,u=e}if(u)return;t=t+3|0,a=(i&7)<<18|(r&63)<<12|(s&63)<<6|l&63}else return;n=`${n}${Ot(a)}`,t=t+1|0}return n}function Cn(e){let t=Sn(e.bytes);return t===void 0?d():t}function wn(e){return Qt(e)}function Tn(e){return Zt(e)}function En(e){let t=wt(0);return k(t,j(M(I(e,56),h))),k(t,j(M(I(e,48),h))),k(t,j(M(I(e,40),h))),k(t,j(M(I(e,32),h))),k(t,j(M(I(e,24),h))),k(t,j(M(I(e,16),h))),k(t,j(M(I(e,8),h))),k(t,j(M(e,h))),w({buf:t,start:0,end:t.length})}function Dn(e){e.length!==8&&_n(`Invalid byte array length`,`/Users/zxch3n/Code/flock/moon/memcomparable/utils.mbt:28:5-28:54`);let t=we,n=t;p(e,0),t=N(n,F(T(e[0]),56));let r=t;p(e,1),t=N(r,F(T(e[1]),48));let i=t;p(e,2),t=N(i,F(T(e[2]),40));let a=t;p(e,3),t=N(a,F(T(e[3]),32));let o=t;p(e,4),t=N(o,F(T(e[4]),24));let s=t;p(e,5),t=N(s,F(T(e[5]),16));let c=t;p(e,6),t=N(c,F(T(e[6]),8));let l=t;return p(e,7),t=N(l,T(e[7])),t}function On(){return{parts:Ct(0)}}function B(e,t){Tt(e.parts,t)}function kn(e){return e===e?e:e<0?-qe:qe}function An(e,t){L(t,1);let n=ft(e);for(;;){let e=jt(n);if(e===-1)break;{let n=e;L(t,n),n===0&&L(t,255);continue}}L(t,0)}function jn(e,t){L(t,2);let n=e.bytes,r=n.length,i=0;for(;;){let e=i;if(e<r){let r=n[e];L(t,r),r===0&&L(t,255),i=e+1|0;continue}else break}L(t,0)}function Mn(e,t){L(t,33);let n=kn(e),r=En(n<0?P(wn(n),Te):P(wn(n),g)),i=r.length,a=0;for(;;){let e=a;if(e<i){let n=r[e];L(t,n),a=e+1|0;continue}else return}}function Nn(e){let t=[],n=e;for(;vt(n,0n);)k(t,de(ct(n,256n))&255),n=st(n,256n);let r=on(t);return w({buf:r,start:0,end:r.length})}function Pn(e,t){if(rt(e,0n)){L(t,20);return}let n=vt(e,0n),r=Nn(n?e:it(e)),i=r.length;if(n===!1){i<=8?L(t,(20-(i&255)|0)&255):(L(t,11),i>255&&b(`n is too large`),L(t,(i&255^255)&255));let e=z(0),n=0;for(;;){let t=n;if(t<r.length){p(r,t);let i=r[t];L(e,(i^255)&255),n=t+1|0;continue}else break}cn(t,R(e));return}else{i<=8?L(t,(20+(i&255)|0)&255):(L(t,29),i>255&&b(`n is too large`),L(t,i&255)),cn(t,r);return}}function Fn(e,t){switch(e.$tag){case 0:{let n=e._0;An(S(n,0,n.length),t);return}case 1:{let n=e._0;jn(n,t);return}case 2:{let n=e._0;Pn(n,t);return}case 3:{let n=e._0;Mn(n,t);return}case 4:L(t,38);return;default:L(t,39);return}}function In(e){let t=z(0),n=e.parts,r=n.length,i=0;for(;;){let e=i;if(e<r){let r=n[e];Fn(r,t),i=e+1|0;continue}else break}return R(t)}function Ln(e,t){let n=z(0),r=t;for(;r<(e.end-e.start|0);){let t=x(e,r);if(r=r+1|0,t===0){let t;if(t=r<(e.end-e.start|0)?x(e,r)===255:!1,t){L(n,0),r=r+1|0;continue}else{let e=R(n);return new De({_0:S(e,0,e.length),_1:r})}}L(n,t)}return new Ee(_)}function V(e){let t=f(we),n=f(Ae),r=(e.end-e.start|0)-1|0;for(;;){let i=r;if(i>=0){let a=f(Bt(x(e,i)));t=at(t,ot(n,a)),n=ot(n,f(je)),r=i-1|0;continue}else break}return t}function Rn(e,t){let n;if(n=20<=t?t<=28:!1,n){let n=(t-20|0)&255;if((e.end-e.start|0)<n)return new v(_);let r=C(e,0,n);return new y({_0:C(e,n,void 0),_1:V(r)})}else{let n;if(n=12<=t?t<20:!1,n){let n=(20-t|0)&255;if((e.end-e.start|0)<n)return new v(_);let r=C(e,0,n),i=C(e,n,void 0),a=z(0),o=0;for(;;){let e=o;if(e<(r.end-r.start|0)){L(a,(x(r,e)^255)&255),o=e+1|0;continue}else break}let s=R(a);return new y({_0:i,_1:it(V(S(s,0,s.length)))})}else if(t===11){if((e.end-e.start|0)<1)return new v(_);let t=(x(e,0)^255)&255;if((e.end-e.start|0)<(t+1|0))return new v(_);let n=C(e,1,t+1|0),r=C(e,t+1|0,void 0),i=z(0),a=0;for(;;){let e=a;if(e<(n.end-n.start|0)){L(i,(x(n,e)^255)&255),a=e+1|0;continue}else break}let o=R(i);return new y({_0:r,_1:it(V(S(o,0,o.length)))})}else if(t===29){if((e.end-e.start|0)<1)return new v(_);let t=x(e,0);if((e.end-e.start|0)<(t+1|0))return new v(_);let n=C(e,1,t+1|0);return new y({_0:C(e,t+1|0,void 0),_1:V(n)})}else return new v(new Oe(t))}}function zn(e,t){if((t+8|0)>(e.end-e.start|0))return new Me(_);let n=wt(0),r=0;for(;;){let i=r;if(i<8){k(n,x(e,t+i|0)),r=i+1|0;continue}else break}let i=Dn(w({buf:n,start:0,end:n.length}));return new Ne({_0:$t(M(i,g),we)?Tn(P(i,Te)):Tn(P(i,g)),_1:t+8|0})}function Bn(e){let t=On(),n=0;for(;n<(e.end-e.start|0);){let r=x(e,n);if(n=n+1|0,r===2){let r=Ln(e,n),i;if(r.$tag===1)i=r._0;else return r;let a=i._0,o=i._1,s=xn(a);if(s===void 0)return new Be(ke);B(t,new Fe(s)),n=o}else if(r===1){let r=Ln(e,n),i;if(r.$tag===1)i=r._0;else return r;let a=i._0,o=i._1;B(t,new Pe(pt(dt(a)))),n=o}else if(r>=11&&r<=29){let i=Rn(C(e,n,void 0),r),a;if(i.$tag===1)a=i._0;else return i;let o=a._0,s=a._1;B(t,new Ie(s)),n=(e.end-e.start|0)-(o.end-o.start|0)|0}else if(r===33){let r=zn(e,n),i;if(r.$tag===1)i=r._0;else return r;let a=i._0,o=i._1;B(t,new Le(a)),n=o}else if(r===38)B(t,Re);else if(r===39)B(t,ze);else return new Be(new Oe(r))}return new Ve(t)}function Vn(e){switch(e.$tag){case 0:{let t=e._0;return new We(t)}case 1:{let t=e._0;return new Ue(Cn(t))}case 2:{let t=e._0;return new He(Xt(ut(t)))}case 3:{let t=e._0;return new He(t)}case 4:return Ke;default:return Ge}}function Hn(e){switch(e.$tag){case 2:{let t=e._0;return new Pe(t)}case 1:{let t=e._0;return new Fe(yn(t))}case 0:{let t=e._0;return Xt(en(t))===t?new Ie(f(en(t))):new Le(t)}case 3:return ze;default:return Re}}function Un(e){let t=On(),n=e.length,r=0;for(;;){let i=r;if(i<n){let n=e[i];Tt(t.parts,Hn(n)),r=i+1|0;continue}else break}return In(t)}function Wn(e){let t;_L:{_L$2:{let n=Bn(S(e,0,e.length));if(n.$tag===1)t=n._0;else{n._0;break _L$2}break _L}t=Je(`Failed to decode key`)}let n=St(0),r=t.parts,i=r.length,a=0;for(;;){let e=a;if(e<i){let t=r[e];Et(n,Vn(t)),a=e+1|0;continue}else break}return n}function Gn(e){if(typeof e==`number`){if(!Number.isFinite(e))throw TypeError(`Key parts must be finite numbers`);return{$tag:0,_0:e}}if(typeof e==`string`)return{$tag:1,_0:e};if(e===!0)return{$tag:3};if(e===!1)return{$tag:4};throw TypeError(`Key parts must be strings, numbers, or booleans`)}function Kn(e){if(e instanceof Uint8Array)return e;if(e&&typeof e==`object`){let t=e.buf;if(t instanceof Uint8Array){let n=e.start??0,r=e.end??t.length;return t.subarray(n,r)}}throw TypeError(`Invalid bytes payload in memcomparable decode`)}function qn(e){switch(e?.$tag){case 0:return e._0;case 1:return e._0;case 3:return!0;case 4:return!1;case 2:return Kn(e._0);default:throw TypeError(`Unsupported memcomparable key part`)}}function H(e){return Un(e.map(Gn))}function Jn(e){return Wn(e).map(e=>qn(e))}function Yn(e,t){let n=Math.min(e.length,t.length);for(let r=0;r<n;r+=1)if(e[r]!==t[r])return e[r]<t[r]?-1:1;return e.length===t.length?0:e.length<t.length?-1:1}function Xn(e){if(e.length===0)return;let t=Array.from(e);for(let e=t.length-1;e>=0;--e){let n=t[e];if(n<255)return t[e]=n+1,new Uint8Array(t.slice(0,e+1))}}function Zn(e){return JSON.stringify(e)}const Qn=new TextEncoder,$n=new TextDecoder,er=globalThis.structuredClone;function tr(e){return Qn.encode(e).length}function U(e){return typeof e==`string`&&tr(e)<128}function nr(){let e=new Uint8Array(32),t=typeof crypto<`u`?crypto:void 0;if(t?.getRandomValues)t.getRandomValues(e);else if(t?.randomBytes){let n=t.randomBytes(32);e.set(n)}else for(let t=0;t<32;t+=1)e[t]=Math.floor(Math.random()*256);return Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}function rr(e){if(e===void 0)return nr();if(!U(e))throw TypeError(`peerId must be a UTF-8 string under 128 bytes`);return e}function W(e){return e===void 0?e:er?er(e):JSON.parse(JSON.stringify(e))}function G(e){if(!(!e||typeof e!=`object`||Array.isArray(e)))return W(e)}function ir(e){return G(e)??{}}function ar(e,t){if(!(!t||typeof t!=`object`)){if(`data`in t){let n=t.data;e.data=n===void 0?void 0:W(n)}`metadata`in t&&(e.metadata=G(t.metadata))}}function K(e){let t={};return ar(t,e),t}function q(e,t){let n=K(e);return ar(n,t),n}function or(e,t){if(e===t)return 0;let n=Math.min(e.length,t.length);for(let r=0;r<n;r+=1){let n=e[r]-t[r];if(n!==0)return n}return e.length-t.length}function sr(e){if(!e||typeof e!=`object`)return[];let t=[];for(let[n,r]of Object.entries(e)){if(!r||!U(n))continue;let{physicalTime:e,logicalCounter:i}=r;if(typeof e!=`number`||!Number.isFinite(e)||typeof i!=`number`||!Number.isFinite(i))continue;let a=Qn.encode(n);t.push({peer:n,peerBytes:a,timestamp:Math.trunc(e),counter:Math.max(0,Math.trunc(i))})}return t.sort((e,t)=>{if(e.timestamp!==t.timestamp)return e.timestamp-t.timestamp;let n=or(e.peerBytes,t.peerBytes);return n===0?e.counter-t.counter:n}),t}function J(e,t){if(!Number.isFinite(e)||e<0)throw TypeError(`leb128 values must be finite and non-negative`);let n=Math.trunc(e);if(n===0){t.push(0);return}for(;n>0;){let e=n%128;n=Math.floor(n/128),t.push(n>0?e|128:e)}}function cr(e,t){J(e.length,t);for(let n=0;n<e.length;n+=1)t.push(e[n])}const Y=new Uint8Array([86,69,86,69]);function lr(e){let t=sr(e),n=Array.from(Y);if(t.length===0)return Uint8Array.from(n);let r=0;for(let e=0;e<t.length;e+=1){let i=t[e];if(i.timestamp<0)throw TypeError(`timestamp must be non-negative`);if(e===0)J(i.timestamp,n),r=i.timestamp;else{let e=i.timestamp-r;if(e<0)throw TypeError(`version vector timestamps must be non-decreasing`);J(e,n),r=i.timestamp}J(i.counter,n),cr(i.peerBytes,n)}return Uint8Array.from(n)}function X(e,t){let n=0,r=1,i=0;for(;t+i<e.length;){let a=e[t+i];if(i+=1,n+=(a&127)*r,!(a&128))break;r*=128}return[n,i]}function ur(e,t){let[n,r]=X(e,t),i=t+r,a=i+n;if(a>e.length)throw TypeError(`varString length exceeds buffer`);let o=e.subarray(i,a);return[$n.decode(o),r+n]}function dr(e){return e.length>=4&&e[0]===Y[0]&&e[1]===Y[1]&&e[2]===Y[2]&&e[3]===Y[3]}function fr(e){let t=0,[n,r]=X(e,t);t+=r;let[i,a]=X(e,t);t+=a;let o={};for(let r=0;r<n;r+=1){let[n,r]=ur(e,t);if(t+=r,!U(n))throw TypeError(`invalid peer id in encoded version vector`);let[a,s]=X(e,t);t+=s;let[c,l]=X(e,t);t+=l,o[n]={physicalTime:i+a,logicalCounter:c}}return o}function pr(e){let t=4,n={};if(t===e.length)return n;let[r,i]=X(e,t);t+=i;let[a,o]=X(e,t);t+=o;let[s,c]=ur(e,t);if(t+=c,!U(s))throw TypeError(`invalid peer id in encoded version vector`);n[s]={physicalTime:r,logicalCounter:a};let l=r;for(;t<e.length;){let[r,i]=X(e,t);t+=i;let[a,o]=X(e,t);t+=o;let[s,c]=ur(e,t);if(t+=c,!U(s))throw TypeError(`invalid peer id in encoded version vector`);let u=l+r;if(u<l)throw TypeError(`version vector timestamps must be non-decreasing`);n[s]={physicalTime:u,logicalCounter:a},l=u}return n}function mr(e){return dr(e)?pr(e):fr(e)}function hr(e){return lr(e)}function gr(e){return mr(e)}function Z(e,t){let n={c:Sr(e)};t.data!==void 0&&(n.d=W(t.data));let r=G(t.metadata);return r!==void 0&&(n.m=r),n}function _r(e){return!e||typeof e!=`object`?{accept:!0}:`accept`in e?e.accept?{accept:!0}:{accept:!1,reason:e.reason??`rejected`}:{accept:!0}}function vr(e){return typeof e==`object`&&!!e&&(Object.prototype.hasOwnProperty.call(e,`hooks`)||Object.prototype.hasOwnProperty.call(e,`from`)||Object.prototype.hasOwnProperty.call(e,`pruneTombstonesBefore`)||Object.prototype.hasOwnProperty.call(e,`peerId`))}function yr(e){return typeof e==`object`&&!!e&&Object.prototype.hasOwnProperty.call(e,`bundle`)}function br(e){if(e)try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return t}catch{}}function Q(e){if(e!=null)return JSON.parse(e)}function $(e){let t=e.split(`,`);if(t.length<3)return{physicalTime:0,logicalCounter:0,peerId:``};let n=Number(t[0]),r=Number(t[1]),i=t.slice(2).join(`,`);return{physicalTime:Number.isFinite(n)?n:0,logicalCounter:Number.isFinite(r)?Math.trunc(r):0,peerId:U(i)?i:``}}function xr(e,t,n){if(!(typeof e!=`number`||typeof t!=`number`||typeof n!=`string`)&&U(n)&&!(!Number.isFinite(e)||!Number.isFinite(t)))return{physicalTime:e,logicalCounter:Math.trunc(t),peerId:n}}function Sr(e){return`${e.physicalTime},${e.logicalCounter},${e.peerId}`}function Cr(e,t){return e.physicalTime===t.physicalTime?e.logicalCounter===t.logicalCounter?e.peerId===t.peerId?0:e.peerId>t.peerId?1:-1:e.logicalCounter>t.logicalCounter?1:-1:e.physicalTime>t.physicalTime?1:-1}function wr(e){if(!e)return;let{physicalTime:t,logicalCounter:n}=e;if(!(!Number.isFinite(t)||!Number.isFinite(n)))return{physicalTime:t,logicalCounter:Math.trunc(n)}}function Tr(e,t){if(t.length===0)return!0;if(e.length<t.length)return!1;for(let n=0;n<t.length;n+=1)if(e[n]!==t[n])return!1;return!0}async function Er(e){return e.map(e=>({key:e.key,data:e.data,metadata:e.metadata,physical:e.physical,logical:e.logical,peer:e.peer}))}function Dr(e){if(!e)return``;if(typeof e!=`string`)throw TypeError(`tablePrefix must be a string`);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw TypeError(`tablePrefix must start with a letter/underscore and use only letters, digits, or underscores`);return e}function Or(e){return{kv:`${e}kv`,overridden:`${e}overridden`,meta:`${e}meta`,idxKvPeerClock:`${e}idx_kv_peer_clock_key`,idxOverriddenKey:`${e}idx_overridden_key`,idxOverriddenSupersededAt:`${e}idx_overridden_superseded_at`}}var kr=class t{db;peerIdValue;vv;maxHlc;listeners;tables;txnEventSink;debounceState;constructor(e,t,n,r,i){this.db=e,this.peerIdValue=t,this.vv=n,this.maxHlc=r,this.listeners=new Set,this.tables=i,this.txnEventSink=void 0,this.debounceState=void 0}static async open(n){let r=n.connection??await e({path:n.path}),i=Or(Dr(n.tablePrefix));await t.ensureSchema(r,i);let a=await t.resolvePeerId(r,i,n.peerId),{vv:o,maxHlc:s}=await t.loadVersionState(r,i);return new t(r,a,o,s,i)}static async fromJson(e){let n=await t.open(e);return await n.importJson(e.bundle),n}async close(){if(this.debounceState!==void 0&&this.disableAutoDebounceCommit(),this.txnEventSink!==void 0){let e=this.txnEventSink;this.txnEventSink=void 0,e.length>0&&this.emitEvents(`local`,e)}await this.db.close()}static async ensureSchema(e,t){await e.exec(`
|
|
1
|
+
import{openStore as e}from"@loro-dev/unisqlite";const t=new TextEncoder;function n(e){return Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}function r(e){let t=BigInt(e),n=[];do{let e=Number(t&127n);t>>=7n,t!==0n&&(e|=128),n.push(e)}while(t!==0n);return new Uint8Array(n)}function i(e){let t=BigInt(e),n=[],r=!0;for(;r;){let e=Number(t&127n);t>>=7n;let i=(e&64)!=0;t===0n&&!i||t===-1n&&i?r=!1:e|=128,n.push(e)}return new Uint8Array(n)}async function a(e){let t=typeof crypto<`u`?crypto:void 0;if(t?.subtle){let n=new ArrayBuffer(e.byteLength);new Uint8Array(n).set(e);let r=await t.subtle.digest(`SHA-256`,n);return new Uint8Array(r)}try{let{createHash:t}=await import(`crypto`),n=t(`sha256`);return n.update(e),new Uint8Array(n.digest())}catch{throw Error(`No crypto implementation available for digest`)}}var o=class{chunks=[];writeTag(e){this.chunks.push(e&255)}writeBool(e){this.chunks.push(e?1:0)}writeBytes(e){this.writeLen(e.length);for(let t=0;t<e.length;t+=1)this.chunks.push(e[t])}writeRawBytes(e){for(let t=0;t<e.length;t+=1)this.chunks.push(e[t])}writeLen(e){this.writeRawBytes(r(e))}writeI64(e){this.writeRawBytes(i(e))}writeF64(e){let t=new DataView(new ArrayBuffer(8));t.setFloat64(0,e,!1);let n=new Uint8Array(t.buffer);this.writeRawBytes(n)}writeString(e){this.writeBytes(t.encode(e))}writeJson(e){if(e===null){this.writeTag(32);return}if(typeof e==`boolean`){this.writeTag(33),this.writeBool(e);return}if(typeof e==`number`){this.writeTag(34),this.writeF64(e);return}if(typeof e==`string`){this.writeTag(35),this.writeString(e);return}if(Array.isArray(e)){this.writeTag(36),this.writeLen(e.length);for(let t of e)this.writeJson(t);return}if(e&&typeof e==`object`){let t=Object.entries(e).sort(([e],[t])=>e<t?-1:e>t?1:0);this.writeTag(37),this.writeLen(t.length);for(let[e,n]of t)this.writeString(e),this.writeJson(n);return}throw TypeError(`Unsupported JSON value in digest`)}writeRawValue(e){if(this.writeTag(16),e.data===void 0?this.writeBool(!1):(this.writeBool(!0),this.writeJson(e.data)),this.writeTag(18),!e.metadata||typeof e.metadata!=`object`)this.writeBool(!1);else{let t=Object.entries(e.metadata).sort(([e],[t])=>e<t?-1:e>t?1:0);this.writeBool(!0),this.writeLen(t.length);for(let[e,n]of t)this.writeString(e),this.writeJson(n)}this.writeTag(17),this.writeF64(e.clock.physicalTime),this.writeI64(Math.trunc(e.clock.logicalCounter)),this.writeBytes(t.encode(e.clock.peerId))}async finish(){return a(new Uint8Array(this.chunks))}};function s(e){if(e)try{let t=JSON.parse(e);return!t||typeof t!=`object`||Array.isArray(t)?void 0:t}catch{return}}function c(e){if(e!=null)return JSON.parse(e)}async function l(e){let t=c(e.data);if(t===void 0)return null;let n=s(e.metadata),r=new o;return r.writeBytes(e.key),r.writeRawValue({data:t,metadata:n,clock:{physicalTime:Number(e.physical),logicalCounter:Number(e.logical),peerId:String(e.peer)}}),r.finish()}async function u(e){let t=new Uint8Array(32);for(let n of e){let e=await l(n);if(e)for(let n=0;n<t.length;n+=1)t[n]^=e[n]}return n(t)}var ee=class{txnEventSink;debounceState;runtime;emit;constructor(e){this.runtime=e.runtime,this.emit=e.emit,this.txnEventSink=void 0,this.debounceState=void 0}handleCommitEvents(e,t,n){if(t.length!==0){if(n&&this.txnEventSink){this.txnEventSink.push(...t);return}if(n&&this.debounceState){this.debounceState.pendingEvents.push(...t),this.resetDebounceTimer();return}this.emit(e,t)}}beforeImport(){this.debounceState!==void 0&&this.commit()}async txn(e){if(this.txnEventSink!==void 0)throw Error(`Nested transactions are not supported`);if(this.debounceState!==void 0)throw Error(`Cannot start transaction while autoDebounceCommit is active`);let t=[];this.txnEventSink=t;try{let n=await e();return t.length>0&&this.emit(`local`,t),n}finally{this.txnEventSink=void 0}}isInTxn(){return this.txnEventSink!==void 0}autoDebounceCommit(e,t){if(this.txnEventSink!==void 0)throw Error(`Cannot enable autoDebounceCommit while transaction is active`);if(this.debounceState!==void 0)throw Error(`autoDebounceCommit is already active`);this.debounceState={timeout:e,maxDebounceTime:t?.maxDebounceTime??1e4,timerId:void 0,maxTimerId:void 0,pendingEvents:[]}}disableAutoDebounceCommit(){if(this.debounceState===void 0)return;let{timerId:e,maxTimerId:t,pendingEvents:n}=this.debounceState;e!==void 0&&this.runtime.clearTimeout(e),t!==void 0&&this.runtime.clearTimeout(t),this.debounceState=void 0,n.length>0&&this.emit(`local`,n)}commit(){if(this.debounceState===void 0)return;let{timerId:e,maxTimerId:t,pendingEvents:n}=this.debounceState;e!==void 0&&(this.runtime.clearTimeout(e),this.debounceState.timerId=void 0),t!==void 0&&(this.runtime.clearTimeout(t),this.debounceState.maxTimerId=void 0),n.length>0&&(this.emit(`local`,n),this.debounceState.pendingEvents=[])}isAutoDebounceActive(){return this.debounceState!==void 0}close(){if(this.debounceState!==void 0&&this.disableAutoDebounceCommit(),this.txnEventSink!==void 0){let e=this.txnEventSink;this.txnEventSink=void 0,e.length>0&&this.emit(`local`,e)}}resetDebounceTimer(){this.debounceState!==void 0&&(this.debounceState.timerId!==void 0&&this.runtime.clearTimeout(this.debounceState.timerId),this.debounceState.timerId=this.runtime.setTimeout(()=>{this.commit()},this.debounceState.timeout),this.debounceState.maxTimerId===void 0&&this.debounceState.pendingEvents.length===1&&(this.debounceState.maxTimerId=this.runtime.setTimeout(()=>{this.commit()},this.debounceState.maxDebounceTime)))}},te=class{map=new Map;constructor(e){if(this.maxSize=e,!Number.isFinite(e)||e<=0)throw Error(`LruMap maxSize must be a positive number, got ${e}`)}get size(){return this.map.size}has(e){return this.map.has(e)}get(e){if(!this.map.has(e))return;let t=this.map.get(e);return this.map.delete(e),this.map.set(e,t),t}set(e,t){this.map.has(e)&&this.map.delete(e),this.map.set(e,t),this.evictIfNeeded()}delete(e){return this.map.delete(e)}clear(){this.map.clear()}evictIfNeeded(){for(;this.map.size>this.maxSize;){let e=this.map.keys().next().value;if(e===void 0)return;this.map.delete(e)}}},ne=class{map;constructor(e){this.map=new te(e)}has(e){return this.map.get(e)!==void 0}add(e){this.map.set(e,!0)}clear(){this.map.clear()}};const re={hi:2146959360,lo:1};var ie=class extends Error{};function d(){throw new ie}const ae=(e,t)=>e<t?-1:e>t?1:0,oe=(e,t)=>e===t,f=e=>BigInt(e.hi)*4294967296n+BigInt(e.lo>>>0),se=e=>-e,ce=(e,t)=>e+t,le=(e,t)=>e*t,ue=(e,t)=>e/t,de=(e,t)=>e%t,fe=(e,t)=>e>>BigInt(t),pe=e=>Number(BigInt.asUintN(32,e))|0,me=e=>Number(BigInt.asIntN(32,e));function p(e,t){if(t<0||t>=e.length)throw Error(`Index out of bounds`)}const he=(e,t)=>e.toString(t);function ge(e,t){let n=new Uint8Array(e);return t!==0&&n.fill(t),n}const m=(e,t)=>{e.push(t)},_e={$tag:0};function ve(e){this._0=e}ve.prototype.$tag=1;function ye(e){this._0=e}ye.prototype.$tag=2;function be(e){this._0=e}be.prototype.$tag=3;function xe(e){this._0=e}xe.prototype.$tag=4;const Se=function e(t){let n=e._view;return n===void 0&&(n=e._view=new DataView(new ArrayBuffer(8))),n.setUint32(0,t.hi),n.setUint32(4,t.lo),n.getFloat64(0)},Ce=function e(t){let n=e._view;return n===void 0&&(n=e._view=new DataView(new ArrayBuffer(8))),n.setFloat64(0,t),{hi:n.getInt32(0),lo:n.getInt32(4)}},we=e=>e.hi*4294967296+(e.lo>>>0),Te=e=>{if(isNaN(e))return{hi:0,lo:0};if(e>=0x8000000000000000)return{hi:2147483647,lo:4294967295};if(e<=-0x8000000000000000)return{hi:-2147483648,lo:0};let t=!1;e<0&&(t=!0,e=-e);let n=1/4294967296*e|0,r=e>>>0;return t&&(r===0?n=~n+1:(n=~n,r=~r+1)),{hi:n,lo:r}},Ee=new Uint8Array,h={hi:0,lo:255},De={hi:0,lo:0},Oe={hi:-1,lo:-1},ke={hi:-2147483648,lo:0};function Ae(e){this._0=e}Ae.prototype.$tag=0;function je(e){this._0=e}je.prototype.$tag=1;function Me(e){this._0=e}Me.prototype.$tag=2;const g={$tag:1},Ne={$tag:0},Pe={hi:0,lo:1},Fe={hi:0,lo:256};function _(e){this._0=e}_.prototype.$tag=0;function v(e){this._0=e}v.prototype.$tag=1;function Ie(e){this._0=e}Ie.prototype.$tag=0;function Le(e){this._0=e}Le.prototype.$tag=1;function Re(e){this._0=e}Re.prototype.$tag=0;function ze(e){this._0=e}ze.prototype.$tag=1;function Be(e){this._0=e}Be.prototype.$tag=2;function Ve(e){this._0=e}Ve.prototype.$tag=3;const He={$tag:4},Ue={$tag:5};function We(e){this._0=e}We.prototype.$tag=0;function Ge(e){this._0=e}Ge.prototype.$tag=1;function Ke(e){this._0=e}Ke.prototype.$tag=0;function qe(e){this._0=e}qe.prototype.$tag=1;function Je(e){this._0=e}Je.prototype.$tag=2;const Ye={$tag:3},Xe={$tag:4},Ze=Ht(re);function Qe(e){return d()}function $e(e){return d()}function et(e){return d()}function y(e){d()}function tt(e){return d()}function nt(e){return Vt(e)}function rt(e,t){if(e.end-e.start|0){let n=e.buf[e.start],r=e.buf,i=1+e.start|0,a={buf:r,start:i,end:e.end},o=T(n),s=o.end-o.start|0,c=a.end-a.start|0,l=0;for(;;){let e=l;if(e<c){let n=r[i+e|0],a=s,o=T(n);s=a+((o.end-o.start|0)+(t.end-t.start|0)|0)|0,l=e+1|0;continue}else break}s<<=1;let u=yt(s);if(D(u,o.str,o.start,o.end-o.start|0),wt(t.str,0,t.start,t.end)){let e=a.end-a.start|0,t=0;for(;;){let n=t;if(n<e){let e=r[i+n|0],a=T(e);D(u,a.str,a.start,a.end-a.start|0),t=n+1|0;continue}else break}}else{let e=a.end-a.start|0,n=0;for(;;){let a=n;if(a<e){let e=r[i+a|0],o=T(e);D(u,t.str,t.start,t.end-t.start|0),D(u,o.str,o.start,o.end-o.start|0),n=a+1|0;continue}else break}}return u.val}else return``}function it(e,t){t(t=>(jt(e,t),1))}function at(e,t){return rt({buf:e,start:0,end:e.length},t)}function ot(e,t){return ae(e,t)}function st(e,t){return oe(e,t)}function ct(e){return se(e)}function lt(e,t){return ce(e,t)}function ut(e,t){return le(e,t)}function dt(e,t){return ue(e,t)}function ft(e,t){return de(e,t)}function pt(e,t){return t<0&&y(`negative shift count`),fe(e,t)}function mt(e){let t=pe(pt(e,32)),n=pe(e);return Zt(Qt(nt(t),32),nt(n))}function b(e,t){if(t>=0&&t<(e.end-e.start|0)){let n=e.bytes,r=e.start+t|0;return p(n,r),n[r]}else return et(`index out of bounds: the len is from 0 to ${E(e.end-e.start|0)} but the index is ${E(t)}`)}function x(e,t,n){let r=e.length,i;if(n===void 0)i=r;else{let e=n;i=e<0?r+e|0:e}let a=t<0?r+t|0:t;return a>=0&&a<=i&&i<=r?{bytes:e,start:a,end:i}:$e(`Invalid index for View`)}function S(e,t,n){let r=e.end-e.start|0,i;if(n===void 0)i=r;else{let e=n;i=e<0?r+e|0:e}let a=t<0?r+t|0:t;return a>=0&&a<=i&&i<=r?{bytes:e.bytes,start:e.start+a|0,end:(e.start+a|0)+(i-a|0)|0}:$e(`Invalid index for View`)}function ht(e){return t=>{let n=e.end-e.start|0,r=0;for(;;){let i=r;if(i<n){if(t(b(e,i))!==1)return 0;r=i+1|0;continue}else return 1}}}function gt(e){let t={val:0},n=e.end-e.start|0;return()=>{if(t.val<n){let n=t.val,r=e.bytes,i=e.start+n|0;p(r,i);let a=r[i];return t.val=t.val+1|0,a}else return-1}}function C(e){return on(e.end-e.start|0,t=>ln(e,t))}function _t(e){let t=Pt(e);return C({buf:t,start:0,end:t.length})}function w(e){return Vt(e)}function T(e){return{str:e,start:0,end:e.length}}function vt(e,t,n,r,i){if(e===n&&t<r){let a=0;for(;;){let o=a;if(o<i){let i=t+o|0,s=r+o|0;p(n,s),p(e,i),e[i]=n[s],a=o+1|0;continue}else return}}else{let a=i-1|0;for(;;){let i=a;if(i>=0){let o=t+i|0,s=r+i|0;p(n,s),p(e,o),e[o]=n[s],a=i-1|0;continue}else return}}}function yt(e){return{val:``}}function bt(e,t){let n=e;n.val=`${n.val}${String.fromCodePoint(t)}`}function xt(e,t){let n=e;n.val=`${n.val}${t}`}function St(e,t){return ot(e,t)>0}function E(e){let t=yt(0);return It(e,{self:t,method_0:xt,method_1:D,method_2:bt}),t.val}function Ct(e,t){return he(e,t)}function wt(e,t,n,r){let i;i=r===void 0?e.length:r;let a=n,o=0;for(;;){let n=a,r=o;if(n<i&&r<t){let t=e.charCodeAt(n);if(55296<=t&&t<=56319&&(n+1|0)<i){let t=n+1|0,i=e.charCodeAt(t);if(56320<=i&&i<=57343){a=n+2|0,o=r+1|0;continue}else y(`invalid surrogate pair`)}a=n+1|0,o=r+1|0;continue}else return r===t&&n===i}}function Tt(e,t,n){let r=e.length,i;return i=n===void 0?r:n,t>=0&&t<=i&&i<=r?e.substring(t,i):d()}function D(e,t,n,r){let i=e;i.val=`${i.val}${Tt(t,n,n+r|0)}`}function Et(e){return[]}function Dt(e){return[]}function Ot(e){return[]}function kt(e,t){m(e,t)}function At(e,t){m(e,t)}function O(e,t){m(e,t)}function k(e,t){m(e,t)}function jt(e,t){m(e,t)}function Mt(e){return String.fromCodePoint(e)}function Nt(e,t){let n={val:_e};e(e=>(t(e),1));let r=n.val;switch(r.$tag){case 0:return;case 1:r._0;return;case 2:return r._0;case 3:d();return;default:d();return}}function Pt(e){let t=[];return Nt(e,e=>{O(t,e)}),t}function Ft(e){return e()}function It(e,t){t.method_0(t.self,Ct(e,10))}function Lt(e){return t=>{let n=e.length,r=0;for(;;){let i=r;if(i<n){let n=e[i];if(t(n)!==1)return 0;r=i+1|0;continue}else return 1}}}function Rt(e,t,n){let r=e.length,i;if(n===void 0)i=r;else{let e=n;i=e<0?r+e|0:e}let a=t<0?r+t|0:t;return a>=0&&a<=i&&i<=r?{buf:e,start:a,end:i}:tt(`View index out of bounds`)}function zt(e){return{hi:0,lo:e}}function Bt(e){return zt(e)}function Vt(e){return Bt(e)}function Ht(e){return Se(e)}function Ut(e){return{hi:e>>31&-1,lo:e|0}}function Wt(e){return Ut(e)}function Gt(e){return e.lo}function A(e){return Gt(e)&255}function Kt(e,t){return{hi:e.hi&t.hi,lo:e.lo&t.lo}}function qt(e,t){return{hi:e.hi|t.hi,lo:e.lo|t.lo}}function Jt(e,t){return{hi:e.hi^t.hi,lo:e.lo^t.lo}}function Yt(e,t){let n=t&63;if(n===0)return e;if(n<32){let t=e.hi,r=e.lo,i=t,a=r;return{hi:i<<n|a>>>(32-n|0)|0,lo:a<<n}}else return{hi:e.lo<<(n-32|0),lo:0}}function Xt(e,t){let n=t&63;return n===0?e:n<32?{hi:e.hi>>>n|0,lo:e.lo>>>n|e.hi<<(32-n|0)}:{hi:0,lo:e.hi>>>(n-32|0)|0}}function Zt(e,t){return qt(e,t)}function Qt(e,t){return Yt(e,t)}function $t(e){return we(e)}function en(e){return $t(e)}function tn(e){return Se(e)}function nn(e){return Ce(e)}function rn(e,t){let n=e,r=t;return n.hi===r.hi&&n.lo===r.lo}function j(e,t){return Kt(e,t)}function M(e,t){return qt(e,t)}function N(e,t){return Jt(e,t)}function P(e,t){return Yt(e,t)}function F(e,t){return Xt(e,t)}function an(e){return Te(e)}function on(e,t){if(e<=0)return Ee;let n=ge(e,t(0)),r=1;for(;;){let i=r;if(i<e){p(n,i),n[i]=t(i),r=i+1|0;continue}else break}return n}function sn(e){console.log(e)}function cn(e,t,n,r,i){let a=(t+i|0)-1|0,o=(r+i|0)-1|0,s=e.length,c=n.length;if(i>=0&&t>=0&&a<s&&r>=0&&o<c){vt(e,t,n,r,i);return}else{d();return}}function ln(e,t){if(t>=0&&t<(e.end-e.start|0)){let n=e.buf,r=e.start+t|0;return p(n,r),n[r]}else return et(`index out of bounds: the len is from 0 to ${E(e.end-e.start|0)} but the index is ${E(t)}`)}function un(e){let t=e.length,n=Array(t),r=0;for(;;){let i=r;if(i<t){n[i]=e[(t-i|0)-1|0],r=i+1|0;continue}else break}return n}function dn(e,t){let n=e.data.length<=0?1:e.data.length,r,i=n;for(;;){let e=i;if(e>=t){r=e;break}i=Math.imul(e,2)|0}if(r!==e.data.length){let t=ge(r,0);vt(t,0,e.data,0,e.len),e.data=t;return}else return}function I(e,t){dn(e,e.len+1|0);let n=e.data,r=e.len;p(n,r),n[r]=t,e.len=e.len+1|0}function L(e){return C(Rt(e.data,0,e.len))}function R(e){return{data:ge(e<1?1:e,0),len:0}}function fn(e,t){let n=t.length;dn(e,e.len+n|0),cn(e.data,e.len,t,0,n),e.len=e.len+n|0}function pn(e){switch(e){case 0:return`40`;case 1:return`41`;case 2:return`42`;case 3:return`43`;case 4:return`44`;case 5:return`45`;case 6:return`46`;case 7:return`47`;default:return`49`}}function mn(e){switch(e){case 0:return`30`;case 1:return`31`;case 2:return`32`;case 3:return`33`;case 4:return`34`;case 5:return`35`;case 6:return`36`;case 7:return`37`;default:return`39`}}function hn(e){let t=[],n=e.color;n===void 0||k(t,mn(n));let r=e.bg_color;r===void 0||k(t,pn(r));let i=e.formats,a=i.length,o=0;for(;;){let e=o;if(e<a){switch(i[e]){case 0:k(t,`1`);break;case 1:k(t,`4`);break;case 2:k(t,`5`);break;case 3:k(t,`7`);break;case 4:k(t,`8`);break;case 5:k(t,`9`);break;default:k(t,`3`)}o=e+1|0;continue}else break}return t.length>0?`[${at(t,{str:`;`,start:0,end:1})}m${e.str}[0m`:e.str}function gn(e){return{str:e,bg_color:void 0,color:void 0,formats:[]}}function _n(e){return{str:e.str,bg_color:e.bg_color,color:1,formats:e.formats}}function vn(e){return{str:e.str,bg_color:e.bg_color,color:3,formats:e.formats}}function yn(e){return{str:e.str,bg_color:e.bg_color,color:4,formats:e.formats}}function bn(e){let t=e.str,n=e.bg_color,r=e.color,i=[];return jt(i,0),it(i,Lt(e.formats)),{str:t,bg_color:n,color:r,formats:i}}function xn(e,t){let n=`${hn(_n(bn(gn(`Panic: `))))}${hn(vn(gn(e)))} at ${hn(yn(gn(t)))}`;sn(n),y(n)}function Sn(e){let t=Ot(0),n=0;for(;n<e.length;){let r=n;p(e,r);let i=e.charCodeAt(r);if(i>=55296&&i<=56319&&(n+1|0)<e.length){let r=n+1|0;p(e,r);let a=e.charCodeAt(r);if(a>=56320&&a<=57343){let e=(65536+(i-55296<<10)|0)+(a-56320|0)|0;O(t,(240|e>>18)&255),O(t,(128|e>>12&63)&255),O(t,(128|e>>6&63)&255),O(t,(128|e&63)&255),n=n+1|0}else O(t,(224|i>>12)&255),O(t,(128|i>>6&63)&255),O(t,(128|i&63)&255)}else i<128?O(t,i&255):i<2048?(O(t,(192|i>>6)&255),O(t,(128|i&63)&255)):(O(t,(224|i>>12)&255),O(t,(128|i>>6&63)&255),O(t,(128|i&63)&255));n=n+1|0}return C({buf:t,start:0,end:t.length})}function Cn(e){return{bytes:Sn(e)}}function wn(e){let t=0;for(;t<(e.end-e.start|0);){let n=b(e,t);if(!(n&128))t=t+1|0;else if((n&224)==192){if((t+1|0)>=(e.end-e.start|0)||(b(e,t+1|0)&192)!=128)return!1;t=t+2|0}else if((n&240)==224){if((t+2|0)>=(e.end-e.start|0))return!1;let n=b(e,t+1|0),r=b(e,t+2|0),i;if(i=(n&192)==128?(r&192)!=128:!0,i)return!1;t=t+3|0}else if((n&248)==240){if((t+3|0)>=(e.end-e.start|0))return!1;let n=b(e,t+1|0),r=b(e,t+2|0),i=b(e,t+3|0),a;if((n&192)!=128)a=!0;else{let e;e=(r&192)==128?(i&192)!=128:!0,a=e}if(a)return!1;t=t+4|0}else return!1}return!0}function Tn(e){if(wn(S(e,0,void 0)))return{bytes:_t(ht(e))}}function En(e){let t=0,n=``;for(;t<e.length;){let r=t;p(e,r);let i=e[r],a;if(!(i&128))a=i;else if((i&224)==192){if((t+1|0)>=e.length)return;let n=t+1|0;p(e,n);let r=e[n];if((r&192)!=128)return;t=t+1|0,a=(i&31)<<6|r&63}else if((i&240)==224){if((t+2|0)>=e.length)return;let n=t+1|0;p(e,n);let r=e[n],o=t+2|0;p(e,o);let s=e[o],c;if(c=(r&192)==128?(s&192)!=128:!0,c)return;t=t+2|0,a=(i&15)<<12|(r&63)<<6|s&63}else if((i&248)==240){if((t+3|0)>=e.length)return;let n=t+1|0;p(e,n);let r=e[n],o=t+2|0;p(e,o);let s=e[o],c=t+3|0;p(e,c);let l=e[c],u;if((r&192)!=128)u=!0;else{let e;e=(s&192)==128?(l&192)!=128:!0,u=e}if(u)return;t=t+3|0,a=(i&7)<<18|(r&63)<<12|(s&63)<<6|l&63}else return;n=`${n}${Mt(a)}`,t=t+1|0}return n}function Dn(e){let t=En(e.bytes);return t===void 0?d():t}function On(e){return nn(e)}function kn(e){return tn(e)}function An(e){let t=Ot(0);return O(t,A(j(F(e,56),h))),O(t,A(j(F(e,48),h))),O(t,A(j(F(e,40),h))),O(t,A(j(F(e,32),h))),O(t,A(j(F(e,24),h))),O(t,A(j(F(e,16),h))),O(t,A(j(F(e,8),h))),O(t,A(j(e,h))),C({buf:t,start:0,end:t.length})}function jn(e){e.length!==8&&xn(`Invalid byte array length`,`/Users/zxch3n/Code/flock/moon/memcomparable/utils.mbt:28:5-28:54`);let t=De,n=t;p(e,0),t=M(n,P(w(e[0]),56));let r=t;p(e,1),t=M(r,P(w(e[1]),48));let i=t;p(e,2),t=M(i,P(w(e[2]),40));let a=t;p(e,3),t=M(a,P(w(e[3]),32));let o=t;p(e,4),t=M(o,P(w(e[4]),24));let s=t;p(e,5),t=M(s,P(w(e[5]),16));let c=t;p(e,6),t=M(c,P(w(e[6]),8));let l=t;return p(e,7),t=M(l,w(e[7])),t}function Mn(){return{parts:Dt(0)}}function z(e,t){kt(e.parts,t)}function Nn(e){return e===e?e:e<0?-Ze:Ze}function Pn(e,t){I(t,1);let n=gt(e);for(;;){let e=Ft(n);if(e===-1)break;{let n=e;I(t,n),n===0&&I(t,255);continue}}I(t,0)}function Fn(e,t){I(t,2);let n=e.bytes,r=n.length,i=0;for(;;){let e=i;if(e<r){let r=n[e];I(t,r),r===0&&I(t,255),i=e+1|0;continue}else break}I(t,0)}function In(e,t){I(t,33);let n=Nn(e),r=An(n<0?N(On(n),Oe):N(On(n),ke)),i=r.length,a=0;for(;;){let e=a;if(e<i){let n=r[e];I(t,n),a=e+1|0;continue}else return}}function Ln(e){let t=[],n=e;for(;St(n,0n);)O(t,me(ft(n,256n))&255),n=dt(n,256n);let r=un(t);return C({buf:r,start:0,end:r.length})}function Rn(e,t){if(st(e,0n)){I(t,20);return}let n=St(e,0n),r=Ln(n?e:ct(e)),i=r.length;if(n===!1){i<=8?I(t,(20-(i&255)|0)&255):(I(t,11),i>255&&y(`n is too large`),I(t,(i&255^255)&255));let e=R(0),n=0;for(;;){let t=n;if(t<r.length){p(r,t);let i=r[t];I(e,(i^255)&255),n=t+1|0;continue}else break}fn(t,L(e));return}else{i<=8?I(t,(20+(i&255)|0)&255):(I(t,29),i>255&&y(`n is too large`),I(t,i&255)),fn(t,r);return}}function zn(e,t){switch(e.$tag){case 0:{let n=e._0;Pn(x(n,0,n.length),t);return}case 1:{let n=e._0;Fn(n,t);return}case 2:{let n=e._0;Rn(n,t);return}case 3:{let n=e._0;In(n,t);return}case 4:I(t,38);return;default:I(t,39);return}}function Bn(e){let t=R(0),n=e.parts,r=n.length,i=0;for(;;){let e=i;if(e<r){let r=n[e];zn(r,t),i=e+1|0;continue}else break}return L(t)}function Vn(e,t){let n=R(0),r=t;for(;r<(e.end-e.start|0);){let t=b(e,r);if(r=r+1|0,t===0){let t;if(t=r<(e.end-e.start|0)?b(e,r)===255:!1,t){I(n,0),r=r+1|0;continue}else{let e=L(n);return new je({_0:x(e,0,e.length),_1:r})}}I(n,t)}return new Ae(g)}function B(e){let t=f(De),n=f(Pe),r=(e.end-e.start|0)-1|0;for(;;){let i=r;if(i>=0){let a=f(Wt(b(e,i)));t=lt(t,ut(n,a)),n=ut(n,f(Fe)),r=i-1|0;continue}else break}return t}function Hn(e,t){let n;if(n=20<=t?t<=28:!1,n){let n=(t-20|0)&255;if((e.end-e.start|0)<n)return new _(g);let r=S(e,0,n);return new v({_0:S(e,n,void 0),_1:B(r)})}else{let n;if(n=12<=t?t<20:!1,n){let n=(20-t|0)&255;if((e.end-e.start|0)<n)return new _(g);let r=S(e,0,n),i=S(e,n,void 0),a=R(0),o=0;for(;;){let e=o;if(e<(r.end-r.start|0)){I(a,(b(r,e)^255)&255),o=e+1|0;continue}else break}let s=L(a);return new v({_0:i,_1:ct(B(x(s,0,s.length)))})}else if(t===11){if((e.end-e.start|0)<1)return new _(g);let t=(b(e,0)^255)&255;if((e.end-e.start|0)<(t+1|0))return new _(g);let n=S(e,1,t+1|0),r=S(e,t+1|0,void 0),i=R(0),a=0;for(;;){let e=a;if(e<(n.end-n.start|0)){I(i,(b(n,e)^255)&255),a=e+1|0;continue}else break}let o=L(i);return new v({_0:r,_1:ct(B(x(o,0,o.length)))})}else if(t===29){if((e.end-e.start|0)<1)return new _(g);let t=b(e,0);if((e.end-e.start|0)<(t+1|0))return new _(g);let n=S(e,1,t+1|0);return new v({_0:S(e,t+1|0,void 0),_1:B(n)})}else return new _(new Me(t))}}function Un(e,t){if((t+8|0)>(e.end-e.start|0))return new Ie(g);let n=Ot(0),r=0;for(;;){let i=r;if(i<8){O(n,b(e,t+i|0)),r=i+1|0;continue}else break}let i=jn(C({buf:n,start:0,end:n.length}));return new Le({_0:rn(j(i,ke),De)?kn(N(i,Oe)):kn(N(i,ke)),_1:t+8|0})}function Wn(e){let t=Mn(),n=0;for(;n<(e.end-e.start|0);){let r=b(e,n);if(n=n+1|0,r===2){let r=Vn(e,n),i;if(r.$tag===1)i=r._0;else return r;let a=i._0,o=i._1,s=Tn(a);if(s===void 0)return new We(Ne);z(t,new ze(s)),n=o}else if(r===1){let r=Vn(e,n),i;if(r.$tag===1)i=r._0;else return r;let a=i._0,o=i._1;z(t,new Re(_t(ht(a)))),n=o}else if(r>=11&&r<=29){let i=Hn(S(e,n,void 0),r),a;if(i.$tag===1)a=i._0;else return i;let o=a._0,s=a._1;z(t,new Be(s)),n=(e.end-e.start|0)-(o.end-o.start|0)|0}else if(r===33){let r=Un(e,n),i;if(r.$tag===1)i=r._0;else return r;let a=i._0,o=i._1;z(t,new Ve(a)),n=o}else if(r===38)z(t,He);else if(r===39)z(t,Ue);else return new We(new Me(r))}return new Ge(t)}function Gn(e){switch(e.$tag){case 0:{let t=e._0;return new Je(t)}case 1:{let t=e._0;return new qe(Dn(t))}case 2:{let t=e._0;return new Ke(en(mt(t)))}case 3:{let t=e._0;return new Ke(t)}case 4:return Xe;default:return Ye}}function Kn(e){switch(e.$tag){case 2:{let t=e._0;return new Re(t)}case 1:{let t=e._0;return new ze(Cn(t))}case 0:{let t=e._0;return en(an(t))===t?new Be(f(an(t))):new Ve(t)}case 3:return Ue;default:return He}}function qn(e){let t=Mn(),n=e.length,r=0;for(;;){let i=r;if(i<n){let n=e[i];kt(t.parts,Kn(n)),r=i+1|0;continue}else break}return Bn(t)}function Jn(e){let t;_L:{_L$2:{let n=Wn(x(e,0,e.length));if(n.$tag===1)t=n._0;else{n._0;break _L$2}break _L}t=Qe(`Failed to decode key`)}let n=Et(0),r=t.parts,i=r.length,a=0;for(;;){let e=a;if(e<i){let t=r[e];At(n,Gn(t)),a=e+1|0;continue}else break}return n}function Yn(e){if(typeof e==`number`){if(!Number.isFinite(e))throw TypeError(`Key parts must be finite numbers`);return{$tag:0,_0:e}}if(typeof e==`string`)return{$tag:1,_0:e};if(e===!0)return{$tag:3};if(e===!1)return{$tag:4};throw TypeError(`Key parts must be strings, numbers, or booleans`)}function Xn(e){if(e instanceof Uint8Array)return e;if(e&&typeof e==`object`){let t=e.buf;if(t instanceof Uint8Array){let n=e.start??0,r=e.end??t.length;return t.subarray(n,r)}}throw TypeError(`Invalid bytes payload in memcomparable decode`)}function Zn(e){switch(e?.$tag){case 0:return e._0;case 1:return e._0;case 3:return!0;case 4:return!1;case 2:return Xn(e._0);default:throw TypeError(`Unsupported memcomparable key part`)}}function V(e){return qn(e.map(Yn))}function Qn(e){return Jn(e).map(e=>Zn(e))}function $n(e,t){let n=Math.min(e.length,t.length);for(let r=0;r<n;r+=1)if(e[r]!==t[r])return e[r]<t[r]?-1:1;return e.length===t.length?0:e.length<t.length?-1:1}function er(e){if(e.length===0)return;let t=Array.from(e);for(let e=t.length-1;e>=0;--e){let n=t[e];if(n<255)return t[e]=n+1,new Uint8Array(t.slice(0,e+1))}}function tr(e){return JSON.stringify(e)}function nr(){return{now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),randomUUID:()=>{try{if(typeof crypto<`u`&&typeof crypto.randomUUID==`function`)return crypto.randomUUID()}catch{}return`${Date.now()}_${Math.random().toString(16).slice(2)}`}}}function rr(e){if(!(typeof BroadcastChannel>`u`))try{let t=new BroadcastChannel(e);return{postMessage:e=>{try{t.postMessage(e)}catch{}},subscribe:e=>{let n=t=>{e(t.data)};return t.addEventListener(`message`,n),()=>{t.removeEventListener(`message`,n)}},close:()=>{try{t.close()}catch{}}}}catch{return}}function ir(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.t===`req`||t.t===`res`||t.t===`commit`}function ar(e){return e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:{name:`Error`,message:String(e)}}function or(e){return e instanceof Error?!!(e.name===`HostLost`||e.message.includes(`Timed out waiting for host response`)):!1}function sr(e){return e<=0?25:Math.min(500,25*2**(e-1))}function H(e,t){return e.origin===t&&e.source===`local`}function cr(e,t){return`${e}|${t}`}function lr(e){let t=Error(e.message);return t.name=e.name,e.stack&&(t.stack=e.stack),t}var ur=class{runtime;tabId;roleValue;roleListeners;roleUnsubscribe;closed;constructor(e,t,n){this.runtime=e,this.tabId=t,this.roleValue=n.getRole(),this.roleListeners=new Set,this.roleUnsubscribe=n.subscribeRoleChange?.(e=>{this.setRole(e)}),this.closed=!1}getRole(){return this.roleValue}isHost(){return this.roleValue===`host`}subscribeRoleChange(e){this.roleListeners.add(e);try{e(this.roleValue)}catch{}return()=>{this.roleListeners.delete(e)}}setRole(e){if(e!==this.roleValue){this.roleValue=e;for(let t of this.roleListeners)try{t(e)}catch{}}}closeRole(){this.roleUnsubscribe?.(),this.roleUnsubscribe=void 0,this.setRole(`unknown`)}},dr=class extends ur{writeQueue;ingestCommit;executeWriteRequest;constructor(e){super(e.runtime,e.tabId,e.roleProvider),this.ingestCommit=e.ingestCommit,this.executeWriteRequest=e.executeWriteRequest,this.writeQueue=Promise.resolve()}enqueueWrite(e){let t=this.writeQueue.then(e,e);return this.writeQueue=t.then(()=>void 0,()=>void 0),t}async dispatchWriteRequest(e){if(this.closed)throw Error(`FlockSQLite is closed`);let t=this.runtime.randomUUID(),{commit:n,result:r}=await this.enqueueWrite(()=>this.executeWriteRequest(e,this.tabId,t));return this.ingestCommit(n,H(n,this.tabId)),{commit:n,result:r}}close(){this.closed=!0,this.closeRole()}},fr=class extends ur{transport;transportUnsubscribe;pendingRequests;hostResponseCache;hostInFlight;writeQueue;ingestCommit;executeWriteRequest;constructor(e){super(e.runtime,e.tabId,e.roleProvider),this.transport=e.transport,this.transportUnsubscribe=this.transport.subscribe(e=>{try{this.handleTransportMessage(e)}catch{}}),this.pendingRequests=new Map,this.hostResponseCache=new te(1024),this.hostInFlight=new Map,this.writeQueue=Promise.resolve(),this.ingestCommit=e.ingestCommit,this.executeWriteRequest=e.executeWriteRequest}enqueueWrite(e){let t=this.writeQueue.then(e,e);return this.writeQueue=t.then(()=>void 0,()=>void 0),t}shouldForwardWrites(){return this.roleValue!==`host`}handleTransportMessage(e){if(ir(e)){if(e.t===`res`){if(e.to!==this.tabId)return;let t=this.pendingRequests.get(e.id);if(!t)return;this.runtime.clearTimeout(t.timeoutId),this.pendingRequests.delete(e.id),t.resolve(e);return}if(e.t===`commit`){let t=e.commit;this.ingestCommit(t,H(t,this.tabId));return}if(e.t===`req`){if(e.from===this.tabId||this.roleValue!==`host`||this.closed)return;this.processHostRequest(e)}}}broadcastCommit(e){this.closed||this.roleValue===`host`&&this.transport.postMessage({t:`commit`,commit:e})}async forwardWriteRequest(e,t,n=3e3){if(this.closed)throw Error(`FlockSQLite is closed`);let r={t:`req`,from:this.tabId,id:t,payload:e},i=await new Promise((e,i)=>{let a=this.runtime.setTimeout(()=>{this.pendingRequests.delete(t),i(Error(`Timed out waiting for host response`))},n);this.pendingRequests.set(t,{resolve:e,reject:i,timeoutId:a}),this.transport.postMessage(r)});if(!i.ok)throw i.error?lr(i.error):Error(`Host rejected request`);let a=i.commit;return a&&this.ingestCommit(a,H(a,this.tabId)),{commit:a,result:i.result}}async dispatchWriteRequest(e){if(this.closed)throw Error(`FlockSQLite is closed`);let t=this.runtime.randomUUID(),n;for(let r=1;r<=5;r+=1){if(!this.shouldForwardWrites()){let{commit:n,result:r}=await this.enqueueWrite(()=>this.executeWriteRequest(e,this.tabId,t));return this.ingestCommit(n,H(n,this.tabId)),this.broadcastCommit(n),{commit:n,result:r}}try{let n=await this.forwardWriteRequest(e,t);if(!n.commit)throw Error(`Host did not return commit`);return{commit:n.commit,result:n.result}}catch(e){if(n=e,r>=5||!or(e))throw e;await new Promise(e=>{this.runtime.setTimeout(()=>e(),sr(r))})}}throw n??Error(`Failed to dispatch write request`)}async processHostRequest(e){let t=cr(e.from,e.id),n=this.hostResponseCache.get(t);if(n){n.ok&&n.commit&&this.broadcastCommit(n.commit),this.transport.postMessage(n);return}let r=this.hostInFlight.get(t);r||(r=this.enqueueWrite(async()=>{if(this.roleValue!==`host`||this.closed)return{t:`res`,to:e.from,id:e.id,ok:!1,error:{name:`HostLost`,message:`Host role was lost`}};try{let{commit:t,result:n}=await this.executeWriteRequest(e.payload,e.from,e.id);return this.ingestCommit(t,H(t,this.tabId)),this.broadcastCommit(t),{t:`res`,to:e.from,id:e.id,ok:!0,commit:t,result:n}}catch(t){return{t:`res`,to:e.from,id:e.id,ok:!1,error:ar(t)}}}),this.hostInFlight.set(t,r),r.finally(()=>{this.hostInFlight.delete(t)}));let i=await r;this.hostResponseCache.set(t,i),this.transport.postMessage(i)}close(){if(!this.closed){this.closed=!0,this.transportUnsubscribe?.(),this.transportUnsubscribe=void 0,this.transport.close?.();for(let{reject:e,timeoutId:t}of this.pendingRequests.values()){this.runtime.clearTimeout(t);try{e(Error(`FlockSQLite closed`))}catch{}}this.pendingRequests.clear(),this.closeRole()}}};function pr(e){return e.transport?new fr({...e,transport:e.transport}):new dr(e)}const mr=new TextEncoder,hr=new TextDecoder,gr=globalThis.structuredClone;function _r(e){return mr.encode(e).length}function U(e){return typeof e==`string`&&_r(e)<128}function vr(){let e=new Uint8Array(32),t=typeof crypto<`u`?crypto:void 0;if(t?.getRandomValues)t.getRandomValues(e);else if(t?.randomBytes){let n=t.randomBytes(32);e.set(n)}else for(let t=0;t<32;t+=1)e[t]=Math.floor(Math.random()*256);return Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}function W(e){if(e===void 0)return vr();if(!U(e))throw TypeError(`peerId must be a UTF-8 string under 128 bytes`);return e}function G(e){return e===void 0?e:gr?gr(e):JSON.parse(JSON.stringify(e))}function K(e){if(!(!e||typeof e!=`object`||Array.isArray(e)))return G(e)}function yr(e){return K(e)??{}}function br(e,t){if(!(!t||typeof t!=`object`)){if(`data`in t){let n=t.data;e.data=n===void 0?void 0:G(n)}`metadata`in t&&(e.metadata=K(t.metadata))}}function q(e){let t={};return br(t,e),t}function J(e,t){let n=q(e);return br(n,t),n}function xr(e,t){if(e===t)return 0;let n=Math.min(e.length,t.length);for(let r=0;r<n;r+=1){let n=e[r]-t[r];if(n!==0)return n}return e.length-t.length}function Sr(e){if(!e||typeof e!=`object`)return[];let t=[];for(let[n,r]of Object.entries(e)){if(!r||!U(n))continue;let{physicalTime:e,logicalCounter:i}=r;if(typeof e!=`number`||!Number.isFinite(e)||typeof i!=`number`||!Number.isFinite(i))continue;let a=mr.encode(n);t.push({peer:n,peerBytes:a,timestamp:Math.trunc(e),counter:Math.max(0,Math.trunc(i))})}return t.sort((e,t)=>{if(e.timestamp!==t.timestamp)return e.timestamp-t.timestamp;let n=xr(e.peerBytes,t.peerBytes);return n===0?e.counter-t.counter:n}),t}function Y(e,t){if(!Number.isFinite(e)||e<0)throw TypeError(`leb128 values must be finite and non-negative`);let n=Math.trunc(e);if(n===0){t.push(0);return}for(;n>0;){let e=n%128;n=Math.floor(n/128),t.push(n>0?e|128:e)}}function Cr(e,t){Y(e.length,t);for(let n=0;n<e.length;n+=1)t.push(e[n])}const X=new Uint8Array([86,69,86,69]);function wr(e){let t=Sr(e),n=Array.from(X);if(t.length===0)return Uint8Array.from(n);let r=0;for(let e=0;e<t.length;e+=1){let i=t[e];if(i.timestamp<0)throw TypeError(`timestamp must be non-negative`);if(e===0)Y(i.timestamp,n),r=i.timestamp;else{let e=i.timestamp-r;if(e<0)throw TypeError(`version vector timestamps must be non-decreasing`);Y(e,n),r=i.timestamp}Y(i.counter,n),Cr(i.peerBytes,n)}return Uint8Array.from(n)}function Z(e,t){let n=0,r=1,i=0;for(;t+i<e.length;){let a=e[t+i];if(i+=1,n+=(a&127)*r,!(a&128))break;r*=128}return[n,i]}function Tr(e,t){let[n,r]=Z(e,t),i=t+r,a=i+n;if(a>e.length)throw TypeError(`varString length exceeds buffer`);let o=e.subarray(i,a);return[hr.decode(o),r+n]}function Er(e){return e.length>=4&&e[0]===X[0]&&e[1]===X[1]&&e[2]===X[2]&&e[3]===X[3]}function Dr(e){let t=0,[n,r]=Z(e,t);t+=r;let[i,a]=Z(e,t);t+=a;let o={};for(let r=0;r<n;r+=1){let[n,r]=Tr(e,t);if(t+=r,!U(n))throw TypeError(`invalid peer id in encoded version vector`);let[a,s]=Z(e,t);t+=s;let[c,l]=Z(e,t);t+=l,o[n]={physicalTime:i+a,logicalCounter:c}}return o}function Or(e){let t=4,n={};if(t===e.length)return n;let[r,i]=Z(e,t);t+=i;let[a,o]=Z(e,t);t+=o;let[s,c]=Tr(e,t);if(t+=c,!U(s))throw TypeError(`invalid peer id in encoded version vector`);n[s]={physicalTime:r,logicalCounter:a};let l=r;for(;t<e.length;){let[r,i]=Z(e,t);t+=i;let[a,o]=Z(e,t);t+=o;let[s,c]=Tr(e,t);if(t+=c,!U(s))throw TypeError(`invalid peer id in encoded version vector`);let u=l+r;if(u<l)throw TypeError(`version vector timestamps must be non-decreasing`);n[s]={physicalTime:u,logicalCounter:a},l=u}return n}function kr(e){return Er(e)?Or(e):Dr(e)}function Ar(e){return wr(e)}function jr(e){return kr(e)}function Q(e,t){let n={c:Rr(e)};t.data!==void 0&&(n.d=G(t.data));let r=K(t.metadata);return r!==void 0&&(n.m=r),n}function Mr(e){return!e||typeof e!=`object`?{accept:!0}:`accept`in e?e.accept?{accept:!0}:{accept:!1,reason:e.reason??`rejected`}:{accept:!0}}function Nr(e){return typeof e==`object`&&!!e&&(Object.prototype.hasOwnProperty.call(e,`hooks`)||Object.prototype.hasOwnProperty.call(e,`from`)||Object.prototype.hasOwnProperty.call(e,`pruneTombstonesBefore`)||Object.prototype.hasOwnProperty.call(e,`peerId`))}function Pr(e){return typeof e==`object`&&!!e&&Object.prototype.hasOwnProperty.call(e,`bundle`)}function Fr(e){if(e)try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return t}catch{}}function $(e){if(e!=null)return JSON.parse(e)}function Ir(e){let t=e.split(`,`);if(t.length<3)return{physicalTime:0,logicalCounter:0,peerId:``};let n=Number(t[0]),r=Number(t[1]),i=t.slice(2).join(`,`);return{physicalTime:Number.isFinite(n)?n:0,logicalCounter:Number.isFinite(r)?Math.trunc(r):0,peerId:U(i)?i:``}}function Lr(e,t,n){if(!(typeof e!=`number`||typeof t!=`number`||typeof n!=`string`)&&U(n)&&!(!Number.isFinite(e)||!Number.isFinite(t)))return{physicalTime:e,logicalCounter:Math.trunc(t),peerId:n}}function Rr(e){return`${e.physicalTime},${e.logicalCounter},${e.peerId}`}function zr(e,t){return e.physicalTime===t.physicalTime?e.logicalCounter===t.logicalCounter?e.peerId===t.peerId?0:e.peerId>t.peerId?1:-1:e.logicalCounter>t.logicalCounter?1:-1:e.physicalTime>t.physicalTime?1:-1}function Br(e){if(!e)return;let{physicalTime:t,logicalCounter:n}=e;if(!(!Number.isFinite(t)||!Number.isFinite(n)))return{physicalTime:t,logicalCounter:Math.trunc(n)}}function Vr(e,t){if(t.length===0)return!0;if(e.length<t.length)return!1;for(let n=0;n<t.length;n+=1)if(e[n]!==t[n])return!1;return!0}async function Hr(e){return e.map(e=>({key:e.key,data:e.data,metadata:e.metadata,physical:e.physical,logical:e.logical,peer:e.peer}))}function Ur(e){if(!e)return``;if(typeof e!=`string`)throw TypeError(`tablePrefix must be a string`);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw TypeError(`tablePrefix must start with a letter/underscore and use only letters, digits, or underscores`);return e}function Wr(e){return{kv:`${e}kv`,overridden:`${e}overridden`,meta:`${e}meta`,idxKvPeerClock:`${e}idx_kv_peer_clock_key`,idxOverriddenKey:`${e}idx_overridden_key`,idxOverriddenSupersededAt:`${e}idx_overridden_superseded_at`}}function Gr(e){if(e===`host`||e===`participant`||e===`unknown`)return e}function Kr(e){let t=e.getRole?.(),n=Gr(t);if(n)return n;let r=e.getSQLiteInfo?.();if(r&&typeof r==`object`){let{isHost:e,isReady:t}=r;if(e===!0&&t===!0)return`host`;if(t===!1)return`unknown`;if(t===!0)return`participant`}return`host`}function qr(e){let t=e.subscribeRoleChange;return{getRole:()=>Kr(e),subscribeRoleChange:typeof t==`function`?n=>t.call(e,e=>{let t=Gr(e);t&&n(t)}):void 0}}function Jr(e,t){return t?`flock:rpc:${e}:${t}`:`flock:rpc:${e}`}function Yr(e,t,n){if(typeof n==`string`&&n.length>0)return n;let r=e.getSQLiteInfo?.();if(r&&typeof r==`object`){let e=r.tabId;if(typeof e==`string`&&e.length>0)return e}return t.randomUUID()}var Xr=class t{db;peerIdValue;vv;maxHlc;listeners;tables;runtime;eventBatcher;coordinator;seenCommitIds;closed;constructor(e,t,n,r,i,a,o,s,c){this.db=e,this.peerIdValue=t,this.vv=n,this.maxHlc=r,this.listeners=new Set,this.tables=i,this.runtime=o,this.eventBatcher=new ee({runtime:o,emit:(e,t)=>this.emitEvents(e,t)}),this.seenCommitIds=new ne(2048),this.coordinator=pr({runtime:o,tabId:a,transport:s,roleProvider:c,ingestCommit:(e,t)=>this.applyCommit(e,t),executeWriteRequest:(e,t,n)=>this.executeWriteRequest(e,t,n)}),this.closed=!1}static async open(n){let r=n.connection??await e({path:n.path}),i=Ur(n.tablePrefix),a=Wr(i);await t.ensureSchema(r,a);let o=await t.resolvePeerId(r,a,n.peerId),{vv:s,maxHlc:c}=await t.loadVersionState(r,a),l=n.multiTab?.runtime??nr(),u=n.multiTab?.roleProvider??qr(r),ee=Jr(n.path,i),te=(n.multiTab?.transportFactory??rr)(ee);return new t(r,o,s,c,a,Yr(r,l,n.multiTab?.tabId),l,te,u)}static async fromJson(e){let n=await t.open(e);return await n.importJson(e.bundle),n}async close(){this.closed||(this.closed=!0,this.coordinator.close(),this.eventBatcher.close(),await this.db.close())}getRole(){return this.coordinator.getRole()}isHost(){return this.coordinator.isHost()}subscribeRoleChange(e){return this.coordinator.subscribeRoleChange(e)}dispatchWriteRequest(e){return this.coordinator.dispatchWriteRequest(e)}applyCommit(e,t){if(this.seenCommitIds.has(e.commitId))return;if(this.seenCommitIds.add(e.commitId),e.meta?.peerId)try{this.peerIdValue=W(e.meta.peerId)}catch{}let n=e.events.map(t=>({key:G(t.key),payload:q(t.payload),source:e.source,clock:{...t.clock}}));for(let e of n)this.bumpVersion(e.clock);n.length!==0&&this.eventBatcher.handleCommitEvents(e.source,n,t)}async executeWriteRequest(e,t,n){let r=[],i,a;if(e.kind===`apply`)await this.applyOperation({key:e.key,payload:e.payload,now:e.now,skipSameValue:e.skipSameValue,source:e.source,eventSink:r});else if(e.kind===`putMvr`)await this.putMvrInternal(e.key,e.value,e.now,r);else if(e.kind===`import`)i=await this.importBundleInternal(e.bundle,r);else if(e.kind===`setPeerId`)await this.setPeerIdInternal(e.peerId),a={peerId:this.peerIdValue};else{let t=e;throw Error(`Unsupported write payload ${String(t)}`)}return{commit:{commitId:`c:${t}:${n}`,origin:t,source:e.source,events:r.map(e=>({key:e.key.slice(),clock:{...e.clock},payload:q(e.payload)})),...a?{meta:a}:{}},result:i}}static async ensureSchema(e,t){await e.exec(`
|
|
2
2
|
CREATE TABLE IF NOT EXISTS ${t.kv} (
|
|
3
3
|
key BLOB PRIMARY KEY,
|
|
4
4
|
data TEXT NULL,
|
|
@@ -16,16 +16,16 @@ import{openStore as e}from"@loro-dev/unisqlite";const t=new TextEncoder;function
|
|
|
16
16
|
logical INTEGER NOT NULL,
|
|
17
17
|
peer TEXT NOT NULL,
|
|
18
18
|
superseded_at INTEGER DEFAULT (unixepoch())
|
|
19
|
-
)`),await e.exec(`CREATE TABLE IF NOT EXISTS ${t.meta} (peer_id TEXT)`),await e.exec(`CREATE INDEX IF NOT EXISTS ${t.idxKvPeerClock} ON ${t.kv}(peer, physical, logical, key)`),await e.exec(`CREATE INDEX IF NOT EXISTS ${t.idxOverriddenKey} ON ${t.overridden}(key)`),await e.exec(`CREATE INDEX IF NOT EXISTS ${t.idxOverriddenSupersededAt} ON ${t.overridden}(superseded_at)`)}static async resolvePeerId(e,t,n){let r=
|
|
19
|
+
)`),await e.exec(`CREATE TABLE IF NOT EXISTS ${t.meta} (peer_id TEXT)`),await e.exec(`CREATE INDEX IF NOT EXISTS ${t.idxKvPeerClock} ON ${t.kv}(peer, physical, logical, key)`),await e.exec(`CREATE INDEX IF NOT EXISTS ${t.idxOverriddenKey} ON ${t.overridden}(key)`),await e.exec(`CREATE INDEX IF NOT EXISTS ${t.idxOverriddenSupersededAt} ON ${t.overridden}(superseded_at)`)}static async resolvePeerId(e,t,n){let r=W(n),i=await e.query(`SELECT peer_id FROM ${t.meta} LIMIT 1`);if(i.length>0&&typeof i[0]?.peer_id==`string`){let a=i[0].peer_id;return n&&a!==r?(await e.run(`UPDATE ${t.meta} SET peer_id = ?`,[r]),r):W(a)}return await e.exec(`DELETE FROM ${t.meta}`),await e.run(`INSERT INTO ${t.meta}(peer_id) VALUES (?)`,[r]),r}static async loadVersionState(e,t){let n=new Map,r=await e.query(`SELECT peer, MAX(physical) AS physical, MAX(logical) AS logical FROM ${t.kv} GROUP BY peer`);for(let e of r){if(!e||typeof e.peer!=`string`)continue;let t=Br({physicalTime:Number(e.physical??0),logicalCounter:Number(e.logical??0)});t&&n.set(e.peer,t)}let i=(await e.query(`SELECT physical, logical FROM ${t.kv} ORDER BY physical DESC, logical DESC LIMIT 1`))[0];return{vv:n,maxHlc:i&&Number.isFinite(i.physical)&&Number.isFinite(i.logical)?{physicalTime:Number(i.physical),logicalCounter:Number(i.logical)}:{physicalTime:0,logicalCounter:0}}}bumpVersion(e){let t=this.vv.get(e.peerId);(!t||zr(e,{...t,peerId:e.peerId})>0)&&this.vv.set(e.peerId,{physicalTime:e.physicalTime,logicalCounter:e.logicalCounter}),(this.maxHlc.physicalTime<e.physicalTime||this.maxHlc.physicalTime===e.physicalTime&&this.maxHlc.logicalCounter<e.logicalCounter)&&(this.maxHlc={physicalTime:e.physicalTime,logicalCounter:e.logicalCounter})}allocateClock(e){let t=e??this.runtime.now(),n=this.maxHlc.physicalTime,r=this.maxHlc.logicalCounter;return t>n?(n=t,r=0):r+=1,{physicalTime:n,logicalCounter:r,peerId:this.peerIdValue}}async applyOperation(e){let t=V(e.key),n=J(e.payload,{}),r=n.data===void 0?null:JSON.stringify(n.data),i=n.metadata===void 0?null:JSON.stringify(n.metadata),a=!1,o;if(await this.db.asyncTransaction(async n=>{let s=await n.query(`SELECT key, data, metadata, physical, logical, peer FROM ${this.tables.kv} WHERE key = ? LIMIT 1`,[t]);if(s.length>0){let t=s[0],n=t.data??null,a=t.metadata??null;if(e.skipSameValue&&r===n&&i===a)return}else if(e.skipSameValue&&r===null&&i===null)return;let c=e.clock??this.allocateClock(e.now);if(o=c,s.length>0){let e=s[0],a=zr(c,{physicalTime:Number(e.physical??0),logicalCounter:Number(e.logical??0),peerId:String(e.peer??``)});if(a<0){await n.run(`INSERT INTO ${this.tables.overridden}(key, data, metadata, physical, logical, peer) VALUES (?, ?, ?, ?, ?, ?)`,[t,r,i,c.physicalTime,c.logicalCounter,c.peerId]);return}if(a>0)await n.run(`INSERT INTO ${this.tables.overridden}(key, data, metadata, physical, logical, peer) VALUES (?, ?, ?, ?, ?, ?)`,[t,e.data??null,e.metadata??null,e.physical??0,e.logical??0,e.peer??``]);else return}await n.run(`INSERT INTO ${this.tables.kv}(key, data, metadata, physical, logical, peer)
|
|
20
20
|
VALUES (?, ?, ?, ?, ?, ?)
|
|
21
21
|
ON CONFLICT(key) DO UPDATE SET
|
|
22
22
|
data=excluded.data,
|
|
23
23
|
metadata=excluded.metadata,
|
|
24
24
|
physical=excluded.physical,
|
|
25
25
|
logical=excluded.logical,
|
|
26
|
-
peer=excluded.peer`,[t,r,i,c.physicalTime,c.logicalCounter,c.peerId]),a=!0}),o&&this.bumpVersion(o),a){let t={key:e.key.slice(),payload:n,source:e.source};e.eventSink
|
|
26
|
+
peer=excluded.peer`,[t,r,i,c.physicalTime,c.logicalCounter,c.peerId]),a=!0}),o&&this.bumpVersion(o),a&&o){let t={key:e.key.slice(),payload:n,source:e.source,clock:o};e.eventSink.push(t)}return a}emitEvents(e,t){if(this.listeners.size===0||t.length===0)return;let n={source:e,events:t.map(e=>({key:G(e.key),clock:{...e.clock},value:e.payload.data===void 0?void 0:G(e.payload.data),metadata:K(e.payload.metadata),payload:q(e.payload)}))};this.listeners.forEach(e=>{e(n)})}async put(e,t,n){await this.dispatchWriteRequest({kind:`apply`,source:`local`,key:e,payload:{data:G(t)},now:n,skipSameValue:!0})}async putWithMeta(e,t,n={}){let r={data:G(t)};n.metadata&&(r.metadata=K(n.metadata));let i=n.hooks?.transform;if(i){let t=q(r),a=J(r,await i({key:e.slice(),now:n.now},t)??t);if(a.data===void 0)throw TypeError(`putWithMeta requires a data value`);await this.dispatchWriteRequest({kind:`apply`,source:`local`,key:e,payload:a,now:n.now,skipSameValue:!0});return}await this.dispatchWriteRequest({kind:`apply`,source:`local`,key:e,payload:r,now:n.now,skipSameValue:!0})}async delete(e,t){await this.dispatchWriteRequest({kind:`apply`,source:`local`,key:e,payload:{},now:t,skipSameValue:!0})}async forcePut(e,t,n){await this.dispatchWriteRequest({kind:`apply`,source:`local`,key:e,payload:{data:G(t)},now:n,skipSameValue:!1})}async forcePutWithMeta(e,t,n={}){let r={data:G(t)};n.metadata&&(r.metadata=K(n.metadata));let i=n.hooks?.transform;if(i){let t=q(r),a=J(r,await i({key:e.slice(),now:n.now},t)??t);if(a.data===void 0)throw TypeError(`forcePutWithMeta requires a data value`);await this.dispatchWriteRequest({kind:`apply`,source:`local`,key:e,payload:a,now:n.now,skipSameValue:!1});return}await this.dispatchWriteRequest({kind:`apply`,source:`local`,key:e,payload:r,now:n.now,skipSameValue:!1})}async forceDelete(e,t){await this.dispatchWriteRequest({kind:`apply`,source:`local`,key:e,payload:{},now:t,skipSameValue:!1})}async set(e,t,n){await this.put(e,t,n)}async setPeerId(e){let t=W(e);await this.dispatchWriteRequest({kind:`setPeerId`,source:`meta`,peerId:t})}async setPeerIdInternal(e){let t=W(e);await this.db.exec(`DELETE FROM ${this.tables.meta}`),await this.db.run(`INSERT INTO ${this.tables.meta}(peer_id) VALUES (?)`,[t]),this.peerIdValue=t}async get(e){let t=V(e),n=(await this.db.query(`SELECT data FROM ${this.tables.kv} WHERE key = ? LIMIT 1`,[t]))[0];if(n)return $(n.data)}async getEntry(e){let t;try{t=V(e)}catch{return}let n=(await this.db.query(`SELECT data, metadata, physical, logical, peer FROM ${this.tables.kv} WHERE key = ? LIMIT 1`,[t]))[0];if(!n)return;let r=Lr(n.physical,n.logical,n.peer);if(!r)return;let i=yr(Fr(n.metadata)),a=$(n.data),o={metadata:i,clock:r};return a!==void 0&&(o.data=a),o}async getMvr(e){let t=await this.scan({prefix:e}),n=[];for(let r of t)r.raw.d===!0&&r.key.length===e.length+1&&n.push(r.key[r.key.length-1]);return n}async putMvr(e,t,n){if(t===null||typeof t==`object`)throw TypeError(`putMvr only accepts scalar values`);await this.dispatchWriteRequest({kind:`putMvr`,source:`local`,key:e,value:t,now:n})}async putMvrInternal(e,t,n,r){if(t===null||typeof t==`object`)throw TypeError(`putMvr only accepts scalar values`);let i=await this.scan({prefix:e});for(let e of i)e.raw.d===!0&&await this.applyOperation({key:e.key,payload:{},now:n,skipSameValue:!0,source:`local`,eventSink:r});let a=e.slice();a.push(t),await this.applyOperation({key:a,payload:{data:!0},now:n,skipSameValue:!0,source:`local`,eventSink:r})}buildScanBounds(e){let t,n,r,i=e=>{if(!t){t=e;return}let n=$n(e.value,t.value);n>0?t=e:n===0&&(t={value:t.value,inclusive:t.inclusive&&e.inclusive})},a=e=>{if(!n){n=e;return}let t=$n(e.value,n.value);t<0?n=e:t===0&&(n={value:n.value,inclusive:n.inclusive&&e.inclusive})};try{if(e.prefix){let t=V(e.prefix);r=t,i({value:t,inclusive:!0});let n=er(t);n&&a({value:n,inclusive:!1})}e.start&&e.start.kind!==`unbounded`&&i({value:V(e.start.key),inclusive:e.start.kind===`inclusive`}),e.end&&e.end.kind!==`unbounded`&&a({value:V(e.end.key),inclusive:e.end.kind===`inclusive`})}catch{return{where:[],params:[],empty:!0}}let o=[],s=[];return t&&(o.push(`key ${t.inclusive?`>=`:`>`} ?`),s.push(t.value)),n&&(o.push(`key ${n.inclusive?`<=`:`<`} ?`),s.push(n.value)),{where:o,params:s,postFilter:r?(e=>t=>Vr(t,e))(r):void 0}}async scan(e={}){let t=this.buildScanBounds(e);if(t.empty)return[];let n=t.where.length>0?`WHERE ${t.where.join(` AND `)}`:``,r=await this.db.query(`SELECT key, data, metadata, physical, logical, peer FROM ${this.tables.kv} ${n} ORDER BY key ASC`,t.params),i=[];for(let e of r){let n=e.key;if(t.postFilter&&!t.postFilter(n))continue;let r=Qn(n),a={physicalTime:Number(e.physical??0),logicalCounter:Number(e.logical??0),peerId:String(e.peer??``)},o={},s=$(e.data);s!==void 0&&(o.data=s);let c=Fr(e.metadata);c!==void 0&&(o.metadata=c);let l=Q(a,o);i.push({key:r,raw:l,value:o.data})}return i}async version(){let e=await this.db.query(`SELECT peer, physical, logical FROM (
|
|
27
27
|
SELECT peer, physical, logical,
|
|
28
28
|
ROW_NUMBER() OVER (PARTITION BY peer ORDER BY physical DESC, logical DESC) as rn
|
|
29
29
|
FROM ${this.tables.kv}
|
|
30
|
-
) WHERE rn = 1`),t={};for(let n of e)t[n.peer]={physicalTime:n.physical,logicalCounter:n.logical};return t}inclusiveVersion(){let e={};for(let[t,n]of this.vv.entries())e[t]={...n};return e}peerId(){return this.peerIdValue}getMaxPhysicalTime(){return this.maxHlc.physicalTime}async exportInternal(e,t,n){let r=new Map;if(e)for(let[t,n]of Object.entries(e)){let e=
|
|
30
|
+
) WHERE rn = 1`),t={};for(let n of e)t[n.peer]={physicalTime:n.physical,logicalCounter:n.logical};return t}inclusiveVersion(){let e={};for(let[t,n]of this.vv.entries())e[t]={...n};return e}peerId(){return this.peerIdValue}getMaxPhysicalTime(){return this.maxHlc.physicalTime}async exportInternal(e,t,n){let r=new Map;if(e)for(let[t,n]of Object.entries(e)){let e=Br(n);e&&r.set(t,e)}let i={},a=n?[n]:Array.from(this.vv.keys()),o=[];for(let e of a){let t=this.vv.get(e),n=r.get(e);t&&n&&(t.physicalTime<n.physicalTime||t.physicalTime===n.physicalTime&&t.logicalCounter<=n.logicalCounter)||o.push({peer:e,fromEntry:n})}if(n&&o.every(e=>e.peer!==n)&&o.push({peer:n,fromEntry:r.get(n)}),o.length===0)return{version:0,entries:i};for(let e of o){let n=[e.peer],r=`WHERE peer = ?`;e.fromEntry&&(r+=` AND physical >= ?`,n.push(e.fromEntry.physicalTime));let a=await this.db.query(`SELECT key, data, metadata, physical, logical, peer FROM ${this.tables.kv} ${r} ORDER BY physical, logical, key`,n);for(let n of a){let r={physicalTime:Number(n.physical??0),logicalCounter:Number(n.logical??0),peerId:String(n.peer??``)},a=e.fromEntry;if(a&&(r.physicalTime<a.physicalTime||r.physicalTime===a.physicalTime&&r.logicalCounter<=a.logicalCounter)||t!==void 0&&Number.isFinite(t)&&n.data===null&&r.physicalTime<t)continue;let o={},s=$(n.data);s!==void 0&&(o.data=s);let c=Fr(n.metadata);c!==void 0&&(o.metadata=c);let l=Qn(n.key);i[tr(l)]=Q(r,o)}}return{version:0,entries:i}}async exportWithHooks(e){let t=await this.exportInternal(e.from,e.pruneTombstonesBefore,e.peerId),n=e.hooks?.transform;if(!n)return t;let r={version:t.version,entries:{}};for(let[e,i]of Object.entries(t.entries)){let t=Ir(i.c),a={key:JSON.parse(e),clock:t,raw:{...i}},o={};i.d!==void 0&&(o.data=G(i.d));let s=K(i.m);s!==void 0&&(o.metadata=s);let c=q(o),l=J(o,await n(a,c)??c);r.entries[e]=Q(t,l)}return r}exportJson(e,t){return Nr(e)?this.exportWithHooks(e):this.exportInternal(e,t)}async importBundleInternal(e,t){if(e.version!==0)throw TypeError(`Unsupported bundle version`);let n=0,r=[];for(let[i,a]of Object.entries(e.entries)){let e;try{let t=JSON.parse(i);e=Array.isArray(t)?t:[]}catch{r.push({key:[],reason:`invalid key`});continue}let o=Ir(a.c),s={};a.d!==void 0&&(s.data=G(a.d));let c=K(a.m);c!==void 0&&(s.metadata=c),n+=1,await this.applyOperation({key:e,payload:s,clock:o,skipSameValue:!1,source:`import`,eventSink:t})}return{accepted:n,skipped:r}}async importJson(e){if(Pr(e)){let t=e.hooks?.preprocess,n=t?{version:e.bundle.version,entries:{...e.bundle.entries}}:e.bundle,r=[];if(t)for(let[e,i]of Object.entries(n.entries)){let a=JSON.parse(e),o=Ir(i.c),s={};i.d!==void 0&&(s.data=G(i.d));let c=K(i.m);c!==void 0&&(s.metadata=c);let l=Mr(await t({key:a,clock:o,raw:i},q(s)));l.accept?n.entries[e]=Q(o,s):(r.push({key:a,reason:l.reason??`rejected`}),delete n.entries[e])}this.eventBatcher.beforeImport();let{result:i}=await this.dispatchWriteRequest({kind:`import`,source:`import`,bundle:n});return{accepted:i.accepted,skipped:r.concat(i.skipped)}}this.eventBatcher.beforeImport();let{result:t}=await this.dispatchWriteRequest({kind:`import`,source:`import`,bundle:e});return t}async importJsonStr(e){let t=JSON.parse(e);return this.importJson(t)}async digest(){return u(await Hr(await this.db.query(`SELECT key, data, metadata, physical, logical, peer FROM ${this.tables.kv} ORDER BY key ASC`)))}async kvToJson(){return this.exportInternal()}async merge(e){let t=await e.exportJson();await this.importJson(t)}static async checkConsistency(e,t){let[n,r]=await Promise.all([e.digest(),t.digest()]);return n===r}checkInvariants(){}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async txn(e){return this.eventBatcher.txn(e)}isInTxn(){return this.eventBatcher.isInTxn()}autoDebounceCommit(e,t){this.eventBatcher.autoDebounceCommit(e,t)}disableAutoDebounceCommit(){this.eventBatcher.disableAutoDebounceCommit()}commit(){this.eventBatcher.commit()}isAutoDebounceActive(){return this.eventBatcher.isAutoDebounceActive()}};export{Xr as Flock,Xr as FlockSQLite,jr as decodeVersionVector,Ar as encodeVersionVector};
|
|
31
31
|
//# sourceMappingURL=index.mjs.map
|