@lunora/shard-engine 1.0.0-alpha.18 → 1.0.0-alpha.180
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/conformance/index.mjs +1 -1
- package/dist/index.d.mts +916 -188
- package/dist/index.d.ts +916 -188
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/ADMIN_FUNCTIONS-CgMPqUvK.mjs +1 -0
- package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs +1 -0
- package/dist/packem_shared/AGG_COUNT-BkqKHbcG.mjs +1 -0
- package/dist/packem_shared/AUDIT_LOG_TABLE-BFJ65SRS.mjs +8 -0
- package/dist/packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs +1 -0
- package/dist/packem_shared/CDC_LOG_TABLE-CTkXVeJx.mjs +18 -0
- package/dist/packem_shared/CLIENT_WATERMARK_TABLE-De7z_OHV.mjs +7 -0
- package/dist/packem_shared/COMMIT_SEQ_FIELD-Da1DjGqo.mjs +4 -0
- package/dist/packem_shared/CURSOR_PREFIX-6offuG6M.mjs +1 -0
- package/dist/packem_shared/CompanionMemo-BXU5vfak.mjs +1 -0
- package/dist/packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs +1 -0
- package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-CFvBS9-M.mjs +31 -0
- package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-DQkJExDV.mjs +1 -0
- package/dist/packem_shared/DEFAULT_MAX_RELAYS-B66neS_B.mjs +8 -0
- package/dist/packem_shared/DEFAULT_PROMOTION_THRESHOLDS-VU44O5kq.mjs +1 -0
- package/dist/packem_shared/DEFAULT_TRANSACTION_LIMITS-Dmj5VBrV.mjs +1 -0
- package/dist/packem_shared/DurableStreamRunner-MMlV5qKQ.mjs +1 -0
- package/dist/packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs +1 -0
- package/dist/packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs +7 -0
- package/dist/packem_shared/GlobalPollTick-BNK4o-XT.mjs +1 -0
- package/dist/packem_shared/IDEMPOTENCY_TABLE-COrgeP3O.mjs +7 -0
- package/dist/packem_shared/MAIL_RETENTION-DMolrLYt.mjs +18 -0
- package/dist/packem_shared/MAX_SQL_ROWS-eRignWyO.mjs +4 -0
- package/dist/packem_shared/MAX_TOKEN_LENGTH-iFEGEcDL-DBPC6ZWl.mjs +1 -0
- package/dist/packem_shared/NotUniqueError-Dn6Cj7W1.mjs +1 -0
- package/dist/packem_shared/QUEUE_TABLE-C-goXtGd.mjs +17 -0
- package/dist/packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs +1 -0
- package/dist/packem_shared/REACTOR_STATE_TABLE-D2Mn204f.mjs +28 -0
- package/dist/packem_shared/RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs +1 -0
- package/dist/packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs +1 -0
- package/dist/packem_shared/RELAY_SIGNATURE_HEADER-DP0glzE_.mjs +1 -0
- package/dist/packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs +1 -0
- package/dist/packem_shared/RLS_UNWRAP_SYMBOL-H6J96vgK.mjs +1 -0
- package/dist/packem_shared/ReactiveCache-Cy7oH_7w.mjs +1 -0
- package/dist/packem_shared/SCAN_DEP-D7qE3iUe.mjs +1 -0
- package/dist/packem_shared/SCHEDULE_OUTBOX_TABLE-DcZI7Yhl.mjs +11 -0
- package/dist/packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs +6 -0
- package/dist/packem_shared/SEARCH_STATE_TABLE-D7w8mRsm.mjs +1 -0
- package/dist/packem_shared/SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs +8 -0
- package/dist/packem_shared/ShapeDiffCache-iNO-hUiy.mjs +1 -0
- package/dist/packem_shared/ShardRunner-CrveaPId.mjs +1 -0
- package/dist/packem_shared/UNVOUCHABLE_DEP-Ds9gxVqs.mjs +1 -0
- package/dist/packem_shared/VECTOR_BACKFILL_MAX_PAGES-UY0toTIR.mjs +1 -0
- package/dist/packem_shared/WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs +1 -0
- package/dist/packem_shared/accepts-null-D1zmJbyR.mjs +1 -0
- package/dist/packem_shared/aggregateTableName-B_CtIQCS.mjs +1 -0
- package/dist/packem_shared/appendStreamChunk-BZYgGE9Y.mjs +17 -0
- package/dist/packem_shared/applyInsertDefaults-BJo578fn.mjs +1 -0
- package/dist/packem_shared/archiveCdcSegment-Cr8oGLfB.mjs +4 -0
- package/dist/packem_shared/{armRestore-BNzdvQ_o.mjs → armRestore-Bu1_8SUa.mjs} +1 -1
- package/dist/packem_shared/assertPatchAllowed-CA_H466g.mjs +1 -0
- package/dist/packem_shared/awaitWsDrain-DMcWBQ7I.mjs +1 -0
- package/dist/packem_shared/backfillAggregateIndexes-CRNxxM19.mjs +1 -0
- package/dist/packem_shared/buildIndexRange-BTChxh3k.mjs +1 -0
- package/dist/packem_shared/buildPokeFrames-WR-hp0mX.mjs +1 -0
- package/dist/packem_shared/buildReprojectionMigration-DAh1inpL.mjs +1 -0
- package/dist/packem_shared/buildSettings-BRkZd6_E.mjs +1 -0
- package/dist/packem_shared/buildShapeDiff-CCpH5fNc.mjs +1 -0
- package/dist/packem_shared/clearMemoryTables-aMRERF0w.mjs +1 -0
- package/dist/packem_shared/compileWhereSql-TgKZIvWM.mjs +1 -0
- package/dist/packem_shared/computeRankPage-BZIpATcs.mjs +1 -0
- package/dist/packem_shared/createCompanionSync-qhvw6wyL.mjs +1 -0
- package/dist/packem_shared/createReplicaLink-D0YNQDzD.mjs +7 -0
- package/dist/packem_shared/createSystemReader-BSCxr8Qs.mjs +1 -0
- package/dist/packem_shared/ctx-db-relay-shapes-DBobAek2.mjs +17 -0
- package/dist/packem_shared/ctx-db-search-state-CPKPy8N6.mjs +1 -0
- package/dist/packem_shared/defineEngineContractSuite-DKON0Z5G.mjs +1 -0
- package/dist/packem_shared/describeRelationWrites-omar6-u9.mjs +1 -0
- package/dist/packem_shared/diffExternalSource-B0FZlDoL.mjs +1 -0
- package/dist/packem_shared/do-sql-RROYQPCM.mjs +1 -0
- package/dist/packem_shared/effective-kind-BmG_zCAy.mjs +1 -0
- package/dist/packem_shared/envOptionalPositiveInt-D2pY-c64.mjs +1 -0
- package/dist/packem_shared/estimate-bytes-_k74s6LZ.mjs +1 -0
- package/dist/packem_shared/exportShardRows-CZh4wrvI.mjs +1 -0
- package/dist/packem_shared/fts-companion-CE3EmIjk.mjs +1 -0
- package/dist/packem_shared/ftsCompanionDdl-B0bFCy6d.mjs +1 -0
- package/dist/packem_shared/hasTrigger-CjlwI4le.mjs +1 -0
- package/dist/packem_shared/isInternalTableName-BoljO2tP.mjs +1 -0
- package/dist/packem_shared/isPushableWhere-BeYAOjUb.mjs +1 -0
- package/dist/packem_shared/isSoftDeleted-QCy5JKnY.mjs +9 -0
- package/dist/packem_shared/isTtlExpired-BmiUp7MF.mjs +1 -0
- package/dist/packem_shared/json-field-path-DeJW4U9z.mjs +1 -0
- package/dist/packem_shared/liftSourceId-CA3ENhXj.mjs +1 -0
- package/dist/packem_shared/materializeExternalRows-BakYlgvb.mjs +1 -0
- package/dist/packem_shared/mergeChangedKeys-DPKhen6e.mjs +1 -0
- package/dist/packem_shared/relation-operators-BEg-CvCH.mjs +1 -0
- package/dist/packem_shared/relay-CKEdfUjH.mjs +1 -0
- package/dist/packem_shared/runDrizzle-RC09zZrh.mjs +1 -0
- package/dist/packem_shared/runShardMigrations-DOiPunti.mjs +5 -0
- package/dist/packem_shared/runSocketPool-CZJ2X9cF.mjs +1 -0
- package/dist/packem_shared/selectShapeMembers-BhK79123.mjs +1 -0
- package/dist/packem_shared/serializeSqlValue-DeoBMpZ2.mjs +1 -0
- package/dist/packem_shared/stubByName-B8cFYipA.mjs +1 -0
- package/dist/packem_shared/where-sql-BjY4rnqb.mjs +1 -0
- package/package.json +5 -4
- package/dist/packem_shared/ADMIN_FUNCTIONS-OnYxyTXW.mjs +0 -1
- package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs +0 -1
- package/dist/packem_shared/AGG_COUNT-CqQLWpb4.mjs +0 -1
- package/dist/packem_shared/AUDIT_LOG_TABLE-C6nwXFPd.mjs +0 -8
- package/dist/packem_shared/CDC_LOG_TABLE-ZqcflEen.mjs +0 -8
- package/dist/packem_shared/CLIENT_WATERMARK_TABLE-CzApRlyv.mjs +0 -7
- package/dist/packem_shared/CountRlsUnsupportedError-8BqPYQoP.mjs +0 -1
- package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-BrpAGtXf.mjs +0 -31
- package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-sPcXaWFW.mjs +0 -1
- package/dist/packem_shared/DEFAULT_MAX_RELAYS-CPBmX1FO.mjs +0 -1
- package/dist/packem_shared/DEFAULT_PROMOTION_THRESHOLDS-B2rUe1bg.mjs +0 -1
- package/dist/packem_shared/DEFAULT_TRANSACTION_LIMITS-q7ouI3i0.mjs +0 -1
- package/dist/packem_shared/GEO_DEFAULT_PRECISION-DyI5zggj.mjs +0 -1
- package/dist/packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-soMJDSBs.mjs +0 -7
- package/dist/packem_shared/IDEMPOTENCY_TABLE-Bvu9JkiL.mjs +0 -7
- package/dist/packem_shared/MAIL_RETENTION-BefR9Sei.mjs +0 -18
- package/dist/packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs +0 -2
- package/dist/packem_shared/NotUniqueError-BItFDsAw.mjs +0 -1
- package/dist/packem_shared/QUEUE_TABLE-DgBqWrXX.mjs +0 -17
- package/dist/packem_shared/RANK_TIEBREAK-DYDRmLKH.mjs +0 -1
- package/dist/packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs +0 -1
- package/dist/packem_shared/REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs +0 -1
- package/dist/packem_shared/RLS_UNWRAP_SYMBOL-DcqORh2s.mjs +0 -1
- package/dist/packem_shared/ReactiveCache-Cu8IfE1M.mjs +0 -1
- package/dist/packem_shared/SCAN_DEP-D_yR9EeV.mjs +0 -1
- package/dist/packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BEU0CuW5.mjs +0 -6
- package/dist/packem_shared/SEARCH_STATE_TABLE-BZ_fxI5l.mjs +0 -1
- package/dist/packem_shared/ShardRunner-DIqVdWtk.mjs +0 -1
- package/dist/packem_shared/aggregateTableName-DV-K7ft2.mjs +0 -1
- package/dist/packem_shared/applyOnDelete-BB6tr2G0.mjs +0 -1
- package/dist/packem_shared/applySelect-i17LYhIU.mjs +0 -1
- package/dist/packem_shared/awaitWsDrain-Bp2jKzIb.mjs +0 -1
- package/dist/packem_shared/backfillAggregateIndexes-tK0jrl43.mjs +0 -1
- package/dist/packem_shared/base64-fKomMf5D.mjs +0 -1
- package/dist/packem_shared/buildIndexRange-DFsdtPjD.mjs +0 -1
- package/dist/packem_shared/buildPokeFrames-CqxaN8_H.mjs +0 -1
- package/dist/packem_shared/buildReprojectionMigration-Ctl4r84d.mjs +0 -1
- package/dist/packem_shared/buildSettings-COIJsw7a.mjs +0 -1
- package/dist/packem_shared/compileWhereSql-B4rPariq.mjs +0 -1
- package/dist/packem_shared/computeRankPage-CRFgJbuz.mjs +0 -1
- package/dist/packem_shared/createCompanionSync-Gp-AesYj.mjs +0 -1
- package/dist/packem_shared/createReadFootprint-DIrrxRTE.mjs +0 -1
- package/dist/packem_shared/createSystemReader-DcDcrtM3.mjs +0 -1
- package/dist/packem_shared/ctx-db-companions-CAJOSdN-.mjs +0 -1
- package/dist/packem_shared/defineEngineContractSuite-CZccUN4c.mjs +0 -1
- package/dist/packem_shared/diffExternalSource-DMpkJta1.mjs +0 -1
- package/dist/packem_shared/do-sql-1Yi1_Yq0.mjs +0 -1
- package/dist/packem_shared/estimate-bytes-Drp8rhPs.mjs +0 -1
- package/dist/packem_shared/exportShardRows-Bbi_JGfn.mjs +0 -1
- package/dist/packem_shared/hasTrigger-CbkOHExZ.mjs +0 -1
- package/dist/packem_shared/isSoftDeleted-Bo-y3DOe.mjs +0 -9
- package/dist/packem_shared/liftSourceId-DApAbu7Q.mjs +0 -1
- package/dist/packem_shared/materializeExternalRows-DcCENzpV.mjs +0 -1
- package/dist/packem_shared/mergeChangedKeys-BXtUgIPW.mjs +0 -1
- package/dist/packem_shared/param-B5lF5Jd9.mjs +0 -1
- package/dist/packem_shared/runDrizzle-B6rnz3so.mjs +0 -1
- package/dist/packem_shared/runShardMigrations-n2dKcH5E.mjs +0 -5
- package/dist/packem_shared/runSocketPool-DPQLVyWF.mjs +0 -1
- package/dist/packem_shared/selectExpiredIds-C6nQK7E2.mjs +0 -1
- package/dist/packem_shared/selectShapeMemberIds-BdBcbrUP.mjs +0 -1
- package/dist/packem_shared/serializeSqlValue-BR4UOWoP.mjs +0 -1
- package/dist/packem_shared/sql-projection-jfoe331H.mjs +0 -1
- package/dist/packem_shared/stableStringify-BjLh4gvA.mjs +0 -1
- package/dist/packem_shared/stableWireKey-l3cjIt-9.mjs +0 -1
- package/dist/packem_shared/wire-codec-Dsy70M3Q.mjs +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as y}from"@lunora/errors";import{q as yt}from"./MAX_TOKEN_LENGTH-iFEGEcDL-DBPC6ZWl.mjs";import{S as Dn,l as We,s as kn}from"./fts-companion-CE3EmIjk.mjs";import{decodeWire as Ln,stableWireKey as qt}from"@lunora/wire";import{sql as a}from"drizzle-orm";import{throwingScheduler as Fn,aggregateSqlFunction as Be,normalizeCountArgument as qn}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as rt,encodeAggregateKey as it,readAggregateValue as st}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as K,CountRlsUnsupportedError as ct,selectIndexForGroupBy as Wn,selectIndexForCount as Bn,selectIndexForAggregate as Pn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Un,searchIndexCoversTable as On}from"./backfillAggregateIndexes-CRNxxM19.mjs";import{backfillAggregateIndexes as $i,backfillRankIndexes as Ei,backfillSearchIndexes as mi}from"./backfillAggregateIndexes-CRNxxM19.mjs";import{appendCdcChange as Hn,readCdcDocAtOrBefore as Gn}from"./CDC_LOG_TABLE-CTkXVeJx.mjs";import{CDC_LOG_TABLE as Ti,applyCdcChanges as Ri,bumpCdcEpoch as _i,cdcCanVouchFor as vi,cdcForkedError as Ii,cdcSeqLeavingRows as Ai,cdcTouchesTables as xi,cdcTrimmedError as Ci,compactCdcDocs as bi,cursorBelowRetainedFloor as Mi,minCdcReplayableSeq as Di,minCdcSeq as ki,readCdcChangeKeys as Li,readCdcChanges as Fi,readCdcCursor as qi,readCdcEpoch as Wi,trimCdcChanges as Bi}from"./CDC_LOG_TABLE-CTkXVeJx.mjs";import{allocateCommitSeq as jn,COMMIT_SEQ_FIELD as Kn}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{createCompanionSync as Nn}from"./createCompanionSync-qhvw6wyL.mjs";import{isMemoryTable as Wt}from"./clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as Bt}from"./computeRankPage-BZIpATcs.mjs";import{SCAN_DEP as H}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as we,runDrizzle as j}from"./runDrizzle-RC09zZrh.mjs";import{p as Qn,j as ft,D as oe,r as Ie,k as ue,b as Pe,A as at,a as Ue,m as fe,e as he,s as Vn,t as Jn,i as zn,q as Pt,h as fn,g as Yn}from"./do-sql-RROYQPCM.mjs";import{renderSql as hn,unionAll as wn,WORKERD_SQLITE_LIMITS as pn}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{coveringGeohashes as Xn,boundingBoxGeohashes as Zn,haversineMeters as eo,pointInBoundingBox as to}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as no}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as oo,assertPatchAllowed as ro,operatorFields as io,readPatchField as Ut}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as so,encodeCursor as Ne,nullsOrderSuffix as co,normalizeOrderKeys as Ot,uniqueIndexFields as ao,buildSeekWhere as lo,decodeCursor as Ht,buildSeekBeforeWhere as uo,softDeleteScope as ve,applySelect as Gt}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as jt,sortColumnName as Kt,resolveRankPartition as fo,encodePartitionKey as ho,RANK_TIEBREAK as wo,rankPivotConditionSql as po}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{UNVOUCHABLE_DEP as Nt}from"./UNVOUCHABLE_DEP-Ds9gxVqs.mjs";import{idIndexKey as go,withUnknownIndexKeys as yo,indexKeysForRow as $o,buildIndexRange as Eo}from"./buildIndexRange-BTChxh3k.mjs";import{r as Qe,j as Ae,c as X,t as Je,i as Qt}from"./where-sql-BjY4rnqb.mjs";import{serializeSqlValue as xe}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as Ce}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as mo,isPushableWhere as So}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as To,findRelated as Ro}from"./RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{assertFlatPredicate as dt,resolveRelationPredicates as _o,composeReadPredicate as vo}from"./DEFAULT_MAX_RELATION_KEYS-DQkJExDV.mjs";import{describeRelationWrites as Io}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as Oe,transformOnlyDefinition as Ao,applyInsertDefaults as ht,resolveWith as Vt,relationHooks as Jt,applyOnDelete as xo,fanOutScalarCounts as Co}from"./applyInsertDefaults-BJo578fn.mjs";import{guardWriter as bo}from"./RLS_UNWRAP_SYMBOL-H6J96vgK.mjs";import{mayHoldProjectedValue as Mo}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as Do}from"./createSystemReader-BSCxr8Qs.mjs";import{ConflictError as ce}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as zt,runTriggers as ko}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as Ui,migrateClientWatermark as Oi,readClientWatermark as Hi}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{IDEMPOTENCY_TABLE as ji,readIdempotent as Ki,trimIdempotent as Ni,writeIdempotent as Qi}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{runShardMigrations as Ji}from"./runShardMigrations-DOiPunti.mjs";import{selectShapeMembers as Yi,selectShapeRows as Xi}from"./selectShapeMembers-BhK79123.mjs";const Lo=n=>{const i=atob(n),o=Uint8Array.from(i,c=>c.codePointAt(0)??0);return new TextDecoder().decode(o)},Fo=()=>new y("BAD_REQUEST","invalid cursor"),Yt=16,Xt=8,J=1024,$t=(n,i)=>i.query(n),qo=(n,i)=>{if(n.length===0)return 0;let o=0;for(const[c,s]of i.entries()){const w=c===i.length-1;let m=0;for(const S of n)(w?S.startsWith(s):S===s)&&(m+=1);if(m===0)return 0;o+=m}return o},Wo=(n,i)=>{if(!i)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",c=(o.codePointAt(0)??0)+1;if(c>=55296&&c<=57343||c>1114111)return{exact:!0,lower:n,upper:n};const s=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:s+String.fromCodePoint(c)}},Bo=(n,i,o)=>{const c={eq:(s,w)=>{if(!n.definition.filterFields?.includes(s))throw new y("INTERNAL",`field "${s}" is not a filter field of search index "${n.indexName}" on table "${i}"`);if(n.filters.length>=Xt)throw new y("BAD_REQUEST",`search index "${n.indexName}" on table "${i}": at most ${String(Xt)} .eq() filters are supported per search query`);return n.filters.push({field:s,value:w}),c},search:(s,w)=>{const m=n;if(s!==m.definition.field)throw new y("INTERNAL",`search index "${m.indexName}" on table "${i}" indexes "${m.definition.field}", not "${s}"`);const S=$t(w,o).length;if(S>Yt)throw new y("BAD_REQUEST",`search index "${m.indexName}" on table "${i}": at most ${String(Yt)} search terms are supported (got ${String(S)})`);return m.field=s,m.query=w,m.hasQuery=!0,c}};return c},Po=n=>{if(n.length>J)throw new y("BAD_REQUEST",`more than ${String(J)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Uo=n=>Math.min(n.offset+n.numItems+1,J),Oo=n=>btoa(`search:${String(n)}`),Ho=n=>{let i;try{i=Lo(n)}catch{return}if(!i.startsWith("search:"))return;const o=Number(i.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},Go=n=>{if(typeof n.endCursor=="string")throw new y("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new y("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const i=Math.max(0,Math.floor(n.numItems)),o=n.cursor?Ho(n.cursor):0;if(o===void 0)throw Fo();if(o+i>=J)throw new y("BAD_REQUEST",`search pagination reaches the ${String(J)}-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,J-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:i,offset:o}},jo=(n,i)=>{const o=i.offset+i.numItems,c=i.numItems>0&&n.length>o;return{continueCursor:c?Oo(o):null,isDone:!c,page:n.slice(i.offset,o)}},Ko=n=>{if(n===void 0)return J+1;if(!Number.isFinite(n))return J;const i=Math.max(0,Math.floor(n));if(i>J)throw new y("BAD_REQUEST",`search returns at most ${String(J)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},gn=500,yn=(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??gn},$n=(n,i,o,c)=>{if(n>i)throw c(`${o}: batch of ${String(n)} exceeds the limit of ${String(i)} (raise options.limit or chunk the call)`)},No=32,Qo=1024,En=(n,i,o,c)=>{const s=`SELECT id, _creationTime, ${Ce(oe)} FROM ${Ce(n)}`,w=`ORDER BY ${o}${c===void 0?"":` LIMIT ${String(c)}`}`;return i===void 0?Qe(`${s} ${w}`):Ae(`${s} WHERE `,i,` ${w}`)},ze={fieldRef:n=>Qe(ft(n)),rangeTypeGuard:(n,i)=>Qe(Qn(n,i)),serialize:xe},Vo=n=>n===void 0?"":co(n==="first"),mn=n=>{const i=n.map(o=>`${ft(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${Vo(o.nulls)}`);return n.some(o=>o.field==="_id"||o.field==="id")||i.push(`${ft("id")} ${so(n)==="desc"?"DESC":"ASC"}`),i.join(", ")},Jo={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},Sn=n=>new Set(n.sqlConditions.filter(i=>i.comparator==="=").map(i=>i.field)),zo=n=>{const i=Sn(n);let o=0;for(;o<n.indexFields.length&&i.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},Yo=(n,i)=>{const o=n.order,c=zo(n),{shape:s}=i;return c.length>0?Ot(c.map(w=>({[w]:o})),s,{pinned:Sn(n),uniqueBy:ao(i.indexes,s)}):Ot([{_creationTime:o}],s)},Xo=(n,i,o,c)=>{const s=n.sqlConditions.map(w=>({[w.field]:{[Jo[w.comparator]??"eq"]:w.value}}));if(o&&s.push(lo(i,Ht(o))),c&&s.push(uo(i,Ht(c))),s.length!==0)return s.length===1?s[0]:{AND:s}},Zo=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,No):n.want},wt=(n,i,o,c,s,w,m)=>{const S=Yo(c,o),I=mn(S),$=[],{filters:F,want:C}=w;let A=w.cursor??void 0,D=Zo(w);if(C===0)return{documents:$,orderKeys:S};for(;;){const P=X(Xo(c,S,A,w.endCursor),ze,Je),q=En(i,s&&P?Ae(P," AND ",s):s??P,I,D),k=we(n,q.text,...q.params).toArray();let W={};m(k.length);for(const O of k)if(W=Ie(O),F.every(ge=>ge(W))&&$.push(W)===C)return{documents:$,orderKeys:S};if(D===void 0||k.length<D)return{documents:$,orderKeys:S};A=Ne(W,S),D=Math.max(D,Math.min(D*2,Qo))}},er=(n,i,o,c,s,w,m,S)=>{const I=Math.max(0,Math.floor(s.numItems));if(typeof s.endCursor=="string"){const{documents:P,orderKeys:q}=wt(n,i,o,c,w,{cursor:s.cursor,endCursor:s.endCursor,filters:m.all,selective:m.selective,want:void 0},S),k=P.length>=2?P[Math.floor(P.length/2)-1]:void 0;return{continueCursor:s.endCursor,isDone:!0,page:P,splitCursor:k?Ne(k,q):null}}const{documents:$,orderKeys:F}=wt(n,i,o,c,w,{cursor:s.cursor,filters:m.all,selective:m.selective,want:I+1},S),C=$.length>I,A=C?$.slice(0,I):$,D=A.at(-1);return{continueCursor:C&&D?Ne(D,F):null,isDone:!C,page:A}},Ye=n=>{const i=new Map;return o=>{const c=i.get(o);if(c!==void 0)return c;const s=n(Ce(o));return i.set(o,s),s}},pe=Ce(oe),tr=Ye(n=>`INSERT INTO ${n} (id, _creationTime, ${pe}) VALUES (?, ?, ?)`),Zt=Ye(n=>`UPDATE ${n} SET ${pe} = ? WHERE id = ? AND ${pe} = ?`),nr=Ye(n=>`UPDATE ${n} SET _creationTime = ?, ${pe} = ? WHERE id = ? AND ${pe} = ?`),or=Ye(n=>`DELETE FROM ${n} WHERE id = ? AND ${pe} = ?`),rr="SELECT changes() AS changed",en=new Map,ir="",sr=n=>{const i=JSON.stringify(n),o=en.get(i);if(o!==void 0)return o;const c=n.map(w=>a`SELECT ${a.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${a.identifier(oe)} FROM ${a.identifier(w)} WHERE id = ${ir}`),{sql:s}=hn("sqlite",a`${wn(c)} LIMIT 1`);return en.set(i,s),s},cr=(n,i)=>i.map(()=>n),ar=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,dr=n=>{if(!ar.test(n))throw new y("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},pt=n=>{if(n.includes("\0"))throw new y("BAD_REQUEST",`invalid row id ${JSON.stringify(n)}: a row id cannot hold a NUL character (U+0000)`)},lr=(n,i,o,c)=>{if(o!==!0)return;const s=n!==void 0&&"serverDefault"in(n.shape._id?._meta?.column??{});for(const w of i){const m=s?ht(n,w,c)._id:w._id;typeof m=="string"&&pt(m)}},tn=50,He=Math.floor(pn.boundParams/3),nn=pn.boundParams,ur=128,Ve=n=>new y("BATCH_LIMIT_EXCEEDED",n,{status:400}),Ge=(n,i,o)=>{$n(n,yn(i,o,Ve),o,Ve)},on=async(n,i,o,c,s)=>{const w=yn(c,s,Ve),{page:m}=await n.findMany(i,Number.isFinite(w)?{limit:w+1,omitContinueCursor:!0,where:o}:{where:o});return m.length>w&&$n(Math.max(await n.count(i,{where:o}),m.length),w,s,Ve),m},fr=n=>{const i={eq:(o,c)=>(n.sqlConditions.push({comparator:"=",field:o,value:c}),i),gt:(o,c)=>(n.sqlConditions.push({comparator:">",field:o,value:c}),i),gte:(o,c)=>(n.sqlConditions.push({comparator:">=",field:o,value:c}),i),lt:(o,c)=>(n.sqlConditions.push({comparator:"<",field:o,value:c}),i),lte:(o,c)=>(n.sqlConditions.push({comparator:"<=",field:o,value:c}),i)};return i},hr=n=>Math.max(n,J),Tn=(n,i)=>{const o=n.filters.map(c=>a`${he(c.field)} = ${xe(c.value)}`);return i&&o.push(i),o},wr=(n,i,o,c,s)=>{const w=$t(o.query,yt(o.definition.language));if(w.length===0)return[];const m=Dn(i,o.indexName),S=`${m}__vocab`,I=w.length-1,$=w.map((q,k)=>{const W=Wo(q,k===I),O=W.exact?a`${a.identifier("term")} = ${W.lower}`:a`${a.identifier("term")} >= ${W.lower} AND ${a.identifier("term")} < ${W.upper}`;return a`SELECT ${a.identifier("doc")}, ${a.raw(String(k))} AS ${a.identifier("__term__")}, COUNT(*) AS ${a.identifier("__n__")} FROM ${a.identifier(S)} WHERE ${O} GROUP BY ${a.identifier("doc")}`}),F=w.map((q,k)=>a`SUM(CASE WHEN u.${a.identifier("__term__")} = ${a.raw(String(k))} THEN u.${a.identifier("__n__")} ELSE 0 END)`),C=a`SELECT f.${a.identifier(We)} AS ${a.identifier(We)}, ${a.join(F,a` + `)} AS ${a.identifier("__score__")} FROM (${wn($)}) u JOIN ${a.identifier(m)} f ON f.rowid = u.${a.identifier("doc")} GROUP BY f.${a.identifier(We)} HAVING ${a.join(F.map(q=>a`${q} > 0`),a` AND `)}`,A=Tn(o,s);let D=a`SELECT m.id, m._creationTime, m.${a.identifier(oe)}, s.${a.identifier("__score__")} AS ${a.identifier("__score__")} FROM (${C}) s JOIN ${a.identifier(i)} m ON m.id = s.${a.identifier(We)}`;A.length>0&&(D=a`${D} WHERE ${a.join(A,a` AND `)}`),D=a`${D} ORDER BY s.${a.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${a.raw(String(c))}`;const P=[];for(const q of j(n,D)){const k=fn(q);if(k){const W=q.__score__;P.push({document:k,score:typeof W=="number"?W:Number(W??0)})}}return P},pr=(n,i,o,c,s)=>{const w=yt(o.definition.language),m=$t(o.query,w);if(m.length===0)return[];const S=Tn(o,s);let I=a`SELECT id, _creationTime, ${a.identifier(oe)} FROM ${a.identifier(i)}`;S.length>0&&(I=a`${I} WHERE ${a.join(S,a` AND `)}`),I=a`${I} ORDER BY _creationTime DESC, id ASC LIMIT ${a.raw(String(hr(c)))}`;const $=j(n,I).toArray(),F=[];for(const C of $){const A=fn(C);if(!A)continue;const D=qo(kn(A,o.definition),m);D>0&&F.push({creationTime:typeof A._creationTime=="number"?A._creationTime:0,doc:A,id:typeof A._id=="string"?A._id:"",score:D})}return F.sort((C,A)=>A.score-C.score||A.creationTime-C.creationTime||C.id.localeCompare(A.id)),F.slice(0,c).map(C=>({document:C.doc,score:C.score}))},lt=(n,i,o,c)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new y("BAD_REQUEST",`geo index "${c}" on table "${o}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},gr=(n,i)=>{const o=n,c={near:(s,w)=>{if(o.within)throw new y("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(lt(s,".near() point",i,o.indexName),!Number.isFinite(w)||w<=0)throw new y("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return o.near={point:{lat:s.lat,lng:s.lng},radiusMeters:w},c},within:s=>{if(o.near)throw new y("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(lt(s.sw,".within() sw corner",i,o.indexName),lt(s.ne,".within() ne corner",i,o.indexName),s.sw.lat>s.ne.lat)throw new y("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(s.sw.lng>s.ne.lng)throw new y("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:s.ne.lat,lng:s.ne.lng},sw:{lat:s.sw.lat,lng:s.sw.lng}},c}};return c},yr=(n,i)=>{const o=n[i];if(o===null||typeof o!="object")return;const{lat:c,lng:s}=o;return typeof c=="number"&&typeof s=="number"?{lat:c,lng:s}:void 0},$r=(n,i)=>{const o=yr(n,i.definition.field);if(!o)return;const c=typeof n._creationTime=="number"?n._creationTime:0;if(i.near){const s=eo(i.near.point,o);return s<=i.near.radiusMeters?{creationTime:c,distance:s}:void 0}return to(o,i.within)?{creationTime:c,distance:0}:void 0},Er=(n,i,o,c)=>{if(!o.near&&!o.within)throw new y("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const s=o.near?Xn(o.near.point,o.near.radiusMeters):Zn(o.within),w=Yn(i,o.indexName),m=s.map(C=>a`(g.${a.identifier("__geohash__")} >= ${C} AND g.${a.identifier("__geohash__")} < ${`${C}{`})`),S=[a`(${a.join(m,a` OR `)})`];c&&S.push(c);const I=a`SELECT m.id, m._creationTime, m.${a.identifier(oe)} FROM ${a.identifier(w)} g JOIN ${a.identifier(i)} m ON m.id = g.${a.identifier("__id__")} WHERE ${a.join(S,a` AND `)}`,$=j(n,I).toArray(),F=[];for(const C of $){const A=Ie(C),D=A?$r(A,o):void 0;A&&D&&F.push({creationTime:D.creationTime,distance:D.distance,doc:A})}return F.sort((C,A)=>C.distance-A.distance||A.creationTime-C.creationTime),F},Rn=(n,i,o,c)=>{const s=[];for(const w of n)if(i.every(m=>m(c(w)))&&(s.push(w),typeof o=="number"&&s.length>=o))break;return s},mr=(n,i,o,c,s,w=()=>{})=>{const m=o.within!==void 0,S=Er(n,i,o,s).map(I=>({distanceMeters:m?null:I.distance,document:I.doc}));return w(S.length),typeof c=="number"?S.slice(0,Math.max(0,Math.floor(c))):S},rn=(n,i,o,c,s,w,m=()=>{})=>{const{geo:S}=o;if(!S)throw new y("INTERNAL","runGeoTerminalScored called without a staged geo query");const I=s.length>0,$=mr(n,i,S,I?void 0:w,c,m);return I?Rn($,s,w,F=>F.document):$},sn=(n,i,o)=>{const c=n.shape[i];if(c!==void 0&&Mo(c))throw new y("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)`)},Sr=n=>{let i=0;const o=[],c={...ze,relationExists:s=>{const{childWhere:w,negated:m,parentTable:S,relation:I}=s,$=`__rel_${String(i)}`,F=o.at(-1)??S;i+=1,n(I.table,H);const C=I.kind==="one"?I.field:I.references,A=I.kind==="one"?I.references:I.field,D=Qe(`${Pt($,A)} = ${Pt(F,C)}`);o.push($);const P=X(w,c,Je);o.pop();const q=P===void 0?D:Ae(D," AND ",P),k=Ae("EXISTS (SELECT 1 FROM ",Qt(I.table)," AS ",Qt($)," WHERE ",q,")");return m?Ae("NOT ",k):k}};return c};class Tr extends y{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const Rr=/\s/u,_r=String.fromCodePoint(0),cn=(n,i,o)=>{if(!n.tables[i])throw new y("INTERNAL",`unknown table: ${i}`);return typeof o!="string"||o.length===0||Rr.test(o)||o.includes(_r)?null:o},_n=(n,i,o,c=()=>{},s=()=>{},w=()=>{},m)=>{const S=i.tables[o];if(!S)throw new y("INTERNAL",`unknown table: ${o}`);const I=ve(S.softDeleteMode,void 0),$=m??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},F=()=>{const E=K(I,$.pushedWhere);return E?X(E,fe):void 0},C=()=>{const E=K(I,$.pushedWhere);return E?X(E,ze,Je):void 0},A=()=>[...$.inMemoryFilters,...$.verifyFilters];let D=0;const P=E=>{const{search:M}=$;if(!M)throw new y("INTERNAL","runSearchFetch called without a staged search");Un(n,o,S);const L=$.inMemoryFilters.length>0,R=Ko(L?void 0:E),Z=zn(n);if(Z&&!On(n,o,M.definition))throw new y("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 re=F(),ie=Z?wr(n,o,M,R,re):pr(n,o,M,R,re);!L&&E===void 0&&Po(ie);const Q=A();return D=ie.length,Q.length>0?Rn(ie,Q,E,se=>se.document):ie},q=E=>P(E).map(M=>M.document),k=E=>{const M=Go(E);return jo(q(Uo(M)),M)},W=()=>{if($.search||$.geo||$.indexName===void 0){s(void 0);return}s(Eo(o,$.indexName,$.indexFields,$.sqlConditions,xe))},O=E=>{W();let M=0;const L=(()=>{if($.search){const R=q(E);return M=D,R}return $.geo?rn(n,o,$,F(),A(),E,R=>{M=R}).map(R=>R.document):wt(n,o,S,$,C(),{filters:A(),selective:$.inMemoryFilters.length>0,want:E===void 0?void 0:Math.max(0,Math.floor(E))},R=>{M+=R}).documents})();return w(Math.max(M,L.length)),L},ge=()=>{if(!$.search&&!$.geo)throw new y("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);W();let E=0;const M=(()=>{if($.search){const L=P(void 0);return E=D,L}return rn(n,o,$,F(),A(),void 0,L=>{E=L})})();return w(Math.max(E,M.length)),M},N={async*[Symbol.asyncIterator](){const E=_n(n,i,o,c,s,w,{...$,indexFields:[...$.indexFields],inMemoryFilters:[...$.inMemoryFilters],sqlConditions:[...$.sqlConditions],verifyFilters:[...$.verifyFilters]});if($.search){yield*await E.collect();return}let M;for(;;){const L=await E.paginate({cursor:M??null,numItems:ur});if(yield*L.page,L.isDone||L.continueCursor===null)return;M=L.continueCursor}},async collect(){return O(void 0)},async collectWithScores(){return ge()},filter(E){const M=mo(E);return M!==void 0&&So(M,S.shape)?($.pushedWhere=K($.pushedWhere,M),$.verifyFilters.push(E)):$.inMemoryFilters.push(E),N},async first(){return O(1)[0]??null},order(E){return $.order=E==="desc"?"desc":"asc",N},async paginate(E){let M=0;if(W(),$.search){const R=k(E);return w(R.page.length),R}if($.geo)throw new y("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const L=er(n,o,S,$,E,C(),{all:A(),selective:$.inMemoryFilters.length>0},R=>{M+=R});return w(Math.max(M,L.page.length)),L},async take(E){return O(E)},async unique(){const E=O(2);if(E.length>1)throw new Tr(`unique() on table "${o}" matched ${String(E.length)} documents; expected at most one`);return E[0]??null},withGeoIndex(E,M){const L=(S.geoIndexes??[]).find(Z=>Z.name===E);if(!L)throw new y("INTERNAL",`unknown geo index "${E}" on table "${o}"`);c(o,E,"geo");const R={definition:L,indexName:E};if($.geo=R,M(gr(R,o)),!R.near&&!R.within)throw new y("INTERNAL",`geo index "${E}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return N},withIndex(E,M){const L=S.indexes.find(R=>R.name===E);if(!L)throw new y("INTERNAL",`unknown index "${E}" on table "${o}"`);return c(o,E,"index"),$.indexName=E,$.indexFields=L.fields,M&&M(fr($)),N},withSearchIndex(E,M){const L=(S.searchIndexes??[]).find(Z=>Z.name===E);if(!L)throw new y("INTERNAL",`unknown search index "${E}" on table "${o}"`);c(o,E,"search");const R={definition:L,field:L.field,filters:[],hasQuery:!1,indexName:E,query:""};if($.search=R,M(Bo(R,o,yt(L.language))),!R.hasQuery)throw new y("INTERNAL",`search index "${E}" on table "${o}" requires a .search(field, query) call`);return N}};return N},ut=(n,i,o,c)=>{const s=o;for(const[w,m]of Jn(n)){if(m.serverDefault){w in i&&(s[w]=m.serverDefault({auth:c}));continue}m.onUpdateFn&&!(w in i)&&(s[w]=m.onUpdateFn())}},an=5,dn=(n,i)=>{for(const o of Object.keys(i))if(i[o]===void 0)throw new y("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},ln=["_commitSeq","_creationTime","_id"],je=n=>ln.some(i=>i in n)?Object.fromEntries(Object.entries(n).filter(([i])=>!ln.includes(i))):n,vr=/unique constraint failed/i,Ir=n=>n instanceof Error&&vr.test(n.message),Ar=/string or blob too big/iu,xr=(n,i)=>{if(!(!(n instanceof Error)||!Ar.test(n.message)))throw new y("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.`)},gt=(n,i,o,c)=>{try{we(n,o,...c)}catch(s){throw Ir(s)?new ce(`unique constraint violation on "${i}"`,"unique"):(xr(s,i),s)}},Ke=(n,i,o,c)=>{if(gt(n,i,o,c),we(n,rr).one().changed===0)throw new ce(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},un=(n,i,o,c,s,w,m)=>{const S=[];for(let C=0;C<o.length+1;C+=1){const A=o[C],D=c[C],P=D?.direction==="desc"?"desc":"asc",q=A===void 0||D===void 0?a`${a.identifier(wo)} < ${m}`:po(A,w[C],P,!1);if(q===void 0)continue;const k=[];for(let O=0;O<C;O+=1)k.push(a`${a.identifier(o[O])} IS ${w[O]}`);k.push(q);const[W]=k;S.push(k.length===1&&W!==void 0?W:a`(${a.join(k,a` AND `)})`)}const I=S.length>0?a.join(S,a` OR `):a`1 = 0`,$=j(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(i)} WHERE ${a.identifier("__partition__")} = ${s} AND (${I})`).one(),F=j(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(i)} WHERE ${a.identifier("__partition__")} = ${s}`).one();return{before:$.c,total:F.c}},Cr=n=>{const i=new Map;for(const[c,s]of Object.entries(n.tables))for(const w of Object.values(s.relationMap??{}))w.kind==="one"&&(w.onDelete==="cascade"||w.onDelete==="set null")&&i.set(w.table,[...i.get(w.table)??[],{holder:c,op:w.onDelete==="cascade"?"delete":"update"}]);const o=c=>{const s=new Set,w=[c];for(let m=w.pop();m!==void 0;m=w.pop())for(const{holder:S,op:I}of i.get(m)??[]){if(S===c||zt(n,S,I))return!0;s.has(S)||(s.add(S),w.push(S))}return!1};return new Set(Object.entries(n.tables).filter(([c,s])=>s.shardMode?.kind==="global"||zt(n,c,"delete")||o(c)).map(([c])=>c))},br=n=>{const i=new Map;for(const[o,c]of Object.entries(n.tables))c.softDeleteMode&&i.set(o,c.softDeleteMode.field);return i},pi=n=>{const{baselineSeq:i,onStalePatchDropped:o}=n,{sql:c}=n,{schema:s}=n,w=n.broadcast??(()=>{}),m=(e,t)=>{if(!Object.hasOwn(s.tables,e))throw new y("BAD_REQUEST",`${t}: "${e}" is not a table in this schema`)},S=To(s),I=new Map;for(const e of S){const t=r=>(s.tables[r]?.shardMode?.kind??"root")==="root";!e.array&&t(e.sourceTable)&&t(e.targetTable)&&I.set(e.sourceTable,[...I.get(e.sourceTable)??[],e])}const $=(e,t,r)=>{for(const d of I.get(e)??[]){const f=t[d.column];if(typeof f!="string"||r?.[d.column]===f||d.targetTable===e&&t._id===f)continue;if(j(c,a`SELECT 1 FROM ${a.identifier(d.targetTable)} WHERE id = ${f} LIMIT 1`).toArray().length===0)throw new y("VALIDATION_ERROR",`${d.name} references ${d.targetTable} row "${f}", which does not exist`)}},F=Io(s,n.inTransaction),C=Cr(s),A=br(s);let D;const P=()=>n.inTransaction?.()===!0,q=e=>s.tables[e]?.commitOrderedMode!==!0?{}:((D===void 0||!P())&&(D=jn(c)),{[Kn]:D}),k=(e,...t)=>{const r=s.tables[e]?.indexes??[],d=[];let f;for(const h of t)h&&(typeof h._id=="string"&&h._id!==f&&(f=h._id,d.push(go(f))),d.push(...yo(r,$o(r,h,xe))));return d.length>0?d:void 0},{headroom:W}=n;let O=!1;const ge=async e=>{const t=O;O=!0;try{return await e()}finally{O=t}},N=n.onRead??(()=>{}),E=e=>{Wt(s.tables[e])&&N(Nt,Nt)},M=n.onReadRange??(e=>{N(e.table,H)}),L=e=>{E(e.table),M(e)},R=(e,t,r)=>{t!==void 0&&t!==H&&!O&&W?.recordRead(1),E(e),N(e,t,r)},Z=(e,t)=>{const r=e.row._id;R(e.tableName,typeof r=="string"?r:t,typeof r=="string")},re=n.onIndexUse??(()=>{}),ie=n.onWrite??(()=>{}),Q=e=>{O||W?.recordWrite(e)},se=async e=>{Q(e.doc),await ie(e)},{cache:ye}=n,$e=n.clock??(()=>Date.now()),Et=n.idGenerator??(()=>crypto.randomUUID()),mt=n.scheduler??Fn,{globalDb:Ee}=n,ae=n.auth??{identity:null,userId:null},St=n.cdc??!1,Xe=mt,vn=Do({scheduler:typeof Xe.list=="function"&&typeof Xe.get=="function"?Xe:void 0,storage:n.storage}),me=(e,t,r,d)=>{St&&!Wt(s.tables[e])&&Hn(c,$e(),e,t,r,d)},Tt=(e,t,r,d)=>{const f=s.tables[e];if(f?.dropStalePatchesMode!==!0||!St)return!1;const h=i?.();if(h===void 0)return!1;const l=Gn(c,e,t,h);if(l===void 0)return!1;const u=io(f,r);return Object.keys(je(r)).some(p=>!u.has(p)&&qt(Ut(l,p))!==qt(Ut(d,p)))},de=e=>s.tables[e]?.shardMode?.kind==="global",Rt=(e,t)=>{if(de(e)){if(!Ee)throw new y("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return Ee}return U},Ze=e=>Rt(e,"cascade"),G=(e,t)=>{if(de(e)){if(!Ee)throw new y("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return Ee}},_t=async(e,t,r,d,f)=>{f&&Q(r);const h=await e.insert(t,r,d);return w({key:h,op:"insert",row:{...r,_id:h},table:t}),h},et=(e,t)=>Rt(e,"relation load").findMany(e,t),vt=(e,t)=>(de(e)&&R(e,H),et(e,t)),In=e=>!de(e.table),It=n.relationExistsPushDown??"auto",At=It!=="never",{maxRelationKeys:xt}=n,be=(e,t,r)=>_o(e,{fetcher:vt,maxRelationKeys:xt,relationBaseWhere:r,schema:s,tableName:t}),Ct=async(e,t,r,d)=>{const f=G(e,"relation grouped count");if(f)return R(e,H),Co((g,B)=>f.count(g,B),e,t,r,d);const h=s.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);R(e,H);const l=ve(h.softDeleteMode,void 0),u={[t]:{in:r}},p=K(K(u,d),l),T=await be(p,e,void 0),x=X(T,fe),_=he(t);let v=a`SELECT ${_} AS __fk__, COUNT(*) AS count FROM ${a.identifier(e)}`;x&&(v=a`${v} WHERE ${x}`),v=a`${v} GROUP BY ${_}`;const b=j(c,v).toArray();return new Map(b.map(g=>[g.__fk__,g.count]))};let Me=0;const bt=new Set;for(const[e,t]of Object.entries(s.tables))for(const r of Object.values(t.triggerMap??{}))bt.add(`${e} ${r.timing} ${r.op}`);const ee=(e,t,r)=>bt.has(`${e} ${t} ${r}`),te=async(e,t,r)=>{if(Me+=1,Me>tn)throw Me-=1,new ce(`trigger recursion exceeded ${String(tn)} levels on "${r.table}" — check for a self-triggering write`,"trigger");try{await ko({ctx:bn,event:r,op:t,schema:s,tableName:r.table,timing:e})}finally{Me-=1}},{ensureBackfilledForTable:Se,ensureBackfilledIndex:tt,ensureRankBackfilled:nt,ensureRankBackfilledForTable:Te,syncAggregates:De,syncCompanionsForInsert:Mt,syncGeo:ke,syncRanks:Re,syncSearch:Le}=Nn({broadcast:w,indexKeysFor:(e,t)=>k(e,t),invalidateCache:(e,t,r)=>ye?.invalidate(e,t,k(e,r)),recordCdc:me,schema:s,sql:c,verified:n.companionMemo?.verified}),Dt=(e,t,r)=>{const{shardMode:d}=t;if(d?.kind==="shardBy"&&!(d.field!==void 0&&(r.partitionBy??[]).includes(d.field)))throw Object.assign(new Error(`rank index "${r.name}" on "${e}" partitions across shards (shard key "${d.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})},kt=e=>Object.entries(s.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),_e=e=>e===void 0||de(e)?Ee:void 0,ot=async(e,t,r,d,f)=>{for(let h=0;h<r.length;h+=1)Q(void 0);if(f!==void 0&&e.deleteMany!==void 0)return e.deleteMany(t,r,f.options);for(const h of r)await e.delete(t,h,d);return{deleted:r.length}},ne=(e,t)=>{const r=kt(t);for(let d=0;d<r.length;d+=nn){const f=r.slice(d,d+nn),[h]=we(c,sr(f),...cr(e,f)).toArray();if(!h)continue;const l=h.__t__,u=Ie(h);if(typeof l!="string"||!u)return;const p=h[oe];return{docJson:typeof p=="string"?p:ue(p??{}),row:u,tableName:l}}},Lt={assertRankPartitionLocal:Dt,ensureRankBackfilled:nt,onRead:R,rowToDocument:Ie,schema:s,sql:c},An=(e,t,r)=>{const d=X(r,fe);return d===void 0||j(c,a`SELECT 1 FROM ${a.identifier(e)} WHERE ${a.identifier("id")} = ${t} AND ${d}`).toArray().length>0},xn=(e,t,r,d)=>Tt(e,t,r,d)?(o?.({fields:Object.keys(je(r)),id:t,table:e}),!0):!1,Cn=async(e,t,r,d,f)=>{const h=ne(t,e);if(!h)return{applied:!1,doc:null};if(R(e,t),!An(e,t,r.where)||xn(e,t,r.patch,h.row))return{applied:!1,doc:h.row};try{await f(r.patch)}catch(l){if(l instanceof ce&&l.kind==="occ"&&d)return;throw l}return{applied:!0,doc:ne(t,e)?.row??null}},Ft=async(e,t,r,d)=>{const{fetchLimit:f,limit:h,orderKeys:l,predicate:u}=await vo(t,r,{canPushExists:At?In:void 0,existsPushMode:It==="always"?"always":"auto",fetcher:vt,maxRelationKeys:xt,schema:s,tableName:e}),p=At?Sr(d):ze,T=X(u,p,Je),x=En(e,T,mn(l),f);return{limit:h,orderKeys:l,statement:x}},U={system:vn,async aggregate(e,t){const r=G(e,"aggregate");if(r)return R(e,H),r.aggregate(e,t);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);if(Be(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 y("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);R(e,H);const f=ve(d.softDeleteMode,void 0),h=K(K(t.baseWhere,t.where),f),l=await be(h,e,t.relationBaseWhere),u=l!==h;if(d.aggregateIndexes&&!t.baseWhere&&!u){const g=Pn(d.aggregateIndexes,t.op,t.field,t.where);if(g){tt(e,g.index);const B=it(g.index.by??[],g.key),z=rt(e,g.index.name),Y=j(c,a`SELECT ${Pe} AS value, ${at} AS count FROM ${a.identifier(z)} WHERE ${Ue} = ${B}`).toArray()[0];return st(t.op,Y)}}sn(d,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const p=X(l,fe),T=Be(t.op),x=he(t.field);let _=a`SELECT ${a.raw(T)}(${x}) AS value FROM ${a.identifier(e)}`;p&&(_=a`${_} WHERE ${p}`);const b=j(c,_).toArray()[0]?.value;return b??null},asId(e,t){const r=cn(s,e,t);if(r===null)throw new y("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return r},async count(e,t){const r=G(e,"count");if(r)return R(e,H),r.count(e,t);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);const f=qn(t);if(f.restrictsCounts)throw new ct(e);R(e,H);const h=ve(d.softDeleteMode,void 0),l=K(K(f.baseWhere,f.where),h),u=await be(l,e,f.relationBaseWhere),p=u!==l;if(d.aggregateIndexes&&!f.baseWhere&&!p){const v=Bn(d.aggregateIndexes,f.where);if(v){tt(e,v.index);const b=it(v.index.by??[],v.key),g=rt(e,v.index.name),B=j(c,a`SELECT ${Pe} AS value FROM ${a.identifier(g)} WHERE ${Ue} = ${b}`).toArray();return B[0]===void 0?0:B[0].value??0}}const T=X(u,fe);let x=a`SELECT COUNT(*) AS count FROM ${a.identifier(e)}`;return T&&(x=a`${x} WHERE ${T}`),j(c,x).one().count},async delete(e,t,r){m(e,"ctx.db.delete(table, id)");const d=ne(t,e);if(!d){const v=_e(e);v&&await ot(v,e,[t],r);return}const{docJson:f,row:h,tableName:l}=d,u=s.tables[l],p=r?.hard===!0,T=!p&&u?.softDeleteMode?u:void 0,x=T?.softDeleteMode?.field;if(x&&h[x]!==null&&h[x]!==void 0)return;if(ee(l,"before","delete")&&await te("before","delete",{id:t,op:"delete",previous:h,table:l}),r?.skipOnDelete!==!0&&await xo({deletedId:t,deletedReference:v=>h[v],findHolders:async(v,b,g,B)=>(await Ze(v).findMany(v,{...B,includeDeleted:p,where:{[b]:g}})).page,onCascade:(v,b)=>Ze(v).delete(v,b,r),onRestrict:v=>{throw new ce(v,"restrict")},onSetNull:(v,b,g)=>Ze(v).patch(v,b,{[g]:null}),schema:s,tableName:l}),Se(l),Te(l),T&&x){const v={[x]:$e()},b={...h,...q(l),...v,_id:t};ut(T,v,b,ae),Ke(c,l,Zt(l),[ue(b),t,f]),Le(l,t,b,h),ke(l,t,void 0),De(l,h,b),Re(l,t,h,void 0);const g=k(l,h,b);ye?.invalidate(l,t,g),me(l,t,"update",b),w({indexKeys:g,key:t,op:"update",row:b,table:l}),ee(l,"after","delete")&&await te("after","delete",{id:t,op:"delete",previous:h,table:l}),await se({id:t,op:"delete",table:l});return}Ke(c,l,or(l),[t,f]),Le(l,t,void 0),ke(l,t,void 0),De(l,h,void 0),Re(l,t,h,void 0);const _=k(l,h);ye?.invalidate(l,t,_),me(l,t,"delete"),w({indexKeys:_,key:t,op:"delete",table:l}),ee(l,"after","delete")&&await te("after","delete",{id:t,op:"delete",previous:h,table:l}),await se({id:t,op:"delete",table:l})},async deleteAll(e,t){if(!s.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);const r=Math.max(1,t?.chunkSize??gn),d=t?.hard===void 0?void 0:{hard:t.hard},f=G(e,"deleteAll");let h=0;return await ge(async()=>{for(;;){const u=(await U.findMany(e,{limit:r})).page.map(p=>String(p._id));if(u.length===0)break;for(const p of u)await(f===void 0?U.delete(e,p,d):ot(f,e,[p],d)),h+=1;if(u.length<r)break}}),{deleted:h}},async deleteMany(e,t,r){m(e,"ctx.db.deleteMany(table, ids)"),Ge(t.length,r?.limit,"deleteMany");for(const d of t)await U.delete(e,d);return{deleted:t.length}},async deleteWhere(e,t,r){const d=G(e,"deleteWhere"),h=(await on(d??U,e,t,r?.limit,"deleteWhere")).map(l=>String(l._id));if(d)return ot(d,e,h,void 0,{options:r});if(U.deleteMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return U.deleteMany(e,h,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 no(`findFirstOrThrow: no "${e}" document matched`);return r},async findMany(e,t={}){const r=G(e,"findMany");if(r)return R(e,H),r.findMany(e,t);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);const f=!t.where&&!t.baseWhere;f?R(e,H):R(e);const{limit:h,orderKeys:l,statement:u}=await Ft(e,d,t,R),p=we(c,u.text,...u.params).toArray();f&&!O&&W?.recordRead(p.length);const T=[];for(const b of p){const g=Ie(b);g&&(T.push(g),!f&&typeof g._id=="string"&&R(e,g._id))}if(h===void 0)return t.with&&await Vt({groupedCounter:Ct,fetcher:et,parents:T,...Jt(t),schema:s,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:Gt(T,t.select,t.with)};const x=T.length>h,_=x?T.slice(0,h):T,v=_.at(-1);return t.with&&await Vt({fetcher:et,groupedCounter:Ct,parents:_,...Jt(t),schema:s,tableName:e,with:t.with}),{continueCursor:x&&v&&t.omitContinueCursor!==!0?Ne(v,l):null,isDone:!x,page:Gt(_,t.select,t.with)}},async explain(e,t={}){const r=G(e,"explain");if(r)return r.explain(e,t);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);const{statement:f}=await Ft(e,d,t,()=>{}),h=we(c,`EXPLAIN QUERY PLAN ${f.text}`,...f.params).toArray();return{params:f.params,plan:h.map(l=>String(l.detail)),sql:f.text}},async get(e,t){m(e,"ctx.db.get(table, id)");const r=ne(t,e);if(!r){const d=_e(e);return d?d.get(e,t):(E(e),N(e,t,!0),null)}return Z(r,t),r.row},async lookupById(e,t){const r=ne(e,t);if(!r){for(const d of kt(t))E(d),N(d,e,!0);return null}return Z(r,e),{row:r.row,tableName:r.tableName}},async groupBy(e,t){const r=G(e,"groupBy");if(r)return R(e,H),r.groupBy(e,t);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);R(e,H);const f=t.agg??{op:"count"};if(Be(f.op),f.op!=="count"&&!f.field)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${f.op}" } }): "field" is required for non-count reducers`);const h=ve(d.softDeleteMode,void 0),l=K(K(t.baseWhere,t.where),h),u=await be(l,e,t.relationBaseWhere),p=u!==l;if(d.aggregateIndexes&&!t.baseWhere&&!p){const g=Wn(d.aggregateIndexes,f.op,f.field,t.by,t.where),B=g===void 0?0:Object.keys(g.partial).length,z=g?.index.by?.length??0;if(g&&(B===0||B===z)){tt(e,g.index);const Y=rt(e,g.index.name),V=Object.keys(g.partial),le=[];if(V.length===(g.index.by??[]).length&&V.length>0){const Fe=it(g.index.by??[],g.partial),qe=j(c,a`SELECT ${Pe} AS value, ${at} AS count FROM ${a.identifier(Y)} WHERE ${Ue} = ${Fe}`).toArray();return qe.length>0&&le.push({key:{...g.partial},value:st(f.op,qe[0])}),le}const Mn=j(c,a`SELECT ${Ue} AS key, ${Pe} AS value, ${at} AS count FROM ${a.identifier(Y)}`).toArray();for(const Fe of Mn){const qe=Ln(JSON.parse(Fe.key));le.push({key:qe,value:st(f.op,Fe)})}return le}}for(const g of[...t.by,f.field]){if(g===void 0)continue;const B=g===f.field?`groupBy(${e}, { agg: { op: "${f.op}", field: "${g}" } })`:`groupBy(${e}, { by: [..."${g}"] })`;sn(d,g,B)}const T=X(u,fe),x=t.by.map(g=>a`${he(g)} AS ${a.identifier(g)}`);if(f.op==="count")x.push(a`COUNT(*) AS value`);else{const{field:g}=f;if(g===void 0)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${f.op}" } }): "field" is required for non-count reducers`);x.push(a`${a.raw(Be(f.op))}(${he(g)}) AS value`)}let _=a`SELECT ${a.join(x,a`, `)} FROM ${a.identifier(e)}`;T&&(_=a`${_} WHERE ${T}`),_=a`${_} GROUP BY ${a.join(t.by.map(g=>he(g)),a`, `)}`;const v=j(c,_).toArray(),b=[];for(const g of v){const B={};for(const Y of t.by)B[Y]=Vn(d.shape[Y],g[Y]??null);const{value:z}=g;b.push({key:B,value:z==null?null:Number(z)})}return b},async insert(e,t,r){const d=G(e,"insert");if(d)return _t(d,e,t,r,!0);const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const h=r?.allowExplicitId===!0,l=Oe(f,ht(f,t,ae),{supplied:t,trusted:h});let u;r?.clientId!==void 0?(dr(r.clientId),u=r.clientId):r?.allowExplicitId&&typeof l._id=="string"?(pt(l._id),u=l._id):u=Et();const p=r?.allowExplicitId&&typeof l._creationTime=="number"?l._creationTime:$e(),T={...l,...q(e),_creationTime:p,_id:u};return ee(e,"before","insert")&&await te("before","insert",{doc:{...T},id:u,op:"insert",table:e}),h||$(e,T),Se(e),Te(e),gt(c,e,tr(e),[u,p,ue(T)]),Mt(e,u,T),ee(e,"after","insert")&&await te("after","insert",{doc:T,id:u,op:"insert",table:e}),await se({doc:T,id:u,op:"insert",table:e}),u},async insertManyUnsafe(e,t,r){if(Ge(t.length,r?.limit,"insertManyUnsafe"),t.length===0)return[];const d=G(e,"insert");if(d){const p=[];lr(s.tables[e],t,r?.allowExplicitId,ae);for(const T of t)Q(T);for(const T of t){const x=await d.insert(e,T,{allowExplicitId:r?.allowExplicitId});w({key:x,op:"insert",row:{...T,_id:x},table:e}),p.push(x)}return p}const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);Se(e),Te(e);const h=[];for(let p=0;p<t.length;p+=He)h.push(q(e));const l=r?.allowExplicitId===!0?void 0:Ao(f),u=t.map((p,T)=>{const x=ht(f,p,ae),_=l===void 0?x:Oe(l,x,{supplied:p}),v=r?.allowExplicitId===!0&&typeof _._id=="string"?_._id:void 0;v!==void 0&&pt(v);const b=v??Et(),g=r?.allowExplicitId===!0&&typeof _._creationTime=="number"?_._creationTime:$e(),B={..._,...h[Math.floor(T/He)],_creationTime:g,_id:b};return{creationTime:g,document:B,id:b}});for(const p of u)Q(p.document);for(let p=0;p<u.length;p+=He){const T=a.join(u.slice(p,p+He).map(_=>a`(${_.id}, ${_.creationTime}, ${ue(_.document)})`),a`, `),x=hn("sqlite",a`INSERT INTO ${a.identifier(e)} (id, _creationTime, ${a.identifier(oe)}) VALUES ${T}`);gt(c,e,x.sql,x.params)}for(const{document:p,id:T}of u)Mt(e,T,p),await ie({doc:p,id:T,op:"insert",table:e});return u.map(p=>p.id)},async insertMany(e,t,r){Ge(t.length,r?.limit,"insertMany");const d=r?.skipDuplicates===!0,f=[],h=G(e,"insert");if(h)for(const u of t)Q(u);const l=async u=>h?_t(h,e,u,void 0,!1):U.insert(e,u);for(const u of t)try{f.push(await l(u))}catch(p){if(d&&p instanceof ce&&p.kind==="unique")f.push(null);else throw p}return f},normalizeId(e,t){return cn(s,e,t)},async patch(e,t,r,d){m(e,"ctx.db.patch(table, id, values)");const f=ne(t,e);if(!f){const b=_e(e);if(b){Q(r),await b.patch(e,t,r,d);return}throw new y("NOT_FOUND",`document not found: ${t}`)}const{docJson:h,row:l,tableName:u}=f,p=s.tables[u];if(!p)throw new y("INTERNAL",`unknown table: ${u}`);if(R(u,t),dn("patch",r),Tt(u,t,r,l)){o?.({fields:Object.keys(je(r)),id:t,table:u});return}const T=oo(p,r,l),x={...l,...je(T),...q(u),_id:t};ut(p,T,x,ae);const _=Oe(p,x,{only:new Set(Object.keys(T)),previous:()=>l,tolerateStoredNull:!0});ro(d,l,_),ee(u,"before","update")&&await te("before","update",{doc:{..._},id:t,op:"update",previous:l,table:u}),$(u,_,l),Se(u),Te(u),Ke(c,u,Zt(u),[ue(_),t,h]),Le(u,t,_,l),ke(u,t,_),De(u,l,_),Re(u,t,l,_);const v=k(u,l,_);ye?.invalidate(u,t,v),me(u,t,"update",_),w({indexKeys:v,key:t,op:"update",row:_,table:u}),ee(u,"after","update")&&await te("after","update",{doc:_,id:t,op:"update",previous:l,table:u}),await se({doc:_,id:t,op:"update",table:u})},async patchIf(e,t,r){const d=G(e,"patchIf");if(d){if(d.patchIf===void 0)throw new y("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);return Q(r.patch),d.patchIf(e,t,r)}if(!s.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);for(let f=1;f<=an;f+=1){const h=await Cn(e,t,r,f<an,l=>U.patch(e,t,l,{verify:r.verify}));if(h!==void 0)return h}throw new ce(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,r){m(e,"ctx.db.patchMany(table, patches)"),Ge(t.length,r?.limit,"patchMany");for(const d of t)await U.patch(e,d.id,d.patch);return{patched:t.length}},async patchWhere(e,t,r){const d=G(e,"patchWhere")??U,h=(await on(d,e,t.where,r?.limit,"patchWhere")).map(l=>({id:String(l._id),patch:t.patch}));if(U.patchMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await U.patchMany(e,h,r),{patched:h.length}},async related(e,t){return Ro(U,S,e,t)},relationEdges:S,deleteRereadTables:C,inTransaction:P,softDeleteFields:A,relationWrites:F,query(e){const t=G(e,"query");return t?(R(e,H),t.query(e)):_n(c,s,e,re,r=>{r?L(r):R(e,H)},r=>{O||W?.recordRead(r)})},async rank(e,t,r){const d=G(e,"rank");if(d)return R(e,H),d.rank(e,t,r);re(e,t,"rank");const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(V=>V.name===t);if(!h)throw new y("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Dt(e,f,h),r.restrictsCounts)throw new ct(e);R(e,H),nt(e,h);const l=typeof r.row=="string"?r.row:r.row._id;if(!l)return null;const u=jt(e,h.name),p=h.sortBy.map((V,le)=>Kt(le)),T=p.map(V=>Ce(V)).join(", "),x=j(c,a`SELECT ${a.identifier("__partition__")}, ${a.raw(T)} FROM ${a.identifier(u)} WHERE ${a.identifier("__id__")} = ${l}`).toArray(),[_]=x;if(_===void 0)return null;let v=_.__partition__;const b=K(r.baseWhere,r.where);dt(b,s,e,"rank");const g=fo(h,b);if(g){const V=ho(h.partitionBy??[],g);if(V!==v)return null;v=V}const B=p.map(V=>_[V]),{before:z,total:Y}=un(c,u,p,h.sortBy,v,B,l);return{position:z+1,total:Y}},async rankBefore(e,t,r){if(de(e))throw new y("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);const f=d.rankIndexes?.find(p=>p.name===t);if(!f)throw new y("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(r.restrictsCounts)throw new ct(e);R(e,H),nt(e,f);const h=jt(e,f.name),l=f.sortBy.map((p,T)=>Kt(T)),u=f.sortBy.map((p,T)=>xe(r.sortValues[T]??null));return un(c,h,l,f.sortBy,r.partitionKey,u,r.rowId)},async rankPage(e,t,r={}){dt(K(r.baseWhere,r.where),s,e,"rankPage");const d=G(e,"rankPage");if(d)return R(e,H),d.rankPage(e,t,r);re(e,t,"rank");const{continueCursor:f,hasMore:h,rows:l}=Bt(Lt,e,t,r);return{continueCursor:f,isDone:!h,page:l.map(u=>u.doc)}},async rankPageRows(e,t,r={}){dt(K(r.baseWhere,r.where),s,e,"rankPage"),re(e,t,"rank");const{directions:d,hasMore:f,rows:h}=Bt(Lt,e,t,r);return{directions:d,hasMore:f,rows:h}},async restore(e,t){m(e,"ctx.db.restore(table, id)");const r=ne(t,e);if(!r){const h=_e(e);if(h?.restore){await h.restore(e,t);return}throw new y("NOT_FOUND",`document not found: ${t}`)}const d=s.tables[r.tableName]?.softDeleteMode?.field;if(!d)throw new y("INTERNAL",`ctx.db.restore: table "${r.tableName}" is not a .softDelete() table`);const f=r.row[d]!==null&&r.row[d]!==void 0;await U.patch(e,t,{[d]:null}),f&&Re(r.tableName,t,void 0,r.row)},async replace(e,t,r,d){m(e,"ctx.db.replace(table, id, document)");const f=ne(t,e);if(!f){const B=_e(e);if(B){Q(r),await B.replace(e,t,r,d);return}throw new y("NOT_FOUND",`document not found: ${t}`)}const{docJson:h,row:l,tableName:u}=f,p=s.tables[u];if(!p)throw new y("INTERNAL",`unknown table: ${u}`);dn("replace",r);const T=d?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:void 0,x=typeof l._creationTime=="number"?l._creationTime:void 0,_=T??x??$e(),v={...r,...q(u),_creationTime:_,_id:t};ut(p,r,v,ae);const b=d?.allowExplicitId===!0,g=Oe(p,v,{previous:()=>l,supplied:r,trusted:b});ee(u,"before","update")&&await te("before","update",{doc:{...g},id:t,op:"update",previous:l,table:u}),b||$(u,g,l),Se(u),Te(u),Ke(c,u,nr(u),[_,ue(g),t,h]),Le(u,t,g,l),ke(u,t,g),De(u,l,g),Re(u,t,l,g),ye?.invalidate(u,t,k(u,l,g)),me(u,t,"update",g),w({indexKeys:k(u,l,g),key:t,op:"update",row:g,table:u}),ee(u,"after","update")&&await te("after","update",{doc:g,id:t,op:"update",previous:l,table:u}),await se({doc:g,id:t,op:"update",table:u})},async wipeShard(e){const t=new Set(e?.exclude),r=e?.tables,d=Object.entries(s.tables).filter(([u,p])=>t.has(u)||r!==void 0&&!r.includes(u)?!1:p.shardMode?.kind!=="global").map(([u])=>u);if(r!==void 0){for(const u of r)if(!s.tables[u])throw new y("INTERNAL",`wipeShard: unknown table: ${u}`)}const f={};let h=0;const{deleteAll:l}=U;if(l===void 0)throw new y("INTERNAL","wipeShard: this writer has no deleteAll");for(const u of d){const p=await l(u,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});f[u]=p.deleted,h+=p.deleted}return{deleted:h,tables:f}}},bn={db:U,scheduler:mt};return n.enforceRls===!0?bo(U,s,(e,t)=>ne(e,t)?.tableName,S):U};export{Ti as CDC_LOG_TABLE,ji as IDEMPOTENCY_TABLE,Tr as NotUniqueError,Ui as advanceClientWatermark,Ri as applyCdcChanges,dn as assertNoExplicitUndefined,pt as assertStorableRowId,dr as assertValidClientId,$i as backfillAggregateIndexes,Ei as backfillRankIndexes,mi as backfillSearchIndexes,_i as bumpCdcEpoch,vi as cdcCanVouchFor,Ii as cdcForkedError,Ai as cdcSeqLeavingRows,xi as cdcTouchesTables,Ci as cdcTrimmedError,bi as compactCdcDocs,pi as createShardCtxDb,Mi as cursorBelowRetainedFloor,Oi as migrateClientWatermark,Di as minCdcReplayableSeq,ki as minCdcSeq,cn as normalizeIdStructurally,Li as readCdcChangeKeys,Fi as readCdcChanges,qi as readCdcCursor,Wi as readCdcEpoch,Hi as readClientWatermark,Ki as readIdempotent,Ji as runShardMigrations,Yi as selectShapeMembers,Xi as selectShapeRows,je as stripReservedPatchFields,Bi as trimCdcChanges,Ni as trimIdempotent,Qi as writeIdempotent};
|
|
@@ -0,0 +1,17 @@
|
|
|
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}" (
|
|
2
|
+
id TEXT PRIMARY KEY,
|
|
3
|
+
captured_at INTEGER NOT NULL,
|
|
4
|
+
message_id TEXT NOT NULL,
|
|
5
|
+
queue TEXT NOT NULL,
|
|
6
|
+
export_name TEXT,
|
|
7
|
+
body TEXT NOT NULL,
|
|
8
|
+
attempts INTEGER NOT NULL,
|
|
9
|
+
outcome TEXT NOT NULL,
|
|
10
|
+
error TEXT,
|
|
11
|
+
dead_lettered INTEGER NOT NULL,
|
|
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)
|
|
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
|
+
WHERE id NOT IN (
|
|
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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{sql as s}from"drizzle-orm";import{matchesStaticWhere as f}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{compareStrings as l}from"./aggregateTableName-B_CtIQCS.mjs";import{serializeSqlValue as d}from"./serializeSqlValue-DeoBMpZ2.mjs";const a=Symbol("not-resolvable"),m=r=>{if(r!==null&&typeof r=="object"&&!Array.isArray(r)){const t=Object.keys(r);return t.length===1&&t[0]==="eq"?r.eq:a}return r},y=(r,t)=>{if(r.length===0)return"";const e={};for(const n of r.toSorted(l))e[n]=t[n]??null;return JSON.stringify(e)},k="__id__",N=r=>`__sort_k${String(r)}__`,h=(r,t)=>{const e=r.partitionBy??[],n=t??{};for(const o of Object.keys(n))if(o==="AND"||o==="OR"||o==="NOT")return;const i={};for(const o of e)if(o in n){const c=m(n[o]);if(c===a)return;i[o]=c}else if(r.where&&o in r.where)i[o]=r.where[o];else return;return i},O=(r,t)=>`${r}__rank_${t}`,$=(r,t)=>({partitionKey:y(r.partitionBy??[],t),rowId:t._id,sortValues:r.sortBy.map(e=>d(t[e.field]??null))}),K=(r,t,e,n)=>{const i=e!=="desc"===n;if(t==null)return i?s`${s.identifier(r)} IS NOT NULL`:void 0;const o=s`${s.identifier(r)} ${s.raw(i?">":"<")} ${t}`;return i?o:s`(${o} OR ${s.identifier(r)} IS NULL)`},R=f;export{k as RANK_TIEBREAK,y as encodePartitionKey,R as matchesRankStaticWhere,$ as rankKeyFromDoc,K as rankPivotConditionSql,O as rankTableName,h as resolveRankPartition,N as sortColumnName};
|
|
@@ -0,0 +1,28 @@
|
|
|
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)} (
|
|
2
|
+
path TEXT PRIMARY KEY,
|
|
3
|
+
digest TEXT NOT NULL,
|
|
4
|
+
tables TEXT NOT NULL,
|
|
5
|
+
runs INTEGER NOT NULL DEFAULT 0,
|
|
6
|
+
suppressed INTEGER NOT NULL DEFAULT 0,
|
|
7
|
+
errors INTEGER NOT NULL DEFAULT 0,
|
|
8
|
+
last_ran_at INTEGER NOT NULL DEFAULT 0,
|
|
9
|
+
last_error TEXT
|
|
10
|
+
)`);const e=new Set(o(r,t`PRAGMA table_info(${t.identifier(a)})`).toArray().map(s=>s.name));for(const[s,i]of c)e.has(s)||o(r,t`ALTER TABLE ${t.identifier(a)} ADD COLUMN ${t.raw(i)}`)},R=r=>{if(typeof r=="string")try{const e=JSON.parse(r);return Array.isArray(e)&&e.every(s=>typeof s=="string")?e:void 0}catch{return}},T=r=>typeof r=="number"&&Number.isFinite(r)?r:0,d=r=>({digest:r.digest,...typeof r.last_error=="string"&&r.last_error.length>0?{lastError:r.last_error}:{},lastRanAt:T(r.last_ran_at),stats:{errors:T(r.errors),runs:T(r.runs),suppressed:T(r.suppressed)},tables:R(r.tables)}),l="path, digest, tables, runs, suppressed, errors, last_ran_at, last_error",f=(r,e)=>{const[s]=o(r,t`SELECT ${t.raw(l)} FROM ${t.identifier(a)} WHERE path = ${e}`);if(!(s===void 0||typeof s.digest!="string"))return d(s)},U=r=>o(r,t`SELECT ${t.raw(l)} FROM ${t.identifier(a)} ORDER BY path`).toArray().filter(e=>typeof e.digest=="string").map(e=>({path:e.path,state:d(e)})),g=(r,e,s)=>{const{digest:i,error:p,now:u,result:n,tables:E}=s,L=i??"",N=E===void 0?"":JSON.stringify([...E]),_=p??null;o(r,t`INSERT INTO ${t.identifier(a)} (path, digest, tables, runs, suppressed, errors, last_ran_at, last_error)
|
|
11
|
+
VALUES (
|
|
12
|
+
${e},
|
|
13
|
+
${L},
|
|
14
|
+
${N},
|
|
15
|
+
${n==="ran"?1:0},
|
|
16
|
+
${n==="suppressed"?1:0},
|
|
17
|
+
${n==="error"?1:0},
|
|
18
|
+
${u},
|
|
19
|
+
${_}
|
|
20
|
+
)
|
|
21
|
+
ON CONFLICT(path) DO UPDATE SET
|
|
22
|
+
digest = ${i===void 0?t.raw(`${a}.digest`):t`excluded.digest`},
|
|
23
|
+
tables = ${E===void 0?t.raw(`${a}.tables`):t`excluded.tables`},
|
|
24
|
+
runs = ${t.raw(`${a}.runs`)} + ${n==="ran"?1:0},
|
|
25
|
+
suppressed = ${t.raw(`${a}.suppressed`)} + ${n==="suppressed"?1:0},
|
|
26
|
+
errors = ${t.raw(`${a}.errors`)} + ${n==="error"?1:0},
|
|
27
|
+
last_ran_at = excluded.last_ran_at,
|
|
28
|
+
last_error = ${n==="error"?t`excluded.last_error`:t.raw("NULL")}`)},S=(r,e)=>r?.tables===void 0?!0:r.tables.some(s=>e.has(s));export{a as REACTOR_STATE_TABLE,U as listReactorStates,O as migrateReactorState,S as reactorNeedsRun,f as readReactorState,g as writeReactorState};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as h}from"@lunora/errors";import{mergeWhere as I}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{decodeCursor as S,CURSOR_PREFIX as v,toBase64 as B}from"./CURSOR_PREFIX-6offuG6M.mjs";const O=4,C=1,L=50,$=200,T=1e4,x=.5,D=t=>{if(t.kind==="id"){const e=t._meta?.tableName;return typeof e=="string"&&e.length>0?{array:!1,targetTable:e}:void 0}if(t.kind!=="array"&&t.kind!=="optional")return;const n=t._meta?.inner,r=n===void 0?void 0:D(n);if(r!==void 0)return{array:r.array||t.kind==="array",targetTable:r.targetTable}},j=t=>{const n=[];for(const[r,e]of Object.entries(t.tables))for(const[s,o]of Object.entries(e.shape)){const a=D(o);a===void 0||t.tables[a.targetTable]===void 0||n.push({array:a.array,column:s,name:`${r}.${s}`,sourceTable:r,targetTable:a.targetTable})}return n},U=t=>v+B(JSON.stringify([t])),M=t=>{const[n]=S(t);if(typeof n!="number"||!Number.isInteger(n)||n<0)throw new h("BAD_REQUEST","invalid cursor");if(n>T)throw new h("BAD_REQUEST",`ctx.db.related: cursor offset ${String(n)} exceeds the maximum of ${String(T)} — narrow the walk with \`edges\` or \`direction\` instead of paging past it`);return n},k=(t,n,r,e)=>{if(t===void 0)return n;if(!Number.isInteger(t)||t<1||t>r)throw new h("BAD_REQUEST",`ctx.db.related: \`${e}\` must be an integer between 1 and ${String(r)}, got ${String(t)}`);return t},N=(t,n)=>{if(n===void 0)return[...t];const r=new Set(t.map(o=>o.name)),e=n.filter(o=>!r.has(o));if(e.length>0)throw new h("BAD_REQUEST",`ctx.db.related: unknown edge ${e.length===1?"name":"names"}: ${e.join(", ")}`);const s=new Set(n);return t.filter(o=>s.has(o.name))},W=(t,n)=>{const r=t[n.column];return n.array?Array.isArray(r)?r.filter(e=>typeof e=="string"&&e.length>0):[]:typeof r=="string"&&r.length>0?[r]:[]},A=async(t,n,r,e)=>{const s=await t.findMany(n,{limit:e.limit,omitContinueCursor:!0,where:I(r,e.relationBaseWhere?.(n))??r});return e.mask?.(n,s.page)??s.page},F={in:{keyColumn:t=>t.column,keysOf:(t,n)=>n.array||t.table!==n.targetTable?[]:[t.id],skipVisitedKeys:!1,table:t=>t.sourceTable},out:{keyColumn:()=>"_id",keysOf:(t,n)=>t.table===n.sourceTable?W(t.document,n):[],skipVisitedKeys:!0,table:t=>t.targetTable}},_=async(t,n,r,e,s)=>{const o=F[s],a=o.keyColumn(r),l=o.table(r),u=new Map;for(const c of n)for(const i of o.keysOf(c,r))!u.has(i)&&!(o.skipVisitedKeys&&e.visited.has(i))&&u.set(i,c);if(u.size===0)return[];const f=await A(t,l,{[a]:{in:[...u.keys()]}},e),m=[];for(const c of f){const i=c._id,g=c[a],d=typeof g=="string"?u.get(g):void 0;typeof i!="string"||d===void 0||e.visited.has(i)||(e.visited.add(i),m.push({document:c,id:i,path:[...d.path,r.name],pathIds:[...d.pathIds,i],table:l}))}return m},Q=async(t,n,r,e)=>{const s=[],o=()=>e.budget-s.length,a=()=>({limit:o(),mask:e.mask,relationBaseWhere:e.relationBaseWhere,visited:e.visited});for(const l of r)e.direction!=="in"&&o()>0&&s.push(...await _(t,n,l,a(),"out")),e.direction!=="out"&&o()>0&&s.push(...await _(t,n,l,a(),"in"));return s},H=async(t,n)=>{const r=n._id;if(typeof r=="string"&&r.length>0){const o=await t.lookupById?.(r);if(!o)throw new h("BAD_REQUEST","ctx.db.related: could not resolve the start document's table from its `_id` — pass `{ table, id }` instead");return{id:r,table:o.tableName}}const{id:e,table:s}=n;if(typeof s!="string"||s.length===0||typeof e!="string"||e.length===0)throw new h("BAD_REQUEST","ctx.db.related: `start` must be a loaded document or `{ table, id }`");return{id:e,table:s}},V=async(t,n,r,e={})=>{const s=k(e.depth,C,O,"depth"),o=k(e.limit,L,$,"limit"),a=e.cursor?M(e.cursor):0,l=e.direction??"both",u=N(n,e.edges),{id:f,table:m}=await H(t,r),[c]=await A(t,m,{_id:f},{limit:1,mask:e.relationMask,relationBaseWhere:e.relationBaseWhere,visited:new Set});if(c===void 0)throw new h("NOT_FOUND",`ctx.db.related: no "${m}" row with id ${f}`);const i=a+o+1,g=new Set([f]),d=[];let w=[{document:c,id:f,path:[],pathIds:[f],table:m}];for(let b=1;b<=s&&w.length>0&&d.length<i;b+=1){const p=await Q(t,w,u,{budget:i-d.length,direction:l,mask:e.relationMask,relationBaseWhere:e.relationBaseWhere,visited:g}),R=x**(b-1);for(const y of p)d.push({depth:b,document:y.document,path:y.path,pathIds:y.pathIds,score:R,table:y.table});w=p}const E=d.length<=a+o;return{continueCursor:E?null:U(a+o),isDone:E,nodes:d.slice(a,a+o)}};export{L as RELATED_DEFAULT_LIMIT,x as RELATED_DEPTH_DECAY,O as RELATED_MAX_DEPTH,$ as RELATED_MAX_LIMIT,T as RELATED_MAX_OFFSET,j as deriveRelationEdges,V as findRelated};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const E=Symbol("lunora.seekRange"),o="__relationExists";export{o as RELATION_EXISTS_KEY,E as SEEK_RANGE};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const i=(t,e)=>{const n=Math.max(t.length,e.length);let o=t.length^e.length;for(let r=0;r<n;r+=1){const c=r<t.length?t.charCodeAt(r):0,s=r<e.length?e.charCodeAt(r):0;o|=c^s}return o===0},a=(t,e)=>{if(t.size<e)return;const n=t.keys().next().value;n!==void 0&&t.delete(n)},l=(t,e,n,o)=>{const r=t.get(e);if(r!==void 0)return r;a(t,o);const c=n().catch(s=>{throw t.get(e)===c&&t.delete(e),s});return t.set(e,c),c},d=new TextEncoder,g=64,h=new Map,E=async t=>l(h,t,async()=>crypto.subtle.importKey("raw",d.encode(t),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),g),u="LUNORA_RELAY_SECRET",A="x-lunora-relay-sig",f=t=>{const e=t?.[u];return typeof e=="string"&&e.length>0?e:void 0},y=async(t,e)=>{const n=await crypto.subtle.sign("HMAC",await E(t),new TextEncoder().encode(e));return[...new Uint8Array(n)].map(o=>o.toString(16).padStart(2,"0")).join("")},v=async(t,e,n)=>{const o=f(t);return o===void 0?!0:e===null?!1:i(e,await y(o,n))};export{A as RELAY_SIGNATURE_HEADER,f as siblingSecretOf,y as signSiblingBody,v as verifySiblingBody};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const o="__lunora_reproject__",e=t=>`${o}${t}`,n=t=>{if(!t.startsWith(o))return;const r=t.slice(o.length);return r===""?void 0:r};export{o as REPROJECTION_MIGRATION_PREFIX,e as reprojectionMigrationId,n as reprojectionMigrationTable};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as f}from"@lunora/errors";import{findRelated as y}from"./RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";const w=Symbol.for("lunora.ctxdb.rls-unwrap");class b extends f{table;constructor(o){super("RLS_REQUIRED",`ctx.db access to "${o}" is denied: the schema is marked .rls("required"), so this table is protected. Apply RLS with .use(rls(policies)) in the procedure, or mark the table .public() to opt it out.`,{name:"RlsRequiredError"}),this.table=o}}const R=n=>Object.entries(n.tables).filter(([,o])=>o.shardMode?.kind!=="global").map(([o])=>o),m=(n,o,l)=>{const i=o?.tables,a=new Set(o?.exclude);for(const s of n)(i===void 0||i.includes(s))&&!a.has(s)&&l(s)},g={aggregate:"loop-gated",asId:"ungated",assertPatchAllowed:"inline-table-gated",cdcChangedTables:"ungated",count:"loop-gated",delete:"inline-table-gated",deleteAll:"loop-gated",deleteMany:"inline-table-gated",deleteWhere:"inline-table-gated",explain:"loop-gated",findFirst:"loop-gated",findFirstOrThrow:"loop-gated",findMany:"loop-gated",get:"inline-table-gated",groupBy:"loop-gated",insert:"loop-gated",insertMany:"loop-gated",insertManyUnsafe:"loop-gated",inTransaction:"ungated",lookupById:"id-gated",normalizeId:"ungated",patch:"inline-table-gated",patchIf:"loop-gated",patchMany:"inline-table-gated",patchWhere:"inline-table-gated",query:"loop-gated",rank:"loop-gated",rankBefore:"loop-gated",rankPage:"loop-gated",rankPageRows:"loop-gated",related:"rebound",relationEdges:"ungated",deleteRereadTables:"ungated",relationWrites:"ungated",softDeleteFields:"ungated",replace:"inline-table-gated",restore:"inline-table-gated",system:"ungated",wipeShard:"sweep-gated"},M=Object.entries(g).filter(([,n])=>n==="loop-gated").map(([n])=>n),S={related:(n,o)=>(...l)=>{const[i,a]=l;return y(n,o,i,a)}},E=Object.entries(g).filter(([,n])=>n==="rebound").map(([n])=>n),O=(n,o,l)=>{for(const i of E)typeof o[i]=="function"&&(n[i]=S[i](n,l))},k=(n,o,l,i=[])=>{if(o.rlsMode!=="required")return n;const a=n,s=e=>{const t=o.tables[e];return t!==void 0&&t.isPublic!==!0},d=e=>{if(s(e))throw new b(e)},p=async(e,t)=>{if(t!==void 0){d(t);return}const r=await l(e);r!==void 0&&d(r)},c={...n,delete:async(e,t,r)=>(d(e),await a.delete(e,t,r)),deleteMany:async(e,t,r)=>(d(e),await a.deleteMany(e,t,r)),deleteWhere:a.deleteWhere?async(e,t,r)=>(d(e),await a.deleteWhere?.(e,t,r)):void 0,get:async(e,t)=>(d(e),await a.get(e,t)),lookupById:async(e,t)=>(await p(e,t),a.lookupById?.(e,t)??null),patch:async(e,t,r,u)=>(d(e),await a.patch(e,t,r,u)),patchMany:async(e,t,r)=>(d(e),await a.patchMany(e,t,r)),assertPatchAllowed:async(e,t)=>(d(e),await a.assertPatchAllowed?.(e,t)),patchWhere:a.patchWhere?async(e,t,r)=>(d(e),await a.patchWhere?.(e,t,r)):void 0,replace:async(e,t,r,u)=>(d(e),await a.replace(e,t,r,u)),restore:async(e,t)=>(d(e),await a.restore?.(e,t))},h=a;for(const e of M){const t=h[e];typeof t=="function"&&(c[e]=(r,...u)=>(d(r),t.call(a,r,...u)))}if(O(c,a,i),a.wipeShard){const{wipeShard:e}=a;c.wipeShard=t=>(m(R(o),t,d),e.call(a,t))}return Object.defineProperty(c,w,{configurable:!0,enumerable:!1,value:n,writable:!1}),c};export{M as LOOP_GATED_METHODS,w as RLS_UNWRAP_SYMBOL,b as RlsRequiredError,g as WRITER_METHOD_GATING,k as guardWriter};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{stableWireKey as y}from"@lunora/wire";import{stableStringify as M,stableWireKey as T}from"@lunora/wire";import{depKey as l,SCAN_DEP as p}from"./SCAN_DEP-D7qE3iUe.mjs";import{e as m}from"./estimate-bytes-_k74s6LZ.mjs";import{isPointRange as x,keysTouchRanges as v}from"./buildIndexRange-BTChxh3k.mjs";const f=(o,t,e)=>{let s=o.get(t);return s===void 0&&(s=e(),o.set(t,s)),s},E=1e3,B=4*1024*1024;class A{entries=new Map;tableIndex=new Map;rangeIndex=new Map;totalBytes=0;hits=0;misses=0;evictions=0;maxEntries;maxBytes;now;monotonic=0;generation=0;constructor(t={}){this.maxEntries=t.maxEntries??E,this.maxBytes=t.maxBytes??B,this.now=t.now??(()=>(this.monotonic+=1,this.monotonic))}async run(t,e,s,i=()=>[]){const r=this.entries.get(t);if(r)return this.hits+=1,r.lastUsed=this.now(),this.entries.delete(t),this.entries.set(t,r),r.result;this.misses+=1;const c=this.generation,a=await s();if(this.generation!==c)return a;const h=m(a);if(h===void 0)return a;const b=i().filter(n=>!x(n)||!e.has(l(n.table,n.lo))),u={bytes:h,deps:e,ranges:b,lastUsed:this.now(),result:a,subscribers:new Set},d=this.entries.get(t);if(d){this.dropEntry(t,d);for(const n of d.subscribers)u.subscribers.add(n)}this.entries.set(t,u),this.totalBytes+=h;for(const n of e)f(this.tableIndex,n,()=>new Set).add(t);for(const n of b){const g=f(this.rangeIndex,n.table,()=>new Map);f(g,n,()=>new Set).add(t)}return this.evict(),a}invalidate(t,e,s){this.generation+=1;const i=[];return this.collectAndDrop(l(t,e),i),this.collectAndDrop(l(t,p),i),this.dropRangeDeps(t,s,i),i}invalidateTable(t){this.generation+=1;const e=[],s=`${t}:`;for(const i of this.tableIndex.keys())i.startsWith(s)&&this.collectAndDrop(i,e);return this.dropRangeDeps(t,void 0,e),e}subscribe(t,e){const s=this.entries.get(t);s&&s.subscribers.add(e)}unsubscribe(t,e){const s=this.entries.get(t);s&&s.subscribers.delete(e)}size(){return{bytes:this.totalBytes,entries:this.entries.size}}clear(){this.generation+=1,this.entries.clear(),this.tableIndex.clear(),this.rangeIndex.clear(),this.totalBytes=0}subscribers(t){const e=this.entries.get(t);return e?[...e.subscribers]:[]}stats(){return{bytes:this.totalBytes,entries:this.entries.size,evictions:this.evictions,hits:this.hits,misses:this.misses}}dropRangeDeps(t,e,s){const i=this.rangeIndex.get(t);if(!(!i||i.size===0))for(const[r,c]of i)v([r],e)&&this.dropKeys(c,s)}collectAndDrop(t,e){const s=this.tableIndex.get(t);s&&this.dropKeys(s,e)}dropKeys(t,e){for(const s of t){const i=this.entries.get(s);i&&(this.dropEntry(s,i),e.push(s))}}dropEntry(t,e){this.entries.delete(t),this.totalBytes-=e.bytes;for(const s of e.deps){const i=this.tableIndex.get(s);i&&(i.delete(t),i.size===0&&this.tableIndex.delete(s))}for(const s of e.ranges){const i=this.rangeIndex.get(s.table),r=i?.get(s);r?.delete(t),i&&r?.size===0&&(i.delete(s),i.size===0&&this.rangeIndex.delete(s.table))}}evict(){if(!(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes))for(const[t,e]of this.entries){if(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes)return;e.subscribers.size>0||(this.dropEntry(t,e),this.evictions+=1)}}}const D=(o,t,e)=>`${e??"\0anon"}\0${o}:${y(t)}`;export{A as ReactiveCache,D as reactiveCacheKey,M as stableStringify,T as stableWireKey};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const r="*scan",t=(e,c)=>`${e}:${c}`,o=e=>{const c=e.indexOf(":");return c===-1?e:e.slice(0,c)},s=()=>{const e=new Set;return{collect(){return e},recordRead(c,n){e.add(t(c,n))}}};export{r as SCAN_DEP,s as createDependencyTracker,t as depKey,o as tableFromDepKey};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import{sql as t}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-RC09zZrh.mjs";const o="__schedule_outbox",_=e=>{a(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(o)} (
|
|
2
|
+
id TEXT PRIMARY KEY,
|
|
3
|
+
envelope_json TEXT NOT NULL,
|
|
4
|
+
attempts INTEGER NOT NULL,
|
|
5
|
+
next_attempt_at REAL NOT NULL,
|
|
6
|
+
created_at REAL NOT NULL,
|
|
7
|
+
dead INTEGER NOT NULL DEFAULT 0
|
|
8
|
+
)`),a(e,t`CREATE INDEX IF NOT EXISTS ${t.identifier(`${o}_due`)} ON ${t.identifier(o)} (dead, next_attempt_at)`)},p=(e,d,E,n)=>{a(e,t`INSERT OR REPLACE INTO ${t.identifier(o)} (id, envelope_json, attempts, next_attempt_at, created_at, dead)
|
|
9
|
+
VALUES (${d}, ${E}, 0, ${n}, ${n}, 0)`)},s=(e,d)=>{a(e,t`DELETE FROM ${t.identifier(o)} WHERE id = ${d}`)},u=(e,d,E)=>a(e,t`SELECT id, envelope_json, attempts, next_attempt_at FROM ${t.identifier(o)}
|
|
10
|
+
WHERE dead = 0 AND next_attempt_at <= ${d}
|
|
11
|
+
ORDER BY next_attempt_at ASC LIMIT ${E}`).toArray().map(i=>({attempts:i.attempts,envelopeJson:i.envelope_json,id:i.id,nextAttemptAt:i.next_attempt_at})),c=(e,d,E,n)=>{a(e,t`UPDATE ${t.identifier(o)} SET attempts = ${E}, next_attempt_at = ${n} WHERE id = ${d}`)},O=(e,d,E)=>{a(e,t`UPDATE ${t.identifier(o)} SET attempts = ${E}, dead = 1 WHERE id = ${d}`)},N=e=>{const E=a(e,t`SELECT MIN(CASE WHEN dead = 0 THEN next_attempt_at END) AS due, COUNT(*) AS total FROM ${t.identifier(o)}`).toArray()[0];return{dueAt:E?.due??void 0,populated:(E?.total??0)>0}},m=(e,d)=>{a(e,t`DELETE FROM ${t.identifier(o)} WHERE dead = 1 AND created_at < ${d}`)};export{o as SCHEDULE_OUTBOX_TABLE,c as deferScheduleOutbox,s as forgetScheduleOutbox,_ as migrateScheduleOutbox,O as parkScheduleOutbox,N as probeScheduleOutbox,u as readDueScheduleOutbox,p as recordScheduleOutbox,m as trimScheduleOutbox};
|
|
@@ -0,0 +1,6 @@
|
|
|
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} (
|
|
2
|
+
hash TEXT PRIMARY KEY,
|
|
3
|
+
seq INTEGER NOT NULL,
|
|
4
|
+
snapshot_json TEXT NOT NULL,
|
|
5
|
+
applied_at INTEGER NOT NULL
|
|
6
|
+
)`)},S=t=>{n(t,`DELETE FROM ${e} WHERE hash NOT IN (SELECT hash FROM ${e} ORDER BY seq DESC LIMIT ?)`,c)},I=(t,s,r,h=Date.now())=>{if(s===""||r==="")return!1;try{if(a(t),n(t,`SELECT hash FROM ${e} WHERE hash = ? LIMIT 1`,s).toArray().length>0)return!1;const[o]=n(t,`SELECT COALESCE(MAX(seq), 0) + 1 AS next FROM ${e}`).toArray(),T=typeof o?.next=="number"?o.next:1;return n(t,`INSERT INTO ${e} (hash, seq, snapshot_json, applied_at) VALUES (?, ?, ?, ?) ON CONFLICT(hash) DO NOTHING`,s,T,r,h),S(t),!0}catch{return!1}},_=t=>{try{return a(t),n(t,`SELECT hash, seq, applied_at FROM ${e} ORDER BY seq DESC`).toArray().map(s=>E(s))}catch{return[]}},u=(t,s)=>{try{a(t);const[r]=n(t,`SELECT hash, seq, applied_at, snapshot_json FROM ${e} WHERE hash = ? LIMIT 1`,s).toArray();return r===void 0?void 0:{...E(r),snapshotJson:typeof r.snapshot_json=="string"?r.snapshot_json:""}}catch{return}};export{c as SCHEMA_HISTORY_MAX_VERSIONS,_ as readSchemaHistory,u as readSchemaVersion,I as recordSchemaVersion};
|
|
@@ -0,0 +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};
|
|
@@ -0,0 +1,8 @@
|
|
|
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)} (
|
|
2
|
+
connection_id TEXT NOT NULL,
|
|
3
|
+
sub_id TEXT NOT NULL,
|
|
4
|
+
cursor INTEGER NOT NULL,
|
|
5
|
+
PRIMARY KEY (connection_id, sub_id)
|
|
6
|
+
)`)},N=(r,e,n)=>s(r,o`SELECT cursor FROM ${o.identifier(c)} WHERE connection_id = ${e} AND sub_id = ${n} LIMIT 1`).toArray()[0]?.cursor,a=(r,e,n,i)=>{s(r,o`INSERT INTO ${o.identifier(c)} (connection_id, sub_id, cursor) VALUES (${e}, ${n}, ${i})
|
|
7
|
+
ON CONFLICT(connection_id, sub_id) DO UPDATE SET cursor = excluded.cursor`)},T=3,R=(r,e)=>{const n=Math.floor(d.boundParams/T);for(let i=0;i<e.length;i+=n){const E=e.slice(i,i+n),u=o.join(E.map(t=>o`(${t.connectionId}, ${t.subId}, ${t.cursor})`),o`, `);s(r,o`INSERT INTO ${o.identifier(c)} (connection_id, sub_id, cursor) VALUES ${u}
|
|
8
|
+
ON CONFLICT(connection_id, sub_id) DO UPDATE SET cursor = excluded.cursor`)}},$=r=>s(r,o`SELECT MIN(cursor) AS cursor FROM ${o.identifier(c)}`).toArray()[0]?.cursor??void 0,C=(r,e,n)=>{s(r,o`DELETE FROM ${o.identifier(c)} WHERE connection_id = ${e} AND sub_id = ${n}`)},I=(r,e)=>{s(r,o`DELETE FROM ${o.identifier(c)} WHERE connection_id = ${e}`)};export{c as SHAPE_POKE_CURSOR_TABLE,C as deleteShapePokeCursor,I as deleteShapePokeCursorsForConnection,L as migrateShapePokeCursor,$ as minShapePokeCursor,N as readShapePokeCursor,a as writeShapePokeCursor,R as writeShapePokeCursors};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{stableWireKey as o}from"@lunora/wire";const s=r=>r.map(e=>`${String(e.length)}:${e}`).join(""),c=r=>o(r.effectiveWhere??null),g=(r,e,t)=>s([r,String(e),String(t)]),h=(r,e)=>{try{return s([c(r),e])}catch{return}};class d{keyScans=new Map;memberProbes=new Map;run=0;served=0;get probesRun(){return this.run}get probesServed(){return this.served}changedKeys(e,t){return this.getOrLoad(this.keyScans,e,t)}members(e,t,n){return this.getOrLoad(this.memberProbes,h(e,t),n)}getOrLoad(e,t,n){if(t!==void 0){const a=e.get(t);if(a!==void 0)return this.served+=1,a}this.run+=1;const i=n();return t!==void 0&&e.set(t,i),i}}const p=()=>new d,b=(r,e)=>{try{return s([r.table,c(r),o({identity:e.identity,userId:e.userId})])}catch{return}};export{d as ShapeDiffCache,p as createShapeDiffCache,b as globalShapeReadKey,g as shapeRangeKey};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
class n{shardHost;socketHost;options;constructor(t,s,r={}){this.shardHost=t,this.socketHost=s,this.options=r}get shardKey(){return this.shardHost.shardKey}socketFor(t){return this.socketHost.handleFor(t)??t}sockets(t){return this.socketHost.getSockets(t)}background(t){return this.shardHost.waitUntil===void 0?!1:(this.shardHost.waitUntil(t),!0)}async runInTransaction(t,s){return this.shardHost.runSerialized(async()=>{const r=await this.shardHost.transaction(t);return s?.(),r})}async handleFetch(t){return this.options.handlers?.handleFetch?this.options.handlers.handleFetch(t):new Response("Not implemented",{status:501})}async handleAlarm(){this.options.handlers?.handleAlarm&&await this.options.handlers.handleAlarm()}}export{n as ShardRunner};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{idRange as d}from"./buildIndexRange-BTChxh3k.mjs";const f=()=>{const o=new Set,n=new Map,s=new Set,r=e=>{o.add(e.table);const t=n.get(e.table);t?t.push(e):n.set(e.table,[e])};return{onRead(e,t,a){if(a===!0&&t!==void 0){r(d(e,t));return}o.add(e),s.add(e)},onReadRange:r,ranges(){for(const e of s)n.delete(e);return n.size>0?n:void 0},tables:o}},i="!unvouchable",b=(o,n,s)=>{if(!n)return o;const r=new Set(s);return new Proxy(o,{get(e,t,a){const u=Reflect.get(e,t,a);return typeof u!="function"||typeof t!="string"||!r.has(t)?u:(...c)=>(n(i),Reflect.apply(u,e,c))}})};export{i as UNVOUCHABLE_DEP,f as createReadFootprint,b as markUnvouchableReads};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{isLunoraError as S}from"@lunora/errors";import{l as R,b as L}from"./ctx-db-search-state-CPKPy8N6.mjs";import{sql as e}from"drizzle-orm";import{readKeysetPage as _}from"./backfillAggregateIndexes-CRNxxM19.mjs";import{runDrizzle as p}from"./runDrizzle-RC09zZrh.mjs";import{h}from"./do-sql-RROYQPCM.mjs";const u="__lunora_vector_backfill",m=50,k=20,w=20,N=3,O=i=>{p(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(u)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("cursor")} TEXT, ${e.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${e.identifier("profile")} TEXT, ${e.identifier("strikes")} INTEGER NOT NULL DEFAULT 0)`);try{p(i,e`ALTER TABLE ${e.identifier(u)} ADD COLUMN ${e.identifier("strikes")} INTEGER NOT NULL DEFAULT 0`)}catch{}},C=(i,o)=>{const[s]=p(i,e`SELECT ${e.identifier("strikes")} FROM ${e.identifier(u)} WHERE ${e.identifier("companion")} = ${o}`).toArray();return s?.strikes??0},$=(i,o,s,d,t,r=0)=>{const n=s??null;p(i,e`INSERT INTO ${e.identifier(u)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("strikes")}) VALUES (${o}, ${n}, ${d?1:0}, ${t}, ${r}) ON CONFLICT (${e.identifier("companion")}) DO UPDATE SET ${e.identifier("cursor")} = excluded.${e.identifier("cursor")}, ${e.identifier("done")} = excluded.${e.identifier("done")}, ${e.identifier("profile")} = excluded.${e.identifier("profile")}, ${e.identifier("strikes")} = excluded.${e.identifier("strikes")}`)},A=(i,o,s)=>{const d=_(i,o,s,m+1),t={documents:[],lastId:s,more:d.length>m,unparseable:[]};for(const r of d.slice(0,m)){if(typeof r.id!="string")continue;t.lastId=r.id;const n=h(r);n?t.documents.push({doc:n,id:t.lastId}):t.unparseable.push(t.lastId)}return t},D=(i,o,s,d,t)=>{const r=t instanceof Error?t.message:String(t),n=L(i,u,o),a=n.profile===d&&n.cursor===s?C(i,o):0;if(S(t)&&t.code==="SERVICE_UNAVAILABLE")return a>0&&$(i,o,s,!1,d,0),{error:r};const f=a+1;if(f<N)return $(i,o,s,!1,d,f),{error:r};const c=A(i,o,s),l=[...c.documents.map(E=>E.id),...c.unparseable];return console.warn(`[@lunora/shard-engine] vector backfill: a page of "${o}" failed ${String(f)} times in a row; its ${String(l.length)} row(s) are recorded as failed:`,t),{failedIds:l,page:c}},F=async(i,o,s,d,t)=>{const{profile:r,table:n}=o;try{const{failures:a,page:f}=await t(()=>A(i,n,s),async c=>({failures:await d(n,c.documents),page:c}));return a.length>0&&console.warn(`[@lunora/shard-engine] vector backfill: ${String(a.length)} row(s) of "${n}" could not be indexed:`,a),{failedIds:[...f.unparseable,...a.map(c=>c.id)],page:f}}catch(a){return D(i,n,s,r,a)}},y=async(i,o,s,d)=>{if(O(i),d.restart===!0)for(const{profile:n,table:a}of o)$(i,a,void 0,!1,n);const t=Math.min(d.maxPages??1,k),r={done:!1,failed:0,failedIds:[],pages:0,rows:0};for(const{profile:n,table:a}of o){const f=R(L(i,u,a),n);let{cursor:c}=f,l=f.finished;for(;!l;){if(r.pages>=t)return r;const E=await F(i,{profile:n,table:a},c,s,d.ordered);if("error"in E)return{...r,error:E.error};const{failedIds:g,page:T}=E,I=T.documents.length+T.unparseable.length;r.pages+=I>0?1:0,r.rows+=I,r.failed+=g.length,r.failedIds=[...r.failedIds,...g].slice(0,w),c=T.lastId,l=!T.more,$(i,a,c,l,n)}}return{...r,done:!0}};export{k as VECTOR_BACKFILL_MAX_PAGES,m as VECTOR_BACKFILL_PAGE_ROWS,y as backfillVectorIndexes};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as f}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{SQLiteDialect as u}from"drizzle-orm/sqlite-core";const S=new u,s={boundParams:100,compoundSelect:5,likePattern:50,sqlTextLength:1e5},d=s.boundParams/2,h=n=>n===null||typeof n=="boolean"?!0:typeof n=="number"?Number.isFinite(n):typeof n=="string"&&n.isWellFormed(),p=n=>{const e=[];for(const r of n){if(!(r instanceof Uint8Array))return;e.push(Array.from(r,o=>o.toString(16).padStart(2,"0")).join(""))}return JSON.stringify(e)},N=(n,e)=>{if(n!=="sqlite")throw new f("INTERNAL",`renderSql only renders SQLite; use SqlDialect.render for "${n}"`);const{params:r,sql:o}=S.sqlToQuery(e);return{params:r,sql:o}},L=n=>t`${n}`,y=n=>{if(n.length===0)throw new Error("unionAll: expected at least one branch");let e=[...n];for(;e.length>s.compoundSelect;){const r=[];for(let o=0;o<e.length;o+=s.compoundSelect){const i=t.join(e.slice(o,o+s.compoundSelect),t` UNION ALL `);r.push(t`SELECT * FROM (${i}) ${t.identifier("__u__")}`)}e=r}return t.join(e,t` UNION ALL `)},T=(n,e,r,o=d)=>{const i=r?t` NOT IN `:t` IN `,a=e.every(l=>h(l)),c=e.length>o&&!a?p(e):void 0;if(c!==void 0)return t`${n}${i}(SELECT unhex(${t.identifier("value")}) FROM json_each(${c}))`;if(e.length>o&&!a)throw new f("BAD_REQUEST",`an "in" list of ${String(e.length)} values holds a value JSON cannot carry (bytes, a non-finite number, or malformed text), so it cannot be bound as one parameter — and ${String(e.length)} placeholders exceed SQLite's per-statement cap of 100 on Durable Objects and D1. Narrow the list to ${String(o)} values or fewer.`);return e.length<=o?t`${n}${i}(${t.join(e.map(l=>L(l)),t`, `)})`:t`${n}${i}(SELECT ${t.identifier("value")} FROM json_each(${JSON.stringify(e)}))`};export{s as WORKERD_SQLITE_LIMITS,p as bytesAsHexJson,h as isJsonSafe,L as param,N as renderSql,T as sqliteInList,y as unionAll};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{e as o}from"./effective-kind-BmG_zCAy.mjs";const a=new Set(["any","null"]),s=(t,n)=>{const l=n.kindOf(t);return l!==void 0&&a.has(l)||n.nullableOf(t)?!0:l==="union"&&(n.membersOf(t)??[]).some(i=>s(i,n))},e=t=>{const n=t._meta?.inner;return t.kind==="optional"&&n?e(n):t},u=t=>s(t,{kindOf:o,membersOf:n=>e(n)._meta?.members,nullableOf:n=>e(n)._meta?.column?.notNull===!1});export{u as v};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";import{encodeWire as i}from"@lunora/wire";const a=BigInt(Number.MAX_SAFE_INTEGER),c=(e,t)=>e<t?-1:e>t?1:0,s=(e,t)=>`${e}__agg_${t}`,l=e=>{if(typeof e=="bigint"){if(e>a||e<-a)throw new g("BAD_REQUEST",`bigint ${e.toString()} exceeds Number.MAX_SAFE_INTEGER, so an aggregateIndex declared over this column cannot tally it exactly (the companion's value column is a REAL) — drop the aggregateIndex, aggregate a narrower column, or read the rows and reduce them in the handler`);return Number(e)}if(typeof e=="number")return Number.isFinite(e)?e:void 0},v=(e,t,n,u)=>{const r=e.get(t)??{count:0,value:null};if(n.op==="count"){r.count+=1,r.value=r.count,e.set(t,r);return}const o=l(u[n.field??""]);if(n.op==="sum"||n.op==="avg"){o!==void 0&&(r.value=(r.value??0)+o,r.count+=1),e.set(t,r);return}r.count+=1,o!==void 0&&(r.value===null?r.value=o:r.value=n.op==="min"?Math.min(r.value,o):Math.max(r.value,o)),e.set(t,r)},d=(e,t)=>e==="count"?t?.value??0:!t||t.count===0?null:e==="avg"?t.value===null?null:t.value/t.count:t.value,A=(e,t)=>{if(e.length===0)return"";const n={};for(const u of e.toSorted(c))n[u]=t[u]??null;return JSON.stringify(i(n))};export{s as aggregateTableName,l as coerceAggregateNumber,c as compareStrings,A as encodeAggregateKey,v as foldAggregateTally,d as readAggregateValue};
|
|
@@ -0,0 +1,17 @@
|
|
|
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)} (
|
|
2
|
+
run_key TEXT PRIMARY KEY,
|
|
3
|
+
status TEXT NOT NULL,
|
|
4
|
+
last_seq INTEGER NOT NULL DEFAULT 0,
|
|
5
|
+
error_code TEXT,
|
|
6
|
+
error TEXT,
|
|
7
|
+
started_at REAL NOT NULL,
|
|
8
|
+
ttl_ms REAL NOT NULL
|
|
9
|
+
)`),o(r,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (
|
|
10
|
+
run_key TEXT NOT NULL,
|
|
11
|
+
seq INTEGER NOT NULL,
|
|
12
|
+
data_json TEXT NOT NULL,
|
|
13
|
+
PRIMARY KEY (run_key, seq)
|
|
14
|
+
)`)},_=(r,e)=>{const s=o(r,t`SELECT status, last_seq, error_code, error, started_at FROM ${t.identifier(E)} WHERE run_key = ${e} LIMIT 1`).toArray()[0];if(s!==void 0)return{...s.error===null?{}:{error:s.error},...s.error_code===null?{}:{errorCode:s.error_code},lastSeq:s.last_seq,startedAt:s.started_at,status:s.status}},T=(r,e)=>{o(r,t`DELETE FROM ${t.identifier(i)} WHERE run_key = ${e}`)},c=(r,e,n,s)=>_(r,e)!==void 0?!1:(T(r,e),o(r,t`INSERT INTO ${t.identifier(E)} (run_key, status, last_seq, started_at, ttl_ms)
|
|
15
|
+
VALUES (${e}, ${"running"}, 0, ${n}, ${s})`),!0),R=(r,e)=>{T(r,e),o(r,t`DELETE FROM ${t.identifier(E)} WHERE run_key = ${e}`)},m=(r,e,n,s)=>{o(r,t`INSERT OR IGNORE INTO ${t.identifier(i)} (run_key, seq, data_json) VALUES (${e}, ${n}, ${s})`)},A=(r,e,n)=>o(r,t`SELECT seq, data_json FROM ${t.identifier(i)} WHERE run_key = ${e} AND seq > ${n} ORDER BY seq ASC`).toArray().map(s=>({dataJson:s.data_json,seq:s.seq})),$=(r,e,n,s,a)=>{if(_(r,e)===void 0){T(r,e);return}const d=a?.code??null,u=a?.message??null;o(r,t`UPDATE ${t.identifier(E)}
|
|
16
|
+
SET status = ${n}, last_seq = ${s}, error_code = ${d}, error = ${u}
|
|
17
|
+
WHERE run_key = ${e}`)},f=(r,e,n)=>{const s=o(r,t`SELECT run_key FROM ${t.identifier(E)} WHERE started_at + ttl_ms < ${e}`).toArray();for(const{run_key:a}of s)n.has(a)||R(r,a)};export{m as appendStreamChunk,c as claimStreamRun,R as deleteStreamRun,$ as finishStreamRun,N as migrateDurableStreams,A as readStreamChunks,_ as readStreamRun,f as trimStreamRuns};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as S}from"@lunora/errors";import{t as z}from"./do-sql-RROYQPCM.mjs";import{applySelect as Y}from"./CURSOR_PREFIX-6offuG6M.mjs";const U=Symbol.for("lunora.relations.fanOutBudget"),de=e=>({fanOutBudget:e[U],relationBaseWhere:e.relationBaseWhere,relationMask:e.relationMask}),L=(e,t)=>t.select?Y(e,t.select,t.with):e,pe=async(e,t,n,r,o)=>{const a=await Promise.all(r.map(async c=>{const u=o?{AND:[{[n]:c},o]}:{[n]:c};return[c,await e(t,u)]}));return new Map(a)},ee=32,B=1e4,te=(e,t,n)=>{const r=new Map;for(const o of e)for(const a of n(o)){const c=a[t],u=r.get(c);u?u.push(a):r.set(c,[a])}return r},W=(e,t)=>({...e,[U]:t}),ne=(e,t)=>{const n=new Map;for(const[o,a]of e)for(const c of a){const u=n.get(c);u?u.push(o):n.set(c,[o])}const r=new Map;for(const o of t)for(const a of n.get(o._id)??[]){const c=r.get(a);c?c.push(o):r.set(a,[o])}return r},D=(e,t)=>{const n=new Set;for(const r of e){const o=r[t];o!=null&&n.add(o)}return[...n]},he=async e=>{const{groupedCounter:t,fanOutBudget:n,fetcher:r,parents:o,relationBaseWhere:a,relationMask:c,schema:u,tableName:p,with:b}=e,O=n??{remaining:ee},y=(f,s)=>c?.(f,s)??s;if(o.length===0)return;const M=u.tables[p];if(!M)throw new S("INTERNAL",`unknown table: ${p}`);const _=M.relationMap??{},G=(f,s)=>{const i=d=>u.tables[d]?.shardMode?.kind??"root";return i(f)===i(s)&&i(f)!=="shardBy"},R=f=>{const s=_[f];if(!s)throw new S("INTERNAL",`unknown relation "${f}" on table "${p}"`);return s},X=async(f,s,i)=>{const d=D(o,s.field);if(d.length===0){for(const h of o)h[f]=null;return}const{page:l}=await r(s.table,W({baseWhere:a?.(s.table),relationBaseWhere:a,relationMask:c,where:{[s.references]:{in:d}},with:i.with},O)),w=new Map;for(const h of y(s.table,l))w.set(h[s.references],h);for(const h of o){const A=w.get(h[s.field]);h[f]=A?L([A],i)[0]??null:null}},j=async(f,s,i,d)=>{const{page:l}=await r(f,W({baseWhere:a?.(f),limit:d,orderBy:s.orderBy,relationBaseWhere:a,relationMask:c,where:s.where?{AND:[s.where,i]}:i,with:s.with},O));return l},T=(f,s,i,d,l)=>{for(const w of o){const h=l.get(w[d])??[];w[f]=L(i===void 0?h:h.slice(0,i),s)}},K=async(f,s,i)=>{const d=D(o,s.references);if(d.length===0){for(const g of o)g[f]=[];return}const l=typeof i.limit=="number"?Math.max(0,Math.floor(i.limit)):void 0,w=(g,k)=>j(s.table,i,g,k);if(l===0){for(const g of o)g[f]=[];return}const h=l!==void 0&&d.length<=O.remaining;h&&(O.remaining-=d.length);const A=h?await Promise.all(d.map(async g=>w({[s.field]:g},l))):[await w({[s.field]:{in:d}},void 0)],m=te(A,s.field,g=>y(s.table,g));T(f,i,l,s.references,m)},I=async f=>{const{from:s,table:i,to:d}=f.through,l=new Map,w=D(o,"_id");if(w.length===0)return l;const h=await j(i,{},{[s]:{in:w}},B+1);if(h.length>B)throw new S("INTERNAL",`loading "${p}" relations through "${i}" read more than ${String(B)} join rows for one page; load fewer ${p} rows at a time`);for(const A of y(i,h)){const m=A[s],g=A[d];if(m==null||g===null||g===void 0)continue;const k=l.get(m);k?k.add(g):l.set(m,new Set([g]))}return l},q=async(f,s,i)=>{const d=typeof i.limit=="number"?Math.max(0,Math.floor(i.limit)):void 0,l=d===0?new Map:await I(s),w=(A,m)=>j(s.table,i,{_id:{in:[...A]}},m);let h=new Map;if(l.size>0&&d!==void 0&&l.size<=O.remaining){O.remaining-=l.size;const A=[...l.keys()],m=await Promise.all([...l.values()].map(async g=>w(g,d)));h=new Map(A.map((g,k)=>[g,y(s.table,m[k]??[])]))}else if(l.size>0){const A=new Set([...l.values()].flatMap(m=>[...m]));h=ne(l,y(s.table,await w(A,void 0)))}T(f,i,d,"_id",h)},Z=async(f,s)=>{const i=[...s];if(i.length===0)return new Set;if(G(p,f)){const l=await t(f,"_id",i,a?.(f));return new Set(i.filter(w=>(l.get(w)??0)>0))}const d=await j(f,{},{_id:{in:i}},void 0);return new Set(d.map(l=>l._id))},J=async(f,s)=>{const i=await I(s),d=await Z(s.table,new Set([...i.values()].flatMap(l=>[...l])));for(const l of o){const w=l._count??{};w[f]=[...i.get(l._id)??[]].filter(h=>d.has(h)).length,l._count=w}},Q=async f=>{for(const s of Object.keys(f)){const i=R(s);if(i.through!==void 0){await J(s,i);continue}const[d,l]=i.kind==="many"?[i.field,i.references]:[i.references,i.field],w=a?.(i.table),h=D(o,l),A=h.length===0?new Map:await t(i.table,d,h,w);for(const m of o){const g=m._count??{},k=m[l];g[s]=k==null?0:A.get(k)??0,m._count=g}}};for(const[f,s]of Object.entries(b)){if(s===void 0||s===!1)continue;if(f==="_count"){await Q(s);continue}const i=R(f),d=s===!0?{}:s;i.through===void 0?await(i.kind==="one"?X(f,i,d):K(f,i,d)):await q(f,i,d)}},N=1e4,x=500,oe=async(e,t,n,r,o)=>{const a=new Set;let c=o;for(;;){const u=c!==void 0,p=c??await e();let b=!1;c=void 0;for(const O of p){const y=O._id;if(!(typeof y!="string"||a.has(y))){if(a.add(y),b=!0,a.size>N)throw n();await t(y)}}if(!u){if(p.length<x)return;if(!b)throw new S("INTERNAL",r)}}},H=(e,t,n)=>new S("CASCADE_LIMIT",`cannot delete "${e}" row: more than ${String(N)} ${t} rows reference it (onDelete: ${n}) — delete or re-point them in batches first`,{status:400}),re=async(e,t,n,r)=>{const{deletedId:o,deletedReference:a,findHolders:c,onRestrict:u,tableName:p}=e,b=n.references==="_id"?o:a(n.references);if(b==null)return;const{field:O}=n,y=`"${t}.${O}"`,M=await c(t,O,b,{limit:r==="restrict"?1:N+1,select:["_id"]});if(M.length!==0){if(r==="restrict")return u(`cannot delete "${p}" row: ${y} still references it`);if(M.length>N)throw H(p,y,r);return{action:r,field:O,holderTable:t,label:y,probe:M,referencedValue:b}}},se=async(e,t,n)=>{const{findHolders:r,onCascade:o,onSetNull:a,tableName:c}=e,{action:u,field:p,holderTable:b,label:O,probe:y,referencedValue:M}=t;await oe(()=>r(b,p,M,{limit:x}),_=>u==="cascade"?o(b,_):a(b,_,p),()=>H(c,O,u),`onDelete on "${c}" made no progress: ${O} rows still match after being processed`,n?y:void 0)},we=async e=>{const{schema:t,tableName:n}=e;if(!t.tables[n])throw new S("INTERNAL",`unknown table: ${n}`);const r=[];for(const[o,a]of Object.entries(t.tables)){const c=a.relationMap;if(c)for(const u of Object.values(c)){if(u.kind!=="one"||u.table!==n||!u.onDelete)continue;const p=await re(e,o,u,u.onDelete);p&&r.push(p)}}for(const[o,a]of r.entries())await se(e,a,o===0)},P=new WeakMap,V=e=>{const t=P.get(e);if(t!==void 0)return t;const n=e._meta,r=[n?.inner,n?.keyValidator,n?.valueValidator,...n?.members??[],...Object.values(n?.shape??{})],o=e.kind==="from"||r.some(a=>a!==void 0&&V(a));return P.set(e,o),o},$=e=>{const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},F=e=>e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):void 0,E=(e,t)=>{if(Object.is(e,t))return!0;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();const n=F(e),r=F(t);if(n!==void 0||r!==void 0)return n!==void 0&&r!==void 0&&Object.getPrototypeOf(e)===Object.getPrototypeOf(t)&&n.length===r.length&&n.every((u,p)=>u===r[p]);if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((u,p)=>E(u,t[p]));if(typeof e!="object"||typeof t!="object"||e===null||t===null||!$(e)||!$(t))return!1;const o=e,a=t,c=Object.keys(o);return c.length===Object.keys(a).length&&c.every(u=>u in a&&E(o[u],a[u]))},C=new WeakMap,ge=e=>{if(C.has(e))return C.get(e);const t=Object.fromEntries(Object.entries(e.shape).filter(([,r])=>V(r))),n=Object.keys(t).length>0?{...e,shape:t}:void 0;return C.set(e,n),n},ie=e=>{let t;return(n,r)=>e===void 0?!1:(t??=e()??{},n in t&&E(r,t[n]))},ae=(e,t)=>{const n=new Set(Object.keys(t).filter(r=>t[r]!==void 0));for(const[r,o]of z(e))o.serverDefault&&n.delete(r);return n},ce=(e,t,n,r,o)=>n.trusted===!0||r!==void 0&&!r.has(e)||o(e,t),v=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=>v(t)):e instanceof Map?new Map([...e].map(([t,n])=>[v(t),v(n)])):e instanceof Set?new Set([...e].map(t=>v(t))):$(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,v(n)])):e,ye=(e,t,n)=>{const r={...t};for(const[o,a]of z(e)){if(a.serverDefault){r[o]=a.serverDefault({auth:n});continue}if(r[o]===void 0){if(a.defaultFn)r[o]=a.defaultFn();else if("defaultValue"in a){const{defaultValue:c}=a;r[o]=v(c)}}}return r},me=(e,t,n={})=>{let r;const o=ie(n.previous),a=n.only??(n.supplied===void 0?void 0:ae(e,n.supplied));for(const[c,u]of Object.entries(e.shape)){if(!(c in t)||typeof u.parse!="function")continue;const p=V(u);if(p&&ce(c,t[c],n,a,o)||n.tolerateStoredNull===!0&&t[c]===null&&u.kind==="optional")continue;const b=u.parse(t[c]);p&&(r??={...t},r[c]=b)}return r??t};export{B as MAX_LINK_ROWS,ye as applyInsertDefaults,we as applyOnDelete,D as distinctValues,pe as fanOutScalarCounts,de as relationHooks,he as resolveWith,me as runRowValidators,ge as transformOnlyDefinition};
|
|
@@ -0,0 +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)} (
|
|
2
|
+
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
3
|
+
seq INTEGER NOT NULL
|
|
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};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as a}from"@lunora/errors";const t=()=>Object.assign(new Error("native PITR is unavailable here (local dev or a non-SQLite Durable Object); use `lunora backup restore` for off-platform recovery"),{code:"PITR_UNAVAILABLE",name:"LunoraError",status:409}),i=o=>{if(typeof o=="number")return o;const r=Date.parse(o);if(Number.isNaN(r))throw new a("BAD_REQUEST",`pitr: invalid time "${o}" — expected epoch-ms or an ISO timestamp`);return r},
|
|
1
|
+
import{LunoraError as a}from"@lunora/errors";const t=()=>Object.assign(new Error("native PITR is unavailable here (local dev or a non-SQLite Durable Object); use `lunora backup restore` for off-platform recovery"),{code:"PITR_UNAVAILABLE",name:"LunoraError",status:409}),i=o=>{if(typeof o=="number")return o;const r=Date.parse(o);if(Number.isNaN(r))throw new a("BAD_REQUEST",`pitr: invalid time "${o}" — expected epoch-ms or an ISO timestamp`);return r},k=async(o,r)=>{if(!o.getCurrentBookmark)throw t();const e=await o.getCurrentBookmark();return r===void 0||!o.getBookmarkForTime?{current:e}:{current:e,forTime:await o.getBookmarkForTime(i(r))}},s=async(o,r)=>{if(!o.onNextSessionRestoreBookmark)throw t();let e=r.bookmark;if(e===void 0){if(r.time===void 0)throw new a("BAD_REQUEST","pitrRestore: provide a `bookmark` or a `time` to restore to");if(!o.getBookmarkForTime)throw t();e=await o.getBookmarkForTime(i(r.time))}const n=await o.onNextSessionRestoreBookmark(e);return{restoredTo:e,undoBookmark:n}};export{s as armRestore,k as readBookmark};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as a}from"@lunora/errors";import{e as u}from"./effective-kind-BmG_zCAy.mjs";import{a as k,i as m,r as $,F as g,e as R,s as F}from"./json-field-path-DeJW4U9z.mjs";const d={decrement:{apply:(e,t)=>e-t,kind:"number"},divide:{apply:(e,t)=>e/t,kind:"number"},increment:{apply:(e,t)=>e+t,kind:"number"},multiply:{apply:(e,t)=>e*t,kind:"number"},toggle:{kind:"boolean"}};class s extends Error{}const w=e=>{if(!k(e))return;const t=Object.keys(e),[n]=t;if(!(t.length!==1||n===void 0||!Object.hasOwn(d,n)))return{operand:e[n],operator:n}},b=e=>w(e)!==void 0,P=(e,t,n,o)=>{const r=d[t];if(r.apply===void 0){if(n!==!0)throw new s(`patch: use { toggle: true } on "${e}".`);if(typeof o!="boolean")throw new s(`patch: cannot toggle "${e}" — its current value is ${String(o)}; set a boolean first.`);return!o}if(typeof n!="number"||!Number.isFinite(n))throw new s(`patch: "${t}" on "${e}" needs a finite number, got ${String(n)}.`);if(typeof o!="number"||!Number.isFinite(o))throw new s(`patch: cannot ${t} "${e}" — its current value is ${String(o)}; set a number first.`);if(t==="divide"&&n===0)throw new s(`patch: cannot divide "${e}" by zero.`);const i=r.apply(o,n);if(!Number.isFinite(i))throw new s(`patch: "${t}" on "${e}" overflows to ${String(i)}.`);return i},v=(e,t)=>{const n=new Set;for(const[o,r]of Object.entries(e))t(o)!==void 0&&b(r)&&n.add(o);return n},E=(e,t,n)=>{let o;for(const r of v(e,n)){const{operand:i,operator:c}=w(e[r]),f=n(r);if(d[c].kind!==f)throw new s(`patch: "${c}" does not apply to the ${String(f)} column "${r}".`);o??={...e},o[r]=P(r,c,i,t[r])}return o??e},j=new Set(["date","number","timestamp"]),l=e=>e.kind==="optional"&&e._meta?.inner!==void 0?l(e._meta.inner):e,p=e=>{const t=l(e);if(t.kind!==void 0&&j.has(t.kind))return"number";if(t.kind==="boolean")return"boolean";if(t.kind!=="union")return;const n=new Set((t._meta?.members??[]).filter(r=>u(r)!=="null").map(r=>p(r))),[o]=n;return n.size===1?o:void 0},O=e=>t=>{const n=Object.hasOwn(e.shape,t)?e.shape[t]:void 0;return n===void 0?void 0:p(n)},A=(e,t)=>v(t,O(e)),I=(e,t,n)=>{try{return E(t,n,O(e))}catch(o){throw o instanceof s?new a("VALIDATION_ERROR",o.message):o}},h=e=>{throw e instanceof g?new a("VALIDATION_ERROR",e.message):e},y=e=>{if(e===void 0)return;const t=l(e);if(t.kind==="object")return t._meta?.shape;if(t.kind!=="union")return;const n=(t._meta?.members??[]).filter(o=>u(o)!=="null");return n.length===1?y(n[0]):void 0},N=(e,t)=>{let n=e.shape[t[0]??""];for(const o of t.slice(1)){const r=y(n);n=r!==void 0&&Object.hasOwn(r,o)?r[o]:void 0}return n},_=(e,t,n)=>{let o=[];try{o=F(t)}catch(i){h(i)}const r=N(e,o);if(r===void 0)throw new a("VALIDATION_ERROR",`patch: "${t}" is not a path into an object column of this table`);if(p(r)!==void 0&&b(n))throw new a("VALIDATION_ERROR",`patch: "${t}" is nested inside a column; operators like increment apply to a top-level column only`);if(typeof r.parse=="function")try{r.parse(n)}catch(i){throw new a("VALIDATION_ERROR",`patch: "${t}" ${i instanceof Error?i.message:"is invalid"}`)}},S=(e,t,n)=>{for(const[o,r]of Object.entries(t))m(o)&&_(e,o,r);try{return R(t,n)}catch(o){return h(o)}},V=(e,t,n)=>S(e,I(e,t,n),n),x=(e,t)=>A(e,t).size>0||Object.keys(t).some(n=>m(n)),z=(e,t,n)=>{if(e?.verify!==void 0&&!e.verify(t,n))throw new a("FORBIDDEN","update denied by policy")},K=(e,t)=>{try{return $(e,t)}catch(n){return h(n)}};export{z as assertPatchAllowed,A as operatorFields,x as patchDependsOnRow,K as readPatchField,V as resolvePatch};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{isPlainObject as w,stableStringify as A,encodeWire as $,needsWireEncoding as L}from"@lunora/wire";const O="_id",g="_creationTime",y="page",_=t=>{let e;for(const s of t){const o=s[g];if(typeof o=="number"){if(e!==void 0){if(o<e)return!0;if(o>e)return!1}e=o}}return!1},E=(t,e)=>{const s=e[g];if(typeof s!="number")return t.length;const o=_(t);for(const[n,r]of t.entries()){const i=r[g];if(typeof i=="number"&&(o?i<s:i>s))return n}return t.length},N="__lunora__",M=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return;const e=t[O];return typeof e=="string"?e:void 0},I=t=>{const e=new Map,s=[];for(const o of t){const n=M(o);if(n===void 0||e.has(n))return;e.set(n,o),s.push(n)}return{byId:e,order:s}},T=(t,e)=>{const s=t.order.filter(n=>e.byId.has(n)),o=e.order.filter(n=>t.byId.has(n));return s.length!==o.length?!1:s.every((n,r)=>o[r]===n)},J=(t,e,s,o)=>{const n=[];for(const r of t.order)e.byId.has(r)||n.push({delta:{key:r,op:"delete",table:s},frame:`{"key":${JSON.stringify(r)},"op":"delete","table":${o}}`});return n},P=(t,e,s,o)=>{const n=[];for(const r of e.order){const i=e.byId.get(r),a=t.byId.get(r),d=JSON.stringify(L(i)?$(i):i),c=a===void 0?void 0:JSON.stringify(a);if(c===d)continue;const f=c===void 0?"insert":"update";n.push({delta:{key:r,op:f,row:i,table:s},frame:`{"key":${JSON.stringify(r)},"op":"${f}","row":${d},"table":${o}}`})}return n},R=(t,e)=>{if(Array.isArray(t)&&Array.isArray(e))return{next:e,previous:t};if(!w(t)||!w(e))return;const s=t[y],o=e[y];if(!Array.isArray(s)||!Array.isArray(o))return;const n=r=>Object.fromEntries(Object.entries(r).filter(([i])=>i!==y));if(A(n(t))===A($(n(e))))return{next:o,previous:s}},k=(t,e,s)=>{const o=s.filter(({delta:r})=>r.op==="insert");if(o.length===0)return!0;const n=t.order.filter(r=>e.byId.has(r)).map(r=>t.byId.get(r));for(const{delta:r}of o){const i=r.row;n.splice(E(n,i),0,i)}return n.length===e.order.length&&n.every((r,i)=>r[O]===e.order[i])},p=(t,e,s)=>{let o;try{o=JSON.parse(t)}catch{return}const n=R(o,e);if(n===void 0)return;const r=I(n.previous),i=I(n.next);if(r===void 0||i===void 0||!T(r,i))return;const a=s===""?N:s,d=JSON.stringify(a),c=[...J(r,i,a,d),...P(r,i,a,d)];return k(r,i,c)?c:void 0},D=new WeakMap,j=(t,e,s,o)=>{if(o===void 0)return p(t,e,s);let n=D.get(o);n===void 0&&(n=new Map,D.set(o,n));let r=n.get(s);if(r===void 0&&(r=new Map,n.set(s,r)),r.has(t))return r.get(t);const i=p(t,e,s);return r.set(t,i),i},G=(t,e,s,o)=>{const n=p(t,e,s);if(n!==void 0){if(o!==void 0)for(const{frame:r}of n)o.push(r);return n.map(({delta:r})=>r)}},K=(t,e)=>{try{return t.send(e),!0}catch{return!1}},U=t=>{const{cursorSuffix:e,lastMutationId:s,nextResult:o,pageDeltas:n,previousJson:r,snapshotJson:i,subId:a,table:d}=t,c=JSON.stringify(a),f=s===void 0?"":`,"lastMutationId":${String(s)}`,v=f+e,l=`{"type":"data","id":${c},"data":${i}${v}}`,u=r!==void 0&&(n===!0||Array.isArray(o))?j(r,o,d,t.diffKey):void 0;if(u===void 0||u.length===0)return[l];const b=[];let h=0;for(const[S,{frame:x}]of u.entries()){const F=S===u.length-1?v:`${f},"more":true`,m=`{"type":"delta","id":${c},"delta":${x}${F}}`;if(h+=m.length,h>=l.length)return[l];b.push(m)}return b},q=async t=>{let e=0;for(;e<100;){e+=1;const{bufferedAmount:s}=t;if(typeof s!="number"||s<1048576)return;await new Promise(o=>{setTimeout(o,20)})}};export{q as awaitWsDrain,U as subscriptionFrames,G as subscriptionListDeltas,K as trySendFrame};
|
|
@@ -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-CPKPy8N6.mjs";import{S as I,c as L,g as _,d as x,e as b,a as k}from"./fts-companion-CE3EmIjk.mjs";import{sql as i}from"drizzle-orm";import{ensureAggregateCompanion as y,ensureRankCompanion as B}from"./createCompanionSync-qhvw6wyL.mjs";import{runDrizzle as p,runAll as C}from"./runDrizzle-RC09zZrh.mjs";import{i as M,D as m,h as A}from"./do-sql-RROYQPCM.mjs";import{sqliteInList as U}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";const v=(e,o)=>p(e,i`SELECT 1 FROM ${i.identifier(o)} LIMIT 1`).toArray().length>0,Q=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(n.shardMode?.kind!=="global")for(const t of n.aggregateIndexes??[])y(e,r,t,n.softDeleteMode?.field)},X=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(n.shardMode?.kind!=="global")for(const t of n.rankIndexes??[])B(e,r,t,n.softDeleteMode?.field)},H=(e,o,r,n)=>p(e,r===void 0?i`SELECT id, _creationTime, ${i.identifier(m)} FROM ${i.identifier(o)} ORDER BY id ASC LIMIT ${i.raw(String(n))}`:i`SELECT id, _creationTime, ${i.identifier(m)} FROM ${i.identifier(o)} WHERE id > ${r} ORDER BY id ASC LIMIT ${i.raw(String(n))}`).toArray(),h=500,O=(e,o,r)=>{const n=I(o,r.name),t=E(r),a=w(T(e,n),t);if(a.finished)return{done:!0,rows:0};const{cursor:c}=a,s=H(e,o,c,h);let f=c;for(const g of s){const{id:u}=g;if(typeof u!="string")continue;f=u;const S=A(g);C(e,S?x(n,u,b(S,r)):k(n,u))}const d=s.length<h;return F(e,n,f,d,t),{done:d,rows:s.length}},l=(e,o)=>i`${i.identifier(e)}.${i.identifier(o)}`,R=500,$=(e,o,r)=>{const n=I(o,r.name),t=p(e,L(n,R)).toArray(),a=_(t);if(a.size===0)return!0;const c=new Map;for(const s of p(e,i`SELECT ${l(o,"id")}, ${l(o,"_creationTime")}, ${l(o,m)} FROM ${i.identifier(o)} WHERE ${U(l(o,"id"),[...a.keys()],!1)}`))c.set(String(s.id),s);for(const[s,f]of a){const d=c.get(s),g=d?A(d):void 0;C(e,g?x(n,s,b(g,r),{unmappedRowids:f}):k(n,s,{unmappedRowids:f}))}return t.length<R},W=(e,o,r,n)=>{let t=0;for(;t<n&&!$(e,o,r);)t+=1;return t},Z=(e,o,r)=>{const n=I(o,r.name),t=E(r);return w(T(e,n),t).finished?!0:D(e,n)},q=(e,o,r)=>{if(M(e))for(const n of r.searchIndexes??[])$(e,o,n),!(n.staged&&v(e,o))&&O(e,o,n)},j=(e,o,r,n)=>{let t=0;for(;;){if(t>=n)return{done:!1,pages:t};const a=O(e,o,r);if(a.rows>0&&(t+=1),a.done)return{done:!0,pages:t}}},ee=(e,o,r={})=>{if(!M(e))return{done:!0,pages:0};P(e);const n=r.maxPages??Number.POSITIVE_INFINITY;let t=0;for(const[a,c]of Object.entries(o.tables))if(!(c.shardMode?.kind==="global"||!c.searchIndexes))for(const s of c.searchIndexes){if(t+=W(e,a,s,n-t),t>=n)return{done:!1,pages:t};const f=j(e,a,s,n-t);if(t+=f.pages,!f.done)return{done:!1,pages:t}}return{done:!0,pages:t}};export{Q as backfillAggregateIndexes,X as backfillRankIndexes,ee as backfillSearchIndexes,q as backfillSearchIndexesForTable,H as readKeysetPage,Z as searchIndexCoversTable};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{compareStrings as S}from"./aggregateTableName-B_CtIQCS.mjs";import{float64SqlKey as I}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";const a="!",d="",f=void 0,R=e=>{const n=new TextEncoder().encode(e);let o="";for(const t of n)o+=t.toString(16).padStart(2,"0");return o},g=e=>e===null?"0":typeof e=="number"?Number.isFinite(e)?`1${I(e)}`:f:typeof e=="string"?`2${R(e)}`:f,m=e=>{const n=[];for(const o of e){const t=g(o);if(t===f)return f;n.push(t)}return n.join(a)},v="=",E=new Set([">",">="]),K=new Set(["<","<="]),N=(e,n,o,t)=>{const r=n.comparator===v,i=E.has(n.comparator)||K.has(n.comparator);return!r&&!i||e.indexOf(n.field)!==o?!1:t===void 0?!0:!r&&t===n.field},k=(e,n,o)=>{const t={equalities:[],lowerExclusive:!1,upperExclusive:!1};let r;for(const i of n){const s=i.comparator===v,u=E.has(i.comparator);if(!N(e,i,t.equalities.length,r))return;if(s){t.equalities.push(o(i.value));continue}if(r=i.field,u){if(t.lower!==void 0)return;t.lower=o(i.value),t.lowerExclusive=i.comparator===">"}else{if(t.upper!==void 0)return;t.upper=o(i.value),t.upperExclusive=i.comparator==="<"}}return t},h=(e,n)=>{const o=g(n);if(o!==void 0)return e===""?o:e+a+o},B=(e,n,o,t,r)=>{if(o.length===0)return;const i=k(o,t,r);if(!i)return;const s=m(i.equalities);if(s===void 0)return;let u=s,l=s+d;if(i.lower!==void 0){const c=h(s,i.lower);if(c===void 0)return;u=i.lowerExclusive?c+a+d:c}if(i.upper!==void 0){const c=h(s,i.upper);if(c===void 0)return;l=i.upperExclusive?c:c+d}if(!(u>=l))return{hi:l,index:n,lo:u,table:e}},C=(e,n,o)=>{const t=[];for(const r of e){const i=m(r.fields.map(s=>o(n[s])));i!==void 0&&t.push({index:r.name,key:i})}return t},H=(e,n)=>e.index===n.index&&n.key>=e.lo&&n.key<e.hi,y="!id",p=d,L=(e,n)=>{if(n.length===e.length)return n;const o=new Set(n.map(t=>t.index));return[...n,...e.filter(t=>!o.has(t.name)).map(t=>({index:t.name,key:p}))]},O=e=>({index:y,key:e}),w=new WeakSet,U=(e,n)=>{const o={hi:`${n}\0`,index:y,lo:n,table:e};return w.add(o),o},Y=e=>w.has(e),A=e=>{const n=e.toSorted((t,r)=>S(t.lo,r.lo)),o=[];for(const t of n){const r=o.at(-1);r&&t.lo<=r.hi?t.hi>r.hi&&(o[o.length-1]={...r,hi:t.hi}):o.push(t)}return o},T=(e,n)=>{let o=0,t=e.length-1;for(;o<=t;){const r=Math.floor((o+t)/2),i=e[r];if(n<i.lo)t=r-1;else if(n>=i.hi)o=r+1;else return!0}return!1},x=(e,n)=>{const o=new Map;for(const t of e){const r=o.get(t.index);r?r.push(n(t)):o.set(t.index,[n(t)])}return o},q=(e,n)=>{let o=!1;for(const t of n)if(t.index===e.index){if(t.key===p||t.key>=e.lo&&t.key<e.hi)return!0;o=!0}return!o},D=(e,n)=>{if(!e||e.length===0||!n||n.length===0)return!0;if(e.length===1)return q(e[0],n);const o=x(n,r=>r.key);if(e.some(r=>!o.has(r.index)))return!0;const t=x(e,r=>r);for(const[r,i]of t){const s=i.length===1?i:A(i);if(o.get(r).some(u=>u===p||T(s,u)))return!0}return!1};export{B as buildIndexRange,O as idIndexKey,U as idRange,C as indexKeysForRow,Y as isPointRange,D as keysTouchRanges,H as rangeContains,L as withUnknownIndexKeys};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{encodeWire as h}from"@lunora/wire";const u=(t,e)=>{if(!e)return t;const a=Object.create(null);for(const s of["_id","_creationTime",...e])Object.hasOwn(t,s)&&(a[s]=t[s]);return a},y=(t,e,a)=>{const{columns:s,table:p}=a,i=new Map,c=[];for(const{doc:n,id:r}of t){const o=u(n,s),d=JSON.stringify(h(o));i.set(r,d);const f=e.get(r);f===void 0?c.push({key:r,op:"insert",table:p,value:o}):f!==d&&c.push({key:r,op:"update",table:p,value:o})}for(const n of e.keys())i.has(n)||c.push({key:n,op:"delete",table:p});return{next:i,rowsPatch:c}},k=t=>t.map(e=>e.value===void 0?e:{...e,value:h(e.value)}),b=(t,e,a={})=>{const{baseCheckpoint:s,checkpoint:p,epoch:i,lastMutationId:c,pokeId:n}=e,r=[JSON.stringify({baseCheckpoint:s,epoch:i,pokeId:n,type:"pokeStart"})];for(const o of t){const d=a.preEncoded?o.rowsPatch:k(o.rowsPatch),f=o.baseCheckpoint??s;r.push(JSON.stringify({pokeId:n,rowsPatch:d,shapeId:o.shapeId,type:"pokePart",...c===void 0?{}:{lastMutationId:c},...f===void 0?{}:{baseCheckpoint:f},...o.reset===!0?{reset:!0}:{}}))}return r.push(JSON.stringify({checkpoint:p,epoch:i,pokeId:n,type:"pokeEnd"})),r};export{b as buildPokeFrames,y as diffGlobalMembership,k as encodeRowsPatch,u as projectColumns};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{encodeWire as u}from"@lunora/wire";import{quoteIdentifier as l}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as d}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{REPROJECTION_MIGRATION_PREFIX as v,reprojectionMigrationId as w}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{runSql as p}from"./runDrizzle-RC09zZrh.mjs";import{k as m,D as E}from"./do-sql-RROYQPCM.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const f=/key|secret|token|password|passwd|credential|private|auth|bearer|session|cookie|salt|signature|dsn|webhook/iu,l=new Set(["LUNORA_ADMIN_TOKEN","LUNORA_WS_BEARER"]),d=["CF_PAGES_URL","WORKER_URL","LUNORA_WORKER_URL"],u=["CF_ENV","ENVIRONMENT","WORKER_ENV","NODE_ENV"],p=n=>n.length<=4?"••••":`${n.slice(0,4)}${"•".repeat(Math.min(8,n.length-4))}`,R=n=>f.test(n),E=n=>{const e=o=>typeof n[o]=="function";return e("idFromName")||e("idFromString")?"durable-object":e("createMultipartUpload")||e("put")&&e("get")&&e("list")&&e("head")?"r2":e("getWithMetadata")?"kv":e("prepare")&&e("dump")?"d1":e("send")&&e("sendBatch")?"queue":e("fetch")&&!e("get")?"service":"object"},N=n=>{if(typeof n!="object"||n===null)return{};const e=n,o=i=>i.map(c=>e[c]).find(c=>typeof c=="string"&&c!==""),t={},r=o(d),s=o(u);r!==void 0&&(t.workerUrl=r),s!==void 0&&(t.environment=s);const a=e.CF_VERSION_METADATA;if(a!==null&&typeof a=="object"){const i=a;typeof i.id=="string"&&(t.deploymentId=i.id),typeof i.tag=="string"&&(t.versionTag=i.tag)}return t},_=/^(?:dev(?:elopment)?|local(?:host)?|test)$/iu,g=n=>{const e=n??{};for(const o of u){const t=e[o];if(typeof t=="string"&&_.test(t))return!0}return!1},v=n=>{const e=n??{},o=[];for(const[t,r]of Object.entries(e))if(!l.has(t)){if(typeof r=="string"){const s=R(t);o.push({kind:s?"secret":"var",name:t,value:p(r)});continue}if(typeof r=="number"||typeof r=="boolean"){o.push({kind:"var",name:t,value:String(r)});continue}if(r!==null&&typeof r=="object"){o.push({bindingType:E(r),kind:"binding",name:t,value:null});continue}o.push({kind:"var",name:t,value:null})}return o.sort((t,r)=>t.name.localeCompare(r.name)),{deploy:N(e),settings:o}};export{v as buildSettings,g as isDevEnvironment,N as readDeployInfo};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-CTkXVeJx.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-BhK79123.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};
|
|
@@ -0,0 +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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./json-field-path-DeJW4U9z.mjs";import"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{c as p,s}from"./where-sql-BjY4rnqb.mjs";import"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";export{p 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-D7qE3iUe.mjs";import{runDrizzle as A}from"./runDrizzle-RC09zZrh.mjs";import{sqliteInList as O}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{decodeCursor as F,CURSOR_PREFIX as P,toBase64 as U}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as V,sortColumnName as z,resolveRankPartition as H,RANK_TIEBREAK as _,encodePartitionKey as J,rankPivotConditionSql as X}from"./RANK_TIEBREAK-D3ye2GsL.mjs";const Y="__doc__",G=n=>P+U(JSON.stringify(n)),Q=n=>n.after?[n.after.partitionKey,...n.after.sortValues,n.after.rowId]:n.cursor?F(n.cursor):void 0,Z=(n,r,f)=>{if(n?.length!==1+r.length+1)return;const t=[{column:"__partition__",direction:"asc"}];for(const[c,u]of r.entries())t.push({column:u,direction:f[c]?.direction??"asc"});t.push({column:_,direction:"asc"});const e=[];for(const[c,u]of t.entries()){const d=X(u.column,n[c],u.direction,!0);if(d===void 0)continue;const s=[];for(const[m,l]of t.slice(0,c).entries())s.push(o`${o.identifier(l.column)} IS ${n[m]}`);s.push(d);const[i]=s;e.push(s.length===1&&i!==void 0?i:o`(${o.join(s,o` AND `)})`)}return e.length===0?o`(1 = 0)`:o`(${o.join(e,o` OR `)})`},v=null,oo=(n,r)=>{if(n===void 0)return v;const f=[n.__partition__,...r.map(t=>n[t]),n[_]];return G(f)},no=(n,r,f)=>{const t=[];for(const e of n){const c=e[_];if(typeof c!="string")continue;const u=r.get(c);if(!u)continue;const d=typeof e.__partition__=="string"?e.__partition__:"",s=f.map(i=>e[i]??null);t.push({doc:u,key:{partitionKey:d,rowId:c,sortValues:s}})}return t},to=o`${o.identifier("id")}`,ro=(n,r,f)=>{const{rowToDocument:t}=n,e=new Map;if(f.length===0)return e;const c=A(n.sql,o`SELECT id, _creationTime, ${o.identifier(Y)} FROM ${o.identifier(r)} WHERE ${O(to,f,!1)}`).toArray();for(const u of c){const d=t(u),s=u.id;d&&typeof s=="string"&&e.set(s,d)}return e},_o=(n,r,f,t)=>{const{assertRankPartitionLocal:e,ensureRankBackfilled:c,onRead:u,schema:d}=n,s=d.tables[r];if(!s)throw new g("INTERNAL",`unknown table: ${r}`);const i=s.rankIndexes?.find(a=>a.name===f);if(!i)throw new g("INTERNAL",`unknown rankIndex "${f}" on table "${r}"`);e(r,s,i),u(r,j),c(r,i);const m=V(r,i.name),l=i.sortBy.map((a,w)=>z(w)),h=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),T=b(t.baseWhere,t.where),k=H(i,T),R=[o`${o.identifier("__partition__")} ASC`];for(const[a,w]of l.entries()){const W=i.sortBy[a]?.direction;R.push(o`${o.identifier(w)} ${o.raw(W==="desc"?"DESC":"ASC")}`)}R.push(o`${o.identifier(_)} ASC`);const p=[];typeof t.partitionKey=="string"?p.push(o`${o.identifier("__partition__")} = ${t.partitionKey}`):k&&p.push(o`${o.identifier("__partition__")} = ${J(i.partitionBy??[],k)}`);const B=Q(t),E=Z(B,l,i.sortBy);E&&p.push(E);const I=o.identifier(_),S=o.identifier("__partition__"),D=p.length>0?o` WHERE ${o.join(p,o` AND `)}`:o``,L=l.length>0?o`${I}, ${S}, ${o.join(l.map(a=>o.identifier(a)),o`, `)}`:o`${I}, ${S}`,M=o`SELECT ${L} FROM ${o.identifier(m)}${D} ORDER BY ${o.join(R,o`, `)} LIMIT ${o.raw(String(h+1))}`,$=A(n.sql,M).toArray(),C=$.length>h,y=C?$.slice(0,h):$,K=y.map(a=>a[_]),q=no(y,ro(n,r,K),l),x=C?oo(y.at(-1),l):v,N=i.sortBy.map(a=>a.direction==="desc"?"desc":"asc");return{continueCursor:x,directions:N,hasMore:C,rows:q}};export{_o as computeRankPage,Q as resolveRankSeekTuple};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{N as lo,S as uo,d as $o,e as Eo,a as go}from"./fts-companion-CE3EmIjk.mjs";import{sql as o}from"drizzle-orm";import{r as Y}from"./json-field-path-DeJW4U9z.mjs";import{matchesStaticWhere as X,aggregateSqlFunction as po}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as j,foldAggregateTally as J,encodeAggregateKey as k,coerceAggregateNumber as U}from"./aggregateTableName-B_CtIQCS.mjs";import{aggregateSignature as mo,readCompanionSignature as Z,rankSignature as ho,writeCompanionSignature as N}from"./CompanionMemo-BXU5vfak.mjs";import{runAll as So,runDrizzle as g}from"./runDrizzle-RC09zZrh.mjs";import{i as _o,g as yo,a as F,b as A,A as h,c as H,D as x,r as oo,e as V}from"./do-sql-RROYQPCM.mjs";import{WORKERD_SQLITE_LIMITS as eo,param as G}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{encodeGeohash as Ro,GEO_DEFAULT_PRECISION as To}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as no}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as B,matchesRankStaticWhere as to,sortColumnName as Ao,encodePartitionKey as Co}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{mayHoldProjectedValue as wo}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{serializeSqlValue as ro}from"./serializeSqlValue-DeoBMpZ2.mjs";const Io=(r,f,t)=>[...r.partitionBy??[],...r.sortBy.map(l=>l.field),...r.where?Object.keys(r.where):[]].every(l=>Y(f,l)===Y(t,l)),so=r=>o.join(["__id__","__partition__",...r.sortBy.map((f,t)=>Ao(t))].map(f=>o.identifier(f)),o`, `),io=(r,f,t)=>{const $=Co(r.partitionBy??[],t),l=r.sortBy.map(s=>ro(t[s.field]??null)),c=o.join([f,$,...l].map(s=>G(s)),o`, `);return o`(${c})`},Oo=(r,f,t,$,l,c)=>{g(r,o`INSERT INTO ${o.identifier(f)} (${$}) VALUES ${io(t,l,c)}`)},Q=1e3,co=function*(f,t,$,l){let c;for(;;){const s=c===void 0?o``:o` WHERE id > ${G(c)}`,y=[...g(f,o`SELECT id, _creationTime, ${o.identifier(x)} FROM ${o.identifier(t)}${s} ORDER BY id LIMIT ${G(Q)}`)];for(const S of y){const R=oo(S);R&&no(R,$)&&l(R)&&(yield R)}if(y.length<Q)return;c=String(y.at(-1)?.id)}},vo=(r,f,t,$,l)=>{const c=j(f,t.name),s=t.by??[],y=new Map;for(const C of co(r,f,$,I=>!t.where||X(I,t.where)))J(y,k(s,C),t,C);g(r,o`DELETE FROM ${o.identifier(c)}`);const S=Math.floor(eo.boundParams/3),R=[...y];for(let C=0;C<R.length;C+=S){const I=R.slice(C,C+S),P=o.join(I.map(([b,D])=>o`(${b}, ${D.value}, ${D.count})`),o`, `);g(r,o`INSERT INTO ${o.identifier(c)} (${F}, ${A}, ${h}) VALUES ${P}`)}N(r,c,l)},ko=(r,f,t,$)=>{const l=mo(t,$);Z(r,j(f,t.name))!==l&&vo(r,f,t,$,l)},Lo=(r,f,t,$,l)=>{const c=B(f,t.name),s=so(t);g(r,o`DELETE FROM ${o.identifier(c)}`);const y=Math.max(1,Math.floor(eo.boundParams/(2+t.sortBy.length)));let S=[];const R=()=>{S.length>0&&(g(r,o`INSERT INTO ${o.identifier(c)} (${s}) VALUES ${o.join(S,o`, `)}`),S=[])};for(const C of co(r,f,$,I=>!t.where||to(I,t.where)))S.push(io(t,C._id,C)),S.length>=y&&R();R(),N(r,c,l)},Fo=(r,f,t,$)=>{const l=ho(t,$);Z(r,B(f,t.name))!==l&&Lo(r,f,t,$,l)},Do=(r,f,t,$,l,c)=>{if(l&&c&&Io(t,l,c))return;const s=B(f,t.name);l&&g(r,o`DELETE FROM ${o.identifier(s)} WHERE ${o.identifier("__id__")} = ${$}`),!(!c||t.where&&!to(c,t.where))&&Oo(r,s,t,so(t),$,c)},Xo=r=>{const{broadcast:f,indexKeysFor:t,invalidateCache:$,recordCdc:l,schema:c,sql:s}=r,y=r.verified??new Set,S=e=>c.tables[e]?.softDeleteMode?.field,R=(e,n)=>{const a=j(e,n.name);y.has(a)||(ko(s,e,n,S(e)),y.add(a))},C=(e,n,a)=>{const p=n.by??[],d=n.field??"",E=[],_=(i,u)=>{const m=ro(u);m===null?E.push(o`${V(i)} IS NULL`):E.push(o`${V(i)} = ${m}`)};for(const i of p)_(i,a[i]??null);const w=S(e);w!==void 0&&_(w,null);for(const[i,u]of Object.entries(n.where??{}))_(i,u!==null&&typeof u=="object"&&!Array.isArray(u)?u.eq:u);const L=E.length>0?o` WHERE ${o.join(E,o` AND `)}`:o``,M=c.tables[e]?.shape[d];if(M&&wo(M)){const i=g(s,o`SELECT id, _creationTime, ${o.identifier(x)} FROM ${o.identifier(e)}${L}`).toArray(),u=new Map;for(const m of i){const v=oo(m);v&&J(u,"",n,v)}return{value:u.get("")?.value??null}}const W=po(n.op),T=V(d);return{value:g(s,o`SELECT ${o.raw(W)}(${T}) AS value FROM ${o.identifier(e)}${L}`).one().value??null}},I=(e,n,a,p)=>{const d=j(e,n.name),{op:E}=n,_=n.field??"",w=i=>{g(s,o`DELETE FROM ${o.identifier(d)} WHERE ${F} = ${i} AND ${h} <= 0`)},L=S(e),M=i=>!n.where||X(i,n.where),W=i=>no(i,L)&&M(i);p!==void 0&&E!=="count"&&M(p)&&U(p[_]);const T=a&&W(a)?a:void 0,O=p&&W(p)?p:void 0;if(!(!T&&!O)){if(E==="count"){for(const[i,u]of[[T,-1],[O,1]]){if(!i)continue;const m=k(n.by??[],i);g(s,H(d,m,u,u,o`${A} = ${A} + excluded.${A}, ${h} = ${h} + excluded.${h}`))}T&&w(k(n.by??[],T));return}if(E==="sum"||E==="avg"){for(const[i,u]of[[T,-1],[O,1]]){if(!i)continue;const m=U(i[_]);if(m===void 0)continue;const v=k(n.by??[],i);g(s,H(d,v,u*m,u,o`${A} = COALESCE(${A}, 0) + excluded.${A}, ${h} = ${h} + excluded.${h}`))}T&&w(k(n.by??[],T));return}if(T){const i=k(n.by??[],T),u=U(T[_]),m=g(s,o`SELECT ${A} AS value, ${h} AS count FROM ${o.identifier(d)} WHERE ${F} = ${i}`).toArray()[0],v=(m?.count??0)-1;if(v<=0)g(s,o`DELETE FROM ${o.identifier(d)} WHERE ${F} = ${i}`);else if(m&&u!==void 0&&m.value!==null&&u===m.value){const fo=C(e,n,T);g(s,o`UPDATE ${o.identifier(d)} SET ${A} = ${fo.value}, ${h} = ${v} WHERE ${F} = ${i}`)}else g(s,o`UPDATE ${o.identifier(d)} SET ${h} = ${h} - 1 WHERE ${F} = ${i}`)}if(O){const i=k(n.by??[],O),u=U(O[_]);if(u===void 0)g(s,H(d,i,null,1,o`${h} = ${h} + 1`));else{const m=E==="min"?"MIN":"MAX";g(s,H(d,i,u,1,o`${A} = ${o.raw(m)}(COALESCE(${A}, excluded.${A}), excluded.${A}), ${h} = ${h} + 1`))}}}},P=e=>{for(const n of c.tables[e]?.aggregateIndexes??[])R(e,n)},b=(e,n,a)=>{for(const p of c.tables[e]?.aggregateIndexes??[])I(e,p,n,a)},D=(e,n)=>{const a=B(e,n.name);y.has(a)||(Fo(s,e,n,S(e)),y.add(a))},ao=e=>{for(const n of c.tables[e]?.rankIndexes??[])D(e,n)},q=(e,n,a,p)=>{for(const d of c.tables[e]?.rankIndexes??[])Do(s,e,d,n,a,p)},K=(e,n,a,p)=>{const d=c.tables[e]?.searchIndexes??[];if(!(d.length===0||!_o(s)))for(const E of d){if(lo(p,a,E))continue;const _=uo(e,E.name);So(s,a?$o(_,n,Eo(a,E)):go(_,n))}},z=(e,n,a)=>{for(const p of c.tables[e]?.geoIndexes??[]){const d=yo(e,p.name);g(s,o`DELETE FROM ${o.identifier(d)} WHERE ${o.identifier("__id__")} = ${n}`);const E=a?.[p.field];if(E!==null&&typeof E=="object"&&typeof E.lat=="number"&&typeof E.lng=="number"){const{lat:_,lng:w}=E,L=Ro({lat:_,lng:w},p.precision??To);g(s,o`INSERT INTO ${o.identifier(d)} (${o.identifier("__id__")}, ${o.identifier("__geohash__")}, ${o.identifier("__lat__")}, ${o.identifier("__lng__")}) VALUES (${n}, ${L}, ${_}, ${w})`)}}};return{ensureBackfilledForTable:P,ensureBackfilledIndex:R,ensureRankBackfilled:D,ensureRankBackfilledForTable:ao,syncAggregates:b,syncCompanionsForInsert:(e,n,a)=>{K(e,n,a),z(e,n,a),b(e,void 0,a),q(e,n,void 0,a),$(e,n,a),l(e,n,"insert",a),f({indexKeys:t(e,a),key:n,op:"insert",row:a,table:e})},syncGeo:z,syncRanks:q,syncSearch:K}};export{Xo as createCompanionSync,ko as ensureAggregateCompanion,Fo as ensureRankCompanion};
|
|
@@ -0,0 +1,7 @@
|
|
|
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-CTkXVeJx.mjs";import{envPositiveInt as E}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{e as I}from"./estimate-bytes-_k74s6LZ.mjs";import{siblingStub as L}from"./stubByName-B8cFYipA.mjs";import{DEFAULT_TRANSACTION_LIMITS as O}from"./DEFAULT_TRANSACTION_LIMITS-Dmj5VBrV.mjs";import{verifySiblingBody as C,RELAY_SIGNATURE_HEADER as S,siblingSecretOf as R,signSiblingBody as U}from"./RELAY_SIGNATURE_HEADER-DP0glzE_.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
|
+
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
3
|
+
epoch TEXT NOT NULL,
|
|
4
|
+
applied_seq INTEGER NOT NULL,
|
|
5
|
+
synced_at REAL NOT NULL
|
|
6
|
+
)`),g.add(r))},h=r=>(m(r),r.exec(`SELECT epoch, applied_seq AS appliedSeq, synced_at AS syncedAtMs FROM ${f} WHERE id = 1`).toArray()[0]),l=(r,e)=>{m(r),r.exec(`INSERT INTO ${f} (id, epoch, applied_seq, synced_at) VALUES (1, ?, ?, ?)
|
|
7
|
+
ON CONFLICT(id) DO UPDATE SET epoch = excluded.epoch, applied_seq = excluded.applied_seq, synced_at = excluded.synced_at`,e.epoch,e.appliedSeq,e.syncedAtMs)},$=r=>{const e=r.doName();if(e!==void 0&&_(e)!==void 0)return new Response("replica cannot serve replicas",{status:409});if(r.ownerEpoch()===void 0)return new Response("shard has no changelog to replicate",{status:409});if(R(r.env())===void 0)return new Response("replica control requires LUNORA_RELAY_SECRET",{status:403})},p=r=>Response.json(N(r)),X=async(r,e)=>{if(r.rowCount()>W(r.env()))return p({cursor:0,epoch:e,rows:[],truncated:!0});const t=r.ownerCursor()??0,s=await r.exportRows();return p({cursor:t,epoch:e,rows:s})},k=(r,e,t)=>{const s=r.ownerFloor();if(b(s,t))return p({changes:[],cursor:r.ownerCursor()??t,epoch:e,floor:s});const n=r.ownerCursor()??0;if(t>n)return p({changes:[],cursor:n,epoch:e,...s===void 0?{}:{floor:s}});const{changes:o,cursor:i}=r.readChanges(t,A);return p({changes:o,cursor:i,epoch:e,...s===void 0?{}:{floor:s}})},te=async(r,e)=>{const t=$(r);if(t!==void 0)return t;const s=r.ownerEpoch();let n;try{n=await e.text()}catch{return new Response("bad request",{status:400})}if(!await C(r.env(),e.headers.get(S),n))return new Response("forbidden",{status:403});let o;try{o=JSON.parse(n)}catch{return new Response("bad request",{status:400})}if(o.type==="replica_bootstrap")return X(r,s);if(o.type==="replica_pull"){const i=typeof o.sinceSeq=="number"&&Number.isInteger(o.sinceSeq)&&o.sinceSeq>=0?o.sinceSeq:0;return k(r,s,i)}return new Response("unknown replica frame",{status:400})},K=r=>{const e=r;return typeof r=="object"&&(e?.retryable===!0||e?.overloaded===!0)},j=(r,e)=>{const t=e.changes.length===0&&e.cursor>r.appliedSeq,s=e.floor??(t?e.cursor:0),n=s>0&&s>r.appliedSeq+1,o=e.cursor<r.appliedSeq;return e.epoch!==r.epoch||o?"fork":n?"compacted":void 0},y=(r,e)=>`${r}\0${e}`;class H{constructor(e,t,s){this.host=e,this.ownerKey=t,this.region=s}host;ownerKey;region;divergent=!1;inFlight;async ensureFresh(e){if(this.divergent)return"unavailable";if(this.isCaughtUp(e))return"fresh";this.inFlight??=this.advance(e).finally(()=>{this.inFlight=void 0});const t=await this.inFlight;return t==="fresh"&&!this.isCaughtUp(e)?"stale":t}appliedSeq(){return h(this.host.sql())?.appliedSeq??0}isDivergent(){return this.divergent}async advance(e){let t=h(this.host.sql());if(t===void 0){const s=await this.bootstrap();if(s===void 0)return"unavailable";t=s}return this.catchUp(t,e)}isCaughtUp(e){const t=h(this.host.sql());return t!==void 0&&this.isFreshEnough(t,e)}async catchUp(e,t){let s=e,n=!1;for(let o=0;o<B;o+=1){const i=await this.pull(s.appliedSeq);if(i===void 0)return this.whenOwnerUnreachable(s,t);const c=j(s,i);if(c!==void 0){const a=await this.recover(s,c,n);if(typeof a=="string")return a;n=!0,s=a;continue}const d=i.changes.length<A,u=await this.applyPage(i,s,d);if(u===void 0)return"unavailable";if(s=u,d||this.isFreshEnough(s,t))return this.verdict(s,t)}return this.verdict(s,t)}verdict(e,t){return this.isFreshEnough(e,t)?"fresh":"stale"}async recover(e,t,s){return t==="fork"?(this.divergent=!0,"unavailable"):s?"unavailable":await this.resnapshot(e)??"unavailable"}whenOwnerUnreachable(e,t){return t===void 0&&this.isFreshEnough(e,void 0)?"fresh":"unavailable"}async applyPage(e,t,s){if(!await this.applyAtomically("replica.applyPage",e.changes))return;const n={appliedSeq:e.cursor,epoch:e.epoch,syncedAtMs:s?Date.now():t.syncedAtMs};return l(this.host.sql(),n),n}async applyAtomically(e,t){if(t.length===0)return!0;try{return await this.host.applyChanges(t),!0}catch(s){return K(s)||(this.divergent=!0),this.host.reportError?.(e,s),!1}}async fetchSnapshot(){const e=await this.request({type:"replica_bootstrap"});if(e===void 0)return;const t=v(await e.json());if(t.truncated===!0){this.divergent=!0;return}return t}async resnapshot(e){const t=await this.fetchSnapshot();if(t===void 0)return;const s={...O,...this.host.transactionLimits()},n=[],o=new Set;let i=0;for(const{doc:d,table:u}of t.rows){const a=String(d._id);o.add(y(u,a)),i+=I(d)??Number.POSITIVE_INFINITY,n.push({doc:d,id:a,op:"insert",seq:t.cursor,table:u,ts:0})}if(this.overWriteBudget(n.length,i,s))return;for(const{doc:d,table:u}of await this.host.exportRows()){const a=String(d._id);o.has(y(u,a))||n.push({id:a,op:"delete",seq:t.cursor,table:u,ts:0})}if(this.overWriteBudget(n.length,i,s)||!await this.applyAtomically("replica.resnapshot",n))return;const c={appliedSeq:t.cursor,epoch:t.epoch,syncedAtMs:e.syncedAtMs};return l(this.host.sql(),c),c}overWriteBudget(e,t,s){return e<=s.maxWrittenRows&&t<=s.maxWrittenBytes?!1:(this.host.reportError?.("replica.resnapshot",new T("TRANSACTION_LIMIT_EXCEEDED",`a re-snapshot would write ${String(e)} documents and ${String(t)} bytes, over the ${String(s.maxWrittenRows)}-document / ${String(s.maxWrittenBytes)}-byte transaction limit`)),!0)}async bootstrap(){const e=await this.fetchSnapshot();if(e===void 0)return;const{errors:t}=await this.host.importRows(e.rows);if(t.length>0){this.divergent=!0;return}const s={appliedSeq:e.cursor,epoch:e.epoch,syncedAtMs:Date.now()};return l(this.host.sql(),s),s}isFreshEnough(e,t){return t!==void 0?e.appliedSeq>=t:Date.now()-e.syncedAtMs<=E(this.host.env(),"LUNORA_REPLICA_MAX_STALENESS_MS",P)}async pull(e){const t=await this.request({sinceSeq:e,type:"replica_pull"});return t===void 0?void 0:v(await t.json())}async request(e){const t=this.host.shardBinding(),s=L(this.host.env(),t,this.ownerKey,this.host.shardJurisdiction());if(s===void 0)return;const n=JSON.stringify(e),o={"content-type":"application/json","x-lunora-shard-binding":t??""},i=R(this.host.env());i!==void 0&&(o[S]=await U(i,n));try{const c=await s.fetch("https://replica.internal/_lunora/replica",{body:n,headers:o,method:"POST"});return c.ok?c:void 0}catch{return}}}const re=r=>{const e=r.doName();if(e===void 0)return;const t=_(e);return t===void 0?void 0:new H(r,t.ownerKey,t.region)},se=async(r,e,t)=>{if(e.headers.get("x-lunora-replica-read")!=="1")return Response.json({error:{code:"REPLICA_READ_ONLY",message:`"${t}" is a write and cannot run on a read replica`}},{status:421});const s=await r.ensureFresh(M(e.headers.get("x-lunora-min-seq")));if(s!=="fresh")return Response.json({error:{code:"REPLICA_NOT_READY",message:`replica is ${s} for this read`}},{headers:{"x-lunora-replica-fallback":s},status:421})};export{re as createReplicaLink,se as gateReplicaDispatch,te as handleReplicaControl};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as i}from"@lunora/errors";const f=t=>{const e={args:t.args??{},enqueuedAt:typeof t.enqueuedAt=="number"?t.enqueuedAt:0,id:typeof t.id=="string"?t.id:"",scheduledFor:typeof t.scheduledFor=="number"?t.scheduledFor:0};typeof t.attempts=="number"&&(e.attempts=t.attempts),typeof t.functionPath=="string"&&(e.functionPath=t.functionPath),typeof t.pool=="string"&&(e.pool=t.pool),typeof t.shardKey=="string"&&(e.shardKey=t.shardKey),typeof t.workflow=="string"&&(e.workflow=t.workflow);const{state:n}=t;return(n==="canceled"||n==="failed"||n==="pending"||n==="running"||n==="succeeded")&&(e.state=n),typeof t.completedAt=="number"&&(e.completedAt=t.completedAt),typeof t.error=="string"&&(e.error=t.error),e},c=t=>{const e={key:typeof t.key=="string"?t.key:"",size:typeof t.size=="number"?t.size:0},n=t.httpMetadata?.contentType??t.contentType;typeof n=="string"&&(e.contentType=n),t.customMetadata&&typeof t.customMetadata=="object"&&(e.customMetadata=t.customMetadata),typeof t.sha256=="string"&&(e.sha256=t.sha256);const{uploaded:s}=t;return typeof s=="number"?e.uploaded=s:s instanceof Date&&(e.uploaded=s.getTime()),e},p=(t={})=>{const e=()=>{if(!t.scheduler)throw new i("INTERNAL",'ctx.db.system.query("_scheduled_functions"): no scheduler configured. Pass `scheduler` to createShardDO().');return t.scheduler},n=()=>{if(!t.storage)throw new i("INTERNAL",'ctx.db.system.query("_storage"): no storage configured. Pass `storage` to createShardDO().');return t.storage},s=async()=>(await e().list()).map(o=>f(o)),d=async()=>{const{objects:a}=await n().list();return a.map(o=>c(o))};return{get:(async(a,o)=>{if(a==="_scheduled_functions"){const r=await e().get(o);return r?f(r):null}const u=await n().getMetadata(o);return u?c(u):null}),query:(a=>a==="_scheduled_functions"?{collect:s}:{collect:d})}};export{p as createSystemReader};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import{encodeWire as l,decodeWire as E}from"@lunora/wire";import{sql as i}from"drizzle-orm";import{runDrizzle as 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)} (
|
|
2
|
+
key TEXT PRIMARY KEY,
|
|
3
|
+
relay_idx INTEGER,
|
|
4
|
+
connection_id TEXT,
|
|
5
|
+
name TEXT NOT NULL,
|
|
6
|
+
args TEXT NOT NULL,
|
|
7
|
+
identity TEXT NOT NULL,
|
|
8
|
+
cursor INTEGER NOT NULL
|
|
9
|
+
)`)},c=e=>JSON.stringify(l(e)),s=e=>E(JSON.parse(e)),$=e=>a(e,i`SELECT key, relay_idx, connection_id, name, args, identity, cursor FROM ${i.identifier(t)}`).toArray().map(r=>({args:s(r.args),connectionId:r.connection_id??void 0,cursor:Number(r.cursor),identity:s(r.identity),key:r.key,name:r.name,relayIndex:r.relay_idx===null?void 0:Number(r.relay_idx)})),L=(e,n)=>{a(e,i`INSERT INTO ${i.identifier(t)} (key, relay_idx, connection_id, name, args, identity, cursor)
|
|
10
|
+
VALUES (${n.key}, ${n.relayIndex??o}, ${n.connectionId??o}, ${n.name}, ${c(n.args)}, ${c(n.identity??{})}, ${n.cursor})
|
|
11
|
+
ON CONFLICT(key) DO UPDATE SET
|
|
12
|
+
relay_idx = excluded.relay_idx,
|
|
13
|
+
connection_id = excluded.connection_id,
|
|
14
|
+
name = excluded.name,
|
|
15
|
+
args = excluded.args,
|
|
16
|
+
identity = excluded.identity,
|
|
17
|
+
cursor = excluded.cursor`)},S=(e,n,r)=>{a(e,i`UPDATE ${i.identifier(t)} SET cursor = ${r} WHERE key = ${n}`)},x=(e,n,r,d)=>{const y=d===void 0?i``:i` AND key = ${T(n,r,d)}`;a(e,i`DELETE FROM ${i.identifier(t)} WHERE relay_idx = ${n} AND connection_id = ${r}${y}`)},p=(e,n)=>{a(e,i`DELETE FROM ${i.identifier(t)} WHERE relay_idx = ${n}`)},O=e=>{a(e,i`DELETE FROM ${i.identifier(t)}`)};export{L as a,p as b,O as c,x as d,R as m,$ as r,S as w};
|
|
@@ -0,0 +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};
|