@lunora/shard-engine 1.0.0-alpha.50 → 1.0.0-alpha.51
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 +20 -4
- package/dist/index.d.ts +20 -4
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/CURSOR_PREFIX-CoJUQfCI.mjs +1 -0
- package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-BHzhEE-y.mjs +31 -0
- package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-Fb5vfB-T.mjs +1 -0
- package/dist/packem_shared/DEFAULT_MAX_RELAYS-CH446J5m.mjs +1 -0
- package/dist/packem_shared/DEFAULT_PROMOTION_THRESHOLDS-DcJw42RT.mjs +1 -0
- package/dist/packem_shared/DurableStreamRunner-C3NUyv3s.mjs +1 -0
- package/dist/packem_shared/NotUniqueError-DucaxGnP.mjs +1 -0
- package/dist/packem_shared/SEARCH_STATE_TABLE-xmYM_nOd.mjs +1 -0
- package/dist/packem_shared/applyOnDelete-BOOJzpbw.mjs +1 -0
- package/dist/packem_shared/backfillAggregateIndexes-CTPj9dAd.mjs +1 -0
- package/dist/packem_shared/{buildShapeDiff-Ds5Q0GJ_.mjs → buildShapeDiff-BW5lKBzQ.mjs} +1 -1
- package/dist/packem_shared/{compileWhereSql-CCvDjnfy.mjs → compileWhereSql-BB1JlUhC.mjs} +1 -1
- package/dist/packem_shared/{computeRankPage-BxtyiLn9.mjs → computeRankPage-BH2rv2mc.mjs} +1 -1
- package/dist/packem_shared/{createCompanionSync-CJo2Uiq7.mjs → createCompanionSync-Bo-oIkyU.mjs} +1 -1
- package/dist/packem_shared/{ctx-db-companions-CN8hWTF_.mjs → ctx-db-companions-BFBIVIOd.mjs} +1 -1
- package/dist/packem_shared/ctx-db-relay-shapes-CnOeftkH.mjs +17 -0
- package/dist/packem_shared/{defineEngineContractSuite-zN1RA5V-.mjs → defineEngineContractSuite-B-fWLvpW.mjs} +1 -1
- package/dist/packem_shared/exportShardRows-4Xezo8F6.mjs +1 -0
- package/dist/packem_shared/{isSoftDeleted-D6x6VWds.mjs → isSoftDeleted-B6TNznFv.mjs} +1 -1
- package/dist/packem_shared/{materializeExternalRows-DGjC_8Hc.mjs → materializeExternalRows-DZPYRDXu.mjs} +1 -1
- package/dist/packem_shared/runShardMigrations-BqH93Q8t.mjs +5 -0
- package/dist/packem_shared/{selectShapeMembers-Dva-Z9VQ.mjs → selectShapeMembers-CLK9q18N.mjs} +1 -1
- package/dist/packem_shared/where-sql-4RHk2frP.mjs +1 -0
- package/package.json +2 -2
- package/dist/packem_shared/CURSOR_PREFIX-D4DUGY5z.mjs +0 -1
- package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-Cp6pbyAp.mjs +0 -31
- package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-B3krmwZL.mjs +0 -1
- package/dist/packem_shared/DEFAULT_MAX_RELAYS-Bjx0HDbs.mjs +0 -1
- package/dist/packem_shared/DEFAULT_PROMOTION_THRESHOLDS-DpUu_mpH.mjs +0 -1
- package/dist/packem_shared/DurableStreamRunner-CWqdczw1.mjs +0 -1
- package/dist/packem_shared/NotUniqueError-Cxbfyre8.mjs +0 -1
- package/dist/packem_shared/SEARCH_STATE_TABLE-BCqn5ksa.mjs +0 -1
- package/dist/packem_shared/applyOnDelete-9f4D4g1z.mjs +0 -1
- package/dist/packem_shared/backfillAggregateIndexes-BCLXdiIS.mjs +0 -1
- package/dist/packem_shared/ctx-db-relay-shapes-CakvRIFx.mjs +0 -17
- package/dist/packem_shared/exportShardRows-CegEECNc.mjs +0 -1
- package/dist/packem_shared/runShardMigrations-D6rTX7Bn.mjs +0 -5
- package/dist/packem_shared/where-sql-D6MSVjdL.mjs +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as $}from"@lunora/errors";import{c as sn,q as rt,S as cn,l as Me,a as an}from"./ctx-db-companions-BFBIVIOd.mjs";import{sql as i}from"drizzle-orm";import{d as dn}from"./wire-codec-COhOSEe4.mjs";import{throwingScheduler as ln,aggregateSqlFunction as De,normalizeCountArgument as un}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as Ke,encodeAggregateKey as Qe,readAggregateValue as ze}from"./aggregateTableName-CGi8gxeK.mjs";import{mergeWhere as Q,CountRlsUnsupportedError as Je,selectIndexForGroupBy as fn,selectIndexForCount as hn,selectIndexForAggregate as wn}from"./CountRlsUnsupportedError-Bdfupt3g.mjs";import{backfillSearchIndexesForTable as pn,searchIndexCoversTable as gn}from"./backfillAggregateIndexes-CTPj9dAd.mjs";import{backfillAggregateIndexes as wr,backfillRankIndexes as pr,backfillSearchIndexes as gr}from"./backfillAggregateIndexes-CTPj9dAd.mjs";import{appendCdcChange as $n}from"./CDC_LOG_TABLE-gl0FuepJ.mjs";import{CDC_LOG_TABLE as yr,applyCdcChanges as Er,bumpCdcEpoch as mr,cdcCanVouchFor as Sr,cdcSeqLeavingRows as _r,cdcTouchesTables as Tr,cdcTrimmedError as Rr,compactCdcDocs as vr,cursorBelowRetainedFloor as Ar,minCdcReplayableSeq as Ir,minCdcSeq as Cr,readCdcChangeKeys as xr,readCdcChanges as br,readCdcCursor as Mr,readCdcEpoch as Dr,trimCdcChanges as kr}from"./CDC_LOG_TABLE-gl0FuepJ.mjs";import{allocateCommitSeq as yn,COMMIT_SEQ_FIELD as En}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{isMemoryTable as mn}from"./clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as mt}from"./computeRankPage-BH2rv2mc.mjs";import{SCAN_DEP as G}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as O,runSql as me}from"./runDrizzle-2ULFQR_k.mjs";import{D as ne,k as ce,r as le,b as ke,A as Ve,a as Le,e as X,t as Gt,j as We,q as St,i as Sn,h as Ht,g as _n}from"./do-sql-bkXQEBl8.mjs";import{renderSql as Nt,unionAll as it,WORKERD_SQLITE_LIMITS as Ot,sqliteInList as Tn}from"./param-DlozcSQu.mjs";import{coveringGeohashes as Rn,boundingBoxGeohashes as vn,haversineMeters as An,pointInBoundingBox as In}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Cn}from"./NotFoundError-BhF7FeFr.mjs";import{softDeleteScope as de,normalizeOrderKeys as et,buildSeekWhere as jt,decodeCursor as tt,applySelect as _t,encodeCursor as nt,tiebreakDirectionFor as Kt,buildSeekBeforeWhere as xn}from"./CURSOR_PREFIX-CoJUQfCI.mjs";import{rankTableName as Tt,sortColumnName as Rt,resolveRankPartition as bn,encodePartitionKey as Mn,RANK_TIEBREAK as Dn}from"./RANK_TIEBREAK-D157XEqw.mjs";import{indexKeysForRow as kn,buildIndexRange as Ln}from"./buildIndexRange-CBKQmHSS.mjs";import{assertFlatPredicate as Ye,resolveRelationPredicates as vt}from"./DEFAULT_MAX_RELATION_KEYS-Fb5vfB-T.mjs";import{runRowValidators as Xe,resolveWith as At,relationHooks as It,applyOnDelete as Fn,fanOutScalarCounts as qn}from"./applyOnDelete-BOOJzpbw.mjs";import{guardWriter as Wn}from"./RLS_UNWRAP_SYMBOL-BWloGsd3.mjs";import{quoteIdentifier as Se}from"./quoteIdentifier-CObIFRhb.mjs";import{i as Bn}from"./sql-projection-BqmxFxQU.mjs";import{createSystemReader as Un}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as ye}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as Pn}from"./hasTrigger-CjlwI4le.mjs";import{c as te,t as Ue,r as Be,j as Ee,i as Ct}from"./where-sql-4RHk2frP.mjs";import{CLIENT_WATERMARK_TABLE as Fr,advanceClientWatermark as qr,migrateClientWatermark as Wr,readClientWatermark as Br}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Pr,deleteGlobalShapeSnapshot as Gr,deleteGlobalShapeSnapshotsForConnection as Hr,migrateGlobalShapeSnapshot as Nr,readGlobalShapeSnapshot as Or,writeGlobalShapeSnapshot as jr}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{IDEMPOTENCY_TABLE as Qr,readIdempotent as zr,trimIdempotent as Jr,writeIdempotent as Vr}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{runShardMigrations as Xr}from"./runShardMigrations-BqH93Q8t.mjs";import{SEARCH_STATE_TABLE as ei}from"./SEARCH_STATE_TABLE-xmYM_nOd.mjs";import{selectShapeMembers as ni,selectShapeRows as oi}from"./selectShapeMembers-CLK9q18N.mjs";import{serializeSqlValue as re}from"./serializeSqlValue-DbI1VQYM.mjs";const Gn=o=>{const r=atob(o),t=Uint8Array.from(r,a=>a.codePointAt(0)??0);return new TextDecoder().decode(t)},Hn=()=>new $("BAD_REQUEST","invalid cursor"),xt=16,bt=8,V=1024,st=(o,r)=>r.query(o),Nn=(o,r)=>{if(o.length===0)return 0;let t=0;for(const[a,d]of r.entries()){const p=a===r.length-1;let E=0;for(const S of o)(p?S.startsWith(d):S===d)&&(E+=1);if(E===0)return 0;t+=E}return t},On=(o,r)=>{if(!r)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",a=(t.codePointAt(0)??0)+1;if(a>=55296&&a<=57343||a>1114111)return{exact:!0,lower:o,upper:o};const d=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:d+String.fromCodePoint(a)}},jn=(o,r,t)=>{const a={eq:(d,p)=>{if(!o.definition.filterFields?.includes(d))throw new $("INTERNAL",`field "${d}" is not a filter field of search index "${o.indexName}" on table "${r}"`);if(o.filters.length>=bt)throw new $("BAD_REQUEST",`search index "${o.indexName}" on table "${r}": at most ${String(bt)} .eq() filters are supported per search query`);return o.filters.push({field:d,value:p}),a},search:(d,p)=>{const E=o;if(d!==E.definition.field)throw new $("INTERNAL",`search index "${E.indexName}" on table "${r}" indexes "${E.definition.field}", not "${d}"`);const S=st(p,t).length;if(S>xt)throw new $("BAD_REQUEST",`search index "${E.indexName}" on table "${r}": at most ${String(xt)} search terms are supported (got ${String(S)})`);return E.field=d,E.query=p,E.hasQuery=!0,a}};return a},Kn=o=>{if(o.length>V)throw new $("BAD_REQUEST",`more than ${String(V)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Qn=o=>Math.min(o.offset+o.numItems+1,V),zn=o=>btoa(`search:${String(o)}`),Jn=o=>{let r;try{r=Gn(o)}catch{return}if(!r.startsWith("search:"))return;const t=Number(r.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},Vn=o=>{if(typeof o.endCursor=="string")throw new $("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(o.numItems))throw new $("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(o.numItems)}`);const r=Math.max(0,Math.floor(o.numItems)),t=o.cursor?Jn(o.cursor):0;if(t===void 0)throw Hn();if(t+r>=V)throw new $("BAD_REQUEST",`search pagination reaches the ${String(V)}-document limit (offset ${String(t)} + ${String(r)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,V-t-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:t}},Yn=(o,r)=>{const t=r.offset+r.numItems,a=r.numItems>0&&o.length>t;return{continueCursor:a?zn(t):null,isDone:!a,page:o.slice(r.offset,t)}},Xn=o=>{if(o===void 0)return V+1;if(!Number.isFinite(o))return V;const r=Math.max(0,Math.floor(o));if(r>V)throw new $("BAD_REQUEST",`search returns at most ${String(V)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},Pe=o=>{const r=new Map;return t=>{const a=r.get(t);if(a!==void 0)return a;const d=o(Se(t));return r.set(t,d),d}},ue=Se(ne),Zn=Pe(o=>`INSERT INTO ${o} (id, _creationTime, ${ue}) VALUES (?, ?, ?)`),Mt=Pe(o=>`UPDATE ${o} SET ${ue} = ? WHERE id = ? AND ${ue} = ?`),eo=Pe(o=>`UPDATE ${o} SET _creationTime = ?, ${ue} = ? WHERE id = ? AND ${ue} = ?`),to=Pe(o=>`DELETE FROM ${o} WHERE id = ? AND ${ue} = ?`),no="SELECT changes() AS changed",Dt=new Map,oo="",ro=o=>{const r=JSON.stringify(o),t=Dt.get(r);if(t!==void 0)return t;const a=o.map(p=>i`SELECT ${i.raw(`'${p.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${i.identifier(ne)} FROM ${i.identifier(p)} WHERE id = ${oo}`),{sql:d}=Nt("sqlite",i`${it(a)} LIMIT 1`);return Dt.set(r,d),d},io=(o,r)=>r.map(()=>o),so=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,co=o=>{if(!so.test(o))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},kt=50,Qt=500,Fe=Math.floor(Ot.boundParams/3),ge=Ot.boundParams,ao=128,ae=(o,r,t)=>{const a=r??Qt;if(o>a)throw new $("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},lo=o=>{const r={eq:(t,a)=>(o.sqlConditions.push({comparator:"=",field:t,value:a}),r),gt:(t,a)=>(o.sqlConditions.push({comparator:">",field:t,value:a}),r),gte:(t,a)=>(o.sqlConditions.push({comparator:">=",field:t,value:a}),r),lt:(t,a)=>(o.sqlConditions.push({comparator:"<",field:t,value:a}),r),lte:(t,a)=>(o.sqlConditions.push({comparator:"<=",field:t,value:a}),r)};return r},uo=o=>Math.max(o,V),zt=(o,r)=>{const t=o.filters.map(a=>i`${X(a.field)} = ${re(a.value)}`);return r&&t.push(r),t},fo=(o,r,t,a,d)=>{const p=st(t.query,rt(t.definition.language));if(p.length===0)return[];const E=cn(r,t.indexName),S=`${E}__vocab`,T=p.length-1,L=p.map((F,x)=>{const q=On(F,x===T),z=q.exact?i`${i.identifier("term")} = ${q.lower}`:i`${i.identifier("term")} >= ${q.lower} AND ${i.identifier("term")} < ${q.upper}`;return i`SELECT ${i.identifier("doc")}, ${i.raw(String(x))} AS ${i.identifier("__term__")}, COUNT(*) AS ${i.identifier("__n__")} FROM ${i.identifier(S)} WHERE ${z} GROUP BY ${i.identifier("doc")}`}),y=p.map((F,x)=>i`SUM(CASE WHEN u.${i.identifier("__term__")} = ${i.raw(String(x))} THEN u.${i.identifier("__n__")} ELSE 0 END)`),A=i`SELECT f.${i.identifier(Me)} AS ${i.identifier(Me)}, ${i.join(y,i` + `)} AS ${i.identifier("__score__")} FROM (${it(L)}) u JOIN ${i.identifier(E)} f ON f.rowid = u.${i.identifier("doc")} GROUP BY f.${i.identifier(Me)} HAVING ${i.join(y.map(F=>i`${F} > 0`),i` AND `)}`,v=zt(t,d);let _=i`SELECT m.id, m._creationTime, m.${i.identifier(ne)}, s.${i.identifier("__score__")} AS ${i.identifier("__score__")} FROM (${A}) s JOIN ${i.identifier(r)} m ON m.id = s.${i.identifier(Me)}`;v.length>0&&(_=i`${_} WHERE ${i.join(v,i` AND `)}`),_=i`${_} ORDER BY s.${i.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${i.raw(String(a))}`;const H=[];for(const F of O(o,_)){const x=Ht(F);if(x){const q=F.__score__;H.push({document:x,score:typeof q=="number"?q:Number(q??0)})}}return H},ho=(o,r,t,a,d)=>{const p=rt(t.definition.language),E=st(t.query,p);if(E.length===0)return[];const S=zt(t,d);let T=i`SELECT id, _creationTime, ${i.identifier(ne)} FROM ${i.identifier(r)}`;S.length>0&&(T=i`${T} WHERE ${i.join(S,i` AND `)}`),T=i`${T} ORDER BY _creationTime DESC, id ASC LIMIT ${i.raw(String(uo(a)))}`;const L=O(o,T).toArray(),y=[];for(const A of L){const v=Ht(A);if(!v)continue;const _=Nn(an(v,t.definition),E);_>0&&y.push({creationTime:typeof v._creationTime=="number"?v._creationTime:0,doc:v,id:typeof v._id=="string"?v._id:"",score:_})}return y.sort((A,v)=>v.score-A.score||v.creationTime-A.creationTime||A.id.localeCompare(v.id)),y.slice(0,a).map(A=>({document:A.doc,score:A.score}))},Ze=(o,r,t,a)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new $("BAD_REQUEST",`geo index "${a}" on table "${t}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},wo=(o,r)=>{const t=o,a={near:(d,p)=>{if(t.within)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(Ze(d,".near() point",r,t.indexName),!Number.isFinite(p)||p<=0)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(p)}`);return t.near={point:{lat:d.lat,lng:d.lng},radiusMeters:p},a},within:d=>{if(t.near)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(Ze(d.sw,".within() sw corner",r,t.indexName),Ze(d.ne,".within() ne corner",r,t.indexName),d.sw.lat>d.ne.lat)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(d.sw.lng>d.ne.lng)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return t.within={ne:{lat:d.ne.lat,lng:d.ne.lng},sw:{lat:d.sw.lat,lng:d.sw.lng}},a}};return a},po=(o,r)=>{const t=o[r];if(t===null||typeof t!="object")return;const{lat:a,lng:d}=t;return typeof a=="number"&&typeof d=="number"?{lat:a,lng:d}:void 0},go=(o,r)=>{const t=po(o,r.definition.field);if(!t)return;const a=typeof o._creationTime=="number"?o._creationTime:0;if(r.near){const d=An(r.near.point,t);return d<=r.near.radiusMeters?{creationTime:a,distance:d}:void 0}return In(t,r.within)?{creationTime:a,distance:0}:void 0},$o=(o,r,t,a)=>{if(!t.near&&!t.within)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const d=t.near?Rn(t.near.point,t.near.radiusMeters):vn(t.within),p=_n(r,t.indexName),E=d.map(A=>i`(g.${i.identifier("__geohash__")} >= ${A} AND g.${i.identifier("__geohash__")} < ${`${A}{`})`),S=[i`(${i.join(E,i` OR `)})`];a&&S.push(a);const T=i`SELECT m.id, m._creationTime, m.${i.identifier(ne)} FROM ${i.identifier(p)} g JOIN ${i.identifier(r)} m ON m.id = g.${i.identifier("__id__")} WHERE ${i.join(S,i` AND `)}`,L=O(o,T).toArray(),y=[];for(const A of L){const v=le(A),_=v?go(v,t):void 0;v&&_&&y.push({creationTime:_.creationTime,distance:_.distance,doc:v})}return y.sort((A,v)=>A.distance-v.distance||v.creationTime-A.creationTime),y},Jt=(o,r,t,a)=>{const d=[];for(const p of o)if(r.every(E=>E(a(p)))&&(d.push(p),typeof t=="number"&&d.length>=t))break;return d},yo=(o,r,t,a,d,p=()=>{})=>{const E=t.within!==void 0,S=$o(o,r,t,d).map(T=>({distanceMeters:E?null:T.distance,document:T.doc}));return p(S.length),typeof a=="number"?S.slice(0,Math.max(0,Math.floor(a))):S},Vt=(o,r,t,a,d,p=()=>{})=>{const{geo:E}=t;if(!E)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const S=t.inMemoryFilters.length>0,T=yo(o,r,E,S?void 0:d,a,p);return S?Jt(T,t.inMemoryFilters,d,L=>L.document):T},Yt=(o,r,t,a)=>{const d=`SELECT id, _creationTime, ${Se(ne)} FROM ${Se(o)}`,p=`ORDER BY ${t}${a===void 0?"":` LIMIT ${String(a)}`}`;return r===void 0?Be(`${d} ${p}`):Ee(`${d} WHERE `,r,` ${p}`)},Eo=(o,r,t,a,d,p=()=>{})=>Vt(o,r,t,a,d,p).map(E=>E.document),mo=(o,r,t,a,d,p,E=()=>{})=>{const S=[];for(const A of t.sqlConditions)S.push(i`${X(A.field)} ${i.raw(A.comparator)} ${re(A.value)}`);a&&S.push(a);let T=i`SELECT id, _creationTime, ${i.identifier(ne)} FROM ${i.identifier(r)}`;S.length>0&&(T=i`${T} WHERE ${i.join(S,i` AND `)}`),T=i`${T} ORDER BY ${d}`,typeof p=="number"&&t.inMemoryFilters.length===0&&(T=i`${T} LIMIT ${i.raw(String(Math.max(0,Math.floor(p))))}`);const L=O(o,T).toArray();E(L.length);const y=[];for(const A of L){const v=le(A);if(v&&t.inMemoryFilters.every(_=>_(v))&&(y.push(v),typeof p=="number"&&y.length>=p))break}return y},$e={fieldRef:X,serialize:re},Xt=(o,r)=>{const t=r===void 0?void 0:o.shape[r];return t!==void 0&&Bn(t)},Lt=(o,r)=>r.some(t=>Xt(o,t)),Ft=(o,r,t)=>{if(Xt(o,r))throw new $("BAD_REQUEST",`${t}: "${r}" is stored as an order-preserving key, which SQL cannot reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it`)},ct={fieldRef:o=>Be(We(o)),serialize:re},So=o=>{let r=0;const t=[],a={fieldRef:d=>Be(We(d)),relationExists:d=>{const{childWhere:p,negated:E,parentTable:S,relation:T}=d,L=`__rel_${String(r)}`,y=t.at(-1)??S;r+=1,o(T.table,G);const A=T.kind==="one"?T.field:T.references,v=T.kind==="one"?T.references:T.field,_=Be(`${St(L,v)} = ${St(y,A)}`);t.push(L);const H=te(p,a,Ue);t.pop();const F=H===void 0?_:Ee(_," AND ",H),x=Ee("EXISTS (SELECT 1 FROM ",Ct(T.table)," AS ",Ct(L)," WHERE ",F,")");return E?Ee("NOT ",x):x},serialize:re};return a},Zt=o=>{const r=o.map(t=>`${We(t.field)} ${t.direction==="desc"?"DESC":"ASC"}`);return o.some(t=>t.field==="_id"||t.field==="id")||r.push(`${We("id")} ${Kt(o)==="desc"?"DESC":"ASC"}`),r.join(", ")},_o=o=>{const r=o.map(t=>i`${X(t.field)} ${i.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||r.push(i`${X("id")} ${i.raw(Kt(o)==="desc"?"DESC":"ASC")}`),i.join(r,i`, `)},To={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},Ro=o=>{const r=new Set(o.sqlConditions.filter(a=>a.comparator==="=").map(a=>a.field));let t=0;for(;t<o.indexFields.length&&r.has(o.indexFields[t]??"");)t+=1;return o.indexFields.slice(t)},en=(o,r)=>{const t=o.order,a=Ro(o);return a.length>0?et(a.map(d=>({[d]:t})),r):et([{_creationTime:t}],r)},vo=(o,r,t,a)=>{const d=o.sqlConditions.map(p=>({[p.field]:{[To[p.comparator]??"eq"]:p.value}}));if(t&&d.push(jt(r,tt(t))),a&&d.push(xn(r,tt(a))),d.length!==0)return d.length===1?d[0]:{AND:d}},Ao=(o,r,t)=>{const a=[];for(const d of o){const p=le(d);if(p&&r.every(E=>E(p))&&(a.push(p),t!==void 0&&a.length>t))break}return a},Io=(o,r,t,a,d,p,E=()=>{})=>{const S=Math.max(0,Math.floor(d.numItems)),T=en(a,t),L=typeof d.endCursor=="string",y=te(vo(a,T,d.cursor,d.endCursor),ct,Ue),A=p&&y?Ee(y," AND ",p):p??y,v=a.inMemoryFilters.length>0,_=Yt(r,A,Zt(T),v||L?void 0:S+1),H=me(o,_.text,..._.params).toArray();E(H.length);const F=Ao(H,a.inMemoryFilters,v||L?void 0:S);if(L){const N=F.length>=2?F[Math.floor(F.length/2)-1]:void 0;return{continueCursor:d.endCursor??null,isDone:!0,page:F,splitCursor:N?nt(N,T):null}}const x=F.length>S,q=x?F.slice(0,S):F,z=q.at(-1);return{continueCursor:x&&z?nt(z,T):null,isDone:!x,page:q}};class Co extends ${constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const xo=/\s/u,bo=String.fromCodePoint(0),qt=(o,r,t)=>{if(!o.tables[r])throw new $("INTERNAL",`unknown table: ${r}`);return typeof t!="string"||t.length===0||xo.test(t)||t.includes(bo)?null:t},Mo=(o,r,t,a=()=>{},d=()=>{},p=()=>{})=>{const E=r.tables[t];if(!E)throw new $("INTERNAL",`unknown table: ${t}`);const S=de(E.softDeleteMode,void 0),T=S?te(S,$e):void 0,L=S?te(S,ct,Ue):void 0,y={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let A=0;const v=m=>{const{search:b}=y;if(!b)throw new $("INTERNAL","runSearchFetch called without a staged search");pn(o,t,E);const C=y.inMemoryFilters.length>0,k=Xn(C?void 0:m),Y=Sn(o);if(Y&&!gn(o,t,b.definition))throw new $("SEARCH_INDEX_BUILDING",`search index "${b.indexName}" on table "${t}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const oe=Y?fo(o,t,b,k,T):ho(o,t,b,k,T);return C?(A=oe.length,Jt(oe,y.inMemoryFilters,m,Ge=>Ge.document)):(m===void 0&&Kn(oe),oe)},_=m=>v(m).map(b=>b.document),H=m=>{const b=Vn(m);return Yn(_(Qn(b)),b)},F=()=>_o(en(y,E.shape)),x=()=>{if(y.search||y.geo||y.indexName===void 0){d(void 0);return}d(Ln(t,y.indexName,y.indexFields,y.sqlConditions,re))},q=m=>{x();let b=0;const C=(()=>{if(y.search){const k=_(m);return b=A,k}return y.geo?Eo(o,t,y,T,m,k=>{b=k}):mo(o,t,y,T,F(),m,k=>{b=k})})();return p(Math.max(b,C.length)),C},z=()=>{if(!y.search&&!y.geo)throw new $("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);x();let m=0;const b=(()=>{if(y.search){const C=v(void 0);return m=A,C}return Vt(o,t,y,T,void 0,C=>{m=C})})();return p(Math.max(m,b.length)),b},N={async*[Symbol.asyncIterator](){if(y.search){yield*q(void 0);return}const m=[...y.inMemoryFilters];let b;y.inMemoryFilters=[];try{for(;;){const C=await N.paginate({cursor:b??null,numItems:ao});for(const k of C.page)m.every(Y=>Y(k))&&(yield k);if(C.isDone||C.continueCursor===null)return;b=C.continueCursor}}finally{y.inMemoryFilters=m}},async collect(){return q(void 0)},async collectWithScores(){return z()},filter(m){return y.inMemoryFilters.push(m),N},async first(){return q(y.inMemoryFilters.length>0?void 0:1)[0]??null},order(m){return y.order=m==="desc"?"desc":"asc",N},async paginate(m){let b=0;if(x(),y.search){const k=H(m);return p(k.page.length),k}if(y.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const C=Io(o,t,E.shape,y,m,L,k=>{b=k});return p(Math.max(b,C.page.length)),C},async take(m){return q(m)},async unique(){const m=q(y.inMemoryFilters.length>0?void 0:2);if(m.length>1)throw new Co(`unique() on table "${t}" matched ${String(m.length)} documents; expected at most one`);return m[0]??null},withGeoIndex(m,b){const C=(E.geoIndexes??[]).find(Y=>Y.name===m);if(!C)throw new $("INTERNAL",`unknown geo index "${m}" on table "${t}"`);a(t,m,"geo");const k={definition:C,indexName:m};if(y.geo=k,b(wo(k,t)),!k.near&&!k.within)throw new $("INTERNAL",`geo index "${m}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return N},withIndex(m,b){const C=E.indexes.find(k=>k.name===m);if(!C)throw new $("INTERNAL",`unknown index "${m}" on table "${t}"`);return a(t,m,"index"),y.indexName=m,y.indexFields=C.fields,b&&b(lo(y)),N},withSearchIndex(m,b){const C=(E.searchIndexes??[]).find(Y=>Y.name===m);if(!C)throw new $("INTERNAL",`unknown search index "${m}" on table "${t}"`);a(t,m,"search");const k={definition:C,field:C.field,filters:[],hasQuery:!1,indexName:m,query:""};if(y.search=k,b(jn(k,t,rt(C.language))),!k.hasQuery)throw new $("INTERNAL",`search index "${m}" on table "${t}" requires a .search(field, query) call`);return N}};return N},Wt=(o,r,t)=>{const a={...r};for(const[d,p]of Gt(o)){if(p.serverDefault){a[d]=p.serverDefault({auth:t});continue}a[d]===void 0&&(p.defaultFn?a[d]=p.defaultFn():"defaultValue"in p&&(a[d]=p.defaultValue))}return a},Bt=(o,r,t,a)=>{const d=t;for(const[p,E]of Gt(o)){if(E.serverDefault){p in r&&(d[p]=E.serverDefault({auth:a}));continue}E.onUpdateFn&&!(p in r)&&(d[p]=E.onUpdateFn())}},Ut=(o,r)=>{for(const t of Object.keys(r))if(r[t]===void 0)throw new $("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Do=/unique constraint failed/i,ko=o=>o instanceof Error&&Do.test(o.message),ot=(o,r,t,a)=>{try{me(o,t,...a)}catch(d){throw ko(d)?new ye(`unique constraint violation on "${r}"`,"unique"):d}},qe=(o,r,t,a)=>{if(ot(o,r,t,a),me(o,no).one().changed===0)throw new ye(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},Pt=(o,r,t,a,d,p,E)=>{const S=[];for(let A=0;A<t.length+1;A+=1){const v=[];for(let x=0;x<A;x+=1)v.push(i`${i.identifier(t[x])} IS ${p[x]}`);const _=t[A],H=a[A];if(_!==void 0&&H!==void 0){const x=H.direction==="desc"?">":"<";v.push(i`${i.identifier(_)} ${i.raw(x)} ${p[A]}`)}else v.push(i`${i.identifier(Dn)} < ${E}`);const[F]=v;S.push(v.length===1&&F!==void 0?F:i`(${i.join(v,i` AND `)})`)}const T=i.join(S,i` OR `),L=O(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${d} AND (${T})`).one(),y=O(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${d}`).one();return{before:L.c,total:y.c}},ur=o=>{const{sql:r}=o,{schema:t}=o,a=o.broadcast??(()=>{});let d;const p=()=>o.inTransaction?.()===!0,E=e=>t.tables[e]?.commitOrderedMode!==!0?{}:((d===void 0||!p())&&(d=yn(r)),{[En]:d}),S=(e,...n)=>{const s=t.tables[e]?.indexes;if(!s||s.length===0)return;const f=[];for(const h of n)h&&f.push(...kn(s,h,re));return f.length>0?f:void 0},{headroom:T}=o;let L=!1;const y=async e=>{const n=L;L=!0;try{return await e()}finally{L=n}},A=o.onRead??(()=>{}),v=o.onReadRange??(e=>{A(e.table,G)}),_=(e,n)=>{n!==void 0&&n!==G&&!L&&T?.recordRead(1),A(e,n)},H=o.onIndexUse??(()=>{}),F=o.onWrite??(()=>{}),x=e=>{L||T?.recordWrite(e)},q=async e=>{x(e.doc),await F(e)},{cache:z}=o,N=o.clock??(()=>Date.now()),m=o.idGenerator??(()=>crypto.randomUUID()),b=o.scheduler??ln,{globalDb:C}=o,k=o.auth??{identity:null,userId:null},Y=o.cdc??!1,oe=b,Ge=Un({scheduler:typeof oe.list=="function"&&typeof oe.get=="function"?oe:void 0,storage:o.storage}),fe=(e,n,s,f)=>{Y&&!mn(t.tables[e])&&$n(r,N(),e,n,s,f)},se=e=>t.tables[e]?.shardMode?.kind==="global",at=(e,n)=>{if(se(e)){if(!C)throw new $("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return C}return B},He=e=>at(e,"cascade"),K=(e,n)=>{if(se(e)){if(!C)throw new $("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return C}},dt=async(e,n,s,f,h)=>{h&&x(s);const u=await e.insert(n,s,f);return a({key:u,op:"insert",row:{...s,_id:u},table:n}),u},Ne=(e,n)=>at(e,"relation load").findMany(e,n),lt=(e,n)=>(se(e)&&_(e,G),Ne(e,n)),tn=e=>!se(e.table),ut=o.relationExistsPushDown??"auto",ft=ut!=="never",{maxRelationKeys:ht}=o,_e=(e,n,s)=>vt(e,{fetcher:lt,maxRelationKeys:ht,relationBaseWhere:s,schema:t,tableName:n}),wt=async(e,n,s,f)=>{const h=K(e,"relation grouped count");if(h)return _(e,G),qn((W,I)=>h.count(W,I),e,n,s,f);const u=t.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);_(e,G);const c=de(u.softDeleteMode,void 0),l={[n]:{in:s}},w=Q(Q(l,f),c),R=await _e(w,e,void 0),g=te(R,$e),D=X(n);let M=i`SELECT ${D} AS __fk__, COUNT(*) AS count FROM ${i.identifier(e)}`;g&&(M=i`${M} WHERE ${g}`),M=i`${M} GROUP BY ${D}`;const U=O(r,M).toArray();return new Map(U.map(W=>[W.__fk__,W.count]))};let Te=0;const pt=new Set;for(const[e,n]of Object.entries(t.tables))for(const s of Object.values(n.triggerMap??{}))pt.add(`${e} ${s.timing} ${s.op}`);const Z=(e,n,s)=>pt.has(`${e} ${n} ${s}`),ee=async(e,n,s)=>{if(Te+=1,Te>kt)throw Te-=1,new ye(`trigger recursion exceeded ${String(kt)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await Pn({ctx:on,event:s,op:n,schema:t,tableName:s.table,timing:e})}finally{Te-=1}},{ensureBackfilledForTable:he,ensureBackfilledIndex:Oe,ensureRankBackfilled:je,ensureRankBackfilledForTable:we,syncAggregates:Re,syncCompanionsForInsert:gt,syncGeo:ve,syncRanks:pe,syncSearch:Ae}=sn({broadcast:a,indexKeysFor:(e,n)=>S(e,n),invalidateCache:(e,n,s)=>z?.invalidate(e,n,S(e,s)),recordCdc:fe,schema:t,sql:r}),$t=(e,n,s)=>{const{shardMode:f}=n;if(f?.kind==="shardBy"&&!(f.field!==void 0&&(s.partitionBy??[]).includes(f.field)))throw Object.assign(new Error(`rank index "${s.name}" on "${e}" partitions across shards (shard key "${f.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},yt=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),ie=(e,n)=>{const s=yt(n);for(let f=0;f<s.length;f+=ge){const h=s.slice(f,f+ge),[u]=me(r,ro(h),...io(e,h)).toArray();if(!u)continue;const c=u.__t__,l=le(u);if(typeof c!="string"||!l)return;const w=u[ne];return{docJson:typeof w=="string"?w:ce(w??{}),row:l,tableName:c}}},nn=(e,n)=>{const s=[...new Set(e)],f=new Map;if(s.length===0)return f;const h=yt(n);for(let u=0;u<h.length;u+=ge){const c=h.slice(u,u+ge),l=Math.floor(ge/c.length),w=Tn(i`${i.identifier("id")}`,s,!1,l),R=c.map(g=>i`SELECT ${i.raw(`'${g.replaceAll("'","''")}'`)} AS __t__, id FROM ${i.identifier(g)} WHERE ${w}`);for(const g of O(r,it(R))){const{id:D,__t__:M}=g;typeof M=="string"&&typeof D=="string"&&f.set(D,M)}}return f},Et={assertRankPartitionLocal:$t,ensureRankBackfilled:je,onRead:_,rowToDocument:le,schema:t,sql:r},B={system:Ge,async aggregate(e,n){const s=K(e,"aggregate");if(s)return _(e,G),s.aggregate(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);if(De(n.op),n.op==="count")return B.count(e,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new $("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);_(e,G);const h=de(f.softDeleteMode,void 0),u=Q(Q(n.baseWhere,n.where),h),c=await _e(u,e,n.relationBaseWhere),l=c!==u;if(f.aggregateIndexes&&!n.baseWhere&&!l&&(!h||Lt(f,[n.field]))){const W=wn(f.aggregateIndexes,n.op,n.field,n.where);if(W){Oe(e,W.index);const I=Qe(W.index.by??[],W.key),j=Ke(e,W.index.name),J=O(r,i`SELECT ${ke} AS value, ${Ve} AS count FROM ${i.identifier(j)} WHERE ${Le} = ${I}`).toArray()[0];return ze(n.op,J)}}Ft(f,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const w=te(c,$e),R=De(n.op),g=X(n.field);let D=i`SELECT ${i.raw(R)}(${g}) AS value FROM ${i.identifier(e)}`;w&&(D=i`${D} WHERE ${w}`);const U=O(r,D).toArray()[0]?.value;return U??null},asId(e,n){const s=qt(t,e,n);if(s===null)throw new $("BAD_REQUEST",`asId("${e}", …): "${n}" is not a valid id for table "${e}"`,{status:400});return s},async count(e,n){const s=K(e,"count");if(s)return _(e,G),s.count(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=un(n);if(h.restrictsCounts)throw new Je(e);_(e,G);const u=de(f.softDeleteMode,void 0),c=Q(Q(h.baseWhere,h.where),u),l=await _e(c,e,h.relationBaseWhere),w=l!==c;if(f.aggregateIndexes&&!h.baseWhere&&!w&&!u){const M=hn(f.aggregateIndexes,h.where);if(M){Oe(e,M.index);const U=Qe(M.index.by??[],M.key),W=Ke(e,M.index.name),I=O(r,i`SELECT ${ke} AS value FROM ${i.identifier(W)} WHERE ${Le} = ${U}`).toArray();return I[0]===void 0?0:I[0].value??0}}const R=te(l,$e);let g=i`SELECT COUNT(*) AS count FROM ${i.identifier(e)}`;return R&&(g=i`${g} WHERE ${R}`),O(r,g).one().count},async delete(e,n,s){const f=ie(e,n);if(!f){const g=n===void 0?C:void 0;g&&(x(void 0),await g.delete(e,void 0,s));return}const{docJson:h,row:u,tableName:c}=f,l=t.tables[c],w=s?.hard===!0,R=!w&&l?.softDeleteMode?l.softDeleteMode.field:void 0;if(!(R&&u[R]!==null&&u[R]!==void 0)){if(Z(c,"before","delete")&&await ee("before","delete",{id:e,op:"delete",previous:u,table:c}),await Fn({deletedId:e,deletedReference:g=>u[g],findHolders:async(g,D,M)=>(await He(g).findMany(g,{includeDeleted:w,where:{[D]:M}})).page,onCascade:(g,D)=>He(g).delete(D,void 0,s),onRestrict:g=>{throw new ye(g,"restrict")},onSetNull:(g,D,M)=>He(g).patch(D,{[M]:null}),schema:t,tableName:c}),he(c),we(c),R){const g={...u,...E(c),[R]:N(),_id:e};qe(r,c,Mt(c),[ce(g),e,h]),Ae(c,e,g,u),ve(c,e,void 0),Re(c,u,g),pe(c,e,u,void 0),z?.invalidate(c,e,S(c,u,g)),fe(c,e,"update",g),a({indexKeys:S(c,u,g),key:e,op:"update",row:g,table:c}),Z(c,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:u,table:c}),await q({id:e,op:"delete",table:c});return}qe(r,c,to(c),[e,h]),Ae(c,e,void 0),ve(c,e,void 0),Re(c,u,void 0),pe(c,e,u,void 0),z?.invalidate(c,e,S(c,u)),fe(c,e,"delete"),a({indexKeys:S(c,u),key:e,op:"delete",table:c}),Z(c,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:u,table:c}),await q({id:e,op:"delete",table:c})}},async deleteAll(e,n){if(!t.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);const s=Math.max(1,n?.chunkSize??Qt),f=n?.hard===void 0?void 0:{hard:n.hard},h=se(e)?void 0:e;let u=0;return await y(async()=>{for(;;){const l=(await B.findMany(e,{limit:s})).page.map(w=>String(w._id));if(l.length===0)break;for(const w of l)await B.delete(w,h,f),u+=1;if(l.length<s)break}}),{deleted:u}},async deleteMany(e,n,s){ae(e.length,n?.limit,"deleteMany");for(const f of e)await B.delete(f,s);return{deleted:e.length}},async deleteWhere(e,n,s){const u=(await(K(e,"deleteWhere")??B).findMany(e,{where:n})).page.map(c=>String(c._id));if(ae(u.length,s?.limit,"deleteWhere"),B.deleteMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return B.deleteMany(u,s)},async findFirst(e,n={}){return(await B.findMany(e,{...n,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,n={}){const s=await B.findFirst(e,n);if(s===null)throw new Cn(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,n={}){const s=K(e,"findMany");if(s)return _(e,G),s.findMany(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=!n.where&&!n.baseWhere;h?_(e,G):_(e);const u=et(n.orderBy,f.shape),c=n.cursor?jt(u,tt(n.cursor)):void 0;let l=Q(n.baseWhere,n.where);l=Q(l,de(f.softDeleteMode,n.includeDeleted)),l=await vt(l,{canPushExists:ft?tn:void 0,existsPushMode:ut==="always"?"always":"auto",fetcher:lt,maxRelationKeys:ht,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),c&&(l=l?{AND:[l,c]}:c);const w=ft?So(_):ct,R=te(l,w,Ue),g=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0,D=Yt(e,R,Zt(u),g===void 0?void 0:g+1),M=me(r,D.text,...D.params).toArray();h&&!L&&T?.recordRead(M.length);const U=[];for(const J of M){const P=le(J);P&&(U.push(P),!h&&typeof P._id=="string"&&_(e,P._id))}if(g===void 0)return n.with&&await At({groupedCounter:wt,fetcher:Ne,parents:U,...It(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:_t(U,n.select,n.with)};const W=U.length>g,I=W?U.slice(0,g):U,j=I.at(-1);return n.with&&await At({fetcher:Ne,groupedCounter:wt,parents:I,...It(n),schema:t,tableName:e,with:n.with}),{continueCursor:W&&j&&n.omitContinueCursor!==!0?nt(j,u):null,isDone:!W,page:_t(I,n.select,n.with)}},async get(e,n){const s=ie(e,n);if(!s){const f=n===void 0?C:void 0;return f?f.get(e):null}return _(s.tableName,e),s.row},async lookupById(e,n){const s=ie(e,n);return s?(_(s.tableName,e),{row:s.row,tableName:s.tableName}):null},async groupBy(e,n){const s=K(e,"groupBy");if(s)return _(e,G),s.groupBy(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);_(e,G);const h=n.agg??{op:"count"};if(De(h.op),h.op!=="count"&&!h.field)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const u=de(f.softDeleteMode,void 0),c=Q(Q(n.baseWhere,n.where),u),l=await _e(c,e,n.relationBaseWhere),w=l!==c,R=[...n.by,h.field];if(f.aggregateIndexes&&!n.baseWhere&&!w&&(!u||Lt(f,R))){const I=fn(f.aggregateIndexes,h.op,h.field,n.by,n.where),j=I===void 0?0:Object.keys(I.partial).length,J=I?.index.by?.length??0;if(I&&(j===0||j===J)){Oe(e,I.index);const P=Ke(e,I.index.name),Ie=Object.keys(I.partial),Ce=[];if(Ie.length===(I.index.by??[]).length&&Ie.length>0){const xe=Qe(I.index.by??[],I.partial),be=O(r,i`SELECT ${ke} AS value, ${Ve} AS count FROM ${i.identifier(P)} WHERE ${Le} = ${xe}`).toArray();return be.length>0&&Ce.push({key:{...I.partial},value:ze(h.op,be[0])}),Ce}const rn=O(r,i`SELECT ${Le} AS key, ${ke} AS value, ${Ve} AS count FROM ${i.identifier(P)}`).toArray();for(const xe of rn){const be=dn(JSON.parse(xe.key));Ce.push({key:be,value:ze(h.op,xe)})}return Ce}}for(const I of R){if(I===void 0)continue;const j=I===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${I}" } })`:`groupBy(${e}, { by: [..."${I}"] })`;Ft(f,I,j)}const g=te(l,$e),D=n.by.map(I=>i`${X(I)} AS ${i.identifier(I)}`);if(h.op==="count")D.push(i`COUNT(*) AS value`);else{const{field:I}=h;if(I===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);D.push(i`${i.raw(De(h.op))}(${X(I)}) AS value`)}let M=i`SELECT ${i.join(D,i`, `)} FROM ${i.identifier(e)}`;g&&(M=i`${M} WHERE ${g}`),M=i`${M} GROUP BY ${i.join(n.by.map(I=>X(I)),i`, `)}`;const U=O(r,M).toArray(),W=[];for(const I of U){const j={};for(const P of n.by)j[P]=I[P]??null;const{value:J}=I;W.push({key:j,value:J==null?null:Number(J)})}return W},async insert(e,n,s){const f=K(e,"insert");if(f)return dt(f,e,n,s,!0);const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const u=Wt(h,n,k);Xe(h,u);let c;s?.clientId!==void 0?(co(s.clientId),c=s.clientId):s?.allowExplicitId&&typeof u._id=="string"?c=u._id:c=m();const l=s?.allowExplicitId&&typeof u._creationTime=="number"?u._creationTime:N(),w={...u,...E(e),_creationTime:l,_id:c};return Z(e,"before","insert")&&await ee("before","insert",{doc:{...w},id:c,op:"insert",table:e}),he(e),we(e),ot(r,e,Zn(e),[c,l,ce(w)]),gt(e,c,w),Z(e,"after","insert")&&await ee("after","insert",{doc:w,id:c,op:"insert",table:e}),await q({doc:w,id:c,op:"insert",table:e}),c},async insertManyUnsafe(e,n,s){if(ae(n.length,s?.limit,"insertManyUnsafe"),n.length===0)return[];const f=K(e,"insert");if(f){const l=[];for(const w of n)x(w);for(const w of n){const R=await f.insert(e,w,{allowExplicitId:s?.allowExplicitId});a({key:R,op:"insert",row:{...w,_id:R},table:e}),l.push(R)}return l}const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);he(e),we(e);const u=[];for(let l=0;l<n.length;l+=Fe)u.push(E(e));const c=n.map((l,w)=>{const R=Wt(h,l,k),g=s?.allowExplicitId===!0&&typeof R._id=="string"?R._id:m(),D=s?.allowExplicitId===!0&&typeof R._creationTime=="number"?R._creationTime:N(),M={...R,...u[Math.floor(w/Fe)],_creationTime:D,_id:g};return{creationTime:D,document:M,id:g}});for(const l of c)x(l.document);for(let l=0;l<c.length;l+=Fe){const w=i.join(c.slice(l,l+Fe).map(g=>i`(${g.id}, ${g.creationTime}, ${ce(g.document)})`),i`, `),R=Nt("sqlite",i`INSERT INTO ${i.identifier(e)} (id, _creationTime, ${i.identifier(ne)}) VALUES ${w}`);ot(r,e,R.sql,R.params)}for(const{document:l,id:w}of c)gt(e,w,l),await F({doc:l,id:w,op:"insert",table:e});return c.map(l=>l.id)},async insertMany(e,n,s){ae(n.length,s?.limit,"insertMany");const f=s?.skipDuplicates===!0,h=[],u=K(e,"insert");if(u)for(const l of n)x(l);const c=async l=>u?dt(u,e,l,void 0,!1):B.insert(e,l);for(const l of n)try{h.push(await c(l))}catch(w){if(f&&w instanceof ye&&w.kind==="unique")h.push(null);else throw w}return h},normalizeId(e,n){return qt(t,e,n)},async patch(e,n,s){const f=ie(e,s);if(!f){const R=s===void 0?C:void 0;if(R){x(n),await R.patch(e,n);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:u,tableName:c}=f,l=t.tables[c];if(!l)throw new $("INTERNAL",`unknown table: ${c}`);_(c,e),Ut("patch",n);const w={...u,...n,...E(c),_id:e};Bt(l,n,w,k),Xe(l,w,!0),Z(c,"before","update")&&await ee("before","update",{doc:{...w},id:e,op:"update",previous:u,table:c}),he(c),we(c),qe(r,c,Mt(c),[ce(w),e,h]),Ae(c,e,w,u),ve(c,e,w),Re(c,u,w),pe(c,e,u,w),z?.invalidate(c,e,S(c,u,w)),fe(c,e,"update",w),a({indexKeys:S(c,u,w),key:e,op:"update",row:w,table:c}),Z(c,"after","update")&&await ee("after","update",{doc:w,id:e,op:"update",previous:u,table:c}),await q({doc:w,id:e,op:"update",table:c})},async patchMany(e,n,s){ae(e.length,n?.limit,"patchMany");for(const f of e)await B.patch(f.id,f.patch,s);return{patched:e.length}},async patchWhere(e,n,s){const u=(await(K(e,"patchWhere")??B).findMany(e,{where:n.where})).page.map(c=>({id:String(c._id),patch:n.patch}));if(ae(u.length,s?.limit,"patchWhere"),B.patchMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await B.patchMany(u,s),{patched:u.length}},query(e){const n=K(e,"query");return n?(_(e,G),n.query(e)):Mo(r,t,e,H,s=>{s?v(s):_(e,G)},s=>{L||T?.recordRead(s)})},async rank(e,n,s){const f=K(e,"rank");if(f)return _(e,G),f.rank(e,n,s);H(e,n,"rank");const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const u=h.rankIndexes?.find(P=>P.name===n);if(!u)throw new $("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if($t(e,h,u),s.restrictsCounts)throw new Je(e);_(e,G),je(e,u);const c=typeof s.row=="string"?s.row:s.row._id;if(!c)return null;const l=Tt(e,u.name),w=u.sortBy.map((P,Ie)=>Rt(Ie)),R=w.map(P=>Se(P)).join(", "),g=O(r,i`SELECT ${i.identifier("__partition__")}, ${i.raw(R)} FROM ${i.identifier(l)} WHERE ${i.identifier("__id__")} = ${c}`).toArray(),[D]=g;if(D===void 0)return null;let M=D.__partition__;const U=Q(s.baseWhere,s.where);Ye(U,t,e,"rank");const W=bn(u,U);if(W){const P=Mn(u.partitionBy??[],W);if(P!==M)return null;M=P}const I=w.map(P=>D[P]),{before:j,total:J}=Pt(r,l,w,u.sortBy,M,I,c);return{position:j+1,total:J}},async rankBefore(e,n,s){if(se(e))throw new $("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(w=>w.name===n);if(!h)throw new $("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(s.restrictsCounts)throw new Je(e);_(e,G),je(e,h);const u=Tt(e,h.name),c=h.sortBy.map((w,R)=>Rt(R)),l=h.sortBy.map((w,R)=>re(s.sortValues[R]??null));return Pt(r,u,c,h.sortBy,s.partitionKey,l,s.rowId)},async rankPage(e,n,s={}){Ye(Q(s.baseWhere,s.where),t,e,"rankPage");const f=K(e,"rankPage");if(f)return _(e,G),f.rankPage(e,n,s);H(e,n,"rank");const{continueCursor:h,hasMore:u,rows:c}=mt(Et,e,n,s);return{continueCursor:h,isDone:!u,page:c.map(l=>l.doc)}},async rankPageRows(e,n,s={}){Ye(Q(s.baseWhere,s.where),t,e,"rankPage"),H(e,n,"rank");const{directions:f,hasMore:h,rows:u}=mt(Et,e,n,s);return{directions:f,hasMore:h,rows:u}},async restore(e,n){const s=ie(e,n);if(!s){const u=n===void 0?C:void 0;if(u?.restore){await u.restore(e);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const f=t.tables[s.tableName]?.softDeleteMode?.field;if(!f)throw new $("INTERNAL",`ctx.db.restore: table "${s.tableName}" is not a .softDelete() table`);const h=s.row[f]!==null&&s.row[f]!==void 0;await B.patch(e,{[f]:null},n),h&&pe(s.tableName,e,void 0,s.row)},async replace(e,n,s,f){const h=ie(e,s);if(!h){const D=s===void 0?C:void 0;if(D){x(n),await D.replace(e,n,void 0,f);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:u,row:c,tableName:l}=h,w=t.tables[l];if(!w)throw new $("INTERNAL",`unknown table: ${l}`);Ut("replace",n);const R=f?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:N(),g={...n,...E(l),_creationTime:R,_id:e};Bt(w,n,g,k),Xe(w,g),Z(l,"before","update")&&await ee("before","update",{doc:{...g},id:e,op:"update",previous:c,table:l}),he(l),we(l),qe(r,l,eo(l),[R,ce(g),e,u]),Ae(l,e,g,c),ve(l,e,g),Re(l,c,g),pe(l,e,c,g),z?.invalidate(l,e,S(l,c,g)),fe(l,e,"update",g),a({indexKeys:S(l,c,g),key:e,op:"update",row:g,table:l}),Z(l,"after","update")&&await ee("after","update",{doc:g,id:e,op:"update",previous:c,table:l}),await q({doc:g,id:e,op:"update",table:l})},async wipeShard(e){const n=new Set(e?.exclude),s=e?.tables,f=Object.entries(t.tables).filter(([l,w])=>n.has(l)||s!==void 0&&!s.includes(l)?!1:w.shardMode?.kind!=="global").map(([l])=>l);if(s!==void 0){for(const l of s)if(!t.tables[l])throw new $("INTERNAL",`wipeShard: unknown table: ${l}`)}const h={};let u=0;const{deleteAll:c}=B;if(c===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of f){const w=await c(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[l]=w.deleted,u+=w.deleted}return{deleted:u,tables:h}}},on={db:B,scheduler:b};return o.enforceRls===!0?Wn(B,t,(e,n)=>ie(e,n)?.tableName,(e,n)=>nn(e,n)):B};export{yr as CDC_LOG_TABLE,Fr as CLIENT_WATERMARK_TABLE,Pr as GLOBAL_SHAPE_SNAPSHOT_TABLE,Qr as IDEMPOTENCY_TABLE,Co as NotUniqueError,ei as SEARCH_STATE_TABLE,qr as advanceClientWatermark,Er as applyCdcChanges,Ut as assertNoExplicitUndefined,co as assertValidClientId,wr as backfillAggregateIndexes,pr as backfillRankIndexes,gr as backfillSearchIndexes,mr as bumpCdcEpoch,Sr as cdcCanVouchFor,_r as cdcSeqLeavingRows,Tr as cdcTouchesTables,Rr as cdcTrimmedError,vr as compactCdcDocs,ur as createShardCtxDb,Ar as cursorBelowRetainedFloor,Gr as deleteGlobalShapeSnapshot,Hr as deleteGlobalShapeSnapshotsForConnection,Wr as migrateClientWatermark,Nr as migrateGlobalShapeSnapshot,Ir as minCdcReplayableSeq,Cr as minCdcSeq,qt as normalizeIdStructurally,xr as readCdcChangeKeys,br as readCdcChanges,Mr as readCdcCursor,Dr as readCdcEpoch,Br as readClientWatermark,Or as readGlobalShapeSnapshot,zr as readIdempotent,Xr as runShardMigrations,ni as selectShapeMembers,oi as selectShapeRows,kr as trimCdcChanges,Jr as trimIdempotent,jr as writeGlobalShapeSnapshot,Vr as writeIdempotent};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as o}from"./runDrizzle-2ULFQR_k.mjs";const r="__lunora_search_state",a=i=>{o(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(r)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("cursor")} TEXT, ${e.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${e.identifier("profile")} TEXT, ${e.identifier("covered")} INTEGER NOT NULL DEFAULT 0)`);try{o(i,e`ALTER TABLE ${e.identifier(r)} ADD COLUMN ${e.identifier("profile")} TEXT`)}catch{}try{o(i,e`ALTER TABLE ${e.identifier(r)} ADD COLUMN ${e.identifier("covered")} INTEGER NOT NULL DEFAULT 0`)}catch{}o(i,e`UPDATE ${e.identifier(r)} SET ${e.identifier("covered")} = 1 WHERE ${e.identifier("done")} = 1 AND ${e.identifier("covered")} = 0`)},f=i=>i===1||i===!0||i==="1",s=(i,d)=>{const t=o(i,e`SELECT ${e.identifier("covered")} FROM ${e.identifier(r)} WHERE ${e.identifier("companion")} = ${d}`).toArray();return f(t[0]?.covered)},A=(i,d)=>{const n=o(i,e`SELECT ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")} FROM ${e.identifier(r)} WHERE ${e.identifier("companion")} = ${d}`).toArray()[0];return n?{cursor:n.cursor??void 0,done:f(n.done),profile:n.profile??void 0}:{cursor:void 0,done:!1,profile:void 0}},L=(i,d,t,n,c)=>{const $=t??null;o(i,e`INSERT INTO ${e.identifier(r)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("covered")}) VALUES (${d}, ${$}, ${n?1:0}, ${c}, ${n?1:0}) ON CONFLICT (${e.identifier("companion")}) DO UPDATE SET ${e.identifier("cursor")} = excluded.${e.identifier("cursor")}, ${e.identifier("done")} = excluded.${e.identifier("done")}, ${e.identifier("profile")} = excluded.${e.identifier("profile")}, ${e.identifier("covered")} = MAX(${e.identifier(r)}.${e.identifier("covered")}, excluded.${e.identifier("covered")})`)};export{r as SEARCH_STATE_TABLE,a as migrateSearchState,A as readSearchBackfillState,s as readSearchIndexCoverage,L as writeSearchBackfillState};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as D}from"@lunora/errors";import{applySelect as I}from"./CURSOR_PREFIX-CoJUQfCI.mjs";const W=Symbol.for("lunora.relations.fanOutBudget"),U=o=>({fanOutBudget:o[W],relationBaseWhere:o.relationBaseWhere,relationMask:o.relationMask}),A=(o,n)=>n.select?I(o,n.select,n.with):o,x=async(o,n,r,a,t)=>{const l=await Promise.all(a.map(async i=>{const h=t?{AND:[{[r]:i},t]}:{[r]:i};return[i,await o(n,h)]}));return new Map(l)},S=32,C=(o,n,r)=>{const a=new Map;for(const t of o)for(const l of r(t)){const i=l[n],h=a.get(i);h?h.push(l):a.set(i,[l])}return a},_=(o,n)=>({...o,[W]:n}),B=(o,n)=>{const r=new Set;for(const a of o){const t=a[n];t!=null&&r.add(t)}return[...r]},H=async o=>{const{groupedCounter:n,fanOutBudget:r,fetcher:a,parents:t,relationBaseWhere:l,relationMask:i,schema:h,tableName:m,with:v}=o,w=r??{remaining:S},k=(c,e)=>i?.(c,e)??e;if(t.length===0)return;const N=h.tables[m];if(!N)throw new D("INTERNAL",`unknown table: ${m}`);const O=N.relationMap??{},R=c=>{const e=O[c];if(!e)throw new D("INTERNAL",`unknown relation "${c}" on table "${m}"`);return e},V=async(c,e,s)=>{const u=B(t,e.field);if(u.length===0){for(const d of t)d[c]=null;return}const{page:p}=await a(e.table,_({baseWhere:l?.(e.table),relationBaseWhere:l,relationMask:i,where:{[e.references]:{in:u}},with:s.with},w)),b=new Map;for(const d of k(e.table,p))b.set(d[e.references],d);for(const d of t){const y=b.get(d[e.field]);d[c]=y?A([y],s)[0]??null:null}},$=async(c,e,s)=>{const u=B(t,e.references);if(u.length===0){for(const f of t)f[c]=[];return}const p=typeof s.limit=="number"?Math.max(0,Math.floor(s.limit)):void 0,b=async(f,g)=>{const{page:E}=await a(e.table,_({baseWhere:l?.(e.table),limit:g,orderBy:s.orderBy,relationBaseWhere:l,relationMask:i,where:s.where?{AND:[s.where,f]}:f,with:s.with},w));return E};if(p===0){for(const f of t)f[c]=[];return}const d=p!==void 0&&u.length<=w.remaining;d&&(w.remaining-=u.length);const y=d?await Promise.all(u.map(async f=>b({[e.field]:f},p))):[await b({[e.field]:{in:u}},void 0)],M=C(y,e.field,f=>k(e.table,f));for(const f of t){const g=M.get(f[e.references])??[];f[c]=A(p===void 0?g:g.slice(0,p),s)}},j=async c=>{for(const e of Object.keys(c)){const s=R(e),[u,p]=s.kind==="many"?[s.field,s.references]:[s.references,s.field],b=l?.(s.table),d=B(t,p),y=d.length===0?new Map:await n(s.table,u,d,b);for(const M of t){const f=M._count??{},g=M[p];f[e]=g==null?0:y.get(g)??0,M._count=f}}};for(const[c,e]of Object.entries(v)){if(e===void 0||e===!1)continue;if(c==="_count"){await j(e);continue}const s=R(c),u=e===!0?{}:e;await(s.kind==="one"?V(c,s,u):$(c,s,u))}},F=async(o,n,r)=>{const{deletedId:a,deletedReference:t,findHolders:l,onCascade:i,onRestrict:h,onSetNull:m,tableName:v}=o,w=r.references==="_id"?a:t(r.references);if(w==null)return;const k=await l(n,r.field,w);if(k.length!==0){r.onDelete==="restrict"&&h(`cannot delete "${v}" row: "${n}.${r.field}" still references it`);for(const N of k){const O=N._id;typeof O=="string"&&await(r.onDelete==="cascade"?i(n,O):m(n,O,r.field))}}},P=async o=>{const{schema:n,tableName:r}=o;if(!n.tables[r])throw new D("INTERNAL",`unknown table: ${r}`);for(const[a,t]of Object.entries(n.tables)){const l=t.relationMap;if(l)for(const i of Object.values(l))i.kind!=="one"||i.table!==r||!i.onDelete||await F(o,a,i)}},q=(o,n,r=!1)=>{for(const[a,t]of Object.entries(o.shape))a in n&&typeof t.parse=="function"&&(r&&n[a]===null&&t.kind==="optional"||t.parse(n[a]))};export{P as applyOnDelete,B as distinctValues,x as fanOutScalarCounts,U as relationHooks,H as resolveWith,q as runRowValidators};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{S as T,q as b,r as O,i as C,l as h,y as L,d as M}from"./ctx-db-companions-BFBIVIOd.mjs";import{sql as t}from"drizzle-orm";import{matchesStaticWhere as x}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as _,encodeAggregateKey as y,foldAggregateTally as F}from"./aggregateTableName-CGi8gxeK.mjs";import{migrateSearchState as N,readSearchBackfillState as E,readSearchIndexCoverage as D,writeSearchBackfillState as v}from"./SEARCH_STATE_TABLE-xmYM_nOd.mjs";import{runDrizzle as l}from"./runDrizzle-2ULFQR_k.mjs";import{i as p,r as w,a as B,b as G,A as U,D as I,h as H}from"./do-sql-bkXQEBl8.mjs";import{isLiveForCompanion as P}from"./CURSOR_PREFIX-CoJUQfCI.mjs";import{rankTableName as W,matchesRankStaticWhere as V}from"./RANK_TIEBREAK-D157XEqw.mjs";const R=(e,o)=>e.profile!==o?{cursor:void 0,finished:!1,wipe:e.cursor!==void 0||e.done}:{cursor:e.cursor,finished:e.done,wipe:!1},k=(e,o)=>l(e,t`SELECT COUNT(*) AS count FROM ${t.identifier(o)}`).one().count>0,Y=(e,o)=>l(e,t`SELECT 1 FROM ${t.identifier(o)} LIMIT 1`).toArray().length>0,A=(e,o)=>l(e,t`SELECT id, _creationTime, ${t.identifier(I)} FROM ${t.identifier(o)}`).toArray(),j=(e,o,n,r)=>{const i=_(o,n.name);if(k(e,i))return;const c=n.by??[],a=new Map,s=A(e,o);for(const d of s){const f=w(d);if(!f||!P(f,r)||n.where&&!x(f,n.where))continue;const g=y(c,f);F(a,g,n,f)}for(const[d,f]of a)l(e,t`INSERT INTO ${t.identifier(i)} (${B}, ${G}, ${U}) VALUES (${d}, ${f.value}, ${f.count})`)},te=(e,o)=>{for(const[n,r]of Object.entries(o.tables))if(!(r.shardMode?.kind==="global"||!r.aggregateIndexes))for(const i of r.aggregateIndexes)j(e,n,i,r.softDeleteMode?.field)},K=(e,o,n)=>{const r=W(o,n.name);if(k(e,r))return;const i=O(n),c=A(e,o);for(const a of c){const s=w(a);!s||n.where&&!V(s,n.where)||C(e,r,n,i,s._id,s)}},ie=(e,o)=>{for(const[n,r]of Object.entries(o.tables))if(!(r.shardMode?.kind==="global"||!r.rankIndexes))for(const i of r.rankIndexes)K(e,n,i)},m=500,$=(e,o,n)=>{const r=T(o,n.name),{profile:i}=b(n.language),c=R(E(e,r),i);if(c.finished)return{done:!0,rows:0};const{cursor:a}=c,s=l(e,a===void 0?t`SELECT id, _creationTime, ${t.identifier(I)} FROM ${t.identifier(o)} ORDER BY id ASC LIMIT ${t.raw(String(m))}`:t`SELECT id, _creationTime, ${t.identifier(I)} FROM ${t.identifier(o)} WHERE id > ${a} ORDER BY id ASC LIMIT ${t.raw(String(m))}`).toArray();let d=a;for(const g of s){const{id:u}=g;if(typeof u!="string")continue;d=u,l(e,t`DELETE FROM ${t.identifier(r)} WHERE ${t.identifier(h)} = ${u}`);const S=H(g);S&&l(e,t`INSERT INTO ${t.identifier(r)} (${t.identifier(L)}, ${t.identifier(h)}) VALUES (${M(S,n)}, ${u})`)}const f=s.length<m;return v(e,r,d,f,i),{done:f,rows:s.length}},ae=(e,o,n)=>{const r=T(o,n.name),{profile:i}=b(n.language);return R(E(e,r),i).finished?!0:D(e,r)},se=(e,o,n)=>{if(p(e))for(const r of n.searchIndexes??[])r.staged&&Y(e,o)||$(e,o,r)},z=(e,o,n,r)=>{let i=0;for(;;){if(i>=r)return{done:!1,pages:i};const c=$(e,o,n);if(c.rows>0&&(i+=1),c.done)return{done:!0,pages:i}}},ce=(e,o,n={})=>{if(!p(e))return{done:!0,pages:0};N(e);const r=n.maxPages??Number.POSITIVE_INFINITY;let i=0;for(const[c,a]of Object.entries(o.tables))if(!(a.shardMode?.kind==="global"||!a.searchIndexes))for(const s of a.searchIndexes){const d=z(e,c,s,r-i);if(i+=d.pages,!d.done)return{done:!1,pages:i}}return{done:!0,pages:i}};export{te as backfillAggregateIndexes,ie as backfillRankIndexes,ce as backfillSearchIndexes,se as backfillSearchIndexesForTable,ae as searchIndexCoversTable};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-gl0FuepJ.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-
|
|
1
|
+
import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-gl0FuepJ.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-CLK9q18N.mjs";import{shapeRangeKey as u}from"./ShapeDiffCache-CLm5XXd1.mjs";import{projectColumns as g}from"./buildPokeFrames-C8km3IhJ.mjs";const C=(m,e,a,i,p,f=s)=>{const r=u(e.table,a,i),n=p.changedKeys(r,()=>f(m,e.table,a,i));if(n.length===0)return[];const b=p.members(e,r,()=>h(m,e.table,e.effectiveWhere,n.map(t=>t.id))),o=[];for(const t of n){const c=b.get(t.id);if(c===void 0){t.op!=="insert"&&o.push({key:t.id,op:"delete",table:e.table});continue}o.push({key:t.id,op:t.op,table:e.table,value:g(c,e.columns)})}return o};export{C as buildShapeDiff};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./param-DlozcSQu.mjs";import{c as o,l as t}from"./where-sql-
|
|
1
|
+
import"./param-DlozcSQu.mjs";import{c as o,l as t}from"./where-sql-4RHk2frP.mjs";import"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";export{o as compileWhereSql,t as literalInList};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as g}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{mergeWhere as j}from"./CountRlsUnsupportedError-Bdfupt3g.mjs";import{SCAN_DEP as q}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as A}from"./runDrizzle-2ULFQR_k.mjs";import{sqliteInList as O}from"./param-DlozcSQu.mjs";import{decodeCursor as F,CURSOR_PREFIX as U,toBase64 as V}from"./CURSOR_PREFIX-
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{mergeWhere as j}from"./CountRlsUnsupportedError-Bdfupt3g.mjs";import{SCAN_DEP as q}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as A}from"./runDrizzle-2ULFQR_k.mjs";import{sqliteInList as O}from"./param-DlozcSQu.mjs";import{decodeCursor as F,CURSOR_PREFIX as U,toBase64 as V}from"./CURSOR_PREFIX-CoJUQfCI.mjs";import{rankTableName as z,sortColumnName as H,resolveRankPartition as P,RANK_TIEBREAK as _,encodePartitionKey as J}from"./RANK_TIEBREAK-D157XEqw.mjs";const X="__doc__",Y=n=>U+V(JSON.stringify(n)),G=n=>n.after?[n.after.partitionKey,...n.after.sortValues,n.after.rowId]:n.cursor?F(n.cursor):void 0,Q=(n,r,a)=>{if(n?.length!==1+r.length+1)return;const t=[{column:"__partition__",direction:"asc"}];for(const[s,c]of r.entries())t.push({column:c,direction:a[s]?.direction??"asc"});t.push({column:_,direction:"asc"});const e=[];for(const[s,c]of t.entries()){const u=[];for(const[i,p]of t.slice(0,s).entries())u.push(o`${o.identifier(p.column)} IS ${n[i]}`);u.push(o`${o.identifier(c.column)} ${o.raw(c.direction==="desc"?"<":">")} ${n[s]}`);const[f]=u;e.push(u.length===1&&f!==void 0?f:o`(${o.join(u,o` AND `)})`)}return o`(${o.join(e,o` OR `)})`},T=null,Z=(n,r)=>{if(n===void 0)return T;const a=[n.__partition__,...r.map(t=>n[t]),n[_]];return Y(a)},oo=(n,r,a)=>{const t=[];for(const e of n){const s=e[_];if(typeof s!="string")continue;const c=r.get(s);if(!c)continue;const u=typeof e.__partition__=="string"?e.__partition__:"",f=a.map(i=>e[i]??null);t.push({doc:c,key:{partitionKey:u,rowId:s,sortValues:f}})}return t},no=o`${o.identifier("id")}`,to=(n,r,a)=>{const{rowToDocument:t}=n,e=new Map;if(a.length===0)return e;const s=A(n.sql,o`SELECT id, _creationTime, ${o.identifier(X)} FROM ${o.identifier(r)} WHERE ${O(no,a,!1)}`).toArray();for(const c of s){const u=t(c),f=c.id;u&&typeof f=="string"&&e.set(f,u)}return e},lo=(n,r,a,t)=>{const{assertRankPartitionLocal:e,ensureRankBackfilled:s,onRead:c,schema:u}=n,f=u.tables[r];if(!f)throw new g("INTERNAL",`unknown table: ${r}`);const i=f.rankIndexes?.find(d=>d.name===a);if(!i)throw new g("INTERNAL",`unknown rankIndex "${a}" on table "${r}"`);e(r,f,i),c(r,q),s(r,i);const p=z(r,i.name),l=i.sortBy.map((d,w)=>H(w)),h=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),B=j(t.baseWhere,t.where),k=P(i,B),$=[o`${o.identifier("__partition__")} ASC`];for(const[d,w]of l.entries()){const b=i.sortBy[d]?.direction;$.push(o`${o.identifier(w)} ${o.raw(b==="desc"?"DESC":"ASC")}`)}$.push(o`${o.identifier(_)} ASC`);const m=[];typeof t.partitionKey=="string"?m.push(o`${o.identifier("__partition__")} = ${t.partitionKey}`):k&&m.push(o`${o.identifier("__partition__")} = ${J(i.partitionBy??[],k)}`);const D=G(t),E=Q(D,l,i.sortBy);E&&m.push(E);const I=o.identifier(_),S=o.identifier("__partition__"),L=m.length>0?o` WHERE ${o.join(m,o` AND `)}`:o``,M=l.length>0?o`${I}, ${S}, ${o.join(l.map(d=>o.identifier(d)),o`, `)}`:o`${I}, ${S}`,v=o`SELECT ${M} FROM ${o.identifier(p)}${L} ORDER BY ${o.join($,o`, `)} LIMIT ${o.raw(String(h+1))}`,R=A(n.sql,v).toArray(),C=R.length>h,y=C?R.slice(0,h):R,K=y.map(d=>d[_]),x=oo(y,to(n,r,K),l),N=C?Z(y.at(-1),l):T,W=i.sortBy.map(d=>d.direction==="desc"?"desc":"asc");return{continueCursor:N,directions:W,hasMore:C,rows:x}};export{lo as computeRankPage,G as resolveRankSeekTuple};
|
package/dist/packem_shared/{createCompanionSync-CJo2Uiq7.mjs → createCompanionSync-Bo-oIkyU.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as l,i as C,r as R}from"./ctx-db-companions-
|
|
1
|
+
import{c as l,i as C,r as R}from"./ctx-db-companions-BFBIVIOd.mjs";import"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import"./aggregateTableName-CGi8gxeK.mjs";import"./runDrizzle-2ULFQR_k.mjs";import"./do-sql-bkXQEBl8.mjs";import"./param-DlozcSQu.mjs";import"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import"./CURSOR_PREFIX-CoJUQfCI.mjs";import"./RANK_TIEBREAK-D157XEqw.mjs";import"./sql-projection-BqmxFxQU.mjs";import"./serializeSqlValue-DbI1VQYM.mjs";export{l as createCompanionSync,C as insertRankRow,R as rankColumnsSql};
|
package/dist/packem_shared/{ctx-db-companions-CN8hWTF_.mjs → ctx-db-companions-BFBIVIOd.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{matchesStaticWhere as P,aggregateSqlFunction as le}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as N,encodeAggregateKey as I,foldAggregateTally as J,coerceAggregateNumber as C}from"./aggregateTableName-CGi8gxeK.mjs";import{runDrizzle as $}from"./runDrizzle-2ULFQR_k.mjs";import{i as fe,g as ue,D,r as M,a as q,b as S,A as g,c as j,e as z}from"./do-sql-bkXQEBl8.mjs";import{param as de,WORKERD_SQLITE_LIMITS as $e}from"./param-DlozcSQu.mjs";import{encodeGeohash as me,GEO_DEFAULT_PRECISION as Ee}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as Q}from"./CURSOR_PREFIX-
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{matchesStaticWhere as P,aggregateSqlFunction as le}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as N,encodeAggregateKey as I,foldAggregateTally as J,coerceAggregateNumber as C}from"./aggregateTableName-CGi8gxeK.mjs";import{runDrizzle as $}from"./runDrizzle-2ULFQR_k.mjs";import{i as fe,g as ue,D,r as M,a as q,b as S,A as g,c as j,e as z}from"./do-sql-bkXQEBl8.mjs";import{param as de,WORKERD_SQLITE_LIMITS as $e}from"./param-DlozcSQu.mjs";import{encodeGeohash as me,GEO_DEFAULT_PRECISION as Ee}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as Q}from"./CURSOR_PREFIX-CoJUQfCI.mjs";import{encodePartitionKey as pe,sortColumnName as he,rankTableName as Z,matchesRankStaticWhere as x}from"./RANK_TIEBREAK-D157XEqw.mjs";import{m as ge}from"./sql-projection-BqmxFxQU.mjs";import{serializeSqlValue as ee}from"./serializeSqlValue-DbI1VQYM.mjs";const ye=["de","en","es","fr","it","nl","none","pt"],_e=n=>ye.includes(n),Se="a an and are as at be but by for if in into is it no not of on or such that the their then there these they this to was will with",we="aber als am an auch auf aus bei bin bis bist da dass der den des dem die das denn dir du ein eine für hat ich im in ist mit nicht noch nur oder sich sie sind über und von vor war wie wir zu zum zur",Te="a al como con de del el en es la las lo los mas no o para pero por que se su sus un una uno y ya",ve="au aux avec ce ces dans de des du elle en et eux il je la le les leur lui ma mais me même mes moi mon ne nos notre nous on ou par pas pour qu que qui sa se ses son sur ta te tes toi ton tu un une vos votre vous y",Re="a ai al alla anche che chi ci coi col come con da dal degli dei del della di do e ed gli ha hai hanno i il in la le lo ma mi ne nei nel non o per più quale quanto se si sono su sul tra un una uno vi",Ae="aan al als bij dan dat de der deze die dit door een en er het hij ij in is je kan me men met mij na naar niet nog nu of om ons ook op over te tot uit van voor was wat we wij zij zijn zo",Fe="a ao aos as até com como da das de do dos e em entre era essa esse esta este eu foi há isso já mais mas me mesmo meu na nas no nos num numa o os ou para pela pelo por qual que quem se sem seu só sua também te tem um uma você",be=/[\u0300-\u036F]/gu,Oe=/[\u0080-\u{10FFFF}]/u,Le=/[\p{L}\p{N}]+/gu,oe=n=>Oe.test(n)?n.normalize("NFD").replaceAll(be,"").normalize("NFC").toLowerCase():n.toLowerCase(),k=n=>new Set(oe(n).split(" ")),Ie={de:k(we),en:k(Se),es:k(Te),fr:k(ve),it:k(Re),nl:k(Ae),none:new Set,pt:k(Fe)},ke=2,qe=256,X=new Map,Ce=n=>{const s=n!==void 0&&_e(n)?n:"none",c=X.get(s);if(c)return c;const w=Ie[s],y=r=>{const A=(oe(r).match(Le)??[]).filter(T=>T.length<=qe);return w.size===0?A:A.filter(T=>!w.has(T))},E={document:y,profile:`${s}-v${String(ke)}`,query:r=>{const A=y(r);return A.filter((T,b)=>A.lastIndexOf(T)===b)}};return X.set(s,E),E},je=(n,s)=>{if(!s.includes("."))return n[s];let c=n;for(const w of s.split(".")){if(c===null||typeof c!="object"||Array.isArray(c))return;c=c[w]}return c},De=(n,s)=>`${n}__fts_${s}`,Me="__text__",Y="__id__",ze=1e3,Ue=(n,s)=>s.document(n),U=(n,s)=>je(n,s),We=n=>typeof n=="string"?n:n==null?"":typeof n=="number"||typeof n=="bigint"||typeof n=="boolean"?String(n):JSON.stringify(n)??"",He=(n,s,c)=>n!==void 0&&s!==void 0&&U(n,c.field)===U(s,c.field),Be=(n,s)=>Ue(We(U(n,s.field)),Ce(s.language)).slice(0,ze),Ke=(n,s)=>Be(n,s).join(" "),Ve=(n,s,c)=>[...n.partitionBy??[],...n.sortBy.map(y=>y.field),...n.where?Object.keys(n.where):[]].every(y=>s[y]===c[y]),ne=n=>e.join(["__id__","__partition__",...n.sortBy.map((s,c)=>he(c))].map(s=>e.identifier(s)),e`, `),te=(n,s,c,w,y,E)=>{const r=pe(c.partitionBy??[],E),A=c.sortBy.map(b=>ee(E[b.field]??null)),T=e.join([y,r,...A].map(b=>de(b)),e`, `);$(n,e`INSERT INTO ${e.identifier(s)} (${w}) VALUES (${T})`)},Ge=(n,s,c,w,y,E)=>{if(y&&E&&Ve(c,y,E))return;const r=Z(s,c.name);y&&$(n,e`DELETE FROM ${e.identifier(r)} WHERE ${e.identifier("__id__")} = ${w}`),!(!E||c.where&&!x(E,c.where))&&te(n,r,c,ne(c),w,E)},so=n=>{const{broadcast:s,indexKeysFor:c,invalidateCache:w,recordCdc:y,schema:E,sql:r}=n,A=new Set,T=t=>E.tables[t]?.softDeleteMode?.field,b=new Set,W=(t,o)=>{const a=`${t}::${o.name}`;if(A.has(a))return;const f=N(t,o.name),u=o.by??[],d=T(t),p=new Map,_=$(r,e`SELECT id, _creationTime, ${e.identifier(D)} FROM ${e.identifier(t)}`).toArray();for(const v of _){const m=M(v);if(!m||!Q(m,d)||o.where&&!P(m,o.where))continue;const R=I(u,m);J(p,R,o,m)}$(r,e`DELETE FROM ${e.identifier(f)}`);const F=Math.floor($e.boundParams/3),O=[...p];for(let v=0;v<O.length;v+=F){const m=O.slice(v,v+F),R=e.join(m.map(([i,l])=>e`(${i}, ${l.value}, ${l.count})`),e`, `);$(r,e`INSERT INTO ${e.identifier(f)} (${q}, ${S}, ${g}) VALUES ${R}`)}A.add(a)},se=(t,o,a)=>{const f=o.by??[],u=o.field??"",d=[],p=(i,l)=>{const h=ee(l);h===null?d.push(e`${z(i)} IS NULL`):d.push(e`${z(i)} = ${h}`)};for(const i of f)p(i,a[i]??null);const _=T(t);_!==void 0&&p(_,null);for(const[i,l]of Object.entries(o.where??{}))p(i,l!==null&&typeof l=="object"&&!Array.isArray(l)?l.eq:l);const F=d.length>0?e` WHERE ${e.join(d,e` AND `)}`:e``,O=E.tables[t]?.shape[u];if(O&&ge(O)){const i=$(r,e`SELECT id, _creationTime, ${e.identifier(D)} FROM ${e.identifier(t)}${F}`).toArray(),l=new Map;for(const h of i){const L=M(h);L&&J(l,"",o,L)}return{value:l.get("")?.value??null}}const v=le(o.op),m=z(u);return{value:$(r,e`SELECT ${e.raw(v)}(${m}) AS value FROM ${e.identifier(t)}${F}`).one().value??null}},ie=(t,o,a,f)=>{const u=N(t,o.name),{op:d}=o,p=o.field??"",_=i=>{$(r,e`DELETE FROM ${e.identifier(u)} WHERE ${q} = ${i} AND ${g} <= 0`)},F=T(t),O=i=>!o.where||P(i,o.where),v=i=>Q(i,F)&&O(i);f!==void 0&&d!=="count"&&O(f)&&C(f[p]);const m=a&&v(a)?a:void 0,R=f&&v(f)?f:void 0;if(!(!m&&!R)){if(d==="count"){for(const[i,l]of[[m,-1],[R,1]]){if(!i)continue;const h=I(o.by??[],i);$(r,j(u,h,l,l,e`${S} = ${S} + excluded.${S}, ${g} = ${g} + excluded.${g}`))}m&&_(I(o.by??[],m));return}if(d==="sum"||d==="avg"){for(const[i,l]of[[m,-1],[R,1]]){if(!i)continue;const h=C(i[p]);if(h===void 0)continue;const L=I(o.by??[],i);$(r,j(u,L,l*h,l,e`${S} = COALESCE(${S}, 0) + excluded.${S}, ${g} = ${g} + excluded.${g}`))}m&&_(I(o.by??[],m));return}if(m){const i=I(o.by??[],m),l=C(m[p]),h=$(r,e`SELECT ${S} AS value, ${g} AS count FROM ${e.identifier(u)} WHERE ${q} = ${i}`).toArray()[0],L=(h?.count??0)-1;if(L<=0)$(r,e`DELETE FROM ${e.identifier(u)} WHERE ${q} = ${i}`);else if(h&&l!==void 0&&h.value!==null&&l===h.value){const ce=se(t,o,m);$(r,e`UPDATE ${e.identifier(u)} SET ${S} = ${ce.value}, ${g} = ${L} WHERE ${q} = ${i}`)}else $(r,e`UPDATE ${e.identifier(u)} SET ${g} = ${g} - 1 WHERE ${q} = ${i}`)}if(R){const i=I(o.by??[],R),l=C(R[p]);if(l===void 0)$(r,j(u,i,null,1,e`${g} = ${g} + 1`));else{const h=d==="min"?"MIN":"MAX";$(r,j(u,i,l,1,e`${S} = ${e.raw(h)}(COALESCE(${S}, excluded.${S}), excluded.${S}), ${g} = ${g} + 1`))}}}},re=t=>{for(const o of E.tables[t]?.aggregateIndexes??[])W(t,o)},H=(t,o,a)=>{for(const f of E.tables[t]?.aggregateIndexes??[])ie(t,f,o,a)},B=(t,o)=>{const a=`${t}::rank::${o.name}`;if(b.has(a))return;const f=Z(t,o.name),u=$(r,e`SELECT id, _creationTime, ${e.identifier(D)} FROM ${e.identifier(t)}`).toArray();$(r,e`DELETE FROM ${e.identifier(f)}`);const d=ne(o);for(const p of u){const _=M(p);!_||o.where&&!x(_,o.where)||te(r,f,o,d,_._id,_)}b.add(a)},ae=t=>{for(const o of E.tables[t]?.rankIndexes??[])B(t,o)},K=(t,o,a,f)=>{for(const u of E.tables[t]?.rankIndexes??[])Ge(r,t,u,o,a,f)},V=(t,o,a,f)=>{const u=E.tables[t]?.searchIndexes??[];if(!(u.length===0||!fe(r)))for(const d of u){if(He(f,a,d))continue;const p=De(t,d.name);$(r,e`DELETE FROM ${e.identifier(p)} WHERE ${e.identifier(Y)} = ${o}`),a&&$(r,e`INSERT INTO ${e.identifier(p)} (${e.identifier(Me)}, ${e.identifier(Y)}) VALUES (${Ke(a,d)}, ${o})`)}},G=(t,o,a)=>{for(const f of E.tables[t]?.geoIndexes??[]){const u=ue(t,f.name);$(r,e`DELETE FROM ${e.identifier(u)} WHERE ${e.identifier("__id__")} = ${o}`);const d=a?.[f.field];if(d!==null&&typeof d=="object"&&typeof d.lat=="number"&&typeof d.lng=="number"){const{lat:p,lng:_}=d,F=me({lat:p,lng:_},f.precision??Ee);$(r,e`INSERT INTO ${e.identifier(u)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${o}, ${F}, ${p}, ${_})`)}}};return{ensureBackfilledForTable:re,ensureBackfilledIndex:W,ensureRankBackfilled:B,ensureRankBackfilledForTable:ae,syncAggregates:H,syncCompanionsForInsert:(t,o,a)=>{V(t,o,a),G(t,o,a),H(t,void 0,a),K(t,o,void 0,a),w(t,o,a),y(t,o,"insert",a),s({indexKeys:c(t,a),key:o,op:"insert",row:a,table:t})},syncGeo:G,syncRanks:K,syncSearch:V}};export{De as S,Be as a,so as c,Ke as d,te as i,Y as l,Ce as q,ne as r,Me as y};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import{sql as i}from"drizzle-orm";import{e as l,d as E}from"./wire-codec-COhOSEe4.mjs";import{runDrizzle as a}from"./runDrizzle-2ULFQR_k.mjs";import{relayProxyKey as T}from"./DEFAULT_PROMOTION_THRESHOLDS-DcJw42RT.mjs";const t="__lunora_relay_shapes",o=null,R=e=>{a(e,i`CREATE TABLE IF NOT EXISTS ${i.identifier(t)} (
|
|
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
|
+
)`)},s=e=>JSON.stringify(l(e)),c=e=>E(JSON.parse(e)),$=e=>a(e,i`SELECT key, relay_idx, connection_id, name, args, identity, cursor FROM ${i.identifier(t)}`).toArray().map(r=>({args:c(r.args),connectionId:r.connection_id??void 0,cursor:Number(r.cursor),identity:c(r.identity),key:r.key,name:r.name,relayIndex:r.relay_idx===null?void 0:Number(r.relay_idx)})),L=(e,n)=>{a(e,i`INSERT INTO ${i.identifier(t)} (key, relay_idx, connection_id, name, args, identity, cursor)
|
|
10
|
+
VALUES (${n.key}, ${n.relayIndex??o}, ${n.connectionId??o}, ${n.name}, ${s(n.args)}, ${s(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)=>{a(e,i`UPDATE ${i.identifier(t)} SET cursor = ${r} WHERE key = ${n}`)},x=(e,n,r,d)=>{const y=d===void 0?i``:i` AND key = ${T(n,r,d)}`;a(e,i`DELETE FROM ${i.identifier(t)} WHERE relay_idx = ${n} AND connection_id = ${r}${y}`)},p=(e,n)=>{a(e,i`DELETE FROM ${i.identifier(t)} WHERE relay_idx = ${n}`)},O=e=>{a(e,i`DELETE FROM ${i.identifier(t)}`)};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 S}from"./NotUniqueError-
|
|
1
|
+
import{createShardCtxDb as S}from"./NotUniqueError-DucaxGnP.mjs";import{createRelayLink as B}from"./DEFAULT_MAX_RELAYS-CH446J5m.mjs";import{ConflictError as I}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as v}from"./runShardMigrations-BqH93Q8t.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-DcJw42RT.mjs";const _=(E,u={})=>({_meta:{column:{notNull:!0,...u}},kind:E}),D=(E,u,N)=>{const{describe:k,expect:i,it:m}=N;k(`engine contract: ${E}`,()=>{k("optimistic concurrency",()=>{const b=h=>({tables:{items:{indexes:[],shape:{title:_("string"),version:_("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{h.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});m("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await i(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(I)}finally{h?.()}}),m("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;i(e.code).toBe("CONFLICT"),i(e.kind).toBe("occ")}finally{h?.()}}),m("leaves the row readable and unchanged after a conflict",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const a=await s.get("i1");i(a?.title).toBe("first"),i(a?.version).toBe(99)}finally{h?.()}}),m("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l={tables:{items:{indexes:[],shape:{title:_("string"),version:_("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch(o.doc._id,{version:99})},op:"update",timing:"before"}}}}};v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;i(e).toBeInstanceOf(I),i(e.code).toBe("CONFLICT"),i(e.kind).toBe("trigger")}finally{h?.()}})}),k("shape-poke ordering",()=>{const b="shard-a",h={args:{},name:"messages"},d=(e,t,o,n)=>e.accept(t?.()??{},{connectionId:o,shapes:{[n]:h}}),c=(e,t)=>{let o=0,n=0;const r=g=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${g}`)},p={fetch:(g,O)=>{if(JSON.parse(O?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const C=t[n];if(n+=1,C===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(C))}},y={get:()=>p,getByName:()=>p,idFromName:g=>g},w={buildShapeDiff:r("buildShapeDiff"),computeOpLogShapeSeed:r("computeOpLogShapeSeed"),currentCdcEpoch:r("currentCdcEpoch"),deliverWhisperLocal:r("deliverWhisperLocal"),doName:()=>F(b,0),env:()=>({SHARD:y}),getWebSockets:()=>e.getSockets(),maskMetadata:r("maskMetadata"),nextPokeId:()=>(o+=1,`poke-${String(o)}`),readAttachment:g=>g.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:r("resolveShape"),rlsMetadata:r("rlsMetadata"),shardBinding:()=>"SHARD",sql:r("sql")},f=B(w);if(f===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return f},l=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,o)=>{const n=await e.seedRelayShape(t,o,h,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},a=(e={})=>l({...h,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});m("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1");await s(r,p,"s1"),await r.handleControl(a());const w=(await o(p)).map(f=>JSON.parse(f));i(w.map(f=>f.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),i(new Set(w.map(f=>f.pokeId)).size).toBe(1),i(w[1]?.shapeId).toBe("s1"),i(w[2]?.checkpoint).toBe(20)}finally{e?.()}}),m("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1"),y=d(n,t,"c-bob","s2");await s(r,p,"s1"),await s(r,y,"s2"),await r.handleControl(a());const w=await o(p);i(w.length).toBe(3);const f=await o(y);i(f.length).toBe(0),await r.handleControl(a());const g=await o(p);i(g.length).toBe(3)}finally{e?.()}}),m("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1");await s(r,p,"s1"),await r.handleControl(a({epoch:"e2"}));const y=await o(p);i(y.length).toBe(0),await r.handleControl(a());const w=await o(p);i(w.length).toBe(3)}finally{e?.()}})}),k("RLS identity under live subscription",()=>{const b="shard-a",h={args:{},name:"lobby-messages"},d={args:{},name:"my-orders"},c=s=>{const a=[],e=[],t={fetch:(r,p)=>(a.push(JSON.parse(p?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=B({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>b,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:r=>r}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(r,p,y)=>(e.push(y),r===d.name?{columns:["id"],effectiveWhere:{org:y?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:a,resolvedUnder:e}},l=async(s,a)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...a,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};m("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:a}=u();try{const{owner:e,resolvedUnder:t}=c(a.sql);await l(e,d),i(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),m("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:a}=u();try{const{owner:e,posts:t}=c(a.sql);await l(e,d),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),m("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:a}=u();try{const{owner:e,posts:t}=c(a.sql);await l(e,h),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{D as defineEngineContractSuite};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{toErrorBody as b}from"@lunora/errors";import{COMMIT_SEQ_FIELD as l}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";const f=200,p=(e,n)=>{const i=r=>{const o=e.tables[r];return o!==void 0&&o.shardMode?.kind!=="global"};return(n&&n.length>0?[...n]:Object.keys(e.tables)).filter(r=>i(r))},u=async function*(e,n,i=f){let r=null,o=!1;for(;!o;){const t=await e.findMany(n,{cursor:r,limit:i});for(const s of t.page)yield{doc:s,table:n};r=t.continueCursor,o=t.isDone||r===null}},k=async function*(e,n,i){const r=p(n,i.tables),o=i.batchSize??f;for(const t of r)yield*u(e,t,o)},y=new Set(["_creationTime","_id"]),h=(e,n)=>{for(const[i,r]of Object.entries(e.shape)){const o=n[i];if(o===void 0&&r.kind==="optional")continue;const t=r.parse;if(typeof t=="function")try{t(o)}catch(s){const c=s instanceof Error?s.message:String(s);return`field "${i}": ${c}`}}},m=(e,n,i)=>{const r=e.tables[n];if(!r)return`unknown table: ${n}`;if(r.shardMode?.kind==="global")return`table "${n}" is a global (.global()) table and is not importable through the shard import path`;const o=Object.fromEntries(Object.entries(i).filter(([t])=>!y.has(t)));for(const t of Object.keys(o))if(!(t in r.shape))return`unexpected field "${t}": not declared in table "${n}"`;return h(r,o)},g=async(e,n)=>{try{return await e.get(n)!==null}catch{return!1}},w=e=>l in e?Object.fromEntries(Object.entries(e).filter(([n])=>n!==l)):e,A=async(e,n,i,r)=>{const{table:o}=i;let{doc:t}=i;if(typeof o!="string"||o.length===0)return{error:{code:"BAD_ROW",line:r,message:"row is missing `table`",table:o},kind:"error"};if(!t||typeof t!="object"||Array.isArray(t))return{error:{code:"BAD_ROW",line:r,message:"row is missing or malformed `doc`",table:o},kind:"error"};t=w(t);const s=m(n,o,t);if(s!==void 0)return{error:{code:"VALIDATION_ERROR",line:r,message:s,table:o},kind:"error"};const c=typeof t._id=="string"?t._id:void 0;if(c!==void 0&&await g(e,c))return{kind:"conflict"};try{return await e.insert(o,t,{allowExplicitId:!0}),{kind:"inserted",table:o}}catch(a){const{body:d}=b(a,{fallbackCode:"INSERT_FAILED"});return{error:{code:d.code,line:r,message:d.message,table:o},kind:"error"}}},O=async(e,n,i)=>{const r=[],o={};let t=0,s=(i.startLine??1)-1;for(const c of i.rows){s+=1;const a=await A(e,n,c,s);a.kind==="error"?r.push(a.error):a.kind==="conflict"?t+=1:o[a.table]=(o[a.table]??0)+1}return{conflicts:t,errors:r,inserted:o}},v=e=>{const n=Array.isArray(e.tables)?e.tables.filter(r=>typeof r=="string"):void 0;return{batchSize:typeof e.batchSize=="number"?e.batchSize:void 0,tables:n}},R=e=>{const n=Array.isArray(e.rows)?e.rows:[],i=[];for(const o of n){if(!o||typeof o!="object")continue;const t=o;if(typeof t.table!="string"||!t.doc||typeof t.doc!="object"||Array.isArray(t.doc)){i.push({doc:t.doc??{},table:typeof t.table=="string"?t.table:""});continue}i.push({doc:t.doc,table:t.table})}const r=typeof e.startLine=="number"?e.startLine:void 0;return{rows:i,startLine:r}};export{k as exportShardRows,O as importShardRows,v as parseExportShardArgs,R as parseImportShardArgs,p as selectExportTables,m as validateImportRow};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-2ULFQR_k.mjs";import{liftSourceId as A}from"./liftSourceId-CA3ENhXj.mjs";import{normalizeSourceValue as W}from"./liftSourceId-CA3ENhXj.mjs";import{runExternalSourceTick as C,materializeExternalRowsIncremental as D}from"./materializeExternalRows-
|
|
1
|
+
import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-2ULFQR_k.mjs";import{liftSourceId as A}from"./liftSourceId-CA3ENhXj.mjs";import{normalizeSourceValue as W}from"./liftSourceId-CA3ENhXj.mjs";import{runExternalSourceTick as C,materializeExternalRowsIncremental as D}from"./materializeExternalRows-DZPYRDXu.mjs";const p="__lunora_source_cursor",M=e=>e instanceof Date?`d:${e.toISOString()}`:typeof e=="bigint"?`b:${e.toString()}`:typeof e=="number"?`n:${e.toString()}`:`s:${e}`,v=e=>{const t=e.slice(2);switch(e[0]){case"b":return BigInt(t);case"d":return new Date(t);case"n":return Number(t);default:return t}},h=/^-?\d+$/,N=/^-?\d+(?:\.\d+)?$/,x=(e,t)=>e instanceof Date&&t instanceof Date?e.getTime()>t.getTime():typeof e=="bigint"&&typeof t=="bigint"||typeof e=="number"&&typeof t=="number"?e>t:typeof e=="string"&&typeof t=="string"&&N.test(e)&&N.test(t)?h.test(e)&&h.test(t)?BigInt(e)>BigInt(t):Number(e)>Number(t):String(e)>String(t),O=(e,t,o)=>{let n=o===null?void 0:v(o);for(const r of e){const c=r[t];if(c==null)continue;const a=c;(n===void 0||x(a,n))&&(n=a)}return n===void 0?null:M(n)},B=e=>{S(e,m`CREATE TABLE IF NOT EXISTS ${m.identifier(p)} (
|
|
2
2
|
table_name TEXT NOT NULL,
|
|
3
3
|
shard_key TEXT NOT NULL,
|
|
4
4
|
watermark TEXT,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{applyCdcChanges as p}from"./CDC_LOG_TABLE-gl0FuepJ.mjs";import{selectShapeRows as m}from"./selectShapeMembers-
|
|
1
|
+
import{applyCdcChanges as p}from"./CDC_LOG_TABLE-gl0FuepJ.mjs";import{selectShapeRows as m}from"./selectShapeMembers-CLK9q18N.mjs";import{diffExternalSource as g,projectExternalSourceRow as l}from"./diffExternalSource-DgDJhslq.mjs";import{stableStringify as d}from"./stableStringify-DibjylKD.mjs";const x=async(t,s,a,e)=>{const{changes:o,nextBaseline:n}=g(s,a,e);return await p(t,o),{applied:o.length,nextBaseline:n}},R=async(t,s,a)=>{const{columns:e,deletedIds:o,table:n}=a,r=[];for(const f of s){const i=l(f,e),c=String(i._id);if(o?.has(c)){await t.get(c,n)&&r.push({id:c,op:"delete",seq:0,table:n,ts:0});continue}const u=await t.get(c,n);u&&d(l({...u,_id:c},e))===d(i)||r.push({doc:i,id:c,op:"insert",seq:0,table:n,ts:0})}return await p(t,r),{applied:r.length}},h=(t,s,a)=>{const e=new Map;for(const{doc:o,id:n}of m(t,s,void 0))e.set(n,d(l({...o,_id:n},a)));return e},_=async(t,s,a,e)=>{const o=h(t,e.table,e.columns);return x(s,a,o,e)};export{x as materializeExternalRows,R as materializeExternalRowsIncremental,h as readExternalSourceBaseline,_ as runExternalSourceTick};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{LunoraError as S}from"@lunora/errors";import{S as p,y as L,l as h}from"./ctx-db-companions-BFBIVIOd.mjs";import{sql as e}from"drizzle-orm";import{aggregateTableName as N}from"./aggregateTableName-CGi8gxeK.mjs";import{backfillSearchIndexesForTable as l}from"./backfillAggregateIndexes-CTPj9dAd.mjs";import{migrateCdcLog as R,migrateCdcMeta as x}from"./CDC_LOG_TABLE-gl0FuepJ.mjs";import{migrateClientWatermark as O}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{migrateCommitSeq as C}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{migrateGlobalShapeSnapshot as $}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{migrateIdempotency as U}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{m as b}from"./ctx-db-relay-shapes-CnOeftkH.mjs";import{migrateSearchState as D}from"./SEARCH_STATE_TABLE-xmYM_nOd.mjs";import{migrateShapePokeCursor as X}from"./SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs";import{runDrizzle as a}from"./runDrizzle-2ULFQR_k.mjs";import{D as G,d as T,e as I,t as M,i as F,g as B,a as y,b as Y,A as g}from"./do-sql-bkXQEBl8.mjs";import{renderSql as k}from"./param-DlozcSQu.mjs";import{migrateDurableStreams as v}from"./appendStreamChunk-8eH4HB1Q.mjs";import{rankTableName as P,sortColumnName as w}from"./RANK_TIEBREAK-D157XEqw.mjs";import{migrateReactorState as j}from"./REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{recordSchemaVersion as K}from"./SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";const u=e`_creationTime, id`,V=(i,o,n,r,t)=>{const d=a(i,e`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${o} AND tbl_name = ${n}`).toArray()[0]?.sql;if(d==null)return;const f=m=>{const _=m.indexOf("(");return _===-1?void 0:m.slice(_,m.lastIndexOf(")")+1)},c=f(k("sqlite",T(o,n,r,t)).sql),E=f(d);if(!(c===void 0||E===void 0||c===E)){if(t&&a(i,e`SELECT 1 FROM ${e.identifier(n)} GROUP BY ${r} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new S("INTERNAL",`unique index "${o}" on "${n}" cannot be re-created with its new column list: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`);a(i,e`DROP INDEX IF EXISTS ${e.identifier(o)}`)}},z=(i,o,n)=>{for(const r of n.indexes){const t=`${o}_${r.name}`,s=r.unique??!1,d=e.join(r.fields.map(c=>I(c)),e`, `),f=s?d:e`${d}, ${u}`;V(i,t,o,f,s),a(i,T(t,o,f,s))}for(const[r,t]of M(n)){if(!t.unique)continue;const s=`${o}_unique_${r}`;a(i,T(s,o,I(r),!0))}},H=(i,o,n)=>{if(!(!n.searchIndexes||n.searchIndexes.length===0||!F(i))){for(const r of n.searchIndexes){const t=p(o,r.name);a(i,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(t)} USING fts5(${e.identifier(L)}, ${e.identifier(h)} UNINDEXED)`),a(i,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${t}__vocab`)} USING fts5vocab(${e.identifier(t)}, ${e.raw("instance")})`)}l(i,o,n)}},W=(i,o,n)=>{if(n.geoIndexes)for(const r of n.geoIndexes){const t=B(o,r.name);a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__geohash__")} TEXT NOT NULL, ${e.identifier("__lat__")} REAL NOT NULL, ${e.identifier("__lng__")} REAL NOT NULL)`);const s=`${o}__geo_${r.name}__btree`;a(i,T(s,t,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},J=(i,o,n)=>{if(n.aggregateIndexes)for(const r of n.aggregateIndexes){const t=N(o,r.name);a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${y} TEXT PRIMARY KEY, ${Y} REAL, ${g} INTEGER NOT NULL DEFAULT 0)`),a(i,e`PRAGMA table_info(${e.identifier(t)})`).toArray().some(d=>d.name==="__count__")||a(i,e`ALTER TABLE ${e.identifier(t)} ADD COLUMN ${g} INTEGER NOT NULL DEFAULT 0`)}},Q=(i,o,n)=>{if(n.rankIndexes)for(const r of n.rankIndexes){const t=P(o,r.name),s=r.sortBy.map((m,_)=>w(_)),d=s.map(m=>e`${e.identifier(m)} BLOB`),f=d.length>0?e`, ${e.join(d,e`, `)}`:e``;a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${f})`);const c=[e`${e.identifier("__partition__")} ASC`];for(const[m,_]of s.entries()){const A=r.sortBy[m]?.direction;c.push(e`${e.identifier(_)} ${e.raw(A==="desc"?"DESC":"ASC")}`)}c.push(e`${e.identifier("__id__")} ASC`);const E=`${o}__rank_${r.name}__btree`;a(i,T(E,t,e.join(c,e`, `),!1))}},Ae=(i,o,n={})=>{n.schemaSnapshot!==void 0&&K(i,n.schemaSnapshot.hash,n.schemaSnapshot.json),D(i);for(const[r,t]of Object.entries(o.tables))t.shardMode?.kind!=="global"&&(a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(r)} (
|
|
2
|
+
id TEXT PRIMARY KEY,
|
|
3
|
+
_creationTime REAL NOT NULL,
|
|
4
|
+
${e.identifier(G)} TEXT NOT NULL
|
|
5
|
+
)`),a(i,T(`${r}__by_creation`,r,u,!1)),z(i,r,t),H(i,r,t),W(i,r,t),J(i,r,t),Q(i,r,t));n.cdc&&(R(i),x(i),O(i),X(i),b(i)),Object.values(o.tables).some(r=>r.commitOrderedMode===!0)&&C(i),j(i),U(i),$(i),v(i)};export{Ae as runShardMigrations};
|
package/dist/packem_shared/{selectShapeMembers-Dva-Z9VQ.mjs → selectShapeMembers-CLK9q18N.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-2ULFQR_k.mjs";import{D as p,r as d,e as h}from"./do-sql-bkXQEBl8.mjs";import{sqliteInList as w}from"./param-DlozcSQu.mjs";import{c as S}from"./where-sql-
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-2ULFQR_k.mjs";import{D as p,r as d,e as h}from"./do-sql-bkXQEBl8.mjs";import{sqliteInList as w}from"./param-DlozcSQu.mjs";import{c as S}from"./where-sql-4RHk2frP.mjs";import{serializeSqlValue as $}from"./serializeSqlValue-DbI1VQYM.mjs";const C={fieldRef:h,serialize:$},g=o=>{if(o.length!==0)return w(e`${e.identifier("id")}`,o,!1)},u=(o,i)=>{const r=[];i&&r.push(i);const t=S(o,C);return t&&r.push(t),r.length===0?e``:e` WHERE ${e.join(r,e` AND `)}`},v=(o,i,r)=>{const t=u(r,void 0),s=m(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${t}`).toArray(),f=[];for(const l of s){const n=d(l),{id:c}=l;n!==void 0&&typeof c=="string"&&f.push({doc:n,id:c})}return f},z=(o,i,r,t)=>{const s=new Map;if(t.length===0)return s;const f=u(r,g(t)),l=m(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${f}`).toArray();for(const n of l){const c=d(n),{id:a}=n;c!==void 0&&typeof a=="string"&&s.set(a,c)}return s};export{z as selectShapeMembers,v as selectShapeRows};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as T}from"@lunora/errors";import{sql as l}from"drizzle-orm";import{sqliteInList as A,isJsonSafe as m,WORKERD_SQLITE_LIMITS as O}from"./param-DlozcSQu.mjs";import{quoteIdentifier as R}from"./quoteIdentifier-CObIFRhb.mjs";import{RELATION_EXISTS_KEY as L}from"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";const $={binary:(n,t,o)=>l`${n} ${l.raw(t)} ${o}`,constant:n=>n?l`1 = 1`:l`0 = 1`,connect:(n,t,o)=>l`(${n}) ${l.raw(o)} (${t})`,contains:(n,t)=>l`instr(lower(${n}), lower(${t})) > 0`,inList:(n,t,o,i)=>A(n,t,o,i),negate:n=>l`NOT (${n})`,nullCheck:(n,t)=>t?l`${n} IS NOT NULL`:l`${n} IS NULL`,value:n=>l`${n}`},u=(...n)=>{let t="";const o=[];for(const i of n)typeof i=="string"?t+=i:(t+=i.text,o.push(...i.params));return{params:o,text:t}},p=n=>({params:[n],text:"?"}),S=n=>({params:[],text:n}),B=n=>S(R(n)),G={binary:(n,t,o)=>u(n," ".concat(t," "),p(o)),constant:n=>S(n?"1 = 1":"0 = 1"),connect:(n,t,o)=>u("(",n,") ".concat(o," ("),t,")"),contains:(n,t)=>u("instr(lower(",n,"), lower(",t,")) > 0"),inList:(n,t,o,i)=>{const s=o?" NOT IN ":" IN ";if(t.length>i&&!t.every(r=>m(r)))throw new T("BAD_REQUEST",`an "in" list of ${String(t.length)} values holds a value JSON cannot carry (bytes, a non-finite number, or malformed text), so it cannot be bound as one parameter — and ${String(t.length)} placeholders exceed SQLite's per-statement cap of 100 on Durable Objects and D1. Narrow the list to ${String(i)} values or fewer.`);if(t.length<=i){const r=[n,s,"("];for(const[e,c]of t.entries())e>0&&r.push(", "),r.push(p(c));return r.push(")"),u(...r)}return u(n,s,'(SELECT "value" FROM json_each(',p(JSON.stringify(t)),"))")},negate:n=>u("NOT (",n,")"),nullCheck:(n,t)=>u(n,t?" IS NOT NULL":" IS NULL"),value:p},x=O.boundParams/2,I=["eq","ne","lt","lte","gt","gte","in","notIn","isNull","contains"],_=new Set(I),j={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},d=n=>{if(n===null||typeof n!="object"||Array.isArray(n))return!1;const t=Object.keys(n);return t.length>0&&t.every(o=>_.has(o))},w=(n,t,o,i)=>{const s=i.value(o.serialize(t));return o.containsExpr?o.containsExpr(n,s):i.contains(n,s)},C=(n,t,o,i,s,r)=>i===null?t==="eq"||t==="ne"?r.nullCheck(n,t==="ne"):r.constant(!1):r.binary(n,o,s.serialize(i)),y=(n,t,o,i,s)=>{const r=Array.isArray(o)?o:[];if(r.length===0)return s.constant(t==="NOT IN");const e=r.map(a=>i.serialize(a)),c=t==="NOT IN";return i.inList?i.inList(n,e,c):s.inList(n,e,c,x)},J=(n,t,o)=>{const i=l.join(t.map(s=>l`${s}`),l`, `);return o?l`${n} NOT IN (${i})`:l`${n} IN (${i})`},k=(n,t,o,i)=>{const s=t,r=[];for(const e of I){if(!(e in s))continue;const c=s[e],a=j[e];a?r.push(C(n,e,a,c,o,i)):e==="isNull"?r.push(i.nullCheck(n,!c)):e==="contains"?r.push(w(n,c,o,i)):r.push(y(n,e==="in"?"IN":"NOT IN",c,o,i))}return r},D=(n,t,o,i)=>{const s=o.fieldRef(n);return d(t)?k(s,t,o,i):t===null?[i.nullCheck(s,!1)]:[i.binary(s,"=",o.serialize(t))]},f=(n,t,o)=>{if(n.length<=1)return n[0];const i=Math.floor(n.length/2);return o.connect(f(n.slice(0,i),t,o),f(n.slice(i),t,o),t)},U=(n,t,o,i)=>{const s=Array.isArray(n)?n:[],r=[];for(const e of s){const c=h(e??{},o,i);c!==void 0&&r.push(c)}return r.length===0?t==="OR"?i.constant(!1):void 0:f(r,t,i)},M=new Set(["AND","NOT","OR",L]),P=(n,t,o,i)=>{if(n===L){if(!o.relationExists)throw new T("INTERNAL","encountered a relation EXISTS marker without a relationExists strategy hook");return o.relationExists(t)}if(n==="NOT"){const s=h(t??{},o,i);return s===void 0?void 0:i.negate(s)}return U(t,n,o,i)},h=(n,t,o)=>{const i=[];for(const[s,r]of Object.entries(n))if(M.has(s)){const e=P(s,r,t,o);e!==void 0&&i.push(e)}else i.push(...D(s,r,t,o));return f(i,"AND",o)},q=O.boundParams/2,E=n=>{let t=0,o=0;const i=s=>{const r=E(s);t+=r.lists,o+=r.scalars};if(Array.isArray(n)){for(const s of n)i(s);return{lists:t,scalars:o}}if(n===null||typeof n!="object")return{lists:t,scalars:o};for(const[s,r]of Object.entries(n))s==="in"||s==="notIn"?t+=1:s==="AND"||s==="NOT"||s==="OR"||d(r)?i(r):o+=1;return{lists:t,scalars:o}},Q=(n,t,o=$)=>{if(!n||Object.keys(n).length===0)return;const{lists:i,scalars:s}=E(n);if(i===0)return h(n,t,o);const r=Math.max(1,Math.floor(Math.min(q,O.boundParams-s)/i)),e=t.inList??((c,a,N,b)=>o.inList(c,a,N,b??r));return h(n,{...t,inList:(c,a,N)=>e(c,a,N,r)},o)};export{Q as c,B as i,u as j,J as l,S as r,G as t};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/shard-engine",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.51",
|
|
4
4
|
"description": "Host-neutral reactive engine for Lunora: per-shard state, OCC, CDC, reactive subscriptions, and the poke protocol. Consumes @lunora/platform host contracts and can be mounted on any platform host.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
"access": "public"
|
|
49
49
|
},
|
|
50
50
|
"dependencies": {
|
|
51
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
51
|
+
"@lunora/errors": "1.0.0-alpha.28",
|
|
52
52
|
"@lunora/platform": "1.0.0-alpha.23",
|
|
53
53
|
"drizzle-orm": "^0.45.2"
|
|
54
54
|
},
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as b}from"@lunora/errors";import{d as S,e as m}from"./wire-codec-COhOSEe4.mjs";const _="id",E=e=>e.at(-1)?.direction==="desc"?"desc":"asc",N=new Set(["_id","id"]),y=new Set(["_creationTime","_id","id"]),C=(e,t)=>{if(y.has(e))return!1;const o=t?.[e];return o===void 0?!0:o.kind==="optional"||o._meta?.column?.notNull===!1},I=(e,t)=>{const o=[];for(const r of e??[])for(const[n,i]of Object.entries(r))o.push({direction:i,field:n,nullable:C(n,t)});return o.length===0?[{direction:"asc",field:"_creationTime",nullable:!1}]:o},F=/[\u0080-\u{10FFFF}]/u,O=e=>{if(!F.test(e))return btoa(e);const t=new TextEncoder().encode(e);let o="";for(const r of t)o+=String.fromCodePoint(r);return btoa(o)},v=e=>{const t=atob(e),o=Uint8Array.from(t,r=>r.codePointAt(0)??0);return new TextDecoder().decode(o)},a="~2",L=(e,t)=>{const o=t.map(r=>e[r.field]??null);return o.push(e._id),a+O(JSON.stringify(m(o)))},u=()=>new b("BAD_REQUEST","invalid cursor"),T=e=>{if(!e.startsWith(a))throw u();let t;try{t=S(JSON.parse(v(e.slice(a.length))))}catch{throw u()}if(!Array.isArray(t))throw u();return t.map(o=>o??null)},R=(e,t,o,r)=>{const{field:n}=e,i=e.direction!=="desc"===o;if(t===null)return i?r?{OR:[{[n]:{isNull:!1}},{[n]:{isNull:!0}}]}:{[n]:{isNull:!1}}:r?{[n]:{isNull:!0}}:{OR:[]};let s=i?"gt":"lt";r&&(s=i?"gte":"lte");const c={[n]:{[s]:t}};return i||!e.nullable?c:{OR:[c,{[n]:{isNull:!0}}]}},f=(e,t,o,r)=>{const n=e.some(s=>N.has(s.field))?e:[...e,{direction:E(e),field:_,nullable:!1}];if(t.length<n.length)throw u();const i=[];for(const[s,c]of n.entries()){const l=[];for(const[p,h]of n.slice(0,s).entries())l.push({[h.field]:{eq:t[p]}});l.push(R(c,t[s],o,r&&s===n.length-1));const[d]=l;i.push(l.length===1&&d!==void 0?d:{AND:l})}return{OR:i}},A=(e,t)=>f(e,t,!0,!1),k=(e,t)=>f(e,t,!1,!0),g=["_id","_creationTime"],W=(e,t,o)=>{if(!t)return e;const r=new Set([...t,...g,...o?Object.keys(o):[]]);return e.map(n=>{const i={};for(const s of r)s in n&&(i[s]=n[s]);return i})},B=(e,t)=>e&&t!==!0?{[e.field]:{isNull:!0}}:void 0,U=(e,t)=>t===void 0||e[t]===null||e[t]===void 0;export{a as CURSOR_PREFIX,W as applySelect,k as buildSeekBeforeWhere,A as buildSeekWhere,T as decodeCursor,L as encodeCursor,v as fromBase64,u as invalidCursor,U as isLiveForCompanion,I as normalizeOrderKeys,B as softDeleteScope,E as tiebreakDirectionFor,O as toBase64};
|
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
import{LunoraError as b}from"@lunora/errors";import{runSql as c}from"./runDrizzle-2ULFQR_k.mjs";const n="__lunora_migrations",x=100,N=3e4,y=1e4,M=e=>{c(e,`CREATE TABLE IF NOT EXISTS "${n}" (
|
|
2
|
-
id TEXT PRIMARY KEY,
|
|
3
|
-
direction TEXT NOT NULL,
|
|
4
|
-
status TEXT NOT NULL,
|
|
5
|
-
cursor TEXT,
|
|
6
|
-
processed INTEGER NOT NULL DEFAULT 0,
|
|
7
|
-
changed INTEGER NOT NULL DEFAULT 0,
|
|
8
|
-
started_at REAL,
|
|
9
|
-
updated_at REAL,
|
|
10
|
-
error TEXT
|
|
11
|
-
)`)},R=e=>({changed:e.changed,cursor:typeof e.cursor=="string"?e.cursor:null,direction:e.direction==="down"?"down":"up",processed:e.processed,status:e.status==="completed"||e.status==="failed"?e.status:"in_progress"}),S=(e,t)=>{const r=c(e,`SELECT * FROM "${n}" WHERE id = ?`,t).toArray()[0];if(r)return{...R(r),startedAt:typeof r.started_at=="number"?r.started_at:void 0}},U=(e,t,s)=>{c(e,`DELETE FROM "${n}"
|
|
12
|
-
WHERE id = ? AND (status <> 'in_progress' OR updated_at IS NULL OR updated_at <= ?)`,t,s)},h=(e,t)=>{c(e,`INSERT INTO "${n}"
|
|
13
|
-
(id, direction, status, cursor, processed, changed, started_at, updated_at, error)
|
|
14
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
15
|
-
ON CONFLICT(id) DO UPDATE SET
|
|
16
|
-
direction = excluded.direction,
|
|
17
|
-
status = excluded.status,
|
|
18
|
-
cursor = excluded.cursor,
|
|
19
|
-
processed = excluded.processed,
|
|
20
|
-
changed = excluded.changed,
|
|
21
|
-
updated_at = excluded.updated_at,
|
|
22
|
-
error = excluded.error`,t.id,t.direction,t.status,t.cursor,t.processed,t.changed,t.startedAt,t.updatedAt,t.error)},C=(e,t,s,r)=>(c(e,`INSERT INTO "${n}"
|
|
23
|
-
(id, direction, status, cursor, processed, changed, started_at, updated_at, error)
|
|
24
|
-
VALUES (?, ?, 'in_progress', NULL, 0, 0, ?, ?, NULL)
|
|
25
|
-
ON CONFLICT(id) DO UPDATE SET
|
|
26
|
-
status = 'in_progress',
|
|
27
|
-
updated_at = excluded.updated_at
|
|
28
|
-
WHERE
|
|
29
|
-
"${n}".status <> 'in_progress'
|
|
30
|
-
OR "${n}".updated_at IS NULL
|
|
31
|
-
OR "${n}".updated_at <= excluded.updated_at - ${String(N)}`,t,s,r,r),c(e,"SELECT changes() AS changed").one().changed>0),$=(e,t,s)=>{c(e,`UPDATE "${n}" SET updated_at = ? WHERE id = ? AND status = 'in_progress'`,s,t)},F=(e,t)=>{c(e,`UPDATE "${n}" SET updated_at = 0 WHERE id = ? AND status = 'in_progress'`,t)},B=(e,t)=>{if(c(e,"SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",n).toArray().length===0)return[];const r=t===void 0?" ORDER BY id":" WHERE id = ?",i=t===void 0?[]:[t];return c(e,`SELECT * FROM "${n}"${r}`,...i).toArray().map(a=>({...R(a),error:typeof a.error=="string"?a.error:null,id:a.id,startedAt:typeof a.started_at=="number"?a.started_at:null,updatedAt:typeof a.updated_at=="number"?a.updated_at:null}))},w=async e=>{const{migration:t,sql:s,writer:r}=e,i=e.direction??"up",o=e.dryRun??!1,a=e.clock??(()=>Date.now()),I=e.maxBatches??Number.POSITIVE_INFINITY,O=e.batchSize??t.batchSize??x,f=i==="up"?t.up:t.down;if(!f)throw new b("INTERNAL",`data migration "${t.id}" has no \`${i}\` transform`);const D={db:{count:r.count.bind(r),findFirst:r.findFirst.bind(r),findMany:r.findMany.bind(r),get:r.get.bind(r)}};let p=null,_=0,g=0,A=a();if(!o){M(s);const d=S(s,t.id);if(d?.direction===i&&d.status==="completed")return{changed:d.changed,cursor:null,direction:i,dryRun:o,id:t.id,processed:d.processed,status:"completed"};if(d&&d.direction!==i&&U(s,t.id,a()-N),!C(s,t.id,i,a())){const u=S(s,t.id);return{changed:u?.changed??0,cursor:u?.cursor??p,direction:u?.direction??i,dryRun:o,id:t.id,processed:u?.processed??0,status:u?.status??"in_progress"}}const l=d?.direction===i?d:void 0;l&&(p=l.cursor,_=l.processed,g=l.changed,A=l.startedAt??A)}let T=!1,m=0,L=A;try{for(;!T&&m<I;){const d=await r.findMany(t.table,{cursor:p,limit:O});for(const E of d.page){_+=1;const l=await f(E,D);if(l!==void 0&&(g+=1,o||await r.replace(String(E._id),{...l,_creationTime:E._creationTime,_id:E._id},void 0,{allowExplicitId:!0})),!o){const u=a();u-L>=y&&($(s,t.id,u),L=u)}}if(p=d.continueCursor,T=d.isDone,m+=1,!o){const E=a();h(s,{changed:g,cursor:T?null:p,direction:i,error:null,id:t.id,processed:_,startedAt:A,status:T?"completed":"in_progress",updatedAt:E}),L=E;try{await e.onBatch?.({batches:m,changed:g,processed:_})}catch{}}}}catch(d){throw o||h(s,{changed:g,cursor:p,direction:i,error:d instanceof Error?d.message:String(d),id:t.id,processed:_,startedAt:A,status:"failed",updatedAt:a()}),d}if(!o&&!T)try{F(s,t.id)}catch(d){console.warn(`data migration "${t.id}": releaseClaim failed`,d)}return{changed:g,cursor:T?null:p,direction:i,dryRun:o,id:t.id,processed:_,status:T?"completed":"in_progress"}};export{n as DATA_MIGRATION_STATE_TABLE,B as readMigrationStatus,w as runDataMigration};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as h}from"@lunora/errors";import{distinctValues as w}from"./applyOnDelete-9f4D4g1z.mjs";import{RELATION_EXISTS_KEY as N}from"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";const g={every:{kind:"many",negateChild:!0,negated:!0},is:{kind:"one",negated:!1},isNot:{kind:"one",negated:!0,nullDisjunct:!0},none:{kind:"many",negated:!0},some:{kind:"many",negated:!1}},T=new Set(Object.keys(g)),p=e=>{const t=g[e];if(!t)throw new h("INTERNAL",`unknown relation operator "${e}"`);return t},j=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},S=5e3,l=Symbol("relation-key-overflow"),b=e=>Array.isArray(e)?e.map(t=>t??{}):[],R=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},y=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(n=>T.has(n))},u=(e,t,n)=>{const r=t.tables[n]?.relationMap??{};return Object.keys(e).some(s=>{const a=e[s];return s==="AND"||s==="OR"?b(a).some(o=>u(o,t,n)):s==="NOT"?u(a??{},t,n):!!r[s]&&y(a)})},K=(e,t,n,r)=>{if(e&&u(e,t,n))throw new h("INTERNAL",`relation-crossing predicates are not supported in ${r}() — use them in findMany/findFirst or an RLS read policy`)},P=async(e,t,n,r,s)=>{const a=await d(t,e.table,r),{page:o}=await r.fetcher(e.table,{baseWhere:r.relationBaseWhere?.(e.table),relationBaseWhere:r.relationBaseWhere,where:a}),i=w(o,n);if(i.length>r.maxRelationKeys){if(s)return l;throw new h("INTERNAL",`relation predicate on "${e.table}" matched ${String(i.length)} rows, exceeding the ${String(r.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)}return i},$=async(e,t,n,r,s)=>{const a=p(e),{clause:o,project:i}=j(t),c=await P(t,a.negateChild?{NOT:n}:n,i,r,s);return c===l?l:a.negated?a.nullDisjunct?{OR:[{[o]:{notIn:c}},{[o]:{isNull:!0}}]}:{[o]:{notIn:c}}:{[o]:{in:c}}},m=async(e,t,n,r,s)=>{const a=p(e),o=s.relationBaseWhere?.(t.table),i=a.negateChild?{NOT:n}:n,A={childWhere:await d(o?{AND:[o,i]}:i,t.table,s),negated:a.negated,parentTable:r,relation:t};return{[N]:A}},k=(e,t,n)=>{const r=g[e];if(r&&r.kind!==n.kind)throw new h("INTERNAL",`relation operator "${e}" requires a to-${r.kind} relation, but "${t}" is to-${n.kind}`)},I=async(e,t,n,r,s)=>{const a=[];for(const o of Object.keys(n)){k(o,e,t);const i=n[o]??{},c=s.canPushExists?.(t)??!1;if(c&&s.existsPushMode==="always"){a.push(await m(o,t,i,r,s));continue}const f=await $(o,t,i,s,c);f===l?a.push(await m(o,t,i,r,s)):a.push(f)}return R(a)},L=async(e,t,n,r)=>{if(e==="AND"||e==="OR"){const a=[];for(const o of b(t))a.push(await d(o,n,r));return{[e]:a}}if(e==="NOT")return{NOT:await d(t??{},n,r)};const s=r.schema.tables[n]?.relationMap?.[e];return s&&y(t)?I(e,s,t,n,r):{[e]:t}},d=async(e,t,n)=>{const r=[];for(const s of Object.keys(e))r.push(await L(s,e[s],t,n));return R(r)},v=async(e,t)=>!e||!u(e,t.schema,t.tableName)?e:d(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??S,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),O=(e,t,n)=>{for(const r of e){const s=E(r,t,n);if(s)return s}},M=(e,t,n,r)=>{if(e==="AND"||e==="OR")return O(b(t),n,r);if(e==="NOT")return O([t??{}],n,r);const s=n.tables[r]?.relationMap?.[e];if(!(!s||!y(t)))return n.tables[s.table]?.shardMode?.kind==="shardBy"?{relation:e,target:s.table}:O(Object.values(t),n,s.table)},E=(e,t,n)=>{for(const r of Object.keys(e)){const s=M(r,e[r],t,n);if(s)return s}},B=(e,t,n)=>{if(!e)return;const r=E(e,t,n);if(r)throw Object.assign(new Error(`shape on "${n}" joins the sharded table "${r.target}" via relation "${r.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${n}", or (b) moving "${r.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{S as DEFAULT_MAX_RELATION_KEYS,K as assertFlatPredicate,B as assertShapeShardable,u as containsRelationPredicate,y as isRelationPredicate,v as resolveRelationPredicates};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{toErrorBody as P,LunoraError as M}from"@lunora/errors";import{e as x,d as I}from"./wire-codec-COhOSEe4.mjs";import{w as _,a as w,m as k,r as N,d as C,b as O}from"./ctx-db-relay-shapes-CakvRIFx.mjs";import{envPositiveInt as g}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{relayName as m,DEFAULT_PROMOTION_THRESHOLDS as E,nextPromotionState as D,shapeRoutingKey as R,parseRelayName as F,clampPromotionThresholds as U}from"./DEFAULT_PROMOTION_THRESHOLDS-DpUu_mpH.mjs";import{encodeRowsPatch as W,buildPokeFrames as T}from"./buildPokeFrames-C8km3IhJ.mjs";import{v as K,R as v,s as Y,a as B,b as H}from"./sibling-channel-Cxvk0Zca.mjs";import{awaitWsDrain as $,trySendFrame as A}from"./awaitWsDrain-CjWMVZOG.mjs";import{stableWireKey as f}from"./stableWireKey-9bjKL5Gy.mjs";const j=2,z=8,b={},G=c=>{throw new M("INTERNAL",`unhandled relay frame: ${JSON.stringify(c)}`)},X=(c,e)=>c===void 0||c.epoch!==e.epoch?!1:c.cursor>=e.fromCursor&&c.cursor<e.checkpoint,J=c=>Response.json(c,{headers:{"content-type":"application/json"}}),S=()=>new Response(null,{status:204});class L{constructor(e,t){this.host=e,this.roleId=t}host;roleId;async handleControl(e){let t;try{t=await e.text()}catch{return new Response("bad request",{status:400})}if(!await K(this.host.env(),e.headers.get(v),t))return new Response("forbidden",{status:403});let s;try{s=JSON.parse(t)}catch{return new Response("bad request",{status:400})}switch(s.type){case"relay_attach":return this.onAttach(s.relayIndex),S();case"relay_detach":return this.onDetach(s.relayIndex),S();case"relay_frame":return this.host.deliverWhisperLocal(s.topic,s.frame,void 0),await this.onWhisperFrame(s),S();case"relay_shape_poke":{const r=this.host.getWebSockets().length,o=Date.now(),a=this.onShapePoke({...s,args:I(s.args)});return this.host.recordShapePokeFanout(r,a,Date.now()-o),S()}case"relay_shape_subscribe":return J(this.onShapeSubscribe({...s,args:I(s.args)}));default:return G(s)}}maxRelays(){return g(this.host.env(),"LUNORA_MAX_RELAYS",z)}canAddressSiblings(){return this.siblingStub(this.roleId.ownerKey)!==void 0}siblingStub(e){return Y(this.host.env(),this.bindingName(),e)}bindingName(){return this.host.shardBinding()}async postRelayMessage(e,t){await this.requestRelayMessage(e,t)}async requestRelayMessage(e,t){const s=this.siblingStub(e);if(s===void 0)return;const r=JSON.stringify(t),o={"content-type":"application/json","x-lunora-shard-binding":this.host.shardBinding()??""},a=B(this.host.env());a!==void 0&&(o[v]=await H(a,r));try{return await s.fetch("https://relay.internal/_lunora/relay",{body:r,headers:o,method:"POST"})}catch{return}}}class V extends L{shapeUniformCache=new Map;relaySetCache;registryCache;recordedBinding;promotionState="owned";constructor(e,t){super(e,{ownerKey:t})}async forwardWhisper(e,t){if(!this.canAddressSiblings())return;const s=this.ownerRelaySet();s.size!==0&&await Promise.all([...s].map(r=>this.postRelayMessage(m(this.roleId.ownerKey,r),{frame:t,topic:e,type:"relay_frame"})))}async onFlush(e,t){this.canAddressSiblings()&&await Promise.all([this.multicastShapePokes(e,t),this.proxyShapePokes(e,t)])}seedRelayShape(){return Promise.resolve(void 0)}announce(){return Promise.resolve()}announceDrain(){return Promise.resolve()}relayCount(){const e=this.host.getWebSockets().length,t=g(this.host.env(),"LUNORA_RELAY_THRESHOLD",E.tUp),s=g(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",E.tDown);if(this.promotionState=D(this.promotionState,e,U(t,s)),this.promotionState==="owned")return 0;const r=g(this.host.env(),"LUNORA_RELAY_FAN",j);return Math.min(this.maxRelays(),Math.max(1,r))}minShapeCursor(){const{cohort:e,proxies:t}=this.relayShapes();let s;for(const r of[...e.values(),...t.values()])s=s===void 0?r.cursor:Math.min(s,r.cursor);return s}isShapeRelayUniform(e,t){const s=R(e,t),r=this.shapeUniformCache.get(s);if(r!==void 0)return r;const o=this.probeShapeRelayUniform(e,t);return this.shapeUniformCache.set(s,o),o}onAttach(e){this.addRelayToSet(e)}onDetach(e){this.removeRelayFromSet(e)}async onWhisperFrame(e){await Promise.all([...this.ownerRelaySet()].filter(t=>t!==e.originRelay).map(t=>this.postRelayMessage(m(this.roleId.ownerKey,t),{frame:e.frame,topic:e.topic,type:"relay_frame"})))}onShapeSubscribe(e){return this.buildShapeSeedFrames(e)}onShapePoke(){return 0}buildShapePoke(e,t,s,r,o){let a;try{a=this.host.resolveShape(e.name,e.args,t)}catch{return}if(a===void 0||a.global===!0||!s.has(a.table))return;const n=e,l=n.cursor,i=this.host.buildShapeDiff(a,l,r);if(i.length!==0)return n.cursor=r,_(this.host.sql(),n.key,r),{args:x(e.args),checkpoint:r,epoch:o,fromCursor:l,name:e.name,rowsPatch:W(i),type:"relay_shape_poke"}}async multicastShapePokes(e,t){const s=this.ownerRelaySet();if(s.size===0)return;const{cohort:r}=this.relayShapes();if(r.size===0)return;const o=this.host.currentCdcEpoch(),a=[];for(const n of r.values()){const l=this.buildShapePoke(n,b,e,t,o);l&&a.push(this.multicastToRelays(s,l,n))}await Promise.all(a)}async multicastToRelays(e,t,s){(await Promise.all([...e].map(async o=>(await this.requestRelayMessage(m(this.roleId.ownerKey,o),t))?.ok===!0))).includes(!1)&&this.rewindShapeCursor(s,t.fromCursor)}async proxyShapePokes(e,t){if(this.ownerRelaySet().size===0)return;const{proxies:s}=this.relayShapes();if(s.size===0)return;const r=this.host.currentCdcEpoch(),o=[];for(const a of s.values()){const n=this.buildShapePoke(a,a.identity,e,t,r);n&&o.push(this.proxyToRelay(n,a))}await Promise.all(o)}async proxyToRelay(e,t){(await this.requestRelayMessage(m(this.roleId.ownerKey,t.relayIndex),{...e,targetConnectionId:t.connectionId}))?.ok!==!0&&this.rewindShapeCursor(t,e.fromCursor)}buildShapeSeedFrames(e){const t={identity:e.identity,userId:e.userId};let s;try{s=this.host.resolveShape(e.name,e.args,t)}catch(h){const{body:u}=P(h,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{error:{code:u.code,message:u.message}}}if(s===void 0||s.global===!0)return{error:{code:"SHAPE_NOT_FOUND",message:`shape not relayable: ${e.name}`}};e.relayIndex!==void 0&&this.addRelayToSet(e.relayIndex);const{baseCheckpoint:r,cursor:o,epoch:a,reset:n,rowsPatch:l}=this.host.computeOpLogShapeSeed({args:e.args,name:e.name,sinceEpoch:e.sinceEpoch,sinceSeq:e.sinceSeq},s);let i=o;const{cohort:d,proxies:p}=this.relayShapes();if(this.isShapeRelayUniform(e.name,e.args)){const h=R(e.name,e.args);let u=d.get(h);u===void 0&&(u={args:e.args,cursor:o,key:h,name:e.name},d.set(h,u),w(this.host.sql(),u)),i=u.cursor}else if(e.relayIndex!==void 0&&e.connectionId!==void 0){const h=`${String(e.relayIndex)}:${e.connectionId}:${e.subId}`,u={args:e.args,connectionId:e.connectionId,cursor:o,identity:t,key:h,name:e.name,relayIndex:e.relayIndex};p.set(h,u),w(this.host.sql(),u)}else return{error:{code:"RELAY_SHAPE_UNROUTABLE",message:`shape ${e.name} is per-socket on a relay, but the subscribe carries no ${e.relayIndex===void 0?"relay index":"connection id"}`}};const y=T([{reset:n,rowsPatch:l,shapeId:e.subId}],{baseCheckpoint:r,checkpoint:i,epoch:a,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:i,epoch:a,frames:y}}ensureRelayTables(){this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relays (idx INTEGER PRIMARY KEY)"),this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relay_binding (id INTEGER PRIMARY KEY, binding TEXT NOT NULL)"),k(this.host.sql())}bindingName(){const e=this.host.shardBinding();if(e!==void 0&&e!=="")return e!==this.recordedBinding&&(this.recordedBinding=e,this.ensureRelayTables(),this.host.sql().exec("INSERT INTO __lunora_relay_binding (id, binding) VALUES (1, ?) ON CONFLICT(id) DO UPDATE SET binding = excluded.binding",e)),e;if(this.recordedBinding!==void 0)return this.recordedBinding;try{const t=this.host.sql().exec("SELECT binding FROM __lunora_relay_binding WHERE id = 1").toArray();this.recordedBinding=t[0]?.binding}catch{this.recordedBinding=void 0}return this.recordedBinding}relayShapes(){const e=this.registryCache;if(e!==void 0)return e;this.ensureRelayTables();const t={cohort:new Map,proxies:new Map};for(const s of N(this.host.sql()))s.relayIndex===void 0||s.connectionId===void 0?t.cohort.set(s.key,{args:s.args,cursor:s.cursor,key:s.key,name:s.name}):t.proxies.set(s.key,{args:s.args,connectionId:s.connectionId,cursor:s.cursor,identity:s.identity??{},key:s.key,name:s.name,relayIndex:s.relayIndex});return this.registryCache=t,t}rewindShapeCursor(e,t){const s=e;s.cursor<=t||(s.cursor=t,_(this.host.sql(),s.key,t))}ownerRelaySet(){if(this.relaySetCache===void 0){this.ensureRelayTables();const e=this.host.sql().exec("SELECT idx FROM __lunora_relays").toArray();this.relaySetCache=new Set(e.map(t=>Number(t.idx)))}return this.relaySetCache}addRelayToSet(e){this.ensureRelayTables(),this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relays (idx) VALUES (?)",e),this.ownerRelaySet().add(e)}removeRelayFromSet(e){this.ensureRelayTables(),this.host.sql().exec("DELETE FROM __lunora_relays WHERE idx = ?",e);const t=this.ownerRelaySet();t.delete(e);const{cohort:s,proxies:r}=this.relayShapes();for(const[o,a]of r)a.relayIndex===e&&r.delete(o);C(this.host.sql(),e),t.size===0&&(s.clear(),this.shapeUniformCache.clear(),O(this.host.sql()))}probeShapeRelayUniform(e,t){let s;try{s=this.host.resolveShape(e,t,b)}catch{return!1}if(s===void 0||s.global===!0||this.host.rlsMetadata().policies.some(i=>i.on==="read"&&i.table===s.table)||this.tableHasAnyMask(s.table))return!1;const r=f(s.effectiveWhere),o=f(s.columns);let a=!1;const n=i=>{const d={groups:[`grp_${i}`],roles:[i],sub:`__lunora_probe_${i}__`};return{identity:new Proxy(d,{get:(y,h)=>typeof h=="symbol"||h in y?Reflect.get(y,h):`${i}:${h}`,getOwnPropertyDescriptor:(y,h)=>(a=!0,Reflect.getOwnPropertyDescriptor(y,h)),has:(y,h)=>typeof h=="symbol"?Reflect.has(y,h):!0,ownKeys:y=>(a=!0,Reflect.ownKeys(y))}),userId:`__lunora_probe_${i}__`}};return[b,n("a"),n("b")].every(i=>{let d;try{d=this.host.resolveShape(e,t,i)}catch{return!1}return d!==void 0&&d.global!==!0&&d.table===s.table&&f(d.effectiveWhere)===r&&f(d.columns)===o})&&!a}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(t=>t.table===e)}}class Q extends L{relayAnnounced=!1;shapeRelayMemos=new WeakMap;constructor(e,t,s){super(e,{ownerKey:t,relayIndex:s})}async forwardWhisper(e,t){this.canAddressSiblings()&&await this.postRelayMessage(this.roleId.ownerKey,{frame:t,originRelay:this.roleId.relayIndex,topic:e,type:"relay_frame"})}onFlush(){return Promise.resolve()}async seedRelayShape(e,t,s,r){if(!this.canAddressSiblings())return{code:"RELAY_MISCONFIGURED",message:"relay cannot address its owner"};await this.announce();const o={args:x(s.args??{}),connectionId:this.host.readAttachment(e).connectionId,identity:r.identity,name:s.name,relayIndex:this.roleId.relayIndex,sinceEpoch:s.sinceEpoch,sinceSeq:s.sinceSeq,subId:t,type:"relay_shape_subscribe",userId:r.userId},a=await this.requestRelayMessage(this.roleId.ownerKey,o);if(a===void 0)return{code:"RELAY_SEED_FAILED",message:"owner did not answer the shape seed"};let n;try{n=await a.json()}catch{return{code:"RELAY_SEED_FAILED",message:"malformed shape seed from owner"}}if(n.error!==void 0)return n.error;if(n.frames===void 0)return{code:"RELAY_SEED_FAILED",message:"owner returned no shape frames"};await $(e);for(const l of n.frames)A(e,l);return this.recordRelayShapeMemo(e,t,n.cursor??0,n.epoch),"ok"}async announce(){if(this.relayAnnounced||!this.canAddressSiblings())return;this.relayAnnounced=!0,(await this.requestRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_attach"}))?.ok||(this.relayAnnounced=!1)}async announceDrain(e){this.canAddressSiblings()&&(this.host.getWebSockets().some(t=>t!==e)||(this.relayAnnounced=!1,await this.postRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_detach"})))}relayCount(){return 0}isShapeRelayUniform(){return!1}minShapeCursor(){}onAttach(){}onDetach(){}onWhisperFrame(){return Promise.resolve()}onShapeSubscribe(){return{error:{code:"RELAY_CANNOT_SEED",message:"a relay has no op-log to seed from"}}}onShapePoke(e){return this.deliverShapePoke(e)}recordRelayShapeMemo(e,t,s,r){let o=this.shapeRelayMemos.get(e);o===void 0&&(o=new Map,this.shapeRelayMemos.set(e,o)),o.set(t,{cursor:s,epoch:r})}deliverShapePoke(e){const t=R(e.name,e.args);let s=0;for(const r of this.host.getWebSockets()){const o=this.host.readAttachment(r),{shapes:a}=o,n=this.shapeRelayMemos.get(r);if(!(a===void 0||n===void 0)&&!(e.targetConnectionId!==void 0&&o.connectionId!==e.targetConnectionId))for(const[l,i]of Object.entries(a)){const d=n.get(l);if(R(i.name,i.args)!==t||!X(d,e))continue;const p=T([{baseCheckpoint:d?.cursor,rowsPatch:e.rowsPatch,shapeId:l}],{baseCheckpoint:void 0,checkpoint:e.checkpoint,epoch:e.epoch,lastMutationId:void 0,pokeId:this.host.nextPokeId()},{preEncoded:!0});for(const y of p)A(r,y);n.set(l,{cursor:e.checkpoint,epoch:e.epoch}),s+=1}}return s}}const ie=c=>{const e=c.doName();if(e===void 0)return;const t=F(e);return t===void 0?new V(c,e):new Q(c,t.ownerKey,t.relayIndex)};export{z as DEFAULT_MAX_RELAYS,V as OwnerRelay,Q as RelayMember,ie as createRelayLink};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as m}from"@lunora/errors";import{stableWireKey as a}from"./stableWireKey-9bjKL5Gy.mjs";const i="::relay::",f=(t,n)=>`${t}${i}${String(n)}`,s=t=>{const n=t.lastIndexOf(i);if(n===-1)return;const o=t.slice(0,n),e=t.slice(n+i.length),r=Number(e);if(!(o.length===0||!Number.isInteger(r)||r<0||String(r)!==e))return{ownerKey:o,relayIndex:r}},d=(t,n)=>a({args:n??{},name:t}),c={tDown:4e3,tUp:8e3},l=(t,n,o=c)=>{if(o.tDown>=o.tUp)throw new m("INTERNAL",`invalid promotion thresholds: tDown (${String(o.tDown)}) must be < tUp (${String(o.tUp)})`);return t==="owned"?n>=o.tUp?"promoted":"owned":n<o.tDown?"owned":"promoted"},g=(t,n)=>n<t?{tDown:n,tUp:t}:{tDown:Math.min(Math.max(1,Math.floor(t/2)),t-1),tUp:t},N=(t,n,o)=>{if(t<=n||n<=0)return 0;const e=t-n,r=Math.ceil(e/n);return Math.min(r,Math.max(0,o))};export{c as DEFAULT_PROMOTION_THRESHOLDS,i as RELAY_NAME_INFIX,g as clampPromotionThresholds,l as nextPromotionState,s as parseRelayName,N as relayCountFor,f as relayName,d as shapeRoutingKey};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{toErrorBody as R,LunoraError as k}from"@lunora/errors";import{e as A}from"./wire-codec-COhOSEe4.mjs";import{readStreamRun as T,deleteStreamRun as w,claimStreamRun as _,appendStreamChunk as b,finishStreamRun as E,trimStreamRuns as y,readStreamChunks as v}from"./appendStreamChunk-8eH4HB1Q.mjs";const p=5e4,S=64*1024*1024,M=864e5,N=36e5,L=(i,e)=>{const r=i?.startedAt??e.live?.generation;return e.resuming&&e.generation!==void 0&&r!==void 0&&e.generation!==r?"interrupted":e.live!==void 0?"attach":i===void 0?e.resuming?"interrupted":"attach":i.status==="complete"||i.status==="error"?e.resuming?"replay-terminal":"reclaim":e.resuming?"interrupted":"reclaim"},O=(i,e,r)=>{(i||r())&&e.fail({code:"STREAM_INTERRUPTED",message:i?"the run this durable stream resumed from no longer exists; start a new run":"the producer for this durable stream did not survive; start a new run"})};class I{lastTrimAt=0;runs=new Map;sql;waitUntil;constructor(e){this.sql=e.sql,this.waitUntil=e.waitUntil}async attach(e){try{await this.attachOrThrow(e)}catch(r){const{body:t,redacted:o}=R(r,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});o&&console.error("[@lunora/shard-engine] durable stream attach failed:",r),e.sink.fail({code:t.code,message:t.message})}}detach(e,r){this.runs.get(e)?.sinks.delete(r)}isLive(e){return this.runs.has(e)}async attachOrThrow(e){const r=this.sql(),{runKey:t,sinceChunk:o,sink:c}=e,n=T(r,t),u=o>0,s=this.runs.get(t),a=n?.startedAt??s?.generation,l=L(n,{generation:e.generation,live:s,resuming:u}),d=()=>{for(const g of v(r,t,o))if(!c.chunk({data:JSON.parse(g.dataJson),generation:a,seq:g.seq}))return!1;return!0};if(l==="replay-terminal"){d()&&(n?.status==="error"?c.fail({code:n.errorCode??"INTERNAL_SERVER_ERROR",message:n.error??"stream failed"}):c.complete());return}if(l==="interrupted"){O(e.generation!==void 0&&a!==void 0&&e.generation!==a,c,d);return}if(s){d()&&s.sinks.add(c);return}l==="reclaim"&&w(r,t),this.trim(r);const m=Math.max(Date.now(),n===void 0?0:n.startedAt+1);_(r,t,m,e.ttlMs??M);const h={generation:m,sinks:new Set([c])};this.runs.set(t,h);const f=this.produce(t,e.iterator,h);this.waitUntil?.(f),await f}async produce(e,r,t){const o=this.sql(),c=new AbortController;let n=0,u=0;try{for await(const s of r(c.signal)){const a=A(s),l=JSON.stringify(a);if(n+=1,u+=l.length,n>p||u>S)throw new k("STREAM_TOO_LONG",`durable stream exceeded its ceiling (${String(p)} chunks / ${String(S)} bytes); yield less, or drop \`durable\``,{status:507});b(o,e,n,l);for(const d of t.sinks)d.chunk({data:a,generation:t.generation,seq:n})||t.sinks.delete(d)}E(o,e,"complete",n);for(const s of t.sinks)s.complete()}catch(s){const{body:a,redacted:l}=R(s,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});l&&console.error("[@lunora/shard-engine] unhandled durable stream error:",s),E(o,e,"error",n,{code:a.code,message:a.message});for(const d of t.sinks)d.fail({code:a.code,message:a.message})}finally{this.runs.delete(e)}}trim(e){const r=Date.now();if(!(r-this.lastTrimAt<=N)){this.lastTrimAt=r;try{y(e,r)}catch{}}}}export{I as DurableStreamRunner,S as MAX_DURABLE_STREAM_BYTES,p as MAX_DURABLE_STREAM_CHUNKS,L as decideDurableAttach};
|