@lunora/replica 0.0.0 → 1.0.0-alpha.100

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.
Files changed (42) hide show
  1. package/LICENSE.md +445 -0
  2. package/README.md +239 -29
  3. package/dist/adapters/better-sqlite3.d.mts +29 -0
  4. package/dist/adapters/better-sqlite3.d.ts +29 -0
  5. package/dist/adapters/better-sqlite3.mjs +1 -0
  6. package/dist/adapters/sqlite-wasm.d.mts +30 -0
  7. package/dist/adapters/sqlite-wasm.d.ts +30 -0
  8. package/dist/adapters/sqlite-wasm.mjs +1 -0
  9. package/dist/adapters/sqljs.d.mts +22 -0
  10. package/dist/adapters/sqljs.d.ts +22 -0
  11. package/dist/adapters/sqljs.mjs +1 -0
  12. package/dist/index.d.mts +1074 -0
  13. package/dist/index.d.ts +1074 -0
  14. package/dist/index.mjs +1 -0
  15. package/dist/packem_shared/EventEmitter-uo75adUL.mjs +1 -0
  16. package/dist/packem_shared/EventLog-SuC_BKwj.mjs +1 -0
  17. package/dist/packem_shared/EventLogDO-BgUx2GGL.mjs +1 -0
  18. package/dist/packem_shared/EventLogDOClient-DWerZ3_n.mjs +1 -0
  19. package/dist/packem_shared/EventSource-Bg6zNmRn.mjs +1 -0
  20. package/dist/packem_shared/EventsSync-B3wzXm-b.mjs +1 -0
  21. package/dist/packem_shared/InMemorySnapshotStore-C4taIG5K.mjs +1 -0
  22. package/dist/packem_shared/LocalMirror-Bn22hyEB.mjs +4 -0
  23. package/dist/packem_shared/MaterializerRuntime-DFXi-aqd.mjs +1 -0
  24. package/dist/packem_shared/SubscriptionManager-AhPw3lFc.mjs +1 -0
  25. package/dist/packem_shared/applyDiff-CZAqAC8Y.mjs +1 -0
  26. package/dist/packem_shared/applyDiffToDb-CK-Dcy17.mjs +1 -0
  27. package/dist/packem_shared/classifyChanges-BBc0-770.mjs +1 -0
  28. package/dist/packem_shared/defineEvents-DHo-VK7G.mjs +1 -0
  29. package/dist/packem_shared/eventsContext-Dxow9Y7S.mjs +1 -0
  30. package/dist/packem_shared/fnv1a-BNN96GYb.mjs +1 -0
  31. package/dist/packem_shared/int64-CCVxepl4.mjs +1 -0
  32. package/dist/packem_shared/isClientSeq-D2Xm0_lj.mjs +1 -0
  33. package/dist/packem_shared/local-mirror.d-DzREvGNM.d.mts +562 -0
  34. package/dist/packem_shared/local-mirror.d-wbGXkXaE.d.ts +562 -0
  35. package/dist/packem_shared/subscribeToMirror-DSn8n1IR.mjs +1 -0
  36. package/dist/packem_shared/types.d-BuLTPLaQ.d.mts +22 -0
  37. package/dist/packem_shared/types.d-BuLTPLaQ.d.ts +22 -0
  38. package/dist/packem_shared/wire-key-DfMHAtqH.mjs +1 -0
  39. package/dist/react.d.mts +77 -0
  40. package/dist/react.d.ts +77 -0
  41. package/dist/react.mjs +1 -0
  42. package/package.json +88 -7
package/dist/index.mjs ADDED
@@ -0,0 +1 @@
1
+ import{createBetterSqlite3Adapter as o}from"./adapters/better-sqlite3.mjs";import{createSqliteWasmAdapter as f}from"./adapters/sqlite-wasm.mjs";import{createSqlJsAdapter as i}from"./adapters/sqljs.mjs";import{applyDiff as m,applyDiffToSnapshot as n,applyDiffs as x}from"./packem_shared/applyDiff-CZAqAC8Y.mjs";import{defineEvents as l}from"./packem_shared/defineEvents-DHo-VK7G.mjs";import{MaterializerRuntime as S,defineMaterializer as E}from"./packem_shared/MaterializerRuntime-DFXi-aqd.mjs";import{applyDiffToDb as v,applyDiffsToDb as y}from"./packem_shared/applyDiffToDb-CK-Dcy17.mjs";import{EventEmitter as d}from"./packem_shared/EventEmitter-uo75adUL.mjs";import{EventLog as M}from"./packem_shared/EventLog-SuC_BKwj.mjs";import{EventLogDO as u}from"./packem_shared/EventLogDO-BgUx2GGL.mjs";import{EventLogDOClient as T}from"./packem_shared/EventLogDOClient-DWerZ3_n.mjs";import{EventSource as C,UNHANDLED as h}from"./packem_shared/EventSource-Bg6zNmRn.mjs";import{eventsContext as I}from"./packem_shared/eventsContext-Dxow9Y7S.mjs";import{LocalMirror as O}from"./packem_shared/LocalMirror-Bn22hyEB.mjs";import{isClientSeq as G,isGlobalSeq as H,isInputEvent as J}from"./packem_shared/isClientSeq-D2Xm0_lj.mjs";import{InMemorySnapshotStore as U}from"./packem_shared/InMemorySnapshotStore-C4taIG5K.mjs";import{subscribeToMirror as j}from"./packem_shared/subscribeToMirror-DSn8n1IR.mjs";import{SubscriptionManager as w}from"./packem_shared/SubscriptionManager-AhPw3lFc.mjs";import{EventsSync as K}from"./packem_shared/EventsSync-B3wzXm-b.mjs";import{classifyChanges as Q,createTableDiff as V,diffSize as X,isDiffEmpty as Y,mergeDiffs as Z}from"./packem_shared/classifyChanges-BBc0-770.mjs";export{d as EventEmitter,M as EventLog,u as EventLogDO,T as EventLogDOClient,C as EventSource,K as EventsSync,U as InMemorySnapshotStore,O as LocalMirror,S as MaterializerRuntime,w as SubscriptionManager,h as UNHANDLED,m as applyDiff,v as applyDiffToDb,n as applyDiffToSnapshot,x as applyDiffs,y as applyDiffsToDb,Q as classifyChanges,o as createBetterSqlite3Adapter,i as createSqlJsAdapter,f as createSqliteWasmAdapter,V as createTableDiff,l as defineEvents,E as defineMaterializer,X as diffSize,I as eventsContext,G as isClientSeq,Y as isDiffEmpty,H as isGlobalSeq,J as isInputEvent,Z as mergeDiffs,j as subscribeToMirror};
@@ -0,0 +1 @@
1
+ class h{#t=new Map;#e=new Set;on(t,s){let e=this.#t.get(t);return e||(e=new Set,this.#t.set(t,e)),e.add(s),()=>{this.off(t,s)}}off(t,s){this.#t.get(t)?.delete(s)}onAny(t){return this.#e.add(t),()=>{this.#e.delete(t)}}offAny(t){this.#e.delete(t)}emit(t,s){let e=!1;const r=this.#t.get(t);if(r)for(const i of r)try{i(s),e=!0}catch{}for(const i of this.#e)try{i(t,s),e=!0}catch{}return e}hasListeners(t){return(this.#t.get(t)?.size??0)>0||this.#e.size>0}listenerCount(t){return this.#t.get(t)?.size??0}clear(){this.#t.clear(),this.#e.clear()}}export{h as EventEmitter};
@@ -0,0 +1 @@
1
+ class f{#e=[];#t=0;#i=0;#s=null;#n;constructor(t){this.#n=f.#o(t?.maxEntries)}static#o(t){if(t!==void 0){if(!Number.isSafeInteger(t)||t<0)throw new RangeError("maxEntries must be a non-negative safe integer");return t}}#r(){return this.#e.slice(this.#t)}#h(){if(this.#n===void 0)return;const e=this.#e.length-this.#t-this.#n;e>0&&(this.#t+=e),this.#t>0&&this.#t>=this.#e.length-this.#t&&(this.#e=this.#e.slice(this.#t),this.#t=0)}append(t,e,s,n){const r=typeof t=="string"?t:t.type,o=typeof t=="string"?e:t.payload;let h,i;typeof t=="string"?(h=s,i=n):(h=void 0,i=e);const a=i?.parentSeqNum??this.#s??void 0,l=this.#i;this.#i+=1;const c={seq:l,type:r,payload:o,timestamp:i?.timestamp??(typeof t=="string"?void 0:t.timestamp)??Date.now(),tableDiffs:h,clientId:i?.clientId,sessionId:i?.sessionId,parentSeqNum:a};return this.#e.push(c),this.#s=c.seq,this.#h(),c}commitAll(t){if(t.length===0)return[];const e=[];for(const s of t){const{type:n}=s,r="payload"in s?s.payload:void 0,o="timestamp"in s?s.timestamp:Date.now(),h=e.at(-1)?.seq??this.#s??void 0,i=this.#i;this.#i+=1;const a={seq:i,type:n,payload:r,timestamp:o,parentSeqNum:h};this.#e.push(a),e.push(a)}return this.#s=e.at(-1)?.seq??this.#s,this.#h(),e}load(t){this.#e=[...t.entries],this.#t=0,this.#i=t.nextSeq,this.#s=t.headSeq,this.#h()}getSince(t){const e=this.#r();if(t<=0)return e;const s=e.findIndex(n=>n.seq>=t);return s===-1?[]:e.slice(s)}getFrom(t,e=50){if(!Number.isSafeInteger(e)||e<1)throw new RangeError("limit must be a positive safe integer");const s=this.#e,n=this.#t,r=s.findIndex((h,i)=>i>=n&&h.seq>=t);if(r===-1)return{entries:[],hasMore:!1};const o=Math.min(r+e,s.length);return{entries:s.slice(r,o),hasMore:o<s.length}}snapshot(){return{entries:this.#r(),nextSeq:this.#i,headSeq:this.#s}}get size(){return this.#e.length-this.#t}get nextSeq(){return this.#i}get isEmpty(){return this.size===0}get headSeq(){return this.#s}clear(){this.#e=[],this.#t=0,this.#i=0,this.#s=null}truncateBelow(t){if(!Number.isSafeInteger(t)||t<0)throw new RangeError("floorSeq must be a non-negative safe integer");const e=this.#r(),s=e.findIndex(n=>n.seq>=t);this.#e=s===-1?[]:e.slice(s),this.#t=0}async*events(t=0){const e=this.getSince(t);for(const s of e)yield s}}export{f as EventLog};
@@ -0,0 +1 @@
1
+ const N=Symbol("lunora.replica.event-log-do.idempotency-conflict"),_=n=>{const t=new Error(n);return Object.defineProperty(t,N,{value:!0}),t},R=n=>n instanceof Error&&N in n,y=n=>{if(Array.isArray(n))return n.map(t=>y(t));if(n!==null&&typeof n=="object"){const t=n,e=Object.keys(t);e.sort();const s={};for(const r of e)s[r]=y(t[r]);return s}return n},O=async n=>{const t=JSON.stringify(y(n)),e=new TextEncoder().encode(t),s=await crypto.subtle.digest("SHA-256",e);return[...new Uint8Array(s)].map(r=>r.toString(16).padStart(2,"0")).join("")},v=500,m=1e3,g=32768,S=4194304,E=(n,t=200)=>Response.json(n,{status:t,headers:{"content-type":"application/json"}}),p=(n,t,e)=>E({error:{code:t,message:e}},n),l=n=>typeof n.toArray=="function"?n.toArray():typeof n[Symbol.iterator]=="function"?[...n]:[],T=n=>({seq:n.seq,type:n.type,payload:JSON.parse(n.payload),timestamp:n.timestamp,clientId:n.client_id??void 0,sessionId:n.session_id??void 0,parentSeqNum:n.parent_seq??void 0}),b=n=>l(n).map(t=>T(t)),L=n=>n.reduce((t,e)=>t+e.payload.length,0),C=(n,t)=>{const e=Math.min(n.length,t);let s=0;for(let r=0;r<e;r+=1)if(s+=n[r].payload.length,s>S&&r>0)return r;return e};class u{state;env;#t=!1;constructor(t,e){this.state=t,this.env=e}async fetch(t){this.#c();const e=new URL(t.url);try{if(t.method==="POST"&&e.pathname==="/append")return await this.#e(t);if(t.method==="GET"&&e.pathname==="/since")return this.#i(e);if(t.method==="GET"&&e.pathname==="/size")return this.#a();if(t.method==="GET"&&e.pathname==="/state")return this.#o()}catch(s){return console.error("[event-log-do] request failed:",s),p(500,"INTERNAL_ERROR","internal error")}return p(404,"NOT_FOUND","unknown route")}async#e(t){let e;try{e=await t.json()}catch{return p(400,"BAD_REQUEST","invalid JSON body")}const s=u.#s(e);if(s)return p(400,"BAD_REQUEST",s);const{sql:r}=this.state.storage,{batchId:a}=e,o=()=>u.#n(r,e,a),{transaction:i}=this.state.storage;let c;try{c=typeof i=="function"?await i(o):await o()}catch(f){if(R(f))return p(409,"CONFLICT",f.message);throw f}return E({entries:c})}static async#n(t,e,s){let r;if(typeof s=="string"){r=await O(e.events);const i=u.#p(t,s);if(i){if(i.fingerprint!==r)throw _(`batchId "${s}" was already used for a different event batch`);return i.entries}}const a=Date.now(),o=[];for(const i of e.events){const d={seq:u.#d(t),type:i.type,payload:i.payload,timestamp:i.timestamp??a,clientId:i.clientId,sessionId:i.sessionId,parentSeqNum:i.parentSeqNum};u.#l(t,d),o.push(d)}if(typeof s=="string"&&r!==void 0){const i=o[0]?.seq,c=o.at(-1)?.seq;i!==void 0&&c!==void 0&&u.#u(t,s,i,c,r)}return o}static#s(t){if(!Array.isArray(t.events)||t.events.length===0)return"events[] with a non-empty string `type` required";if(t.batchId!==void 0&&(typeof t.batchId!="string"||t.batchId.length===0))return"batchId must be a non-empty string";for(const e of t.events){const s=u.#r(e);if(s!==void 0)return s}}static#r(t){if(typeof t.type!="string"||t.type.length===0)return"events[] with a non-empty string `type` required";if(t.timestamp!==void 0&&!Number.isFinite(t.timestamp))return"events[].timestamp must be a finite number";if(t.clientId!==void 0&&typeof t.clientId!="string")return"events[].clientId must be a string";if(t.sessionId!==void 0&&typeof t.sessionId!="string")return"events[].sessionId must be a string";if(t.parentSeqNum!==void 0&&(typeof t.parentSeqNum!="number"||!Number.isInteger(t.parentSeqNum)||t.parentSeqNum<0))return"events[].parentSeqNum must be a non-negative integer";if(t.payload===void 0)return"events[].payload is required";if(JSON.stringify(t.payload).length>g)return`events[].payload must serialise to at most ${String(g)} characters`}#i(t){const e=t.searchParams.get("seq"),s=e===null?0:Number(e),r=t.searchParams.get("limit"),a=r===null?v:Number(r);if(!Number.isSafeInteger(s)||s<0)return p(400,"BAD_REQUEST","invalid seq");if(!Number.isSafeInteger(a)||a<1||a>m)return p(400,"BAD_REQUEST","invalid limit");const{sql:o}=this.state.storage,i=o.exec("SELECT seq, type, payload, timestamp, client_id, session_id, parent_seq FROM events WHERE seq >= ? ORDER BY seq ASC LIMIT ?",s,a+1),c=l(i),d=C(c,a),f=d<c.length,h=c.slice(0,d).map(I=>T(I)),q=h.at(-1),A=f&&q!==void 0?{entries:h,truncated:!0,cursor:q.seq+1}:{entries:h,truncated:!1};return E(A)}#a(){const{sql:t}=this.state.storage,e=t.exec("SELECT COUNT(*) AS count FROM events"),r=l(e)[0]?.count??0;return E({count:r})}#o(){const{sql:t}=this.state.storage,e=t.exec("SELECT seq, type, payload, timestamp, client_id, session_id, parent_seq FROM events ORDER BY seq ASC LIMIT ?",m+1),s=l(e);if(s.length>m||L(s)>S)return p(413,"PAYLOAD_TOO_LARGE",`the log is larger than /state can return in one body (over ${String(m)} entries, or over ${String(S)} characters of payload) — walk /since?seq=0 with its truncated/cursor pages instead`);const a=s.map(i=>T(i)),o=(a.at(-1)?.seq??-1)+1;return E({entries:a,nextSeq:o})}#c(){if(this.#t)return;const{sql:t}=this.state.storage;t.exec("CREATE TABLE IF NOT EXISTS events (seq INTEGER PRIMARY KEY AUTOINCREMENT, type TEXT NOT NULL, payload TEXT NOT NULL, timestamp INTEGER NOT NULL, client_id TEXT, session_id TEXT, parent_seq INTEGER)"),t.exec("CREATE TABLE IF NOT EXISTS event_batches (batch_id TEXT PRIMARY KEY, first_seq INTEGER NOT NULL, last_seq INTEGER NOT NULL, fingerprint TEXT NOT NULL)"),this.#t=!0}static#p(t,e){const s=t.exec("SELECT first_seq, last_seq, fingerprint FROM event_batches WHERE batch_id = ?",e),a=l(s)[0];if(!a)return;const o=t.exec("SELECT seq, type, payload, timestamp, client_id, session_id, parent_seq FROM events WHERE seq >= ? AND seq <= ? ORDER BY seq ASC",a.first_seq,a.last_seq);return{entries:b(o),fingerprint:a.fingerprint}}static#u(t,e,s,r,a){t.exec("INSERT INTO event_batches (batch_id, first_seq, last_seq, fingerprint) VALUES (?, ?, ?, ?)",e,s,r,a)}static#d(t){const e=t.exec("SELECT COALESCE(MAX(seq), -1) + 1 AS next_seq FROM events");return l(e)[0]?.next_seq??0}static#l(t,e){const s=typeof e.parentSeqNum=="number"?e.parentSeqNum:null;t.exec("INSERT INTO events (seq, type, payload, timestamp, client_id, session_id, parent_seq) VALUES (?, ?, ?, ?, ?, ?, ?)",e.seq,e.type,JSON.stringify(e.payload),e.timestamp,e.clientId??null,e.sessionId??null,s)}}export{u as EventLogDO};
@@ -0,0 +1 @@
1
+ class n{#t;constructor(t){this.#t=t.fetch}async append(t,a){const e=JSON.stringify({events:t,batchId:a?.batchId}),s=await this.#t(new Request("https://do/append",{method:"POST",headers:{"content-type":"application/json"},body:e}));if(!s.ok)throw await n.#e(s,"append");return(await s.json()).entries}async getSince(t,a){const e=a===void 0?"":`&limit=${String(a)}`;return this.#a(`/since?seq=${String(t)}${e}`,"getSince")}async getSize(){return(await this.#a("/size","getSize")).count}async getState(){return this.#a("/state","getState")}async#a(t,a){const e=await this.#t(new Request(`https://do${t}`));if(!e.ok)throw await n.#e(e,a);return await e.json()}static async#e(t,a){try{const s=(await t.json()).error?.message??t.statusText;return new Error(`EventLogDO.${a} failed (${String(t.status)}): ${s}`)}catch{return new Error(`EventLogDO.${a} failed (${String(t.status)}): ${t.statusText}`)}}}export{n as EventLogDOClient};
@@ -0,0 +1 @@
1
+ import{EventEmitter as m}from"./EventEmitter-uo75adUL.mjs";import{EventLog as u}from"./EventLog-SuC_BKwj.mjs";const d=Symbol("lunora.replica.event-source.unhandled");class w{emitter=new m;log;#e;#t;#n=!1;#i;#r=-1;constructor(e,n,t){this.#e={...e},this.#t=n,this.#i=t?.unknownEventHandling??"warn",this.log=new u({maxEntries:t?.maxLogEntries})}get state(){return this.#e}get replayed(){return this.#n}applyEvent(e,n,t){let r,o,i;typeof e=="string"?(r=e,o=n,i=t):(r=e.type,o=e.payload,i=n);const s={seq:this.log.nextSeq,type:r,payload:o,timestamp:Date.now(),clientId:i?.clientId,sessionId:i?.sessionId,parentSeqNum:i?.parentSeqNum??this.log.headSeq??void 0};let a;try{a=this.#t(this.#e,s)}catch(l){const p=l instanceof Error?l:new Error(String(l));throw this.emitter.emit("replay-error",{entry:s,error:p}),p}let c=!0;a===d&&(c=this.#s(s));const h=this.log.append(r,o,void 0,{...i,timestamp:s.timestamp});return a===d?(c&&this.emitter.emit("state-changed",{state:this.#e,entry:h}),h):(this.#e=a,this.emitter.emit("state-changed",{state:this.#e,entry:h}),h)}replayFromLog(e){const n=e.getSince(this.#r+1);for(const t of n)try{const r=this.#t(this.#e,t);r!==d&&(this.#e=r);const o=this.log.append(t.type,t.payload,t.tableDiffs,{clientId:t.clientId,sessionId:t.sessionId,parentSeqNum:t.parentSeqNum,timestamp:t.timestamp});this.emitter.emit("state-changed",{state:this.#e,entry:o})}catch(r){this.emitter.emit("replay-error",{entry:t,error:r instanceof Error?r:new Error(String(r))})}finally{this.#r=t.seq}this.#n=!0,this.emitter.emit("ready",{entryCount:this.log.size})}reset(e,n=-1){this.#e={...e},this.#r=n,this.#n=n>=0}async*events(e){const n=[];let t;const r=this.emitter.on("state-changed",({entry:i})=>{n.push(i),t?.()}),o=()=>{t?.()};e?.addEventListener("abort",o,{once:!0});try{let i=0;for(;i<this.log.size;){if(e?.aborted)return;for(const s of this.log.getSince(i))yield s;i=this.log.nextSeq}for(;!e?.aborted;){for(;n.length>0;){const s=n.shift();s&&(yield s)}n.length===0&&await new Promise(s=>{t=s})}}finally{r(),e?.removeEventListener("abort",o)}}#s(e){const n=this.#i;if(typeof n=="function")return n(e);switch(n){case"ignore":return!1;case"fail":throw new Error(`EventSource: unhandled event type "${e.type}" (seq ${String(e.seq)}). Configure \`unknownEventHandling\` to handle this event or change the strategy.`);default:return console.warn(`[EventSource] unhandled event type "${e.type}" (seq ${String(e.seq)}). The event was skipped. Configure \`unknownEventHandling\` if this is expected.`),!1}}}export{w as EventSource,d as UNHANDLED};
@@ -0,0 +1 @@
1
+ class c{#t;#r=0;#i=0;#s;#e;constructor(t){this.#t=t}get watermark(){return this.#r}start(){if(this.#s!==void 0)return;const t=this.#t.pollInterval??5e3;this.#s=setInterval(()=>{this.#n().catch(()=>{})},t)}stop(){this.#s!==void 0&&(clearInterval(this.#s),this.#s=void 0)}async sync(){return this.#n()}async#n(){if(this.#e)return this.#e;const t=this.#o().finally(()=>{this.#e=void 0});return this.#e=t,t}async#o(){let t=0;try{for(let r=0;r<1e3;r+=1){const s=await this.#t.fetchEventsSince(this.#r);if(s.length===0)return t;const e=s.filter(i=>i.seq>=this.#i);e.length>0&&(this.#t.applyEvents(e),this.#i=e[e.length-1].seq+1);const o=this.#t.getTableDiffs();for(const i of o)this.#t.mirror.applyDiff(i);t+=s.length;const n=s[s.length-1].seq+1;if(n<=this.#r)return t;this.#r=n}return t}catch(r){return(this.#t.onError??console.error)(r),t}}}export{c as EventsSync};
@@ -0,0 +1 @@
1
+ class t{#e=new Map;save(e,r){return this.#e.set(e,structuredClone(r)),Promise.resolve()}load(e){const r=this.#e.get(e);return Promise.resolve(r===void 0?null:structuredClone(r))}list(){return Promise.resolve([...this.#e.keys()])}delete(e){return this.#e.delete(e),Promise.resolve()}clear(){return this.#e.clear(),Promise.resolve()}}export{t as InMemorySnapshotStore};
@@ -0,0 +1,4 @@
1
+ import{createSqlJsAdapter as m}from"../adapters/sqljs.mjs";import{applyDiffToDb as b,escapeIdentifier as o}from"./applyDiffToDb-CK-Dcy17.mjs";import{EventLog as p}from"./EventLog-SuC_BKwj.mjs";const A=1e3,f="__lunora_mirror_meta",R=a=>{a.exec(`CREATE TABLE IF NOT EXISTS ${f} (
2
+ key TEXT PRIMARY KEY NOT NULL,
3
+ value TEXT NOT NULL
4
+ )`)},T="schema_version",y=4,l=a=>typeof a=="bigint"||typeof a=="boolean"?"INTEGER":typeof a=="number"?Number.isInteger(a)?"INTEGER":"REAL":"TEXT",h=a=>a??"";class E{#e;#t;#n;#s=new Set;#i=0;static create(e,t){const n=m(e);return new E({db:n,tables:t?.tables})}constructor(e){this.#e=e.db,this.#t={...e.tables},this.#n=new p({maxEntries:e.maxEventLogEntries??A}),R(this.#e),this.#o()}onChange(e){return this.#s.add(e),()=>{this.#s.delete(e)}}get eventLog(){return this.#n}get db(){return this.#e}get version(){return this.#i}applyDiff(e){e.changes.length!==0&&(this.#h(e),b(this.#e,e,this.primaryKeyOf(e.table)),this.#n.append("table-diff",e,[e]),this.#r("diff"))}query(e,t){return this.#e.query(e,t)}clearData(){const e=this.#a();this.#e.transaction(()=>{for(const{name:t}of e)this.#e.exec(`DELETE FROM ${o(t)}`)}),this.#r("clear")}#r(e){this.#i+=1;for(const t of this.#s)try{t(e)}catch{}}close(){this.#e.close(),this.#n.clear(),this.#s.clear()}registerTable(e,t){this.#t[e]={...this.#t[e],...t}}primaryKeyOf(e){return this.#t[e]?.primaryKey??"id"}get mirroredTables(){return Object.keys(this.#t)}#a(){return this.#e.query(String.raw`SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE '\_\_lunora\_%' ESCAPE '\' AND name NOT LIKE 'sqlite\_%' ESCAPE '\'`)}#o(){if(this.#e.query(`SELECT key, value FROM ${f}`).find(s=>s.key===T)?.value===String(y))return;const n=this.#a();this.#e.transaction(()=>{for(const{name:s}of n)this.#e.exec(`DROP TABLE IF EXISTS ${o(s)}`);this.#e.exec(`INSERT OR REPLACE INTO ${f} (key, value) VALUES (?, ?)`,[T,String(y)])})}static#c(e,t){const n=new Set;for(const s of e.changes)if(s.type!=="delete")for(const c of Object.keys(s.data))c!==t&&n.add(c);return n}static#E(e,t,n){const s=new Map;for(const c of e.changes)if(!(c.type==="delete"||s.size===n.size))for(const r of n){if(r===t||s.has(r))continue;const i=c.data[r];i!=null&&s.set(r,l(i))}return s}static#l(e,t){for(const n of e.changes){const s=n.type==="delete"?n.id:n.data[t];if(s!=null)return l(s);if(n.type==="update")return l(n.id)}}#h(e){const t=this.primaryKeyOf(e.table),n=E.#c(e,t),s=E.#E(e,t,n);if(this.#e.query("SELECT name FROM sqlite_master WHERE type='table' AND name=?",[e.table]).length===0){const r=E.#l(e,t);let i=`${o(t)} ${r==="INTEGER"?"INT":h(r)} PRIMARY KEY NOT NULL`;for(const u of n)i+=`, ${o(u)} ${h(s.get(u))}`;this.#e.exec(`CREATE TABLE IF NOT EXISTS ${o(e.table)} (${i})`)}else if(n.size>0){const r=new Set(this.#e.query(`PRAGMA table_info(${o(e.table)})`).map(i=>i.name));for(const i of n)r.has(i)||this.#e.exec(`ALTER TABLE ${o(e.table)} ADD COLUMN ${o(i)} ${h(s.get(i))}`)}}}export{E as LocalMirror};
@@ -0,0 +1 @@
1
+ import{UNHANDLED as o}from"./EventSource-Bg6zNmRn.mjs";const h=1e3,p=s=>{let e=s.initial();return{def:s,get state(){return Object.freeze(e)},setState(t){e=t},apply(t){const n=s.handle(e,t);return n===o?!1:(e=n,!0)},reset(){e=s.initial()}}};class c{#e;#n;#i;#r;#t;constructor(e,t={}){this.#e=[...e],this.#t=this.#e.map(()=>0),this.#n=t.snapshotStore,this.#i=t.doClient,this.#r=t.unknownEventHandling??"warn"}get appliedSeq(){return this.#t.length>0?Math.min(...this.#t):0}applyEntries(e){let t=0;for(const n of e){const{advancedIndices:r,anyHandled:i}=this.#a(n);if(r.length!==0){!i&&r.length===this.#e.length&&this.#o(n);for(const a of r)this.#t[a]=n.seq+1;t+=1}}return t}#a(e){const t=[];let n=!1;for(const[r,i]of this.#e.entries())e.seq<(this.#t[r]??0)||(i.apply(e)&&(n=!0),t.push(r));return{advancedIndices:t,anyHandled:n}}#o(e){const t=this.#r;if(typeof t=="function"){t(e);return}switch(t){case"ignore":return;case"fail":throw new Error(`MaterializerRuntime: unhandled event type "${e.type}" (seq ${String(e.seq)}). Configure \`unknownEventHandling\` to handle this event or change the strategy.`);default:console.warn(`[MaterializerRuntime] unhandled event type "${e.type}" (seq ${String(e.seq)}). The event was skipped. Configure \`unknownEventHandling\` if this is expected.`)}}async recoverFromSnapshots(){if(!this.#n)return 0;let e=0;for(const[t,n]of this.#e.entries()){const r=await this.#n.load(n.def.name);if(r!==null&&typeof r=="object"){const i=r;if(Number.isSafeInteger(i.appliedSeq)&&i.appliedSeq>=0&&i.state!==void 0){const a=i.appliedSeq;n.setState(i.state),this.#t[t]=a,a>e&&(e=a)}}}return e}async persistSnapshots(){if(this.#n)for(const[e,t]of this.#e.entries())await this.#n.save(t.def.name,{appliedSeq:this.#t[e]??0,state:t.state})}async initialize(){return this.#i?(await this.recoverFromSnapshots(),this.#s()):0}async#s(){const e=this.#i;if(!e)return 0;let t=this.appliedSeq,n=0;for(let r=0;r<h;r+=1){const i=await e.getSince(t);if(n+=this.applyEntries(i.entries),!i.truncated||i.cursor===void 0||i.cursor<=t)return n;t=i.cursor}return n}async appendEvent(e){if(!this.#i)throw new Error("MaterializerRuntime.appendEvent requires a doClient — pass one in the constructor options.");const n=(await this.#i.append([e]))[0];if(!n)throw new Error("MaterializerRuntime.appendEvent: DO returned empty result");return this.#e.length>0&&this.appliedSeq<n.seq&&(await this.#s(),this.appliedSeq<n.seq)||this.applyEntries([n]),n}reset(){for(const[e,t]of this.#e.entries())this.#t[e]=0,t.reset()}get materializers(){return this.#e}}export{c as MaterializerRuntime,p as defineMaterializer};
@@ -0,0 +1 @@
1
+ class i{#t=new Map;#e=0;#s(e){const t=String(this.#e);return this.#e+=1,this.#t.set(t,{...e,id:t}),()=>{this.#t.delete(t)}}onStateChange(e){return this.#s({kind:"state",callback:e})}onEvent(e,t){return this.#s({kind:"event",eventType:e,callback:t})}notifyState(e){for(const t of this.#t.values())if(t.kind==="state")try{t.callback(e)}catch{}}notifyEvent(e){for(const t of this.#t.values())if(t.kind==="event"&&t.eventType===e.type)try{t.callback(e)}catch{}}get size(){return this.#t.size}clear(){this.#t.clear()}}export{i as SubscriptionManager};
@@ -0,0 +1 @@
1
+ import{f as r}from"./fnv1a-BNN96GYb.mjs";import{s as p}from"./wire-key-DfMHAtqH.mjs";const c=(e,n)=>`row-${r(`${e.table}::${p(n)}`)}`,o=(e,n)=>{for(const t of n.changes)switch(t.type){case"delete":{e.delete(t.id);break}case"insert":{const a=t.data.id,s=typeof a=="bigint"||typeof a=="number"||typeof a=="string"?String(a):c(n,t.data);e.set(s,{...t.data,id:s});break}case"update":{const a=e.get(t.id);a&&e.set(t.id,{...a,...t.data});break}}},i=(e,n)=>{const t=new Map(e);return o(t,n),t},l=(e,n)=>{const t=new Map(e);for(const a of n)o(t,a);return t},b=(e,n)=>{const t=new Map(e),a=t.get(n.table)??new Map;return t.set(n.table,i(a,n)),t};export{i as applyDiff,b as applyDiffToSnapshot,l as applyDiffs,c as deriveInsertId,r as fnv1a64Hex};
@@ -0,0 +1 @@
1
+ import{deriveInsertId as $}from"./applyDiff-CZAqAC8Y.mjs";const p=t=>`\`${t.replaceAll("`","``")}\``,D=t=>t.map(n=>`${p(n)} = ?`).join(", "),h=t=>`(${t.map(n=>p(n)).join(", ")})`,T=t=>`(${Array.from({length:t}).fill("?").join(", ")})`,f=t=>t==null?null:typeof t=="number"||typeof t=="bigint"||typeof t=="string"?t:typeof t=="boolean"?t?1:0:t instanceof Uint8Array?t:typeof t=="object"?JSON.stringify(t):String(t),g=(t,n,o)=>{if(n.changes.length===0)return;const a=p(n.table),l=p(o);for(const i of n.changes)switch(i.type){case"delete":{t.exec(`DELETE FROM ${a} WHERE ${l} = ?`,[f(i.id)]);break}case"insert":{const{data:e}=i;if(Object.keys(e).length===0)continue;const s=e[o],c=typeof s=="bigint"||typeof s=="number"||typeof s=="string"?e:{...e,[o]:$(n,e)},r=Object.keys(c),y=`INSERT OR REPLACE INTO ${a} ${h(r)} VALUES ${T(r.length)}`,b=r.map(E=>f(c[E]));t.exec(y,b);break}case"update":{const{data:e}=i,s=Object.keys(e);if(s.length===0)continue;const c=`UPDATE ${a} SET ${D(s)} WHERE ${l} = ?`,r=[...s.map(y=>f(e[y])),f(i.id)];t.exec(c,r);break}}},d=(t,n,o)=>{t.transaction(()=>{g(t,n,o??"id")})},j=(t,n)=>{n.length!==0&&t.transaction(()=>{for(const o of n)g(t,o,"id")})};export{d as applyDiffToDb,j as applyDiffsToDb,p as escapeIdentifier,f as normalizeBindValue};
@@ -0,0 +1 @@
1
+ import{f as a}from"./fnv1a-BNN96GYb.mjs";let s=0;const c=()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();s+=1;const t=typeof crypto<"u"&&typeof crypto.getRandomValues=="function"?Array.from(crypto.getRandomValues(new Uint8Array(8)),n=>n.toString(16).padStart(2,"0")).join(""):Math.random().toString(16).slice(2,12);return`id_${Date.now().toString(36)}_${s.toString(36)}_${t}`},i=(t,n,o,r)=>({table:t,changes:n,timestamp:o??Date.now(),id:r??c()}),g=t=>t.changes.length===0,m=t=>t.changes.length,f=t=>{const n=[],o=[],r=[];for(const e of t.changes)e.type==="insert"?n.push(e):e.type==="update"?o.push(e):r.push(e);return{inserts:n,updates:o,deletes:r}},u=t=>{if(t.length===0)return null;const n=t[0],o=t[t.length-1],r=`merge:${a(t.map(e=>e.id??String(e.timestamp)).join("|"))}`;return i(n.table,t.flatMap(e=>e.changes),o.timestamp,r)};export{f as classifyChanges,i as createTableDiff,m as diffSize,g as isDiffEmpty,u as mergeDiffs};
@@ -0,0 +1 @@
1
+ const v=(a,n)=>{const e={},s={},i=n?.version?`${n.version}.`:"";for(const[o,p]of Object.entries(a)){const c={};for(const r of Object.keys(p)){const t=`${i}${o}.${r}`;s[t]=void 0;const f=Object.assign(y=>({type:t,payload:y,timestamp:Date.now()}),{type:t});c[r]=f}e[o]=c}return e._types=s,e};export{v as defineEvents};
@@ -0,0 +1 @@
1
+ const o=t=>{const e=t;return async({ctx:c,next:n})=>n({ctx:{events:e}})};export{o as eventsContext};
@@ -0,0 +1 @@
1
+ const o=c=>c.toString(16).padStart(4,"0"),g=c=>{let t=8997,n=33826,e=40164,s=52210;for(let h=0;h<c.length;h+=1){t^=c.charCodeAt(h);const r=t*435,p=n*435,x=e*435+t*256,d=s*435+n*256,l=p+(r>>>16),a=x+(l>>>16),f=d+(a>>>16);t=r&65535,n=l&65535,e=a&65535,s=f&65535}return o(s)+o(e)+o(n)+o(t)};export{g as f};
@@ -0,0 +1 @@
1
+ const I=n=>typeof n=="bigint"&&n>=BigInt(Number.MIN_SAFE_INTEGER)&&n<=BigInt(Number.MAX_SAFE_INTEGER)?Number(n):n,c=n=>n.map(t=>{let e;for(const[s,r]of Object.entries(t)){const o=I(r);o!==r&&(e??={...t},e[s]=o)}return e??t});export{c as n};
@@ -0,0 +1 @@
1
+ const n=t=>typeof t=="number",e=t=>typeof t!="number"&&"rebaseGeneration"in t,o=t=>typeof t=="object"&&t!==null&&"type"in t&&typeof t.type=="string"&&"payload"in t&&"timestamp"in t;export{e as isClientSeq,n as isGlobalSeq,o as isInputEvent};