@lunora/shard-engine 1.0.0-alpha.59 → 1.0.0-alpha.60

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 (58) hide show
  1. package/dist/conformance/index.mjs +1 -1
  2. package/dist/index.d.mts +15 -4
  3. package/dist/index.d.ts +15 -4
  4. package/dist/index.mjs +1 -1
  5. package/dist/packem_shared/{ADMIN_FUNCTIONS-MzNUYBeH.mjs → ADMIN_FUNCTIONS-CkHqihb_.mjs} +1 -1
  6. package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs +1 -0
  7. package/dist/packem_shared/AGG_COUNT-ZuAKCecq.mjs +1 -0
  8. package/dist/packem_shared/BIGINT_KEY_DIGITS-DIS6kqPO.mjs +1 -0
  9. package/dist/packem_shared/{CDC_LOG_TABLE-CAyqu8cg.mjs → CDC_LOG_TABLE-B-SKH98h.mjs} +1 -1
  10. package/dist/packem_shared/CURSOR_PREFIX-Bn8SFoGd.mjs +1 -0
  11. package/dist/packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs +1 -0
  12. package/dist/packem_shared/{DATA_MIGRATION_STATE_TABLE-BttUL9Sv.mjs → DATA_MIGRATION_STATE_TABLE-BNMWxRzv.mjs} +1 -1
  13. package/dist/packem_shared/{DEFAULT_MAX_RELATION_KEYS-Ciwtjo9t.mjs → DEFAULT_MAX_RELATION_KEYS-XESc7TiB.mjs} +1 -1
  14. package/dist/packem_shared/DEFAULT_MAX_RELAYS-DDOVsK5A.mjs +8 -0
  15. package/dist/packem_shared/{DEFAULT_TRANSACTION_LIMITS-D_xv2cwd.mjs → DEFAULT_TRANSACTION_LIMITS-UeeQm79B.mjs} +1 -1
  16. package/dist/packem_shared/NotUniqueError-BO_Arsyi.mjs +1 -0
  17. package/dist/packem_shared/{RANK_TIEBREAK-CkNuGm6a.mjs → RANK_TIEBREAK-3pXm7Ng_.mjs} +1 -1
  18. package/dist/packem_shared/RLS_UNWRAP_SYMBOL-BF5gi64E.mjs +1 -0
  19. package/dist/packem_shared/{ReactiveCache-Co_Q4zWX.mjs → ReactiveCache-D9NC5C9j.mjs} +1 -1
  20. package/dist/packem_shared/{applyOnDelete-tDhKaeB6.mjs → applyOnDelete-7JZ4vR9r.mjs} +1 -1
  21. package/dist/packem_shared/{backfillAggregateIndexes-pQWaX2Yu.mjs → backfillAggregateIndexes-BXftO36q.mjs} +1 -1
  22. package/dist/packem_shared/buildReprojectionMigration-Cmo0g3p3.mjs +1 -0
  23. package/dist/packem_shared/{buildShapeDiff-C-ipEyt_.mjs → buildShapeDiff-IXpIxdnF.mjs} +1 -1
  24. package/dist/packem_shared/{compileWhereSql-ByHAmOE-.mjs → compileWhereSql-B8tS0_nD.mjs} +1 -1
  25. package/dist/packem_shared/{computeRankPage-DEkYJ9Tz.mjs → computeRankPage-BvVrHUOx.mjs} +1 -1
  26. package/dist/packem_shared/createCompanionSync-CfuiObtd.mjs +1 -0
  27. package/dist/packem_shared/{createReplicaLink-D1Rmca3b.mjs → createReplicaLink-BPmCx8rV.mjs} +3 -3
  28. package/dist/packem_shared/ctx-db-companions-kHoblDbS.mjs +1 -0
  29. package/dist/packem_shared/defineEngineContractSuite-J4VL-C0q.mjs +1 -0
  30. package/dist/packem_shared/do-sql-ByyZb9U0.mjs +1 -0
  31. package/dist/packem_shared/estimate-bytes-DCVD8-i6.mjs +1 -0
  32. package/dist/packem_shared/{isSoftDeleted-CVu_TCeK.mjs → isSoftDeleted-BlFMzng2.mjs} +1 -1
  33. package/dist/packem_shared/{materializeExternalRows-CAPAra-0.mjs → materializeExternalRows-CFE0QRYx.mjs} +1 -1
  34. package/dist/packem_shared/{runShardMigrations-CkG92fSl.mjs → runShardMigrations-BvgoGgwG.mjs} +1 -1
  35. package/dist/packem_shared/{selectExpiredIds-BjZ_UtMx.mjs → selectExpiredIds-D-W5WEPH.mjs} +1 -1
  36. package/dist/packem_shared/{selectShapeMembers-DqikYFjS.mjs → selectShapeMembers-OatGcYrk.mjs} +1 -1
  37. package/dist/packem_shared/serializeSqlValue-xohfS85H.mjs +1 -0
  38. package/dist/packem_shared/sibling-channel-BkL5cTCc.mjs +1 -0
  39. package/dist/packem_shared/sql-projection-DML1_ex4.mjs +1 -0
  40. package/dist/packem_shared/where-sql-x1YKldcq.mjs +1 -0
  41. package/package.json +2 -2
  42. package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs +0 -1
  43. package/dist/packem_shared/AGG_COUNT-DnmDMp-h.mjs +0 -1
  44. package/dist/packem_shared/BIGINT_KEY_DIGITS-GvEBhyR5.mjs +0 -1
  45. package/dist/packem_shared/CURSOR_PREFIX-qn6nNVS7.mjs +0 -1
  46. package/dist/packem_shared/CountRlsUnsupportedError-Bdfupt3g.mjs +0 -1
  47. package/dist/packem_shared/DEFAULT_MAX_RELAYS-C3L_1GLp.mjs +0 -8
  48. package/dist/packem_shared/NotUniqueError-CTSwCMsP.mjs +0 -1
  49. package/dist/packem_shared/RLS_UNWRAP_SYMBOL-B3RgW-Kb.mjs +0 -1
  50. package/dist/packem_shared/buildReprojectionMigration-C-EJ_eKR.mjs +0 -1
  51. package/dist/packem_shared/createCompanionSync-BpWcC55_.mjs +0 -1
  52. package/dist/packem_shared/ctx-db-companions-B4O4d95S.mjs +0 -1
  53. package/dist/packem_shared/defineEngineContractSuite-F4j85ofN.mjs +0 -1
  54. package/dist/packem_shared/do-sql-FNOnpyHm.mjs +0 -1
  55. package/dist/packem_shared/estimate-bytes-DKqVDdZQ.mjs +0 -1
  56. package/dist/packem_shared/serializeSqlValue-B_-zaEWZ.mjs +0 -1
  57. package/dist/packem_shared/sibling-channel-Cxvk0Zca.mjs +0 -1
  58. package/dist/packem_shared/where-sql-B1l5NcUZ.mjs +0 -1
@@ -1 +0,0 @@
1
- import{LunoraError as $}from"@lunora/errors";import{D as st}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{c as un,S as fn,l as De,a as hn}from"./ctx-db-companions-B4O4d95S.mjs";import{sql as i}from"drizzle-orm";import{d as wn}from"./wire-codec-C-FpWm52.mjs";import{throwingScheduler as pn,aggregateSqlFunction as Le,normalizeCountArgument as gn}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as Ve,encodeAggregateKey as ze,readAggregateValue as Je}from"./aggregateTableName-C7o-gpms.mjs";import{mergeWhere as z,CountRlsUnsupportedError as Ye,selectIndexForGroupBy as $n,selectIndexForCount as yn,selectIndexForAggregate as En}from"./CountRlsUnsupportedError-Bdfupt3g.mjs";import{backfillSearchIndexesForTable as mn,searchIndexCoversTable as Sn}from"./backfillAggregateIndexes-pQWaX2Yu.mjs";import{backfillAggregateIndexes as Rr,backfillRankIndexes as Tr,backfillSearchIndexes as Ar}from"./backfillAggregateIndexes-pQWaX2Yu.mjs";import{appendCdcChange as _n}from"./CDC_LOG_TABLE-CAyqu8cg.mjs";import{CDC_LOG_TABLE as Ir,applyCdcChanges as Cr,bumpCdcEpoch as xr,cdcCanVouchFor as br,cdcSeqLeavingRows as Mr,cdcTouchesTables as Dr,cdcTrimmedError as Lr,compactCdcDocs as kr,cursorBelowRetainedFloor as Fr,minCdcReplayableSeq as qr,minCdcSeq as Br,readCdcChangeKeys as Wr,readCdcChanges as Ur,readCdcCursor as Pr,readCdcEpoch as Gr,trimCdcChanges as Hr}from"./CDC_LOG_TABLE-CAyqu8cg.mjs";import{allocateCommitSeq as Rn,COMMIT_SEQ_FIELD as Tn}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{isMemoryTable as _t}from"./clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as Rt}from"./computeRankPage-DEkYJ9Tz.mjs";import{SCAN_DEP as H}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as N,runSql as Se}from"./runDrizzle-2ULFQR_k.mjs";import{D as oe,k as ce,r as le,b as ke,A as Xe,a as Fe,e as X,t as jt,j as We,q as Tt,i as An,h as Kt,g as vn}from"./do-sql-FNOnpyHm.mjs";import{renderSql as Qt,unionAll as ct,WORKERD_SQLITE_LIMITS as Vt,sqliteInList as In}from"./param-DlozcSQu.mjs";import{coveringGeohashes as Cn,boundingBoxGeohashes as xn,haversineMeters as bn,pointInBoundingBox as Mn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Dn}from"./NotFoundError-BhF7FeFr.mjs";import{softDeleteScope as de,normalizeOrderKeys as nt,buildSeekWhere as zt,decodeCursor as ot,applySelect as At,encodeCursor as rt,tiebreakDirectionFor as Jt,buildSeekBeforeWhere as Ln}from"./CURSOR_PREFIX-qn6nNVS7.mjs";import{rankTableName as vt,sortColumnName as It,resolveRankPartition as kn,encodePartitionKey as Fn,RANK_TIEBREAK as qn,rankPivotConditionSql as Bn}from"./RANK_TIEBREAK-CkNuGm6a.mjs";import{UNVOUCHABLE_DEP as Ct}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as Wn,buildIndexRange as Un}from"./buildIndexRange-CBKQmHSS.mjs";import{assertFlatPredicate as Ze,resolveRelationPredicates as xt}from"./DEFAULT_MAX_RELATION_KEYS-Ciwtjo9t.mjs";import{runRowValidators as et,resolveWith as bt,relationHooks as Mt,applyOnDelete as Pn,fanOutScalarCounts as Gn}from"./applyOnDelete-tDhKaeB6.mjs";import{guardWriter as Hn}from"./RLS_UNWRAP_SYMBOL-B3RgW-Kb.mjs";import{quoteIdentifier as _e}from"./quoteIdentifier-CObIFRhb.mjs";import{mayHoldProjectedValue as On}from"./BIGINT_KEY_DIGITS-GvEBhyR5.mjs";import{createSystemReader as Nn}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as Ee}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as jn}from"./hasTrigger-CjlwI4le.mjs";import{c as ne,t as Pe,r as Ue,j as me,i as Dt}from"./where-sql-B1l5NcUZ.mjs";import{CLIENT_WATERMARK_TABLE as Nr,advanceClientWatermark as jr,migrateClientWatermark as Kr,readClientWatermark as Qr}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as zr,deleteGlobalShapeSnapshot as Jr,deleteGlobalShapeSnapshotsForConnection as Yr,migrateGlobalShapeSnapshot as Xr,readGlobalShapeSnapshot as Zr,writeGlobalShapeSnapshot as ei}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{IDEMPOTENCY_TABLE as ni,readIdempotent as oi,trimIdempotent as ri,writeIdempotent as ii}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{runShardMigrations as ci}from"./runShardMigrations-CkG92fSl.mjs";import{S as di}from"./ctx-db-search-state-ruTuCsxa.mjs";import{selectShapeMembers as ui,selectShapeRows as fi}from"./selectShapeMembers-DqikYFjS.mjs";import{serializeSqlValue as re}from"./serializeSqlValue-B_-zaEWZ.mjs";const Kn=o=>{const r=atob(o),t=Uint8Array.from(r,a=>a.codePointAt(0)??0);return new TextDecoder().decode(t)},Qn=()=>new $("BAD_REQUEST","invalid cursor"),Lt=16,kt=8,Y=1024,at=(o,r)=>r.query(o),Vn=(o,r)=>{if(o.length===0)return 0;let t=0;for(const[a,d]of r.entries()){const p=a===r.length-1;let E=0;for(const S of o)(p?S.startsWith(d):S===d)&&(E+=1);if(E===0)return 0;t+=E}return t},zn=(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 d=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:d+String.fromCodePoint(a)}},Jn=(o,r,t)=>{const a={eq:(d,p)=>{if(!o.definition.filterFields?.includes(d))throw new $("INTERNAL",`field "${d}" is not a filter field of search index "${o.indexName}" on table "${r}"`);if(o.filters.length>=kt)throw new $("BAD_REQUEST",`search index "${o.indexName}" on table "${r}": at most ${String(kt)} .eq() filters are supported per search query`);return o.filters.push({field:d,value:p}),a},search:(d,p)=>{const E=o;if(d!==E.definition.field)throw new $("INTERNAL",`search index "${E.indexName}" on table "${r}" indexes "${E.definition.field}", not "${d}"`);const S=at(p,t).length;if(S>Lt)throw new $("BAD_REQUEST",`search index "${E.indexName}" on table "${r}": at most ${String(Lt)} search terms are supported (got ${String(S)})`);return E.field=d,E.query=p,E.hasQuery=!0,a}};return a},Yn=o=>{if(o.length>Y)throw new $("BAD_REQUEST",`more than ${String(Y)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Xn=o=>Math.min(o.offset+o.numItems+1,Y),Zn=o=>btoa(`search:${String(o)}`),eo=o=>{let r;try{r=Kn(o)}catch{return}if(!r.startsWith("search:"))return;const t=Number(r.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},to=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?eo(o.cursor):0;if(t===void 0)throw Qn();if(t+r>=Y)throw new $("BAD_REQUEST",`search pagination reaches the ${String(Y)}-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,Y-t-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:t}},no=(o,r)=>{const t=r.offset+r.numItems,a=r.numItems>0&&o.length>t;return{continueCursor:a?Zn(t):null,isDone:!a,page:o.slice(r.offset,t)}},oo=o=>{if(o===void 0)return Y+1;if(!Number.isFinite(o))return Y;const r=Math.max(0,Math.floor(o));if(r>Y)throw new $("BAD_REQUEST",`search returns at most ${String(Y)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},Ge=o=>{const r=new Map;return t=>{const a=r.get(t);if(a!==void 0)return a;const d=o(_e(t));return r.set(t,d),d}},ue=_e(oe),ro=Ge(o=>`INSERT INTO ${o} (id, _creationTime, ${ue}) VALUES (?, ?, ?)`),Ft=Ge(o=>`UPDATE ${o} SET ${ue} = ? WHERE id = ? AND ${ue} = ?`),io=Ge(o=>`UPDATE ${o} SET _creationTime = ?, ${ue} = ? WHERE id = ? AND ${ue} = ?`),so=Ge(o=>`DELETE FROM ${o} WHERE id = ? AND ${ue} = ?`),co="SELECT changes() AS changed",qt=new Map,ao="",lo=o=>{const r=JSON.stringify(o),t=qt.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(oe)} FROM ${i.identifier(p)} WHERE id = ${ao}`),{sql:d}=Qt("sqlite",i`${ct(a)} LIMIT 1`);return qt.set(r,d),d},uo=(o,r)=>r.map(()=>o),fo=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,ho=o=>{if(!fo.test(o))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},Bt=50,Yt=500,qe=Math.floor(Vt.boundParams/3),$e=Vt.boundParams,wo=128,ae=(o,r,t)=>{const a=r??Yt;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})},po=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},go=o=>Math.max(o,Y),Xt=(o,r)=>{const t=o.filters.map(a=>i`${X(a.field)} = ${re(a.value)}`);return r&&t.push(r),t},$o=(o,r,t,a,d)=>{const p=at(t.query,st(t.definition.language));if(p.length===0)return[];const E=fn(r,t.indexName),S=`${E}__vocab`,_=p.length-1,D=p.map((R,k)=>{const q=zn(R,k===_),W=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(k))} AS ${i.identifier("__term__")}, COUNT(*) AS ${i.identifier("__n__")} FROM ${i.identifier(S)} WHERE ${W} GROUP BY ${i.identifier("doc")}`}),y=p.map((R,k)=>i`SUM(CASE WHEN u.${i.identifier("__term__")} = ${i.raw(String(k))} THEN u.${i.identifier("__n__")} ELSE 0 END)`),A=i`SELECT f.${i.identifier(De)} AS ${i.identifier(De)}, ${i.join(y,i` + `)} AS ${i.identifier("__score__")} FROM (${ct(D)}) u JOIN ${i.identifier(E)} f ON f.rowid = u.${i.identifier("doc")} GROUP BY f.${i.identifier(De)} HAVING ${i.join(y.map(R=>i`${R} > 0`),i` AND `)}`,I=Xt(t,d);let F=i`SELECT m.id, m._creationTime, m.${i.identifier(oe)}, s.${i.identifier("__score__")} AS ${i.identifier("__score__")} FROM (${A}) s JOIN ${i.identifier(r)} m ON m.id = s.${i.identifier(De)}`;I.length>0&&(F=i`${F} WHERE ${i.join(I,i` AND `)}`),F=i`${F} ORDER BY s.${i.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${i.raw(String(a))}`;const j=[];for(const R of N(o,F)){const k=Kt(R);if(k){const q=R.__score__;j.push({document:k,score:typeof q=="number"?q:Number(q??0)})}}return j},yo=(o,r,t,a,d)=>{const p=st(t.definition.language),E=at(t.query,p);if(E.length===0)return[];const S=Xt(t,d);let _=i`SELECT id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(r)}`;S.length>0&&(_=i`${_} WHERE ${i.join(S,i` AND `)}`),_=i`${_} ORDER BY _creationTime DESC, id ASC LIMIT ${i.raw(String(go(a)))}`;const D=N(o,_).toArray(),y=[];for(const A of D){const I=Kt(A);if(!I)continue;const F=Vn(hn(I,t.definition),E);F>0&&y.push({creationTime:typeof I._creationTime=="number"?I._creationTime:0,doc:I,id:typeof I._id=="string"?I._id:"",score:F})}return y.sort((A,I)=>I.score-A.score||I.creationTime-A.creationTime||A.id.localeCompare(I.id)),y.slice(0,a).map(A=>({document:A.doc,score:A.score}))},tt=(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]`)},Eo=(o,r)=>{const t=o,a={near:(d,p)=>{if(t.within)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(tt(d,".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:d.lat,lng:d.lng},radiusMeters:p},a},within:d=>{if(t.near)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(tt(d.sw,".within() sw corner",r,t.indexName),tt(d.ne,".within() ne corner",r,t.indexName),d.sw.lat>d.ne.lat)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(d.sw.lng>d.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:d.ne.lat,lng:d.ne.lng},sw:{lat:d.sw.lat,lng:d.sw.lng}},a}};return a},mo=(o,r)=>{const t=o[r];if(t===null||typeof t!="object")return;const{lat:a,lng:d}=t;return typeof a=="number"&&typeof d=="number"?{lat:a,lng:d}:void 0},So=(o,r)=>{const t=mo(o,r.definition.field);if(!t)return;const a=typeof o._creationTime=="number"?o._creationTime:0;if(r.near){const d=bn(r.near.point,t);return d<=r.near.radiusMeters?{creationTime:a,distance:d}:void 0}return Mn(t,r.within)?{creationTime:a,distance:0}:void 0},_o=(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 d=t.near?Cn(t.near.point,t.near.radiusMeters):xn(t.within),p=vn(r,t.indexName),E=d.map(A=>i`(g.${i.identifier("__geohash__")} >= ${A} AND g.${i.identifier("__geohash__")} < ${`${A}{`})`),S=[i`(${i.join(E,i` OR `)})`];a&&S.push(a);const _=i`SELECT m.id, m._creationTime, m.${i.identifier(oe)} FROM ${i.identifier(p)} g JOIN ${i.identifier(r)} m ON m.id = g.${i.identifier("__id__")} WHERE ${i.join(S,i` AND `)}`,D=N(o,_).toArray(),y=[];for(const A of D){const I=le(A),F=I?So(I,t):void 0;I&&F&&y.push({creationTime:F.creationTime,distance:F.distance,doc:I})}return y.sort((A,I)=>A.distance-I.distance||I.creationTime-A.creationTime),y},Zt=(o,r,t,a)=>{const d=[];for(const p of o)if(r.every(E=>E(a(p)))&&(d.push(p),typeof t=="number"&&d.length>=t))break;return d},Ro=(o,r,t,a,d,p=()=>{})=>{const E=t.within!==void 0,S=_o(o,r,t,d).map(_=>({distanceMeters:E?null:_.distance,document:_.doc}));return p(S.length),typeof a=="number"?S.slice(0,Math.max(0,Math.floor(a))):S},en=(o,r,t,a,d,p=()=>{})=>{const{geo:E}=t;if(!E)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const S=t.inMemoryFilters.length>0,_=Ro(o,r,E,S?void 0:d,a,p);return S?Zt(_,t.inMemoryFilters,d,D=>D.document):_},tn=(o,r,t,a)=>{const d=`SELECT id, _creationTime, ${_e(oe)} FROM ${_e(o)}`,p=`ORDER BY ${t}${a===void 0?"":` LIMIT ${String(a)}`}`;return r===void 0?Ue(`${d} ${p}`):me(`${d} WHERE `,r,` ${p}`)},To=(o,r,t,a,d,p=()=>{})=>en(o,r,t,a,d,p).map(E=>E.document),Ao=(o,r,t,a,d,p,E=()=>{})=>{const S=[];for(const A of t.sqlConditions)S.push(i`${X(A.field)} ${i.raw(A.comparator)} ${re(A.value)}`);a&&S.push(a);let _=i`SELECT id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(r)}`;S.length>0&&(_=i`${_} WHERE ${i.join(S,i` AND `)}`),_=i`${_} ORDER BY ${d}`,typeof p=="number"&&t.inMemoryFilters.length===0&&(_=i`${_} LIMIT ${i.raw(String(Math.max(0,Math.floor(p))))}`);const D=N(o,_).toArray();E(D.length);const y=[];for(const A of D){const I=le(A);if(I&&t.inMemoryFilters.every(F=>F(I))&&(y.push(I),typeof p=="number"&&y.length>=p))break}return y},ye={fieldRef:X,serialize:re},nn=(o,r)=>{const t=r===void 0?void 0:o.shape[r];return t!==void 0&&On(t)},Wt=(o,r)=>r.some(t=>nn(o,t)),Ut=(o,r,t)=>{if(nn(o,r))throw new $("BAD_REQUEST",`${t}: "${r}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},dt={fieldRef:o=>Ue(We(o)),serialize:re},vo=o=>{let r=0;const t=[],a={fieldRef:d=>Ue(We(d)),relationExists:d=>{const{childWhere:p,negated:E,parentTable:S,relation:_}=d,D=`__rel_${String(r)}`,y=t.at(-1)??S;r+=1,o(_.table,H);const A=_.kind==="one"?_.field:_.references,I=_.kind==="one"?_.references:_.field,F=Ue(`${Tt(D,I)} = ${Tt(y,A)}`);t.push(D);const j=ne(p,a,Pe);t.pop();const R=j===void 0?F:me(F," AND ",j),k=me("EXISTS (SELECT 1 FROM ",Dt(_.table)," AS ",Dt(D)," WHERE ",R,")");return E?me("NOT ",k):k},serialize:re};return a},on=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")} ${Jt(o)==="desc"?"DESC":"ASC"}`),r.join(", ")},Io=o=>{const r=o.map(t=>i`${X(t.field)} ${i.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||r.push(i`${X("id")} ${i.raw(Jt(o)==="desc"?"DESC":"ASC")}`),i.join(r,i`, `)},Co={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},xo=o=>{const r=new Set(o.sqlConditions.filter(a=>a.comparator==="=").map(a=>a.field));let t=0;for(;t<o.indexFields.length&&r.has(o.indexFields[t]??"");)t+=1;return o.indexFields.slice(t)},rn=(o,r)=>{const t=o.order,a=xo(o);return a.length>0?nt(a.map(d=>({[d]:t})),r):nt([{_creationTime:t}],r)},bo=(o,r,t,a)=>{const d=o.sqlConditions.map(p=>({[p.field]:{[Co[p.comparator]??"eq"]:p.value}}));if(t&&d.push(zt(r,ot(t))),a&&d.push(Ln(r,ot(a))),d.length!==0)return d.length===1?d[0]:{AND:d}},Mo=(o,r,t)=>{const a=[];for(const d of o){const p=le(d);if(p&&r.every(E=>E(p))&&(a.push(p),t!==void 0&&a.length>t))break}return a},Do=(o,r,t,a,d,p,E=()=>{})=>{const S=Math.max(0,Math.floor(d.numItems)),_=rn(a,t),D=typeof d.endCursor=="string",y=ne(bo(a,_,d.cursor,d.endCursor),dt,Pe),A=p&&y?me(y," AND ",p):p??y,I=a.inMemoryFilters.length>0,F=tn(r,A,on(_),I||D?void 0:S+1),j=Se(o,F.text,...F.params).toArray();E(j.length);const R=Mo(j,a.inMemoryFilters,I||D?void 0:S);if(D){const O=R.length>=2?R[Math.floor(R.length/2)-1]:void 0;return{continueCursor:d.endCursor??null,isDone:!0,page:R,splitCursor:O?rt(O,_):null}}const k=R.length>S,q=k?R.slice(0,S):R,W=q.at(-1);return{continueCursor:k&&W?rt(W,_):null,isDone:!k,page:q}};class Lo extends ${constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const ko=/\s/u,Fo=String.fromCodePoint(0),Pt=(o,r,t)=>{if(!o.tables[r])throw new $("INTERNAL",`unknown table: ${r}`);return typeof t!="string"||t.length===0||ko.test(t)||t.includes(Fo)?null:t},qo=(o,r,t,a=()=>{},d=()=>{},p=()=>{})=>{const E=r.tables[t];if(!E)throw new $("INTERNAL",`unknown table: ${t}`);const S=de(E.softDeleteMode,void 0),_=S?ne(S,ye):void 0,D=S?ne(S,dt,Pe):void 0,y={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let A=0;const I=m=>{const{search:C}=y;if(!C)throw new $("INTERNAL","runSearchFetch called without a staged search");mn(o,t,E);const M=y.inMemoryFilters.length>0,L=oo(M?void 0:m),K=An(o);if(K&&!Sn(o,t,C.definition))throw new $("SEARCH_INDEX_BUILDING",`search index "${C.indexName}" on table "${t}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const Z=K?$o(o,t,C,L,_):yo(o,t,C,L,_);return M?(A=Z.length,Zt(Z,y.inMemoryFilters,m,He=>He.document)):(m===void 0&&Yn(Z),Z)},F=m=>I(m).map(C=>C.document),j=m=>{const C=to(m);return no(F(Xn(C)),C)},R=()=>Io(rn(y,E.shape)),k=()=>{if(y.search||y.geo||y.indexName===void 0){d(void 0);return}d(Un(t,y.indexName,y.indexFields,y.sqlConditions,re))},q=m=>{k();let C=0;const M=(()=>{if(y.search){const L=F(m);return C=A,L}return y.geo?To(o,t,y,_,m,L=>{C=L}):Ao(o,t,y,_,R(),m,L=>{C=L})})();return p(Math.max(C,M.length)),M},W=()=>{if(!y.search&&!y.geo)throw new $("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);k();let m=0;const C=(()=>{if(y.search){const M=I(void 0);return m=A,M}return en(o,t,y,_,void 0,M=>{m=M})})();return p(Math.max(m,C.length)),C},O={async*[Symbol.asyncIterator](){if(y.search){yield*q(void 0);return}const m=[...y.inMemoryFilters];let C;y.inMemoryFilters=[];try{for(;;){const M=await O.paginate({cursor:C??null,numItems:wo});for(const L of M.page)m.every(K=>K(L))&&(yield L);if(M.isDone||M.continueCursor===null)return;C=M.continueCursor}}finally{y.inMemoryFilters=m}},async collect(){return q(void 0)},async collectWithScores(){return W()},filter(m){return y.inMemoryFilters.push(m),O},async first(){return q(y.inMemoryFilters.length>0?void 0:1)[0]??null},order(m){return y.order=m==="desc"?"desc":"asc",O},async paginate(m){let C=0;if(k(),y.search){const L=j(m);return p(L.page.length),L}if(y.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const M=Do(o,t,E.shape,y,m,D,L=>{C=L});return p(Math.max(C,M.page.length)),M},async take(m){return q(m)},async unique(){const m=q(y.inMemoryFilters.length>0?void 0:2);if(m.length>1)throw new Lo(`unique() on table "${t}" matched ${String(m.length)} documents; expected at most one`);return m[0]??null},withGeoIndex(m,C){const M=(E.geoIndexes??[]).find(K=>K.name===m);if(!M)throw new $("INTERNAL",`unknown geo index "${m}" on table "${t}"`);a(t,m,"geo");const L={definition:M,indexName:m};if(y.geo=L,C(Eo(L,t)),!L.near&&!L.within)throw new $("INTERNAL",`geo index "${m}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return O},withIndex(m,C){const M=E.indexes.find(L=>L.name===m);if(!M)throw new $("INTERNAL",`unknown index "${m}" on table "${t}"`);return a(t,m,"index"),y.indexName=m,y.indexFields=M.fields,C&&C(po(y)),O},withSearchIndex(m,C){const M=(E.searchIndexes??[]).find(K=>K.name===m);if(!M)throw new $("INTERNAL",`unknown search index "${m}" on table "${t}"`);a(t,m,"search");const L={definition:M,field:M.field,filters:[],hasQuery:!1,indexName:m,query:""};if(y.search=L,C(Jn(L,t,st(M.language))),!L.hasQuery)throw new $("INTERNAL",`search index "${m}" on table "${t}" requires a .search(field, query) call`);return O}};return O},Gt=(o,r,t)=>{const a={...r};for(const[d,p]of jt(o)){if(p.serverDefault){a[d]=p.serverDefault({auth:t});continue}a[d]===void 0&&(p.defaultFn?a[d]=p.defaultFn():"defaultValue"in p&&(a[d]=p.defaultValue))}return a},Ht=(o,r,t,a)=>{const d=t;for(const[p,E]of jt(o)){if(E.serverDefault){p in r&&(d[p]=E.serverDefault({auth:a}));continue}E.onUpdateFn&&!(p in r)&&(d[p]=E.onUpdateFn())}},Ot=(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.`)},Bo=/unique constraint failed/i,Wo=o=>o instanceof Error&&Bo.test(o.message),Uo=/string or blob too big/iu,Po=(o,r)=>{if(!(!(o instanceof Error)||!Uo.test(o.message)))throw new $("PAYLOAD_TOO_LARGE",`document is too large to store in "${r}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},it=(o,r,t,a)=>{try{Se(o,t,...a)}catch(d){throw Wo(d)?new Ee(`unique constraint violation on "${r}"`,"unique"):(Po(d,r),d)}},Be=(o,r,t,a)=>{if(it(o,r,t,a),Se(o,co).one().changed===0)throw new Ee(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},Nt=(o,r,t,a,d,p,E)=>{const S=[];for(let A=0;A<t.length+1;A+=1){const I=t[A],F=a[A],j=F?.direction==="desc"?"desc":"asc",R=I===void 0||F===void 0?i`${i.identifier(qn)} < ${E}`:Bn(I,p[A],j,!1);if(R===void 0)continue;const k=[];for(let W=0;W<A;W+=1)k.push(i`${i.identifier(t[W])} IS ${p[W]}`);k.push(R);const[q]=k;S.push(k.length===1&&q!==void 0?q:i`(${i.join(k,i` AND `)})`)}const _=S.length>0?i.join(S,i` OR `):i`1 = 0`,D=N(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${d} AND (${_})`).one(),y=N(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${d}`).one();return{before:D.c,total:y.c}},mr=o=>{const{sql:r}=o,{schema:t}=o,a=o.broadcast??(()=>{});let d;const p=()=>o.inTransaction?.()===!0,E=e=>t.tables[e]?.commitOrderedMode!==!0?{}:((d===void 0||!p())&&(d=Rn(r)),{[Tn]:d}),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(...Wn(s,h,re));return f.length>0?f:void 0},{headroom:_}=o;let D=!1;const y=async e=>{const n=D;D=!0;try{return await e()}finally{D=n}},A=o.onRead??(()=>{}),I=e=>{_t(t.tables[e])&&A(Ct,Ct)},F=o.onReadRange??(e=>{A(e.table,H)}),j=e=>{I(e.table),F(e)},R=(e,n)=>{n!==void 0&&n!==H&&!D&&_?.recordRead(1),I(e),A(e,n)},k=o.onIndexUse??(()=>{}),q=o.onWrite??(()=>{}),W=e=>{D||_?.recordWrite(e)},O=async e=>{W(e.doc),await q(e)},{cache:m}=o,C=o.clock??(()=>Date.now()),M=o.idGenerator??(()=>crypto.randomUUID()),L=o.scheduler??pn,{globalDb:K}=o,Z=o.auth??{identity:null,userId:null},He=o.cdc??!1,Oe=L,sn=Nn({scheduler:typeof Oe.list=="function"&&typeof Oe.get=="function"?Oe:void 0,storage:o.storage}),fe=(e,n,s,f)=>{He&&!_t(t.tables[e])&&_n(r,C(),e,n,s,f)},ie=e=>t.tables[e]?.shardMode?.kind==="global",lt=(e,n)=>{if(ie(e)){if(!K)throw new $("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return K}return U},Ne=e=>lt(e,"cascade"),V=(e,n)=>{if(ie(e)){if(!K)throw new $("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return K}},ut=async(e,n,s,f,h)=>{h&&W(s);const u=await e.insert(n,s,f);return a({key:u,op:"insert",row:{...s,_id:u},table:n}),u},je=(e,n)=>lt(e,"relation load").findMany(e,n),ft=(e,n)=>(ie(e)&&R(e,H),je(e,n)),cn=e=>!ie(e.table),ht=o.relationExistsPushDown??"auto",wt=ht!=="never",{maxRelationKeys:pt}=o,Re=(e,n,s)=>xt(e,{fetcher:ft,maxRelationKeys:pt,relationBaseWhere:s,schema:t,tableName:n}),gt=async(e,n,s,f)=>{const h=V(e,"relation grouped count");if(h)return R(e,H),Gn((B,v)=>h.count(B,v),e,n,s,f);const u=t.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);R(e,H);const c=de(u.softDeleteMode,void 0),l={[n]:{in:s}},w=z(z(l,f),c),T=await Re(w,e,void 0),g=ne(T,ye),b=X(n);let x=i`SELECT ${b} AS __fk__, COUNT(*) AS count FROM ${i.identifier(e)}`;g&&(x=i`${x} WHERE ${g}`),x=i`${x} GROUP BY ${b}`;const P=N(r,x).toArray();return new Map(P.map(B=>[B.__fk__,B.count]))};let Te=0;const $t=new Set;for(const[e,n]of Object.entries(t.tables))for(const s of Object.values(n.triggerMap??{}))$t.add(`${e} ${s.timing} ${s.op}`);const ee=(e,n,s)=>$t.has(`${e} ${n} ${s}`),te=async(e,n,s)=>{if(Te+=1,Te>Bt)throw Te-=1,new Ee(`trigger recursion exceeded ${String(Bt)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await jn({ctx:dn,event:s,op:n,schema:t,tableName:s.table,timing:e})}finally{Te-=1}},{ensureBackfilledForTable:he,ensureBackfilledIndex:Ke,ensureRankBackfilled:Qe,ensureRankBackfilledForTable:we,syncAggregates:Ae,syncCompanionsForInsert:yt,syncGeo:ve,syncRanks:pe,syncSearch:Ie}=un({broadcast:a,indexKeysFor:(e,n)=>S(e,n),invalidateCache:(e,n,s)=>m?.invalidate(e,n,S(e,s)),recordCdc:fe,schema:t,sql:r}),Et=(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})},mt=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),ge=e=>e===void 0||ie(e)?K:void 0,se=(e,n)=>{const s=mt(n);for(let f=0;f<s.length;f+=$e){const h=s.slice(f,f+$e),[u]=Se(r,lo(h),...uo(e,h)).toArray();if(!u)continue;const c=u.__t__,l=le(u);if(typeof c!="string"||!l)return;const w=u[oe];return{docJson:typeof w=="string"?w:ce(w??{}),row:l,tableName:c}}},an=(e,n)=>{const s=[...new Set(e)],f=new Map;if(s.length===0)return f;const h=mt(n);for(let u=0;u<h.length;u+=$e){const c=h.slice(u,u+$e),l=Math.floor($e/c.length),w=In(i`${i.identifier("id")}`,s,!1,l),T=c.map(g=>i`SELECT ${i.raw(`'${g.replaceAll("'","''")}'`)} AS __t__, id FROM ${i.identifier(g)} WHERE ${w}`);for(const g of N(r,ct(T))){const{id:b,__t__:x}=g;typeof x=="string"&&typeof b=="string"&&f.set(b,x)}}return f},St={assertRankPartitionLocal:Et,ensureRankBackfilled:Qe,onRead:R,rowToDocument:le,schema:t,sql:r},U={system:sn,async aggregate(e,n){const s=V(e,"aggregate");if(s)return R(e,H),s.aggregate(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);if(Le(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`);R(e,H);const h=de(f.softDeleteMode,void 0),u=z(z(n.baseWhere,n.where),h),c=await Re(u,e,n.relationBaseWhere),l=c!==u;if(f.aggregateIndexes&&!n.baseWhere&&!l&&(!h||Wt(f,[n.field]))){const B=En(f.aggregateIndexes,n.op,n.field,n.where);if(B){Ke(e,B.index);const v=ze(B.index.by??[],B.key),Q=Ve(e,B.index.name),J=N(r,i`SELECT ${ke} AS value, ${Xe} AS count FROM ${i.identifier(Q)} WHERE ${Fe} = ${v}`).toArray()[0];return Je(n.op,J)}}Ut(f,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const w=ne(c,ye),T=Le(n.op),g=X(n.field);let b=i`SELECT ${i.raw(T)}(${g}) AS value FROM ${i.identifier(e)}`;w&&(b=i`${b} WHERE ${w}`);const P=N(r,b).toArray()[0]?.value;return P??null},asId(e,n){const s=Pt(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=V(e,"count");if(s)return R(e,H),s.count(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=gn(n);if(h.restrictsCounts)throw new Ye(e);R(e,H);const u=de(f.softDeleteMode,void 0),c=z(z(h.baseWhere,h.where),u),l=await Re(c,e,h.relationBaseWhere),w=l!==c;if(f.aggregateIndexes&&!h.baseWhere&&!w&&!u){const x=yn(f.aggregateIndexes,h.where);if(x){Ke(e,x.index);const P=ze(x.index.by??[],x.key),B=Ve(e,x.index.name),v=N(r,i`SELECT ${ke} AS value FROM ${i.identifier(B)} WHERE ${Fe} = ${P}`).toArray();return v[0]===void 0?0:v[0].value??0}}const T=ne(l,ye);let g=i`SELECT COUNT(*) AS count FROM ${i.identifier(e)}`;return T&&(g=i`${g} WHERE ${T}`),N(r,g).one().count},async delete(e,n,s){const f=se(e,n);if(!f){const g=ge(n);g&&(W(void 0),await g.delete(e,n,s));return}const{docJson:h,row:u,tableName:c}=f,l=t.tables[c],w=s?.hard===!0,T=!w&&l?.softDeleteMode?l.softDeleteMode.field:void 0;if(!(T&&u[T]!==null&&u[T]!==void 0)){if(ee(c,"before","delete")&&await te("before","delete",{id:e,op:"delete",previous:u,table:c}),await Pn({deletedId:e,deletedReference:g=>u[g],findHolders:async(g,b,x)=>(await Ne(g).findMany(g,{includeDeleted:w,where:{[b]:x}})).page,onCascade:(g,b)=>Ne(g).delete(b,void 0,s),onRestrict:g=>{throw new Ee(g,"restrict")},onSetNull:(g,b,x)=>Ne(g).patch(b,{[x]:null}),schema:t,tableName:c}),he(c),we(c),T){const g={...u,...E(c),[T]:C(),_id:e};Be(r,c,Ft(c),[ce(g),e,h]),Ie(c,e,g,u),ve(c,e,void 0),Ae(c,u,g),pe(c,e,u,void 0),m?.invalidate(c,e,S(c,u,g)),fe(c,e,"update",g),a({indexKeys:S(c,u,g),key:e,op:"update",row:g,table:c}),ee(c,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:u,table:c}),await O({id:e,op:"delete",table:c});return}Be(r,c,so(c),[e,h]),Ie(c,e,void 0),ve(c,e,void 0),Ae(c,u,void 0),pe(c,e,u,void 0),m?.invalidate(c,e,S(c,u)),fe(c,e,"delete"),a({indexKeys:S(c,u),key:e,op:"delete",table:c}),ee(c,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:u,table:c}),await O({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??Yt),f=n?.hard===void 0?void 0:{hard:n.hard},h=ie(e)?void 0:e;let u=0;return await y(async()=>{for(;;){const l=(await U.findMany(e,{limit:s})).page.map(w=>String(w._id));if(l.length===0)break;for(const w of l)await U.delete(w,h,f),u+=1;if(l.length<s)break}}),{deleted:u}},async deleteMany(e,n,s){ae(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 u=(await(V(e,"deleteWhere")??U).findMany(e,{where:n})).page.map(c=>String(c._id));if(ae(u.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(u,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 Dn(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,n={}){const s=V(e,"findMany");if(s)return R(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?R(e,H):R(e);const u=nt(n.orderBy,f.shape),c=n.cursor?zt(u,ot(n.cursor)):void 0;let l=z(n.baseWhere,n.where);l=z(l,de(f.softDeleteMode,n.includeDeleted)),l=await xt(l,{canPushExists:wt?cn:void 0,existsPushMode:ht==="always"?"always":"auto",fetcher:ft,maxRelationKeys:pt,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),c&&(l=l?{AND:[l,c]}:c);const w=wt?vo(R):dt,T=ne(l,w,Pe),g=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0,b=tn(e,T,on(u),g===void 0?void 0:g+1),x=Se(r,b.text,...b.params).toArray();h&&!D&&_?.recordRead(x.length);const P=[];for(const J of x){const G=le(J);G&&(P.push(G),!h&&typeof G._id=="string"&&R(e,G._id))}if(g===void 0)return n.with&&await bt({groupedCounter:gt,fetcher:je,parents:P,...Mt(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:At(P,n.select,n.with)};const B=P.length>g,v=B?P.slice(0,g):P,Q=v.at(-1);return n.with&&await bt({fetcher:je,groupedCounter:gt,parents:v,...Mt(n),schema:t,tableName:e,with:n.with}),{continueCursor:B&&Q&&n.omitContinueCursor!==!0?rt(Q,u):null,isDone:!B,page:At(v,n.select,n.with)}},async get(e,n){const s=se(e,n);if(!s){const f=ge(n);return f?f.get(e,n):null}return R(s.tableName,e),s.row},async lookupById(e,n){const s=se(e,n);return s?(R(s.tableName,e),{row:s.row,tableName:s.tableName}):null},async groupBy(e,n){const s=V(e,"groupBy");if(s)return R(e,H),s.groupBy(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);R(e,H);const h=n.agg??{op:"count"};if(Le(h.op),h.op!=="count"&&!h.field)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const u=de(f.softDeleteMode,void 0),c=z(z(n.baseWhere,n.where),u),l=await Re(c,e,n.relationBaseWhere),w=l!==c,T=[...n.by,h.field];if(f.aggregateIndexes&&!n.baseWhere&&!w&&(!u||Wt(f,T))){const v=$n(f.aggregateIndexes,h.op,h.field,n.by,n.where),Q=v===void 0?0:Object.keys(v.partial).length,J=v?.index.by?.length??0;if(v&&(Q===0||Q===J)){Ke(e,v.index);const G=Ve(e,v.index.name),Ce=Object.keys(v.partial),xe=[];if(Ce.length===(v.index.by??[]).length&&Ce.length>0){const be=ze(v.index.by??[],v.partial),Me=N(r,i`SELECT ${ke} AS value, ${Xe} AS count FROM ${i.identifier(G)} WHERE ${Fe} = ${be}`).toArray();return Me.length>0&&xe.push({key:{...v.partial},value:Je(h.op,Me[0])}),xe}const ln=N(r,i`SELECT ${Fe} AS key, ${ke} AS value, ${Xe} AS count FROM ${i.identifier(G)}`).toArray();for(const be of ln){const Me=wn(JSON.parse(be.key));xe.push({key:Me,value:Je(h.op,be)})}return xe}}for(const v of T){if(v===void 0)continue;const Q=v===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${v}" } })`:`groupBy(${e}, { by: [..."${v}"] })`;Ut(f,v,Q)}const g=ne(l,ye),b=n.by.map(v=>i`${X(v)} AS ${i.identifier(v)}`);if(h.op==="count")b.push(i`COUNT(*) AS value`);else{const{field:v}=h;if(v===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);b.push(i`${i.raw(Le(h.op))}(${X(v)}) AS value`)}let x=i`SELECT ${i.join(b,i`, `)} FROM ${i.identifier(e)}`;g&&(x=i`${x} WHERE ${g}`),x=i`${x} GROUP BY ${i.join(n.by.map(v=>X(v)),i`, `)}`;const P=N(r,x).toArray(),B=[];for(const v of P){const Q={};for(const G of n.by)Q[G]=v[G]??null;const{value:J}=v;B.push({key:Q,value:J==null?null:Number(J)})}return B},async insert(e,n,s){const f=V(e,"insert");if(f)return ut(f,e,n,s,!0);const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const u=Gt(h,n,Z);et(h,u);let c;s?.clientId!==void 0?(ho(s.clientId),c=s.clientId):s?.allowExplicitId&&typeof u._id=="string"?c=u._id:c=M();const l=s?.allowExplicitId&&typeof u._creationTime=="number"?u._creationTime:C(),w={...u,...E(e),_creationTime:l,_id:c};return ee(e,"before","insert")&&await te("before","insert",{doc:{...w},id:c,op:"insert",table:e}),he(e),we(e),it(r,e,ro(e),[c,l,ce(w)]),yt(e,c,w),ee(e,"after","insert")&&await te("after","insert",{doc:w,id:c,op:"insert",table:e}),await O({doc:w,id:c,op:"insert",table:e}),c},async insertManyUnsafe(e,n,s){if(ae(n.length,s?.limit,"insertManyUnsafe"),n.length===0)return[];const f=V(e,"insert");if(f){const l=[];for(const w of n)W(w);for(const w of n){const T=await f.insert(e,w,{allowExplicitId:s?.allowExplicitId});a({key:T,op:"insert",row:{...w,_id:T},table:e}),l.push(T)}return l}const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);he(e),we(e);const u=[];for(let l=0;l<n.length;l+=qe)u.push(E(e));const c=n.map((l,w)=>{const T=Gt(h,l,Z),g=s?.allowExplicitId===!0&&typeof T._id=="string"?T._id:M(),b=s?.allowExplicitId===!0&&typeof T._creationTime=="number"?T._creationTime:C(),x={...T,...u[Math.floor(w/qe)],_creationTime:b,_id:g};return{creationTime:b,document:x,id:g}});for(const l of c)W(l.document);for(let l=0;l<c.length;l+=qe){const w=i.join(c.slice(l,l+qe).map(g=>i`(${g.id}, ${g.creationTime}, ${ce(g.document)})`),i`, `),T=Qt("sqlite",i`INSERT INTO ${i.identifier(e)} (id, _creationTime, ${i.identifier(oe)}) VALUES ${w}`);it(r,e,T.sql,T.params)}for(const{document:l,id:w}of c)yt(e,w,l),await q({doc:l,id:w,op:"insert",table:e});return c.map(l=>l.id)},async insertMany(e,n,s){ae(n.length,s?.limit,"insertMany");const f=s?.skipDuplicates===!0,h=[],u=V(e,"insert");if(u)for(const l of n)W(l);const c=async l=>u?ut(u,e,l,void 0,!1):U.insert(e,l);for(const l of n)try{h.push(await c(l))}catch(w){if(f&&w instanceof Ee&&w.kind==="unique")h.push(null);else throw w}return h},normalizeId(e,n){return Pt(t,e,n)},async patch(e,n,s){const f=se(e,s);if(!f){const T=ge(s);if(T){W(n),await T.patch(e,n,s);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:u,tableName:c}=f,l=t.tables[c];if(!l)throw new $("INTERNAL",`unknown table: ${c}`);R(c,e),Ot("patch",n);const w={...u,...n,...E(c),_id:e};Ht(l,n,w,Z),et(l,w,!0),ee(c,"before","update")&&await te("before","update",{doc:{...w},id:e,op:"update",previous:u,table:c}),he(c),we(c),Be(r,c,Ft(c),[ce(w),e,h]),Ie(c,e,w,u),ve(c,e,w),Ae(c,u,w),pe(c,e,u,w),m?.invalidate(c,e,S(c,u,w)),fe(c,e,"update",w),a({indexKeys:S(c,u,w),key:e,op:"update",row:w,table:c}),ee(c,"after","update")&&await te("after","update",{doc:w,id:e,op:"update",previous:u,table:c}),await O({doc:w,id:e,op:"update",table:c})},async patchMany(e,n,s){ae(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 u=(await(V(e,"patchWhere")??U).findMany(e,{where:n.where})).page.map(c=>({id:String(c._id),patch:n.patch}));if(ae(u.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(u,s),{patched:u.length}},query(e){const n=V(e,"query");return n?(R(e,H),n.query(e)):qo(r,t,e,k,s=>{s?j(s):R(e,H)},s=>{D||_?.recordRead(s)})},async rank(e,n,s){const f=V(e,"rank");if(f)return R(e,H),f.rank(e,n,s);k(e,n,"rank");const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const u=h.rankIndexes?.find(G=>G.name===n);if(!u)throw new $("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(Et(e,h,u),s.restrictsCounts)throw new Ye(e);R(e,H),Qe(e,u);const c=typeof s.row=="string"?s.row:s.row._id;if(!c)return null;const l=vt(e,u.name),w=u.sortBy.map((G,Ce)=>It(Ce)),T=w.map(G=>_e(G)).join(", "),g=N(r,i`SELECT ${i.identifier("__partition__")}, ${i.raw(T)} FROM ${i.identifier(l)} WHERE ${i.identifier("__id__")} = ${c}`).toArray(),[b]=g;if(b===void 0)return null;let x=b.__partition__;const P=z(s.baseWhere,s.where);Ze(P,t,e,"rank");const B=kn(u,P);if(B){const G=Fn(u.partitionBy??[],B);if(G!==x)return null;x=G}const v=w.map(G=>b[G]),{before:Q,total:J}=Nt(r,l,w,u.sortBy,x,v,c);return{position:Q+1,total:J}},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 Ye(e);R(e,H),Qe(e,h);const u=vt(e,h.name),c=h.sortBy.map((w,T)=>It(T)),l=h.sortBy.map((w,T)=>re(s.sortValues[T]??null));return Nt(r,u,c,h.sortBy,s.partitionKey,l,s.rowId)},async rankPage(e,n,s={}){Ze(z(s.baseWhere,s.where),t,e,"rankPage");const f=V(e,"rankPage");if(f)return R(e,H),f.rankPage(e,n,s);k(e,n,"rank");const{continueCursor:h,hasMore:u,rows:c}=Rt(St,e,n,s);return{continueCursor:h,isDone:!u,page:c.map(l=>l.doc)}},async rankPageRows(e,n,s={}){Ze(z(s.baseWhere,s.where),t,e,"rankPage"),k(e,n,"rank");const{directions:f,hasMore:h,rows:u}=Rt(St,e,n,s);return{directions:f,hasMore:h,rows:u}},async restore(e,n){const s=se(e,n);if(!s){const u=ge(n);if(u?.restore){await u.restore(e,n);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=se(e,s);if(!h){const b=ge(s);if(b){W(n),await b.replace(e,n,s,f);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:u,row:c,tableName:l}=h,w=t.tables[l];if(!w)throw new $("INTERNAL",`unknown table: ${l}`);Ot("replace",n);const T=f?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:C(),g={...n,...E(l),_creationTime:T,_id:e};Ht(w,n,g,Z),et(w,g),ee(l,"before","update")&&await te("before","update",{doc:{...g},id:e,op:"update",previous:c,table:l}),he(l),we(l),Be(r,l,io(l),[T,ce(g),e,u]),Ie(l,e,g,c),ve(l,e,g),Ae(l,c,g),pe(l,e,c,g),m?.invalidate(l,e,S(l,c,g)),fe(l,e,"update",g),a({indexKeys:S(l,c,g),key:e,op:"update",row:g,table:l}),ee(l,"after","update")&&await te("after","update",{doc:g,id:e,op:"update",previous:c,table:l}),await O({doc:g,id:e,op:"update",table:l})},async wipeShard(e){const n=new Set(e?.exclude),s=e?.tables,f=Object.entries(t.tables).filter(([l,w])=>n.has(l)||s!==void 0&&!s.includes(l)?!1:w.shardMode?.kind!=="global").map(([l])=>l);if(s!==void 0){for(const l of s)if(!t.tables[l])throw new $("INTERNAL",`wipeShard: unknown table: ${l}`)}const h={};let u=0;const{deleteAll:c}=U;if(c===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of f){const w=await c(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[l]=w.deleted,u+=w.deleted}return{deleted:u,tables:h}}},dn={db:U,scheduler:L};return o.enforceRls===!0?Hn(U,t,(e,n)=>se(e,n)?.tableName,(e,n)=>an(e,n)):U};export{Ir as CDC_LOG_TABLE,Nr as CLIENT_WATERMARK_TABLE,zr as GLOBAL_SHAPE_SNAPSHOT_TABLE,ni as IDEMPOTENCY_TABLE,Lo as NotUniqueError,di as SEARCH_STATE_TABLE,jr as advanceClientWatermark,Cr as applyCdcChanges,Ot as assertNoExplicitUndefined,ho as assertValidClientId,Rr as backfillAggregateIndexes,Tr as backfillRankIndexes,Ar as backfillSearchIndexes,xr as bumpCdcEpoch,br as cdcCanVouchFor,Mr as cdcSeqLeavingRows,Dr as cdcTouchesTables,Lr as cdcTrimmedError,kr as compactCdcDocs,mr as createShardCtxDb,Fr as cursorBelowRetainedFloor,Jr as deleteGlobalShapeSnapshot,Yr as deleteGlobalShapeSnapshotsForConnection,Kr as migrateClientWatermark,Xr as migrateGlobalShapeSnapshot,qr as minCdcReplayableSeq,Br as minCdcSeq,Pt as normalizeIdStructurally,Wr as readCdcChangeKeys,Ur as readCdcChanges,Pr as readCdcCursor,Gr as readCdcEpoch,Qr as readClientWatermark,Zr as readGlobalShapeSnapshot,oi as readIdempotent,ci as runShardMigrations,ui as selectShapeMembers,fi as selectShapeRows,Hr as trimCdcChanges,ri as trimIdempotent,ei as writeGlobalShapeSnapshot,ii as writeIdempotent};
@@ -1 +0,0 @@
1
- import{LunoraError as f}from"@lunora/errors";const w=Symbol.for("lunora.ctxdb.rls-unwrap");class R extends f{table;constructor(n){super("RLS_REQUIRED",`ctx.db access to "${n}" is denied: the schema is marked .rls("required"), so this table is protected. Apply RLS with .use(rls(policies)) in the procedure, or mark the table .public() to opt it out.`,{name:"RlsRequiredError"}),this.table=n}}const M=o=>Object.entries(o.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n),S=(o,n,u)=>{const l=n?.tables,a=new Set(n?.exclude);for(const c of o)(l===void 0||l.includes(c))&&!a.has(c)&&u(c)},m={aggregate:"loop-gated",asId:"ungated",cdcChangedTables:"ungated",count:"loop-gated",delete:"id-gated",deleteAll:"loop-gated",deleteMany:"id-gated",deleteWhere:"inline-table-gated",findFirst:"loop-gated",findFirstOrThrow:"loop-gated",findMany:"loop-gated",get:"id-gated",groupBy:"loop-gated",insert:"loop-gated",insertMany:"loop-gated",insertManyUnsafe:"loop-gated",lookupById:"id-gated",normalizeId:"ungated",patch:"id-gated",patchMany:"id-gated",patchWhere:"inline-table-gated",query:"loop-gated",rank:"loop-gated",rankBefore:"loop-gated",rankPage:"loop-gated",rankPageRows:"loop-gated",replace:"id-gated",restore:"id-gated",system:"ungated",wipeShard:"sweep-gated"},W=Object.entries(m).filter(([,o])=>o==="loop-gated").map(([o])=>o),v=(o,n,u,l)=>{if(n.rlsMode!=="required")return o;const a=o,c=e=>{const t=n.tables[e];return t!==void 0&&t.isPublic!==!0},d=e=>{if(c(e))throw new R(e)},i=async(e,t)=>{if(t!==void 0){d(t);return}const r=await u(e);r!==void 0&&d(r)},p=async(e,t)=>{if(t!==void 0){d(t);return}if(!l){for(const s of e)await i(s,t);return}const r=await l([...new Set(e)],t);for(const s of e){const h=r.get(s);h!==void 0&&d(h)}},g={...o,[w]:o,delete:async(e,t,r)=>(await i(e,t),a.delete(e,t,r)),deleteMany:async(e,t,r)=>(await p(e,r),a.deleteMany(e,t,r)),deleteWhere:a.deleteWhere?async(e,t,r)=>(d(e),await a.deleteWhere?.(e,t,r)):void 0,get:async(e,t)=>(await i(e,t),a.get(e,t)),lookupById:async(e,t)=>(await i(e,t),a.lookupById?.(e,t)??null),patch:async(e,t,r)=>(await i(e,r),a.patch(e,t,r)),patchMany:async(e,t,r)=>(await p(e.map(s=>s.id),r),a.patchMany(e,t,r)),patchWhere:a.patchWhere?async(e,t,r)=>(d(e),await a.patchWhere?.(e,t,r)):void 0,replace:async(e,t,r,s)=>(await i(e,r),a.replace(e,t,r,s)),restore:async(e,t)=>(await i(e,t),a.restore?.(e,t))},y=a;for(const e of W){const t=y[e];typeof t=="function"&&(g[e]=(r,...s)=>(d(r),t.call(a,r,...s)))}if(a.wipeShard){const{wipeShard:e}=a;g.wipeShard=t=>(S(M(n),t,d),e.call(a,t))}return g};export{W as LOOP_GATED_METHODS,w as RLS_UNWRAP_SYMBOL,R as RlsRequiredError,m as WRITER_METHOD_GATING,v as guardWriter};
@@ -1 +0,0 @@
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 d}from"./wire-codec-C-FpWm52.mjs";import{runSql as p}from"./runDrizzle-2ULFQR_k.mjs";import{k as m,D as E}from"./do-sql-FNOnpyHm.mjs";import{mayHoldProjectedValue as g}from"./BIGINT_KEY_DIGITS-GvEBhyR5.mjs";const b=d(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{m(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 +0,0 @@
1
- import{c as l,i as C,r as R}from"./ctx-db-companions-B4O4d95S.mjs";import"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import"./aggregateTableName-C7o-gpms.mjs";import"./runDrizzle-2ULFQR_k.mjs";import"./do-sql-FNOnpyHm.mjs";import"./param-DlozcSQu.mjs";import"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import"./CURSOR_PREFIX-qn6nNVS7.mjs";import"./RANK_TIEBREAK-CkNuGm6a.mjs";import"./BIGINT_KEY_DIGITS-GvEBhyR5.mjs";import"./serializeSqlValue-B_-zaEWZ.mjs";export{l as createCompanionSync,C as insertRankRow,R as rankColumnsSql};
@@ -1 +0,0 @@
1
- import{D as ie}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as P,aggregateSqlFunction as ce}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as z,encodeAggregateKey as v,foldAggregateTally as J,coerceAggregateNumber as b}from"./aggregateTableName-C7o-gpms.mjs";import{runDrizzle as u}from"./runDrizzle-2ULFQR_k.mjs";import{i as fe,g as ae,D as M,r as q,a as L,b as h,A as p,c as D,e as U}from"./do-sql-FNOnpyHm.mjs";import{param as le,WORKERD_SQLITE_LIMITS as $e}from"./param-DlozcSQu.mjs";import{encodeGeohash as de,GEO_DEFAULT_PRECISION as ue}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as N}from"./CURSOR_PREFIX-qn6nNVS7.mjs";import{encodePartitionKey as Ee,sortColumnName as _e,rankTableName as X,matchesRankStaticWhere as Y}from"./RANK_TIEBREAK-CkNuGm6a.mjs";import{mayHoldProjectedValue as ye}from"./BIGINT_KEY_DIGITS-GvEBhyR5.mjs";import{serializeSqlValue as Z}from"./serializeSqlValue-B_-zaEWZ.mjs";const ge=(t,i)=>{if(!i.includes("."))return t[i];let f=t;for(const A of i.split(".")){if(f===null||typeof f!="object"||Array.isArray(f))return;f=f[A]}return f},pe=(t,i)=>`${t}__fts_${i}`,me="__text__",Q="__id__",he=1e3,Se=(t,i)=>i.document(t),W=(t,i)=>ge(t,i),Te=t=>typeof t=="string"?t:t==null?"":typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"?String(t):JSON.stringify(t)??"",Re=(t,i,f)=>t!==void 0&&i!==void 0&&W(t,f.field)===W(i,f.field),Ae=(t,i)=>Se(Te(W(t,i.field)),ie(i.language)).slice(0,he),we=(t,i)=>Ae(t,i).join(" "),Fe=(t,i,f)=>[...t.partitionBy??[],...t.sortBy.map(S=>S.field),...t.where?Object.keys(t.where):[]].every(S=>i[S]===f[S]),x=t=>e.join(["__id__","__partition__",...t.sortBy.map((i,f)=>_e(f))].map(i=>e.identifier(i)),e`, `),ee=(t,i,f,A,S,y)=>{const c=Ee(f.partitionBy??[],y),C=f.sortBy.map(I=>Z(y[I.field]??null)),k=e.join([S,c,...C].map(I=>le(I)),e`, `);u(t,e`INSERT INTO ${e.identifier(i)} (${A}) VALUES (${k})`)},Oe=(t,i,f,A,S,y)=>{if(S&&y&&Fe(f,S,y))return;const c=X(i,f.name);S&&u(t,e`DELETE FROM ${e.identifier(c)} WHERE ${e.identifier("__id__")} = ${A}`),!(!y||f.where&&!Y(y,f.where))&&ee(t,c,f,x(f),A,y)},Be=t=>{const{broadcast:i,indexKeysFor:f,invalidateCache:A,recordCdc:S,schema:y,sql:c}=t,C=new Set,k=n=>y.tables[n]?.softDeleteMode?.field,I=new Set,j=(n,o)=>{const s=`${n}::${o.name}`;if(C.has(s))return;const l=z(n,o.name),$=o.by??[],d=k(n),_=new Map,m=u(c,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(n)}`).toArray();for(const T of m){const E=q(T);if(!E||!N(E,d)||o.where&&!P(E,o.where))continue;const R=v($,E);J(_,R,o,E)}u(c,e`DELETE FROM ${e.identifier(l)}`);const w=Math.floor($e.boundParams/3),F=[..._];for(let T=0;T<F.length;T+=w){const E=F.slice(T,T+w),R=e.join(E.map(([r,a])=>e`(${r}, ${a.value}, ${a.count})`),e`, `);u(c,e`INSERT INTO ${e.identifier(l)} (${L}, ${h}, ${p}) VALUES ${R}`)}C.add(s)},oe=(n,o,s)=>{const l=o.by??[],$=o.field??"",d=[],_=(r,a)=>{const g=Z(a);g===null?d.push(e`${U(r)} IS NULL`):d.push(e`${U(r)} = ${g}`)};for(const r of l)_(r,s[r]??null);const m=k(n);m!==void 0&&_(m,null);for(const[r,a]of Object.entries(o.where??{}))_(r,a!==null&&typeof a=="object"&&!Array.isArray(a)?a.eq:a);const w=d.length>0?e` WHERE ${e.join(d,e` AND `)}`:e``,F=y.tables[n]?.shape[$];if(F&&ye(F)){const r=u(c,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(n)}${w}`).toArray(),a=new Map;for(const g of r){const O=q(g);O&&J(a,"",o,O)}return{value:a.get("")?.value??null}}const T=ce(o.op),E=U($);return{value:u(c,e`SELECT ${e.raw(T)}(${E}) AS value FROM ${e.identifier(n)}${w}`).one().value??null}},ne=(n,o,s,l)=>{const $=z(n,o.name),{op:d}=o,_=o.field??"",m=r=>{u(c,e`DELETE FROM ${e.identifier($)} WHERE ${L} = ${r} AND ${p} <= 0`)},w=k(n),F=r=>!o.where||P(r,o.where),T=r=>N(r,w)&&F(r);l!==void 0&&d!=="count"&&F(l)&&b(l[_]);const E=s&&T(s)?s:void 0,R=l&&T(l)?l:void 0;if(!(!E&&!R)){if(d==="count"){for(const[r,a]of[[E,-1],[R,1]]){if(!r)continue;const g=v(o.by??[],r);u(c,D($,g,a,a,e`${h} = ${h} + excluded.${h}, ${p} = ${p} + excluded.${p}`))}E&&m(v(o.by??[],E));return}if(d==="sum"||d==="avg"){for(const[r,a]of[[E,-1],[R,1]]){if(!r)continue;const g=b(r[_]);if(g===void 0)continue;const O=v(o.by??[],r);u(c,D($,O,a*g,a,e`${h} = COALESCE(${h}, 0) + excluded.${h}, ${p} = ${p} + excluded.${p}`))}E&&m(v(o.by??[],E));return}if(E){const r=v(o.by??[],E),a=b(E[_]),g=u(c,e`SELECT ${h} AS value, ${p} AS count FROM ${e.identifier($)} WHERE ${L} = ${r}`).toArray()[0],O=(g?.count??0)-1;if(O<=0)u(c,e`DELETE FROM ${e.identifier($)} WHERE ${L} = ${r}`);else if(g&&a!==void 0&&g.value!==null&&a===g.value){const se=oe(n,o,E);u(c,e`UPDATE ${e.identifier($)} SET ${h} = ${se.value}, ${p} = ${O} WHERE ${L} = ${r}`)}else u(c,e`UPDATE ${e.identifier($)} SET ${p} = ${p} - 1 WHERE ${L} = ${r}`)}if(R){const r=v(o.by??[],R),a=b(R[_]);if(a===void 0)u(c,D($,r,null,1,e`${p} = ${p} + 1`));else{const g=d==="min"?"MIN":"MAX";u(c,D($,r,a,1,e`${h} = ${e.raw(g)}(COALESCE(${h}, excluded.${h}), excluded.${h}), ${p} = ${p} + 1`))}}}},te=n=>{for(const o of y.tables[n]?.aggregateIndexes??[])j(n,o)},H=(n,o,s)=>{for(const l of y.tables[n]?.aggregateIndexes??[])ne(n,l,o,s)},B=(n,o)=>{const s=`${n}::rank::${o.name}`;if(I.has(s))return;const l=X(n,o.name),$=u(c,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(n)}`).toArray();u(c,e`DELETE FROM ${e.identifier(l)}`);const d=x(o);for(const _ of $){const m=q(_);!m||o.where&&!Y(m,o.where)||ee(c,l,o,d,m._id,m)}I.add(s)},re=n=>{for(const o of y.tables[n]?.rankIndexes??[])B(n,o)},K=(n,o,s,l)=>{for(const $ of y.tables[n]?.rankIndexes??[])Oe(c,n,$,o,s,l)},V=(n,o,s,l)=>{const $=y.tables[n]?.searchIndexes??[];if(!($.length===0||!fe(c)))for(const d of $){if(Re(l,s,d))continue;const _=pe(n,d.name);u(c,e`DELETE FROM ${e.identifier(_)} WHERE ${e.identifier(Q)} = ${o}`),s&&u(c,e`INSERT INTO ${e.identifier(_)} (${e.identifier(me)}, ${e.identifier(Q)}) VALUES (${we(s,d)}, ${o})`)}},G=(n,o,s)=>{for(const l of y.tables[n]?.geoIndexes??[]){const $=ae(n,l.name);u(c,e`DELETE FROM ${e.identifier($)} WHERE ${e.identifier("__id__")} = ${o}`);const d=s?.[l.field];if(d!==null&&typeof d=="object"&&typeof d.lat=="number"&&typeof d.lng=="number"){const{lat:_,lng:m}=d,w=de({lat:_,lng:m},l.precision??ue);u(c,e`INSERT INTO ${e.identifier($)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${o}, ${w}, ${_}, ${m})`)}}};return{ensureBackfilledForTable:te,ensureBackfilledIndex:j,ensureRankBackfilled:B,ensureRankBackfilledForTable:re,syncAggregates:H,syncCompanionsForInsert:(n,o,s)=>{V(n,o,s),G(n,o,s),H(n,void 0,s),K(n,o,void 0,s),A(n,o,s),S(n,o,"insert",s),i({indexKeys:f(n,s),key:o,op:"insert",row:s,table:n})},syncGeo:G,syncRanks:K,syncSearch:V}};export{pe as S,Ae as a,Be as c,we as d,ee as i,Q as l,x as r,me as y};
@@ -1 +0,0 @@
1
- import{createShardCtxDb as v}from"./NotUniqueError-CTSwCMsP.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-C3L_1GLp.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as _}from"./runShardMigrations-CkG92fSl.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";const E=(C,m={})=>({_meta:{column:{notNull:!0,...m}},kind:C}),W=(C,m,O)=>{const{describe:S,expect:n,it:y}=O;S(`engine contract: ${C}`,()=>{S("optimistic concurrency",()=>{const b=u=>({tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});y("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await n(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(N)}finally{u?.()}}),y("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e.code).toBe("CONFLICT"),n(e.kind).toBe("occ")}finally{u?.()}}),y("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const o=await s.get("i1");n(o?.title).toBe("first"),n(o?.version).toBe(99)}finally{u?.()}}),y("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l={tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,a)=>{await t.db.patch(a.doc._id,{version:99})},op:"update",timing:"before"}}}}};_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e).toBeInstanceOf(N),n(e.code).toBe("CONFLICT"),n(e.kind).toBe("trigger")}finally{u?.()}})}),S("shape-poke ordering",()=>{const b="shard-a",u={args:{},name:"messages"},h=(e,t,a,r)=>e.accept(t?.()??{},{connectionId:a,shapes:{[r]:u}}),i=(e,t,a)=>{let r=0,d=0;const c=g=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${g}`)},p={fetch:(g,q)=>{if(JSON.parse(q?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const B=a[d];if(d+=1,B===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(B))}},k={get:()=>p,getByName:()=>p,idFromName:g=>g},w={buildShapeDiff:c("buildShapeDiff"),computeOpLogShapeSeed:c("computeOpLogShapeSeed"),currentCdcEpoch:c("currentCdcEpoch"),deliverWhisperLocal:c("deliverWhisperLocal"),doName:()=>F(b,0),env:()=>({SHARD:k}),getWebSockets:()=>e.getSockets(),maskMetadata:c("maskMetadata"),nextPokeId:()=>(r+=1,`poke-${String(r)}`),readAttachment:g=>g.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:c("resolveShape"),rlsMetadata:c("rlsMetadata"),shardBinding:()=>"SHARD",sql:()=>t},f=I(w);if(f===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return f},l=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,a)=>{const r=await e.seedRelayShape(t,a,u,{identity:void 0,userId:void 0});if(r!=="ok")throw new Error(`seed failed: ${JSON.stringify(r)}`)},o=(e={})=>l({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});y("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o());const w=(await r(p)).map(f=>JSON.parse(f));n(w.map(f=>f.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),n(new Set(w.map(f=>f.pokeId)).size).toBe(1),n(w[1]?.shapeId).toBe("s1"),n(w[2]?.checkpoint).toBe(20)}finally{e?.()}}),y("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1"),k=h(d,t,"c-bob","s2");await s(c,p,"s1"),await s(c,k,"s2"),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3);const f=await r(k);n(f.length).toBe(0),await c.handleControl(o());const g=await r(p);n(g.length).toBe(3)}finally{e?.()}}),y("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o({epoch:"e2"}));const k=await r(p);n(k.length).toBe(0),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3)}finally{e?.()}})}),S("RLS identity under live subscription",()=>{const b="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},i=s=>{const o=[],e=[],t={fetch:(d,c)=>(o.push(JSON.parse(c?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},r=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>b,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:d=>d}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(d,c,p)=>(e.push(p),d===h.name?{columns:["id"],effectiveWhere:{org:p?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",sql:()=>s});if(r===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:r,posts:o,resolvedUnder:e}},l=async(s,o)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...o,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};y("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:o}=m();try{const{owner:e,resolvedUnder:t}=i(o.sql);await l(e,h),n(t.some(a=>a?.userId==="u1"&&a.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),y("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),y("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{W as defineEngineContractSuite};
@@ -1 +0,0 @@
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-C-FpWm52.mjs";import{runDrizzle as l}from"./runDrizzle-2ULFQR_k.mjs";import{sqlComparableProjection as S}from"./BIGINT_KEY_DIGITS-GvEBhyR5.mjs";import"./serializeSqlValue-B_-zaEWZ.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 +0,0 @@
1
- import{BIGINT_KEY_DIGITS as c}from"./BIGINT_KEY_DIGITS-GvEBhyR5.mjs";const n=40,s=i=>{let e=0;const o=(r,t)=>typeof t=="bigint"?(e+=c+1+n,t.toString()):t instanceof ArrayBuffer||ArrayBuffer.isView(t)?(e+=2*Math.ceil(t.byteLength/3)*4+n,""):t;try{const r=JSON.stringify(i,o);return(r===void 0?0:r.length)+e}catch{return}};export{s as e};
@@ -1 +0,0 @@
1
- import{sqlComparableProjection as o}from"./BIGINT_KEY_DIGITS-GvEBhyR5.mjs";const n=r=>typeof r=="boolean"?r?1:0:r===null||typeof r=="string"||typeof r=="number"?r:o(r)??JSON.stringify(r);export{n as serializeSqlValue};
@@ -1 +0,0 @@
1
- const a=(n,t)=>{const o=Math.max(n.length,t.length);let e=n.length^t.length;for(let r=0;r<o;r+=1){const i=r<n.length?n.charCodeAt(r):0,s=r<t.length?t.charCodeAt(r):0;e|=i^s}return e===0},c="LUNORA_RELAY_SECRET",u="x-lunora-relay-sig",l=n=>{const t=n?.[c];return typeof t=="string"&&t.length>0?t:void 0},g=async(n,t)=>{const o=new TextEncoder,e=await crypto.subtle.importKey("raw",o.encode(n),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),r=await crypto.subtle.sign("HMAC",e,o.encode(t));return[...new Uint8Array(r)].map(i=>i.toString(16).padStart(2,"0")).join("")},f=async(n,t,o)=>{const e=l(n);return e===void 0?!0:t===null?!1:a(t,await g(e,o))},d=n=>{if(n===null||typeof n!="object")return;const t=n;return typeof t.idFromName=="function"&&typeof t.get=="function"?t:void 0},y=(n,t,o)=>{if(t===void 0)return;const e=d(n?.[t]);if(e!==void 0)return typeof e.getByName=="function"?e.getByName(o):e.get(e.idFromName(o))};export{u as R,l as a,g as b,y as s,f as v};
@@ -1 +0,0 @@
1
- import{LunoraError as T}from"@lunora/errors";import{sql as l}from"drizzle-orm";import{sqliteInList as A,isJsonSafe as $,WORKERD_SQLITE_LIMITS as O}from"./param-DlozcSQu.mjs";import{quoteIdentifier as m}from"./quoteIdentifier-CObIFRhb.mjs";import{RELATION_EXISTS_KEY as L}from"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";const R={binary:(n,t,o)=>l`${n} ${l.raw(t)} ${o}`,constant:n=>n?l`1 = 1`:l`0 = 1`,connect:(n,t,o)=>l`(${n}) ${l.raw(o)} (${t})`,contains:(n,t)=>l`instr(lower(${n}), lower(${t})) > 0`,inList:(n,t,o,i)=>A(n,t,o,i),negate:n=>l`NOT (${n})`,nullCheck:(n,t)=>t?l`${n} IS NOT NULL`:l`${n} IS NULL`,value:n=>l`${n}`},p=(...n)=>{let t="";const o=[];for(const i of n)typeof i=="string"?t+=i:(t+=i.text,o.push(...i.params));return{params:o,text:t}},f=n=>({params:[n],text:"?"}),I=n=>({params:[],text:n}),Y=n=>I(m(n)),Q={binary:(n,t,o)=>p(n," ".concat(t," "),f(o)),constant:n=>I(n?"1 = 1":"0 = 1"),connect:(n,t,o)=>p("(",n,") ".concat(o," ("),t,")"),contains:(n,t)=>p("instr(lower(",n,"), lower(",t,")) > 0"),inList:(n,t,o,i)=>{const s=o?" NOT IN ":" IN ";if(t.length>i&&!t.every(r=>$(r)))throw new T("BAD_REQUEST",`an "in" list of ${String(t.length)} values holds a value JSON cannot carry (bytes, a non-finite number, or malformed text), so it cannot be bound as one parameter — and ${String(t.length)} placeholders exceed SQLite's per-statement cap of 100 on Durable Objects and D1. Narrow the list to ${String(i)} values or fewer.`);if(t.length<=i){const r=[n,s,"("];for(const[c,e]of t.entries())c>0&&r.push(", "),r.push(f(e));return r.push(")"),p(...r)}return p(n,s,'(SELECT "value" FROM json_each(',f(JSON.stringify(t)),"))")},negate:n=>p("NOT (",n,")"),nullCheck:(n,t)=>p(n,t?" IS NOT NULL":" IS NULL"),value:f},x=O.boundParams/2,S=["eq","ne","lt","lte","gt","gte","in","notIn","isNull","contains"],_=new Set(S),j={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},E=n=>{if(n===null||typeof n!="object"||Array.isArray(n))return!1;const t=Object.keys(n);return t.length>0&&t.every(o=>_.has(o))},w=(n,t,o,i)=>{const s=i.value(o.serialize(t));return o.containsExpr?o.containsExpr(n,s):i.contains(n,s)},y=(n,t,o,i,s,r)=>i===null?t==="eq"||t==="ne"?r.nullCheck(n,t==="ne"):r.constant(!1):r.binary(n,o,s.serialize(i)),C=(n,t,o,i,s,r)=>{if(!Array.isArray(i))throw new T("BAD_REQUEST",`\`${o==="IN"?"in":"notIn"}\` on "${n}" expects an array of values, received ${i===null?"null":typeof i}`);const c=i;if(c.length===0)return r.constant(o==="NOT IN");const e=c.map(u=>s.serialize(u)),a=o==="NOT IN";return s.inList?s.inList(t,e,a):r.inList(t,e,a,x)},G=(n,t,o)=>{const i=l.join(t.map(s=>l`${s}`),l`, `);return o?l`${n} NOT IN (${i})`:l`${n} IN (${i})`},D=(n,t,o,i,s)=>{const r=o,c=[];for(const e of S){if(!(e in r))continue;const a=r[e],u=j[e];u?c.push(y(t,e,u,a,i,s)):e==="isNull"?c.push(s.nullCheck(t,!a)):e==="contains"?c.push(w(t,a,i,s)):c.push(C(n,t,e==="in"?"IN":"NOT IN",a,i,s))}return c},U=(n,t,o,i)=>{const s=o.fieldRef(n);return E(t)?D(n,s,t,o,i):t===null?[i.nullCheck(s,!1)]:[i.binary(s,"=",o.serialize(t))]},h=(n,t,o)=>{if(n.length<=1)return n[0];const i=Math.floor(n.length/2);return o.connect(h(n.slice(0,i),t,o),h(n.slice(i),t,o),t)},k=(n,t,o,i)=>{const s=Array.isArray(n)?n:[],r=[];for(const c of s){const e=N(c??{},o,i);e!==void 0&&r.push(e)}return r.length===0?t==="OR"?i.constant(!1):void 0:h(r,t,i)},M=new Set(["AND","NOT","OR",L]),P=(n,t,o,i)=>{if(n===L){if(!o.relationExists)throw new T("INTERNAL","encountered a relation EXISTS marker without a relationExists strategy hook");return o.relationExists(t)}if(n==="NOT"){const s=N(t??{},o,i);return s===void 0?void 0:i.negate(s)}return k(t,n,o,i)},N=(n,t,o)=>{const i=[];for(const[s,r]of Object.entries(n))if(M.has(s)){const c=P(s,r,t,o);c!==void 0&&i.push(c)}else i.push(...U(s,r,t,o));return h(i,"AND",o)},q=O.boundParams/2,d=n=>{let t=0,o=0;const i=s=>{const r=d(s);t+=r.lists,o+=r.scalars};if(Array.isArray(n)){for(const s of n)i(s);return{lists:t,scalars:o}}if(n===null||typeof n!="object")return{lists:t,scalars:o};for(const[s,r]of Object.entries(n))s==="in"||s==="notIn"?t+=1:s==="AND"||s==="NOT"||s==="OR"||E(r)?i(r):o+=1;return{lists:t,scalars:o}},J=(n,t,o=R)=>{if(!n||Object.keys(n).length===0)return;const{lists:i,scalars:s}=d(n);if(i===0)return N(n,t,o);const r=Math.max(1,Math.floor(Math.min(q,O.boundParams-s)/i)),c=t.inList??((e,a,u,b)=>o.inList(e,a,u,b??r));return N(n,{...t,inList:(e,a,u)=>c(e,a,u,r)},o)};export{J as c,Y as i,p as j,G as l,I as r,Q as t};