@lunora/shard-engine 1.0.0-alpha.27 → 1.0.0-alpha.28
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/dist/conformance/index.mjs +1 -1
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/ADMIN_FUNCTIONS-Ddr79XHG.mjs +1 -0
- package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs +1 -0
- package/dist/packem_shared/AGG_COUNT-DOlqqroz.mjs +1 -0
- package/dist/packem_shared/AUDIT_LOG_TABLE-uNVU9O1W.mjs +8 -0
- package/dist/packem_shared/CDC_LOG_TABLE-B58N8NQO.mjs +8 -0
- package/dist/packem_shared/CLIENT_WATERMARK_TABLE-BoS1HEqz.mjs +7 -0
- package/dist/packem_shared/CountRlsUnsupportedError-Bdfupt3g.mjs +1 -0
- package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-4l6aU1Vc.mjs +31 -0
- package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-BAWGIEvC.mjs +1 -0
- package/dist/packem_shared/DEFAULT_MAX_RELAYS-DeVcEXBh.mjs +1 -0
- package/dist/packem_shared/DEFAULT_PROMOTION_THRESHOLDS-DVTD9iu0.mjs +1 -0
- package/dist/packem_shared/DEFAULT_TRANSACTION_LIMITS-Bcoi7Bvf.mjs +1 -0
- package/dist/packem_shared/DurableStreamRunner-Bm6KDMBU.mjs +1 -0
- package/dist/packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs +1 -0
- package/dist/packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-NWaL77m5.mjs +7 -0
- package/dist/packem_shared/IDEMPOTENCY_TABLE-DKVe2Ohf.mjs +7 -0
- package/dist/packem_shared/MAIL_RETENTION-Cig9Dmc8.mjs +18 -0
- package/dist/packem_shared/MAX_SQL_ROWS-DnDyeZph.mjs +2 -0
- package/dist/packem_shared/NotUniqueError-BixDiv4O.mjs +1 -0
- package/dist/packem_shared/QUEUE_TABLE-zj9Tt6tk.mjs +17 -0
- package/dist/packem_shared/RANK_TIEBREAK-ci3MaM65.mjs +1 -0
- package/dist/packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs +1 -0
- package/dist/packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs +1 -0
- package/dist/packem_shared/RLS_UNWRAP_SYMBOL-BWloGsd3.mjs +1 -0
- package/dist/packem_shared/ReactiveCache-DfyeaJOA.mjs +1 -0
- package/dist/packem_shared/SCAN_DEP-D7qE3iUe.mjs +1 -0
- package/dist/packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-DsycDXWm.mjs +6 -0
- package/dist/packem_shared/SEARCH_STATE_TABLE-Dju8ebbU.mjs +1 -0
- package/dist/packem_shared/SHAPE_POKE_CURSOR_TABLE-Dh4HfSdC.mjs +7 -0
- package/dist/packem_shared/ShardRunner-C9p5DVOx.mjs +1 -0
- package/dist/packem_shared/aggregateTableName-Cy5e03oz.mjs +1 -0
- package/dist/packem_shared/appendStreamChunk-CH4e4nJn.mjs +19 -0
- package/dist/packem_shared/applyOnDelete-BlcwKjuO.mjs +1 -0
- package/dist/packem_shared/applySelect-BQbHyo-W.mjs +1 -0
- package/dist/packem_shared/{armRestore-BNzdvQ_o.mjs → armRestore-Bu1_8SUa.mjs} +1 -1
- package/dist/packem_shared/awaitWsDrain-kSGvAfw1.mjs +1 -0
- package/dist/packem_shared/backfillAggregateIndexes-DVQ2sVuV.mjs +1 -0
- package/dist/packem_shared/base64-DfpzS4o_.mjs +1 -0
- package/dist/packem_shared/buildIndexRange-CBKQmHSS.mjs +1 -0
- package/dist/packem_shared/buildPokeFrames-BXejpiII.mjs +1 -0
- package/dist/packem_shared/buildReprojectionMigration-8nVn8Qwb.mjs +1 -0
- package/dist/packem_shared/buildSettings-B4igo4rJ.mjs +1 -0
- package/dist/packem_shared/compileWhereSql-JBpSfQm9.mjs +1 -0
- package/dist/packem_shared/computeRankPage-Bby1Npkd.mjs +1 -0
- package/dist/packem_shared/createCompanionSync-zCwaB6wj.mjs +1 -0
- package/dist/packem_shared/createReadFootprint-MRH1If3F.mjs +1 -0
- package/dist/packem_shared/createReplicaLink-C1JuP_DN.mjs +7 -0
- package/dist/packem_shared/createSystemReader-BtYeSMDb.mjs +1 -0
- package/dist/packem_shared/ctx-db-companions-lTt-rvKG.mjs +1 -0
- package/dist/packem_shared/defineEngineContractSuite-0XtjRA7F.mjs +1 -0
- package/dist/packem_shared/diffExternalSource-pozJ4UdZ.mjs +1 -0
- package/dist/packem_shared/do-sql-Dk_DJxn4.mjs +1 -0
- package/dist/packem_shared/estimate-bytes-CzG5x1f8.mjs +1 -0
- package/dist/packem_shared/exportShardRows-Cgt3ITwH.mjs +1 -0
- package/dist/packem_shared/hasTrigger-CjlwI4le.mjs +1 -0
- package/dist/packem_shared/isSoftDeleted-DcGB0pov.mjs +9 -0
- package/dist/packem_shared/liftSourceId-CA3ENhXj.mjs +1 -0
- package/dist/packem_shared/materializeExternalRows-Drn0FGdb.mjs +1 -0
- package/dist/packem_shared/mergeChangedKeys-D1T-TPUb.mjs +1 -0
- package/dist/packem_shared/param-Ib8WHnrF.mjs +1 -0
- package/dist/packem_shared/runDrizzle-it6rL9bR.mjs +1 -0
- package/dist/packem_shared/runShardMigrations-Crppyq1f.mjs +5 -0
- package/dist/packem_shared/runSocketPool-CZJ2X9cF.mjs +1 -0
- package/dist/packem_shared/selectExpiredIds-_5514W_v.mjs +1 -0
- package/dist/packem_shared/selectShapeMemberIds-B-pQJHAu.mjs +1 -0
- package/dist/packem_shared/serializeSqlValue-DbI1VQYM.mjs +1 -0
- package/dist/packem_shared/sibling-channel-BRZpLiDA.mjs +1 -0
- package/dist/packem_shared/sql-projection-BqmxFxQU.mjs +1 -0
- package/dist/packem_shared/stableStringify-CujpENIO.mjs +1 -0
- package/dist/packem_shared/stableWireKey-BYB5GQJa.mjs +1 -0
- package/dist/packem_shared/wire-codec-BU9T2xJ7.mjs +1 -0
- package/package.json +3 -3
- package/dist/packem_shared/ADMIN_FUNCTIONS-Cj1pJjVg.mjs +0 -1
- package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs +0 -1
- package/dist/packem_shared/AGG_COUNT-CKtq03Go.mjs +0 -1
- package/dist/packem_shared/AUDIT_LOG_TABLE-Bl2mYtAQ.mjs +0 -8
- package/dist/packem_shared/CDC_LOG_TABLE-DNFFQwF_.mjs +0 -8
- package/dist/packem_shared/CLIENT_WATERMARK_TABLE-LrKfdxyt.mjs +0 -7
- package/dist/packem_shared/CountRlsUnsupportedError-8BqPYQoP.mjs +0 -1
- package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-DIQTu___.mjs +0 -31
- package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-BV1RCoat.mjs +0 -1
- package/dist/packem_shared/DEFAULT_MAX_RELAYS-Cinp9pPC.mjs +0 -1
- package/dist/packem_shared/DEFAULT_PROMOTION_THRESHOLDS-DYGNAo1I.mjs +0 -1
- package/dist/packem_shared/DEFAULT_TRANSACTION_LIMITS-DLUzZbta.mjs +0 -1
- package/dist/packem_shared/DurableStreamRunner-B54Jt9Iu.mjs +0 -1
- package/dist/packem_shared/GEO_DEFAULT_PRECISION-DyI5zggj.mjs +0 -1
- package/dist/packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-B2LKe4KU.mjs +0 -7
- package/dist/packem_shared/IDEMPOTENCY_TABLE-tQ5mnqvw.mjs +0 -7
- package/dist/packem_shared/MAIL_RETENTION-CzZuX9bd.mjs +0 -18
- package/dist/packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs +0 -2
- package/dist/packem_shared/NotUniqueError-BlrEp5pr.mjs +0 -1
- package/dist/packem_shared/QUEUE_TABLE-BX0nopuT.mjs +0 -17
- package/dist/packem_shared/RANK_TIEBREAK-BGk411OR.mjs +0 -1
- package/dist/packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs +0 -1
- package/dist/packem_shared/REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs +0 -1
- package/dist/packem_shared/RLS_UNWRAP_SYMBOL-DcqORh2s.mjs +0 -1
- package/dist/packem_shared/ReactiveCache-D_T10KLy.mjs +0 -1
- package/dist/packem_shared/SCAN_DEP-D_yR9EeV.mjs +0 -1
- package/dist/packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEK7b_7v.mjs +0 -6
- package/dist/packem_shared/SEARCH_STATE_TABLE-DRk_SB72.mjs +0 -1
- package/dist/packem_shared/SHAPE_POKE_CURSOR_TABLE-pybVwKps.mjs +0 -7
- package/dist/packem_shared/ShardRunner-DIqVdWtk.mjs +0 -1
- package/dist/packem_shared/aggregateTableName-DN7gk6uh.mjs +0 -1
- package/dist/packem_shared/appendStreamChunk-ksZYy1hZ.mjs +0 -19
- package/dist/packem_shared/applyOnDelete-crbAzVfE.mjs +0 -1
- package/dist/packem_shared/applySelect-5w13bMAR.mjs +0 -1
- package/dist/packem_shared/awaitWsDrain-PT9o0d6J.mjs +0 -1
- package/dist/packem_shared/backfillAggregateIndexes-DTOIsYbi.mjs +0 -1
- package/dist/packem_shared/base64-fKomMf5D.mjs +0 -1
- package/dist/packem_shared/buildIndexRange-DFsdtPjD.mjs +0 -1
- package/dist/packem_shared/buildPokeFrames-DmB-FBeQ.mjs +0 -1
- package/dist/packem_shared/buildReprojectionMigration-JUwsTNTB.mjs +0 -1
- package/dist/packem_shared/buildSettings-COIJsw7a.mjs +0 -1
- package/dist/packem_shared/compileWhereSql-B3hq_v98.mjs +0 -1
- package/dist/packem_shared/computeRankPage-BU8LXvQs.mjs +0 -1
- package/dist/packem_shared/createCompanionSync-D-ckGBdA.mjs +0 -1
- package/dist/packem_shared/createReadFootprint-DIrrxRTE.mjs +0 -1
- package/dist/packem_shared/createReplicaLink-BMNW0SX6.mjs +0 -7
- package/dist/packem_shared/createSystemReader-DcDcrtM3.mjs +0 -1
- package/dist/packem_shared/ctx-db-companions-BJlCofon.mjs +0 -1
- package/dist/packem_shared/defineEngineContractSuite-ClCoUG6r.mjs +0 -1
- package/dist/packem_shared/diffExternalSource-DMpkJta1.mjs +0 -1
- package/dist/packem_shared/do-sql-DKSFK627.mjs +0 -1
- package/dist/packem_shared/estimate-bytes-Drp8rhPs.mjs +0 -1
- package/dist/packem_shared/exportShardRows-Bbi_JGfn.mjs +0 -1
- package/dist/packem_shared/hasTrigger-CbkOHExZ.mjs +0 -1
- package/dist/packem_shared/isSoftDeleted-DyEJueIu.mjs +0 -9
- package/dist/packem_shared/liftSourceId-DApAbu7Q.mjs +0 -1
- package/dist/packem_shared/materializeExternalRows-C-5TKdc1.mjs +0 -1
- package/dist/packem_shared/mergeChangedKeys-BXtUgIPW.mjs +0 -1
- package/dist/packem_shared/param-CYxL68V-.mjs +0 -1
- package/dist/packem_shared/runDrizzle-C3n5gJsk.mjs +0 -1
- package/dist/packem_shared/runShardMigrations-C1mjoJS4.mjs +0 -5
- package/dist/packem_shared/runSocketPool-DPQLVyWF.mjs +0 -1
- package/dist/packem_shared/selectExpiredIds-C4Ry_NxG.mjs +0 -1
- package/dist/packem_shared/selectShapeMemberIds-Bkkug6vU.mjs +0 -1
- package/dist/packem_shared/serializeSqlValue-BR4UOWoP.mjs +0 -1
- package/dist/packem_shared/sibling-channel-bg9FBL5s.mjs +0 -1
- package/dist/packem_shared/sql-projection-jfoe331H.mjs +0 -1
- package/dist/packem_shared/stableStringify-BjLh4gvA.mjs +0 -1
- package/dist/packem_shared/stableWireKey-Diuu1gGc.mjs +0 -1
- package/dist/packem_shared/wire-codec-Dh0j-GnY.mjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as a}from"@lunora/errors";const t=()=>Object.assign(new Error("native PITR is unavailable here (local dev or a non-SQLite Durable Object); use `lunora backup restore` for off-platform recovery"),{code:"PITR_UNAVAILABLE",name:"LunoraError",status:409}),i=o=>{if(typeof o=="number")return o;const r=Date.parse(o);if(Number.isNaN(r))throw new a("BAD_REQUEST",`pitr: invalid time "${o}" — expected epoch-ms or an ISO timestamp`);return r},
|
|
1
|
+
import{LunoraError as a}from"@lunora/errors";const t=()=>Object.assign(new Error("native PITR is unavailable here (local dev or a non-SQLite Durable Object); use `lunora backup restore` for off-platform recovery"),{code:"PITR_UNAVAILABLE",name:"LunoraError",status:409}),i=o=>{if(typeof o=="number")return o;const r=Date.parse(o);if(Number.isNaN(r))throw new a("BAD_REQUEST",`pitr: invalid time "${o}" — expected epoch-ms or an ISO timestamp`);return r},k=async(o,r)=>{if(!o.getCurrentBookmark)throw t();const e=await o.getCurrentBookmark();return r===void 0||!o.getBookmarkForTime?{current:e}:{current:e,forTime:await o.getBookmarkForTime(i(r))}},s=async(o,r)=>{if(!o.onNextSessionRestoreBookmark)throw t();let e=r.bookmark;if(e===void 0){if(r.time===void 0)throw new a("BAD_REQUEST","pitrRestore: provide a `bookmark` or a `time` to restore to");if(!o.getBookmarkForTime)throw t();e=await o.getBookmarkForTime(i(r.time))}const n=await o.onNextSessionRestoreBookmark(e);return{restoredTo:e,undoBookmark:n}};export{s as armRestore,k as readBookmark};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{stableStringify as h}from"./stableStringify-CujpENIO.mjs";import{i as m,e as I}from"./wire-codec-BU9T2xJ7.mjs";const w="_id",p="_creationTime",y="page",$=e=>{let t;for(const s of e){const n=s[p];if(typeof n=="number"){if(t!==void 0){if(n<t)return!0;if(n>t)return!1}t=n}}return!1},J=(e,t)=>{const s=t[p];if(typeof s!="number")return e.length;const n=$(e);for(const[o,r]of e.entries()){const i=r[p];if(typeof i=="number"&&(n?i<s:i>s))return o}return e.length},S="__lunora__",_=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return;const t=e[w];return typeof t=="string"?t:void 0},A=e=>{const t=new Map,s=[];for(const n of e){const o=_(n);if(o===void 0||t.has(o))return;t.set(o,n),s.push(o)}return{byId:t,order:s}},x=(e,t)=>{const s=e.order.filter(o=>t.byId.has(o)),n=t.order.filter(o=>e.byId.has(o));return s.length!==n.length?!1:s.every((o,r)=>n[r]===o)},F=(e,t,s,n)=>{const o=[];for(const r of e.order)t.byId.has(r)||o.push({delta:{key:r,op:"delete",table:s},frame:`{"key":${JSON.stringify(r)},"op":"delete","table":${n}}`});return o},L=(e,t,s,n)=>{const o=[];for(const r of t.order){const i=t.byId.get(r),c=e.byId.get(r),d=JSON.stringify(I(i)),a=c===void 0?void 0:JSON.stringify(c);if(a===d)continue;const f=a===void 0?"insert":"update";o.push({delta:{key:r,op:f,row:i,table:s},frame:`{"key":${JSON.stringify(r)},"op":"${f}","row":${d},"table":${n}}`})}return o},N=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return{next:t,previous:e};if(!m(e)||!m(t))return;const s=e[y],n=t[y];if(!Array.isArray(s)||!Array.isArray(n))return;const o=r=>Object.fromEntries(Object.entries(r).filter(([i])=>i!==y));if(h(o(e))===h(I(o(t))))return{next:n,previous:s}},E=(e,t,s)=>{const n=s.filter(({delta:r})=>r.op==="insert");if(n.length===0)return!0;const o=e.order.filter(r=>t.byId.has(r)).map(r=>e.byId.get(r));for(const{delta:r}of n){const i=r.row;o.splice(J(o,i),0,i)}return o.length===t.order.length&&o.every((r,i)=>r[w]===t.order[i])},D=(e,t,s)=>{let n;try{n=JSON.parse(e)}catch{return}const o=N(n,t);if(o===void 0)return;const r=A(o.previous),i=A(o.next);if(r===void 0||i===void 0||!x(r,i))return;const c=s===""?S:s,d=JSON.stringify(c),a=[...F(r,i,c,d),...L(r,i,c,d)];return E(r,i,a)?a:void 0},j=(e,t,s,n)=>{const o=D(e,t,s);if(o!==void 0){if(n!==void 0)for(const{frame:r}of o)n.push(r);return o.map(({delta:r})=>r)}},k=(e,t)=>{try{return e.send(t),!0}catch{return!1}},M=e=>{const{cursorSuffix:t,lastMutationId:s,nextResult:n,pageDeltas:o,previousJson:r,snapshotJson:i,subId:c,table:d}=e,a=JSON.stringify(c),f=(s===void 0?"":`,"lastMutationId":${String(s)}`)+t,u=`{"type":"data","id":${a},"data":${i}${f}}`,l=r!==void 0&&(o===!0||Array.isArray(n))?D(r,n,d):void 0;if(l===void 0||l.length===0)return[u];const g=[];let v=0;for(const{frame:O}of l){const b=`{"type":"delta","id":${a},"delta":${O}${f}}`;if(v+=b.length,v>=u.length)return[u];g.push(b)}return g},B=async e=>{let t=0;for(;t<100;){t+=1;const{bufferedAmount:s}=e;if(typeof s!="number"||s<1048576)return;await new Promise(n=>{setTimeout(n,20)})}};export{B as awaitWsDrain,M as subscriptionFrames,j as subscriptionListDeltas,k as trySendFrame};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as k,i as A,a as p,j as $,y as E,S as O,h as C}from"./ctx-db-companions-lTt-rvKG.mjs";import{sql as n}from"drizzle-orm";import{matchesStaticWhere as L}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as M,encodeAggregateKey as _,foldAggregateTally as y}from"./aggregateTableName-Cy5e03oz.mjs";import{migrateSearchState as D,readSearchBackfillState as F,writeSearchBackfillState as x}from"./SEARCH_STATE_TABLE-Dju8ebbU.mjs";import{runDrizzle as d}from"./runDrizzle-it6rL9bR.mjs";import{i as T,r as b,a as N,b as v,A as B,D as S,h as G}from"./do-sql-Dk_DJxn4.mjs";import{isLiveForCompanion as U}from"./applySelect-BQbHyo-W.mjs";import{rankTableName as W,matchesRankStaticWhere as j}from"./RANK_TIEBREAK-ci3MaM65.mjs";const H=(e,i)=>e.profile!==i?{cursor:void 0,finished:!1,wipe:e.cursor!==void 0||e.done}:{cursor:e.cursor,finished:e.done,wipe:!1},I=(e,i)=>d(e,n`SELECT COUNT(*) AS count FROM ${n.identifier(i)}`).one().count>0,R=(e,i)=>d(e,n`SELECT id, _creationTime, ${n.identifier(S)} FROM ${n.identifier(i)}`).toArray(),K=(e,i,t,o)=>{const r=M(i,t.name);if(I(e,r))return;const c=t.by??[],f=new Map,s=R(e,i);for(const l of s){const a=b(l);if(!a||!U(a,o)||t.where&&!L(a,t.where))continue;const g=_(c,a);y(f,g,t,a)}for(const[l,a]of f)d(e,n`INSERT INTO ${n.identifier(r)} (${N}, ${v}, ${B}) VALUES (${l}, ${a.value}, ${a.count})`)},oe=(e,i)=>{for(const[t,o]of Object.entries(i.tables))if(!(o.shardMode?.kind==="global"||!o.aggregateIndexes))for(const r of o.aggregateIndexes)K(e,t,r,o.softDeleteMode?.field)},V=(e,i,t)=>{const o=W(i,t.name);if(I(e,o))return;const r=k(t),c=R(e,i);for(const f of c){const s=b(f);!s||t.where&&!j(s,t.where)||A(e,o,t,r,s._id,s)}},ne=(e,i)=>{for(const[t,o]of Object.entries(i.tables))if(!(o.shardMode?.kind==="global"||!o.rankIndexes))for(const r of o.rankIndexes)V(e,t,r)},u=500,w=(e,i,t)=>{const o=p(i,t.name),{profile:r}=$(t.language),c=H(F(e,o),r);if(c.finished)return!0;c.wipe&&d(e,n`DELETE FROM ${n.identifier(o)}`);const{cursor:f}=c,s=d(e,f===void 0?n`SELECT id, _creationTime, ${n.identifier(S)} FROM ${n.identifier(i)} ORDER BY id ASC LIMIT ${n.raw(String(u))}`:n`SELECT id, _creationTime, ${n.identifier(S)} FROM ${n.identifier(i)} WHERE id > ${f} ORDER BY id ASC LIMIT ${n.raw(String(u))}`).toArray();let l=f;for(const g of s){const{id:m}=g;if(typeof m!="string")continue;l=m,d(e,n`DELETE FROM ${n.identifier(o)} WHERE ${n.identifier(E)} = ${m}`);const h=G(g);h&&d(e,n`INSERT INTO ${n.identifier(o)} (${n.identifier(O)}, ${n.identifier(E)}) VALUES (${C(h,t)}, ${m})`)}const a=s.length<u;return x(e,o,l,a,r),a},ie=(e,i,t)=>{if(T(e))for(const o of t.searchIndexes??[])o.staged||w(e,i,o)},te=(e,i)=>{if(T(e)){D(e);for(const[t,o]of Object.entries(i.tables))if(!(o.shardMode?.kind==="global"||!o.searchIndexes))for(const r of o.searchIndexes){let c=!1;for(;!c;)c=w(e,t,r)}}};export{oe as backfillAggregateIndexes,ne as backfillRankIndexes,te as backfillSearchIndexes,ie as backfillSearchIndexesForTable};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const o=r=>{let n="";for(let t=0;t<r.length;t+=32768)n+=String.fromCharCode(...r.subarray(t,t+32768));return btoa(n)},a=r=>{const n=atob(r),e=new Uint8Array(n.length);for(let t=0;t<n.length;t+=1)e[t]=n.codePointAt(t)??0;return e};export{a as f,o as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const E=t=>{const o=new DataView(new ArrayBuffer(8));o.setFloat64(0,t,!1);let n=o.getUint32(0,!1),e=o.getUint32(4,!1);return(n&2147483648)===0?n=(n^2147483648)>>>0:(n=~n>>>0,e=~e>>>0),n.toString(16).padStart(8,"0")+e.toString(16).padStart(8,"0")},v=t=>{const o=new TextEncoder().encode(t);let n="";for(const e of o)n+=e.toString(16).padStart(2,"0");return n},a=t=>{if(t===null)return"0";if(typeof t=="number")return Number.isFinite(t)?`1${E(t===0?0:t)}`:void 0;if(typeof t=="string")return`2${v(t)}`},l=t=>{const o=[];for(const n of t){const e=a(n);if(e===void 0)return;o.push(e)}return o.join("!")};const p=new Set([">",">="]),x=new Set(["<","<="]),A=(t,o,n,e)=>{const i=o.comparator==="=",r=p.has(o.comparator)||x.has(o.comparator);return!i&&!r||t.indexOf(o.field)!==n?!1:e===void 0?!0:!i&&e===o.field},h=(t,o,n)=>{const e={equalities:[],lowerExclusive:!1,upperExclusive:!1};let i;for(const r of o){const s=r.comparator==="=",c=p.has(r.comparator);if(!A(t,r,e.equalities.length,i))return;if(s){e.equalities.push(n(r.value));continue}if(i=r.field,c){if(e.lower!==void 0)return;e.lower=n(r.value),e.lowerExclusive=r.comparator===">"}else{if(e.upper!==void 0)return;e.upper=n(r.value),e.upperExclusive=r.comparator==="<"}}return e},f=(t,o)=>{const n=a(o);if(n!==void 0)return t===""?n:t+"!"+n},g=(t,o,n,e,i)=>{if(n.length===0)return;const r=h(n,e,i);if(!r)return;const s=l(r.equalities);if(s===void 0)return;let c=s,d=s+"";if(r.lower!==void 0){const u=f(s,r.lower);if(u===void 0)return;c=r.lowerExclusive?u+"!":u}if(r.upper!==void 0){const u=f(s,r.upper);if(u===void 0)return;d=r.upperExclusive?u:u+""}if(!(c>=d))return{hi:d,index:o,lo:c,table:t}},m=(t,o,n)=>{const e=[];for(const i of t){const r=l(i.fields.map(s=>n(o[s])));r!==void 0&&e.push({index:i.name,key:r})}return e},w=(t,o)=>t.index===o.index&&o.key>=t.lo&&o.key<t.hi,S=(t,o)=>{if(!t||t.length===0||!o||o.length===0)return!0;const n=new Map;for(const e of o){const i=n.get(e.index);i?i.push(e):n.set(e.index,[e])}return t.some(e=>{const i=n.get(e.index);return!i||i.length===0?!0:i.some(r=>w(e,r))})};export{g as buildIndexRange,m as indexKeysForRow,S as keysTouchRanges,w as rangeContains};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{e as h}from"./wire-codec-BU9T2xJ7.mjs";const u=(t,e)=>{if(!e)return t;const a=Object.create(null);for(const n of["_id","_creationTime",...e])Object.hasOwn(t,n)&&(a[n]=t[n]);return a},y=(t,e,a)=>{const{columns:n,table:p}=a,i=new Map,r=[];for(const{doc:o,id:s}of t){const c=u(o,n),f=JSON.stringify(h(c));i.set(s,f);const d=e.get(s);d===void 0?r.push({key:s,op:"insert",table:p,value:c}):d!==f&&r.push({key:s,op:"update",table:p,value:c})}for(const o of e.keys())i.has(o)||r.push({key:o,op:"delete",table:p});return{next:i,rowsPatch:r}},l=t=>t.map(e=>e.value===void 0?e:{...e,value:h(e.value)}),b=(t,e,a={})=>{const{baseCheckpoint:n,checkpoint:p,epoch:i,lastMutationId:r,pokeId:o}=e,s=[JSON.stringify({baseCheckpoint:n,epoch:i,pokeId:o,type:"pokeStart"})];for(const c of t){const f=a.preEncoded?c.rowsPatch:l(c.rowsPatch);s.push(JSON.stringify({pokeId:o,rowsPatch:f,shapeId:c.shapeId,type:"pokePart",...r===void 0?{}:{lastMutationId:r}}))}return s.push(JSON.stringify({checkpoint:p,epoch:i,pokeId:o,type:"pokeEnd"})),s};export{b as buildPokeFrames,y as diffGlobalMembership,l as encodeRowsPatch,u as projectColumns};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{quoteIdentifier as l}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as u}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{REPROJECTION_MIGRATION_PREFIX as v,reprojectionMigrationId as w}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{e as m}from"./wire-codec-BU9T2xJ7.mjs";import{runSql as p}from"./runDrizzle-it6rL9bR.mjs";import{k as d,D as E}from"./do-sql-Dk_DJxn4.mjs";import{m as g}from"./sql-projection-BqmxFxQU.mjs";const b=m(0n)[0],_=e=>e.shardMode?.kind==="global"?[]:Object.entries(e.shape).filter(([,r])=>g(r)).map(([r])=>r),M=e=>Object.entries(e.tables).filter(([,r])=>_(r).length>0).map(([r])=>r),f=e=>{const r=`json_each(${l(E)}) AS __f__`;return{params:[JSON.stringify(e),b,"bigint","bytes"],sql:`EXISTS (SELECT 1 FROM ${r} WHERE __f__.type = 'array' AND __f__.key IN (SELECT value FROM json_each(?)) AND json_extract(__f__.value, '$[0]') = ? AND json_extract(__f__.value, '$[1]') IN (?, ?))`}},N=(e,r,o)=>{if(o.length===0)return 0;const{params:t,sql:n}=f(o);return p(e,`SELECT COUNT(*) AS count FROM ${l(r)} WHERE ${n}`,...t).toArray()[0]?.count??0},R=(e,r,o,t)=>{const{params:n,sql:i}=f(o);return p(e,`SELECT 1 FROM ${l(r)} WHERE id = ? AND (${i}) LIMIT 1`,t,...n).toArray().length>0},S=(e,r,o)=>{const t=u(e);if(t===void 0)return;const n=r.tables[t];if(!n)return;const i=_(n);if(i.length!==0)return{id:e,table:t,up:s=>{const a=s._id;if(!(typeof a!="string"||!R(o,t,i,a))){try{d(s)}catch(c){console.warn(`${e}: skipping row ${a} — it cannot be re-projected: ${c instanceof Error?c.message:String(c)}`);return}return s}}}};export{v as REPROJECTION_MIGRATION_PREFIX,S as buildReprojectionMigration,N as countLegacyRows,_ as reprojectableFields,w as reprojectionMigrationId,M as reprojectionTables};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const u=/key|secret|token|password|passwd|credential|private|auth|bearer|session|cookie|salt|signature|dsn|webhook/iu,f=new Set(["LUNORA_ADMIN_TOKEN","LUNORA_WS_BEARER"]),l=["CF_PAGES_URL","WORKER_URL","LUNORA_WORKER_URL"],c=["CF_ENV","ENVIRONMENT","WORKER_ENV","NODE_ENV"],d=n=>n.length<=4?"••••":`${n.slice(0,4)}${"•".repeat(Math.min(8,n.length-4))}`,p=n=>u.test(n),R=n=>{const e=t=>typeof n[t]=="function";return e("idFromName")||e("idFromString")?"durable-object":e("createMultipartUpload")||e("put")&&e("get")&&e("list")&&e("head")?"r2":e("getWithMetadata")?"kv":e("prepare")&&e("dump")?"d1":e("send")&&e("sendBatch")?"queue":e("fetch")&&!e("get")?"service":"object"},E=n=>{const e=i=>i.map(a=>n[a]).find(a=>typeof a=="string"&&a!==""),t={},o=e(l),r=e(c);o!==void 0&&(t.workerUrl=o),r!==void 0&&(t.environment=r);const s=n.CF_VERSION_METADATA;if(s!==null&&typeof s=="object"){const i=s;typeof i.id=="string"&&(t.deploymentId=i.id),typeof i.tag=="string"&&(t.versionTag=i.tag)}return t},N=/^(?:dev(?:elopment)?|local(?:host)?|test)$/iu,_=n=>{const e=n??{};for(const t of c){const o=e[t];if(typeof o=="string"&&N.test(o))return!0}return!1},g=n=>{const e=n??{},t=[];for(const[o,r]of Object.entries(e))if(!f.has(o)){if(typeof r=="string"){const s=p(o);t.push({kind:s?"secret":"var",name:o,value:d(r)});continue}if(typeof r=="number"||typeof r=="boolean"){t.push({kind:"var",name:o,value:String(r)});continue}if(r!==null&&typeof r=="object"){t.push({bindingType:R(r),kind:"binding",name:o,value:null});continue}t.push({kind:"var",name:o,value:null})}return t.sort((o,r)=>o.name.localeCompare(r.name)),{deploy:E(e),settings:t}};export{R as bindingType,g as buildSettings,_ as isDevEnvironment,p as looksSecret,E as readDeployInfo,d as redact};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as L}from"@lunora/errors";import{sql as s}from"drizzle-orm";import{sqliteInList as a,WORKERD_SQLITE_LIMITS as I}from"./param-Ib8WHnrF.mjs";import{RELATION_EXISTS_KEY as N}from"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";const m=["eq","ne","lt","lte","gt","gte","in","notIn","isNull","contains"],T=new Set(m),E={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},O=t=>{if(t===null||typeof t!="object"||Array.isArray(t))return!1;const o=Object.keys(t);return o.length>0&&o.every(n=>T.has(n))},$=(t,o,n)=>{const i=s`${n.serialize(o)}`;return n.containsExpr?n.containsExpr(t,i):s`instr(lower(${t}), lower(${i})) > 0`},A=(t,o,n,i,r)=>i===null?o==="ne"?s`${t} IS NOT NULL`:s`${t} IS NULL`:s`${t} ${s.raw(n)} ${r.serialize(i)}`,S=(t,o,n,i)=>{const r=Array.isArray(n)?n:[];if(r.length===0)return o==="IN"?s`0 = 1`:s`1 = 1`;const e=r.map(l=>i.serialize(l)),c=o==="NOT IN";return(i.inList??a)(t,e,c)},M=(t,o,n)=>{const i=s.join(o.map(r=>s`${r}`),s`, `);return n?s`${t} NOT IN (${i})`:s`${t} IN (${i})`},h=(t,o,n)=>{const i=o,r=[];for(const e of m){if(!(e in i))continue;const c=i[e],l=E[e];l?r.push(A(t,e,l,c,n)):e==="isNull"?r.push(c?s`${t} IS NULL`:s`${t} IS NOT NULL`):e==="contains"?r.push($(t,c,n)):r.push(S(t,e==="in"?"IN":"NOT IN",c,n))}return r},R=(t,o,n)=>{const i=n.fieldRef(t);return O(o)?h(i,o,n):o===null?[s`${i} IS NULL`]:[s`${i} = ${n.serialize(o)}`]},p=(t,o)=>{if(t.length<=1)return t[0];const n=Math.floor(t.length/2);return s`(${p(t.slice(0,n),o)}) ${s.raw(o)} (${p(t.slice(n),o)})`},d=(t,o,n)=>{const i=Array.isArray(t)?t:[],r=[];for(const e of i){const c=f(e??{},n);c&&r.push(c)}return r.length===0?o==="OR"?s`0 = 1`:void 0:p(r,o)},_=new Set(["AND","NOT","OR",N]),b=(t,o,n)=>{if(t===N){if(!n.relationExists)throw new L("INTERNAL","encountered a relation EXISTS marker without a relationExists strategy hook");return n.relationExists(o)}if(t==="NOT"){const i=f(o??{},n);return i?s`NOT (${i})`:void 0}return d(o,t,n)},f=(t,o)=>{const n=[];for(const[i,r]of Object.entries(t))if(_.has(i)){const e=b(i,r,o);e&&n.push(e)}else n.push(...R(i,r,o));return p(n,"AND")},j=I.boundParams/2,u=t=>{if(Array.isArray(t))return t.reduce((n,i)=>n+u(i),0);if(t===null||typeof t!="object")return 0;let o=0;for(const[n,i]of Object.entries(t))n==="in"||n==="notIn"?o+=1:(n==="AND"||n==="NOT"||n==="OR"||O(i))&&(o+=u(i));return o},q=(t,o)=>{if(!t||Object.keys(t).length===0)return;const n=o.inList??a,i=u(t);if(i===0)return f(t,o);const r=Math.max(1,Math.floor(j/i));return f(t,{...o,inList:(e,c,l)=>n(e,c,l,r)})};export{q as compileWhereSql,M as literalInList};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as A}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{mergeWhere as j}from"./CountRlsUnsupportedError-Bdfupt3g.mjs";import{SCAN_DEP as q}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as S}from"./runDrizzle-it6rL9bR.mjs";import{sqliteInList as O}from"./param-Ib8WHnrF.mjs";import{decodeCursor as F,toBase64 as V}from"./applySelect-BQbHyo-W.mjs";import{rankTableName as z,sortColumnName as H,resolveRankPartition as U,RANK_TIEBREAK as _,encodePartitionKey as J}from"./RANK_TIEBREAK-ci3MaM65.mjs";const P="__doc__",Y=n=>V(JSON.stringify(n)),G=n=>n.after?[n.after.partitionKey,...n.after.sortValues,n.after.rowId]:n.cursor?F(n.cursor):void 0,Q=(n,r,a)=>{if(n?.length!==1+r.length+1)return;const t=[{column:"__partition__",direction:"asc"}];for(const[s,c]of r.entries())t.push({column:c,direction:a[s]?.direction??"asc"});t.push({column:_,direction:"asc"});const e=[];for(const[s,c]of t.entries()){const u=[];for(const[i,p]of t.slice(0,s).entries())u.push(o`${o.identifier(p.column)} IS ${n[i]}`);u.push(o`${o.identifier(c.column)} ${o.raw(c.direction==="desc"?"<":">")} ${n[s]}`);const[f]=u;e.push(u.length===1&&f!==void 0?f:o`(${o.join(u,o` AND `)})`)}return o`(${o.join(e,o` OR `)})`},T=null,X=(n,r)=>{if(n===void 0)return T;const a=[n.__partition__,...r.map(t=>n[t]),n[_]];return Y(a)},Z=(n,r,a)=>{const t=[];for(const e of n){const s=e[_];if(typeof s!="string")continue;const c=r.get(s);if(!c)continue;const u=typeof e.__partition__=="string"?e.__partition__:"",f=a.map(i=>e[i]??null);t.push({doc:c,key:{partitionKey:u,rowId:s,sortValues:f}})}return t},oo=o`${o.identifier("id")}`,no=(n,r,a)=>{const{rowToDocument:t}=n,e=new Map;if(a.length===0)return e;const s=S(n.sql,o`SELECT id, _creationTime, ${o.identifier(P)} FROM ${o.identifier(r)} WHERE ${O(oo,a,!1)}`).toArray();for(const c of s){const u=t(c),f=c.id;u&&typeof f=="string"&&e.set(f,u)}return e},fo=(n,r,a,t)=>{const{assertRankPartitionLocal:e,ensureRankBackfilled:s,onRead:c,schema:u}=n,f=u.tables[r];if(!f)throw new A("INTERNAL",`unknown table: ${r}`);const i=f.rankIndexes?.find(d=>d.name===a);if(!i)throw new A("INTERNAL",`unknown rankIndex "${a}" on table "${r}"`);e(r,f,i),c(r,q),s(r,i);const p=z(r,i.name),l=i.sortBy.map((d,w)=>H(w)),h=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),B=j(t.baseWhere,t.where),k=U(i,B),$=[o`${o.identifier("__partition__")} ASC`];for(const[d,w]of l.entries()){const b=i.sortBy[d]?.direction;$.push(o`${o.identifier(w)} ${o.raw(b==="desc"?"DESC":"ASC")}`)}$.push(o`${o.identifier(_)} ASC`);const m=[];typeof t.partitionKey=="string"?m.push(o`${o.identifier("__partition__")} = ${t.partitionKey}`):k&&m.push(o`${o.identifier("__partition__")} = ${J(i.partitionBy??[],k)}`);const D=G(t),E=Q(D,l,i.sortBy);E&&m.push(E);const I=o.identifier(_),g=o.identifier("__partition__"),L=m.length>0?o` WHERE ${o.join(m,o` AND `)}`:o``,M=l.length>0?o`${I}, ${g}, ${o.join(l.map(d=>o.identifier(d)),o`, `)}`:o`${I}, ${g}`,v=o`SELECT ${M} FROM ${o.identifier(p)}${L} ORDER BY ${o.join($,o`, `)} LIMIT ${o.raw(String(h+1))}`,R=S(n.sql,v).toArray(),C=R.length>h,y=C?R.slice(0,h):R,K=y.map(d=>d[_]),x=Z(y,no(n,r,K),l),N=C?X(y.at(-1),l):T,W=i.sortBy.map(d=>d.direction==="desc"?"desc":"asc");return{continueCursor:N,directions:W,hasMore:C,rows:x}};export{fo as computeRankPage,no as hydrateDocsById};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as l,i as C,r as R}from"./ctx-db-companions-lTt-rvKG.mjs";import"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import"./aggregateTableName-Cy5e03oz.mjs";import"./runDrizzle-it6rL9bR.mjs";import"./do-sql-Dk_DJxn4.mjs";import"./param-Ib8WHnrF.mjs";import"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import"./applySelect-BQbHyo-W.mjs";import"./RANK_TIEBREAK-ci3MaM65.mjs";import"./sql-projection-BqmxFxQU.mjs";import"./serializeSqlValue-DbI1VQYM.mjs";export{l as createCompanionSync,C as insertRankRow,R as rankColumnsSql};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const s=()=>{const n=new Set,t=new Map,o=new Set;return{onRead(e){n.add(e),o.add(e)},onReadRange(e){n.add(e.table);const a=t.get(e.table);a?a.push(e):t.set(e.table,[e])},ranges(){for(const e of o)t.delete(e);return t.size>0?t:void 0},tables:n}};export{s as createReadFootprint};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{v as w,R as v,e as f,s as y,a as g,b as A}from"./sibling-channel-BRZpLiDA.mjs";const N=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],T=new Set(N),L=s=>typeof s=="string"&&T.has(s),h="::replica::",E=s=>{const e=s.lastIndexOf(h);if(e===-1)return;const t=s.slice(0,e),n=s.slice(e+h.length);if(!(t.length===0||!L(n)))return{ownerKey:t,region:n}},O=s=>{if(s==null||!/^\d+$/.test(s))return;const e=Number.parseInt(s,10);return Number.isSafeInteger(e)&&e>0?e:void 0},b=1e3,R=1e3,I=10,C=5e4,q=s=>f(s,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",C),d="__replica_state",u=new WeakSet,S=s=>{u.has(s)||(s.exec(`CREATE TABLE IF NOT EXISTS ${d} (
|
|
2
|
+
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
3
|
+
epoch TEXT NOT NULL,
|
|
4
|
+
applied_seq INTEGER NOT NULL,
|
|
5
|
+
synced_at REAL NOT NULL
|
|
6
|
+
)`),u.add(s))},c=s=>(S(s),s.exec(`SELECT epoch, applied_seq AS appliedSeq, synced_at AS syncedAtMs FROM ${d} WHERE id = 1`).toArray()[0]),l=(s,e)=>{S(s),s.exec(`INSERT INTO ${d} (id, epoch, applied_seq, synced_at) VALUES (1, ?, ?, ?)
|
|
7
|
+
ON CONFLICT(id) DO UPDATE SET epoch = excluded.epoch, applied_seq = excluded.applied_seq, synced_at = excluded.synced_at`,e.epoch,e.appliedSeq,e.syncedAtMs)},m=s=>{const e=s.doName();if(e!==void 0&&E(e)!==void 0)return new Response("replica cannot serve replicas",{status:409});if(s.ownerEpoch()===void 0)return new Response("shard has no changelog to replicate",{status:409});if(g(s.env())===void 0)return new Response("replica control requires LUNORA_RELAY_SECRET",{status:403})},P=async(s,e)=>{const t=m(s);if(t!==void 0)return t;const n=s.ownerEpoch();let i;try{i=await e.text()}catch{return new Response("bad request",{status:400})}if(!await w(s.env(),e.headers.get(v),i))return new Response("forbidden",{status:403});let r;try{r=JSON.parse(i)}catch{return new Response("bad request",{status:400})}if(r.type==="replica_bootstrap"){if(s.rowCount()>q(s.env()))return Response.json({cursor:0,epoch:n,rows:[],truncated:!0});const o=s.ownerCursor()??0,a=await s.exportRows();return Response.json({cursor:o,epoch:n,rows:a})}if(r.type==="replica_pull"){const o=typeof r.sinceSeq=="number"&&Number.isInteger(r.sinceSeq)&&r.sinceSeq>=0?r.sinceSeq:0,{changes:a,cursor:_}=s.readChanges(o,R),p=s.ownerFloor();return Response.json({changes:a,cursor:_,epoch:n,...p===void 0?{}:{floor:p}})}return new Response("unknown replica frame",{status:400})};class U{constructor(e,t,n){this.host=e,this.ownerKey=t,this.region=n}host;ownerKey;region;divergent=!1;inFlight;async ensureFresh(e){if(this.divergent)return"unavailable";if(this.isCaughtUp(e))return"fresh";this.inFlight??=this.advance(e).finally(()=>{this.inFlight=void 0});const t=await this.inFlight;return t==="fresh"&&!this.isCaughtUp(e)?"stale":t}appliedSeq(){return c(this.host.sql())?.appliedSeq??0}isDivergent(){return this.divergent}async advance(e){let t=c(this.host.sql());if(t===void 0){const n=await this.bootstrap();if(n===void 0)return"unavailable";t=n}return this.catchUp(t,e)}isCaughtUp(e){const t=c(this.host.sql());return t!==void 0&&this.isFreshEnough(t,e)}async catchUp(e,t){let n=e;for(let i=0;i<I;i+=1){const r=await this.pull(n.appliedSeq);if(r===void 0)return t===void 0&&this.isFreshEnough(n,void 0)?"fresh":"unavailable";if(this.hasDiverged(n,r))return"unavailable";const o=r.changes.length<R;if(n=await this.applyPage(r),o||this.isFreshEnough(n,t))return this.isFreshEnough(n,t)?"fresh":"stale"}return this.isFreshEnough(n,t)?"fresh":"stale"}async applyPage(e){e.changes.length>0&&await this.host.applyChanges(e.changes);const t={appliedSeq:e.cursor,epoch:e.epoch,syncedAtMs:Date.now()};return l(this.host.sql(),t),t}hasDiverged(e,t){const n=t.changes.length===0&&t.cursor>e.appliedSeq,i=t.floor??(n?t.cursor:0),r=i>0&&i>e.appliedSeq+1;return t.epoch===e.epoch&&!r?!1:(this.divergent=!0,!0)}async bootstrap(){const e=await this.request({type:"replica_bootstrap"});if(e===void 0)return;const t=await e.json();if(t.truncated===!0){this.divergent=!0;return}const{errors:n}=await this.host.importRows(t.rows);if(n.length>0){this.divergent=!0;return}const i={appliedSeq:t.cursor,epoch:t.epoch,syncedAtMs:Date.now()};return l(this.host.sql(),i),i}isFreshEnough(e,t){return t!==void 0?e.appliedSeq>=t:Date.now()-e.syncedAtMs<=f(this.host.env(),"LUNORA_REPLICA_MAX_STALENESS_MS",b)}async pull(e){const t=await this.request({sinceSeq:e,type:"replica_pull"});return t===void 0?void 0:await t.json()}async request(e){const t=this.host.shardBinding(),n=y(this.host.env(),t,this.ownerKey);if(n===void 0)return;const i=JSON.stringify(e),r={"content-type":"application/json","x-lunora-shard-binding":t??""},o=g(this.host.env());o!==void 0&&(r[v]=await A(o,i));try{const a=await n.fetch("https://replica.internal/_lunora/replica",{body:i,headers:r,method:"POST"});return a.ok?a:void 0}catch{return}}}const x=s=>{const e=s.doName();if(e===void 0)return;const t=E(e);return t===void 0?void 0:new U(s,t.ownerKey,t.region)},M=async(s,e,t)=>{if(e.headers.get("x-lunora-replica-read")!=="1")return Response.json({error:{code:"REPLICA_READ_ONLY",message:`"${t}" is a write and cannot run on a read replica`}},{status:421});const n=await s.ensureFresh(O(e.headers.get("x-lunora-min-seq")));if(n!=="fresh")return Response.json({error:{code:"REPLICA_NOT_READY",message:`replica is ${n} for this read`}},{headers:{"x-lunora-replica-fallback":n},status:421})};export{x as createReplicaLink,M as gateReplicaDispatch,P as handleReplicaControl};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as c}from"@lunora/errors";const d=e=>{const t={args:e.args??{},enqueuedAt:typeof e.enqueuedAt=="number"?e.enqueuedAt:0,functionPath:typeof e.functionPath=="string"?e.functionPath:"",id:typeof e.id=="string"?e.id:"",scheduledFor:typeof e.scheduledFor=="number"?e.scheduledFor:0};return typeof e.attempts=="number"&&(t.attempts=e.attempts),typeof e.shardKey=="string"&&(t.shardKey=e.shardKey),t},i=e=>{const t={key:typeof e.key=="string"?e.key:"",size:typeof e.size=="number"?e.size:0},r=e.httpMetadata?.contentType??e.contentType;typeof r=="string"&&(t.contentType=r),e.customMetadata&&typeof e.customMetadata=="object"&&(t.customMetadata=e.customMetadata),typeof e.sha256=="string"&&(t.sha256=e.sha256);const{uploaded:a}=e;return typeof a=="number"?t.uploaded=a:a instanceof Date&&(t.uploaded=a.getTime()),t},h=(e={})=>{const t=()=>{if(!e.scheduler)throw new c("INTERNAL",'ctx.db.system.query("_scheduled_functions"): no scheduler configured. Pass `scheduler` to createShardDO().');return e.scheduler},r=()=>{if(!e.storage)throw new c("INTERNAL",'ctx.db.system.query("_storage"): no storage configured. Pass `storage` to createShardDO().');return e.storage},a=async()=>(await t().list()).map(s=>d(s)),f=async()=>{const{objects:n}=await r().list();return n.map(s=>i(s))};return{get:(async(n,s)=>{if(n==="_scheduled_functions"){const o=await t().get(s);return o?d(o):null}const u=await r().getMetadata(s);return u?i(u):null}),query:(n=>n==="_scheduled_functions"?{collect:a}:{collect:f})}};export{h as createSystemReader};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{matchesStaticWhere as P,aggregateSqlFunction as le}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as N,encodeAggregateKey as L,foldAggregateTally as J,coerceAggregateNumber as C}from"./aggregateTableName-Cy5e03oz.mjs";import{runDrizzle as $}from"./runDrizzle-it6rL9bR.mjs";import{i as fe,g as ue,D,r as M,a as q,b as S,A as g,c as j,e as z}from"./do-sql-Dk_DJxn4.mjs";import{param as de,WORKERD_SQLITE_LIMITS as $e}from"./param-Ib8WHnrF.mjs";import{encodeGeohash as me,GEO_DEFAULT_PRECISION as Ee}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as Q}from"./applySelect-BQbHyo-W.mjs";import{encodePartitionKey as pe,sortColumnName as he,rankTableName as Z,matchesRankStaticWhere as x}from"./RANK_TIEBREAK-ci3MaM65.mjs";import{m as ge}from"./sql-projection-BqmxFxQU.mjs";import{serializeSqlValue as ee}from"./serializeSqlValue-DbI1VQYM.mjs";const ye=["de","en","es","fr","it","nl","none","pt"],_e=n=>ye.includes(n),Se="a an and are as at be but by for if in into is it no not of on or such that the their then there these they this to was will with",we="aber als am an auch auf aus bei bin bis bist da dass der den des dem die das denn dir du ein eine für hat ich im in ist mit nicht noch nur oder sich sie sind über und von vor war wie wir zu zum zur",Te="a al como con de del el en es la las lo los mas no o para pero por que se su sus un una uno y ya",ve="au aux avec ce ces dans de des du elle en et eux il je la le les leur lui ma mais me même mes moi mon ne nos notre nous on ou par pas pour qu que qui sa se ses son sur ta te tes toi ton tu un une vos votre vous y",Re="a ai al alla anche che chi ci coi col come con da dal degli dei del della di do e ed gli ha hai hanno i il in la le lo ma mi ne nei nel non o per più quale quanto se si sono su sul tra un una uno vi",Ae="aan al als bij dan dat de der deze die dit door een en er het hij ij in is je kan me men met mij na naar niet nog nu of om ons ook op over te tot uit van voor was wat we wij zij zijn zo",be="a ao aos as até com como da das de do dos e em entre era essa esse esta este eu foi há isso já mais mas me mesmo meu na nas no nos num numa o os ou para pela pelo por qual que quem se sem seu só sua também te tem um uma você",Fe=/[\u0300-\u036F]/gu,oe=n=>n.normalize("NFD").replaceAll(Fe,"").normalize("NFC").toLowerCase(),k=n=>new Set(oe(n).split(" ")),Oe={de:k(we),en:k(Se),es:k(Te),fr:k(ve),it:k(Re),nl:k(Ae),none:new Set,pt:k(be)},Ie=2,Le=256,X=new Map,ke=n=>{const r=n!==void 0&&_e(n)?n:"none",c=X.get(r);if(c)return c;const w=Oe[r],y=i=>{const A=(oe(i).match(/[\p{L}\p{N}]+/gu)??[]).filter(T=>T.length<=Le);return w.size===0?A:A.filter(T=>!w.has(T))},E={document:y,profile:`${r}-v${String(Ie)}`,query:i=>{const A=y(i);return A.filter((T,F)=>A.lastIndexOf(T)===F)}};return X.set(r,E),E},qe=(n,r)=>{if(!r.includes("."))return n[r];let c=n;for(const w of r.split(".")){if(c===null||typeof c!="object"||Array.isArray(c))return;c=c[w]}return c},Ce=(n,r)=>`${n}__fts_${r}`,je="__text__",Y="__id__",De=1e3,Me=(n,r)=>r.document(n),U=(n,r)=>qe(n,r),ze=n=>typeof n=="string"?n:n==null?"":typeof n=="number"||typeof n=="bigint"||typeof n=="boolean"?String(n):JSON.stringify(n)??"",Ue=(n,r,c)=>n!==void 0&&r!==void 0&&U(n,c.field)===U(r,c.field),We=(n,r)=>Me(ze(U(n,r.field)),ke(r.language)).slice(0,De).join(" "),He=(n,r,c)=>[...n.partitionBy??[],...n.sortBy.map(y=>y.field),...n.where?Object.keys(n.where):[]].every(y=>r[y]===c[y]),ne=n=>e.join(["__id__","__partition__",...n.sortBy.map((r,c)=>he(c))].map(r=>e.identifier(r)),e`, `),te=(n,r,c,w,y,E)=>{const i=pe(c.partitionBy??[],E),A=c.sortBy.map(F=>ee(E[F.field]??null)),T=e.join([y,i,...A].map(F=>de(F)),e`, `);$(n,e`INSERT INTO ${e.identifier(r)} (${w}) VALUES (${T})`)},Be=(n,r,c,w,y,E)=>{if(y&&E&&He(c,y,E))return;const i=Z(r,c.name);y&&$(n,e`DELETE FROM ${e.identifier(i)} WHERE ${e.identifier("__id__")} = ${w}`),!(!E||c.where&&!x(E,c.where))&&te(n,i,c,ne(c),w,E)},oo=n=>{const{broadcast:r,indexKeysFor:c,invalidateCache:w,recordCdc:y,schema:E,sql:i}=n,A=new Set,T=t=>E.tables[t]?.softDeleteMode?.field,F=new Set,W=(t,o)=>{const a=`${t}::${o.name}`;if(A.has(a))return;const f=N(t,o.name),u=o.by??[],d=T(t),p=new Map,_=$(i,e`SELECT id, _creationTime, ${e.identifier(D)} FROM ${e.identifier(t)}`).toArray();for(const v of _){const m=M(v);if(!m||!Q(m,d)||o.where&&!P(m,o.where))continue;const R=L(u,m);J(p,R,o,m)}$(i,e`DELETE FROM ${e.identifier(f)}`);const b=Math.floor($e.boundParams/3),O=[...p];for(let v=0;v<O.length;v+=b){const m=O.slice(v,v+b),R=e.join(m.map(([s,l])=>e`(${s}, ${l.value}, ${l.count})`),e`, `);$(i,e`INSERT INTO ${e.identifier(f)} (${q}, ${S}, ${g}) VALUES ${R}`)}A.add(a)},se=(t,o,a)=>{const f=o.by??[],u=o.field??"",d=[],p=(s,l)=>{const h=ee(l);h===null?d.push(e`${z(s)} IS NULL`):d.push(e`${z(s)} = ${h}`)};for(const s of f)p(s,a[s]??null);const _=T(t);_!==void 0&&p(_,null);for(const[s,l]of Object.entries(o.where??{}))p(s,l!==null&&typeof l=="object"&&!Array.isArray(l)?l.eq:l);const b=d.length>0?e` WHERE ${e.join(d,e` AND `)}`:e``,O=E.tables[t]?.shape[u];if(O&&ge(O)){const s=$(i,e`SELECT id, _creationTime, ${e.identifier(D)} FROM ${e.identifier(t)}${b}`).toArray(),l=new Map;for(const h of s){const I=M(h);I&&J(l,"",o,I)}return{value:l.get("")?.value??null}}const v=le(o.op),m=z(u);return{value:$(i,e`SELECT ${e.raw(v)}(${m}) AS value FROM ${e.identifier(t)}${b}`).one().value??null}},ie=(t,o,a,f)=>{const u=N(t,o.name),{op:d}=o,p=o.field??"",_=s=>{$(i,e`DELETE FROM ${e.identifier(u)} WHERE ${q} = ${s} AND ${g} <= 0`)},b=T(t),O=s=>!o.where||P(s,o.where),v=s=>Q(s,b)&&O(s);f!==void 0&&d!=="count"&&O(f)&&C(f[p]);const m=a&&v(a)?a:void 0,R=f&&v(f)?f:void 0;if(!(!m&&!R)){if(d==="count"){for(const[s,l]of[[m,-1],[R,1]]){if(!s)continue;const h=L(o.by??[],s);$(i,j(u,h,l,l,e`${S} = ${S} + excluded.${S}, ${g} = ${g} + excluded.${g}`))}m&&_(L(o.by??[],m));return}if(d==="sum"||d==="avg"){for(const[s,l]of[[m,-1],[R,1]]){if(!s)continue;const h=C(s[p]);if(h===void 0)continue;const I=L(o.by??[],s);$(i,j(u,I,l*h,l,e`${S} = COALESCE(${S}, 0) + excluded.${S}, ${g} = ${g} + excluded.${g}`))}m&&_(L(o.by??[],m));return}if(m){const s=L(o.by??[],m),l=C(m[p]),h=$(i,e`SELECT ${S} AS value, ${g} AS count FROM ${e.identifier(u)} WHERE ${q} = ${s}`).toArray()[0],I=(h?.count??0)-1;if(I<=0)$(i,e`DELETE FROM ${e.identifier(u)} WHERE ${q} = ${s}`);else if(h&&l!==void 0&&h.value!==null&&l===h.value){const ce=se(t,o,m);$(i,e`UPDATE ${e.identifier(u)} SET ${S} = ${ce.value}, ${g} = ${I} WHERE ${q} = ${s}`)}else $(i,e`UPDATE ${e.identifier(u)} SET ${g} = ${g} - 1 WHERE ${q} = ${s}`)}if(R){const s=L(o.by??[],R),l=C(R[p]);if(l===void 0)$(i,j(u,s,null,1,e`${g} = ${g} + 1`));else{const h=d==="min"?"MIN":"MAX";$(i,j(u,s,l,1,e`${S} = ${e.raw(h)}(COALESCE(${S}, excluded.${S}), excluded.${S}), ${g} = ${g} + 1`))}}}},re=t=>{for(const o of E.tables[t]?.aggregateIndexes??[])W(t,o)},H=(t,o,a)=>{for(const f of E.tables[t]?.aggregateIndexes??[])ie(t,f,o,a)},B=(t,o)=>{const a=`${t}::rank::${o.name}`;if(F.has(a))return;const f=Z(t,o.name),u=$(i,e`SELECT id, _creationTime, ${e.identifier(D)} FROM ${e.identifier(t)}`).toArray();$(i,e`DELETE FROM ${e.identifier(f)}`);const d=ne(o);for(const p of u){const _=M(p);!_||o.where&&!x(_,o.where)||te(i,f,o,d,_._id,_)}F.add(a)},ae=t=>{for(const o of E.tables[t]?.rankIndexes??[])B(t,o)},K=(t,o,a,f)=>{for(const u of E.tables[t]?.rankIndexes??[])Be(i,t,u,o,a,f)},V=(t,o,a,f)=>{const u=E.tables[t]?.searchIndexes??[];if(!(u.length===0||!fe(i)))for(const d of u){if(Ue(f,a,d))continue;const p=Ce(t,d.name);$(i,e`DELETE FROM ${e.identifier(p)} WHERE ${e.identifier(Y)} = ${o}`),a&&$(i,e`INSERT INTO ${e.identifier(p)} (${e.identifier(je)}, ${e.identifier(Y)}) VALUES (${We(a,d)}, ${o})`)}},G=(t,o,a)=>{for(const f of E.tables[t]?.geoIndexes??[]){const u=ue(t,f.name);$(i,e`DELETE FROM ${e.identifier(u)} WHERE ${e.identifier("__id__")} = ${o}`);const d=a?.[f.field];if(d!==null&&typeof d=="object"&&typeof d.lat=="number"&&typeof d.lng=="number"){const{lat:p,lng:_}=d,b=me({lat:p,lng:_},f.precision??Ee);$(i,e`INSERT INTO ${e.identifier(u)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${o}, ${b}, ${p}, ${_})`)}}};return{ensureBackfilledForTable:re,ensureBackfilledIndex:W,ensureRankBackfilled:B,ensureRankBackfilledForTable:ae,syncAggregates:H,syncCompanionsForInsert:(t,o,a)=>{V(t,o,a),G(t,o,a),H(t,void 0,a),K(t,o,void 0,a),w(t,o,a),y(t,o,"insert",a),r({indexKeys:c(t,a),key:o,op:"insert",row:a,table:t})},syncGeo:G,syncRanks:K,syncSearch:V}};export{je as S,Ce as a,oo as c,We as h,te as i,ke as j,ne as r,Me as s,Y as y};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createShardCtxDb as S}from"./NotUniqueError-BixDiv4O.mjs";import{createRelayLink as B}from"./DEFAULT_MAX_RELAYS-DeVcEXBh.mjs";import{ConflictError as I}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as v}from"./runShardMigrations-Crppyq1f.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-DVTD9iu0.mjs";const _=(E,u={})=>({_meta:{column:{notNull:!0,...u}},kind:E}),D=(E,u,N)=>{const{describe:k,expect:i,it:m}=N;k(`engine contract: ${E}`,()=>{k("optimistic concurrency",()=>{const b=h=>({tables:{items:{indexes:[],shape:{title:_("string"),version:_("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{h.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});m("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await i(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(I)}finally{h?.()}}),m("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;i(e.code).toBe("CONFLICT"),i(e.kind).toBe("occ")}finally{h?.()}}),m("leaves the row readable and unchanged after a conflict",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const a=await s.get("i1");i(a?.title).toBe("first"),i(a?.version).toBe(99)}finally{h?.()}}),m("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l={tables:{items:{indexes:[],shape:{title:_("string"),version:_("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch(o.doc._id,{version:99})},op:"update",timing:"before"}}}}};v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;i(e).toBeInstanceOf(I),i(e.code).toBe("CONFLICT"),i(e.kind).toBe("trigger")}finally{h?.()}})}),k("shape-poke ordering",()=>{const b="shard-a",h={args:{},name:"messages"},d=(e,t,o,n)=>e.accept(t?.()??{},{connectionId:o,shapes:{[n]:h}}),c=(e,t)=>{let o=0,n=0;const r=g=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${g}`)},p={fetch:(g,O)=>{if(JSON.parse(O?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const C=t[n];if(n+=1,C===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(C))}},y={get:()=>p,getByName:()=>p,idFromName:g=>g},w={buildShapeDiff:r("buildShapeDiff"),computeOpLogShapeSeed:r("computeOpLogShapeSeed"),currentCdcEpoch:r("currentCdcEpoch"),deliverWhisperLocal:r("deliverWhisperLocal"),doName:()=>F(b,0),env:()=>({SHARD:y}),getWebSockets:()=>e.getSockets(),maskMetadata:r("maskMetadata"),nextPokeId:()=>(o+=1,`poke-${String(o)}`),readAttachment:g=>g.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:r("resolveShape"),rlsMetadata:r("rlsMetadata"),shardBinding:()=>"SHARD",sql:r("sql")},f=B(w);if(f===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return f},l=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,o)=>{const n=await e.seedRelayShape(t,o,h,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},a=(e={})=>l({...h,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});m("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1");await s(r,p,"s1"),await r.handleControl(a());const w=(await o(p)).map(f=>JSON.parse(f));i(w.map(f=>f.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),i(new Set(w.map(f=>f.pokeId)).size).toBe(1),i(w[1]?.shapeId).toBe("s1"),i(w[2]?.checkpoint).toBe(20)}finally{e?.()}}),m("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1"),y=d(n,t,"c-bob","s2");await s(r,p,"s1"),await s(r,y,"s2"),await r.handleControl(a());const w=await o(p);i(w.length).toBe(3);const f=await o(y);i(f.length).toBe(0),await r.handleControl(a());const g=await o(p);i(g.length).toBe(3)}finally{e?.()}}),m("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1");await s(r,p,"s1"),await r.handleControl(a({epoch:"e2"}));const y=await o(p);i(y.length).toBe(0),await r.handleControl(a());const w=await o(p);i(w.length).toBe(3)}finally{e?.()}})}),k("RLS identity under live subscription",()=>{const b="shard-a",h={args:{},name:"lobby-messages"},d={args:{},name:"my-orders"},c=s=>{const a=[],e=[],t={fetch:(r,p)=>(a.push(JSON.parse(p?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=B({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>b,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:r=>r}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(r,p,y)=>(e.push(y),r===d.name?{columns:["id"],effectiveWhere:{org:y?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:a,resolvedUnder:e}},l=async(s,a)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...a,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};m("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:a}=u();try{const{owner:e,resolvedUnder:t}=c(a.sql);await l(e,d),i(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),m("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:a}=u();try{const{owner:e,posts:t}=c(a.sql);await l(e,d),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),m("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:a}=u();try{const{owner:e,posts:t}=c(a.sql);await l(e,h),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{D as defineEngineContractSuite};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{stableStringify as u}from"./stableStringify-CujpENIO.mjs";const l=(t,s)=>{const o={_id:t._id};if(s){for(const e of s)Object.hasOwn(t,e)&&(o[e]=t[e]);return o}for(const[e,n]of Object.entries(t))e!=="_id"&&e!=="_creationTime"&&(o[e]=n);return o},j=(t,s,o)=>{const{columns:e,table:n}=o,c=[],d=new Map;for(const r of t){const i=l(r,e),f=String(i._id),a=u(i);d.set(f,a);const p=s.get(f);p===void 0?c.push({doc:i,id:f,op:"insert",seq:0,table:n,ts:0}):p!==a&&c.push({doc:i,id:f,op:"update",seq:0,table:n,ts:0})}for(const r of s.keys())d.has(r)||c.push({id:r,op:"delete",seq:0,table:n,ts:0});return{changes:c,nextBaseline:d}};export{j as diffExternalSource,l as projectExternalSourceRow};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as c}from"@lunora/errors";import{sql as n}from"drizzle-orm";import{quoteIdentifier as m}from"./quoteIdentifier-CObIFRhb.mjs";import{d as T,e as $}from"./wire-codec-BU9T2xJ7.mjs";import{runDrizzle as l}from"./runDrizzle-it6rL9bR.mjs";import{s as A}from"./sql-projection-BqmxFxQU.mjs";import"./serializeSqlValue-DbI1VQYM.mjs";const E=/^[A-Za-z_$][\w$]*$/u,p=e=>E.test(e)?e:`"${e.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,d="__doc__",i="__originals__",C=e=>{if(Object.hasOwn(e,i))throw new c("BAD_REQUEST",`"${i}" is reserved by the row store's document encoding and cannot be used as a field name — rename the field`);let t,o;for(const[r,s]of Object.entries(e)){const a=A(s);a!==void 0&&(t??={...e},o??=Object.create(null),t[r]=a,o[r]=s)}t&&o&&(t[i]=o);try{return JSON.stringify($(t??e))}catch(r){throw new c("BAD_REQUEST",`this document cannot be stored: ${r instanceof Error?r.message:String(r)}`)}},S=e=>{const t=T(JSON.parse(e)),{[i]:o,...r}=t;return o===null||typeof o!="object"||Array.isArray(o)?t:{...r,...o}},L=(e,t)=>`${e}__geo_${t}`,u=(e,t)=>t==="_id"||t==="id"?`${e}id`:t==="_creationTime"?`${e}_creationTime`:`json_extract(${e}${d}, '$.${p(t).replaceAll("'","''")}')`,h=e=>u("",e),P=e=>n.raw(h(e)),O=(e,t)=>u(`${m(e)}.`,t),R=(e,t)=>n.raw(O(e,t)),G=(e,t,o,r)=>n`CREATE ${r?n`UNIQUE `:n``}INDEX IF NOT EXISTS ${n.identifier(e)} ON ${n.identifier(t)} (${o})`,_=n.identifier("__key__"),b=n.identifier("__value__"),g=n.identifier("__count__"),q=(e,t,o,r,s)=>n`INSERT INTO ${n.identifier(e)} (${_}, ${b}, ${g}) VALUES (${t}, ${o}, ${r}) ON CONFLICT(${_}) DO UPDATE SET ${s}`,J=e=>{const t=[];for(const[o,r]of Object.entries(e.shape)){const s=r._meta?.column;s&&t.push([o,s])}return t},y=e=>{if(!e)return;const t=e[d];let o;typeof t=="string"?o=S(t):t&&typeof t=="object"?o=t:o={};const{id:r}=e;typeof r=="string"&&(o._id=r);const s=e._creationTime;return typeof s=="number"&&(o._creationTime=s),o},B=e=>{try{return y(e)}catch{return}},f=new WeakMap,F=e=>{const t=f.get(e);if(t!==void 0)return t;let o;try{l(e,n`CREATE VIRTUAL TABLE IF NOT EXISTS ${n.identifier("__lunora_fts_probe")} USING fts5(x)`),o=!0}catch{o=!1}finally{try{l(e,n`DROP TABLE IF EXISTS ${n.identifier("__lunora_fts_probe")}`)}catch{}}return f.set(e,o),o};export{g as A,d as D,_ as a,b,q as c,G as d,P as e,R as f,L as g,B as h,F as i,h as j,C as k,S as l,p as m,i as n,O as q,y as r,J as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{B as s}from"./sql-projection-BqmxFxQU.mjs";const n=40,f=i=>{let e=0;const o=(r,t)=>typeof t=="bigint"?(e+=s+1+n,t.toString()):t instanceof ArrayBuffer||ArrayBuffer.isView(t)?(e+=2*Math.ceil(t.byteLength/3)*4+n,""):t;try{const r=JSON.stringify(i,o);return(r===void 0?0:r.length)+e}catch{return}};export{f as e};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{toErrorBody as f}from"@lunora/errors";const l=200,b=(r,n)=>{const i=e=>{const o=r.tables[e];return o!==void 0&&o.shardMode?.kind!=="global"};return(n&&n.length>0?[...n]:Object.keys(r.tables)).filter(e=>i(e))},p=async function*(r,n,i=l){let e=null,o=!1;for(;!o;){const t=await r.findMany(n,{cursor:e,limit:i});for(const s of t.page)yield{doc:s,table:n};e=t.continueCursor,o=t.isDone||e===null}},A=async function*(r,n,i){const e=b(n,i.tables),o=i.batchSize??l;for(const t of e)yield*p(r,t,o)},u=new Set(["_creationTime","_id"]),y=(r,n)=>{for(const[i,e]of Object.entries(r.shape)){const o=n[i];if(o===void 0&&e.kind==="optional")continue;const t=e.parse;if(typeof t=="function")try{t(o)}catch(s){const c=s instanceof Error?s.message:String(s);return`field "${i}": ${c}`}}},h=(r,n,i)=>{const e=r.tables[n];if(!e)return`unknown table: ${n}`;if(e.shardMode?.kind==="global")return`table "${n}" is a global (.global()) table and is not importable through the shard import path`;const o=Object.fromEntries(Object.entries(i).filter(([t])=>!u.has(t)));for(const t of Object.keys(o))if(!(t in e.shape))return`unexpected field "${t}": not declared in table "${n}"`;return y(e,o)},m=async(r,n)=>{try{return await r.get(n)!==null}catch{return!1}},g=async(r,n,i,e)=>{const{doc:o,table:t}=i;if(typeof t!="string"||t.length===0)return{error:{code:"BAD_ROW",line:e,message:"row is missing `table`",table:t},kind:"error"};if(!o||typeof o!="object"||Array.isArray(o))return{error:{code:"BAD_ROW",line:e,message:"row is missing or malformed `doc`",table:t},kind:"error"};const s=h(n,t,o);if(s!==void 0)return{error:{code:"VALIDATION_ERROR",line:e,message:s,table:t},kind:"error"};const c=typeof o._id=="string"?o._id:void 0;if(c!==void 0&&await m(r,c))return{kind:"conflict"};try{return await r.insert(t,o,{allowExplicitId:!0}),{kind:"inserted",table:t}}catch(a){const{body:d}=f(a,{fallbackCode:"INSERT_FAILED"});return{error:{code:d.code,line:e,message:d.message,table:t},kind:"error"}}},S=async(r,n,i)=>{const e=[],o={};let t=0,s=(i.startLine??1)-1;for(const c of i.rows){s+=1;const a=await g(r,n,c,s);a.kind==="error"?e.push(a.error):a.kind==="conflict"?t+=1:o[a.table]=(o[a.table]??0)+1}return{conflicts:t,errors:e,inserted:o}},k=r=>{const n=Array.isArray(r.tables)?r.tables.filter(e=>typeof e=="string"):void 0;return{batchSize:typeof r.batchSize=="number"?r.batchSize:void 0,tables:n}},E=r=>{const n=Array.isArray(r.rows)?r.rows:[],i=[];for(const o of n){if(!o||typeof o!="object")continue;const t=o;if(typeof t.table!="string"||!t.doc||typeof t.doc!="object"||Array.isArray(t.doc)){i.push({doc:t.doc??{},table:typeof t.table=="string"?t.table:""});continue}i.push({doc:t.doc,table:t.table})}const e=typeof r.startLine=="number"?r.startLine:void 0;return{rows:i,startLine:e}};export{A as exportShardRows,p as exportShardTable,S as importShardRows,k as parseExportShardArgs,E as parseImportShardArgs,b as selectExportTables,h as validateImportRow};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const n=async e=>{const r=e.schema.tables[e.tableName]?.triggerMap;if(r)for(const t of Object.values(r))t.timing===e.timing&&t.op===e.op&&await t.handler(e.ctx,e.event)},s=(e,r,t)=>{const i=e.tables[r]?.triggerMap;return i?Object.values(i).some(a=>a.op===t):!1};export{s as hasTrigger,n as runTriggers};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-it6rL9bR.mjs";import{liftSourceId as A}from"./liftSourceId-CA3ENhXj.mjs";import{normalizeSourceValue as W}from"./liftSourceId-CA3ENhXj.mjs";import{runExternalSourceTick as C,materializeExternalRowsIncremental as D}from"./materializeExternalRows-Drn0FGdb.mjs";const p="__lunora_source_cursor",M=e=>e instanceof Date?`d:${e.toISOString()}`:typeof e=="bigint"?`b:${e.toString()}`:typeof e=="number"?`n:${e.toString()}`:`s:${e}`,v=e=>{const t=e.slice(2);switch(e[0]){case"b":return BigInt(t);case"d":return new Date(t);case"n":return Number(t);default:return t}},h=/^-?\d+$/,N=/^-?\d+(?:\.\d+)?$/,x=(e,t)=>e instanceof Date&&t instanceof Date?e.getTime()>t.getTime():typeof e=="bigint"&&typeof t=="bigint"||typeof e=="number"&&typeof t=="number"?e>t:typeof e=="string"&&typeof t=="string"&&N.test(e)&&N.test(t)?h.test(e)&&h.test(t)?BigInt(e)>BigInt(t):Number(e)>Number(t):String(e)>String(t),O=(e,t,o)=>{let n=o===null?void 0:v(o);for(const r of e){const c=r[t];if(c==null)continue;const a=c;(n===void 0||x(a,n))&&(n=a)}return n===void 0?null:M(n)},B=e=>{S(e,m`CREATE TABLE IF NOT EXISTS ${m.identifier(p)} (
|
|
2
|
+
table_name TEXT NOT NULL,
|
|
3
|
+
shard_key TEXT NOT NULL,
|
|
4
|
+
watermark TEXT,
|
|
5
|
+
last_reconcile_ms INTEGER,
|
|
6
|
+
PRIMARY KEY (table_name, shard_key)
|
|
7
|
+
)`)},b=(e,t,o)=>{const r=S(e,m`SELECT watermark, last_reconcile_ms FROM ${m.identifier(p)} WHERE table_name = ${t} AND shard_key = ${o} LIMIT 1`).toArray()[0];return{lastReconcileMs:r?.last_reconcile_ms??null,watermark:r?.watermark??null}},q=(e,t,o,n)=>{S(e,m`INSERT INTO ${m.identifier(p)} (table_name, shard_key, watermark, last_reconcile_ms)
|
|
8
|
+
VALUES (${t}, ${o}, ${n.watermark}, ${n.lastReconcileMs})
|
|
9
|
+
ON CONFLICT(table_name, shard_key) DO UPDATE SET watermark = excluded.watermark, last_reconcile_ms = excluded.last_reconcile_ms`)},F=(e,t,o)=>e==="manual"?!1:e===void 0||t===void 0?!0:o-t>=e.everyMs,_=async(e,t,o,n)=>{const r=await e.query(t,o);return{documents:r.map(a=>A(a,{idColumn:n.idColumn,map:n.map})),rows:r}},P=async(e,t,o,n,r,c)=>{const a=r.tenantBy?r.tenantBy(c):[],{documents:i}=await _(o,r.query,a,r);return C(e,t,i,{columns:r.columns,table:n})},$=(e,t)=>{const o=e[t];return o!=null&&o!==!1&&o!==0},V=async(e,t,o,n,r,c,a)=>{const{cursor:i}=r;if(!i)throw new T("INTERNAL",`external-source: table "${n}" is mode "incremental" but has no \`cursor\` — this should have been rejected at defineSchema`);B(e);const u=b(e,n,c),g=r.tenantBy?r.tenantBy(c):[],k=r.reconcileEveryMs!==void 0&&(u.lastReconcileMs===null||a-u.lastReconcileMs>=r.reconcileEveryMs),f=u.watermark===null||k;let s,w;if(u.watermark===null||k){s=await _(o,r.query,g,r);const{softDeleteColumn:l}=r,y=l?s.documents.filter((R,E)=>{const d=s.rows[E];return!(d&&$(d,l))}):s.documents;({applied:w}=await C(e,t,y,{columns:r.columns,table:n}))}else{s=await _(o,i.query,[...g,v(u.watermark)],r);const{softDeleteColumn:l}=r,y=l?new Set(s.documents.flatMap((R,E)=>{const d=s.rows[E];return d&&$(d,l)?[String(R._id)]:[]})):void 0;({applied:w}=await D(t,s.documents,{columns:r.columns,deletedIds:y,table:n}))}const I=O(s.rows,i.column,u.watermark);if(f&&I===null&&s.rows.length>0)throw new T("INTERNAL",`external-source: table "${n}" (mode "incremental") pulled ${String(s.rows.length)} rows but none carry the cursor column "${i.column}" — the seed \`query\` must project it (matching \`cursor.query\`'s alias), or the watermark can never advance.`);const L=s.rows.length>0&&s.rows.every(l=>l[i.column]===null||l[i.column]===void 0);if(!f&&L)throw new T("INTERNAL",`external-source: table "${n}" (mode "incremental") pulled ${String(s.rows.length)} rows but none carry the cursor column "${i.column}" — \`cursor.query\` must project it (matching the seed \`query\`'s alias), or the watermark can never advance and every tick re-pulls the same stranded slice.`);return q(e,n,c,{lastReconcileMs:f?a:u.lastReconcileMs,watermark:I}),{applied:w}};export{$ as isSoftDeleted,F as isSourceDue,A as liftSourceId,W as normalizeSourceValue,V as pullExternalSourceIncrementalTick,P as pullExternalSourceTick};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as p}from"@lunora/errors";const u=r=>r instanceof Date?r.toISOString():typeof r=="bigint"?String(r):Array.isArray(r)?r.map(t=>u(t)):r!==null&&typeof r=="object"&&Object.getPrototypeOf(r)===Object.prototype?i(r):r,i=r=>{const t={};for(const[o,e]of Object.entries(r))t[o]=u(e);return t},d=(r,t={})=>{const{idColumn:o="id",map:e}=t,n=r[o];if(n==null)throw new p("INTERNAL",`external-source: row is missing id column "${o}"`);if(typeof n!="string"&&typeof n!="number"&&typeof n!="bigint")throw new TypeError(`external-source: id column "${o}" must be a string or number`);const c=String(n);if(e)return i({...e(r),_id:c});const s={};for(const[f,m]of Object.entries(r))f!==o&&(s[f]=m);return i({...s,_id:c})};export{d as liftSourceId,i as normalizeSourceDocument,u as normalizeSourceValue};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{applyCdcChanges as p}from"./CDC_LOG_TABLE-B58N8NQO.mjs";import{selectShapeRows as m}from"./selectShapeMemberIds-B-pQJHAu.mjs";import{diffExternalSource as g,projectExternalSourceRow as l}from"./diffExternalSource-pozJ4UdZ.mjs";import{stableStringify as d}from"./stableStringify-CujpENIO.mjs";const x=async(t,s,a,e)=>{const{changes:o,nextBaseline:n}=g(s,a,e);return await p(t,o),{applied:o.length,nextBaseline:n}},R=async(t,s,a)=>{const{columns:e,deletedIds:o,table:n}=a,r=[];for(const f of s){const i=l(f,e),c=String(i._id);if(o?.has(c)){await t.get(c,n)&&r.push({id:c,op:"delete",seq:0,table:n,ts:0});continue}const u=await t.get(c,n);u&&d(l({...u,_id:c},e))===d(i)||r.push({doc:i,id:c,op:"insert",seq:0,table:n,ts:0})}return await p(t,r),{applied:r.length}},h=(t,s,a)=>{const e=new Map;for(const{doc:o,id:n}of m(t,s,void 0))e.set(n,d(l({...o,_id:n},a)));return e},_=async(t,s,a,e)=>{const o=h(t,e.table,e.columns);return x(s,a,o,e)};export{x as materializeExternalRows,R as materializeExternalRowsIncremental,h as readExternalSourceBaseline,_ as runExternalSourceTick};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{keysTouchRanges as i}from"./buildIndexRange-CBKQmHSS.mjs";const f=(o,r,n)=>{const e=o??new Map;for(const t of n){const s=r?.get(t),u=e.get(t),c=e.has(t)&&u===void 0;if(!r?.has(t)||s===void 0||c){e.set(t,void 0);continue}e.set(t,u?[...u,...s]:s)}return e},a=(o,r,n)=>{const e=o??new Map;if(e.has(r)&&e.get(r)===void 0)return e;if(!n||n.length===0)return e.set(r,void 0),e;const t=e.get(r);return e.set(r,t?[...t,...n]:[...n]),e},h=(o,r,n)=>{if(!n)return!0;for(const e of r){if(!o.tables.has(e))continue;const t=o.ranges?.get(e);if(!t||t.length===0||i(t,n.get(e)))return!0}return!1};export{f as mergeChangedKeys,a as recordChangedKeys,h as writeTouchesMemo};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as c}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{MySqlDialect as S}from"drizzle-orm/mysql-core";import{PgDialect as p}from"drizzle-orm/pg-core";import{SQLiteSyncDialect as u}from"drizzle-orm/sqlite-core";const f=new p,m=new S,L=new u,d={mysql:m,postgres:f,sqlite:L},l={boundParams:100,compoundSelect:5,likePattern:50,sqlTextLength:1e5},h=l.boundParams/2,E=e=>e===null||typeof e=="boolean"?!0:typeof e=="number"?Number.isFinite(e):typeof e=="string"&&e.isWellFormed(),D=(e,n)=>{const{params:r,sql:o}=d[e].sqlToQuery(n);return{params:r,sql:o}},I=e=>t`${e}`,N=e=>{if(e.length===0)throw new Error("unionAll: expected at least one branch");let n=[...e];for(;n.length>l.compoundSelect;){const r=[];for(let o=0;o<n.length;o+=l.compoundSelect){const s=t.join(n.slice(o,o+l.compoundSelect),t` UNION ALL `);r.push(t`SELECT * FROM (${s}) ${t.identifier("__u__")}`)}n=r}return t.join(n,t` UNION ALL `)},w=(e,n,r,o=h)=>{const s=r?t` NOT IN `:t` IN `,a=n.every(i=>E(i));if(n.length>o&&!a)throw new c("BAD_REQUEST",`an "in" list of ${String(n.length)} values holds a value JSON cannot carry (bytes, a non-finite number, or malformed text), so it cannot be bound as one parameter — and ${String(n.length)} placeholders exceed SQLite's per-statement cap of 100 on Durable Objects and D1. Narrow the list to ${String(o)} values or fewer.`);return n.length<=o?t`${e}${s}(${t.join(n.map(i=>I(i)),t`, `)})`:t`${e}${s}(SELECT ${t.identifier("value")} FROM json_each(${JSON.stringify(n)}))`};export{l as WORKERD_SQLITE_LIMITS,I as param,D as renderSql,w as sqliteInList,N as unionAll};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as s}from"@lunora/errors";import{renderSql as l,WORKERD_SQLITE_LIMITS as r}from"./param-Ib8WHnrF.mjs";const c=(t,n,...e)=>{if(n.length*3>r.sqlTextLength){const i=new TextEncoder().encode(n).length;if(i>r.sqlTextLength)throw new s("INTERNAL",`SQL statement is ${String(i)} bytes, over this runtime's ${String(r.sqlTextLength)}-byte limit`)}if(e.length>r.boundParams)throw new s("INTERNAL",`SQL statement binds ${String(e.length)} parameters, over this runtime's limit of ${String(r.boundParams)}`);return t.exec.call(t,n,...e)},h=(t,n)=>{const{params:e,sql:o}=l("sqlite",n);return c(t,o,...e)},d=t=>t??null,g=t=>{if(!(t==null||t===""))try{return JSON.parse(t)}catch{return}};export{g as decodeJsonColumn,d as orNull,h as runDrizzle,c as runSql};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{a as L,S,y as N}from"./ctx-db-companions-lTt-rvKG.mjs";import{sql as e}from"drizzle-orm";import{aggregateTableName as u}from"./aggregateTableName-Cy5e03oz.mjs";import{backfillSearchIndexesForTable as h}from"./backfillAggregateIndexes-DVQ2sVuV.mjs";import{migrateCdcLog as p,migrateCdcMeta as x}from"./CDC_LOG_TABLE-B58N8NQO.mjs";import{migrateClientWatermark as R}from"./CLIENT_WATERMARK_TABLE-BoS1HEqz.mjs";import{migrateGlobalShapeSnapshot as C}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-NWaL77m5.mjs";import{migrateIdempotency as O}from"./IDEMPOTENCY_TABLE-DKVe2Ohf.mjs";import{migrateSearchState as U}from"./SEARCH_STATE_TABLE-Dju8ebbU.mjs";import{migrateShapePokeCursor as $}from"./SHAPE_POKE_CURSOR_TABLE-Dh4HfSdC.mjs";import{runDrizzle as a}from"./runDrizzle-it6rL9bR.mjs";import{D as b,e as T,d,t as l,i as X,g as G,a as D,b as B,A as E}from"./do-sql-Dk_DJxn4.mjs";import{migrateDurableStreams as k}from"./appendStreamChunk-CH4e4nJn.mjs";import{rankTableName as F,sortColumnName as M}from"./RANK_TIEBREAK-ci3MaM65.mjs";import{recordSchemaVersion as Y}from"./SCHEMA_HISTORY_MAX_VERSIONS-DsycDXWm.mjs";const P=(r,o,t)=>{for(const i of t.indexes){const n=`${o}_${i.name}`,s=e.join(i.fields.map(m=>T(m)),e`, `);a(r,d(n,o,s,i.unique??!1))}for(const[i,n]of l(t)){if(!n.unique)continue;const s=`${o}_unique_${i}`;a(r,d(s,o,T(i),!0))}},j=(r,o,t)=>{if(!(!t.searchIndexes||t.searchIndexes.length===0||!X(r))){for(const i of t.searchIndexes){const n=L(o,i.name);a(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(n)} USING fts5(${e.identifier(S)}, ${e.identifier(N)} UNINDEXED)`),a(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${n}__vocab`)} USING fts5vocab(${e.identifier(n)}, ${e.raw("instance")})`)}h(r,o,t)}},y=(r,o,t)=>{if(t.geoIndexes)for(const i of t.geoIndexes){const n=G(o,i.name);a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__geohash__")} TEXT NOT NULL, ${e.identifier("__lat__")} REAL NOT NULL, ${e.identifier("__lng__")} REAL NOT NULL)`);const s=`${o}__geo_${i.name}__btree`;a(r,d(s,n,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},K=(r,o,t)=>{if(t.aggregateIndexes)for(const i of t.aggregateIndexes){const n=u(o,i.name);a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${D} TEXT PRIMARY KEY, ${B} REAL, ${E} INTEGER NOT NULL DEFAULT 0)`),a(r,e`PRAGMA table_info(${e.identifier(n)})`).toArray().some(m=>m.name==="__count__")||a(r,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${E} INTEGER NOT NULL DEFAULT 0`)}},v=(r,o,t)=>{if(t.rankIndexes)for(const i of t.rankIndexes){const n=F(o,i.name),s=i.sortBy.map((f,c)=>M(c)),m=s.map(f=>e`${e.identifier(f)} BLOB`),A=m.length>0?e`, ${e.join(m,e`, `)}`:e``;a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${A})`);const _=[e`${e.identifier("__partition__")} ASC`];for(const[f,c]of s.entries()){const I=i.sortBy[f]?.direction;_.push(e`${e.identifier(c)} ${e.raw(I==="desc"?"DESC":"ASC")}`)}_.push(e`${e.identifier("__id__")} ASC`);const g=`${o}__rank_${i.name}__btree`;a(r,d(g,n,e.join(_,e`, `),!1))}},ae=(r,o,t={})=>{t.schemaSnapshot!==void 0&&Y(r,t.schemaSnapshot.hash,t.schemaSnapshot.json),U(r);for(const[i,n]of Object.entries(o.tables))n.shardMode?.kind!=="global"&&(a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(i)} (
|
|
2
|
+
id TEXT PRIMARY KEY,
|
|
3
|
+
_creationTime REAL NOT NULL,
|
|
4
|
+
${e.identifier(b)} TEXT NOT NULL
|
|
5
|
+
)`),P(r,i,n),j(r,i,n),y(r,i,n),K(r,i,n),v(r,i,n));t.cdc&&(p(r),x(r),R(r),$(r)),O(r),C(r),k(r)};export{ae as runShardMigrations};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const l=async(o,a,c=8)=>{let t=0;const e=async()=>{let r=o[t];for(t+=1;r!==void 0;){try{await a(r)}catch{}r=o[t],t+=1}};await Promise.all(Array.from({length:Math.min(c,o.length)},()=>e()))};export{l as runSocketPool};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{sql as o}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-it6rL9bR.mjs";import{e}from"./do-sql-Dk_DJxn4.mjs";const E=(s,t,f,r)=>{const d=f-(t.after??0),i=[o`${e(t.field)} IS NOT NULL`,o`${e(t.field)} < ${d}`];t.softDeleteField!==void 0&&i.push(o`${e(t.softDeleteField)} IS NULL`);const l=o`SELECT id FROM ${o.identifier(t.table)} WHERE ${o.join(i,o` AND `)} LIMIT ${o.raw(String(Math.max(0,Math.floor(r))+1))}`,n=h(s,l).toArray(),a=n.length>r,$=n.slice(0,r).map(c=>c.id);return{hasMore:a,ids:$}};export{E as selectExpiredIds};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-it6rL9bR.mjs";import{D as p,r as u,e as d}from"./do-sql-Dk_DJxn4.mjs";import{sqliteInList as h}from"./param-Ib8WHnrF.mjs";import{compileWhereSql as S}from"./compileWhereSql-JBpSfQm9.mjs";import{serializeSqlValue as w}from"./serializeSqlValue-DbI1VQYM.mjs";const C={fieldRef:d,serialize:w},$=r=>{if(r.length!==0)return h(e`${e.identifier("id")}`,r,!1)},m=(r,i)=>{const o=[];i&&o.push(i);const t=S(r,C);return t&&o.push(t),o.length===0?e``:e` WHERE ${e.join(o,e` AND `)}`},L=(r,i,o)=>{const t=m(o,void 0),c=a(r,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${t}`).toArray(),n=[];for(const s of c){const f=u(s),{id:l}=s;f!==void 0&&typeof l=="string"&&n.push({doc:f,id:l})}return n},M=(r,i,o,t)=>{if(t.length===0)return new Set;const c=m(o,$(t)),n=a(r,e`SELECT id FROM ${e.identifier(i)}${c}`).toArray();return new Set(n.map(s=>s.id))};export{M as selectShapeMemberIds,L as selectShapeRows};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{s as o}from"./sql-projection-BqmxFxQU.mjs";const n=r=>typeof r=="boolean"?r?1:0:r===null||typeof r=="string"||typeof r=="number"?r:o(r)??JSON.stringify(r);export{n as serializeSqlValue};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const a=/^\d+$/,d=(n,t,r)=>{const e=n?.[t];let o=Number.NaN;return typeof e=="string"&&a.test(e.trim())?o=Number(e.trim()):typeof e=="number"&&(o=e),Number.isSafeInteger(o)&&o>0?o:r},c=(n,t)=>{const r=Math.max(n.length,t.length);let e=n.length^t.length;for(let o=0;o<r;o+=1){const s=o<n.length?n.charCodeAt(o):0,i=o<t.length?t.charCodeAt(o):0;e|=s^i}return e===0},u="LUNORA_RELAY_SECRET",y="x-lunora-relay-sig",f=n=>{const t=n?.[u];return typeof t=="string"&&t.length>0?t:void 0},l=async(n,t)=>{const r=new TextEncoder,e=await crypto.subtle.importKey("raw",r.encode(n),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),o=await crypto.subtle.sign("HMAC",e,r.encode(t));return[...new Uint8Array(o)].map(s=>s.toString(16).padStart(2,"0")).join("")},m=async(n,t,r)=>{const e=f(n);return e===void 0?!0:t===null?!1:c(t,await l(e,r))},g=n=>{if(n===null||typeof n!="object")return;const t=n;return typeof t.idFromName=="function"&&typeof t.get=="function"?t:void 0},E=(n,t,r)=>{if(t===void 0)return;const e=g(n?.[t]);if(e!==void 0)return typeof e.getByName=="function"?e.getByName(r):e.get(e.idFromName(r))};export{y as R,f as a,l as b,d as e,E as s,m as v};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as c}from"@lunora/errors";import{t as s}from"./base64-DfpzS4o_.mjs";const e=n=>{if(n.kind!=="optional")return n.kind;const t=n._meta?.inner;return t?e(t):n.kind},i=39,g="0",d="1",m=n=>{const t=n<0n,r=(t?-n:n).toString();if(r.length>i)throw new c("BAD_REQUEST",`bigint ${n.toString()} has ${String(r.length)} digits, over the ${String(i)}-digit limit for a queryable column`);const o=r.padStart(i,"0");return t?g+Array.from(o,f=>String(9-Number(f))).join(""):d+o},u=n=>typeof n=="bigint"?m(n):n instanceof ArrayBuffer?s(new Uint8Array(n)):ArrayBuffer.isView(n)?s(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)):void 0,y=n=>{const t=e(n);return t==="bigint"||t==="bytes"},S=n=>{const t=e(n);return y(n)||t==="any"||t==="union"||t==="from"};export{i as B,y as i,S as m,u as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const y=(t,e)=>t<e?-1:t>e?1:0,s=t=>{if(t===void 0)return"null";if(typeof t=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key — pass it as a string, or use stableWireKey");if(t===null||typeof t!="object")return JSON.stringify(t);if(Array.isArray(t))return`[${t.map(r=>s(r)).join(",")}]`;const e=Object.getPrototypeOf(t);if(e!==null&&e!==Object.prototype){const r=t.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${r} in a stable JSON cache key — only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}const n=t,c=Object.keys(n).toSorted(y),o=[];for(const r of c){const i=n[r];i!==void 0&&o.push(`${JSON.stringify(r)}:${s(i)}`)}return`{${o.join(",")}}`};export{s as stableStringify};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{stableStringify as r}from"./stableStringify-CujpENIO.mjs";import{e as o}from"./wire-codec-BU9T2xJ7.mjs";const m=e=>r(o(e));export{m as stableWireKey};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as w,f as O}from"./base64-DfpzS4o_.mjs";const o="$lunora.wire$",m=64,A=1024,d="__proto__",p={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},E={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},j=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype},a=(e,t=0)=>{if(t>m)throw new RangeError(`wire-codec: value nesting exceeds the ${m}-level limit`);if(e===void 0)return[o,"undefined"];if(e===null)return null;const y=typeof e;if(y==="bigint")return[o,"bigint",e.toString()];if(y==="number"){const r=e;return Number.isNaN(r)?[o,"nan"]:r===1/0?[o,"inf"]:r===-1/0?[o,"-inf"]:r}if(y!=="object")return e;if(e instanceof Date)return[o,"date",a(e.getTime(),t+1)];if(e instanceof Error){const r=e,n={};for(const c of Object.keys(r))r[c]!==void 0&&(n[c]=a(r[c],t+1));const i=[o,"error",r.name,r.message,n];return r.cause!==void 0&&i.push(a(r.cause,t+1)),i}if(e instanceof URL)return[o,"url",e.href];if(e instanceof Map)return[o,"map",[...e.entries()].map(([r,n])=>[a(r,t+1),a(n,t+1)])];if(e instanceof Set)return[o,"set",[...e].map(r=>a(r,t+1))];if(e instanceof ArrayBuffer)return[o,"bytes",w(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const r=e,n=r.constructor.name,i=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);return n==="Uint8Array"?[o,"bytes",w(i)]:[o,"bytes",w(i),n]}if(Array.isArray(e)){const r=e.map(n=>a(n,t+1));return r.length>0&&r[0]===o?[o,"arr",r]:r}if(!j(e)){const r=e.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${r} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const u=e,s={};for(const r of Object.keys(u)){const n=u[r];if(n===void 0)continue;const i=a(n,t+1);r===d?Object.defineProperty(s,r,{configurable:!0,enumerable:!0,value:i,writable:!0}):s[r]=i}return s},f=(e,t=0)=>{if(t>m)throw new RangeError(`wire-codec: value nesting exceeds the ${m}-level limit`);if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===o)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(r=>f(r,t+1));case"bigint":{const r=e[2];if(typeof r!="string"||r.length>A||!/^-?\d+$/.test(r))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${A} digits)`);return BigInt(r)}case"date":return new Date(f(e[2],t+1));case"map":return new Map(e[2].map(([r,n])=>[f(r,t+1),f(n,t+1)]));case"set":return new Set(e[2].map(r=>f(r,t+1)));case"url":return new URL(e[2]);case"error":{const r=e[2],n=e[3],i=(Object.hasOwn(E,r)?E[r]:void 0)??Error,c=new i(n);c.name!==r&&Object.defineProperty(c,"name",{configurable:!0,value:r,writable:!0});const g=f(e[4],t+1);for(const b of Object.keys(g))b===d?Object.defineProperty(c,b,{configurable:!0,enumerable:!0,value:g[b],writable:!0}):c[b]=g[b];return e.length>5&&Object.defineProperty(c,"cause",{configurable:!0,value:f(e[5],t+1),writable:!0}),c}case"bytes":{const r=O(e[2]),n=e[3]??"Uint8Array";if(n==="ArrayBuffer")return r.buffer.byteLength===r.byteLength?r.buffer:r.slice().buffer;const i=Object.hasOwn(p,n)?p[n]:void 0;return i?new i(r.slice().buffer):r}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(r=>f(r,t+1))}return e.map(s=>f(s,t+1))}const y=e,u={};for(const s of Object.keys(y)){const r=f(y[s],t+1);s===d?Object.defineProperty(u,s,{configurable:!0,enumerable:!0,value:r,writable:!0}):u[s]=r}return u};export{f as d,a as e,j as i};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/shard-engine",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.28",
|
|
4
4
|
"description": "Host-neutral reactive engine for Lunora: per-shard state, OCC, CDC, reactive subscriptions, and the poke protocol. Consumes @lunora/platform host contracts and can be mounted on any platform host.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -48,8 +48,8 @@
|
|
|
48
48
|
"access": "public"
|
|
49
49
|
},
|
|
50
50
|
"dependencies": {
|
|
51
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
52
|
-
"@lunora/platform": "1.0.0-alpha.
|
|
51
|
+
"@lunora/errors": "1.0.0-alpha.22",
|
|
52
|
+
"@lunora/platform": "1.0.0-alpha.11",
|
|
53
53
|
"drizzle-orm": "^0.45.2"
|
|
54
54
|
},
|
|
55
55
|
"engines": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as T}from"@lunora/errors";import{j as L,s as k}from"./do-sql-DKSFK627.mjs";import{quoteIdentifier as d}from"./quoteIdentifier-CObIFRhb.mjs";import{s as P}from"./wire-codec-Dh0j-GnY.mjs";const te="__lunora_admin__:",ae="__lunora_relation__:",re="__lunora_flags__:",se={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",getAdvisories:"__lunora_admin__:getAdvisories",getAdvisorProcedures:"__lunora_admin__:getAdvisorProcedures",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",listTablesIndexes:"__lunora_admin__:listTablesIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",replayQueueMessage:"__lunora_admin__:replayQueueMessage",resolveIssue:"__lunora_admin__:resolveIssue",rlsPolicies:"__lunora_admin__:rlsPolicies",schemaHistory:"__lunora_admin__:schemaHistory",schemaVersion:"__lunora_admin__:schemaVersion",runAs:"__lunora_admin__:runAs",runMigration:"__lunora_admin__:runMigration",runSql:"__lunora_admin__:runSql",sendQueueMessage:"__lunora_admin__:sendQueueMessage",sendTestMail:"__lunora_admin__:sendTestMail",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},D=50,f=500,U=30,q=200,m="__doc__",R=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},W=e=>{const{[k]:t,...a}=e;return t===void 0?a:t===null||typeof t!="object"||Array.isArray(t)?{[k]:t,...a}:{...a,...P(t)}},j=(e,t)=>{if(!e.includes(m))return{columns:e,rows:t};const a=[];for(const s of t){const _=s[m],u=typeof _=="string"?R(_):void 0;if(u===void 0)return{columns:e,rows:t};const i=Object.fromEntries(Object.entries(s).filter(([l])=>l!==m));a.push({...i,...W(u)})}const r=e.filter(s=>s!==m),o=[],n=new Set(r);for(const s of a)for(const _ of Object.keys(s))n.has(_)||(n.add(_),o.push(_));return{columns:[...r,...o],rows:a}},w=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,I=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),v=(e,t,a)=>Math.min(Math.max(e,t),a),$=(e,t)=>{const a=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(a.c)},oe=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),a=[];for(const{name:r}of t)I(r)||a.push({name:r,rowCount:$(e,d(r))});return a},x=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,C=(e,t)=>{if(I(t)||!x(e,t))throw new T("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},b=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(a=>a.name),Q={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},B=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",M=(e,t)=>{const a=t.includes(e),r=t.includes(m);if(!(!a&&!r))return a?{expression:d(e),params:[]}:{expression:`json_extract(${d(m)}, ?)`,params:[`$.${L(e)}`]}},H=(e,t)=>{const a=M(e.column,t);if(a===void 0)return;const{expression:r,params:o}=a;return e.operator==="contains"?{params:[...o,B(e.value)],sql:w(r)}:{params:[...o,e.value],sql:`${r} ${Q[e.operator]} ?`}},G=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,X=e=>{const t=G.exec(e.trim());if(t===null)return;const a=Number(t[1]),r=t[2]===void 0?void 0:Number(t[2]),o=t[3]===void 0?void 0:Number(t[3]);if(r!==void 0&&(r<1||r>12)||o!==void 0&&(o<1||o>31)||a<100)return;const n=Date.UTC(a,(r??1)-1,o??1);if(o!==void 0&&new Date(n).getUTCDate()!==o)return;let s;return o!==void 0?s=Date.UTC(a,(r??1)-1,o+1):r===void 0?s=Date.UTC(a+1,0,1):s=Date.UTC(a,r,1),{from:n,to:s}},E=(e,t,a)=>{const r=[],o=[];if(t!==""&&e.length>0){const n=e.map(_=>w(d(_)));o.push(...e.map(()=>t));const s=X(t);if(s!==void 0)for(const _ of e)n.push(`(${d(_)} >= ? AND ${d(_)} < ?)`),o.push(s.from,s.to);r.push(`(${n.join(" OR ")})`)}for(const n of a??[]){const s=H(n,e);s!==void 0&&(r.push(`(${s.sql})`),o.push(...s.params))}return r.length===0?void 0:{parameters:o,where:r.join(" AND ")}},Y=(e,t)=>{if(e===void 0)return;const a=M(e.column,t);if(a===void 0)return;const r=e.direction==="desc"?"DESC":"ASC";return{params:a.params,sql:`${a.expression} ${r}`}},ne=(e,t)=>{const{table:a}=t;C(e,a);const r=v(Math.trunc(t.limit??D),1,f),o=Math.max(0,Math.trunc(t.offset??0)),n=d(a),s=b(e,n),_=t.search?.trim()??"",u=h=>{if(t.refs===void 0)return h;const S={};for(const y of h.columns){const O=t.refs[y];O!==void 0&&(S[y]=O)}return Object.keys(S).length>0?{...h,refs:S}:h},i=E(s,_,t.filters),l=Y(t.orderBy,s),c=i===void 0?"":` WHERE ${i.where}`,p=l===void 0?"":` ORDER BY ${l.sql}`,g=i?.parameters??[],N=l?.params??[];let A;t.skipCount||(A=i===void 0?$(e,n):Number(e.exec(`SELECT COUNT(*) AS c FROM ${n}${c}`,...g).one().c));const F=e.exec(`SELECT * FROM ${n}${c}${p} LIMIT ? OFFSET ?`,...g,...N,r,o).toArray();return u({...j(s,F),total:A})},_e=(e,t)=>{const{table:a}=t;C(e,a);const r=v(Math.trunc(t.limit??f),1,f),o=d(a),n=b(e,o),s=t.search?.trim()??"",_=E(n,s,t.filters),u=_===void 0?e.exec(`SELECT id FROM ${o} LIMIT ?`,r+1).toArray():e.exec(`SELECT id FROM ${o} WHERE ${_.where} LIMIT ?`,..._.parameters,r+1).toArray(),i=u.length>r,l=u.slice(0,r).map(c=>c.id);return{hasMore:i,ids:l}},K=(e,t,a)=>{const r=new Set(a.filter(n=>n!==m));if(!a.includes(m))return r;const o=e.exec(`SELECT ${d(m)} AS doc FROM ${t} LIMIT ?`,f).toArray();for(const{doc:n}of o){const s=typeof n=="string"?R(n):void 0;if(s!==void 0)for(const _ of Object.keys(s))r.add(_)}return r},ie=(e,t)=>{const{column:a,table:r}=t;C(e,r);const o=d(r),n=b(e,o);if(!K(e,o,n).has(a))throw new T("UNKNOWN_COLUMN",`unknown column: ${a}`,{status:404});const s=M(a,n);if(s===void 0)throw new T("UNKNOWN_COLUMN",`unknown column: ${a}`,{status:404});const _=v(Math.trunc(t.limit??U),1,q),u=t.search?.trim()??"",i=E(n,u,t.filters),l=i===void 0?"":` WHERE ${i.where}`,c=i?.parameters??[],p=e.exec(`SELECT ${s.expression} AS value, COUNT(*) AS count FROM ${o}${l} GROUP BY ${s.expression} ORDER BY count DESC LIMIT ?`,...s.params,...c,...s.params,_+1).toArray();return{truncated:p.length>_,values:p.slice(0,_).map(g=>({count:Number(g.count),value:g.value}))}},ue=(e,t,a)=>{const r={},o=a.slice(0,f);for(const s of o)r[s]=[];if(o.length===0)return{references:r,storageColumns:t};const n=o.map(()=>"?").join(", ");for(const[s,_]of Object.entries(t)){if(I(s)||!x(e,s))continue;const u=d(s),i=b(e,u);for(const l of _){const c=M(l,i);if(c===void 0)continue;const p=e.exec(`SELECT id, ${c.expression} AS ref FROM ${u} WHERE ${c.expression} IN (${n})`,...c.params,...c.params,...o).toArray();for(const g of p)r[g.ref]?.push({column:l,id:g.id,table:s})}}return{references:r,storageColumns:t}},le=e=>{const t=e.map((r,o)=>{const n=Object.values(r.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:r.admin===!0,id:o,subscriptions:n}}),a=t.reduce((r,o)=>r+o.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:a}},z=20,ce=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),de=(e,t,a,r)=>({maxMs:Math.max(e.maxMs,r),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+a,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+r}),me=(e,t=z)=>{const a=new Map,r=new Map;for(const n of e){for(const s of Object.values(n.shapes??{})){const _=s.name??"(unknown shape)";a.set(_,(a.get(_)??0)+1)}for(const s of n.whispers??[])r.set(s,(r.get(s)??0)+1)}const o=[...[...a].map(([n,s])=>({kind:"shape",subscribers:s,topic:n})),...[...r].map(([n,s])=>({kind:"whisper",subscribers:s,topic:n}))];return o.sort((n,s)=>s.subscribers-n.subscribers||n.topic.localeCompare(s.topic)),{peakSubscribers:o[0]?.subscribers??0,topics:o.slice(0,t),totalConnections:e.length}};export{se as ADMIN_FUNCTIONS,te as ADMIN_FUNCTION_PREFIX,z as DEFAULT_FANOUT_TOPIC_LIMIT,re as FLAGS_FUNCTION_PREFIX,f as MAX_PAGE_SIZE,ae as RELATION_FUNCTION_PREFIX,ce as createFanoutCounters,X as datePrefixRange,ie as facetColumn,ue as findStorageReferences,oe as listTables,ne as readTablePage,de as recordFanoutPass,_e as selectMatchingIds,me as summarizeFanoutTopics,le as summarizeSubscriptions};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as i}from"@lunora/errors";const a=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),c=()=>{throw new i("INTERNAL","ctx.scheduler: no scheduler configured for triggers. Pass `scheduler` to the ctx-db factory.")},h=(e,r)=>{for(const[n,t]of Object.entries(r)){const o=e[n];if(t!==null&&typeof t=="object"&&!Array.isArray(t)){const s=Object.keys(t);if(s.length===1&&s[0]==="eq"){if(o!==t.eq)return!1;continue}return!1}if(o!==t)return!1}return!0},g=e=>{if(e===void 0)return{};if(typeof e!="object"||Array.isArray(e))return{where:e};const r=Object.keys(e);return r.length===0?{}:r.every(n=>a.has(n))?e:{where:e}},u={avg:"AVG",count:"COUNT",max:"MAX",min:"MIN",sum:"SUM"},l=e=>{const r=u[e];if(r===void 0)throw new i("INTERNAL",`unknown aggregate op "${e}": expected one of ${Object.keys(u).join(", ")}`);return r},A={runAfter:c,runAt:c};export{u as AGGREGATE_SQL_FUNCTION,l as aggregateSqlFunction,h as matchesStaticWhere,g as normalizeCountArgument,A as throwingScheduler};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import"@lunora/errors";import"drizzle-orm";import{T as l,c as m,p as n,a as p,s as c,A as q,y as d,g as u,L as A,h as D,C as G,_ as S,N as _,S as f,O as C,E as O,I as h,D as I}from"./do-sql-DKSFK627.mjs";import{quoteIdentifier as T}from"./quoteIdentifier-CObIFRhb.mjs";import"./wire-codec-Dh0j-GnY.mjs";import"./runDrizzle-C3n5gJsk.mjs";import"./sql-projection-jfoe331H.mjs";import{serializeSqlValue as x}from"./serializeSqlValue-BR4UOWoP.mjs";export{l as AGG_COUNT,m as AGG_KEY,n as AGG_VALUE,p as DOC_COLUMN,c as DOC_ORIGINALS_KEY,q as aggUpsertSql,d as createIndexSql,u as decodeDocJson,A as encodeDocJson,D as geoTableName,G as isFtsAvailable,S as jsonPath,_ as jsonPathSql,f as qualifiedJsonPath,C as qualifiedJsonPathSql,T as quoteIdentifier,O as rowToDocument,x as serializeSqlValue,h as tableColumns,I as tryRowToDocument};
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import{runSql as i}from"./runDrizzle-C3n5gJsk.mjs";const a="__lunora_audit__",T=1e3,s=E=>{i(E,`CREATE TABLE IF NOT EXISTS "${a}" (
|
|
2
|
-
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
3
|
-
ts REAL NOT NULL,
|
|
4
|
-
op TEXT NOT NULL,
|
|
5
|
-
"table" TEXT,
|
|
6
|
-
id TEXT,
|
|
7
|
-
detail TEXT
|
|
8
|
-
)`)},o=(E,l)=>{s(E),i(E,`INSERT INTO "${a}" (ts, op, "table", id, detail) VALUES (?, ?, ?, ?, ?)`,l.ts,l.op,l.table??null,l.id??null,l.detail===void 0?null:JSON.stringify(l.detail)),i(E,`DELETE FROM "${a}" WHERE seq <= (SELECT MAX(seq) - ? FROM "${a}")`,T)},u=(E,l={})=>{s(E);const d=l.sinceSeq??0,r=Math.max(1,Math.min(l.limit??T,1e4));return i(E,`SELECT seq, ts, op, "table", id, detail FROM "${a}" WHERE seq > ? ORDER BY seq DESC LIMIT ?`,d,r).toArray().map(t=>{const e={op:t.op,seq:t.seq,ts:t.ts};return t.table!==null&&(e.table=t.table),t.id!==null&&(e.id=t.id),t.detail!==null&&(e.detail=JSON.parse(t.detail)),e})};export{a as AUDIT_LOG_TABLE,o as appendAuditEntry,s as ensureAuditTable,u as readAuditLog};
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-C3n5gJsk.mjs";import{L as C,g as l}from"./do-sql-DKSFK627.mjs";import{ConflictError as L}from"./ConflictError-C8GtJmjS.mjs";const d="__cdc_log",I=t=>{a(t,e`CREATE TABLE IF NOT EXISTS ${e.identifier(d)} (
|
|
2
|
-
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
3
|
-
ts REAL NOT NULL,
|
|
4
|
-
${e.identifier("table")} TEXT NOT NULL,
|
|
5
|
-
id TEXT NOT NULL,
|
|
6
|
-
op TEXT NOT NULL,
|
|
7
|
-
doc TEXT
|
|
8
|
-
)`)},m=(t,i,r,E,s,c)=>{const o=c===void 0?null:C(c);a(t,e`INSERT INTO ${e.identifier(d)} (ts, ${e.identifier("table")}, id, op, doc) VALUES (${i}, ${r}, ${E}, ${s}, ${o})`)},q=(t,i={})=>{const r=i.sinceSeq??0,E=Math.max(1,Math.min(i.limit??1e3,1e4)),s=i.tables&&i.tables.size>0?e` AND ${e.identifier("table")} IN (${e.join([...i.tables].map(o=>e`${o}`),e`, `)})`:e``,c=a(t,e`SELECT seq, ts, ${e.identifier("table")}, id, op, doc FROM ${e.identifier(d)} WHERE seq > ${r}${s} ORDER BY seq ASC LIMIT ${E}`).toArray().map(o=>{const T={id:o.id,op:o.op,seq:o.seq,table:o.table,ts:o.ts};return o.doc===null?T:{...T,doc:l(o.doc)}});return{changes:c,cursor:c.at(-1)?.seq??r}},O=(t,i)=>{a(t,e`DELETE FROM ${e.identifier(d)} WHERE seq <= ${i}`)},S=t=>{const i=a(t,e`SELECT seq FROM sqlite_sequence WHERE name = ${d}`).toArray()[0]?.seq;return typeof i=="number"?i:a(t,e`SELECT MAX(seq) AS seq FROM ${e.identifier(d)}`).toArray()[0]?.seq??0},h=t=>a(t,e`SELECT MIN(seq) AS seq FROM ${e.identifier(d)}`).toArray()[0]?.seq??void 0,n="__cdc_meta",p=t=>{a(t,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (id INTEGER PRIMARY KEY CHECK (id = 1), epoch TEXT NOT NULL)`)},u=t=>{p(t);const i=a(t,e`SELECT epoch FROM ${e.identifier(n)} WHERE id = 1`).toArray()[0]?.epoch;if(typeof i=="string"&&i.length>0)return i;const r=crypto.randomUUID();return a(t,e`INSERT INTO ${e.identifier(n)} (id, epoch) VALUES (1, ${r})`),r},M=t=>{p(t);const i=crypto.randomUUID();return a(t,e`INSERT INTO ${e.identifier(n)} (id, epoch) VALUES (1, ${i}) ON CONFLICT(id) DO UPDATE SET epoch = excluded.epoch`),i},$=async(t,i)=>{if(i.op==="delete"){await t.delete(i.id,i.table);return}const r=i.doc??{};try{await t.insert(i.table,r,{allowExplicitId:!0})}catch(E){if(!(E instanceof L))throw E;const s={...r};delete s._id,await t.replace(i.id,s,void 0,{allowExplicitId:!0})}},b=async(t,i)=>{for(const r of i)await $(t,r)};export{d as CDC_LOG_TABLE,n as CDC_META_TABLE,m as appendCdcChange,b as applyCdcChanges,M as bumpCdcEpoch,I as migrateCdcLog,p as migrateCdcMeta,h as minCdcSeq,q as readCdcChanges,S as readCdcCursor,u as readCdcEpoch,O as trimCdcChanges};
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import{sql as t}from"drizzle-orm";import{runDrizzle as n}from"./runDrizzle-C3n5gJsk.mjs";const _="__client_watermark",l=i=>{n(i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(_)} (
|
|
2
|
-
identity TEXT NOT NULL,
|
|
3
|
-
client_id TEXT NOT NULL,
|
|
4
|
-
last_mutation_id INTEGER NOT NULL,
|
|
5
|
-
PRIMARY KEY (identity, client_id)
|
|
6
|
-
)`)},E=(i,e,a)=>n(i,t`SELECT last_mutation_id FROM ${t.identifier(_)} WHERE identity = ${e} AND client_id = ${a} LIMIT 1`).toArray()[0]?.last_mutation_id??0,m=(i,e,a,d)=>{n(i,t`INSERT INTO ${t.identifier(_)} (identity, client_id, last_mutation_id) VALUES (${e}, ${a}, ${d})
|
|
7
|
-
ON CONFLICT(identity, client_id) DO UPDATE SET last_mutation_id = MAX(last_mutation_id, excluded.last_mutation_id)`)};export{_ as CLIENT_WATERMARK_TABLE,m as advanceClientWatermark,l as migrateClientWatermark,E as readClientWatermark};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as y}from"@lunora/errors";class A extends y{constructor(e){super("COUNT_RLS_UNSUPPORTED",e===void 0?"count() is not supported in an RLS-restricted context":`count() is not supported on table "${e}" inside an RLS-restricted context`)}}const R=(t,e)=>t?e?{AND:[t,e]}:t:e,g=new Set(["AND","NOT","OR"]),f=Symbol("not-eq"),x=t=>{if(t!==null&&typeof t=="object"&&!Array.isArray(t)){const e=Object.keys(t);return e.length===1&&e[0]==="eq"?t.eq:f}return t},d=(t,e)=>{const s={};for(const[r,n]of Object.entries(t)){if(g.has(r)||!e(r))return;const o=x(n);if(o===f)return;s[r]=o}return s},a=(t,e,s)=>{const r={...e};if(!t)return r;for(const[n,o]of Object.entries(t))if(n in r){if(r[n]!==o)return}else if(n in s){if(s[n]!==o)return}else r[n]=o;return r},b=(t,e)=>{const s=t.by??[],r=e??{},n=d(r,o=>s.includes(o));if(n!==void 0){for(const o of s)if(!(o in n))return;return a(t.where,n,r)}},h=(t,e,s)=>{const r=d(e??{},n=>s.has(n));if(r!==void 0)return a(t.where,r,{})},l=(t,e,s,r)=>{let n;for(const o of t){if(o.op!==e||e!=="count"&&o.field!==s)continue;const i=b(o,r);i&&(!n||(o.by?.length??0)>(n.index.by?.length??0))&&(n={index:o,key:i})}return n},S=(t,e)=>l(t,"count",void 0,e),v=(t,e,s,r)=>l(t,e,s,r),L=(t,e,s,r,n)=>{const o=new Set(r);for(const i of t){if(i.op!==e||e!=="count"&&i.field!==s)continue;const c=i.by??[];if(c.length!==o.size||!c.every(p=>o.has(p)))continue;const u=h(i,n,o);if(u!==void 0)return{index:i,partial:u}}};export{A as CountRlsUnsupportedError,R as mergeWhere,b as planAggregateLookup,v as selectIndexForAggregate,S as selectIndexForCount,L as selectIndexForGroupBy};
|
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
import{LunoraError as y}from"@lunora/errors";import{runSql as n}from"./runDrizzle-C3n5gJsk.mjs";const o="__lunora_migrations",D=100,$=3e4,U=1e4,b=r=>{n(r,`CREATE TABLE IF NOT EXISTS "${o}" (
|
|
2
|
-
id TEXT PRIMARY KEY,
|
|
3
|
-
direction TEXT NOT NULL,
|
|
4
|
-
status TEXT NOT NULL,
|
|
5
|
-
cursor TEXT,
|
|
6
|
-
processed INTEGER NOT NULL DEFAULT 0,
|
|
7
|
-
changed INTEGER NOT NULL DEFAULT 0,
|
|
8
|
-
started_at REAL,
|
|
9
|
-
updated_at REAL,
|
|
10
|
-
error TEXT
|
|
11
|
-
)`)},m=r=>({changed:r.changed,cursor:typeof r.cursor=="string"?r.cursor:null,direction:r.direction==="down"?"down":"up",processed:r.processed,status:r.status==="completed"||r.status==="failed"?r.status:"in_progress"}),N=(r,t)=>{const e=n(r,`SELECT * FROM "${o}" WHERE id = ?`,t).toArray()[0];if(e)return{...m(e),startedAt:typeof e.started_at=="number"?e.started_at:void 0}},w=(r,t)=>{n(r,`DELETE FROM "${o}" WHERE id = ?`,t)},R=(r,t)=>{n(r,`INSERT INTO "${o}"
|
|
12
|
-
(id, direction, status, cursor, processed, changed, started_at, updated_at, error)
|
|
13
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
14
|
-
ON CONFLICT(id) DO UPDATE SET
|
|
15
|
-
direction = excluded.direction,
|
|
16
|
-
status = excluded.status,
|
|
17
|
-
cursor = excluded.cursor,
|
|
18
|
-
processed = excluded.processed,
|
|
19
|
-
changed = excluded.changed,
|
|
20
|
-
updated_at = excluded.updated_at,
|
|
21
|
-
error = excluded.error`,t.id,t.direction,t.status,t.cursor,t.processed,t.changed,t.startedAt,t.updatedAt,t.error)},x=(r,t,e,a)=>(n(r,`INSERT INTO "${o}"
|
|
22
|
-
(id, direction, status, cursor, processed, changed, started_at, updated_at, error)
|
|
23
|
-
VALUES (?, ?, 'in_progress', NULL, 0, 0, ?, ?, NULL)
|
|
24
|
-
ON CONFLICT(id) DO UPDATE SET
|
|
25
|
-
status = 'in_progress',
|
|
26
|
-
updated_at = excluded.updated_at
|
|
27
|
-
WHERE
|
|
28
|
-
"${o}".direction <> excluded.direction
|
|
29
|
-
OR "${o}".status <> 'in_progress'
|
|
30
|
-
OR "${o}".updated_at IS NULL
|
|
31
|
-
OR "${o}".updated_at <= excluded.updated_at - ${String($)}`,t,e,a,a),n(r,"SELECT changes() AS changed").one().changed>0),F=(r,t,e)=>{n(r,`UPDATE "${o}" SET updated_at = ? WHERE id = ? AND status = 'in_progress'`,e,t)},M=(r,t)=>{n(r,`UPDATE "${o}" SET updated_at = 0 WHERE id = ? AND status = 'in_progress'`,t)},W=(r,t)=>{if(n(r,"SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",o).toArray().length===0)return[];const e=t===void 0?" ORDER BY id":" WHERE id = ?",a=t===void 0?[]:[t];return n(r,`SELECT * FROM "${o}"${e}`,...a).toArray().map(d=>({...m(d),error:typeof d.error=="string"?d.error:null,id:d.id,startedAt:typeof d.started_at=="number"?d.started_at:null,updatedAt:typeof d.updated_at=="number"?d.updated_at:null}))},v=async r=>{const{migration:t,sql:e,writer:a}=r,d=r.direction??"up",c=r.dryRun??!1,g=r.clock??(()=>Date.now()),S=r.maxBatches??Number.POSITIVE_INFINITY,I=r.batchSize??t.batchSize??D,f=d==="up"?t.up:t.down;if(!f)throw new y("INTERNAL",`data migration "${t.id}" has no \`${d}\` transform`);const O={db:{count:a.count.bind(a),findFirst:a.findFirst.bind(a),findMany:a.findMany.bind(a),get:a.get.bind(a)}};let u=null,l=0,T=0,_=g();if(!c){b(e);const s=N(e,t.id);if(s?.direction===d&&s.status==="completed")return{changed:s.changed,cursor:null,direction:d,dryRun:c,id:t.id,processed:s.processed,status:"completed"};if(s&&s.direction!==d&&w(e,t.id),!x(e,t.id,d,g())){const E=N(e,t.id);return{changed:E?.changed??0,cursor:E?.cursor??u,direction:d,dryRun:c,id:t.id,processed:E?.processed??0,status:E?.status??"in_progress"}}const i=s?.direction===d?s:void 0;i&&(u=i.cursor,l=i.processed,T=i.changed,_=i.startedAt??_)}let p=!1,A=0,h=_;try{for(;!p&&A<S;){const s=await a.findMany(t.table,{cursor:u,limit:I});for(const i of s.page){l+=1;const E=await f(i,O);if(E!==void 0&&(T+=1,c||await a.replace(String(i._id),{...E,_creationTime:i._creationTime,_id:i._id},void 0,{allowExplicitId:!0})),!c){const L=g();L-h>=U&&(F(e,t.id,L),h=L)}}if(u=s.continueCursor,p=s.isDone,A+=1,!c){const i=g();R(e,{changed:T,cursor:p?null:u,direction:d,error:null,id:t.id,processed:l,startedAt:_,status:p?"completed":"in_progress",updatedAt:i}),h=i;try{await r.onBatch?.({batches:A,changed:T,processed:l})}catch{}}}}catch(s){throw c||R(e,{changed:T,cursor:u,direction:d,error:s instanceof Error?s.message:String(s),id:t.id,processed:l,startedAt:_,status:"failed",updatedAt:g()}),s}if(!c&&!p)try{M(e,t.id)}catch(s){console.warn(`data migration "${t.id}": releaseClaim failed`,s)}return{changed:T,cursor:p?null:u,direction:d,dryRun:c,id:t.id,processed:l,status:p?"completed":"in_progress"}};export{o as DATA_MIGRATION_STATE_TABLE,W as readMigrationStatus,v as runDataMigration};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as d}from"@lunora/errors";import{distinctValues as R}from"./applyOnDelete-crbAzVfE.mjs";import{RELATION_EXISTS_KEY as k}from"./RELATION_EXISTS_KEY-BaqSIFU1.mjs";const y={every:{kind:"many",negateChild:!0,negated:!0},is:{kind:"one",negated:!1},isNot:{kind:"one",negated:!0,nullDisjunct:!0},none:{kind:"many",negated:!0},some:{kind:"many",negated:!1}},A=new Set(Object.keys(y)),w=e=>{const t=y[e];if(!t)throw new d("INTERNAL",`unknown relation operator "${e}"`);return t},E=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},j=5e3,h=Symbol("relation-key-overflow"),b=e=>Array.isArray(e)?e.map(t=>t??{}):[],N=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},p=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(n=>A.has(n))},u=(e,t,n)=>{const a=t.tables[n]?.relationMap??{};return Object.keys(e).some(r=>{const s=e[r];return r==="AND"||r==="OR"?b(s).some(o=>u(o,t,n)):r==="NOT"?u(s??{},t,n):!!a[r]&&p(s)})},M=(e,t,n,a)=>{if(e&&u(e,t,n))throw new d("INTERNAL",`relation-crossing predicates are not supported in ${a}() — use them in findMany/findFirst or an RLS read policy`)},S=async(e,t,n,a,r)=>{const s=await c(t,e.table,a),{page:o}=await a.fetcher(e.table,{baseWhere:a.relationBaseWhere?.(e.table),relationBaseWhere:a.relationBaseWhere,where:s}),i=R(o,n);if(i.length>a.maxRelationKeys){if(r)return h;throw new d("INTERNAL",`relation predicate on "${e.table}" matched ${String(i.length)} rows, exceeding the ${String(a.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)}return i},T=async(e,t,n,a,r)=>{const s=w(e),{clause:o,project:i}=E(t),l=await S(t,s.negateChild?{NOT:n}:n,i,a,r);return l===h?h:s.negated?s.nullDisjunct?{OR:[{[o]:{notIn:l}},{[o]:{isNull:!0}}]}:{[o]:{notIn:l}}:{[o]:{in:l}}},g=async(e,t,n,a,r)=>{const s=w(e),o=r.relationBaseWhere?.(t.table),i=s.negateChild?{NOT:n}:n,l={childWhere:await c(o?{AND:[o,i]}:i,t.table,r),negated:s.negated,parentTable:a,relation:t};return{[k]:l}},$=(e,t,n)=>{const a=y[e];if(a&&a.kind!==n.kind)throw new d("INTERNAL",`relation operator "${e}" requires a to-${a.kind} relation, but "${t}" is to-${n.kind}`)},x=async(e,t,n,a,r)=>{const s=[];for(const o of Object.keys(n)){$(o,e,t);const i=n[o]??{},l=r.canPushExists?.(t)??!1;if(l&&r.existsPushMode==="always"){s.push(await g(o,t,i,a,r));continue}const m=await T(o,t,i,r,l);m===h?s.push(await g(o,t,i,a,r)):s.push(m)}return N(s)},D=async(e,t,n,a)=>{if(e==="AND"||e==="OR"){const s=[];for(const o of b(t))s.push(await c(o,n,a));return{[e]:s}}if(e==="NOT")return{NOT:await c(t??{},n,a)};const r=a.schema.tables[n]?.relationMap?.[e];return r&&p(t)?x(e,r,t,n,a):{[e]:t}},c=async(e,t,n)=>{const a=[];for(const r of Object.keys(e))a.push(await D(r,e[r],t,n));return N(a)},W=async(e,t)=>!e||!u(e,t.schema,t.tableName)?e:c(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??j,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),f=(e,t,n)=>{for(const a of e){const r=O(a,t,n);if(r)return r}},I=(e,t,n,a)=>{if(e==="AND"||e==="OR")return f(b(t),n,a);if(e==="NOT")return f([t??{}],n,a);const r=n.tables[a]?.relationMap?.[e];if(!(!r||!p(t)))return n.tables[r.table]?.shardMode?.kind==="shardBy"?{relation:e,target:r.table}:f(Object.values(t),n,r.table)},O=(e,t,n)=>{for(const a of Object.keys(e)){const r=I(a,e[a],t,n);if(r)return r}},_=(e,t,n)=>{if(!e)return;const a=O(e,t,n);if(a)throw Object.assign(new Error(`shape on "${n}" joins the sharded table "${a.target}" via relation "${a.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${n}", or (b) moving "${a.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{j as DEFAULT_MAX_RELATION_KEYS,M as assertFlatPredicate,_ as assertShapeShardable,u as containsRelationPredicate,p as isRelationPredicate,W as resolveRelationPredicates};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{toErrorBody as A,LunoraError as x}from"@lunora/errors";import{a as w,s as g}from"./wire-codec-Dh0j-GnY.mjs";import{u as m,f as P,g as R,l as k,s as M,o as L}from"./sibling-channel-bg9FBL5s.mjs";import{relayName as y,nextPromotionState as O,shapeRoutingKey as S,parseRelayName as D,clampPromotionThresholds as C,DEFAULT_PROMOTION_THRESHOLDS as b}from"./DEFAULT_PROMOTION_THRESHOLDS-DYGNAo1I.mjs";import{encodeRowsPatch as T,buildPokeFrames as _}from"./buildPokeFrames-DmB-FBeQ.mjs";import{awaitWsDrain as N,trySendFrame as I}from"./awaitWsDrain-PT9o0d6J.mjs";import{stableWireKey as p}from"./stableWireKey-Diuu1gGc.mjs";const F=2,$=8,f={},U=d=>{throw new x("INTERNAL",`unhandled relay frame: ${JSON.stringify(d)}`)},K=d=>Response.json(d,{headers:{"content-type":"application/json"}}),u=()=>new Response(null,{status:204});class E{constructor(e,s){this.host=e,this.roleId=s}host;roleId;async handleControl(e){let s;try{s=await e.text()}catch{return new Response("bad request",{status:400})}if(!await P(this.host.env(),e.headers.get(R),s))return new Response("forbidden",{status:403});let t;try{t=JSON.parse(s)}catch{return new Response("bad request",{status:400})}switch(t.type){case"relay_attach":return this.onAttach(t.relayIndex),u();case"relay_detach":return this.onDetach(t.relayIndex),u();case"relay_frame":return this.host.deliverWhisperLocal(t.topic,t.frame,void 0),await this.onWhisperFrame(t),u();case"relay_shape_poke":{const r=this.host.getWebSockets().length,a=Date.now(),o=this.onShapePoke({...t,args:g(t.args)});return this.host.recordShapePokeFanout(r,o,Date.now()-a),u()}case"relay_shape_subscribe":return K(this.onShapeSubscribe({...t,args:g(t.args)}));default:return U(t)}}maxRelays(){return m(this.host.env(),"LUNORA_MAX_RELAYS",$)}canAddressSiblings(){return this.siblingStub(this.roleId.ownerKey)!==void 0}siblingStub(e){return k(this.host.env(),this.host.shardBinding(),e)}async postRelayMessage(e,s){await this.requestRelayMessage(e,s)}async requestRelayMessage(e,s){const t=this.siblingStub(e);if(t===void 0)return;const r=JSON.stringify(s),a={"content-type":"application/json","x-lunora-shard-binding":this.host.shardBinding()??""},o=M(this.host.env());o!==void 0&&(a[R]=await L(o,r));try{return await t.fetch("https://relay.internal/_lunora/relay",{body:r,headers:a,method:"POST"})}catch{return}}}class W extends E{shapeUniformCache=new Map;relaySetCache;relayShapeRegistry=new Map;relayShapeProxies=new Map;promotionState="owned";constructor(e,s){super(e,{ownerKey:s})}async forwardWhisper(e,s){if(!this.canAddressSiblings())return;const t=this.ownerRelaySet();t.size!==0&&await Promise.all([...t].map(r=>this.postRelayMessage(y(this.roleId.ownerKey,r),{frame:s,topic:e,type:"relay_frame"})))}async onFlush(e,s){await Promise.all([this.multicastShapePokes(e,s),this.proxyShapePokes(e,s)])}seedRelayShape(){return Promise.resolve(void 0)}announce(){return Promise.resolve()}announceDrain(){return Promise.resolve()}relayCount(){const e=this.host.getWebSockets().length,s=m(this.host.env(),"LUNORA_RELAY_THRESHOLD",b.tUp),t=m(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",b.tDown);if(this.promotionState=O(this.promotionState,e,C(s,t)),this.promotionState==="owned")return 0;const r=m(this.host.env(),"LUNORA_RELAY_FAN",F);return Math.min(this.maxRelays(),Math.max(1,r))}isShapeRelayUniform(e,s){const t=S(e,s),r=this.shapeUniformCache.get(t);if(r!==void 0)return r;const a=this.probeShapeRelayUniform(e,s);return this.shapeUniformCache.set(t,a),a}onAttach(e){this.addRelayToSet(e)}onDetach(e){this.removeRelayFromSet(e)}async onWhisperFrame(e){await Promise.all([...this.ownerRelaySet()].filter(s=>s!==e.originRelay).map(s=>this.postRelayMessage(y(this.roleId.ownerKey,s),{frame:e.frame,topic:e.topic,type:"relay_frame"})))}onShapeSubscribe(e){return this.buildShapeSeedFrames(e)}onShapePoke(){return 0}buildShapePoke(e,s,t,r,a){let o;try{o=this.host.resolveShape(e.name,e.args,s)}catch{return}if(o===void 0||o.global===!0||!t.has(o.table))return;const i=e,n=i.cursor,l=this.host.buildShapeDiff(o,n,r);if(l.length!==0)return i.cursor=r,{args:w(e.args),checkpoint:r,epoch:a,fromCursor:n,name:e.name,rowsPatch:T(l),type:"relay_shape_poke"}}async multicastShapePokes(e,s){if(this.relayShapeRegistry.size===0)return;const t=this.ownerRelaySet();if(t.size===0)return;const r=this.host.currentCdcEpoch(),a=[];for(const o of this.relayShapeRegistry.values()){const i=this.buildShapePoke(o,f,e,s,r);if(i)for(const n of t)a.push(this.postRelayMessage(y(this.roleId.ownerKey,n),i))}await Promise.all(a)}async proxyShapePokes(e,s){if(this.relayShapeProxies.size===0)return;const t=this.host.currentCdcEpoch(),r=[];for(const a of this.relayShapeProxies.values()){const o=this.buildShapePoke(a,a.identity,e,s,t);o&&r.push(this.postRelayMessage(y(this.roleId.ownerKey,a.relayIndex),{...o,targetConnectionId:a.connectionId}))}await Promise.all(r)}buildShapeSeedFrames(e){const s={identity:e.identity,userId:e.userId};let t;try{t=this.host.resolveShape(e.name,e.args,s)}catch(c){const{body:h}=A(c,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{error:{code:h.code,message:h.message}}}if(t===void 0||t.global===!0)return{error:{code:"SHAPE_NOT_FOUND",message:`shape not relayable: ${e.name}`}};e.relayIndex!==void 0&&this.addRelayToSet(e.relayIndex);const{baseCheckpoint:r,cursor:a,epoch:o,rowsPatch:i}=this.host.computeOpLogShapeSeed({args:e.args,name:e.name,sinceEpoch:e.sinceEpoch,sinceSeq:e.sinceSeq},t);let n=a;if(this.isShapeRelayUniform(e.name,e.args)){const c=S(e.name,e.args);let h=this.relayShapeRegistry.get(c);h===void 0&&(h={args:e.args,cursor:a,name:e.name},this.relayShapeRegistry.set(c,h)),n=h.cursor}else e.relayIndex!==void 0&&e.connectionId!==void 0&&this.relayShapeProxies.set(`${String(e.relayIndex)}:${e.connectionId}:${e.subId}`,{args:e.args,connectionId:e.connectionId,cursor:a,epoch:o,identity:s,name:e.name,relayIndex:e.relayIndex,subId:e.subId});const l=_([{rowsPatch:i,shapeId:e.subId}],{baseCheckpoint:r,checkpoint:a,epoch:o,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:n,epoch:o,frames:l}}ensureRelayTable(){this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relays (idx INTEGER PRIMARY KEY)")}ownerRelaySet(){if(this.relaySetCache===void 0){this.ensureRelayTable();const e=this.host.sql().exec("SELECT idx FROM __lunora_relays").toArray();this.relaySetCache=new Set(e.map(s=>Number(s.idx)))}return this.relaySetCache}addRelayToSet(e){this.ensureRelayTable(),this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relays (idx) VALUES (?)",e),this.ownerRelaySet().add(e)}removeRelayFromSet(e){this.ensureRelayTable(),this.host.sql().exec("DELETE FROM __lunora_relays WHERE idx = ?",e);const s=this.ownerRelaySet();s.delete(e);for(const[t,r]of this.relayShapeProxies)r.relayIndex===e&&this.relayShapeProxies.delete(t);s.size===0&&(this.relayShapeRegistry.clear(),this.shapeUniformCache.clear())}probeShapeRelayUniform(e,s){let t;try{t=this.host.resolveShape(e,s,f)}catch{return!1}if(t===void 0||t.global===!0||this.host.rlsMetadata().policies.some(n=>n.on==="read"&&n.table===t.table)||this.tableHasAnyMask(t.table))return!1;const r=p(t.effectiveWhere),a=p(t.columns);let o=!1;const i=n=>{const l={groups:[`grp_${n}`],roles:[n],sub:`__lunora_probe_${n}__`};return{identity:new Proxy(l,{get:(c,h)=>typeof h=="symbol"||h in c?Reflect.get(c,h):`${n}:${h}`,getOwnPropertyDescriptor:(c,h)=>(o=!0,Reflect.getOwnPropertyDescriptor(c,h)),has:(c,h)=>typeof h=="symbol"?Reflect.has(c,h):!0,ownKeys:c=>(o=!0,Reflect.ownKeys(c))}),userId:`__lunora_probe_${n}__`}};return[f,i("a"),i("b")].every(n=>{let l;try{l=this.host.resolveShape(e,s,n)}catch{return!1}return l!==void 0&&l.global!==!0&&l.table===t.table&&p(l.effectiveWhere)===r&&p(l.columns)===a})&&!o}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(s=>s.table===e)}}class q extends E{relayAnnounced=!1;shapeRelayMemos=new WeakMap;constructor(e,s,t){super(e,{ownerKey:s,relayIndex:t})}async forwardWhisper(e,s){this.canAddressSiblings()&&await this.postRelayMessage(this.roleId.ownerKey,{frame:s,originRelay:this.roleId.relayIndex,topic:e,type:"relay_frame"})}onFlush(){return Promise.resolve()}async seedRelayShape(e,s,t,r){if(!this.canAddressSiblings())return{code:"RELAY_MISCONFIGURED",message:"relay cannot address its owner"};await this.announce();const a={args:w(t.args??{}),connectionId:this.host.readAttachment(e).connectionId,identity:r.identity,name:t.name,relayIndex:this.roleId.relayIndex,sinceEpoch:t.sinceEpoch,sinceSeq:t.sinceSeq,subId:s,type:"relay_shape_subscribe",userId:r.userId},o=await this.requestRelayMessage(this.roleId.ownerKey,a);if(o===void 0)return{code:"RELAY_SEED_FAILED",message:"owner did not answer the shape seed"};let i;try{i=await o.json()}catch{return{code:"RELAY_SEED_FAILED",message:"malformed shape seed from owner"}}if(i.error!==void 0)return i.error;if(i.frames===void 0)return{code:"RELAY_SEED_FAILED",message:"owner returned no shape frames"};await N(e);for(const n of i.frames)I(e,n);return this.recordRelayShapeMemo(e,s,i.cursor??0,i.epoch),"ok"}async announce(){this.relayAnnounced||!this.canAddressSiblings()||(this.relayAnnounced=!0,(await this.requestRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_attach"}))?.ok||(this.relayAnnounced=!1))}async announceDrain(e){this.canAddressSiblings()&&(this.host.getWebSockets().some(s=>s!==e)||(this.relayAnnounced=!1,await this.postRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_detach"})))}relayCount(){return 0}isShapeRelayUniform(){return!1}onAttach(){}onDetach(){}onWhisperFrame(){return Promise.resolve()}onShapeSubscribe(){return{error:{code:"RELAY_CANNOT_SEED",message:"a relay has no op-log to seed from"}}}onShapePoke(e){return this.deliverShapePoke(e)}recordRelayShapeMemo(e,s,t,r){let a=this.shapeRelayMemos.get(e);a===void 0&&(a=new Map,this.shapeRelayMemos.set(e,a)),a.set(s,{cursor:t,epoch:r})}deliverShapePoke(e){const s=S(e.name,e.args);let t=0;for(const r of this.host.getWebSockets()){const a=this.host.readAttachment(r),{shapes:o}=a,i=this.shapeRelayMemos.get(r);if(!(o===void 0||i===void 0)&&!(e.targetConnectionId!==void 0&&a.connectionId!==e.targetConnectionId))for(const[n,l]of Object.entries(o)){const c=i.get(n);if(c?.cursor!==e.fromCursor||c.epoch!==e.epoch||S(l.name,l.args)!==s)continue;const h=_([{rowsPatch:e.rowsPatch,shapeId:n}],{baseCheckpoint:void 0,checkpoint:e.checkpoint,epoch:e.epoch,lastMutationId:void 0,pokeId:this.host.nextPokeId()},{preEncoded:!0});for(const v of h)I(r,v);i.set(n,{cursor:e.checkpoint,epoch:e.epoch}),t+=1}}return t}}const X=d=>{const e=d.doName();if(e===void 0)return;const s=D(e);return s===void 0?new W(d,e):new q(d,s.ownerKey,s.relayIndex)};export{$ as DEFAULT_MAX_RELAYS,W as OwnerRelay,q as RelayMember,X as createRelayLink};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as s}from"@lunora/errors";import{stableWireKey as i}from"./stableWireKey-Diuu1gGc.mjs";const a="::relay::",h=(t,o)=>`${t}${a}${String(o)}`,w=t=>{const o=t.lastIndexOf(a);if(o===-1)return;const r=t.slice(0,o),n=t.slice(o+a.length),e=Number(n);if(!(r.length===0||!Number.isInteger(e)||e<0||String(e)!==n))return{ownerKey:r,relayIndex:e}},d=(t,o)=>i({args:o??{},name:t}),m={tDown:4e3,tUp:8e3},u=(t,o,r=m)=>{if(r.tDown>=r.tUp)throw new s("INTERNAL",`invalid promotion thresholds: tDown (${String(r.tDown)}) must be < tUp (${String(r.tUp)})`);return t==="owned"?o>=r.tUp?"promoted":"owned":o<r.tDown?"owned":"promoted"},c=(t,o)=>o<t?{tDown:o,tUp:t}:{tDown:Math.min(Math.max(1,Math.floor(t/2)),t-1),tUp:t},g=(t,o,r)=>{if(t<=o||o<=0)return 0;const n=t-o,e=Math.ceil(n/o);return Math.min(e,Math.max(0,r))};export{m as DEFAULT_PROMOTION_THRESHOLDS,a as RELAY_NAME_INFIX,c as clampPromotionThresholds,u as nextPromotionState,w as parseRelayName,g as relayCountFor,h as relayName,d as shapeRoutingKey};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as i}from"@lunora/errors";import{o as e}from"./estimate-bytes-Drp8rhPs.mjs";const r={maxReadRows:1e5,maxWrittenBytes:32*1024*1024,maxWrittenRows:5e4};class w{readRows=0;writtenRows=0;writtenBytes=0;limits;constructor(t={}){this.limits={...r,...t}}recordRead(t){if(this.readRows+=t,this.readRows>this.limits.maxReadRows)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction read ${String(this.readRows)} documents, over the ${String(this.limits.maxReadRows)}-document limit`)}recordWrite(t){const s=e(t);if(s===void 0)throw new i("BAD_REQUEST","this document is not JSON-serializable (cyclic or non-JSON value); it cannot be written");if(this.writtenRows+=1,this.writtenBytes+=s,this.writtenRows>this.limits.maxWrittenRows)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction wrote ${String(this.writtenRows)} documents, over the ${String(this.limits.maxWrittenRows)}-document limit`);if(this.writtenBytes>this.limits.maxWrittenBytes)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction wrote ${String(this.writtenBytes)} bytes, over the ${String(this.limits.maxWrittenBytes)}-byte limit`)}headroom(){return{readRows:this.readRows,remainingReadRows:Math.max(0,this.limits.maxReadRows-this.readRows),remainingWrittenBytes:Math.max(0,this.limits.maxWrittenBytes-this.writtenBytes),remainingWrittenRows:Math.max(0,this.limits.maxWrittenRows-this.writtenRows),writtenBytes:this.writtenBytes,writtenRows:this.writtenRows}}}export{r as DEFAULT_TRANSACTION_LIMITS,w as TransactionHeadroomTracker};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{toErrorBody as f,LunoraError as S}from"@lunora/errors";import{a as p}from"./wire-codec-Dh0j-GnY.mjs";import{readStreamRun as k,deleteStreamRun as T,claimStreamRun as w,appendStreamChunk as y,finishStreamRun as R,trimStreamRuns as A,readStreamChunks as _}from"./appendStreamChunk-ksZYy1hZ.mjs";const g=5e4,E=64*1024*1024,b=864e5,N=36e5,M=(d,e)=>d===void 0||e.live?"attach":d.status==="complete"||d.status==="error"?e.resuming?"replay-terminal":"reclaim":e.resuming?"interrupted":"reclaim";class v{lastTrimAt=0;runs=new Map;sql;waitUntil;constructor(e){this.sql=e.sql,this.waitUntil=e.waitUntil}async attach(e){try{await this.attachOrThrow(e)}catch(r){const{body:t,redacted:i}=f(r,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});i&&console.error("[@lunora/shard-engine] durable stream attach failed:",r),e.sink.fail({code:t.code,message:t.message})}}detach(e,r){this.runs.get(e)?.sinks.delete(r)}isLive(e){return this.runs.has(e)}async attachOrThrow(e){const r=this.sql(),{runKey:t,sinceChunk:i,sink:o}=e,s=k(r,t),u=i>0,n=this.runs.get(t),a=M(s,{live:n!==void 0,resuming:u}),c=()=>{for(const h of _(r,t,i))if(!o.chunk({data:JSON.parse(h.dataJson),seq:h.seq}))return!1;return!0};if(a==="replay-terminal"){c()&&(s?.status==="error"?o.fail({code:s.errorCode??"INTERNAL_SERVER_ERROR",message:s.error??"stream failed"}):o.complete());return}if(a==="interrupted"){c()&&o.fail({code:"STREAM_INTERRUPTED",message:"the producer for this durable stream did not survive; start a new run"});return}if(n){c()&&n.sinks.add(o);return}a==="reclaim"&&T(r,t),this.trim(r),w(r,t,Date.now(),e.ttlMs??b);const l={sinks:new Set([o])};this.runs.set(t,l);const m=this.produce(t,e.iterator,l);this.waitUntil?.(m),await m}async produce(e,r,t){const i=this.sql(),o=new AbortController;let s=0,u=0;try{for await(const n of r(o.signal)){const a=p(n),c=JSON.stringify(a);if(s+=1,u+=c.length,s>g||u>E)throw new S("STREAM_TOO_LONG",`durable stream exceeded its ceiling (${String(g)} chunks / ${String(E)} bytes); yield less, or drop \`durable\``,{status:507});y(i,e,s,c);for(const l of t.sinks)l.chunk({data:a,seq:s})||t.sinks.delete(l)}R(i,e,"complete",s);for(const n of t.sinks)n.complete()}catch(n){const{body:a,redacted:c}=f(n,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});c&&console.error("[@lunora/shard-engine] unhandled durable stream error:",n),R(i,e,"error",s,{code:a.code,message:a.message});for(const l of t.sinks)l.fail({code:a.code,message:a.message})}finally{this.runs.delete(e)}}trim(e){const r=Date.now();if(!(r-this.lastTrimAt<=N)){this.lastTrimAt=r;try{A(e,r)}catch{}}}}export{v as DurableStreamRunner,E as MAX_DURABLE_STREAM_BYTES,g as MAX_DURABLE_STREAM_CHUNKS,M as decideDurableAttach};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const x="0123456789bcdefghjkmnpqrstuvwxyz",T=9,b=63710088e-1,g=Math.PI/180,w=[Number.POSITIVE_INFINITY,5009400,1252300,156500,39100,4900,1200,152.9,38.2,4.77,1.19,.149,.037],I=w.map((t,n)=>n%2===0?t/2:t),p=.01,k=Math.acos(p)/g,B=2,v=t=>t/b/g,S=t=>{const n=5*t;return{latBands:2**Math.floor(n/2),lngSectors:2**Math.ceil(n/2)}},E=t=>Math.min(Math.max(Math.trunc(t),1),12),z=(t,n)=>{const o=E(n);let s=-90,e=90,a=-180,r=180,u="",i=0,h=0,M=!0;for(;u.length<o;){if(M){const c=(a+r)/2;t.lng>=c?(h=h*2+1,a=c):(h*=2,r=c)}else{const c=(s+e)/2;t.lat>=c?(h=h*2+1,s=c):(h*=2,e=c)}M=!M,i<4?i+=1:(u+=x[h]??"0",i=0,h=0)}return u},y=(t,n)=>Math.min(90,Math.abs(t)+v(n)),G=(t,n)=>{const o=(n.lat-t.lat)*g,s=(n.lng-t.lng)*g,e=t.lat*g,a=n.lat*g,r=Math.sin(o/2)**2+Math.cos(e)*Math.cos(a)*Math.sin(s/2)**2;return 2*b*Math.asin(Math.min(1,Math.sqrt(r)))},C=(t,n)=>{const o=Math.max(Math.cos(y(n,t)*g),p);for(let s=w.length-1;s>=1;s-=1){const e=w[s],a=I[s];if(e!==void 0&&a!==void 0&&e*o>=t&&a>=t)return s}return 1},N={east:["bc01fg45238967deuvhjyznpkmstqrwx","p0r21436x8zb9dcf5h7kjnmqesgutwvy"],north:["p0r21436x8zb9dcf5h7kjnmqesgutwvy","bc01fg45238967deuvhjyznpkmstqrwx"],south:["14365h7k9dcfesgujnmqp0r2twvyx8zb","238967debc01fg45kmstqrwxuvhjyznp"],west:["238967debc01fg45kmstqrwxuvhjyznp","14365h7k9dcfesgujnmqp0r2twvyx8zb"]},O={east:["bcfguvyz","prxz"],north:["prxz","bcfguvyz"],south:["028b","0145hjnp"],west:["0145hjnp","028b"]},l=(t,n)=>{const o=t.toLowerCase(),s=o.at(-1)??"";let e=o.slice(0,-1);const a=o.length%2===0?0:1;return O[n][a].includes(s)&&e!==""&&(e=l(e,n)),e+(x[N[n][a].indexOf(s)]??"")},P=(t,n,o)=>{const s=Math.min(o,B),{latBands:e,lngSectors:a}=S(s),r=180/e,u=360/a,i=v(n),h=Math.max(-90,t.lat-i),M=Math.min(90,t.lat+i),c=new Set;for(let d=0;d<e;d+=1){const f=-90+d*r;if(f+r<h||f>M)continue;const j=f+r/2;for(let m=0;m<a;m+=1){const q=-180+(m+.5)*u;c.add(z({lat:j,lng:q},s))}}return[...c]},_=(t,n)=>{const o=Math.max(n,1),s=C(o,t.lat);if(y(t.lat,o)>=k)return P(t,o,s);const e=z(t,s),a=l(e,"north"),r=l(e,"south"),u=[e,a,r,l(e,"east"),l(e,"west"),l(a,"east"),l(a,"west"),l(r,"east"),l(r,"west")];return[...new Set(u)]},F=(t,n)=>t.lat>=n.sw.lat&&t.lat<=n.ne.lat&&t.lng>=n.sw.lng&&t.lng<=n.ne.lng,L=t=>({lat:(t.sw.lat+t.ne.lat)/2,lng:(t.sw.lng+t.ne.lng)/2}),R=t=>{const n=L(t);return _(n,Math.max(G(n,t.ne),1))};export{T as GEO_DEFAULT_PRECISION,L as boundingBoxCenter,R as boundingBoxGeohashes,_ as coveringGeohashes,z as encodeGeohash,G as haversineMeters,F as pointInBoundingBox};
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{runDrizzle as r}from"./runDrizzle-C3n5gJsk.mjs";const s="__global_shape_snapshot",d=n=>{r(n,e`CREATE TABLE IF NOT EXISTS ${e.identifier(s)} (
|
|
2
|
-
connection_id TEXT NOT NULL,
|
|
3
|
-
sub_id TEXT NOT NULL,
|
|
4
|
-
members TEXT NOT NULL,
|
|
5
|
-
PRIMARY KEY (connection_id, sub_id)
|
|
6
|
-
)`)},T=(n,i,o)=>{const a=r(n,e`SELECT members FROM ${e.identifier(s)} WHERE connection_id = ${i} AND sub_id = ${o} LIMIT 1`).toArray()[0]?.members;if(a===void 0)return new Map;try{const t=JSON.parse(a);return t===null||typeof t!="object"?new Map:new Map(Object.entries(t))}catch{return new Map}},p=(n,i,o,a)=>{const t=JSON.stringify(Object.fromEntries(a));r(n,e`INSERT INTO ${e.identifier(s)} (connection_id, sub_id, members) VALUES (${i}, ${o}, ${t})
|
|
7
|
-
ON CONFLICT(connection_id, sub_id) DO UPDATE SET members = excluded.members`)},S=(n,i,o)=>{r(n,e`DELETE FROM ${e.identifier(s)} WHERE connection_id = ${i} AND sub_id = ${o}`)},b=(n,i)=>{r(n,e`DELETE FROM ${e.identifier(s)} WHERE connection_id = ${i}`)};export{s as GLOBAL_SHAPE_SNAPSHOT_TABLE,S as deleteGlobalShapeSnapshot,b as deleteGlobalShapeSnapshotsForConnection,d as migrateGlobalShapeSnapshot,T as readGlobalShapeSnapshot,p as writeGlobalShapeSnapshot};
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import{sql as t}from"drizzle-orm";import{runDrizzle as r}from"./runDrizzle-C3n5gJsk.mjs";const E="__idempotency",m=i=>{r(i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(E)} (
|
|
2
|
-
identity TEXT NOT NULL,
|
|
3
|
-
mutation_id TEXT NOT NULL,
|
|
4
|
-
result_json TEXT NOT NULL,
|
|
5
|
-
ts REAL NOT NULL,
|
|
6
|
-
PRIMARY KEY (identity, mutation_id)
|
|
7
|
-
)`)},L=(i,e,o)=>{const n=r(i,t`SELECT result_json, ts FROM ${t.identifier(E)} WHERE identity = ${e} AND mutation_id = ${o} LIMIT 1`).toArray()[0];return n===void 0?void 0:{resultJson:n.result_json,ts:n.ts}},N=(i,e,o,n,s)=>{r(i,t`INSERT OR IGNORE INTO ${t.identifier(E)} (identity, mutation_id, result_json, ts) VALUES (${e}, ${o}, ${n}, ${s})`)},I=(i,e)=>{r(i,t`DELETE FROM ${t.identifier(E)} WHERE ts < ${e}`)};export{E as IDEMPOTENCY_TABLE,m as migrateIdempotency,L as readIdempotent,I as trimIdempotent,N as writeIdempotent};
|
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
import{runSql as e,decodeJsonColumn as c,orNull as T}from"./runDrizzle-C3n5gJsk.mjs";const r="__lunora_mail",l=500,_=256*1024,i=d=>d!==void 0&&d.length>_?`${d.slice(0,_)}
|
|
2
|
-
… [truncated by the dev mail catcher]`:d,E=d=>d===void 0?null:JSON.stringify(d),s=d=>{e(d,`CREATE TABLE IF NOT EXISTS "${r}" (
|
|
3
|
-
id TEXT PRIMARY KEY,
|
|
4
|
-
captured_at INTEGER NOT NULL,
|
|
5
|
-
from_addr TEXT,
|
|
6
|
-
to_addrs TEXT NOT NULL,
|
|
7
|
-
cc_addrs TEXT,
|
|
8
|
-
bcc_addrs TEXT,
|
|
9
|
-
reply_to TEXT,
|
|
10
|
-
subject TEXT NOT NULL,
|
|
11
|
-
html TEXT,
|
|
12
|
-
body_text TEXT,
|
|
13
|
-
headers TEXT
|
|
14
|
-
)`)},m=(d,t,o)=>{s(d);const a=crypto.randomUUID();return e(d,`INSERT INTO "${r}" (id, captured_at, from_addr, to_addrs, cc_addrs, bcc_addrs, reply_to, subject, html, body_text, headers)
|
|
15
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,a,o,T(t.from),JSON.stringify(t.to),E(t.cc),E(t.bcc),T(t.replyTo),t.subject,T(i(t.html)),T(i(t.text)),E(t.headers)),e(d,`DELETE FROM "${r}"
|
|
16
|
-
WHERE id NOT IN (
|
|
17
|
-
SELECT id FROM "${r}" ORDER BY captured_at DESC, id DESC LIMIT ?
|
|
18
|
-
)`,l),{id:a}},n=(d,t={})=>{s(d);const o=Math.min(Math.max(t.limit??50,1),l);return{entries:e(d,`SELECT * FROM "${r}" ORDER BY captured_at DESC, id DESC LIMIT ?`,o).toArray().map(a=>({bcc:c(a.bcc_addrs),capturedAt:a.captured_at,cc:c(a.cc_addrs),from:a.from_addr??void 0,headers:c(a.headers),html:a.html??void 0,id:a.id,replyTo:a.reply_to??void 0,subject:a.subject,text:a.body_text??void 0,to:c(a.to_addrs)??a.to_addrs}))}},p=d=>(s(d),e(d,`DELETE FROM "${r}"`),{cleared:!0});export{l as MAIL_RETENTION,r as MAIL_TABLE,_ as MAX_BODY_CHARS,p as clearCapturedMail,s as ensureMailTable,n as readCapturedMail,m as recordCapturedMail};
|