@lunora/shard-engine 1.0.0-alpha.48 → 1.0.0-alpha.49

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/conformance/index.mjs +1 -1
  2. package/dist/index.d.mts +3 -3
  3. package/dist/index.d.ts +3 -3
  4. package/dist/index.mjs +1 -1
  5. package/dist/packem_shared/ADMIN_FUNCTIONS-oJ7IyZP6.mjs +1 -0
  6. package/dist/packem_shared/{AGG_COUNT-DLoWGwBC.mjs → AGG_COUNT-JTc_jUaL.mjs} +1 -1
  7. package/dist/packem_shared/{CDC_LOG_TABLE-BknLCi4r.mjs → CDC_LOG_TABLE-gl0FuepJ.mjs} +1 -1
  8. package/dist/packem_shared/{CURSOR_PREFIX-CheBVHA7.mjs → CURSOR_PREFIX-C0HEpLAN.mjs} +1 -1
  9. package/dist/packem_shared/{DEFAULT_MAX_RELATION_KEYS-DrUSQbcU.mjs → DEFAULT_MAX_RELATION_KEYS-Bl7H97aj.mjs} +1 -1
  10. package/dist/packem_shared/{DEFAULT_MAX_RELAYS-JVr88opJ.mjs → DEFAULT_MAX_RELAYS-Bjx0HDbs.mjs} +1 -1
  11. package/dist/packem_shared/{DEFAULT_PROMOTION_THRESHOLDS-DFAcRYsv.mjs → DEFAULT_PROMOTION_THRESHOLDS-DpUu_mpH.mjs} +1 -1
  12. package/dist/packem_shared/{DurableStreamRunner-cq7kMv9M.mjs → DurableStreamRunner-CWqdczw1.mjs} +1 -1
  13. package/dist/packem_shared/{NotUniqueError-DJFaCeQK.mjs → NotUniqueError-Dwab63fS.mjs} +1 -1
  14. package/dist/packem_shared/{RANK_TIEBREAK-DBzb8aDX.mjs → RANK_TIEBREAK-D157XEqw.mjs} +1 -1
  15. package/dist/packem_shared/{ReactiveCache-BpnU4D2r.mjs → ReactiveCache-BngdZxr9.mjs} +1 -1
  16. package/dist/packem_shared/{ShapeDiffCache-DIqpvunX.mjs → ShapeDiffCache-CLm5XXd1.mjs} +1 -1
  17. package/dist/packem_shared/{aggregateTableName-XtEbp1DE.mjs → aggregateTableName-CGi8gxeK.mjs} +1 -1
  18. package/dist/packem_shared/{applyOnDelete-DxgoRrx9.mjs → applyOnDelete-82J3ehcF.mjs} +1 -1
  19. package/dist/packem_shared/{awaitWsDrain-KLafbnds.mjs → awaitWsDrain-CjWMVZOG.mjs} +1 -1
  20. package/dist/packem_shared/{backfillAggregateIndexes-92hEoqfj.mjs → backfillAggregateIndexes-BtC-XM_S.mjs} +1 -1
  21. package/dist/packem_shared/{buildPokeFrames-BvgtmTHk.mjs → buildPokeFrames-C8km3IhJ.mjs} +1 -1
  22. package/dist/packem_shared/{buildReprojectionMigration-DcEoW2QQ.mjs → buildReprojectionMigration-CR2RSgJd.mjs} +1 -1
  23. package/dist/packem_shared/{buildShapeDiff-CphrFTHd.mjs → buildShapeDiff-Bmn0jPTM.mjs} +1 -1
  24. package/dist/packem_shared/{computeRankPage-EhvBDg7F.mjs → computeRankPage-kpaDsuAs.mjs} +1 -1
  25. package/dist/packem_shared/createCompanionSync-Bi6IG6fu.mjs +1 -0
  26. package/dist/packem_shared/{createReplicaLink-GrknD9FY.mjs → createReplicaLink-DujqFlHs.mjs} +1 -1
  27. package/dist/packem_shared/{ctx-db-companions-BeVsHnEe.mjs → ctx-db-companions-DKBBb0u8.mjs} +1 -1
  28. package/dist/packem_shared/{ctx-db-relay-shapes-C93UQ7LV.mjs → ctx-db-relay-shapes-CakvRIFx.mjs} +1 -1
  29. package/dist/packem_shared/{defineEngineContractSuite-DwDn7oH9.mjs → defineEngineContractSuite-DzZCsNfm.mjs} +1 -1
  30. package/dist/packem_shared/{do-sql-DqQTxsj_.mjs → do-sql-bkXQEBl8.mjs} +1 -1
  31. package/dist/packem_shared/{exportShardRows-Cgt3ITwH.mjs → exportShardRows-CegEECNc.mjs} +1 -1
  32. package/dist/packem_shared/{isSoftDeleted-h1UH0yYz.mjs → isSoftDeleted-BhchsmqX.mjs} +1 -1
  33. package/dist/packem_shared/{materializeExternalRows-C4G4u8QD.mjs → materializeExternalRows-DZnPHEJw.mjs} +1 -1
  34. package/dist/packem_shared/{runShardMigrations-DS2tQC3s.mjs → runShardMigrations-PZnc7KFE.mjs} +1 -1
  35. package/dist/packem_shared/{selectExpiredIds-rvmKjueQ.mjs → selectExpiredIds-D784Mqvh.mjs} +1 -1
  36. package/dist/packem_shared/{selectShapeMembers-Ce5Jr6UH.mjs → selectShapeMembers-CKQv8nwD.mjs} +1 -1
  37. package/dist/packem_shared/{stableWireKey-DQUcEqhM.mjs → stableWireKey-9bjKL5Gy.mjs} +1 -1
  38. package/dist/packem_shared/{wire-codec-CDds5uQW.mjs → wire-codec-COhOSEe4.mjs} +1 -1
  39. package/package.json +3 -3
  40. package/dist/packem_shared/ADMIN_FUNCTIONS-DKos6M_I.mjs +0 -1
  41. package/dist/packem_shared/createCompanionSync-rsUA_OO2.mjs +0 -1
@@ -1 +1 @@
1
- import{LunoraError as $}from"@lunora/errors";import{c as nn,q as nt,S as on,l as Me,a as rn}from"./ctx-db-companions-BeVsHnEe.mjs";import{sql as i}from"drizzle-orm";import{d as sn}from"./wire-codec-CDds5uQW.mjs";import{throwingScheduler as cn,aggregateSqlFunction as De,normalizeCountArgument as an}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as Ke,encodeAggregateKey as Oe,readAggregateValue as Qe}from"./aggregateTableName-XtEbp1DE.mjs";import{mergeWhere as Q,CountRlsUnsupportedError as ze,selectIndexForGroupBy as dn,selectIndexForCount as ln,selectIndexForAggregate as un}from"./CountRlsUnsupportedError-Bdfupt3g.mjs";import{backfillSearchIndexesForTable as fn}from"./backfillAggregateIndexes-92hEoqfj.mjs";import{backfillAggregateIndexes as ur,backfillRankIndexes as fr,backfillSearchIndexes as hr}from"./backfillAggregateIndexes-92hEoqfj.mjs";import{appendCdcChange as hn}from"./CDC_LOG_TABLE-BknLCi4r.mjs";import{CDC_LOG_TABLE as pr,applyCdcChanges as gr,bumpCdcEpoch as $r,cdcCanVouchFor as yr,cdcSeqLeavingRows as Er,cdcTouchesTables as mr,cdcTrimmedError as Sr,compactCdcDocs as _r,cursorBelowRetainedFloor as Tr,minCdcReplayableSeq as Rr,minCdcSeq as vr,readCdcChangeKeys as Ar,readCdcChanges as Ir,readCdcCursor as Cr,readCdcEpoch as xr,trimCdcChanges as br}from"./CDC_LOG_TABLE-BknLCi4r.mjs";import{allocateCommitSeq as wn,COMMIT_SEQ_FIELD as pn}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{isMemoryTable as gn}from"./clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as yt}from"./computeRankPage-EhvBDg7F.mjs";import{SCAN_DEP as H}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as N,runSql as me}from"./runDrizzle-2ULFQR_k.mjs";import{D as ne,k as se,r as de,b as ke,A as Je,a as Le,e as Y,t as Pt,j as We,q as Et,i as $n,h as Ut,g as yn}from"./do-sql-DqQTxsj_.mjs";import{renderSql as Gt,unionAll as ot,WORKERD_SQLITE_LIMITS as Ht,sqliteInList as En}from"./param-DlozcSQu.mjs";import{coveringGeohashes as mn,boundingBoxGeohashes as Sn,haversineMeters as _n,pointInBoundingBox as Tn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Rn}from"./NotFoundError-BhF7FeFr.mjs";import{softDeleteScope as ae,normalizeOrderKeys as vn,buildSeekWhere as Nt,decodeCursor as Ze,applySelect as mt,encodeCursor as et,tiebreakDirectionFor as An,buildSeekBeforeWhere as In}from"./CURSOR_PREFIX-CheBVHA7.mjs";import{rankTableName as St,sortColumnName as _t,resolveRankPartition as Cn,encodePartitionKey as xn,RANK_TIEBREAK as bn}from"./RANK_TIEBREAK-DBzb8aDX.mjs";import{indexKeysForRow as Mn,buildIndexRange as Dn}from"./buildIndexRange-CBKQmHSS.mjs";import{assertFlatPredicate as Ve,resolveRelationPredicates as Tt}from"./DEFAULT_MAX_RELATION_KEYS-DrUSQbcU.mjs";import{runRowValidators as Ye,resolveWith as Rt,relationHooks as vt,applyOnDelete as kn,fanOutScalarCounts as Ln}from"./applyOnDelete-DxgoRrx9.mjs";import{guardWriter as Fn}from"./RLS_UNWRAP_SYMBOL-BWloGsd3.mjs";import{quoteIdentifier as Se}from"./quoteIdentifier-CObIFRhb.mjs";import{i as qn}from"./sql-projection-BqmxFxQU.mjs";import{createSystemReader as Wn}from"./createSystemReader-BtYeSMDb.mjs";import{ConflictError as ye}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as Bn}from"./hasTrigger-CjlwI4le.mjs";import{c as te,t as Pe,r as Be,j as Ee,i as At}from"./where-sql-DxCbgqDJ.mjs";import{CLIENT_WATERMARK_TABLE as Dr,advanceClientWatermark as kr,migrateClientWatermark as Lr,readClientWatermark as Fr}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Wr,deleteGlobalShapeSnapshot as Br,deleteGlobalShapeSnapshotsForConnection as Pr,migrateGlobalShapeSnapshot as Ur,readGlobalShapeSnapshot as Gr,writeGlobalShapeSnapshot as Hr}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-BicDuO0a.mjs";import{IDEMPOTENCY_TABLE as jr,readIdempotent as Kr,trimIdempotent as Or,writeIdempotent as Qr}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{runShardMigrations as Jr}from"./runShardMigrations-DS2tQC3s.mjs";import{SEARCH_STATE_TABLE as Yr}from"./SEARCH_STATE_TABLE-BCqn5ksa.mjs";import{selectShapeMembers as Zr,selectShapeRows as ei}from"./selectShapeMembers-Ce5Jr6UH.mjs";import{serializeSqlValue as oe}from"./serializeSqlValue-DbI1VQYM.mjs";const Pn=o=>{const r=atob(o),t=Uint8Array.from(r,a=>a.codePointAt(0)??0);return new TextDecoder().decode(t)},Un=()=>new $("BAD_REQUEST","invalid cursor"),It=16,Ct=8,X=1024,rt=(o,r)=>r.query(o),Gn=(o,r)=>{if(o.length===0)return 0;let t=0;for(const[a,u]of r.entries()){const p=a===r.length-1;let y=0;for(const S of o)(p?S.startsWith(u):S===u)&&(y+=1);if(y===0)return 0;t+=y}return t},Hn=(o,r)=>{if(!r)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",a=(t.codePointAt(0)??0)+1;if(a>=55296&&a<=57343||a>1114111)return{exact:!0,lower:o,upper:o};const u=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:u+String.fromCodePoint(a)}},Nn=(o,r,t)=>{const a={eq:(u,p)=>{if(!o.definition.filterFields?.includes(u))throw new $("INTERNAL",`field "${u}" is not a filter field of search index "${o.indexName}" on table "${r}"`);if(o.filters.length>=Ct)throw new $("BAD_REQUEST",`search index "${o.indexName}" on table "${r}": at most ${String(Ct)} .eq() filters are supported per search query`);return o.filters.push({field:u,value:p}),a},search:(u,p)=>{const y=o;if(u!==y.definition.field)throw new $("INTERNAL",`search index "${y.indexName}" on table "${r}" indexes "${y.definition.field}", not "${u}"`);const S=rt(p,t).length;if(S>It)throw new $("BAD_REQUEST",`search index "${y.indexName}" on table "${r}": at most ${String(It)} search terms are supported (got ${String(S)})`);return y.field=u,y.query=p,y.hasQuery=!0,a}};return a},jn=o=>{if(o.length>X)throw new $("BAD_REQUEST",`more than ${String(X)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Kn=o=>Math.min(o.offset+o.numItems+1,X),On=o=>btoa(`search:${String(o)}`),Qn=o=>{let r;try{r=Pn(o)}catch{return}if(!r.startsWith("search:"))return;const t=Number(r.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},zn=o=>{if(typeof o.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(o.numItems))throw new $("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(o.numItems)}`);const r=Math.max(0,Math.floor(o.numItems)),t=o.cursor?Qn(o.cursor):0;if(t===void 0)throw Un();if(t+r>=X)throw new $("BAD_REQUEST",`search pagination reaches the ${String(X)}-document limit (offset ${String(t)} + ${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,X-t-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:t}},Jn=(o,r)=>{const t=r.offset+r.numItems,a=r.numItems>0&&o.length>t;return{continueCursor:a?On(t):null,isDone:!a,page:o.slice(r.offset,t)}},Vn=o=>{if(o===void 0)return X+1;if(!Number.isFinite(o))return X;const r=Math.max(0,Math.floor(o));if(r>X)throw new $("BAD_REQUEST",`search returns at most ${String(X)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},Ue=o=>{const r=new Map;return t=>{const a=r.get(t);if(a!==void 0)return a;const u=o(Se(t));return r.set(t,u),u}},le=Se(ne),Yn=Ue(o=>`INSERT INTO ${o} (id, _creationTime, ${le}) VALUES (?, ?, ?)`),xt=Ue(o=>`UPDATE ${o} SET ${le} = ? WHERE id = ? AND ${le} = ?`),Xn=Ue(o=>`UPDATE ${o} SET _creationTime = ?, ${le} = ? WHERE id = ? AND ${le} = ?`),Zn=Ue(o=>`DELETE FROM ${o} WHERE id = ? AND ${le} = ?`),eo="SELECT changes() AS changed",bt=new Map,to="",no=o=>{const r=JSON.stringify(o),t=bt.get(r);if(t!==void 0)return t;const a=o.map(p=>i`SELECT ${i.raw(`'${p.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${i.identifier(ne)} FROM ${i.identifier(p)} WHERE id = ${to}`),{sql:u}=Gt("sqlite",i`${ot(a)} LIMIT 1`);return bt.set(r,u),u},oo=(o,r)=>r.map(()=>o),ro=/^[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=o=>{if(!ro.test(o))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},Mt=50,jt=500,Fe=Math.floor(Ht.boundParams/3),ge=Ht.boundParams,so=128,ce=(o,r,t)=>{const a=r??jt;if(o>a)throw new $("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},co=o=>{const r={eq:(t,a)=>(o.sqlConditions.push({comparator:"=",field:t,value:a}),r),gt:(t,a)=>(o.sqlConditions.push({comparator:">",field:t,value:a}),r),gte:(t,a)=>(o.sqlConditions.push({comparator:">=",field:t,value:a}),r),lt:(t,a)=>(o.sqlConditions.push({comparator:"<",field:t,value:a}),r),lte:(t,a)=>(o.sqlConditions.push({comparator:"<=",field:t,value:a}),r)};return r},ao=o=>Math.max(o,X),Kt=(o,r)=>{const t=o.filters.map(a=>i`${Y(a.field)} = ${oe(a.value)}`);return r&&t.push(r),t},lo=(o,r,t,a,u)=>{const p=rt(t.query,nt(t.definition.language));if(p.length===0)return[];const y=on(r,t.indexName),S=`${y}__vocab`,T=p.length-1,L=p.map((B,D)=>{const q=Hn(B,D===T),z=q.exact?i`${i.identifier("term")} = ${q.lower}`:i`${i.identifier("term")} >= ${q.lower} AND ${i.identifier("term")} < ${q.upper}`;return i`SELECT ${i.identifier("doc")}, ${i.raw(String(D))} AS ${i.identifier("__term__")}, COUNT(*) AS ${i.identifier("__n__")} FROM ${i.identifier(S)} WHERE ${z} GROUP BY ${i.identifier("doc")}`}),E=p.map((B,D)=>i`SUM(CASE WHEN u.${i.identifier("__term__")} = ${i.raw(String(D))} THEN u.${i.identifier("__n__")} ELSE 0 END)`),v=i`SELECT f.${i.identifier(Me)} AS ${i.identifier(Me)}, ${i.join(E,i` + `)} AS ${i.identifier("__score__")} FROM (${ot(L)}) u JOIN ${i.identifier(y)} f ON f.rowid = u.${i.identifier("doc")} GROUP BY f.${i.identifier(Me)} HAVING ${i.join(E.map(B=>i`${B} > 0`),i` AND `)}`,A=Kt(t,u);let _=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(Me)}`;A.length>0&&(_=i`${_} WHERE ${i.join(A,i` AND `)}`),_=i`${_} ORDER BY s.${i.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${i.raw(String(a))}`;const F=[];for(const B of N(o,_)){const D=Ut(B);if(D){const q=B.__score__;F.push({document:D,score:typeof q=="number"?q:Number(q??0)})}}return F},uo=(o,r,t,a,u)=>{const p=nt(t.definition.language),y=rt(t.query,p);if(y.length===0)return[];const S=Kt(t,u);let T=i`SELECT id, _creationTime, ${i.identifier(ne)} FROM ${i.identifier(r)}`;S.length>0&&(T=i`${T} WHERE ${i.join(S,i` AND `)}`),T=i`${T} ORDER BY _creationTime DESC, id ASC LIMIT ${i.raw(String(ao(a)))}`;const L=N(o,T).toArray(),E=[];for(const v of L){const A=Ut(v);if(!A)continue;const _=Gn(rn(A,t.definition),y);_>0&&E.push({creationTime:typeof A._creationTime=="number"?A._creationTime:0,doc:A,id:typeof A._id=="string"?A._id:"",score:_})}return E.sort((v,A)=>A.score-v.score||A.creationTime-v.creationTime||v.id.localeCompare(A.id)),E.slice(0,a).map(v=>({document:v.doc,score:v.score}))},Xe=(o,r,t,a)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new $("BAD_REQUEST",`geo index "${a}" on table "${t}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},fo=(o,r)=>{const t=o,a={near:(u,p)=>{if(t.within)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(Xe(u,".near() point",r,t.indexName),!Number.isFinite(p)||p<=0)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(p)}`);return t.near={point:{lat:u.lat,lng:u.lng},radiusMeters:p},a},within:u=>{if(t.near)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(Xe(u.sw,".within() sw corner",r,t.indexName),Xe(u.ne,".within() ne corner",r,t.indexName),u.sw.lat>u.ne.lat)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(u.sw.lng>u.ne.lng)throw new $("BAD_REQUEST",`geo index "${t.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 t.within={ne:{lat:u.ne.lat,lng:u.ne.lng},sw:{lat:u.sw.lat,lng:u.sw.lng}},a}};return a},ho=(o,r)=>{const t=o[r];if(t===null||typeof t!="object")return;const{lat:a,lng:u}=t;return typeof a=="number"&&typeof u=="number"?{lat:a,lng:u}:void 0},wo=(o,r)=>{const t=ho(o,r.definition.field);if(!t)return;const a=typeof o._creationTime=="number"?o._creationTime:0;if(r.near){const u=_n(r.near.point,t);return u<=r.near.radiusMeters?{creationTime:a,distance:u}:void 0}return Tn(t,r.within)?{creationTime:a,distance:0}:void 0},po=(o,r,t,a)=>{if(!t.near&&!t.within)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const u=t.near?mn(t.near.point,t.near.radiusMeters):Sn(t.within),p=yn(r,t.indexName),y=u.map(v=>i`(g.${i.identifier("__geohash__")} >= ${v} AND g.${i.identifier("__geohash__")} < ${`${v}{`})`),S=[i`(${i.join(y,i` OR `)})`];a&&S.push(a);const T=i`SELECT m.id, m._creationTime, m.${i.identifier(ne)} FROM ${i.identifier(p)} g JOIN ${i.identifier(r)} m ON m.id = g.${i.identifier("__id__")} WHERE ${i.join(S,i` AND `)}`,L=N(o,T).toArray(),E=[];for(const v of L){const A=de(v),_=A?wo(A,t):void 0;A&&_&&E.push({creationTime:_.creationTime,distance:_.distance,doc:A})}return E.sort((v,A)=>v.distance-A.distance||A.creationTime-v.creationTime),E},Ot=(o,r,t,a)=>{const u=[];for(const p of o)if(r.every(y=>y(a(p)))&&(u.push(p),typeof t=="number"&&u.length>=t))break;return u},go=(o,r,t,a,u,p=()=>{})=>{const y=t.within!==void 0,S=po(o,r,t,u).map(T=>({distanceMeters:y?null:T.distance,document:T.doc}));return p(S.length),typeof a=="number"?S.slice(0,Math.max(0,Math.floor(a))):S},Qt=(o,r,t,a,u,p=()=>{})=>{const{geo:y}=t;if(!y)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const S=t.inMemoryFilters.length>0,T=go(o,r,y,S?void 0:u,a,p);return S?Ot(T,t.inMemoryFilters,u,L=>L.document):T},zt=(o,r,t,a)=>{const u=`SELECT id, _creationTime, ${Se(ne)} FROM ${Se(o)}`,p=`ORDER BY ${t}${a===void 0?"":` LIMIT ${String(a)}`}`;return r===void 0?Be(`${u} ${p}`):Ee(`${u} WHERE `,r,` ${p}`)},$o=(o,r,t,a,u,p=()=>{})=>Qt(o,r,t,a,u,p).map(y=>y.document),yo=(o,r,t,a,u,p,y=()=>{})=>{const S=[];for(const v of t.sqlConditions)S.push(i`${Y(v.field)} ${i.raw(v.comparator)} ${oe(v.value)}`);a&&S.push(a);let T=i`SELECT id, _creationTime, ${i.identifier(ne)} FROM ${i.identifier(r)}`;S.length>0&&(T=i`${T} WHERE ${i.join(S,i` AND `)}`),T=i`${T} ORDER BY ${u}`,typeof p=="number"&&t.inMemoryFilters.length===0&&(T=i`${T} LIMIT ${i.raw(String(Math.max(0,Math.floor(p))))}`);const L=N(o,T).toArray();y(L.length);const E=[];for(const v of L){const A=de(v);if(A&&t.inMemoryFilters.every(_=>_(A))&&(E.push(A),typeof p=="number"&&E.length>=p))break}return E},$e={fieldRef:Y,serialize:oe},Jt=(o,r)=>{const t=r===void 0?void 0:o.shape[r];return t!==void 0&&qn(t)},Dt=(o,r)=>r.some(t=>Jt(o,t)),kt=(o,r,t)=>{if(Jt(o,r))throw new $("BAD_REQUEST",`${t}: "${r}" is stored as an order-preserving key, which SQL cannot reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it`)},it={fieldRef:o=>Be(We(o)),serialize:oe},Eo=o=>{let r=0;const t=[],a={fieldRef:u=>Be(We(u)),relationExists:u=>{const{childWhere:p,negated:y,parentTable:S,relation:T}=u,L=`__rel_${String(r)}`,E=t.at(-1)??S;r+=1,o(T.table,H);const v=T.kind==="one"?T.field:T.references,A=T.kind==="one"?T.references:T.field,_=Be(`${Et(L,A)} = ${Et(E,v)}`);t.push(L);const F=te(p,a,Pe);t.pop();const B=F===void 0?_:Ee(_," AND ",F),D=Ee("EXISTS (SELECT 1 FROM ",At(T.table)," AS ",At(L)," WHERE ",B,")");return y?Ee("NOT ",D):D},serialize:oe};return a},Vt=o=>{const r=o.map(t=>`${We(t.field)} ${t.direction==="desc"?"DESC":"ASC"}`);return o.some(t=>t.field==="_id"||t.field==="id")||r.push(`${We("id")} ${An(o)==="desc"?"DESC":"ASC"}`),r.join(", ")},mo={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},So=o=>{const r=o.order;return o.indexFields.length>0?o.indexFields.map(t=>({direction:r,field:t})):[{direction:r,field:"_creationTime"}]},_o=(o,r,t,a)=>{const u=o.sqlConditions.map(p=>({[p.field]:{[mo[p.comparator]??"eq"]:p.value}}));if(t&&u.push(Nt(r,Ze(t))),a&&u.push(In(r,Ze(a))),u.length!==0)return u.length===1?u[0]:{AND:u}},To=(o,r,t)=>{const a=[];for(const u of o){const p=de(u);if(p&&r.every(y=>y(p))&&(a.push(p),t!==void 0&&a.length>t))break}return a},Ro=(o,r,t,a,u,p=()=>{})=>{const y=Math.max(0,Math.floor(a.numItems)),S=So(t),T=typeof a.endCursor=="string",L=te(_o(t,S,a.cursor,a.endCursor),it,Pe),E=u&&L?Ee(L," AND ",u):u??L,v=t.inMemoryFilters.length>0,A=zt(r,E,Vt(S),v||T?void 0:y+1),_=me(o,A.text,...A.params).toArray();p(_.length);const F=To(_,t.inMemoryFilters,v||T?void 0:y);if(T){const z=F.length>=2?F[Math.floor(F.length/2)-1]:void 0;return{continueCursor:a.endCursor??null,isDone:!0,page:F,splitCursor:z?et(z,S):null}}const B=F.length>y,D=B?F.slice(0,y):F,q=D.at(-1);return{continueCursor:B&&q?et(q,S):null,isDone:!B,page:D}};class vo extends ${constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Ao=/\s/u,Io=String.fromCodePoint(0),Lt=(o,r,t)=>{if(!o.tables[r])throw new $("INTERNAL",`unknown table: ${r}`);return typeof t!="string"||t.length===0||Ao.test(t)||t.includes(Io)?null:t},Co=(o,r,t,a=()=>{},u=()=>{},p=()=>{})=>{const y=r.tables[t];if(!y)throw new $("INTERNAL",`unknown table: ${t}`);const S=ae(y.softDeleteMode,void 0),T=S?te(S,$e):void 0,L=S?te(S,it,Pe):void 0,E={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let v=0;const A=m=>{const{search:b}=E;if(!b)throw new $("INTERNAL","runSearchFetch called without a staged search");fn(o,t,y);const I=E.inMemoryFilters.length>0,x=Vn(I?void 0:m),J=$n(o)?lo(o,t,b,x,T):uo(o,t,b,x,T);return I?(v=J.length,Ot(J,E.inMemoryFilters,m,ue=>ue.document)):(m===void 0&&jn(J),J)},_=m=>A(m).map(b=>b.document),F=m=>{const b=zn(m);return Jn(_(Kn(b)),b)},B=()=>{const m=E.indexFields.length>0?E.indexFields:["_creationTime"],b=E.order==="desc"?"DESC":"ASC",I=m.map(x=>i`${Y(x)} ${i.raw(b)}`);return m.includes("_creationTime")||I.push(i`${Y("_creationTime")} ${i.raw(b)}`),m.some(x=>x==="_id"||x==="id")||I.push(i`${Y("id")} ${i.raw(b)}`),i.join(I,i`, `)},D=()=>{if(E.search||E.geo||E.indexName===void 0){u(void 0);return}u(Dn(t,E.indexName,E.indexFields,E.sqlConditions,oe))},q=m=>{D();let b=0;const I=(()=>{if(E.search){const x=_(m);return b=v,x}return E.geo?$o(o,t,E,T,m,x=>{b=x}):yo(o,t,E,T,B(),m,x=>{b=x})})();return p(Math.max(b,I.length)),I},z=()=>{if(!E.search&&!E.geo)throw new $("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);D();let m=0;const b=(()=>{if(E.search){const I=A(void 0);return m=v,I}return Qt(o,t,E,T,void 0,I=>{m=I})})();return p(Math.max(m,b.length)),b},K={async*[Symbol.asyncIterator](){if(E.search){yield*q(void 0);return}const m=[...E.inMemoryFilters];let b;E.inMemoryFilters=[];try{for(;;){const I=await K.paginate({cursor:b??null,numItems:so});for(const x of I.page)m.every(J=>J(x))&&(yield x);if(I.isDone||I.continueCursor===null)return;b=I.continueCursor}}finally{E.inMemoryFilters=m}},async collect(){return q(void 0)},async collectWithScores(){return z()},filter(m){return E.inMemoryFilters.push(m),K},async first(){return q(E.inMemoryFilters.length>0?void 0:1)[0]??null},order(m){return E.order=m==="desc"?"desc":"asc",K},async paginate(m){let b=0;if(D(),E.search){const x=F(m);return p(x.page.length),x}if(E.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const I=Ro(o,t,E,m,L,x=>{b=x});return p(Math.max(b,I.page.length)),I},async take(m){return q(m)},async unique(){const m=q(E.inMemoryFilters.length>0?void 0:2);if(m.length>1)throw new vo(`unique() on table "${t}" matched ${String(m.length)} documents; expected at most one`);return m[0]??null},withGeoIndex(m,b){const I=(y.geoIndexes??[]).find(J=>J.name===m);if(!I)throw new $("INTERNAL",`unknown geo index "${m}" on table "${t}"`);a(t,m,"geo");const x={definition:I,indexName:m};if(E.geo=x,b(fo(x,t)),!x.near&&!x.within)throw new $("INTERNAL",`geo index "${m}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return K},withIndex(m,b){const I=y.indexes.find(x=>x.name===m);if(!I)throw new $("INTERNAL",`unknown index "${m}" on table "${t}"`);return a(t,m,"index"),E.indexName=m,E.indexFields=I.fields,b&&b(co(E)),K},withSearchIndex(m,b){const I=(y.searchIndexes??[]).find(J=>J.name===m);if(!I)throw new $("INTERNAL",`unknown search index "${m}" on table "${t}"`);a(t,m,"search");const x={definition:I,field:I.field,filters:[],hasQuery:!1,indexName:m,query:""};if(E.search=x,b(Nn(x,t,nt(I.language))),!x.hasQuery)throw new $("INTERNAL",`search index "${m}" on table "${t}" requires a .search(field, query) call`);return K}};return K},Ft=(o,r,t)=>{const a={...r};for(const[u,p]of Pt(o)){if(p.serverDefault){a[u]=p.serverDefault({auth:t});continue}a[u]===void 0&&(p.defaultFn?a[u]=p.defaultFn():"defaultValue"in p&&(a[u]=p.defaultValue))}return a},qt=(o,r,t,a)=>{const u=t;for(const[p,y]of Pt(o)){if(y.serverDefault){p in r&&(u[p]=y.serverDefault({auth:a}));continue}y.onUpdateFn&&!(p in r)&&(u[p]=y.onUpdateFn())}},Wt=(o,r)=>{for(const t of Object.keys(r))if(r[t]===void 0)throw new $("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},xo=/unique constraint failed/i,bo=o=>o instanceof Error&&xo.test(o.message),tt=(o,r,t,a)=>{try{me(o,t,...a)}catch(u){throw bo(u)?new ye(`unique constraint violation on "${r}"`,"unique"):u}},qe=(o,r,t,a)=>{if(tt(o,r,t,a),me(o,eo).one().changed===0)throw new ye(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},Bt=(o,r,t,a,u,p,y)=>{const S=[];for(let v=0;v<t.length+1;v+=1){const A=[];for(let D=0;D<v;D+=1)A.push(i`${i.identifier(t[D])} IS ${p[D]}`);const _=t[v],F=a[v];if(_!==void 0&&F!==void 0){const D=F.direction==="desc"?">":"<";A.push(i`${i.identifier(_)} ${i.raw(D)} ${p[v]}`)}else A.push(i`${i.identifier(bn)} < ${y}`);const[B]=A;S.push(A.length===1&&B!==void 0?B:i`(${i.join(A,i` AND `)})`)}const T=i.join(S,i` OR `),L=N(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${u} AND (${T})`).one(),E=N(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${u}`).one();return{before:L.c,total:E.c}},ar=o=>{const{sql:r}=o,{schema:t}=o,a=o.broadcast??(()=>{});let u;const p=()=>o.inTransaction?.()===!0,y=e=>t.tables[e]?.commitOrderedMode!==!0?{}:((u===void 0||!p())&&(u=wn(r)),{[pn]:u}),S=(e,...n)=>{const s=t.tables[e]?.indexes;if(!s||s.length===0)return;const f=[];for(const h of n)h&&f.push(...Mn(s,h,oe));return f.length>0?f:void 0},{headroom:T}=o;let L=!1;const E=async e=>{const n=L;L=!0;try{return await e()}finally{L=n}},v=o.onRead??(()=>{}),A=o.onReadRange??(e=>{v(e.table,H)}),_=(e,n)=>{n!==void 0&&n!==H&&!L&&T?.recordRead(1),v(e,n)},F=o.onIndexUse??(()=>{}),B=o.onWrite??(()=>{}),D=e=>{L||T?.recordWrite(e)},q=async e=>{D(e.doc),await B(e)},{cache:z}=o,K=o.clock??(()=>Date.now()),m=o.idGenerator??(()=>crypto.randomUUID()),b=o.scheduler??cn,{globalDb:I}=o,x=o.auth??{identity:null,userId:null},J=o.cdc??!1,ue=b,Yt=Wn({scheduler:typeof ue.list=="function"&&typeof ue.get=="function"?ue:void 0,storage:o.storage}),fe=(e,n,s,f)=>{J&&!gn(t.tables[e])&&hn(r,K(),e,n,s,f)},ie=e=>t.tables[e]?.shardMode?.kind==="global",st=(e,n)=>{if(ie(e)){if(!I)throw new $("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return I}return P},Ge=e=>st(e,"cascade"),O=(e,n)=>{if(ie(e)){if(!I)throw new $("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return I}},ct=async(e,n,s,f,h)=>{h&&D(s);const l=await e.insert(n,s,f);return a({key:l,op:"insert",row:{...s,_id:l},table:n}),l},He=(e,n)=>st(e,"relation load").findMany(e,n),at=(e,n)=>(ie(e)&&_(e,H),He(e,n)),Xt=e=>!ie(e.table),dt=o.relationExistsPushDown??"auto",lt=dt!=="never",{maxRelationKeys:ut}=o,_e=(e,n,s)=>Tt(e,{fetcher:at,maxRelationKeys:ut,relationBaseWhere:s,schema:t,tableName:n}),ft=async(e,n,s,f)=>{const h=O(e,"relation grouped count");if(h)return _(e,H),Ln((W,C)=>h.count(W,C),e,n,s,f);const l=t.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);_(e,H);const c=ae(l.softDeleteMode,void 0),d={[n]:{in:s}},w=Q(Q(d,f),c),R=await _e(w,e,void 0),g=te(R,$e),k=Y(n);let M=i`SELECT ${k} AS __fk__, COUNT(*) AS count FROM ${i.identifier(e)}`;g&&(M=i`${M} WHERE ${g}`),M=i`${M} GROUP BY ${k}`;const U=N(r,M).toArray();return new Map(U.map(W=>[W.__fk__,W.count]))};let Te=0;const ht=new Set;for(const[e,n]of Object.entries(t.tables))for(const s of Object.values(n.triggerMap??{}))ht.add(`${e} ${s.timing} ${s.op}`);const Z=(e,n,s)=>ht.has(`${e} ${n} ${s}`),ee=async(e,n,s)=>{if(Te+=1,Te>Mt)throw Te-=1,new ye(`trigger recursion exceeded ${String(Mt)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await Bn({ctx:en,event:s,op:n,schema:t,tableName:s.table,timing:e})}finally{Te-=1}},{ensureBackfilledForTable:he,ensureBackfilledIndex:Ne,ensureRankBackfilled:je,ensureRankBackfilledForTable:we,syncAggregates:Re,syncCompanionsForInsert:wt,syncGeo:ve,syncRanks:pe,syncSearch:Ae}=nn({broadcast:a,indexKeysFor:(e,n)=>S(e,n),invalidateCache:(e,n,s)=>z?.invalidate(e,n,S(e,s)),recordCdc:fe,schema:t,sql:r}),pt=(e,n,s)=>{const{shardMode:f}=n;if(f?.kind==="shardBy"&&!(f.field!==void 0&&(s.partitionBy??[]).includes(f.field)))throw Object.assign(new Error(`rank index "${s.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})},gt=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),re=(e,n)=>{const s=gt(n);for(let f=0;f<s.length;f+=ge){const h=s.slice(f,f+ge),[l]=me(r,no(h),...oo(e,h)).toArray();if(!l)continue;const c=l.__t__,d=de(l);if(typeof c!="string"||!d)return;const w=l[ne];return{docJson:typeof w=="string"?w:se(w??{}),row:d,tableName:c}}},Zt=(e,n)=>{const s=[...new Set(e)],f=new Map;if(s.length===0)return f;const h=gt(n);for(let l=0;l<h.length;l+=ge){const c=h.slice(l,l+ge),d=Math.floor(ge/c.length),w=En(i`${i.identifier("id")}`,s,!1,d),R=c.map(g=>i`SELECT ${i.raw(`'${g.replaceAll("'","''")}'`)} AS __t__, id FROM ${i.identifier(g)} WHERE ${w}`);for(const g of N(r,ot(R))){const{id:k,__t__:M}=g;typeof M=="string"&&typeof k=="string"&&f.set(k,M)}}return f},$t={assertRankPartitionLocal:pt,ensureRankBackfilled:je,onRead:_,rowToDocument:de,schema:t,sql:r},P={system:Yt,async aggregate(e,n){const s=O(e,"aggregate");if(s)return _(e,H),s.aggregate(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);if(De(n.op),n.op==="count")return P.count(e,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new $("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);_(e,H);const h=ae(f.softDeleteMode,void 0),l=Q(Q(n.baseWhere,n.where),h),c=await _e(l,e,n.relationBaseWhere),d=c!==l;if(f.aggregateIndexes&&!n.baseWhere&&!d&&(!h||Dt(f,[n.field]))){const W=un(f.aggregateIndexes,n.op,n.field,n.where);if(W){Ne(e,W.index);const C=Oe(W.index.by??[],W.key),j=Ke(e,W.index.name),V=N(r,i`SELECT ${ke} AS value, ${Je} AS count FROM ${i.identifier(j)} WHERE ${Le} = ${C}`).toArray()[0];return Qe(n.op,V)}}kt(f,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const w=te(c,$e),R=De(n.op),g=Y(n.field);let k=i`SELECT ${i.raw(R)}(${g}) AS value FROM ${i.identifier(e)}`;w&&(k=i`${k} WHERE ${w}`);const U=N(r,k).toArray()[0]?.value;return U??null},asId(e,n){const s=Lt(t,e,n);if(s===null)throw new $("BAD_REQUEST",`asId("${e}", …): "${n}" is not a valid id for table "${e}"`,{status:400});return s},async count(e,n){const s=O(e,"count");if(s)return _(e,H),s.count(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=an(n);if(h.restrictsCounts)throw new ze(e);_(e,H);const l=ae(f.softDeleteMode,void 0),c=Q(Q(h.baseWhere,h.where),l),d=await _e(c,e,h.relationBaseWhere),w=d!==c;if(f.aggregateIndexes&&!h.baseWhere&&!w&&!l){const M=ln(f.aggregateIndexes,h.where);if(M){Ne(e,M.index);const U=Oe(M.index.by??[],M.key),W=Ke(e,M.index.name),C=N(r,i`SELECT ${ke} AS value FROM ${i.identifier(W)} WHERE ${Le} = ${U}`).toArray();return C[0]===void 0?0:C[0].value??0}}const R=te(d,$e);let g=i`SELECT COUNT(*) AS count FROM ${i.identifier(e)}`;return R&&(g=i`${g} WHERE ${R}`),N(r,g).one().count},async delete(e,n,s){const f=re(e,n);if(!f){const g=n===void 0?I:void 0;g&&(D(void 0),await g.delete(e,void 0,s));return}const{docJson:h,row:l,tableName:c}=f,d=t.tables[c],w=s?.hard===!0,R=!w&&d?.softDeleteMode?d.softDeleteMode.field:void 0;if(!(R&&l[R]!==null&&l[R]!==void 0)){if(Z(c,"before","delete")&&await ee("before","delete",{id:e,op:"delete",previous:l,table:c}),await kn({deletedId:e,deletedReference:g=>l[g],findHolders:async(g,k,M)=>(await Ge(g).findMany(g,{includeDeleted:w,where:{[k]:M}})).page,onCascade:(g,k)=>Ge(g).delete(k,void 0,s),onRestrict:g=>{throw new ye(g,"restrict")},onSetNull:(g,k,M)=>Ge(g).patch(k,{[M]:null}),schema:t,tableName:c}),he(c),we(c),R){const g={...l,...y(c),[R]:K(),_id:e};qe(r,c,xt(c),[se(g),e,h]),Ae(c,e,g,l),ve(c,e,void 0),Re(c,l,g),pe(c,e,l,void 0),z?.invalidate(c,e,S(c,l,g)),fe(c,e,"update",g),a({indexKeys:S(c,l,g),key:e,op:"update",row:g,table:c}),Z(c,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:c}),await q({id:e,op:"delete",table:c});return}qe(r,c,Zn(c),[e,h]),Ae(c,e,void 0),ve(c,e,void 0),Re(c,l,void 0),pe(c,e,l,void 0),z?.invalidate(c,e,S(c,l)),fe(c,e,"delete"),a({indexKeys:S(c,l),key:e,op:"delete",table:c}),Z(c,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:c}),await q({id:e,op:"delete",table:c})}},async deleteAll(e,n){if(!t.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);const s=Math.max(1,n?.chunkSize??jt),f=n?.hard===void 0?void 0:{hard:n.hard},h=ie(e)?void 0:e;let l=0;return await E(async()=>{for(;;){const d=(await P.findMany(e,{limit:s})).page.map(w=>String(w._id));if(d.length===0)break;for(const w of d)await P.delete(w,h,f),l+=1;if(d.length<s)break}}),{deleted:l}},async deleteMany(e,n,s){ce(e.length,n?.limit,"deleteMany");for(const f of e)await P.delete(f,s);return{deleted:e.length}},async deleteWhere(e,n,s){const l=(await(O(e,"deleteWhere")??P).findMany(e,{where:n})).page.map(c=>String(c._id));if(ce(l.length,s?.limit,"deleteWhere"),P.deleteMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return P.deleteMany(l,s)},async findFirst(e,n={}){return(await P.findMany(e,{...n,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,n={}){const s=await P.findFirst(e,n);if(s===null)throw new Rn(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,n={}){const s=O(e,"findMany");if(s)return _(e,H),s.findMany(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=!n.where&&!n.baseWhere;h?_(e,H):_(e);const l=vn(n.orderBy),c=n.cursor?Nt(l,Ze(n.cursor)):void 0;let d=Q(n.baseWhere,n.where);d=Q(d,ae(f.softDeleteMode,n.includeDeleted)),d=await Tt(d,{canPushExists:lt?Xt:void 0,existsPushMode:dt==="always"?"always":"auto",fetcher:at,maxRelationKeys:ut,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),c&&(d=d?{AND:[d,c]}:c);const w=lt?Eo(_):it,R=te(d,w,Pe),g=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0,k=zt(e,R,Vt(l),g===void 0?void 0:g+1),M=me(r,k.text,...k.params).toArray();h&&!L&&T?.recordRead(M.length);const U=[];for(const V of M){const G=de(V);G&&(U.push(G),!h&&typeof G._id=="string"&&_(e,G._id))}if(g===void 0)return n.with&&await Rt({groupedCounter:ft,fetcher:He,parents:U,...vt(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:mt(U,n.select,n.with)};const W=U.length>g,C=W?U.slice(0,g):U,j=C.at(-1);return n.with&&await Rt({fetcher:He,groupedCounter:ft,parents:C,...vt(n),schema:t,tableName:e,with:n.with}),{continueCursor:W&&j&&n.omitContinueCursor!==!0?et(j,l):null,isDone:!W,page:mt(C,n.select,n.with)}},async get(e,n){const s=re(e,n);if(!s){const f=n===void 0?I:void 0;return f?f.get(e):null}return _(s.tableName,e),s.row},async lookupById(e,n){const s=re(e,n);return s?(_(s.tableName,e),{row:s.row,tableName:s.tableName}):null},async groupBy(e,n){const s=O(e,"groupBy");if(s)return _(e,H),s.groupBy(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);_(e,H);const h=n.agg??{op:"count"};if(De(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=ae(f.softDeleteMode,void 0),c=Q(Q(n.baseWhere,n.where),l),d=await _e(c,e,n.relationBaseWhere),w=d!==c,R=[...n.by,h.field];if(f.aggregateIndexes&&!n.baseWhere&&!w&&(!l||Dt(f,R))){const C=dn(f.aggregateIndexes,h.op,h.field,n.by,n.where),j=C===void 0?0:Object.keys(C.partial).length,V=C?.index.by?.length??0;if(C&&(j===0||j===V)){Ne(e,C.index);const G=Ke(e,C.index.name),Ie=Object.keys(C.partial),Ce=[];if(Ie.length===(C.index.by??[]).length&&Ie.length>0){const xe=Oe(C.index.by??[],C.partial),be=N(r,i`SELECT ${ke} AS value, ${Je} AS count FROM ${i.identifier(G)} WHERE ${Le} = ${xe}`).toArray();return be.length>0&&Ce.push({key:{...C.partial},value:Qe(h.op,be[0])}),Ce}const tn=N(r,i`SELECT ${Le} AS key, ${ke} AS value, ${Je} AS count FROM ${i.identifier(G)}`).toArray();for(const xe of tn){const be=sn(JSON.parse(xe.key));Ce.push({key:be,value:Qe(h.op,xe)})}return Ce}}for(const C of R){if(C===void 0)continue;const j=C===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${C}" } })`:`groupBy(${e}, { by: [..."${C}"] })`;kt(f,C,j)}const g=te(d,$e),k=n.by.map(C=>i`${Y(C)} AS ${i.identifier(C)}`);if(h.op==="count")k.push(i`COUNT(*) AS value`);else{const{field:C}=h;if(C===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);k.push(i`${i.raw(De(h.op))}(${Y(C)}) AS value`)}let M=i`SELECT ${i.join(k,i`, `)} FROM ${i.identifier(e)}`;g&&(M=i`${M} WHERE ${g}`),M=i`${M} GROUP BY ${i.join(n.by.map(C=>Y(C)),i`, `)}`;const U=N(r,M).toArray(),W=[];for(const C of U){const j={};for(const G of n.by)j[G]=C[G]??null;const{value:V}=C;W.push({key:j,value:V==null?null:Number(V)})}return W},async insert(e,n,s){const f=O(e,"insert");if(f)return ct(f,e,n,s,!0);const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const l=Ft(h,n,x);Ye(h,l);let c;s?.clientId!==void 0?(io(s.clientId),c=s.clientId):s?.allowExplicitId&&typeof l._id=="string"?c=l._id:c=m();const d=s?.allowExplicitId&&typeof l._creationTime=="number"?l._creationTime:K(),w={...l,...y(e),_creationTime:d,_id:c};return Z(e,"before","insert")&&await ee("before","insert",{doc:{...w},id:c,op:"insert",table:e}),he(e),we(e),tt(r,e,Yn(e),[c,d,se(w)]),wt(e,c,w),Z(e,"after","insert")&&await ee("after","insert",{doc:w,id:c,op:"insert",table:e}),await q({doc:w,id:c,op:"insert",table:e}),c},async insertManyUnsafe(e,n,s){if(ce(n.length,s?.limit,"insertManyUnsafe"),n.length===0)return[];const f=O(e,"insert");if(f){const d=[];for(const w of n)D(w);for(const w of n){const R=await f.insert(e,w,{allowExplicitId:s?.allowExplicitId});a({key:R,op:"insert",row:{...w,_id:R},table:e}),d.push(R)}return d}const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);he(e),we(e);const l=[];for(let d=0;d<n.length;d+=Fe)l.push(y(e));const c=n.map((d,w)=>{const R=Ft(h,d,x),g=s?.allowExplicitId===!0&&typeof R._id=="string"?R._id:m(),k=s?.allowExplicitId===!0&&typeof R._creationTime=="number"?R._creationTime:K(),M={...R,...l[Math.floor(w/Fe)],_creationTime:k,_id:g};return{creationTime:k,document:M,id:g}});for(const d of c)D(d.document);for(let d=0;d<c.length;d+=Fe){const w=i.join(c.slice(d,d+Fe).map(g=>i`(${g.id}, ${g.creationTime}, ${se(g.document)})`),i`, `),R=Gt("sqlite",i`INSERT INTO ${i.identifier(e)} (id, _creationTime, ${i.identifier(ne)}) VALUES ${w}`);tt(r,e,R.sql,R.params)}for(const{document:d,id:w}of c)wt(e,w,d),await B({doc:d,id:w,op:"insert",table:e});return c.map(d=>d.id)},async insertMany(e,n,s){ce(n.length,s?.limit,"insertMany");const f=s?.skipDuplicates===!0,h=[],l=O(e,"insert");if(l)for(const d of n)D(d);const c=async d=>l?ct(l,e,d,void 0,!1):P.insert(e,d);for(const d of n)try{h.push(await c(d))}catch(w){if(f&&w instanceof ye&&w.kind==="unique")h.push(null);else throw w}return h},normalizeId(e,n){return Lt(t,e,n)},async patch(e,n,s){const f=re(e,s);if(!f){const R=s===void 0?I:void 0;if(R){D(n),await R.patch(e,n);return}throw new $("INTERNAL",`document not found: ${e}`)}const{docJson:h,row:l,tableName:c}=f,d=t.tables[c];if(!d)throw new $("INTERNAL",`unknown table: ${c}`);_(c,e),Wt("patch",n);const w={...l,...n,...y(c),_id:e};qt(d,n,w,x),Ye(d,w,!0),Z(c,"before","update")&&await ee("before","update",{doc:{...w},id:e,op:"update",previous:l,table:c}),he(c),we(c),qe(r,c,xt(c),[se(w),e,h]),Ae(c,e,w,l),ve(c,e,w),Re(c,l,w),pe(c,e,l,w),z?.invalidate(c,e,S(c,l,w)),fe(c,e,"update",w),a({indexKeys:S(c,l,w),key:e,op:"update",row:w,table:c}),Z(c,"after","update")&&await ee("after","update",{doc:w,id:e,op:"update",previous:l,table:c}),await q({doc:w,id:e,op:"update",table:c})},async patchMany(e,n,s){ce(e.length,n?.limit,"patchMany");for(const f of e)await P.patch(f.id,f.patch,s);return{patched:e.length}},async patchWhere(e,n,s){const l=(await(O(e,"patchWhere")??P).findMany(e,{where:n.where})).page.map(c=>({id:String(c._id),patch:n.patch}));if(ce(l.length,s?.limit,"patchWhere"),P.patchMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await P.patchMany(l,s),{patched:l.length}},query(e){const n=O(e,"query");return n?(_(e,H),n.query(e)):Co(r,t,e,F,s=>{s?A(s):_(e,H)},s=>{L||T?.recordRead(s)})},async rank(e,n,s){const f=O(e,"rank");if(f)return _(e,H),f.rank(e,n,s);F(e,n,"rank");const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const l=h.rankIndexes?.find(G=>G.name===n);if(!l)throw new $("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(pt(e,h,l),s.restrictsCounts)throw new ze(e);_(e,H),je(e,l);const c=typeof s.row=="string"?s.row:s.row._id;if(!c)return null;const d=St(e,l.name),w=l.sortBy.map((G,Ie)=>_t(Ie)),R=w.map(G=>Se(G)).join(", "),g=N(r,i`SELECT ${i.identifier("__partition__")}, ${i.raw(R)} FROM ${i.identifier(d)} WHERE ${i.identifier("__id__")} = ${c}`).toArray(),[k]=g;if(k===void 0)return null;let M=k.__partition__;const U=Q(s.baseWhere,s.where);Ve(U,t,e,"rank");const W=Cn(l,U);if(W){const G=xn(l.partitionBy??[],W);if(G!==M)return null;M=G}const C=w.map(G=>k[G]),{before:j,total:V}=Bt(r,d,w,l.sortBy,M,C,c);return{position:j+1,total:V}},async rankBefore(e,n,s){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=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(w=>w.name===n);if(!h)throw new $("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(s.restrictsCounts)throw new ze(e);_(e,H),je(e,h);const l=St(e,h.name),c=h.sortBy.map((w,R)=>_t(R)),d=h.sortBy.map((w,R)=>oe(s.sortValues[R]??null));return Bt(r,l,c,h.sortBy,s.partitionKey,d,s.rowId)},async rankPage(e,n,s={}){Ve(Q(s.baseWhere,s.where),t,e,"rankPage");const f=O(e,"rankPage");if(f)return _(e,H),f.rankPage(e,n,s);F(e,n,"rank");const{continueCursor:h,hasMore:l,rows:c}=yt($t,e,n,s);return{continueCursor:h,isDone:!l,page:c.map(d=>d.doc)}},async rankPageRows(e,n,s={}){Ve(Q(s.baseWhere,s.where),t,e,"rankPage"),F(e,n,"rank");const{directions:f,hasMore:h,rows:l}=yt($t,e,n,s);return{directions:f,hasMore:h,rows:l}},async restore(e,n){const s=re(e,n);if(!s){const l=n===void 0?I:void 0;if(l?.restore){await l.restore(e);return}throw new $("INTERNAL",`document not found: ${e}`)}const f=t.tables[s.tableName]?.softDeleteMode?.field;if(!f)throw new $("INTERNAL",`ctx.db.restore: table "${s.tableName}" is not a .softDelete() table`);const h=s.row[f]!==null&&s.row[f]!==void 0;await P.patch(e,{[f]:null},n),h&&pe(s.tableName,e,void 0,s.row)},async replace(e,n,s,f){const h=re(e,s);if(!h){const k=s===void 0?I:void 0;if(k){D(n),await k.replace(e,n,void 0,f);return}throw new $("INTERNAL",`document not found: ${e}`)}const{docJson:l,row:c,tableName:d}=h,w=t.tables[d];if(!w)throw new $("INTERNAL",`unknown table: ${d}`);Wt("replace",n);const R=f?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:K(),g={...n,...y(d),_creationTime:R,_id:e};qt(w,n,g,x),Ye(w,g),Z(d,"before","update")&&await ee("before","update",{doc:{...g},id:e,op:"update",previous:c,table:d}),he(d),we(d),qe(r,d,Xn(d),[R,se(g),e,l]),Ae(d,e,g,c),ve(d,e,g),Re(d,c,g),pe(d,e,c,g),z?.invalidate(d,e,S(d,c,g)),fe(d,e,"update",g),a({indexKeys:S(d,c,g),key:e,op:"update",row:g,table:d}),Z(d,"after","update")&&await ee("after","update",{doc:g,id:e,op:"update",previous:c,table:d}),await q({doc:g,id:e,op:"update",table:d})},async wipeShard(e){const n=new Set(e?.exclude),s=e?.tables,f=Object.entries(t.tables).filter(([d,w])=>n.has(d)||s!==void 0&&!s.includes(d)?!1:w.shardMode?.kind!=="global").map(([d])=>d);if(s!==void 0){for(const d of s)if(!t.tables[d])throw new $("INTERNAL",`wipeShard: unknown table: ${d}`)}const h={};let l=0;const{deleteAll:c}=P;if(c===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const d of f){const w=await c(d,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[d]=w.deleted,l+=w.deleted}return{deleted:l,tables:h}}},en={db:P,scheduler:b};return o.enforceRls===!0?Fn(P,t,(e,n)=>re(e,n)?.tableName,(e,n)=>Zt(e,n)):P};export{pr as CDC_LOG_TABLE,Dr as CLIENT_WATERMARK_TABLE,Wr as GLOBAL_SHAPE_SNAPSHOT_TABLE,jr as IDEMPOTENCY_TABLE,vo as NotUniqueError,Yr as SEARCH_STATE_TABLE,kr as advanceClientWatermark,gr as applyCdcChanges,Wt as assertNoExplicitUndefined,io as assertValidClientId,ur as backfillAggregateIndexes,fr as backfillRankIndexes,hr as backfillSearchIndexes,$r as bumpCdcEpoch,yr as cdcCanVouchFor,Er as cdcSeqLeavingRows,mr as cdcTouchesTables,Sr as cdcTrimmedError,_r as compactCdcDocs,ar as createShardCtxDb,Tr as cursorBelowRetainedFloor,Br as deleteGlobalShapeSnapshot,Pr as deleteGlobalShapeSnapshotsForConnection,Lr as migrateClientWatermark,Ur as migrateGlobalShapeSnapshot,Rr as minCdcReplayableSeq,vr as minCdcSeq,Lt as normalizeIdStructurally,Ar as readCdcChangeKeys,Ir as readCdcChanges,Cr as readCdcCursor,xr as readCdcEpoch,Fr as readClientWatermark,Gr as readGlobalShapeSnapshot,Kr as readIdempotent,Jr as runShardMigrations,Zr as selectShapeMembers,ei as selectShapeRows,br as trimCdcChanges,Or as trimIdempotent,Hr as writeGlobalShapeSnapshot,Qr as writeIdempotent};
1
+ import{LunoraError as $}from"@lunora/errors";import{c as nn,q as nt,S as on,l as Me,a as rn}from"./ctx-db-companions-DKBBb0u8.mjs";import{sql as i}from"drizzle-orm";import{d as sn}from"./wire-codec-COhOSEe4.mjs";import{throwingScheduler as cn,aggregateSqlFunction as De,normalizeCountArgument as an}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as je,encodeAggregateKey as Ke,readAggregateValue as Qe}from"./aggregateTableName-CGi8gxeK.mjs";import{mergeWhere as Q,CountRlsUnsupportedError as ze,selectIndexForGroupBy as dn,selectIndexForCount as ln,selectIndexForAggregate as un}from"./CountRlsUnsupportedError-Bdfupt3g.mjs";import{backfillSearchIndexesForTable as fn}from"./backfillAggregateIndexes-BtC-XM_S.mjs";import{backfillAggregateIndexes as ur,backfillRankIndexes as fr,backfillSearchIndexes as hr}from"./backfillAggregateIndexes-BtC-XM_S.mjs";import{appendCdcChange as hn}from"./CDC_LOG_TABLE-gl0FuepJ.mjs";import{CDC_LOG_TABLE as pr,applyCdcChanges as gr,bumpCdcEpoch as $r,cdcCanVouchFor as yr,cdcSeqLeavingRows as Er,cdcTouchesTables as mr,cdcTrimmedError as Sr,compactCdcDocs as _r,cursorBelowRetainedFloor as Tr,minCdcReplayableSeq as Rr,minCdcSeq as vr,readCdcChangeKeys as Ar,readCdcChanges as Ir,readCdcCursor as Cr,readCdcEpoch as xr,trimCdcChanges as br}from"./CDC_LOG_TABLE-gl0FuepJ.mjs";import{allocateCommitSeq as wn,COMMIT_SEQ_FIELD as pn}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{isMemoryTable as gn}from"./clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as yt}from"./computeRankPage-kpaDsuAs.mjs";import{SCAN_DEP as H}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as N,runSql as me}from"./runDrizzle-2ULFQR_k.mjs";import{D as ne,k as se,r as de,b as ke,A as Je,a as Le,e as Y,t as Ut,j as We,q as Et,i as $n,h as Pt,g as yn}from"./do-sql-bkXQEBl8.mjs";import{renderSql as Gt,unionAll as ot,WORKERD_SQLITE_LIMITS as Ht,sqliteInList as En}from"./param-DlozcSQu.mjs";import{coveringGeohashes as mn,boundingBoxGeohashes as Sn,haversineMeters as _n,pointInBoundingBox as Tn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Rn}from"./NotFoundError-BhF7FeFr.mjs";import{softDeleteScope as ae,normalizeOrderKeys as vn,buildSeekWhere as Nt,decodeCursor as Ze,applySelect as mt,encodeCursor as et,tiebreakDirectionFor as An,buildSeekBeforeWhere as In}from"./CURSOR_PREFIX-C0HEpLAN.mjs";import{rankTableName as St,sortColumnName as _t,resolveRankPartition as Cn,encodePartitionKey as xn,RANK_TIEBREAK as bn}from"./RANK_TIEBREAK-D157XEqw.mjs";import{indexKeysForRow as Mn,buildIndexRange as Dn}from"./buildIndexRange-CBKQmHSS.mjs";import{assertFlatPredicate as Ve,resolveRelationPredicates as Tt}from"./DEFAULT_MAX_RELATION_KEYS-Bl7H97aj.mjs";import{runRowValidators as Ye,resolveWith as Rt,relationHooks as vt,applyOnDelete as kn,fanOutScalarCounts as Ln}from"./applyOnDelete-82J3ehcF.mjs";import{guardWriter as Fn}from"./RLS_UNWRAP_SYMBOL-BWloGsd3.mjs";import{quoteIdentifier as Se}from"./quoteIdentifier-CObIFRhb.mjs";import{i as qn}from"./sql-projection-BqmxFxQU.mjs";import{createSystemReader as Wn}from"./createSystemReader-BtYeSMDb.mjs";import{ConflictError as ye}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as Bn}from"./hasTrigger-CjlwI4le.mjs";import{c as te,t as Ue,r as Be,j as Ee,i as At}from"./where-sql-DxCbgqDJ.mjs";import{CLIENT_WATERMARK_TABLE as Dr,advanceClientWatermark as kr,migrateClientWatermark as Lr,readClientWatermark as Fr}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Wr,deleteGlobalShapeSnapshot as Br,deleteGlobalShapeSnapshotsForConnection as Ur,migrateGlobalShapeSnapshot as Pr,readGlobalShapeSnapshot as Gr,writeGlobalShapeSnapshot as Hr}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-BicDuO0a.mjs";import{IDEMPOTENCY_TABLE as Or,readIdempotent as jr,trimIdempotent as Kr,writeIdempotent as Qr}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{runShardMigrations as Jr}from"./runShardMigrations-PZnc7KFE.mjs";import{SEARCH_STATE_TABLE as Yr}from"./SEARCH_STATE_TABLE-BCqn5ksa.mjs";import{selectShapeMembers as Zr,selectShapeRows as ei}from"./selectShapeMembers-CKQv8nwD.mjs";import{serializeSqlValue as oe}from"./serializeSqlValue-DbI1VQYM.mjs";const Un=o=>{const r=atob(o),t=Uint8Array.from(r,a=>a.codePointAt(0)??0);return new TextDecoder().decode(t)},Pn=()=>new $("BAD_REQUEST","invalid cursor"),It=16,Ct=8,X=1024,rt=(o,r)=>r.query(o),Gn=(o,r)=>{if(o.length===0)return 0;let t=0;for(const[a,u]of r.entries()){const p=a===r.length-1;let y=0;for(const S of o)(p?S.startsWith(u):S===u)&&(y+=1);if(y===0)return 0;t+=y}return t},Hn=(o,r)=>{if(!r)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",a=(t.codePointAt(0)??0)+1;if(a>=55296&&a<=57343||a>1114111)return{exact:!0,lower:o,upper:o};const u=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:u+String.fromCodePoint(a)}},Nn=(o,r,t)=>{const a={eq:(u,p)=>{if(!o.definition.filterFields?.includes(u))throw new $("INTERNAL",`field "${u}" is not a filter field of search index "${o.indexName}" on table "${r}"`);if(o.filters.length>=Ct)throw new $("BAD_REQUEST",`search index "${o.indexName}" on table "${r}": at most ${String(Ct)} .eq() filters are supported per search query`);return o.filters.push({field:u,value:p}),a},search:(u,p)=>{const y=o;if(u!==y.definition.field)throw new $("INTERNAL",`search index "${y.indexName}" on table "${r}" indexes "${y.definition.field}", not "${u}"`);const S=rt(p,t).length;if(S>It)throw new $("BAD_REQUEST",`search index "${y.indexName}" on table "${r}": at most ${String(It)} search terms are supported (got ${String(S)})`);return y.field=u,y.query=p,y.hasQuery=!0,a}};return a},On=o=>{if(o.length>X)throw new $("BAD_REQUEST",`more than ${String(X)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},jn=o=>Math.min(o.offset+o.numItems+1,X),Kn=o=>btoa(`search:${String(o)}`),Qn=o=>{let r;try{r=Un(o)}catch{return}if(!r.startsWith("search:"))return;const t=Number(r.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},zn=o=>{if(typeof o.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(o.numItems))throw new $("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(o.numItems)}`);const r=Math.max(0,Math.floor(o.numItems)),t=o.cursor?Qn(o.cursor):0;if(t===void 0)throw Pn();if(t+r>=X)throw new $("BAD_REQUEST",`search pagination reaches the ${String(X)}-document limit (offset ${String(t)} + ${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,X-t-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:t}},Jn=(o,r)=>{const t=r.offset+r.numItems,a=r.numItems>0&&o.length>t;return{continueCursor:a?Kn(t):null,isDone:!a,page:o.slice(r.offset,t)}},Vn=o=>{if(o===void 0)return X+1;if(!Number.isFinite(o))return X;const r=Math.max(0,Math.floor(o));if(r>X)throw new $("BAD_REQUEST",`search returns at most ${String(X)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},Pe=o=>{const r=new Map;return t=>{const a=r.get(t);if(a!==void 0)return a;const u=o(Se(t));return r.set(t,u),u}},le=Se(ne),Yn=Pe(o=>`INSERT INTO ${o} (id, _creationTime, ${le}) VALUES (?, ?, ?)`),xt=Pe(o=>`UPDATE ${o} SET ${le} = ? WHERE id = ? AND ${le} = ?`),Xn=Pe(o=>`UPDATE ${o} SET _creationTime = ?, ${le} = ? WHERE id = ? AND ${le} = ?`),Zn=Pe(o=>`DELETE FROM ${o} WHERE id = ? AND ${le} = ?`),eo="SELECT changes() AS changed",bt=new Map,to="",no=o=>{const r=JSON.stringify(o),t=bt.get(r);if(t!==void 0)return t;const a=o.map(p=>i`SELECT ${i.raw(`'${p.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${i.identifier(ne)} FROM ${i.identifier(p)} WHERE id = ${to}`),{sql:u}=Gt("sqlite",i`${ot(a)} LIMIT 1`);return bt.set(r,u),u},oo=(o,r)=>r.map(()=>o),ro=/^[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=o=>{if(!ro.test(o))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},Mt=50,Ot=500,Fe=Math.floor(Ht.boundParams/3),ge=Ht.boundParams,so=128,ce=(o,r,t)=>{const a=r??Ot;if(o>a)throw new $("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},co=o=>{const r={eq:(t,a)=>(o.sqlConditions.push({comparator:"=",field:t,value:a}),r),gt:(t,a)=>(o.sqlConditions.push({comparator:">",field:t,value:a}),r),gte:(t,a)=>(o.sqlConditions.push({comparator:">=",field:t,value:a}),r),lt:(t,a)=>(o.sqlConditions.push({comparator:"<",field:t,value:a}),r),lte:(t,a)=>(o.sqlConditions.push({comparator:"<=",field:t,value:a}),r)};return r},ao=o=>Math.max(o,X),jt=(o,r)=>{const t=o.filters.map(a=>i`${Y(a.field)} = ${oe(a.value)}`);return r&&t.push(r),t},lo=(o,r,t,a,u)=>{const p=rt(t.query,nt(t.definition.language));if(p.length===0)return[];const y=on(r,t.indexName),S=`${y}__vocab`,T=p.length-1,L=p.map((B,D)=>{const q=Hn(B,D===T),z=q.exact?i`${i.identifier("term")} = ${q.lower}`:i`${i.identifier("term")} >= ${q.lower} AND ${i.identifier("term")} < ${q.upper}`;return i`SELECT ${i.identifier("doc")}, ${i.raw(String(D))} AS ${i.identifier("__term__")}, COUNT(*) AS ${i.identifier("__n__")} FROM ${i.identifier(S)} WHERE ${z} GROUP BY ${i.identifier("doc")}`}),E=p.map((B,D)=>i`SUM(CASE WHEN u.${i.identifier("__term__")} = ${i.raw(String(D))} THEN u.${i.identifier("__n__")} ELSE 0 END)`),v=i`SELECT f.${i.identifier(Me)} AS ${i.identifier(Me)}, ${i.join(E,i` + `)} AS ${i.identifier("__score__")} FROM (${ot(L)}) u JOIN ${i.identifier(y)} f ON f.rowid = u.${i.identifier("doc")} GROUP BY f.${i.identifier(Me)} HAVING ${i.join(E.map(B=>i`${B} > 0`),i` AND `)}`,A=jt(t,u);let _=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(Me)}`;A.length>0&&(_=i`${_} WHERE ${i.join(A,i` AND `)}`),_=i`${_} ORDER BY s.${i.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${i.raw(String(a))}`;const F=[];for(const B of N(o,_)){const D=Pt(B);if(D){const q=B.__score__;F.push({document:D,score:typeof q=="number"?q:Number(q??0)})}}return F},uo=(o,r,t,a,u)=>{const p=nt(t.definition.language),y=rt(t.query,p);if(y.length===0)return[];const S=jt(t,u);let T=i`SELECT id, _creationTime, ${i.identifier(ne)} FROM ${i.identifier(r)}`;S.length>0&&(T=i`${T} WHERE ${i.join(S,i` AND `)}`),T=i`${T} ORDER BY _creationTime DESC, id ASC LIMIT ${i.raw(String(ao(a)))}`;const L=N(o,T).toArray(),E=[];for(const v of L){const A=Pt(v);if(!A)continue;const _=Gn(rn(A,t.definition),y);_>0&&E.push({creationTime:typeof A._creationTime=="number"?A._creationTime:0,doc:A,id:typeof A._id=="string"?A._id:"",score:_})}return E.sort((v,A)=>A.score-v.score||A.creationTime-v.creationTime||v.id.localeCompare(A.id)),E.slice(0,a).map(v=>({document:v.doc,score:v.score}))},Xe=(o,r,t,a)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new $("BAD_REQUEST",`geo index "${a}" on table "${t}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},fo=(o,r)=>{const t=o,a={near:(u,p)=>{if(t.within)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(Xe(u,".near() point",r,t.indexName),!Number.isFinite(p)||p<=0)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(p)}`);return t.near={point:{lat:u.lat,lng:u.lng},radiusMeters:p},a},within:u=>{if(t.near)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(Xe(u.sw,".within() sw corner",r,t.indexName),Xe(u.ne,".within() ne corner",r,t.indexName),u.sw.lat>u.ne.lat)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(u.sw.lng>u.ne.lng)throw new $("BAD_REQUEST",`geo index "${t.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 t.within={ne:{lat:u.ne.lat,lng:u.ne.lng},sw:{lat:u.sw.lat,lng:u.sw.lng}},a}};return a},ho=(o,r)=>{const t=o[r];if(t===null||typeof t!="object")return;const{lat:a,lng:u}=t;return typeof a=="number"&&typeof u=="number"?{lat:a,lng:u}:void 0},wo=(o,r)=>{const t=ho(o,r.definition.field);if(!t)return;const a=typeof o._creationTime=="number"?o._creationTime:0;if(r.near){const u=_n(r.near.point,t);return u<=r.near.radiusMeters?{creationTime:a,distance:u}:void 0}return Tn(t,r.within)?{creationTime:a,distance:0}:void 0},po=(o,r,t,a)=>{if(!t.near&&!t.within)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const u=t.near?mn(t.near.point,t.near.radiusMeters):Sn(t.within),p=yn(r,t.indexName),y=u.map(v=>i`(g.${i.identifier("__geohash__")} >= ${v} AND g.${i.identifier("__geohash__")} < ${`${v}{`})`),S=[i`(${i.join(y,i` OR `)})`];a&&S.push(a);const T=i`SELECT m.id, m._creationTime, m.${i.identifier(ne)} FROM ${i.identifier(p)} g JOIN ${i.identifier(r)} m ON m.id = g.${i.identifier("__id__")} WHERE ${i.join(S,i` AND `)}`,L=N(o,T).toArray(),E=[];for(const v of L){const A=de(v),_=A?wo(A,t):void 0;A&&_&&E.push({creationTime:_.creationTime,distance:_.distance,doc:A})}return E.sort((v,A)=>v.distance-A.distance||A.creationTime-v.creationTime),E},Kt=(o,r,t,a)=>{const u=[];for(const p of o)if(r.every(y=>y(a(p)))&&(u.push(p),typeof t=="number"&&u.length>=t))break;return u},go=(o,r,t,a,u,p=()=>{})=>{const y=t.within!==void 0,S=po(o,r,t,u).map(T=>({distanceMeters:y?null:T.distance,document:T.doc}));return p(S.length),typeof a=="number"?S.slice(0,Math.max(0,Math.floor(a))):S},Qt=(o,r,t,a,u,p=()=>{})=>{const{geo:y}=t;if(!y)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const S=t.inMemoryFilters.length>0,T=go(o,r,y,S?void 0:u,a,p);return S?Kt(T,t.inMemoryFilters,u,L=>L.document):T},zt=(o,r,t,a)=>{const u=`SELECT id, _creationTime, ${Se(ne)} FROM ${Se(o)}`,p=`ORDER BY ${t}${a===void 0?"":` LIMIT ${String(a)}`}`;return r===void 0?Be(`${u} ${p}`):Ee(`${u} WHERE `,r,` ${p}`)},$o=(o,r,t,a,u,p=()=>{})=>Qt(o,r,t,a,u,p).map(y=>y.document),yo=(o,r,t,a,u,p,y=()=>{})=>{const S=[];for(const v of t.sqlConditions)S.push(i`${Y(v.field)} ${i.raw(v.comparator)} ${oe(v.value)}`);a&&S.push(a);let T=i`SELECT id, _creationTime, ${i.identifier(ne)} FROM ${i.identifier(r)}`;S.length>0&&(T=i`${T} WHERE ${i.join(S,i` AND `)}`),T=i`${T} ORDER BY ${u}`,typeof p=="number"&&t.inMemoryFilters.length===0&&(T=i`${T} LIMIT ${i.raw(String(Math.max(0,Math.floor(p))))}`);const L=N(o,T).toArray();y(L.length);const E=[];for(const v of L){const A=de(v);if(A&&t.inMemoryFilters.every(_=>_(A))&&(E.push(A),typeof p=="number"&&E.length>=p))break}return E},$e={fieldRef:Y,serialize:oe},Jt=(o,r)=>{const t=r===void 0?void 0:o.shape[r];return t!==void 0&&qn(t)},Dt=(o,r)=>r.some(t=>Jt(o,t)),kt=(o,r,t)=>{if(Jt(o,r))throw new $("BAD_REQUEST",`${t}: "${r}" is stored as an order-preserving key, which SQL cannot reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it`)},it={fieldRef:o=>Be(We(o)),serialize:oe},Eo=o=>{let r=0;const t=[],a={fieldRef:u=>Be(We(u)),relationExists:u=>{const{childWhere:p,negated:y,parentTable:S,relation:T}=u,L=`__rel_${String(r)}`,E=t.at(-1)??S;r+=1,o(T.table,H);const v=T.kind==="one"?T.field:T.references,A=T.kind==="one"?T.references:T.field,_=Be(`${Et(L,A)} = ${Et(E,v)}`);t.push(L);const F=te(p,a,Ue);t.pop();const B=F===void 0?_:Ee(_," AND ",F),D=Ee("EXISTS (SELECT 1 FROM ",At(T.table)," AS ",At(L)," WHERE ",B,")");return y?Ee("NOT ",D):D},serialize:oe};return a},Vt=o=>{const r=o.map(t=>`${We(t.field)} ${t.direction==="desc"?"DESC":"ASC"}`);return o.some(t=>t.field==="_id"||t.field==="id")||r.push(`${We("id")} ${An(o)==="desc"?"DESC":"ASC"}`),r.join(", ")},mo={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},So=o=>{const r=o.order;return o.indexFields.length>0?o.indexFields.map(t=>({direction:r,field:t})):[{direction:r,field:"_creationTime"}]},_o=(o,r,t,a)=>{const u=o.sqlConditions.map(p=>({[p.field]:{[mo[p.comparator]??"eq"]:p.value}}));if(t&&u.push(Nt(r,Ze(t))),a&&u.push(In(r,Ze(a))),u.length!==0)return u.length===1?u[0]:{AND:u}},To=(o,r,t)=>{const a=[];for(const u of o){const p=de(u);if(p&&r.every(y=>y(p))&&(a.push(p),t!==void 0&&a.length>t))break}return a},Ro=(o,r,t,a,u,p=()=>{})=>{const y=Math.max(0,Math.floor(a.numItems)),S=So(t),T=typeof a.endCursor=="string",L=te(_o(t,S,a.cursor,a.endCursor),it,Ue),E=u&&L?Ee(L," AND ",u):u??L,v=t.inMemoryFilters.length>0,A=zt(r,E,Vt(S),v||T?void 0:y+1),_=me(o,A.text,...A.params).toArray();p(_.length);const F=To(_,t.inMemoryFilters,v||T?void 0:y);if(T){const z=F.length>=2?F[Math.floor(F.length/2)-1]:void 0;return{continueCursor:a.endCursor??null,isDone:!0,page:F,splitCursor:z?et(z,S):null}}const B=F.length>y,D=B?F.slice(0,y):F,q=D.at(-1);return{continueCursor:B&&q?et(q,S):null,isDone:!B,page:D}};class vo extends ${constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Ao=/\s/u,Io=String.fromCodePoint(0),Lt=(o,r,t)=>{if(!o.tables[r])throw new $("INTERNAL",`unknown table: ${r}`);return typeof t!="string"||t.length===0||Ao.test(t)||t.includes(Io)?null:t},Co=(o,r,t,a=()=>{},u=()=>{},p=()=>{})=>{const y=r.tables[t];if(!y)throw new $("INTERNAL",`unknown table: ${t}`);const S=ae(y.softDeleteMode,void 0),T=S?te(S,$e):void 0,L=S?te(S,it,Ue):void 0,E={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let v=0;const A=m=>{const{search:b}=E;if(!b)throw new $("INTERNAL","runSearchFetch called without a staged search");fn(o,t,y);const I=E.inMemoryFilters.length>0,x=Vn(I?void 0:m),J=$n(o)?lo(o,t,b,x,T):uo(o,t,b,x,T);return I?(v=J.length,Kt(J,E.inMemoryFilters,m,ue=>ue.document)):(m===void 0&&On(J),J)},_=m=>A(m).map(b=>b.document),F=m=>{const b=zn(m);return Jn(_(jn(b)),b)},B=()=>{const m=E.indexFields.length>0?E.indexFields:["_creationTime"],b=E.order==="desc"?"DESC":"ASC",I=m.map(x=>i`${Y(x)} ${i.raw(b)}`);return m.includes("_creationTime")||I.push(i`${Y("_creationTime")} ${i.raw(b)}`),m.some(x=>x==="_id"||x==="id")||I.push(i`${Y("id")} ${i.raw(b)}`),i.join(I,i`, `)},D=()=>{if(E.search||E.geo||E.indexName===void 0){u(void 0);return}u(Dn(t,E.indexName,E.indexFields,E.sqlConditions,oe))},q=m=>{D();let b=0;const I=(()=>{if(E.search){const x=_(m);return b=v,x}return E.geo?$o(o,t,E,T,m,x=>{b=x}):yo(o,t,E,T,B(),m,x=>{b=x})})();return p(Math.max(b,I.length)),I},z=()=>{if(!E.search&&!E.geo)throw new $("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);D();let m=0;const b=(()=>{if(E.search){const I=A(void 0);return m=v,I}return Qt(o,t,E,T,void 0,I=>{m=I})})();return p(Math.max(m,b.length)),b},j={async*[Symbol.asyncIterator](){if(E.search){yield*q(void 0);return}const m=[...E.inMemoryFilters];let b;E.inMemoryFilters=[];try{for(;;){const I=await j.paginate({cursor:b??null,numItems:so});for(const x of I.page)m.every(J=>J(x))&&(yield x);if(I.isDone||I.continueCursor===null)return;b=I.continueCursor}}finally{E.inMemoryFilters=m}},async collect(){return q(void 0)},async collectWithScores(){return z()},filter(m){return E.inMemoryFilters.push(m),j},async first(){return q(E.inMemoryFilters.length>0?void 0:1)[0]??null},order(m){return E.order=m==="desc"?"desc":"asc",j},async paginate(m){let b=0;if(D(),E.search){const x=F(m);return p(x.page.length),x}if(E.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const I=Ro(o,t,E,m,L,x=>{b=x});return p(Math.max(b,I.page.length)),I},async take(m){return q(m)},async unique(){const m=q(E.inMemoryFilters.length>0?void 0:2);if(m.length>1)throw new vo(`unique() on table "${t}" matched ${String(m.length)} documents; expected at most one`);return m[0]??null},withGeoIndex(m,b){const I=(y.geoIndexes??[]).find(J=>J.name===m);if(!I)throw new $("INTERNAL",`unknown geo index "${m}" on table "${t}"`);a(t,m,"geo");const x={definition:I,indexName:m};if(E.geo=x,b(fo(x,t)),!x.near&&!x.within)throw new $("INTERNAL",`geo index "${m}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return j},withIndex(m,b){const I=y.indexes.find(x=>x.name===m);if(!I)throw new $("INTERNAL",`unknown index "${m}" on table "${t}"`);return a(t,m,"index"),E.indexName=m,E.indexFields=I.fields,b&&b(co(E)),j},withSearchIndex(m,b){const I=(y.searchIndexes??[]).find(J=>J.name===m);if(!I)throw new $("INTERNAL",`unknown search index "${m}" on table "${t}"`);a(t,m,"search");const x={definition:I,field:I.field,filters:[],hasQuery:!1,indexName:m,query:""};if(E.search=x,b(Nn(x,t,nt(I.language))),!x.hasQuery)throw new $("INTERNAL",`search index "${m}" on table "${t}" requires a .search(field, query) call`);return j}};return j},Ft=(o,r,t)=>{const a={...r};for(const[u,p]of Ut(o)){if(p.serverDefault){a[u]=p.serverDefault({auth:t});continue}a[u]===void 0&&(p.defaultFn?a[u]=p.defaultFn():"defaultValue"in p&&(a[u]=p.defaultValue))}return a},qt=(o,r,t,a)=>{const u=t;for(const[p,y]of Ut(o)){if(y.serverDefault){p in r&&(u[p]=y.serverDefault({auth:a}));continue}y.onUpdateFn&&!(p in r)&&(u[p]=y.onUpdateFn())}},Wt=(o,r)=>{for(const t of Object.keys(r))if(r[t]===void 0)throw new $("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},xo=/unique constraint failed/i,bo=o=>o instanceof Error&&xo.test(o.message),tt=(o,r,t,a)=>{try{me(o,t,...a)}catch(u){throw bo(u)?new ye(`unique constraint violation on "${r}"`,"unique"):u}},qe=(o,r,t,a)=>{if(tt(o,r,t,a),me(o,eo).one().changed===0)throw new ye(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},Bt=(o,r,t,a,u,p,y)=>{const S=[];for(let v=0;v<t.length+1;v+=1){const A=[];for(let D=0;D<v;D+=1)A.push(i`${i.identifier(t[D])} IS ${p[D]}`);const _=t[v],F=a[v];if(_!==void 0&&F!==void 0){const D=F.direction==="desc"?">":"<";A.push(i`${i.identifier(_)} ${i.raw(D)} ${p[v]}`)}else A.push(i`${i.identifier(bn)} < ${y}`);const[B]=A;S.push(A.length===1&&B!==void 0?B:i`(${i.join(A,i` AND `)})`)}const T=i.join(S,i` OR `),L=N(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${u} AND (${T})`).one(),E=N(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${u}`).one();return{before:L.c,total:E.c}},ar=o=>{const{sql:r}=o,{schema:t}=o,a=o.broadcast??(()=>{});let u;const p=()=>o.inTransaction?.()===!0,y=e=>t.tables[e]?.commitOrderedMode!==!0?{}:((u===void 0||!p())&&(u=wn(r)),{[pn]:u}),S=(e,...n)=>{const s=t.tables[e]?.indexes;if(!s||s.length===0)return;const f=[];for(const h of n)h&&f.push(...Mn(s,h,oe));return f.length>0?f:void 0},{headroom:T}=o;let L=!1;const E=async e=>{const n=L;L=!0;try{return await e()}finally{L=n}},v=o.onRead??(()=>{}),A=o.onReadRange??(e=>{v(e.table,H)}),_=(e,n)=>{n!==void 0&&n!==H&&!L&&T?.recordRead(1),v(e,n)},F=o.onIndexUse??(()=>{}),B=o.onWrite??(()=>{}),D=e=>{L||T?.recordWrite(e)},q=async e=>{D(e.doc),await B(e)},{cache:z}=o,j=o.clock??(()=>Date.now()),m=o.idGenerator??(()=>crypto.randomUUID()),b=o.scheduler??cn,{globalDb:I}=o,x=o.auth??{identity:null,userId:null},J=o.cdc??!1,ue=b,Yt=Wn({scheduler:typeof ue.list=="function"&&typeof ue.get=="function"?ue:void 0,storage:o.storage}),fe=(e,n,s,f)=>{J&&!gn(t.tables[e])&&hn(r,j(),e,n,s,f)},ie=e=>t.tables[e]?.shardMode?.kind==="global",st=(e,n)=>{if(ie(e)){if(!I)throw new $("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return I}return U},Ge=e=>st(e,"cascade"),K=(e,n)=>{if(ie(e)){if(!I)throw new $("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return I}},ct=async(e,n,s,f,h)=>{h&&D(s);const l=await e.insert(n,s,f);return a({key:l,op:"insert",row:{...s,_id:l},table:n}),l},He=(e,n)=>st(e,"relation load").findMany(e,n),at=(e,n)=>(ie(e)&&_(e,H),He(e,n)),Xt=e=>!ie(e.table),dt=o.relationExistsPushDown??"auto",lt=dt!=="never",{maxRelationKeys:ut}=o,_e=(e,n,s)=>Tt(e,{fetcher:at,maxRelationKeys:ut,relationBaseWhere:s,schema:t,tableName:n}),ft=async(e,n,s,f)=>{const h=K(e,"relation grouped count");if(h)return _(e,H),Ln((W,C)=>h.count(W,C),e,n,s,f);const l=t.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);_(e,H);const c=ae(l.softDeleteMode,void 0),d={[n]:{in:s}},w=Q(Q(d,f),c),R=await _e(w,e,void 0),g=te(R,$e),k=Y(n);let M=i`SELECT ${k} AS __fk__, COUNT(*) AS count FROM ${i.identifier(e)}`;g&&(M=i`${M} WHERE ${g}`),M=i`${M} GROUP BY ${k}`;const P=N(r,M).toArray();return new Map(P.map(W=>[W.__fk__,W.count]))};let Te=0;const ht=new Set;for(const[e,n]of Object.entries(t.tables))for(const s of Object.values(n.triggerMap??{}))ht.add(`${e} ${s.timing} ${s.op}`);const Z=(e,n,s)=>ht.has(`${e} ${n} ${s}`),ee=async(e,n,s)=>{if(Te+=1,Te>Mt)throw Te-=1,new ye(`trigger recursion exceeded ${String(Mt)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await Bn({ctx:en,event:s,op:n,schema:t,tableName:s.table,timing:e})}finally{Te-=1}},{ensureBackfilledForTable:he,ensureBackfilledIndex:Ne,ensureRankBackfilled:Oe,ensureRankBackfilledForTable:we,syncAggregates:Re,syncCompanionsForInsert:wt,syncGeo:ve,syncRanks:pe,syncSearch:Ae}=nn({broadcast:a,indexKeysFor:(e,n)=>S(e,n),invalidateCache:(e,n,s)=>z?.invalidate(e,n,S(e,s)),recordCdc:fe,schema:t,sql:r}),pt=(e,n,s)=>{const{shardMode:f}=n;if(f?.kind==="shardBy"&&!(f.field!==void 0&&(s.partitionBy??[]).includes(f.field)))throw Object.assign(new Error(`rank index "${s.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})},gt=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),re=(e,n)=>{const s=gt(n);for(let f=0;f<s.length;f+=ge){const h=s.slice(f,f+ge),[l]=me(r,no(h),...oo(e,h)).toArray();if(!l)continue;const c=l.__t__,d=de(l);if(typeof c!="string"||!d)return;const w=l[ne];return{docJson:typeof w=="string"?w:se(w??{}),row:d,tableName:c}}},Zt=(e,n)=>{const s=[...new Set(e)],f=new Map;if(s.length===0)return f;const h=gt(n);for(let l=0;l<h.length;l+=ge){const c=h.slice(l,l+ge),d=Math.floor(ge/c.length),w=En(i`${i.identifier("id")}`,s,!1,d),R=c.map(g=>i`SELECT ${i.raw(`'${g.replaceAll("'","''")}'`)} AS __t__, id FROM ${i.identifier(g)} WHERE ${w}`);for(const g of N(r,ot(R))){const{id:k,__t__:M}=g;typeof M=="string"&&typeof k=="string"&&f.set(k,M)}}return f},$t={assertRankPartitionLocal:pt,ensureRankBackfilled:Oe,onRead:_,rowToDocument:de,schema:t,sql:r},U={system:Yt,async aggregate(e,n){const s=K(e,"aggregate");if(s)return _(e,H),s.aggregate(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);if(De(n.op),n.op==="count")return U.count(e,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new $("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);_(e,H);const h=ae(f.softDeleteMode,void 0),l=Q(Q(n.baseWhere,n.where),h),c=await _e(l,e,n.relationBaseWhere),d=c!==l;if(f.aggregateIndexes&&!n.baseWhere&&!d&&(!h||Dt(f,[n.field]))){const W=un(f.aggregateIndexes,n.op,n.field,n.where);if(W){Ne(e,W.index);const C=Ke(W.index.by??[],W.key),O=je(e,W.index.name),V=N(r,i`SELECT ${ke} AS value, ${Je} AS count FROM ${i.identifier(O)} WHERE ${Le} = ${C}`).toArray()[0];return Qe(n.op,V)}}kt(f,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const w=te(c,$e),R=De(n.op),g=Y(n.field);let k=i`SELECT ${i.raw(R)}(${g}) AS value FROM ${i.identifier(e)}`;w&&(k=i`${k} WHERE ${w}`);const P=N(r,k).toArray()[0]?.value;return P??null},asId(e,n){const s=Lt(t,e,n);if(s===null)throw new $("BAD_REQUEST",`asId("${e}", …): "${n}" is not a valid id for table "${e}"`,{status:400});return s},async count(e,n){const s=K(e,"count");if(s)return _(e,H),s.count(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=an(n);if(h.restrictsCounts)throw new ze(e);_(e,H);const l=ae(f.softDeleteMode,void 0),c=Q(Q(h.baseWhere,h.where),l),d=await _e(c,e,h.relationBaseWhere),w=d!==c;if(f.aggregateIndexes&&!h.baseWhere&&!w&&!l){const M=ln(f.aggregateIndexes,h.where);if(M){Ne(e,M.index);const P=Ke(M.index.by??[],M.key),W=je(e,M.index.name),C=N(r,i`SELECT ${ke} AS value FROM ${i.identifier(W)} WHERE ${Le} = ${P}`).toArray();return C[0]===void 0?0:C[0].value??0}}const R=te(d,$e);let g=i`SELECT COUNT(*) AS count FROM ${i.identifier(e)}`;return R&&(g=i`${g} WHERE ${R}`),N(r,g).one().count},async delete(e,n,s){const f=re(e,n);if(!f){const g=n===void 0?I:void 0;g&&(D(void 0),await g.delete(e,void 0,s));return}const{docJson:h,row:l,tableName:c}=f,d=t.tables[c],w=s?.hard===!0,R=!w&&d?.softDeleteMode?d.softDeleteMode.field:void 0;if(!(R&&l[R]!==null&&l[R]!==void 0)){if(Z(c,"before","delete")&&await ee("before","delete",{id:e,op:"delete",previous:l,table:c}),await kn({deletedId:e,deletedReference:g=>l[g],findHolders:async(g,k,M)=>(await Ge(g).findMany(g,{includeDeleted:w,where:{[k]:M}})).page,onCascade:(g,k)=>Ge(g).delete(k,void 0,s),onRestrict:g=>{throw new ye(g,"restrict")},onSetNull:(g,k,M)=>Ge(g).patch(k,{[M]:null}),schema:t,tableName:c}),he(c),we(c),R){const g={...l,...y(c),[R]:j(),_id:e};qe(r,c,xt(c),[se(g),e,h]),Ae(c,e,g,l),ve(c,e,void 0),Re(c,l,g),pe(c,e,l,void 0),z?.invalidate(c,e,S(c,l,g)),fe(c,e,"update",g),a({indexKeys:S(c,l,g),key:e,op:"update",row:g,table:c}),Z(c,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:c}),await q({id:e,op:"delete",table:c});return}qe(r,c,Zn(c),[e,h]),Ae(c,e,void 0),ve(c,e,void 0),Re(c,l,void 0),pe(c,e,l,void 0),z?.invalidate(c,e,S(c,l)),fe(c,e,"delete"),a({indexKeys:S(c,l),key:e,op:"delete",table:c}),Z(c,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:c}),await q({id:e,op:"delete",table:c})}},async deleteAll(e,n){if(!t.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);const s=Math.max(1,n?.chunkSize??Ot),f=n?.hard===void 0?void 0:{hard:n.hard},h=ie(e)?void 0:e;let l=0;return await E(async()=>{for(;;){const d=(await U.findMany(e,{limit:s})).page.map(w=>String(w._id));if(d.length===0)break;for(const w of d)await U.delete(w,h,f),l+=1;if(d.length<s)break}}),{deleted:l}},async deleteMany(e,n,s){ce(e.length,n?.limit,"deleteMany");for(const f of e)await U.delete(f,s);return{deleted:e.length}},async deleteWhere(e,n,s){const l=(await(K(e,"deleteWhere")??U).findMany(e,{where:n})).page.map(c=>String(c._id));if(ce(l.length,s?.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,s)},async findFirst(e,n={}){return(await U.findMany(e,{...n,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,n={}){const s=await U.findFirst(e,n);if(s===null)throw new Rn(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,n={}){const s=K(e,"findMany");if(s)return _(e,H),s.findMany(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=!n.where&&!n.baseWhere;h?_(e,H):_(e);const l=vn(n.orderBy),c=n.cursor?Nt(l,Ze(n.cursor)):void 0;let d=Q(n.baseWhere,n.where);d=Q(d,ae(f.softDeleteMode,n.includeDeleted)),d=await Tt(d,{canPushExists:lt?Xt:void 0,existsPushMode:dt==="always"?"always":"auto",fetcher:at,maxRelationKeys:ut,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),c&&(d=d?{AND:[d,c]}:c);const w=lt?Eo(_):it,R=te(d,w,Ue),g=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0,k=zt(e,R,Vt(l),g===void 0?void 0:g+1),M=me(r,k.text,...k.params).toArray();h&&!L&&T?.recordRead(M.length);const P=[];for(const V of M){const G=de(V);G&&(P.push(G),!h&&typeof G._id=="string"&&_(e,G._id))}if(g===void 0)return n.with&&await Rt({groupedCounter:ft,fetcher:He,parents:P,...vt(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:mt(P,n.select,n.with)};const W=P.length>g,C=W?P.slice(0,g):P,O=C.at(-1);return n.with&&await Rt({fetcher:He,groupedCounter:ft,parents:C,...vt(n),schema:t,tableName:e,with:n.with}),{continueCursor:W&&O&&n.omitContinueCursor!==!0?et(O,l):null,isDone:!W,page:mt(C,n.select,n.with)}},async get(e,n){const s=re(e,n);if(!s){const f=n===void 0?I:void 0;return f?f.get(e):null}return _(s.tableName,e),s.row},async lookupById(e,n){const s=re(e,n);return s?(_(s.tableName,e),{row:s.row,tableName:s.tableName}):null},async groupBy(e,n){const s=K(e,"groupBy");if(s)return _(e,H),s.groupBy(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);_(e,H);const h=n.agg??{op:"count"};if(De(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=ae(f.softDeleteMode,void 0),c=Q(Q(n.baseWhere,n.where),l),d=await _e(c,e,n.relationBaseWhere),w=d!==c,R=[...n.by,h.field];if(f.aggregateIndexes&&!n.baseWhere&&!w&&(!l||Dt(f,R))){const C=dn(f.aggregateIndexes,h.op,h.field,n.by,n.where),O=C===void 0?0:Object.keys(C.partial).length,V=C?.index.by?.length??0;if(C&&(O===0||O===V)){Ne(e,C.index);const G=je(e,C.index.name),Ie=Object.keys(C.partial),Ce=[];if(Ie.length===(C.index.by??[]).length&&Ie.length>0){const xe=Ke(C.index.by??[],C.partial),be=N(r,i`SELECT ${ke} AS value, ${Je} AS count FROM ${i.identifier(G)} WHERE ${Le} = ${xe}`).toArray();return be.length>0&&Ce.push({key:{...C.partial},value:Qe(h.op,be[0])}),Ce}const tn=N(r,i`SELECT ${Le} AS key, ${ke} AS value, ${Je} AS count FROM ${i.identifier(G)}`).toArray();for(const xe of tn){const be=sn(JSON.parse(xe.key));Ce.push({key:be,value:Qe(h.op,xe)})}return Ce}}for(const C of R){if(C===void 0)continue;const O=C===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${C}" } })`:`groupBy(${e}, { by: [..."${C}"] })`;kt(f,C,O)}const g=te(d,$e),k=n.by.map(C=>i`${Y(C)} AS ${i.identifier(C)}`);if(h.op==="count")k.push(i`COUNT(*) AS value`);else{const{field:C}=h;if(C===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);k.push(i`${i.raw(De(h.op))}(${Y(C)}) AS value`)}let M=i`SELECT ${i.join(k,i`, `)} FROM ${i.identifier(e)}`;g&&(M=i`${M} WHERE ${g}`),M=i`${M} GROUP BY ${i.join(n.by.map(C=>Y(C)),i`, `)}`;const P=N(r,M).toArray(),W=[];for(const C of P){const O={};for(const G of n.by)O[G]=C[G]??null;const{value:V}=C;W.push({key:O,value:V==null?null:Number(V)})}return W},async insert(e,n,s){const f=K(e,"insert");if(f)return ct(f,e,n,s,!0);const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const l=Ft(h,n,x);Ye(h,l);let c;s?.clientId!==void 0?(io(s.clientId),c=s.clientId):s?.allowExplicitId&&typeof l._id=="string"?c=l._id:c=m();const d=s?.allowExplicitId&&typeof l._creationTime=="number"?l._creationTime:j(),w={...l,...y(e),_creationTime:d,_id:c};return Z(e,"before","insert")&&await ee("before","insert",{doc:{...w},id:c,op:"insert",table:e}),he(e),we(e),tt(r,e,Yn(e),[c,d,se(w)]),wt(e,c,w),Z(e,"after","insert")&&await ee("after","insert",{doc:w,id:c,op:"insert",table:e}),await q({doc:w,id:c,op:"insert",table:e}),c},async insertManyUnsafe(e,n,s){if(ce(n.length,s?.limit,"insertManyUnsafe"),n.length===0)return[];const f=K(e,"insert");if(f){const d=[];for(const w of n)D(w);for(const w of n){const R=await f.insert(e,w,{allowExplicitId:s?.allowExplicitId});a({key:R,op:"insert",row:{...w,_id:R},table:e}),d.push(R)}return d}const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);he(e),we(e);const l=[];for(let d=0;d<n.length;d+=Fe)l.push(y(e));const c=n.map((d,w)=>{const R=Ft(h,d,x),g=s?.allowExplicitId===!0&&typeof R._id=="string"?R._id:m(),k=s?.allowExplicitId===!0&&typeof R._creationTime=="number"?R._creationTime:j(),M={...R,...l[Math.floor(w/Fe)],_creationTime:k,_id:g};return{creationTime:k,document:M,id:g}});for(const d of c)D(d.document);for(let d=0;d<c.length;d+=Fe){const w=i.join(c.slice(d,d+Fe).map(g=>i`(${g.id}, ${g.creationTime}, ${se(g.document)})`),i`, `),R=Gt("sqlite",i`INSERT INTO ${i.identifier(e)} (id, _creationTime, ${i.identifier(ne)}) VALUES ${w}`);tt(r,e,R.sql,R.params)}for(const{document:d,id:w}of c)wt(e,w,d),await B({doc:d,id:w,op:"insert",table:e});return c.map(d=>d.id)},async insertMany(e,n,s){ce(n.length,s?.limit,"insertMany");const f=s?.skipDuplicates===!0,h=[],l=K(e,"insert");if(l)for(const d of n)D(d);const c=async d=>l?ct(l,e,d,void 0,!1):U.insert(e,d);for(const d of n)try{h.push(await c(d))}catch(w){if(f&&w instanceof ye&&w.kind==="unique")h.push(null);else throw w}return h},normalizeId(e,n){return Lt(t,e,n)},async patch(e,n,s){const f=re(e,s);if(!f){const R=s===void 0?I:void 0;if(R){D(n),await R.patch(e,n);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:l,tableName:c}=f,d=t.tables[c];if(!d)throw new $("INTERNAL",`unknown table: ${c}`);_(c,e),Wt("patch",n);const w={...l,...n,...y(c),_id:e};qt(d,n,w,x),Ye(d,w,!0),Z(c,"before","update")&&await ee("before","update",{doc:{...w},id:e,op:"update",previous:l,table:c}),he(c),we(c),qe(r,c,xt(c),[se(w),e,h]),Ae(c,e,w,l),ve(c,e,w),Re(c,l,w),pe(c,e,l,w),z?.invalidate(c,e,S(c,l,w)),fe(c,e,"update",w),a({indexKeys:S(c,l,w),key:e,op:"update",row:w,table:c}),Z(c,"after","update")&&await ee("after","update",{doc:w,id:e,op:"update",previous:l,table:c}),await q({doc:w,id:e,op:"update",table:c})},async patchMany(e,n,s){ce(e.length,n?.limit,"patchMany");for(const f of e)await U.patch(f.id,f.patch,s);return{patched:e.length}},async patchWhere(e,n,s){const l=(await(K(e,"patchWhere")??U).findMany(e,{where:n.where})).page.map(c=>({id:String(c._id),patch:n.patch}));if(ce(l.length,s?.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,s),{patched:l.length}},query(e){const n=K(e,"query");return n?(_(e,H),n.query(e)):Co(r,t,e,F,s=>{s?A(s):_(e,H)},s=>{L||T?.recordRead(s)})},async rank(e,n,s){const f=K(e,"rank");if(f)return _(e,H),f.rank(e,n,s);F(e,n,"rank");const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const l=h.rankIndexes?.find(G=>G.name===n);if(!l)throw new $("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(pt(e,h,l),s.restrictsCounts)throw new ze(e);_(e,H),Oe(e,l);const c=typeof s.row=="string"?s.row:s.row._id;if(!c)return null;const d=St(e,l.name),w=l.sortBy.map((G,Ie)=>_t(Ie)),R=w.map(G=>Se(G)).join(", "),g=N(r,i`SELECT ${i.identifier("__partition__")}, ${i.raw(R)} FROM ${i.identifier(d)} WHERE ${i.identifier("__id__")} = ${c}`).toArray(),[k]=g;if(k===void 0)return null;let M=k.__partition__;const P=Q(s.baseWhere,s.where);Ve(P,t,e,"rank");const W=Cn(l,P);if(W){const G=xn(l.partitionBy??[],W);if(G!==M)return null;M=G}const C=w.map(G=>k[G]),{before:O,total:V}=Bt(r,d,w,l.sortBy,M,C,c);return{position:O+1,total:V}},async rankBefore(e,n,s){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=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(w=>w.name===n);if(!h)throw new $("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(s.restrictsCounts)throw new ze(e);_(e,H),Oe(e,h);const l=St(e,h.name),c=h.sortBy.map((w,R)=>_t(R)),d=h.sortBy.map((w,R)=>oe(s.sortValues[R]??null));return Bt(r,l,c,h.sortBy,s.partitionKey,d,s.rowId)},async rankPage(e,n,s={}){Ve(Q(s.baseWhere,s.where),t,e,"rankPage");const f=K(e,"rankPage");if(f)return _(e,H),f.rankPage(e,n,s);F(e,n,"rank");const{continueCursor:h,hasMore:l,rows:c}=yt($t,e,n,s);return{continueCursor:h,isDone:!l,page:c.map(d=>d.doc)}},async rankPageRows(e,n,s={}){Ve(Q(s.baseWhere,s.where),t,e,"rankPage"),F(e,n,"rank");const{directions:f,hasMore:h,rows:l}=yt($t,e,n,s);return{directions:f,hasMore:h,rows:l}},async restore(e,n){const s=re(e,n);if(!s){const l=n===void 0?I:void 0;if(l?.restore){await l.restore(e);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const f=t.tables[s.tableName]?.softDeleteMode?.field;if(!f)throw new $("INTERNAL",`ctx.db.restore: table "${s.tableName}" is not a .softDelete() table`);const h=s.row[f]!==null&&s.row[f]!==void 0;await U.patch(e,{[f]:null},n),h&&pe(s.tableName,e,void 0,s.row)},async replace(e,n,s,f){const h=re(e,s);if(!h){const k=s===void 0?I:void 0;if(k){D(n),await k.replace(e,n,void 0,f);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:l,row:c,tableName:d}=h,w=t.tables[d];if(!w)throw new $("INTERNAL",`unknown table: ${d}`);Wt("replace",n);const R=f?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:j(),g={...n,...y(d),_creationTime:R,_id:e};qt(w,n,g,x),Ye(w,g),Z(d,"before","update")&&await ee("before","update",{doc:{...g},id:e,op:"update",previous:c,table:d}),he(d),we(d),qe(r,d,Xn(d),[R,se(g),e,l]),Ae(d,e,g,c),ve(d,e,g),Re(d,c,g),pe(d,e,c,g),z?.invalidate(d,e,S(d,c,g)),fe(d,e,"update",g),a({indexKeys:S(d,c,g),key:e,op:"update",row:g,table:d}),Z(d,"after","update")&&await ee("after","update",{doc:g,id:e,op:"update",previous:c,table:d}),await q({doc:g,id:e,op:"update",table:d})},async wipeShard(e){const n=new Set(e?.exclude),s=e?.tables,f=Object.entries(t.tables).filter(([d,w])=>n.has(d)||s!==void 0&&!s.includes(d)?!1:w.shardMode?.kind!=="global").map(([d])=>d);if(s!==void 0){for(const d of s)if(!t.tables[d])throw new $("INTERNAL",`wipeShard: unknown table: ${d}`)}const h={};let l=0;const{deleteAll:c}=U;if(c===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const d of f){const w=await c(d,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[d]=w.deleted,l+=w.deleted}return{deleted:l,tables:h}}},en={db:U,scheduler:b};return o.enforceRls===!0?Fn(U,t,(e,n)=>re(e,n)?.tableName,(e,n)=>Zt(e,n)):U};export{pr as CDC_LOG_TABLE,Dr as CLIENT_WATERMARK_TABLE,Wr as GLOBAL_SHAPE_SNAPSHOT_TABLE,Or as IDEMPOTENCY_TABLE,vo as NotUniqueError,Yr as SEARCH_STATE_TABLE,kr as advanceClientWatermark,gr as applyCdcChanges,Wt as assertNoExplicitUndefined,io as assertValidClientId,ur as backfillAggregateIndexes,fr as backfillRankIndexes,hr as backfillSearchIndexes,$r as bumpCdcEpoch,yr as cdcCanVouchFor,Er as cdcSeqLeavingRows,mr as cdcTouchesTables,Sr as cdcTrimmedError,_r as compactCdcDocs,ar as createShardCtxDb,Tr as cursorBelowRetainedFloor,Br as deleteGlobalShapeSnapshot,Ur as deleteGlobalShapeSnapshotsForConnection,Lr as migrateClientWatermark,Pr as migrateGlobalShapeSnapshot,Rr as minCdcReplayableSeq,vr as minCdcSeq,Lt as normalizeIdStructurally,Ar as readCdcChangeKeys,Ir as readCdcChanges,Cr as readCdcCursor,xr as readCdcEpoch,Fr as readClientWatermark,Gr as readGlobalShapeSnapshot,jr as readIdempotent,Jr as runShardMigrations,Zr as selectShapeMembers,ei as selectShapeRows,br as trimCdcChanges,Kr as trimIdempotent,Hr as writeGlobalShapeSnapshot,Qr as writeIdempotent};
@@ -1 +1 @@
1
- import{matchesStaticWhere as a}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{compareStrings as l}from"./aggregateTableName-XtEbp1DE.mjs";import{serializeSqlValue as f}from"./serializeSqlValue-DbI1VQYM.mjs";const c=Symbol("not-resolvable"),y=r=>{if(r!==null&&typeof r=="object"&&!Array.isArray(r)){const t=Object.keys(r);return t.length===1&&t[0]==="eq"?r.eq:c}return r},m=(r,t)=>{if(r.length===0)return"";const o={};for(const n of r.toSorted(l))o[n]=t[n]??null;return JSON.stringify(o)},k="__id__",d=r=>`__sort_k${String(r)}__`,h=(r,t)=>{const o=r.partitionBy??[],n=t??{};for(const e of Object.keys(n))if(e==="AND"||e==="OR"||e==="NOT")return;const s={};for(const e of o)if(e in n){const i=y(n[e]);if(i===c)return;s[e]=i}else if(r.where&&e in r.where)s[e]=r.where[e];else return;return s},S=(r,t)=>`${r}__rank_${t}`,K=(r,t)=>({partitionKey:m(r.partitionBy??[],t),rowId:t._id,sortValues:r.sortBy.map(o=>f(t[o.field]??null))}),N=a;export{k as RANK_TIEBREAK,m as encodePartitionKey,N as matchesRankStaticWhere,K as rankKeyFromDoc,S as rankTableName,h as resolveRankPartition,d as sortColumnName};
1
+ import{matchesStaticWhere as a}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{compareStrings as l}from"./aggregateTableName-CGi8gxeK.mjs";import{serializeSqlValue as f}from"./serializeSqlValue-DbI1VQYM.mjs";const c=Symbol("not-resolvable"),y=r=>{if(r!==null&&typeof r=="object"&&!Array.isArray(r)){const t=Object.keys(r);return t.length===1&&t[0]==="eq"?r.eq:c}return r},m=(r,t)=>{if(r.length===0)return"";const o={};for(const n of r.toSorted(l))o[n]=t[n]??null;return JSON.stringify(o)},k="__id__",d=r=>`__sort_k${String(r)}__`,h=(r,t)=>{const o=r.partitionBy??[],n=t??{};for(const e of Object.keys(n))if(e==="AND"||e==="OR"||e==="NOT")return;const s={};for(const e of o)if(e in n){const i=y(n[e]);if(i===c)return;s[e]=i}else if(r.where&&e in r.where)s[e]=r.where[e];else return;return s},S=(r,t)=>`${r}__rank_${t}`,K=(r,t)=>({partitionKey:m(r.partitionBy??[],t),rowId:t._id,sortValues:r.sortBy.map(o=>f(t[o.field]??null))}),N=a;export{k as RANK_TIEBREAK,m as encodePartitionKey,N as matchesRankStaticWhere,K as rankKeyFromDoc,S as rankTableName,h as resolveRankPartition,d as sortColumnName};
@@ -1 +1 @@
1
- import{stableWireKey as y}from"./stableWireKey-DQUcEqhM.mjs";import{depKey as b,SCAN_DEP as p}from"./SCAN_DEP-D7qE3iUe.mjs";import{e as m}from"./estimate-bytes-CzG5x1f8.mjs";import{keysTouchRanges as x}from"./buildIndexRange-CBKQmHSS.mjs";import{stableStringify as K}from"./stableStringify-DibjylKD.mjs";const l=(o,t,s)=>{let e=o.get(t);return e===void 0&&(e=s(),o.set(t,e)),e},v=1e3,E=4*1024*1024;class A{entries=new Map;tableIndex=new Map;rangeIndex=new Map;totalBytes=0;hits=0;misses=0;evictions=0;maxEntries;maxBytes;now;monotonic=0;generation=0;constructor(t={}){this.maxEntries=t.maxEntries??v,this.maxBytes=t.maxBytes??E,this.now=t.now??(()=>(this.monotonic+=1,this.monotonic))}async run(t,s,e,i=()=>[]){const n=this.entries.get(t);if(n)return this.hits+=1,n.lastUsed=this.now(),this.entries.delete(t),this.entries.set(t,n),n.result;this.misses+=1;const c=this.generation,a=await e();if(this.generation!==c)return a;const h=m(a);if(h===void 0)return a;const f=i(),u={bytes:h,deps:s,ranges:f,lastUsed:this.now(),result:a,subscribers:new Set},d=this.entries.get(t);if(d){this.dropEntry(t,d);for(const r of d.subscribers)u.subscribers.add(r)}this.entries.set(t,u),this.totalBytes+=h;for(const r of s)l(this.tableIndex,r,()=>new Set).add(t);for(const r of f){const g=l(this.rangeIndex,r.table,()=>new Map);l(g,r,()=>new Set).add(t)}return this.evict(),a}invalidate(t,s,e){this.generation+=1;const i=[];return this.collectAndDrop(b(t,s),i),this.collectAndDrop(b(t,p),i),this.dropRangeDeps(t,e,i),i}invalidateTable(t){this.generation+=1;const s=[],e=`${t}:`;for(const i of this.tableIndex.keys())i.startsWith(e)&&this.collectAndDrop(i,s);return this.dropRangeDeps(t,void 0,s),s}subscribe(t,s){const e=this.entries.get(t);e&&e.subscribers.add(s)}unsubscribe(t,s){const e=this.entries.get(t);e&&e.subscribers.delete(s)}size(){return{bytes:this.totalBytes,entries:this.entries.size}}clear(){this.generation+=1,this.entries.clear(),this.tableIndex.clear(),this.rangeIndex.clear(),this.totalBytes=0}subscribers(t){const s=this.entries.get(t);return s?[...s.subscribers]:[]}stats(){return{bytes:this.totalBytes,entries:this.entries.size,evictions:this.evictions,hits:this.hits,misses:this.misses}}dropRangeDeps(t,s,e){const i=this.rangeIndex.get(t);if(!(!i||i.size===0))for(const[n,c]of i)x([n],s)&&this.dropKeys(c,e)}collectAndDrop(t,s){const e=this.tableIndex.get(t);e&&this.dropKeys(e,s)}dropKeys(t,s){for(const e of t){const i=this.entries.get(e);i&&(this.dropEntry(e,i),s.push(e))}}dropEntry(t,s){this.entries.delete(t),this.totalBytes-=s.bytes;for(const e of s.deps){const i=this.tableIndex.get(e);i&&(i.delete(t),i.size===0&&this.tableIndex.delete(e))}for(const e of s.ranges){const i=this.rangeIndex.get(e.table),n=i?.get(e);n?.delete(t),i&&n?.size===0&&(i.delete(e),i.size===0&&this.rangeIndex.delete(e.table))}}evict(){if(!(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes))for(const[t,s]of this.entries){if(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes)return;s.subscribers.size>0||(this.dropEntry(t,s),this.evictions+=1)}}}const D=(o,t,s)=>`${s??"\0anon"}\0${o}:${y(t)}`;export{A as ReactiveCache,D as reactiveCacheKey,K as stableStringify,y as stableWireKey};
1
+ import{stableWireKey as y}from"./stableWireKey-9bjKL5Gy.mjs";import{depKey as b,SCAN_DEP as p}from"./SCAN_DEP-D7qE3iUe.mjs";import{e as m}from"./estimate-bytes-CzG5x1f8.mjs";import{keysTouchRanges as x}from"./buildIndexRange-CBKQmHSS.mjs";import{stableStringify as K}from"./stableStringify-DibjylKD.mjs";const l=(o,t,s)=>{let e=o.get(t);return e===void 0&&(e=s(),o.set(t,e)),e},v=1e3,E=4*1024*1024;class A{entries=new Map;tableIndex=new Map;rangeIndex=new Map;totalBytes=0;hits=0;misses=0;evictions=0;maxEntries;maxBytes;now;monotonic=0;generation=0;constructor(t={}){this.maxEntries=t.maxEntries??v,this.maxBytes=t.maxBytes??E,this.now=t.now??(()=>(this.monotonic+=1,this.monotonic))}async run(t,s,e,i=()=>[]){const n=this.entries.get(t);if(n)return this.hits+=1,n.lastUsed=this.now(),this.entries.delete(t),this.entries.set(t,n),n.result;this.misses+=1;const c=this.generation,a=await e();if(this.generation!==c)return a;const h=m(a);if(h===void 0)return a;const f=i(),u={bytes:h,deps:s,ranges:f,lastUsed:this.now(),result:a,subscribers:new Set},d=this.entries.get(t);if(d){this.dropEntry(t,d);for(const r of d.subscribers)u.subscribers.add(r)}this.entries.set(t,u),this.totalBytes+=h;for(const r of s)l(this.tableIndex,r,()=>new Set).add(t);for(const r of f){const g=l(this.rangeIndex,r.table,()=>new Map);l(g,r,()=>new Set).add(t)}return this.evict(),a}invalidate(t,s,e){this.generation+=1;const i=[];return this.collectAndDrop(b(t,s),i),this.collectAndDrop(b(t,p),i),this.dropRangeDeps(t,e,i),i}invalidateTable(t){this.generation+=1;const s=[],e=`${t}:`;for(const i of this.tableIndex.keys())i.startsWith(e)&&this.collectAndDrop(i,s);return this.dropRangeDeps(t,void 0,s),s}subscribe(t,s){const e=this.entries.get(t);e&&e.subscribers.add(s)}unsubscribe(t,s){const e=this.entries.get(t);e&&e.subscribers.delete(s)}size(){return{bytes:this.totalBytes,entries:this.entries.size}}clear(){this.generation+=1,this.entries.clear(),this.tableIndex.clear(),this.rangeIndex.clear(),this.totalBytes=0}subscribers(t){const s=this.entries.get(t);return s?[...s.subscribers]:[]}stats(){return{bytes:this.totalBytes,entries:this.entries.size,evictions:this.evictions,hits:this.hits,misses:this.misses}}dropRangeDeps(t,s,e){const i=this.rangeIndex.get(t);if(!(!i||i.size===0))for(const[n,c]of i)x([n],s)&&this.dropKeys(c,e)}collectAndDrop(t,s){const e=this.tableIndex.get(t);e&&this.dropKeys(e,s)}dropKeys(t,s){for(const e of t){const i=this.entries.get(e);i&&(this.dropEntry(e,i),s.push(e))}}dropEntry(t,s){this.entries.delete(t),this.totalBytes-=s.bytes;for(const e of s.deps){const i=this.tableIndex.get(e);i&&(i.delete(t),i.size===0&&this.tableIndex.delete(e))}for(const e of s.ranges){const i=this.rangeIndex.get(e.table),n=i?.get(e);n?.delete(t),i&&n?.size===0&&(i.delete(e),i.size===0&&this.rangeIndex.delete(e.table))}}evict(){if(!(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes))for(const[t,s]of this.entries){if(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes)return;s.subscribers.size>0||(this.dropEntry(t,s),this.evictions+=1)}}}const D=(o,t,s)=>`${s??"\0anon"}\0${o}:${y(t)}`;export{A as ReactiveCache,D as reactiveCacheKey,K as stableStringify,y as stableWireKey};
@@ -1 +1 @@
1
- import{stableWireKey as o}from"./stableWireKey-DQUcEqhM.mjs";const s=r=>r.map(e=>`${String(e.length)}:${e}`).join(""),c=r=>o(r.effectiveWhere??null),g=(r,e,t)=>s([r,String(e),String(t)]),h=(r,e)=>{try{return s([c(r),e])}catch{return}};class d{keyScans=new Map;memberProbes=new Map;run=0;served=0;get probesRun(){return this.run}get probesServed(){return this.served}changedKeys(e,t){return this.getOrLoad(this.keyScans,e,t)}members(e,t,n){return this.getOrLoad(this.memberProbes,h(e,t),n)}getOrLoad(e,t,n){if(t!==void 0){const a=e.get(t);if(a!==void 0)return this.served+=1,a}this.run+=1;const i=n();return t!==void 0&&e.set(t,i),i}}const p=()=>new d,b=(r,e)=>{try{return s([r.table,c(r),o({identity:e.identity,userId:e.userId})])}catch{return}};export{d as ShapeDiffCache,p as createShapeDiffCache,b as globalShapeReadKey,g as shapeRangeKey};
1
+ import{stableWireKey as o}from"./stableWireKey-9bjKL5Gy.mjs";const s=r=>r.map(e=>`${String(e.length)}:${e}`).join(""),c=r=>o(r.effectiveWhere??null),g=(r,e,t)=>s([r,String(e),String(t)]),h=(r,e)=>{try{return s([c(r),e])}catch{return}};class d{keyScans=new Map;memberProbes=new Map;run=0;served=0;get probesRun(){return this.run}get probesServed(){return this.served}changedKeys(e,t){return this.getOrLoad(this.keyScans,e,t)}members(e,t,n){return this.getOrLoad(this.memberProbes,h(e,t),n)}getOrLoad(e,t,n){if(t!==void 0){const a=e.get(t);if(a!==void 0)return this.served+=1,a}this.run+=1;const i=n();return t!==void 0&&e.set(t,i),i}}const p=()=>new d,b=(r,e)=>{try{return s([r.table,c(r),o({identity:e.identity,userId:e.userId})])}catch{return}};export{d as ShapeDiffCache,p as createShapeDiffCache,b as globalShapeReadKey,g as shapeRangeKey};
@@ -1 +1 @@
1
- import{LunoraError as g}from"@lunora/errors";import{e as i}from"./wire-codec-CDds5uQW.mjs";const a=BigInt(Number.MAX_SAFE_INTEGER),c=(e,t)=>e<t?-1:e>t?1:0,m=(e,t)=>`${e}__agg_${t}`,l=e=>{if(typeof e=="bigint"){if(e>a||e<-a)throw new g("BAD_REQUEST",`bigint ${e.toString()} exceeds Number.MAX_SAFE_INTEGER, so an aggregateIndex declared over this column cannot tally it exactly (the companion's value column is a REAL) — drop the aggregateIndex, aggregate a narrower column, or read the rows and reduce them in the handler`);return Number(e)}if(typeof e=="number")return Number.isFinite(e)?e:void 0},v=(e,t,n,u)=>{const r=e.get(t)??{count:0,value:null};if(n.op==="count"){r.count+=1,r.value=r.count,e.set(t,r);return}const o=l(u[n.field??""]);if(n.op==="sum"||n.op==="avg"){o!==void 0&&(r.value=(r.value??0)+o,r.count+=1),e.set(t,r);return}r.count+=1,o!==void 0&&(r.value===null?r.value=o:r.value=n.op==="min"?Math.min(r.value,o):Math.max(r.value,o)),e.set(t,r)},d=(e,t)=>e==="count"?t?.value??0:!t||t.count===0?null:e==="avg"?t.value===null?null:t.value/t.count:t.value,A=(e,t)=>{if(e.length===0)return"";const n={};for(const u of e.toSorted(c))n[u]=t[u]??null;return JSON.stringify(i(n))};export{m as aggregateTableName,l as coerceAggregateNumber,c as compareStrings,A as encodeAggregateKey,v as foldAggregateTally,d as readAggregateValue};
1
+ import{LunoraError as g}from"@lunora/errors";import{e as i}from"./wire-codec-COhOSEe4.mjs";const a=BigInt(Number.MAX_SAFE_INTEGER),c=(e,t)=>e<t?-1:e>t?1:0,m=(e,t)=>`${e}__agg_${t}`,l=e=>{if(typeof e=="bigint"){if(e>a||e<-a)throw new g("BAD_REQUEST",`bigint ${e.toString()} exceeds Number.MAX_SAFE_INTEGER, so an aggregateIndex declared over this column cannot tally it exactly (the companion's value column is a REAL) — drop the aggregateIndex, aggregate a narrower column, or read the rows and reduce them in the handler`);return Number(e)}if(typeof e=="number")return Number.isFinite(e)?e:void 0},v=(e,t,n,u)=>{const r=e.get(t)??{count:0,value:null};if(n.op==="count"){r.count+=1,r.value=r.count,e.set(t,r);return}const o=l(u[n.field??""]);if(n.op==="sum"||n.op==="avg"){o!==void 0&&(r.value=(r.value??0)+o,r.count+=1),e.set(t,r);return}r.count+=1,o!==void 0&&(r.value===null?r.value=o:r.value=n.op==="min"?Math.min(r.value,o):Math.max(r.value,o)),e.set(t,r)},d=(e,t)=>e==="count"?t?.value??0:!t||t.count===0?null:e==="avg"?t.value===null?null:t.value/t.count:t.value,A=(e,t)=>{if(e.length===0)return"";const n={};for(const u of e.toSorted(c))n[u]=t[u]??null;return JSON.stringify(i(n))};export{m as aggregateTableName,l as coerceAggregateNumber,c as compareStrings,A as encodeAggregateKey,v as foldAggregateTally,d as readAggregateValue};
@@ -1 +1 @@
1
- import{LunoraError as R}from"@lunora/errors";import{applySelect as B}from"./CURSOR_PREFIX-CheBVHA7.mjs";const _=c=>({relationBaseWhere:c.relationBaseWhere,relationMask:c.relationMask}),W=(c,o)=>o.select?B(c,o.select,o.with):c,E=async(c,o,t,r,s)=>{const u=await Promise.all(r.map(async i=>{const w=s?{AND:[{[t]:i},s]}:{[t]:i};return[i,await c(o,w)]}));return new Map(u)},O=(c,o)=>{const t=new Set;for(const r of c){const s=r[o];s!=null&&t.add(s)}return[...t]},L=async c=>{const{groupedCounter:o,fetcher:t,parents:r,relationBaseWhere:s,relationMask:u,schema:i,tableName:w,with:D}=c,M=(a,e)=>u?.(a,e)??e;if(r.length===0)return;const y=i.tables[w];if(!y)throw new R("INTERNAL",`unknown table: ${w}`);const N=y.relationMap??{},v=a=>{const e=N[a];if(!e)throw new R("INTERNAL",`unknown relation "${a}" on table "${w}"`);return e},m=async(a,e,n)=>{const p=O(r,e.field);if(p.length===0){for(const l of r)l[a]=null;return}const{page:b}=await t(e.table,{baseWhere:s?.(e.table),relationBaseWhere:s,relationMask:u,where:{[e.references]:{in:p}},with:n.with}),k=new Map;for(const l of M(e.table,b))k.set(l[e.references],l);for(const l of r){const h=k.get(l[e.field]);l[a]=h?W([h],n)[0]??null:null}},$=async(a,e,n)=>{const p=O(r,e.references);if(p.length===0){for(const f of r)f[a]=[];return}const b={[e.field]:{in:p}},k=n.where?{AND:[n.where,b]}:b,{page:l}=await t(e.table,{baseWhere:s?.(e.table),orderBy:n.orderBy,relationBaseWhere:s,relationMask:u,where:k,with:n.with}),h=new Map;for(const f of M(e.table,l)){const d=f[e.field],V=h.get(d);V?V.push(f):h.set(d,[f])}const g=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0;for(const f of r){const d=h.get(f[e.references])??[];f[a]=W(g===void 0?d:d.slice(0,g),n)}},j=async a=>{for(const e of Object.keys(a)){const n=v(e),[p,b]=n.kind==="many"?[n.field,n.references]:[n.references,n.field],k=s?.(n.table),l=O(r,b),h=l.length===0?new Map:await o(n.table,p,l,k);for(const g of r){const f=g._count??{},d=g[b];f[e]=d==null?0:h.get(d)??0,g._count=f}}};for(const[a,e]of Object.entries(D)){if(e===void 0||e===!1)continue;if(a==="_count"){await j(e);continue}const n=v(a),p=e===!0?{}:e;await(n.kind==="one"?m(a,n,p):$(a,n,p))}},I=async(c,o,t)=>{const{deletedId:r,deletedReference:s,findHolders:u,onCascade:i,onRestrict:w,onSetNull:D,tableName:M}=c,y=t.references==="_id"?r:s(t.references);if(y==null)return;const N=await u(o,t.field,y);if(N.length!==0){t.onDelete==="restrict"&&w(`cannot delete "${M}" row: "${o}.${t.field}" still references it`);for(const v of N){const m=v._id;typeof m=="string"&&await(t.onDelete==="cascade"?i(o,m):D(o,m,t.field))}}},S=async c=>{const{schema:o,tableName:t}=c;if(!o.tables[t])throw new R("INTERNAL",`unknown table: ${t}`);for(const[r,s]of Object.entries(o.tables)){const u=s.relationMap;if(u)for(const i of Object.values(u))i.kind!=="one"||i.table!==t||!i.onDelete||await I(c,r,i)}},x=(c,o,t=!1)=>{for(const[r,s]of Object.entries(c.shape))r in o&&typeof s.parse=="function"&&(t&&o[r]===null&&s.kind==="optional"||s.parse(o[r]))};export{S as applyOnDelete,O as distinctValues,E as fanOutScalarCounts,_ as relationHooks,L as resolveWith,x as runRowValidators};
1
+ import{LunoraError as R}from"@lunora/errors";import{applySelect as B}from"./CURSOR_PREFIX-C0HEpLAN.mjs";const _=c=>({relationBaseWhere:c.relationBaseWhere,relationMask:c.relationMask}),W=(c,o)=>o.select?B(c,o.select,o.with):c,E=async(c,o,t,r,s)=>{const u=await Promise.all(r.map(async i=>{const w=s?{AND:[{[t]:i},s]}:{[t]:i};return[i,await c(o,w)]}));return new Map(u)},O=(c,o)=>{const t=new Set;for(const r of c){const s=r[o];s!=null&&t.add(s)}return[...t]},L=async c=>{const{groupedCounter:o,fetcher:t,parents:r,relationBaseWhere:s,relationMask:u,schema:i,tableName:w,with:D}=c,M=(a,e)=>u?.(a,e)??e;if(r.length===0)return;const y=i.tables[w];if(!y)throw new R("INTERNAL",`unknown table: ${w}`);const N=y.relationMap??{},v=a=>{const e=N[a];if(!e)throw new R("INTERNAL",`unknown relation "${a}" on table "${w}"`);return e},m=async(a,e,n)=>{const p=O(r,e.field);if(p.length===0){for(const l of r)l[a]=null;return}const{page:b}=await t(e.table,{baseWhere:s?.(e.table),relationBaseWhere:s,relationMask:u,where:{[e.references]:{in:p}},with:n.with}),k=new Map;for(const l of M(e.table,b))k.set(l[e.references],l);for(const l of r){const h=k.get(l[e.field]);l[a]=h?W([h],n)[0]??null:null}},$=async(a,e,n)=>{const p=O(r,e.references);if(p.length===0){for(const f of r)f[a]=[];return}const b={[e.field]:{in:p}},k=n.where?{AND:[n.where,b]}:b,{page:l}=await t(e.table,{baseWhere:s?.(e.table),orderBy:n.orderBy,relationBaseWhere:s,relationMask:u,where:k,with:n.with}),h=new Map;for(const f of M(e.table,l)){const d=f[e.field],V=h.get(d);V?V.push(f):h.set(d,[f])}const g=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0;for(const f of r){const d=h.get(f[e.references])??[];f[a]=W(g===void 0?d:d.slice(0,g),n)}},j=async a=>{for(const e of Object.keys(a)){const n=v(e),[p,b]=n.kind==="many"?[n.field,n.references]:[n.references,n.field],k=s?.(n.table),l=O(r,b),h=l.length===0?new Map:await o(n.table,p,l,k);for(const g of r){const f=g._count??{},d=g[b];f[e]=d==null?0:h.get(d)??0,g._count=f}}};for(const[a,e]of Object.entries(D)){if(e===void 0||e===!1)continue;if(a==="_count"){await j(e);continue}const n=v(a),p=e===!0?{}:e;await(n.kind==="one"?m(a,n,p):$(a,n,p))}},I=async(c,o,t)=>{const{deletedId:r,deletedReference:s,findHolders:u,onCascade:i,onRestrict:w,onSetNull:D,tableName:M}=c,y=t.references==="_id"?r:s(t.references);if(y==null)return;const N=await u(o,t.field,y);if(N.length!==0){t.onDelete==="restrict"&&w(`cannot delete "${M}" row: "${o}.${t.field}" still references it`);for(const v of N){const m=v._id;typeof m=="string"&&await(t.onDelete==="cascade"?i(o,m):D(o,m,t.field))}}},S=async c=>{const{schema:o,tableName:t}=c;if(!o.tables[t])throw new R("INTERNAL",`unknown table: ${t}`);for(const[r,s]of Object.entries(o.tables)){const u=s.relationMap;if(u)for(const i of Object.values(u))i.kind!=="one"||i.table!==t||!i.onDelete||await I(c,r,i)}},x=(c,o,t=!1)=>{for(const[r,s]of Object.entries(c.shape))r in o&&typeof s.parse=="function"&&(t&&o[r]===null&&s.kind==="optional"||s.parse(o[r]))};export{S as applyOnDelete,O as distinctValues,E as fanOutScalarCounts,_ as relationHooks,L as resolveWith,x as runRowValidators};
@@ -1 +1 @@
1
- import{stableStringify as m}from"./stableStringify-DibjylKD.mjs";import{i as A,e as w,n as J}from"./wire-codec-CDds5uQW.mjs";const D="_id",p="_creationTime",y="page",_=e=>{let t;for(const s of e){const o=s[p];if(typeof o=="number"){if(t!==void 0){if(o<t)return!0;if(o>t)return!1}t=o}}return!1},F=(e,t)=>{const s=t[p];if(typeof s!="number")return e.length;const o=_(e);for(const[n,r]of e.entries()){const i=r[p];if(typeof i=="number"&&(o?i<s:i>s))return n}return e.length},L="__lunora__",E=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return;const t=e[D];return typeof t=="string"?t:void 0},I=e=>{const t=new Map,s=[];for(const o of e){const n=E(o);if(n===void 0||t.has(n))return;t.set(n,o),s.push(n)}return{byId:t,order:s}},N=(e,t)=>{const s=e.order.filter(n=>t.byId.has(n)),o=t.order.filter(n=>e.byId.has(n));return s.length!==o.length?!1:s.every((n,r)=>o[r]===n)},R=(e,t,s,o)=>{const n=[];for(const r of e.order)t.byId.has(r)||n.push({delta:{key:r,op:"delete",table:s},frame:`{"key":${JSON.stringify(r)},"op":"delete","table":${o}}`});return n},P=(e,t,s,o)=>{const n=[];for(const r of t.order){const i=t.byId.get(r),a=e.byId.get(r),d=JSON.stringify(J(i)?w(i):i),c=a===void 0?void 0:JSON.stringify(a);if(c===d)continue;const f=c===void 0?"insert":"update";n.push({delta:{key:r,op:f,row:i,table:s},frame:`{"key":${JSON.stringify(r)},"op":"${f}","row":${d},"table":${o}}`})}return n},T=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return{next:t,previous:e};if(!A(e)||!A(t))return;const s=e[y],o=t[y];if(!Array.isArray(s)||!Array.isArray(o))return;const n=r=>Object.fromEntries(Object.entries(r).filter(([i])=>i!==y));if(m(n(e))===m(w(n(t))))return{next:o,previous:s}},k=(e,t,s)=>{const o=s.filter(({delta:r})=>r.op==="insert");if(o.length===0)return!0;const n=e.order.filter(r=>t.byId.has(r)).map(r=>e.byId.get(r));for(const{delta:r}of o){const i=r.row;n.splice(F(n,i),0,i)}return n.length===t.order.length&&n.every((r,i)=>r[D]===t.order[i])},O=(e,t,s)=>{let o;try{o=JSON.parse(e)}catch{return}const n=T(o,t);if(n===void 0)return;const r=I(n.previous),i=I(n.next);if(r===void 0||i===void 0||!N(r,i))return;const a=s===""?L:s,d=JSON.stringify(a),c=[...R(r,i,a,d),...P(r,i,a,d)];return k(r,i,c)?c:void 0},W=(e,t,s,o)=>{const n=O(e,t,s);if(n!==void 0){if(o!==void 0)for(const{frame:r}of n)o.push(r);return n.map(({delta:r})=>r)}},C=(e,t)=>{try{return e.send(t),!0}catch{return!1}},K=e=>{const{cursorSuffix:t,lastMutationId:s,nextResult:o,pageDeltas:n,previousJson:r,snapshotJson:i,subId:a,table:d}=e,c=JSON.stringify(a),f=s===void 0?"":`,"lastMutationId":${String(s)}`,g=f+t,l=`{"type":"data","id":${c},"data":${i}${g}}`,u=r!==void 0&&(n===!0||Array.isArray(o))?O(r,o,d):void 0;if(u===void 0||u.length===0)return[l];const v=[];let b=0;for(const[$,{frame:x}]of u.entries()){const S=$===u.length-1,h=`{"type":"delta","id":${c},"delta":${x}${S?g:f}}`;if(b+=h.length,b>=l.length)return[l];v.push(h)}return v},G=async e=>{let t=0;for(;t<100;){t+=1;const{bufferedAmount:s}=e;if(typeof s!="number"||s<1048576)return;await new Promise(o=>{setTimeout(o,20)})}};export{G as awaitWsDrain,K as subscriptionFrames,W as subscriptionListDeltas,C as trySendFrame};
1
+ import{stableStringify as m}from"./stableStringify-DibjylKD.mjs";import{i as A,e as w,n as J}from"./wire-codec-COhOSEe4.mjs";const D="_id",p="_creationTime",y="page",_=e=>{let t;for(const s of e){const o=s[p];if(typeof o=="number"){if(t!==void 0){if(o<t)return!0;if(o>t)return!1}t=o}}return!1},F=(e,t)=>{const s=t[p];if(typeof s!="number")return e.length;const o=_(e);for(const[n,r]of e.entries()){const i=r[p];if(typeof i=="number"&&(o?i<s:i>s))return n}return e.length},L="__lunora__",E=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return;const t=e[D];return typeof t=="string"?t:void 0},I=e=>{const t=new Map,s=[];for(const o of e){const n=E(o);if(n===void 0||t.has(n))return;t.set(n,o),s.push(n)}return{byId:t,order:s}},N=(e,t)=>{const s=e.order.filter(n=>t.byId.has(n)),o=t.order.filter(n=>e.byId.has(n));return s.length!==o.length?!1:s.every((n,r)=>o[r]===n)},R=(e,t,s,o)=>{const n=[];for(const r of e.order)t.byId.has(r)||n.push({delta:{key:r,op:"delete",table:s},frame:`{"key":${JSON.stringify(r)},"op":"delete","table":${o}}`});return n},P=(e,t,s,o)=>{const n=[];for(const r of t.order){const i=t.byId.get(r),a=e.byId.get(r),d=JSON.stringify(J(i)?w(i):i),c=a===void 0?void 0:JSON.stringify(a);if(c===d)continue;const f=c===void 0?"insert":"update";n.push({delta:{key:r,op:f,row:i,table:s},frame:`{"key":${JSON.stringify(r)},"op":"${f}","row":${d},"table":${o}}`})}return n},T=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return{next:t,previous:e};if(!A(e)||!A(t))return;const s=e[y],o=t[y];if(!Array.isArray(s)||!Array.isArray(o))return;const n=r=>Object.fromEntries(Object.entries(r).filter(([i])=>i!==y));if(m(n(e))===m(w(n(t))))return{next:o,previous:s}},k=(e,t,s)=>{const o=s.filter(({delta:r})=>r.op==="insert");if(o.length===0)return!0;const n=e.order.filter(r=>t.byId.has(r)).map(r=>e.byId.get(r));for(const{delta:r}of o){const i=r.row;n.splice(F(n,i),0,i)}return n.length===t.order.length&&n.every((r,i)=>r[D]===t.order[i])},O=(e,t,s)=>{let o;try{o=JSON.parse(e)}catch{return}const n=T(o,t);if(n===void 0)return;const r=I(n.previous),i=I(n.next);if(r===void 0||i===void 0||!N(r,i))return;const a=s===""?L:s,d=JSON.stringify(a),c=[...R(r,i,a,d),...P(r,i,a,d)];return k(r,i,c)?c:void 0},W=(e,t,s,o)=>{const n=O(e,t,s);if(n!==void 0){if(o!==void 0)for(const{frame:r}of n)o.push(r);return n.map(({delta:r})=>r)}},C=(e,t)=>{try{return e.send(t),!0}catch{return!1}},K=e=>{const{cursorSuffix:t,lastMutationId:s,nextResult:o,pageDeltas:n,previousJson:r,snapshotJson:i,subId:a,table:d}=e,c=JSON.stringify(a),f=s===void 0?"":`,"lastMutationId":${String(s)}`,g=f+t,l=`{"type":"data","id":${c},"data":${i}${g}}`,u=r!==void 0&&(n===!0||Array.isArray(o))?O(r,o,d):void 0;if(u===void 0||u.length===0)return[l];const v=[];let b=0;for(const[$,{frame:x}]of u.entries()){const S=$===u.length-1,h=`{"type":"delta","id":${c},"delta":${x}${S?g:f}}`;if(b+=h.length,b>=l.length)return[l];v.push(h)}return v},G=async e=>{let t=0;for(;t<100;){t+=1;const{bufferedAmount:s}=e;if(typeof s!="number"||s<1048576)return;await new Promise(o=>{setTimeout(o,20)})}};export{G as awaitWsDrain,K as subscriptionFrames,W as subscriptionListDeltas,C as trySendFrame};
@@ -1 +1 @@
1
- import{r as R,i as k,S as A,q as O,l as h,y as $,d as C}from"./ctx-db-companions-BeVsHnEe.mjs";import{sql as t}from"drizzle-orm";import{matchesStaticWhere as L}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as M,encodeAggregateKey as x,foldAggregateTally as N}from"./aggregateTableName-XtEbp1DE.mjs";import{migrateSearchState as _,readSearchBackfillState as F,writeSearchBackfillState as y}from"./SEARCH_STATE_TABLE-BCqn5ksa.mjs";import{runDrizzle as l}from"./runDrizzle-2ULFQR_k.mjs";import{i as E,r as T,a as D,b as v,A as B,D as S,h as G}from"./do-sql-DqQTxsj_.mjs";import{isLiveForCompanion as U}from"./CURSOR_PREFIX-CheBVHA7.mjs";import{rankTableName as P,matchesRankStaticWhere as W}from"./RANK_TIEBREAK-DBzb8aDX.mjs";const H=(e,n)=>e.profile!==n?{cursor:void 0,finished:!1,wipe:e.cursor!==void 0||e.done}:{cursor:e.cursor,finished:e.done,wipe:!1},b=(e,n)=>l(e,t`SELECT COUNT(*) AS count FROM ${t.identifier(n)}`).one().count>0,p=(e,n)=>l(e,t`SELECT id, _creationTime, ${t.identifier(S)} FROM ${t.identifier(n)}`).toArray(),V=(e,n,r,o)=>{const i=M(n,r.name);if(b(e,i))return;const a=r.by??[],s=new Map,c=p(e,n);for(const d of c){const f=T(d);if(!f||!U(f,o)||r.where&&!L(f,r.where))continue;const g=x(a,f);N(s,g,r,f)}for(const[d,f]of s)l(e,t`INSERT INTO ${t.identifier(i)} (${D}, ${v}, ${B}) VALUES (${d}, ${f.value}, ${f.count})`)},ne=(e,n)=>{for(const[r,o]of Object.entries(n.tables))if(!(o.shardMode?.kind==="global"||!o.aggregateIndexes))for(const i of o.aggregateIndexes)V(e,r,i,o.softDeleteMode?.field)},Y=(e,n,r)=>{const o=P(n,r.name);if(b(e,o))return;const i=R(r),a=p(e,n);for(const s of a){const c=T(s);!c||r.where&&!W(c,r.where)||k(e,o,r,i,c._id,c)}},re=(e,n)=>{for(const[r,o]of Object.entries(n.tables))if(!(o.shardMode?.kind==="global"||!o.rankIndexes))for(const i of o.rankIndexes)Y(e,r,i)},m=500,w=(e,n,r)=>{const o=A(n,r.name),{profile:i}=O(r.language),a=H(F(e,o),i);if(a.finished)return{done:!0,rows:0};a.wipe&&l(e,t`DELETE FROM ${t.identifier(o)}`);const{cursor:s}=a,c=l(e,s===void 0?t`SELECT id, _creationTime, ${t.identifier(S)} FROM ${t.identifier(n)} ORDER BY id ASC LIMIT ${t.raw(String(m))}`:t`SELECT id, _creationTime, ${t.identifier(S)} FROM ${t.identifier(n)} WHERE id > ${s} ORDER BY id ASC LIMIT ${t.raw(String(m))}`).toArray();let d=s;for(const g of c){const{id:u}=g;if(typeof u!="string")continue;d=u,l(e,t`DELETE FROM ${t.identifier(o)} WHERE ${t.identifier(h)} = ${u}`);const I=G(g);I&&l(e,t`INSERT INTO ${t.identifier(o)} (${t.identifier($)}, ${t.identifier(h)}) VALUES (${C(I,r)}, ${u})`)}const f=c.length<m;return y(e,o,d,f,i),{done:f,rows:c.length}},te=(e,n,r)=>{if(E(e))for(const o of r.searchIndexes??[])o.staged||w(e,n,o)},j=(e,n,r,o)=>{let i=0;for(;;){if(i>=o)return{done:!1,pages:i};const a=w(e,n,r);if(a.rows>0&&(i+=1),a.done)return{done:!0,pages:i}}},ie=(e,n,r={})=>{if(!E(e))return{done:!0,pages:0};_(e);const o=r.maxPages??Number.POSITIVE_INFINITY;let i=0;for(const[a,s]of Object.entries(n.tables))if(!(s.shardMode?.kind==="global"||!s.searchIndexes))for(const c of s.searchIndexes){const d=j(e,a,c,o-i);if(i+=d.pages,!d.done)return{done:!1,pages:i}}return{done:!0,pages:i}};export{ne as backfillAggregateIndexes,re as backfillRankIndexes,ie as backfillSearchIndexes,te as backfillSearchIndexesForTable};
1
+ import{r as R,i as k,S as A,q as O,l as h,y as $,d as C}from"./ctx-db-companions-DKBBb0u8.mjs";import{sql as t}from"drizzle-orm";import{matchesStaticWhere as L}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as M,encodeAggregateKey as x,foldAggregateTally as N}from"./aggregateTableName-CGi8gxeK.mjs";import{migrateSearchState as _,readSearchBackfillState as F,writeSearchBackfillState as y}from"./SEARCH_STATE_TABLE-BCqn5ksa.mjs";import{runDrizzle as l}from"./runDrizzle-2ULFQR_k.mjs";import{i as E,r as T,a as D,b as v,A as B,D as S,h as G}from"./do-sql-bkXQEBl8.mjs";import{isLiveForCompanion as U}from"./CURSOR_PREFIX-C0HEpLAN.mjs";import{rankTableName as P,matchesRankStaticWhere as W}from"./RANK_TIEBREAK-D157XEqw.mjs";const H=(e,n)=>e.profile!==n?{cursor:void 0,finished:!1,wipe:e.cursor!==void 0||e.done}:{cursor:e.cursor,finished:e.done,wipe:!1},b=(e,n)=>l(e,t`SELECT COUNT(*) AS count FROM ${t.identifier(n)}`).one().count>0,p=(e,n)=>l(e,t`SELECT id, _creationTime, ${t.identifier(S)} FROM ${t.identifier(n)}`).toArray(),V=(e,n,r,o)=>{const i=M(n,r.name);if(b(e,i))return;const a=r.by??[],s=new Map,c=p(e,n);for(const d of c){const f=T(d);if(!f||!U(f,o)||r.where&&!L(f,r.where))continue;const g=x(a,f);N(s,g,r,f)}for(const[d,f]of s)l(e,t`INSERT INTO ${t.identifier(i)} (${D}, ${v}, ${B}) VALUES (${d}, ${f.value}, ${f.count})`)},ne=(e,n)=>{for(const[r,o]of Object.entries(n.tables))if(!(o.shardMode?.kind==="global"||!o.aggregateIndexes))for(const i of o.aggregateIndexes)V(e,r,i,o.softDeleteMode?.field)},Y=(e,n,r)=>{const o=P(n,r.name);if(b(e,o))return;const i=R(r),a=p(e,n);for(const s of a){const c=T(s);!c||r.where&&!W(c,r.where)||k(e,o,r,i,c._id,c)}},re=(e,n)=>{for(const[r,o]of Object.entries(n.tables))if(!(o.shardMode?.kind==="global"||!o.rankIndexes))for(const i of o.rankIndexes)Y(e,r,i)},m=500,w=(e,n,r)=>{const o=A(n,r.name),{profile:i}=O(r.language),a=H(F(e,o),i);if(a.finished)return{done:!0,rows:0};a.wipe&&l(e,t`DELETE FROM ${t.identifier(o)}`);const{cursor:s}=a,c=l(e,s===void 0?t`SELECT id, _creationTime, ${t.identifier(S)} FROM ${t.identifier(n)} ORDER BY id ASC LIMIT ${t.raw(String(m))}`:t`SELECT id, _creationTime, ${t.identifier(S)} FROM ${t.identifier(n)} WHERE id > ${s} ORDER BY id ASC LIMIT ${t.raw(String(m))}`).toArray();let d=s;for(const g of c){const{id:u}=g;if(typeof u!="string")continue;d=u,l(e,t`DELETE FROM ${t.identifier(o)} WHERE ${t.identifier(h)} = ${u}`);const I=G(g);I&&l(e,t`INSERT INTO ${t.identifier(o)} (${t.identifier($)}, ${t.identifier(h)}) VALUES (${C(I,r)}, ${u})`)}const f=c.length<m;return y(e,o,d,f,i),{done:f,rows:c.length}},te=(e,n,r)=>{if(E(e))for(const o of r.searchIndexes??[])o.staged||w(e,n,o)},j=(e,n,r,o)=>{let i=0;for(;;){if(i>=o)return{done:!1,pages:i};const a=w(e,n,r);if(a.rows>0&&(i+=1),a.done)return{done:!0,pages:i}}},ie=(e,n,r={})=>{if(!E(e))return{done:!0,pages:0};_(e);const o=r.maxPages??Number.POSITIVE_INFINITY;let i=0;for(const[a,s]of Object.entries(n.tables))if(!(s.shardMode?.kind==="global"||!s.searchIndexes))for(const c of s.searchIndexes){const d=j(e,a,c,o-i);if(i+=d.pages,!d.done)return{done:!1,pages:i}}return{done:!0,pages:i}};export{ne as backfillAggregateIndexes,re as backfillRankIndexes,ie as backfillSearchIndexes,te as backfillSearchIndexesForTable};
@@ -1 +1 @@
1
- import{e as h}from"./wire-codec-CDds5uQW.mjs";const u=(t,e)=>{if(!e)return t;const a=Object.create(null);for(const s of["_id","_creationTime",...e])Object.hasOwn(t,s)&&(a[s]=t[s]);return a},y=(t,e,a)=>{const{columns:s,table:p}=a,i=new Map,c=[];for(const{doc:n,id:r}of t){const o=u(n,s),d=JSON.stringify(h(o));i.set(r,d);const f=e.get(r);f===void 0?c.push({key:r,op:"insert",table:p,value:o}):f!==d&&c.push({key:r,op:"update",table:p,value:o})}for(const n of e.keys())i.has(n)||c.push({key:n,op:"delete",table:p});return{next:i,rowsPatch:c}},k=t=>t.map(e=>e.value===void 0?e:{...e,value:h(e.value)}),b=(t,e,a={})=>{const{baseCheckpoint:s,checkpoint:p,epoch:i,lastMutationId:c,pokeId:n}=e,r=[JSON.stringify({baseCheckpoint:s,epoch:i,pokeId:n,type:"pokeStart"})];for(const o of t){const d=a.preEncoded?o.rowsPatch:k(o.rowsPatch),f=o.baseCheckpoint??s;r.push(JSON.stringify({pokeId:n,rowsPatch:d,shapeId:o.shapeId,type:"pokePart",...c===void 0?{}:{lastMutationId:c},...f===void 0?{}:{baseCheckpoint:f},...o.reset===!0?{reset:!0}:{}}))}return r.push(JSON.stringify({checkpoint:p,epoch:i,pokeId:n,type:"pokeEnd"})),r};export{b as buildPokeFrames,y as diffGlobalMembership,k as encodeRowsPatch,u as projectColumns};
1
+ import{e as h}from"./wire-codec-COhOSEe4.mjs";const u=(t,e)=>{if(!e)return t;const a=Object.create(null);for(const s of["_id","_creationTime",...e])Object.hasOwn(t,s)&&(a[s]=t[s]);return a},y=(t,e,a)=>{const{columns:s,table:p}=a,i=new Map,c=[];for(const{doc:n,id:r}of t){const o=u(n,s),d=JSON.stringify(h(o));i.set(r,d);const f=e.get(r);f===void 0?c.push({key:r,op:"insert",table:p,value:o}):f!==d&&c.push({key:r,op:"update",table:p,value:o})}for(const n of e.keys())i.has(n)||c.push({key:n,op:"delete",table:p});return{next:i,rowsPatch:c}},k=t=>t.map(e=>e.value===void 0?e:{...e,value:h(e.value)}),b=(t,e,a={})=>{const{baseCheckpoint:s,checkpoint:p,epoch:i,lastMutationId:c,pokeId:n}=e,r=[JSON.stringify({baseCheckpoint:s,epoch:i,pokeId:n,type:"pokeStart"})];for(const o of t){const d=a.preEncoded?o.rowsPatch:k(o.rowsPatch),f=o.baseCheckpoint??s;r.push(JSON.stringify({pokeId:n,rowsPatch:d,shapeId:o.shapeId,type:"pokePart",...c===void 0?{}:{lastMutationId:c},...f===void 0?{}:{baseCheckpoint:f},...o.reset===!0?{reset:!0}:{}}))}return r.push(JSON.stringify({checkpoint:p,epoch:i,pokeId:n,type:"pokeEnd"})),r};export{b as buildPokeFrames,y as diffGlobalMembership,k as encodeRowsPatch,u as projectColumns};
@@ -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-CDds5uQW.mjs";import{runSql as p}from"./runDrizzle-2ULFQR_k.mjs";import{k as d,D as E}from"./do-sql-DqQTxsj_.mjs";import{m as g}from"./sql-projection-BqmxFxQU.mjs";const b=m(0n)[0],_=e=>e.shardMode?.kind==="global"?[]:Object.entries(e.shape).filter(([,r])=>g(r)).map(([r])=>r),M=e=>Object.entries(e.tables).filter(([,r])=>_(r).length>0).map(([r])=>r),f=e=>{const r=`json_each(${l(E)}) AS __f__`;return{params:[JSON.stringify(e),b,"bigint","bytes"],sql:`EXISTS (SELECT 1 FROM ${r} WHERE __f__.type = 'array' AND __f__.key IN (SELECT value FROM json_each(?)) AND json_extract(__f__.value, '$[0]') = ? AND json_extract(__f__.value, '$[1]') IN (?, ?))`}},N=(e,r,o)=>{if(o.length===0)return 0;const{params:t,sql:n}=f(o);return p(e,`SELECT COUNT(*) AS count FROM ${l(r)} WHERE ${n}`,...t).toArray()[0]?.count??0},R=(e,r,o,t)=>{const{params:n,sql:i}=f(o);return p(e,`SELECT 1 FROM ${l(r)} WHERE id = ? AND (${i}) LIMIT 1`,t,...n).toArray().length>0},S=(e,r,o)=>{const t=u(e);if(t===void 0)return;const n=r.tables[t];if(!n)return;const i=_(n);if(i.length!==0)return{id:e,table:t,up:s=>{const a=s._id;if(!(typeof a!="string"||!R(o,t,i,a))){try{d(s)}catch(c){console.warn(`${e}: skipping row ${a} — it cannot be re-projected: ${c instanceof Error?c.message:String(c)}`);return}return s}}}};export{v as REPROJECTION_MIGRATION_PREFIX,S as buildReprojectionMigration,N as countLegacyRows,_ as reprojectableFields,w as reprojectionMigrationId,M as reprojectionTables};
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-COhOSEe4.mjs";import{runSql as p}from"./runDrizzle-2ULFQR_k.mjs";import{k as d,D as E}from"./do-sql-bkXQEBl8.mjs";import{m as g}from"./sql-projection-BqmxFxQU.mjs";const b=m(0n)[0],_=e=>e.shardMode?.kind==="global"?[]:Object.entries(e.shape).filter(([,r])=>g(r)).map(([r])=>r),M=e=>Object.entries(e.tables).filter(([,r])=>_(r).length>0).map(([r])=>r),f=e=>{const r=`json_each(${l(E)}) AS __f__`;return{params:[JSON.stringify(e),b,"bigint","bytes"],sql:`EXISTS (SELECT 1 FROM ${r} WHERE __f__.type = 'array' AND __f__.key IN (SELECT value FROM json_each(?)) AND json_extract(__f__.value, '$[0]') = ? AND json_extract(__f__.value, '$[1]') IN (?, ?))`}},N=(e,r,o)=>{if(o.length===0)return 0;const{params:t,sql:n}=f(o);return p(e,`SELECT COUNT(*) AS count FROM ${l(r)} WHERE ${n}`,...t).toArray()[0]?.count??0},R=(e,r,o,t)=>{const{params:n,sql:i}=f(o);return p(e,`SELECT 1 FROM ${l(r)} WHERE id = ? AND (${i}) LIMIT 1`,t,...n).toArray().length>0},S=(e,r,o)=>{const t=u(e);if(t===void 0)return;const n=r.tables[t];if(!n)return;const i=_(n);if(i.length!==0)return{id:e,table:t,up:s=>{const a=s._id;if(!(typeof a!="string"||!R(o,t,i,a))){try{d(s)}catch(c){console.warn(`${e}: skipping row ${a} — it cannot be re-projected: ${c instanceof Error?c.message:String(c)}`);return}return s}}}};export{v as REPROJECTION_MIGRATION_PREFIX,S as buildReprojectionMigration,N as countLegacyRows,_ as reprojectableFields,w as reprojectionMigrationId,M as reprojectionTables};
@@ -1 +1 @@
1
- import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-BknLCi4r.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-Ce5Jr6UH.mjs";import{shapeRangeKey as u}from"./ShapeDiffCache-DIqpvunX.mjs";import{projectColumns as g}from"./buildPokeFrames-BvgtmTHk.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};
1
+ import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-gl0FuepJ.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-CKQv8nwD.mjs";import{shapeRangeKey as u}from"./ShapeDiffCache-CLm5XXd1.mjs";import{projectColumns as g}from"./buildPokeFrames-C8km3IhJ.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};
@@ -1 +1 @@
1
- import{LunoraError as g}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{mergeWhere as j}from"./CountRlsUnsupportedError-Bdfupt3g.mjs";import{SCAN_DEP as q}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as A}from"./runDrizzle-2ULFQR_k.mjs";import{sqliteInList as O}from"./param-DlozcSQu.mjs";import{decodeCursor as F,CURSOR_PREFIX as U,toBase64 as V}from"./CURSOR_PREFIX-CheBVHA7.mjs";import{rankTableName as z,sortColumnName as H,resolveRankPartition as P,RANK_TIEBREAK as _,encodePartitionKey as J}from"./RANK_TIEBREAK-DBzb8aDX.mjs";const X="__doc__",Y=n=>U+V(JSON.stringify(n)),G=n=>n.after?[n.after.partitionKey,...n.after.sortValues,n.after.rowId]:n.cursor?F(n.cursor):void 0,Q=(n,r,a)=>{if(n?.length!==1+r.length+1)return;const t=[{column:"__partition__",direction:"asc"}];for(const[s,c]of r.entries())t.push({column:c,direction:a[s]?.direction??"asc"});t.push({column:_,direction:"asc"});const e=[];for(const[s,c]of t.entries()){const u=[];for(const[i,p]of t.slice(0,s).entries())u.push(o`${o.identifier(p.column)} IS ${n[i]}`);u.push(o`${o.identifier(c.column)} ${o.raw(c.direction==="desc"?"<":">")} ${n[s]}`);const[f]=u;e.push(u.length===1&&f!==void 0?f:o`(${o.join(u,o` AND `)})`)}return o`(${o.join(e,o` OR `)})`},T=null,Z=(n,r)=>{if(n===void 0)return T;const a=[n.__partition__,...r.map(t=>n[t]),n[_]];return Y(a)},oo=(n,r,a)=>{const t=[];for(const e of n){const s=e[_];if(typeof s!="string")continue;const c=r.get(s);if(!c)continue;const u=typeof e.__partition__=="string"?e.__partition__:"",f=a.map(i=>e[i]??null);t.push({doc:c,key:{partitionKey:u,rowId:s,sortValues:f}})}return t},no=o`${o.identifier("id")}`,to=(n,r,a)=>{const{rowToDocument:t}=n,e=new Map;if(a.length===0)return e;const s=A(n.sql,o`SELECT id, _creationTime, ${o.identifier(X)} FROM ${o.identifier(r)} WHERE ${O(no,a,!1)}`).toArray();for(const c of s){const u=t(c),f=c.id;u&&typeof f=="string"&&e.set(f,u)}return e},lo=(n,r,a,t)=>{const{assertRankPartitionLocal:e,ensureRankBackfilled:s,onRead:c,schema:u}=n,f=u.tables[r];if(!f)throw new g("INTERNAL",`unknown table: ${r}`);const i=f.rankIndexes?.find(d=>d.name===a);if(!i)throw new g("INTERNAL",`unknown rankIndex "${a}" on table "${r}"`);e(r,f,i),c(r,q),s(r,i);const p=z(r,i.name),l=i.sortBy.map((d,w)=>H(w)),h=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),B=j(t.baseWhere,t.where),k=P(i,B),$=[o`${o.identifier("__partition__")} ASC`];for(const[d,w]of l.entries()){const b=i.sortBy[d]?.direction;$.push(o`${o.identifier(w)} ${o.raw(b==="desc"?"DESC":"ASC")}`)}$.push(o`${o.identifier(_)} ASC`);const m=[];typeof t.partitionKey=="string"?m.push(o`${o.identifier("__partition__")} = ${t.partitionKey}`):k&&m.push(o`${o.identifier("__partition__")} = ${J(i.partitionBy??[],k)}`);const D=G(t),E=Q(D,l,i.sortBy);E&&m.push(E);const I=o.identifier(_),S=o.identifier("__partition__"),L=m.length>0?o` WHERE ${o.join(m,o` AND `)}`:o``,M=l.length>0?o`${I}, ${S}, ${o.join(l.map(d=>o.identifier(d)),o`, `)}`:o`${I}, ${S}`,v=o`SELECT ${M} FROM ${o.identifier(p)}${L} ORDER BY ${o.join($,o`, `)} LIMIT ${o.raw(String(h+1))}`,R=A(n.sql,v).toArray(),C=R.length>h,y=C?R.slice(0,h):R,K=y.map(d=>d[_]),x=oo(y,to(n,r,K),l),N=C?Z(y.at(-1),l):T,W=i.sortBy.map(d=>d.direction==="desc"?"desc":"asc");return{continueCursor:N,directions:W,hasMore:C,rows:x}};export{lo as computeRankPage,to as hydrateDocsById,G as resolveRankSeekTuple};
1
+ import{LunoraError as g}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{mergeWhere as j}from"./CountRlsUnsupportedError-Bdfupt3g.mjs";import{SCAN_DEP as q}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as A}from"./runDrizzle-2ULFQR_k.mjs";import{sqliteInList as O}from"./param-DlozcSQu.mjs";import{decodeCursor as F,CURSOR_PREFIX as U,toBase64 as V}from"./CURSOR_PREFIX-C0HEpLAN.mjs";import{rankTableName as z,sortColumnName as H,resolveRankPartition as P,RANK_TIEBREAK as _,encodePartitionKey as J}from"./RANK_TIEBREAK-D157XEqw.mjs";const X="__doc__",Y=n=>U+V(JSON.stringify(n)),G=n=>n.after?[n.after.partitionKey,...n.after.sortValues,n.after.rowId]:n.cursor?F(n.cursor):void 0,Q=(n,r,a)=>{if(n?.length!==1+r.length+1)return;const t=[{column:"__partition__",direction:"asc"}];for(const[s,c]of r.entries())t.push({column:c,direction:a[s]?.direction??"asc"});t.push({column:_,direction:"asc"});const e=[];for(const[s,c]of t.entries()){const u=[];for(const[i,p]of t.slice(0,s).entries())u.push(o`${o.identifier(p.column)} IS ${n[i]}`);u.push(o`${o.identifier(c.column)} ${o.raw(c.direction==="desc"?"<":">")} ${n[s]}`);const[f]=u;e.push(u.length===1&&f!==void 0?f:o`(${o.join(u,o` AND `)})`)}return o`(${o.join(e,o` OR `)})`},T=null,Z=(n,r)=>{if(n===void 0)return T;const a=[n.__partition__,...r.map(t=>n[t]),n[_]];return Y(a)},oo=(n,r,a)=>{const t=[];for(const e of n){const s=e[_];if(typeof s!="string")continue;const c=r.get(s);if(!c)continue;const u=typeof e.__partition__=="string"?e.__partition__:"",f=a.map(i=>e[i]??null);t.push({doc:c,key:{partitionKey:u,rowId:s,sortValues:f}})}return t},no=o`${o.identifier("id")}`,to=(n,r,a)=>{const{rowToDocument:t}=n,e=new Map;if(a.length===0)return e;const s=A(n.sql,o`SELECT id, _creationTime, ${o.identifier(X)} FROM ${o.identifier(r)} WHERE ${O(no,a,!1)}`).toArray();for(const c of s){const u=t(c),f=c.id;u&&typeof f=="string"&&e.set(f,u)}return e},lo=(n,r,a,t)=>{const{assertRankPartitionLocal:e,ensureRankBackfilled:s,onRead:c,schema:u}=n,f=u.tables[r];if(!f)throw new g("INTERNAL",`unknown table: ${r}`);const i=f.rankIndexes?.find(d=>d.name===a);if(!i)throw new g("INTERNAL",`unknown rankIndex "${a}" on table "${r}"`);e(r,f,i),c(r,q),s(r,i);const p=z(r,i.name),l=i.sortBy.map((d,w)=>H(w)),h=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),B=j(t.baseWhere,t.where),k=P(i,B),$=[o`${o.identifier("__partition__")} ASC`];for(const[d,w]of l.entries()){const b=i.sortBy[d]?.direction;$.push(o`${o.identifier(w)} ${o.raw(b==="desc"?"DESC":"ASC")}`)}$.push(o`${o.identifier(_)} ASC`);const m=[];typeof t.partitionKey=="string"?m.push(o`${o.identifier("__partition__")} = ${t.partitionKey}`):k&&m.push(o`${o.identifier("__partition__")} = ${J(i.partitionBy??[],k)}`);const D=G(t),E=Q(D,l,i.sortBy);E&&m.push(E);const I=o.identifier(_),S=o.identifier("__partition__"),L=m.length>0?o` WHERE ${o.join(m,o` AND `)}`:o``,M=l.length>0?o`${I}, ${S}, ${o.join(l.map(d=>o.identifier(d)),o`, `)}`:o`${I}, ${S}`,v=o`SELECT ${M} FROM ${o.identifier(p)}${L} ORDER BY ${o.join($,o`, `)} LIMIT ${o.raw(String(h+1))}`,R=A(n.sql,v).toArray(),C=R.length>h,y=C?R.slice(0,h):R,K=y.map(d=>d[_]),x=oo(y,to(n,r,K),l),N=C?Z(y.at(-1),l):T,W=i.sortBy.map(d=>d.direction==="desc"?"desc":"asc");return{continueCursor:N,directions:W,hasMore:C,rows:x}};export{lo as computeRankPage,G as resolveRankSeekTuple};
@@ -0,0 +1 @@
1
+ import{c as l,i as C,r as R}from"./ctx-db-companions-DKBBb0u8.mjs";import"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import"./aggregateTableName-CGi8gxeK.mjs";import"./runDrizzle-2ULFQR_k.mjs";import"./do-sql-bkXQEBl8.mjs";import"./param-DlozcSQu.mjs";import"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import"./CURSOR_PREFIX-C0HEpLAN.mjs";import"./RANK_TIEBREAK-D157XEqw.mjs";import"./sql-projection-BqmxFxQU.mjs";import"./serializeSqlValue-DbI1VQYM.mjs";export{l as createCompanionSync,C as insertRankRow,R as rankColumnsSql};
@@ -1,4 +1,4 @@
1
- import{cursorBelowRetainedFloor as w}from"./CDC_LOG_TABLE-BknLCi4r.mjs";import{envPositiveInt as h}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{v as _,R as f,s as S,a as v,b as y}from"./sibling-channel-Cxvk0Zca.mjs";const A=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],N=new Set(A),T=s=>typeof s=="string"&&N.has(s),p="::replica::",R=s=>{const e=s.lastIndexOf(p);if(e===-1)return;const t=s.slice(0,e),r=s.slice(e+p.length);if(!(t.length===0||!T(r)))return{ownerKey:t,region:r}},L=s=>{if(s==null||!/^\d+$/.test(s))return;const e=Number.parseInt(s,10);return Number.isSafeInteger(e)&&e>0?e:void 0},O=1e3,g=1e3,b=10,I=5e4,m=s=>h(s,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",I),c="__replica_state",u=new WeakSet,E=s=>{u.has(s)||(s.exec(`CREATE TABLE IF NOT EXISTS ${c} (
1
+ import{cursorBelowRetainedFloor as w}from"./CDC_LOG_TABLE-gl0FuepJ.mjs";import{envPositiveInt as h}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{v as _,R as f,s as S,a as v,b as y}from"./sibling-channel-Cxvk0Zca.mjs";const A=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],N=new Set(A),T=s=>typeof s=="string"&&N.has(s),p="::replica::",R=s=>{const e=s.lastIndexOf(p);if(e===-1)return;const t=s.slice(0,e),r=s.slice(e+p.length);if(!(t.length===0||!T(r)))return{ownerKey:t,region:r}},L=s=>{if(s==null||!/^\d+$/.test(s))return;const e=Number.parseInt(s,10);return Number.isSafeInteger(e)&&e>0?e:void 0},O=1e3,g=1e3,b=10,I=5e4,m=s=>h(s,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",I),c="__replica_state",u=new WeakSet,E=s=>{u.has(s)||(s.exec(`CREATE TABLE IF NOT EXISTS ${c} (
2
2
  id INTEGER PRIMARY KEY CHECK (id = 1),
3
3
  epoch TEXT NOT NULL,
4
4
  applied_seq INTEGER NOT NULL,
@@ -1 +1 @@
1
- import{sql as e}from"drizzle-orm";import{matchesStaticWhere as P,aggregateSqlFunction as le}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as N,encodeAggregateKey as I,foldAggregateTally as J,coerceAggregateNumber as C}from"./aggregateTableName-XtEbp1DE.mjs";import{runDrizzle as $}from"./runDrizzle-2ULFQR_k.mjs";import{i as fe,g as ue,D,r as M,a as q,b as S,A as g,c as j,e as z}from"./do-sql-DqQTxsj_.mjs";import{param as de,WORKERD_SQLITE_LIMITS as $e}from"./param-DlozcSQu.mjs";import{encodeGeohash as me,GEO_DEFAULT_PRECISION as Ee}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as Q}from"./CURSOR_PREFIX-CheBVHA7.mjs";import{encodePartitionKey as pe,sortColumnName as he,rankTableName as Z,matchesRankStaticWhere as x}from"./RANK_TIEBREAK-DBzb8aDX.mjs";import{m as ge}from"./sql-projection-BqmxFxQU.mjs";import{serializeSqlValue as ee}from"./serializeSqlValue-DbI1VQYM.mjs";const ye=["de","en","es","fr","it","nl","none","pt"],_e=n=>ye.includes(n),Se="a an and are as at be but by for if in into is it no not of on or such that the their then there these they this to was will with",we="aber als am an auch auf aus bei bin bis bist da dass der den des dem die das denn dir du ein eine für hat ich im in ist mit nicht noch nur oder sich sie sind über und von vor war wie wir zu zum zur",Te="a al como con de del el en es la las lo los mas no o para pero por que se su sus un una uno y ya",ve="au aux avec ce ces dans de des du elle en et eux il je la le les leur lui ma mais me même mes moi mon ne nos notre nous on ou par pas pour qu que qui sa se ses son sur ta te tes toi ton tu un une vos votre vous y",Re="a ai al alla anche che chi ci coi col come con da dal degli dei del della di do e ed gli ha hai hanno i il in la le lo ma mi ne nei nel non o per più quale quanto se si sono su sul tra un una uno vi",Ae="aan al als bij dan dat de der deze die dit door een en er het hij ij in is je kan me men met mij na naar niet nog nu of om ons ook op over te tot uit van voor was wat we wij zij zijn zo",Fe="a ao aos as até com como da das de do dos e em entre era essa esse esta este eu foi há isso já mais mas me mesmo meu na nas no nos num numa o os ou para pela pelo por qual que quem se sem seu só sua também te tem um uma você",be=/[\u0300-\u036F]/gu,Oe=/[\u0080-\u{10FFFF}]/u,Le=/[\p{L}\p{N}]+/gu,oe=n=>Oe.test(n)?n.normalize("NFD").replaceAll(be,"").normalize("NFC").toLowerCase():n.toLowerCase(),k=n=>new Set(oe(n).split(" ")),Ie={de:k(we),en:k(Se),es:k(Te),fr:k(ve),it:k(Re),nl:k(Ae),none:new Set,pt:k(Fe)},ke=2,qe=256,X=new Map,Ce=n=>{const s=n!==void 0&&_e(n)?n:"none",c=X.get(s);if(c)return c;const w=Ie[s],y=r=>{const A=(oe(r).match(Le)??[]).filter(T=>T.length<=qe);return w.size===0?A:A.filter(T=>!w.has(T))},E={document:y,profile:`${s}-v${String(ke)}`,query:r=>{const A=y(r);return A.filter((T,b)=>A.lastIndexOf(T)===b)}};return X.set(s,E),E},je=(n,s)=>{if(!s.includes("."))return n[s];let c=n;for(const w of s.split(".")){if(c===null||typeof c!="object"||Array.isArray(c))return;c=c[w]}return c},De=(n,s)=>`${n}__fts_${s}`,Me="__text__",Y="__id__",ze=1e3,Ue=(n,s)=>s.document(n),U=(n,s)=>je(n,s),We=n=>typeof n=="string"?n:n==null?"":typeof n=="number"||typeof n=="bigint"||typeof n=="boolean"?String(n):JSON.stringify(n)??"",He=(n,s,c)=>n!==void 0&&s!==void 0&&U(n,c.field)===U(s,c.field),Be=(n,s)=>Ue(We(U(n,s.field)),Ce(s.language)).slice(0,ze),Ke=(n,s)=>Be(n,s).join(" "),Ve=(n,s,c)=>[...n.partitionBy??[],...n.sortBy.map(y=>y.field),...n.where?Object.keys(n.where):[]].every(y=>s[y]===c[y]),ne=n=>e.join(["__id__","__partition__",...n.sortBy.map((s,c)=>he(c))].map(s=>e.identifier(s)),e`, `),te=(n,s,c,w,y,E)=>{const r=pe(c.partitionBy??[],E),A=c.sortBy.map(b=>ee(E[b.field]??null)),T=e.join([y,r,...A].map(b=>de(b)),e`, `);$(n,e`INSERT INTO ${e.identifier(s)} (${w}) VALUES (${T})`)},Ge=(n,s,c,w,y,E)=>{if(y&&E&&Ve(c,y,E))return;const r=Z(s,c.name);y&&$(n,e`DELETE FROM ${e.identifier(r)} WHERE ${e.identifier("__id__")} = ${w}`),!(!E||c.where&&!x(E,c.where))&&te(n,r,c,ne(c),w,E)},so=n=>{const{broadcast:s,indexKeysFor:c,invalidateCache:w,recordCdc:y,schema:E,sql:r}=n,A=new Set,T=t=>E.tables[t]?.softDeleteMode?.field,b=new Set,W=(t,o)=>{const a=`${t}::${o.name}`;if(A.has(a))return;const f=N(t,o.name),u=o.by??[],d=T(t),p=new Map,_=$(r,e`SELECT id, _creationTime, ${e.identifier(D)} FROM ${e.identifier(t)}`).toArray();for(const v of _){const m=M(v);if(!m||!Q(m,d)||o.where&&!P(m,o.where))continue;const R=I(u,m);J(p,R,o,m)}$(r,e`DELETE FROM ${e.identifier(f)}`);const F=Math.floor($e.boundParams/3),O=[...p];for(let v=0;v<O.length;v+=F){const m=O.slice(v,v+F),R=e.join(m.map(([i,l])=>e`(${i}, ${l.value}, ${l.count})`),e`, `);$(r,e`INSERT INTO ${e.identifier(f)} (${q}, ${S}, ${g}) VALUES ${R}`)}A.add(a)},se=(t,o,a)=>{const f=o.by??[],u=o.field??"",d=[],p=(i,l)=>{const h=ee(l);h===null?d.push(e`${z(i)} IS NULL`):d.push(e`${z(i)} = ${h}`)};for(const i of f)p(i,a[i]??null);const _=T(t);_!==void 0&&p(_,null);for(const[i,l]of Object.entries(o.where??{}))p(i,l!==null&&typeof l=="object"&&!Array.isArray(l)?l.eq:l);const F=d.length>0?e` WHERE ${e.join(d,e` AND `)}`:e``,O=E.tables[t]?.shape[u];if(O&&ge(O)){const i=$(r,e`SELECT id, _creationTime, ${e.identifier(D)} FROM ${e.identifier(t)}${F}`).toArray(),l=new Map;for(const h of i){const L=M(h);L&&J(l,"",o,L)}return{value:l.get("")?.value??null}}const v=le(o.op),m=z(u);return{value:$(r,e`SELECT ${e.raw(v)}(${m}) AS value FROM ${e.identifier(t)}${F}`).one().value??null}},ie=(t,o,a,f)=>{const u=N(t,o.name),{op:d}=o,p=o.field??"",_=i=>{$(r,e`DELETE FROM ${e.identifier(u)} WHERE ${q} = ${i} AND ${g} <= 0`)},F=T(t),O=i=>!o.where||P(i,o.where),v=i=>Q(i,F)&&O(i);f!==void 0&&d!=="count"&&O(f)&&C(f[p]);const m=a&&v(a)?a:void 0,R=f&&v(f)?f:void 0;if(!(!m&&!R)){if(d==="count"){for(const[i,l]of[[m,-1],[R,1]]){if(!i)continue;const h=I(o.by??[],i);$(r,j(u,h,l,l,e`${S} = ${S} + excluded.${S}, ${g} = ${g} + excluded.${g}`))}m&&_(I(o.by??[],m));return}if(d==="sum"||d==="avg"){for(const[i,l]of[[m,-1],[R,1]]){if(!i)continue;const h=C(i[p]);if(h===void 0)continue;const L=I(o.by??[],i);$(r,j(u,L,l*h,l,e`${S} = COALESCE(${S}, 0) + excluded.${S}, ${g} = ${g} + excluded.${g}`))}m&&_(I(o.by??[],m));return}if(m){const i=I(o.by??[],m),l=C(m[p]),h=$(r,e`SELECT ${S} AS value, ${g} AS count FROM ${e.identifier(u)} WHERE ${q} = ${i}`).toArray()[0],L=(h?.count??0)-1;if(L<=0)$(r,e`DELETE FROM ${e.identifier(u)} WHERE ${q} = ${i}`);else if(h&&l!==void 0&&h.value!==null&&l===h.value){const ce=se(t,o,m);$(r,e`UPDATE ${e.identifier(u)} SET ${S} = ${ce.value}, ${g} = ${L} WHERE ${q} = ${i}`)}else $(r,e`UPDATE ${e.identifier(u)} SET ${g} = ${g} - 1 WHERE ${q} = ${i}`)}if(R){const i=I(o.by??[],R),l=C(R[p]);if(l===void 0)$(r,j(u,i,null,1,e`${g} = ${g} + 1`));else{const h=d==="min"?"MIN":"MAX";$(r,j(u,i,l,1,e`${S} = ${e.raw(h)}(COALESCE(${S}, excluded.${S}), excluded.${S}), ${g} = ${g} + 1`))}}}},re=t=>{for(const o of E.tables[t]?.aggregateIndexes??[])W(t,o)},H=(t,o,a)=>{for(const f of E.tables[t]?.aggregateIndexes??[])ie(t,f,o,a)},B=(t,o)=>{const a=`${t}::rank::${o.name}`;if(b.has(a))return;const f=Z(t,o.name),u=$(r,e`SELECT id, _creationTime, ${e.identifier(D)} FROM ${e.identifier(t)}`).toArray();$(r,e`DELETE FROM ${e.identifier(f)}`);const d=ne(o);for(const p of u){const _=M(p);!_||o.where&&!x(_,o.where)||te(r,f,o,d,_._id,_)}b.add(a)},ae=t=>{for(const o of E.tables[t]?.rankIndexes??[])B(t,o)},K=(t,o,a,f)=>{for(const u of E.tables[t]?.rankIndexes??[])Ge(r,t,u,o,a,f)},V=(t,o,a,f)=>{const u=E.tables[t]?.searchIndexes??[];if(!(u.length===0||!fe(r)))for(const d of u){if(He(f,a,d))continue;const p=De(t,d.name);$(r,e`DELETE FROM ${e.identifier(p)} WHERE ${e.identifier(Y)} = ${o}`),a&&$(r,e`INSERT INTO ${e.identifier(p)} (${e.identifier(Me)}, ${e.identifier(Y)}) VALUES (${Ke(a,d)}, ${o})`)}},G=(t,o,a)=>{for(const f of E.tables[t]?.geoIndexes??[]){const u=ue(t,f.name);$(r,e`DELETE FROM ${e.identifier(u)} WHERE ${e.identifier("__id__")} = ${o}`);const d=a?.[f.field];if(d!==null&&typeof d=="object"&&typeof d.lat=="number"&&typeof d.lng=="number"){const{lat:p,lng:_}=d,F=me({lat:p,lng:_},f.precision??Ee);$(r,e`INSERT INTO ${e.identifier(u)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${o}, ${F}, ${p}, ${_})`)}}};return{ensureBackfilledForTable:re,ensureBackfilledIndex:W,ensureRankBackfilled:B,ensureRankBackfilledForTable:ae,syncAggregates:H,syncCompanionsForInsert:(t,o,a)=>{V(t,o,a),G(t,o,a),H(t,void 0,a),K(t,o,void 0,a),w(t,o,a),y(t,o,"insert",a),s({indexKeys:c(t,a),key:o,op:"insert",row:a,table:t})},syncGeo:G,syncRanks:K,syncSearch:V}};export{De as S,Be as a,so as c,Ke as d,te as i,Y as l,Ce as q,ne as r,Me as y};
1
+ import{sql as e}from"drizzle-orm";import{matchesStaticWhere as P,aggregateSqlFunction as le}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as N,encodeAggregateKey as I,foldAggregateTally as J,coerceAggregateNumber as C}from"./aggregateTableName-CGi8gxeK.mjs";import{runDrizzle as $}from"./runDrizzle-2ULFQR_k.mjs";import{i as fe,g as ue,D,r as M,a as q,b as S,A as g,c as j,e as z}from"./do-sql-bkXQEBl8.mjs";import{param as de,WORKERD_SQLITE_LIMITS as $e}from"./param-DlozcSQu.mjs";import{encodeGeohash as me,GEO_DEFAULT_PRECISION as Ee}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as Q}from"./CURSOR_PREFIX-C0HEpLAN.mjs";import{encodePartitionKey as pe,sortColumnName as he,rankTableName as Z,matchesRankStaticWhere as x}from"./RANK_TIEBREAK-D157XEqw.mjs";import{m as ge}from"./sql-projection-BqmxFxQU.mjs";import{serializeSqlValue as ee}from"./serializeSqlValue-DbI1VQYM.mjs";const ye=["de","en","es","fr","it","nl","none","pt"],_e=n=>ye.includes(n),Se="a an and are as at be but by for if in into is it no not of on or such that the their then there these they this to was will with",we="aber als am an auch auf aus bei bin bis bist da dass der den des dem die das denn dir du ein eine für hat ich im in ist mit nicht noch nur oder sich sie sind über und von vor war wie wir zu zum zur",Te="a al como con de del el en es la las lo los mas no o para pero por que se su sus un una uno y ya",ve="au aux avec ce ces dans de des du elle en et eux il je la le les leur lui ma mais me même mes moi mon ne nos notre nous on ou par pas pour qu que qui sa se ses son sur ta te tes toi ton tu un une vos votre vous y",Re="a ai al alla anche che chi ci coi col come con da dal degli dei del della di do e ed gli ha hai hanno i il in la le lo ma mi ne nei nel non o per più quale quanto se si sono su sul tra un una uno vi",Ae="aan al als bij dan dat de der deze die dit door een en er het hij ij in is je kan me men met mij na naar niet nog nu of om ons ook op over te tot uit van voor was wat we wij zij zijn zo",Fe="a ao aos as até com como da das de do dos e em entre era essa esse esta este eu foi há isso já mais mas me mesmo meu na nas no nos num numa o os ou para pela pelo por qual que quem se sem seu só sua também te tem um uma você",be=/[\u0300-\u036F]/gu,Oe=/[\u0080-\u{10FFFF}]/u,Le=/[\p{L}\p{N}]+/gu,oe=n=>Oe.test(n)?n.normalize("NFD").replaceAll(be,"").normalize("NFC").toLowerCase():n.toLowerCase(),k=n=>new Set(oe(n).split(" ")),Ie={de:k(we),en:k(Se),es:k(Te),fr:k(ve),it:k(Re),nl:k(Ae),none:new Set,pt:k(Fe)},ke=2,qe=256,X=new Map,Ce=n=>{const s=n!==void 0&&_e(n)?n:"none",c=X.get(s);if(c)return c;const w=Ie[s],y=r=>{const A=(oe(r).match(Le)??[]).filter(T=>T.length<=qe);return w.size===0?A:A.filter(T=>!w.has(T))},E={document:y,profile:`${s}-v${String(ke)}`,query:r=>{const A=y(r);return A.filter((T,b)=>A.lastIndexOf(T)===b)}};return X.set(s,E),E},je=(n,s)=>{if(!s.includes("."))return n[s];let c=n;for(const w of s.split(".")){if(c===null||typeof c!="object"||Array.isArray(c))return;c=c[w]}return c},De=(n,s)=>`${n}__fts_${s}`,Me="__text__",Y="__id__",ze=1e3,Ue=(n,s)=>s.document(n),U=(n,s)=>je(n,s),We=n=>typeof n=="string"?n:n==null?"":typeof n=="number"||typeof n=="bigint"||typeof n=="boolean"?String(n):JSON.stringify(n)??"",He=(n,s,c)=>n!==void 0&&s!==void 0&&U(n,c.field)===U(s,c.field),Be=(n,s)=>Ue(We(U(n,s.field)),Ce(s.language)).slice(0,ze),Ke=(n,s)=>Be(n,s).join(" "),Ve=(n,s,c)=>[...n.partitionBy??[],...n.sortBy.map(y=>y.field),...n.where?Object.keys(n.where):[]].every(y=>s[y]===c[y]),ne=n=>e.join(["__id__","__partition__",...n.sortBy.map((s,c)=>he(c))].map(s=>e.identifier(s)),e`, `),te=(n,s,c,w,y,E)=>{const r=pe(c.partitionBy??[],E),A=c.sortBy.map(b=>ee(E[b.field]??null)),T=e.join([y,r,...A].map(b=>de(b)),e`, `);$(n,e`INSERT INTO ${e.identifier(s)} (${w}) VALUES (${T})`)},Ge=(n,s,c,w,y,E)=>{if(y&&E&&Ve(c,y,E))return;const r=Z(s,c.name);y&&$(n,e`DELETE FROM ${e.identifier(r)} WHERE ${e.identifier("__id__")} = ${w}`),!(!E||c.where&&!x(E,c.where))&&te(n,r,c,ne(c),w,E)},so=n=>{const{broadcast:s,indexKeysFor:c,invalidateCache:w,recordCdc:y,schema:E,sql:r}=n,A=new Set,T=t=>E.tables[t]?.softDeleteMode?.field,b=new Set,W=(t,o)=>{const a=`${t}::${o.name}`;if(A.has(a))return;const f=N(t,o.name),u=o.by??[],d=T(t),p=new Map,_=$(r,e`SELECT id, _creationTime, ${e.identifier(D)} FROM ${e.identifier(t)}`).toArray();for(const v of _){const m=M(v);if(!m||!Q(m,d)||o.where&&!P(m,o.where))continue;const R=I(u,m);J(p,R,o,m)}$(r,e`DELETE FROM ${e.identifier(f)}`);const F=Math.floor($e.boundParams/3),O=[...p];for(let v=0;v<O.length;v+=F){const m=O.slice(v,v+F),R=e.join(m.map(([i,l])=>e`(${i}, ${l.value}, ${l.count})`),e`, `);$(r,e`INSERT INTO ${e.identifier(f)} (${q}, ${S}, ${g}) VALUES ${R}`)}A.add(a)},se=(t,o,a)=>{const f=o.by??[],u=o.field??"",d=[],p=(i,l)=>{const h=ee(l);h===null?d.push(e`${z(i)} IS NULL`):d.push(e`${z(i)} = ${h}`)};for(const i of f)p(i,a[i]??null);const _=T(t);_!==void 0&&p(_,null);for(const[i,l]of Object.entries(o.where??{}))p(i,l!==null&&typeof l=="object"&&!Array.isArray(l)?l.eq:l);const F=d.length>0?e` WHERE ${e.join(d,e` AND `)}`:e``,O=E.tables[t]?.shape[u];if(O&&ge(O)){const i=$(r,e`SELECT id, _creationTime, ${e.identifier(D)} FROM ${e.identifier(t)}${F}`).toArray(),l=new Map;for(const h of i){const L=M(h);L&&J(l,"",o,L)}return{value:l.get("")?.value??null}}const v=le(o.op),m=z(u);return{value:$(r,e`SELECT ${e.raw(v)}(${m}) AS value FROM ${e.identifier(t)}${F}`).one().value??null}},ie=(t,o,a,f)=>{const u=N(t,o.name),{op:d}=o,p=o.field??"",_=i=>{$(r,e`DELETE FROM ${e.identifier(u)} WHERE ${q} = ${i} AND ${g} <= 0`)},F=T(t),O=i=>!o.where||P(i,o.where),v=i=>Q(i,F)&&O(i);f!==void 0&&d!=="count"&&O(f)&&C(f[p]);const m=a&&v(a)?a:void 0,R=f&&v(f)?f:void 0;if(!(!m&&!R)){if(d==="count"){for(const[i,l]of[[m,-1],[R,1]]){if(!i)continue;const h=I(o.by??[],i);$(r,j(u,h,l,l,e`${S} = ${S} + excluded.${S}, ${g} = ${g} + excluded.${g}`))}m&&_(I(o.by??[],m));return}if(d==="sum"||d==="avg"){for(const[i,l]of[[m,-1],[R,1]]){if(!i)continue;const h=C(i[p]);if(h===void 0)continue;const L=I(o.by??[],i);$(r,j(u,L,l*h,l,e`${S} = COALESCE(${S}, 0) + excluded.${S}, ${g} = ${g} + excluded.${g}`))}m&&_(I(o.by??[],m));return}if(m){const i=I(o.by??[],m),l=C(m[p]),h=$(r,e`SELECT ${S} AS value, ${g} AS count FROM ${e.identifier(u)} WHERE ${q} = ${i}`).toArray()[0],L=(h?.count??0)-1;if(L<=0)$(r,e`DELETE FROM ${e.identifier(u)} WHERE ${q} = ${i}`);else if(h&&l!==void 0&&h.value!==null&&l===h.value){const ce=se(t,o,m);$(r,e`UPDATE ${e.identifier(u)} SET ${S} = ${ce.value}, ${g} = ${L} WHERE ${q} = ${i}`)}else $(r,e`UPDATE ${e.identifier(u)} SET ${g} = ${g} - 1 WHERE ${q} = ${i}`)}if(R){const i=I(o.by??[],R),l=C(R[p]);if(l===void 0)$(r,j(u,i,null,1,e`${g} = ${g} + 1`));else{const h=d==="min"?"MIN":"MAX";$(r,j(u,i,l,1,e`${S} = ${e.raw(h)}(COALESCE(${S}, excluded.${S}), excluded.${S}), ${g} = ${g} + 1`))}}}},re=t=>{for(const o of E.tables[t]?.aggregateIndexes??[])W(t,o)},H=(t,o,a)=>{for(const f of E.tables[t]?.aggregateIndexes??[])ie(t,f,o,a)},B=(t,o)=>{const a=`${t}::rank::${o.name}`;if(b.has(a))return;const f=Z(t,o.name),u=$(r,e`SELECT id, _creationTime, ${e.identifier(D)} FROM ${e.identifier(t)}`).toArray();$(r,e`DELETE FROM ${e.identifier(f)}`);const d=ne(o);for(const p of u){const _=M(p);!_||o.where&&!x(_,o.where)||te(r,f,o,d,_._id,_)}b.add(a)},ae=t=>{for(const o of E.tables[t]?.rankIndexes??[])B(t,o)},K=(t,o,a,f)=>{for(const u of E.tables[t]?.rankIndexes??[])Ge(r,t,u,o,a,f)},V=(t,o,a,f)=>{const u=E.tables[t]?.searchIndexes??[];if(!(u.length===0||!fe(r)))for(const d of u){if(He(f,a,d))continue;const p=De(t,d.name);$(r,e`DELETE FROM ${e.identifier(p)} WHERE ${e.identifier(Y)} = ${o}`),a&&$(r,e`INSERT INTO ${e.identifier(p)} (${e.identifier(Me)}, ${e.identifier(Y)}) VALUES (${Ke(a,d)}, ${o})`)}},G=(t,o,a)=>{for(const f of E.tables[t]?.geoIndexes??[]){const u=ue(t,f.name);$(r,e`DELETE FROM ${e.identifier(u)} WHERE ${e.identifier("__id__")} = ${o}`);const d=a?.[f.field];if(d!==null&&typeof d=="object"&&typeof d.lat=="number"&&typeof d.lng=="number"){const{lat:p,lng:_}=d,F=me({lat:p,lng:_},f.precision??Ee);$(r,e`INSERT INTO ${e.identifier(u)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${o}, ${F}, ${p}, ${_})`)}}};return{ensureBackfilledForTable:re,ensureBackfilledIndex:W,ensureRankBackfilled:B,ensureRankBackfilledForTable:ae,syncAggregates:H,syncCompanionsForInsert:(t,o,a)=>{V(t,o,a),G(t,o,a),H(t,void 0,a),K(t,o,void 0,a),w(t,o,a),y(t,o,"insert",a),s({indexKeys:c(t,a),key:o,op:"insert",row:a,table:t})},syncGeo:G,syncRanks:K,syncSearch:V}};export{De as S,Be as a,so as c,Ke as d,te as i,Y as l,Ce as q,ne as r,Me as y};
@@ -1,4 +1,4 @@
1
- import{sql as i}from"drizzle-orm";import{e as o,d as l}from"./wire-codec-CDds5uQW.mjs";import{runDrizzle as d}from"./runDrizzle-2ULFQR_k.mjs";const a="__lunora_relay_shapes",t=null,u=e=>{d(e,i`CREATE TABLE IF NOT EXISTS ${i.identifier(a)} (
1
+ import{sql as i}from"drizzle-orm";import{e as o,d as l}from"./wire-codec-COhOSEe4.mjs";import{runDrizzle as d}from"./runDrizzle-2ULFQR_k.mjs";const a="__lunora_relay_shapes",t=null,u=e=>{d(e,i`CREATE TABLE IF NOT EXISTS ${i.identifier(a)} (
2
2
  key TEXT PRIMARY KEY,
3
3
  relay_idx INTEGER,
4
4
  connection_id TEXT,
@@ -1 +1 @@
1
- import{createShardCtxDb as S}from"./NotUniqueError-DJFaCeQK.mjs";import{createRelayLink as B}from"./DEFAULT_MAX_RELAYS-JVr88opJ.mjs";import{ConflictError as I}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as v}from"./runShardMigrations-DS2tQC3s.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-DFAcRYsv.mjs";const _=(E,u={})=>({_meta:{column:{notNull:!0,...u}},kind:E}),D=(E,u,N)=>{const{describe:k,expect:i,it:m}=N;k(`engine contract: ${E}`,()=>{k("optimistic concurrency",()=>{const b=h=>({tables:{items:{indexes:[],shape:{title:_("string"),version:_("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{h.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});m("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await i(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(I)}finally{h?.()}}),m("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;i(e.code).toBe("CONFLICT"),i(e.kind).toBe("occ")}finally{h?.()}}),m("leaves the row readable and unchanged after a conflict",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const a=await s.get("i1");i(a?.title).toBe("first"),i(a?.version).toBe(99)}finally{h?.()}}),m("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l={tables:{items:{indexes:[],shape:{title:_("string"),version:_("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch(o.doc._id,{version:99})},op:"update",timing:"before"}}}}};v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;i(e).toBeInstanceOf(I),i(e.code).toBe("CONFLICT"),i(e.kind).toBe("trigger")}finally{h?.()}})}),k("shape-poke ordering",()=>{const b="shard-a",h={args:{},name:"messages"},d=(e,t,o,n)=>e.accept(t?.()??{},{connectionId:o,shapes:{[n]:h}}),c=(e,t)=>{let o=0,n=0;const r=g=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${g}`)},p={fetch:(g,O)=>{if(JSON.parse(O?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const C=t[n];if(n+=1,C===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(C))}},y={get:()=>p,getByName:()=>p,idFromName:g=>g},w={buildShapeDiff:r("buildShapeDiff"),computeOpLogShapeSeed:r("computeOpLogShapeSeed"),currentCdcEpoch:r("currentCdcEpoch"),deliverWhisperLocal:r("deliverWhisperLocal"),doName:()=>F(b,0),env:()=>({SHARD:y}),getWebSockets:()=>e.getSockets(),maskMetadata:r("maskMetadata"),nextPokeId:()=>(o+=1,`poke-${String(o)}`),readAttachment:g=>g.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:r("resolveShape"),rlsMetadata:r("rlsMetadata"),shardBinding:()=>"SHARD",sql:r("sql")},f=B(w);if(f===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return f},l=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,o)=>{const n=await e.seedRelayShape(t,o,h,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},a=(e={})=>l({...h,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});m("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1");await s(r,p,"s1"),await r.handleControl(a());const w=(await o(p)).map(f=>JSON.parse(f));i(w.map(f=>f.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),i(new Set(w.map(f=>f.pokeId)).size).toBe(1),i(w[1]?.shapeId).toBe("s1"),i(w[2]?.checkpoint).toBe(20)}finally{e?.()}}),m("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1"),y=d(n,t,"c-bob","s2");await s(r,p,"s1"),await s(r,y,"s2"),await r.handleControl(a());const w=await o(p);i(w.length).toBe(3);const f=await o(y);i(f.length).toBe(0),await r.handleControl(a());const g=await o(p);i(g.length).toBe(3)}finally{e?.()}}),m("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1");await s(r,p,"s1"),await r.handleControl(a({epoch:"e2"}));const y=await o(p);i(y.length).toBe(0),await r.handleControl(a());const w=await o(p);i(w.length).toBe(3)}finally{e?.()}})}),k("RLS identity under live subscription",()=>{const b="shard-a",h={args:{},name:"lobby-messages"},d={args:{},name:"my-orders"},c=s=>{const a=[],e=[],t={fetch:(r,p)=>(a.push(JSON.parse(p?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=B({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>b,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:r=>r}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(r,p,y)=>(e.push(y),r===d.name?{columns:["id"],effectiveWhere:{org:y?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:a,resolvedUnder:e}},l=async(s,a)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...a,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};m("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:a}=u();try{const{owner:e,resolvedUnder:t}=c(a.sql);await l(e,d),i(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),m("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:a}=u();try{const{owner:e,posts:t}=c(a.sql);await l(e,d),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),m("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:a}=u();try{const{owner:e,posts:t}=c(a.sql);await l(e,h),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{D as defineEngineContractSuite};
1
+ import{createShardCtxDb as S}from"./NotUniqueError-Dwab63fS.mjs";import{createRelayLink as B}from"./DEFAULT_MAX_RELAYS-Bjx0HDbs.mjs";import{ConflictError as I}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as v}from"./runShardMigrations-PZnc7KFE.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-DpUu_mpH.mjs";const _=(E,u={})=>({_meta:{column:{notNull:!0,...u}},kind:E}),D=(E,u,N)=>{const{describe:k,expect:i,it:m}=N;k(`engine contract: ${E}`,()=>{k("optimistic concurrency",()=>{const b=h=>({tables:{items:{indexes:[],shape:{title:_("string"),version:_("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{h.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});m("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await i(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(I)}finally{h?.()}}),m("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;i(e.code).toBe("CONFLICT"),i(e.kind).toBe("occ")}finally{h?.()}}),m("leaves the row readable and unchanged after a conflict",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const a=await s.get("i1");i(a?.title).toBe("first"),i(a?.version).toBe(99)}finally{h?.()}}),m("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l={tables:{items:{indexes:[],shape:{title:_("string"),version:_("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch(o.doc._id,{version:99})},op:"update",timing:"before"}}}}};v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;i(e).toBeInstanceOf(I),i(e.code).toBe("CONFLICT"),i(e.kind).toBe("trigger")}finally{h?.()}})}),k("shape-poke ordering",()=>{const b="shard-a",h={args:{},name:"messages"},d=(e,t,o,n)=>e.accept(t?.()??{},{connectionId:o,shapes:{[n]:h}}),c=(e,t)=>{let o=0,n=0;const r=g=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${g}`)},p={fetch:(g,O)=>{if(JSON.parse(O?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const C=t[n];if(n+=1,C===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(C))}},y={get:()=>p,getByName:()=>p,idFromName:g=>g},w={buildShapeDiff:r("buildShapeDiff"),computeOpLogShapeSeed:r("computeOpLogShapeSeed"),currentCdcEpoch:r("currentCdcEpoch"),deliverWhisperLocal:r("deliverWhisperLocal"),doName:()=>F(b,0),env:()=>({SHARD:y}),getWebSockets:()=>e.getSockets(),maskMetadata:r("maskMetadata"),nextPokeId:()=>(o+=1,`poke-${String(o)}`),readAttachment:g=>g.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:r("resolveShape"),rlsMetadata:r("rlsMetadata"),shardBinding:()=>"SHARD",sql:r("sql")},f=B(w);if(f===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return f},l=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,o)=>{const n=await e.seedRelayShape(t,o,h,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},a=(e={})=>l({...h,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});m("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1");await s(r,p,"s1"),await r.handleControl(a());const w=(await o(p)).map(f=>JSON.parse(f));i(w.map(f=>f.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),i(new Set(w.map(f=>f.pokeId)).size).toBe(1),i(w[1]?.shapeId).toBe("s1"),i(w[2]?.checkpoint).toBe(20)}finally{e?.()}}),m("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1"),y=d(n,t,"c-bob","s2");await s(r,p,"s1"),await s(r,y,"s2"),await r.handleControl(a());const w=await o(p);i(w.length).toBe(3);const f=await o(y);i(f.length).toBe(0),await r.handleControl(a());const g=await o(p);i(g.length).toBe(3)}finally{e?.()}}),m("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1");await s(r,p,"s1"),await r.handleControl(a({epoch:"e2"}));const y=await o(p);i(y.length).toBe(0),await r.handleControl(a());const w=await o(p);i(w.length).toBe(3)}finally{e?.()}})}),k("RLS identity under live subscription",()=>{const b="shard-a",h={args:{},name:"lobby-messages"},d={args:{},name:"my-orders"},c=s=>{const a=[],e=[],t={fetch:(r,p)=>(a.push(JSON.parse(p?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=B({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>b,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:r=>r}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(r,p,y)=>(e.push(y),r===d.name?{columns:["id"],effectiveWhere:{org:y?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:a,resolvedUnder:e}},l=async(s,a)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...a,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};m("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:a}=u();try{const{owner:e,resolvedUnder:t}=c(a.sql);await l(e,d),i(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),m("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:a}=u();try{const{owner:e,posts:t}=c(a.sql);await l(e,d),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),m("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:a}=u();try{const{owner:e,posts:t}=c(a.sql);await l(e,h),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{D as defineEngineContractSuite};
@@ -1 +1 @@
1
- import{LunoraError as _}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{quoteIdentifier as A}from"./quoteIdentifier-CObIFRhb.mjs";import{d as T,n as $,e as p}from"./wire-codec-CDds5uQW.mjs";import{runDrizzle as l}from"./runDrizzle-2ULFQR_k.mjs";import{s as S}from"./sql-projection-BqmxFxQU.mjs";import"./serializeSqlValue-DbI1VQYM.mjs";const O=/^[A-Za-z_$][\w$]*$/u,b=e=>O.test(e)?e:`"${e.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,m="__doc__",i="__originals__",R=e=>{if(Object.hasOwn(e,i))throw new _("BAD_REQUEST",`"${i}" is reserved by the row store's document encoding and cannot be used as a field name — rename the field`);let t,r;for(const[s,a]of Object.entries(e)){const c=S(a);c!==void 0&&(t??={...e},r??=Object.create(null),t[s]=c,r[s]=a)}t&&r&&(t[i]=r);const n=t??e;try{return $(n)?JSON.stringify(p(n)):JSON.stringify(n)}catch(s){throw new _("BAD_REQUEST",`this document cannot be stored: ${s instanceof Error?s.message:String(s)}`)}},h=e=>{const t=T(JSON.parse(e)),r=t[i];if(r===null||typeof r!="object"||Array.isArray(r))return t;const n={...t};return delete n[i],{...n,...r}},G=(e,t)=>`${e}__geo_${t}`,E=(e,t)=>t==="_id"||t==="id"?`${e}id`:t==="_creationTime"?`${e}_creationTime`:`json_extract(${e}${m}, '$.${b(t).replaceAll("'","''")}')`,g=e=>E("",e),J=e=>o.raw(g(e)),N=(e,t)=>E(`${A(e)}.`,t),q=(e,t)=>o.raw(N(e,t)),B=(e,t,r,n)=>o`CREATE ${n?o`UNIQUE `:o``}INDEX IF NOT EXISTS ${o.identifier(e)} ON ${o.identifier(t)} (${r})`,f=o.identifier("__key__"),y=o.identifier("__value__"),I=o.identifier("__count__"),z=(e,t,r,n,s)=>o`INSERT INTO ${o.identifier(e)} (${f}, ${y}, ${I}) VALUES (${t}, ${r}, ${n}) ON CONFLICT(${f}) DO UPDATE SET ${s}`,d=new WeakMap,F=e=>{const t=d.get(e);if(t!==void 0)return t;const r=[];for(const[n,s]of Object.entries(e.shape)){const a=s._meta?.column;a&&r.push(Object.freeze([n,a]))}return Object.freeze(r),d.set(e,r),r},j=e=>{if(!e)return;const t=e[m];let r;typeof t=="string"?r=h(t):t&&typeof t=="object"?r=t:r={};const{id:n}=e;typeof n=="string"&&(r._id=n);const s=e._creationTime;return typeof s=="number"&&(r._creationTime=s),r},W=e=>{try{return j(e)}catch{return}},u=new WeakMap,k=e=>{const t=u.get(e);if(t!==void 0)return t;let r;try{l(e,o`CREATE VIRTUAL TABLE IF NOT EXISTS ${o.identifier("__lunora_fts_probe")} USING fts5(x)`),r=!0}catch{r=!1}finally{try{l(e,o`DROP TABLE IF EXISTS ${o.identifier("__lunora_fts_probe")}`)}catch{}}return u.set(e,r),r};export{I as A,m as D,f as a,y as b,z as c,B as d,J as e,q as f,G as g,W as h,k as i,g as j,R as k,h as l,b as m,i as n,N as q,j as r,F as t};
1
+ import{LunoraError as _}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{quoteIdentifier as A}from"./quoteIdentifier-CObIFRhb.mjs";import{d as T,n as $,e as p}from"./wire-codec-COhOSEe4.mjs";import{runDrizzle as l}from"./runDrizzle-2ULFQR_k.mjs";import{s as S}from"./sql-projection-BqmxFxQU.mjs";import"./serializeSqlValue-DbI1VQYM.mjs";const O=/^[A-Za-z_$][\w$]*$/u,b=e=>O.test(e)?e:`"${e.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,m="__doc__",i="__originals__",R=e=>{if(Object.hasOwn(e,i))throw new _("BAD_REQUEST",`"${i}" is reserved by the row store's document encoding and cannot be used as a field name — rename the field`);let t,r;for(const[s,a]of Object.entries(e)){const c=S(a);c!==void 0&&(t??={...e},r??=Object.create(null),t[s]=c,r[s]=a)}t&&r&&(t[i]=r);const n=t??e;try{return $(n)?JSON.stringify(p(n)):JSON.stringify(n)}catch(s){throw new _("BAD_REQUEST",`this document cannot be stored: ${s instanceof Error?s.message:String(s)}`)}},h=e=>{const t=T(JSON.parse(e)),r=t[i];if(r===null||typeof r!="object"||Array.isArray(r))return t;const n={...t};return delete n[i],{...n,...r}},G=(e,t)=>`${e}__geo_${t}`,E=(e,t)=>t==="_id"||t==="id"?`${e}id`:t==="_creationTime"?`${e}_creationTime`:`json_extract(${e}${m}, '$.${b(t).replaceAll("'","''")}')`,g=e=>E("",e),J=e=>o.raw(g(e)),N=(e,t)=>E(`${A(e)}.`,t),q=(e,t)=>o.raw(N(e,t)),B=(e,t,r,n)=>o`CREATE ${n?o`UNIQUE `:o``}INDEX IF NOT EXISTS ${o.identifier(e)} ON ${o.identifier(t)} (${r})`,f=o.identifier("__key__"),y=o.identifier("__value__"),I=o.identifier("__count__"),z=(e,t,r,n,s)=>o`INSERT INTO ${o.identifier(e)} (${f}, ${y}, ${I}) VALUES (${t}, ${r}, ${n}) ON CONFLICT(${f}) DO UPDATE SET ${s}`,d=new WeakMap,F=e=>{const t=d.get(e);if(t!==void 0)return t;const r=[];for(const[n,s]of Object.entries(e.shape)){const a=s._meta?.column;a&&r.push(Object.freeze([n,a]))}return Object.freeze(r),d.set(e,r),r},j=e=>{if(!e)return;const t=e[m];let r;typeof t=="string"?r=h(t):t&&typeof t=="object"?r=t:r={};const{id:n}=e;typeof n=="string"&&(r._id=n);const s=e._creationTime;return typeof s=="number"&&(r._creationTime=s),r},W=e=>{try{return j(e)}catch{return}},u=new WeakMap,k=e=>{const t=u.get(e);if(t!==void 0)return t;let r;try{l(e,o`CREATE VIRTUAL TABLE IF NOT EXISTS ${o.identifier("__lunora_fts_probe")} USING fts5(x)`),r=!0}catch{r=!1}finally{try{l(e,o`DROP TABLE IF EXISTS ${o.identifier("__lunora_fts_probe")}`)}catch{}}return u.set(e,r),r};export{I as A,m as D,f as a,y as b,z as c,B as d,J as e,q as f,G as g,W as h,k as i,g as j,R as k,h as l,b as m,i as n,N as q,j as r,F as t};
@@ -1 +1 @@
1
- import{toErrorBody as f}from"@lunora/errors";const l=200,b=(r,n)=>{const i=e=>{const o=r.tables[e];return o!==void 0&&o.shardMode?.kind!=="global"};return(n&&n.length>0?[...n]:Object.keys(r.tables)).filter(e=>i(e))},p=async function*(r,n,i=l){let e=null,o=!1;for(;!o;){const t=await r.findMany(n,{cursor:e,limit:i});for(const s of t.page)yield{doc:s,table:n};e=t.continueCursor,o=t.isDone||e===null}},A=async function*(r,n,i){const e=b(n,i.tables),o=i.batchSize??l;for(const t of e)yield*p(r,t,o)},u=new Set(["_creationTime","_id"]),y=(r,n)=>{for(const[i,e]of Object.entries(r.shape)){const o=n[i];if(o===void 0&&e.kind==="optional")continue;const t=e.parse;if(typeof t=="function")try{t(o)}catch(s){const c=s instanceof Error?s.message:String(s);return`field "${i}": ${c}`}}},h=(r,n,i)=>{const e=r.tables[n];if(!e)return`unknown table: ${n}`;if(e.shardMode?.kind==="global")return`table "${n}" is a global (.global()) table and is not importable through the shard import path`;const o=Object.fromEntries(Object.entries(i).filter(([t])=>!u.has(t)));for(const t of Object.keys(o))if(!(t in e.shape))return`unexpected field "${t}": not declared in table "${n}"`;return y(e,o)},m=async(r,n)=>{try{return await r.get(n)!==null}catch{return!1}},g=async(r,n,i,e)=>{const{doc:o,table:t}=i;if(typeof t!="string"||t.length===0)return{error:{code:"BAD_ROW",line:e,message:"row is missing `table`",table:t},kind:"error"};if(!o||typeof o!="object"||Array.isArray(o))return{error:{code:"BAD_ROW",line:e,message:"row is missing or malformed `doc`",table:t},kind:"error"};const s=h(n,t,o);if(s!==void 0)return{error:{code:"VALIDATION_ERROR",line:e,message:s,table:t},kind:"error"};const c=typeof o._id=="string"?o._id:void 0;if(c!==void 0&&await m(r,c))return{kind:"conflict"};try{return await r.insert(t,o,{allowExplicitId:!0}),{kind:"inserted",table:t}}catch(a){const{body:d}=f(a,{fallbackCode:"INSERT_FAILED"});return{error:{code:d.code,line:e,message:d.message,table:t},kind:"error"}}},S=async(r,n,i)=>{const e=[],o={};let t=0,s=(i.startLine??1)-1;for(const c of i.rows){s+=1;const a=await g(r,n,c,s);a.kind==="error"?e.push(a.error):a.kind==="conflict"?t+=1:o[a.table]=(o[a.table]??0)+1}return{conflicts:t,errors:e,inserted:o}},k=r=>{const n=Array.isArray(r.tables)?r.tables.filter(e=>typeof e=="string"):void 0;return{batchSize:typeof r.batchSize=="number"?r.batchSize:void 0,tables:n}},E=r=>{const n=Array.isArray(r.rows)?r.rows:[],i=[];for(const o of n){if(!o||typeof o!="object")continue;const t=o;if(typeof t.table!="string"||!t.doc||typeof t.doc!="object"||Array.isArray(t.doc)){i.push({doc:t.doc??{},table:typeof t.table=="string"?t.table:""});continue}i.push({doc:t.doc,table:t.table})}const e=typeof r.startLine=="number"?r.startLine:void 0;return{rows:i,startLine:e}};export{A as exportShardRows,p as exportShardTable,S as importShardRows,k as parseExportShardArgs,E as parseImportShardArgs,b as selectExportTables,h as validateImportRow};
1
+ import{toErrorBody as f}from"@lunora/errors";const l=200,b=(r,n)=>{const i=e=>{const o=r.tables[e];return o!==void 0&&o.shardMode?.kind!=="global"};return(n&&n.length>0?[...n]:Object.keys(r.tables)).filter(e=>i(e))},p=async function*(r,n,i=l){let e=null,o=!1;for(;!o;){const t=await r.findMany(n,{cursor:e,limit:i});for(const s of t.page)yield{doc:s,table:n};e=t.continueCursor,o=t.isDone||e===null}},A=async function*(r,n,i){const e=b(n,i.tables),o=i.batchSize??l;for(const t of e)yield*p(r,t,o)},u=new Set(["_creationTime","_id"]),y=(r,n)=>{for(const[i,e]of Object.entries(r.shape)){const o=n[i];if(o===void 0&&e.kind==="optional")continue;const t=e.parse;if(typeof t=="function")try{t(o)}catch(s){const c=s instanceof Error?s.message:String(s);return`field "${i}": ${c}`}}},h=(r,n,i)=>{const e=r.tables[n];if(!e)return`unknown table: ${n}`;if(e.shardMode?.kind==="global")return`table "${n}" is a global (.global()) table and is not importable through the shard import path`;const o=Object.fromEntries(Object.entries(i).filter(([t])=>!u.has(t)));for(const t of Object.keys(o))if(!(t in e.shape))return`unexpected field "${t}": not declared in table "${n}"`;return y(e,o)},m=async(r,n)=>{try{return await r.get(n)!==null}catch{return!1}},g=async(r,n,i,e)=>{const{doc:o,table:t}=i;if(typeof t!="string"||t.length===0)return{error:{code:"BAD_ROW",line:e,message:"row is missing `table`",table:t},kind:"error"};if(!o||typeof o!="object"||Array.isArray(o))return{error:{code:"BAD_ROW",line:e,message:"row is missing or malformed `doc`",table:t},kind:"error"};const s=h(n,t,o);if(s!==void 0)return{error:{code:"VALIDATION_ERROR",line:e,message:s,table:t},kind:"error"};const c=typeof o._id=="string"?o._id:void 0;if(c!==void 0&&await m(r,c))return{kind:"conflict"};try{return await r.insert(t,o,{allowExplicitId:!0}),{kind:"inserted",table:t}}catch(a){const{body:d}=f(a,{fallbackCode:"INSERT_FAILED"});return{error:{code:d.code,line:e,message:d.message,table:t},kind:"error"}}},S=async(r,n,i)=>{const e=[],o={};let t=0,s=(i.startLine??1)-1;for(const c of i.rows){s+=1;const a=await g(r,n,c,s);a.kind==="error"?e.push(a.error):a.kind==="conflict"?t+=1:o[a.table]=(o[a.table]??0)+1}return{conflicts:t,errors:e,inserted:o}},k=r=>{const n=Array.isArray(r.tables)?r.tables.filter(e=>typeof e=="string"):void 0;return{batchSize:typeof r.batchSize=="number"?r.batchSize:void 0,tables:n}},E=r=>{const n=Array.isArray(r.rows)?r.rows:[],i=[];for(const o of n){if(!o||typeof o!="object")continue;const t=o;if(typeof t.table!="string"||!t.doc||typeof t.doc!="object"||Array.isArray(t.doc)){i.push({doc:t.doc??{},table:typeof t.table=="string"?t.table:""});continue}i.push({doc:t.doc,table:t.table})}const e=typeof r.startLine=="number"?r.startLine:void 0;return{rows:i,startLine:e}};export{A as exportShardRows,S as importShardRows,k as parseExportShardArgs,E as parseImportShardArgs,b as selectExportTables,h as validateImportRow};
@@ -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-2ULFQR_k.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-C4G4u8QD.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)} (
1
+ import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-2ULFQR_k.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-DZnPHEJw.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-BknLCi4r.mjs";import{selectShapeRows as m}from"./selectShapeMembers-Ce5Jr6UH.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};
1
+ import{applyCdcChanges as p}from"./CDC_LOG_TABLE-gl0FuepJ.mjs";import{selectShapeRows as m}from"./selectShapeMembers-CKQv8nwD.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};