@lunora/shard-engine 1.0.0-alpha.80 → 1.0.0-alpha.82
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.d.mts +40 -3
- package/dist/index.d.ts +40 -3
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/ADMIN_FUNCTIONS-BdZ3gTHm.mjs +1 -0
- package/dist/packem_shared/{AGG_COUNT-TzzFAsyw.mjs → AGG_COUNT-B7izQELK.mjs} +1 -1
- package/dist/packem_shared/{AUDIT_LOG_TABLE-ONxmEAIz.mjs → AUDIT_LOG_TABLE-CEdsC6vT.mjs} +1 -1
- package/dist/packem_shared/{CDC_LOG_TABLE-DXEAcmsr.mjs → CDC_LOG_TABLE-BFbP2eiJ.mjs} +1 -1
- package/dist/packem_shared/{CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs → CLIENT_WATERMARK_TABLE-BdKYbah0.mjs} +1 -1
- package/dist/packem_shared/{COMMIT_SEQ_FIELD-BUdOMG5y.mjs → COMMIT_SEQ_FIELD-D6uMUaiR.mjs} +1 -1
- package/dist/packem_shared/{DATA_MIGRATION_STATE_TABLE-BwFz6NTT.mjs → DATA_MIGRATION_STATE_TABLE-BbDr6pc7.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_MAX_RELATION_KEYS-XESc7TiB.mjs → DEFAULT_MAX_RELATION_KEYS-BfAQvZT8.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_MAX_RELAYS-Ng4SyJ7k.mjs → DEFAULT_MAX_RELAYS-DG9iXjzF.mjs} +1 -1
- package/dist/packem_shared/{DurableStreamRunner-rTYp4v03.mjs → DurableStreamRunner-Cliu09-j.mjs} +1 -1
- package/dist/packem_shared/{GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs → GLOBAL_SHAPE_SNAPSHOT_TABLE-wWaEWj5f.mjs} +1 -1
- package/dist/packem_shared/{IDEMPOTENCY_TABLE-DOpm_oMF.mjs → IDEMPOTENCY_TABLE-DKrXVEUe.mjs} +1 -1
- package/dist/packem_shared/{MAIL_RETENTION-DGAQTHHs.mjs → MAIL_RETENTION-DXpGFjOt.mjs} +1 -1
- package/dist/packem_shared/NotUniqueError-D0LwVtXI.mjs +1 -0
- package/dist/packem_shared/{QUEUE_TABLE-s7QJZvBz.mjs → QUEUE_TABLE-D-cL1NPj.mjs} +1 -1
- package/dist/packem_shared/{REACTOR_STATE_TABLE-QPRFyxMS.mjs → REACTOR_STATE_TABLE-CBHASjH9.mjs} +1 -1
- package/dist/packem_shared/{SCHEDULE_OUTBOX_TABLE-CD_UjYVx.mjs → SCHEDULE_OUTBOX_TABLE-BHpxtEy4.mjs} +1 -1
- package/dist/packem_shared/{SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs → SCHEMA_HISTORY_MAX_VERSIONS-CXznJRUG.mjs} +1 -1
- package/dist/packem_shared/SEARCH_STATE_TABLE-D_KJ04Bn.mjs +1 -0
- package/dist/packem_shared/{SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs → SHAPE_POKE_CURSOR_TABLE-Bbpou9XZ.mjs} +1 -1
- package/dist/packem_shared/VECTOR_BACKFILL_MAX_PAGES-C-KZJbgA.mjs +1 -0
- package/dist/packem_shared/{appendStreamChunk-C1Ok4b6J.mjs → appendStreamChunk-pPeR5nbF.mjs} +1 -1
- package/dist/packem_shared/{archiveCdcSegment-E_R_b5Qz.mjs → archiveCdcSegment-C7taIEpg.mjs} +1 -1
- package/dist/packem_shared/backfillAggregateIndexes-D-S4qiCu.mjs +1 -0
- package/dist/packem_shared/{buildReprojectionMigration-DNjOe6AP.mjs → buildReprojectionMigration-DDZhSO95.mjs} +1 -1
- package/dist/packem_shared/{buildShapeDiff-CnCHKdCw.mjs → buildShapeDiff-Bd5nLaY8.mjs} +1 -1
- package/dist/packem_shared/{clearMemoryTables-BGbmag2i.mjs → clearMemoryTables-C5Wivufe.mjs} +1 -1
- package/dist/packem_shared/{computeRankPage-pTaG_r9F.mjs → computeRankPage-CQewnemg.mjs} +1 -1
- package/dist/packem_shared/createCompanionSync-BwWcSwvy.mjs +1 -0
- package/dist/packem_shared/{createReplicaLink-CUnl1y_Q.mjs → createReplicaLink-CTyOjpjh.mjs} +1 -1
- package/dist/packem_shared/{ctx-db-relay-shapes-Bg5YYnmN.mjs → ctx-db-relay-shapes-BcgjOtG1.mjs} +1 -1
- package/dist/packem_shared/ctx-db-search-state-fIiMVPXO.mjs +1 -0
- package/dist/packem_shared/{defineEngineContractSuite-BS0T_g0Z.mjs → defineEngineContractSuite-BD9v9a97.mjs} +1 -1
- package/dist/packem_shared/{do-sql-kpl5Kt1j.mjs → do-sql-BSoH-O04.mjs} +1 -1
- package/dist/packem_shared/{exportShardRows-1TkeNJI6.mjs → exportShardRows-DmFKSzLZ.mjs} +1 -1
- package/dist/packem_shared/fts-companion-B7jllLhZ.mjs +1 -0
- package/dist/packem_shared/ftsCompanionDdl-BKeIk9KQ.mjs +1 -0
- package/dist/packem_shared/{isSoftDeleted-DIMlSsdB.mjs → isSoftDeleted-CCDHCtX3.mjs} +1 -1
- package/dist/packem_shared/{materializeExternalRows-B1623YXA.mjs → materializeExternalRows-j_8glxcE.mjs} +1 -1
- package/dist/packem_shared/runDrizzle-CfKnGpV2.mjs +1 -0
- package/dist/packem_shared/runShardMigrations-o-qjyKt5.mjs +5 -0
- package/dist/packem_shared/{selectExpiredIds-D5DEpBbi.mjs → selectExpiredIds-Do1q2HQr.mjs} +1 -1
- package/dist/packem_shared/{selectShapeMembers-B8gTOeOB.mjs → selectShapeMembers-Cp98I-ot.mjs} +1 -1
- package/package.json +2 -2
- package/dist/packem_shared/ADMIN_FUNCTIONS-BjpFlIz5.mjs +0 -1
- package/dist/packem_shared/NotUniqueError-1OMgp1sA.mjs +0 -1
- package/dist/packem_shared/SEARCH_STATE_TABLE-D5mnK5kX.mjs +0 -1
- package/dist/packem_shared/backfillAggregateIndexes-DTemznr7.mjs +0 -1
- package/dist/packem_shared/createCompanionSync-Cb567rkq.mjs +0 -1
- package/dist/packem_shared/ctx-db-companions-DsNfXSbb.mjs +0 -1
- package/dist/packem_shared/ctx-db-search-state-ruTuCsxa.mjs +0 -1
- package/dist/packem_shared/runDrizzle-2ULFQR_k.mjs +0 -1
- package/dist/packem_shared/runShardMigrations-DGlaC68E.mjs +0 -5
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as $}from"@lunora/errors";import{D as dt}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{S as En,l as Fe,h as Sn}from"./fts-companion-B7jllLhZ.mjs";import{sql as i}from"drizzle-orm";import{d as _n}from"./wire-codec-C-FpWm52.mjs";import{stableWireKey as At}from"./stableWireKey-D2US4k_J.mjs";import{throwingScheduler as Rn,aggregateSqlFunction as qe,normalizeCountArgument as Tn}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as Je,encodeAggregateKey as Ye,readAggregateValue as Xe}from"./aggregateTableName-C7o-gpms.mjs";import{mergeWhere as z,CountRlsUnsupportedError as Ze,selectIndexForGroupBy as vn,selectIndexForCount as An,selectIndexForAggregate as In}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Cn,searchIndexCoversTable as xn}from"./backfillAggregateIndexes-D-S4qiCu.mjs";import{backfillAggregateIndexes as Ur,backfillRankIndexes as Gr,backfillSearchIndexes as Or}from"./backfillAggregateIndexes-D-S4qiCu.mjs";import{appendCdcChange as bn,readCdcDocAtOrBefore as Mn}from"./CDC_LOG_TABLE-BFbP2eiJ.mjs";import{CDC_LOG_TABLE as Nr,applyCdcChanges as jr,bumpCdcEpoch as Kr,cdcCanVouchFor as Qr,cdcForkedError as Vr,cdcSeqLeavingRows as zr,cdcTouchesTables as Jr,cdcTrimmedError as Yr,compactCdcDocs as Xr,cursorBelowRetainedFloor as Zr,minCdcReplayableSeq as ei,minCdcSeq as ti,readCdcChangeKeys as ni,readCdcChanges as oi,readCdcCursor as ri,readCdcEpoch as ii,trimCdcChanges as si}from"./CDC_LOG_TABLE-BFbP2eiJ.mjs";import{allocateCommitSeq as Dn,COMMIT_SEQ_FIELD as kn}from"./COMMIT_SEQ_FIELD-D6uMUaiR.mjs";import{createCompanionSync as Ln}from"./createCompanionSync-BwWcSwvy.mjs";import{isMemoryTable as It}from"./clearMemoryTables-C5Wivufe.mjs";import{computeRankPage as Ct}from"./computeRankPage-CQewnemg.mjs";import{SCAN_DEP as O}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as N,runSql as _e}from"./runDrizzle-CfKnGpV2.mjs";import{D as ne,k as ce,r as le,b as Be,A as et,a as We,e as X,o as Fn,t as Yt,j as Ge,q as xt,i as qn,h as Xt,g as Bn}from"./do-sql-BSoH-O04.mjs";import{renderSql as Zt,unionAll as lt,WORKERD_SQLITE_LIMITS as en,sqliteInList as Wn}from"./param-DlozcSQu.mjs";import{coveringGeohashes as Pn,boundingBoxGeohashes as Un,haversineMeters as Gn,pointInBoundingBox as On}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Hn}from"./NotFoundError-BhF7FeFr.mjs";import{softDeleteScope as de,normalizeOrderKeys as it,uniqueIndexFields as tn,equalityPinnedFields as Nn,buildSeekWhere as nn,decodeCursor as st,applySelect as bt,encodeCursor as ct,tiebreakDirectionFor as on,buildSeekBeforeWhere as jn}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{rankTableName as Mt,sortColumnName as Dt,resolveRankPartition as Kn,encodePartitionKey as Qn,RANK_TIEBREAK as Vn,rankPivotConditionSql as zn}from"./RANK_TIEBREAK-D5xNdzB3.mjs";import{UNVOUCHABLE_DEP as kt}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as Jn,buildIndexRange as Yn}from"./buildIndexRange-DvN8Qj8e.mjs";import{deriveRelationEdges as Xn,findRelated as Zn}from"./RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs";import{assertFlatPredicate as tt,resolveRelationPredicates as Lt}from"./DEFAULT_MAX_RELATION_KEYS-BfAQvZT8.mjs";import{runRowValidators as nt,resolveWith as Ft,relationHooks as qt,applyOnDelete as eo,fanOutScalarCounts as to}from"./applyOnDelete-7JZ4vR9r.mjs";import{guardWriter as no}from"./RLS_UNWRAP_SYMBOL-BwwTbz3Q.mjs";import{quoteIdentifier as Re}from"./quoteIdentifier-CObIFRhb.mjs";import{m as oo}from"./sql-projection-D3qdaItY.mjs";import{createSystemReader as ro}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as Ee}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as io}from"./hasTrigger-CjlwI4le.mjs";import{c as te,t as He,r as Oe,j as Se,i as Bt}from"./where-sql-x1YKldcq.mjs";import{CLIENT_WATERMARK_TABLE as ai,advanceClientWatermark as di,migrateClientWatermark as li,readClientWatermark as ui}from"./CLIENT_WATERMARK_TABLE-BdKYbah0.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as hi,deleteGlobalShapeSnapshot as wi,deleteGlobalShapeSnapshotsForConnection as pi,migrateGlobalShapeSnapshot as gi,readGlobalShapeSnapshot as $i,writeGlobalShapeSnapshot as yi}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-wWaEWj5f.mjs";import{IDEMPOTENCY_TABLE as Ei,readIdempotent as Si,trimIdempotent as _i,writeIdempotent as Ri}from"./IDEMPOTENCY_TABLE-DKrXVEUe.mjs";import{runShardMigrations as vi}from"./runShardMigrations-o-qjyKt5.mjs";import{S as Ii}from"./ctx-db-search-state-fIiMVPXO.mjs";import{selectShapeMembers as xi,selectShapeRows as bi}from"./selectShapeMembers-Cp98I-ot.mjs";import{serializeSqlValue as oe}from"./serializeSqlValue-BEMMYX1n.mjs";const so=n=>{const r=atob(n),o=Uint8Array.from(r,a=>a.codePointAt(0)??0);return new TextDecoder().decode(o)},co=()=>new $("BAD_REQUEST","invalid cursor"),Wt=16,Pt=8,Y=1024,ut=(n,r)=>r.query(n),ao=(n,r)=>{if(n.length===0)return 0;let o=0;for(const[a,s]of r.entries()){const w=a===r.length-1;let y=0;for(const R of n)(w?R.startsWith(s):R===s)&&(y+=1);if(y===0)return 0;o+=y}return o},lo=(n,r)=>{if(!r)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",a=(o.codePointAt(0)??0)+1;if(a>=55296&&a<=57343||a>1114111)return{exact:!0,lower:n,upper:n};const s=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:s+String.fromCodePoint(a)}},uo=(n,r,o)=>{const a={eq:(s,w)=>{if(!n.definition.filterFields?.includes(s))throw new $("INTERNAL",`field "${s}" is not a filter field of search index "${n.indexName}" on table "${r}"`);if(n.filters.length>=Pt)throw new $("BAD_REQUEST",`search index "${n.indexName}" on table "${r}": at most ${String(Pt)} .eq() filters are supported per search query`);return n.filters.push({field:s,value:w}),a},search:(s,w)=>{const y=n;if(s!==y.definition.field)throw new $("INTERNAL",`search index "${y.indexName}" on table "${r}" indexes "${y.definition.field}", not "${s}"`);const R=ut(w,o).length;if(R>Wt)throw new $("BAD_REQUEST",`search index "${y.indexName}" on table "${r}": at most ${String(Wt)} search terms are supported (got ${String(R)})`);return y.field=s,y.query=w,y.hasQuery=!0,a}};return a},fo=n=>{if(n.length>Y)throw new $("BAD_REQUEST",`more than ${String(Y)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},ho=n=>Math.min(n.offset+n.numItems+1,Y),wo=n=>btoa(`search:${String(n)}`),po=n=>{let r;try{r=so(n)}catch{return}if(!r.startsWith("search:"))return;const o=Number(r.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},go=n=>{if(typeof n.endCursor=="string")throw new $("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new $("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const r=Math.max(0,Math.floor(n.numItems)),o=n.cursor?po(n.cursor):0;if(o===void 0)throw co();if(o+r>=Y)throw new $("BAD_REQUEST",`search pagination reaches the ${String(Y)}-document limit (offset ${String(o)} + ${String(r)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,Y-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:o}},$o=(n,r)=>{const o=r.offset+r.numItems,a=r.numItems>0&&n.length>o;return{continueCursor:a?wo(o):null,isDone:!a,page:n.slice(r.offset,o)}},yo=n=>{if(n===void 0)return Y+1;if(!Number.isFinite(n))return Y;const r=Math.max(0,Math.floor(n));if(r>Y)throw new $("BAD_REQUEST",`search returns at most ${String(Y)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},Ne=n=>{const r=new Map;return o=>{const a=r.get(o);if(a!==void 0)return a;const s=n(Re(o));return r.set(o,s),s}},ue=Re(ne),mo=Ne(n=>`INSERT INTO ${n} (id, _creationTime, ${ue}) VALUES (?, ?, ?)`),Ut=Ne(n=>`UPDATE ${n} SET ${ue} = ? WHERE id = ? AND ${ue} = ?`),Eo=Ne(n=>`UPDATE ${n} SET _creationTime = ?, ${ue} = ? WHERE id = ? AND ${ue} = ?`),So=Ne(n=>`DELETE FROM ${n} WHERE id = ? AND ${ue} = ?`),_o="SELECT changes() AS changed",Gt=new Map,Ro="",To=n=>{const r=JSON.stringify(n),o=Gt.get(r);if(o!==void 0)return o;const a=n.map(w=>i`SELECT ${i.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${i.identifier(ne)} FROM ${i.identifier(w)} WHERE id = ${Ro}`),{sql:s}=Zt("sqlite",i`${lt(a)} LIMIT 1`);return Gt.set(r,s),s},vo=(n,r)=>r.map(()=>n),Ao=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Io=n=>{if(!Ao.test(n))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},Ot=50,rn=500,Pe=Math.floor(en.boundParams/3),ye=en.boundParams,Co=128,ae=(n,r,o)=>{const a=r??rn;if(n>a)throw new $("BATCH_LIMIT_EXCEEDED",`${o}: batch of ${String(n)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},xo=n=>{const r={eq:(o,a)=>(n.sqlConditions.push({comparator:"=",field:o,value:a}),r),gt:(o,a)=>(n.sqlConditions.push({comparator:">",field:o,value:a}),r),gte:(o,a)=>(n.sqlConditions.push({comparator:">=",field:o,value:a}),r),lt:(o,a)=>(n.sqlConditions.push({comparator:"<",field:o,value:a}),r),lte:(o,a)=>(n.sqlConditions.push({comparator:"<=",field:o,value:a}),r)};return r},bo=n=>Math.max(n,Y),sn=(n,r)=>{const o=n.filters.map(a=>i`${X(a.field)} = ${oe(a.value)}`);return r&&o.push(r),o},Mo=(n,r,o,a,s)=>{const w=ut(o.query,dt(o.definition.language));if(w.length===0)return[];const y=En(r,o.indexName),R=`${y}__vocab`,_=w.length-1,k=w.map((q,F)=>{const W=lo(q,F===_),x=W.exact?i`${i.identifier("term")} = ${W.lower}`:i`${i.identifier("term")} >= ${W.lower} AND ${i.identifier("term")} < ${W.upper}`;return i`SELECT ${i.identifier("doc")}, ${i.raw(String(F))} AS ${i.identifier("__term__")}, COUNT(*) AS ${i.identifier("__n__")} FROM ${i.identifier(R)} WHERE ${x} GROUP BY ${i.identifier("doc")}`}),g=w.map((q,F)=>i`SUM(CASE WHEN u.${i.identifier("__term__")} = ${i.raw(String(F))} THEN u.${i.identifier("__n__")} ELSE 0 END)`),v=i`SELECT f.${i.identifier(Fe)} AS ${i.identifier(Fe)}, ${i.join(g,i` + `)} AS ${i.identifier("__score__")} FROM (${lt(k)}) u JOIN ${i.identifier(y)} f ON f.rowid = u.${i.identifier("doc")} GROUP BY f.${i.identifier(Fe)} HAVING ${i.join(g.map(q=>i`${q} > 0`),i` AND `)}`,T=sn(o,s);let L=i`SELECT m.id, m._creationTime, m.${i.identifier(ne)}, s.${i.identifier("__score__")} AS ${i.identifier("__score__")} FROM (${v}) s JOIN ${i.identifier(r)} m ON m.id = s.${i.identifier(Fe)}`;T.length>0&&(L=i`${L} WHERE ${i.join(T,i` AND `)}`),L=i`${L} ORDER BY s.${i.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${i.raw(String(a))}`;const H=[];for(const q of N(n,L)){const F=Xt(q);if(F){const W=q.__score__;H.push({document:F,score:typeof W=="number"?W:Number(W??0)})}}return H},Do=(n,r,o,a,s)=>{const w=dt(o.definition.language),y=ut(o.query,w);if(y.length===0)return[];const R=sn(o,s);let _=i`SELECT id, _creationTime, ${i.identifier(ne)} FROM ${i.identifier(r)}`;R.length>0&&(_=i`${_} WHERE ${i.join(R,i` AND `)}`),_=i`${_} ORDER BY _creationTime DESC, id ASC LIMIT ${i.raw(String(bo(a)))}`;const k=N(n,_).toArray(),g=[];for(const v of k){const T=Xt(v);if(!T)continue;const L=ao(Sn(T,o.definition),y);L>0&&g.push({creationTime:typeof T._creationTime=="number"?T._creationTime:0,doc:T,id:typeof T._id=="string"?T._id:"",score:L})}return g.sort((v,T)=>T.score-v.score||T.creationTime-v.creationTime||v.id.localeCompare(T.id)),g.slice(0,a).map(v=>({document:v.doc,score:v.score}))},ot=(n,r,o,a)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new $("BAD_REQUEST",`geo index "${a}" on table "${o}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},ko=(n,r)=>{const o=n,a={near:(s,w)=>{if(o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(ot(s,".near() point",r,o.indexName),!Number.isFinite(w)||w<=0)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return o.near={point:{lat:s.lat,lng:s.lng},radiusMeters:w},a},within:s=>{if(o.near)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(ot(s.sw,".within() sw corner",r,o.indexName),ot(s.ne,".within() ne corner",r,o.indexName),s.sw.lat>s.ne.lat)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(s.sw.lng>s.ne.lng)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return o.within={ne:{lat:s.ne.lat,lng:s.ne.lng},sw:{lat:s.sw.lat,lng:s.sw.lng}},a}};return a},Lo=(n,r)=>{const o=n[r];if(o===null||typeof o!="object")return;const{lat:a,lng:s}=o;return typeof a=="number"&&typeof s=="number"?{lat:a,lng:s}:void 0},Fo=(n,r)=>{const o=Lo(n,r.definition.field);if(!o)return;const a=typeof n._creationTime=="number"?n._creationTime:0;if(r.near){const s=Gn(r.near.point,o);return s<=r.near.radiusMeters?{creationTime:a,distance:s}:void 0}return On(o,r.within)?{creationTime:a,distance:0}:void 0},qo=(n,r,o,a)=>{if(!o.near&&!o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const s=o.near?Pn(o.near.point,o.near.radiusMeters):Un(o.within),w=Bn(r,o.indexName),y=s.map(v=>i`(g.${i.identifier("__geohash__")} >= ${v} AND g.${i.identifier("__geohash__")} < ${`${v}{`})`),R=[i`(${i.join(y,i` OR `)})`];a&&R.push(a);const _=i`SELECT m.id, m._creationTime, m.${i.identifier(ne)} FROM ${i.identifier(w)} g JOIN ${i.identifier(r)} m ON m.id = g.${i.identifier("__id__")} WHERE ${i.join(R,i` AND `)}`,k=N(n,_).toArray(),g=[];for(const v of k){const T=le(v),L=T?Fo(T,o):void 0;T&&L&&g.push({creationTime:L.creationTime,distance:L.distance,doc:T})}return g.sort((v,T)=>v.distance-T.distance||T.creationTime-v.creationTime),g},cn=(n,r,o,a)=>{const s=[];for(const w of n)if(r.every(y=>y(a(w)))&&(s.push(w),typeof o=="number"&&s.length>=o))break;return s},Bo=(n,r,o,a,s,w=()=>{})=>{const y=o.within!==void 0,R=qo(n,r,o,s).map(_=>({distanceMeters:y?null:_.distance,document:_.doc}));return w(R.length),typeof a=="number"?R.slice(0,Math.max(0,Math.floor(a))):R},an=(n,r,o,a,s,w=()=>{})=>{const{geo:y}=o;if(!y)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const R=o.inMemoryFilters.length>0,_=Bo(n,r,y,R?void 0:s,a,w);return R?cn(_,o.inMemoryFilters,s,k=>k.document):_},dn=(n,r,o,a)=>{const s=`SELECT id, _creationTime, ${Re(ne)} FROM ${Re(n)}`,w=`ORDER BY ${o}${a===void 0?"":` LIMIT ${String(a)}`}`;return r===void 0?Oe(`${s} ${w}`):Se(`${s} WHERE `,r,` ${w}`)},Wo=(n,r,o,a,s,w=()=>{})=>an(n,r,o,a,s,w).map(y=>y.document),Po=(n,r,o,a,s,w,y=()=>{})=>{const R=[];for(const v of o.sqlConditions)R.push(i`${X(v.field)} ${i.raw(v.comparator)} ${oe(v.value)}`);a&&R.push(a);let _=i`SELECT id, _creationTime, ${i.identifier(ne)} FROM ${i.identifier(r)}`;R.length>0&&(_=i`${_} WHERE ${i.join(R,i` AND `)}`),_=i`${_} ORDER BY ${s}`,typeof w=="number"&&o.inMemoryFilters.length===0&&(_=i`${_} LIMIT ${i.raw(String(Math.max(0,Math.floor(w))))}`);const k=N(n,_).toArray();y(k.length);const g=[];for(const v of k){const T=le(v);if(T&&o.inMemoryFilters.every(L=>L(T))&&(g.push(T),typeof w=="number"&&g.length>=w))break}return g},me={fieldRef:X,serialize:oe},ln=(n,r)=>{const o=r===void 0?void 0:n.shape[r];return o!==void 0&&oo(o)},Ht=(n,r)=>r.some(o=>ln(n,o)),Nt=(n,r,o)=>{if(ln(n,r))throw new $("BAD_REQUEST",`${o}: "${r}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},ft={fieldRef:n=>Oe(Ge(n)),serialize:oe},Uo=n=>{let r=0;const o=[],a={fieldRef:s=>Oe(Ge(s)),relationExists:s=>{const{childWhere:w,negated:y,parentTable:R,relation:_}=s,k=`__rel_${String(r)}`,g=o.at(-1)??R;r+=1,n(_.table,O);const v=_.kind==="one"?_.field:_.references,T=_.kind==="one"?_.references:_.field,L=Oe(`${xt(k,T)} = ${xt(g,v)}`);o.push(k);const H=te(w,a,He);o.pop();const q=H===void 0?L:Se(L," AND ",H),F=Se("EXISTS (SELECT 1 FROM ",Bt(_.table)," AS ",Bt(k)," WHERE ",q,")");return y?Se("NOT ",F):F},serialize:oe};return a},un=n=>{const r=n.map(o=>`${Ge(o.field)} ${o.direction==="desc"?"DESC":"ASC"}`);return n.some(o=>o.field==="_id"||o.field==="id")||r.push(`${Ge("id")} ${on(n)==="desc"?"DESC":"ASC"}`),r.join(", ")},Go=n=>{const r=n.map(o=>i`${X(o.field)} ${i.raw(o.direction==="desc"?"DESC":"ASC")}`);return n.some(o=>o.field==="_id"||o.field==="id")||r.push(i`${X("id")} ${i.raw(on(n)==="desc"?"DESC":"ASC")}`),i.join(r,i`, `)},Oo={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},fn=n=>new Set(n.sqlConditions.filter(r=>r.comparator==="=").map(r=>r.field)),Ho=n=>{const r=fn(n);let o=0;for(;o<n.indexFields.length&&r.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},hn=(n,r)=>{const o=n.order,a=Ho(n),{shape:s}=r;return a.length>0?it(a.map(w=>({[w]:o})),s,{pinned:fn(n),uniqueBy:tn(r.indexes,s)}):it([{_creationTime:o}],s)},No=(n,r,o,a)=>{const s=n.sqlConditions.map(w=>({[w.field]:{[Oo[w.comparator]??"eq"]:w.value}}));if(o&&s.push(nn(r,st(o))),a&&s.push(jn(r,st(a))),s.length!==0)return s.length===1?s[0]:{AND:s}},jo=(n,r,o)=>{const a=[];for(const s of n){const w=le(s);if(w&&r.every(y=>y(w))&&(a.push(w),o!==void 0&&a.length>o))break}return a},Ko=(n,r,o,a,s,w,y=()=>{})=>{const R=Math.max(0,Math.floor(s.numItems)),_=hn(a,o),k=typeof s.endCursor=="string",g=te(No(a,_,s.cursor,s.endCursor),ft,He),v=w&&g?Se(g," AND ",w):w??g,T=a.inMemoryFilters.length>0,L=dn(r,v,un(_),T||k?void 0:R+1),H=_e(n,L.text,...L.params).toArray();y(H.length);const q=jo(H,a.inMemoryFilters,T||k?void 0:R);if(k){const j=q.length>=2?q[Math.floor(q.length/2)-1]:void 0;return{continueCursor:s.endCursor??null,isDone:!0,page:q,splitCursor:j?ct(j,_):null}}const F=q.length>R,W=F?q.slice(0,R):q,x=W.at(-1);return{continueCursor:F&&x?ct(x,_):null,isDone:!F,page:W}};class Qo extends ${constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Vo=/\s/u,zo=String.fromCodePoint(0),jt=(n,r,o)=>{if(!n.tables[r])throw new $("INTERNAL",`unknown table: ${r}`);return typeof o!="string"||o.length===0||Vo.test(o)||o.includes(zo)?null:o},Jo=(n,r,o,a=()=>{},s=()=>{},w=()=>{})=>{const y=r.tables[o];if(!y)throw new $("INTERNAL",`unknown table: ${o}`);const R=de(y.softDeleteMode,void 0),_=R?te(R,me):void 0,k=R?te(R,ft,He):void 0,g={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let v=0;const T=E=>{const{search:C}=g;if(!C)throw new $("INTERNAL","runSearchFetch called without a staged search");Cn(n,o,y);const b=g.inMemoryFilters.length>0,M=yo(b?void 0:E),K=qn(n);if(K&&!xn(n,o,C.definition))throw new $("SEARCH_INDEX_BUILDING",`search index "${C.indexName}" on table "${o}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const re=K?Mo(n,o,C,M,_):Do(n,o,C,M,_);return b?(v=re.length,cn(re,g.inMemoryFilters,E,Te=>Te.document)):(E===void 0&&fo(re),re)},L=E=>T(E).map(C=>C.document),H=E=>{const C=go(E);return $o(L(ho(C)),C)},q=()=>Go(hn(g,y)),F=()=>{if(g.search||g.geo||g.indexName===void 0){s(void 0);return}s(Yn(o,g.indexName,g.indexFields,g.sqlConditions,oe))},W=E=>{F();let C=0;const b=(()=>{if(g.search){const M=L(E);return C=v,M}return g.geo?Wo(n,o,g,_,E,M=>{C=M}):Po(n,o,g,_,q(),E,M=>{C=M})})();return w(Math.max(C,b.length)),b},x=()=>{if(!g.search&&!g.geo)throw new $("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);F();let E=0;const C=(()=>{if(g.search){const b=T(void 0);return E=v,b}return an(n,o,g,_,void 0,b=>{E=b})})();return w(Math.max(E,C.length)),C},j={async*[Symbol.asyncIterator](){if(g.search){yield*W(void 0);return}const E=[...g.inMemoryFilters];let C;g.inMemoryFilters=[];try{for(;;){const b=await j.paginate({cursor:C??null,numItems:Co});for(const M of b.page)E.every(K=>K(M))&&(yield M);if(b.isDone||b.continueCursor===null)return;C=b.continueCursor}}finally{g.inMemoryFilters=E}},async collect(){return W(void 0)},async collectWithScores(){return x()},filter(E){return g.inMemoryFilters.push(E),j},async first(){return W(g.inMemoryFilters.length>0?void 0:1)[0]??null},order(E){return g.order=E==="desc"?"desc":"asc",j},async paginate(E){let C=0;if(F(),g.search){const M=H(E);return w(M.page.length),M}if(g.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const b=Ko(n,o,y,g,E,k,M=>{C=M});return w(Math.max(C,b.page.length)),b},async take(E){return W(E)},async unique(){const E=W(g.inMemoryFilters.length>0?void 0:2);if(E.length>1)throw new Qo(`unique() on table "${o}" matched ${String(E.length)} documents; expected at most one`);return E[0]??null},withGeoIndex(E,C){const b=(y.geoIndexes??[]).find(K=>K.name===E);if(!b)throw new $("INTERNAL",`unknown geo index "${E}" on table "${o}"`);a(o,E,"geo");const M={definition:b,indexName:E};if(g.geo=M,C(ko(M,o)),!M.near&&!M.within)throw new $("INTERNAL",`geo index "${E}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return j},withIndex(E,C){const b=y.indexes.find(M=>M.name===E);if(!b)throw new $("INTERNAL",`unknown index "${E}" on table "${o}"`);return a(o,E,"index"),g.indexName=E,g.indexFields=b.fields,C&&C(xo(g)),j},withSearchIndex(E,C){const b=(y.searchIndexes??[]).find(K=>K.name===E);if(!b)throw new $("INTERNAL",`unknown search index "${E}" on table "${o}"`);a(o,E,"search");const M={definition:b,field:b.field,filters:[],hasQuery:!1,indexName:E,query:""};if(g.search=M,C(uo(M,o,dt(b.language))),!M.hasQuery)throw new $("INTERNAL",`search index "${E}" on table "${o}" requires a .search(field, query) call`);return j}};return j},Kt=(n,r,o)=>{const a={...r};for(const[s,w]of Yt(n)){if(w.serverDefault){a[s]=w.serverDefault({auth:o});continue}a[s]===void 0&&(w.defaultFn?a[s]=w.defaultFn():"defaultValue"in w&&(a[s]=w.defaultValue))}return a},Qt=(n,r,o,a)=>{const s=o;for(const[w,y]of Yt(n)){if(y.serverDefault){w in r&&(s[w]=y.serverDefault({auth:a}));continue}y.onUpdateFn&&!(w in r)&&(s[w]=y.onUpdateFn())}},Vt=(n,r)=>{for(const o of Object.keys(r))if(r[o]===void 0)throw new $("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},zt=["_commitSeq","_creationTime","_id"],rt=n=>zt.some(r=>r in n)?Object.fromEntries(Object.entries(n).filter(([r])=>!zt.includes(r))):n,Yo=/unique constraint failed/i,Xo=n=>n instanceof Error&&Yo.test(n.message),Zo=/string or blob too big/iu,er=(n,r)=>{if(!(!(n instanceof Error)||!Zo.test(n.message)))throw new $("PAYLOAD_TOO_LARGE",`document is too large to store in "${r}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},at=(n,r,o,a)=>{try{_e(n,o,...a)}catch(s){throw Xo(s)?new Ee(`unique constraint violation on "${r}"`,"unique"):(er(s,r),s)}},Ue=(n,r,o,a)=>{if(at(n,r,o,a),_e(n,_o).one().changed===0)throw new Ee(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},Jt=(n,r,o,a,s,w,y)=>{const R=[];for(let v=0;v<o.length+1;v+=1){const T=o[v],L=a[v],H=L?.direction==="desc"?"desc":"asc",q=T===void 0||L===void 0?i`${i.identifier(Vn)} < ${y}`:zn(T,w[v],H,!1);if(q===void 0)continue;const F=[];for(let x=0;x<v;x+=1)F.push(i`${i.identifier(o[x])} IS ${w[x]}`);F.push(q);const[W]=F;R.push(F.length===1&&W!==void 0?W:i`(${i.join(F,i` AND `)})`)}const _=R.length>0?i.join(R,i` OR `):i`1 = 0`,k=N(n,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${s} AND (${_})`).one(),g=N(n,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${s}`).one();return{before:k.c,total:g.c}},Br=n=>{const{baselineSeq:r,onStalePatchDropped:o}=n,{sql:a}=n,{schema:s}=n,w=n.broadcast??(()=>{}),y=Xn(s);let R;const _=()=>n.inTransaction?.()===!0,k=e=>s.tables[e]?.commitOrderedMode!==!0?{}:((R===void 0||!_())&&(R=Dn(a)),{[kn]:R}),g=(e,...t)=>{const c=s.tables[e]?.indexes;if(!c||c.length===0)return;const f=[];for(const h of t)h&&f.push(...Jn(c,h,oe));return f.length>0?f:void 0},{headroom:v}=n;let T=!1;const L=async e=>{const t=T;T=!0;try{return await e()}finally{T=t}},H=n.onRead??(()=>{}),q=e=>{It(s.tables[e])&&H(kt,kt)},F=n.onReadRange??(e=>{H(e.table,O)}),W=e=>{q(e.table),F(e)},x=(e,t)=>{t!==void 0&&t!==O&&!T&&v?.recordRead(1),q(e),H(e,t)},j=n.onIndexUse??(()=>{}),E=n.onWrite??(()=>{}),C=e=>{T||v?.recordWrite(e)},b=async e=>{C(e.doc),await E(e)},{cache:M}=n,K=n.clock??(()=>Date.now()),re=n.idGenerator??(()=>crypto.randomUUID()),Te=n.scheduler??Rn,{globalDb:fe}=n,ve=n.auth??{identity:null,userId:null},ht=n.cdc??!1,je=Te,wn=ro({scheduler:typeof je.list=="function"&&typeof je.get=="function"?je:void 0,storage:n.storage}),he=(e,t,c,f)=>{ht&&!It(s.tables[e])&&bn(a,K(),e,t,c,f)},pn=(e,t,c,f)=>{if(s.tables[e]?.dropStalePatchesMode!==!0||!ht)return!1;const h=r?.();if(h===void 0)return!1;const l=Mn(a,e,t,h);return l===void 0?!1:Object.keys(rt(c)).some(d=>At(l[d])!==At(f[d]))},ie=e=>s.tables[e]?.shardMode?.kind==="global",wt=(e,t)=>{if(ie(e)){if(!fe)throw new $("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return fe}return U},Ke=e=>wt(e,"cascade"),V=(e,t)=>{if(ie(e)){if(!fe)throw new $("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return fe}},pt=async(e,t,c,f,h)=>{h&&C(c);const l=await e.insert(t,c,f);return w({key:l,op:"insert",row:{...c,_id:l},table:t}),l},Qe=(e,t)=>wt(e,"relation load").findMany(e,t),gt=(e,t)=>(ie(e)&&x(e,O),Qe(e,t)),gn=e=>!ie(e.table),$t=n.relationExistsPushDown??"auto",yt=$t!=="never",{maxRelationKeys:mt}=n,Ae=(e,t,c)=>Lt(e,{fetcher:gt,maxRelationKeys:mt,relationBaseWhere:c,schema:s,tableName:t}),Et=async(e,t,c,f)=>{const h=V(e,"relation grouped count");if(h)return x(e,O),to((P,I)=>h.count(P,I),e,t,c,f);const l=s.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);x(e,O);const d=de(l.softDeleteMode,void 0),u={[t]:{in:c}},p=z(z(u,f),d),A=await Ae(p,e,void 0),m=te(A,me),D=X(t);let S=i`SELECT ${D} AS __fk__, COUNT(*) AS count FROM ${i.identifier(e)}`;m&&(S=i`${S} WHERE ${m}`),S=i`${S} GROUP BY ${D}`;const B=N(a,S).toArray();return new Map(B.map(P=>[P.__fk__,P.count]))};let Ie=0;const St=new Set;for(const[e,t]of Object.entries(s.tables))for(const c of Object.values(t.triggerMap??{}))St.add(`${e} ${c.timing} ${c.op}`);const Z=(e,t,c)=>St.has(`${e} ${t} ${c}`),ee=async(e,t,c)=>{if(Ie+=1,Ie>Ot)throw Ie-=1,new Ee(`trigger recursion exceeded ${String(Ot)} levels on "${c.table}" — check for a self-triggering write`,"trigger");try{await io({ctx:yn,event:c,op:t,schema:s,tableName:c.table,timing:e})}finally{Ie-=1}},{ensureBackfilledForTable:we,ensureBackfilledIndex:Ve,ensureRankBackfilled:ze,ensureRankBackfilledForTable:pe,syncAggregates:Ce,syncCompanionsForInsert:_t,syncGeo:xe,syncRanks:ge,syncSearch:be}=Ln({broadcast:w,indexKeysFor:(e,t)=>g(e,t),invalidateCache:(e,t,c)=>M?.invalidate(e,t,g(e,c)),recordCdc:he,schema:s,sql:a}),Rt=(e,t,c)=>{const{shardMode:f}=t;if(f?.kind==="shardBy"&&!(f.field!==void 0&&(c.partitionBy??[]).includes(f.field)))throw Object.assign(new Error(`rank index "${c.name}" on "${e}" partitions across shards (shard key "${f.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},Tt=e=>Object.entries(s.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),$e=e=>e===void 0||ie(e)?fe:void 0,se=(e,t)=>{const c=Tt(t);for(let f=0;f<c.length;f+=ye){const h=c.slice(f,f+ye),[l]=_e(a,To(h),...vo(e,h)).toArray();if(!l)continue;const d=l.__t__,u=le(l);if(typeof d!="string"||!u)return;const p=l[ne];return{docJson:typeof p=="string"?p:ce(p??{}),row:u,tableName:d}}},$n=(e,t)=>{const c=[...new Set(e)],f=new Map;if(c.length===0)return f;const h=Tt(t);for(let l=0;l<h.length;l+=ye){const d=h.slice(l,l+ye),u=Math.floor(ye/d.length),p=Wn(i`${i.identifier("id")}`,c,!1,u),A=d.map(m=>i`SELECT ${i.raw(`'${m.replaceAll("'","''")}'`)} AS __t__, id FROM ${i.identifier(m)} WHERE ${p}`);for(const m of N(a,lt(A))){const{id:D,__t__:S}=m;typeof S=="string"&&typeof D=="string"&&f.set(D,S)}}return f},vt={assertRankPartitionLocal:Rt,ensureRankBackfilled:ze,onRead:x,rowToDocument:le,schema:s,sql:a},U={system:wn,async aggregate(e,t){const c=V(e,"aggregate");if(c)return x(e,O),c.aggregate(e,t);const f=s.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);if(qe(t.op),t.op==="count")return U.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new $("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);x(e,O);const h=de(f.softDeleteMode,void 0),l=z(z(t.baseWhere,t.where),h),d=await Ae(l,e,t.relationBaseWhere),u=d!==l;if(f.aggregateIndexes&&!t.baseWhere&&!u&&(!h||Ht(f,[t.field]))){const P=In(f.aggregateIndexes,t.op,t.field,t.where);if(P){Ve(e,P.index);const I=Ye(P.index.by??[],P.key),Q=Je(e,P.index.name),J=N(a,i`SELECT ${Be} AS value, ${et} AS count FROM ${i.identifier(Q)} WHERE ${We} = ${I}`).toArray()[0];return Xe(t.op,J)}}Nt(f,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const p=te(d,me),A=qe(t.op),m=X(t.field);let D=i`SELECT ${i.raw(A)}(${m}) AS value FROM ${i.identifier(e)}`;p&&(D=i`${D} WHERE ${p}`);const B=N(a,D).toArray()[0]?.value;return B??null},asId(e,t){const c=jt(s,e,t);if(c===null)throw new $("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return c},async count(e,t){const c=V(e,"count");if(c)return x(e,O),c.count(e,t);const f=s.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=Tn(t);if(h.restrictsCounts)throw new Ze(e);x(e,O);const l=de(f.softDeleteMode,void 0),d=z(z(h.baseWhere,h.where),l),u=await Ae(d,e,h.relationBaseWhere),p=u!==d;if(f.aggregateIndexes&&!h.baseWhere&&!p&&!l){const S=An(f.aggregateIndexes,h.where);if(S){Ve(e,S.index);const B=Ye(S.index.by??[],S.key),P=Je(e,S.index.name),I=N(a,i`SELECT ${Be} AS value FROM ${i.identifier(P)} WHERE ${We} = ${B}`).toArray();return I[0]===void 0?0:I[0].value??0}}const A=te(u,me);let m=i`SELECT COUNT(*) AS count FROM ${i.identifier(e)}`;return A&&(m=i`${m} WHERE ${A}`),N(a,m).one().count},async delete(e,t,c){const f=se(e,t);if(!f){const m=$e(t);m&&(C(void 0),await m.delete(e,t,c));return}const{docJson:h,row:l,tableName:d}=f,u=s.tables[d],p=c?.hard===!0,A=!p&&u?.softDeleteMode?u.softDeleteMode.field:void 0;if(!(A&&l[A]!==null&&l[A]!==void 0)){if(Z(d,"before","delete")&&await ee("before","delete",{id:e,op:"delete",previous:l,table:d}),await eo({deletedId:e,deletedReference:m=>l[m],findHolders:async(m,D,S)=>(await Ke(m).findMany(m,{includeDeleted:p,where:{[D]:S}})).page,onCascade:(m,D)=>Ke(m).delete(D,void 0,c),onRestrict:m=>{throw new Ee(m,"restrict")},onSetNull:(m,D,S)=>Ke(m).patch(D,{[S]:null}),schema:s,tableName:d}),we(d),pe(d),A){const m={...l,...k(d),[A]:K(),_id:e};Ue(a,d,Ut(d),[ce(m),e,h]),be(d,e,m,l),xe(d,e,void 0),Ce(d,l,m),ge(d,e,l,void 0),M?.invalidate(d,e,g(d,l,m)),he(d,e,"update",m),w({indexKeys:g(d,l,m),key:e,op:"update",row:m,table:d}),Z(d,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:d}),await b({id:e,op:"delete",table:d});return}Ue(a,d,So(d),[e,h]),be(d,e,void 0),xe(d,e,void 0),Ce(d,l,void 0),ge(d,e,l,void 0),M?.invalidate(d,e,g(d,l)),he(d,e,"delete"),w({indexKeys:g(d,l),key:e,op:"delete",table:d}),Z(d,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:d}),await b({id:e,op:"delete",table:d})}},async deleteAll(e,t){if(!s.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);const c=Math.max(1,t?.chunkSize??rn),f=t?.hard===void 0?void 0:{hard:t.hard},h=ie(e)?void 0:e;let l=0;return await L(async()=>{for(;;){const u=(await U.findMany(e,{limit:c})).page.map(p=>String(p._id));if(u.length===0)break;for(const p of u)await U.delete(p,h,f),l+=1;if(u.length<c)break}}),{deleted:l}},async deleteMany(e,t,c){ae(e.length,t?.limit,"deleteMany");for(const f of e)await U.delete(f,c);return{deleted:e.length}},async deleteWhere(e,t,c){const l=(await(V(e,"deleteWhere")??U).findMany(e,{where:t})).page.map(d=>String(d._id));if(ae(l.length,c?.limit,"deleteWhere"),U.deleteMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return U.deleteMany(l,c)},async findFirst(e,t={}){return(await U.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const c=await U.findFirst(e,t);if(c===null)throw new Hn(`findFirstOrThrow: no "${e}" document matched`);return c},async findMany(e,t={}){const c=V(e,"findMany");if(c)return x(e,O),c.findMany(e,t);const f=s.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=!t.where&&!t.baseWhere;h?x(e,O):x(e);const l=it(t.orderBy,f.shape,{pinned:Nn(t.where),uniqueBy:tn(f.indexes,f.shape)}),d=t.cursor?nn(l,st(t.cursor)):void 0;let u=z(t.baseWhere,t.where);u=z(u,de(f.softDeleteMode,t.includeDeleted)),u=await Lt(u,{canPushExists:yt?gn:void 0,existsPushMode:$t==="always"?"always":"auto",fetcher:gt,maxRelationKeys:mt,relationBaseWhere:t.relationBaseWhere,schema:s,tableName:e}),d&&(u=u?{AND:[u,d]}:d);const p=yt?Uo(x):ft,A=te(u,p,He),m=typeof t.limit=="number"?Math.max(0,Math.floor(t.limit)):void 0,D=dn(e,A,un(l),m===void 0?void 0:m+1),S=_e(a,D.text,...D.params).toArray();h&&!T&&v?.recordRead(S.length);const B=[];for(const J of S){const G=le(J);G&&(B.push(G),!h&&typeof G._id=="string"&&x(e,G._id))}if(m===void 0)return t.with&&await Ft({groupedCounter:Et,fetcher:Qe,parents:B,...qt(t),schema:s,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:bt(B,t.select,t.with)};const P=B.length>m,I=P?B.slice(0,m):B,Q=I.at(-1);return t.with&&await Ft({fetcher:Qe,groupedCounter:Et,parents:I,...qt(t),schema:s,tableName:e,with:t.with}),{continueCursor:P&&Q&&t.omitContinueCursor!==!0?ct(Q,l):null,isDone:!P,page:bt(I,t.select,t.with)}},async get(e,t){const c=se(e,t);if(!c){const f=$e(t);return f?f.get(e,t):null}return x(c.tableName,e),c.row},async lookupById(e,t){const c=se(e,t);return c?(x(c.tableName,e),{row:c.row,tableName:c.tableName}):null},async groupBy(e,t){const c=V(e,"groupBy");if(c)return x(e,O),c.groupBy(e,t);const f=s.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);x(e,O);const h=t.agg??{op:"count"};if(qe(h.op),h.op!=="count"&&!h.field)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const l=de(f.softDeleteMode,void 0),d=z(z(t.baseWhere,t.where),l),u=await Ae(d,e,t.relationBaseWhere),p=u!==d,A=[...t.by,h.field];if(f.aggregateIndexes&&!t.baseWhere&&!p&&(!l||Ht(f,A))){const I=vn(f.aggregateIndexes,h.op,h.field,t.by,t.where),Q=I===void 0?0:Object.keys(I.partial).length,J=I?.index.by?.length??0;if(I&&(Q===0||Q===J)){Ve(e,I.index);const G=Je(e,I.index.name),Me=Object.keys(I.partial),De=[];if(Me.length===(I.index.by??[]).length&&Me.length>0){const ke=Ye(I.index.by??[],I.partial),Le=N(a,i`SELECT ${Be} AS value, ${et} AS count FROM ${i.identifier(G)} WHERE ${We} = ${ke}`).toArray();return Le.length>0&&De.push({key:{...I.partial},value:Xe(h.op,Le[0])}),De}const mn=N(a,i`SELECT ${We} AS key, ${Be} AS value, ${et} AS count FROM ${i.identifier(G)}`).toArray();for(const ke of mn){const Le=_n(JSON.parse(ke.key));De.push({key:Le,value:Xe(h.op,ke)})}return De}}for(const I of A){if(I===void 0)continue;const Q=I===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${I}" } })`:`groupBy(${e}, { by: [..."${I}"] })`;Nt(f,I,Q)}const m=te(u,me),D=t.by.map(I=>i`${X(I)} AS ${i.identifier(I)}`);if(h.op==="count")D.push(i`COUNT(*) AS value`);else{const{field:I}=h;if(I===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);D.push(i`${i.raw(qe(h.op))}(${X(I)}) AS value`)}let S=i`SELECT ${i.join(D,i`, `)} FROM ${i.identifier(e)}`;m&&(S=i`${S} WHERE ${m}`),S=i`${S} GROUP BY ${i.join(t.by.map(I=>X(I)),i`, `)}`;const B=N(a,S).toArray(),P=[];for(const I of B){const Q={};for(const G of t.by)Q[G]=Fn(f.shape[G],I[G]??null);const{value:J}=I;P.push({key:Q,value:J==null?null:Number(J)})}return P},async insert(e,t,c){const f=V(e,"insert");if(f)return pt(f,e,t,c,!0);const h=s.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const l=Kt(h,t,ve);nt(h,l);let d;c?.clientId!==void 0?(Io(c.clientId),d=c.clientId):c?.allowExplicitId&&typeof l._id=="string"?d=l._id:d=re();const u=c?.allowExplicitId&&typeof l._creationTime=="number"?l._creationTime:K(),p={...l,...k(e),_creationTime:u,_id:d};return Z(e,"before","insert")&&await ee("before","insert",{doc:{...p},id:d,op:"insert",table:e}),we(e),pe(e),at(a,e,mo(e),[d,u,ce(p)]),_t(e,d,p),Z(e,"after","insert")&&await ee("after","insert",{doc:p,id:d,op:"insert",table:e}),await b({doc:p,id:d,op:"insert",table:e}),d},async insertManyUnsafe(e,t,c){if(ae(t.length,c?.limit,"insertManyUnsafe"),t.length===0)return[];const f=V(e,"insert");if(f){const u=[];for(const p of t)C(p);for(const p of t){const A=await f.insert(e,p,{allowExplicitId:c?.allowExplicitId});w({key:A,op:"insert",row:{...p,_id:A},table:e}),u.push(A)}return u}const h=s.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);we(e),pe(e);const l=[];for(let u=0;u<t.length;u+=Pe)l.push(k(e));const d=t.map((u,p)=>{const A=Kt(h,u,ve),m=c?.allowExplicitId===!0&&typeof A._id=="string"?A._id:re(),D=c?.allowExplicitId===!0&&typeof A._creationTime=="number"?A._creationTime:K(),S={...A,...l[Math.floor(p/Pe)],_creationTime:D,_id:m};return{creationTime:D,document:S,id:m}});for(const u of d)C(u.document);for(let u=0;u<d.length;u+=Pe){const p=i.join(d.slice(u,u+Pe).map(m=>i`(${m.id}, ${m.creationTime}, ${ce(m.document)})`),i`, `),A=Zt("sqlite",i`INSERT INTO ${i.identifier(e)} (id, _creationTime, ${i.identifier(ne)}) VALUES ${p}`);at(a,e,A.sql,A.params)}for(const{document:u,id:p}of d)_t(e,p,u),await E({doc:u,id:p,op:"insert",table:e});return d.map(u=>u.id)},async insertMany(e,t,c){ae(t.length,c?.limit,"insertMany");const f=c?.skipDuplicates===!0,h=[],l=V(e,"insert");if(l)for(const u of t)C(u);const d=async u=>l?pt(l,e,u,void 0,!1):U.insert(e,u);for(const u of t)try{h.push(await d(u))}catch(p){if(f&&p instanceof Ee&&p.kind==="unique")h.push(null);else throw p}return h},normalizeId(e,t){return jt(s,e,t)},async patch(e,t,c){const f=se(e,c);if(!f){const A=$e(c);if(A){C(t),await A.patch(e,t,c);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:l,tableName:d}=f,u=s.tables[d];if(!u)throw new $("INTERNAL",`unknown table: ${d}`);if(x(d,e),Vt("patch",t),pn(d,e,t,l)){o?.({fields:Object.keys(rt(t)),id:e,table:d});return}const p={...l,...rt(t),...k(d),_id:e};Qt(u,t,p,ve),nt(u,p,!0),Z(d,"before","update")&&await ee("before","update",{doc:{...p},id:e,op:"update",previous:l,table:d}),we(d),pe(d),Ue(a,d,Ut(d),[ce(p),e,h]),be(d,e,p,l),xe(d,e,p),Ce(d,l,p),ge(d,e,l,p),M?.invalidate(d,e,g(d,l,p)),he(d,e,"update",p),w({indexKeys:g(d,l,p),key:e,op:"update",row:p,table:d}),Z(d,"after","update")&&await ee("after","update",{doc:p,id:e,op:"update",previous:l,table:d}),await b({doc:p,id:e,op:"update",table:d})},async patchMany(e,t,c){ae(e.length,t?.limit,"patchMany");for(const f of e)await U.patch(f.id,f.patch,c);return{patched:e.length}},async patchWhere(e,t,c){const l=(await(V(e,"patchWhere")??U).findMany(e,{where:t.where})).page.map(d=>({id:String(d._id),patch:t.patch}));if(ae(l.length,c?.limit,"patchWhere"),U.patchMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await U.patchMany(l,c),{patched:l.length}},async related(e,t){return Zn(U,y,e,t)},relationEdges:y,query(e){const t=V(e,"query");return t?(x(e,O),t.query(e)):Jo(a,s,e,j,c=>{c?W(c):x(e,O)},c=>{T||v?.recordRead(c)})},async rank(e,t,c){const f=V(e,"rank");if(f)return x(e,O),f.rank(e,t,c);j(e,t,"rank");const h=s.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const l=h.rankIndexes?.find(G=>G.name===t);if(!l)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Rt(e,h,l),c.restrictsCounts)throw new Ze(e);x(e,O),ze(e,l);const d=typeof c.row=="string"?c.row:c.row._id;if(!d)return null;const u=Mt(e,l.name),p=l.sortBy.map((G,Me)=>Dt(Me)),A=p.map(G=>Re(G)).join(", "),m=N(a,i`SELECT ${i.identifier("__partition__")}, ${i.raw(A)} FROM ${i.identifier(u)} WHERE ${i.identifier("__id__")} = ${d}`).toArray(),[D]=m;if(D===void 0)return null;let S=D.__partition__;const B=z(c.baseWhere,c.where);tt(B,s,e,"rank");const P=Kn(l,B);if(P){const G=Qn(l.partitionBy??[],P);if(G!==S)return null;S=G}const I=p.map(G=>D[G]),{before:Q,total:J}=Jt(a,u,p,l.sortBy,S,I,d);return{position:Q+1,total:J}},async rankBefore(e,t,c){if(ie(e))throw new $("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const f=s.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(p=>p.name===t);if(!h)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(c.restrictsCounts)throw new Ze(e);x(e,O),ze(e,h);const l=Mt(e,h.name),d=h.sortBy.map((p,A)=>Dt(A)),u=h.sortBy.map((p,A)=>oe(c.sortValues[A]??null));return Jt(a,l,d,h.sortBy,c.partitionKey,u,c.rowId)},async rankPage(e,t,c={}){tt(z(c.baseWhere,c.where),s,e,"rankPage");const f=V(e,"rankPage");if(f)return x(e,O),f.rankPage(e,t,c);j(e,t,"rank");const{continueCursor:h,hasMore:l,rows:d}=Ct(vt,e,t,c);return{continueCursor:h,isDone:!l,page:d.map(u=>u.doc)}},async rankPageRows(e,t,c={}){tt(z(c.baseWhere,c.where),s,e,"rankPage"),j(e,t,"rank");const{directions:f,hasMore:h,rows:l}=Ct(vt,e,t,c);return{directions:f,hasMore:h,rows:l}},async restore(e,t){const c=se(e,t);if(!c){const l=$e(t);if(l?.restore){await l.restore(e,t);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const f=s.tables[c.tableName]?.softDeleteMode?.field;if(!f)throw new $("INTERNAL",`ctx.db.restore: table "${c.tableName}" is not a .softDelete() table`);const h=c.row[f]!==null&&c.row[f]!==void 0;await U.patch(e,{[f]:null},t),h&&ge(c.tableName,e,void 0,c.row)},async replace(e,t,c,f){const h=se(e,c);if(!h){const B=$e(c);if(B){C(t),await B.replace(e,t,c,f);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:l,row:d,tableName:u}=h,p=s.tables[u];if(!p)throw new $("INTERNAL",`unknown table: ${u}`);Vt("replace",t);const A=f?.allowExplicitId&&typeof t._creationTime=="number"?t._creationTime:void 0,m=typeof d._creationTime=="number"?d._creationTime:void 0,D=A??m??K(),S={...t,...k(u),_creationTime:D,_id:e};Qt(p,t,S,ve),nt(p,S),Z(u,"before","update")&&await ee("before","update",{doc:{...S},id:e,op:"update",previous:d,table:u}),we(u),pe(u),Ue(a,u,Eo(u),[D,ce(S),e,l]),be(u,e,S,d),xe(u,e,S),Ce(u,d,S),ge(u,e,d,S),M?.invalidate(u,e,g(u,d,S)),he(u,e,"update",S),w({indexKeys:g(u,d,S),key:e,op:"update",row:S,table:u}),Z(u,"after","update")&&await ee("after","update",{doc:S,id:e,op:"update",previous:d,table:u}),await b({doc:S,id:e,op:"update",table:u})},async wipeShard(e){const t=new Set(e?.exclude),c=e?.tables,f=Object.entries(s.tables).filter(([u,p])=>t.has(u)||c!==void 0&&!c.includes(u)?!1:p.shardMode?.kind!=="global").map(([u])=>u);if(c!==void 0){for(const u of c)if(!s.tables[u])throw new $("INTERNAL",`wipeShard: unknown table: ${u}`)}const h={};let l=0;const{deleteAll:d}=U;if(d===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const u of f){const p=await d(u,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[u]=p.deleted,l+=p.deleted}return{deleted:l,tables:h}}},yn={db:U,scheduler:Te};return n.enforceRls===!0?no(U,s,(e,t)=>se(e,t)?.tableName,(e,t)=>$n(e,t),y):U};export{Nr as CDC_LOG_TABLE,ai as CLIENT_WATERMARK_TABLE,hi as GLOBAL_SHAPE_SNAPSHOT_TABLE,Ei as IDEMPOTENCY_TABLE,Qo as NotUniqueError,Ii as SEARCH_STATE_TABLE,di as advanceClientWatermark,jr as applyCdcChanges,Vt as assertNoExplicitUndefined,Io as assertValidClientId,Ur as backfillAggregateIndexes,Gr as backfillRankIndexes,Or as backfillSearchIndexes,Kr as bumpCdcEpoch,Qr as cdcCanVouchFor,Vr as cdcForkedError,zr as cdcSeqLeavingRows,Jr as cdcTouchesTables,Yr as cdcTrimmedError,Xr as compactCdcDocs,Br as createShardCtxDb,Zr as cursorBelowRetainedFloor,wi as deleteGlobalShapeSnapshot,pi as deleteGlobalShapeSnapshotsForConnection,li as migrateClientWatermark,gi as migrateGlobalShapeSnapshot,ei as minCdcReplayableSeq,ti as minCdcSeq,jt as normalizeIdStructurally,ni as readCdcChangeKeys,oi as readCdcChanges,ri as readCdcCursor,ii as readCdcEpoch,ui as readClientWatermark,$i as readGlobalShapeSnapshot,Si as readIdempotent,vi as runShardMigrations,xi as selectShapeMembers,bi as selectShapeRows,rt as stripReservedPatchFields,si as trimCdcChanges,_i as trimIdempotent,yi as writeGlobalShapeSnapshot,Ri as writeIdempotent};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{runSql as o,orNull as a,decodeJsonColumn as _}from"./runDrizzle-
|
|
1
|
+
import{runSql as o,orNull as a,decodeJsonColumn as _}from"./runDrizzle-CfKnGpV2.mjs";const s="__lunora_queue_messages",n=500,E=128*1024,T="… [truncated by the dev queue catcher]",c="[unserializable message body]",R=e=>{if(e===void 0)return"null";try{const r=JSON.stringify(e);return r.length>E?JSON.stringify(`${r.slice(0,E)}${T}`):r}catch{return JSON.stringify(c)}},g=e=>typeof e=="string"&&(e===c||e.endsWith(T)),u=e=>{o(e,`CREATE TABLE IF NOT EXISTS "${s}" (
|
|
2
2
|
id TEXT PRIMARY KEY,
|
|
3
3
|
captured_at INTEGER NOT NULL,
|
|
4
4
|
message_id TEXT NOT NULL,
|
package/dist/packem_shared/{REACTOR_STATE_TABLE-QPRFyxMS.mjs → REACTOR_STATE_TABLE-CBHASjH9.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{sql as t}from"drizzle-orm";import{runDrizzle as o}from"./runDrizzle-
|
|
1
|
+
import{sql as t}from"drizzle-orm";import{runDrizzle as o}from"./runDrizzle-CfKnGpV2.mjs";const a="__reactor_state",c=[["runs","runs INTEGER NOT NULL DEFAULT 0"],["suppressed","suppressed INTEGER NOT NULL DEFAULT 0"],["errors","errors INTEGER NOT NULL DEFAULT 0"],["last_ran_at","last_ran_at INTEGER NOT NULL DEFAULT 0"],["last_error","last_error TEXT"]],O=r=>{o(r,t`CREATE TABLE IF NOT EXISTS ${t.identifier(a)} (
|
|
2
2
|
path TEXT PRIMARY KEY,
|
|
3
3
|
digest TEXT NOT NULL,
|
|
4
4
|
tables TEXT NOT NULL,
|
package/dist/packem_shared/{SCHEDULE_OUTBOX_TABLE-CD_UjYVx.mjs → SCHEDULE_OUTBOX_TABLE-BHpxtEy4.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{sql as t}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-
|
|
1
|
+
import{sql as t}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-CfKnGpV2.mjs";const o="__schedule_outbox",_=e=>{a(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(o)} (
|
|
2
2
|
id TEXT PRIMARY KEY,
|
|
3
3
|
envelope_json TEXT NOT NULL,
|
|
4
4
|
attempts INTEGER NOT NULL,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{quoteIdentifier as i}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as n}from"./runDrizzle-
|
|
1
|
+
import{quoteIdentifier as i}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as n}from"./runDrizzle-CfKnGpV2.mjs";const p="__lunora_schema_history",c=50,e=i(p),E=t=>({appliedAt:typeof t.applied_at=="number"?t.applied_at:0,hash:typeof t.hash=="string"?t.hash:"",seq:typeof t.seq=="number"?t.seq:0}),a=t=>{n(t,`CREATE TABLE IF NOT EXISTS ${e} (
|
|
2
2
|
hash TEXT PRIMARY KEY,
|
|
3
3
|
seq INTEGER NOT NULL,
|
|
4
4
|
snapshot_json TEXT NOT NULL,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{S as t,m as S,b as c,r as i,a as l,w as s}from"./ctx-db-search-state-fIiMVPXO.mjs";import"./runDrizzle-CfKnGpV2.mjs";export{t as SEARCH_STATE_TABLE,S as migrateSearchState,c as readBackfillState,i as readSearchBackfillState,l as readSearchIndexCoverage,s as writeSearchBackfillState};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{sql as o}from"drizzle-orm";import{runDrizzle as s}from"./runDrizzle-
|
|
1
|
+
import{sql as o}from"drizzle-orm";import{runDrizzle as s}from"./runDrizzle-CfKnGpV2.mjs";import{WORKERD_SQLITE_LIMITS as d}from"./param-DlozcSQu.mjs";const c="__shape_poke_cursor",L=r=>{s(r,o`CREATE TABLE IF NOT EXISTS ${o.identifier(c)} (
|
|
2
2
|
connection_id TEXT NOT NULL,
|
|
3
3
|
sub_id TEXT NOT NULL,
|
|
4
4
|
cursor INTEGER NOT NULL,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{l as A,b as _}from"./ctx-db-search-state-fIiMVPXO.mjs";import{sql as r}from"drizzle-orm";import{readKeysetPage as h}from"./backfillAggregateIndexes-D-S4qiCu.mjs";import{runDrizzle as $}from"./runDrizzle-CfKnGpV2.mjs";import{h as L}from"./do-sql-BSoH-O04.mjs";const m="__lunora_vector_backfill",p=50,S=20,w=20,R=i=>{$(i,r`CREATE TABLE IF NOT EXISTS ${r.identifier(m)} (${r.identifier("companion")} TEXT PRIMARY KEY, ${r.identifier("cursor")} TEXT, ${r.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${r.identifier("profile")} TEXT)`)},I=(i,t,d,n,o)=>{const e=d??null;$(i,r`INSERT INTO ${r.identifier(m)} (${r.identifier("companion")}, ${r.identifier("cursor")}, ${r.identifier("done")}, ${r.identifier("profile")}) VALUES (${t}, ${e}, ${n?1:0}, ${o}) ON CONFLICT (${r.identifier("companion")}) DO UPDATE SET ${r.identifier("cursor")} = excluded.${r.identifier("cursor")}, ${r.identifier("done")} = excluded.${r.identifier("done")}, ${r.identifier("profile")} = excluded.${r.identifier("profile")}`)},O=(i,t,d)=>{const n=h(i,t,d,p+1),o={documents:[],lastId:d,more:n.length>p,unparseable:[]};for(const e of n.slice(0,p)){if(typeof e.id!="string")continue;o.lastId=e.id;const s=L(e);s?o.documents.push({doc:s,id:o.lastId}):o.unparseable.push(o.lastId)}return o},P=async(i,t,d,n,o)=>{try{const{failures:e,page:s}=await o(()=>O(i,t,d),async a=>({failures:await n(t,a.documents),page:a}));return e.length>0&&console.warn(`[@lunora/shard-engine] vector backfill: ${String(e.length)} row(s) of "${t}" could not be indexed:`,e),{failedIds:[...s.unparseable,...e.map(a=>a.id)],page:s}}catch(e){return{error:e instanceof Error?e.message:String(e)}}},y=async(i,t,d,n)=>{if(R(i),n.restart===!0)for(const{profile:s,table:a}of t)I(i,a,void 0,!1,s);const o=Math.min(n.maxPages??1,S),e={done:!1,failed:0,failedIds:[],pages:0,rows:0};for(const{profile:s,table:a}of t){const E=A(_(i,m,a),s);let{cursor:f}=E,l=E.finished;for(;!l;){if(e.pages>=o)return e;const u=await P(i,a,f,d,n.ordered);if("error"in u)return{...e,error:u.error};const{failedIds:T,page:c}=u,g=c.documents.length+c.unparseable.length;e.pages+=g>0?1:0,e.rows+=g,e.failed+=T.length,e.failedIds=[...e.failedIds,...T].slice(0,w),f=c.lastId,l=!c.more,I(i,a,f,l,s)}}return{...e,done:!0}};export{S as VECTOR_BACKFILL_MAX_PAGES,p as VECTOR_BACKFILL_PAGE_ROWS,y as backfillVectorIndexes};
|
package/dist/packem_shared/{appendStreamChunk-C1Ok4b6J.mjs → appendStreamChunk-pPeR5nbF.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{runDrizzle as E}from"./runDrizzle-
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as E}from"./runDrizzle-CfKnGpV2.mjs";const a="__stream_runs",o="__stream_chunks",N=r=>{E(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(a)} (
|
|
2
2
|
run_key TEXT PRIMARY KEY,
|
|
3
3
|
status TEXT NOT NULL,
|
|
4
4
|
last_seq INTEGER NOT NULL DEFAULT 0,
|
package/dist/packem_shared/{archiveCdcSegment-E_R_b5Qz.mjs → archiveCdcSegment-C7taIEpg.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{sql as s}from"drizzle-orm";import{runDrizzle as d}from"./runDrizzle-
|
|
1
|
+
import{sql as s}from"drizzle-orm";import{runDrizzle as d}from"./runDrizzle-CfKnGpV2.mjs";const C=16,T=32,v=1e4,R=1e3,h=t=>String(t).padStart(C,"0"),f=t=>`cdc/${encodeURIComponent(t.shard)}/${encodeURIComponent(t.epoch)}/`,y=(t,n)=>`${f(t)}${h(n)}.json`,E="__cdc_archive",g=t=>{d(t,s`CREATE TABLE IF NOT EXISTS ${s.identifier(E)} (
|
|
2
2
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
3
3
|
seq INTEGER NOT NULL
|
|
4
4
|
)`)},$=t=>(g(t),d(t,s`SELECT seq FROM ${s.identifier(E)} WHERE id = 1`).toArray()[0]?.seq??0),w=(t,n)=>{g(t),d(t,s`INSERT INTO ${s.identifier(E)} (id, seq) VALUES (1, ${n}) ON CONFLICT (id) DO UPDATE SET seq = ${n}`)},L=async(t,n,e)=>{const o=e[0]?.seq,r=e.at(-1)?.seq;o===void 0||r===void 0||await t.put(y(n,r),JSON.stringify({changes:e,from:o,to:r}),{httpMetadata:{contentType:"application/json"}})},j=async(t,n,e)=>{const o=f(n);return(await t.list({limit:1,prefix:o,startAfter:`${o}${h(e)}.json`})).objects.length>0},S=t=>{let n;try{n=JSON.parse(t)}catch{return}if(typeof n!="object"||n===null)return;const e=n;return typeof e.from=="number"&&typeof e.to=="number"&&Array.isArray(e.changes)?e:void 0},_=(t,n)=>{const e=[];for(const o of t.changes)if(!(o.seq<=n)){if(o.op!=="delete"&&o.doc===void 0)break;e.push(o)}return e},I=(t,n,e)=>{let o=e;for(const r of n){if(r.seq!==o+1)break;t.push(r),o=r.seq}return o},b=async(t,n)=>{const e=await t.get(n);return e===null?void 0:S(await e.text())},q=async(t,n,e,o)=>{const r=f(n),p=Math.max(1,Math.min(o??R,v)),A=await t.list({limit:T,prefix:r,startAfter:`${r}${h(e)}.json`}),c=[];let i=e;for(const l of A.objects){const a=await b(t,l.key);if(a===void 0)break;const m=_(a,i);if(i=I(c,m,i),c.length>=p||i!==a.to)break}if(c[0]?.seq!==e+1)return;const u=c.slice(0,p);return{changes:u,cursor:u.at(-1)?.seq??e}};export{L as archiveCdcSegment,j as cdcArchiveRewound,q as readArchivedCdcChanges,$ as readCdcArchivedThrough,w as writeCdcArchivedThrough};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{m as x,c as T,l as R,r as E,a as P,w as D}from"./ctx-db-search-state-fIiMVPXO.mjs";import{S,c as U,g as v,d as A,e as k,a as b}from"./fts-companion-B7jllLhZ.mjs";import{sql as s}from"drizzle-orm";import{matchesStaticWhere as G}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as W,encodeAggregateKey as B,foldAggregateTally as H}from"./aggregateTableName-C7o-gpms.mjs";import{rankColumnsSql as N,insertRankRow as K}from"./createCompanionSync-BwWcSwvy.mjs";import{runDrizzle as l,runAll as $}from"./runDrizzle-CfKnGpV2.mjs";import{i as C,h as O,D as p,r as M,a as Y,b as j,A as z}from"./do-sql-BSoH-O04.mjs";import{sqliteInList as V}from"./param-DlozcSQu.mjs";import{isLiveForCompanion as J}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{rankTableName as Q,matchesRankStaticWhere as X}from"./RANK_TIEBREAK-D5xNdzB3.mjs";const L=(e,o)=>l(e,s`SELECT COUNT(*) AS count FROM ${s.identifier(o)}`).one().count>0,Z=(e,o)=>l(e,s`SELECT 1 FROM ${s.identifier(o)} LIMIT 1`).toArray().length>0,_=(e,o)=>l(e,s`SELECT id, _creationTime, ${s.identifier(p)} FROM ${s.identifier(o)}`).toArray(),q=(e,o,r,n)=>{const t=W(o,r.name);if(L(e,t))return;const a=r.by??[],c=new Map,i=_(e,o);for(const d of i){const f=M(d);if(!f||!J(f,n)||r.where&&!G(f,r.where))continue;const g=B(a,f);H(c,g,r,f)}for(const[d,f]of c)l(e,s`INSERT INTO ${s.identifier(t)} (${Y}, ${j}, ${z}) VALUES (${d}, ${f.value}, ${f.count})`)},pe=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(!(n.shardMode?.kind==="global"||!n.aggregateIndexes))for(const t of n.aggregateIndexes)q(e,r,t,n.softDeleteMode?.field)},ee=(e,o,r)=>{const n=Q(o,r.name);if(L(e,n))return;const t=N(r),a=_(e,o);for(const c of a){const i=M(c);!i||r.where&&!X(i,r.where)||K(e,n,r,t,i._id,i)}},Se=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(!(n.shardMode?.kind==="global"||!n.rankIndexes))for(const t of n.rankIndexes)ee(e,r,t)},oe=(e,o,r,n)=>l(e,r===void 0?s`SELECT id, _creationTime, ${s.identifier(p)} FROM ${s.identifier(o)} ORDER BY id ASC LIMIT ${s.raw(String(n))}`:s`SELECT id, _creationTime, ${s.identifier(p)} FROM ${s.identifier(o)} WHERE id > ${r} ORDER BY id ASC LIMIT ${s.raw(String(n))}`).toArray(),h=500,y=(e,o,r)=>{const n=S(o,r.name),t=T(r),a=R(E(e,n),t);if(a.finished)return{done:!0,rows:0};const{cursor:c}=a,i=oe(e,o,c,h);let d=c;for(const g of i){const{id:u}=g;if(typeof u!="string")continue;d=u;const I=O(g);$(e,I?A(n,u,k(I,r)):b(n,u))}const f=i.length<h;return D(e,n,d,f,t),{done:f,rows:i.length}},m=(e,o)=>s`${s.identifier(e)}.${s.identifier(o)}`,w=500,F=(e,o,r)=>{const n=S(o,r.name),t=l(e,U(n,w)).toArray(),a=v(t);if(a.size===0)return!0;const c=new Map;for(const i of l(e,s`SELECT ${m(o,"id")}, ${m(o,"_creationTime")}, ${m(o,p)} FROM ${s.identifier(o)} WHERE ${V(m(o,"id"),[...a.keys()],!1)}`))c.set(String(i.id),i);for(const[i,d]of a){const f=c.get(i),g=f?O(f):void 0;$(e,g?A(n,i,k(g,r),{unmappedRowids:d}):b(n,i,{unmappedRowids:d}))}return t.length<w},ne=(e,o,r,n)=>{let t=0;for(;t<n&&!F(e,o,r);)t+=1;return t},Ie=(e,o,r)=>{const n=S(o,r.name),t=T(r);return R(E(e,n),t).finished?!0:P(e,n)},he=(e,o,r)=>{if(C(e))for(const n of r.searchIndexes??[])F(e,o,n),!(n.staged&&Z(e,o))&&y(e,o,n)},re=(e,o,r,n)=>{let t=0;for(;;){if(t>=n)return{done:!1,pages:t};const a=y(e,o,r);if(a.rows>0&&(t+=1),a.done)return{done:!0,pages:t}}},we=(e,o,r={})=>{if(!C(e))return{done:!0,pages:0};x(e);const n=r.maxPages??Number.POSITIVE_INFINITY;let t=0;for(const[a,c]of Object.entries(o.tables))if(!(c.shardMode?.kind==="global"||!c.searchIndexes))for(const i of c.searchIndexes){if(t+=ne(e,a,i,n-t),t>=n)return{done:!1,pages:t};const d=re(e,a,i,n-t);if(t+=d.pages,!d.done)return{done:!1,pages:t}}return{done:!0,pages:t}};export{pe as backfillAggregateIndexes,Se as backfillRankIndexes,we as backfillSearchIndexes,he as backfillSearchIndexesForTable,F as drainUnmappedFtsRows,oe as readKeysetPage,Ie as searchIndexCoversTable};
|
|
@@ -1 +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-C-FpWm52.mjs";import{runSql as p}from"./runDrizzle-
|
|
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-C-FpWm52.mjs";import{runSql as p}from"./runDrizzle-CfKnGpV2.mjs";import{k as d,D as E}from"./do-sql-BSoH-O04.mjs";import{m as g}from"./sql-projection-D3qdaItY.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};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-
|
|
1
|
+
import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-BFbP2eiJ.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-Cp98I-ot.mjs";import{shapeRangeKey as u}from"./ShapeDiffCache-gdaILV5E.mjs";import{projectColumns as g}from"./buildPokeFrames-BBE6J91z.mjs";const C=(m,e,a,i,p,f=s)=>{const r=u(e.table,a,i),n=p.changedKeys(r,()=>f(m,e.table,a,i));if(n.length===0)return[];const b=p.members(e,r,()=>h(m,e.table,e.effectiveWhere,n.map(t=>t.id))),o=[];for(const t of n){const c=b.get(t.id);if(c===void 0){t.op!=="insert"&&o.push({key:t.id,op:"delete",table:e.table});continue}o.push({key:t.id,op:t.op,table:e.table,value:g(c,e.columns)})}return o};export{C as buildShapeDiff};
|
package/dist/packem_shared/{clearMemoryTables-BGbmag2i.mjs → clearMemoryTables-C5Wivufe.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as t}from"drizzle-orm";import{runDrizzle as s}from"./runDrizzle-
|
|
1
|
+
import{sql as t}from"drizzle-orm";import{runDrizzle as s}from"./runDrizzle-CfKnGpV2.mjs";const a=r=>r?.memoryMode===!0,l=r=>Object.entries(r.tables).filter(([,e])=>a(e)&&e.shardMode?.kind!=="global").map(([e])=>e),i=(r,e)=>{const o=l(e);for(const m of o)s(r,t`DELETE FROM ${t.identifier(m)}`);return o.length};export{i as clearMemoryTables,a as isMemoryTable,l as memoryTableNames};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as g}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{mergeWhere as b}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{SCAN_DEP as j}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as A}from"./runDrizzle-
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{mergeWhere as b}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{SCAN_DEP as j}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as A}from"./runDrizzle-CfKnGpV2.mjs";import{sqliteInList as O}from"./param-DlozcSQu.mjs";import{decodeCursor as F,CURSOR_PREFIX as P,toBase64 as U}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{rankTableName as V,sortColumnName as z,resolveRankPartition as H,RANK_TIEBREAK as _,encodePartitionKey as J,rankPivotConditionSql as X}from"./RANK_TIEBREAK-D5xNdzB3.mjs";const Y="__doc__",G=n=>P+U(JSON.stringify(n)),Q=n=>n.after?[n.after.partitionKey,...n.after.sortValues,n.after.rowId]:n.cursor?F(n.cursor):void 0,Z=(n,r,f)=>{if(n?.length!==1+r.length+1)return;const t=[{column:"__partition__",direction:"asc"}];for(const[c,u]of r.entries())t.push({column:u,direction:f[c]?.direction??"asc"});t.push({column:_,direction:"asc"});const e=[];for(const[c,u]of t.entries()){const d=X(u.column,n[c],u.direction,!0);if(d===void 0)continue;const s=[];for(const[m,l]of t.slice(0,c).entries())s.push(o`${o.identifier(l.column)} IS ${n[m]}`);s.push(d);const[i]=s;e.push(s.length===1&&i!==void 0?i:o`(${o.join(s,o` AND `)})`)}return e.length===0?o`(1 = 0)`:o`(${o.join(e,o` OR `)})`},v=null,oo=(n,r)=>{if(n===void 0)return v;const f=[n.__partition__,...r.map(t=>n[t]),n[_]];return G(f)},no=(n,r,f)=>{const t=[];for(const e of n){const c=e[_];if(typeof c!="string")continue;const u=r.get(c);if(!u)continue;const d=typeof e.__partition__=="string"?e.__partition__:"",s=f.map(i=>e[i]??null);t.push({doc:u,key:{partitionKey:d,rowId:c,sortValues:s}})}return t},to=o`${o.identifier("id")}`,ro=(n,r,f)=>{const{rowToDocument:t}=n,e=new Map;if(f.length===0)return e;const c=A(n.sql,o`SELECT id, _creationTime, ${o.identifier(Y)} FROM ${o.identifier(r)} WHERE ${O(to,f,!1)}`).toArray();for(const u of c){const d=t(u),s=u.id;d&&typeof s=="string"&&e.set(s,d)}return e},_o=(n,r,f,t)=>{const{assertRankPartitionLocal:e,ensureRankBackfilled:c,onRead:u,schema:d}=n,s=d.tables[r];if(!s)throw new g("INTERNAL",`unknown table: ${r}`);const i=s.rankIndexes?.find(a=>a.name===f);if(!i)throw new g("INTERNAL",`unknown rankIndex "${f}" on table "${r}"`);e(r,s,i),u(r,j),c(r,i);const m=V(r,i.name),l=i.sortBy.map((a,w)=>z(w)),h=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),T=b(t.baseWhere,t.where),k=H(i,T),R=[o`${o.identifier("__partition__")} ASC`];for(const[a,w]of l.entries()){const W=i.sortBy[a]?.direction;R.push(o`${o.identifier(w)} ${o.raw(W==="desc"?"DESC":"ASC")}`)}R.push(o`${o.identifier(_)} ASC`);const p=[];typeof t.partitionKey=="string"?p.push(o`${o.identifier("__partition__")} = ${t.partitionKey}`):k&&p.push(o`${o.identifier("__partition__")} = ${J(i.partitionBy??[],k)}`);const B=Q(t),E=Z(B,l,i.sortBy);E&&p.push(E);const I=o.identifier(_),S=o.identifier("__partition__"),D=p.length>0?o` WHERE ${o.join(p,o` AND `)}`:o``,L=l.length>0?o`${I}, ${S}, ${o.join(l.map(a=>o.identifier(a)),o`, `)}`:o`${I}, ${S}`,M=o`SELECT ${L} FROM ${o.identifier(m)}${D} ORDER BY ${o.join(R,o`, `)} LIMIT ${o.raw(String(h+1))}`,$=A(n.sql,M).toArray(),C=$.length>h,y=C?$.slice(0,h):$,K=y.map(a=>a[_]),q=no(y,ro(n,r,K),l),x=C?oo(y.at(-1),l):v,N=i.sortBy.map(a=>a.direction==="desc"?"desc":"asc");return{continueCursor:x,directions:N,hasMore:C,rows:q}};export{_o as computeRankPage,Q as resolveRankSeekTuple};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{N as re,S as se,d as ie,e as ce,a as ae}from"./fts-companion-B7jllLhZ.mjs";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as V,aggregateSqlFunction as fe}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as P,encodeAggregateKey as v,foldAggregateTally as z,coerceAggregateNumber as D}from"./aggregateTableName-C7o-gpms.mjs";import{runDrizzle as $,runAll as le}from"./runDrizzle-CfKnGpV2.mjs";import{i as $e,g as de,D as b,r as q,a as O,b as _,A as g,c as M,e as W}from"./do-sql-BSoH-O04.mjs";import{param as ue,WORKERD_SQLITE_LIMITS as Ee}from"./param-DlozcSQu.mjs";import{encodeGeohash as ge,GEO_DEFAULT_PRECISION as pe}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as Q}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{encodePartitionKey as ye,sortColumnName as me,rankTableName as X,matchesRankStaticWhere as Y}from"./RANK_TIEBREAK-D5xNdzB3.mjs";import{m as _e}from"./sql-projection-D3qdaItY.mjs";import{serializeSqlValue as J}from"./serializeSqlValue-BEMMYX1n.mjs";const he=(m,R,p)=>[...m.partitionBy??[],...m.sortBy.map(h=>h.field),...m.where?Object.keys(m.where):[]].every(h=>R[h]===p[h]),Z=m=>e.join(["__id__","__partition__",...m.sortBy.map((R,p)=>me(p))].map(R=>e.identifier(R)),e`, `),N=(m,R,p,F,h,u)=>{const s=ye(p.partitionBy??[],u),C=p.sortBy.map(I=>J(u[I.field]??null)),L=e.join([h,s,...C].map(I=>ue(I)),e`, `);$(m,e`INSERT INTO ${e.identifier(R)} (${F}) VALUES (${L})`)},Te=(m,R,p,F,h,u)=>{if(h&&u&&he(p,h,u))return;const s=X(R,p.name);h&&$(m,e`DELETE FROM ${e.identifier(s)} WHERE ${e.identifier("__id__")} = ${F}`),!(!u||p.where&&!Y(u,p.where))&&N(m,s,p,Z(p),F,u)},be=m=>{const{broadcast:R,indexKeysFor:p,invalidateCache:F,recordCdc:h,schema:u,sql:s}=m,C=new Set,L=n=>u.tables[n]?.softDeleteMode?.field,I=new Set,U=(n,o)=>{const r=`${n}::${o.name}`;if(C.has(r))return;const c=P(n,o.name),a=o.by??[],f=L(n),d=new Map,y=$(s,e`SELECT id, _creationTime, ${e.identifier(b)} FROM ${e.identifier(n)}`).toArray();for(const T of y){const l=q(T);if(!l||!Q(l,f)||o.where&&!V(l,o.where))continue;const S=v(a,l);z(d,S,o,l)}$(s,e`DELETE FROM ${e.identifier(c)}`);const A=Math.floor(Ee.boundParams/3),w=[...d];for(let T=0;T<w.length;T+=A){const l=w.slice(T,T+A),S=e.join(l.map(([t,i])=>e`(${t}, ${i.value}, ${i.count})`),e`, `);$(s,e`INSERT INTO ${e.identifier(c)} (${O}, ${_}, ${g}) VALUES ${S}`)}C.add(r)},x=(n,o,r)=>{const c=o.by??[],a=o.field??"",f=[],d=(t,i)=>{const E=J(i);E===null?f.push(e`${W(t)} IS NULL`):f.push(e`${W(t)} = ${E}`)};for(const t of c)d(t,r[t]??null);const y=L(n);y!==void 0&&d(y,null);for(const[t,i]of Object.entries(o.where??{}))d(t,i!==null&&typeof i=="object"&&!Array.isArray(i)?i.eq:i);const A=f.length>0?e` WHERE ${e.join(f,e` AND `)}`:e``,w=u.tables[n]?.shape[a];if(w&&_e(w)){const t=$(s,e`SELECT id, _creationTime, ${e.identifier(b)} FROM ${e.identifier(n)}${A}`).toArray(),i=new Map;for(const E of t){const k=q(E);k&&z(i,"",o,k)}return{value:i.get("")?.value??null}}const T=fe(o.op),l=W(a);return{value:$(s,e`SELECT ${e.raw(T)}(${l}) AS value FROM ${e.identifier(n)}${A}`).one().value??null}},ee=(n,o,r,c)=>{const a=P(n,o.name),{op:f}=o,d=o.field??"",y=t=>{$(s,e`DELETE FROM ${e.identifier(a)} WHERE ${O} = ${t} AND ${g} <= 0`)},A=L(n),w=t=>!o.where||V(t,o.where),T=t=>Q(t,A)&&w(t);c!==void 0&&f!=="count"&&w(c)&&D(c[d]);const l=r&&T(r)?r:void 0,S=c&&T(c)?c:void 0;if(!(!l&&!S)){if(f==="count"){for(const[t,i]of[[l,-1],[S,1]]){if(!t)continue;const E=v(o.by??[],t);$(s,M(a,E,i,i,e`${_} = ${_} + excluded.${_}, ${g} = ${g} + excluded.${g}`))}l&&y(v(o.by??[],l));return}if(f==="sum"||f==="avg"){for(const[t,i]of[[l,-1],[S,1]]){if(!t)continue;const E=D(t[d]);if(E===void 0)continue;const k=v(o.by??[],t);$(s,M(a,k,i*E,i,e`${_} = COALESCE(${_}, 0) + excluded.${_}, ${g} = ${g} + excluded.${g}`))}l&&y(v(o.by??[],l));return}if(l){const t=v(o.by??[],l),i=D(l[d]),E=$(s,e`SELECT ${_} AS value, ${g} AS count FROM ${e.identifier(a)} WHERE ${O} = ${t}`).toArray()[0],k=(E?.count??0)-1;if(k<=0)$(s,e`DELETE FROM ${e.identifier(a)} WHERE ${O} = ${t}`);else if(E&&i!==void 0&&E.value!==null&&i===E.value){const te=x(n,o,l);$(s,e`UPDATE ${e.identifier(a)} SET ${_} = ${te.value}, ${g} = ${k} WHERE ${O} = ${t}`)}else $(s,e`UPDATE ${e.identifier(a)} SET ${g} = ${g} - 1 WHERE ${O} = ${t}`)}if(S){const t=v(o.by??[],S),i=D(S[d]);if(i===void 0)$(s,M(a,t,null,1,e`${g} = ${g} + 1`));else{const E=f==="min"?"MIN":"MAX";$(s,M(a,t,i,1,e`${_} = ${e.raw(E)}(COALESCE(${_}, excluded.${_}), excluded.${_}), ${g} = ${g} + 1`))}}}},oe=n=>{for(const o of u.tables[n]?.aggregateIndexes??[])U(n,o)},j=(n,o,r)=>{for(const c of u.tables[n]?.aggregateIndexes??[])ee(n,c,o,r)},B=(n,o)=>{const r=`${n}::rank::${o.name}`;if(I.has(r))return;const c=X(n,o.name),a=$(s,e`SELECT id, _creationTime, ${e.identifier(b)} FROM ${e.identifier(n)}`).toArray();$(s,e`DELETE FROM ${e.identifier(c)}`);const f=Z(o);for(const d of a){const y=q(d);!y||o.where&&!Y(y,o.where)||N(s,c,o,f,y._id,y)}I.add(r)},ne=n=>{for(const o of u.tables[n]?.rankIndexes??[])B(n,o)},H=(n,o,r,c)=>{for(const a of u.tables[n]?.rankIndexes??[])Te(s,n,a,o,r,c)},K=(n,o,r,c)=>{const a=u.tables[n]?.searchIndexes??[];if(!(a.length===0||!$e(s)))for(const f of a){if(re(c,r,f))continue;const d=se(n,f.name);le(s,r?ie(d,o,ce(r,f)):ae(d,o))}},G=(n,o,r)=>{for(const c of u.tables[n]?.geoIndexes??[]){const a=de(n,c.name);$(s,e`DELETE FROM ${e.identifier(a)} WHERE ${e.identifier("__id__")} = ${o}`);const f=r?.[c.field];if(f!==null&&typeof f=="object"&&typeof f.lat=="number"&&typeof f.lng=="number"){const{lat:d,lng:y}=f,A=ge({lat:d,lng:y},c.precision??pe);$(s,e`INSERT INTO ${e.identifier(a)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${o}, ${A}, ${d}, ${y})`)}}};return{ensureBackfilledForTable:oe,ensureBackfilledIndex:U,ensureRankBackfilled:B,ensureRankBackfilledForTable:ne,syncAggregates:j,syncCompanionsForInsert:(n,o,r)=>{K(n,o,r),G(n,o,r),j(n,void 0,r),H(n,o,void 0,r),F(n,o,r),h(n,o,"insert",r),R({indexKeys:p(n,r),key:o,op:"insert",row:r,table:n})},syncGeo:G,syncRanks:H,syncSearch:K}};export{be as createCompanionSync,N as insertRankRow,Z as rankColumnsSql};
|
package/dist/packem_shared/{createReplicaLink-CUnl1y_Q.mjs → createReplicaLink-CTyOjpjh.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{d as p,e as S}from"./wire-codec-C-FpWm52.mjs";import{cursorBelowRetainedFloor as y}from"./CDC_LOG_TABLE-
|
|
1
|
+
import{d as p,e as S}from"./wire-codec-C-FpWm52.mjs";import{cursorBelowRetainedFloor as y}from"./CDC_LOG_TABLE-BFbP2eiJ.mjs";import{envPositiveInt as v}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{v as A,R as g,s as N,a as E,b as T}from"./sibling-channel-BkL5cTCc.mjs";const L=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],O=new Set(L),b=s=>typeof s=="string"&&O.has(s),h="::replica::",R=s=>{const e=s.lastIndexOf(h);if(e===-1)return;const t=s.slice(0,e),r=s.slice(e+h.length);if(!(t.length===0||!b(r)))return{ownerKey:t,region:r}},I=s=>{if(s==null||!/^\d+$/.test(s))return;const e=Number.parseInt(s,10);return Number.isSafeInteger(e)&&e>0?e:void 0},m=1e3,w=1e3,C=10,U=5e4,F=s=>v(s,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",U),d="__replica_state",l=new WeakSet,_=s=>{l.has(s)||(s.exec(`CREATE TABLE IF NOT EXISTS ${d} (
|
|
2
2
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
3
3
|
epoch TEXT NOT NULL,
|
|
4
4
|
applied_seq INTEGER NOT NULL,
|
package/dist/packem_shared/{ctx-db-relay-shapes-Bg5YYnmN.mjs → ctx-db-relay-shapes-BcgjOtG1.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{sql as i}from"drizzle-orm";import{e as l,d as E}from"./wire-codec-C-FpWm52.mjs";import{runDrizzle as a}from"./runDrizzle-
|
|
1
|
+
import{sql as i}from"drizzle-orm";import{e as l,d as E}from"./wire-codec-C-FpWm52.mjs";import{runDrizzle as a}from"./runDrizzle-CfKnGpV2.mjs";import{relayProxyKey as T}from"./DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";const t="__lunora_relay_shapes",o=null,R=e=>{a(e,i`CREATE TABLE IF NOT EXISTS ${i.identifier(t)} (
|
|
2
2
|
key TEXT PRIMARY KEY,
|
|
3
3
|
relay_idx INTEGER,
|
|
4
4
|
connection_id TEXT,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{D as E}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{sql as e}from"drizzle-orm";import{runDrizzle as t}from"./runDrizzle-CfKnGpV2.mjs";const S=i=>`${E(i.language).profile}:${i.field}`,c=i=>{const r=i.slice(i.indexOf(":")+1),o=r.lastIndexOf("/");return o===-1?r:r.slice(0,o)},N=(i,r)=>i.profile!==r?{cursor:void 0,finished:!1,wipe:i.cursor!==void 0||i.done}:{cursor:i.cursor,finished:i.done,wipe:!1},T=(i,r)=>typeof i=="string"&&c(i)===c(r),n="__lunora_search_state",R=i=>{t(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("cursor")} TEXT, ${e.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${e.identifier("profile")} TEXT, ${e.identifier("covered")} INTEGER NOT NULL DEFAULT 0)`);try{t(i,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${e.identifier("profile")} TEXT`)}catch{}try{t(i,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${e.identifier("covered")} INTEGER NOT NULL DEFAULT 0`)}catch{}t(i,e`UPDATE ${e.identifier(n)} SET ${e.identifier("covered")} = 1 WHERE ${e.identifier("done")} = 1 AND ${e.identifier("covered")} = 0`)},s=i=>i===1||i===!0||i==="1",O=(i,r)=>{const o=t(i,e`SELECT ${e.identifier("covered")} FROM ${e.identifier(n)} WHERE ${e.identifier("companion")} = ${r}`).toArray();return s(o[0]?.covered)},l=(i,r,o)=>{const d=t(i,e`SELECT ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")} FROM ${e.identifier(r)} WHERE ${e.identifier("companion")} = ${o}`).toArray()[0];return d?{cursor:d.cursor??void 0,done:s(d.done),profile:d.profile??void 0}:{cursor:void 0,done:!1,profile:void 0}},u=(i,r)=>l(i,n,r),D=(i,r,o,f,d)=>{const $=o??null,a=T(u(i,r).profile,d)?e`MAX(${e.identifier(n)}.${e.identifier("covered")}, excluded.${e.identifier("covered")})`:e`excluded.${e.identifier("covered")}`;t(i,e`INSERT INTO ${e.identifier(n)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("covered")}) VALUES (${r}, ${$}, ${f?1:0}, ${d}, ${f?1:0}) ON CONFLICT (${e.identifier("companion")}) DO UPDATE SET ${e.identifier("cursor")} = excluded.${e.identifier("cursor")}, ${e.identifier("done")} = excluded.${e.identifier("done")}, ${e.identifier("profile")} = excluded.${e.identifier("profile")}, ${e.identifier("covered")} = ${a}`)};export{n as S,O as a,l as b,S as c,N as l,R as m,u as r,D as w};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createShardCtxDb as v}from"./NotUniqueError-
|
|
1
|
+
import{createShardCtxDb as v}from"./NotUniqueError-D0LwVtXI.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-DG9iXjzF.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as _}from"./runShardMigrations-o-qjyKt5.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";const E=(C,m={})=>({_meta:{column:{notNull:!0,...m}},kind:C}),W=(C,m,O)=>{const{describe:S,expect:n,it:y}=O;S(`engine contract: ${C}`,()=>{S("optimistic concurrency",()=>{const b=u=>({tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});y("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await n(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(N)}finally{u?.()}}),y("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e.code).toBe("CONFLICT"),n(e.kind).toBe("occ")}finally{u?.()}}),y("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const o=await s.get("i1");n(o?.title).toBe("first"),n(o?.version).toBe(99)}finally{u?.()}}),y("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l={tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,a)=>{await t.db.patch(a.doc._id,{version:99})},op:"update",timing:"before"}}}}};_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e).toBeInstanceOf(N),n(e.code).toBe("CONFLICT"),n(e.kind).toBe("trigger")}finally{u?.()}})}),S("shape-poke ordering",()=>{const b="shard-a",u={args:{},name:"messages"},h=(e,t,a,r)=>e.accept(t?.()??{},{connectionId:a,shapes:{[r]:u}}),i=(e,t,a)=>{let r=0,d=0;const c=g=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${g}`)},p={fetch:(g,q)=>{if(JSON.parse(q?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const B=a[d];if(d+=1,B===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(B))}},k={get:()=>p,getByName:()=>p,idFromName:g=>g},w={buildShapeDiff:c("buildShapeDiff"),computeOpLogShapeSeed:c("computeOpLogShapeSeed"),currentCdcEpoch:c("currentCdcEpoch"),deliverWhisperLocal:c("deliverWhisperLocal"),doName:()=>F(b,0),env:()=>({SHARD:k}),getWebSockets:()=>e.getSockets(),maskMetadata:c("maskMetadata"),nextPokeId:()=>(r+=1,`poke-${String(r)}`),readAttachment:g=>g.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:c("resolveShape"),rlsMetadata:c("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},f=I(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,a)=>{const r=await e.seedRelayShape(t,a,u,{identity:void 0,userId:void 0});if(r!=="ok")throw new Error(`seed failed: ${JSON.stringify(r)}`)},o=(e={})=>l({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});y("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o());const w=(await r(p)).map(f=>JSON.parse(f));n(w.map(f=>f.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),n(new Set(w.map(f=>f.pokeId)).size).toBe(1),n(w[1]?.shapeId).toBe("s1"),n(w[2]?.checkpoint).toBe(20)}finally{e?.()}}),y("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1"),k=h(d,t,"c-bob","s2");await s(c,p,"s1"),await s(c,k,"s2"),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3);const f=await r(k);n(f.length).toBe(0),await c.handleControl(o());const g=await r(p);n(g.length).toBe(3)}finally{e?.()}}),y("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o({epoch:"e2"}));const k=await r(p);n(k.length).toBe(0),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3)}finally{e?.()}})}),S("RLS identity under live subscription",()=>{const b="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},i=s=>{const o=[],e=[],t={fetch:(d,c)=>(o.push(JSON.parse(c?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},r=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>b,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:d=>d}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(d,c,p)=>(e.push(p),d===h.name?{columns:["id"],effectiveWhere:{org:p?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(r===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:r,posts:o,resolvedUnder:e}},l=async(s,o)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...o,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};y("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:o}=m();try{const{owner:e,resolvedUnder:t}=i(o.sql);await l(e,h),n(t.some(a=>a?.userId==="u1"&&a.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),y("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),y("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{W as defineEngineContractSuite};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as _}from"@lunora/errors";import{sql as r}from"drizzle-orm";import{e as A,s as T}from"./sql-projection-D3qdaItY.mjs";import{quoteIdentifier as p}from"./quoteIdentifier-CObIFRhb.mjs";import{d as $,n as S,e as O}from"./wire-codec-C-FpWm52.mjs";import{runDrizzle as f}from"./runDrizzle-
|
|
1
|
+
import{LunoraError as _}from"@lunora/errors";import{sql as r}from"drizzle-orm";import{e as A,s as T}from"./sql-projection-D3qdaItY.mjs";import{quoteIdentifier as p}from"./quoteIdentifier-CObIFRhb.mjs";import{d as $,n as S,e as O}from"./wire-codec-C-FpWm52.mjs";import{runDrizzle as f}from"./runDrizzle-CfKnGpV2.mjs";import"./serializeSqlValue-BEMMYX1n.mjs";const b=/^[A-Za-z_$][\w$]*$/u,h=e=>b.test(e)?e:`"${e.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,m="__doc__",a="__originals__",G=e=>{if(Object.hasOwn(e,a))throw new _("BAD_REQUEST",`"${a}" 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[s,i]of Object.entries(e)){const c=T(i);c!==void 0&&(t??={...e},o??=Object.create(null),t[s]=c,o[s]=i)}t&&o&&(t[a]=o);const n=t??e;try{return S(n)?JSON.stringify(O(n)):JSON.stringify(n)}catch(s){throw new _("BAD_REQUEST",`this document cannot be stored: ${s instanceof Error?s.message:String(s)}`)}},g=e=>{const t=$(JSON.parse(e)),o=t[a];if(o===null||typeof o!="object"||Array.isArray(o))return t;const n={...t};return delete n[a],{...n,...o}},J=(e,t)=>`${e}__geo_${t}`,E=(e,t)=>t==="_id"||t==="id"?`${e}id`:t==="_creationTime"?`${e}_creationTime`:`json_extract(${e}${m}, '$.${h(t).replaceAll("'","''")}')`,y=e=>E("",e),q=e=>r.raw(y(e)),N=(e,t)=>E(`${p(e)}.`,t),B=(e,t)=>r.raw(N(e,t)),z=(e,t,o,n)=>r`CREATE ${n?r`UNIQUE `:r``}INDEX IF NOT EXISTS ${r.identifier(e)} ON ${r.identifier(t)} (${o})`,l=r.identifier("__key__"),I=r.identifier("__value__"),j=r.identifier("__count__"),F=(e,t,o,n,s)=>r`INSERT INTO ${r.identifier(e)} (${l}, ${I}, ${j}) VALUES (${t}, ${o}, ${n}) ON CONFLICT(${l}) DO UPDATE SET ${s}`,W=(e,t)=>e===void 0||t!==0&&t!==1||A(e)!=="boolean"?t:t===1,d=new WeakMap,k=e=>{const t=d.get(e);if(t!==void 0)return t;const o=[];for(const[n,s]of Object.entries(e.shape)){const i=s._meta?.column;i&&o.push(Object.freeze([n,i]))}return Object.freeze(o),d.set(e,o),o},C=e=>{if(!e)return;const t=e[m];let o;typeof t=="string"?o=g(t):t&&typeof t=="object"?o=t:o={};const{id:n}=e;typeof n=="string"&&(o._id=n);const s=e._creationTime;return typeof s=="number"&&(o._creationTime=s),o},K=e=>{try{return C(e)}catch{return}},u=new WeakMap,M=e=>{const t=u.get(e);if(t!==void 0)return t;let o;try{f(e,r`CREATE VIRTUAL TABLE IF NOT EXISTS ${r.identifier("__lunora_fts_probe")} USING fts5(x)`),o=!0}catch{o=!1}finally{try{f(e,r`DROP TABLE IF EXISTS ${r.identifier("__lunora_fts_probe")}`)}catch{}}return u.set(e,o),o};export{j as A,m as D,l as a,I as b,F as c,z as d,q as e,B as f,J as g,K as h,M as i,y as j,G as k,g as l,h as m,a as n,W as o,N as q,C as r,k as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{toErrorBody as b}from"@lunora/errors";import{COMMIT_SEQ_FIELD as l}from"./COMMIT_SEQ_FIELD-
|
|
1
|
+
import{toErrorBody as b}from"@lunora/errors";import{COMMIT_SEQ_FIELD as l}from"./COMMIT_SEQ_FIELD-D6uMUaiR.mjs";const f=200,u=(o,n)=>{const i=r=>{const e=o.tables[r];return e!==void 0&&e.shardMode?.kind!=="global"};return(n&&n.length>0?[...n]:Object.keys(o.tables)).filter(r=>i(r))},p=async function*(o,n,i=f){let r=null,e=!1;for(;!e;){const t=await o.findMany(n,{cursor:r,includeDeleted:!0,limit:i});for(const s of t.page)yield{doc:s,table:n};r=t.continueCursor,e=t.isDone||r===null}},O=async function*(o,n,i){const r=u(n,i.tables),e=i.batchSize??f;for(const t of r)yield*p(o,t,e)},y=new Set(["_creationTime","_id"]),h=(o,n)=>{for(const[i,r]of Object.entries(o.shape)){const e=n[i];if(e===void 0&&r.kind==="optional")continue;const t=r.parse;if(typeof t=="function")try{t(e)}catch(s){const c=s instanceof Error?s.message:String(s);return`field "${i}": ${c}`}}},m=(o,n,i)=>{const r=o.tables[n];if(!r)return`unknown table: ${n}`;if(r.shardMode?.kind==="global")return`table "${n}" is a global (.global()) table and is not importable through the shard import path`;const e=Object.fromEntries(Object.entries(i).filter(([t])=>!y.has(t)));for(const t of Object.keys(e))if(!Object.hasOwn(r.shape,t))return`unexpected field "${t}": not declared in table "${n}"`;return h(r,e)},g=async(o,n,i)=>{try{if(o.lookupById){const r=await o.lookupById(i);return r===null?void 0:r.tableName}return await o.get(i,n)===null?void 0:n}catch{return}},w=o=>l in o?Object.fromEntries(Object.entries(o).filter(([n])=>n!==l)):o,S=async(o,n,i,r)=>{const{table:e}=i;let{doc:t}=i;if(typeof e!="string"||e.length===0)return{error:{code:"BAD_ROW",line:r,message:"row is missing `table`",table:e},kind:"error"};if(!t||typeof t!="object"||Array.isArray(t))return{error:{code:"BAD_ROW",line:r,message:"row is missing or malformed `doc`",table:e},kind:"error"};t=w(t);const s=m(n,e,t);if(s!==void 0)return{error:{code:"VALIDATION_ERROR",line:r,message:s,table:e},kind:"error"};const c=typeof t._id=="string"?t._id:void 0;if(c!==void 0){const a=await g(o,e,c);if(a===e)return{kind:"conflict"};if(a!==void 0)return{error:{code:"ID_COLLISION",line:r,message:`_id "${c}" already belongs to table "${a}"`,table:e},kind:"error"}}try{return await o.insert(e,t,{allowExplicitId:!0}),{kind:"inserted",table:e}}catch(a){const{body:d}=b(a,{fallbackCode:"INSERT_FAILED"});return{error:{code:d.code,line:r,message:d.message,table:e},kind:"error"}}},v=async(o,n,i)=>{const r=[],e={};let t=0,s=(i.startLine??1)-1;for(const c of i.rows){s+=1;const a=await S(o,n,c,s);a.kind==="error"?r.push(a.error):a.kind==="conflict"?t+=1:e[a.table]=(e[a.table]??0)+1}return{conflicts:t,errors:r,inserted:e}},E=o=>{const n=Array.isArray(o.tables)?o.tables.filter(r=>typeof r=="string"):void 0;return{batchSize:typeof o.batchSize=="number"?o.batchSize:void 0,tables:n}},I=o=>{const n=Array.isArray(o.rows)?o.rows:[],i=[];for(const e of n){if(!e||typeof e!="object")continue;const t=e;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 r=typeof o.startLine=="number"?o.startLine:void 0;return{rows:i,startLine:r}};export{O as exportShardRows,v as importShardRows,E as parseExportShardArgs,I as parseImportShardArgs,u as selectExportTables,m as validateImportRow};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{D as I}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{sql as e}from"drizzle-orm";import{sqliteInList as L}from"./param-DlozcSQu.mjs";const u=(i,t)=>{if(!t.includes("."))return i[t];let r=i;for(const $ of t.split(".")){if(r===null||typeof r!="object"||Array.isArray(r))return;r=r[$]}return r},D=(i,t)=>`${i}__fts_${t}`,o="__text__",s="__id__",A=1e3,O=(i,t)=>t.document(i),N=(i,t)=>u(i,t),_=i=>typeof i=="string"?i:i==null?"":typeof i=="number"||typeof i=="bigint"||typeof i=="boolean"?String(i):JSON.stringify(i)??"",w=(i,t,r)=>i!==void 0&&t!==void 0&&N(i,r.field)===N(t,r.field),c=(i,t)=>O(_(N(i,t.field)),I(t.language)).slice(0,A),M=(i,t)=>c(i,t).join(" "),a=50,n="__rowid__",T=i=>`${i}__ids`,E=(i,t)=>e`${e.identifier(i)}.${e.identifier(t)}`,S=(i,t,{guard:r,unmappedRowids:$})=>{const d=T(i),f=r===void 0?e``:e` AND ${r}`,R=$===void 0?e`${E(i,"rowid")} > 0`:L(E(i,"rowid"),$,!1,a);return[e`DELETE FROM ${e.identifier(i)} WHERE ${R} AND CAST(${E(i,s)} AS TEXT) = ${t}${f}`,e`DELETE FROM ${e.identifier(i)} WHERE ${E(i,"rowid")} = (SELECT ${E(d,n)} FROM ${e.identifier(d)} WHERE ${E(d,s)} = ${t}) AND ${E(i,s)} = ${t}${f}`]},U=i=>[e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(i)} USING fts5(${e.identifier(o)}, ${e.identifier(s)} UNINDEXED)`,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${i}__vocab`)} USING fts5vocab(${e.identifier(i)}, ${e.raw("instance")})`,e`CREATE TABLE IF NOT EXISTS ${e.identifier(T(i))} (${e.identifier(n)} INTEGER PRIMARY KEY, ${e.identifier(s)} TEXT NOT NULL UNIQUE)`,e`INSERT INTO ${e.identifier(i)} (rowid, ${e.identifier(o)}, ${e.identifier(s)}) SELECT 0, '', '' WHERE NOT EXISTS (SELECT 1 FROM ${e.identifier(i)} WHERE ${E(i,"rowid")} = 0)`],F=(i,t,r,$={})=>{const d=T(i),f=$.guard===void 0?e``:e` AND ${$.guard}`,R=e`MIN(COALESCE((SELECT MIN(${E(d,n)}) FROM ${e.identifier(d)}), 0), 0) - 1`;return[...S(i,t,$),e`INSERT OR REPLACE INTO ${e.identifier(d)} (${e.identifier(n)}, ${e.identifier(s)}) SELECT ${R}, ${t} WHERE 1 = 1${f}`,e`INSERT OR REPLACE INTO ${e.identifier(i)} (rowid, ${e.identifier(o)}, ${e.identifier(s)}) SELECT ${E(d,n)}, ${r}, ${E(d,s)} FROM ${e.identifier(d)} WHERE ${E(d,s)} = ${t}${f}`]},y=(i,t,r={})=>{const $=T(i),d=r.guard===void 0?e``:e` AND ${r.guard}`;return[...S(i,t,r),e`DELETE FROM ${e.identifier($)} WHERE ${E($,s)} = ${t}${d}`]},W=(i,t,r=0)=>e`SELECT ${E(i,"rowid")} AS ${e.identifier("rowid")}, ${E(i,s)} AS ${e.identifier("id")} FROM ${e.identifier(i)} WHERE ${E(i,"rowid")} > ${e.param(Math.max(0,r))} AND ${E(i,s)} IS NOT NULL ORDER BY ${E(i,"rowid")} ASC LIMIT ${e.raw(String(t))}`,b=i=>{const t=new Map;for(const r of i){const $=String(r.id);t.set($,[...t.get($)??[],Number(r.rowid)])}return t};export{w as N,D as S,y as a,T as b,W as c,F as d,M as e,U as f,b as g,c as h,s as l};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{f as t,a as e,b as p,c as m,d as f,g as n}from"./fts-companion-B7jllLhZ.mjs";import"./param-DlozcSQu.mjs";export{t as ftsCompanionDdl,e as ftsPurgeDocument,p as ftsRowidMapName,m as ftsUnmappedPage,f as ftsWriteDocument,n as groupUnmappedRows};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-
|
|
1
|
+
import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-CfKnGpV2.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-j_8glxcE.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
2
|
table_name TEXT NOT NULL,
|
|
3
3
|
shard_key TEXT NOT NULL,
|
|
4
4
|
watermark TEXT,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{applyCdcChanges as p}from"./CDC_LOG_TABLE-
|
|
1
|
+
import{applyCdcChanges as p}from"./CDC_LOG_TABLE-BFbP2eiJ.mjs";import{selectShapeRows as m}from"./selectShapeMembers-Cp98I-ot.mjs";import{diffExternalSource as g,projectExternalSourceRow as l}from"./diffExternalSource-DgDJhslq.mjs";import{stableStringify as d}from"./stableStringify-DibjylKD.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{LunoraError as i}from"@lunora/errors";import{renderSql as l,WORKERD_SQLITE_LIMITS as e}from"./param-DlozcSQu.mjs";const c=(t,n,...r)=>{if(n.length*3>e.sqlTextLength){const s=new TextEncoder().encode(n).length;if(s>e.sqlTextLength)throw new i("INTERNAL",`SQL statement is ${String(s)} bytes, over this runtime's ${String(e.sqlTextLength)}-byte limit`)}if(r.length>e.boundParams)throw new i("INTERNAL",`SQL statement binds ${String(r.length)} parameters, over this runtime's limit of ${String(e.boundParams)}`);return t.exec.call(t,n,...r)},u=(t,n)=>{const{params:r,sql:o}=l("sqlite",n);return c(t,o,...r)},d=(t,n)=>{for(const r of n)u(t,r)},g=t=>t??null,S=t=>{if(!(t==null||t===""))try{return JSON.parse(t)}catch{return}};export{S as decodeJsonColumn,g as orNull,d as runAll,u as runDrizzle,c as runSql};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{LunoraError as l}from"@lunora/errors";import{f as L,S as h}from"./fts-companion-B7jllLhZ.mjs";import{sql as r}from"drizzle-orm";import{aggregateTableName as O}from"./aggregateTableName-C7o-gpms.mjs";import{backfillSearchIndexesForTable as R}from"./backfillAggregateIndexes-D-S4qiCu.mjs";import{migrateCdcLog as x,migrateCdcMeta as N}from"./CDC_LOG_TABLE-BFbP2eiJ.mjs";import{migrateClientWatermark as C}from"./CLIENT_WATERMARK_TABLE-BdKYbah0.mjs";import{migrateCommitSeq as $}from"./COMMIT_SEQ_FIELD-D6uMUaiR.mjs";import{migrateGlobalShapeSnapshot as b}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-wWaEWj5f.mjs";import{migrateIdempotency as D}from"./IDEMPOTENCY_TABLE-DKrXVEUe.mjs";import{m as U}from"./ctx-db-relay-shapes-BcgjOtG1.mjs";import{migrateScheduleOutbox as M}from"./SCHEDULE_OUTBOX_TABLE-BHpxtEy4.mjs";import{m as G}from"./ctx-db-search-state-fIiMVPXO.mjs";import{migrateShapePokeCursor as X}from"./SHAPE_POKE_CURSOR_TABLE-Bbpou9XZ.mjs";import{runDrizzle as s,runAll as y}from"./runDrizzle-CfKnGpV2.mjs";import{D as F,d as E,e as g,t as P,i as Y,g as k,a as B,b as j,A as p}from"./do-sql-BSoH-O04.mjs";import{renderSql as v}from"./param-DlozcSQu.mjs";import{migrateDurableStreams as w}from"./appendStreamChunk-pPeR5nbF.mjs";import{rankTableName as H,sortColumnName as K}from"./RANK_TIEBREAK-D5xNdzB3.mjs";import{migrateReactorState as W}from"./REACTOR_STATE_TABLE-CBHASjH9.mjs";import{recordSchemaVersion as V}from"./SCHEMA_HISTORY_MAX_VERSIONS-CXznJRUG.mjs";const A=r`_creationTime, id`,S=(e,i,o,t,n,a)=>{const c=r.join(n.map(d=>r`${d} IS NOT NULL`),r` AND `);if(s(e,r`SELECT 1 FROM ${r.identifier(o)} WHERE ${c} GROUP BY ${t} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new l("INTERNAL",`unique index "${i}" on "${o}" ${a}: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)},z=(e,i,o,t,n,a)=>{const m=s(e,r`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${i} AND tbl_name = ${o}`).toArray()[0]?.sql;if(m==null)return;const d=_=>{const u=_.indexOf("(");return u===-1?void 0:_.slice(u,_.lastIndexOf(")")+1)},T=d(v("sqlite",E(i,o,t,n)).sql),f=d(m);T===void 0||f===void 0||T===f||(n&&S(e,i,o,t,a,"cannot be re-created with its new column list"),s(e,r`DROP INDEX IF EXISTS ${r.identifier(i)}`))},J=(e,i,o)=>s(e,r`SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ${i} AND tbl_name = ${o} LIMIT 1`).toArray().length>0,I=(e,i,o,t,n,a)=>{n&&!J(e,i,o)&&S(e,i,o,t,a,"cannot be created"),s(e,E(i,o,t,n))},Q=(e,i,o)=>{for(const t of o.indexes){const n=`${i}_${t.name}`,a=t.unique??!1,c=t.fields.map(T=>g(T)),m=r.join(c,r`, `),d=a?m:r`${m}, ${A}`;z(e,n,i,d,a,c),I(e,n,i,d,a,c)}for(const[t,n]of P(o)){if(!n.unique)continue;const a=g(t);I(e,`${i}_unique_${t}`,i,a,!0,[a])}},Z=(e,i,o)=>{if(!(!o.searchIndexes||o.searchIndexes.length===0||!Y(e))){for(const t of o.searchIndexes)y(e,L(h(i,t.name)));R(e,i,o)}},q=(e,i,o)=>{if(o.geoIndexes)for(const t of o.geoIndexes){const n=k(i,t.name);s(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(n)} (${r.identifier("__id__")} TEXT PRIMARY KEY, ${r.identifier("__geohash__")} TEXT NOT NULL, ${r.identifier("__lat__")} REAL NOT NULL, ${r.identifier("__lng__")} REAL NOT NULL)`);const a=`${i}__geo_${t.name}__btree`;s(e,E(a,n,r`${r.identifier("__geohash__")} ASC, ${r.identifier("__id__")} ASC`,!1))}},ee=(e,i,o)=>{if(o.aggregateIndexes)for(const t of o.aggregateIndexes){const n=O(i,t.name);s(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(n)} (${B} TEXT PRIMARY KEY, ${j} REAL, ${p} INTEGER NOT NULL DEFAULT 0)`),s(e,r`PRAGMA table_info(${r.identifier(n)})`).toArray().some(c=>c.name==="__count__")||s(e,r`ALTER TABLE ${r.identifier(n)} ADD COLUMN ${p} INTEGER NOT NULL DEFAULT 0`)}},re=(e,i,o)=>{if(o.rankIndexes)for(const t of o.rankIndexes){const n=H(i,t.name),a=t.sortBy.map((f,_)=>K(_)),c=a.map(f=>r`${r.identifier(f)} BLOB`),m=c.length>0?r`, ${r.join(c,r`, `)}`:r``;s(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(n)} (${r.identifier("__id__")} TEXT PRIMARY KEY, ${r.identifier("__partition__")} TEXT NOT NULL${m})`);const d=[r`${r.identifier("__partition__")} ASC`];for(const[f,_]of a.entries()){const u=t.sortBy[f]?.direction;d.push(r`${r.identifier(_)} ${r.raw(u==="desc"?"DESC":"ASC")}`)}d.push(r`${r.identifier("__id__")} ASC`);const T=`${i}__rank_${t.name}__btree`;s(e,E(T,n,r.join(d,r`, `),!1))}},he=(e,i,o={})=>{o.schemaSnapshot!==void 0&&V(e,o.schemaSnapshot.hash,o.schemaSnapshot.json),G(e);for(const[t,n]of Object.entries(i.tables))n.shardMode?.kind!=="global"&&(s(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(t)} (
|
|
2
|
+
id TEXT PRIMARY KEY,
|
|
3
|
+
_creationTime REAL NOT NULL,
|
|
4
|
+
${r.identifier(F)} TEXT NOT NULL
|
|
5
|
+
)`),s(e,E(`${t}__by_creation`,t,A,!1)),Q(e,t,n),Z(e,t,n),q(e,t,n),ee(e,t,n),re(e,t,n));o.cdc&&(x(e,{rowHistoryIndex:Object.values(i.tables).some(t=>t.dropStalePatchesMode===!0)}),N(e),C(e),X(e),U(e)),Object.values(i.tables).some(t=>t.commitOrderedMode===!0)&&$(e),W(e),D(e),M(e),b(e),w(e)};export{he as runShardMigrations};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as o}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-
|
|
1
|
+
import{sql as o}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-CfKnGpV2.mjs";import{e}from"./do-sql-BSoH-O04.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};
|
package/dist/packem_shared/{selectShapeMembers-B8gTOeOB.mjs → selectShapeMembers-Cp98I-ot.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-CfKnGpV2.mjs";import{D as p,r as d,e as h}from"./do-sql-BSoH-O04.mjs";import{sqliteInList as w}from"./param-DlozcSQu.mjs";import{c as S}from"./where-sql-x1YKldcq.mjs";import{serializeSqlValue as $}from"./serializeSqlValue-BEMMYX1n.mjs";const C={fieldRef:h,serialize:$},g=o=>{if(o.length!==0)return w(e`${e.identifier("id")}`,o,!1)},u=(o,i)=>{const r=[];i&&r.push(i);const t=S(o,C);return t&&r.push(t),r.length===0?e``:e` WHERE ${e.join(r,e` AND `)}`},v=(o,i,r)=>{const t=u(r,void 0),s=m(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${t}`).toArray(),f=[];for(const l of s){const n=d(l),{id:c}=l;n!==void 0&&typeof c=="string"&&f.push({doc:n,id:c})}return f},z=(o,i,r,t)=>{const s=new Map;if(t.length===0)return s;const f=u(r,g(t)),l=m(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${f}`).toArray();for(const n of l){const c=d(n),{id:a}=n;c!==void 0&&typeof a=="string"&&s.set(a,c)}return s};export{z as selectShapeMembers,v as selectShapeRows};
|
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.82",
|
|
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",
|
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
},
|
|
50
50
|
"dependencies": {
|
|
51
51
|
"@lunora/errors": "1.0.0-alpha.41",
|
|
52
|
-
"@lunora/platform": "1.0.0-alpha.
|
|
52
|
+
"@lunora/platform": "1.0.0-alpha.36",
|
|
53
53
|
"drizzle-orm": "^0.45.2"
|
|
54
54
|
},
|
|
55
55
|
"engines": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as I}from"@lunora/errors";import{m as x,n as y}from"./do-sql-kpl5Kt1j.mjs";import{quoteIdentifier as d}from"./quoteIdentifier-CObIFRhb.mjs";import{d as L}from"./wire-codec-C-FpWm52.mjs";const te="__lunora_admin__:",re="__lunora_relation__:",ne="__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",backfillSearch:"__lunora_admin__:backfillSearch",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",findRelated:"__lunora_admin__:findRelated",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",listReactors:"__lunora_admin__:listReactors",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",patchRows:"__lunora_admin__:patchRows",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,h=500,U=30,j=200,f="__doc__",O=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},W=e=>{const{[y]:t,...r}=e;return t===void 0?r:t===null||typeof t!="object"||Array.isArray(t)?{[y]:t,...r}:{...r,...L(t)}},q=(e,t)=>{if(!e.includes(f))return{columns:e,rows:t};const r=[];for(const s of t){const a=s[f],i=typeof a=="string"?O(a):void 0;if(i===void 0)return{columns:e,rows:t};const c=Object.fromEntries(Object.entries(s).filter(([u])=>u!==f));r.push({...c,...W(i)})}const n=e.filter(s=>s!==f),o=[],_=new Set(n);for(const s of r)for(const a of Object.keys(s))_.has(a)||(_.add(a),o.push(a));return{columns:[...n,...o],rows:r}},N=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,E=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),C=(e,t,r)=>Math.min(Math.max(e,t),r),F=(e,t)=>{const r=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(r.c)},oe=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),r=[];for(const{name:n}of t)E(n)||r.push({name:n,rowCount:F(e,d(n))});return r},P=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,A=(e,t)=>{if(E(t)||!P(e,t))throw new I("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},M=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(r=>r.name),Q={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},B=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",v=(e,t)=>{const r=t.includes(e),n=t.includes(f);if(!(!r&&!n))return r?{expression:d(e),params:[]}:{expression:`json_extract(${d(f)}, ?)`,params:[`$.${x(e)}`]}},G=(e,t)=>{const r=v(e.column,t);if(r===void 0)return;const{expression:n,params:o}=r;return e.operator==="contains"?{params:[...o,B(e.value)],sql:N(n)}:e.value===null&&(e.operator==="eq"||e.operator==="ne")?{params:o,sql:`${n} IS ${e.operator==="ne"?"NOT ":""}NULL`}:{params:[...o,e.value],sql:`${n} ${Q[e.operator]} ?`}},H=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,X=e=>{const t=H.exec(e.trim());if(t===null)return;const r=Number(t[1]),n=t[2]===void 0?void 0:Number(t[2]),o=t[3]===void 0?void 0:Number(t[3]);if(n!==void 0&&(n<1||n>12)||o!==void 0&&(o<1||o>31)||r<100)return;const _=Date.UTC(r,(n??1)-1,o??1);if(o!==void 0&&new Date(_).getUTCDate()!==o)return;let s;return o!==void 0?s=Date.UTC(r,(n??1)-1,o+1):n===void 0?s=Date.UTC(r+1,0,1):s=Date.UTC(r,n,1),{from:_,to:s}},R=(e,t,r)=>{const n=[],o=[];if(t!==""&&e.length>0){const _=e.map(a=>N(d(a)));o.push(...e.map(()=>t));const s=X(t);if(s!==void 0)for(const a of e)_.push(`(${d(a)} >= ? AND ${d(a)} < ?)`),o.push(s.from,s.to);n.push(`(${_.join(" OR ")})`)}for(const _ of r??[]){const s=G(_,e);s!==void 0&&(n.push(`(${s.sql})`),o.push(...s.params))}return n.length===0?void 0:{parameters:o,where:n.join(" AND ")}},Y=(e,t)=>{if(e===void 0)return;const r=v(e.column,t);if(r===void 0)return;const n=e.direction==="desc"?"DESC":"ASC";return{params:r.params,sql:`${r.expression} ${n}`}},ae=(e,t)=>{const{table:r}=t;A(e,r);const n=C(Math.trunc(t.limit??D),1,h),o=Math.max(0,Math.trunc(t.offset??0)),_=d(r),s=M(e,_),a=t.search?.trim()??"",i=b=>{if(t.refs===void 0)return b;const T={};for(const w of b.columns){const k=t.refs[w];k!==void 0&&(T[w]=k)}return Object.keys(T).length>0?{...b,refs:T}:b},c=R(s,a,t.filters),u=Y(t.orderBy,s),l=c===void 0?"":` WHERE ${c.where}`,m=u===void 0?"":` ORDER BY ${u.sql}`,p=c?.parameters??[],g=u?.params??[];let S;t.skipCount||(S=c===void 0?F(e,_):Number(e.exec(`SELECT COUNT(*) AS c FROM ${_}${l}`,...p).one().c));const $=e.exec(`SELECT * FROM ${_}${l}${m} LIMIT ? OFFSET ?`,...p,...g,n,o).toArray();return i({...q(s,$),sqlColumns:s,total:S})},_e=(e,t)=>{const{table:r}=t;A(e,r);const n=C(Math.trunc(t.limit??h),1,h),o=d(r),_=M(e,o),s=t.search?.trim()??"",a=R(_,s,t.filters),i=[],c=[];a!==void 0&&(i.push(a.where),c.push(...a.parameters)),t.after!==void 0&&(i.push("id > ?"),c.push(t.after));const u=i.length===0?"":` WHERE ${i.join(" AND ")}`,l=t.after===void 0?"":" ORDER BY id",m=e.exec(`SELECT id FROM ${o}${u}${l} LIMIT ?`,...c,n+1).toArray(),p=m.length>n,g=m.slice(0,n).map(S=>S.id);return{hasMore:p,ids:g}},K=(e,t,r)=>{const n=new Set(r.filter(_=>_!==f));if(!r.includes(f))return n;const o=e.exec(`SELECT ${d(f)} AS doc FROM ${t} LIMIT ?`,h).toArray();for(const{doc:_}of o){const s=typeof _=="string"?O(_):void 0;if(s!==void 0)for(const a of Object.keys(s))n.add(a)}return n},ie=(e,t)=>{const{column:r,table:n}=t;A(e,n);const o=d(n),_=M(e,o);if(!K(e,o,_).has(r))throw new I("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const s=v(r,_);if(s===void 0)throw new I("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const a=C(Math.trunc(t.limit??U),1,j),i=t.search?.trim()??"",c=R(_,i,t.filters),u=c===void 0?"":` WHERE ${c.where}`,l=c?.parameters??[],m=e.exec(`SELECT ${s.expression} AS value, COUNT(*) AS count FROM ${o}${u} GROUP BY ${s.expression} ORDER BY count DESC LIMIT ?`,...s.params,...l,...s.params,a+1).toArray();return{truncated:m.length>a,values:m.slice(0,a).map(g=>({count:Number(g.count),value:g.value}))}},ce=(e,t,r)=>{const n={},o=r.slice(0,h);for(const s of o)n[s]=[];if(o.length===0)return{references:n,storageColumns:t};const _=o.map(()=>"?").join(", ");for(const[s,a]of Object.entries(t)){if(E(s)||!P(e,s))continue;const i=d(s),c=M(e,i);for(const u of a){const l=v(u,c);if(l===void 0)continue;const m=e.exec(`SELECT id, ${l.expression} AS ref FROM ${i} WHERE ${l.expression} IN (${_})`,...l.params,...l.params,...o).toArray();for(const p of m)n[p.ref]?.push({column:u,id:p.id,table:s})}}return{references:n,storageColumns:t}},ue=e=>{const t=e.map((n,o)=>{const _=Object.values(n.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:n.admin===!0,id:o,subscriptions:_}}),r=t.reduce((n,o)=>n+o.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:r}},V=20,le=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),de=()=>({run:0,served:0}),me=()=>({drains:0,pairsSkipped:0}),fe=(e,t,r)=>({drains:e.drains+t,pairsSkipped:e.pairsSkipped+r}),pe=(e,t,r)=>({run:e.run+t,served:e.served+r}),ge=(e,t,r,n)=>({maxMs:Math.max(e.maxMs,n),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+r,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+n}),he=(e,t=V)=>{const r=new Map,n=new Map;for(const s of e){for(const a of Object.values(s.shapes??{})){const i=a.name??"(unknown shape)";r.set(i,(r.get(i)??0)+1)}for(const a of s.whispers??[])n.set(a,(n.get(a)??0)+1)}const o=[...[...r].map(([s,a])=>({kind:"shape",subscribers:a,topic:s})),...[...n].map(([s,a])=>({kind:"whisper",subscribers:a,topic:s}))];return o.sort((s,a)=>a.subscribers-s.subscribers||s.topic.localeCompare(a.topic)),{peakSubscribers:o[0]?.subscribers??0,topics:o.slice(0,t),totalConnections:e.length}};export{se as ADMIN_FUNCTIONS,te as ADMIN_FUNCTION_PREFIX,V as DEFAULT_FANOUT_TOPIC_LIMIT,ne as FLAGS_FUNCTION_PREFIX,h as MAX_PAGE_SIZE,re as RELATION_FUNCTION_PREFIX,le as createFanoutCounters,me as createGlobalPollCounters,de as createShapeProbeCounters,X as datePrefixRange,ie as facetColumn,ce as findStorageReferences,oe as listTables,ae as readTablePage,ge as recordFanoutPass,fe as recordGlobalPollPass,pe as recordShapeProbePass,_e as selectMatchingIds,he as summarizeFanoutTopics,ue as summarizeSubscriptions};
|