@lunora/shard-engine 1.0.0-alpha.129 → 1.0.0-alpha.130
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/conformance/index.mjs +1 -1
- package/dist/index.d.mts +2 -3
- package/dist/index.d.ts +2 -3
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/ADMIN_FUNCTIONS-B0QCN3HM.mjs +1 -0
- package/dist/packem_shared/{AGGREGATE_SQL_FUNCTION-BMtvQHac.mjs → AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs} +1 -1
- package/dist/packem_shared/AGG_COUNT-CBe5drFS.mjs +1 -0
- package/dist/packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs +1 -0
- package/dist/packem_shared/{CDC_LOG_TABLE-CvInVdXu.mjs → CDC_LOG_TABLE-DsCz-DAV.mjs} +1 -1
- package/dist/packem_shared/CURSOR_PREFIX-6offuG6M.mjs +1 -0
- package/dist/packem_shared/{DATA_MIGRATION_STATE_TABLE-CGF7qQsu.mjs → DATA_MIGRATION_STATE_TABLE-CmsAKy5V.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_MAX_RELATION_KEYS-COmk7y1x.mjs → DEFAULT_MAX_RELATION_KEYS-BYfAkNAH.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_MAX_RELAYS-DSIYUnPB.mjs → DEFAULT_MAX_RELAYS-ZRhh4qpX.mjs} +2 -2
- package/dist/packem_shared/DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs +1 -0
- package/dist/packem_shared/{DEFAULT_TRANSACTION_LIMITS-DiR5z5EX.mjs → DEFAULT_TRANSACTION_LIMITS-Dmj5VBrV.mjs} +1 -1
- package/dist/packem_shared/DurableStreamRunner-Dzge_ywD.mjs +1 -0
- package/dist/packem_shared/NotUniqueError-CApXRyGS.mjs +1 -0
- package/dist/packem_shared/{RANK_TIEBREAK-BKugKf70.mjs → RANK_TIEBREAK-D3ye2GsL.mjs} +1 -1
- package/dist/packem_shared/{RELATED_DEFAULT_LIMIT-Me5elP-K.mjs → RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs} +1 -1
- package/dist/packem_shared/{RLS_UNWRAP_SYMBOL-BV39QRFd.mjs → RLS_UNWRAP_SYMBOL-DQt9luIF.mjs} +1 -1
- package/dist/packem_shared/ReactiveCache-DHhhLJtN.mjs +1 -0
- package/dist/packem_shared/ShapeDiffCache-iNO-hUiy.mjs +1 -0
- package/dist/packem_shared/{VECTOR_BACKFILL_MAX_PAGES-CIi7v65O.mjs → VECTOR_BACKFILL_MAX_PAGES-DY_3FYts.mjs} +1 -1
- package/dist/packem_shared/aggregateTableName-B_CtIQCS.mjs +1 -0
- package/dist/packem_shared/{applyOnDelete-CGVYKtaW.mjs → applyOnDelete-BwxDC4lU.mjs} +1 -1
- package/dist/packem_shared/assertPatchAllowed-CA_H466g.mjs +1 -0
- package/dist/packem_shared/awaitWsDrain-N-oR29RI.mjs +1 -0
- package/dist/packem_shared/{backfillAggregateIndexes-DBrKU3Ya.mjs → backfillAggregateIndexes-Dw4Azd33.mjs} +1 -1
- package/dist/packem_shared/{buildIndexRange-6nIZDf4m.mjs → buildIndexRange-DQ3eWAGd.mjs} +1 -1
- package/dist/packem_shared/buildPokeFrames-WR-hp0mX.mjs +1 -0
- package/dist/packem_shared/buildReprojectionMigration-DQV0q3w9.mjs +1 -0
- package/dist/packem_shared/{buildShapeDiff-CdT2gjFd.mjs → buildShapeDiff-BHr3i1m6.mjs} +1 -1
- package/dist/packem_shared/{clearCompanionSignatures-Qf67j6dd.mjs → clearCompanionSignatures-8uVX84aT.mjs} +1 -1
- package/dist/packem_shared/compileWhereSql-CKoO19by.mjs +1 -0
- package/dist/packem_shared/{computeRankPage-D9mACvr3.mjs → computeRankPage-DLSi_oBt.mjs} +1 -1
- package/dist/packem_shared/{createCompanionSync-C2cZNaCR.mjs → createCompanionSync-DhYLePyV.mjs} +1 -1
- package/dist/packem_shared/{createReplicaLink-DjykIKTn.mjs → createReplicaLink-Bd7jCjDt.mjs} +1 -1
- package/dist/packem_shared/ctx-db-relay-shapes-CPwELrMf.mjs +17 -0
- package/dist/packem_shared/{defineEngineContractSuite-DCw8RIP6.mjs → defineEngineContractSuite-CMbAZiZB.mjs} +1 -1
- package/dist/packem_shared/diffExternalSource-B0FZlDoL.mjs +1 -0
- package/dist/packem_shared/do-sql-DqU-17Fs.mjs +1 -0
- package/dist/packem_shared/{estimate-bytes-CTuiPWMD.mjs → estimate-bytes-_k74s6LZ.mjs} +1 -1
- package/dist/packem_shared/{isSoftDeleted-CLY0FNLV.mjs → isSoftDeleted-D5MeQSk0.mjs} +1 -1
- package/dist/packem_shared/json-field-path-DeJW4U9z.mjs +1 -0
- package/dist/packem_shared/materializeExternalRows-D2zEvCAa.mjs +1 -0
- package/dist/packem_shared/{mergeChangedKeys-DH9RAARR.mjs → mergeChangedKeys-CF2mjYuy.mjs} +1 -1
- package/dist/packem_shared/{runShardMigrations-B6FUu4iW.mjs → runShardMigrations-BeqUbznb.mjs} +1 -1
- package/dist/packem_shared/{selectExpiredIds-CGR1ndMV.mjs → selectExpiredIds-B8PxwbIr.mjs} +1 -1
- package/dist/packem_shared/{selectShapeMembers-DS28-P_Z.mjs → selectShapeMembers-B1MIaRkE.mjs} +1 -1
- package/dist/packem_shared/serializeSqlValue-DeoBMpZ2.mjs +1 -0
- package/dist/packem_shared/{where-sql-CxnXsLbt.mjs → where-sql-DO1vOrhc.mjs} +1 -1
- package/package.json +2 -1
- package/dist/packem_shared/ADMIN_FUNCTIONS-DmacEYTh.mjs +0 -1
- package/dist/packem_shared/AGG_COUNT-DYFE3qB4.mjs +0 -1
- package/dist/packem_shared/BIGINT_KEY_DIGITS-C9a7Ix7k.mjs +0 -1
- package/dist/packem_shared/CURSOR_PREFIX-BztyXqNP.mjs +0 -1
- package/dist/packem_shared/DEFAULT_PROMOTION_THRESHOLDS-DEURXMvk.mjs +0 -1
- package/dist/packem_shared/DurableStreamRunner-SCTUaMG0.mjs +0 -1
- package/dist/packem_shared/NotUniqueError-B69J01E7.mjs +0 -1
- package/dist/packem_shared/ReactiveCache-Bdzsahf3.mjs +0 -1
- package/dist/packem_shared/ShapeDiffCache-Br3kxusw.mjs +0 -1
- package/dist/packem_shared/aggregateTableName-DbAttCNH.mjs +0 -1
- package/dist/packem_shared/assertPatchAllowed-BJ_2LgkQ.mjs +0 -1
- package/dist/packem_shared/awaitWsDrain-D4E7Oiwo.mjs +0 -1
- package/dist/packem_shared/base64-DfpzS4o_.mjs +0 -1
- package/dist/packem_shared/buildPokeFrames-CDOP-XYp.mjs +0 -1
- package/dist/packem_shared/buildReprojectionMigration-D29YmeMF.mjs +0 -1
- package/dist/packem_shared/compileWhereSql-Dol9VRTW.mjs +0 -1
- package/dist/packem_shared/ctx-db-relay-shapes-OAI2tSoy.mjs +0 -17
- package/dist/packem_shared/diffExternalSource-DgDJhslq.mjs +0 -1
- package/dist/packem_shared/do-sql-CeuVvE0W.mjs +0 -1
- package/dist/packem_shared/json-field-path-B2fjnGc3.mjs +0 -1
- package/dist/packem_shared/materializeExternalRows-UxGuXjjF.mjs +0 -1
- package/dist/packem_shared/serializeSqlValue-BbZ5hKM7.mjs +0 -1
- package/dist/packem_shared/stableStringify-DibjylKD.mjs +0 -1
- package/dist/packem_shared/stableWireKey-Bdh5JSdg.mjs +0 -1
- package/dist/packem_shared/wire-codec-BYCSiazv.mjs +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as y}from"@lunora/errors";import{D as ut}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{S as Rn,l as qe,h as Tn}from"./fts-companion-DzfEHonU.mjs";import{decodeWire as vn,stableWireKey as xt}from"@lunora/wire";import{sql as a}from"drizzle-orm";import{throwingScheduler as An,aggregateSqlFunction as We,normalizeCountArgument as In}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as Ze,encodeAggregateKey as et,readAggregateValue as tt}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as N,CountRlsUnsupportedError as nt,selectIndexForGroupBy as Cn,selectIndexForCount as xn,selectIndexForAggregate as bn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Mn,searchIndexCoversTable as Dn}from"./backfillAggregateIndexes-Dw4Azd33.mjs";import{backfillAggregateIndexes as oi,backfillRankIndexes as ii,backfillSearchIndexes as si}from"./backfillAggregateIndexes-Dw4Azd33.mjs";import{appendCdcChange as kn,readCdcDocAtOrBefore as Ln}from"./CDC_LOG_TABLE-DsCz-DAV.mjs";import{CDC_LOG_TABLE as ai,applyCdcChanges as di,bumpCdcEpoch as li,cdcCanVouchFor as ui,cdcForkedError as fi,cdcSeqLeavingRows as hi,cdcTouchesTables as wi,cdcTrimmedError as pi,compactCdcDocs as gi,cursorBelowRetainedFloor as yi,minCdcReplayableSeq as $i,minCdcSeq as Ei,readCdcChangeKeys as mi,readCdcChanges as Si,readCdcCursor as _i,readCdcEpoch as Ri,trimCdcChanges as Ti}from"./CDC_LOG_TABLE-DsCz-DAV.mjs";import{allocateCommitSeq as Fn,COMMIT_SEQ_FIELD as qn}from"./COMMIT_SEQ_FIELD-BcUO15fR.mjs";import{createCompanionSync as Wn}from"./createCompanionSync-DhYLePyV.mjs";import{isMemoryTable as bt}from"./clearMemoryTables-Lu0S2GOb.mjs";import{computeRankPage as Mt}from"./computeRankPage-DLSi_oBt.mjs";import{SCAN_DEP as O}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as he,runDrizzle as G}from"./runDrizzle-B2GG3IJa.mjs";import{p as Bn,j as at,D as re,r as ve,k as de,b as Be,A as rt,a as Pe,m as ue,e as fe,s as Pn,t as rn,i as Un,q as Dt,h as on,g as On}from"./do-sql-DqU-17Fs.mjs";import{renderSql as sn,unionAll as ft,WORKERD_SQLITE_LIMITS as cn,sqliteInList as Hn}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{coveringGeohashes as Gn,boundingBoxGeohashes as jn,haversineMeters as Kn,pointInBoundingBox as Nn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Qn}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as Vn,assertPatchAllowed as Jn,operatorFields as zn,readPatchField as kt}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as Yn,encodeCursor as Ge,nullsOrderSuffix as Xn,normalizeOrderKeys as Lt,uniqueIndexFields as Zn,buildSeekWhere as er,decodeCursor as Ft,buildSeekBeforeWhere as tr,softDeleteScope as Te,applySelect as qt}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as Wt,sortColumnName as Bt,resolveRankPartition as nr,encodePartitionKey as rr,RANK_TIEBREAK as or,rankPivotConditionSql as ir}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{UNVOUCHABLE_DEP as Pt}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as sr,buildIndexRange as cr}from"./buildIndexRange-DQ3eWAGd.mjs";import{r as je,j as Ae,c as Y,t as Ke,i as Ut}from"./where-sql-DO1vOrhc.mjs";import{serializeSqlValue as Ie}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as Ce}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as ar,isPushableWhere as dr}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as lr,findRelated as ur}from"./RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{assertFlatPredicate as ot,resolveRelationPredicates as fr,composeReadPredicate as hr}from"./DEFAULT_MAX_RELATION_KEYS-BYfAkNAH.mjs";import{describeRelationWrites as wr}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as it,resolveWith as Ot,relationHooks as Ht,applyOnDelete as pr,fanOutScalarCounts as gr}from"./applyOnDelete-BwxDC4lU.mjs";import{guardWriter as yr}from"./RLS_UNWRAP_SYMBOL-DQt9luIF.mjs";import{mayHoldProjectedValue as $r}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as Er}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as ce}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as Gt,runTriggers as mr}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as Ai,migrateClientWatermark as Ii,readClientWatermark as Ci}from"./CLIENT_WATERMARK_TABLE-_CkdMnT2.mjs";import{IDEMPOTENCY_TABLE as bi,readIdempotent as Mi,trimIdempotent as Di,writeIdempotent as ki}from"./IDEMPOTENCY_TABLE-CymJf4r0.mjs";import{runShardMigrations as Fi}from"./runShardMigrations-BeqUbznb.mjs";import{selectShapeMembers as Wi,selectShapeRows as Bi}from"./selectShapeMembers-B1MIaRkE.mjs";const Sr=n=>{const s=atob(n),r=Uint8Array.from(s,c=>c.codePointAt(0)??0);return new TextDecoder().decode(r)},_r=()=>new y("BAD_REQUEST","invalid cursor"),jt=16,Kt=8,J=1024,ht=(n,s)=>s.query(n),Rr=(n,s)=>{if(n.length===0)return 0;let r=0;for(const[c,i]of s.entries()){const w=c===s.length-1;let _=0;for(const S of n)(w?S.startsWith(i):S===i)&&(_+=1);if(_===0)return 0;r+=_}return r},Tr=(n,s)=>{if(!s)return{exact:!0,lower:n,upper:n};const r=[...n].at(-1)??"",c=(r.codePointAt(0)??0)+1;if(c>=55296&&c<=57343||c>1114111)return{exact:!0,lower:n,upper:n};const i=n.slice(0,n.length-r.length);return{exact:!1,lower:n,upper:i+String.fromCodePoint(c)}},vr=(n,s,r)=>{const c={eq:(i,w)=>{if(!n.definition.filterFields?.includes(i))throw new y("INTERNAL",`field "${i}" is not a filter field of search index "${n.indexName}" on table "${s}"`);if(n.filters.length>=Kt)throw new y("BAD_REQUEST",`search index "${n.indexName}" on table "${s}": at most ${String(Kt)} .eq() filters are supported per search query`);return n.filters.push({field:i,value:w}),c},search:(i,w)=>{const _=n;if(i!==_.definition.field)throw new y("INTERNAL",`search index "${_.indexName}" on table "${s}" indexes "${_.definition.field}", not "${i}"`);const S=ht(w,r).length;if(S>jt)throw new y("BAD_REQUEST",`search index "${_.indexName}" on table "${s}": at most ${String(jt)} search terms are supported (got ${String(S)})`);return _.field=i,_.query=w,_.hasQuery=!0,c}};return c},Ar=n=>{if(n.length>J)throw new y("BAD_REQUEST",`more than ${String(J)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Ir=n=>Math.min(n.offset+n.numItems+1,J),Cr=n=>btoa(`search:${String(n)}`),xr=n=>{let s;try{s=Sr(n)}catch{return}if(!s.startsWith("search:"))return;const r=Number(s.slice(7));return Number.isInteger(r)&&r>=0?r:void 0},br=n=>{if(typeof n.endCursor=="string")throw new y("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new y("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const s=Math.max(0,Math.floor(n.numItems)),r=n.cursor?xr(n.cursor):0;if(r===void 0)throw _r();if(r+s>=J)throw new y("BAD_REQUEST",`search pagination reaches the ${String(J)}-document limit (offset ${String(r)} + ${String(s)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,J-r-1))} or fewer, or narrow the query or the filters instead`);return{numItems:s,offset:r}},Mr=(n,s)=>{const r=s.offset+s.numItems,c=s.numItems>0&&n.length>r;return{continueCursor:c?Cr(r):null,isDone:!c,page:n.slice(s.offset,r)}},Dr=n=>{if(n===void 0)return J+1;if(!Number.isFinite(n))return J;const s=Math.max(0,Math.floor(n));if(s>J)throw new y("BAD_REQUEST",`search returns at most ${String(J)} documents (asked for ${String(s)}) — narrow the query or paginate instead`);return s},kr=32,Lr=1024,an=(n,s,r,c)=>{const i=`SELECT id, _creationTime, ${Ce(re)} FROM ${Ce(n)}`,w=`ORDER BY ${r}${c===void 0?"":` LIMIT ${String(c)}`}`;return s===void 0?je(`${i} ${w}`):Ae(`${i} WHERE `,s,` ${w}`)},Ne={fieldRef:n=>je(at(n)),rangeTypeGuard:(n,s)=>je(Bn(n,s)),serialize:Ie},Fr=n=>n===void 0?"":Xn(n==="first"),dn=n=>{const s=n.map(r=>`${at(r.field)} ${r.direction==="desc"?"DESC":"ASC"}${Fr(r.nulls)}`);return n.some(r=>r.field==="_id"||r.field==="id")||s.push(`${at("id")} ${Yn(n)==="desc"?"DESC":"ASC"}`),s.join(", ")},qr={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},ln=n=>new Set(n.sqlConditions.filter(s=>s.comparator==="=").map(s=>s.field)),Wr=n=>{const s=ln(n);let r=0;for(;r<n.indexFields.length&&s.has(n.indexFields[r]??"");)r+=1;return n.indexFields.slice(r)},Br=(n,s)=>{const r=n.order,c=Wr(n),{shape:i}=s;return c.length>0?Lt(c.map(w=>({[w]:r})),i,{pinned:ln(n),uniqueBy:Zn(s.indexes,i)}):Lt([{_creationTime:r}],i)},Pr=(n,s,r,c)=>{const i=n.sqlConditions.map(w=>({[w.field]:{[qr[w.comparator]??"eq"]:w.value}}));if(r&&i.push(er(s,Ft(r))),c&&i.push(tr(s,Ft(c))),i.length!==0)return i.length===1?i[0]:{AND:i}},Ur=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,kr):n.want},dt=(n,s,r,c,i,w,_)=>{const S=Br(c,r),C=dn(S),g=[],{filters:q,want:I}=w;let R=w.cursor??void 0,M=Ur(w);if(I===0)return{documents:g,orderKeys:S};for(;;){const F=Y(Pr(c,S,R,w.endCursor),Ne,Ke),B=an(s,i&&F?Ae(F," AND ",i):i??F,C,M),L=he(n,B.text,...B.params).toArray();let W={};_(L.length);for(const j of L)if(W=ve(j),q.every(pe=>pe(W))&&g.push(W)===I)return{documents:g,orderKeys:S};if(M===void 0||L.length<M)return{documents:g,orderKeys:S};R=Ge(W,S),M=Math.max(M,Math.min(M*2,Lr))}},Or=(n,s,r,c,i,w,_,S)=>{const C=Math.max(0,Math.floor(i.numItems));if(typeof i.endCursor=="string"){const{documents:F,orderKeys:B}=dt(n,s,r,c,w,{cursor:i.cursor,endCursor:i.endCursor,filters:_.all,selective:_.selective,want:void 0},S),L=F.length>=2?F[Math.floor(F.length/2)-1]:void 0;return{continueCursor:i.endCursor,isDone:!0,page:F,splitCursor:L?Ge(L,B):null}}const{documents:g,orderKeys:q}=dt(n,s,r,c,w,{cursor:i.cursor,filters:_.all,selective:_.selective,want:C+1},S),I=g.length>C,R=I?g.slice(0,C):g,M=R.at(-1);return{continueCursor:I&&M?Ge(M,q):null,isDone:!I,page:R}},Qe=n=>{const s=new Map;return r=>{const c=s.get(r);if(c!==void 0)return c;const i=n(Ce(r));return s.set(r,i),i}},we=Ce(re),Hr=Qe(n=>`INSERT INTO ${n} (id, _creationTime, ${we}) VALUES (?, ?, ?)`),Nt=Qe(n=>`UPDATE ${n} SET ${we} = ? WHERE id = ? AND ${we} = ?`),Gr=Qe(n=>`UPDATE ${n} SET _creationTime = ?, ${we} = ? WHERE id = ? AND ${we} = ?`),jr=Qe(n=>`DELETE FROM ${n} WHERE id = ? AND ${we} = ?`),Kr="SELECT changes() AS changed",Qt=new Map,Nr="",Qr=n=>{const s=JSON.stringify(n),r=Qt.get(s);if(r!==void 0)return r;const c=n.map(w=>a`SELECT ${a.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${a.identifier(re)} FROM ${a.identifier(w)} WHERE id = ${Nr}`),{sql:i}=sn("sqlite",a`${ft(c)} LIMIT 1`);return Qt.set(s,i),i},Vr=(n,s)=>s.map(()=>n),Jr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,zr=n=>{if(!Jr.test(n))throw new y("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},Vt=50,un=500,Ue=Math.floor(cn.boundParams/3),Re=cn.boundParams,Yr=128,le=(n,s,r)=>{const c=s??un;if(n>c)throw new y("BATCH_LIMIT_EXCEEDED",`${r}: batch of ${String(n)} exceeds the limit of ${String(c)} (raise options.limit or chunk the call)`,{status:400})},Xr=n=>{const s={eq:(r,c)=>(n.sqlConditions.push({comparator:"=",field:r,value:c}),s),gt:(r,c)=>(n.sqlConditions.push({comparator:">",field:r,value:c}),s),gte:(r,c)=>(n.sqlConditions.push({comparator:">=",field:r,value:c}),s),lt:(r,c)=>(n.sqlConditions.push({comparator:"<",field:r,value:c}),s),lte:(r,c)=>(n.sqlConditions.push({comparator:"<=",field:r,value:c}),s)};return s},Zr=n=>Math.max(n,J),fn=(n,s)=>{const r=n.filters.map(c=>a`${fe(c.field)} = ${Ie(c.value)}`);return s&&r.push(s),r},eo=(n,s,r,c,i)=>{const w=ht(r.query,ut(r.definition.language));if(w.length===0)return[];const _=Rn(s,r.indexName),S=`${_}__vocab`,C=w.length-1,g=w.map((B,L)=>{const W=Tr(B,L===C),j=W.exact?a`${a.identifier("term")} = ${W.lower}`:a`${a.identifier("term")} >= ${W.lower} AND ${a.identifier("term")} < ${W.upper}`;return a`SELECT ${a.identifier("doc")}, ${a.raw(String(L))} AS ${a.identifier("__term__")}, COUNT(*) AS ${a.identifier("__n__")} FROM ${a.identifier(S)} WHERE ${j} GROUP BY ${a.identifier("doc")}`}),q=w.map((B,L)=>a`SUM(CASE WHEN u.${a.identifier("__term__")} = ${a.raw(String(L))} THEN u.${a.identifier("__n__")} ELSE 0 END)`),I=a`SELECT f.${a.identifier(qe)} AS ${a.identifier(qe)}, ${a.join(q,a` + `)} AS ${a.identifier("__score__")} FROM (${ft(g)}) u JOIN ${a.identifier(_)} f ON f.rowid = u.${a.identifier("doc")} GROUP BY f.${a.identifier(qe)} HAVING ${a.join(q.map(B=>a`${B} > 0`),a` AND `)}`,R=fn(r,i);let M=a`SELECT m.id, m._creationTime, m.${a.identifier(re)}, s.${a.identifier("__score__")} AS ${a.identifier("__score__")} FROM (${I}) s JOIN ${a.identifier(s)} m ON m.id = s.${a.identifier(qe)}`;R.length>0&&(M=a`${M} WHERE ${a.join(R,a` AND `)}`),M=a`${M} ORDER BY s.${a.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${a.raw(String(c))}`;const F=[];for(const B of G(n,M)){const L=on(B);if(L){const W=B.__score__;F.push({document:L,score:typeof W=="number"?W:Number(W??0)})}}return F},to=(n,s,r,c,i)=>{const w=ut(r.definition.language),_=ht(r.query,w);if(_.length===0)return[];const S=fn(r,i);let C=a`SELECT id, _creationTime, ${a.identifier(re)} FROM ${a.identifier(s)}`;S.length>0&&(C=a`${C} WHERE ${a.join(S,a` AND `)}`),C=a`${C} ORDER BY _creationTime DESC, id ASC LIMIT ${a.raw(String(Zr(c)))}`;const g=G(n,C).toArray(),q=[];for(const I of g){const R=on(I);if(!R)continue;const M=Rr(Tn(R,r.definition),_);M>0&&q.push({creationTime:typeof R._creationTime=="number"?R._creationTime:0,doc:R,id:typeof R._id=="string"?R._id:"",score:M})}return q.sort((I,R)=>R.score-I.score||R.creationTime-I.creationTime||I.id.localeCompare(R.id)),q.slice(0,c).map(I=>({document:I.doc,score:I.score}))},st=(n,s,r,c)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new y("BAD_REQUEST",`geo index "${c}" on table "${r}": ${s} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},no=(n,s)=>{const r=n,c={near:(i,w)=>{if(r.within)throw new y("INTERNAL",`geo index "${r.indexName}" on table "${s}": call .near() or .within(), not both`);if(st(i,".near() point",s,r.indexName),!Number.isFinite(w)||w<=0)throw new y("BAD_REQUEST",`geo index "${r.indexName}" on table "${s}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return r.near={point:{lat:i.lat,lng:i.lng},radiusMeters:w},c},within:i=>{if(r.near)throw new y("INTERNAL",`geo index "${r.indexName}" on table "${s}": call .near() or .within(), not both`);if(st(i.sw,".within() sw corner",s,r.indexName),st(i.ne,".within() ne corner",s,r.indexName),i.sw.lat>i.ne.lat)throw new y("BAD_REQUEST",`geo index "${r.indexName}" on table "${s}": .within() corners are transposed (sw.lat > ne.lat)`);if(i.sw.lng>i.ne.lng)throw new y("BAD_REQUEST",`geo index "${r.indexName}" on table "${s}": .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 r.within={ne:{lat:i.ne.lat,lng:i.ne.lng},sw:{lat:i.sw.lat,lng:i.sw.lng}},c}};return c},ro=(n,s)=>{const r=n[s];if(r===null||typeof r!="object")return;const{lat:c,lng:i}=r;return typeof c=="number"&&typeof i=="number"?{lat:c,lng:i}:void 0},oo=(n,s)=>{const r=ro(n,s.definition.field);if(!r)return;const c=typeof n._creationTime=="number"?n._creationTime:0;if(s.near){const i=Kn(s.near.point,r);return i<=s.near.radiusMeters?{creationTime:c,distance:i}:void 0}return Nn(r,s.within)?{creationTime:c,distance:0}:void 0},io=(n,s,r,c)=>{if(!r.near&&!r.within)throw new y("INTERNAL",`geo index "${r.indexName}" on table "${s}": call .near(point, radius) or .within(box)`);const i=r.near?Gn(r.near.point,r.near.radiusMeters):jn(r.within),w=On(s,r.indexName),_=i.map(I=>a`(g.${a.identifier("__geohash__")} >= ${I} AND g.${a.identifier("__geohash__")} < ${`${I}{`})`),S=[a`(${a.join(_,a` OR `)})`];c&&S.push(c);const C=a`SELECT m.id, m._creationTime, m.${a.identifier(re)} FROM ${a.identifier(w)} g JOIN ${a.identifier(s)} m ON m.id = g.${a.identifier("__id__")} WHERE ${a.join(S,a` AND `)}`,g=G(n,C).toArray(),q=[];for(const I of g){const R=ve(I),M=R?oo(R,r):void 0;R&&M&&q.push({creationTime:M.creationTime,distance:M.distance,doc:R})}return q.sort((I,R)=>I.distance-R.distance||R.creationTime-I.creationTime),q},hn=(n,s,r,c)=>{const i=[];for(const w of n)if(s.every(_=>_(c(w)))&&(i.push(w),typeof r=="number"&&i.length>=r))break;return i},so=(n,s,r,c,i,w=()=>{})=>{const _=r.within!==void 0,S=io(n,s,r,i).map(C=>({distanceMeters:_?null:C.distance,document:C.doc}));return w(S.length),typeof c=="number"?S.slice(0,Math.max(0,Math.floor(c))):S},Jt=(n,s,r,c,i,w,_=()=>{})=>{const{geo:S}=r;if(!S)throw new y("INTERNAL","runGeoTerminalScored called without a staged geo query");const C=i.length>0,g=so(n,s,S,C?void 0:w,c,_);return C?hn(g,i,w,q=>q.document):g},zt=(n,s,r)=>{const c=n.shape[s];if(c!==void 0&&$r(c))throw new y("BAD_REQUEST",`${r}: "${s}" 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)`)},co=n=>{let s=0;const r=[],c={...Ne,relationExists:i=>{const{childWhere:w,negated:_,parentTable:S,relation:C}=i,g=`__rel_${String(s)}`,q=r.at(-1)??S;s+=1,n(C.table,O);const I=C.kind==="one"?C.field:C.references,R=C.kind==="one"?C.references:C.field,M=je(`${Dt(g,R)} = ${Dt(q,I)}`);r.push(g);const F=Y(w,c,Ke);r.pop();const B=F===void 0?M:Ae(M," AND ",F),L=Ae("EXISTS (SELECT 1 FROM ",Ut(C.table)," AS ",Ut(g)," WHERE ",B,")");return _?Ae("NOT ",L):L}};return c};class ao extends y{constructor(s="unique() found more than one matching document"){super("NOT_UNIQUE",s,{name:"NotUniqueError"})}}const lo=/\s/u,uo=String.fromCodePoint(0),Yt=(n,s,r)=>{if(!n.tables[s])throw new y("INTERNAL",`unknown table: ${s}`);return typeof r!="string"||r.length===0||lo.test(r)||r.includes(uo)?null:r},wn=(n,s,r,c=()=>{},i=()=>{},w=()=>{},_)=>{const S=s.tables[r];if(!S)throw new y("INTERNAL",`unknown table: ${r}`);const C=Te(S.softDeleteMode,void 0),g=_??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},q=()=>{const $=N(C,g.pushedWhere);return $?Y($,ue):void 0},I=()=>{const $=N(C,g.pushedWhere);return $?Y($,Ne,Ke):void 0},R=()=>[...g.inMemoryFilters,...g.verifyFilters];let M=0;const F=$=>{const{search:x}=g;if(!x)throw new y("INTERNAL","runSearchFetch called without a staged search");Mn(n,r,S);const b=g.inMemoryFilters.length>0,k=Dr(b?void 0:$),Q=Un(n);if(Q&&!Dn(n,r,x.definition))throw new y("SEARCH_INDEX_BUILDING",`search index "${x.indexName}" on table "${r}" 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 ne=q(),oe=Q?eo(n,r,x,k,ne):to(n,r,x,k,ne);!b&&$===void 0&&Ar(oe);const ge=R();return M=oe.length,ge.length>0?hn(oe,ge,$,ie=>ie.document):oe},B=$=>F($).map(x=>x.document),L=$=>{const x=br($);return Mr(B(Ir(x)),x)},W=()=>{if(g.search||g.geo||g.indexName===void 0){i(void 0);return}i(cr(r,g.indexName,g.indexFields,g.sqlConditions,Ie))},j=$=>{W();let x=0;const b=(()=>{if(g.search){const k=B($);return x=M,k}return g.geo?Jt(n,r,g,q(),R(),$,k=>{x=k}).map(k=>k.document):dt(n,r,S,g,I(),{filters:R(),selective:g.inMemoryFilters.length>0,want:$===void 0?void 0:Math.max(0,Math.floor($))},k=>{x+=k}).documents})();return w(Math.max(x,b.length)),b},pe=()=>{if(!g.search&&!g.geo)throw new y("INTERNAL",`ctx.db.query("${r}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);W();let $=0;const x=(()=>{if(g.search){const b=F(void 0);return $=M,b}return Jt(n,r,g,q(),R(),void 0,b=>{$=b})})();return w(Math.max($,x.length)),x},D={async*[Symbol.asyncIterator](){const $=wn(n,s,r,c,i,w,{...g,indexFields:[...g.indexFields],inMemoryFilters:[...g.inMemoryFilters],sqlConditions:[...g.sqlConditions],verifyFilters:[...g.verifyFilters]});if(g.search){yield*await $.collect();return}let x;for(;;){const b=await $.paginate({cursor:x??null,numItems:Yr});if(yield*b.page,b.isDone||b.continueCursor===null)return;x=b.continueCursor}},async collect(){return j(void 0)},async collectWithScores(){return pe()},filter($){const x=ar($);return x!==void 0&&dr(x,S.shape)?(g.pushedWhere=N(g.pushedWhere,x),g.verifyFilters.push($)):g.inMemoryFilters.push($),D},async first(){return j(1)[0]??null},order($){return g.order=$==="desc"?"desc":"asc",D},async paginate($){let x=0;if(W(),g.search){const k=L($);return w(k.page.length),k}if(g.geo)throw new y("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const b=Or(n,r,S,g,$,I(),{all:R(),selective:g.inMemoryFilters.length>0},k=>{x+=k});return w(Math.max(x,b.page.length)),b},async take($){return j($)},async unique(){const $=j(2);if($.length>1)throw new ao(`unique() on table "${r}" matched ${String($.length)} documents; expected at most one`);return $[0]??null},withGeoIndex($,x){const b=(S.geoIndexes??[]).find(Q=>Q.name===$);if(!b)throw new y("INTERNAL",`unknown geo index "${$}" on table "${r}"`);c(r,$,"geo");const k={definition:b,indexName:$};if(g.geo=k,x(no(k,r)),!k.near&&!k.within)throw new y("INTERNAL",`geo index "${$}" on table "${r}" requires a .near(point, radius) or .within(box) call`);return D},withIndex($,x){const b=S.indexes.find(k=>k.name===$);if(!b)throw new y("INTERNAL",`unknown index "${$}" on table "${r}"`);return c(r,$,"index"),g.indexName=$,g.indexFields=b.fields,x&&x(Xr(g)),D},withSearchIndex($,x){const b=(S.searchIndexes??[]).find(Q=>Q.name===$);if(!b)throw new y("INTERNAL",`unknown search index "${$}" on table "${r}"`);c(r,$,"search");const k={definition:b,field:b.field,filters:[],hasQuery:!1,indexName:$,query:""};if(g.search=k,x(vr(k,r,ut(b.language))),!k.hasQuery)throw new y("INTERNAL",`search index "${$}" on table "${r}" requires a .search(field, query) call`);return D}};return D},Xt=(n,s,r)=>{const c={...s};for(const[i,w]of rn(n)){if(w.serverDefault){c[i]=w.serverDefault({auth:r});continue}c[i]===void 0&&(w.defaultFn?c[i]=w.defaultFn():"defaultValue"in w&&(c[i]=w.defaultValue))}return c},ct=(n,s,r,c)=>{const i=r;for(const[w,_]of rn(n)){if(_.serverDefault){w in s&&(i[w]=_.serverDefault({auth:c}));continue}_.onUpdateFn&&!(w in s)&&(i[w]=_.onUpdateFn())}},Zt=5,en=(n,s)=>{for(const r of Object.keys(s))if(s[r]===void 0)throw new y("INTERNAL",`Cannot ${n} field '${r}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},tn=["_commitSeq","_creationTime","_id"],Oe=n=>tn.some(s=>s in n)?Object.fromEntries(Object.entries(n).filter(([s])=>!tn.includes(s))):n,fo=/unique constraint failed/i,ho=n=>n instanceof Error&&fo.test(n.message),wo=/string or blob too big/iu,po=(n,s)=>{if(!(!(n instanceof Error)||!wo.test(n.message)))throw new y("PAYLOAD_TOO_LARGE",`document is too large to store in "${s}": 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.`)},lt=(n,s,r,c)=>{try{he(n,r,...c)}catch(i){throw ho(i)?new ce(`unique constraint violation on "${s}"`,"unique"):(po(i,s),i)}},He=(n,s,r,c)=>{if(lt(n,s,r,c),he(n,Kr).one().changed===0)throw new ce(`optimistic concurrency conflict on "${s}" — the row changed during this mutation; refetch and retry`,"occ")},nn=(n,s,r,c,i,w,_)=>{const S=[];for(let I=0;I<r.length+1;I+=1){const R=r[I],M=c[I],F=M?.direction==="desc"?"desc":"asc",B=R===void 0||M===void 0?a`${a.identifier(or)} < ${_}`:ir(R,w[I],F,!1);if(B===void 0)continue;const L=[];for(let j=0;j<I;j+=1)L.push(a`${a.identifier(r[j])} IS ${w[j]}`);L.push(B);const[W]=L;S.push(L.length===1&&W!==void 0?W:a`(${a.join(L,a` AND `)})`)}const C=S.length>0?a.join(S,a` OR `):a`1 = 0`,g=G(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(s)} WHERE ${a.identifier("__partition__")} = ${i} AND (${C})`).one(),q=G(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(s)} WHERE ${a.identifier("__partition__")} = ${i}`).one();return{before:g.c,total:q.c}},go=n=>{const s=new Map;for(const[c,i]of Object.entries(n.tables))for(const w of Object.values(i.relationMap??{}))w.kind==="one"&&(w.onDelete==="cascade"||w.onDelete==="set null")&&s.set(w.table,[...s.get(w.table)??[],{holder:c,op:w.onDelete==="cascade"?"delete":"update"}]);const r=c=>{const i=new Set,w=[c];for(let _=w.pop();_!==void 0;_=w.pop())for(const{holder:S,op:C}of s.get(_)??[]){if(S===c||Gt(n,S,C))return!0;i.has(S)||(i.add(S),w.push(S))}return!1};return new Set(Object.entries(n.tables).filter(([c,i])=>i.shardMode?.kind==="global"||Gt(n,c,"delete")||r(c)).map(([c])=>c))},ti=n=>{const{baselineSeq:s,onStalePatchDropped:r}=n,{sql:c}=n,{schema:i}=n,w=n.broadcast??(()=>{}),_=lr(i),S=wr(i,n.inTransaction),C=go(i);let g;const q=()=>n.inTransaction?.()===!0,I=e=>i.tables[e]?.commitOrderedMode!==!0?{}:((g===void 0||!q())&&(g=Fn(c)),{[qn]:g}),R=(e,...t)=>{const o=i.tables[e]?.indexes;if(!o||o.length===0)return;const u=[];for(const h of t)h&&u.push(...sr(o,h,Ie));return u.length>0?u:void 0},{headroom:M}=n;let F=!1;const B=async e=>{const t=F;F=!0;try{return await e()}finally{F=t}},L=n.onRead??(()=>{}),W=e=>{bt(i.tables[e])&&L(Pt,Pt)},j=n.onReadRange??(e=>{L(e.table,O)}),pe=e=>{W(e.table),j(e)},D=(e,t)=>{t!==void 0&&t!==O&&!F&&M?.recordRead(1),W(e),L(e,t)},$=n.onIndexUse??(()=>{}),x=n.onWrite??(()=>{}),b=e=>{F||M?.recordWrite(e)},k=async e=>{b(e.doc),await x(e)},{cache:Q}=n,ne=n.clock??(()=>Date.now()),oe=n.idGenerator??(()=>crypto.randomUUID()),ge=n.scheduler??An,{globalDb:ie}=n,ye=n.auth??{identity:null,userId:null},wt=n.cdc??!1,Ve=ge,pn=Er({scheduler:typeof Ve.list=="function"&&typeof Ve.get=="function"?Ve:void 0,storage:n.storage}),$e=(e,t,o,u)=>{wt&&!bt(i.tables[e])&&kn(c,ne(),e,t,o,u)},pt=(e,t,o,u)=>{const h=i.tables[e];if(h?.dropStalePatchesMode!==!0||!wt)return!1;const f=s?.();if(f===void 0)return!1;const d=Ln(c,e,t,f);if(d===void 0)return!1;const l=zn(h,o);return Object.keys(Oe(o)).some(p=>!l.has(p)&&xt(kt(d,p))!==xt(kt(u,p)))},se=e=>i.tables[e]?.shardMode?.kind==="global",gt=(e,t)=>{if(se(e)){if(!ie)throw new y("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return ie}return P},Je=e=>gt(e,"cascade"),K=(e,t)=>{if(se(e)){if(!ie)throw new y("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return ie}},yt=async(e,t,o,u,h)=>{h&&b(o);const f=await e.insert(t,o,u);return w({key:f,op:"insert",row:{...o,_id:f},table:t}),f},ze=(e,t)=>gt(e,"relation load").findMany(e,t),$t=(e,t)=>(se(e)&&D(e,O),ze(e,t)),gn=e=>!se(e.table),Et=n.relationExistsPushDown??"auto",mt=Et!=="never",{maxRelationKeys:St}=n,xe=(e,t,o)=>fr(e,{fetcher:$t,maxRelationKeys:St,relationBaseWhere:o,schema:i,tableName:t}),_t=async(e,t,o,u)=>{const h=K(e,"relation grouped count");if(h)return D(e,O),gr((v,H)=>h.count(v,H),e,t,o,u);const f=i.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);D(e,O);const d=Te(f.softDeleteMode,void 0),l={[t]:{in:o}},p=N(N(l,u),d),A=await xe(p,e,void 0),E=Y(A,ue),T=fe(t);let m=a`SELECT ${T} AS __fk__, COUNT(*) AS count FROM ${a.identifier(e)}`;E&&(m=a`${m} WHERE ${E}`),m=a`${m} GROUP BY ${T}`;const U=G(c,m).toArray();return new Map(U.map(v=>[v.__fk__,v.count]))};let be=0;const Rt=new Set;for(const[e,t]of Object.entries(i.tables))for(const o of Object.values(t.triggerMap??{}))Rt.add(`${e} ${o.timing} ${o.op}`);const X=(e,t,o)=>Rt.has(`${e} ${t} ${o}`),Z=async(e,t,o)=>{if(be+=1,be>Vt)throw be-=1,new ce(`trigger recursion exceeded ${String(Vt)} levels on "${o.table}" — check for a self-triggering write`,"trigger");try{await mr({ctx:Sn,event:o,op:t,schema:i,tableName:o.table,timing:e})}finally{be-=1}},{ensureBackfilledForTable:Ee,ensureBackfilledIndex:Ye,ensureRankBackfilled:Xe,ensureRankBackfilledForTable:me,syncAggregates:Me,syncCompanionsForInsert:Tt,syncGeo:De,syncRanks:Se,syncSearch:ke}=Wn({broadcast:w,indexKeysFor:(e,t)=>R(e,t),invalidateCache:(e,t,o)=>Q?.invalidate(e,t,R(e,o)),recordCdc:$e,schema:i,sql:c}),vt=(e,t,o)=>{const{shardMode:u}=t;if(u?.kind==="shardBy"&&!(u.field!==void 0&&(o.partitionBy??[]).includes(u.field)))throw Object.assign(new Error(`rank index "${o.name}" on "${e}" partitions across shards (shard key "${u.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})},At=e=>Object.entries(i.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),_e=e=>e===void 0||se(e)?ie:void 0,ee=(e,t)=>{const o=At(t);for(let u=0;u<o.length;u+=Re){const h=o.slice(u,u+Re),[f]=he(c,Qr(h),...Vr(e,h)).toArray();if(!f)continue;const d=f.__t__,l=ve(f);if(typeof d!="string"||!l)return;const p=f[re];return{docJson:typeof p=="string"?p:de(p??{}),row:l,tableName:d}}},yn=(e,t)=>{const o=[...new Set(e)],u=new Map;if(o.length===0)return u;const h=At(t);for(let f=0;f<h.length;f+=Re){const d=h.slice(f,f+Re),l=Math.floor(Re/d.length),p=Hn(a`${a.identifier("id")}`,o,!1,l),A=d.map(E=>a`SELECT ${a.raw(`'${E.replaceAll("'","''")}'`)} AS __t__, id FROM ${a.identifier(E)} WHERE ${p}`);for(const E of G(c,ft(A))){const{id:T,__t__:m}=E;typeof m=="string"&&typeof T=="string"&&u.set(T,m)}}return u},It={assertRankPartitionLocal:vt,ensureRankBackfilled:Xe,onRead:D,rowToDocument:ve,schema:i,sql:c},$n=(e,t,o)=>{const u=Y(o,ue);return u===void 0||G(c,a`SELECT 1 FROM ${a.identifier(e)} WHERE ${a.identifier("id")} = ${t} AND ${u}`).toArray().length>0},En=(e,t,o,u)=>pt(e,t,o,u)?(r?.({fields:Object.keys(Oe(o)),id:t,table:e}),!0):!1,mn=async(e,t,o,u,h)=>{const f=ee(t,e);if(!f)return{applied:!1,doc:null};if(D(e,t),!$n(e,t,o.where)||En(e,t,o.patch,f.row))return{applied:!1,doc:f.row};try{await h(o.patch)}catch(d){if(d instanceof ce&&d.kind==="occ"&&u)return;throw d}return{applied:!0,doc:ee(t,e)?.row??null}},Ct=async(e,t,o,u)=>{const{fetchLimit:h,limit:f,orderKeys:d,predicate:l}=await hr(t,o,{canPushExists:mt?gn:void 0,existsPushMode:Et==="always"?"always":"auto",fetcher:$t,maxRelationKeys:St,schema:i,tableName:e}),p=mt?co(u):Ne,A=Y(l,p,Ke),E=an(e,A,dn(d),h);return{limit:f,orderKeys:d,statement:E}},P={system:pn,async aggregate(e,t){const o=K(e,"aggregate");if(o)return D(e,O),o.aggregate(e,t);const u=i.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);if(We(t.op),t.op==="count")return P.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new y("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);D(e,O);const h=Te(u.softDeleteMode,void 0),f=N(N(t.baseWhere,t.where),h),d=await xe(f,e,t.relationBaseWhere),l=d!==f;if(u.aggregateIndexes&&!t.baseWhere&&!l){const v=bn(u.aggregateIndexes,t.op,t.field,t.where);if(v){Ye(e,v.index);const H=et(v.index.by??[],v.key),te=Ze(e,v.index.name),z=G(c,a`SELECT ${Be} AS value, ${rt} AS count FROM ${a.identifier(te)} WHERE ${Pe} = ${H}`).toArray()[0];return tt(t.op,z)}}zt(u,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const p=Y(d,ue),A=We(t.op),E=fe(t.field);let T=a`SELECT ${a.raw(A)}(${E}) AS value FROM ${a.identifier(e)}`;p&&(T=a`${T} WHERE ${p}`);const U=G(c,T).toArray()[0]?.value;return U??null},asId(e,t){const o=Yt(i,e,t);if(o===null)throw new y("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return o},async count(e,t){const o=K(e,"count");if(o)return D(e,O),o.count(e,t);const u=i.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const h=In(t);if(h.restrictsCounts)throw new nt(e);D(e,O);const f=Te(u.softDeleteMode,void 0),d=N(N(h.baseWhere,h.where),f),l=await xe(d,e,h.relationBaseWhere),p=l!==d;if(u.aggregateIndexes&&!h.baseWhere&&!p){const m=xn(u.aggregateIndexes,h.where);if(m){Ye(e,m.index);const U=et(m.index.by??[],m.key),v=Ze(e,m.index.name),H=G(c,a`SELECT ${Be} AS value FROM ${a.identifier(v)} WHERE ${Pe} = ${U}`).toArray();return H[0]===void 0?0:H[0].value??0}}const A=Y(l,ue);let E=a`SELECT COUNT(*) AS count FROM ${a.identifier(e)}`;return A&&(E=a`${E} WHERE ${A}`),G(c,E).one().count},async delete(e,t,o){const u=ee(e,t);if(!u){const T=_e(t);T&&(b(void 0),await T.delete(e,t,o));return}const{docJson:h,row:f,tableName:d}=u,l=i.tables[d],p=o?.hard===!0,A=!p&&l?.softDeleteMode?l:void 0,E=A?.softDeleteMode?.field;if(!(E&&f[E]!==null&&f[E]!==void 0)){if(X(d,"before","delete")&&await Z("before","delete",{id:e,op:"delete",previous:f,table:d}),await pr({deletedId:e,deletedReference:T=>f[T],findHolders:async(T,m,U)=>(await Je(T).findMany(T,{includeDeleted:p,where:{[m]:U}})).page,onCascade:(T,m)=>Je(T).delete(m,void 0,o),onRestrict:T=>{throw new ce(T,"restrict")},onSetNull:(T,m,U)=>Je(T).patch(m,{[U]:null}),schema:i,tableName:d}),Ee(d),me(d),A&&E){const T={[E]:ne()},m={...f,...I(d),...T,_id:e};ct(A,T,m,ye),He(c,d,Nt(d),[de(m),e,h]),ke(d,e,m,f),De(d,e,void 0),Me(d,f,m),Se(d,e,f,void 0),Q?.invalidate(d,e,R(d,f,m)),$e(d,e,"update",m),w({indexKeys:R(d,f,m),key:e,op:"update",row:m,table:d}),X(d,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:f,table:d}),await k({id:e,op:"delete",table:d});return}He(c,d,jr(d),[e,h]),ke(d,e,void 0),De(d,e,void 0),Me(d,f,void 0),Se(d,e,f,void 0),Q?.invalidate(d,e,R(d,f)),$e(d,e,"delete"),w({indexKeys:R(d,f),key:e,op:"delete",table:d}),X(d,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:f,table:d}),await k({id:e,op:"delete",table:d})}},async deleteAll(e,t){if(!i.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);const o=Math.max(1,t?.chunkSize??un),u=t?.hard===void 0?void 0:{hard:t.hard},h=se(e)?void 0:e;let f=0;return await B(async()=>{for(;;){const l=(await P.findMany(e,{limit:o})).page.map(p=>String(p._id));if(l.length===0)break;for(const p of l)await P.delete(p,h,u),f+=1;if(l.length<o)break}}),{deleted:f}},async deleteMany(e,t,o){le(e.length,t?.limit,"deleteMany");for(const u of e)await P.delete(u,o);return{deleted:e.length}},async deleteWhere(e,t,o){const f=(await(K(e,"deleteWhere")??P).findMany(e,{where:t})).page.map(d=>String(d._id));if(le(f.length,o?.limit,"deleteWhere"),P.deleteMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return P.deleteMany(f,o)},async findFirst(e,t={}){return(await P.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const o=await P.findFirst(e,t);if(o===null)throw new Qn(`findFirstOrThrow: no "${e}" document matched`);return o},async findMany(e,t={}){const o=K(e,"findMany");if(o)return D(e,O),o.findMany(e,t);const u=i.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const h=!t.where&&!t.baseWhere;h?D(e,O):D(e);const{limit:f,orderKeys:d,statement:l}=await Ct(e,u,t,D),p=he(c,l.text,...l.params).toArray();h&&!F&&M?.recordRead(p.length);const A=[];for(const U of p){const v=ve(U);v&&(A.push(v),!h&&typeof v._id=="string"&&D(e,v._id))}if(f===void 0)return t.with&&await Ot({groupedCounter:_t,fetcher:ze,parents:A,...Ht(t),schema:i,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:qt(A,t.select,t.with)};const E=A.length>f,T=E?A.slice(0,f):A,m=T.at(-1);return t.with&&await Ot({fetcher:ze,groupedCounter:_t,parents:T,...Ht(t),schema:i,tableName:e,with:t.with}),{continueCursor:E&&m&&t.omitContinueCursor!==!0?Ge(m,d):null,isDone:!E,page:qt(T,t.select,t.with)}},async explain(e,t={}){const o=K(e,"explain");if(o)return o.explain(e,t);const u=i.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const{statement:h}=await Ct(e,u,t,()=>{}),f=he(c,`EXPLAIN QUERY PLAN ${h.text}`,...h.params).toArray();return{params:h.params,plan:f.map(d=>String(d.detail)),sql:h.text}},async get(e,t){const o=ee(e,t);if(!o){const u=_e(t);return u?u.get(e,t):null}return D(o.tableName,e),o.row},async lookupById(e,t){const o=ee(e,t);return o?(D(o.tableName,e),{row:o.row,tableName:o.tableName}):null},async groupBy(e,t){const o=K(e,"groupBy");if(o)return D(e,O),o.groupBy(e,t);const u=i.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);D(e,O);const h=t.agg??{op:"count"};if(We(h.op),h.op!=="count"&&!h.field)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const f=Te(u.softDeleteMode,void 0),d=N(N(t.baseWhere,t.where),f),l=await xe(d,e,t.relationBaseWhere),p=l!==d;if(u.aggregateIndexes&&!t.baseWhere&&!p){const v=Cn(u.aggregateIndexes,h.op,h.field,t.by,t.where),H=v===void 0?0:Object.keys(v.partial).length,te=v?.index.by?.length??0;if(v&&(H===0||H===te)){Ye(e,v.index);const z=Ze(e,v.index.name),V=Object.keys(v.partial),ae=[];if(V.length===(v.index.by??[]).length&&V.length>0){const Le=et(v.index.by??[],v.partial),Fe=G(c,a`SELECT ${Be} AS value, ${rt} AS count FROM ${a.identifier(z)} WHERE ${Pe} = ${Le}`).toArray();return Fe.length>0&&ae.push({key:{...v.partial},value:tt(h.op,Fe[0])}),ae}const _n=G(c,a`SELECT ${Pe} AS key, ${Be} AS value, ${rt} AS count FROM ${a.identifier(z)}`).toArray();for(const Le of _n){const Fe=vn(JSON.parse(Le.key));ae.push({key:Fe,value:tt(h.op,Le)})}return ae}}for(const v of[...t.by,h.field]){if(v===void 0)continue;const H=v===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${v}" } })`:`groupBy(${e}, { by: [..."${v}"] })`;zt(u,v,H)}const A=Y(l,ue),E=t.by.map(v=>a`${fe(v)} AS ${a.identifier(v)}`);if(h.op==="count")E.push(a`COUNT(*) AS value`);else{const{field:v}=h;if(v===void 0)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);E.push(a`${a.raw(We(h.op))}(${fe(v)}) AS value`)}let T=a`SELECT ${a.join(E,a`, `)} FROM ${a.identifier(e)}`;A&&(T=a`${T} WHERE ${A}`),T=a`${T} GROUP BY ${a.join(t.by.map(v=>fe(v)),a`, `)}`;const m=G(c,T).toArray(),U=[];for(const v of m){const H={};for(const z of t.by)H[z]=Pn(u.shape[z],v[z]??null);const{value:te}=v;U.push({key:H,value:te==null?null:Number(te)})}return U},async insert(e,t,o){const u=K(e,"insert");if(u)return yt(u,e,t,o,!0);const h=i.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);const f=Xt(h,t,ye);it(h,f);let d;o?.clientId!==void 0?(zr(o.clientId),d=o.clientId):o?.allowExplicitId&&typeof f._id=="string"?d=f._id:d=oe();const l=o?.allowExplicitId&&typeof f._creationTime=="number"?f._creationTime:ne(),p={...f,...I(e),_creationTime:l,_id:d};return X(e,"before","insert")&&await Z("before","insert",{doc:{...p},id:d,op:"insert",table:e}),Ee(e),me(e),lt(c,e,Hr(e),[d,l,de(p)]),Tt(e,d,p),X(e,"after","insert")&&await Z("after","insert",{doc:p,id:d,op:"insert",table:e}),await k({doc:p,id:d,op:"insert",table:e}),d},async insertManyUnsafe(e,t,o){if(le(t.length,o?.limit,"insertManyUnsafe"),t.length===0)return[];const u=K(e,"insert");if(u){const l=[];for(const p of t)b(p);for(const p of t){const A=await u.insert(e,p,{allowExplicitId:o?.allowExplicitId});w({key:A,op:"insert",row:{...p,_id:A},table:e}),l.push(A)}return l}const h=i.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);Ee(e),me(e);const f=[];for(let l=0;l<t.length;l+=Ue)f.push(I(e));const d=t.map((l,p)=>{const A=Xt(h,l,ye),E=o?.allowExplicitId===!0&&typeof A._id=="string"?A._id:oe(),T=o?.allowExplicitId===!0&&typeof A._creationTime=="number"?A._creationTime:ne(),m={...A,...f[Math.floor(p/Ue)],_creationTime:T,_id:E};return{creationTime:T,document:m,id:E}});for(const l of d)b(l.document);for(let l=0;l<d.length;l+=Ue){const p=a.join(d.slice(l,l+Ue).map(E=>a`(${E.id}, ${E.creationTime}, ${de(E.document)})`),a`, `),A=sn("sqlite",a`INSERT INTO ${a.identifier(e)} (id, _creationTime, ${a.identifier(re)}) VALUES ${p}`);lt(c,e,A.sql,A.params)}for(const{document:l,id:p}of d)Tt(e,p,l),await x({doc:l,id:p,op:"insert",table:e});return d.map(l=>l.id)},async insertMany(e,t,o){le(t.length,o?.limit,"insertMany");const u=o?.skipDuplicates===!0,h=[],f=K(e,"insert");if(f)for(const l of t)b(l);const d=async l=>f?yt(f,e,l,void 0,!1):P.insert(e,l);for(const l of t)try{h.push(await d(l))}catch(p){if(u&&p instanceof ce&&p.kind==="unique")h.push(null);else throw p}return h},normalizeId(e,t){return Yt(i,e,t)},async patch(e,t,o,u){const h=ee(e,o);if(!h){const T=_e(o);if(T){b(t),await T.patch(e,t,o,u);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const{docJson:f,row:d,tableName:l}=h,p=i.tables[l];if(!p)throw new y("INTERNAL",`unknown table: ${l}`);if(D(l,e),en("patch",t),pt(l,e,t,d)){r?.({fields:Object.keys(Oe(t)),id:e,table:l});return}const A=Vn(p,t,d),E={...d,...Oe(A),...I(l),_id:e};ct(p,A,E,ye),Jn(u,d,E),it(p,E,!0),X(l,"before","update")&&await Z("before","update",{doc:{...E},id:e,op:"update",previous:d,table:l}),Ee(l),me(l),He(c,l,Nt(l),[de(E),e,f]),ke(l,e,E,d),De(l,e,E),Me(l,d,E),Se(l,e,d,E),Q?.invalidate(l,e,R(l,d,E)),$e(l,e,"update",E),w({indexKeys:R(l,d,E),key:e,op:"update",row:E,table:l}),X(l,"after","update")&&await Z("after","update",{doc:E,id:e,op:"update",previous:d,table:l}),await k({doc:E,id:e,op:"update",table:l})},async patchIf(e,t,o){const u=K(e,"patchIf");if(u){if(u.patchIf===void 0)throw new y("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);return b(o.patch),u.patchIf(e,t,o)}if(!i.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);for(let h=1;h<=Zt;h+=1){const f=await mn(e,t,o,h<Zt,d=>P.patch(t,d,e,{verify:o.verify}));if(f!==void 0)return f}throw new ce(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,o){le(e.length,t?.limit,"patchMany");for(const u of e)await P.patch(u.id,u.patch,o);return{patched:e.length}},async patchWhere(e,t,o){const f=(await(K(e,"patchWhere")??P).findMany(e,{where:t.where})).page.map(d=>({id:String(d._id),patch:t.patch}));if(le(f.length,o?.limit,"patchWhere"),P.patchMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await P.patchMany(f,o),{patched:f.length}},async related(e,t){return ur(P,_,e,t)},relationEdges:_,deleteRereadTables:C,relationWrites:S,query(e){const t=K(e,"query");return t?(D(e,O),t.query(e)):wn(c,i,e,$,o=>{o?pe(o):D(e,O)},o=>{F||M?.recordRead(o)})},async rank(e,t,o){const u=K(e,"rank");if(u)return D(e,O),u.rank(e,t,o);$(e,t,"rank");const h=i.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);const f=h.rankIndexes?.find(V=>V.name===t);if(!f)throw new y("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(vt(e,h,f),o.restrictsCounts)throw new nt(e);D(e,O),Xe(e,f);const d=typeof o.row=="string"?o.row:o.row._id;if(!d)return null;const l=Wt(e,f.name),p=f.sortBy.map((V,ae)=>Bt(ae)),A=p.map(V=>Ce(V)).join(", "),E=G(c,a`SELECT ${a.identifier("__partition__")}, ${a.raw(A)} FROM ${a.identifier(l)} WHERE ${a.identifier("__id__")} = ${d}`).toArray(),[T]=E;if(T===void 0)return null;let m=T.__partition__;const U=N(o.baseWhere,o.where);ot(U,i,e,"rank");const v=nr(f,U);if(v){const V=rr(f.partitionBy??[],v);if(V!==m)return null;m=V}const H=p.map(V=>T[V]),{before:te,total:z}=nn(c,l,p,f.sortBy,m,H,d);return{position:te+1,total:z}},async rankBefore(e,t,o){if(se(e))throw new y("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const u=i.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const h=u.rankIndexes?.find(p=>p.name===t);if(!h)throw new y("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(o.restrictsCounts)throw new nt(e);D(e,O),Xe(e,h);const f=Wt(e,h.name),d=h.sortBy.map((p,A)=>Bt(A)),l=h.sortBy.map((p,A)=>Ie(o.sortValues[A]??null));return nn(c,f,d,h.sortBy,o.partitionKey,l,o.rowId)},async rankPage(e,t,o={}){ot(N(o.baseWhere,o.where),i,e,"rankPage");const u=K(e,"rankPage");if(u)return D(e,O),u.rankPage(e,t,o);$(e,t,"rank");const{continueCursor:h,hasMore:f,rows:d}=Mt(It,e,t,o);return{continueCursor:h,isDone:!f,page:d.map(l=>l.doc)}},async rankPageRows(e,t,o={}){ot(N(o.baseWhere,o.where),i,e,"rankPage"),$(e,t,"rank");const{directions:u,hasMore:h,rows:f}=Mt(It,e,t,o);return{directions:u,hasMore:h,rows:f}},async restore(e,t){const o=ee(e,t);if(!o){const f=_e(t);if(f?.restore){await f.restore(e,t);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const u=i.tables[o.tableName]?.softDeleteMode?.field;if(!u)throw new y("INTERNAL",`ctx.db.restore: table "${o.tableName}" is not a .softDelete() table`);const h=o.row[u]!==null&&o.row[u]!==void 0;await P.patch(e,{[u]:null},t),h&&Se(o.tableName,e,void 0,o.row)},async replace(e,t,o,u){const h=ee(e,o);if(!h){const U=_e(o);if(U){b(t),await U.replace(e,t,o,u);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const{docJson:f,row:d,tableName:l}=h,p=i.tables[l];if(!p)throw new y("INTERNAL",`unknown table: ${l}`);en("replace",t);const A=u?.allowExplicitId&&typeof t._creationTime=="number"?t._creationTime:void 0,E=typeof d._creationTime=="number"?d._creationTime:void 0,T=A??E??ne(),m={...t,...I(l),_creationTime:T,_id:e};ct(p,t,m,ye),it(p,m),X(l,"before","update")&&await Z("before","update",{doc:{...m},id:e,op:"update",previous:d,table:l}),Ee(l),me(l),He(c,l,Gr(l),[T,de(m),e,f]),ke(l,e,m,d),De(l,e,m),Me(l,d,m),Se(l,e,d,m),Q?.invalidate(l,e,R(l,d,m)),$e(l,e,"update",m),w({indexKeys:R(l,d,m),key:e,op:"update",row:m,table:l}),X(l,"after","update")&&await Z("after","update",{doc:m,id:e,op:"update",previous:d,table:l}),await k({doc:m,id:e,op:"update",table:l})},async wipeShard(e){const t=new Set(e?.exclude),o=e?.tables,u=Object.entries(i.tables).filter(([l,p])=>t.has(l)||o!==void 0&&!o.includes(l)?!1:p.shardMode?.kind!=="global").map(([l])=>l);if(o!==void 0){for(const l of o)if(!i.tables[l])throw new y("INTERNAL",`wipeShard: unknown table: ${l}`)}const h={};let f=0;const{deleteAll:d}=P;if(d===void 0)throw new y("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of u){const p=await d(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[l]=p.deleted,f+=p.deleted}return{deleted:f,tables:h}}},Sn={db:P,scheduler:ge};return n.enforceRls===!0?yr(P,i,(e,t)=>ee(e,t)?.tableName,(e,t)=>yn(e,t),_):P};export{ai as CDC_LOG_TABLE,bi as IDEMPOTENCY_TABLE,ao as NotUniqueError,Ai as advanceClientWatermark,di as applyCdcChanges,en as assertNoExplicitUndefined,zr as assertValidClientId,oi as backfillAggregateIndexes,ii as backfillRankIndexes,si as backfillSearchIndexes,li as bumpCdcEpoch,ui as cdcCanVouchFor,fi as cdcForkedError,hi as cdcSeqLeavingRows,wi as cdcTouchesTables,pi as cdcTrimmedError,gi as compactCdcDocs,ti as createShardCtxDb,yi as cursorBelowRetainedFloor,Ii as migrateClientWatermark,$i as minCdcReplayableSeq,Ei as minCdcSeq,Yt as normalizeIdStructurally,mi as readCdcChangeKeys,Si as readCdcChanges,_i as readCdcCursor,Ri as readCdcEpoch,Ci as readClientWatermark,Mi as readIdempotent,Fi as runShardMigrations,Wi as selectShapeMembers,Bi as selectShapeRows,Oe as stripReservedPatchFields,Ti as trimCdcChanges,Di as trimIdempotent,ki as writeIdempotent};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as s}from"drizzle-orm";import{matchesStaticWhere as f}from"./AGGREGATE_SQL_FUNCTION-
|
|
1
|
+
import{sql as s}from"drizzle-orm";import{matchesStaticWhere as f}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{compareStrings as l}from"./aggregateTableName-B_CtIQCS.mjs";import{serializeSqlValue as d}from"./serializeSqlValue-DeoBMpZ2.mjs";const a=Symbol("not-resolvable"),m=r=>{if(r!==null&&typeof r=="object"&&!Array.isArray(r)){const t=Object.keys(r);return t.length===1&&t[0]==="eq"?r.eq:a}return r},y=(r,t)=>{if(r.length===0)return"";const e={};for(const n of r.toSorted(l))e[n]=t[n]??null;return JSON.stringify(e)},k="__id__",N=r=>`__sort_k${String(r)}__`,h=(r,t)=>{const e=r.partitionBy??[],n=t??{};for(const o of Object.keys(n))if(o==="AND"||o==="OR"||o==="NOT")return;const i={};for(const o of e)if(o in n){const c=m(n[o]);if(c===a)return;i[o]=c}else if(r.where&&o in r.where)i[o]=r.where[o];else return;return i},O=(r,t)=>`${r}__rank_${t}`,$=(r,t)=>({partitionKey:y(r.partitionBy??[],t),rowId:t._id,sortValues:r.sortBy.map(e=>d(t[e.field]??null))}),K=(r,t,e,n)=>{const i=e!=="desc"===n;if(t==null)return i?s`${s.identifier(r)} IS NOT NULL`:void 0;const o=s`${s.identifier(r)} ${s.raw(i?">":"<")} ${t}`;return i?o:s`(${o} OR ${s.identifier(r)} IS NULL)`},R=f;export{k as RANK_TIEBREAK,y as encodePartitionKey,R as matchesRankStaticWhere,$ as rankKeyFromDoc,K as rankPivotConditionSql,O as rankTableName,h as resolveRankPartition,N as sortColumnName};
|
package/dist/packem_shared/{RELATED_DEFAULT_LIMIT-Me5elP-K.mjs → RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as h}from"@lunora/errors";import{mergeWhere as I}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{decodeCursor as S,CURSOR_PREFIX as v,toBase64 as B}from"./CURSOR_PREFIX-
|
|
1
|
+
import{LunoraError as h}from"@lunora/errors";import{mergeWhere as I}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{decodeCursor as S,CURSOR_PREFIX as v,toBase64 as B}from"./CURSOR_PREFIX-6offuG6M.mjs";const O=4,C=1,L=50,$=200,T=1e4,x=.5,D=t=>{if(t.kind==="id"){const e=t._meta?.tableName;return typeof e=="string"&&e.length>0?{array:!1,targetTable:e}:void 0}if(t.kind!=="array"&&t.kind!=="optional")return;const n=t._meta?.inner,r=n===void 0?void 0:D(n);if(r!==void 0)return{array:r.array||t.kind==="array",targetTable:r.targetTable}},j=t=>{const n=[];for(const[r,e]of Object.entries(t.tables))for(const[s,o]of Object.entries(e.shape)){const a=D(o);a===void 0||t.tables[a.targetTable]===void 0||n.push({array:a.array,column:s,name:`${r}.${s}`,sourceTable:r,targetTable:a.targetTable})}return n},U=t=>v+B(JSON.stringify([t])),M=t=>{const[n]=S(t);if(typeof n!="number"||!Number.isInteger(n)||n<0)throw new h("BAD_REQUEST","invalid cursor");if(n>T)throw new h("BAD_REQUEST",`ctx.db.related: cursor offset ${String(n)} exceeds the maximum of ${String(T)} — narrow the walk with \`edges\` or \`direction\` instead of paging past it`);return n},k=(t,n,r,e)=>{if(t===void 0)return n;if(!Number.isInteger(t)||t<1||t>r)throw new h("BAD_REQUEST",`ctx.db.related: \`${e}\` must be an integer between 1 and ${String(r)}, got ${String(t)}`);return t},N=(t,n)=>{if(n===void 0)return[...t];const r=new Set(t.map(o=>o.name)),e=n.filter(o=>!r.has(o));if(e.length>0)throw new h("BAD_REQUEST",`ctx.db.related: unknown edge ${e.length===1?"name":"names"}: ${e.join(", ")}`);const s=new Set(n);return t.filter(o=>s.has(o.name))},W=(t,n)=>{const r=t[n.column];return n.array?Array.isArray(r)?r.filter(e=>typeof e=="string"&&e.length>0):[]:typeof r=="string"&&r.length>0?[r]:[]},A=async(t,n,r,e)=>{const s=await t.findMany(n,{limit:e.limit,omitContinueCursor:!0,where:I(r,e.relationBaseWhere?.(n))??r});return e.mask?.(n,s.page)??s.page},F={in:{keyColumn:t=>t.column,keysOf:(t,n)=>n.array||t.table!==n.targetTable?[]:[t.id],skipVisitedKeys:!1,table:t=>t.sourceTable},out:{keyColumn:()=>"_id",keysOf:(t,n)=>t.table===n.sourceTable?W(t.document,n):[],skipVisitedKeys:!0,table:t=>t.targetTable}},_=async(t,n,r,e,s)=>{const o=F[s],a=o.keyColumn(r),l=o.table(r),u=new Map;for(const c of n)for(const i of o.keysOf(c,r))!u.has(i)&&!(o.skipVisitedKeys&&e.visited.has(i))&&u.set(i,c);if(u.size===0)return[];const f=await A(t,l,{[a]:{in:[...u.keys()]}},e),m=[];for(const c of f){const i=c._id,g=c[a],d=typeof g=="string"?u.get(g):void 0;typeof i!="string"||d===void 0||e.visited.has(i)||(e.visited.add(i),m.push({document:c,id:i,path:[...d.path,r.name],pathIds:[...d.pathIds,i],table:l}))}return m},Q=async(t,n,r,e)=>{const s=[],o=()=>e.budget-s.length,a=()=>({limit:o(),mask:e.mask,relationBaseWhere:e.relationBaseWhere,visited:e.visited});for(const l of r)e.direction!=="in"&&o()>0&&s.push(...await _(t,n,l,a(),"out")),e.direction!=="out"&&o()>0&&s.push(...await _(t,n,l,a(),"in"));return s},H=async(t,n)=>{const r=n._id;if(typeof r=="string"&&r.length>0){const o=await t.lookupById?.(r);if(!o)throw new h("BAD_REQUEST","ctx.db.related: could not resolve the start document's table from its `_id` — pass `{ table, id }` instead");return{id:r,table:o.tableName}}const{id:e,table:s}=n;if(typeof s!="string"||s.length===0||typeof e!="string"||e.length===0)throw new h("BAD_REQUEST","ctx.db.related: `start` must be a loaded document or `{ table, id }`");return{id:e,table:s}},V=async(t,n,r,e={})=>{const s=k(e.depth,C,O,"depth"),o=k(e.limit,L,$,"limit"),a=e.cursor?M(e.cursor):0,l=e.direction??"both",u=N(n,e.edges),{id:f,table:m}=await H(t,r),[c]=await A(t,m,{_id:f},{limit:1,mask:e.relationMask,relationBaseWhere:e.relationBaseWhere,visited:new Set});if(c===void 0)throw new h("NOT_FOUND",`ctx.db.related: no "${m}" row with id ${f}`);const i=a+o+1,g=new Set([f]),d=[];let w=[{document:c,id:f,path:[],pathIds:[f],table:m}];for(let b=1;b<=s&&w.length>0&&d.length<i;b+=1){const p=await Q(t,w,u,{budget:i-d.length,direction:l,mask:e.relationMask,relationBaseWhere:e.relationBaseWhere,visited:g}),R=x**(b-1);for(const y of p)d.push({depth:b,document:y.document,path:y.path,pathIds:y.pathIds,score:R,table:y.table});w=p}const E=d.length<=a+o;return{continueCursor:E?null:U(a+o),isDone:E,nodes:d.slice(a,a+o)}};export{L as RELATED_DEFAULT_LIMIT,x as RELATED_DEPTH_DECAY,O as RELATED_MAX_DEPTH,$ as RELATED_MAX_LIMIT,T as RELATED_MAX_OFFSET,j as deriveRelationEdges,V as findRelated};
|
package/dist/packem_shared/{RLS_UNWRAP_SYMBOL-BV39QRFd.mjs → RLS_UNWRAP_SYMBOL-DQt9luIF.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as R}from"@lunora/errors";import{findRelated as m}from"./RELATED_DEFAULT_LIMIT-
|
|
1
|
+
import{LunoraError as R}from"@lunora/errors";import{findRelated as m}from"./RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";const M=Symbol.for("lunora.ctxdb.rls-unwrap");class S extends R{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 b=o=>Object.entries(o.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n),E=(o,n,c)=>{const d=n?.tables,u=new Set(n?.exclude);for(const r of o)(d===void 0||d.includes(r))&&!u.has(r)&&c(r)},y={aggregate:"loop-gated",asId:"ungated",assertPatchAllowed:"id-gated",cdcChangedTables:"ungated",count:"loop-gated",delete:"id-gated",deleteAll:"loop-gated",deleteMany:"id-gated",deleteWhere:"inline-table-gated",explain:"loop-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",patchIf:"loop-gated",patchMany:"id-gated",patchWhere:"inline-table-gated",query:"loop-gated",rank:"loop-gated",rankBefore:"loop-gated",rankPage:"loop-gated",rankPageRows:"loop-gated",related:"rebound",relationEdges:"ungated",deleteRereadTables:"ungated",relationWrites:"ungated",replace:"id-gated",restore:"id-gated",system:"ungated",wipeShard:"sweep-gated"},W=Object.entries(y).filter(([,o])=>o==="loop-gated").map(([o])=>o),I={related:(o,n)=>(...c)=>{const[d,u]=c;return m(o,n,d,u)}},O=Object.entries(y).filter(([,o])=>o==="rebound").map(([o])=>o),k=(o,n,c)=>{for(const d of O)typeof n[d]=="function"&&(o[d]=I[d](o,c))},P=(o,n,c,d,u=[])=>{if(n.rlsMode!=="required")return o;const r=o,p=e=>{const t=n.tables[e];return t!==void 0&&t.isPublic!==!0},i=e=>{if(p(e))throw new S(e)},l=async(e,t)=>{if(t!==void 0){i(t);return}const a=await c(e);a!==void 0&&i(a)},f=async(e,t)=>{if(t!==void 0){i(t);return}if(!d){for(const s of e)await l(s,t);return}const a=await d([...new Set(e)],t);for(const s of e){const h=a.get(s);h!==void 0&&i(h)}},g={...o,delete:async(e,t,a)=>(await l(e,t),r.delete(e,t,a)),deleteMany:async(e,t,a)=>(await f(e,a),r.deleteMany(e,t,a)),deleteWhere:r.deleteWhere?async(e,t,a)=>(i(e),await r.deleteWhere?.(e,t,a)):void 0,get:async(e,t)=>(await l(e,t),r.get(e,t)),lookupById:async(e,t)=>(await l(e,t),r.lookupById?.(e,t)??null),patch:async(e,t,a,s)=>(await l(e,a),r.patch(e,t,a,s)),patchMany:async(e,t,a)=>(await f(e.map(s=>s.id),a),r.patchMany(e,t,a)),assertPatchAllowed:async(e,t)=>(await l(e,t),r.assertPatchAllowed?.(e,t)),patchWhere:r.patchWhere?async(e,t,a)=>(i(e),await r.patchWhere?.(e,t,a)):void 0,replace:async(e,t,a,s)=>(await l(e,a),r.replace(e,t,a,s)),restore:async(e,t)=>(await l(e,t),r.restore?.(e,t))},w=r;for(const e of W){const t=w[e];typeof t=="function"&&(g[e]=(a,...s)=>(i(a),t.call(r,a,...s)))}if(k(g,r,u),r.wipeShard){const{wipeShard:e}=r;g.wipeShard=t=>(E(b(n),t,i),e.call(r,t))}return Object.defineProperty(g,M,{configurable:!0,enumerable:!1,value:o,writable:!1}),g};export{W as LOOP_GATED_METHODS,M as RLS_UNWRAP_SYMBOL,S as RlsRequiredError,y as WRITER_METHOD_GATING,P as guardWriter};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{stableWireKey as y}from"@lunora/wire";import{stableStringify as S,stableWireKey as M}from"@lunora/wire";import{depKey as u,SCAN_DEP as p}from"./SCAN_DEP-D7qE3iUe.mjs";import{e as m}from"./estimate-bytes-_k74s6LZ.mjs";import{keysTouchRanges as x}from"./buildIndexRange-DQ3eWAGd.mjs";const l=(o,e,s)=>{let t=o.get(e);return t===void 0&&(t=s(),o.set(e,t)),t},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(e={}){this.maxEntries=e.maxEntries??v,this.maxBytes=e.maxBytes??E,this.now=e.now??(()=>(this.monotonic+=1,this.monotonic))}async run(e,s,t,i=()=>[]){const n=this.entries.get(e);if(n)return this.hits+=1,n.lastUsed=this.now(),this.entries.delete(e),this.entries.set(e,n),n.result;this.misses+=1;const c=this.generation,a=await t();if(this.generation!==c)return a;const h=m(a);if(h===void 0)return a;const f=i(),b={bytes:h,deps:s,ranges:f,lastUsed:this.now(),result:a,subscribers:new Set},d=this.entries.get(e);if(d){this.dropEntry(e,d);for(const r of d.subscribers)b.subscribers.add(r)}this.entries.set(e,b),this.totalBytes+=h;for(const r of s)l(this.tableIndex,r,()=>new Set).add(e);for(const r of f){const g=l(this.rangeIndex,r.table,()=>new Map);l(g,r,()=>new Set).add(e)}return this.evict(),a}invalidate(e,s,t){this.generation+=1;const i=[];return this.collectAndDrop(u(e,s),i),this.collectAndDrop(u(e,p),i),this.dropRangeDeps(e,t,i),i}invalidateTable(e){this.generation+=1;const s=[],t=`${e}:`;for(const i of this.tableIndex.keys())i.startsWith(t)&&this.collectAndDrop(i,s);return this.dropRangeDeps(e,void 0,s),s}subscribe(e,s){const t=this.entries.get(e);t&&t.subscribers.add(s)}unsubscribe(e,s){const t=this.entries.get(e);t&&t.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(e){const s=this.entries.get(e);return s?[...s.subscribers]:[]}stats(){return{bytes:this.totalBytes,entries:this.entries.size,evictions:this.evictions,hits:this.hits,misses:this.misses}}dropRangeDeps(e,s,t){const i=this.rangeIndex.get(e);if(!(!i||i.size===0))for(const[n,c]of i)x([n],s)&&this.dropKeys(c,t)}collectAndDrop(e,s){const t=this.tableIndex.get(e);t&&this.dropKeys(t,s)}dropKeys(e,s){for(const t of e){const i=this.entries.get(t);i&&(this.dropEntry(t,i),s.push(t))}}dropEntry(e,s){this.entries.delete(e),this.totalBytes-=s.bytes;for(const t of s.deps){const i=this.tableIndex.get(t);i&&(i.delete(e),i.size===0&&this.tableIndex.delete(t))}for(const t of s.ranges){const i=this.rangeIndex.get(t.table),n=i?.get(t);n?.delete(e),i&&n?.size===0&&(i.delete(t),i.size===0&&this.rangeIndex.delete(t.table))}}evict(){if(!(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes))for(const[e,s]of this.entries){if(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes)return;s.subscribers.size>0||(this.dropEntry(e,s),this.evictions+=1)}}}const D=(o,e,s)=>`${s??"\0anon"}\0${o}:${y(e)}`;export{A as ReactiveCache,D as reactiveCacheKey,S as stableStringify,M as stableWireKey};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{stableWireKey as o}from"@lunora/wire";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{isLunoraError as S}from"@lunora/errors";import{l as R,b as L}from"./ctx-db-search-state-CrTLPmFN.mjs";import{sql as e}from"drizzle-orm";import{readKeysetPage as _}from"./backfillAggregateIndexes-
|
|
1
|
+
import{isLunoraError as S}from"@lunora/errors";import{l as R,b as L}from"./ctx-db-search-state-CrTLPmFN.mjs";import{sql as e}from"drizzle-orm";import{readKeysetPage as _}from"./backfillAggregateIndexes-Dw4Azd33.mjs";import{runDrizzle as p}from"./runDrizzle-B2GG3IJa.mjs";import{h}from"./do-sql-DqU-17Fs.mjs";const u="__lunora_vector_backfill",m=50,k=20,w=20,N=3,O=i=>{p(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(u)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("cursor")} TEXT, ${e.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${e.identifier("profile")} TEXT, ${e.identifier("strikes")} INTEGER NOT NULL DEFAULT 0)`);try{p(i,e`ALTER TABLE ${e.identifier(u)} ADD COLUMN ${e.identifier("strikes")} INTEGER NOT NULL DEFAULT 0`)}catch{}},C=(i,o)=>{const[s]=p(i,e`SELECT ${e.identifier("strikes")} FROM ${e.identifier(u)} WHERE ${e.identifier("companion")} = ${o}`).toArray();return s?.strikes??0},$=(i,o,s,d,t,r=0)=>{const n=s??null;p(i,e`INSERT INTO ${e.identifier(u)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("strikes")}) VALUES (${o}, ${n}, ${d?1:0}, ${t}, ${r}) ON CONFLICT (${e.identifier("companion")}) DO UPDATE SET ${e.identifier("cursor")} = excluded.${e.identifier("cursor")}, ${e.identifier("done")} = excluded.${e.identifier("done")}, ${e.identifier("profile")} = excluded.${e.identifier("profile")}, ${e.identifier("strikes")} = excluded.${e.identifier("strikes")}`)},A=(i,o,s)=>{const d=_(i,o,s,m+1),t={documents:[],lastId:s,more:d.length>m,unparseable:[]};for(const r of d.slice(0,m)){if(typeof r.id!="string")continue;t.lastId=r.id;const n=h(r);n?t.documents.push({doc:n,id:t.lastId}):t.unparseable.push(t.lastId)}return t},D=(i,o,s,d,t)=>{const r=t instanceof Error?t.message:String(t),n=L(i,u,o),a=n.profile===d&&n.cursor===s?C(i,o):0;if(S(t)&&t.code==="SERVICE_UNAVAILABLE")return a>0&&$(i,o,s,!1,d,0),{error:r};const f=a+1;if(f<N)return $(i,o,s,!1,d,f),{error:r};const c=A(i,o,s),l=[...c.documents.map(E=>E.id),...c.unparseable];return console.warn(`[@lunora/shard-engine] vector backfill: a page of "${o}" failed ${String(f)} times in a row; its ${String(l.length)} row(s) are recorded as failed:`,t),{failedIds:l,page:c}},F=async(i,o,s,d,t)=>{const{profile:r,table:n}=o;try{const{failures:a,page:f}=await t(()=>A(i,n,s),async c=>({failures:await d(n,c.documents),page:c}));return a.length>0&&console.warn(`[@lunora/shard-engine] vector backfill: ${String(a.length)} row(s) of "${n}" could not be indexed:`,a),{failedIds:[...f.unparseable,...a.map(c=>c.id)],page:f}}catch(a){return D(i,n,s,r,a)}},y=async(i,o,s,d)=>{if(O(i),d.restart===!0)for(const{profile:n,table:a}of o)$(i,a,void 0,!1,n);const t=Math.min(d.maxPages??1,k),r={done:!1,failed:0,failedIds:[],pages:0,rows:0};for(const{profile:n,table:a}of o){const f=R(L(i,u,a),n);let{cursor:c}=f,l=f.finished;for(;!l;){if(r.pages>=t)return r;const E=await F(i,{profile:n,table:a},c,s,d.ordered);if("error"in E)return{...r,error:E.error};const{failedIds:g,page:T}=E,I=T.documents.length+T.unparseable.length;r.pages+=I>0?1:0,r.rows+=I,r.failed+=g.length,r.failedIds=[...r.failedIds,...g].slice(0,w),c=T.lastId,l=!T.more,$(i,a,c,l,n)}}return{...r,done:!0}};export{k as VECTOR_BACKFILL_MAX_PAGES,m as VECTOR_BACKFILL_PAGE_ROWS,y as backfillVectorIndexes};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";import{encodeWire as i}from"@lunora/wire";const a=BigInt(Number.MAX_SAFE_INTEGER),c=(e,t)=>e<t?-1:e>t?1:0,s=(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{s as aggregateTableName,l as coerceAggregateNumber,c as compareStrings,A as encodeAggregateKey,v as foldAggregateTally,d as readAggregateValue};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as S}from"@lunora/errors";import{applySelect as x}from"./CURSOR_PREFIX-
|
|
1
|
+
import{LunoraError as S}from"@lunora/errors";import{applySelect as x}from"./CURSOR_PREFIX-6offuG6M.mjs";const L=Symbol.for("lunora.relations.fanOutBudget"),q=c=>({fanOutBudget:c[L],relationBaseWhere:c.relationBaseWhere,relationMask:c.relationMask}),I=(c,r)=>r.select?x(c,r.select,r.with):c,J=async(c,r,i,u,s)=>{const d=await Promise.all(u.map(async f=>{const y=s?{AND:[{[i]:f},s]}:{[i]:f};return[f,await c(r,y)]}));return new Map(d)},P=32,R=1e4,U=(c,r,i)=>{const u=new Map;for(const s of c)for(const d of i(s)){const f=d[r],y=u.get(f);y?y.push(d):u.set(f,[d])}return u},W=(c,r)=>({...c,[L]:r}),G=(c,r)=>{const i=new Map;for(const[s,d]of c)for(const f of d){const y=i.get(f);y?y.push(s):i.set(f,[s])}const u=new Map;for(const s of r)for(const d of i.get(s._id)??[]){const f=u.get(d);f?f.push(s):u.set(d,[s])}return u},N=(c,r)=>{const i=new Set;for(const u of c){const s=u[r];s!=null&&i.add(s)}return[...i]},Q=async c=>{const{groupedCounter:r,fanOutBudget:i,fetcher:u,parents:s,relationBaseWhere:d,relationMask:f,schema:y,tableName:M,with:B}=c,b=i??{remaining:P},k=(t,e)=>f?.(t,e)??e;if(s.length===0)return;const _=y.tables[M];if(!_)throw new S("INTERNAL",`unknown table: ${M}`);const v=_.relationMap??{},T=(t,e)=>{const n=a=>y.tables[a]?.shardMode?.kind??"root";return n(t)===n(e)&&n(t)!=="shardBy"},A=t=>{const e=v[t];if(!e)throw new S("INTERNAL",`unknown relation "${t}" on table "${M}"`);return e},j=async(t,e,n)=>{const a=N(s,e.field);if(a.length===0){for(const l of s)l[t]=null;return}const{page:o}=await u(e.table,W({baseWhere:d?.(e.table),relationBaseWhere:d,relationMask:f,where:{[e.references]:{in:a}},with:n.with},b)),w=new Map;for(const l of k(e.table,o))w.set(l[e.references],l);for(const l of s){const g=w.get(l[e.field]);l[t]=g?I([g],n)[0]??null:null}},O=async(t,e,n,a)=>{const{page:o}=await u(t,W({baseWhere:d?.(t),limit:a,orderBy:e.orderBy,relationBaseWhere:d,relationMask:f,where:e.where?{AND:[e.where,n]}:n,with:e.with},b));return o},D=(t,e,n,a,o)=>{for(const w of s){const l=o.get(w[a])??[];w[t]=I(n===void 0?l:l.slice(0,n),e)}},E=async(t,e,n)=>{const a=N(s,e.references);if(a.length===0){for(const h of s)h[t]=[];return}const o=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0,w=(h,m)=>O(e.table,n,h,m);if(o===0){for(const h of s)h[t]=[];return}const l=o!==void 0&&a.length<=b.remaining;l&&(b.remaining-=a.length);const g=l?await Promise.all(a.map(async h=>w({[e.field]:h},o))):[await w({[e.field]:{in:a}},void 0)],p=U(g,e.field,h=>k(e.table,h));D(t,n,o,e.references,p)},$=async t=>{const{from:e,table:n,to:a}=t.through,o=new Map,w=N(s,"_id");if(w.length===0)return o;const l=await O(n,{},{[e]:{in:w}},R+1);if(l.length>R)throw new S("INTERNAL",`loading "${M}" relations through "${n}" read more than ${String(R)} join rows for one page; load fewer ${M} rows at a time`);for(const g of k(n,l)){const p=g[e],h=g[a];if(p==null||h===null||h===void 0)continue;const m=o.get(p);m?m.add(h):o.set(p,new Set([h]))}return o},V=async(t,e,n)=>{const a=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0,o=a===0?new Map:await $(e),w=(g,p)=>O(e.table,n,{_id:{in:[...g]}},p);let l=new Map;if(o.size>0&&a!==void 0&&o.size<=b.remaining){b.remaining-=o.size;const g=[...o.keys()],p=await Promise.all([...o.values()].map(async h=>w(h,a)));l=new Map(g.map((h,m)=>[h,k(e.table,p[m]??[])]))}else if(o.size>0){const g=new Set([...o.values()].flatMap(p=>[...p]));l=G(o,k(e.table,await w(g,void 0)))}D(t,n,a,"_id",l)},C=async(t,e)=>{const n=[...e];if(n.length===0)return new Set;if(T(M,t)){const o=await r(t,"_id",n,d?.(t));return new Set(n.filter(w=>(o.get(w)??0)>0))}const a=await O(t,{},{_id:{in:n}},void 0);return new Set(a.map(o=>o._id))},F=async(t,e)=>{const n=await $(e),a=await C(e.table,new Set([...n.values()].flatMap(o=>[...o])));for(const o of s){const w=o._count??{};w[t]=[...n.get(o._id)??[]].filter(l=>a.has(l)).length,o._count=w}},z=async t=>{for(const e of Object.keys(t)){const n=A(e);if(n.through!==void 0){await F(e,n);continue}const[a,o]=n.kind==="many"?[n.field,n.references]:[n.references,n.field],w=d?.(n.table),l=N(s,o),g=l.length===0?new Map:await r(n.table,a,l,w);for(const p of s){const h=p._count??{},m=p[o];h[e]=m==null?0:g.get(m)??0,p._count=h}}};for(const[t,e]of Object.entries(B)){if(e===void 0||e===!1)continue;if(t==="_count"){await z(e);continue}const n=A(t),a=e===!0?{}:e;n.through===void 0?await(n.kind==="one"?j(t,n,a):E(t,n,a)):await V(t,n,a)}},H=async(c,r,i)=>{const{deletedId:u,deletedReference:s,findHolders:d,onCascade:f,onRestrict:y,onSetNull:M,tableName:B}=c,b=i.references==="_id"?u:s(i.references);if(b==null)return;const k=await d(r,i.field,b);if(k.length!==0){i.onDelete==="restrict"&&y(`cannot delete "${B}" row: "${r}.${i.field}" still references it`);for(const _ of k){const v=_._id;typeof v=="string"&&await(i.onDelete==="cascade"?f(r,v):M(r,v,i.field))}}},Y=async c=>{const{schema:r,tableName:i}=c;if(!r.tables[i])throw new S("INTERNAL",`unknown table: ${i}`);for(const[u,s]of Object.entries(r.tables)){const d=s.relationMap;if(d)for(const f of Object.values(d))f.kind!=="one"||f.table!==i||!f.onDelete||await H(c,u,f)}},Z=(c,r,i=!1)=>{for(const[u,s]of Object.entries(c.shape))u in r&&typeof s.parse=="function"&&(i&&r[u]===null&&s.kind==="optional"||s.parse(r[u]))};export{R as MAX_LINK_ROWS,Y as applyOnDelete,N as distinctValues,J as fanOutScalarCounts,q as relationHooks,Q as resolveWith,Z as runRowValidators};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as a}from"@lunora/errors";import{e as u}from"./effective-kind-BmG_zCAy.mjs";import{a as k,i as m,r as $,F as g,e as R,s as F}from"./json-field-path-DeJW4U9z.mjs";const d={decrement:{apply:(e,t)=>e-t,kind:"number"},divide:{apply:(e,t)=>e/t,kind:"number"},increment:{apply:(e,t)=>e+t,kind:"number"},multiply:{apply:(e,t)=>e*t,kind:"number"},toggle:{kind:"boolean"}};class s extends Error{}const w=e=>{if(!k(e))return;const t=Object.keys(e),[n]=t;if(!(t.length!==1||n===void 0||!Object.hasOwn(d,n)))return{operand:e[n],operator:n}},b=e=>w(e)!==void 0,P=(e,t,n,o)=>{const r=d[t];if(r.apply===void 0){if(n!==!0)throw new s(`patch: use { toggle: true } on "${e}".`);if(typeof o!="boolean")throw new s(`patch: cannot toggle "${e}" — its current value is ${String(o)}; set a boolean first.`);return!o}if(typeof n!="number"||!Number.isFinite(n))throw new s(`patch: "${t}" on "${e}" needs a finite number, got ${String(n)}.`);if(typeof o!="number"||!Number.isFinite(o))throw new s(`patch: cannot ${t} "${e}" — its current value is ${String(o)}; set a number first.`);if(t==="divide"&&n===0)throw new s(`patch: cannot divide "${e}" by zero.`);const i=r.apply(o,n);if(!Number.isFinite(i))throw new s(`patch: "${t}" on "${e}" overflows to ${String(i)}.`);return i},v=(e,t)=>{const n=new Set;for(const[o,r]of Object.entries(e))t(o)!==void 0&&b(r)&&n.add(o);return n},E=(e,t,n)=>{let o;for(const r of v(e,n)){const{operand:i,operator:c}=w(e[r]),f=n(r);if(d[c].kind!==f)throw new s(`patch: "${c}" does not apply to the ${String(f)} column "${r}".`);o??={...e},o[r]=P(r,c,i,t[r])}return o??e},j=new Set(["date","number","timestamp"]),l=e=>e.kind==="optional"&&e._meta?.inner!==void 0?l(e._meta.inner):e,p=e=>{const t=l(e);if(t.kind!==void 0&&j.has(t.kind))return"number";if(t.kind==="boolean")return"boolean";if(t.kind!=="union")return;const n=new Set((t._meta?.members??[]).filter(r=>u(r)!=="null").map(r=>p(r))),[o]=n;return n.size===1?o:void 0},O=e=>t=>{const n=Object.hasOwn(e.shape,t)?e.shape[t]:void 0;return n===void 0?void 0:p(n)},A=(e,t)=>v(t,O(e)),I=(e,t,n)=>{try{return E(t,n,O(e))}catch(o){throw o instanceof s?new a("VALIDATION_ERROR",o.message):o}},h=e=>{throw e instanceof g?new a("VALIDATION_ERROR",e.message):e},y=e=>{if(e===void 0)return;const t=l(e);if(t.kind==="object")return t._meta?.shape;if(t.kind!=="union")return;const n=(t._meta?.members??[]).filter(o=>u(o)!=="null");return n.length===1?y(n[0]):void 0},N=(e,t)=>{let n=e.shape[t[0]??""];for(const o of t.slice(1)){const r=y(n);n=r!==void 0&&Object.hasOwn(r,o)?r[o]:void 0}return n},_=(e,t,n)=>{let o=[];try{o=F(t)}catch(i){h(i)}const r=N(e,o);if(r===void 0)throw new a("VALIDATION_ERROR",`patch: "${t}" is not a path into an object column of this table`);if(p(r)!==void 0&&b(n))throw new a("VALIDATION_ERROR",`patch: "${t}" is nested inside a column; operators like increment apply to a top-level column only`);if(typeof r.parse=="function")try{r.parse(n)}catch(i){throw new a("VALIDATION_ERROR",`patch: "${t}" ${i instanceof Error?i.message:"is invalid"}`)}},S=(e,t,n)=>{for(const[o,r]of Object.entries(t))m(o)&&_(e,o,r);try{return R(t,n)}catch(o){return h(o)}},V=(e,t,n)=>S(e,I(e,t,n),n),x=(e,t)=>A(e,t).size>0||Object.keys(t).some(n=>m(n)),z=(e,t,n)=>{if(e?.verify!==void 0&&!e.verify(t,n))throw new a("FORBIDDEN","update denied by policy")},K=(e,t)=>{try{return $(e,t)}catch(n){return h(n)}};export{z as assertPatchAllowed,A as operatorFields,x as patchDependsOnRow,K as readPatchField,V as resolvePatch};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{isPlainObject as m,stableStringify as A,encodeWire as w,needsWireEncoding as J}from"@lunora/wire";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),c=e.byId.get(r),d=JSON.stringify(J(i)?w(i):i),a=c===void 0?void 0:JSON.stringify(c);if(a===d)continue;const f=a===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(!m(e)||!m(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(A(n(e))===A(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 c=s===""?L:s,d=JSON.stringify(c),a=[...R(r,i,c,d),...P(r,i,c,d)];return k(r,i,a)?a:void 0},B=(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)}},W=(e,t)=>{try{return e.send(t),!0}catch{return!1}},C=e=>{const{cursorSuffix:t,lastMutationId:s,nextResult:o,pageDeltas:n,previousJson:r,snapshotJson:i,subId:c,table:d}=e,a=JSON.stringify(c),f=s===void 0?"":`,"lastMutationId":${String(s)}`,g=f+t,l=`{"type":"data","id":${a},"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":${a},"delta":${x}${S?g:f}}`;if(b+=h.length,b>=l.length)return[l];v.push(h)}return v},K=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{K as awaitWsDrain,C as subscriptionFrames,B as subscriptionListDeltas,W as trySendFrame};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{m as P,c as E,l as w,r as T,a as D,w as F}from"./ctx-db-search-state-CrTLPmFN.mjs";import{S as I,c as L,g as _,d as x,e as b,a as k}from"./fts-companion-DzfEHonU.mjs";import{sql as i}from"drizzle-orm";import{ensureAggregateCompanion as y,ensureRankCompanion as B}from"./createCompanionSync-
|
|
1
|
+
import{m as P,c as E,l as w,r as T,a as D,w as F}from"./ctx-db-search-state-CrTLPmFN.mjs";import{S as I,c as L,g as _,d as x,e as b,a as k}from"./fts-companion-DzfEHonU.mjs";import{sql as i}from"drizzle-orm";import{ensureAggregateCompanion as y,ensureRankCompanion as B}from"./createCompanionSync-DhYLePyV.mjs";import{runDrizzle as p,runAll as C}from"./runDrizzle-B2GG3IJa.mjs";import{i as M,D as m,h as A}from"./do-sql-DqU-17Fs.mjs";import{sqliteInList as U}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";const v=(e,o)=>p(e,i`SELECT 1 FROM ${i.identifier(o)} LIMIT 1`).toArray().length>0,Q=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(n.shardMode?.kind!=="global")for(const t of n.aggregateIndexes??[])y(e,r,t,n.softDeleteMode?.field)},X=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(n.shardMode?.kind!=="global")for(const t of n.rankIndexes??[])B(e,r,t,n.softDeleteMode?.field)},H=(e,o,r,n)=>p(e,r===void 0?i`SELECT id, _creationTime, ${i.identifier(m)} FROM ${i.identifier(o)} ORDER BY id ASC LIMIT ${i.raw(String(n))}`:i`SELECT id, _creationTime, ${i.identifier(m)} FROM ${i.identifier(o)} WHERE id > ${r} ORDER BY id ASC LIMIT ${i.raw(String(n))}`).toArray(),h=500,O=(e,o,r)=>{const n=I(o,r.name),t=E(r),a=w(T(e,n),t);if(a.finished)return{done:!0,rows:0};const{cursor:c}=a,s=H(e,o,c,h);let f=c;for(const g of s){const{id:u}=g;if(typeof u!="string")continue;f=u;const S=A(g);C(e,S?x(n,u,b(S,r)):k(n,u))}const d=s.length<h;return F(e,n,f,d,t),{done:d,rows:s.length}},l=(e,o)=>i`${i.identifier(e)}.${i.identifier(o)}`,R=500,$=(e,o,r)=>{const n=I(o,r.name),t=p(e,L(n,R)).toArray(),a=_(t);if(a.size===0)return!0;const c=new Map;for(const s of p(e,i`SELECT ${l(o,"id")}, ${l(o,"_creationTime")}, ${l(o,m)} FROM ${i.identifier(o)} WHERE ${U(l(o,"id"),[...a.keys()],!1)}`))c.set(String(s.id),s);for(const[s,f]of a){const d=c.get(s),g=d?A(d):void 0;C(e,g?x(n,s,b(g,r),{unmappedRowids:f}):k(n,s,{unmappedRowids:f}))}return t.length<R},W=(e,o,r,n)=>{let t=0;for(;t<n&&!$(e,o,r);)t+=1;return t},Z=(e,o,r)=>{const n=I(o,r.name),t=E(r);return w(T(e,n),t).finished?!0:D(e,n)},q=(e,o,r)=>{if(M(e))for(const n of r.searchIndexes??[])$(e,o,n),!(n.staged&&v(e,o))&&O(e,o,n)},j=(e,o,r,n)=>{let t=0;for(;;){if(t>=n)return{done:!1,pages:t};const a=O(e,o,r);if(a.rows>0&&(t+=1),a.done)return{done:!0,pages:t}}},ee=(e,o,r={})=>{if(!M(e))return{done:!0,pages:0};P(e);const n=r.maxPages??Number.POSITIVE_INFINITY;let t=0;for(const[a,c]of Object.entries(o.tables))if(!(c.shardMode?.kind==="global"||!c.searchIndexes))for(const s of c.searchIndexes){if(t+=W(e,a,s,n-t),t>=n)return{done:!1,pages:t};const f=j(e,a,s,n-t);if(t+=f.pages,!f.done)return{done:!1,pages:t}}return{done:!0,pages:t}};export{Q as backfillAggregateIndexes,X as backfillRankIndexes,ee as backfillSearchIndexes,q as backfillSearchIndexesForTable,H as readKeysetPage,Z as searchIndexCoversTable};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{float64SqlKey as m}from"./BIGINT_KEY_DIGITS-
|
|
1
|
+
import{float64SqlKey as m}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";const a="!",l="",d=void 0,w=t=>{const o=new TextEncoder().encode(t);let r="";for(const e of o)r+=e.toString(16).padStart(2,"0");return r},v=t=>t===null?"0":typeof t=="number"?Number.isFinite(t)?`1${m(t)}`:d:typeof t=="string"?`2${w(t)}`:d,x=t=>{const o=[];for(const r of t){const e=v(r);if(e===d)return d;o.push(e)}return o.join(a)},E="=",h=new Set([">",">="]),y=new Set(["<","<="]),g=(t,o,r,e)=>{const i=o.comparator===E,n=h.has(o.comparator)||y.has(o.comparator);return!i&&!n||t.indexOf(o.field)!==r?!1:e===void 0?!0:!i&&e===o.field},S=(t,o,r)=>{const e={equalities:[],lowerExclusive:!1,upperExclusive:!1};let i;for(const n of o){const s=n.comparator===E,c=h.has(n.comparator);if(!g(t,n,e.equalities.length,i))return;if(s){e.equalities.push(r(n.value));continue}if(i=n.field,c){if(e.lower!==void 0)return;e.lower=r(n.value),e.lowerExclusive=n.comparator===">"}else{if(e.upper!==void 0)return;e.upper=r(n.value),e.upperExclusive=n.comparator==="<"}}return e},p=(t,o)=>{const r=v(o);if(r!==void 0)return t===""?r:t+a+r},q=(t,o,r,e,i)=>{if(r.length===0)return;const n=S(r,e,i);if(!n)return;const s=x(n.equalities);if(s===void 0)return;let c=s,f=s+l;if(n.lower!==void 0){const u=p(s,n.lower);if(u===void 0)return;c=n.lowerExclusive?u+a+l:u}if(n.upper!==void 0){const u=p(s,n.upper);if(u===void 0)return;f=n.upperExclusive?u:u+l}if(!(c>=f))return{hi:f,index:o,lo:c,table:t}},R=(t,o,r)=>{const e=[];for(const i of t){const n=x(i.fields.map(s=>r(o[s])));n!==void 0&&e.push({index:i.name,key:n})}return e},b=(t,o)=>t.index===o.index&&o.key>=t.lo&&o.key<t.hi,T=(t,o)=>{if(!t||t.length===0||!o||o.length===0)return!0;const r=new Map;for(const e of o){const i=r.get(e.index);i?i.push(e):r.set(e.index,[e])}return t.some(e=>{const i=r.get(e.index);return!i||i.length===0?!0:i.some(n=>b(e,n))})};export{q as buildIndexRange,R as indexKeysForRow,T as keysTouchRanges,b as rangeContains};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{encodeWire as h}from"@lunora/wire";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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{encodeWire as u}from"@lunora/wire";import{quoteIdentifier as l}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as d}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{REPROJECTION_MIGRATION_PREFIX as v,reprojectionMigrationId as w}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{runSql as p}from"./runDrizzle-B2GG3IJa.mjs";import{k as m,D as E}from"./do-sql-DqU-17Fs.mjs";import{mayHoldProjectedValue as g}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";const b=u(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=d(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 +1 @@
|
|
|
1
|
-
import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-
|
|
1
|
+
import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-DsCz-DAV.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-B1MIaRkE.mjs";import{shapeRangeKey as u}from"./ShapeDiffCache-iNO-hUiy.mjs";import{projectColumns as g}from"./buildPokeFrames-WR-hp0mX.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{sql as t}from"drizzle-orm";import{compareStrings as a,encodeAggregateKey as T}from"./aggregateTableName-
|
|
1
|
+
import{sql as t}from"drizzle-orm";import{compareStrings as a,encodeAggregateKey as T}from"./aggregateTableName-B_CtIQCS.mjs";import{runDrizzle as r}from"./runDrizzle-B2GG3IJa.mjs";import{sqliteInList as f}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";const n="__lunora_companion_state",g=1,c=1,E=i=>i?T(Object.keys(i),i):"",$=(i,e)=>JSON.stringify([g,(i.by??[]).toSorted(a),i.field??"",i.op,E(i.where),e??""]),d=(i,e)=>JSON.stringify([c,(i.partitionBy??[]).toSorted(a),i.sortBy.map(o=>o.field),E(i.where),e??""]),s=i=>{r(i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(n)} (${t.identifier("companion")} TEXT PRIMARY KEY, ${t.identifier("signature")} TEXT NOT NULL)`)},u=(i,e)=>{s(i),r(i,e.length===0?t`DELETE FROM ${t.identifier(n)}`:t`DELETE FROM ${t.identifier(n)} WHERE ${f(t.raw('"companion"'),e,!0)}`)},R=(i,e)=>r(i,t`SELECT ${t.identifier("signature")} FROM ${t.identifier(n)} WHERE ${t.identifier("companion")} = ${e}`).toArray()[0]?.signature,A=(i,e,o)=>{r(i,t`INSERT INTO ${t.identifier(n)} (${t.identifier("companion")}, ${t.identifier("signature")}) VALUES (${e}, ${o}) ON CONFLICT (${t.identifier("companion")}) DO UPDATE SET ${t.identifier("signature")} = excluded.${t.identifier("signature")}`)},N=i=>{s(i),r(i,t`DELETE FROM ${t.identifier(n)}`)};export{$ as aggregateSignature,N as clearCompanionSignatures,u as migrateCompanionState,d as rankSignature,R as readCompanionSignature,A as writeCompanionSignature};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./json-field-path-DeJW4U9z.mjs";import"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{c as p,s}from"./where-sql-DO1vOrhc.mjs";import"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";export{p as compileWhereSql,s as serverInList};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as g}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{mergeWhere as b}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{SCAN_DEP as j}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as A}from"./runDrizzle-B2GG3IJa.mjs";import{sqliteInList as O}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{decodeCursor as F,CURSOR_PREFIX as P,toBase64 as U}from"./CURSOR_PREFIX-
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{mergeWhere as b}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{SCAN_DEP as j}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as A}from"./runDrizzle-B2GG3IJa.mjs";import{sqliteInList as O}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{decodeCursor as F,CURSOR_PREFIX as P,toBase64 as U}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as V,sortColumnName as z,resolveRankPartition as H,RANK_TIEBREAK as _,encodePartitionKey as J,rankPivotConditionSql as X}from"./RANK_TIEBREAK-D3ye2GsL.mjs";const Y="__doc__",G=n=>P+U(JSON.stringify(n)),Q=n=>n.after?[n.after.partitionKey,...n.after.sortValues,n.after.rowId]:n.cursor?F(n.cursor):void 0,Z=(n,r,f)=>{if(n?.length!==1+r.length+1)return;const t=[{column:"__partition__",direction:"asc"}];for(const[c,u]of r.entries())t.push({column:u,direction:f[c]?.direction??"asc"});t.push({column:_,direction:"asc"});const e=[];for(const[c,u]of t.entries()){const d=X(u.column,n[c],u.direction,!0);if(d===void 0)continue;const s=[];for(const[m,l]of t.slice(0,c).entries())s.push(o`${o.identifier(l.column)} IS ${n[m]}`);s.push(d);const[i]=s;e.push(s.length===1&&i!==void 0?i:o`(${o.join(s,o` AND `)})`)}return e.length===0?o`(1 = 0)`:o`(${o.join(e,o` OR `)})`},v=null,oo=(n,r)=>{if(n===void 0)return v;const f=[n.__partition__,...r.map(t=>n[t]),n[_]];return G(f)},no=(n,r,f)=>{const t=[];for(const e of n){const c=e[_];if(typeof c!="string")continue;const u=r.get(c);if(!u)continue;const d=typeof e.__partition__=="string"?e.__partition__:"",s=f.map(i=>e[i]??null);t.push({doc:u,key:{partitionKey:d,rowId:c,sortValues:s}})}return t},to=o`${o.identifier("id")}`,ro=(n,r,f)=>{const{rowToDocument:t}=n,e=new Map;if(f.length===0)return e;const c=A(n.sql,o`SELECT id, _creationTime, ${o.identifier(Y)} FROM ${o.identifier(r)} WHERE ${O(to,f,!1)}`).toArray();for(const u of c){const d=t(u),s=u.id;d&&typeof s=="string"&&e.set(s,d)}return e},_o=(n,r,f,t)=>{const{assertRankPartitionLocal:e,ensureRankBackfilled:c,onRead:u,schema:d}=n,s=d.tables[r];if(!s)throw new g("INTERNAL",`unknown table: ${r}`);const i=s.rankIndexes?.find(a=>a.name===f);if(!i)throw new g("INTERNAL",`unknown rankIndex "${f}" on table "${r}"`);e(r,s,i),u(r,j),c(r,i);const m=V(r,i.name),l=i.sortBy.map((a,w)=>z(w)),h=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),T=b(t.baseWhere,t.where),k=H(i,T),R=[o`${o.identifier("__partition__")} ASC`];for(const[a,w]of l.entries()){const W=i.sortBy[a]?.direction;R.push(o`${o.identifier(w)} ${o.raw(W==="desc"?"DESC":"ASC")}`)}R.push(o`${o.identifier(_)} ASC`);const p=[];typeof t.partitionKey=="string"?p.push(o`${o.identifier("__partition__")} = ${t.partitionKey}`):k&&p.push(o`${o.identifier("__partition__")} = ${J(i.partitionBy??[],k)}`);const B=Q(t),E=Z(B,l,i.sortBy);E&&p.push(E);const I=o.identifier(_),S=o.identifier("__partition__"),D=p.length>0?o` WHERE ${o.join(p,o` AND `)}`:o``,L=l.length>0?o`${I}, ${S}, ${o.join(l.map(a=>o.identifier(a)),o`, `)}`:o`${I}, ${S}`,M=o`SELECT ${L} FROM ${o.identifier(m)}${D} ORDER BY ${o.join(R,o`, `)} LIMIT ${o.raw(String(h+1))}`,$=A(n.sql,M).toArray(),C=$.length>h,y=C?$.slice(0,h):$,K=y.map(a=>a[_]),q=no(y,ro(n,r,K),l),x=C?oo(y.at(-1),l):v,N=i.sortBy.map(a=>a.direction==="desc"?"desc":"asc");return{continueCursor:x,directions:N,hasMore:C,rows:q}};export{_o as computeRankPage,Q as resolveRankSeekTuple};
|
package/dist/packem_shared/{createCompanionSync-C2cZNaCR.mjs → createCompanionSync-DhYLePyV.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{N as co,S as ao,d as fo,e as lo,a as uo}from"./fts-companion-DzfEHonU.mjs";import{sql as o}from"drizzle-orm";import{r as z}from"./json-field-path-
|
|
1
|
+
import{N as co,S as ao,d as fo,e as lo,a as uo}from"./fts-companion-DzfEHonU.mjs";import{sql as o}from"drizzle-orm";import{r as z}from"./json-field-path-DeJW4U9z.mjs";import{matchesStaticWhere as Q,aggregateSqlFunction as $o}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as H,foldAggregateTally as X,encodeAggregateKey as k,coerceAggregateNumber as U}from"./aggregateTableName-B_CtIQCS.mjs";import{aggregateSignature as Eo,readCompanionSignature as Y,rankSignature as go,writeCompanionSignature as J}from"./clearCompanionSignatures-8uVX84aT.mjs";import{runAll as po,runDrizzle as g}from"./runDrizzle-B2GG3IJa.mjs";import{i as mo,g as _o,a as O,b as T,A as _,c as j,D as Z,r as N,e as P}from"./do-sql-DqU-17Fs.mjs";import{WORKERD_SQLITE_LIMITS as yo,param as ho}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{encodeGeohash as So,GEO_DEFAULT_PRECISION as To}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as x}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as B,matchesRankStaticWhere as oo,sortColumnName as Ro,encodePartitionKey as Ao}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{mayHoldProjectedValue as wo}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{serializeSqlValue as eo}from"./serializeSqlValue-DeoBMpZ2.mjs";const Co=(s,l,r)=>[...s.partitionBy??[],...s.sortBy.map(f=>f.field),...s.where?Object.keys(s.where):[]].every(f=>z(l,f)===z(r,f)),no=s=>o.join(["__id__","__partition__",...s.sortBy.map((l,r)=>Ro(r))].map(l=>o.identifier(l)),o`, `),ro=(s,l,r,E,f,a)=>{const t=Ao(r.partitionBy??[],a),R=r.sortBy.map(A=>eo(a[A.field]??null)),y=o.join([f,t,...R].map(A=>ho(A)),o`, `);g(s,o`INSERT INTO ${o.identifier(l)} (${E}) VALUES (${y})`)},to=(s,l,r,E)=>{const f=[];for(const a of g(s,o`SELECT id, _creationTime, ${o.identifier(Z)} FROM ${o.identifier(l)}`)){const t=N(a);t&&x(t,r)&&E(t)&&f.push(t)}return f},vo=(s,l,r,E,f)=>{const a=H(l,r.name),t=r.by??[],R=new Map;for(const w of to(s,l,E,L=>!r.where||Q(L,r.where)))X(R,k(t,w),r,w);g(s,o`DELETE FROM ${o.identifier(a)}`);const y=Math.floor(yo.boundParams/3),A=[...R];for(let w=0;w<A.length;w+=y){const L=A.slice(w,w+y),G=o.join(L.map(([b,D])=>o`(${b}, ${D.value}, ${D.count})`),o`, `);g(s,o`INSERT INTO ${o.identifier(a)} (${O}, ${T}, ${_}) VALUES ${G}`)}J(s,a,f)},Io=(s,l,r,E)=>{const f=Eo(r,E);Y(s,H(l,r.name))!==f&&vo(s,l,r,E,f)},ko=(s,l,r,E,f)=>{const a=B(l,r.name),t=no(r),R=to(s,l,E,y=>!r.where||oo(y,r.where));g(s,o`DELETE FROM ${o.identifier(a)}`);for(const y of R)ro(s,a,r,t,y._id,y);J(s,a,f)},Fo=(s,l,r,E)=>{const f=go(r,E);Y(s,B(l,r.name))!==f&&ko(s,l,r,E,f)},Oo=(s,l,r,E,f,a)=>{if(f&&a&&Co(r,f,a))return;const t=B(l,r.name);f&&g(s,o`DELETE FROM ${o.identifier(t)} WHERE ${o.identifier("__id__")} = ${E}`),!(!a||r.where&&!oo(a,r.where))&&ro(s,t,r,no(r),E,a)},Qo=s=>{const{broadcast:l,indexKeysFor:r,invalidateCache:E,recordCdc:f,schema:a,sql:t}=s,R=new Set,y=e=>a.tables[e]?.softDeleteMode?.field,A=(e,n)=>{const c=H(e,n.name);R.has(c)||(Io(t,e,n,y(e)),R.add(c))},w=(e,n,c)=>{const p=n.by??[],d=n.field??"",$=[],h=(i,u)=>{const m=eo(u);m===null?$.push(o`${P(i)} IS NULL`):$.push(o`${P(i)} = ${m}`)};for(const i of p)h(i,c[i]??null);const C=y(e);C!==void 0&&h(C,null);for(const[i,u]of Object.entries(n.where??{}))h(i,u!==null&&typeof u=="object"&&!Array.isArray(u)?u.eq:u);const F=$.length>0?o` WHERE ${o.join($,o` AND `)}`:o``,M=a.tables[e]?.shape[d];if(M&&wo(M)){const i=g(t,o`SELECT id, _creationTime, ${o.identifier(Z)} FROM ${o.identifier(e)}${F}`).toArray(),u=new Map;for(const m of i){const I=N(m);I&&X(u,"",n,I)}return{value:u.get("")?.value??null}}const W=$o(n.op),S=P(d);return{value:g(t,o`SELECT ${o.raw(W)}(${S}) AS value FROM ${o.identifier(e)}${F}`).one().value??null}},L=(e,n,c,p)=>{const d=H(e,n.name),{op:$}=n,h=n.field??"",C=i=>{g(t,o`DELETE FROM ${o.identifier(d)} WHERE ${O} = ${i} AND ${_} <= 0`)},F=y(e),M=i=>!n.where||Q(i,n.where),W=i=>x(i,F)&&M(i);p!==void 0&&$!=="count"&&M(p)&&U(p[h]);const S=c&&W(c)?c:void 0,v=p&&W(p)?p:void 0;if(!(!S&&!v)){if($==="count"){for(const[i,u]of[[S,-1],[v,1]]){if(!i)continue;const m=k(n.by??[],i);g(t,j(d,m,u,u,o`${T} = ${T} + excluded.${T}, ${_} = ${_} + excluded.${_}`))}S&&C(k(n.by??[],S));return}if($==="sum"||$==="avg"){for(const[i,u]of[[S,-1],[v,1]]){if(!i)continue;const m=U(i[h]);if(m===void 0)continue;const I=k(n.by??[],i);g(t,j(d,I,u*m,u,o`${T} = COALESCE(${T}, 0) + excluded.${T}, ${_} = ${_} + excluded.${_}`))}S&&C(k(n.by??[],S));return}if(S){const i=k(n.by??[],S),u=U(S[h]),m=g(t,o`SELECT ${T} AS value, ${_} AS count FROM ${o.identifier(d)} WHERE ${O} = ${i}`).toArray()[0],I=(m?.count??0)-1;if(I<=0)g(t,o`DELETE FROM ${o.identifier(d)} WHERE ${O} = ${i}`);else if(m&&u!==void 0&&m.value!==null&&u===m.value){const io=w(e,n,S);g(t,o`UPDATE ${o.identifier(d)} SET ${T} = ${io.value}, ${_} = ${I} WHERE ${O} = ${i}`)}else g(t,o`UPDATE ${o.identifier(d)} SET ${_} = ${_} - 1 WHERE ${O} = ${i}`)}if(v){const i=k(n.by??[],v),u=U(v[h]);if(u===void 0)g(t,j(d,i,null,1,o`${_} = ${_} + 1`));else{const m=$==="min"?"MIN":"MAX";g(t,j(d,i,u,1,o`${T} = ${o.raw(m)}(COALESCE(${T}, excluded.${T}), excluded.${T}), ${_} = ${_} + 1`))}}}},G=e=>{for(const n of a.tables[e]?.aggregateIndexes??[])A(e,n)},b=(e,n,c)=>{for(const p of a.tables[e]?.aggregateIndexes??[])L(e,p,n,c)},D=(e,n)=>{const c=B(e,n.name);R.has(c)||(Fo(t,e,n,y(e)),R.add(c))},so=e=>{for(const n of a.tables[e]?.rankIndexes??[])D(e,n)},V=(e,n,c,p)=>{for(const d of a.tables[e]?.rankIndexes??[])Oo(t,e,d,n,c,p)},K=(e,n,c,p)=>{const d=a.tables[e]?.searchIndexes??[];if(!(d.length===0||!mo(t)))for(const $ of d){if(co(p,c,$))continue;const h=ao(e,$.name);po(t,c?fo(h,n,lo(c,$)):uo(h,n))}},q=(e,n,c)=>{for(const p of a.tables[e]?.geoIndexes??[]){const d=_o(e,p.name);g(t,o`DELETE FROM ${o.identifier(d)} WHERE ${o.identifier("__id__")} = ${n}`);const $=c?.[p.field];if($!==null&&typeof $=="object"&&typeof $.lat=="number"&&typeof $.lng=="number"){const{lat:h,lng:C}=$,F=So({lat:h,lng:C},p.precision??To);g(t,o`INSERT INTO ${o.identifier(d)} (${o.identifier("__id__")}, ${o.identifier("__geohash__")}, ${o.identifier("__lat__")}, ${o.identifier("__lng__")}) VALUES (${n}, ${F}, ${h}, ${C})`)}}};return{ensureBackfilledForTable:G,ensureBackfilledIndex:A,ensureRankBackfilled:D,ensureRankBackfilledForTable:so,syncAggregates:b,syncCompanionsForInsert:(e,n,c)=>{K(e,n,c),q(e,n,c),b(e,void 0,c),V(e,n,void 0,c),E(e,n,c),f(e,n,"insert",c),l({indexKeys:r(e,c),key:n,op:"insert",row:c,table:e})},syncGeo:q,syncRanks:V,syncSearch:K}};export{Qo as createCompanionSync,Io as ensureAggregateCompanion,Fo as ensureRankCompanion};
|
package/dist/packem_shared/{createReplicaLink-DjykIKTn.mjs → createReplicaLink-Bd7jCjDt.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{decodeWire as p,encodeWire as S}from"@lunora/wire";import{cursorBelowRetainedFloor as y}from"./CDC_LOG_TABLE-DsCz-DAV.mjs";import{envPositiveInt as v}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{verifySiblingBody as A,RELAY_SIGNATURE_HEADER as g,siblingStub as N,siblingSecretOf as E,signSiblingBody as T}from"./stubByName-C_P73AOx.mjs";const L=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],O=new Set(L),I=s=>typeof s=="string"&&O.has(s),h="::replica::",R=s=>{const e=s.lastIndexOf(h);if(e===-1)return;const t=s.slice(0,e),r=s.slice(e+h.length);if(!(t.length===0||!I(r)))return{ownerKey:t,region:r}},b=s=>{if(s==null||!/^\d+$/.test(s))return;const e=Number.parseInt(s,10);return Number.isSafeInteger(e)&&e>0?e:void 0},m=1e3,w=1e3,C=10,U=5e4,F=s=>v(s,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",U),d="__replica_state",l=new WeakSet,_=s=>{l.has(s)||(s.exec(`CREATE TABLE IF NOT EXISTS ${d} (
|
|
2
2
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
3
3
|
epoch TEXT NOT NULL,
|
|
4
4
|
applied_seq INTEGER NOT NULL,
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import{encodeWire as l,decodeWire as E}from"@lunora/wire";import{sql as i}from"drizzle-orm";import{runDrizzle as t}from"./runDrizzle-B2GG3IJa.mjs";import{relayProxyKey as T}from"./DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";const a="__lunora_relay_shapes",o=null,R=e=>{t(e,i`CREATE TABLE IF NOT EXISTS ${i.identifier(a)} (
|
|
2
|
+
key TEXT PRIMARY KEY,
|
|
3
|
+
relay_idx INTEGER,
|
|
4
|
+
connection_id TEXT,
|
|
5
|
+
name TEXT NOT NULL,
|
|
6
|
+
args TEXT NOT NULL,
|
|
7
|
+
identity TEXT NOT NULL,
|
|
8
|
+
cursor INTEGER NOT NULL
|
|
9
|
+
)`)},c=e=>JSON.stringify(l(e)),s=e=>E(JSON.parse(e)),$=e=>t(e,i`SELECT key, relay_idx, connection_id, name, args, identity, cursor FROM ${i.identifier(a)}`).toArray().map(r=>({args:s(r.args),connectionId:r.connection_id??void 0,cursor:Number(r.cursor),identity:s(r.identity),key:r.key,name:r.name,relayIndex:r.relay_idx===null?void 0:Number(r.relay_idx)})),L=(e,n)=>{t(e,i`INSERT INTO ${i.identifier(a)} (key, relay_idx, connection_id, name, args, identity, cursor)
|
|
10
|
+
VALUES (${n.key}, ${n.relayIndex??o}, ${n.connectionId??o}, ${n.name}, ${c(n.args)}, ${c(n.identity??{})}, ${n.cursor})
|
|
11
|
+
ON CONFLICT(key) DO UPDATE SET
|
|
12
|
+
relay_idx = excluded.relay_idx,
|
|
13
|
+
connection_id = excluded.connection_id,
|
|
14
|
+
name = excluded.name,
|
|
15
|
+
args = excluded.args,
|
|
16
|
+
identity = excluded.identity,
|
|
17
|
+
cursor = excluded.cursor`)},S=(e,n,r)=>{t(e,i`UPDATE ${i.identifier(a)} SET cursor = ${r} WHERE key = ${n}`)},x=(e,n,r,d)=>{const y=d===void 0?i``:i` AND key = ${T(n,r,d)}`;t(e,i`DELETE FROM ${i.identifier(a)} WHERE relay_idx = ${n} AND connection_id = ${r}${y}`)},p=(e,n)=>{t(e,i`DELETE FROM ${i.identifier(a)} WHERE relay_idx = ${n}`)},O=e=>{t(e,i`DELETE FROM ${i.identifier(a)}`)};export{L as a,p as b,O as c,x as d,R as m,$ as r,S as w};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createShardCtxDb as _}from"./NotUniqueError-
|
|
1
|
+
import{createShardCtxDb as _}from"./NotUniqueError-CApXRyGS.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-ZRhh4qpX.mjs";import{ConflictError as q}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as E}from"./runShardMigrations-BeqUbznb.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";const S=(O,m={})=>({_meta:{column:{notNull:!0,...m}},kind:O}),A=(O,m,x)=>{const{describe:v,expect:d,it:b}=x;v(`engine contract: ${O}`,()=>{v("optimistic concurrency",()=>{const w=u=>({tables:{items:{indexes:[],shape:{title:S("string"),version:S("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});b("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await d(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(q)}finally{u?.()}}),b("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,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;d(e.code).toBe("CONFLICT"),d(e.kind).toBe("occ")}finally{u?.()}}),b("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,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");d(a?.title).toBe("first"),d(a?.version).toBe(99)}finally{u?.()}}),b("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 c=h.sql,p={tables:{items:{indexes:[],shape:{title:S("string"),version:S("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch(o.doc._id,{version:99})},op:"update",timing:"before"}}}}};E(c,p);const s=_({schema:p,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;d(e).toBeInstanceOf(q),d(e.code).toBe("CONFLICT"),d(e.kind).toBe("trigger")}finally{u?.()}})}),v("shape-poke ordering",()=>{const w="shard-a",u={args:{},name:"messages"},h=(e,t,o,n)=>e.accept(t?.()??{},{connectionId:o,shapes:{[n]:u}}),c=(e,t,o)=>{let n=0,l=0;const r=k=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${k}`)},i={fetch:(k,C)=>{if(JSON.parse(C?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const N=o[l];if(l+=1,N===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(N))}},f={get:()=>i,getByName:()=>i,idFromName:k=>k},g={buildShapeDiff:r("buildShapeDiff"),computeOpLogShapeSeed:r("computeOpLogShapeSeed"),currentCdcEpoch:r("currentCdcEpoch"),deliverWhisperLocal:r("deliverWhisperLocal"),doName:()=>F(w,0),env:()=>({SHARD:f}),getWebSockets:()=>e.getSockets(),maskMetadata:r("maskMetadata"),nextPokeId:()=>(n+=1,`poke-${String(n)}`),readAttachment:k=>k.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:r("resolveShape"),rlsMetadata:r("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},y=I(g);if(y===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return y},p=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,u,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},a=(e={})=>p({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});b("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1");await s(r,i,"s1"),await r.handleControl(a());const g=(await n(i)).map(y=>JSON.parse(y));d(g.map(y=>y.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),d(new Set(g.map(y=>y.pokeId)).size).toBe(1),d(g[1]?.shapeId).toBe("s1"),d(g[2]?.checkpoint).toBe(20)}finally{e?.()}}),b("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1"),f=h(l,t,"c-bob","s2");await s(r,i,"s1"),await s(r,f,"s2"),await r.handleControl(a());const g=await n(i);d(g.length).toBe(3);const y=await n(f);d(y.length).toBe(0),await r.handleControl(a());const k=await n(i);d(k.length).toBe(3)}finally{e?.()}}),b("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1");await s(r,i,"s1"),await r.handleControl(a({epoch:"e2"}));const f=await n(i);d(f.length).toBe(0),await r.handleControl(a());const g=await n(i);d(g.length).toBe(3)}finally{e?.()}})}),v("orderBy null placement",()=>{const w=[["a",void 0],["b",3],["c",void 0],["d",1],["e",void 0],["f",3],["g",2],["h",void 0]],u=[{nulls:"first",sort:"asc"},{nulls:"last",sort:"asc"},{nulls:"first",sort:"desc"},{nulls:"last",sort:"desc"}],h=({nulls:p,sort:s})=>{const a=new Map(w.map(([t],o)=>[t,o])),e=s==="asc"?1:-1;return w.toSorted(([t,o],[n,l])=>o!==l?o===void 0?p==="first"?-1:1:l===void 0?p==="first"?1:-1:(o-l)*e:((a.get(t)??0)-(a.get(n)??0))*e).map(([t])=>t)},c=p=>p.map(s=>String(s.label));b("pages every placement in threes with no row skipped or repeated",async()=>{const{close:p,host:s}=m();try{const a=s.sql,e=u.map((r,i)=>`items_${String(i)}`),t={label:S("string"),score:S("number",{notNull:!1})},o={tables:Object.fromEntries(e.map(r=>[r,{indexes:[{fields:["score"],name:"by_score"}],shape:t}]))};E(a,o);let n=17e11;const l=_({clock:()=>(n+=1e3,n),schema:o,sql:a});for(const r of e)for(const[i,f]of w)await l.insert(r,f===void 0?{label:i}:{label:i,score:f});for(const[r,i]of u.entries()){const f=e[r]??"",g=await l.findMany(f,{orderBy:[{score:i}]});d(c(g.page)).toStrictEqual(h(i));const y=[];let k;for(let C=0;C<w.length+2;C+=1){const B=await l.findMany(f,{cursor:k,limit:3,orderBy:[{score:i}]});if(y.push(...c(B.page)),B.isDone)break;k=B.continueCursor}d(y).toStrictEqual(h(i))}}finally{p?.()}})}),v("RLS identity under live subscription",()=>{const w="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},c=s=>{const a=[],e=[],t={fetch:(l,r)=>(a.push(JSON.parse(r?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>w,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:l=>l}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(l,r,i)=>(e.push(i),l===h.name?{columns:["id"],effectiveWhere:{org:i?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},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}},p=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"}))};b("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:a}=m();try{const{owner:e,resolvedUnder:t}=c(a.sql);await p(e,h),d(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),b("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:a}=m();try{const{owner:e,posts:t}=c(a.sql);await p(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");d(o.length).toBe(1),d(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),b("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:a}=m();try{const{owner:e,posts:t}=c(a.sql);await p(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");d(o.length).toBe(1),d(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{A as defineEngineContractSuite};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{stableStringify as u}from"@lunora/wire";const l=(t,s)=>{const o={_id:t._id};if(s){for(const e of s)Object.hasOwn(t,e)&&(o[e]=t[e]);return o}for(const[e,n]of Object.entries(t))e!=="_id"&&e!=="_creationTime"&&(o[e]=n);return o},j=(t,s,o)=>{const{columns:e,table:n}=o,c=[],d=new Map;for(const r of t){const i=l(r,e),f=String(i._id),a=u(i);d.set(f,a);const p=s.get(f);p===void 0?c.push({doc:i,id:f,op:"insert",seq:0,table:n,ts:0}):p!==a&&c.push({doc:i,id:f,op:"update",seq:0,table:n,ts:0})}for(const r of s.keys())d.has(r)||c.push({id:r,op:"delete",seq:0,table:n,ts:0});return{changes:c,nextBaseline:d}};export{j as diffExternalSource,l as projectExternalSourceRow};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as c}from"@lunora/errors";import{decodeWire as T,needsWireEncoding as h,encodeWire as A}from"@lunora/wire";import{sql as o}from"drizzle-orm";import{e as $}from"./effective-kind-BmG_zCAy.mjs";import{S as O,i as g,s as y,F as N}from"./json-field-path-DeJW4U9z.mjs";import{quoteIdentifier as b}from"./quoteIdentifier-CObIFRhb.mjs";import{runDrizzle as f}from"./runDrizzle-B2GG3IJa.mjs";import{serializeSqlValue as I}from"./serializeSqlValue-DeoBMpZ2.mjs";import{sqlComparableProjection as j}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";const L=/^[A-Za-z_$][\w$]*$/u,d=e=>L.test(e)?e:`"${e.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,l="__doc__",i="__originals__",X=e=>{if(Object.hasOwn(e,i))throw new c("BAD_REQUEST",`"${i}" is reserved by the row store's document encoding and cannot be used as a field name — rename the field`);let t,r;for(const[s,a]of Object.entries(e)){const _=j(a);_!==void 0&&(t??={...e},r??=Object.create(null),t[s]=_,r[s]=a)}t&&r&&(t[i]=r);const n=t??e;try{return h(n)?JSON.stringify(A(n)):JSON.stringify(n)}catch(s){throw new c("BAD_REQUEST",`this document cannot be stored: ${s instanceof Error?s.message:String(s)}`)}},w=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}},Y=(e,t)=>`${e}__geo_${t}`,D=e=>{try{return y(e)}catch(t){throw t instanceof N?new c("VALIDATION_ERROR",t.message):t}},S=e=>`'$.${(g(e)?D(e).map(r=>d(r)).join("."):d(e)).replaceAll("'","''")}'`,E=(e,t)=>t==="_id"||t==="id"?`${e}id`:t==="_creationTime"?`${e}_creationTime`:`json_extract(${e}${l}, ${S(t)})`,P=e=>E("",e),C=(e,t)=>`NULLIF(json_type(${l}, ${S(e)}), 'null') IN (${O[t]})`,R=e=>o.raw(P(e)),U=(e,t)=>o.raw(C(e,t)),G=(e,t)=>E(`${b(e)}.`,t),x=(e,t)=>o.raw(G(e,t)),H=(e,t,r,n)=>o`CREATE ${n?o`UNIQUE `:o``}INDEX IF NOT EXISTS ${o.identifier(e)} ON ${o.identifier(t)} (${r})`,u=o.identifier("__key__"),q=o.identifier("__value__"),v=o.identifier("__count__"),Z=(e,t,r,n,s)=>o`INSERT INTO ${o.identifier(e)} (${u}, ${q}, ${v}) VALUES (${t}, ${r}, ${n}) ON CONFLICT(${u}) DO UPDATE SET ${s}`,ee=(e,t)=>e===void 0||t!==0&&t!==1||$(e)!=="boolean"?t:t===1,m=new WeakMap,te=e=>{const t=m.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),m.set(e,r),r},F=e=>{if(!e)return;const t=e[l];let r;typeof t=="string"?r=w(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},re=e=>{try{return F(e)}catch{return}},p=new WeakMap,oe=e=>{const t=p.get(e);if(t!==void 0)return t;let r;try{f(e,o`CREATE VIRTUAL TABLE IF NOT EXISTS ${o.identifier("__lunora_fts_probe")} USING fts5(x)`),r=!0}catch{r=!1}finally{try{f(e,o`DROP TABLE IF EXISTS ${o.identifier("__lunora_fts_probe")}`)}catch{}}return p.set(e,r),r},ne={fieldRef:R,rangeTypeGuard:U,serialize:I};export{v as A,l as D,u as a,q as b,Z as c,H as d,R as e,x as f,Y as g,re as h,oe as i,P as j,X as k,w as l,ne as m,i as n,d as o,C as p,G as q,F as r,ee as s,te as t,U as u};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{BIGINT_KEY_DIGITS as c}from"./BIGINT_KEY_DIGITS-
|
|
1
|
+
import{BIGINT_KEY_DIGITS as c}from"./BIGINT_KEY_DIGITS-DE6yshOt.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,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-B2GG3IJa.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-
|
|
1
|
+
import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-B2GG3IJa.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-D2zEvCAa.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,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const h=t=>{if(t===null||typeof t!="object")return!1;const e=Object.getPrototypeOf(t);return e===null||e===Object.prototype};class a extends Error{}const c=t=>t.includes("."),l=t=>{const e=t.split(".");if(e.length>4||e.includes(""))throw new a(`field path "${t}" must have 1 to ${String(4)} non-empty segments`);return e},d=(t,e)=>{if(!c(e))return t[e];let o=t;for(const r of l(e)){if(!h(o)||!Object.hasOwn(o,r))return;o=o[r]}return o},p=(t,e,o,r)=>{const[n,...s]=e;if(n===void 0)throw new a(`field path "${r}" is empty`);if(t!=null&&!h(t))throw new a(`cannot set "${r}": "${n}" sits inside a value that is not an object`);const i=t??{};return{...i,[n]:s.length===0?o:p(i[n],s,o,r)}},f=(t,e)=>{const o=Object.keys(t).filter(n=>c(n));if(o.length===0)return t;for(const n of o){const s=o.find(i=>i!==n&&i.startsWith(`${n}.`));if(s!==void 0)throw new a(`patch sets both "${n}" and "${s}", which overlap; set one or the other`)}const r={};for(const[n,s]of Object.entries(t))c(n)||(r[n]=s);for(const n of o){const[s="",...i]=l(n);if(Object.hasOwn(t,s))throw new a(`patch sets both "${s}" and "${n}"; set one or the other`);r[s]=p(Object.hasOwn(r,s)?r[s]:e[s],i,t[n],n)}return r},b=t=>{const e=typeof t;return e==="number"||e==="string"||e==="boolean"?e:void 0},O={boolean:"'true', 'false'",number:"'integer', 'real'",string:"'text'"};export{a as F,O as S,h as a,b,f as e,c as i,d as r,l as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{applyCdcChanges as p}from"./CDC_LOG_TABLE-DsCz-DAV.mjs";import{selectShapeRows as m}from"./selectShapeMembers-B1MIaRkE.mjs";import{diffExternalSource as g,projectExternalSourceRow as l}from"./diffExternalSource-B0FZlDoL.mjs";import{stableStringify as d}from"@lunora/wire";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 +1 @@
|
|
|
1
|
-
import{keysTouchRanges as i}from"./buildIndexRange-
|
|
1
|
+
import{keysTouchRanges as i}from"./buildIndexRange-DQ3eWAGd.mjs";const f=(o,r,n)=>{const e=o??new Map;for(const t of n){const s=r?.get(t),u=e.get(t),c=e.has(t)&&u===void 0;if(!r?.has(t)||s===void 0||c){e.set(t,void 0);continue}e.set(t,u?[...u,...s]:s)}return e},a=(o,r,n)=>{const e=o??new Map;if(e.has(r)&&e.get(r)===void 0)return e;if(!n||n.length===0)return e.set(r,void 0),e;const t=e.get(r);return e.set(r,t?[...t,...n]:[...n]),e},h=(o,r,n)=>{if(!n)return!0;for(const e of r){if(!o.tables.has(e))continue;const t=o.ranges?.get(e);if(!t||t.length===0||i(t,n.get(e)))return!0}return!1};export{f as mergeChangedKeys,a as recordChangedKeys,h as writeTouchesMemo};
|