@lunora/shard-engine 1.0.0-alpha.213 → 1.0.0-alpha.215

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/dist/conformance/index.mjs +1 -1
  2. package/dist/index.d.mts +4 -930
  3. package/dist/index.d.ts +4 -930
  4. package/dist/index.mjs +1 -1
  5. package/dist/packem_shared/{ADMIN_FUNCTIONS-olXwJWFQ.mjs → ADMIN_FUNCTIONS-voPpYb3p.mjs} +1 -1
  6. package/dist/packem_shared/AGG_COUNT-DzvM-UU5.mjs +1 -0
  7. package/dist/packem_shared/{AUDIT_LOG_TABLE-BFJ65SRS.mjs → AUDIT_LOG_TABLE-CGyZ2LNx.mjs} +1 -1
  8. package/dist/packem_shared/{CDC_LOG_TABLE-fCPCjSE4.mjs → CDC_LOG_TABLE-DchHJJ5G.mjs} +6 -6
  9. package/dist/packem_shared/{CLIENT_WATERMARK_TABLE-De7z_OHV.mjs → CLIENT_WATERMARK_TABLE-CMUFBMfO.mjs} +1 -1
  10. package/dist/packem_shared/{COMMIT_SEQ_FIELD-Da1DjGqo.mjs → COMMIT_SEQ_FIELD-lEe6aaMv.mjs} +1 -1
  11. package/dist/packem_shared/CompanionMemo-CYnosDCb.mjs +1 -0
  12. package/dist/packem_shared/{DATA_MIGRATION_STATE_TABLE-CPWZjliE.mjs → DATA_MIGRATION_STATE_TABLE-D5giMetp.mjs} +1 -1
  13. package/dist/packem_shared/{DEFAULT_MAX_RELATION_KEYS-xz76_vX6.mjs → DEFAULT_MAX_RELATION_KEYS-UrlFzZB3.mjs} +1 -1
  14. package/dist/packem_shared/{DEFAULT_MAX_RELAYS-BZLpaaq1.mjs → DEFAULT_MAX_RELAYS-BcyWWSdU.mjs} +1 -1
  15. package/dist/packem_shared/DOC_COLUMN-BNhw3l1X.mjs +1 -0
  16. package/dist/packem_shared/{DurableStreamRunner-MMlV5qKQ.mjs → DurableStreamRunner-BikgXQLq.mjs} +1 -1
  17. package/dist/packem_shared/{GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs → GLOBAL_SHAPE_SNAPSHOT_TABLE-Cdq1nHtu.mjs} +1 -1
  18. package/dist/packem_shared/{IDEMPOTENCY_TABLE-BVosXEq_.mjs → IDEMPOTENCY_TABLE-DyKgfnGa.mjs} +1 -1
  19. package/dist/packem_shared/IMPORT_MANIFEST_TTL_MS-g0o4UIT_.mjs +1 -0
  20. package/dist/packem_shared/{MAIL_RETENTION-DMolrLYt.mjs → MAIL_RETENTION-C0LZvTbG.mjs} +3 -3
  21. package/dist/packem_shared/NotUniqueError-C_IDBwvG.mjs +1 -0
  22. package/dist/packem_shared/{QUEUE_TABLE-C-goXtGd.mjs → QUEUE_TABLE-CWUNphDm.mjs} +3 -3
  23. package/dist/packem_shared/RANK_TIEBREAK-BknRdgt8.mjs +1 -0
  24. package/dist/packem_shared/{REACTOR_STATE_TABLE-D2Mn204f.mjs → REACTOR_STATE_TABLE-B2x69RYJ.mjs} +1 -1
  25. package/dist/packem_shared/{SCHEDULE_OUTBOX_TABLE-iyyiSjsO.mjs → SCHEDULE_OUTBOX_TABLE-BPs0yEDb.mjs} +1 -1
  26. package/dist/packem_shared/{SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs → SCHEMA_HISTORY_MAX_VERSIONS-Cgw1Tg1r.mjs} +1 -1
  27. package/dist/packem_shared/{SEARCH_STATE_TABLE-D7w8mRsm.mjs → SEARCH_STATE_TABLE-DJywWtgJ.mjs} +1 -1
  28. package/dist/packem_shared/{SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs → SHAPE_POKE_CURSOR_TABLE-CKl7syse.mjs} +1 -1
  29. package/dist/packem_shared/VECTOR_BACKFILL_MAX_PAGES-CxiEhH8V.mjs +1 -0
  30. package/dist/packem_shared/WORKERD_SQLITE_LIMITS-C9dUlw3o.mjs +1 -0
  31. package/dist/packem_shared/{adminTokenExists-CQ0qedmu.mjs → adminTokenExists-CDwEWaFF.mjs} +1 -1
  32. package/dist/packem_shared/{appendStreamChunk-BZYgGE9Y.mjs → appendStreamChunk-DIxOE9q_.mjs} +1 -1
  33. package/dist/packem_shared/{applyInsertDefaults-CaVH3fJ7.mjs → applyInsertDefaults-Bt6LYmPD.mjs} +1 -1
  34. package/dist/packem_shared/{archiveCdcSegment-Cr8oGLfB.mjs → archiveCdcSegment-B3UKVQ9U.mjs} +1 -1
  35. package/dist/packem_shared/backfillAggregateIndexes-BkCo8Dpf.mjs +1 -0
  36. package/dist/packem_shared/buildReprojectionMigration-CCr-Pv9T.mjs +1 -0
  37. package/dist/packem_shared/{buildShapeDiff-DrXTkXKH.mjs → buildShapeDiff-CrLtKTuR.mjs} +1 -1
  38. package/dist/packem_shared/{clearMemoryTables-aMRERF0w.mjs → clearMemoryTables-CIfrwTj8.mjs} +1 -1
  39. package/dist/packem_shared/compileWhereSql-CEy6QwJx.mjs +1 -0
  40. package/dist/packem_shared/computeRankPage-De_JKnna.mjs +1 -0
  41. package/dist/packem_shared/createCompanionSync-D5cqtwqR.mjs +1 -0
  42. package/dist/packem_shared/{createReplicaLink-BapaAUfm.mjs → createReplicaLink-auEtD_6G.mjs} +1 -1
  43. package/dist/packem_shared/{ctx-db-relay-shapes-DBobAek2.mjs → ctx-db-relay-shapes-V1HnPPPX.mjs} +1 -1
  44. package/dist/packem_shared/{ctx-db-search-state-CPKPy8N6.mjs → ctx-db-search-state-Bv_NxB1g.mjs} +1 -1
  45. package/dist/packem_shared/{defineEngineContractSuite-BGiRhp-9.mjs → defineEngineContractSuite-IBU5qtmg.mjs} +1 -1
  46. package/dist/packem_shared/do-sql-DT8JBpG8.mjs +1 -0
  47. package/dist/packem_shared/{exportShardRows-BEzRTBwD.mjs → exportShardRows-BxhBKedl.mjs} +1 -1
  48. package/dist/packem_shared/fts-companion-Cfz-hJum.mjs +1 -0
  49. package/dist/packem_shared/ftsCompanionDdl-NFICsmqs.mjs +1 -0
  50. package/dist/packem_shared/ftsRowidMapName-CGnFBC6P.mjs +1 -0
  51. package/dist/packem_shared/{isSoftDeleted-By7iuPdW.mjs → isSoftDeleted-Dc3VHgrR.mjs} +1 -1
  52. package/dist/packem_shared/isTtlExpired-ktYeluAa.mjs +1 -0
  53. package/dist/packem_shared/{materializeExternalRows-gZqs4Rsj.mjs → materializeExternalRows-LugivbOG.mjs} +1 -1
  54. package/dist/packem_shared/param-Y0zw_1Cv.mjs +1 -0
  55. package/dist/packem_shared/rankPivotConditionSql-CUX4Vuhv.mjs +1 -0
  56. package/dist/packem_shared/runDrizzle-DAtZbzBn.mjs +1 -0
  57. package/dist/packem_shared/runShardMigrations-DeOECCjz.mjs +5 -0
  58. package/dist/packem_shared/runSql-BBRXi81G.mjs +1 -0
  59. package/dist/packem_shared/selectShapeMembers-BP30uxpp.mjs +1 -0
  60. package/dist/packem_shared/sql-engine.d-CMrMcDfK.d.mts +888 -0
  61. package/dist/packem_shared/sql-engine.d-CMrMcDfK.d.ts +888 -0
  62. package/dist/packem_shared/where-sql-AVR5KloI.mjs +1 -0
  63. package/dist/sql.d.mts +47 -0
  64. package/dist/sql.d.ts +47 -0
  65. package/dist/sql.mjs +1 -0
  66. package/package.json +5 -1
  67. package/dist/packem_shared/AGG_COUNT-BaMXGlVQ.mjs +0 -1
  68. package/dist/packem_shared/CompanionMemo-jmlDbPlr.mjs +0 -1
  69. package/dist/packem_shared/IMPORT_MANIFEST_TTL_MS-BrNT0vUO.mjs +0 -1
  70. package/dist/packem_shared/NotUniqueError-Cv97uGOS.mjs +0 -1
  71. package/dist/packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs +0 -1
  72. package/dist/packem_shared/VECTOR_BACKFILL_MAX_PAGES-DbNHRd5m.mjs +0 -1
  73. package/dist/packem_shared/WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs +0 -1
  74. package/dist/packem_shared/backfillAggregateIndexes-BfJ2FeLv.mjs +0 -1
  75. package/dist/packem_shared/buildReprojectionMigration-wSas3lLT.mjs +0 -1
  76. package/dist/packem_shared/compileWhereSql--dIcrS0b.mjs +0 -1
  77. package/dist/packem_shared/computeRankPage-B6umzbg4.mjs +0 -1
  78. package/dist/packem_shared/createCompanionSync-DmciS_rv.mjs +0 -1
  79. package/dist/packem_shared/do-sql-Cf2rnuLV.mjs +0 -1
  80. package/dist/packem_shared/fts-companion-CE3EmIjk.mjs +0 -1
  81. package/dist/packem_shared/ftsCompanionDdl-B0bFCy6d.mjs +0 -1
  82. package/dist/packem_shared/isTtlExpired-Bymg2-13.mjs +0 -1
  83. package/dist/packem_shared/runDrizzle-RC09zZrh.mjs +0 -1
  84. package/dist/packem_shared/runShardMigrations-4_ene2xR.mjs +0 -5
  85. package/dist/packem_shared/selectShapeMembers-Ce6pOHKe.mjs +0 -1
  86. package/dist/packem_shared/where-sql-Cb_dSAMj.mjs +0 -1
@@ -0,0 +1 @@
1
+ import{LunoraError as v}from"@lunora/errors";import{q as At}from"./MAX_TOKEN_LENGTH-iFEGEcDL-DBPC6ZWl.mjs";import{S as eo,l as Ue,s as to}from"./fts-companion-Cfz-hJum.mjs";import{decodeWire as no,stableWireKey as Nt}from"@lunora/wire";import{sql as u}from"drizzle-orm";import{throwingScheduler as oo,aggregateSqlFunction as Ge,normalizeCountArgument as Qt}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as lt,encodeAggregateKey as ft,readAggregateValue as ut}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as Q,CountRlsUnsupportedError as ht,selectIndexForGroupBy as ro,selectIndexForCount as io,selectIndexForAggregate as so}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as co,searchIndexCoversTable as ao}from"./backfillAggregateIndexes-BkCo8Dpf.mjs";import{backfillAggregateIndexes as ps,backfillRankIndexes as gs,backfillSearchIndexes as ys}from"./backfillAggregateIndexes-BkCo8Dpf.mjs";import{appendCdcChange as lo,readCdcDocAtOrBefore as fo}from"./CDC_LOG_TABLE-DchHJJ5G.mjs";import{CDC_LOG_TABLE as Es,applyCdcChanges as ms,bumpCdcEpoch as vs,cdcCanVouchFor as Ss,cdcForkedError as Rs,cdcSeqLeavingRows as _s,cdcTouchesTables as Ts,cdcTrimmedError as As,compactCdcDocs as Is,cursorBelowRetainedFloor as bs,minCdcReplayableSeq as Cs,minCdcSeq as xs,readCdcChangeKeys as Ms,readCdcChanges as Ds,readCdcCursor as ks,readCdcEpoch as Ls,trimCdcChanges as Fs}from"./CDC_LOG_TABLE-DchHJJ5G.mjs";import{allocateCommitSeq as uo,COMMIT_SEQ_FIELD as ho}from"./COMMIT_SEQ_FIELD-lEe6aaMv.mjs";import{createCompanionSync as wo}from"./createCompanionSync-D5cqtwqR.mjs";import{isMemoryTable as zt}from"./clearMemoryTables-CIfrwTj8.mjs";import{computeRankPage as Vt}from"./computeRankPage-De_JKnna.mjs";import{SCAN_DEP as G,PRIMARY_READ as po}from"./SCAN_DEP-B4Uu4g7l.mjs";import{runDrizzle as H}from"./runDrizzle-DAtZbzBn.mjs";import{b as go,j as Et,D as oe,r as Me,W as yo,e as de,h as $o,t as Eo,u as mo,i as vo,q as Jt,a as _n,g as So}from"./do-sql-DT8JBpG8.mjs";import{AGG_VALUE as je,AGG_COUNT as wt,AGG_KEY as He,doWhereSqlStrategy as ge,jsonPathSql as ye}from"./AGG_COUNT-DzvM-UU5.mjs";import{renderSql as Tn,unionAll as An}from"./param-Y0zw_1Cv.mjs";import{a as Ro,u as _o}from"./estimate-bytes-C-C35VXL.mjs";import{coveringGeohashes as To,boundingBoxGeohashes as Ao,haversineMeters as Io,pointInBoundingBox as bo}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Co}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as xo,assertPatchAllowed as Mo,operatorFields as Do,readPatchField as Yt}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as ko,encodeCursor as mt,nullsOrderSuffix as Lo,normalizeOrderKeys as Xt,uniqueIndexFields as Fo,buildSeekWhere as Wo,decodeCursor as Zt,buildSeekBeforeWhere as Bo,softDeleteScope as Ce,applySelect as In}from"./CURSOR_PREFIX-rOdoinP8.mjs";import{rankTableName as en,sortColumnName as tn,resolveRankPartition as qo,encodePartitionKey as Po,RANK_TIEBREAK as Oo}from"./RANK_TIEBREAK-BknRdgt8.mjs";import Uo from"./rankPivotConditionSql-CUX4Vuhv.mjs";import{UNVOUCHABLE_DEP as nn}from"./ADMIN_WILDCARD-BUrgWQ3-.mjs";import{idIndexKey as Go,withUnknownIndexKeys as jo,indexKeysForRow as Ho,buildIndexRange as Ko}from"./buildIndexRange-BTChxh3k.mjs";import $e from"./runSql-BBRXi81G.mjs";import{r as Je,j as De,c as Z,t as Ze,i as on}from"./where-sql-AVR5KloI.mjs";import{serializeSqlValue as ke}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as Le}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as No,isPushableWhere as Qo}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as zo,findRelated as Vo}from"./RELATED_DEFAULT_LIMIT-CAh3WUMn.mjs";import{assertFlatPredicate as pt,findManyPage as Jo,relationPredicateTables as Yo,resolveRelationPredicates as Xo,composeReadPredicate as Zo}from"./DEFAULT_MAX_RELATION_KEYS-UrlFzZB3.mjs";import{bindRelationWrites as er,describeSchemaRelationWrites as tr}from"./describeRelationWrites-BKd7YU5R.mjs";import{runRowValidators as Ke,transformOnlyDefinition as nr,applyInsertDefaults as vt,resolveWith as or,relationHooks as rr,applyOnDelete as ir,fanOutScalarCounts as sr,CASCADE_MAX_ROWS as cr}from"./applyInsertDefaults-Bt6LYmPD.mjs";import{guardWriter as ar}from"./RLS_UNWRAP_SYMBOL-CWo1Bk9y.mjs";import{WORKERD_SQLITE_LIMITS as bn}from"./WORKERD_SQLITE_LIMITS-C9dUlw3o.mjs";import{mayHoldProjectedValue as dr}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as lr}from"./createSystemReader-BSCxr8Qs.mjs";import{ConflictError as le}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as rn,runTriggers as fr}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as Bs,migrateClientWatermark as qs,readClientWatermark as Ps}from"./CLIENT_WATERMARK_TABLE-CMUFBMfO.mjs";import{IDEMPOTENCY_TABLE as Us,readIdempotent as Gs,trimIdempotent as js,writeIdempotent as Hs}from"./IDEMPOTENCY_TABLE-DyKgfnGa.mjs";import{runShardMigrations as Ns}from"./runShardMigrations-DeOECCjz.mjs";import{selectShapeMembers as zs,selectShapeRows as Vs}from"./selectShapeMembers-BP30uxpp.mjs";const ur=n=>{const i=atob(n),o=Uint8Array.from(i,s=>s.codePointAt(0)??0);return new TextDecoder().decode(o)},hr=()=>new v("INVALID_CURSOR","invalid cursor"),sn=16,cn=8,X=1024,It=(n,i)=>i.query(n),wr=(n,i)=>{if(n.length===0)return 0;let o=0;for(const[s,c]of i.entries()){const h=s===i.length-1;let g=0;for(const E of n)(h?E.startsWith(c):E===c)&&(g+=1);if(g===0)return 0;o+=g}return o},pr=(n,i)=>{if(!i)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",s=(o.codePointAt(0)??0)+1;if(s>=55296&&s<=57343||s>1114111)return{exact:!0,lower:n,upper:n};const c=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:c+String.fromCodePoint(s)}},gr=(n,i,o)=>{const s={eq:(c,h)=>{if(!n.definition.filterFields?.includes(c))throw new v("INTERNAL",`field "${c}" is not a filter field of search index "${n.indexName}" on table "${i}"`);if(n.filters.length>=cn)throw new v("BAD_REQUEST",`search index "${n.indexName}" on table "${i}": at most ${String(cn)} .eq() filters are supported per search query`);return n.filters.push({field:c,value:h}),s},search:(c,h)=>{const g=n;if(c!==g.definition.field)throw new v("INTERNAL",`search index "${g.indexName}" on table "${i}" indexes "${g.definition.field}", not "${c}"`);const E=It(h,o).length;if(E>sn)throw new v("BAD_REQUEST",`search index "${g.indexName}" on table "${i}": at most ${String(sn)} search terms are supported (got ${String(E)})`);return g.field=c,g.query=h,g.hasQuery=!0,s}};return s},yr=n=>{if(n.length>X)throw new v("BAD_REQUEST",`more than ${String(X)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},$r=n=>Math.min(n.offset+n.numItems+1,X),Er=n=>btoa(`search:${String(n)}`),mr=n=>{let i;try{i=ur(n)}catch{return}if(!i.startsWith("search:"))return;const o=Number(i.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},vr=n=>{if(typeof n.endCursor=="string")throw new v("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new v("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const i=Math.max(0,Math.floor(n.numItems)),o=n.cursor?mr(n.cursor):0;if(o===void 0)throw hr();if(o+i>=X)throw new v("BAD_REQUEST",`search pagination reaches the ${String(X)}-document limit (offset ${String(o)} + ${String(i)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,X-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:i,offset:o}},Sr=(n,i)=>{const o=i.offset+i.numItems,s=i.numItems>0&&n.length>o;return{continueCursor:s?Er(o):null,isDone:!s,page:n.slice(i.offset,o)}},Rr=n=>{if(n===void 0)return X+1;if(!Number.isFinite(n))return X;const i=Math.max(0,Math.floor(n));if(i>X)throw new v("BAD_REQUEST",`search returns at most ${String(X)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},Cn=500,xn=(n,i,o)=>{if(n!==void 0&&n!==Number.POSITIVE_INFINITY&&(!Number.isInteger(n)||n<0))throw o(`${i}: batch limit must be a non-negative integer`);return n??Cn},Mn=(n,i,o,s)=>{if(n>i)throw s(`${o}: batch of ${String(n)} exceeds the limit of ${String(i)} (raise options.limit or chunk the call)`)},_r=32,Tr=1024,Dn=(n,i,o,s)=>{const c=`SELECT id, _creationTime, ${Le(oe)} FROM ${Le(n)}`,h=`ORDER BY ${o}${s===void 0?"":` LIMIT ${String(s)}`}`;return i===void 0?Je(`${c} ${h}`):De(`${c} WHERE `,i,` ${h}`)},et={fieldRef:n=>Je(Et(n)),rangeTypeGuard:(n,i)=>Je(go(n,i)),serialize:ke},Ar=n=>n===void 0?"":Lo(n==="first"),kn=n=>{const i=n.map(o=>`${Et(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${Ar(o.nulls)}`);return n.some(o=>o.field==="_id"||o.field==="id")||i.push(`${Et("id")} ${ko(n)==="desc"?"DESC":"ASC"}`),i.join(", ")},Ir={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},Ln=n=>new Set(n.sqlConditions.filter(i=>i.comparator==="=").map(i=>i.field)),br=n=>{const i=Ln(n);let o=0;for(;o<n.indexFields.length&&i.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},Cr=(n,i)=>{const o=n.order,s=br(n),{shape:c}=i;return s.length>0?Xt(s.map(h=>({[h]:o})),c,{pinned:Ln(n),uniqueBy:Fo(i.indexes,c)}):Xt([{_creationTime:o}],c)},xr=(n,i,o,s)=>{const c=n.sqlConditions.map(h=>({[h.field]:{[Ir[h.comparator]??"eq"]:h.value}}));if(o&&c.push(Wo(i,Zt(o))),s&&c.push(Bo(i,Zt(s))),c.length!==0)return c.length===1?c[0]:{AND:c}},Mr=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,_r):n.want},St=(n,i,o,s,c,h,g)=>{const E=Cr(s,o),y=kn(E),w=[],{filters:x,want:T}=h;let A=h.cursor??void 0,C=Mr(h);if(T===0)return{documents:w,orderKeys:E};for(;;){const B=Z(xr(s,E,A,h.endCursor),et,Ze),P=Dn(i,c&&B?De(B," AND ",c):c??B,y,C),F=$e(n,P.text,...P.params).toArray();let O={};g(F.length);for(const K of F)if(O=Me(K),x.every(fe=>fe(O))&&w.push(O)===T)return{documents:w,orderKeys:E};if(C===void 0||F.length<C)return{documents:w,orderKeys:E};A=mt(O,E),C=Math.max(C,Math.min(C*2,Tr))}},Dr=(n,i,o,s,c,h,g,E)=>{const y=Math.max(0,Math.floor(c.numItems));if(typeof c.endCursor=="string"){const{documents:B,orderKeys:P}=St(n,i,o,s,h,{cursor:c.cursor,endCursor:c.endCursor,filters:g.all,selective:g.selective,want:void 0},E),F=B.length>=2?B[Math.floor(B.length/2)-1]:void 0;return{continueCursor:c.endCursor,isDone:!0,page:B,splitCursor:F?mt(F,P):null}}const{documents:w,orderKeys:x}=St(n,i,o,s,h,{cursor:c.cursor,filters:g.all,selective:g.selective,want:y+1},E),T=w.length>y,A=T?w.slice(0,y):w,C=A.at(-1);return{continueCursor:T&&C?mt(C,x):null,isDone:!T,page:A}},tt=n=>{const i=new Map;return o=>{const s=i.get(o);if(s!==void 0)return s;const c=n(Le(o));return i.set(o,c),c}},Ee=Le(oe),kr=tt(n=>`INSERT INTO ${n} (id, _creationTime, ${Ee}) VALUES (?, ?, ?)`),an=tt(n=>`UPDATE ${n} SET ${Ee} = ? WHERE id = ? AND ${Ee} = ?`),Lr=tt(n=>`UPDATE ${n} SET _creationTime = ?, ${Ee} = ? WHERE id = ? AND ${Ee} = ?`),Fr=tt(n=>`DELETE FROM ${n} WHERE id = ? AND ${Ee} = ?`),Wr="SELECT changes() AS changed",dn=new Map,Br="",qr=n=>{const i=JSON.stringify(n),o=dn.get(i);if(o!==void 0)return o;const s=n.map(h=>u`SELECT ${u.raw(`'${h.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${u.identifier(oe)} FROM ${u.identifier(h)} WHERE id = ${Br}`),{sql:c}=Tn("sqlite",u`${An(s)} LIMIT 1`);return dn.set(i,c),c},Pr=(n,i)=>i.map(()=>n),Or=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Ur=n=>{if(!Or.test(n))throw new v("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},Rt=n=>{if(n.includes("\0"))throw new v("BAD_REQUEST",`invalid row id ${JSON.stringify(n)}: a row id cannot hold a NUL character (U+0000)`)},Gr=(n,i,o,s)=>{if(o!==!0)return;const c=n!==void 0&&"serverDefault"in(n.shape._id?._meta?.column??{});for(const h of i){const g=c?vt(n,h,s)._id:h._id;typeof g=="string"&&Rt(g)}},ln=50,Ne=Math.floor(bn.boundParams/3),fn=bn.boundParams,jr=128,Ye=n=>new v("BATCH_LIMIT_EXCEEDED",n,{status:400}),Qe=(n,i,o)=>{Mn(n,xn(i,o,Ye),o,Ye)},un=async(n,i,o,s,c)=>{const h=xn(s,c,Ye),{page:g}=await n.findMany(i,Number.isFinite(h)?{limit:h+1,omitContinueCursor:!0,where:o}:{where:o});return g.length>h&&Mn(Math.max(await n.count(i,{where:o}),g.length),h,c,Ye),g},Hr=n=>{const i={eq:(o,s)=>(n.sqlConditions.push({comparator:"=",field:o,value:s}),i),gt:(o,s)=>(n.sqlConditions.push({comparator:">",field:o,value:s}),i),gte:(o,s)=>(n.sqlConditions.push({comparator:">=",field:o,value:s}),i),lt:(o,s)=>(n.sqlConditions.push({comparator:"<",field:o,value:s}),i),lte:(o,s)=>(n.sqlConditions.push({comparator:"<=",field:o,value:s}),i)};return i},Kr=n=>Math.max(n,X),Fn=(n,i)=>{const o=n.filters.map(s=>u`${ye(s.field)} = ${ke(s.value)}`);return i&&o.push(i),o},Nr=(n,i,o,s,c)=>{const h=It(o.query,At(o.definition.language));if(h.length===0)return[];const g=eo(i,o.indexName),E=`${g}__vocab`,y=h.length-1,w=h.map((P,F)=>{const O=pr(P,F===y),K=O.exact?u`${u.identifier("term")} = ${O.lower}`:u`${u.identifier("term")} >= ${O.lower} AND ${u.identifier("term")} < ${O.upper}`;return u`SELECT ${u.identifier("doc")}, ${u.raw(String(F))} AS ${u.identifier("__term__")}, COUNT(*) AS ${u.identifier("__n__")} FROM ${u.identifier(E)} WHERE ${K} GROUP BY ${u.identifier("doc")}`}),x=h.map((P,F)=>u`SUM(CASE WHEN u.${u.identifier("__term__")} = ${u.raw(String(F))} THEN u.${u.identifier("__n__")} ELSE 0 END)`),T=u`SELECT f.${u.identifier(Ue)} AS ${u.identifier(Ue)}, ${u.join(x,u` + `)} AS ${u.identifier("__score__")} FROM (${An(w)}) u JOIN ${u.identifier(g)} f ON f.rowid = u.${u.identifier("doc")} GROUP BY f.${u.identifier(Ue)} HAVING ${u.join(x.map(P=>u`${P} > 0`),u` AND `)}`,A=Fn(o,c);let C=u`SELECT m.id, m._creationTime, m.${u.identifier(oe)}, s.${u.identifier("__score__")} AS ${u.identifier("__score__")} FROM (${T}) s JOIN ${u.identifier(i)} m ON m.id = s.${u.identifier(Ue)}`;A.length>0&&(C=u`${C} WHERE ${u.join(A,u` AND `)}`),C=u`${C} ORDER BY s.${u.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${u.raw(String(s))}`;const B=[];for(const P of H(n,C)){const F=_n(P);if(F){const O=P.__score__;B.push({document:F,score:typeof O=="number"?O:Number(O??0)})}}return B},Qr=(n,i,o,s,c)=>{const h=At(o.definition.language),g=It(o.query,h);if(g.length===0)return[];const E=Fn(o,c);let y=u`SELECT id, _creationTime, ${u.identifier(oe)} FROM ${u.identifier(i)}`;E.length>0&&(y=u`${y} WHERE ${u.join(E,u` AND `)}`),y=u`${y} ORDER BY _creationTime DESC, id ASC LIMIT ${u.raw(String(Kr(s)))}`;const w=H(n,y).toArray(),x=[];for(const T of w){const A=_n(T);if(!A)continue;const C=wr(to(A,o.definition),g);C>0&&x.push({creationTime:typeof A._creationTime=="number"?A._creationTime:0,doc:A,id:typeof A._id=="string"?A._id:"",score:C})}return x.sort((T,A)=>A.score-T.score||A.creationTime-T.creationTime||T.id.localeCompare(A.id)),x.slice(0,s).map(T=>({document:T.doc,score:T.score}))},gt=(n,i,o,s)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new v("BAD_REQUEST",`geo index "${s}" on table "${o}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},zr=(n,i)=>{const o=n,s={near:(c,h)=>{if(o.within)throw new v("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(gt(c,".near() point",i,o.indexName),!Number.isFinite(h)||h<=0)throw new v("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(h)}`);return o.near={point:{lat:c.lat,lng:c.lng},radiusMeters:h},s},within:c=>{if(o.near)throw new v("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(gt(c.sw,".within() sw corner",i,o.indexName),gt(c.ne,".within() ne corner",i,o.indexName),c.sw.lat>c.ne.lat)throw new v("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(c.sw.lng>c.ne.lng)throw new v("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return o.within={ne:{lat:c.ne.lat,lng:c.ne.lng},sw:{lat:c.sw.lat,lng:c.sw.lng}},s}};return s},Vr=(n,i)=>{const o=n[i];if(o===null||typeof o!="object")return;const{lat:s,lng:c}=o;return typeof s=="number"&&typeof c=="number"?{lat:s,lng:c}:void 0},Jr=(n,i)=>{const o=Vr(n,i.definition.field);if(!o)return;const s=typeof n._creationTime=="number"?n._creationTime:0;if(i.near){const c=Io(i.near.point,o);return c<=i.near.radiusMeters?{creationTime:s,distance:c}:void 0}return bo(o,i.within)?{creationTime:s,distance:0}:void 0},Yr=(n,i,o,s)=>{if(!o.near&&!o.within)throw new v("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const c=o.near?To(o.near.point,o.near.radiusMeters):Ao(o.within),h=So(i,o.indexName),g=c.map(T=>u`(g.${u.identifier("__geohash__")} >= ${T} AND g.${u.identifier("__geohash__")} < ${`${T}{`})`),E=[u`(${u.join(g,u` OR `)})`];s&&E.push(s);const y=u`SELECT m.id, m._creationTime, m.${u.identifier(oe)} FROM ${u.identifier(h)} g JOIN ${u.identifier(i)} m ON m.id = g.${u.identifier("__id__")} WHERE ${u.join(E,u` AND `)}`,w=H(n,y).toArray(),x=[];for(const T of w){const A=Me(T),C=A?Jr(A,o):void 0;A&&C&&x.push({creationTime:C.creationTime,distance:C.distance,doc:A})}return x.sort((T,A)=>T.distance-A.distance||A.creationTime-T.creationTime),x},Wn=(n,i,o,s)=>{const c=[];for(const h of n)if(i.every(g=>g(s(h)))&&(c.push(h),typeof o=="number"&&c.length>=o))break;return c},Xr=(n,i,o,s,c,h=()=>{})=>{const g=o.within!==void 0,E=Yr(n,i,o,c).map(y=>({distanceMeters:g?null:y.distance,document:y.doc}));return h(E.length),typeof s=="number"?E.slice(0,Math.max(0,Math.floor(s))):E},hn=(n,i,o,s,c,h,g=()=>{})=>{const{geo:E}=o;if(!E)throw new v("INTERNAL","runGeoTerminalScored called without a staged geo query");const y=c.length>0,w=Xr(n,i,E,y?void 0:h,s,g);return y?Wn(w,c,h,x=>x.document):w},wn=(n,i,o)=>{const s=n.shape[i];if(s!==void 0&&dr(s))throw new v("BAD_REQUEST",`${o}: "${i}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},Zr=n=>{let i=0;const o=[],s={...et,relationExists:c=>{const{childWhere:h,negated:g,parentTable:E,relation:y}=c,w=`__rel_${String(i)}`,x=o.at(-1)??E;i+=1,n(y.table,G);const T=y.kind==="one"?y.field:y.references,A=y.kind==="one"?y.references:y.field,C=Je(`${Jt(w,A)} = ${Jt(x,T)}`);o.push(w);const B=Z(h,s,Ze);o.pop();const P=B===void 0?C:De(C," AND ",B),F=De("EXISTS (SELECT 1 FROM ",on(y.table)," AS ",on(w)," WHERE ",P,")");return g?De("NOT ",F):F}};return s};class ei extends v{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const ti=/\s/u,ni=String.fromCodePoint(0),pn=(n,i,o)=>{if(!n.tables[i])throw new v("INTERNAL",`unknown table: ${i}`);return typeof o!="string"||o.length===0||ti.test(o)||o.includes(ni)?null:o},Bn=(n,i,o,s=()=>{},c=()=>{},h=()=>{},g)=>{const E=i.tables[o];if(!E)throw new v("INTERNAL",`unknown table: ${o}`);const y=Ce(E.softDeleteMode,void 0),w=g??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},x=()=>{const R=Q(y,w.pushedWhere);return R?Z(R,ge):void 0},T=()=>{const R=Q(y,w.pushedWhere);return R?Z(R,et,Ze):void 0},A=()=>[...w.inMemoryFilters,...w.verifyFilters];let C=0;const B=R=>{const{search:M}=w;if(!M)throw new v("INTERNAL","runSearchFetch called without a staged search");co(mo(n),o,E);const k=w.inMemoryFilters.length>0,L=Rr(k?void 0:R),re=vo(n);if(re&&!ao(n,o,M.definition))throw new v("SEARCH_INDEX_BUILDING",`search index "${M.indexName}" on table "${o}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const q=x(),ce=re?Nr(n,o,M,L,q):Qr(n,o,M,L,q);!k&&R===void 0&&yr(ce);const ae=A();return C=ce.length,ae.length>0?Wn(ce,ae,R,me=>me.document):ce},P=R=>B(R).map(M=>M.document),F=R=>{const M=vr(R);return Sr(P($r(M)),M)},O=()=>{if(w.search||w.geo||w.indexName===void 0){c(void 0);return}c(Ko(o,w.indexName,w.indexFields,w.sqlConditions,ke))},K=R=>{O();let M=0;const k=(()=>{if(w.search){const L=P(R);return M=C,L}return w.geo?hn(n,o,w,x(),A(),R,L=>{M=L}).map(L=>L.document):St(n,o,E,w,T(),{filters:A(),selective:w.inMemoryFilters.length>0,want:R===void 0?void 0:Math.max(0,Math.floor(R))},L=>{M+=L}).documents})();return h(Math.max(M,k.length)),k},fe=()=>{if(!w.search&&!w.geo)throw new v("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);O();let R=0;const M=(()=>{if(w.search){const k=B(void 0);return R=C,k}return hn(n,o,w,x(),A(),void 0,k=>{R=k})})();return h(Math.max(R,M.length)),M},z={async*[Symbol.asyncIterator](){const R=Bn(n,i,o,s,c,h,{...w,indexFields:[...w.indexFields],inMemoryFilters:[...w.inMemoryFilters],sqlConditions:[...w.sqlConditions],verifyFilters:[...w.verifyFilters]});if(w.search){yield*await R.collect();return}let M;for(;;){const k=await R.paginate({cursor:M??null,numItems:jr});if(yield*k.page,k.isDone||k.continueCursor===null)return;M=k.continueCursor}},async collect(){return K(void 0)},async collectWithScores(){return fe()},filter(R){const M=No(R);return M!==void 0&&Qo(M,E.shape)?(w.pushedWhere=Q(w.pushedWhere,M),w.verifyFilters.push(R)):w.inMemoryFilters.push(R),z},async first(){return K(1)[0]??null},order(R){return w.order=R==="desc"?"desc":"asc",z},async paginate(R){let M=0;if(O(),w.search){const L=F(R);return h(L.page.length),L}if(w.geo)throw new v("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const k=Dr(n,o,E,w,R,T(),{all:A(),selective:w.inMemoryFilters.length>0},L=>{M+=L});return h(Math.max(M,k.page.length)),k},async take(R){return K(R)},async unique(){const R=K(2);if(R.length>1)throw new ei(`unique() on table "${o}" matched ${String(R.length)} documents; expected at most one`);return R[0]??null},withGeoIndex(R,M){const k=(E.geoIndexes??[]).find(re=>re.name===R);if(!k)throw new v("INTERNAL",`unknown geo index "${R}" on table "${o}"`);s(o,R,"geo");const L={definition:k,indexName:R};if(w.geo=L,M(zr(L,o)),!L.near&&!L.within)throw new v("INTERNAL",`geo index "${R}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return z},withIndex(R,M){const k=E.indexes.find(L=>L.name===R);if(!k)throw new v("INTERNAL",`unknown index "${R}" on table "${o}"`);return s(o,R,"index"),w.indexName=R,w.indexFields=k.fields,M&&M(Hr(w)),z},withSearchIndex(R,M){const k=(E.searchIndexes??[]).find(re=>re.name===R);if(!k)throw new v("INTERNAL",`unknown search index "${R}" on table "${o}"`);s(o,R,"search");const L={definition:k,field:k.field,filters:[],hasQuery:!1,indexName:R,query:""};if(w.search=L,M(gr(L,o,At(k.language))),!L.hasQuery)throw new v("INTERNAL",`search index "${R}" on table "${o}" requires a .search(field, query) call`);return z}};return z},yt=(n,i,o,s)=>{const c=o;for(const[h,g]of Eo(n)){if(g.serverDefault){h in i&&(c[h]=g.serverDefault({auth:s}));continue}g.onUpdateFn&&!(h in i)&&(c[h]=g.onUpdateFn())}},gn=5,yn=(n,i)=>{for(const o of Object.keys(i))if(i[o]===void 0)throw new v("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},$n=["_commitSeq","_creationTime","_id"],ze=n=>$n.some(i=>i in n)?Object.fromEntries(Object.entries(n).filter(([i])=>!$n.includes(i))):n,oi=/unique constraint failed/i,ri=n=>n instanceof Error&&oi.test(n.message),ii=/string or blob too big/iu,si=(n,i)=>{if(!(!(n instanceof Error)||!ii.test(n.message)))throw new v("PAYLOAD_TOO_LARGE",`document is too large to store in "${i}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},_t=(n,i,o,s)=>{try{$e(n,o,...s)}catch(c){throw ri(c)?new le(`unique constraint violation on "${i}"`,"unique"):(si(c,i),c)}},Ve=(n,i,o,s)=>{if(_t(n,i,o,s),$e(n,Wr).one().changed===0)throw new le(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},En=(n,i,o,s,c,h,g)=>{const E=[];for(let T=0;T<o.length+1;T+=1){const A=o[T],C=s[T],B=C?.direction==="desc"?"desc":"asc",P=A===void 0||C===void 0?u`${u.identifier(Oo)} < ${g}`:Uo(A,h[T],B,!1);if(P===void 0)continue;const F=[];for(let K=0;K<T;K+=1)F.push(u`${u.identifier(o[K])} IS ${h[K]}`);F.push(P);const[O]=F;E.push(F.length===1&&O!==void 0?O:u`(${u.join(F,u` AND `)})`)}const y=E.length>0?u.join(E,u` OR `):u`1 = 0`,w=H(n,u`SELECT COUNT(*) AS c FROM ${u.identifier(i)} WHERE ${u.identifier("__partition__")} = ${c} AND (${y})`).one(),x=H(n,u`SELECT COUNT(*) AS c FROM ${u.identifier(i)} WHERE ${u.identifier("__partition__")} = ${c}`).one();return{before:w.c,total:x.c}},ci=n=>{const i=new Map;for(const[s,c]of Object.entries(n.tables))for(const h of Object.values(c.relationMap??{}))h.kind==="one"&&(h.onDelete==="cascade"||h.onDelete==="set null")&&i.set(h.table,[...i.get(h.table)??[],{holder:s,op:h.onDelete==="cascade"?"delete":"update"}]);const o=s=>{const c=new Set,h=[s];for(let g=h.pop();g!==void 0;g=h.pop())for(const{holder:E,op:y}of i.get(g)??[]){if(E===s||rn(n,E,y))return!0;c.has(E)||(c.add(E),h.push(E))}return!1};return new Set(Object.entries(n.tables).filter(([s,c])=>c.shardMode?.kind==="global"||rn(n,s,"delete")||o(s)).map(([s])=>s))},ai=n=>{const i=new Map;for(const[o,s]of Object.entries(n.tables))s.softDeleteMode&&i.set(o,s.softDeleteMode.field);return i},mn=new WeakMap,di=n=>{const i=Object.freeze({entries:()=>n.entries(),forEach:(o,s)=>{for(const c of n)o.call(s,c,c,i)},has:o=>n.has(o),keys:()=>n.keys(),get size(){return n.size},values:()=>n.values(),[Symbol.iterator]:()=>n.values()});return i},li=n=>{const i=Object.freeze({entries:()=>n.entries(),forEach:(o,s)=>{for(const[c,h]of n)o.call(s,h,c,i)},get:o=>n.get(o),has:o=>n.has(o),keys:()=>n.keys(),get size(){return n.size},values:()=>n.values(),[Symbol.iterator]:()=>n.entries()});return i},fi=n=>{const i=mn.get(n);if(i!==void 0)return i;const o=Object.freeze(zo(n).map(g=>Object.freeze(g))),s=new Map,c=g=>(n.tables[g]?.shardMode?.kind??"root")==="root";for(const g of o)!g.array&&c(g.sourceTable)&&c(g.targetTable)&&s.set(g.sourceTable,[...s.get(g.sourceTable)??[],g]);for(const g of s.values())Object.freeze(g);const h={checkedForeignKeys:s,deleteRereadTables:di(ci(n)),relationEdges:o,relationWrites:tr(n),softDeleteFields:li(ai(n))};return mn.set(n,h),h},$t=new WeakMap,ui=(n,i)=>{let o=$t.get(i.tables);if(!$t.has(i.tables)){const c=Object.keys(i.tables).map(h=>h.replaceAll(/[$()*+.?[\\\]^{|}]/gu,String.raw`\$&`));o=c.length===0?void 0:new RegExp(`"(${c.join("|")})"`,"gu"),$t.set(i.tables,o)}if(o===void 0)return;const s=new Set;for(const c of n.matchAll(o))s.add(c[1]);return s.size===1?[...s][0]:void 0},hi=(n,i,o)=>{for(const s of n){const c=s,h=c?.[oe];if(typeof h=="string"){const g=c?.id,E=_o(h);typeof g!="string"?i.recordReadBytes(E):o===void 0?i.recordDocumentRead(`${g}\0${String(E)}`,E):i.recordDocumentRead(`${o}\0${g}`,E)}}},wi=(n,i,o)=>{if(i===void 0)return n;const s=(c,...h)=>{const g=n.exec(c,...h),E=g.one.bind(g),y=g[Symbol.iterator].bind(g),w=o===void 0?void 0:ui(c,o);let x=!1;const T=A=>{hi(A,i,w)};return g.toArray=()=>{const A=[];for(const C of{[Symbol.iterator]:y})T([C]),A.push(C);return A},g.one=()=>{x=!0;try{const A=E();return T([A]),A}finally{x=!1}},g[Symbol.iterator]=function*(){for(const C of{[Symbol.iterator]:y})x||T([C]),yield C},g};return new Proxy(n,{get:(c,h)=>h==="exec"?s:h===yo?c:Reflect.get(c,h,c)})},pi=new Map([["findFirst","rows"],["findFirstOrThrow","rows"],["findMany","page"],["get","rows"],["lookupById","lookup"],["rankPage","page"]]),gi=new Map([["collect","rows"],["collectWithScores","scored"],["first","rows"],["paginate","page"],["take","rows"],["unique","rows"]]),xe=(n,i,o)=>{if(typeof n!="object"||n===null)return;const s=Ro(n);if(s===void 0)return;const c=n._id;typeof c=="string"?o.recordDocumentRead(`global\0${i}\0${c}`,s):o.recordReadBytes(s)},Xe=(n,i,o,s)=>{if(typeof n!="object"||n===null)return;const c=n;switch(i){case"lookup":{xe(c.row,typeof c.tableName=="string"?c.tableName:o,s);return}case"page":{for(const h of c.page??[])xe(h,o,s);return}case"rows":{for(const h of Array.isArray(n)?n:[n])xe(h,o,s);return}default:for(const h of Array.isArray(n)?n:[])xe(h.document,o,s)}},qn=(n,i,o)=>new Proxy(n,{get:(s,c)=>{const h=Reflect.get(s,c,s);if(typeof h!="function")return h;if(c===Symbol.asyncIterator)return async function*(){for await(const y of Reflect.apply(h,s,[]))xe(y,i,o),yield y};const g=gi.get(c);return(...E)=>{const y=Reflect.apply(h,s,E);return g!==void 0?Promise.resolve(y).then(w=>(Xe(w,g,i,o),w)):typeof y=="object"&&y!==null&&!(y instanceof Promise)?qn(y,i,o):y}}}),yi=new Set(["findFirst","findFirstOrThrow","findMany"]),$i=n=>{const i=n[1],o=i?.select;if(!Array.isArray(o))return;const s=Object.fromEntries(Object.entries(i).filter(([g])=>g!=="select")),c=s.with,h=g=>In(g,o,c);return{args:[n[0],s,...n.slice(2)],project:(g,E)=>typeof g!="object"||g===null?g:E==="page"?{...g,page:h(g.page)}:h([g])[0]}},vn=256,Tt=4096,Ei=1024*1024,mi=async(n,i,o,s)=>{const c=i[1]??{},h=[];let{cursor:g}=c,E=vn,y=0;for(;;){const w=await n([i[0],{...c,cursor:g,limit:E},...i.slice(2)]);if(Array.isArray(w))return Xe(w,"rows",o,s),[...h,...w];const x=s.headroom().readBytes;if(Xe(w,"page",o,s),h.push(...w.page),w.isDone||typeof w.continueCursor!="string")return{continueCursor:null,isDone:!0,page:h};g=w.continueCursor,y+=s.headroom().readBytes-x,E=y>0?Math.min(Tt,Math.max(vn,Math.floor(Ei*h.length/y))):Tt}},vi=(n,i)=>n===void 0||i===void 0?n:new Proxy(n,{get:(o,s)=>{const c=Reflect.get(o,s,o);if(typeof c!="function")return c;if(s==="query")return(...g)=>qn(Reflect.apply(c,o,g),String(g[0]),i);const h=pi.get(s);return h===void 0?c:async(...g)=>{const E=yi.has(s)?$i(g):void 0;let y=E?.args??g;const w=String(g[0]),x=y[1],T=s==="findMany"&&typeof x?.endCursor=="string",A=s==="findMany"&&typeof x?.limit!="number"&&!T;if(T&&typeof x.limit!="number"&&(y=[y[0],{...x,limit:Tt},...y.slice(2)]),A){const B=await mi(P=>Reflect.apply(c,o,P),y,w,i);return E===void 0?B:E.project(B,h)}const C=await Reflect.apply(c,o,y);return Xe(C,h,w,i),E===void 0?C:E.project(C,h)}}}),Sn=new WeakMap,Rn=new WeakMap,Si=500,Ri=n=>{const{baselineSeq:i,onStalePatchDropped:o}=n,{headroom:s}=n,c=Sn.get(n)??{value:void 0},h=Rn.get(n)??{value:0};let g;const E=()=>{if(g===void 0){const e={...n,enforceRls:!1,headroom:void 0};Sn.set(e,c),Rn.set(e,h),g=Ri(e)}return g},y=wi(n.sql,s,n.schema),{schema:w}=n,x=n.broadcast??(()=>{}),T=(e,t)=>{if(!Object.hasOwn(w.tables,e))throw new v("BAD_REQUEST",`${t}: "${e}" is not a table in this schema`)},{checkedForeignKeys:A,deleteRereadTables:C,relationEdges:B,relationWrites:P,softDeleteFields:F}=fi(w),O=(e,t,r)=>{for(const a of A.get(e)??[]){const l=t[a.column];if(typeof l!="string"||r?.[a.column]===l||a.targetTable===e&&t._id===l)continue;if(H(y,u`SELECT 1 FROM ${u.identifier(a.targetTable)} WHERE id = ${l} LIMIT 1`).toArray().length===0)throw new v("VALIDATION_ERROR",`${a.name} references ${a.targetTable} row "${l}", which does not exist`)}},K=er(P,n.inTransaction),fe=()=>n.inTransaction?.()===!0,z=e=>w.tables[e]?.commitOrderedMode!==!0?{}:((c.value===void 0||!fe())&&(c.value=uo(y)),{[ho]:c.value}),R=(e,...t)=>{const r=w.tables[e]?.indexes??[],a=[];let l;for(const p of t)p&&(typeof p._id=="string"&&p._id!==l&&(l=p._id,a.push(Go(l))),a.push(...jo(r,Ho(r,p,ke))));return a.length>0?a:void 0},M=n.onRead??(()=>{}),k=e=>{zt(w.tables[e])&&M(nn,nn)},L=n.onReadRange??(e=>{M(e.table,G)}),re=e=>{k(e.table),L(e)},q=(e,t,r)=>{t!==void 0&&(r===!0||t!==G)&&s?.recordRead(1),k(e),M(e,t,r)},ce=(e,t)=>{const r=e.row._id;q(e.tableName,typeof r=="string"?r:t,typeof r=="string")},ae=n.onIndexUse??(()=>{}),me=n.onWrite??(()=>{}),ee=e=>{s?.recordWrite(e)},ve=async e=>{ee(e.doc),await me(e)},{cache:ue}=n,Se=n.clock??(()=>Date.now()),bt=n.idGenerator??(()=>crypto.randomUUID()),Ct=n.scheduler??oo,Re=vi(n.globalDb,s),he=n.auth??{identity:null,userId:null},xt=n.cdc??!1,nt=Ct,Pn=lr({scheduler:typeof nt.list=="function"&&typeof nt.get=="function"?nt:void 0,storage:n.storage}),_e=(e,t,r,a)=>{xt&&!zt(w.tables[e])&&lo(y,Se(),e,t,r,a)},Mt=(e,t,r,a)=>{const l=w.tables[e];if(l?.dropStalePatchesMode!==!0||!xt)return!1;const p=i?.();if(p===void 0)return!1;const d=fo(y,e,t,p);if(d===void 0)return!1;const f=Do(l,r);return Object.keys(ze(r)).some(m=>!f.has(m)&&Nt(Yt(d,m))!==Nt(Yt(a,m)))},ie=e=>w.tables[e]?.shardMode?.kind==="global",Dt=(e,t)=>{if(ie(e)){if(!Re)throw new v("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return Re}return U},ot=e=>Dt(e,"cascade"),j=(e,t)=>{if(ie(e)){if(!Re)throw new v("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return Re}},Te=(e,t)=>{q(e,G);for(const r of Yo(Q(t.baseWhere,t.where),w,e,t.relationBaseWhere))q(r,G)},se=(e,t,r)=>{ue?.invalidateTable(t),x({key:r,op:e,table:t})},kt=(e,t,r)=>{x({key:r,op:"insert",row:{...t,_id:r},table:e})},rt=async(e,t,r,a,l)=>{l&&ee(r);const p=await e.insert(t,r,a);return kt(t,r,p),p},Lt=async(e,t,r,a)=>{if(e.insertMany===void 0){const p=[];for(const d of r)p.push(await rt(e,t,d,{allowExplicitId:a},!1));return p}const l=await e.insertMany(t,r,{allowExplicitId:a,limit:Number.POSITIVE_INFINITY,onStored:(p,d)=>{for(const[f,m]of p.entries()){const b=r[d+f];if(b===void 0)throw new v("INTERNAL",`insertMany on global table '${t}' reported row ${String(d+f)} of ${String(r.length)}`);kt(t,b,m)}}});return r.map((p,d)=>{const f=l[d];if(typeof f!="string")throw new v("INTERNAL",`insertMany on global table '${t}' returned no id for row ${String(d)}`);return f})},On=(e,t)=>Dt(e,"relation load").findMany(e,t),Un=e=>e.through===void 0?[e.table]:[e.through.table,e.table],Ft=e=>{for(const t of e===void 0?[]:Un(e))ie(t)&&q(t,G)},Wt=(e,t)=>{const r=w.tables[e]?.relationMap??{};for(const[a,l]of Object.entries(t??{})){if(a==="_count"){for(const d of Object.keys(typeof l=="object"?l:{}))Ft(r[d]);continue}const p=r[a];p===void 0||l===void 0||l===!1||(Ft(p),typeof l=="object"&&Wt(p.table,l.with))}},it=(e,t)=>(ie(e)&&(q(e,G),Wt(e,t.with)),On(e,t)),Gn=e=>!ie(e.table),Bt=n.relationExistsPushDown??"auto",qt=Bt!=="never",{maxRelationKeys:Pt}=n,Fe=(e,t,r)=>Xo(e,{fetcher:it,maxRelationKeys:Pt,relationBaseWhere:r,schema:w,tableName:t}),jn=async(e,t,r,a,l)=>{const p=j(e,"relation grouped count");if(p)return Te(e,{relationBaseWhere:l,where:a}),sr((W,N)=>p.count(W,{relationBaseWhere:l,where:N}),e,t,r,a);const d=w.tables[e];if(!d)throw new v("INTERNAL",`unknown table: ${e}`);q(e,G);const f=Ce(d.softDeleteMode,void 0),m={[t]:{in:r}},b=Q(Q(m,a),f),_=await Fe(b,e,l),D=Z(_,ge),S=ye(t);let I=u`SELECT ${S} AS __fk__, COUNT(*) AS count FROM ${u.identifier(e)}`;D&&(I=u`${I} WHERE ${D}`),I=u`${I} GROUP BY ${S}`;const $=H(y,I).toArray();return new Map($.map(W=>[W.__fk__,W.count]))},Ot=new Set;for(const[e,t]of Object.entries(w.tables))for(const r of Object.values(t.triggerMap??{}))Ot.add(`${e} ${r.timing} ${r.op}`);const te=(e,t,r)=>Ot.has(`${e} ${t} ${r}`),ne=async(e,t,r)=>{if(h.value+=1,h.value>ln)throw h.value-=1,new le(`trigger recursion exceeded ${String(ln)} levels on "${r.table}" — check for a self-triggering write`,"trigger");try{await fr({ctx:Xn,event:r,op:t,schema:w,tableName:r.table,timing:e})}finally{h.value-=1}},{ensureBackfilledForTable:Ae,ensureBackfilledIndex:st,ensureRankBackfilled:ct,ensureRankBackfilledForTable:Ie,syncAggregates:We,syncCompanionsForInsert:at,syncGeo:Be,syncRanks:we,syncSearch:qe}=wo({broadcast:x,indexKeysFor:(e,t)=>R(e,t),invalidateCache:(e,t,r)=>ue?.invalidate(e,t,R(e,r)),recordCdc:_e,schema:w,sql:y,verified:n.companionMemo?.verified}),Hn=async(e,t)=>{const r=t.filter(({document:a,id:l})=>{try{return at(e,l,a),!0}catch(p){return console.warn(`[@lunora/shard-engine] insertManyUnsafe: companions of committed row "${l}" in "${e}" could not be synced:`,p),!1}});for(const{document:a,id:l}of r)if(Y(l,e)?.docJson===de(a))try{await me({doc:a,id:l,op:"insert",table:e})}catch(p){console.warn(`[@lunora/shard-engine] insertManyUnsafe: write report of committed row "${l}" in "${e}" failed:`,p)}},Ut=(e,t,r)=>{const{shardMode:a}=t;if(a?.kind==="shardBy"&&!(a.field!==void 0&&(r.partitionBy??[]).includes(a.field)))throw Object.assign(new Error(`rank index "${r.name}" on "${e}" partitions across shards (shard key "${a.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},Gt=e=>Object.entries(w.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),be=e=>e===void 0||ie(e)?Re:void 0,Kn=e=>Object.entries(w.tables).flatMap(([t,r])=>ie(t)?Object.values(r.relationMap??{}).flatMap(a=>a.through!==void 0||a.kind!=="one"||a.table!==e?[]:a.onDelete!=="cascade"&&a.onDelete!=="set null"?[]:[{action:a.onDelete==="cascade"?"delete":"update",field:a.field,holderTable:t,references:a.references}]):[]),Nn=async(e,t,r,a)=>r==="_id"?a:(await e.get(t,a))?.[r],Qn=async(e,t,r,a,l)=>{const p=[];let d;do{const f=await e.findMany(t,{cursor:d,includeDeleted:l,limit:Si,where:{[r]:a}});for(const m of f.page)p.push(String(m._id));d=f.isDone?void 0:f.continueCursor??void 0}while(d!==void 0&&p.length<=cr);return p},zn=async(e,t,r,a,l,p)=>{const{action:d,field:f,holderTable:m,references:b}=r,_=await Nn(e,t,b,a);if(_==null)return{effects:[],toExpand:[]};const D=await Qn(e,m,f,_,p),S=D.filter($=>!l.announced.has(`${d}:${m}:${$}`)),I=d==="delete"?D.filter($=>!l.expanded.has(`${m}:${$}`)):[];for(const $ of S)l.announced.add(`${d}:${m}:${$}`);for(const $ of I)l.expanded.add(`${m}:${$}`);return{effects:S.map($=>({id:$,op:d,table:m})),toExpand:I}},jt=async(e,t,r,a,l)=>{const p=[];for(const d of Kn(t))for(const f of r){const m=await zn(e,t,d,f,a,l);p.push(...m.effects),m.toExpand.length>0&&p.push(...await jt(e,d.holderTable,m.toExpand,a,l))}return p},dt=async(e,t,r,a,l)=>{for(let d=0;d<r.length;d+=1)ee(void 0);const p=a?.skipOnDelete===!0?[]:await jt(e,t,r,{announced:new Set,expanded:new Set},a?.hard===!0);try{if(l!==void 0&&e.deleteMany!==void 0)try{return await e.deleteMany(t,r,l.options)}finally{for(const d of r)se("delete",t,d)}for(const d of r)try{await e.delete(t,d,a)}finally{se("delete",t,d)}return{deleted:r.length}}finally{for(const d of p)se(d.op,d.table,d.id)}},Y=(e,t)=>{const r=Gt(t);for(let a=0;a<r.length;a+=fn){const l=r.slice(a,a+fn),[p]=$e(y,qr(l),...Pr(e,l)).toArray();if(!p)continue;const d=p.__t__,f=Me(p);if(typeof d!="string"||!f)return;const m=p[oe];return{docJson:typeof m=="string"?m:de(m??{}),row:f,tableName:d}}},Ht={assertRankPartitionLocal:Ut,ensureRankBackfilled:ct,onRead:q,rowToDocument:Me,schema:w,sql:y},Vn=(e,t,r)=>{const a=Z(r,ge);return a===void 0||H(y,u`SELECT 1 FROM ${u.identifier(e)} WHERE ${u.identifier("id")} = ${t} AND ${a}`).toArray().length>0},Jn=(e,t,r,a)=>Mt(e,t,r,a)?(o?.({fields:Object.keys(ze(r)),id:t,table:e}),!0):!1,Yn=async(e,t,r,a,l)=>{const p=Y(t,e);if(!p)return{applied:!1,doc:null};if(q(e,t),!Vn(e,t,r.where)||Jn(e,t,r.patch,p.row))return{applied:!1,doc:p.row};try{await l(r.patch)}catch(d){if(d instanceof le&&d.kind==="occ"&&a)return;throw d}return{applied:!0,doc:Y(t,e)?.row??null}},Kt=async(e,t,r,a)=>{const{fetchLimit:l,limit:p,orderKeys:d,predicate:f}=await Zo(t,r,{canPushExists:qt?Gn:void 0,existsPushMode:Bt==="always"?"always":"auto",fetcher:it,maxRelationKeys:Pt,schema:w,tableName:e}),m=qt?Zr(a):et,b=Z(f,m,Ze),_=Dn(e,b,kn(d),l);return{limit:p,orderKeys:d,statement:_}},U={system:Pn,async aggregate(e,t){const r=j(e,"aggregate");if(r)return Te(e,t),r.aggregate(e,t);const a=w.tables[e];if(!a)throw new v("INTERNAL",`unknown table: ${e}`);if(Ge(t.op),t.op==="count")return U.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new v("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);q(e,G);const l=Ce(a.softDeleteMode,void 0),p=Q(Q(t.baseWhere,t.where),l),d=await Fe(p,e,t.relationBaseWhere),f=d!==p;if(a.aggregateIndexes&&!t.baseWhere&&!f){const $=so(a.aggregateIndexes,t.op,t.field,t.where);if($){st(e,$.index);const W=ft($.index.by??[],$.key),N=lt(e,$.index.name),V=H(y,u`SELECT ${je} AS value, ${wt} AS count FROM ${u.identifier(N)} WHERE ${He} = ${W}`).toArray()[0];return ut(t.op,V)}}wn(a,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const m=Z(d,ge),b=Ge(t.op),_=ye(t.field);let D=u`SELECT ${u.raw(b)}(${_}) AS value FROM ${u.identifier(e)}`;m&&(D=u`${D} WHERE ${m}`);const I=H(y,D).toArray()[0]?.value;return I??null},asId(e,t){const r=pn(w,e,t);if(r===null)throw new v("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return r},async count(e,t){const r=j(e,"count");if(r)return Te(e,Qt(t)),r.count(e,t);const a=w.tables[e];if(!a)throw new v("INTERNAL",`unknown table: ${e}`);const l=Qt(t);if(l.restrictsCounts)throw new ht(e);q(e,G);const p=Ce(a.softDeleteMode,void 0),d=Q(Q(l.baseWhere,l.where),p),f=await Fe(d,e,l.relationBaseWhere),m=f!==d;if(a.aggregateIndexes&&!l.baseWhere&&!m){const S=io(a.aggregateIndexes,l.where);if(S){st(e,S.index);const I=ft(S.index.by??[],S.key),$=lt(e,S.index.name),W=H(y,u`SELECT ${je} AS value FROM ${u.identifier($)} WHERE ${He} = ${I}`).toArray();return W[0]===void 0?0:W[0].value??0}}const b=Z(f,ge);let _=u`SELECT COUNT(*) AS count FROM ${u.identifier(e)}`;return b&&(_=u`${_} WHERE ${b}`),H(y,_).one().count},async delete(e,t,r){T(e,"ctx.db.delete(table, id)");const a=Y(t,e);if(!a){const S=be(e);S&&await dt(S,e,[t],r);return}const{docJson:l,row:p,tableName:d}=a,f=w.tables[d],m=r?.hard===!0,b=!m&&f?.softDeleteMode?f:void 0,_=b?.softDeleteMode?.field;if(_&&p[_]!==null&&p[_]!==void 0)return;if(te(d,"before","delete")&&await ne("before","delete",{id:t,op:"delete",previous:p,table:d}),r?.skipOnDelete!==!0&&await ir({deletedId:t,deletedReference:S=>p[S],findHolders:async(S,I,$,W)=>(await ot(S).findMany(S,{...W,includeDeleted:m,where:{[I]:$}})).page,onCascade:(S,I)=>ot(S).delete(S,I,r),onRestrict:S=>{throw new le(S,"restrict")},onSetNull:(S,I,$)=>ot(S).patch(S,I,{[$]:null}),schema:w,tableName:d}),Ae(d),Ie(d),b&&_){const S={[_]:Se()},I={...p,...z(d),...S,_id:t};yt(b,S,I,he),Ve(y,d,an(d),[de(I),t,l]),qe(d,t,I,p),Be(d,t,void 0),We(d,p,I),we(d,t,p,void 0);const $=R(d,p,I);ue?.invalidate(d,t,$),_e(d,t,"update",I),x({indexKeys:$,key:t,op:"update",row:I,table:d}),te(d,"after","delete")&&await ne("after","delete",{id:t,op:"delete",previous:p,table:d}),await ve({id:t,op:"delete",table:d});return}Ve(y,d,Fr(d),[t,l]),qe(d,t,void 0),Be(d,t,void 0),We(d,p,void 0),we(d,t,p,void 0);const D=R(d,p);ue?.invalidate(d,t,D),_e(d,t,"delete"),x({indexKeys:D,key:t,op:"delete",table:d}),te(d,"after","delete")&&await ne("after","delete",{id:t,op:"delete",previous:p,table:d}),await ve({id:t,op:"delete",table:d})},async deleteAll(e,t){if(!w.tables[e])throw new v("INTERNAL",`unknown table: ${e}`);if(s!==void 0)return E().deleteAll(e,t);const r=Math.max(1,t?.chunkSize??Cn),a=t?.hard===void 0?void 0:{hard:t.hard},l=j(e,"deleteAll");let p=0;for(;;){const f=(await U.findMany(e,{includeDeleted:t?.hard===!0,limit:r})).page.map(m=>String(m._id));if(f.length===0)break;for(const m of f)await(l===void 0?U.delete(e,m,a):dt(l,e,[m],a)),p+=1;if(f.length<r)break}return{deleted:p}},async deleteMany(e,t,r){T(e,"ctx.db.deleteMany(table, ids)"),Qe(t.length,r?.limit,"deleteMany");for(const a of t)await U.delete(e,a);return{deleted:t.length}},async deleteWhere(e,t,r){const a=j(e,"deleteWhere"),p=(await un(a??U,e,t,r?.limit,"deleteWhere")).map(d=>String(d._id));if(a)return dt(a,e,p,void 0,{options:r});if(U.deleteMany===void 0)throw new v("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return U.deleteMany(e,p,r)},async findFirst(e,t={}){return(await U.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const r=await U.findFirst(e,t);if(r===null)throw new Co(`findFirstOrThrow: no "${e}" document matched`);return r},async findMany(e,t={}){const r=j(e,"findMany");if(r)return Te(e,t),t.consistency==="primary"&&M(e,po),r.findMany(e,t);const a=w.tables[e];if(!a)throw new v("INTERNAL",`unknown table: ${e}`);const l=!t.where&&!t.baseWhere;l?q(e,G):q(e);const{limit:p,orderKeys:d,statement:f}=await Kt(e,a,t,q),m=$e(y,f.text,...f.params).toArray();l&&s?.recordRead(m.length);const b=[];for(const D of m){const S=Me(D);S&&(b.push(S),!l&&typeof S._id=="string"&&q(e,S._id))}const _=Jo(b,{endCursor:t.endCursor,limit:p,omitContinueCursor:t.omitContinueCursor,orderKeys:d});return t.with&&await or({fetcher:it,groupedCounter:jn,parents:_.page,...rr(t),schema:w,tableName:e,with:t.with}),{..._,page:In(_.page,t.select,t.with)}},async explain(e,t={}){const r=j(e,"explain");if(r)return r.explain(e,t);const a=w.tables[e];if(!a)throw new v("INTERNAL",`unknown table: ${e}`);const{statement:l}=await Kt(e,a,t,()=>{}),p=$e(y,`EXPLAIN QUERY PLAN ${l.text}`,...l.params).toArray();return{params:l.params,plan:p.map(d=>String(d.detail)),sql:l.text}},async get(e,t){T(e,"ctx.db.get(table, id)");const r=Y(t,e);if(!r){const a=be(e);return a?(M(e,t,!0),a.get(e,t)):(k(e),M(e,t,!0),null)}return ce(r,t),r.row},async lookupById(e,t){const r=Y(e,t);if(!r){for(const a of Gt(t))k(a),M(a,e,!0);return null}return ce(r,e),{row:r.row,tableName:r.tableName}},async groupBy(e,t){const r=j(e,"groupBy");if(r)return Te(e,t),r.groupBy(e,t);const a=w.tables[e];if(!a)throw new v("INTERNAL",`unknown table: ${e}`);q(e,G);const l=t.agg??{op:"count"};if(Ge(l.op),l.op!=="count"&&!l.field)throw new v("INTERNAL",`groupBy(${e}, { agg: { op: "${l.op}" } }): "field" is required for non-count reducers`);const p=Ce(a.softDeleteMode,void 0),d=Q(Q(t.baseWhere,t.where),p),f=await Fe(d,e,t.relationBaseWhere),m=f!==d;if(a.aggregateIndexes&&!t.baseWhere&&!m){const $=ro(a.aggregateIndexes,l.op,l.field,t.by,t.where),W=$===void 0?0:Object.keys($.partial).length,N=$?.index.by?.length??0;if($&&(W===0||W===N)){st(e,$.index);const V=lt(e,$.index.name),J=Object.keys($.partial),pe=[];if(J.length===($.index.by??[]).length&&J.length>0){const Pe=ft($.index.by??[],$.partial),Oe=H(y,u`SELECT ${je} AS value, ${wt} AS count FROM ${u.identifier(V)} WHERE ${He} = ${Pe}`).toArray();return Oe.length>0&&pe.push({key:{...$.partial},value:ut(l.op,Oe[0])}),pe}const Zn=H(y,u`SELECT ${He} AS key, ${je} AS value, ${wt} AS count FROM ${u.identifier(V)}`).toArray();for(const Pe of Zn){const Oe=no(JSON.parse(Pe.key));pe.push({key:Oe,value:ut(l.op,Pe)})}return pe}}for(const $ of[...t.by,l.field]){if($===void 0)continue;const W=$===l.field?`groupBy(${e}, { agg: { op: "${l.op}", field: "${$}" } })`:`groupBy(${e}, { by: [..."${$}"] })`;wn(a,$,W)}const b=Z(f,ge),_=t.by.map($=>u`${ye($)} AS ${u.identifier($)}`);if(l.op==="count")_.push(u`COUNT(*) AS value`);else{const{field:$}=l;if($===void 0)throw new v("INTERNAL",`groupBy(${e}, { agg: { op: "${l.op}" } }): "field" is required for non-count reducers`);_.push(u`${u.raw(Ge(l.op))}(${ye($)}) AS value`)}let D=u`SELECT ${u.join(_,u`, `)} FROM ${u.identifier(e)}`;b&&(D=u`${D} WHERE ${b}`),D=u`${D} GROUP BY ${u.join(t.by.map($=>ye($)),u`, `)}`;const S=H(y,D).toArray(),I=[];for(const $ of S){const W={};for(const V of t.by)W[V]=$o(a.shape[V],$[V]??null);const{value:N}=$;I.push({key:W,value:N==null?null:Number(N)})}return I},async insert(e,t,r){const a=j(e,"insert");if(a)return rt(a,e,t,r,!0);const l=w.tables[e];if(!l)throw new v("INTERNAL",`unknown table: ${e}`);const p=r?.allowExplicitId===!0,d=Ke(l,vt(l,t,he),{supplied:t,table:e,trusted:p});let f;r?.clientId!==void 0?(Ur(r.clientId),f=r.clientId):r?.allowExplicitId&&typeof d._id=="string"?(Rt(d._id),f=d._id):f=bt();const m=r?.allowExplicitId&&typeof d._creationTime=="number"?d._creationTime:Se(),b={...d,...z(e),_creationTime:m,_id:f};return te(e,"before","insert")&&await ne("before","insert",{doc:{...b},id:f,op:"insert",table:e}),p||O(e,b),Ae(e),Ie(e),_t(y,e,kr(e),[f,m,de(b)]),at(e,f,b),te(e,"after","insert")&&await ne("after","insert",{doc:b,id:f,op:"insert",table:e}),await ve({doc:b,id:f,op:"insert",table:e}),f},async insertManyUnsafe(e,t,r){if(Qe(t.length,r?.limit,"insertManyUnsafe"),t.length===0)return[];const a=j(e,"insert");if(a){Gr(w.tables[e],t,r?.allowExplicitId,he);for(const _ of t)ee(_);return Lt(a,e,t,r?.allowExplicitId)}const l=w.tables[e];if(!l)throw new v("INTERNAL",`unknown table: ${e}`);Ae(e),Ie(e);const p=[];for(let _=0;_<t.length;_+=Ne)p.push(z(e));const d=r?.allowExplicitId===!0?void 0:nr(l),f=t.map((_,D)=>{const S=vt(l,_,he),I=d===void 0?S:Ke(d,S,{supplied:_,table:e}),$=r?.allowExplicitId===!0&&typeof I._id=="string"?I._id:void 0;$!==void 0&&Rt($);const W=$??bt(),N=r?.allowExplicitId===!0&&typeof I._creationTime=="number"?I._creationTime:Se(),V={...I,...p[Math.floor(D/Ne)],_creationTime:N,_id:W};return{creationTime:N,document:V,id:W}});for(const _ of f)ee(_.document);const m=async _=>{for(const{document:D,id:S}of _)at(e,S,D);for(const{document:D,id:S}of _)await me({doc:D,id:S,op:"insert",table:e})};let b=0;try{for(let _=0;_<f.length;_+=Ne){const D=f.slice(_,_+Ne),S=u.join(D.map($=>u`(${$.id}, ${$.creationTime}, ${de($.document)})`),u`, `),I=Tn("sqlite",u`INSERT INTO ${u.identifier(e)} (id, _creationTime, ${u.identifier(oe)}) VALUES ${S}`);_t(y,e,I.sql,I.params),b=_+D.length}}catch(_){throw await Hn(e,f.slice(0,b)),_}return await m(f),f.map(_=>_.id)},async insertMany(e,t,r){Qe(t.length,r?.limit,"insertMany");const a=r?.skipDuplicates===!0,l=[],p=j(e,"insert");if(p){for(const f of t)ee(f);if(!a)return Lt(p,e,t,void 0)}const d=async f=>p?rt(p,e,f,void 0,!1):U.insert(e,f);for(const f of t)try{l.push(await d(f))}catch(m){if(a&&m instanceof le&&m.kind==="unique")l.push(null);else throw m}return l},normalizeId(e,t){return pn(w,e,t)},async patch(e,t,r,a){T(e,"ctx.db.patch(table, id, values)");const l=Y(t,e);if(!l){const $=be(e);if($){ee(r);try{await $.patch(e,t,r,a)}finally{se("update",e,t)}return}throw new v("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:d,tableName:f}=l,m=w.tables[f];if(!m)throw new v("INTERNAL",`unknown table: ${f}`);if(q(f,t),yn("patch",r),Mt(f,t,r,d)){o?.({fields:Object.keys(ze(r)),id:t,table:f});return}const b=xo(m,r,d),_={...d,...ze(b),...z(f),_id:t};yt(m,b,_,he);const D=new Set(Object.keys(b)),S=Ke(m,_,{only:D,patched:D,previous:()=>d,table:f,tolerateStoredNull:!0});Mo(a,d,S),te(f,"before","update")&&await ne("before","update",{doc:{...S},id:t,op:"update",previous:d,table:f}),O(f,S,d),Ae(f),Ie(f),Ve(y,f,an(f),[de(S),t,p]),qe(f,t,S,d),Be(f,t,S),We(f,d,S),we(f,t,d,S);const I=R(f,d,S);ue?.invalidate(f,t,I),_e(f,t,"update",S),x({indexKeys:I,key:t,op:"update",row:S,table:f}),te(f,"after","update")&&await ne("after","update",{doc:S,id:t,op:"update",previous:d,table:f}),await ve({doc:S,id:t,op:"update",table:f})},async patchIf(e,t,r){const a=j(e,"patchIf");if(a){if(a.patchIf===void 0)throw new v("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);ee(r.patch);let l;try{l=await a.patchIf(e,t,r)}catch(p){throw se("update",e,t),p}return l.applied&&se("update",e,t),l}if(!w.tables[e])throw new v("INTERNAL",`unknown table: ${e}`);for(let l=1;l<=gn;l+=1){const p=await Yn(e,t,r,l<gn,d=>U.patch(e,t,d,{verify:r.verify}));if(p!==void 0)return p}throw new le(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,r){T(e,"ctx.db.patchMany(table, patches)"),Qe(t.length,r?.limit,"patchMany");for(const a of t)await U.patch(e,a.id,a.patch);return{patched:t.length}},async patchWhere(e,t,r){const a=j(e,"patchWhere")??U,p=(await un(a,e,t.where,r?.limit,"patchWhere")).map(d=>({id:String(d._id),patch:t.patch}));if(U.patchMany===void 0)throw new v("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await U.patchMany(e,p,r),{patched:p.length}},async related(e,t){return Vo(U,B,e,t)},relationEdges:B,deleteRereadTables:C,inTransaction:fe,softDeleteFields:F,relationWrites:K,query(e){const t=j(e,"query");return t?(q(e,G),t.query(e)):Bn(y,w,e,ae,r=>{r?re(r):q(e,G)},r=>{s?.recordRead(r)})},async rank(e,t,r){const a=j(e,"rank");if(ae(e,t,"rank"),a)return q(e,G),a.rank(e,t,r);const l=w.tables[e];if(!l)throw new v("INTERNAL",`unknown table: ${e}`);const p=l.rankIndexes?.find(J=>J.name===t);if(!p)throw new v("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Ut(e,l,p),r.restrictsCounts)throw new ht(e);q(e,G),ct(e,p);const d=typeof r.row=="string"?r.row:r.row._id;if(!d)return null;const f=en(e,p.name),m=p.sortBy.map((J,pe)=>tn(pe)),b=m.map(J=>Le(J)).join(", "),_=H(y,u`SELECT ${u.identifier("__partition__")}, ${u.raw(b)} FROM ${u.identifier(f)} WHERE ${u.identifier("__id__")} = ${d}`).toArray(),[D]=_;if(D===void 0)return null;let S=D.__partition__;const I=Q(r.baseWhere,r.where);pt(I,w,e,"rank");const $=qo(p,I);if($){const J=Po(p.partitionBy??[],$);if(J!==S)return null;S=J}const W=m.map(J=>D[J]),{before:N,total:V}=En(y,f,m,p.sortBy,S,W,d);return{position:N+1,total:V}},async rankBefore(e,t,r){if(ie(e))throw new v("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const a=w.tables[e];if(!a)throw new v("INTERNAL",`unknown table: ${e}`);const l=a.rankIndexes?.find(m=>m.name===t);if(!l)throw new v("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(r.restrictsCounts)throw new ht(e);q(e,G),ct(e,l);const p=en(e,l.name),d=l.sortBy.map((m,b)=>tn(b)),f=l.sortBy.map((m,b)=>ke(r.sortValues[b]??null));return En(y,p,d,l.sortBy,r.partitionKey,f,r.rowId)},async rankPage(e,t,r={}){pt(Q(r.baseWhere,r.where),w,e,"rankPage");const a=j(e,"rankPage");if(ae(e,t,"rank"),a)return q(e,G),a.rankPage(e,t,r);const{continueCursor:l,hasMore:p,rows:d}=Vt(Ht,e,t,r);return{continueCursor:l,isDone:!p,page:d.map(f=>f.doc)}},async rankPageRows(e,t,r={}){pt(Q(r.baseWhere,r.where),w,e,"rankPage"),ae(e,t,"rank");const{directions:a,hasMore:l,rows:p}=Vt(Ht,e,t,r);return{directions:a,hasMore:l,rows:p}},async restore(e,t){T(e,"ctx.db.restore(table, id)");const r=Y(t,e);if(!r){const d=be(e);if(d?.restore){try{await d.restore(e,t)}finally{se("update",e,t)}return}throw new v("NOT_FOUND",`document not found: ${t}`)}const a=w.tables[r.tableName]?.softDeleteMode?.field;if(!a)throw new v("INTERNAL",`ctx.db.restore: table "${r.tableName}" is not a .softDelete() table`);const l=r.row[a]!==null&&r.row[a]!==void 0;await U.patch(e,t,{[a]:null});const p=l?Y(t,e)?.row:void 0;p&&(we(r.tableName,t,p,void 0),we(r.tableName,t,void 0,p))},async replace(e,t,r,a){T(e,"ctx.db.replace(table, id, document)");const l=Y(t,e);if(!l){const W=be(e);if(W){ee(r);try{await W.replace(e,t,r,a)}finally{se("update",e,t)}return}throw new v("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:d,tableName:f}=l,m=w.tables[f];if(!m)throw new v("INTERNAL",`unknown table: ${f}`);yn("replace",r);const b=a?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:void 0,_=typeof d._creationTime=="number"?d._creationTime:void 0,D=b??_??Se(),S={...r,...z(f),_creationTime:D,_id:t};yt(m,r,S,he);const I=a?.allowExplicitId===!0,$=Ke(m,S,{previous:()=>d,supplied:r,table:f,trusted:I});te(f,"before","update")&&await ne("before","update",{doc:{...$},id:t,op:"update",previous:d,table:f}),I||O(f,$,d),Ae(f),Ie(f),Ve(y,f,Lr(f),[D,de($),t,p]),qe(f,t,$,d),Be(f,t,$),We(f,d,$),we(f,t,d,$),ue?.invalidate(f,t,R(f,d,$)),_e(f,t,"update",$),x({indexKeys:R(f,d,$),key:t,op:"update",row:$,table:f}),te(f,"after","update")&&await ne("after","update",{doc:$,id:t,op:"update",previous:d,table:f}),await ve({doc:$,id:t,op:"update",table:f})},async wipeShard(e){const t=new Set(e?.exclude),r=e?.tables,a=Object.entries(w.tables).filter(([f,m])=>t.has(f)||r!==void 0&&!r.includes(f)?!1:m.shardMode?.kind!=="global").map(([f])=>f);if(r!==void 0){for(const f of r)if(!w.tables[f])throw new v("INTERNAL",`wipeShard: unknown table: ${f}`)}const l={};let p=0;const{deleteAll:d}=U;if(d===void 0)throw new v("INTERNAL","wipeShard: this writer has no deleteAll");for(const f of a){const m=await d(f,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});l[f]=m.deleted,p+=m.deleted}return{deleted:p,tables:l}}},Xn={db:U,scheduler:Ct};return n.enforceRls===!0?ar(U,w,(e,t)=>Y(e,t)?.tableName,B):U};export{Es as CDC_LOG_TABLE,Us as IDEMPOTENCY_TABLE,ei as NotUniqueError,Bs as advanceClientWatermark,ms as applyCdcChanges,yn as assertNoExplicitUndefined,Rt as assertStorableRowId,Ur as assertValidClientId,ps as backfillAggregateIndexes,gs as backfillRankIndexes,ys as backfillSearchIndexes,vs as bumpCdcEpoch,Ss as cdcCanVouchFor,Rs as cdcForkedError,_s as cdcSeqLeavingRows,Ts as cdcTouchesTables,As as cdcTrimmedError,Is as compactCdcDocs,Ri as createShardCtxDb,bs as cursorBelowRetainedFloor,wi as meterReadBytes,qs as migrateClientWatermark,Cs as minCdcReplayableSeq,xs as minCdcSeq,pn as normalizeIdStructurally,Ms as readCdcChangeKeys,Ds as readCdcChanges,ks as readCdcCursor,Ls as readCdcEpoch,Ps as readClientWatermark,Gs as readIdempotent,Ns as runShardMigrations,zs as selectShapeMembers,Vs as selectShapeRows,ze as stripReservedPatchFields,Fs as trimCdcChanges,js as trimIdempotent,Hs as writeIdempotent};
@@ -1,4 +1,4 @@
1
- import{runSql as o,orNull as a,decodeJsonColumn as _}from"./runDrizzle-RC09zZrh.mjs";const s="__lunora_queue_messages",n=500,E=128*1024,T="… [truncated by the dev queue catcher]",c="[unserializable message body]",R=e=>{if(e===void 0)return"null";try{const r=JSON.stringify(e);return r.length>E?JSON.stringify(`${r.slice(0,E)}${T}`):r}catch{return JSON.stringify(c)}},g=e=>typeof e=="string"&&(e===c||e.endsWith(T)),u=e=>{o(e,`CREATE TABLE IF NOT EXISTS "${s}" (
1
+ import{orNull as a,decodeJsonColumn as _}from"./runDrizzle-DAtZbzBn.mjs";import o from"./runSql-BBRXi81G.mjs";const s="__lunora_queue_messages",n=500,E=128*1024,T="… [truncated by the dev queue catcher]",c="[unserializable message body]",R=e=>{if(e===void 0)return"null";try{const r=JSON.stringify(e);return r.length>E?JSON.stringify(`${r.slice(0,E)}${T}`):r}catch{return JSON.stringify(c)}},g=e=>typeof e=="string"&&(e===c||e.endsWith(T)),u=e=>{o(e,`CREATE TABLE IF NOT EXISTS "${s}" (
2
2
  id TEXT PRIMARY KEY,
3
3
  captured_at INTEGER NOT NULL,
4
4
  message_id TEXT NOT NULL,
@@ -10,8 +10,8 @@ import{runSql as o,orNull as a,decodeJsonColumn as _}from"./runDrizzle-RC09zZrh.
10
10
  error TEXT,
11
11
  dead_lettered INTEGER NOT NULL,
12
12
  message_ts INTEGER NOT NULL
13
- )`)},p=(e,r,d)=>{u(e);for(const t of r)o(e,`INSERT INTO "${s}" (id, captured_at, message_id, queue, export_name, body, attempts, outcome, error, dead_lettered, message_ts)
13
+ )`)},y=(e,r,d)=>{u(e);for(const t of r)o(e,`INSERT INTO "${s}" (id, captured_at, message_id, queue, export_name, body, attempts, outcome, error, dead_lettered, message_ts)
14
14
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,crypto.randomUUID(),d,t.messageId,t.queue,a(t.exportName),R(t.body),t.attempts,t.outcome,a(t.error),t.deadLettered===!0?1:0,t.timestamp);return o(e,`DELETE FROM "${s}"
15
15
  WHERE id NOT IN (
16
16
  SELECT id FROM "${s}" ORDER BY captured_at DESC, id DESC LIMIT ?
17
- )`,n),{recorded:r.length}},i=e=>({attempts:e.attempts,body:_(e.body),capturedAt:e.captured_at,deadLettered:e.dead_lettered===1,error:e.error??void 0,exportName:e.export_name??void 0,id:e.id,messageId:e.message_id,outcome:e.outcome,queue:e.queue,timestamp:e.message_ts}),y=(e,r={})=>{u(e);const d=Math.min(Math.max(r.limit??100,1),n),t=typeof r.queue=="string"&&r.queue.length>0?r.queue:void 0,m=t===void 0?"":"WHERE queue = ?",N=t===void 0?[d]:[t,d];return{entries:o(e,`SELECT * FROM "${s}" ${m} ORDER BY captured_at DESC, id DESC LIMIT ?`,...N).toArray().map(L=>i(L))}},S=(e,r)=>{u(e);const t=o(e,`SELECT * FROM "${s}" WHERE id = ? LIMIT 1`,r).toArray()[0];return t===void 0?void 0:i(t)},U=e=>(u(e),o(e,`DELETE FROM "${s}"`),{cleared:!0});export{E as MAX_BODY_CHARS,n as QUEUE_RETENTION,s as QUEUE_TABLE,U as clearQueueMessages,u as ensureQueueTable,g as isLossyBody,S as readQueueMessageById,y as readQueueMessages,p as recordQueueMessages};
17
+ )`,n),{recorded:r.length}},i=e=>({attempts:e.attempts,body:_(e.body),capturedAt:e.captured_at,deadLettered:e.dead_lettered===1,error:e.error??void 0,exportName:e.export_name??void 0,id:e.id,messageId:e.message_id,outcome:e.outcome,queue:e.queue,timestamp:e.message_ts}),S=(e,r={})=>{u(e);const d=Math.min(Math.max(r.limit??100,1),n),t=typeof r.queue=="string"&&r.queue.length>0?r.queue:void 0,m=t===void 0?"":"WHERE queue = ?",N=t===void 0?[d]:[t,d];return{entries:o(e,`SELECT * FROM "${s}" ${m} ORDER BY captured_at DESC, id DESC LIMIT ?`,...N).toArray().map(L=>i(L))}},U=(e,r)=>{u(e);const t=o(e,`SELECT * FROM "${s}" WHERE id = ? LIMIT 1`,r).toArray()[0];return t===void 0?void 0:i(t)},M=e=>(u(e),o(e,`DELETE FROM "${s}"`),{cleared:!0});export{E as MAX_BODY_CHARS,n as QUEUE_RETENTION,s as QUEUE_TABLE,M as clearQueueMessages,u as ensureQueueTable,g as isLossyBody,U as readQueueMessageById,S as readQueueMessages,y as recordQueueMessages};
@@ -0,0 +1 @@
1
+ import{matchesStaticWhere as a}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{compareStrings as l}from"./aggregateTableName-B_CtIQCS.mjs";import{serializeSqlValue as f}from"./serializeSqlValue-DeoBMpZ2.mjs";const c=Symbol("not-resolvable"),y=r=>{if(r!==null&&typeof r=="object"&&!Array.isArray(r)){const t=Object.keys(r);return t.length===1&&t[0]==="eq"?r.eq:c}return r},m=(r,t)=>{if(r.length===0)return"";const o={};for(const n of r.toSorted(l))o[n]=t[n]??null;return JSON.stringify(o)},k="__id__",d=r=>`__sort_k${String(r)}__`,h=(r,t)=>{const o=r.partitionBy??[],n=t??{};for(const e of Object.keys(n))if(e==="AND"||e==="OR"||e==="NOT")return;const s={};for(const e of o)if(e in n){const i=y(n[e]);if(i===c)return;s[e]=i}else if(r.where&&e in r.where)s[e]=r.where[e];else return;return s},S=(r,t)=>`${r}__rank_${t}`,K=(r,t)=>({partitionKey:m(r.partitionBy??[],t),rowId:t._id,sortValues:r.sortBy.map(o=>f(t[o.field]??null))}),N=a;export{k as RANK_TIEBREAK,m as encodePartitionKey,N as matchesRankStaticWhere,K as rankKeyFromDoc,S as rankTableName,h as resolveRankPartition,d as sortColumnName};
@@ -1,4 +1,4 @@
1
- import{sql as t}from"drizzle-orm";import{runDrizzle as o}from"./runDrizzle-RC09zZrh.mjs";const a="__reactor_state",c=[["runs","runs INTEGER NOT NULL DEFAULT 0"],["suppressed","suppressed INTEGER NOT NULL DEFAULT 0"],["errors","errors INTEGER NOT NULL DEFAULT 0"],["last_ran_at","last_ran_at INTEGER NOT NULL DEFAULT 0"],["last_error","last_error TEXT"]],O=r=>{o(r,t`CREATE TABLE IF NOT EXISTS ${t.identifier(a)} (
1
+ import{sql as t}from"drizzle-orm";import{runDrizzle as o}from"./runDrizzle-DAtZbzBn.mjs";const a="__reactor_state",c=[["runs","runs INTEGER NOT NULL DEFAULT 0"],["suppressed","suppressed INTEGER NOT NULL DEFAULT 0"],["errors","errors INTEGER NOT NULL DEFAULT 0"],["last_ran_at","last_ran_at INTEGER NOT NULL DEFAULT 0"],["last_error","last_error TEXT"]],O=r=>{o(r,t`CREATE TABLE IF NOT EXISTS ${t.identifier(a)} (
2
2
  path TEXT PRIMARY KEY,
3
3
  digest TEXT NOT NULL,
4
4
  tables TEXT NOT NULL,
@@ -1,4 +1,4 @@
1
- import{LunoraError as $}from"@lunora/errors";import{isPlainObject as S}from"@lunora/wire";import{sql as n}from"drizzle-orm";import{runDrizzle as d}from"./runDrizzle-RC09zZrh.mjs";const a="__schedule_outbox",h=t=>{d(t,n`CREATE TABLE IF NOT EXISTS ${n.identifier(a)} (
1
+ import{LunoraError as $}from"@lunora/errors";import{isPlainObject as S}from"@lunora/wire";import{sql as n}from"drizzle-orm";import{runDrizzle as d}from"./runDrizzle-DAtZbzBn.mjs";const a="__schedule_outbox",h=t=>{d(t,n`CREATE TABLE IF NOT EXISTS ${n.identifier(a)} (
2
2
  id TEXT PRIMARY KEY,
3
3
  envelope_json TEXT NOT NULL,
4
4
  attempts INTEGER NOT NULL,
@@ -1,4 +1,4 @@
1
- import{quoteIdentifier as i}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as n}from"./runDrizzle-RC09zZrh.mjs";const p="__lunora_schema_history",c=50,e=i(p),E=t=>({appliedAt:typeof t.applied_at=="number"?t.applied_at:0,hash:typeof t.hash=="string"?t.hash:"",seq:typeof t.seq=="number"?t.seq:0}),a=t=>{n(t,`CREATE TABLE IF NOT EXISTS ${e} (
1
+ import{quoteIdentifier as i}from"./quoteIdentifier-CObIFRhb.mjs";import n from"./runSql-BBRXi81G.mjs";const p="__lunora_schema_history",c=50,e=i(p),E=t=>({appliedAt:typeof t.applied_at=="number"?t.applied_at:0,hash:typeof t.hash=="string"?t.hash:"",seq:typeof t.seq=="number"?t.seq:0}),a=t=>{n(t,`CREATE TABLE IF NOT EXISTS ${e} (
2
2
  hash TEXT PRIMARY KEY,
3
3
  seq INTEGER NOT NULL,
4
4
  snapshot_json TEXT NOT NULL,
@@ -1 +1 @@
1
- import{S as t,m as S,b as c,r as i,a as l,w as s}from"./ctx-db-search-state-CPKPy8N6.mjs";import"./runDrizzle-RC09zZrh.mjs";export{t as SEARCH_STATE_TABLE,S as migrateSearchState,c as readBackfillState,i as readSearchBackfillState,l as readSearchIndexCoverage,s as writeSearchBackfillState};
1
+ import{S as t,m as S,b as c,r as i,a as l,w as s}from"./ctx-db-search-state-Bv_NxB1g.mjs";import"./runDrizzle-DAtZbzBn.mjs";export{t as SEARCH_STATE_TABLE,S as migrateSearchState,c as readBackfillState,i as readSearchBackfillState,l as readSearchIndexCoverage,s as writeSearchBackfillState};
@@ -1,4 +1,4 @@
1
- import{sql as o}from"drizzle-orm";import{runDrizzle as s}from"./runDrizzle-RC09zZrh.mjs";import{WORKERD_SQLITE_LIMITS as d}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";const c="__shape_poke_cursor",L=r=>{s(r,o`CREATE TABLE IF NOT EXISTS ${o.identifier(c)} (
1
+ import{sql as o}from"drizzle-orm";import{runDrizzle as s}from"./runDrizzle-DAtZbzBn.mjs";import{WORKERD_SQLITE_LIMITS as d}from"./WORKERD_SQLITE_LIMITS-C9dUlw3o.mjs";const c="__shape_poke_cursor",L=r=>{s(r,o`CREATE TABLE IF NOT EXISTS ${o.identifier(c)} (
2
2
  connection_id TEXT NOT NULL,
3
3
  sub_id TEXT NOT NULL,
4
4
  cursor INTEGER NOT NULL,
@@ -0,0 +1 @@
1
+ import{isLunoraError as S}from"@lunora/errors";import{l as R,b as L}from"./ctx-db-search-state-Bv_NxB1g.mjs";import{sql as e}from"drizzle-orm";import{readKeysetPage as _}from"./backfillAggregateIndexes-BkCo8Dpf.mjs";import{runDrizzle as p}from"./runDrizzle-DAtZbzBn.mjs";import{a as k}from"./do-sql-DT8JBpG8.mjs";const u="__lunora_vector_backfill",m=50,w=20,h=20,N=3,O=i=>{p(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(u)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("cursor")} TEXT, ${e.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${e.identifier("profile")} TEXT, ${e.identifier("strikes")} INTEGER NOT NULL DEFAULT 0)`);try{p(i,e`ALTER TABLE ${e.identifier(u)} ADD COLUMN ${e.identifier("strikes")} INTEGER NOT NULL DEFAULT 0`)}catch{}},C=(i,o)=>{const[s]=p(i,e`SELECT ${e.identifier("strikes")} FROM ${e.identifier(u)} WHERE ${e.identifier("companion")} = ${o}`).toArray();return s?.strikes??0},$=(i,o,s,d,t,r=0)=>{const n=s??null;p(i,e`INSERT INTO ${e.identifier(u)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("strikes")}) VALUES (${o}, ${n}, ${d?1:0}, ${t}, ${r}) ON CONFLICT (${e.identifier("companion")}) DO UPDATE SET ${e.identifier("cursor")} = excluded.${e.identifier("cursor")}, ${e.identifier("done")} = excluded.${e.identifier("done")}, ${e.identifier("profile")} = excluded.${e.identifier("profile")}, ${e.identifier("strikes")} = excluded.${e.identifier("strikes")}`)},A=(i,o,s)=>{const d=_(i,o,s,m+1),t={documents:[],lastId:s,more:d.length>m,unparseable:[]};for(const r of d.slice(0,m)){if(typeof r.id!="string")continue;t.lastId=r.id;const n=k(r);n?t.documents.push({doc:n,id:t.lastId}):t.unparseable.push(t.lastId)}return t},D=(i,o,s,d,t)=>{const r=t instanceof Error?t.message:String(t),n=L(i,u,o),a=n.profile===d&&n.cursor===s?C(i,o):0;if(S(t)&&t.code==="SERVICE_UNAVAILABLE")return a>0&&$(i,o,s,!1,d,0),{error:r};const f=a+1;if(f<N)return $(i,o,s,!1,d,f),{error:r};const c=A(i,o,s),l=[...c.documents.map(E=>E.id),...c.unparseable];return console.warn(`[@lunora/shard-engine] vector backfill: a page of "${o}" failed ${String(f)} times in a row; its ${String(l.length)} row(s) are recorded as failed:`,t),{failedIds:l,page:c}},F=async(i,o,s,d,t)=>{const{profile:r,table:n}=o;try{const{failures:a,page:f}=await t(()=>A(i,n,s),async c=>({failures:await d(n,c.documents),page:c}));return a.length>0&&console.warn(`[@lunora/shard-engine] vector backfill: ${String(a.length)} row(s) of "${n}" could not be indexed:`,a),{failedIds:[...f.unparseable,...a.map(c=>c.id)],page:f}}catch(a){return D(i,n,s,r,a)}},y=async(i,o,s,d)=>{if(O(i),d.restart===!0)for(const{profile:n,table:a}of o)$(i,a,void 0,!1,n);const t=Math.min(d.maxPages??1,w),r={done:!1,failed:0,failedIds:[],pages:0,rows:0};for(const{profile:n,table:a}of o){const f=R(L(i,u,a),n);let{cursor:c}=f,l=f.finished;for(;!l;){if(r.pages>=t)return r;const E=await F(i,{profile:n,table:a},c,s,d.ordered);if("error"in E)return{...r,error:E.error};const{failedIds:g,page:T}=E,I=T.documents.length+T.unparseable.length;r.pages+=I>0?1:0,r.rows+=I,r.failed+=g.length,r.failedIds=[...r.failedIds,...g].slice(0,h),c=T.lastId,l=!T.more,$(i,a,c,l,n)}}return{...r,done:!0}};export{w as VECTOR_BACKFILL_MAX_PAGES,m as VECTOR_BACKFILL_PAGE_ROWS,y as backfillVectorIndexes};
@@ -0,0 +1 @@
1
+ const e={boundParams:100,compoundSelect:5,likePattern:50,sqlTextLength:1e5};export{e as WORKERD_SQLITE_LIMITS};
@@ -1,4 +1,4 @@
1
- import{ADMIN_TOKEN_TABLE as n}from"./ADMIN_TOKEN_TABLE-DfQ5osdI.mjs";import{c as T}from"./constant-time-equal-BRh9yUCr.mjs";import{runSql as r}from"./runDrizzle-RC09zZrh.mjs";const u=["migrations"],A=e=>u.some(t=>t===e),m=6e4,d=new WeakSet,o=e=>{if(r(e,`CREATE TABLE IF NOT EXISTS "${n}" (
1
+ import{ADMIN_TOKEN_TABLE as n}from"./ADMIN_TOKEN_TABLE-DfQ5osdI.mjs";import{c as T}from"./constant-time-equal-BRh9yUCr.mjs";import r from"./runSql-BBRXi81G.mjs";const u=["migrations"],A=e=>u.some(t=>t===e),m=6e4,d=new WeakSet,o=e=>{if(r(e,`CREATE TABLE IF NOT EXISTS "${n}" (
2
2
  name TEXT PRIMARY KEY,
3
3
  digest TEXT NOT NULL,
4
4
  created_at REAL NOT NULL,
@@ -1,4 +1,4 @@
1
- import{sql as t}from"drizzle-orm";import{runDrizzle as o}from"./runDrizzle-RC09zZrh.mjs";const E="__stream_runs",i="__stream_chunks",N=r=>{o(r,t`CREATE TABLE IF NOT EXISTS ${t.identifier(E)} (
1
+ import{sql as t}from"drizzle-orm";import{runDrizzle as o}from"./runDrizzle-DAtZbzBn.mjs";const E="__stream_runs",i="__stream_chunks",N=r=>{o(r,t`CREATE TABLE IF NOT EXISTS ${t.identifier(E)} (
2
2
  run_key TEXT PRIMARY KEY,
3
3
  status TEXT NOT NULL,
4
4
  last_seq INTEGER NOT NULL DEFAULT 0,
@@ -1,2 +1,2 @@
1
- import{LunoraError as S}from"@lunora/errors";import{t as F}from"./do-sql-Cf2rnuLV.mjs";import{applySelect as Y}from"./CURSOR_PREFIX-rOdoinP8.mjs";const z=Symbol.for("lunora.relations.fanOutBudget"),me=e=>({fanOutBudget:e[z],relationBaseWhere:e.relationBaseWhere,relationMask:e.relationMask}),W=(e,t)=>t.select?Y(e,t.select,t.with):e,be=async(e,t,n,o,s)=>{const i=await Promise.all(o.map(async c=>{const f=s?{AND:[{[n]:c},s]}:{[n]:c};return[c,await e(t,f)]}));return new Map(i)},ee=32,E=1e4,te=(e,t,n)=>{const o=new Map;for(const s of e)for(const i of n(s)){const c=i[t],f=o.get(c);f?f.push(i):o.set(c,[i])}return o},x=(e,t)=>({...e,[z]:t}),ne=(e,t)=>{const n=new Map;for(const[s,i]of e)for(const c of i){const f=n.get(c);f?f.push(s):n.set(c,[s])}const o=new Map;for(const s of t)for(const i of n.get(s._id)??[]){const c=o.get(i);c?c.push(s):o.set(i,[s])}return o},j=(e,t)=>{const n=new Set;for(const o of e){const s=o[t];s!=null&&n.add(s)}return[...n]},ve=async e=>{const{groupedCounter:t,fanOutBudget:n,fetcher:o,parents:s,relationBaseWhere:i,relationMask:c,schema:f,tableName:h,with:m}=e,g=n??{remaining:ee},b=(l,r)=>c?.(l,r)??r;if(s.length===0)return;const A=f.tables[h];if(!A)throw new S("INTERNAL",`unknown table: ${h}`);const $=A.relationMap??{},G=(l,r)=>{const a=d=>f.tables[d]?.shardMode?.kind??"root";return a(l)===a(r)&&a(l)!=="shardBy"},R=l=>{const r=$[l];if(!r)throw new S("INTERNAL",`unknown relation "${l}" on table "${h}"`);return r},X=async(l,r,a)=>{const d=j(s,r.field);if(d.length===0){for(const p of s)p[l]=null;return}const{page:u}=await o(r.table,x({baseWhere:i?.(r.table),relationBaseWhere:i,relationMask:c,where:{[r.references]:{in:d}},with:a.with},g)),w=new Map;for(const p of b(r.table,u))w.set(p[r.references],p);for(const p of s){const O=w.get(p[r.field]);p[l]=O?W([O],a)[0]??null:null}},_=async(l,r,a,d)=>{const{page:u}=await o(l,x({baseWhere:i?.(l),limit:d,orderBy:r.orderBy,relationBaseWhere:i,relationMask:c,where:r.where?{AND:[r.where,a]}:a,with:r.with},g));return u},T=(l,r,a,d,u)=>{for(const w of s){const p=u.get(w[d])??[];w[l]=W(a===void 0?p:p.slice(0,a),r)}},q=async(l,r,a)=>{const d=j(s,r.references);if(d.length===0){for(const y of s)y[l]=[];return}const u=typeof a.limit=="number"?Math.max(0,Math.floor(a.limit)):void 0,w=(y,k)=>_(r.table,a,y,k);if(u===0){for(const y of s)y[l]=[];return}const p=u!==void 0&&d.length<=g.remaining;p&&(g.remaining-=d.length);const O=p?await Promise.all(d.map(async y=>w({[r.field]:y},u))):[await w({[r.field]:{in:d}},void 0)],v=te(O,r.field,y=>b(r.table,y));T(l,a,u,r.references,v)},I=async l=>{const{from:r,table:a,to:d}=l.through,u=new Map,w=j(s,"_id");if(w.length===0)return u;const p=await _(a,{},{[r]:{in:w}},E+1);if(p.length>E)throw new S("INTERNAL",`loading "${h}" relations through "${a}" read more than ${String(E)} join rows for one page; load fewer ${h} rows at a time`);for(const O of b(a,p)){const v=O[r],y=O[d];if(v==null||y===null||y===void 0)continue;const k=u.get(v);k?k.add(y):u.set(v,new Set([y]))}return u},K=async(l,r,a)=>{const d=typeof a.limit=="number"?Math.max(0,Math.floor(a.limit)):void 0,u=d===0?new Map:await I(r),w=(O,v)=>_(r.table,a,{_id:{in:[...O]}},v);let p=new Map;if(u.size>0&&d!==void 0&&u.size<=g.remaining){g.remaining-=u.size;const O=[...u.keys()],v=await Promise.all([...u.values()].map(async y=>w(y,d)));p=new Map(O.map((y,k)=>[y,b(r.table,v[k]??[])]))}else if(u.size>0){const O=new Set([...u.values()].flatMap(v=>[...v]));p=ne(u,b(r.table,await w(O,void 0)))}T(l,a,d,"_id",p)},Z=async(l,r)=>{const a=[...r];if(a.length===0)return new Set;if(G(h,l)){const u=await t(l,"_id",a,i?.(l),i);return new Set(a.filter(w=>(u.get(w)??0)>0))}const d=await _(l,{},{_id:{in:a}},void 0);return new Set(d.map(u=>u._id))},J=async(l,r)=>{const a=await I(r),d=await Z(r.table,new Set([...a.values()].flatMap(u=>[...u])));for(const u of s){const w=u._count??{};w[l]=[...a.get(u._id)??[]].filter(p=>d.has(p)).length,u._count=w}},Q=async l=>{for(const r of Object.keys(l)){const a=R(r);if(a.through!==void 0){await J(r,a);continue}const[d,u]=a.kind==="many"?[a.field,a.references]:[a.references,a.field],w=i?.(a.table),p=j(s,u),O=p.length===0?new Map:await t(a.table,d,p,w,i);for(const v of s){const y=v._count??{},k=v[u];y[r]=k==null?0:O.get(k)??0,v._count=y}}};for(const[l,r]of Object.entries(m)){if(r===void 0||r===!1)continue;if(l==="_count"){await Q(r);continue}const a=R(l),d=r===!0?{}:r;a.through===void 0?await(a.kind==="one"?X(l,a,d):q(l,a,d)):await K(l,a,d)}},D=1e4,U=500,oe=async(e,t,n,o,s)=>{const i=new Set;let c=s;for(;;){const f=c!==void 0,h=c??await e();let m=!1;c=void 0;for(const g of h){const b=g._id;if(!(typeof b!="string"||i.has(b))){if(i.add(b),m=!0,i.size>D)throw n();await t(b)}}if(!f){if(h.length<U)return;if(!m)throw new S("INTERNAL",o)}}},H=(e,t,n)=>new S("CASCADE_LIMIT",`cannot delete "${e}" row: more than ${String(D)} ${t} rows reference it (onDelete: ${n}) — delete or re-point them in batches first`,{status:400}),se=async(e,t,n,o)=>{const{deletedId:s,deletedReference:i,findHolders:c,onRestrict:f,tableName:h}=e,m=n.references==="_id"?s:i(n.references);if(m==null)return;const{field:g}=n,b=`"${t}.${g}"`,A=await c(t,g,m,{limit:o==="restrict"?1:D+1,select:["_id"]});if(A.length!==0){if(o==="restrict")return f(`cannot delete "${h}" row: ${b} still references it`);if(A.length>D)throw H(h,b,o);return{action:o,field:g,holderTable:t,label:b,probe:A,referencedValue:m}}},re=async(e,t,n)=>{const{findHolders:o,onCascade:s,onSetNull:i,tableName:c}=e,{action:f,field:h,holderTable:m,label:g,probe:b,referencedValue:A}=t;await oe(()=>o(m,h,A,{limit:U}),$=>f==="cascade"?s(m,$):i(m,$,h),()=>H(c,g,f),`onDelete on "${c}" made no progress: ${g} rows still match after being processed`,n?b:void 0)},Oe=async e=>{const{schema:t,tableName:n}=e;if(!t.tables[n])throw new S("INTERNAL",`unknown table: ${n}`);const o=[];for(const[s,i]of Object.entries(t.tables)){const c=i.relationMap;if(c)for(const f of Object.values(c)){if(f.kind!=="one"||f.table!==n||!f.onDelete)continue;const h=await se(e,s,f,f.onDelete);h&&o.push(h)}}for(const[s,i]of o.entries())await re(e,i,s===0)},L=new WeakMap,B=e=>{const t=L.get(e);if(t!==void 0)return t;const n=e._meta,o=[n?.inner,n?.keyValidator,n?.valueValidator,...n?.members??[],...Object.values(n?.shape??{})],s=e.kind==="from"||o.some(i=>i!==void 0&&B(i));return L.set(e,s),s},C=e=>{const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},P=e=>e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):void 0,V=(e,t)=>{if(Object.is(e,t))return!0;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();const n=P(e),o=P(t);if(n!==void 0||o!==void 0)return n!==void 0&&o!==void 0&&Object.getPrototypeOf(e)===Object.getPrototypeOf(t)&&n.length===o.length&&n.every((f,h)=>f===o[h]);if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((f,h)=>V(f,t[h]));if(typeof e!="object"||typeof t!="object"||e===null||t===null||!C(e)||!C(t))return!1;const s=e,i=t,c=Object.keys(s);return c.length===Object.keys(i).length&&c.every(f=>f in i&&V(s[f],i[f]))},N=new WeakMap,Ae=e=>{if(N.has(e))return N.get(e);const t=Object.fromEntries(Object.entries(e.shape).filter(([,o])=>B(o))),n=Object.keys(t).length>0?{...e,shape:t}:void 0;return N.set(e,n),n},ae=e=>{let t;return(n,o)=>e===void 0?!1:(t??=e()??{},n in t&&V(o,t[n]))},ie=(e,t)=>{const n=new Set(Object.keys(t).filter(o=>t[o]!==void 0));for(const[o,s]of F(e))s.serverDefault&&n.delete(o);return n},ce=(e,t,n,o,s)=>n.trusted===!0||o!==void 0&&!o.has(e)||s(e,t),M=e=>typeof e!="object"||e===null?e:e instanceof Date?new Date(e):e instanceof ArrayBuffer||ArrayBuffer.isView(e)?structuredClone(e):Array.isArray(e)?e.map(t=>M(t)):e instanceof Map?new Map([...e].map(([t,n])=>[M(t),M(n)])):e instanceof Set?new Set([...e].map(t=>M(t))):C(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,M(n)])):e,ke=(e,t,n)=>{const o={...t};for(const[s,i]of F(e)){if(i.serverDefault){o[s]=i.serverDefault({auth:n});continue}if(o[s]===void 0){if(i.defaultFn)o[s]=i.defaultFn();else if("defaultValue"in i){const{defaultValue:c}=i;o[s]=M(c)}}}return o},fe=e=>e.map((t,n)=>typeof t=="number"?`[${String(t)}]`:n===0?t:`.${t}`).join(""),le=(e,t,n,o)=>o.patched===void 0?"":o.patched.has(e)?n?" (set by the column's server default, which replaces what this patch sent)":" (set by this patch)":Object.is(o.previous?.()?.[e],t)?" (a stored value this patch does not set: the row already holds it, and every patch of the row fails until it is fixed)":" (not set by this patch: an update hook assigned it)",ue=e=>e.message.startsWith("object has ")?"object":e.received.startsWith("object")?e.received:e.received.split(" ")[0]??e.received,de=e=>e instanceof Error&&e.code==="VALIDATION_ERROR"&&Array.isArray(e.path)&&typeof e.expected=="string"&&typeof e.received=="string",he=(e,t,n)=>{const{field:o,serverDefault:s,value:i}=t,c=[o,...e.path],f=`${n.table===void 0?"":`${n.table}.`}${fe(c)}`,h=e.message.startsWith(`Expected ${e.expected} at `)&&e.message.endsWith(`, received ${e.received}`),m=ue(e),g=h?`expected ${e.expected}, received ${m}`:e.message,b=e.constructor,A=new b(`${f}: ${g}${le(o,i,s,n)}`,{expected:e.expected,path:c,received:m}),$=e.stack?.indexOf(`
1
+ import{LunoraError as S}from"@lunora/errors";import{t as F}from"./do-sql-DT8JBpG8.mjs";import{applySelect as Y}from"./CURSOR_PREFIX-rOdoinP8.mjs";const z=Symbol.for("lunora.relations.fanOutBudget"),me=e=>({fanOutBudget:e[z],relationBaseWhere:e.relationBaseWhere,relationMask:e.relationMask}),W=(e,t)=>t.select?Y(e,t.select,t.with):e,be=async(e,t,n,o,s)=>{const i=await Promise.all(o.map(async c=>{const f=s?{AND:[{[n]:c},s]}:{[n]:c};return[c,await e(t,f)]}));return new Map(i)},ee=32,E=1e4,te=(e,t,n)=>{const o=new Map;for(const s of e)for(const i of n(s)){const c=i[t],f=o.get(c);f?f.push(i):o.set(c,[i])}return o},x=(e,t)=>({...e,[z]:t}),ne=(e,t)=>{const n=new Map;for(const[s,i]of e)for(const c of i){const f=n.get(c);f?f.push(s):n.set(c,[s])}const o=new Map;for(const s of t)for(const i of n.get(s._id)??[]){const c=o.get(i);c?c.push(s):o.set(i,[s])}return o},j=(e,t)=>{const n=new Set;for(const o of e){const s=o[t];s!=null&&n.add(s)}return[...n]},ve=async e=>{const{groupedCounter:t,fanOutBudget:n,fetcher:o,parents:s,relationBaseWhere:i,relationMask:c,schema:f,tableName:h,with:m}=e,g=n??{remaining:ee},b=(l,r)=>c?.(l,r)??r;if(s.length===0)return;const A=f.tables[h];if(!A)throw new S("INTERNAL",`unknown table: ${h}`);const $=A.relationMap??{},G=(l,r)=>{const a=d=>f.tables[d]?.shardMode?.kind??"root";return a(l)===a(r)&&a(l)!=="shardBy"},R=l=>{const r=$[l];if(!r)throw new S("INTERNAL",`unknown relation "${l}" on table "${h}"`);return r},X=async(l,r,a)=>{const d=j(s,r.field);if(d.length===0){for(const p of s)p[l]=null;return}const{page:u}=await o(r.table,x({baseWhere:i?.(r.table),relationBaseWhere:i,relationMask:c,where:{[r.references]:{in:d}},with:a.with},g)),w=new Map;for(const p of b(r.table,u))w.set(p[r.references],p);for(const p of s){const O=w.get(p[r.field]);p[l]=O?W([O],a)[0]??null:null}},_=async(l,r,a,d)=>{const{page:u}=await o(l,x({baseWhere:i?.(l),limit:d,orderBy:r.orderBy,relationBaseWhere:i,relationMask:c,where:r.where?{AND:[r.where,a]}:a,with:r.with},g));return u},T=(l,r,a,d,u)=>{for(const w of s){const p=u.get(w[d])??[];w[l]=W(a===void 0?p:p.slice(0,a),r)}},q=async(l,r,a)=>{const d=j(s,r.references);if(d.length===0){for(const y of s)y[l]=[];return}const u=typeof a.limit=="number"?Math.max(0,Math.floor(a.limit)):void 0,w=(y,k)=>_(r.table,a,y,k);if(u===0){for(const y of s)y[l]=[];return}const p=u!==void 0&&d.length<=g.remaining;p&&(g.remaining-=d.length);const O=p?await Promise.all(d.map(async y=>w({[r.field]:y},u))):[await w({[r.field]:{in:d}},void 0)],v=te(O,r.field,y=>b(r.table,y));T(l,a,u,r.references,v)},I=async l=>{const{from:r,table:a,to:d}=l.through,u=new Map,w=j(s,"_id");if(w.length===0)return u;const p=await _(a,{},{[r]:{in:w}},E+1);if(p.length>E)throw new S("INTERNAL",`loading "${h}" relations through "${a}" read more than ${String(E)} join rows for one page; load fewer ${h} rows at a time`);for(const O of b(a,p)){const v=O[r],y=O[d];if(v==null||y===null||y===void 0)continue;const k=u.get(v);k?k.add(y):u.set(v,new Set([y]))}return u},K=async(l,r,a)=>{const d=typeof a.limit=="number"?Math.max(0,Math.floor(a.limit)):void 0,u=d===0?new Map:await I(r),w=(O,v)=>_(r.table,a,{_id:{in:[...O]}},v);let p=new Map;if(u.size>0&&d!==void 0&&u.size<=g.remaining){g.remaining-=u.size;const O=[...u.keys()],v=await Promise.all([...u.values()].map(async y=>w(y,d)));p=new Map(O.map((y,k)=>[y,b(r.table,v[k]??[])]))}else if(u.size>0){const O=new Set([...u.values()].flatMap(v=>[...v]));p=ne(u,b(r.table,await w(O,void 0)))}T(l,a,d,"_id",p)},Z=async(l,r)=>{const a=[...r];if(a.length===0)return new Set;if(G(h,l)){const u=await t(l,"_id",a,i?.(l),i);return new Set(a.filter(w=>(u.get(w)??0)>0))}const d=await _(l,{},{_id:{in:a}},void 0);return new Set(d.map(u=>u._id))},J=async(l,r)=>{const a=await I(r),d=await Z(r.table,new Set([...a.values()].flatMap(u=>[...u])));for(const u of s){const w=u._count??{};w[l]=[...a.get(u._id)??[]].filter(p=>d.has(p)).length,u._count=w}},Q=async l=>{for(const r of Object.keys(l)){const a=R(r);if(a.through!==void 0){await J(r,a);continue}const[d,u]=a.kind==="many"?[a.field,a.references]:[a.references,a.field],w=i?.(a.table),p=j(s,u),O=p.length===0?new Map:await t(a.table,d,p,w,i);for(const v of s){const y=v._count??{},k=v[u];y[r]=k==null?0:O.get(k)??0,v._count=y}}};for(const[l,r]of Object.entries(m)){if(r===void 0||r===!1)continue;if(l==="_count"){await Q(r);continue}const a=R(l),d=r===!0?{}:r;a.through===void 0?await(a.kind==="one"?X(l,a,d):q(l,a,d)):await K(l,a,d)}},D=1e4,U=500,oe=async(e,t,n,o,s)=>{const i=new Set;let c=s;for(;;){const f=c!==void 0,h=c??await e();let m=!1;c=void 0;for(const g of h){const b=g._id;if(!(typeof b!="string"||i.has(b))){if(i.add(b),m=!0,i.size>D)throw n();await t(b)}}if(!f){if(h.length<U)return;if(!m)throw new S("INTERNAL",o)}}},H=(e,t,n)=>new S("CASCADE_LIMIT",`cannot delete "${e}" row: more than ${String(D)} ${t} rows reference it (onDelete: ${n}) — delete or re-point them in batches first`,{status:400}),se=async(e,t,n,o)=>{const{deletedId:s,deletedReference:i,findHolders:c,onRestrict:f,tableName:h}=e,m=n.references==="_id"?s:i(n.references);if(m==null)return;const{field:g}=n,b=`"${t}.${g}"`,A=await c(t,g,m,{limit:o==="restrict"?1:D+1,select:["_id"]});if(A.length!==0){if(o==="restrict")return f(`cannot delete "${h}" row: ${b} still references it`);if(A.length>D)throw H(h,b,o);return{action:o,field:g,holderTable:t,label:b,probe:A,referencedValue:m}}},re=async(e,t,n)=>{const{findHolders:o,onCascade:s,onSetNull:i,tableName:c}=e,{action:f,field:h,holderTable:m,label:g,probe:b,referencedValue:A}=t;await oe(()=>o(m,h,A,{limit:U}),$=>f==="cascade"?s(m,$):i(m,$,h),()=>H(c,g,f),`onDelete on "${c}" made no progress: ${g} rows still match after being processed`,n?b:void 0)},Oe=async e=>{const{schema:t,tableName:n}=e;if(!t.tables[n])throw new S("INTERNAL",`unknown table: ${n}`);const o=[];for(const[s,i]of Object.entries(t.tables)){const c=i.relationMap;if(c)for(const f of Object.values(c)){if(f.kind!=="one"||f.table!==n||!f.onDelete)continue;const h=await se(e,s,f,f.onDelete);h&&o.push(h)}}for(const[s,i]of o.entries())await re(e,i,s===0)},L=new WeakMap,B=e=>{const t=L.get(e);if(t!==void 0)return t;const n=e._meta,o=[n?.inner,n?.keyValidator,n?.valueValidator,...n?.members??[],...Object.values(n?.shape??{})],s=e.kind==="from"||o.some(i=>i!==void 0&&B(i));return L.set(e,s),s},C=e=>{const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},P=e=>e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):void 0,V=(e,t)=>{if(Object.is(e,t))return!0;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();const n=P(e),o=P(t);if(n!==void 0||o!==void 0)return n!==void 0&&o!==void 0&&Object.getPrototypeOf(e)===Object.getPrototypeOf(t)&&n.length===o.length&&n.every((f,h)=>f===o[h]);if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((f,h)=>V(f,t[h]));if(typeof e!="object"||typeof t!="object"||e===null||t===null||!C(e)||!C(t))return!1;const s=e,i=t,c=Object.keys(s);return c.length===Object.keys(i).length&&c.every(f=>f in i&&V(s[f],i[f]))},N=new WeakMap,Ae=e=>{if(N.has(e))return N.get(e);const t=Object.fromEntries(Object.entries(e.shape).filter(([,o])=>B(o))),n=Object.keys(t).length>0?{...e,shape:t}:void 0;return N.set(e,n),n},ae=e=>{let t;return(n,o)=>e===void 0?!1:(t??=e()??{},n in t&&V(o,t[n]))},ie=(e,t)=>{const n=new Set(Object.keys(t).filter(o=>t[o]!==void 0));for(const[o,s]of F(e))s.serverDefault&&n.delete(o);return n},ce=(e,t,n,o,s)=>n.trusted===!0||o!==void 0&&!o.has(e)||s(e,t),M=e=>typeof e!="object"||e===null?e:e instanceof Date?new Date(e):e instanceof ArrayBuffer||ArrayBuffer.isView(e)?structuredClone(e):Array.isArray(e)?e.map(t=>M(t)):e instanceof Map?new Map([...e].map(([t,n])=>[M(t),M(n)])):e instanceof Set?new Set([...e].map(t=>M(t))):C(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,M(n)])):e,ke=(e,t,n)=>{const o={...t};for(const[s,i]of F(e)){if(i.serverDefault){o[s]=i.serverDefault({auth:n});continue}if(o[s]===void 0){if(i.defaultFn)o[s]=i.defaultFn();else if("defaultValue"in i){const{defaultValue:c}=i;o[s]=M(c)}}}return o},fe=e=>e.map((t,n)=>typeof t=="number"?`[${String(t)}]`:n===0?t:`.${t}`).join(""),le=(e,t,n,o)=>o.patched===void 0?"":o.patched.has(e)?n?" (set by the column's server default, which replaces what this patch sent)":" (set by this patch)":Object.is(o.previous?.()?.[e],t)?" (a stored value this patch does not set: the row already holds it, and every patch of the row fails until it is fixed)":" (not set by this patch: an update hook assigned it)",ue=e=>e.message.startsWith("object has ")?"object":e.received.startsWith("object")?e.received:e.received.split(" ")[0]??e.received,de=e=>e instanceof Error&&e.code==="VALIDATION_ERROR"&&Array.isArray(e.path)&&typeof e.expected=="string"&&typeof e.received=="string",he=(e,t,n)=>{const{field:o,serverDefault:s,value:i}=t,c=[o,...e.path],f=`${n.table===void 0?"":`${n.table}.`}${fe(c)}`,h=e.message.startsWith(`Expected ${e.expected} at `)&&e.message.endsWith(`, received ${e.received}`),m=ue(e),g=h?`expected ${e.expected}, received ${m}`:e.message,b=e.constructor,A=new b(`${f}: ${g}${le(o,i,s,n)}`,{expected:e.expected,path:c,received:m}),$=e.stack?.indexOf(`
2
2
  at `)??-1;return $!==-1&&e.stack!==void 0&&(A.stack=`${A.name}: ${A.message}${e.stack.slice($)}`),A},pe=(e,t,n)=>{try{return e(t.value)}catch(o){throw de(o)?he(o,t,n):o}},$e=(e,t,n={})=>{let o;const s=ae(n.previous),i=n.only??(n.supplied===void 0?void 0:ie(e,n.supplied));for(const[c,f]of Object.entries(e.shape)){if(!(c in t)||typeof f.parse!="function")continue;const h=B(f);if(h&&ce(c,t[c],n,i,s)||n.tolerateStoredNull===!0&&t[c]===null&&f.kind==="optional")continue;const m=pe(g=>f.parse?.(g),{field:c,serverDefault:f._meta?.column?.serverDefault!==void 0,value:t[c]},n);h&&(o??={...t},o[c]=m)}return o??t};export{D as CASCADE_MAX_ROWS,E as MAX_LINK_ROWS,ke as applyInsertDefaults,Oe as applyOnDelete,j as distinctValues,be as fanOutScalarCounts,me as relationHooks,ve as resolveWith,$e as runRowValidators,Ae as transformOnlyDefinition};
@@ -1,4 +1,4 @@
1
- import{sql as s}from"drizzle-orm";import{runDrizzle as d}from"./runDrizzle-RC09zZrh.mjs";const C=16,T=32,v=1e4,R=1e3,h=t=>String(t).padStart(C,"0"),f=t=>`cdc/${encodeURIComponent(t.shard)}/${encodeURIComponent(t.epoch)}/`,y=(t,n)=>`${f(t)}${h(n)}.json`,E="__cdc_archive",g=t=>{d(t,s`CREATE TABLE IF NOT EXISTS ${s.identifier(E)} (
1
+ import{sql as s}from"drizzle-orm";import{runDrizzle as d}from"./runDrizzle-DAtZbzBn.mjs";const C=16,T=32,v=1e4,R=1e3,h=t=>String(t).padStart(C,"0"),f=t=>`cdc/${encodeURIComponent(t.shard)}/${encodeURIComponent(t.epoch)}/`,y=(t,n)=>`${f(t)}${h(n)}.json`,E="__cdc_archive",g=t=>{d(t,s`CREATE TABLE IF NOT EXISTS ${s.identifier(E)} (
2
2
  id INTEGER PRIMARY KEY CHECK (id = 1),
3
3
  seq INTEGER NOT NULL
4
4
  )`)},$=t=>(g(t),d(t,s`SELECT seq FROM ${s.identifier(E)} WHERE id = 1`).toArray()[0]?.seq??0),w=(t,n)=>{g(t),d(t,s`INSERT INTO ${s.identifier(E)} (id, seq) VALUES (1, ${n}) ON CONFLICT (id) DO UPDATE SET seq = ${n}`)},L=async(t,n,e)=>{const o=e[0]?.seq,r=e.at(-1)?.seq;o===void 0||r===void 0||await t.put(y(n,r),JSON.stringify({changes:e,from:o,to:r}),{httpMetadata:{contentType:"application/json"}})},j=async(t,n,e)=>{const o=f(n);return(await t.list({limit:1,prefix:o,startAfter:`${o}${h(e)}.json`})).objects.length>0},S=t=>{let n;try{n=JSON.parse(t)}catch{return}if(typeof n!="object"||n===null)return;const e=n;return typeof e.from=="number"&&typeof e.to=="number"&&Array.isArray(e.changes)?e:void 0},_=(t,n)=>{const e=[];for(const o of t.changes)if(!(o.seq<=n)){if(o.op!=="delete"&&o.doc===void 0)break;e.push(o)}return e},I=(t,n,e)=>{let o=e;for(const r of n){if(r.seq!==o+1)break;t.push(r),o=r.seq}return o},b=async(t,n)=>{const e=await t.get(n);return e===null?void 0:S(await e.text())},q=async(t,n,e,o)=>{const r=f(n),p=Math.max(1,Math.min(o??R,v)),A=await t.list({limit:T,prefix:r,startAfter:`${r}${h(e)}.json`}),c=[];let i=e;for(const l of A.objects){const a=await b(t,l.key);if(a===void 0)break;const m=_(a,i);if(i=I(c,m,i),c.length>=p||i!==a.to)break}if(c[0]?.seq!==e+1)return;const u=c.slice(0,p);return{changes:u,cursor:u.at(-1)?.seq??e}};export{L as archiveCdcSegment,j as cdcArchiveRewound,q as readArchivedCdcChanges,$ as readCdcArchivedThrough,w as writeCdcArchivedThrough};
@@ -0,0 +1 @@
1
+ import{m as P,c as E,l as w,r as T,a as D,w as F}from"./ctx-db-search-state-Bv_NxB1g.mjs";import{S as I,b as L,c as b,d as x,a as k}from"./fts-companion-Cfz-hJum.mjs";import{sql as i}from"drizzle-orm";import{ensureAggregateCompanion as _,ensureRankCompanion as y}from"./createCompanionSync-D5cqtwqR.mjs";import{runDrizzle as p,runAll as C}from"./runDrizzle-DAtZbzBn.mjs";import{i as M,D as m,a as A}from"./do-sql-DT8JBpG8.mjs";import{sqliteInList as B}from"./param-Y0zw_1Cv.mjs";import{groupUnmappedRows as U}from"./ftsRowidMapName-CGnFBC6P.mjs";const v=(e,o)=>p(e,i`SELECT 1 FROM ${i.identifier(o)} LIMIT 1`).toArray().length>0,X=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(n.shardMode?.kind!=="global")for(const t of n.aggregateIndexes??[])_(e,r,t,n.softDeleteMode?.field)},Z=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(n.shardMode?.kind!=="global")for(const t of n.rankIndexes??[])y(e,r,t,n.softDeleteMode?.field)},H=(e,o,r,n)=>p(e,r===void 0?i`SELECT id, _creationTime, ${i.identifier(m)} FROM ${i.identifier(o)} ORDER BY id ASC LIMIT ${i.raw(String(n))}`:i`SELECT id, _creationTime, ${i.identifier(m)} FROM ${i.identifier(o)} WHERE id > ${r} ORDER BY id ASC LIMIT ${i.raw(String(n))}`).toArray(),h=500,O=(e,o,r)=>{const n=I(o,r.name),t=E(r),a=w(T(e,n),t);if(a.finished)return{done:!0,rows:0};const{cursor:c}=a,s=H(e,o,c,h);let f=c;for(const g of s){const{id:u}=g;if(typeof u!="string")continue;f=u;const S=A(g);C(e,S?b(n,u,x(S,r)):k(n,u))}const d=s.length<h;return F(e,n,f,d,t),{done:d,rows:s.length}},l=(e,o)=>i`${i.identifier(e)}.${i.identifier(o)}`,R=500,$=(e,o,r)=>{const n=I(o,r.name),t=p(e,L(n,R)).toArray(),a=U(t);if(a.size===0)return!0;const c=new Map;for(const s of p(e,i`SELECT ${l(o,"id")}, ${l(o,"_creationTime")}, ${l(o,m)} FROM ${i.identifier(o)} WHERE ${B(l(o,"id"),[...a.keys()],!1)}`))c.set(String(s.id),s);for(const[s,f]of a){const d=c.get(s),g=d?A(d):void 0;C(e,g?b(n,s,x(g,r),{unmappedRowids:f}):k(n,s,{unmappedRowids:f}))}return t.length<R},W=(e,o,r,n)=>{let t=0;for(;t<n&&!$(e,o,r);)t+=1;return t},q=(e,o,r)=>{const n=I(o,r.name),t=E(r);return w(T(e,n),t).finished?!0:D(e,n)},ee=(e,o,r)=>{if(M(e))for(const n of r.searchIndexes??[])$(e,o,n),!(n.staged&&v(e,o))&&O(e,o,n)},j=(e,o,r,n)=>{let t=0;for(;;){if(t>=n)return{done:!1,pages:t};const a=O(e,o,r);if(a.rows>0&&(t+=1),a.done)return{done:!0,pages:t}}},ne=(e,o,r={})=>{if(!M(e))return{done:!0,pages:0};P(e);const n=r.maxPages??Number.POSITIVE_INFINITY;let t=0;for(const[a,c]of Object.entries(o.tables))if(!(c.shardMode?.kind==="global"||!c.searchIndexes))for(const s of c.searchIndexes){if(t+=W(e,a,s,n-t),t>=n)return{done:!1,pages:t};const f=j(e,a,s,n-t);if(t+=f.pages,!f.done)return{done:!1,pages:t}}return{done:!0,pages:t}};export{X as backfillAggregateIndexes,Z as backfillRankIndexes,ne as backfillSearchIndexes,ee as backfillSearchIndexesForTable,H as readKeysetPage,q as searchIndexCoversTable};
@@ -0,0 +1 @@
1
+ import{encodeWire as u}from"@lunora/wire";import{quoteIdentifier as l}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as d}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{REPROJECTION_MIGRATION_PREFIX as v,reprojectionMigrationId as w}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{e as m,D as E}from"./do-sql-DT8JBpG8.mjs";import p from"./runSql-BBRXi81G.mjs";import{mayHoldProjectedValue as g}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";const b=u(0n)[0],_=e=>e.shardMode?.kind==="global"?[]:Object.entries(e.shape).filter(([,r])=>g(r)).map(([r])=>r),M=e=>Object.entries(e.tables).filter(([,r])=>_(r).length>0).map(([r])=>r),f=e=>{const r=`json_each(${l(E)}) AS __f__`;return{params:[JSON.stringify(e),b,"bigint","bytes"],sql:`EXISTS (SELECT 1 FROM ${r} WHERE __f__.type = 'array' AND __f__.key IN (SELECT value FROM json_each(?)) AND json_extract(__f__.value, '$[0]') = ? AND json_extract(__f__.value, '$[1]') IN (?, ?))`}},N=(e,r,o)=>{if(o.length===0)return 0;const{params:t,sql:n}=f(o);return p(e,`SELECT COUNT(*) AS count FROM ${l(r)} WHERE ${n}`,...t).toArray()[0]?.count??0},R=(e,r,o,t)=>{const{params:n,sql:i}=f(o);return p(e,`SELECT 1 FROM ${l(r)} WHERE id = ? AND (${i}) LIMIT 1`,t,...n).toArray().length>0},S=(e,r,o)=>{const t=d(e);if(t===void 0)return;const n=r.tables[t];if(!n)return;const i=_(n);if(i.length!==0)return{id:e,table:t,up:s=>{const a=s._id;if(!(typeof a!="string"||!R(o,t,i,a))){try{m(s)}catch(c){console.warn(`${e}: skipping row ${a} — it cannot be re-projected: ${c instanceof Error?c.message:String(c)}`);return}return s}}}};export{v as REPROJECTION_MIGRATION_PREFIX,S as buildReprojectionMigration,N as countLegacyRows,_ as reprojectableFields,w as reprojectionMigrationId,M as reprojectionTables};
@@ -1 +1 @@
1
- import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-fCPCjSE4.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-Ce6pOHKe.mjs";import{shapeRangeKey as u}from"./ShapeDiffCache-iNO-hUiy.mjs";import{projectColumns as g}from"./buildPokeFrames-WR-hp0mX.mjs";const C=(m,e,a,i,p,f=s)=>{const r=u(e.table,a,i),n=p.changedKeys(r,()=>f(m,e.table,a,i));if(n.length===0)return[];const b=p.members(e,r,()=>h(m,e.table,e.effectiveWhere,n.map(t=>t.id))),o=[];for(const t of n){const c=b.get(t.id);if(c===void 0){t.op!=="insert"&&o.push({key:t.id,op:"delete",table:e.table});continue}o.push({key:t.id,op:t.op,table:e.table,value:g(c,e.columns)})}return o};export{C as buildShapeDiff};
1
+ import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-DchHJJ5G.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-BP30uxpp.mjs";import{shapeRangeKey as u}from"./ShapeDiffCache-iNO-hUiy.mjs";import{projectColumns as g}from"./buildPokeFrames-WR-hp0mX.mjs";const C=(m,e,a,i,p,f=s)=>{const r=u(e.table,a,i),n=p.changedKeys(r,()=>f(m,e.table,a,i));if(n.length===0)return[];const b=p.members(e,r,()=>h(m,e.table,e.effectiveWhere,n.map(t=>t.id))),o=[];for(const t of n){const c=b.get(t.id);if(c===void 0){t.op!=="insert"&&o.push({key:t.id,op:"delete",table:e.table});continue}o.push({key:t.id,op:t.op,table:e.table,value:g(c,e.columns)})}return o};export{C as buildShapeDiff};
@@ -1 +1 @@
1
- import{sql as t}from"drizzle-orm";import{runDrizzle as s}from"./runDrizzle-RC09zZrh.mjs";const a=r=>r?.memoryMode===!0,l=r=>Object.entries(r.tables).filter(([,e])=>a(e)&&e.shardMode?.kind!=="global").map(([e])=>e),i=(r,e)=>{const o=l(e);for(const m of o)s(r,t`DELETE FROM ${t.identifier(m)}`);return o.length};export{i as clearMemoryTables,a as isMemoryTable,l as memoryTableNames};
1
+ import{sql as t}from"drizzle-orm";import{runDrizzle as s}from"./runDrizzle-DAtZbzBn.mjs";const a=r=>r?.memoryMode===!0,l=r=>Object.entries(r.tables).filter(([,e])=>a(e)&&e.shardMode?.kind!=="global").map(([e])=>e),i=(r,e)=>{const o=l(e);for(const m of o)s(r,t`DELETE FROM ${t.identifier(m)}`);return o.length};export{i as clearMemoryTables,a as isMemoryTable,l as memoryTableNames};
@@ -0,0 +1 @@
1
+ import"./json-field-path-DeJW4U9z.mjs";import"./param-Y0zw_1Cv.mjs";import"./WORKERD_SQLITE_LIMITS-C9dUlw3o.mjs";import{c as t,s}from"./where-sql-AVR5KloI.mjs";import"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";export{t as compileWhereSql,s as serverInList};
@@ -0,0 +1 @@
1
+ import{LunoraError as g}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{mergeWhere as b}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{SCAN_DEP as j}from"./SCAN_DEP-B4Uu4g7l.mjs";import{runDrizzle as A}from"./runDrizzle-DAtZbzBn.mjs";import{sqliteInList as O}from"./param-Y0zw_1Cv.mjs";import{decodeCursor as F,CURSOR_PREFIX as P,toBase64 as U}from"./CURSOR_PREFIX-rOdoinP8.mjs";import{rankTableName as V,sortColumnName as z,resolveRankPartition as H,RANK_TIEBREAK as _,encodePartitionKey as J}from"./RANK_TIEBREAK-BknRdgt8.mjs";import X from"./rankPivotConditionSql-CUX4Vuhv.mjs";const Y="__doc__",G=n=>P+U(JSON.stringify(n)),Q=n=>n.after?[n.after.partitionKey,...n.after.sortValues,n.after.rowId]:n.cursor?F(n.cursor):void 0,Z=(n,r,f)=>{if(n?.length!==1+r.length+1)return;const t=[{column:"__partition__",direction:"asc"}];for(const[c,u]of r.entries())t.push({column:u,direction:f[c]?.direction??"asc"});t.push({column:_,direction:"asc"});const e=[];for(const[c,u]of t.entries()){const d=X(u.column,n[c],u.direction,!0);if(d===void 0)continue;const s=[];for(const[p,l]of t.slice(0,c).entries())s.push(o`${o.identifier(l.column)} IS ${n[p]}`);s.push(d);const[i]=s;e.push(s.length===1&&i!==void 0?i:o`(${o.join(s,o` AND `)})`)}return e.length===0?o`(1 = 0)`:o`(${o.join(e,o` OR `)})`},v=null,oo=(n,r)=>{if(n===void 0)return v;const f=[n.__partition__,...r.map(t=>n[t]),n[_]];return G(f)},no=(n,r,f)=>{const t=[];for(const e of n){const c=e[_];if(typeof c!="string")continue;const u=r.get(c);if(!u)continue;const d=typeof e.__partition__=="string"?e.__partition__:"",s=f.map(i=>e[i]??null);t.push({doc:u,key:{partitionKey:d,rowId:c,sortValues:s}})}return t},to=o`${o.identifier("id")}`,ro=(n,r,f)=>{const{rowToDocument:t}=n,e=new Map;if(f.length===0)return e;const c=A(n.sql,o`SELECT id, _creationTime, ${o.identifier(Y)} FROM ${o.identifier(r)} WHERE ${O(to,f,!1)}`).toArray();for(const u of c){const d=t(u),s=u.id;d&&typeof s=="string"&&e.set(s,d)}return e},mo=(n,r,f,t)=>{const{assertRankPartitionLocal:e,ensureRankBackfilled:c,onRead:u,schema:d}=n,s=d.tables[r];if(!s)throw new g("INTERNAL",`unknown table: ${r}`);const i=s.rankIndexes?.find(a=>a.name===f);if(!i)throw new g("INTERNAL",`unknown rankIndex "${f}" on table "${r}"`);e(r,s,i),u(r,j),c(r,i);const p=V(r,i.name),l=i.sortBy.map((a,w)=>z(w)),h=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),T=b(t.baseWhere,t.where),k=H(i,T),R=[o`${o.identifier("__partition__")} ASC`];for(const[a,w]of l.entries()){const W=i.sortBy[a]?.direction;R.push(o`${o.identifier(w)} ${o.raw(W==="desc"?"DESC":"ASC")}`)}R.push(o`${o.identifier(_)} ASC`);const 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 B=Q(t),E=Z(B,l,i.sortBy);E&&m.push(E);const I=o.identifier(_),S=o.identifier("__partition__"),D=m.length>0?o` WHERE ${o.join(m,o` AND `)}`:o``,L=l.length>0?o`${I}, ${S}, ${o.join(l.map(a=>o.identifier(a)),o`, `)}`:o`${I}, ${S}`,M=o`SELECT ${L} FROM ${o.identifier(p)}${D} ORDER BY ${o.join(R,o`, `)} LIMIT ${o.raw(String(h+1))}`,$=A(n.sql,M).toArray(),C=$.length>h,y=C?$.slice(0,h):$,K=y.map(a=>a[_]),q=no(y,ro(n,r,K),l),x=C?oo(y.at(-1),l):v,N=i.sortBy.map(a=>a.direction==="desc"?"desc":"asc");return{continueCursor:x,directions:N,hasMore:C,rows:q}};export{mo as computeRankPage,Q as resolveRankSeekTuple};
@@ -0,0 +1 @@
1
+ import{N as uo,S as $o,c as Eo,d as go,a as po}from"./fts-companion-Cfz-hJum.mjs";import{sql as o}from"drizzle-orm";import{r as Q}from"./json-field-path-DeJW4U9z.mjs";import{matchesStaticWhere as J,aggregateSqlFunction as mo}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as B,foldAggregateTally as Z,encodeAggregateKey as v,coerceAggregateNumber as H}from"./aggregateTableName-B_CtIQCS.mjs";import{aggregateSignature as ho,readCompanionSignature as N,rankSignature as So,writeCompanionSignature as x}from"./CompanionMemo-CYnosDCb.mjs";import{runAll as _o,runDrizzle as g}from"./runDrizzle-DAtZbzBn.mjs";import{i as yo,g as Ro,D as oo,u as eo,r as no}from"./do-sql-DT8JBpG8.mjs";import{AGG_KEY as D,AGG_VALUE as A,AGG_COUNT as _,aggUpsertSql as j,jsonPathSql as q}from"./AGG_COUNT-DzvM-UU5.mjs";import{param as G}from"./param-Y0zw_1Cv.mjs";import{encodeGeohash as To,GEO_DEFAULT_PRECISION as Ao}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as W}from"./CURSOR_PREFIX-rOdoinP8.mjs";import{rankTableName as P,matchesRankStaticWhere as to,sortColumnName as wo,encodePartitionKey as Co}from"./RANK_TIEBREAK-BknRdgt8.mjs";import{WORKERD_SQLITE_LIMITS as ro}from"./WORKERD_SQLITE_LIMITS-C9dUlw3o.mjs";import{mayHoldProjectedValue as Io}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{serializeSqlValue as io}from"./serializeSqlValue-DeoBMpZ2.mjs";const Oo=(i,f,t)=>[...i.partitionBy??[],...i.sortBy.map(l=>l.field),...i.where?Object.keys(i.where):[]].every(l=>Q(f,l)===Q(t,l)),so=i=>o.join(["__id__","__partition__",...i.sortBy.map((f,t)=>wo(t))].map(f=>o.identifier(f)),o`, `),co=(i,f,t)=>{const u=Co(i.partitionBy??[],t),l=i.sortBy.map(r=>io(t[r.field]??null)),a=o.join([f,u,...l].map(r=>G(r)),o`, `);return o`(${a})`},ko=(i,f,t,u,l,a)=>{g(i,o`INSERT INTO ${o.identifier(f)} (${u}) VALUES ${co(t,l,a)}`)},X=1e3,ao=function*(f,t,u,l){let a;for(;;){const r=a===void 0?o``:o` WHERE id > ${G(a)}`,m=[...g(eo(f),o`SELECT id, _creationTime, ${o.identifier(oo)} FROM ${o.identifier(t)}${r} ORDER BY id LIMIT ${G(X)}`)];for(const h of m){const R=no(h);R&&W(R,u)&&l(R)&&(yield R)}if(m.length<X)return;a=String(m.at(-1)?.id)}},vo=(i,f,t,u,l)=>{const a=B(f,t.name),r=t.by??[],m=new Map;for(const w of ao(i,f,u,I=>!t.where||J(I,t.where)))Z(m,v(r,w),t,w);g(i,o`DELETE FROM ${o.identifier(a)}`);const h=Math.floor(ro.boundParams/3),R=[...m];for(let w=0;w<R.length;w+=h){const I=R.slice(w,w+h),V=o.join(I.map(([U,F])=>o`(${U}, ${F.value}, ${F.count})`),o`, `);g(i,o`INSERT INTO ${o.identifier(a)} (${D}, ${A}, ${_}) VALUES ${V}`)}x(i,a,l)},Lo=(i,f,t,u)=>{const l=ho(t,u);N(i,B(f,t.name))!==l&&vo(i,f,t,u,l)},Do=(i,f,t,u,l)=>{const a=P(f,t.name),r=so(t);g(i,o`DELETE FROM ${o.identifier(a)}`);const m=Math.max(1,Math.floor(ro.boundParams/(2+t.sortBy.length)));let h=[];const R=()=>{h.length>0&&(g(i,o`INSERT INTO ${o.identifier(a)} (${r}) VALUES ${o.join(h,o`, `)}`),h=[])};for(const w of ao(i,f,u,I=>!t.where||to(I,t.where)))h.push(co(t,w._id,w)),h.length>=m&&R();R(),x(i,a,l)},Fo=(i,f,t,u)=>{const l=So(t,u);N(i,P(f,t.name))!==l&&Do(i,f,t,u,l)},Mo=(i,f,t,u,l,a,r)=>{if(a&&r&&W(a,u)===W(r,u)&&Oo(t,a,r))return;const m=P(f,t.name);a&&g(i,o`DELETE FROM ${o.identifier(m)} WHERE ${o.identifier("__id__")} = ${l}`),!(!r||!W(r,u)||t.where&&!to(r,t.where))&&ko(i,m,t,so(t),l,r)},No=i=>{const{broadcast:f,indexKeysFor:t,invalidateCache:u,recordCdc:l,schema:a,sql:r}=i,m=i.verified??new Set,h=e=>a.tables[e]?.softDeleteMode?.field,R=(e,n)=>{const c=B(e,n.name);m.has(c)||(Lo(r,e,n,h(e)),m.add(c))},w=(e,n,c)=>{const p=n.by??[],d=n.field??"",E=[],y=(s,$)=>{const S=io($);S===null?E.push(o`${q(s)} IS NULL`):E.push(o`${q(s)} = ${S}`)};for(const s of p)y(s,c[s]??null);const C=h(e);C!==void 0&&y(C,null);for(const[s,$]of Object.entries(n.where??{}))y(s,$!==null&&typeof $=="object"&&!Array.isArray($)?$.eq:$);const L=E.length>0?o` WHERE ${o.join(E,o` AND `)}`:o``,M=a.tables[e]?.shape[d];if(M&&Io(M)){const s=g(eo(r),o`SELECT id, _creationTime, ${o.identifier(oo)} FROM ${o.identifier(e)}${L}`).toArray(),$=new Map;for(const S of s){const k=no(S);k&&Z($,"",n,k)}return{value:$.get("")?.value??null}}const b=mo(n.op),T=q(d);return{value:g(r,o`SELECT ${o.raw(b)}(${T}) AS value FROM ${o.identifier(e)}${L}`).one().value??null}},I=(e,n,c,p)=>{const d=B(e,n.name),{op:E}=n,y=n.field??"",C=s=>{g(r,o`DELETE FROM ${o.identifier(d)} WHERE ${D} = ${s} AND ${_} <= 0`)},L=h(e),M=s=>!n.where||J(s,n.where),b=s=>W(s,L)&&M(s);p!==void 0&&E!=="count"&&M(p)&&H(p[y]);const T=c&&b(c)?c:void 0,O=p&&b(p)?p:void 0;if(!(!T&&!O)){if(E==="count"){for(const[s,$]of[[T,-1],[O,1]]){if(!s)continue;const S=v(n.by??[],s);g(r,j(d,S,$,$,o`${A} = ${A} + excluded.${A}, ${_} = ${_} + excluded.${_}`))}T&&C(v(n.by??[],T));return}if(E==="sum"||E==="avg"){for(const[s,$]of[[T,-1],[O,1]]){if(!s)continue;const S=H(s[y]);if(S===void 0)continue;const k=v(n.by??[],s);g(r,j(d,k,$*S,$,o`${A} = COALESCE(${A}, 0) + excluded.${A}, ${_} = ${_} + excluded.${_}`))}T&&C(v(n.by??[],T));return}if(T){const s=v(n.by??[],T),$=H(T[y]),S=g(r,o`SELECT ${A} AS value, ${_} AS count FROM ${o.identifier(d)} WHERE ${D} = ${s}`).toArray()[0],k=(S?.count??0)-1;if(k<=0)g(r,o`DELETE FROM ${o.identifier(d)} WHERE ${D} = ${s}`);else if(S&&$!==void 0&&S.value!==null&&$===S.value){const lo=w(e,n,T);g(r,o`UPDATE ${o.identifier(d)} SET ${A} = ${lo.value}, ${_} = ${k} WHERE ${D} = ${s}`)}else g(r,o`UPDATE ${o.identifier(d)} SET ${_} = ${_} - 1 WHERE ${D} = ${s}`)}if(O){const s=v(n.by??[],O),$=H(O[y]);if($===void 0)g(r,j(d,s,null,1,o`${_} = ${_} + 1`));else{const S=E==="min"?"MIN":"MAX";g(r,j(d,s,$,1,o`${A} = ${o.raw(S)}(COALESCE(${A}, excluded.${A}), excluded.${A}), ${_} = ${_} + 1`))}}}},V=e=>{for(const n of a.tables[e]?.aggregateIndexes??[])R(e,n)},U=(e,n,c)=>{for(const p of a.tables[e]?.aggregateIndexes??[])I(e,p,n,c)},F=(e,n)=>{const c=P(e,n.name);m.has(c)||(Fo(r,e,n,h(e)),m.add(c))},fo=e=>{for(const n of a.tables[e]?.rankIndexes??[])F(e,n)},K=(e,n,c,p)=>{for(const d of a.tables[e]?.rankIndexes??[])Mo(r,e,d,h(e),n,c,p)},z=(e,n,c,p)=>{const d=a.tables[e]?.searchIndexes??[];if(!(d.length===0||!yo(r)))for(const E of d){if(uo(p,c,E))continue;const y=$o(e,E.name);_o(r,c?Eo(y,n,go(c,E)):po(y,n))}},Y=(e,n,c)=>{for(const p of a.tables[e]?.geoIndexes??[]){const d=Ro(e,p.name);g(r,o`DELETE FROM ${o.identifier(d)} WHERE ${o.identifier("__id__")} = ${n}`);const E=c?.[p.field];if(E!==null&&typeof E=="object"&&typeof E.lat=="number"&&typeof E.lng=="number"){const{lat:y,lng:C}=E,L=To({lat:y,lng:C},p.precision??Ao);g(r,o`INSERT INTO ${o.identifier(d)} (${o.identifier("__id__")}, ${o.identifier("__geohash__")}, ${o.identifier("__lat__")}, ${o.identifier("__lng__")}) VALUES (${n}, ${L}, ${y}, ${C})`)}}};return{ensureBackfilledForTable:V,ensureBackfilledIndex:R,ensureRankBackfilled:F,ensureRankBackfilledForTable:fo,syncAggregates:U,syncCompanionsForInsert:(e,n,c)=>{z(e,n,c),Y(e,n,c),U(e,void 0,c),K(e,n,void 0,c),u(e,n,c),l(e,n,"insert",c),f({indexKeys:t(e,c),key:n,op:"insert",row:c,table:e})},syncGeo:Y,syncRanks:K,syncSearch:z}};export{No as createCompanionSync,Lo as ensureAggregateCompanion,Fo as ensureRankCompanion};
@@ -1,4 +1,4 @@
1
- import{LunoraError as T}from"@lunora/errors";import{decodeWire as v,encodeWire as N}from"@lunora/wire";import{cursorBelowRetainedFloor as b}from"./CDC_LOG_TABLE-fCPCjSE4.mjs";import{envPositiveInt as E}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{e as I}from"./estimate-bytes-C-C35VXL.mjs";import{siblingStub as L}from"./stubByName-DQSivmvb.mjs";import{DEFAULT_TRANSACTION_LIMITS as O}from"./DEFAULT_TRANSACTION_LIMITS-D7p7Ys0M.mjs";import{verifySiblingBody as C,RELAY_SIGNATURE_HEADER as S,siblingSecretOf as R,signSiblingBody as U}from"./RELAY_SIGNATURE_HEADER-CAfC4tqg.mjs";const q=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],x=new Set(q),F=r=>typeof r=="string"&&x.has(r),w="::replica::",_=r=>{const e=r.lastIndexOf(w);if(e===-1)return;const t=r.slice(0,e),s=r.slice(e+w.length);if(!(t.length===0||!F(s)))return{ownerKey:t,region:s}},M=r=>{if(r==null||!/^\d+$/.test(r))return;const e=Number.parseInt(r,10);return Number.isSafeInteger(e)&&e>0?e:void 0},P=1e3,A=1e3,B=10,D=5e4,W=r=>E(r,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",D),f="__replica_state",g=new WeakSet,m=r=>{g.has(r)||(r.exec(`CREATE TABLE IF NOT EXISTS ${f} (
1
+ import{LunoraError as T}from"@lunora/errors";import{decodeWire as v,encodeWire as N}from"@lunora/wire";import{cursorBelowRetainedFloor as b}from"./CDC_LOG_TABLE-DchHJJ5G.mjs";import{envPositiveInt as E}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{e as I}from"./estimate-bytes-C-C35VXL.mjs";import{siblingStub as L}from"./stubByName-DQSivmvb.mjs";import{DEFAULT_TRANSACTION_LIMITS as O}from"./DEFAULT_TRANSACTION_LIMITS-D7p7Ys0M.mjs";import{verifySiblingBody as C,RELAY_SIGNATURE_HEADER as S,siblingSecretOf as R,signSiblingBody as U}from"./RELAY_SIGNATURE_HEADER-CAfC4tqg.mjs";const q=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],x=new Set(q),F=r=>typeof r=="string"&&x.has(r),w="::replica::",_=r=>{const e=r.lastIndexOf(w);if(e===-1)return;const t=r.slice(0,e),s=r.slice(e+w.length);if(!(t.length===0||!F(s)))return{ownerKey:t,region:s}},M=r=>{if(r==null||!/^\d+$/.test(r))return;const e=Number.parseInt(r,10);return Number.isSafeInteger(e)&&e>0?e:void 0},P=1e3,A=1e3,B=10,D=5e4,W=r=>E(r,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",D),f="__replica_state",g=new WeakSet,m=r=>{g.has(r)||(r.exec(`CREATE TABLE IF NOT EXISTS ${f} (
2
2
  id INTEGER PRIMARY KEY CHECK (id = 1),
3
3
  epoch TEXT NOT NULL,
4
4
  applied_seq INTEGER NOT NULL,
@@ -1,4 +1,4 @@
1
- import{encodeWire as l,decodeWire as E}from"@lunora/wire";import{sql as i}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-RC09zZrh.mjs";import{a as T}from"./relay-CKEdfUjH.mjs";const t="__lunora_relay_shapes",o=null,R=e=>{a(e,i`CREATE TABLE IF NOT EXISTS ${i.identifier(t)} (
1
+ import{encodeWire as l,decodeWire as E}from"@lunora/wire";import{sql as i}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-DAtZbzBn.mjs";import{a as T}from"./relay-CKEdfUjH.mjs";const t="__lunora_relay_shapes",o=null,R=e=>{a(e,i`CREATE TABLE IF NOT EXISTS ${i.identifier(t)} (
2
2
  key TEXT PRIMARY KEY,
3
3
  relay_idx INTEGER,
4
4
  connection_id TEXT,
@@ -1 +1 @@
1
- import{q as E}from"./MAX_TOKEN_LENGTH-iFEGEcDL-DBPC6ZWl.mjs";import{sql as e}from"drizzle-orm";import{runDrizzle as d}from"./runDrizzle-RC09zZrh.mjs";const S=i=>`${E(i.language).profile}:${i.field}`,c=i=>{const r=i.slice(i.indexOf(":")+1),o=r.lastIndexOf("/");return o===-1?r:r.slice(0,o)},N=(i,r)=>i.profile!==r?{cursor:void 0,finished:!1,wipe:i.cursor!==void 0||i.done}:{cursor:i.cursor,finished:i.done,wipe:!1},T=(i,r)=>typeof i=="string"&&c(i)===c(r),n="__lunora_search_state",R=i=>{d(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("cursor")} TEXT, ${e.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${e.identifier("profile")} TEXT, ${e.identifier("covered")} INTEGER NOT NULL DEFAULT 0)`);const r=new Set(d(i,e`PRAGMA table_info(${e.identifier(n)})`).toArray().map(o=>o.name));r.has("profile")||d(i,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${e.identifier("profile")} TEXT`),r.has("covered")||d(i,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${e.identifier("covered")} INTEGER NOT NULL DEFAULT 0`),d(i,e`UPDATE ${e.identifier(n)} SET ${e.identifier("covered")} = 1 WHERE ${e.identifier("done")} = 1 AND ${e.identifier("covered")} = 0`)},s=i=>i===1||i===!0||i==="1",m=(i,r)=>{const o=d(i,e`SELECT ${e.identifier("covered")} FROM ${e.identifier(n)} WHERE ${e.identifier("companion")} = ${r}`).toArray();return s(o[0]?.covered)},l=(i,r,o)=>{const t=d(i,e`SELECT ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")} FROM ${e.identifier(r)} WHERE ${e.identifier("companion")} = ${o}`).toArray()[0];return t?{cursor:t.cursor??void 0,done:s(t.done),profile:t.profile??void 0}:{cursor:void 0,done:!1,profile:void 0}},u=(i,r)=>l(i,n,r),O=(i,r,o,f,t)=>{const $=o??null,a=T(u(i,r).profile,t)?e`MAX(${e.identifier(n)}.${e.identifier("covered")}, excluded.${e.identifier("covered")})`:e`excluded.${e.identifier("covered")}`;d(i,e`INSERT INTO ${e.identifier(n)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("covered")}) VALUES (${r}, ${$}, ${f?1:0}, ${t}, ${f?1:0}) ON CONFLICT (${e.identifier("companion")}) DO UPDATE SET ${e.identifier("cursor")} = excluded.${e.identifier("cursor")}, ${e.identifier("done")} = excluded.${e.identifier("done")}, ${e.identifier("profile")} = excluded.${e.identifier("profile")}, ${e.identifier("covered")} = ${a}`)};export{n as S,m as a,l as b,S as c,N as l,R as m,u as r,O as w};
1
+ import{q as E}from"./MAX_TOKEN_LENGTH-iFEGEcDL-DBPC6ZWl.mjs";import{sql as e}from"drizzle-orm";import{runDrizzle as d}from"./runDrizzle-DAtZbzBn.mjs";const S=i=>`${E(i.language).profile}:${i.field}`,c=i=>{const r=i.slice(i.indexOf(":")+1),o=r.lastIndexOf("/");return o===-1?r:r.slice(0,o)},N=(i,r)=>i.profile!==r?{cursor:void 0,finished:!1,wipe:i.cursor!==void 0||i.done}:{cursor:i.cursor,finished:i.done,wipe:!1},T=(i,r)=>typeof i=="string"&&c(i)===c(r),n="__lunora_search_state",R=i=>{d(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("cursor")} TEXT, ${e.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${e.identifier("profile")} TEXT, ${e.identifier("covered")} INTEGER NOT NULL DEFAULT 0)`);const r=new Set(d(i,e`PRAGMA table_info(${e.identifier(n)})`).toArray().map(o=>o.name));r.has("profile")||d(i,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${e.identifier("profile")} TEXT`),r.has("covered")||d(i,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${e.identifier("covered")} INTEGER NOT NULL DEFAULT 0`),d(i,e`UPDATE ${e.identifier(n)} SET ${e.identifier("covered")} = 1 WHERE ${e.identifier("done")} = 1 AND ${e.identifier("covered")} = 0`)},s=i=>i===1||i===!0||i==="1",m=(i,r)=>{const o=d(i,e`SELECT ${e.identifier("covered")} FROM ${e.identifier(n)} WHERE ${e.identifier("companion")} = ${r}`).toArray();return s(o[0]?.covered)},l=(i,r,o)=>{const t=d(i,e`SELECT ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")} FROM ${e.identifier(r)} WHERE ${e.identifier("companion")} = ${o}`).toArray()[0];return t?{cursor:t.cursor??void 0,done:s(t.done),profile:t.profile??void 0}:{cursor:void 0,done:!1,profile:void 0}},u=(i,r)=>l(i,n,r),O=(i,r,o,f,t)=>{const $=o??null,a=T(u(i,r).profile,t)?e`MAX(${e.identifier(n)}.${e.identifier("covered")}, excluded.${e.identifier("covered")})`:e`excluded.${e.identifier("covered")}`;d(i,e`INSERT INTO ${e.identifier(n)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("covered")}) VALUES (${r}, ${$}, ${f?1:0}, ${t}, ${f?1:0}) ON CONFLICT (${e.identifier("companion")}) DO UPDATE SET ${e.identifier("cursor")} = excluded.${e.identifier("cursor")}, ${e.identifier("done")} = excluded.${e.identifier("done")}, ${e.identifier("profile")} = excluded.${e.identifier("profile")}, ${e.identifier("covered")} = ${a}`)};export{n as S,m as a,l as b,S as c,N as l,R as m,u as r,O as w};
@@ -1 +1 @@
1
- import{createShardCtxDb as C}from"./NotUniqueError-Cv97uGOS.mjs";import{createRelayLink as N}from"./DEFAULT_MAX_RELAYS-BZLpaaq1.mjs";import{ConflictError as q}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as B}from"./runShardMigrations-4_ene2xR.mjs";import{d as x}from"./relay-CKEdfUjH.mjs";const v=(O,y={})=>({_meta:{column:{notNull:!0,...y}},kind:O}),W=(O,y,F)=>{const{describe:_,expect:l,it:b}=F;_(`engine contract: ${O}`,()=>{_("optimistic concurrency",()=>{const g=u=>({tables:{items:{indexes:[],shape:{title:v("string"),version:v("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});b("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p=g(d);B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await l(s.patch("items","i1",{title:"second"})).rejects.toBeInstanceOf(q)}finally{u?.()}}),b("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p=g(d);B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("items","i1",{title:"second"})}catch(t){r=t}const e=r;l(e.code).toBe("CONFLICT"),l(e.kind).toBe("occ")}finally{u?.()}}),b("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p=g(d);B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("items","i1",{title:"second"})}catch{}const r=await s.get("items","i1");l(r?.title).toBe("first"),l(r?.version).toBe(99)}finally{u?.()}}),b("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p={tables:{items:{indexes:[],shape:{title:v("string"),version:v("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,a)=>{await t.db.patch("items",a.doc._id,{version:99})},op:"update",timing:"before"}}}}};B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("items","i1",{title:"second"})}catch(t){r=t}const e=r;l(e).toBeInstanceOf(q),l(e.code).toBe("CONFLICT"),l(e.kind).toBe("trigger")}finally{u?.()}})}),_("shape-poke ordering",()=>{const g="shard-a",u={args:{},name:"messages"},h=(e,t,a,n)=>e.accept(t?.()??{},{connectionId:a,shapes:{[n]:u}}),d=(e,t,a,n=new Set)=>{let c=0,i=0;const o=k=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${k}`)},m={fetch:(k,E)=>{if(JSON.parse(E?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const I=a[i];if(i+=1,I===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(I))}},f={get:()=>m,getByName:()=>m,idFromName:k=>k},w={buildShapeDiff:o("buildShapeDiff"),computeOpLogShapeSeed:o("computeOpLogShapeSeed"),currentCdcEpoch:o("currentCdcEpoch"),deliverWhisperLocal:o("deliverWhisperLocal"),dropIfLapsed:k=>n.has((k.deserializeAttachment?.()).connectionId??""),doName:()=>x(g,0),env:()=>({SHARD:f}),getWebSockets:()=>e.getSockets(),maskMetadata:o("maskMetadata"),nextPokeId:()=>(c+=1,`poke-${String(c)}`),readAttachment:k=>k.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:o("resolveShape"),rlsMetadata:o("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},S=N(w);if(S===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return S},p=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,a)=>{const n=await e.seedRelayShape(t,a,u,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},r=(e={})=>p({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});b("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),o=h(c,t,"c-alice","s1");await s(i,o,"s1"),await i.handleControl(r());const f=(await n(o)).map(w=>JSON.parse(w));l(f.map(w=>w.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),l(new Set(f.map(w=>w.pokeId)).size).toBe(1),l(f[1]?.shapeId).toBe("s1"),l(f[2]?.checkpoint).toBe(20)}finally{e?.()}}),b("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),o=h(c,t,"c-alice","s1"),m=h(c,t,"c-bob","s2");await s(i,o,"s1"),await s(i,m,"s2"),await i.handleControl(r());const f=await n(o);l(f.length).toBe(3);const w=await n(m);l(w.length).toBe(0),await i.handleControl(r());const S=await n(o);l(S.length).toBe(3)}finally{e?.()}}),b("pokes no subscriber the host reports lapsed, and still pokes the others",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=new Set,o=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:10,epoch:"e1",frames:[]}],i),m=h(c,t,"c-alice","s1"),f=h(c,t,"c-bob","s2");await s(o,m,"s1"),await s(o,f,"s2"),i.add("c-bob"),await o.handleControl(r());const w=await n(m),S=await n(f);l(w.length).toBe(3),l(S.length).toBe(0)}finally{e?.()}}),b("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),o=h(c,t,"c-alice","s1");await s(i,o,"s1"),await i.handleControl(r({epoch:"e2"}));const m=await n(o);l(m.length).toBe(0),await i.handleControl(r());const f=await n(o);l(f.length).toBe(3)}finally{e?.()}})}),_("orderBy null placement",()=>{const g=[["a",void 0],["b",3],["c",void 0],["d",1],["e",void 0],["f",3],["g",2],["h",void 0]],u=[{nulls:"first",sort:"asc"},{nulls:"last",sort:"asc"},{nulls:"first",sort:"desc"},{nulls:"last",sort:"desc"}],h=({nulls:p,sort:s})=>{const r=new Map(g.map(([t],a)=>[t,a])),e=s==="asc"?1:-1;return g.toSorted(([t,a],[n,c])=>a!==c?a===void 0?p==="first"?-1:1:c===void 0?p==="first"?1:-1:(a-c)*e:((r.get(t)??0)-(r.get(n)??0))*e).map(([t])=>t)},d=p=>p.map(s=>String(s.label));b("pages every placement in threes with no row skipped or repeated",async()=>{const{close:p,host:s}=y();try{const r=s.sql,e=u.map((i,o)=>`items_${String(o)}`),t={label:v("string"),score:v("number",{notNull:!1})},a={tables:Object.fromEntries(e.map(i=>[i,{indexes:[{fields:["score"],name:"by_score"}],shape:t}]))};B(r,a);let n=17e11;const c=C({clock:()=>(n+=1e3,n),schema:a,sql:r});for(const i of e)for(const[o,m]of g)await c.insert(i,m===void 0?{label:o}:{label:o,score:m});for(const[i,o]of u.entries()){const m=e[i]??"",f=await c.findMany(m,{orderBy:[{score:o}]});l(d(f.page)).toStrictEqual(h(o));const w=[];let S;for(let k=0;k<g.length+2;k+=1){const E=await c.findMany(m,{cursor:S,limit:3,orderBy:[{score:o}]});if(w.push(...d(E.page)),E.isDone)break;S=E.continueCursor}l(w).toStrictEqual(h(o))}}finally{p?.()}})}),_("RLS identity under live subscription",()=>{const g="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},d=s=>{const r=[],e=[],t={fetch:(c,i)=>(r.push(JSON.parse(i?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=N({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,dropIfLapsed:()=>!1,doName:()=>g,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:c=>c}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(c,i,o)=>(e.push(o),c===h.name?{columns:["id"],effectiveWhere:{org:o?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:r,resolvedUnder:e}},p=async(s,r)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...r,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};b("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:r}=y();try{const{owner:e,resolvedUnder:t}=d(r.sql);await p(e,h),l(t.some(a=>a?.userId==="u1"&&a.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),b("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:r}=y();try{const{owner:e,posts:t}=d(r.sql);await p(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const a=t.filter(n=>n.type==="relay_shape_poke");l(a.length).toBe(1),l(a[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),b("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:r}=y();try{const{owner:e,posts:t}=d(r.sql);await p(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const a=t.filter(n=>n.type==="relay_shape_poke");l(a.length).toBe(1),l(a[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{W as defineEngineContractSuite};
1
+ import{createShardCtxDb as C}from"./NotUniqueError-C_IDBwvG.mjs";import{createRelayLink as N}from"./DEFAULT_MAX_RELAYS-BcyWWSdU.mjs";import{ConflictError as q}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as B}from"./runShardMigrations-DeOECCjz.mjs";import{d as x}from"./relay-CKEdfUjH.mjs";const v=(O,y={})=>({_meta:{column:{notNull:!0,...y}},kind:O}),W=(O,y,F)=>{const{describe:_,expect:l,it:b}=F;_(`engine contract: ${O}`,()=>{_("optimistic concurrency",()=>{const g=u=>({tables:{items:{indexes:[],shape:{title:v("string"),version:v("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});b("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p=g(d);B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await l(s.patch("items","i1",{title:"second"})).rejects.toBeInstanceOf(q)}finally{u?.()}}),b("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p=g(d);B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("items","i1",{title:"second"})}catch(t){r=t}const e=r;l(e.code).toBe("CONFLICT"),l(e.kind).toBe("occ")}finally{u?.()}}),b("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p=g(d);B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("items","i1",{title:"second"})}catch{}const r=await s.get("items","i1");l(r?.title).toBe("first"),l(r?.version).toBe(99)}finally{u?.()}}),b("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p={tables:{items:{indexes:[],shape:{title:v("string"),version:v("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,a)=>{await t.db.patch("items",a.doc._id,{version:99})},op:"update",timing:"before"}}}}};B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("items","i1",{title:"second"})}catch(t){r=t}const e=r;l(e).toBeInstanceOf(q),l(e.code).toBe("CONFLICT"),l(e.kind).toBe("trigger")}finally{u?.()}})}),_("shape-poke ordering",()=>{const g="shard-a",u={args:{},name:"messages"},h=(e,t,a,n)=>e.accept(t?.()??{},{connectionId:a,shapes:{[n]:u}}),d=(e,t,a,n=new Set)=>{let c=0,i=0;const o=k=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${k}`)},m={fetch:(k,E)=>{if(JSON.parse(E?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const I=a[i];if(i+=1,I===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(I))}},f={get:()=>m,getByName:()=>m,idFromName:k=>k},w={buildShapeDiff:o("buildShapeDiff"),computeOpLogShapeSeed:o("computeOpLogShapeSeed"),currentCdcEpoch:o("currentCdcEpoch"),deliverWhisperLocal:o("deliverWhisperLocal"),dropIfLapsed:k=>n.has((k.deserializeAttachment?.()).connectionId??""),doName:()=>x(g,0),env:()=>({SHARD:f}),getWebSockets:()=>e.getSockets(),maskMetadata:o("maskMetadata"),nextPokeId:()=>(c+=1,`poke-${String(c)}`),readAttachment:k=>k.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:o("resolveShape"),rlsMetadata:o("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},S=N(w);if(S===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return S},p=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,a)=>{const n=await e.seedRelayShape(t,a,u,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},r=(e={})=>p({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});b("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),o=h(c,t,"c-alice","s1");await s(i,o,"s1"),await i.handleControl(r());const f=(await n(o)).map(w=>JSON.parse(w));l(f.map(w=>w.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),l(new Set(f.map(w=>w.pokeId)).size).toBe(1),l(f[1]?.shapeId).toBe("s1"),l(f[2]?.checkpoint).toBe(20)}finally{e?.()}}),b("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),o=h(c,t,"c-alice","s1"),m=h(c,t,"c-bob","s2");await s(i,o,"s1"),await s(i,m,"s2"),await i.handleControl(r());const f=await n(o);l(f.length).toBe(3);const w=await n(m);l(w.length).toBe(0),await i.handleControl(r());const S=await n(o);l(S.length).toBe(3)}finally{e?.()}}),b("pokes no subscriber the host reports lapsed, and still pokes the others",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=new Set,o=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:10,epoch:"e1",frames:[]}],i),m=h(c,t,"c-alice","s1"),f=h(c,t,"c-bob","s2");await s(o,m,"s1"),await s(o,f,"s2"),i.add("c-bob"),await o.handleControl(r());const w=await n(m),S=await n(f);l(w.length).toBe(3),l(S.length).toBe(0)}finally{e?.()}}),b("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),o=h(c,t,"c-alice","s1");await s(i,o,"s1"),await i.handleControl(r({epoch:"e2"}));const m=await n(o);l(m.length).toBe(0),await i.handleControl(r());const f=await n(o);l(f.length).toBe(3)}finally{e?.()}})}),_("orderBy null placement",()=>{const g=[["a",void 0],["b",3],["c",void 0],["d",1],["e",void 0],["f",3],["g",2],["h",void 0]],u=[{nulls:"first",sort:"asc"},{nulls:"last",sort:"asc"},{nulls:"first",sort:"desc"},{nulls:"last",sort:"desc"}],h=({nulls:p,sort:s})=>{const r=new Map(g.map(([t],a)=>[t,a])),e=s==="asc"?1:-1;return g.toSorted(([t,a],[n,c])=>a!==c?a===void 0?p==="first"?-1:1:c===void 0?p==="first"?1:-1:(a-c)*e:((r.get(t)??0)-(r.get(n)??0))*e).map(([t])=>t)},d=p=>p.map(s=>String(s.label));b("pages every placement in threes with no row skipped or repeated",async()=>{const{close:p,host:s}=y();try{const r=s.sql,e=u.map((i,o)=>`items_${String(o)}`),t={label:v("string"),score:v("number",{notNull:!1})},a={tables:Object.fromEntries(e.map(i=>[i,{indexes:[{fields:["score"],name:"by_score"}],shape:t}]))};B(r,a);let n=17e11;const c=C({clock:()=>(n+=1e3,n),schema:a,sql:r});for(const i of e)for(const[o,m]of g)await c.insert(i,m===void 0?{label:o}:{label:o,score:m});for(const[i,o]of u.entries()){const m=e[i]??"",f=await c.findMany(m,{orderBy:[{score:o}]});l(d(f.page)).toStrictEqual(h(o));const w=[];let S;for(let k=0;k<g.length+2;k+=1){const E=await c.findMany(m,{cursor:S,limit:3,orderBy:[{score:o}]});if(w.push(...d(E.page)),E.isDone)break;S=E.continueCursor}l(w).toStrictEqual(h(o))}}finally{p?.()}})}),_("RLS identity under live subscription",()=>{const g="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},d=s=>{const r=[],e=[],t={fetch:(c,i)=>(r.push(JSON.parse(i?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=N({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,dropIfLapsed:()=>!1,doName:()=>g,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:c=>c}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(c,i,o)=>(e.push(o),c===h.name?{columns:["id"],effectiveWhere:{org:o?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:r,resolvedUnder:e}},p=async(s,r)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...r,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};b("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:r}=y();try{const{owner:e,resolvedUnder:t}=d(r.sql);await p(e,h),l(t.some(a=>a?.userId==="u1"&&a.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),b("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:r}=y();try{const{owner:e,posts:t}=d(r.sql);await p(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const a=t.filter(n=>n.type==="relay_shape_poke");l(a.length).toBe(1),l(a[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),b("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:r}=y();try{const{owner:e,posts:t}=d(r.sql);await p(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const a=t.filter(n=>n.type==="relay_shape_poke");l(a.length).toBe(1),l(a[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{W as defineEngineContractSuite};
@@ -0,0 +1 @@
1
+ import{LunoraError as u}from"@lunora/errors";import{WIRE_TAG as S,decodeWire as E,needsWireEncoding as A,encodeWire as T}from"@lunora/wire";import{sql as s}from"drizzle-orm";import{e as y}from"./effective-kind-BmG_zCAy.mjs";import{S as b,i as $,s as O,F as g}from"./json-field-path-DeJW4U9z.mjs";import{quoteIdentifier as j}from"./quoteIdentifier-CObIFRhb.mjs";import{runDrizzle as i}from"./runDrizzle-DAtZbzBn.mjs";import{sqlComparableProjection as L}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import"./serializeSqlValue-DeoBMpZ2.mjs";const I=/^[A-Za-z_$][\w$]*$/u,_=e=>I.test(e)?e:`"${e.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,f="__doc__",c="__originals__",z=e=>{if(Object.hasOwn(e,c))throw new u("BAD_REQUEST",`"${c}" is reserved by the row store's document encoding and cannot be used as a field name — rename the field`);let t,r;for(const[o,a]of Object.entries(e)){const d=L(a);d!==void 0&&(t??={...e},r??=Object.create(null),t[o]=d,r[o]=a)}t&&r&&(t[c]=r);const n=t??e;try{return A(n)?JSON.stringify(T(n)):JSON.stringify(n)}catch(o){throw new u("BAD_REQUEST",`this document cannot be stored: ${o instanceof Error?o.message:String(o)}`)}},w=e=>{const t=JSON.parse(e),r=e.includes(S)||e.includes(String.raw`\u`)?E(t):t,n=r[c];if(n===null||typeof n!="object"||Array.isArray(n))return r;const o={...r};return delete o[c],{...o,...n}},G=(e,t)=>`${e}__geo_${t}`,N=e=>{try{return O(e)}catch(t){throw t instanceof g?new u("VALIDATION_ERROR",t.message):t}},p=e=>`'$.${($(e)?N(e).map(r=>_(r)).join("."):_(e)).replaceAll("'","''")}'`,h=(e,t)=>t==="_id"||t==="id"?`${e}id`:t==="_creationTime"?`${e}_creationTime`:`json_extract(${e}${f}, ${p(t)})`,Q=e=>h("",e),K=(e,t)=>`NULLIF(json_type(${f}, ${p(e)}), 'null') IN (${b[t]})`,V=(e,t)=>h(`${j(e)}.`,t),k=(e,t)=>e===void 0||t!==0&&t!==1||y(e)!=="boolean"?t:t===1,m=new WeakMap,H=e=>{const t=m.get(e);if(t!==void 0)return t;const r=[];for(const[n,o]of Object.entries(e.shape)){const a=o._meta?.column;a&&r.push(Object.freeze([n,a]))}return Object.freeze(r),m.set(e,r),r},P=e=>{if(!e)return;const t=e[f];let r;typeof t=="string"?r=w(t):t&&typeof t=="object"?r=t:r={};const{id:n}=e;typeof n=="string"&&(r._id=n);const o=e._creationTime;return typeof o=="number"&&(r._creationTime=o),r},X=e=>{try{return P(e)}catch{return}},l=new WeakMap,R=Symbol("lunora.wrappedSql"),D=e=>e[R]??e,Y=(e,t)=>{const r=D(e),n=l.get(r);if(n!==void 0)return n;if(t!==void 0)try{return i(r,s`SELECT 1 FROM ${s.identifier(t)} LIMIT 0`).toArray(),l.set(r,!0),!0}catch{}let o;try{i(r,s`CREATE VIRTUAL TABLE IF NOT EXISTS ${s.identifier("__lunora_fts_probe")} USING fts5(x)`),o=!0}catch{o=!1}finally{try{i(r,s`DROP TABLE IF EXISTS ${s.identifier("__lunora_fts_probe")}`)}catch{}}return l.set(r,o),o};export{f as D,R as W,X as a,K as b,c,w as d,z as e,_ as f,G as g,k as h,Y as i,Q as j,V as q,P as r,H as t,D as u};
@@ -1 +1 @@
1
- import{toErrorBody as b}from"@lunora/errors";import{COMMIT_SEQ_FIELD as u}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";const y=200,_=(e,t)=>{const o=r=>{const s=e.tables[r];return s!==void 0&&s.shardMode?.kind!=="global"};return(t&&t.length>0?[...t]:Object.keys(e.tables)).filter(r=>o(r))},h=async function*(e,t,o=y){let r=null,s=!1;for(;!s;){const n=await e.findMany(t,{cursor:r,includeDeleted:!0,limit:o});for(const i of n.page)yield{doc:i,table:t};r=n.continueCursor,s=n.isDone||r===null}},W=async function*(e,t,o){const r=_(t,o.tables),s=o.batchSize??y;for(const n of r)yield*h(e,n,s)},E=new Set(["_creationTime","_id"]),R=(e,t)=>{for(const[o,r]of Object.entries(e.shape)){const s=t[o];if(s===void 0&&r.kind==="optional")continue;const n=r.parse;if(typeof n=="function")try{n(s)}catch(i){const a=i instanceof Error?i.message:String(i);return`field "${o}": ${a}`}}},A=(e,t,o)=>{const r=e.tables[t];if(!r)return`unknown table: ${t}`;if(r.shardMode?.kind==="global")return`table "${t}" is a global (.global()) table and is not importable through the shard import path`;const s=Object.fromEntries(Object.entries(o).filter(([n])=>!E.has(n)));for(const n of Object.keys(s))if(!Object.hasOwn(r.shape,n))return`unexpected field "${n}": not declared in table "${t}"`;return R(r,s)},k=async(e,t,o)=>{if(e.lookupById){const r=await e.lookupById(o);return r===null?void 0:r.tableName}return await e.get(t,o)===null?void 0:t},S=async(e,t,o)=>{try{return await k(e,t,o)}catch{return}},v=e=>u in e?Object.fromEntries(Object.entries(e).filter(([t])=>t!==u)):e,m=(e,t,o)=>{const{table:r}=t;if(typeof r!="string"||r.length===0)return{code:"BAD_ROW",line:o,message:"row is missing `table`",table:r};if(!t.doc||typeof t.doc!="object"||Array.isArray(t.doc))return{code:"BAD_ROW",line:o,message:"row is missing or malformed `doc`",table:r};const s=A(e,r,v(t.doc));return s===void 0?void 0:{code:"VALIDATION_ERROR",line:o,message:s,table:r}},g=(e,t,o)=>{const r=e.tables[t.table];return r===void 0?{code:"BAD_ROW",line:o,message:`unknown table: ${t.table}`,table:t.table}:r.shardMode?.kind==="global"?{code:"BAD_ROW",line:o,message:`table "${t.table}" is a global (.global()) table and is not importable through the shard import path`,table:t.table}:typeof t.doc?._id=="string"?void 0:{code:"BAD_ROW",line:o,message:"a delete row needs the `_id` to delete",table:t.table}},I=async(e,t,o,r)=>{const s=g(t,o,r);if(s!==void 0)return{error:s,kind:"error"};const n=o.doc._id;try{const i=await k(e,o.table,n);return i===void 0?{kind:"absent"}:i!==o.table?{error:{code:"ID_COLLISION",line:r,message:`_id "${n}" belongs to table "${i}", not "${o.table}"`,table:o.table},kind:"error"}:(await e.delete(o.table,n,{hard:!0,skipOnDelete:!0}),{kind:"deleted"})}catch(i){const{body:a}=b(i,{fallbackCode:"DELETE_FAILED"});return{error:{code:a.code,line:r,message:a.message,table:o.table},kind:"error"}}},D=async(e,t,o,r,s)=>{const n=m(t,o,r);if(n!==void 0)return{error:n,kind:"error"};const{table:i}=o,a=v(o.doc),l=typeof a._id=="string"?a._id:void 0,d=l===void 0?void 0:await S(e,i,l);if(d!==void 0&&d!==i)return{error:{code:"ID_COLLISION",line:r,message:`_id "${String(l)}" already belongs to table "${d}"`,table:i},kind:"error"};if(d===i&&l!==void 0){if(s!=="replace")return{kind:"conflict"};try{const c={...a};return delete c._id,await e.replace(i,l,c,{allowExplicitId:!0}),{kind:"replaced"}}catch(c){const{body:f}=b(c,{fallbackCode:"REPLACE_FAILED"});return{error:{code:f.code,line:r,message:f.message,table:i},kind:"error"}}}try{return await e.insert(i,a,{allowExplicitId:!0}),{kind:"inserted",table:i}}catch(c){const{body:f}=b(c,{fallbackCode:"INSERT_FAILED"});return{error:{code:f.code,line:r,message:f.message,table:i},kind:"error"}}},O=(e,t,o)=>e.op==="delete"?o?void 0:{code:"BAD_ROW",line:t,message:'a row with `op: "delete"` needs `deletes: true` on the import',table:e.table}:e.op===void 0?void 0:{code:"BAD_ROW",line:t,message:`row \`op\` must be "delete" when set, got ${JSON.stringify(e.op)}`,table:e.table},L=async(e,t,o)=>{const r={};for(const s of t){const n=[];for await(const{doc:i}of h(e,s)){const a=i._id;typeof a=="string"&&!o.has(a)&&n.push(a)}for(const i of n)await e.delete(s,i,{hard:!0});r[s]=n.length}return r},$=(e,t)=>e.has(t.table)?typeof t.doc?._id=="string"?void 0:"a replace import row must carry its `_id`":`table "${t.table}" is not in this replace import's tables`,C=async(e,t,o,r,s,n)=>{const i=O(o,r,n);return i!==void 0?{error:i,kind:"error"}:o.op==="delete"?I(e,t,o,r):D(e,t,o,r,s)},B=(e,t,o,r)=>{const s=n=>{e.inserted[n]=(e.inserted[n]??0)+1};switch(t.kind){case"absent":break;case"conflict":{e.conflicts+=1;break}case"deleted":{e.deleted+=1;break}case"error":{e.errors.push(t.error);break}case"replaced":{r?s(o):e.replaced+=1;break}default:s(t.table)}},T=(e,t)=>t?.filter(o=>{const r=e.tables[o];return r!==void 0&&r.shardMode?.kind!=="global"}),j=(e,t,o,r)=>O(t,o,r)??(t.op==="delete"?g(e,t,o):m(e,t,o)),F=async(e,t,o)=>{const r={conflicts:0,deleted:0,errors:[],inserted:{},replaced:0};let s=(o.startLine??1)-1;const n=T(t,o.replaceTables),i=new Set(n),a=n===void 0?o.onConflict??"skip":"replace";for(const d of o.rows){s+=1;const c=n===void 0?void 0:$(i,d);if(c!==void 0){r.errors.push({code:"BAD_ROW",line:s,message:c,table:d.table});continue}if(o.dryRun===!0){const p=j(t,d,s,o.deletes===!0);p!==void 0&&r.errors.push(p);continue}const f=await C(e,t,d,s,a,o.deletes===!0);B(r,f,d.table,n!==void 0)}if(n===void 0||o.keepIds===void 0||r.errors.length>0||o.dryRun===!0)return r;const l=new Set([...o.keepIds,...o.rows.flatMap(d=>d.op!=="delete"&&typeof d.doc._id=="string"?[d.doc._id]:[])]);return{...r,pruned:await L(e,n,l)}},N=e=>{const t=Array.isArray(e.tables)?e.tables.filter(r=>typeof r=="string"):void 0;return{batchSize:typeof e.batchSize=="number"?e.batchSize:void 0,tables:t}},w=e=>e===void 0?{}:{op:typeof e=="string"?e:JSON.stringify(e)},z=e=>{const t=Array.isArray(e.rows)?e.rows:[],o=[];for(const s of t){if(!s||typeof s!="object")continue;const n=s;if(typeof n.table!="string"||!n.doc||typeof n.doc!="object"||Array.isArray(n.doc)){o.push({doc:n.doc??{},table:typeof n.table=="string"?n.table:""});continue}o.push({doc:n.doc,...w(n.op),table:n.table})}const r=typeof e.startLine=="number"?e.startLine:void 0;return{deletes:e.deletes===!0,dryRun:e.dryRun===!0,onConflict:e.onConflict==="replace"?"replace":"skip",rows:o,startLine:r}};export{W as exportShardRows,F as importShardRows,N as parseExportShardArgs,z as parseImportShardArgs,$ as replaceRefusal,_ as selectExportTables,A as validateImportRow};
1
+ import{toErrorBody as b}from"@lunora/errors";import{COMMIT_SEQ_FIELD as u}from"./COMMIT_SEQ_FIELD-lEe6aaMv.mjs";const y=200,_=(e,t)=>{const o=r=>{const s=e.tables[r];return s!==void 0&&s.shardMode?.kind!=="global"};return(t&&t.length>0?[...t]:Object.keys(e.tables)).filter(r=>o(r))},h=async function*(e,t,o=y){let r=null,s=!1;for(;!s;){const n=await e.findMany(t,{cursor:r,includeDeleted:!0,limit:o});for(const i of n.page)yield{doc:i,table:t};r=n.continueCursor,s=n.isDone||r===null}},W=async function*(e,t,o){const r=_(t,o.tables),s=o.batchSize??y;for(const n of r)yield*h(e,n,s)},E=new Set(["_creationTime","_id"]),R=(e,t)=>{for(const[o,r]of Object.entries(e.shape)){const s=t[o];if(s===void 0&&r.kind==="optional")continue;const n=r.parse;if(typeof n=="function")try{n(s)}catch(i){const a=i instanceof Error?i.message:String(i);return`field "${o}": ${a}`}}},A=(e,t,o)=>{const r=e.tables[t];if(!r)return`unknown table: ${t}`;if(r.shardMode?.kind==="global")return`table "${t}" is a global (.global()) table and is not importable through the shard import path`;const s=Object.fromEntries(Object.entries(o).filter(([n])=>!E.has(n)));for(const n of Object.keys(s))if(!Object.hasOwn(r.shape,n))return`unexpected field "${n}": not declared in table "${t}"`;return R(r,s)},k=async(e,t,o)=>{if(e.lookupById){const r=await e.lookupById(o);return r===null?void 0:r.tableName}return await e.get(t,o)===null?void 0:t},S=async(e,t,o)=>{try{return await k(e,t,o)}catch{return}},v=e=>u in e?Object.fromEntries(Object.entries(e).filter(([t])=>t!==u)):e,m=(e,t,o)=>{const{table:r}=t;if(typeof r!="string"||r.length===0)return{code:"BAD_ROW",line:o,message:"row is missing `table`",table:r};if(!t.doc||typeof t.doc!="object"||Array.isArray(t.doc))return{code:"BAD_ROW",line:o,message:"row is missing or malformed `doc`",table:r};const s=A(e,r,v(t.doc));return s===void 0?void 0:{code:"VALIDATION_ERROR",line:o,message:s,table:r}},g=(e,t,o)=>{const r=e.tables[t.table];return r===void 0?{code:"BAD_ROW",line:o,message:`unknown table: ${t.table}`,table:t.table}:r.shardMode?.kind==="global"?{code:"BAD_ROW",line:o,message:`table "${t.table}" is a global (.global()) table and is not importable through the shard import path`,table:t.table}:typeof t.doc?._id=="string"?void 0:{code:"BAD_ROW",line:o,message:"a delete row needs the `_id` to delete",table:t.table}},I=async(e,t,o,r)=>{const s=g(t,o,r);if(s!==void 0)return{error:s,kind:"error"};const n=o.doc._id;try{const i=await k(e,o.table,n);return i===void 0?{kind:"absent"}:i!==o.table?{error:{code:"ID_COLLISION",line:r,message:`_id "${n}" belongs to table "${i}", not "${o.table}"`,table:o.table},kind:"error"}:(await e.delete(o.table,n,{hard:!0,skipOnDelete:!0}),{kind:"deleted"})}catch(i){const{body:a}=b(i,{fallbackCode:"DELETE_FAILED"});return{error:{code:a.code,line:r,message:a.message,table:o.table},kind:"error"}}},D=async(e,t,o,r,s)=>{const n=m(t,o,r);if(n!==void 0)return{error:n,kind:"error"};const{table:i}=o,a=v(o.doc),l=typeof a._id=="string"?a._id:void 0,d=l===void 0?void 0:await S(e,i,l);if(d!==void 0&&d!==i)return{error:{code:"ID_COLLISION",line:r,message:`_id "${String(l)}" already belongs to table "${d}"`,table:i},kind:"error"};if(d===i&&l!==void 0){if(s!=="replace")return{kind:"conflict"};try{const c={...a};return delete c._id,await e.replace(i,l,c,{allowExplicitId:!0}),{kind:"replaced"}}catch(c){const{body:f}=b(c,{fallbackCode:"REPLACE_FAILED"});return{error:{code:f.code,line:r,message:f.message,table:i},kind:"error"}}}try{return await e.insert(i,a,{allowExplicitId:!0}),{kind:"inserted",table:i}}catch(c){const{body:f}=b(c,{fallbackCode:"INSERT_FAILED"});return{error:{code:f.code,line:r,message:f.message,table:i},kind:"error"}}},O=(e,t,o)=>e.op==="delete"?o?void 0:{code:"BAD_ROW",line:t,message:'a row with `op: "delete"` needs `deletes: true` on the import',table:e.table}:e.op===void 0?void 0:{code:"BAD_ROW",line:t,message:`row \`op\` must be "delete" when set, got ${JSON.stringify(e.op)}`,table:e.table},L=async(e,t,o)=>{const r={};for(const s of t){const n=[];for await(const{doc:i}of h(e,s)){const a=i._id;typeof a=="string"&&!o.has(a)&&n.push(a)}for(const i of n)await e.delete(s,i,{hard:!0});r[s]=n.length}return r},$=(e,t)=>e.has(t.table)?typeof t.doc?._id=="string"?void 0:"a replace import row must carry its `_id`":`table "${t.table}" is not in this replace import's tables`,C=async(e,t,o,r,s,n)=>{const i=O(o,r,n);return i!==void 0?{error:i,kind:"error"}:o.op==="delete"?I(e,t,o,r):D(e,t,o,r,s)},B=(e,t,o,r)=>{const s=n=>{e.inserted[n]=(e.inserted[n]??0)+1};switch(t.kind){case"absent":break;case"conflict":{e.conflicts+=1;break}case"deleted":{e.deleted+=1;break}case"error":{e.errors.push(t.error);break}case"replaced":{r?s(o):e.replaced+=1;break}default:s(t.table)}},T=(e,t)=>t?.filter(o=>{const r=e.tables[o];return r!==void 0&&r.shardMode?.kind!=="global"}),j=(e,t,o,r)=>O(t,o,r)??(t.op==="delete"?g(e,t,o):m(e,t,o)),F=async(e,t,o)=>{const r={conflicts:0,deleted:0,errors:[],inserted:{},replaced:0};let s=(o.startLine??1)-1;const n=T(t,o.replaceTables),i=new Set(n),a=n===void 0?o.onConflict??"skip":"replace";for(const d of o.rows){s+=1;const c=n===void 0?void 0:$(i,d);if(c!==void 0){r.errors.push({code:"BAD_ROW",line:s,message:c,table:d.table});continue}if(o.dryRun===!0){const p=j(t,d,s,o.deletes===!0);p!==void 0&&r.errors.push(p);continue}const f=await C(e,t,d,s,a,o.deletes===!0);B(r,f,d.table,n!==void 0)}if(n===void 0||o.keepIds===void 0||r.errors.length>0||o.dryRun===!0)return r;const l=new Set([...o.keepIds,...o.rows.flatMap(d=>d.op!=="delete"&&typeof d.doc._id=="string"?[d.doc._id]:[])]);return{...r,pruned:await L(e,n,l)}},N=e=>{const t=Array.isArray(e.tables)?e.tables.filter(r=>typeof r=="string"):void 0;return{batchSize:typeof e.batchSize=="number"?e.batchSize:void 0,tables:t}},w=e=>e===void 0?{}:{op:typeof e=="string"?e:JSON.stringify(e)},z=e=>{const t=Array.isArray(e.rows)?e.rows:[],o=[];for(const s of t){if(!s||typeof s!="object")continue;const n=s;if(typeof n.table!="string"||!n.doc||typeof n.doc!="object"||Array.isArray(n.doc)){o.push({doc:n.doc??{},table:typeof n.table=="string"?n.table:""});continue}o.push({doc:n.doc,...w(n.op),table:n.table})}const r=typeof e.startLine=="number"?e.startLine:void 0;return{deletes:e.deletes===!0,dryRun:e.dryRun===!0,onConflict:e.onConflict==="replace"?"replace":"skip",rows:o,startLine:r}};export{W as exportShardRows,F as importShardRows,N as parseExportShardArgs,z as parseImportShardArgs,$ as replaceRefusal,_ as selectExportTables,A as validateImportRow};
@@ -0,0 +1 @@
1
+ import{q as L}from"./MAX_TOKEN_LENGTH-iFEGEcDL-DBPC6ZWl.mjs";import{sql as e}from"drizzle-orm";import{sqliteInList as o}from"./param-Y0zw_1Cv.mjs";import{ftsRowidMapName as n}from"./ftsRowidMapName-CGnFBC6P.mjs";const A=(i,t)=>{if(!t.includes("."))return i[t];let r=i;for(const f of t.split(".")){if(r===null||typeof r!="object"||Array.isArray(r))return;r=r[f]}return r},a=(i,t)=>`${i}__fts_${t}`,N="__text__",d="__id__",O=1e3,u=(i,t)=>t.document(i),S=(i,t)=>A(i,t),_=i=>typeof i=="string"?i:i==null?"":typeof i=="number"||typeof i=="bigint"||typeof i=="boolean"?String(i):JSON.stringify(i)??"",w=(i,t,r)=>i!==void 0&&t!==void 0&&S(i,r.field)===S(t,r.field),l=(i,t)=>u(_(S(i,t.field)),L(t.language)).slice(0,O),F=(i,t)=>l(i,t).join(" "),c=50,T="__rowid__",E=(i,t)=>e`${e.identifier(i)}.${e.identifier(t)}`,I=(i,t,{guard:r,unmappedRowids:f})=>{const $=n(i),s=r===void 0?e``:e` AND ${r}`,R=f===void 0?e`${E(i,"rowid")} > 0`:o(E(i,"rowid"),f,!1,c);return[e`DELETE FROM ${e.identifier(i)} WHERE ${R} AND CAST(${E(i,d)} AS TEXT) = ${t}${s}`,e`DELETE FROM ${e.identifier(i)} WHERE ${E(i,"rowid")} = (SELECT ${E($,T)} FROM ${e.identifier($)} WHERE ${E($,d)} = ${t}) AND ${E(i,d)} = ${t}${s}`]},U=i=>[e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(i)} USING fts5(${e.identifier(N)}, ${e.identifier(d)} UNINDEXED)`,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${i}__vocab`)} USING fts5vocab(${e.identifier(i)}, ${e.raw("instance")})`,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n(i))} (${e.identifier(T)} INTEGER PRIMARY KEY, ${e.identifier(d)} TEXT NOT NULL UNIQUE)`,e`INSERT INTO ${e.identifier(i)} (rowid, ${e.identifier(N)}, ${e.identifier(d)}) SELECT 0, '', '' WHERE NOT EXISTS (SELECT 1 FROM ${e.identifier(i)} WHERE ${E(i,"rowid")} = 0)`],W=(i,t,r,f={})=>{const $=n(i),s=f.guard===void 0?e``:e` AND ${f.guard}`,R=e`MIN(COALESCE((SELECT MIN(${E($,T)}) FROM ${e.identifier($)}), 0), 0) - 1`;return[...I(i,t,f),e`INSERT OR REPLACE INTO ${e.identifier($)} (${e.identifier(T)}, ${e.identifier(d)}) SELECT ${R}, ${t} WHERE 1 = 1${s}`,e`INSERT OR REPLACE INTO ${e.identifier(i)} (rowid, ${e.identifier(N)}, ${e.identifier(d)}) SELECT ${E($,T)}, ${r}, ${E($,d)} FROM ${e.identifier($)} WHERE ${E($,d)} = ${t}${s}`]},y=(i,t,r={})=>{const f=n(i),$=r.guard===void 0?e``:e` AND ${r.guard}`;return[...I(i,t,r),e`DELETE FROM ${e.identifier(f)} WHERE ${E(f,d)} = ${t}${$}`]},H=(i,t,r=0)=>e`SELECT ${E(i,"rowid")} AS ${e.identifier("rowid")}, ${E(i,d)} AS ${e.identifier("id")} FROM ${e.identifier(i)} WHERE ${E(i,"rowid")} > ${e.param(Math.max(0,r))} AND ${E(i,d)} IS NOT NULL ORDER BY ${E(i,"rowid")} ASC LIMIT ${e.raw(String(t))}`;export{w as N,a as S,y as a,H as b,W as c,F as d,U as f,d as l,l as s};
@@ -0,0 +1 @@
1
+ import{f as e,a as m,b as f,c as p}from"./fts-companion-Cfz-hJum.mjs";import"./param-Y0zw_1Cv.mjs";import"./ftsRowidMapName-CGnFBC6P.mjs";export{e as ftsCompanionDdl,m as ftsPurgeDocument,f as ftsUnmappedPage,p as ftsWriteDocument};
@@ -0,0 +1 @@
1
+ const s=o=>`${o}__ids`,e=o=>{const t=new Map;for(const n of o){const r=String(n.id);t.set(r,[...t.get(r)??[],Number(n.rowid)])}return t};export{s as ftsRowidMapName,e as groupUnmappedRows};
@@ -1,4 +1,4 @@
1
- import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-RC09zZrh.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-gZqs4Rsj.mjs";const p="__lunora_source_cursor",M=e=>e instanceof Date?`d:${e.toISOString()}`:typeof e=="bigint"?`b:${e.toString()}`:typeof e=="number"?`n:${e.toString()}`:`s:${e}`,v=e=>{const t=e.slice(2);switch(e[0]){case"b":return BigInt(t);case"d":return new Date(t);case"n":return Number(t);default:return t}},h=/^-?\d+$/,N=/^-?\d+(?:\.\d+)?$/,x=(e,t)=>e instanceof Date&&t instanceof Date?e.getTime()>t.getTime():typeof e=="bigint"&&typeof t=="bigint"||typeof e=="number"&&typeof t=="number"?e>t:typeof e=="string"&&typeof t=="string"&&N.test(e)&&N.test(t)?h.test(e)&&h.test(t)?BigInt(e)>BigInt(t):Number(e)>Number(t):String(e)>String(t),O=(e,t,o)=>{let n=o===null?void 0:v(o);for(const r of e){const c=r[t];if(c==null)continue;const a=c;(n===void 0||x(a,n))&&(n=a)}return n===void 0?null:M(n)},B=e=>{S(e,m`CREATE TABLE IF NOT EXISTS ${m.identifier(p)} (
1
+ import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-DAtZbzBn.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-LugivbOG.mjs";const p="__lunora_source_cursor",M=e=>e instanceof Date?`d:${e.toISOString()}`:typeof e=="bigint"?`b:${e.toString()}`:typeof e=="number"?`n:${e.toString()}`:`s:${e}`,v=e=>{const t=e.slice(2);switch(e[0]){case"b":return BigInt(t);case"d":return new Date(t);case"n":return Number(t);default:return t}},h=/^-?\d+$/,N=/^-?\d+(?:\.\d+)?$/,x=(e,t)=>e instanceof Date&&t instanceof Date?e.getTime()>t.getTime():typeof e=="bigint"&&typeof t=="bigint"||typeof e=="number"&&typeof t=="number"?e>t:typeof e=="string"&&typeof t=="string"&&N.test(e)&&N.test(t)?h.test(e)&&h.test(t)?BigInt(e)>BigInt(t):Number(e)>Number(t):String(e)>String(t),O=(e,t,o)=>{let n=o===null?void 0:v(o);for(const r of e){const c=r[t];if(c==null)continue;const a=c;(n===void 0||x(a,n))&&(n=a)}return n===void 0?null:M(n)},B=e=>{S(e,m`CREATE TABLE IF NOT EXISTS ${m.identifier(p)} (
2
2
  table_name TEXT NOT NULL,
3
3
  shard_key TEXT NOT NULL,
4
4
  watermark TEXT,
@@ -0,0 +1 @@
1
+ import{sql as t}from"drizzle-orm";import{runDrizzle as l}from"./runDrizzle-DAtZbzBn.mjs";import{jsonPathSql as d}from"./AGG_COUNT-DzvM-UU5.mjs";const s=(o,e)=>{const i=e-(o.after??0),r=[t`${d(o.field)} IS NOT NULL`,t`${d(o.field)} < ${i}`];return o.softDeleteField!==void 0&&r.push(t`${d(o.softDeleteField)} IS NULL`),r},L=(o,e,i,r)=>{const n=t`SELECT id FROM ${t.identifier(e.table)} WHERE ${t.join(s(e,i),t` AND `)} LIMIT ${t.raw(String(Math.max(0,Math.floor(r))+1))}`,f=l(o,n).toArray(),a=f.length>r,E=f.slice(0,r).map($=>$.id);return{hasMore:a,ids:E}},S=(o,e,i,r)=>{const n=t`SELECT 1 AS hit FROM ${t.identifier(e.table)} WHERE id = ${i} AND ${t.join(s(e,r),t` AND `)}`;return l(o,n).toArray().length>0},c=(o,e)=>{const i=e.softDeleteField===void 0?t``:t` WHERE ${d(e.softDeleteField)} IS NULL`,r=t`SELECT MIN(${d(e.field)}) AS expiry FROM ${t.identifier(e.table)}${i}`,n=l(o,r).toArray()[0]?.expiry;return typeof n=="number"?n+(e.after??0):void 0};export{S as isTtlExpired,c as nextTtlExpiry,L as selectExpiredIds};
@@ -1 +1 @@
1
- import{applyCdcChanges as p}from"./CDC_LOG_TABLE-fCPCjSE4.mjs";import{selectShapeRows as m}from"./selectShapeMembers-Ce6pOHKe.mjs";import{diffExternalSource as g,projectExternalSourceRow as l}from"./diffExternalSource-B0FZlDoL.mjs";import{stableStringify as d}from"@lunora/wire";const x=async(t,s,a,e)=>{const{changes:o,nextBaseline:n}=g(s,a,e);return await p(t,o),{applied:o.length,nextBaseline:n}},R=async(t,s,a)=>{const{columns:e,deletedIds:o,table:n}=a,r=[];for(const f of s){const i=l(f,e),c=String(i._id);if(o?.has(c)){await t.get(n,c)&&r.push({id:c,op:"delete",seq:0,table:n,ts:0});continue}const u=await t.get(n,c);u&&d(l({...u,_id:c},e))===d(i)||r.push({doc:i,id:c,op:"insert",seq:0,table:n,ts:0})}return await p(t,r),{applied:r.length}},h=(t,s,a)=>{const e=new Map;for(const{doc:o,id:n}of m(t,s,void 0))e.set(n,d(l({...o,_id:n},a)));return e},_=async(t,s,a,e)=>{const o=h(t,e.table,e.columns);return x(s,a,o,e)};export{x as materializeExternalRows,R as materializeExternalRowsIncremental,h as readExternalSourceBaseline,_ as runExternalSourceTick};
1
+ import{applyCdcChanges as p}from"./CDC_LOG_TABLE-DchHJJ5G.mjs";import{selectShapeRows as m}from"./selectShapeMembers-BP30uxpp.mjs";import{diffExternalSource as g,projectExternalSourceRow as l}from"./diffExternalSource-B0FZlDoL.mjs";import{stableStringify as d}from"@lunora/wire";const x=async(t,s,a,e)=>{const{changes:o,nextBaseline:n}=g(s,a,e);return await p(t,o),{applied:o.length,nextBaseline:n}},R=async(t,s,a)=>{const{columns:e,deletedIds:o,table:n}=a,r=[];for(const f of s){const i=l(f,e),c=String(i._id);if(o?.has(c)){await t.get(n,c)&&r.push({id:c,op:"delete",seq:0,table:n,ts:0});continue}const u=await t.get(n,c);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};