@lunora/shard-engine 1.0.0-alpha.56 → 1.0.0-alpha.58

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/conformance/index.mjs +1 -1
  2. package/dist/index.d.mts +0 -1
  3. package/dist/index.d.ts +0 -1
  4. package/dist/index.mjs +1 -1
  5. package/dist/packem_shared/{ADMIN_FUNCTIONS-D-D50Y99.mjs → ADMIN_FUNCTIONS-MzNUYBeH.mjs} +1 -1
  6. package/dist/packem_shared/{AGG_COUNT-jFen2XIa.mjs → AGG_COUNT-DnmDMp-h.mjs} +1 -1
  7. package/dist/packem_shared/CDC_LOG_TABLE-CAyqu8cg.mjs +15 -0
  8. package/dist/packem_shared/{CURSOR_PREFIX-D8c7Ccj3.mjs → CURSOR_PREFIX-qn6nNVS7.mjs} +1 -1
  9. package/dist/packem_shared/{DATA_MIGRATION_STATE_TABLE-ByxFSsGa.mjs → DATA_MIGRATION_STATE_TABLE-BttUL9Sv.mjs} +1 -1
  10. package/dist/packem_shared/{DEFAULT_MAX_RELATION_KEYS--MhxjwFp.mjs → DEFAULT_MAX_RELATION_KEYS-Ciwtjo9t.mjs} +1 -1
  11. package/dist/packem_shared/{DEFAULT_MAX_RELAYS-05EHd-ef.mjs → DEFAULT_MAX_RELAYS-C3L_1GLp.mjs} +1 -1
  12. package/dist/packem_shared/{DEFAULT_PROMOTION_THRESHOLDS-CIJjsrCU.mjs → DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs} +1 -1
  13. package/dist/packem_shared/{DurableStreamRunner-BU1-FoTv.mjs → DurableStreamRunner-rTYp4v03.mjs} +1 -1
  14. package/dist/packem_shared/MAX_SQL_ROWS-RvXZ7S7f.mjs +4 -0
  15. package/dist/packem_shared/NotUniqueError-CTSwCMsP.mjs +1 -0
  16. package/dist/packem_shared/{RANK_TIEBREAK-B6iDKDW3.mjs → RANK_TIEBREAK-CkNuGm6a.mjs} +1 -1
  17. package/dist/packem_shared/{ReactiveCache-cZHAGM4z.mjs → ReactiveCache-Co_Q4zWX.mjs} +1 -1
  18. package/dist/packem_shared/{ShapeDiffCache-SgPO8heC.mjs → ShapeDiffCache-gdaILV5E.mjs} +1 -1
  19. package/dist/packem_shared/{aggregateTableName-BvenuaDR.mjs → aggregateTableName-C7o-gpms.mjs} +1 -1
  20. package/dist/packem_shared/{applyOnDelete-CmYAshr-.mjs → applyOnDelete-tDhKaeB6.mjs} +1 -1
  21. package/dist/packem_shared/{awaitWsDrain-C9bPJ23I.mjs → awaitWsDrain-apizgmKY.mjs} +1 -1
  22. package/dist/packem_shared/{backfillAggregateIndexes-CMtnLFZa.mjs → backfillAggregateIndexes-pQWaX2Yu.mjs} +1 -1
  23. package/dist/packem_shared/{buildPokeFrames-CkVxoDaR.mjs → buildPokeFrames-BBE6J91z.mjs} +1 -1
  24. package/dist/packem_shared/{buildReprojectionMigration-5EW5Fu9A.mjs → buildReprojectionMigration-C-EJ_eKR.mjs} +1 -1
  25. package/dist/packem_shared/{buildShapeDiff-Bkqtx7Jp.mjs → buildShapeDiff-C-ipEyt_.mjs} +1 -1
  26. package/dist/packem_shared/{computeRankPage-CrFzfXK5.mjs → computeRankPage-DEkYJ9Tz.mjs} +1 -1
  27. package/dist/packem_shared/createCompanionSync-BpWcC55_.mjs +1 -0
  28. package/dist/packem_shared/createReplicaLink-D1Rmca3b.mjs +7 -0
  29. package/dist/packem_shared/{ctx-db-companions-Z9JQ9xo1.mjs → ctx-db-companions-B4O4d95S.mjs} +1 -1
  30. package/dist/packem_shared/{ctx-db-relay-shapes-Y0jy6_Qb.mjs → ctx-db-relay-shapes-Bg5YYnmN.mjs} +1 -1
  31. package/dist/packem_shared/{defineEngineContractSuite-DesaEHOQ.mjs → defineEngineContractSuite-F4j85ofN.mjs} +1 -1
  32. package/dist/packem_shared/{do-sql-Cv3yRshL.mjs → do-sql-FNOnpyHm.mjs} +1 -1
  33. package/dist/packem_shared/{isSoftDeleted-jScoPSzf.mjs → isSoftDeleted-CVu_TCeK.mjs} +1 -1
  34. package/dist/packem_shared/{materializeExternalRows-CXfp_DGO.mjs → materializeExternalRows-CAPAra-0.mjs} +1 -1
  35. package/dist/packem_shared/{runShardMigrations-B1ilHmKB.mjs → runShardMigrations-CkG92fSl.mjs} +1 -1
  36. package/dist/packem_shared/{selectExpiredIds-HTDo17et.mjs → selectExpiredIds-BjZ_UtMx.mjs} +1 -1
  37. package/dist/packem_shared/{selectShapeMembers-jydcnpzn.mjs → selectShapeMembers-DqikYFjS.mjs} +1 -1
  38. package/dist/packem_shared/{stableWireKey-DQZmSvS2.mjs → stableWireKey-D2US4k_J.mjs} +1 -1
  39. package/dist/packem_shared/wire-codec-C-FpWm52.mjs +1 -0
  40. package/package.json +3 -3
  41. package/dist/packem_shared/CDC_LOG_TABLE-CMCaSndb.mjs +0 -15
  42. package/dist/packem_shared/MAX_SQL_ROWS-CY5qwGU3.mjs +0 -4
  43. package/dist/packem_shared/NotUniqueError-DGa-X5AB.mjs +0 -1
  44. package/dist/packem_shared/createCompanionSync-Bhoxm4x2.mjs +0 -1
  45. package/dist/packem_shared/createReplicaLink-CfcxVD0P.mjs +0 -7
  46. package/dist/packem_shared/wire-codec-CKV-4MEN.mjs +0 -1
@@ -1 +1 @@
1
- import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-DesaEHOQ.mjs";export{t as defineEngineContractSuite};
1
+ import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-F4j85ofN.mjs";export{t as defineEngineContractSuite};
package/dist/index.d.mts CHANGED
@@ -704,7 +704,6 @@ declare const appendCdcChange: (sql: SqlExec, ts: number, table: string, id: str
704
704
  declare const readCdcChanges: (sql: SqlExec, options?: {
705
705
  limit?: number;
706
706
  sinceSeq?: number;
707
- tables?: ReadonlySet<string>;
708
707
  }) => {
709
708
  changes: CdcChange[];
710
709
  cursor: number;
package/dist/index.d.ts CHANGED
@@ -704,7 +704,6 @@ declare const appendCdcChange: (sql: SqlExec, ts: number, table: string, id: str
704
704
  declare const readCdcChanges: (sql: SqlExec, options?: {
705
705
  limit?: number;
706
706
  sinceSeq?: number;
707
- tables?: ReadonlySet<string>;
708
707
  }) => {
709
708
  changes: CdcChange[];
710
709
  cursor: number;
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as n,selectExportTables as i,validateImportRow as s}from"./packem_shared/exportShardRows-D_upYHRQ.mjs";import{AGGREGATE_SQL_FUNCTION as m,aggregateSqlFunction as c,matchesStaticWhere as d,normalizeCountArgument as p,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as f,coerceAggregateNumber as h,encodeAggregateKey as x,foldAggregateTally as C,readAggregateValue as T}from"./packem_shared/aggregateTableName-BvenuaDR.mjs";import{CountRlsUnsupportedError as R,mergeWhere as g,planAggregateLookup as A,selectIndexForAggregate as _,selectIndexForCount as I,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-Bdfupt3g.mjs";import{AUDIT_LOG_TABLE as P,appendAuditEntry as M,ensureAuditTable as D,readAuditLog as N}from"./packem_shared/AUDIT_LOG_TABLE-ONxmEAIz.mjs";import{NotUniqueError as O,assertNoExplicitUndefined as k,assertValidClientId as F,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-DGa-X5AB.mjs";import{backfillAggregateIndexes as q,backfillRankIndexes as w,backfillSearchIndexes as K,backfillSearchIndexesForTable as v}from"./packem_shared/backfillAggregateIndexes-CMtnLFZa.mjs";import{CDC_LOG_TABLE as X,CDC_LOG_TABLE_SEQ_INDEX as H,CDC_META_TABLE as z,appendCdcChange as V,applyCdcChanges as Q,bumpCdcEpoch as Y,cdcCanVouchFor as j,cdcSeqLeavingRows as J,cdcTouchesTables as Z,cdcTrimmedError as $,compactCdcDocs as ee,cursorBelowRetainedFloor as re,migrateCdcLog as oe,migrateCdcMeta as ae,minCdcReplayableSeq as te,minCdcSeq as ne,readCdcChangeKeys as ie,readCdcChanges as se,readCdcCursor as le,readCdcEpoch as me,trimCdcChanges as ce}from"./packem_shared/CDC_LOG_TABLE-CMCaSndb.mjs";import{archiveCdcSegment as pe,readArchivedCdcChanges as Se,readCdcArchivedThrough as ue,writeCdcArchivedThrough as fe}from"./packem_shared/archiveCdcSegment-DU4uzDFQ.mjs";import{CLIENT_WATERMARK_TABLE as xe,advanceClientWatermark as Ce,migrateClientWatermark as Te,readClientWatermark as Ee}from"./packem_shared/CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{COMMIT_SEQ_FIELD as ge,COMMIT_SEQ_TABLE as Ae,allocateCommitSeq as _e,migrateCommitSeq as Ie,readCommitSeq as be}from"./packem_shared/COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{c as Pe}from"./packem_shared/ctx-db-companions-Z9JQ9xo1.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as De,deleteGlobalShapeSnapshot as Ne,deleteGlobalShapeSnapshotsForConnection as ye,migrateGlobalShapeSnapshot as Oe,readGlobalShapeSnapshot as ke,writeGlobalShapeSnapshot as Fe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{IDEMPOTENCY_TABLE as Ge,migrateIdempotency as Ue,readIdempotent as qe,trimIdempotent as we,writeIdempotent as Ke}from"./packem_shared/IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{clearMemoryTables as We,isMemoryTable as Xe,memoryTableNames as He}from"./packem_shared/clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as Ve,resolveRankSeekTuple as Qe}from"./packem_shared/computeRankPage-CrFzfXK5.mjs";import{S as je,m as Je,r as Ze,w as $e}from"./packem_shared/ctx-db-search-state-ruTuCsxa.mjs";import{SHAPE_POKE_CURSOR_TABLE as rr,deleteShapePokeCursor as or,deleteShapePokeCursorsForConnection as ar,migrateShapePokeCursor as tr,minShapePokeCursor as nr,readShapePokeCursor as ir,writeShapePokeCursor as sr,writeShapePokeCursors as lr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs";import{selectShapeMembers as cr,selectShapeRows as dr}from"./packem_shared/selectShapeMembers-jydcnpzn.mjs";import{DATA_MIGRATION_STATE_TABLE as Sr,readMigrationStatus as ur,runDataMigration as fr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-ByxFSsGa.mjs";import{SCAN_DEP as xr,createDependencyTracker as Cr,depKey as Tr,tableFromDepKey as Er}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as gr,runSql as Ar}from"./packem_shared/runDrizzle-2ULFQR_k.mjs";import{A as Ir,a as br,b as Lr,D as Pr,c as Mr,d as Dr,g as Nr,i as yr,j as Or,e as kr,q as Fr,f as Br,r as Gr,t as Ur,h as qr}from"./packem_shared/do-sql-Cv3yRshL.mjs";import{param as Kr,renderSql as vr,sqliteInList as Wr,unionAll as Xr}from"./packem_shared/param-DlozcSQu.mjs";import{appendStreamChunk as zr,claimStreamRun as Vr,deleteStreamRun as Qr,finishStreamRun as Yr,migrateDurableStreams as jr,readStreamChunks as Jr,readStreamRun as Zr,trimStreamRuns as $r}from"./packem_shared/appendStreamChunk-C1Ok4b6J.mjs";import{DurableStreamRunner as ro,MAX_DURABLE_STREAM_BYTES as oo,MAX_DURABLE_STREAM_CHUNKS as ao,decideDurableAttach as to}from"./packem_shared/DurableStreamRunner-BU1-FoTv.mjs";import{envOptionalPositiveInt as io,envPositiveInt as so}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as mo}from"./packem_shared/diffExternalSource-DgDJhslq.mjs";import{liftSourceId as po,normalizeSourceDocument as So,normalizeSourceValue as uo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as ho,materializeExternalRowsIncremental as xo,readExternalSourceBaseline as Co,runExternalSourceTick as To}from"./packem_shared/materializeExternalRows-CXfp_DGO.mjs";import{isSoftDeleted as Ro,isSourceDue as go,pullExternalSourceIncrementalTick as Ao,pullExternalSourceTick as _o}from"./packem_shared/isSoftDeleted-jScoPSzf.mjs";import{GEO_DEFAULT_PRECISION as bo,boundingBoxCenter as Lo,boundingBoxGeohashes as Po,coveringGeohashes as Mo,encodeGeohash as Do,haversineMeters as No,pointInBoundingBox as yo}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as ko}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as Bo,ADMIN_FUNCTION_PREFIX as Go,DEFAULT_FANOUT_TOPIC_LIMIT as Uo,FLAGS_FUNCTION_PREFIX as qo,MAX_PAGE_SIZE as wo,RELATION_FUNCTION_PREFIX as Ko,createFanoutCounters as vo,createGlobalPollCounters as Wo,createShapeProbeCounters as Xo,facetColumn as Ho,findStorageReferences as zo,listTables as Vo,readTablePage as Qo,recordFanoutPass as Yo,recordGlobalPollPass as jo,recordShapeProbePass as Jo,selectMatchingIds as Zo,summarizeFanoutTopics as $o,summarizeSubscriptions as ea}from"./packem_shared/ADMIN_FUNCTIONS-D-D50Y99.mjs";import{MAIL_RETENTION as oa,MAIL_TABLE as aa,clearCapturedMail as ta,ensureMailTable as na,readCapturedMail as ia,recordCapturedMail as sa}from"./packem_shared/MAIL_RETENTION-DGAQTHHs.mjs";import{NotFoundError as ma}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as da,readBookmark as pa}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as ua,applySelect as fa,buildSeekBeforeWhere as ha,buildSeekWhere as xa,decodeCursor as Ca,encodeCursor as Ta,normalizeOrderKeys as Ea,softDeleteScope as Ra,tiebreakDirectionFor as ga}from"./packem_shared/CURSOR_PREFIX-D8c7Ccj3.mjs";import{QUEUE_TABLE as _a,clearQueueMessages as Ia,isLossyBody as ba,readQueueMessageById as La,readQueueMessages as Pa,recordQueueMessages as Ma}from"./packem_shared/QUEUE_TABLE-s7QJZvBz.mjs";import{RANK_TIEBREAK as Na,encodePartitionKey as ya,matchesRankStaticWhere as Oa,rankKeyFromDoc as ka,rankPivotConditionSql as Fa,rankTableName as Ba,resolveRankPartition as Ga,sortColumnName as Ua}from"./packem_shared/RANK_TIEBREAK-B6iDKDW3.mjs";import{ReactiveCache as wa,reactiveCacheKey as Ka}from"./packem_shared/ReactiveCache-cZHAGM4z.mjs";import{REACTOR_STATE_TABLE as Wa,listReactorStates as Xa,migrateReactorState as Ha,reactorNeedsRun as za,readReactorState as Va,writeReactorState as Qa}from"./packem_shared/REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{UNVOUCHABLE_DEP as ja,createReadFootprint as Ja,markUnvouchableReads as Za}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as et,indexKeysForRow as rt,keysTouchRanges as ot}from"./packem_shared/buildIndexRange-CBKQmHSS.mjs";import{DEFAULT_MAX_RELATION_KEYS as tt,assertFlatPredicate as nt,assertShapeShardable as it,containsRelationPredicate as st,isRelationPredicate as lt,resolveRelationPredicates as mt}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS--MhxjwFp.mjs";import{applyOnDelete as dt,distinctValues as pt,fanOutScalarCounts as St,relationHooks as ut,resolveWith as ft,runRowValidators as ht}from"./packem_shared/applyOnDelete-CmYAshr-.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as Ct,clampPromotionThresholds as Tt,nextPromotionState as Et,relayCountFor as Rt,shapeRoutingKey as gt}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-CIJjsrCU.mjs";import{DEFAULT_MAX_RELAYS as _t,OwnerRelay as It,RelayMember as bt,createRelayLink as Lt}from"./packem_shared/DEFAULT_MAX_RELAYS-05EHd-ef.mjs";import{createReplicaLink as Mt,gateReplicaDispatch as Dt,handleReplicaControl as Nt}from"./packem_shared/createReplicaLink-CfcxVD0P.mjs";import{buildReprojectionMigration as Ot,countLegacyRows as kt,reprojectableFields as Ft,reprojectionTables as Bt}from"./packem_shared/buildReprojectionMigration-5EW5Fu9A.mjs";import{RLS_UNWRAP_SYMBOL as Ut,RlsRequiredError as qt,guardWriter as wt}from"./packem_shared/RLS_UNWRAP_SYMBOL-B3RgW-Kb.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as vt,readSchemaHistory as Wt,readSchemaVersion as Xt,recordSchemaVersion as Ht}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";import{serializeSqlValue as Vt}from"./packem_shared/serializeSqlValue-B_-zaEWZ.mjs";import{buildSettings as Yt,isDevEnvironment as jt}from"./packem_shared/buildSettings-B4igo4rJ.mjs";import{buildShapeDiff as Zt}from"./packem_shared/buildShapeDiff-Bkqtx7Jp.mjs";import{ShapeDiffCache as en,createShapeDiffCache as rn,globalShapeReadKey as on}from"./packem_shared/ShapeDiffCache-SgPO8heC.mjs";import{buildPokeFrames as tn,diffGlobalMembership as nn,encodeRowsPatch as sn,projectColumns as ln}from"./packem_shared/buildPokeFrames-CkVxoDaR.mjs";import{ShardRunner as cn}from"./packem_shared/ShardRunner-C9p5DVOx.mjs";import{runSocketPool as pn}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as un,assertReadonly as fn,lintReadonlySql as hn,runReadonlySql as xn}from"./packem_shared/MAX_SQL_ROWS-CY5qwGU3.mjs";import{BIGINT_KEY_DIGITS as Tn,bigintSqlKey as En,decodeBigintSqlKey as Rn}from"./packem_shared/BIGINT_KEY_DIGITS-GvEBhyR5.mjs";import{awaitWsDrain as An,subscriptionFrames as _n,subscriptionListDeltas as In,trySendFrame as bn}from"./packem_shared/awaitWsDrain-C9bPJ23I.mjs";import{mergeChangedKeys as Pn,recordChangedKeys as Mn,writeTouchesMemo as Dn}from"./packem_shared/mergeChangedKeys-D1T-TPUb.mjs";import{createSystemReader as yn}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as kn}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Bn,TransactionHeadroomTracker as Gn}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-D_xv2cwd.mjs";import{hasTrigger as qn,runTriggers as wn}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as vn}from"./packem_shared/selectExpiredIds-HTDo17et.mjs";import{c as Xn,l as Hn}from"./packem_shared/where-sql-B1l5NcUZ.mjs";import{RELATION_EXISTS_KEY as Vn}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as Yn,reprojectionMigrationId as jn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{quoteIdentifier as Zn}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as ei}from"./packem_shared/runShardMigrations-B1ilHmKB.mjs";import{stableStringify as oi}from"./packem_shared/stableStringify-DibjylKD.mjs";import{stableWireKey as ti}from"./packem_shared/stableWireKey-DQZmSvS2.mjs";export{Bo as ADMIN_FUNCTIONS,Go as ADMIN_FUNCTION_PREFIX,m as AGGREGATE_SQL_FUNCTION,Ir as AGG_COUNT,br as AGG_KEY,Lr as AGG_VALUE,P as AUDIT_LOG_TABLE,Tn as BIGINT_KEY_DIGITS,X as CDC_LOG_TABLE,H as CDC_LOG_TABLE_SEQ_INDEX,z as CDC_META_TABLE,xe as CLIENT_WATERMARK_TABLE,ge as COMMIT_SEQ_FIELD,Ae as COMMIT_SEQ_TABLE,ua as CURSOR_PREFIX,kn as ConflictError,R as CountRlsUnsupportedError,Sr as DATA_MIGRATION_STATE_TABLE,Uo as DEFAULT_FANOUT_TOPIC_LIMIT,tt as DEFAULT_MAX_RELATION_KEYS,_t as DEFAULT_MAX_RELAYS,Ct as DEFAULT_PROMOTION_THRESHOLDS,Bn as DEFAULT_TRANSACTION_LIMITS,Pr as DOC_COLUMN,ro as DurableStreamRunner,qo as FLAGS_FUNCTION_PREFIX,bo as GEO_DEFAULT_PRECISION,De as GLOBAL_SHAPE_SNAPSHOT_TABLE,ko as GlobalPollTick,Ge as IDEMPOTENCY_TABLE,oa as MAIL_RETENTION,aa as MAIL_TABLE,oo as MAX_DURABLE_STREAM_BYTES,ao as MAX_DURABLE_STREAM_CHUNKS,wo as MAX_PAGE_SIZE,un as MAX_SQL_ROWS,ma as NotFoundError,O as NotUniqueError,It as OwnerRelay,_a as QUEUE_TABLE,Na as RANK_TIEBREAK,Wa as REACTOR_STATE_TABLE,Vn as RELATION_EXISTS_KEY,Ko as RELATION_FUNCTION_PREFIX,Yn as REPROJECTION_MIGRATION_PREFIX,Ut as RLS_UNWRAP_SYMBOL,wa as ReactiveCache,bt as RelayMember,qt as RlsRequiredError,xr as SCAN_DEP,vt as SCHEMA_HISTORY_MAX_VERSIONS,je as SEARCH_STATE_TABLE,rr as SHAPE_POKE_CURSOR_TABLE,en as ShapeDiffCache,cn as ShardRunner,Gn as TransactionHeadroomTracker,ja as UNVOUCHABLE_DEP,Ce as advanceClientWatermark,Mr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,_e as allocateCommitSeq,M as appendAuditEntry,V as appendCdcChange,zr as appendStreamChunk,Q as applyCdcChanges,dt as applyOnDelete,fa as applySelect,pe as archiveCdcSegment,da as armRestore,nt as assertFlatPredicate,k as assertNoExplicitUndefined,fn as assertReadonly,it as assertShapeShardable,F as assertValidClientId,An as awaitWsDrain,q as backfillAggregateIndexes,w as backfillRankIndexes,K as backfillSearchIndexes,v as backfillSearchIndexesForTable,En as bigintSqlKey,Lo as boundingBoxCenter,Po as boundingBoxGeohashes,et as buildIndexRange,tn as buildPokeFrames,Ot as buildReprojectionMigration,ha as buildSeekBeforeWhere,xa as buildSeekWhere,Yt as buildSettings,Zt as buildShapeDiff,Y as bumpCdcEpoch,j as cdcCanVouchFor,J as cdcSeqLeavingRows,Z as cdcTouchesTables,$ as cdcTrimmedError,Vr as claimStreamRun,Tt as clampPromotionThresholds,ta as clearCapturedMail,We as clearMemoryTables,Ia as clearQueueMessages,h as coerceAggregateNumber,ee as compactCdcDocs,Xn as compileWhereSql,Ve as computeRankPage,st as containsRelationPredicate,kt as countLegacyRows,Mo as coveringGeohashes,Pe as createCompanionSync,Cr as createDependencyTracker,vo as createFanoutCounters,Wo as createGlobalPollCounters,Dr as createIndexSql,Ja as createReadFootprint,Lt as createRelayLink,Mt as createReplicaLink,rn as createShapeDiffCache,Xo as createShapeProbeCounters,B as createShardCtxDb,yn as createSystemReader,re as cursorBelowRetainedFloor,to as decideDurableAttach,Rn as decodeBigintSqlKey,Ca as decodeCursor,Ne as deleteGlobalShapeSnapshot,ye as deleteGlobalShapeSnapshotsForConnection,or as deleteShapePokeCursor,ar as deleteShapePokeCursorsForConnection,Qr as deleteStreamRun,Tr as depKey,mo as diffExternalSource,nn as diffGlobalMembership,pt as distinctValues,x as encodeAggregateKey,Ta as encodeCursor,Do as encodeGeohash,ya as encodePartitionKey,sn as encodeRowsPatch,D as ensureAuditTable,na as ensureMailTable,io as envOptionalPositiveInt,so as envPositiveInt,o as exportShardRows,Ho as facetColumn,St as fanOutScalarCounts,zo as findStorageReferences,Yr as finishStreamRun,C as foldAggregateTally,Dt as gateReplicaDispatch,Nr as geoTableName,on as globalShapeReadKey,wt as guardWriter,Nt as handleReplicaControl,qn as hasTrigger,No as haversineMeters,a as importShardRows,rt as indexKeysForRow,jt as isDevEnvironment,yr as isFtsAvailable,ba as isLossyBody,Xe as isMemoryTable,lt as isRelationPredicate,Ro as isSoftDeleted,go as isSourceDue,Or as jsonPath,kr as jsonPathSql,ot as keysTouchRanges,po as liftSourceId,hn as lintReadonlySql,Xa as listReactorStates,Vo as listTables,Hn as literalInList,Za as markUnvouchableReads,Oa as matchesRankStaticWhere,d as matchesStaticWhere,ho as materializeExternalRows,xo as materializeExternalRowsIncremental,He as memoryTableNames,Pn as mergeChangedKeys,g as mergeWhere,oe as migrateCdcLog,ae as migrateCdcMeta,Te as migrateClientWatermark,Ie as migrateCommitSeq,jr as migrateDurableStreams,Oe as migrateGlobalShapeSnapshot,Ue as migrateIdempotency,Ha as migrateReactorState,Je as migrateSearchState,tr as migrateShapePokeCursor,te as minCdcReplayableSeq,ne as minCdcSeq,nr as minShapePokeCursor,Et as nextPromotionState,p as normalizeCountArgument,G as normalizeIdStructurally,Ea as normalizeOrderKeys,So as normalizeSourceDocument,uo as normalizeSourceValue,Kr as param,t as parseExportShardArgs,n as parseImportShardArgs,A as planAggregateLookup,yo as pointInBoundingBox,ln as projectColumns,Ao as pullExternalSourceIncrementalTick,_o as pullExternalSourceTick,Fr as qualifiedJsonPath,Br as qualifiedJsonPathSql,Zn as quoteIdentifier,ka as rankKeyFromDoc,Fa as rankPivotConditionSql,Ba as rankTableName,Ka as reactiveCacheKey,za as reactorNeedsRun,T as readAggregateValue,Se as readArchivedCdcChanges,N as readAuditLog,pa as readBookmark,ia as readCapturedMail,ue as readCdcArchivedThrough,ie as readCdcChangeKeys,se as readCdcChanges,le as readCdcCursor,me as readCdcEpoch,Ee as readClientWatermark,be as readCommitSeq,Co as readExternalSourceBaseline,ke as readGlobalShapeSnapshot,qe as readIdempotent,ur as readMigrationStatus,La as readQueueMessageById,Pa as readQueueMessages,Va as readReactorState,Wt as readSchemaHistory,Xt as readSchemaVersion,Ze as readSearchBackfillState,ir as readShapePokeCursor,Jr as readStreamChunks,Zr as readStreamRun,Qo as readTablePage,sa as recordCapturedMail,Mn as recordChangedKeys,Yo as recordFanoutPass,jo as recordGlobalPollPass,Ma as recordQueueMessages,Ht as recordSchemaVersion,Jo as recordShapeProbePass,ut as relationHooks,Rt as relayCountFor,vr as renderSql,Ft as reprojectableFields,jn as reprojectionMigrationId,Bt as reprojectionTables,Ga as resolveRankPartition,Qe as resolveRankSeekTuple,mt as resolveRelationPredicates,ft as resolveWith,Gr as rowToDocument,fr as runDataMigration,gr as runDrizzle,To as runExternalSourceTick,xn as runReadonlySql,ht as runRowValidators,ei as runShardMigrations,pn as runSocketPool,Ar as runSql,wn as runTriggers,vn as selectExpiredIds,i as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,Zo as selectMatchingIds,cr as selectShapeMembers,dr as selectShapeRows,Vt as serializeSqlValue,gt as shapeRoutingKey,Ra as softDeleteScope,Ua as sortColumnName,Wr as sqliteInList,oi as stableStringify,ti as stableWireKey,_n as subscriptionFrames,In as subscriptionListDeltas,$o as summarizeFanoutTopics,ea as summarizeSubscriptions,Ur as tableColumns,Er as tableFromDepKey,S as throwingScheduler,ga as tiebreakDirectionFor,ce as trimCdcChanges,we as trimIdempotent,$r as trimStreamRuns,qr as tryRowToDocument,bn as trySendFrame,Xr as unionAll,s as validateImportRow,fe as writeCdcArchivedThrough,Fe as writeGlobalShapeSnapshot,Ke as writeIdempotent,Qa as writeReactorState,$e as writeSearchBackfillState,sr as writeShapePokeCursor,lr as writeShapePokeCursors,Dn as writeTouchesMemo};
1
+ import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as n,selectExportTables as i,validateImportRow as s}from"./packem_shared/exportShardRows-D_upYHRQ.mjs";import{AGGREGATE_SQL_FUNCTION as m,aggregateSqlFunction as c,matchesStaticWhere as d,normalizeCountArgument as p,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as f,coerceAggregateNumber as h,encodeAggregateKey as x,foldAggregateTally as C,readAggregateValue as T}from"./packem_shared/aggregateTableName-C7o-gpms.mjs";import{CountRlsUnsupportedError as R,mergeWhere as g,planAggregateLookup as A,selectIndexForAggregate as _,selectIndexForCount as I,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-Bdfupt3g.mjs";import{AUDIT_LOG_TABLE as P,appendAuditEntry as M,ensureAuditTable as D,readAuditLog as N}from"./packem_shared/AUDIT_LOG_TABLE-ONxmEAIz.mjs";import{NotUniqueError as O,assertNoExplicitUndefined as k,assertValidClientId as F,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-CTSwCMsP.mjs";import{backfillAggregateIndexes as q,backfillRankIndexes as w,backfillSearchIndexes as K,backfillSearchIndexesForTable as v}from"./packem_shared/backfillAggregateIndexes-pQWaX2Yu.mjs";import{CDC_LOG_TABLE as X,CDC_LOG_TABLE_SEQ_INDEX as H,CDC_META_TABLE as z,appendCdcChange as V,applyCdcChanges as Q,bumpCdcEpoch as Y,cdcCanVouchFor as j,cdcSeqLeavingRows as J,cdcTouchesTables as Z,cdcTrimmedError as $,compactCdcDocs as ee,cursorBelowRetainedFloor as re,migrateCdcLog as oe,migrateCdcMeta as ae,minCdcReplayableSeq as te,minCdcSeq as ne,readCdcChangeKeys as ie,readCdcChanges as se,readCdcCursor as le,readCdcEpoch as me,trimCdcChanges as ce}from"./packem_shared/CDC_LOG_TABLE-CAyqu8cg.mjs";import{archiveCdcSegment as pe,readArchivedCdcChanges as Se,readCdcArchivedThrough as ue,writeCdcArchivedThrough as fe}from"./packem_shared/archiveCdcSegment-DU4uzDFQ.mjs";import{CLIENT_WATERMARK_TABLE as xe,advanceClientWatermark as Ce,migrateClientWatermark as Te,readClientWatermark as Ee}from"./packem_shared/CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{COMMIT_SEQ_FIELD as ge,COMMIT_SEQ_TABLE as Ae,allocateCommitSeq as _e,migrateCommitSeq as Ie,readCommitSeq as be}from"./packem_shared/COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{c as Pe}from"./packem_shared/ctx-db-companions-B4O4d95S.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as De,deleteGlobalShapeSnapshot as Ne,deleteGlobalShapeSnapshotsForConnection as ye,migrateGlobalShapeSnapshot as Oe,readGlobalShapeSnapshot as ke,writeGlobalShapeSnapshot as Fe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{IDEMPOTENCY_TABLE as Ge,migrateIdempotency as Ue,readIdempotent as qe,trimIdempotent as we,writeIdempotent as Ke}from"./packem_shared/IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{clearMemoryTables as We,isMemoryTable as Xe,memoryTableNames as He}from"./packem_shared/clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as Ve,resolveRankSeekTuple as Qe}from"./packem_shared/computeRankPage-DEkYJ9Tz.mjs";import{S as je,m as Je,r as Ze,w as $e}from"./packem_shared/ctx-db-search-state-ruTuCsxa.mjs";import{SHAPE_POKE_CURSOR_TABLE as rr,deleteShapePokeCursor as or,deleteShapePokeCursorsForConnection as ar,migrateShapePokeCursor as tr,minShapePokeCursor as nr,readShapePokeCursor as ir,writeShapePokeCursor as sr,writeShapePokeCursors as lr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs";import{selectShapeMembers as cr,selectShapeRows as dr}from"./packem_shared/selectShapeMembers-DqikYFjS.mjs";import{DATA_MIGRATION_STATE_TABLE as Sr,readMigrationStatus as ur,runDataMigration as fr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-BttUL9Sv.mjs";import{SCAN_DEP as xr,createDependencyTracker as Cr,depKey as Tr,tableFromDepKey as Er}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as gr,runSql as Ar}from"./packem_shared/runDrizzle-2ULFQR_k.mjs";import{A as Ir,a as br,b as Lr,D as Pr,c as Mr,d as Dr,g as Nr,i as yr,j as Or,e as kr,q as Fr,f as Br,r as Gr,t as Ur,h as qr}from"./packem_shared/do-sql-FNOnpyHm.mjs";import{param as Kr,renderSql as vr,sqliteInList as Wr,unionAll as Xr}from"./packem_shared/param-DlozcSQu.mjs";import{appendStreamChunk as zr,claimStreamRun as Vr,deleteStreamRun as Qr,finishStreamRun as Yr,migrateDurableStreams as jr,readStreamChunks as Jr,readStreamRun as Zr,trimStreamRuns as $r}from"./packem_shared/appendStreamChunk-C1Ok4b6J.mjs";import{DurableStreamRunner as ro,MAX_DURABLE_STREAM_BYTES as oo,MAX_DURABLE_STREAM_CHUNKS as ao,decideDurableAttach as to}from"./packem_shared/DurableStreamRunner-rTYp4v03.mjs";import{envOptionalPositiveInt as io,envPositiveInt as so}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as mo}from"./packem_shared/diffExternalSource-DgDJhslq.mjs";import{liftSourceId as po,normalizeSourceDocument as So,normalizeSourceValue as uo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as ho,materializeExternalRowsIncremental as xo,readExternalSourceBaseline as Co,runExternalSourceTick as To}from"./packem_shared/materializeExternalRows-CAPAra-0.mjs";import{isSoftDeleted as Ro,isSourceDue as go,pullExternalSourceIncrementalTick as Ao,pullExternalSourceTick as _o}from"./packem_shared/isSoftDeleted-CVu_TCeK.mjs";import{GEO_DEFAULT_PRECISION as bo,boundingBoxCenter as Lo,boundingBoxGeohashes as Po,coveringGeohashes as Mo,encodeGeohash as Do,haversineMeters as No,pointInBoundingBox as yo}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as ko}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as Bo,ADMIN_FUNCTION_PREFIX as Go,DEFAULT_FANOUT_TOPIC_LIMIT as Uo,FLAGS_FUNCTION_PREFIX as qo,MAX_PAGE_SIZE as wo,RELATION_FUNCTION_PREFIX as Ko,createFanoutCounters as vo,createGlobalPollCounters as Wo,createShapeProbeCounters as Xo,facetColumn as Ho,findStorageReferences as zo,listTables as Vo,readTablePage as Qo,recordFanoutPass as Yo,recordGlobalPollPass as jo,recordShapeProbePass as Jo,selectMatchingIds as Zo,summarizeFanoutTopics as $o,summarizeSubscriptions as ea}from"./packem_shared/ADMIN_FUNCTIONS-MzNUYBeH.mjs";import{MAIL_RETENTION as oa,MAIL_TABLE as aa,clearCapturedMail as ta,ensureMailTable as na,readCapturedMail as ia,recordCapturedMail as sa}from"./packem_shared/MAIL_RETENTION-DGAQTHHs.mjs";import{NotFoundError as ma}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as da,readBookmark as pa}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as ua,applySelect as fa,buildSeekBeforeWhere as ha,buildSeekWhere as xa,decodeCursor as Ca,encodeCursor as Ta,normalizeOrderKeys as Ea,softDeleteScope as Ra,tiebreakDirectionFor as ga}from"./packem_shared/CURSOR_PREFIX-qn6nNVS7.mjs";import{QUEUE_TABLE as _a,clearQueueMessages as Ia,isLossyBody as ba,readQueueMessageById as La,readQueueMessages as Pa,recordQueueMessages as Ma}from"./packem_shared/QUEUE_TABLE-s7QJZvBz.mjs";import{RANK_TIEBREAK as Na,encodePartitionKey as ya,matchesRankStaticWhere as Oa,rankKeyFromDoc as ka,rankPivotConditionSql as Fa,rankTableName as Ba,resolveRankPartition as Ga,sortColumnName as Ua}from"./packem_shared/RANK_TIEBREAK-CkNuGm6a.mjs";import{ReactiveCache as wa,reactiveCacheKey as Ka}from"./packem_shared/ReactiveCache-Co_Q4zWX.mjs";import{REACTOR_STATE_TABLE as Wa,listReactorStates as Xa,migrateReactorState as Ha,reactorNeedsRun as za,readReactorState as Va,writeReactorState as Qa}from"./packem_shared/REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{UNVOUCHABLE_DEP as ja,createReadFootprint as Ja,markUnvouchableReads as Za}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as et,indexKeysForRow as rt,keysTouchRanges as ot}from"./packem_shared/buildIndexRange-CBKQmHSS.mjs";import{DEFAULT_MAX_RELATION_KEYS as tt,assertFlatPredicate as nt,assertShapeShardable as it,containsRelationPredicate as st,isRelationPredicate as lt,resolveRelationPredicates as mt}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-Ciwtjo9t.mjs";import{applyOnDelete as dt,distinctValues as pt,fanOutScalarCounts as St,relationHooks as ut,resolveWith as ft,runRowValidators as ht}from"./packem_shared/applyOnDelete-tDhKaeB6.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as Ct,clampPromotionThresholds as Tt,nextPromotionState as Et,relayCountFor as Rt,shapeRoutingKey as gt}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";import{DEFAULT_MAX_RELAYS as _t,OwnerRelay as It,RelayMember as bt,createRelayLink as Lt}from"./packem_shared/DEFAULT_MAX_RELAYS-C3L_1GLp.mjs";import{createReplicaLink as Mt,gateReplicaDispatch as Dt,handleReplicaControl as Nt}from"./packem_shared/createReplicaLink-D1Rmca3b.mjs";import{buildReprojectionMigration as Ot,countLegacyRows as kt,reprojectableFields as Ft,reprojectionTables as Bt}from"./packem_shared/buildReprojectionMigration-C-EJ_eKR.mjs";import{RLS_UNWRAP_SYMBOL as Ut,RlsRequiredError as qt,guardWriter as wt}from"./packem_shared/RLS_UNWRAP_SYMBOL-B3RgW-Kb.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as vt,readSchemaHistory as Wt,readSchemaVersion as Xt,recordSchemaVersion as Ht}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";import{serializeSqlValue as Vt}from"./packem_shared/serializeSqlValue-B_-zaEWZ.mjs";import{buildSettings as Yt,isDevEnvironment as jt}from"./packem_shared/buildSettings-B4igo4rJ.mjs";import{buildShapeDiff as Zt}from"./packem_shared/buildShapeDiff-C-ipEyt_.mjs";import{ShapeDiffCache as en,createShapeDiffCache as rn,globalShapeReadKey as on}from"./packem_shared/ShapeDiffCache-gdaILV5E.mjs";import{buildPokeFrames as tn,diffGlobalMembership as nn,encodeRowsPatch as sn,projectColumns as ln}from"./packem_shared/buildPokeFrames-BBE6J91z.mjs";import{ShardRunner as cn}from"./packem_shared/ShardRunner-C9p5DVOx.mjs";import{runSocketPool as pn}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as un,assertReadonly as fn,lintReadonlySql as hn,runReadonlySql as xn}from"./packem_shared/MAX_SQL_ROWS-RvXZ7S7f.mjs";import{BIGINT_KEY_DIGITS as Tn,bigintSqlKey as En,decodeBigintSqlKey as Rn}from"./packem_shared/BIGINT_KEY_DIGITS-GvEBhyR5.mjs";import{awaitWsDrain as An,subscriptionFrames as _n,subscriptionListDeltas as In,trySendFrame as bn}from"./packem_shared/awaitWsDrain-apizgmKY.mjs";import{mergeChangedKeys as Pn,recordChangedKeys as Mn,writeTouchesMemo as Dn}from"./packem_shared/mergeChangedKeys-D1T-TPUb.mjs";import{createSystemReader as yn}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as kn}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Bn,TransactionHeadroomTracker as Gn}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-D_xv2cwd.mjs";import{hasTrigger as qn,runTriggers as wn}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as vn}from"./packem_shared/selectExpiredIds-BjZ_UtMx.mjs";import{c as Xn,l as Hn}from"./packem_shared/where-sql-B1l5NcUZ.mjs";import{RELATION_EXISTS_KEY as Vn}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as Yn,reprojectionMigrationId as jn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{quoteIdentifier as Zn}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as ei}from"./packem_shared/runShardMigrations-CkG92fSl.mjs";import{stableStringify as oi}from"./packem_shared/stableStringify-DibjylKD.mjs";import{stableWireKey as ti}from"./packem_shared/stableWireKey-D2US4k_J.mjs";export{Bo as ADMIN_FUNCTIONS,Go as ADMIN_FUNCTION_PREFIX,m as AGGREGATE_SQL_FUNCTION,Ir as AGG_COUNT,br as AGG_KEY,Lr as AGG_VALUE,P as AUDIT_LOG_TABLE,Tn as BIGINT_KEY_DIGITS,X as CDC_LOG_TABLE,H as CDC_LOG_TABLE_SEQ_INDEX,z as CDC_META_TABLE,xe as CLIENT_WATERMARK_TABLE,ge as COMMIT_SEQ_FIELD,Ae as COMMIT_SEQ_TABLE,ua as CURSOR_PREFIX,kn as ConflictError,R as CountRlsUnsupportedError,Sr as DATA_MIGRATION_STATE_TABLE,Uo as DEFAULT_FANOUT_TOPIC_LIMIT,tt as DEFAULT_MAX_RELATION_KEYS,_t as DEFAULT_MAX_RELAYS,Ct as DEFAULT_PROMOTION_THRESHOLDS,Bn as DEFAULT_TRANSACTION_LIMITS,Pr as DOC_COLUMN,ro as DurableStreamRunner,qo as FLAGS_FUNCTION_PREFIX,bo as GEO_DEFAULT_PRECISION,De as GLOBAL_SHAPE_SNAPSHOT_TABLE,ko as GlobalPollTick,Ge as IDEMPOTENCY_TABLE,oa as MAIL_RETENTION,aa as MAIL_TABLE,oo as MAX_DURABLE_STREAM_BYTES,ao as MAX_DURABLE_STREAM_CHUNKS,wo as MAX_PAGE_SIZE,un as MAX_SQL_ROWS,ma as NotFoundError,O as NotUniqueError,It as OwnerRelay,_a as QUEUE_TABLE,Na as RANK_TIEBREAK,Wa as REACTOR_STATE_TABLE,Vn as RELATION_EXISTS_KEY,Ko as RELATION_FUNCTION_PREFIX,Yn as REPROJECTION_MIGRATION_PREFIX,Ut as RLS_UNWRAP_SYMBOL,wa as ReactiveCache,bt as RelayMember,qt as RlsRequiredError,xr as SCAN_DEP,vt as SCHEMA_HISTORY_MAX_VERSIONS,je as SEARCH_STATE_TABLE,rr as SHAPE_POKE_CURSOR_TABLE,en as ShapeDiffCache,cn as ShardRunner,Gn as TransactionHeadroomTracker,ja as UNVOUCHABLE_DEP,Ce as advanceClientWatermark,Mr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,_e as allocateCommitSeq,M as appendAuditEntry,V as appendCdcChange,zr as appendStreamChunk,Q as applyCdcChanges,dt as applyOnDelete,fa as applySelect,pe as archiveCdcSegment,da as armRestore,nt as assertFlatPredicate,k as assertNoExplicitUndefined,fn as assertReadonly,it as assertShapeShardable,F as assertValidClientId,An as awaitWsDrain,q as backfillAggregateIndexes,w as backfillRankIndexes,K as backfillSearchIndexes,v as backfillSearchIndexesForTable,En as bigintSqlKey,Lo as boundingBoxCenter,Po as boundingBoxGeohashes,et as buildIndexRange,tn as buildPokeFrames,Ot as buildReprojectionMigration,ha as buildSeekBeforeWhere,xa as buildSeekWhere,Yt as buildSettings,Zt as buildShapeDiff,Y as bumpCdcEpoch,j as cdcCanVouchFor,J as cdcSeqLeavingRows,Z as cdcTouchesTables,$ as cdcTrimmedError,Vr as claimStreamRun,Tt as clampPromotionThresholds,ta as clearCapturedMail,We as clearMemoryTables,Ia as clearQueueMessages,h as coerceAggregateNumber,ee as compactCdcDocs,Xn as compileWhereSql,Ve as computeRankPage,st as containsRelationPredicate,kt as countLegacyRows,Mo as coveringGeohashes,Pe as createCompanionSync,Cr as createDependencyTracker,vo as createFanoutCounters,Wo as createGlobalPollCounters,Dr as createIndexSql,Ja as createReadFootprint,Lt as createRelayLink,Mt as createReplicaLink,rn as createShapeDiffCache,Xo as createShapeProbeCounters,B as createShardCtxDb,yn as createSystemReader,re as cursorBelowRetainedFloor,to as decideDurableAttach,Rn as decodeBigintSqlKey,Ca as decodeCursor,Ne as deleteGlobalShapeSnapshot,ye as deleteGlobalShapeSnapshotsForConnection,or as deleteShapePokeCursor,ar as deleteShapePokeCursorsForConnection,Qr as deleteStreamRun,Tr as depKey,mo as diffExternalSource,nn as diffGlobalMembership,pt as distinctValues,x as encodeAggregateKey,Ta as encodeCursor,Do as encodeGeohash,ya as encodePartitionKey,sn as encodeRowsPatch,D as ensureAuditTable,na as ensureMailTable,io as envOptionalPositiveInt,so as envPositiveInt,o as exportShardRows,Ho as facetColumn,St as fanOutScalarCounts,zo as findStorageReferences,Yr as finishStreamRun,C as foldAggregateTally,Dt as gateReplicaDispatch,Nr as geoTableName,on as globalShapeReadKey,wt as guardWriter,Nt as handleReplicaControl,qn as hasTrigger,No as haversineMeters,a as importShardRows,rt as indexKeysForRow,jt as isDevEnvironment,yr as isFtsAvailable,ba as isLossyBody,Xe as isMemoryTable,lt as isRelationPredicate,Ro as isSoftDeleted,go as isSourceDue,Or as jsonPath,kr as jsonPathSql,ot as keysTouchRanges,po as liftSourceId,hn as lintReadonlySql,Xa as listReactorStates,Vo as listTables,Hn as literalInList,Za as markUnvouchableReads,Oa as matchesRankStaticWhere,d as matchesStaticWhere,ho as materializeExternalRows,xo as materializeExternalRowsIncremental,He as memoryTableNames,Pn as mergeChangedKeys,g as mergeWhere,oe as migrateCdcLog,ae as migrateCdcMeta,Te as migrateClientWatermark,Ie as migrateCommitSeq,jr as migrateDurableStreams,Oe as migrateGlobalShapeSnapshot,Ue as migrateIdempotency,Ha as migrateReactorState,Je as migrateSearchState,tr as migrateShapePokeCursor,te as minCdcReplayableSeq,ne as minCdcSeq,nr as minShapePokeCursor,Et as nextPromotionState,p as normalizeCountArgument,G as normalizeIdStructurally,Ea as normalizeOrderKeys,So as normalizeSourceDocument,uo as normalizeSourceValue,Kr as param,t as parseExportShardArgs,n as parseImportShardArgs,A as planAggregateLookup,yo as pointInBoundingBox,ln as projectColumns,Ao as pullExternalSourceIncrementalTick,_o as pullExternalSourceTick,Fr as qualifiedJsonPath,Br as qualifiedJsonPathSql,Zn as quoteIdentifier,ka as rankKeyFromDoc,Fa as rankPivotConditionSql,Ba as rankTableName,Ka as reactiveCacheKey,za as reactorNeedsRun,T as readAggregateValue,Se as readArchivedCdcChanges,N as readAuditLog,pa as readBookmark,ia as readCapturedMail,ue as readCdcArchivedThrough,ie as readCdcChangeKeys,se as readCdcChanges,le as readCdcCursor,me as readCdcEpoch,Ee as readClientWatermark,be as readCommitSeq,Co as readExternalSourceBaseline,ke as readGlobalShapeSnapshot,qe as readIdempotent,ur as readMigrationStatus,La as readQueueMessageById,Pa as readQueueMessages,Va as readReactorState,Wt as readSchemaHistory,Xt as readSchemaVersion,Ze as readSearchBackfillState,ir as readShapePokeCursor,Jr as readStreamChunks,Zr as readStreamRun,Qo as readTablePage,sa as recordCapturedMail,Mn as recordChangedKeys,Yo as recordFanoutPass,jo as recordGlobalPollPass,Ma as recordQueueMessages,Ht as recordSchemaVersion,Jo as recordShapeProbePass,ut as relationHooks,Rt as relayCountFor,vr as renderSql,Ft as reprojectableFields,jn as reprojectionMigrationId,Bt as reprojectionTables,Ga as resolveRankPartition,Qe as resolveRankSeekTuple,mt as resolveRelationPredicates,ft as resolveWith,Gr as rowToDocument,fr as runDataMigration,gr as runDrizzle,To as runExternalSourceTick,xn as runReadonlySql,ht as runRowValidators,ei as runShardMigrations,pn as runSocketPool,Ar as runSql,wn as runTriggers,vn as selectExpiredIds,i as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,Zo as selectMatchingIds,cr as selectShapeMembers,dr as selectShapeRows,Vt as serializeSqlValue,gt as shapeRoutingKey,Ra as softDeleteScope,Ua as sortColumnName,Wr as sqliteInList,oi as stableStringify,ti as stableWireKey,_n as subscriptionFrames,In as subscriptionListDeltas,$o as summarizeFanoutTopics,ea as summarizeSubscriptions,Ur as tableColumns,Er as tableFromDepKey,S as throwingScheduler,ga as tiebreakDirectionFor,ce as trimCdcChanges,we as trimIdempotent,$r as trimStreamRuns,qr as tryRowToDocument,bn as trySendFrame,Xr as unionAll,s as validateImportRow,fe as writeCdcArchivedThrough,Fe as writeGlobalShapeSnapshot,Ke as writeIdempotent,Qa as writeReactorState,$e as writeSearchBackfillState,sr as writeShapePokeCursor,lr as writeShapePokeCursors,Dn as writeTouchesMemo};
@@ -1 +1 @@
1
- import{LunoraError as E}from"@lunora/errors";import{m as $,n as y}from"./do-sql-Cv3yRshL.mjs";import{quoteIdentifier as d}from"./quoteIdentifier-CObIFRhb.mjs";import{d as L}from"./wire-codec-CKV-4MEN.mjs";const te="__lunora_admin__:",re="__lunora_relation__:",ne="__lunora_flags__:",se={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backfillSearch:"__lunora_admin__:backfillSearch",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",getAdvisories:"__lunora_admin__:getAdvisories",getAdvisorProcedures:"__lunora_admin__:getAdvisorProcedures",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",listTablesIndexes:"__lunora_admin__:listTablesIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listReactors:"__lunora_admin__:listReactors",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",patchRows:"__lunora_admin__:patchRows",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",replayQueueMessage:"__lunora_admin__:replayQueueMessage",resolveIssue:"__lunora_admin__:resolveIssue",rlsPolicies:"__lunora_admin__:rlsPolicies",schemaHistory:"__lunora_admin__:schemaHistory",schemaVersion:"__lunora_admin__:schemaVersion",runAs:"__lunora_admin__:runAs",runMigration:"__lunora_admin__:runMigration",runSql:"__lunora_admin__:runSql",sendQueueMessage:"__lunora_admin__:sendQueueMessage",sendTestMail:"__lunora_admin__:sendTestMail",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},D=50,h=500,U=30,j=200,f="__doc__",O=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},W=e=>{const{[y]:t,...r}=e;return t===void 0?r:t===null||typeof t!="object"||Array.isArray(t)?{[y]:t,...r}:{...r,...L(t)}},q=(e,t)=>{if(!e.includes(f))return{columns:e,rows:t};const r=[];for(const s of t){const o=s[f],i=typeof o=="string"?O(o):void 0;if(i===void 0)return{columns:e,rows:t};const c=Object.fromEntries(Object.entries(s).filter(([u])=>u!==f));r.push({...c,...W(i)})}const n=e.filter(s=>s!==f),a=[],_=new Set(n);for(const s of r)for(const o of Object.keys(s))_.has(o)||(_.add(o),a.push(o));return{columns:[...n,...a],rows:r}},F=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,I=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),C=(e,t,r)=>Math.min(Math.max(e,t),r),P=(e,t)=>{const r=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(r.c)},ae=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),r=[];for(const{name:n}of t)I(n)||r.push({name:n,rowCount:P(e,d(n))});return r},x=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,A=(e,t)=>{if(I(t)||!x(e,t))throw new E("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},M=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(r=>r.name),Q={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},B=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",v=(e,t)=>{const r=t.includes(e),n=t.includes(f);if(!(!r&&!n))return r?{expression:d(e),params:[]}:{expression:`json_extract(${d(f)}, ?)`,params:[`$.${$(e)}`]}},G=(e,t)=>{const r=v(e.column,t);if(r===void 0)return;const{expression:n,params:a}=r;return e.operator==="contains"?{params:[...a,B(e.value)],sql:F(n)}:{params:[...a,e.value],sql:`${n} ${Q[e.operator]} ?`}},H=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,X=e=>{const t=H.exec(e.trim());if(t===null)return;const r=Number(t[1]),n=t[2]===void 0?void 0:Number(t[2]),a=t[3]===void 0?void 0:Number(t[3]);if(n!==void 0&&(n<1||n>12)||a!==void 0&&(a<1||a>31)||r<100)return;const _=Date.UTC(r,(n??1)-1,a??1);if(a!==void 0&&new Date(_).getUTCDate()!==a)return;let s;return a!==void 0?s=Date.UTC(r,(n??1)-1,a+1):n===void 0?s=Date.UTC(r+1,0,1):s=Date.UTC(r,n,1),{from:_,to:s}},R=(e,t,r)=>{const n=[],a=[];if(t!==""&&e.length>0){const _=e.map(o=>F(d(o)));a.push(...e.map(()=>t));const s=X(t);if(s!==void 0)for(const o of e)_.push(`(${d(o)} >= ? AND ${d(o)} < ?)`),a.push(s.from,s.to);n.push(`(${_.join(" OR ")})`)}for(const _ of r??[]){const s=G(_,e);s!==void 0&&(n.push(`(${s.sql})`),a.push(...s.params))}return n.length===0?void 0:{parameters:a,where:n.join(" AND ")}},Y=(e,t)=>{if(e===void 0)return;const r=v(e.column,t);if(r===void 0)return;const n=e.direction==="desc"?"DESC":"ASC";return{params:r.params,sql:`${r.expression} ${n}`}},oe=(e,t)=>{const{table:r}=t;A(e,r);const n=C(Math.trunc(t.limit??D),1,h),a=Math.max(0,Math.trunc(t.offset??0)),_=d(r),s=M(e,_),o=t.search?.trim()??"",i=S=>{if(t.refs===void 0)return S;const T={};for(const w of S.columns){const k=t.refs[w];k!==void 0&&(T[w]=k)}return Object.keys(T).length>0?{...S,refs:T}:S},c=R(s,o,t.filters),u=Y(t.orderBy,s),l=c===void 0?"":` WHERE ${c.where}`,m=u===void 0?"":` ORDER BY ${u.sql}`,p=c?.parameters??[],g=u?.params??[];let b;t.skipCount||(b=c===void 0?P(e,_):Number(e.exec(`SELECT COUNT(*) AS c FROM ${_}${l}`,...p).one().c));const N=e.exec(`SELECT * FROM ${_}${l}${m} LIMIT ? OFFSET ?`,...p,...g,n,a).toArray();return i({...q(s,N),total:b})},_e=(e,t)=>{const{table:r}=t;A(e,r);const n=C(Math.trunc(t.limit??h),1,h),a=d(r),_=M(e,a),s=t.search?.trim()??"",o=R(_,s,t.filters),i=[],c=[];o!==void 0&&(i.push(o.where),c.push(...o.parameters)),t.after!==void 0&&(i.push("id > ?"),c.push(t.after));const u=i.length===0?"":` WHERE ${i.join(" AND ")}`,l=t.after===void 0?"":" ORDER BY id",m=e.exec(`SELECT id FROM ${a}${u}${l} LIMIT ?`,...c,n+1).toArray(),p=m.length>n,g=m.slice(0,n).map(b=>b.id);return{hasMore:p,ids:g}},K=(e,t,r)=>{const n=new Set(r.filter(_=>_!==f));if(!r.includes(f))return n;const a=e.exec(`SELECT ${d(f)} AS doc FROM ${t} LIMIT ?`,h).toArray();for(const{doc:_}of a){const s=typeof _=="string"?O(_):void 0;if(s!==void 0)for(const o of Object.keys(s))n.add(o)}return n},ie=(e,t)=>{const{column:r,table:n}=t;A(e,n);const a=d(n),_=M(e,a);if(!K(e,a,_).has(r))throw new E("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const s=v(r,_);if(s===void 0)throw new E("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const o=C(Math.trunc(t.limit??U),1,j),i=t.search?.trim()??"",c=R(_,i,t.filters),u=c===void 0?"":` WHERE ${c.where}`,l=c?.parameters??[],m=e.exec(`SELECT ${s.expression} AS value, COUNT(*) AS count FROM ${a}${u} GROUP BY ${s.expression} ORDER BY count DESC LIMIT ?`,...s.params,...l,...s.params,o+1).toArray();return{truncated:m.length>o,values:m.slice(0,o).map(g=>({count:Number(g.count),value:g.value}))}},ce=(e,t,r)=>{const n={},a=r.slice(0,h);for(const s of a)n[s]=[];if(a.length===0)return{references:n,storageColumns:t};const _=a.map(()=>"?").join(", ");for(const[s,o]of Object.entries(t)){if(I(s)||!x(e,s))continue;const i=d(s),c=M(e,i);for(const u of o){const l=v(u,c);if(l===void 0)continue;const m=e.exec(`SELECT id, ${l.expression} AS ref FROM ${i} WHERE ${l.expression} IN (${_})`,...l.params,...l.params,...a).toArray();for(const p of m)n[p.ref]?.push({column:u,id:p.id,table:s})}}return{references:n,storageColumns:t}},ue=e=>{const t=e.map((n,a)=>{const _=Object.values(n.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:n.admin===!0,id:a,subscriptions:_}}),r=t.reduce((n,a)=>n+a.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:r}},V=20,le=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),de=()=>({run:0,served:0}),me=()=>({drains:0,pairsSkipped:0}),fe=(e,t,r)=>({drains:e.drains+t,pairsSkipped:e.pairsSkipped+r}),pe=(e,t,r)=>({run:e.run+t,served:e.served+r}),ge=(e,t,r,n)=>({maxMs:Math.max(e.maxMs,n),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+r,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+n}),he=(e,t=V)=>{const r=new Map,n=new Map;for(const s of e){for(const o of Object.values(s.shapes??{})){const i=o.name??"(unknown shape)";r.set(i,(r.get(i)??0)+1)}for(const o of s.whispers??[])n.set(o,(n.get(o)??0)+1)}const a=[...[...r].map(([s,o])=>({kind:"shape",subscribers:o,topic:s})),...[...n].map(([s,o])=>({kind:"whisper",subscribers:o,topic:s}))];return a.sort((s,o)=>o.subscribers-s.subscribers||s.topic.localeCompare(o.topic)),{peakSubscribers:a[0]?.subscribers??0,topics:a.slice(0,t),totalConnections:e.length}};export{se as ADMIN_FUNCTIONS,te as ADMIN_FUNCTION_PREFIX,V as DEFAULT_FANOUT_TOPIC_LIMIT,ne as FLAGS_FUNCTION_PREFIX,h as MAX_PAGE_SIZE,re as RELATION_FUNCTION_PREFIX,le as createFanoutCounters,me as createGlobalPollCounters,de as createShapeProbeCounters,X as datePrefixRange,ie as facetColumn,ce as findStorageReferences,ae as listTables,oe as readTablePage,ge as recordFanoutPass,fe as recordGlobalPollPass,pe as recordShapeProbePass,_e as selectMatchingIds,he as summarizeFanoutTopics,ue as summarizeSubscriptions};
1
+ import{LunoraError as E}from"@lunora/errors";import{m as $,n as y}from"./do-sql-FNOnpyHm.mjs";import{quoteIdentifier as d}from"./quoteIdentifier-CObIFRhb.mjs";import{d as L}from"./wire-codec-C-FpWm52.mjs";const te="__lunora_admin__:",re="__lunora_relation__:",ne="__lunora_flags__:",se={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backfillSearch:"__lunora_admin__:backfillSearch",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",getAdvisories:"__lunora_admin__:getAdvisories",getAdvisorProcedures:"__lunora_admin__:getAdvisorProcedures",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",listTablesIndexes:"__lunora_admin__:listTablesIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listReactors:"__lunora_admin__:listReactors",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",patchRows:"__lunora_admin__:patchRows",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",replayQueueMessage:"__lunora_admin__:replayQueueMessage",resolveIssue:"__lunora_admin__:resolveIssue",rlsPolicies:"__lunora_admin__:rlsPolicies",schemaHistory:"__lunora_admin__:schemaHistory",schemaVersion:"__lunora_admin__:schemaVersion",runAs:"__lunora_admin__:runAs",runMigration:"__lunora_admin__:runMigration",runSql:"__lunora_admin__:runSql",sendQueueMessage:"__lunora_admin__:sendQueueMessage",sendTestMail:"__lunora_admin__:sendTestMail",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},D=50,h=500,U=30,j=200,f="__doc__",O=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},W=e=>{const{[y]:t,...r}=e;return t===void 0?r:t===null||typeof t!="object"||Array.isArray(t)?{[y]:t,...r}:{...r,...L(t)}},q=(e,t)=>{if(!e.includes(f))return{columns:e,rows:t};const r=[];for(const s of t){const o=s[f],i=typeof o=="string"?O(o):void 0;if(i===void 0)return{columns:e,rows:t};const c=Object.fromEntries(Object.entries(s).filter(([u])=>u!==f));r.push({...c,...W(i)})}const n=e.filter(s=>s!==f),a=[],_=new Set(n);for(const s of r)for(const o of Object.keys(s))_.has(o)||(_.add(o),a.push(o));return{columns:[...n,...a],rows:r}},F=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,I=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),C=(e,t,r)=>Math.min(Math.max(e,t),r),P=(e,t)=>{const r=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(r.c)},ae=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),r=[];for(const{name:n}of t)I(n)||r.push({name:n,rowCount:P(e,d(n))});return r},x=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,A=(e,t)=>{if(I(t)||!x(e,t))throw new E("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},M=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(r=>r.name),Q={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},B=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",v=(e,t)=>{const r=t.includes(e),n=t.includes(f);if(!(!r&&!n))return r?{expression:d(e),params:[]}:{expression:`json_extract(${d(f)}, ?)`,params:[`$.${$(e)}`]}},G=(e,t)=>{const r=v(e.column,t);if(r===void 0)return;const{expression:n,params:a}=r;return e.operator==="contains"?{params:[...a,B(e.value)],sql:F(n)}:{params:[...a,e.value],sql:`${n} ${Q[e.operator]} ?`}},H=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,X=e=>{const t=H.exec(e.trim());if(t===null)return;const r=Number(t[1]),n=t[2]===void 0?void 0:Number(t[2]),a=t[3]===void 0?void 0:Number(t[3]);if(n!==void 0&&(n<1||n>12)||a!==void 0&&(a<1||a>31)||r<100)return;const _=Date.UTC(r,(n??1)-1,a??1);if(a!==void 0&&new Date(_).getUTCDate()!==a)return;let s;return a!==void 0?s=Date.UTC(r,(n??1)-1,a+1):n===void 0?s=Date.UTC(r+1,0,1):s=Date.UTC(r,n,1),{from:_,to:s}},R=(e,t,r)=>{const n=[],a=[];if(t!==""&&e.length>0){const _=e.map(o=>F(d(o)));a.push(...e.map(()=>t));const s=X(t);if(s!==void 0)for(const o of e)_.push(`(${d(o)} >= ? AND ${d(o)} < ?)`),a.push(s.from,s.to);n.push(`(${_.join(" OR ")})`)}for(const _ of r??[]){const s=G(_,e);s!==void 0&&(n.push(`(${s.sql})`),a.push(...s.params))}return n.length===0?void 0:{parameters:a,where:n.join(" AND ")}},Y=(e,t)=>{if(e===void 0)return;const r=v(e.column,t);if(r===void 0)return;const n=e.direction==="desc"?"DESC":"ASC";return{params:r.params,sql:`${r.expression} ${n}`}},oe=(e,t)=>{const{table:r}=t;A(e,r);const n=C(Math.trunc(t.limit??D),1,h),a=Math.max(0,Math.trunc(t.offset??0)),_=d(r),s=M(e,_),o=t.search?.trim()??"",i=S=>{if(t.refs===void 0)return S;const T={};for(const w of S.columns){const k=t.refs[w];k!==void 0&&(T[w]=k)}return Object.keys(T).length>0?{...S,refs:T}:S},c=R(s,o,t.filters),u=Y(t.orderBy,s),l=c===void 0?"":` WHERE ${c.where}`,m=u===void 0?"":` ORDER BY ${u.sql}`,p=c?.parameters??[],g=u?.params??[];let b;t.skipCount||(b=c===void 0?P(e,_):Number(e.exec(`SELECT COUNT(*) AS c FROM ${_}${l}`,...p).one().c));const N=e.exec(`SELECT * FROM ${_}${l}${m} LIMIT ? OFFSET ?`,...p,...g,n,a).toArray();return i({...q(s,N),total:b})},_e=(e,t)=>{const{table:r}=t;A(e,r);const n=C(Math.trunc(t.limit??h),1,h),a=d(r),_=M(e,a),s=t.search?.trim()??"",o=R(_,s,t.filters),i=[],c=[];o!==void 0&&(i.push(o.where),c.push(...o.parameters)),t.after!==void 0&&(i.push("id > ?"),c.push(t.after));const u=i.length===0?"":` WHERE ${i.join(" AND ")}`,l=t.after===void 0?"":" ORDER BY id",m=e.exec(`SELECT id FROM ${a}${u}${l} LIMIT ?`,...c,n+1).toArray(),p=m.length>n,g=m.slice(0,n).map(b=>b.id);return{hasMore:p,ids:g}},K=(e,t,r)=>{const n=new Set(r.filter(_=>_!==f));if(!r.includes(f))return n;const a=e.exec(`SELECT ${d(f)} AS doc FROM ${t} LIMIT ?`,h).toArray();for(const{doc:_}of a){const s=typeof _=="string"?O(_):void 0;if(s!==void 0)for(const o of Object.keys(s))n.add(o)}return n},ie=(e,t)=>{const{column:r,table:n}=t;A(e,n);const a=d(n),_=M(e,a);if(!K(e,a,_).has(r))throw new E("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const s=v(r,_);if(s===void 0)throw new E("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const o=C(Math.trunc(t.limit??U),1,j),i=t.search?.trim()??"",c=R(_,i,t.filters),u=c===void 0?"":` WHERE ${c.where}`,l=c?.parameters??[],m=e.exec(`SELECT ${s.expression} AS value, COUNT(*) AS count FROM ${a}${u} GROUP BY ${s.expression} ORDER BY count DESC LIMIT ?`,...s.params,...l,...s.params,o+1).toArray();return{truncated:m.length>o,values:m.slice(0,o).map(g=>({count:Number(g.count),value:g.value}))}},ce=(e,t,r)=>{const n={},a=r.slice(0,h);for(const s of a)n[s]=[];if(a.length===0)return{references:n,storageColumns:t};const _=a.map(()=>"?").join(", ");for(const[s,o]of Object.entries(t)){if(I(s)||!x(e,s))continue;const i=d(s),c=M(e,i);for(const u of o){const l=v(u,c);if(l===void 0)continue;const m=e.exec(`SELECT id, ${l.expression} AS ref FROM ${i} WHERE ${l.expression} IN (${_})`,...l.params,...l.params,...a).toArray();for(const p of m)n[p.ref]?.push({column:u,id:p.id,table:s})}}return{references:n,storageColumns:t}},ue=e=>{const t=e.map((n,a)=>{const _=Object.values(n.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:n.admin===!0,id:a,subscriptions:_}}),r=t.reduce((n,a)=>n+a.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:r}},V=20,le=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),de=()=>({run:0,served:0}),me=()=>({drains:0,pairsSkipped:0}),fe=(e,t,r)=>({drains:e.drains+t,pairsSkipped:e.pairsSkipped+r}),pe=(e,t,r)=>({run:e.run+t,served:e.served+r}),ge=(e,t,r,n)=>({maxMs:Math.max(e.maxMs,n),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+r,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+n}),he=(e,t=V)=>{const r=new Map,n=new Map;for(const s of e){for(const o of Object.values(s.shapes??{})){const i=o.name??"(unknown shape)";r.set(i,(r.get(i)??0)+1)}for(const o of s.whispers??[])n.set(o,(n.get(o)??0)+1)}const a=[...[...r].map(([s,o])=>({kind:"shape",subscribers:o,topic:s})),...[...n].map(([s,o])=>({kind:"whisper",subscribers:o,topic:s}))];return a.sort((s,o)=>o.subscribers-s.subscribers||s.topic.localeCompare(o.topic)),{peakSubscribers:a[0]?.subscribers??0,topics:a.slice(0,t),totalConnections:e.length}};export{se as ADMIN_FUNCTIONS,te as ADMIN_FUNCTION_PREFIX,V as DEFAULT_FANOUT_TOPIC_LIMIT,ne as FLAGS_FUNCTION_PREFIX,h as MAX_PAGE_SIZE,re as RELATION_FUNCTION_PREFIX,le as createFanoutCounters,me as createGlobalPollCounters,de as createShapeProbeCounters,X as datePrefixRange,ie as facetColumn,ce as findStorageReferences,ae as listTables,oe as readTablePage,ge as recordFanoutPass,fe as recordGlobalPollPass,pe as recordShapeProbePass,_e as selectMatchingIds,he as summarizeFanoutTopics,ue as summarizeSubscriptions};
@@ -1 +1 @@
1
- import{A as r,a as l,b as i,D as n,n as m,c as q,d as c,l as d,k as f,g as p,i as u,j as A,e as D,q as G,f as S,r as _,t as h,h as C}from"./do-sql-Cv3yRshL.mjs";import{quoteIdentifier as b}from"./quoteIdentifier-CObIFRhb.mjs";import"./wire-codec-CKV-4MEN.mjs";import"./runDrizzle-2ULFQR_k.mjs";import"./BIGINT_KEY_DIGITS-GvEBhyR5.mjs";import{serializeSqlValue as x}from"./serializeSqlValue-B_-zaEWZ.mjs";export{r as AGG_COUNT,l as AGG_KEY,i as AGG_VALUE,n as DOC_COLUMN,m as DOC_ORIGINALS_KEY,q as aggUpsertSql,c as createIndexSql,d as decodeDocJson,f as encodeDocJson,p as geoTableName,u as isFtsAvailable,A as jsonPath,D as jsonPathSql,G as qualifiedJsonPath,S as qualifiedJsonPathSql,b as quoteIdentifier,_ as rowToDocument,x as serializeSqlValue,h as tableColumns,C as tryRowToDocument};
1
+ import{A as r,a as l,b as i,D as n,n as m,c as q,d as c,l as d,k as f,g as p,i as u,j as A,e as D,q as G,f as S,r as _,t as h,h as C}from"./do-sql-FNOnpyHm.mjs";import{quoteIdentifier as b}from"./quoteIdentifier-CObIFRhb.mjs";import"./wire-codec-C-FpWm52.mjs";import"./runDrizzle-2ULFQR_k.mjs";import"./BIGINT_KEY_DIGITS-GvEBhyR5.mjs";import{serializeSqlValue as x}from"./serializeSqlValue-B_-zaEWZ.mjs";export{r as AGG_COUNT,l as AGG_KEY,i as AGG_VALUE,n as DOC_COLUMN,m as DOC_ORIGINALS_KEY,q as aggUpsertSql,c as createIndexSql,d as decodeDocJson,f as encodeDocJson,p as geoTableName,u as isFtsAvailable,A as jsonPath,D as jsonPathSql,G as qualifiedJsonPath,S as qualifiedJsonPathSql,b as quoteIdentifier,_ as rowToDocument,x as serializeSqlValue,h as tableColumns,C as tryRowToDocument};
@@ -0,0 +1,15 @@
1
+ import{LunoraError as L}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{quoteIdentifier as C}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as p,runDrizzle as s}from"./runDrizzle-2ULFQR_k.mjs";import{k as u,l as m}from"./do-sql-FNOnpyHm.mjs";import{ConflictError as A}from"./ConflictError-C8GtJmjS.mjs";const n="__cdc_log",q=`INSERT INTO ${C(n)} (ts, ${C("table")}, id, op, doc) VALUES (?, ?, ?, ?, ?)`,I="__cdc_log_table_seq",y=e=>{s(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(n)} (
2
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
3
+ ts REAL NOT NULL,
4
+ ${t.identifier("table")} TEXT NOT NULL,
5
+ id TEXT NOT NULL,
6
+ op TEXT NOT NULL,
7
+ doc TEXT
8
+ )`);try{s(e,t`CREATE INDEX IF NOT EXISTS ${t.identifier(I)} ON ${t.identifier(n)} (${t.identifier("table")}, seq)`)}catch{}},F=(e,o,r,i,c,a)=>{const d=a===void 0?null:u(a);p(e,q,o,r,i,c,d)},f=90,N=e=>t` AND ${t.identifier("table")} IN (${t.join([...e].map(o=>t`${o}`),t`, `)})`,U=(e,o={})=>{const r=o.sinceSeq??0,i=Math.max(1,Math.min(o.limit??1e3,1e4)),a=s(e,t`SELECT seq, ts, ${t.identifier("table")}, id, op, doc FROM ${t.identifier(n)} WHERE seq > ${r} ORDER BY seq ASC LIMIT ${i}`).toArray().map(d=>{const l={id:d.id,op:d.op,seq:d.seq,table:d.table,ts:d.ts};return d.doc===null?l:{...l,doc:m(d.doc)}});return{changes:a,cursor:a.at(-1)?.seq??r}},g=(e,o,r)=>{if(r.size===0)return!1;const i=[...r];for(let c=0;c<i.length;c+=f){const a=new Set(i.slice(c,c+f));if(s(e,t`SELECT 1 AS hit FROM ${t.identifier(n)} WHERE seq > ${o}${N(a)} LIMIT 1`).toArray().length>0)return!0}return!1},T=new WeakMap,S=e=>new Set(s(e,t`SELECT name FROM sqlite_master WHERE type = 'table'`).toArray().map(o=>o.name)),X=(e,o)=>{if(o.size===0)return!1;let r=T.get(e),i=!1;r===void 0&&(r=S(e),i=!0,T.set(e,r));for(const c of o)if(!r.has(c)&&(i||(r=S(e),i=!0,T.set(e,r),!r.has(c))))return!1;return!0},B=(e,o,r,i)=>s(e,t`SELECT id, op, MAX(seq) AS maxSeq, COUNT(*) AS ops FROM ${t.identifier(n)}
9
+ WHERE ${t.identifier("table")} = ${o} AND seq > ${r} AND seq <= ${i}
10
+ GROUP BY id
11
+ ORDER BY maxSeq ASC`).toArray().map(a=>{const d=a.op;return{id:a.id,op:d==="insert"&&a.ops>1?"update":d,seq:a.maxSeq}}),H=(e,o,r)=>{s(e,t`DELETE FROM ${t.identifier(n)} WHERE seq IN (
12
+ SELECT seq FROM ${t.identifier(n)} WHERE seq <= ${o} ORDER BY seq ASC LIMIT ${r}
13
+ )`)},x=(e,o,r)=>{s(e,t`UPDATE ${t.identifier(n)} SET doc = NULL WHERE seq IN (
14
+ SELECT seq FROM ${t.identifier(n)} WHERE seq <= ${o} AND doc IS NOT NULL ORDER BY seq ASC LIMIT ${r}
15
+ )`)},W=(e,o)=>{if(o<=0)return s(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(n)}`).toArray()[0]?.seq??void 0;const i=s(e,t`SELECT seq FROM ${t.identifier(n)} ORDER BY seq DESC LIMIT 1 OFFSET ${o-1}`).toArray()[0]?.seq;return i===void 0?void 0:i-1},v=e=>{const r=s(e,t`SELECT seq FROM sqlite_sequence WHERE name = ${n}`).toArray()[0]?.seq;return typeof r=="number"?r:s(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(n)}`).toArray()[0]?.seq??0},Y=(e,o)=>e!==void 0&&e>o+1,P=(e,o,r)=>new L("CDC_LOG_TRIMMED",`${r==="global"?"global cdc":"cdc"} entries at or below seq ${String(e-1)} have been trimmed; resume from a snapshot (sinceSeq ${String(o)} is below the retained window)`,{status:409}),O=e=>s(e,t`SELECT MIN(seq) AS seq FROM ${t.identifier(n)}`).toArray()[0]?.seq??void 0,G=e=>{const r=s(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(n)} WHERE op <> 'delete' AND doc IS NULL`).toArray()[0]?.seq??void 0,i=O(e);return r===void 0?i:Math.max(r+1,i??0)},E="__cdc_meta",R=e=>{s(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(E)} (id INTEGER PRIMARY KEY CHECK (id = 1), epoch TEXT NOT NULL)`)},K=e=>{R(e);const r=s(e,t`SELECT epoch FROM ${t.identifier(E)} WHERE id = 1`).toArray()[0]?.epoch;if(typeof r=="string"&&r.length>0)return r;const i=crypto.randomUUID();return s(e,t`INSERT INTO ${t.identifier(E)} (id, epoch) VALUES (1, ${i})`),i},V=e=>{R(e);const o=crypto.randomUUID();return s(e,t`INSERT INTO ${t.identifier(E)} (id, epoch) VALUES (1, ${o}) ON CONFLICT(id) DO UPDATE SET epoch = excluded.epoch`),o},$=async(e,o)=>{if(o.op==="delete"){await e.delete(o.id,o.table);return}const r=o.doc??{};try{await e.insert(o.table,r,{allowExplicitId:!0})}catch(i){if(!(i instanceof A))throw i;const c={...r};delete c._id,await e.replace(o.id,c,o.table,{allowExplicitId:!0})}},z=async(e,o)=>{for(const r of o)await $(e,r)};export{q as CDC_APPEND_SQL,n as CDC_LOG_TABLE,I as CDC_LOG_TABLE_SEQ_INDEX,E as CDC_META_TABLE,F as appendCdcChange,z as applyCdcChanges,V as bumpCdcEpoch,X as cdcCanVouchFor,W as cdcSeqLeavingRows,g as cdcTouchesTables,P as cdcTrimmedError,x as compactCdcDocs,Y as cursorBelowRetainedFloor,y as migrateCdcLog,R as migrateCdcMeta,G as minCdcReplayableSeq,O as minCdcSeq,B as readCdcChangeKeys,U as readCdcChanges,v as readCdcCursor,K as readCdcEpoch,H as trimCdcChanges};
@@ -1 +1 @@
1
- import{LunoraError as _}from"@lunora/errors";import{d as N,e as E}from"./wire-codec-CKV-4MEN.mjs";const p="id",b=e=>e.at(-1)?.direction==="desc"?"desc":"asc",h=new Set(["_id","id"]),y=new Set(["_creationTime","_id","id"]),g=(e,t)=>{if(y.has(e))return!1;const n=t?.[e];return n===void 0?!0:n.kind==="optional"||n._meta?.column?.notNull===!1},A=(e,t)=>{const n=[];for(const r of e??[])for(const[o,i]of Object.entries(r))n.push({direction:i,field:o,nullable:g(o,t)});return n.length===0?[{direction:"asc",field:"_creationTime",nullable:!1}]:(n.some(r=>h.has(r.field)||r.field==="_creationTime")||n.push({direction:b(n),field:"_creationTime",nullable:!1}),n)},F=/[\u0080-\u{10FFFF}]/u,O=e=>{if(!F.test(e))return btoa(e);const t=new TextEncoder().encode(e);let n="";for(const r of t)n+=String.fromCodePoint(r);return btoa(n)},T=e=>{const t=atob(e),n=Uint8Array.from(t,r=>r.codePointAt(0)??0);return new TextDecoder().decode(n)},u="~3",C=(e,t)=>{const n=t.map(r=>e[r.field]??null);return n.push(e._id),u+O(JSON.stringify(E(n)))},d=()=>new _("BAD_REQUEST","invalid cursor"),I=e=>{if(!e.startsWith(u))throw d();let t;try{t=N(JSON.parse(T(e.slice(u.length))))}catch{throw d()}if(!Array.isArray(t))throw d();return t.map(n=>n??null)},m=(e,t,n,r)=>{const{field:o}=e,i=e.direction!=="desc"===n;if(t===null)return i?r?{OR:[{[o]:{isNull:!1}},{[o]:{isNull:!0}}]}:{[o]:{isNull:!1}}:r?{[o]:{isNull:!0}}:{OR:[]};let s=i?"gt":"lt";r&&(s=i?"gte":"lte");const c={[o]:{[s]:t}};return i||!e.nullable?c:{OR:[c,{[o]:{isNull:!0}}]}},S=(e,t,n,r)=>{const o=e.some(l=>h.has(l.field))?e:[...e,{direction:b(e),field:p,nullable:!1}];if(t.length<o.length)throw d();const i=l=>{const a=o[l];if(a===void 0)throw d();const f=m(a,t[l],n,r&&l===o.length-1);return l===o.length-1?f:{OR:[f,{AND:[{[a.field]:{eq:t[l]}},i(l+1)]}]}},s=i(0),[c]=o;return o.length<2||c===void 0||c.nullable||t[0]===null?s:{AND:[m(c,t[0],n,!0),s]}},L=(e,t)=>S(e,t,!0,!1),k=(e,t)=>S(e,t,!1,!0),D=["_id","_creationTime"],W=(e,t,n)=>{if(!t)return e;const r=new Set([...t,...D,...n?Object.keys(n):[]]);return e.map(o=>{const i={};for(const s of r)s in o&&(i[s]=o[s]);return i})},B=(e,t)=>e&&t!==!0?{[e.field]:{isNull:!0}}:void 0,v=(e,t)=>t===void 0||e[t]===null||e[t]===void 0;export{u as CURSOR_PREFIX,W as applySelect,k as buildSeekBeforeWhere,L as buildSeekWhere,I as decodeCursor,C as encodeCursor,T as fromBase64,d as invalidCursor,v as isLiveForCompanion,A as normalizeOrderKeys,B as softDeleteScope,b as tiebreakDirectionFor,O as toBase64};
1
+ import{LunoraError as _}from"@lunora/errors";import{d as N,e as E}from"./wire-codec-C-FpWm52.mjs";const p="id",b=e=>e.at(-1)?.direction==="desc"?"desc":"asc",h=new Set(["_id","id"]),y=new Set(["_creationTime","_id","id"]),g=(e,t)=>{if(y.has(e))return!1;const n=t?.[e];return n===void 0?!0:n.kind==="optional"||n._meta?.column?.notNull===!1},A=(e,t)=>{const n=[];for(const r of e??[])for(const[o,i]of Object.entries(r))n.push({direction:i,field:o,nullable:g(o,t)});return n.length===0?[{direction:"asc",field:"_creationTime",nullable:!1}]:(n.some(r=>h.has(r.field)||r.field==="_creationTime")||n.push({direction:b(n),field:"_creationTime",nullable:!1}),n)},F=/[\u0080-\u{10FFFF}]/u,O=e=>{if(!F.test(e))return btoa(e);const t=new TextEncoder().encode(e);let n="";for(const r of t)n+=String.fromCodePoint(r);return btoa(n)},T=e=>{const t=atob(e),n=Uint8Array.from(t,r=>r.codePointAt(0)??0);return new TextDecoder().decode(n)},u="~3",C=(e,t)=>{const n=t.map(r=>e[r.field]??null);return n.push(e._id),u+O(JSON.stringify(E(n)))},d=()=>new _("BAD_REQUEST","invalid cursor"),I=e=>{if(!e.startsWith(u))throw d();let t;try{t=N(JSON.parse(T(e.slice(u.length))))}catch{throw d()}if(!Array.isArray(t))throw d();return t.map(n=>n??null)},m=(e,t,n,r)=>{const{field:o}=e,i=e.direction!=="desc"===n;if(t===null)return i?r?{OR:[{[o]:{isNull:!1}},{[o]:{isNull:!0}}]}:{[o]:{isNull:!1}}:r?{[o]:{isNull:!0}}:{OR:[]};let s=i?"gt":"lt";r&&(s=i?"gte":"lte");const c={[o]:{[s]:t}};return i||!e.nullable?c:{OR:[c,{[o]:{isNull:!0}}]}},S=(e,t,n,r)=>{const o=e.some(l=>h.has(l.field))?e:[...e,{direction:b(e),field:p,nullable:!1}];if(t.length<o.length)throw d();const i=l=>{const a=o[l];if(a===void 0)throw d();const f=m(a,t[l],n,r&&l===o.length-1);return l===o.length-1?f:{OR:[f,{AND:[{[a.field]:{eq:t[l]}},i(l+1)]}]}},s=i(0),[c]=o;return o.length<2||c===void 0||c.nullable||t[0]===null?s:{AND:[m(c,t[0],n,!0),s]}},L=(e,t)=>S(e,t,!0,!1),k=(e,t)=>S(e,t,!1,!0),D=["_id","_creationTime"],W=(e,t,n)=>{if(!t)return e;const r=new Set([...t,...D,...n?Object.keys(n):[]]);return e.map(o=>{const i={};for(const s of r)s in o&&(i[s]=o[s]);return i})},B=(e,t)=>e&&t!==!0?{[e.field]:{isNull:!0}}:void 0,v=(e,t)=>t===void 0||e[t]===null||e[t]===void 0;export{u as CURSOR_PREFIX,W as applySelect,k as buildSeekBeforeWhere,L as buildSeekWhere,I as decodeCursor,C as encodeCursor,T as fromBase64,d as invalidCursor,v as isLiveForCompanion,A as normalizeOrderKeys,B as softDeleteScope,b as tiebreakDirectionFor,O as toBase64};
@@ -1,4 +1,4 @@
1
- import{LunoraError as D}from"@lunora/errors";import{stableWireKey as N}from"./stableWireKey-DQZmSvS2.mjs";import{runSql as u}from"./runDrizzle-2ULFQR_k.mjs";import{encodeCursor as M,CURSOR_PREFIX as x}from"./CURSOR_PREFIX-D8c7Ccj3.mjs";import{ConflictError as U}from"./ConflictError-C8GtJmjS.mjs";const c="__lunora_migrations",$=100,y=3e4,w=1e4,F=e=>{u(e,`CREATE TABLE IF NOT EXISTS "${c}" (
1
+ import{LunoraError as D}from"@lunora/errors";import{stableWireKey as N}from"./stableWireKey-D2US4k_J.mjs";import{runSql as u}from"./runDrizzle-2ULFQR_k.mjs";import{encodeCursor as M,CURSOR_PREFIX as x}from"./CURSOR_PREFIX-qn6nNVS7.mjs";import{ConflictError as U}from"./ConflictError-C8GtJmjS.mjs";const c="__lunora_migrations",$=100,y=3e4,w=1e4,F=e=>{u(e,`CREATE TABLE IF NOT EXISTS "${c}" (
2
2
  id TEXT PRIMARY KEY,
3
3
  direction TEXT NOT NULL,
4
4
  status TEXT NOT NULL,
@@ -1 +1 @@
1
- import{LunoraError as u}from"@lunora/errors";import{isMemoryTable as p}from"./clearMemoryTables-BGbmag2i.mjs";import{distinctValues as v}from"./applyOnDelete-CmYAshr-.mjs";import{RELATION_EXISTS_KEY as j}from"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";const S=["every","is","isNot","none","some"],O=new Set(S),$=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(r=>O.has(r))},E={every:{kind:"many",negateChild:!0,negated:!0},is:{kind:"one",negated:!1},isNot:{kind:"one",negated:!0,nullDisjunct:!0},none:{kind:"many",negated:!0},some:{kind:"many",negated:!1}},R=e=>O.has(e)?e:void 0,w=e=>{const t=R(e),r=t===void 0?void 0:E[t];if(!r)throw new u("INTERNAL",`unknown relation operator "${e}"`);return r},_=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},L=5e3,h=Symbol("relation-key-overflow"),m=e=>Array.isArray(e)?e.map(t=>t??{}):[],A=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},y=e=>$(e),l=(e,t,r)=>{const n=t.tables[r]?.relationMap??{};return Object.keys(e).some(s=>{const o=e[s];return s==="AND"||s==="OR"?m(o).some(a=>l(a,t,r)):s==="NOT"?l(o??{},t,r):!!n[s]&&y(o)})},Y=(e,t,r,n)=>{if(e&&l(e,t,r))throw new u("INTERNAL",`relation-crossing predicates are not supported in ${n}() — use them in findMany/findFirst or an RLS read policy`)},M=async(e,t,r,n,s)=>{const o=await d(t,e.table,n),{page:a}=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),relationBaseWhere:n.relationBaseWhere,where:o}),i=v(a,r);if(i.length>n.maxRelationKeys){if(s)return h;throw new u("INTERNAL",`relation predicate on "${e.table}" matched ${String(i.length)} rows, exceeding the ${String(n.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)}return i},P=async(e,t,r,n,s)=>{const o=w(e),{clause:a,project:i}=_(t),c=await M(t,o.negateChild?{NOT:r}:r,i,n,s);return c===h?h:o.negated?o.nullDisjunct?{OR:[{[a]:{notIn:c}},{[a]:{isNull:!0}}]}:{[a]:{notIn:c}}:{[a]:{in:c}}},b=async(e,t,r,n,s)=>{const o=w(e),a=s.relationBaseWhere?.(t.table),i=o.negateChild?{NOT:r}:r,N={childWhere:await d(a?{AND:[a,i]}:i,t.table,s),negated:o.negated,parentTable:n,relation:t};return{[j]:N}},k=(e,t,r)=>{const n=R(e),s=n===void 0?void 0:E[n];if(s&&s.kind!==r.kind)throw new u("INTERNAL",`relation operator "${e}" requires a to-${s.kind} relation, but "${t}" is to-${r.kind}`)},I=async(e,t,r,n,s)=>{const o=[];for(const a of Object.keys(r)){k(a,e,t);const i=r[a]??{},c=s.canPushExists?.(t)??!1;if(c&&s.existsPushMode==="always"){o.push(await b(a,t,i,n,s));continue}const f=await P(a,t,i,s,c);f===h?o.push(await b(a,t,i,n,s)):o.push(f)}return A(o)},D=async(e,t,r,n)=>{if(e==="AND"||e==="OR"){const o=[];for(const a of m(t))o.push(await d(a,r,n));return{[e]:o}}if(e==="NOT")return{NOT:await d(t??{},r,n)};const s=n.schema.tables[r]?.relationMap?.[e];return s&&y(t)?I(e,s,t,r,n):{[e]:t}},d=async(e,t,r)=>{const n=[];for(const s of Object.keys(e))n.push(await D(s,e[s],t,r));return A(n)},H=async(e,t)=>!e||!l(e,t.schema,t.tableName)?e:d(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??L,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),g=(e,t,r)=>{for(const n of e){const s=T(n,t,r);if(s)return s}},K=(e,t,r,n)=>{if(e==="AND"||e==="OR")return g(m(t),r,n);if(e==="NOT")return g([t??{}],r,n);const s=r.tables[n]?.relationMap?.[e];if(!(!s||!y(t)))return r.tables[s.table]?.shardMode?.kind==="shardBy"?{kind:"shard",relation:e,target:s.table}:p(r.tables[s.table])?{kind:"memory",relation:e,target:s.table}:g(Object.values(t),r,s.table)},T=(e,t,r)=>{for(const n of Object.keys(e)){const s=K(n,e[n],t,r);if(s)return s}},q=(e,t,r)=>{if(p(t.tables[r]))throw Object.assign(new Error(`shape on "${r}" replicates from the changelog, which never records a .memory() table — the shape would seed once and never update again. Fix it by (a) dropping .memory() from "${r}" so its writes reach the changelog, or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400});if(!e)return;const n=T(e,t,r);if(n)throw n.kind==="memory"?Object.assign(new Error(`shape on "${r}" joins the .memory() table "${n.target}" via relation "${n.relation}" — writes to a .memory() table never reach the changelog, so the shape is never told its membership changed and would serve stale rows indefinitely. Fix it by (a) dropping .memory() from "${n.target}", or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400}):Object.assign(new Error(`shape on "${r}" joins the sharded table "${n.target}" via relation "${n.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${r}", or (b) moving "${n.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{L as DEFAULT_MAX_RELATION_KEYS,Y as assertFlatPredicate,q as assertShapeShardable,l as containsRelationPredicate,y as isRelationPredicate,H as resolveRelationPredicates};
1
+ import{LunoraError as u}from"@lunora/errors";import{isMemoryTable as p}from"./clearMemoryTables-BGbmag2i.mjs";import{distinctValues as v}from"./applyOnDelete-tDhKaeB6.mjs";import{RELATION_EXISTS_KEY as j}from"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";const S=["every","is","isNot","none","some"],O=new Set(S),$=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(r=>O.has(r))},E={every:{kind:"many",negateChild:!0,negated:!0},is:{kind:"one",negated:!1},isNot:{kind:"one",negated:!0,nullDisjunct:!0},none:{kind:"many",negated:!0},some:{kind:"many",negated:!1}},R=e=>O.has(e)?e:void 0,w=e=>{const t=R(e),r=t===void 0?void 0:E[t];if(!r)throw new u("INTERNAL",`unknown relation operator "${e}"`);return r},_=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},L=5e3,h=Symbol("relation-key-overflow"),m=e=>Array.isArray(e)?e.map(t=>t??{}):[],A=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},y=e=>$(e),l=(e,t,r)=>{const n=t.tables[r]?.relationMap??{};return Object.keys(e).some(s=>{const o=e[s];return s==="AND"||s==="OR"?m(o).some(a=>l(a,t,r)):s==="NOT"?l(o??{},t,r):!!n[s]&&y(o)})},Y=(e,t,r,n)=>{if(e&&l(e,t,r))throw new u("INTERNAL",`relation-crossing predicates are not supported in ${n}() — use them in findMany/findFirst or an RLS read policy`)},M=async(e,t,r,n,s)=>{const o=await d(t,e.table,n),{page:a}=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),relationBaseWhere:n.relationBaseWhere,where:o}),i=v(a,r);if(i.length>n.maxRelationKeys){if(s)return h;throw new u("INTERNAL",`relation predicate on "${e.table}" matched ${String(i.length)} rows, exceeding the ${String(n.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)}return i},P=async(e,t,r,n,s)=>{const o=w(e),{clause:a,project:i}=_(t),c=await M(t,o.negateChild?{NOT:r}:r,i,n,s);return c===h?h:o.negated?o.nullDisjunct?{OR:[{[a]:{notIn:c}},{[a]:{isNull:!0}}]}:{[a]:{notIn:c}}:{[a]:{in:c}}},b=async(e,t,r,n,s)=>{const o=w(e),a=s.relationBaseWhere?.(t.table),i=o.negateChild?{NOT:r}:r,N={childWhere:await d(a?{AND:[a,i]}:i,t.table,s),negated:o.negated,parentTable:n,relation:t};return{[j]:N}},k=(e,t,r)=>{const n=R(e),s=n===void 0?void 0:E[n];if(s&&s.kind!==r.kind)throw new u("INTERNAL",`relation operator "${e}" requires a to-${s.kind} relation, but "${t}" is to-${r.kind}`)},I=async(e,t,r,n,s)=>{const o=[];for(const a of Object.keys(r)){k(a,e,t);const i=r[a]??{},c=s.canPushExists?.(t)??!1;if(c&&s.existsPushMode==="always"){o.push(await b(a,t,i,n,s));continue}const f=await P(a,t,i,s,c);f===h?o.push(await b(a,t,i,n,s)):o.push(f)}return A(o)},D=async(e,t,r,n)=>{if(e==="AND"||e==="OR"){const o=[];for(const a of m(t))o.push(await d(a,r,n));return{[e]:o}}if(e==="NOT")return{NOT:await d(t??{},r,n)};const s=n.schema.tables[r]?.relationMap?.[e];return s&&y(t)?I(e,s,t,r,n):{[e]:t}},d=async(e,t,r)=>{const n=[];for(const s of Object.keys(e))n.push(await D(s,e[s],t,r));return A(n)},H=async(e,t)=>!e||!l(e,t.schema,t.tableName)?e:d(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??L,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),g=(e,t,r)=>{for(const n of e){const s=T(n,t,r);if(s)return s}},K=(e,t,r,n)=>{if(e==="AND"||e==="OR")return g(m(t),r,n);if(e==="NOT")return g([t??{}],r,n);const s=r.tables[n]?.relationMap?.[e];if(!(!s||!y(t)))return r.tables[s.table]?.shardMode?.kind==="shardBy"?{kind:"shard",relation:e,target:s.table}:p(r.tables[s.table])?{kind:"memory",relation:e,target:s.table}:g(Object.values(t),r,s.table)},T=(e,t,r)=>{for(const n of Object.keys(e)){const s=K(n,e[n],t,r);if(s)return s}},q=(e,t,r)=>{if(p(t.tables[r]))throw Object.assign(new Error(`shape on "${r}" replicates from the changelog, which never records a .memory() table — the shape would seed once and never update again. Fix it by (a) dropping .memory() from "${r}" so its writes reach the changelog, or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400});if(!e)return;const n=T(e,t,r);if(n)throw n.kind==="memory"?Object.assign(new Error(`shape on "${r}" joins the .memory() table "${n.target}" via relation "${n.relation}" — writes to a .memory() table never reach the changelog, so the shape is never told its membership changed and would serve stale rows indefinitely. Fix it by (a) dropping .memory() from "${n.target}", or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400}):Object.assign(new Error(`shape on "${r}" joins the sharded table "${n.target}" via relation "${n.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${r}", or (b) moving "${n.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{L as DEFAULT_MAX_RELATION_KEYS,Y as assertFlatPredicate,q as assertShapeShardable,l as containsRelationPredicate,y as isRelationPredicate,H as resolveRelationPredicates};
@@ -1,4 +1,4 @@
1
- import{toErrorBody as k,LunoraError as D}from"@lunora/errors";import{e as N,d as v}from"./wire-codec-CKV-4MEN.mjs";import{sql as y}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-2ULFQR_k.mjs";import{WORKERD_SQLITE_LIMITS as F}from"./param-DlozcSQu.mjs";import{d as U,w,a as A,m as K,r as Y,b as $,c as W}from"./ctx-db-relay-shapes-Y0jy6_Qb.mjs";import{envPositiveInt as g}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{relayName as R,DEFAULT_PROMOTION_THRESHOLDS as T,nextPromotionState as B,shapeRoutingKey as E,relayProxyKey as M,parseRelayName as H,clampPromotionThresholds as q}from"./DEFAULT_PROMOTION_THRESHOLDS-CIJjsrCU.mjs";import{encodeRowsPatch as X,buildPokeFrames as O}from"./buildPokeFrames-CkVxoDaR.mjs";import{v as j,R as L,s as z,a as G,b as V}from"./sibling-channel-Cxvk0Zca.mjs";import{awaitWsDrain as J,trySendFrame as x}from"./awaitWsDrain-C9bPJ23I.mjs";import{stableWireKey as b}from"./stableWireKey-DQZmSvS2.mjs";const f="__lunora_relay_memos",Q=i=>{m(i,y`CREATE TABLE IF NOT EXISTS ${y.identifier(f)} (
1
+ import{toErrorBody as k,LunoraError as D}from"@lunora/errors";import{e as N,d as v}from"./wire-codec-C-FpWm52.mjs";import{sql as y}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-2ULFQR_k.mjs";import{WORKERD_SQLITE_LIMITS as F}from"./param-DlozcSQu.mjs";import{d as U,w,a as A,m as K,r as Y,b as $,c as W}from"./ctx-db-relay-shapes-Bg5YYnmN.mjs";import{envPositiveInt as g}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{relayName as R,DEFAULT_PROMOTION_THRESHOLDS as T,nextPromotionState as B,shapeRoutingKey as E,relayProxyKey as M,parseRelayName as H,clampPromotionThresholds as q}from"./DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";import{encodeRowsPatch as X,buildPokeFrames as O}from"./buildPokeFrames-BBE6J91z.mjs";import{v as j,R as L,s as z,a as G,b as V}from"./sibling-channel-Cxvk0Zca.mjs";import{awaitWsDrain as J,trySendFrame as x}from"./awaitWsDrain-apizgmKY.mjs";import{stableWireKey as b}from"./stableWireKey-D2US4k_J.mjs";const f="__lunora_relay_memos",Q=i=>{m(i,y`CREATE TABLE IF NOT EXISTS ${y.identifier(f)} (
2
2
  connection_id TEXT NOT NULL,
3
3
  sub_id TEXT NOT NULL,
4
4
  cursor INTEGER NOT NULL,
@@ -1 +1 @@
1
- import{LunoraError as m}from"@lunora/errors";import{stableWireKey as a}from"./stableWireKey-DQZmSvS2.mjs";const i="::relay::",w=(t,n)=>`${t}${i}${String(n)}`,f=t=>{const n=t.lastIndexOf(i);if(n===-1)return;const o=t.slice(0,n),e=t.slice(n+i.length),r=Number(e);if(!(o.length===0||!Number.isInteger(r)||r<0||String(r)!==e))return{ownerKey:o,relayIndex:r}},l=(t,n)=>a({args:n??{},name:t}),d=(t,n,o)=>`${String(t)}:${n}:${o}`,c={tDown:4e3,tUp:8e3},g=(t,n,o=c)=>{if(o.tDown>=o.tUp)throw new m("INTERNAL",`invalid promotion thresholds: tDown (${String(o.tDown)}) must be < tUp (${String(o.tUp)})`);return t==="owned"?n>=o.tUp?"promoted":"owned":n<o.tDown?"owned":"promoted"},x=(t,n)=>n<t?{tDown:n,tUp:t}:{tDown:Math.min(Math.max(1,Math.floor(t/2)),t-1),tUp:t},N=(t,n,o)=>{if(t<=n||n<=0)return 0;const e=t-n,r=Math.ceil(e/n);return Math.min(r,Math.max(0,o))};export{c as DEFAULT_PROMOTION_THRESHOLDS,i as RELAY_NAME_INFIX,x as clampPromotionThresholds,g as nextPromotionState,f as parseRelayName,N as relayCountFor,w as relayName,d as relayProxyKey,l as shapeRoutingKey};
1
+ import{LunoraError as m}from"@lunora/errors";import{stableWireKey as a}from"./stableWireKey-D2US4k_J.mjs";const i="::relay::",w=(t,n)=>`${t}${i}${String(n)}`,f=t=>{const n=t.lastIndexOf(i);if(n===-1)return;const o=t.slice(0,n),e=t.slice(n+i.length),r=Number(e);if(!(o.length===0||!Number.isInteger(r)||r<0||String(r)!==e))return{ownerKey:o,relayIndex:r}},l=(t,n)=>a({args:n??{},name:t}),d=(t,n,o)=>`${String(t)}:${n}:${o}`,c={tDown:4e3,tUp:8e3},g=(t,n,o=c)=>{if(o.tDown>=o.tUp)throw new m("INTERNAL",`invalid promotion thresholds: tDown (${String(o.tDown)}) must be < tUp (${String(o.tUp)})`);return t==="owned"?n>=o.tUp?"promoted":"owned":n<o.tDown?"owned":"promoted"},x=(t,n)=>n<t?{tDown:n,tUp:t}:{tDown:Math.min(Math.max(1,Math.floor(t/2)),t-1),tUp:t},N=(t,n,o)=>{if(t<=n||n<=0)return 0;const e=t-n,r=Math.ceil(e/n);return Math.min(r,Math.max(0,o))};export{c as DEFAULT_PROMOTION_THRESHOLDS,i as RELAY_NAME_INFIX,x as clampPromotionThresholds,g as nextPromotionState,f as parseRelayName,N as relayCountFor,w as relayName,d as relayProxyKey,l as shapeRoutingKey};
@@ -1 +1 @@
1
- import{toErrorBody as R,LunoraError as k}from"@lunora/errors";import{e as A}from"./wire-codec-CKV-4MEN.mjs";import{readStreamRun as T,deleteStreamRun as w,claimStreamRun as _,appendStreamChunk as y,finishStreamRun as E,trimStreamRuns as b,readStreamChunks as v}from"./appendStreamChunk-C1Ok4b6J.mjs";const p=5e4,S=64*1024*1024,M=864e5,N=36e5,L=(i,e)=>{const r=i?.startedAt??e.live?.generation;return e.resuming&&e.generation!==void 0&&r!==void 0&&e.generation!==r?"interrupted":e.live!==void 0?"attach":i===void 0?e.resuming?"interrupted":"attach":i.status==="complete"||i.status==="error"?e.resuming?"replay-terminal":"reclaim":e.resuming?"interrupted":"reclaim"},O=(i,e,r)=>{(i||r())&&e.fail({code:"STREAM_INTERRUPTED",message:i?"the run this durable stream resumed from no longer exists; start a new run":"the producer for this durable stream did not survive; start a new run"})};class I{lastTrimAt=0;runs=new Map;sql;waitUntil;constructor(e){this.sql=e.sql,this.waitUntil=e.waitUntil}async attach(e){try{await this.attachOrThrow(e)}catch(r){const{body:t,redacted:o}=R(r,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});o&&console.error("[@lunora/shard-engine] durable stream attach failed:",r),e.sink.fail({code:t.code,message:t.message})}finally{this.trim(this.sql())}}detach(e,r){this.runs.get(e)?.sinks.delete(r)}isLive(e){return this.runs.has(e)}async attachOrThrow(e){const r=this.sql(),{runKey:t,sinceChunk:o,sink:c}=e,s=T(r,t),u=o>0,n=this.runs.get(t),a=s?.startedAt??n?.generation,l=L(s,{generation:e.generation,live:n,resuming:u}),d=()=>{for(const g of v(r,t,o))if(!c.chunk({data:JSON.parse(g.dataJson),generation:a,seq:g.seq}))return!1;return!0};if(l==="replay-terminal"){d()&&(s?.status==="error"?c.fail({code:s.errorCode??"INTERNAL_SERVER_ERROR",message:s.error??"stream failed"}):c.complete());return}if(l==="interrupted"){O(e.generation!==void 0&&a!==void 0&&e.generation!==a,c,d);return}if(n){d()&&n.sinks.add(c);return}l==="reclaim"&&w(r,t);const m=Math.max(Date.now(),s===void 0?0:s.startedAt+1);_(r,t,m,e.ttlMs??M);const h={generation:m,sinks:new Set([c])};this.runs.set(t,h);const f=this.produce(t,e.iterator,h);this.waitUntil?.(f),await f}async produce(e,r,t){const o=this.sql(),c=new AbortController;let s=0,u=0;try{for await(const n of r(c.signal)){const a=A(n),l=JSON.stringify(a);if(s+=1,u+=l.length,s>p||u>S)throw new k("STREAM_TOO_LONG",`durable stream exceeded its ceiling (${String(p)} chunks / ${String(S)} bytes); yield less, or drop \`durable\``,{status:507});y(o,e,s,l);for(const d of t.sinks)d.chunk({data:a,generation:t.generation,seq:s})||t.sinks.delete(d)}E(o,e,"complete",s);for(const n of t.sinks)n.complete()}catch(n){const{body:a,redacted:l}=R(n,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});l&&console.error("[@lunora/shard-engine] unhandled durable stream error:",n),E(o,e,"error",s,{code:a.code,message:a.message});for(const d of t.sinks)d.fail({code:a.code,message:a.message})}finally{this.runs.delete(e)}}trim(e){const r=Date.now();if(!(r-this.lastTrimAt<=N)){this.lastTrimAt=r;try{b(e,r)}catch{}}}}export{I as DurableStreamRunner,S as MAX_DURABLE_STREAM_BYTES,p as MAX_DURABLE_STREAM_CHUNKS,L as decideDurableAttach};
1
+ import{toErrorBody as R,LunoraError as k}from"@lunora/errors";import{e as A}from"./wire-codec-C-FpWm52.mjs";import{readStreamRun as T,deleteStreamRun as w,claimStreamRun as _,appendStreamChunk as y,finishStreamRun as E,trimStreamRuns as b,readStreamChunks as v}from"./appendStreamChunk-C1Ok4b6J.mjs";const p=5e4,S=64*1024*1024,M=864e5,N=36e5,L=(i,e)=>{const r=i?.startedAt??e.live?.generation;return e.resuming&&e.generation!==void 0&&r!==void 0&&e.generation!==r?"interrupted":e.live!==void 0?"attach":i===void 0?e.resuming?"interrupted":"attach":i.status==="complete"||i.status==="error"?e.resuming?"replay-terminal":"reclaim":e.resuming?"interrupted":"reclaim"},O=(i,e,r)=>{(i||r())&&e.fail({code:"STREAM_INTERRUPTED",message:i?"the run this durable stream resumed from no longer exists; start a new run":"the producer for this durable stream did not survive; start a new run"})};class I{lastTrimAt=0;runs=new Map;sql;waitUntil;constructor(e){this.sql=e.sql,this.waitUntil=e.waitUntil}async attach(e){try{await this.attachOrThrow(e)}catch(r){const{body:t,redacted:o}=R(r,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});o&&console.error("[@lunora/shard-engine] durable stream attach failed:",r),e.sink.fail({code:t.code,message:t.message})}finally{this.trim(this.sql())}}detach(e,r){this.runs.get(e)?.sinks.delete(r)}isLive(e){return this.runs.has(e)}async attachOrThrow(e){const r=this.sql(),{runKey:t,sinceChunk:o,sink:c}=e,s=T(r,t),u=o>0,n=this.runs.get(t),a=s?.startedAt??n?.generation,l=L(s,{generation:e.generation,live:n,resuming:u}),d=()=>{for(const g of v(r,t,o))if(!c.chunk({data:JSON.parse(g.dataJson),generation:a,seq:g.seq}))return!1;return!0};if(l==="replay-terminal"){d()&&(s?.status==="error"?c.fail({code:s.errorCode??"INTERNAL_SERVER_ERROR",message:s.error??"stream failed"}):c.complete());return}if(l==="interrupted"){O(e.generation!==void 0&&a!==void 0&&e.generation!==a,c,d);return}if(n){d()&&n.sinks.add(c);return}l==="reclaim"&&w(r,t);const m=Math.max(Date.now(),s===void 0?0:s.startedAt+1);_(r,t,m,e.ttlMs??M);const h={generation:m,sinks:new Set([c])};this.runs.set(t,h);const f=this.produce(t,e.iterator,h);this.waitUntil?.(f),await f}async produce(e,r,t){const o=this.sql(),c=new AbortController;let s=0,u=0;try{for await(const n of r(c.signal)){const a=A(n),l=JSON.stringify(a);if(s+=1,u+=l.length,s>p||u>S)throw new k("STREAM_TOO_LONG",`durable stream exceeded its ceiling (${String(p)} chunks / ${String(S)} bytes); yield less, or drop \`durable\``,{status:507});y(o,e,s,l);for(const d of t.sinks)d.chunk({data:a,generation:t.generation,seq:s})||t.sinks.delete(d)}E(o,e,"complete",s);for(const n of t.sinks)n.complete()}catch(n){const{body:a,redacted:l}=R(n,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});l&&console.error("[@lunora/shard-engine] unhandled durable stream error:",n),E(o,e,"error",s,{code:a.code,message:a.message});for(const d of t.sinks)d.fail({code:a.code,message:a.message})}finally{this.runs.delete(e)}}trim(e){const r=Date.now();if(!(r-this.lastTrimAt<=N)){this.lastTrimAt=r;try{b(e,r)}catch{}}}}export{I as DurableStreamRunner,S as MAX_DURABLE_STREAM_BYTES,p as MAX_DURABLE_STREAM_CHUNKS,L as decideDurableAttach};
@@ -0,0 +1,4 @@
1
+ import{LunoraError as h}from"@lunora/errors";const m="x",d=" ",E={'"':'"',"'":"'","[":"]","`":"`"},f=(n,t)=>{let e=t+2;for(;e<n.length&&n[e]!==`
2
+ `;)e+=1;return e},g=(n,t)=>{const e=n.indexOf("*/",t+2);return e===-1?-1:e+2},S=n=>{const t=n.split("");let e=0;for(;e<n.length;){const o=n[e]??"",c=E[o];if(o==="-"&&n[e+1]==="-"){const s=f(n,e);t.fill(d,e,s),e=s}else if(o==="/"&&n[e+1]==="*"){const s=g(n,e);if(s===-1)return;t.fill(d,e,s),e=s}else if(c!==void 0){let s=e+1;for(;s<n.length;)if(n[s]!==c)s+=1;else if(c!=="]"&&n[s+1]===c)s+=2;else break;if(s>=n.length)return;t.fill(m,e,s+1),e=s+1}else e+=1}for(let o=0;o<n.length;o+=1)n[o]===`
3
+ `&&(t[o]=`
4
+ `);return t.join("")},L=/^(?:explain\s+(?:query\s+plan\s+)?)?(?:select|with)\b/iu,A=/\b(?:alter|attach|create|delete|detach|drop|insert|pragma|reindex|truncate|update|vacuum)\b|\breplace\b(?!\s*\()/iu,p=/^\w+/u,N=/;\s*$/u,x=/\s/u,y=n=>{let t=0;for(;t<n.length;){const e=n[t];if(e!==void 0&&x.test(e))t+=1;else if(e==="-"&&n[t+1]==="-")t=f(n,t);else if(e==="/"&&n[t+1]==="*"){const o=g(n,t);if(o===-1)break;t=o}else break}return t},u=n=>{const t=y(n),e=n.slice(t).trimEnd();if(e==="")return{code:"SQL_EMPTY",message:"the query is empty"};const c=(S(e)??e).replace(N,""),s=e.slice(0,c.length),r=c.indexOf(";");if(r!==-1)return{code:"SQL_MULTIPLE_STATEMENTS",length:1,message:"only a single statement may be run",offset:t+r};const i="the SQL editor is read-only — only SELECT / WITH / EXPLAIN queries are allowed";if(!L.test(s))return{code:"SQL_NOT_READONLY",length:p.exec(s)?.[0].length??1,message:i,offset:t};const a=A.exec(s);if(a!==null)return{code:"SQL_NOT_READONLY",length:a[0].length,message:`${i} (\`${a[0].toUpperCase()}\` is not allowed)`,offset:t+a.index}},l=1e3,_=n=>{const t=u(n);if(t!==void 0)throw new h(t.code,t.message,{status:400})},C=(n,t)=>{_(t);const e=n.exec(t).toArray(),o=e.length>l?e.slice(0,l):e;return{columns:o.length>0?Object.keys(o[0]):[],rowCount:e.length,rows:o,truncated:e.length>l}},O=/near "([^"]*)": syntax error/iu,T=/^SCAN (?:TABLE )?(?!CONSTANT\b|SUBQUERY\b)([^\s(]+)/u,R=(n,t)=>{if(t==="")return{};const e=n.indexOf(t);return e===-1?{}:{length:t.length,offset:e}},v=(n,t)=>{const e=u(t);if(e!==void 0)return{diagnostics:e.code==="SQL_EMPTY"?[]:[{length:e.length,message:e.message,offset:e.offset,severity:"error",source:"gate"}],plan:[]};let o;try{o=n.exec(`EXPLAIN QUERY PLAN ${t}`).toArray().map(r=>{const{detail:i}=r;return typeof i=="string"?i:""}).filter(r=>r!=="")}catch(r){const i=r instanceof Error?r.message:String(r),a=O.exec(i);return{diagnostics:[{...a?R(t,a[1]??""):{},message:i,severity:"error",source:"syntax"}],plan:[]}}const c=[],s=new Set;for(const r of o){const i=T.exec(r);if(i){const a=i[1]??"";s.has(a)||(s.add(a),c.push({message:`full table scan on \`${a}\` — this query reads every row`,severity:"warning",source:"plan"}))}}return{diagnostics:c,plan:o}};export{l as MAX_SQL_ROWS,_ as assertReadonly,v as lintReadonlySql,C as runReadonlySql};
@@ -0,0 +1 @@
1
+ import{LunoraError as $}from"@lunora/errors";import{D as st}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{c as un,S as fn,l as De,a as hn}from"./ctx-db-companions-B4O4d95S.mjs";import{sql as i}from"drizzle-orm";import{d as wn}from"./wire-codec-C-FpWm52.mjs";import{throwingScheduler as pn,aggregateSqlFunction as Le,normalizeCountArgument as gn}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as Ve,encodeAggregateKey as ze,readAggregateValue as Je}from"./aggregateTableName-C7o-gpms.mjs";import{mergeWhere as z,CountRlsUnsupportedError as Ye,selectIndexForGroupBy as $n,selectIndexForCount as yn,selectIndexForAggregate as En}from"./CountRlsUnsupportedError-Bdfupt3g.mjs";import{backfillSearchIndexesForTable as mn,searchIndexCoversTable as Sn}from"./backfillAggregateIndexes-pQWaX2Yu.mjs";import{backfillAggregateIndexes as Rr,backfillRankIndexes as Tr,backfillSearchIndexes as Ar}from"./backfillAggregateIndexes-pQWaX2Yu.mjs";import{appendCdcChange as _n}from"./CDC_LOG_TABLE-CAyqu8cg.mjs";import{CDC_LOG_TABLE as Ir,applyCdcChanges as Cr,bumpCdcEpoch as xr,cdcCanVouchFor as br,cdcSeqLeavingRows as Mr,cdcTouchesTables as Dr,cdcTrimmedError as Lr,compactCdcDocs as kr,cursorBelowRetainedFloor as Fr,minCdcReplayableSeq as qr,minCdcSeq as Br,readCdcChangeKeys as Wr,readCdcChanges as Ur,readCdcCursor as Pr,readCdcEpoch as Gr,trimCdcChanges as Hr}from"./CDC_LOG_TABLE-CAyqu8cg.mjs";import{allocateCommitSeq as Rn,COMMIT_SEQ_FIELD as Tn}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{isMemoryTable as _t}from"./clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as Rt}from"./computeRankPage-DEkYJ9Tz.mjs";import{SCAN_DEP as H}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as N,runSql as Se}from"./runDrizzle-2ULFQR_k.mjs";import{D as oe,k as ce,r as le,b as ke,A as Xe,a as Fe,e as X,t as jt,j as We,q as Tt,i as An,h as Kt,g as vn}from"./do-sql-FNOnpyHm.mjs";import{renderSql as Qt,unionAll as ct,WORKERD_SQLITE_LIMITS as Vt,sqliteInList as In}from"./param-DlozcSQu.mjs";import{coveringGeohashes as Cn,boundingBoxGeohashes as xn,haversineMeters as bn,pointInBoundingBox as Mn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Dn}from"./NotFoundError-BhF7FeFr.mjs";import{softDeleteScope as de,normalizeOrderKeys as nt,buildSeekWhere as zt,decodeCursor as ot,applySelect as At,encodeCursor as rt,tiebreakDirectionFor as Jt,buildSeekBeforeWhere as Ln}from"./CURSOR_PREFIX-qn6nNVS7.mjs";import{rankTableName as vt,sortColumnName as It,resolveRankPartition as kn,encodePartitionKey as Fn,RANK_TIEBREAK as qn,rankPivotConditionSql as Bn}from"./RANK_TIEBREAK-CkNuGm6a.mjs";import{UNVOUCHABLE_DEP as Ct}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as Wn,buildIndexRange as Un}from"./buildIndexRange-CBKQmHSS.mjs";import{assertFlatPredicate as Ze,resolveRelationPredicates as xt}from"./DEFAULT_MAX_RELATION_KEYS-Ciwtjo9t.mjs";import{runRowValidators as et,resolveWith as bt,relationHooks as Mt,applyOnDelete as Pn,fanOutScalarCounts as Gn}from"./applyOnDelete-tDhKaeB6.mjs";import{guardWriter as Hn}from"./RLS_UNWRAP_SYMBOL-B3RgW-Kb.mjs";import{quoteIdentifier as _e}from"./quoteIdentifier-CObIFRhb.mjs";import{mayHoldProjectedValue as On}from"./BIGINT_KEY_DIGITS-GvEBhyR5.mjs";import{createSystemReader as Nn}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as Ee}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as jn}from"./hasTrigger-CjlwI4le.mjs";import{c as ne,t as Pe,r as Ue,j as me,i as Dt}from"./where-sql-B1l5NcUZ.mjs";import{CLIENT_WATERMARK_TABLE as Nr,advanceClientWatermark as jr,migrateClientWatermark as Kr,readClientWatermark as Qr}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as zr,deleteGlobalShapeSnapshot as Jr,deleteGlobalShapeSnapshotsForConnection as Yr,migrateGlobalShapeSnapshot as Xr,readGlobalShapeSnapshot as Zr,writeGlobalShapeSnapshot as ei}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{IDEMPOTENCY_TABLE as ni,readIdempotent as oi,trimIdempotent as ri,writeIdempotent as ii}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{runShardMigrations as ci}from"./runShardMigrations-CkG92fSl.mjs";import{S as di}from"./ctx-db-search-state-ruTuCsxa.mjs";import{selectShapeMembers as ui,selectShapeRows as fi}from"./selectShapeMembers-DqikYFjS.mjs";import{serializeSqlValue as re}from"./serializeSqlValue-B_-zaEWZ.mjs";const Kn=o=>{const r=atob(o),t=Uint8Array.from(r,a=>a.codePointAt(0)??0);return new TextDecoder().decode(t)},Qn=()=>new $("BAD_REQUEST","invalid cursor"),Lt=16,kt=8,Y=1024,at=(o,r)=>r.query(o),Vn=(o,r)=>{if(o.length===0)return 0;let t=0;for(const[a,d]of r.entries()){const p=a===r.length-1;let E=0;for(const S of o)(p?S.startsWith(d):S===d)&&(E+=1);if(E===0)return 0;t+=E}return t},zn=(o,r)=>{if(!r)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",a=(t.codePointAt(0)??0)+1;if(a>=55296&&a<=57343||a>1114111)return{exact:!0,lower:o,upper:o};const d=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:d+String.fromCodePoint(a)}},Jn=(o,r,t)=>{const a={eq:(d,p)=>{if(!o.definition.filterFields?.includes(d))throw new $("INTERNAL",`field "${d}" is not a filter field of search index "${o.indexName}" on table "${r}"`);if(o.filters.length>=kt)throw new $("BAD_REQUEST",`search index "${o.indexName}" on table "${r}": at most ${String(kt)} .eq() filters are supported per search query`);return o.filters.push({field:d,value:p}),a},search:(d,p)=>{const E=o;if(d!==E.definition.field)throw new $("INTERNAL",`search index "${E.indexName}" on table "${r}" indexes "${E.definition.field}", not "${d}"`);const S=at(p,t).length;if(S>Lt)throw new $("BAD_REQUEST",`search index "${E.indexName}" on table "${r}": at most ${String(Lt)} search terms are supported (got ${String(S)})`);return E.field=d,E.query=p,E.hasQuery=!0,a}};return a},Yn=o=>{if(o.length>Y)throw new $("BAD_REQUEST",`more than ${String(Y)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Xn=o=>Math.min(o.offset+o.numItems+1,Y),Zn=o=>btoa(`search:${String(o)}`),eo=o=>{let r;try{r=Kn(o)}catch{return}if(!r.startsWith("search:"))return;const t=Number(r.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},to=o=>{if(typeof o.endCursor=="string")throw new $("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(o.numItems))throw new $("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(o.numItems)}`);const r=Math.max(0,Math.floor(o.numItems)),t=o.cursor?eo(o.cursor):0;if(t===void 0)throw Qn();if(t+r>=Y)throw new $("BAD_REQUEST",`search pagination reaches the ${String(Y)}-document limit (offset ${String(t)} + ${String(r)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,Y-t-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:t}},no=(o,r)=>{const t=r.offset+r.numItems,a=r.numItems>0&&o.length>t;return{continueCursor:a?Zn(t):null,isDone:!a,page:o.slice(r.offset,t)}},oo=o=>{if(o===void 0)return Y+1;if(!Number.isFinite(o))return Y;const r=Math.max(0,Math.floor(o));if(r>Y)throw new $("BAD_REQUEST",`search returns at most ${String(Y)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},Ge=o=>{const r=new Map;return t=>{const a=r.get(t);if(a!==void 0)return a;const d=o(_e(t));return r.set(t,d),d}},ue=_e(oe),ro=Ge(o=>`INSERT INTO ${o} (id, _creationTime, ${ue}) VALUES (?, ?, ?)`),Ft=Ge(o=>`UPDATE ${o} SET ${ue} = ? WHERE id = ? AND ${ue} = ?`),io=Ge(o=>`UPDATE ${o} SET _creationTime = ?, ${ue} = ? WHERE id = ? AND ${ue} = ?`),so=Ge(o=>`DELETE FROM ${o} WHERE id = ? AND ${ue} = ?`),co="SELECT changes() AS changed",qt=new Map,ao="",lo=o=>{const r=JSON.stringify(o),t=qt.get(r);if(t!==void 0)return t;const a=o.map(p=>i`SELECT ${i.raw(`'${p.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(p)} WHERE id = ${ao}`),{sql:d}=Qt("sqlite",i`${ct(a)} LIMIT 1`);return qt.set(r,d),d},uo=(o,r)=>r.map(()=>o),fo=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,ho=o=>{if(!fo.test(o))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},Bt=50,Yt=500,qe=Math.floor(Vt.boundParams/3),$e=Vt.boundParams,wo=128,ae=(o,r,t)=>{const a=r??Yt;if(o>a)throw new $("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},po=o=>{const r={eq:(t,a)=>(o.sqlConditions.push({comparator:"=",field:t,value:a}),r),gt:(t,a)=>(o.sqlConditions.push({comparator:">",field:t,value:a}),r),gte:(t,a)=>(o.sqlConditions.push({comparator:">=",field:t,value:a}),r),lt:(t,a)=>(o.sqlConditions.push({comparator:"<",field:t,value:a}),r),lte:(t,a)=>(o.sqlConditions.push({comparator:"<=",field:t,value:a}),r)};return r},go=o=>Math.max(o,Y),Xt=(o,r)=>{const t=o.filters.map(a=>i`${X(a.field)} = ${re(a.value)}`);return r&&t.push(r),t},$o=(o,r,t,a,d)=>{const p=at(t.query,st(t.definition.language));if(p.length===0)return[];const E=fn(r,t.indexName),S=`${E}__vocab`,_=p.length-1,D=p.map((R,k)=>{const q=zn(R,k===_),W=q.exact?i`${i.identifier("term")} = ${q.lower}`:i`${i.identifier("term")} >= ${q.lower} AND ${i.identifier("term")} < ${q.upper}`;return i`SELECT ${i.identifier("doc")}, ${i.raw(String(k))} AS ${i.identifier("__term__")}, COUNT(*) AS ${i.identifier("__n__")} FROM ${i.identifier(S)} WHERE ${W} GROUP BY ${i.identifier("doc")}`}),y=p.map((R,k)=>i`SUM(CASE WHEN u.${i.identifier("__term__")} = ${i.raw(String(k))} THEN u.${i.identifier("__n__")} ELSE 0 END)`),A=i`SELECT f.${i.identifier(De)} AS ${i.identifier(De)}, ${i.join(y,i` + `)} AS ${i.identifier("__score__")} FROM (${ct(D)}) u JOIN ${i.identifier(E)} f ON f.rowid = u.${i.identifier("doc")} GROUP BY f.${i.identifier(De)} HAVING ${i.join(y.map(R=>i`${R} > 0`),i` AND `)}`,I=Xt(t,d);let F=i`SELECT m.id, m._creationTime, m.${i.identifier(oe)}, s.${i.identifier("__score__")} AS ${i.identifier("__score__")} FROM (${A}) s JOIN ${i.identifier(r)} m ON m.id = s.${i.identifier(De)}`;I.length>0&&(F=i`${F} WHERE ${i.join(I,i` AND `)}`),F=i`${F} ORDER BY s.${i.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${i.raw(String(a))}`;const j=[];for(const R of N(o,F)){const k=Kt(R);if(k){const q=R.__score__;j.push({document:k,score:typeof q=="number"?q:Number(q??0)})}}return j},yo=(o,r,t,a,d)=>{const p=st(t.definition.language),E=at(t.query,p);if(E.length===0)return[];const S=Xt(t,d);let _=i`SELECT id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(r)}`;S.length>0&&(_=i`${_} WHERE ${i.join(S,i` AND `)}`),_=i`${_} ORDER BY _creationTime DESC, id ASC LIMIT ${i.raw(String(go(a)))}`;const D=N(o,_).toArray(),y=[];for(const A of D){const I=Kt(A);if(!I)continue;const F=Vn(hn(I,t.definition),E);F>0&&y.push({creationTime:typeof I._creationTime=="number"?I._creationTime:0,doc:I,id:typeof I._id=="string"?I._id:"",score:F})}return y.sort((A,I)=>I.score-A.score||I.creationTime-A.creationTime||A.id.localeCompare(I.id)),y.slice(0,a).map(A=>({document:A.doc,score:A.score}))},tt=(o,r,t,a)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new $("BAD_REQUEST",`geo index "${a}" on table "${t}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},Eo=(o,r)=>{const t=o,a={near:(d,p)=>{if(t.within)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(tt(d,".near() point",r,t.indexName),!Number.isFinite(p)||p<=0)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(p)}`);return t.near={point:{lat:d.lat,lng:d.lng},radiusMeters:p},a},within:d=>{if(t.near)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(tt(d.sw,".within() sw corner",r,t.indexName),tt(d.ne,".within() ne corner",r,t.indexName),d.sw.lat>d.ne.lat)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(d.sw.lng>d.ne.lng)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return t.within={ne:{lat:d.ne.lat,lng:d.ne.lng},sw:{lat:d.sw.lat,lng:d.sw.lng}},a}};return a},mo=(o,r)=>{const t=o[r];if(t===null||typeof t!="object")return;const{lat:a,lng:d}=t;return typeof a=="number"&&typeof d=="number"?{lat:a,lng:d}:void 0},So=(o,r)=>{const t=mo(o,r.definition.field);if(!t)return;const a=typeof o._creationTime=="number"?o._creationTime:0;if(r.near){const d=bn(r.near.point,t);return d<=r.near.radiusMeters?{creationTime:a,distance:d}:void 0}return Mn(t,r.within)?{creationTime:a,distance:0}:void 0},_o=(o,r,t,a)=>{if(!t.near&&!t.within)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const d=t.near?Cn(t.near.point,t.near.radiusMeters):xn(t.within),p=vn(r,t.indexName),E=d.map(A=>i`(g.${i.identifier("__geohash__")} >= ${A} AND g.${i.identifier("__geohash__")} < ${`${A}{`})`),S=[i`(${i.join(E,i` OR `)})`];a&&S.push(a);const _=i`SELECT m.id, m._creationTime, m.${i.identifier(oe)} FROM ${i.identifier(p)} g JOIN ${i.identifier(r)} m ON m.id = g.${i.identifier("__id__")} WHERE ${i.join(S,i` AND `)}`,D=N(o,_).toArray(),y=[];for(const A of D){const I=le(A),F=I?So(I,t):void 0;I&&F&&y.push({creationTime:F.creationTime,distance:F.distance,doc:I})}return y.sort((A,I)=>A.distance-I.distance||I.creationTime-A.creationTime),y},Zt=(o,r,t,a)=>{const d=[];for(const p of o)if(r.every(E=>E(a(p)))&&(d.push(p),typeof t=="number"&&d.length>=t))break;return d},Ro=(o,r,t,a,d,p=()=>{})=>{const E=t.within!==void 0,S=_o(o,r,t,d).map(_=>({distanceMeters:E?null:_.distance,document:_.doc}));return p(S.length),typeof a=="number"?S.slice(0,Math.max(0,Math.floor(a))):S},en=(o,r,t,a,d,p=()=>{})=>{const{geo:E}=t;if(!E)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const S=t.inMemoryFilters.length>0,_=Ro(o,r,E,S?void 0:d,a,p);return S?Zt(_,t.inMemoryFilters,d,D=>D.document):_},tn=(o,r,t,a)=>{const d=`SELECT id, _creationTime, ${_e(oe)} FROM ${_e(o)}`,p=`ORDER BY ${t}${a===void 0?"":` LIMIT ${String(a)}`}`;return r===void 0?Ue(`${d} ${p}`):me(`${d} WHERE `,r,` ${p}`)},To=(o,r,t,a,d,p=()=>{})=>en(o,r,t,a,d,p).map(E=>E.document),Ao=(o,r,t,a,d,p,E=()=>{})=>{const S=[];for(const A of t.sqlConditions)S.push(i`${X(A.field)} ${i.raw(A.comparator)} ${re(A.value)}`);a&&S.push(a);let _=i`SELECT id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(r)}`;S.length>0&&(_=i`${_} WHERE ${i.join(S,i` AND `)}`),_=i`${_} ORDER BY ${d}`,typeof p=="number"&&t.inMemoryFilters.length===0&&(_=i`${_} LIMIT ${i.raw(String(Math.max(0,Math.floor(p))))}`);const D=N(o,_).toArray();E(D.length);const y=[];for(const A of D){const I=le(A);if(I&&t.inMemoryFilters.every(F=>F(I))&&(y.push(I),typeof p=="number"&&y.length>=p))break}return y},ye={fieldRef:X,serialize:re},nn=(o,r)=>{const t=r===void 0?void 0:o.shape[r];return t!==void 0&&On(t)},Wt=(o,r)=>r.some(t=>nn(o,t)),Ut=(o,r,t)=>{if(nn(o,r))throw new $("BAD_REQUEST",`${t}: "${r}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},dt={fieldRef:o=>Ue(We(o)),serialize:re},vo=o=>{let r=0;const t=[],a={fieldRef:d=>Ue(We(d)),relationExists:d=>{const{childWhere:p,negated:E,parentTable:S,relation:_}=d,D=`__rel_${String(r)}`,y=t.at(-1)??S;r+=1,o(_.table,H);const A=_.kind==="one"?_.field:_.references,I=_.kind==="one"?_.references:_.field,F=Ue(`${Tt(D,I)} = ${Tt(y,A)}`);t.push(D);const j=ne(p,a,Pe);t.pop();const R=j===void 0?F:me(F," AND ",j),k=me("EXISTS (SELECT 1 FROM ",Dt(_.table)," AS ",Dt(D)," WHERE ",R,")");return E?me("NOT ",k):k},serialize:re};return a},on=o=>{const r=o.map(t=>`${We(t.field)} ${t.direction==="desc"?"DESC":"ASC"}`);return o.some(t=>t.field==="_id"||t.field==="id")||r.push(`${We("id")} ${Jt(o)==="desc"?"DESC":"ASC"}`),r.join(", ")},Io=o=>{const r=o.map(t=>i`${X(t.field)} ${i.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||r.push(i`${X("id")} ${i.raw(Jt(o)==="desc"?"DESC":"ASC")}`),i.join(r,i`, `)},Co={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},xo=o=>{const r=new Set(o.sqlConditions.filter(a=>a.comparator==="=").map(a=>a.field));let t=0;for(;t<o.indexFields.length&&r.has(o.indexFields[t]??"");)t+=1;return o.indexFields.slice(t)},rn=(o,r)=>{const t=o.order,a=xo(o);return a.length>0?nt(a.map(d=>({[d]:t})),r):nt([{_creationTime:t}],r)},bo=(o,r,t,a)=>{const d=o.sqlConditions.map(p=>({[p.field]:{[Co[p.comparator]??"eq"]:p.value}}));if(t&&d.push(zt(r,ot(t))),a&&d.push(Ln(r,ot(a))),d.length!==0)return d.length===1?d[0]:{AND:d}},Mo=(o,r,t)=>{const a=[];for(const d of o){const p=le(d);if(p&&r.every(E=>E(p))&&(a.push(p),t!==void 0&&a.length>t))break}return a},Do=(o,r,t,a,d,p,E=()=>{})=>{const S=Math.max(0,Math.floor(d.numItems)),_=rn(a,t),D=typeof d.endCursor=="string",y=ne(bo(a,_,d.cursor,d.endCursor),dt,Pe),A=p&&y?me(y," AND ",p):p??y,I=a.inMemoryFilters.length>0,F=tn(r,A,on(_),I||D?void 0:S+1),j=Se(o,F.text,...F.params).toArray();E(j.length);const R=Mo(j,a.inMemoryFilters,I||D?void 0:S);if(D){const O=R.length>=2?R[Math.floor(R.length/2)-1]:void 0;return{continueCursor:d.endCursor??null,isDone:!0,page:R,splitCursor:O?rt(O,_):null}}const k=R.length>S,q=k?R.slice(0,S):R,W=q.at(-1);return{continueCursor:k&&W?rt(W,_):null,isDone:!k,page:q}};class Lo extends ${constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const ko=/\s/u,Fo=String.fromCodePoint(0),Pt=(o,r,t)=>{if(!o.tables[r])throw new $("INTERNAL",`unknown table: ${r}`);return typeof t!="string"||t.length===0||ko.test(t)||t.includes(Fo)?null:t},qo=(o,r,t,a=()=>{},d=()=>{},p=()=>{})=>{const E=r.tables[t];if(!E)throw new $("INTERNAL",`unknown table: ${t}`);const S=de(E.softDeleteMode,void 0),_=S?ne(S,ye):void 0,D=S?ne(S,dt,Pe):void 0,y={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let A=0;const I=m=>{const{search:C}=y;if(!C)throw new $("INTERNAL","runSearchFetch called without a staged search");mn(o,t,E);const M=y.inMemoryFilters.length>0,L=oo(M?void 0:m),K=An(o);if(K&&!Sn(o,t,C.definition))throw new $("SEARCH_INDEX_BUILDING",`search index "${C.indexName}" on table "${t}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const Z=K?$o(o,t,C,L,_):yo(o,t,C,L,_);return M?(A=Z.length,Zt(Z,y.inMemoryFilters,m,He=>He.document)):(m===void 0&&Yn(Z),Z)},F=m=>I(m).map(C=>C.document),j=m=>{const C=to(m);return no(F(Xn(C)),C)},R=()=>Io(rn(y,E.shape)),k=()=>{if(y.search||y.geo||y.indexName===void 0){d(void 0);return}d(Un(t,y.indexName,y.indexFields,y.sqlConditions,re))},q=m=>{k();let C=0;const M=(()=>{if(y.search){const L=F(m);return C=A,L}return y.geo?To(o,t,y,_,m,L=>{C=L}):Ao(o,t,y,_,R(),m,L=>{C=L})})();return p(Math.max(C,M.length)),M},W=()=>{if(!y.search&&!y.geo)throw new $("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);k();let m=0;const C=(()=>{if(y.search){const M=I(void 0);return m=A,M}return en(o,t,y,_,void 0,M=>{m=M})})();return p(Math.max(m,C.length)),C},O={async*[Symbol.asyncIterator](){if(y.search){yield*q(void 0);return}const m=[...y.inMemoryFilters];let C;y.inMemoryFilters=[];try{for(;;){const M=await O.paginate({cursor:C??null,numItems:wo});for(const L of M.page)m.every(K=>K(L))&&(yield L);if(M.isDone||M.continueCursor===null)return;C=M.continueCursor}}finally{y.inMemoryFilters=m}},async collect(){return q(void 0)},async collectWithScores(){return W()},filter(m){return y.inMemoryFilters.push(m),O},async first(){return q(y.inMemoryFilters.length>0?void 0:1)[0]??null},order(m){return y.order=m==="desc"?"desc":"asc",O},async paginate(m){let C=0;if(k(),y.search){const L=j(m);return p(L.page.length),L}if(y.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const M=Do(o,t,E.shape,y,m,D,L=>{C=L});return p(Math.max(C,M.page.length)),M},async take(m){return q(m)},async unique(){const m=q(y.inMemoryFilters.length>0?void 0:2);if(m.length>1)throw new Lo(`unique() on table "${t}" matched ${String(m.length)} documents; expected at most one`);return m[0]??null},withGeoIndex(m,C){const M=(E.geoIndexes??[]).find(K=>K.name===m);if(!M)throw new $("INTERNAL",`unknown geo index "${m}" on table "${t}"`);a(t,m,"geo");const L={definition:M,indexName:m};if(y.geo=L,C(Eo(L,t)),!L.near&&!L.within)throw new $("INTERNAL",`geo index "${m}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return O},withIndex(m,C){const M=E.indexes.find(L=>L.name===m);if(!M)throw new $("INTERNAL",`unknown index "${m}" on table "${t}"`);return a(t,m,"index"),y.indexName=m,y.indexFields=M.fields,C&&C(po(y)),O},withSearchIndex(m,C){const M=(E.searchIndexes??[]).find(K=>K.name===m);if(!M)throw new $("INTERNAL",`unknown search index "${m}" on table "${t}"`);a(t,m,"search");const L={definition:M,field:M.field,filters:[],hasQuery:!1,indexName:m,query:""};if(y.search=L,C(Jn(L,t,st(M.language))),!L.hasQuery)throw new $("INTERNAL",`search index "${m}" on table "${t}" requires a .search(field, query) call`);return O}};return O},Gt=(o,r,t)=>{const a={...r};for(const[d,p]of jt(o)){if(p.serverDefault){a[d]=p.serverDefault({auth:t});continue}a[d]===void 0&&(p.defaultFn?a[d]=p.defaultFn():"defaultValue"in p&&(a[d]=p.defaultValue))}return a},Ht=(o,r,t,a)=>{const d=t;for(const[p,E]of jt(o)){if(E.serverDefault){p in r&&(d[p]=E.serverDefault({auth:a}));continue}E.onUpdateFn&&!(p in r)&&(d[p]=E.onUpdateFn())}},Ot=(o,r)=>{for(const t of Object.keys(r))if(r[t]===void 0)throw new $("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Bo=/unique constraint failed/i,Wo=o=>o instanceof Error&&Bo.test(o.message),Uo=/string or blob too big/iu,Po=(o,r)=>{if(!(!(o instanceof Error)||!Uo.test(o.message)))throw new $("PAYLOAD_TOO_LARGE",`document is too large to store in "${r}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},it=(o,r,t,a)=>{try{Se(o,t,...a)}catch(d){throw Wo(d)?new Ee(`unique constraint violation on "${r}"`,"unique"):(Po(d,r),d)}},Be=(o,r,t,a)=>{if(it(o,r,t,a),Se(o,co).one().changed===0)throw new Ee(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},Nt=(o,r,t,a,d,p,E)=>{const S=[];for(let A=0;A<t.length+1;A+=1){const I=t[A],F=a[A],j=F?.direction==="desc"?"desc":"asc",R=I===void 0||F===void 0?i`${i.identifier(qn)} < ${E}`:Bn(I,p[A],j,!1);if(R===void 0)continue;const k=[];for(let W=0;W<A;W+=1)k.push(i`${i.identifier(t[W])} IS ${p[W]}`);k.push(R);const[q]=k;S.push(k.length===1&&q!==void 0?q:i`(${i.join(k,i` AND `)})`)}const _=S.length>0?i.join(S,i` OR `):i`1 = 0`,D=N(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${d} AND (${_})`).one(),y=N(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${d}`).one();return{before:D.c,total:y.c}},mr=o=>{const{sql:r}=o,{schema:t}=o,a=o.broadcast??(()=>{});let d;const p=()=>o.inTransaction?.()===!0,E=e=>t.tables[e]?.commitOrderedMode!==!0?{}:((d===void 0||!p())&&(d=Rn(r)),{[Tn]:d}),S=(e,...n)=>{const s=t.tables[e]?.indexes;if(!s||s.length===0)return;const f=[];for(const h of n)h&&f.push(...Wn(s,h,re));return f.length>0?f:void 0},{headroom:_}=o;let D=!1;const y=async e=>{const n=D;D=!0;try{return await e()}finally{D=n}},A=o.onRead??(()=>{}),I=e=>{_t(t.tables[e])&&A(Ct,Ct)},F=o.onReadRange??(e=>{A(e.table,H)}),j=e=>{I(e.table),F(e)},R=(e,n)=>{n!==void 0&&n!==H&&!D&&_?.recordRead(1),I(e),A(e,n)},k=o.onIndexUse??(()=>{}),q=o.onWrite??(()=>{}),W=e=>{D||_?.recordWrite(e)},O=async e=>{W(e.doc),await q(e)},{cache:m}=o,C=o.clock??(()=>Date.now()),M=o.idGenerator??(()=>crypto.randomUUID()),L=o.scheduler??pn,{globalDb:K}=o,Z=o.auth??{identity:null,userId:null},He=o.cdc??!1,Oe=L,sn=Nn({scheduler:typeof Oe.list=="function"&&typeof Oe.get=="function"?Oe:void 0,storage:o.storage}),fe=(e,n,s,f)=>{He&&!_t(t.tables[e])&&_n(r,C(),e,n,s,f)},ie=e=>t.tables[e]?.shardMode?.kind==="global",lt=(e,n)=>{if(ie(e)){if(!K)throw new $("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return K}return U},Ne=e=>lt(e,"cascade"),V=(e,n)=>{if(ie(e)){if(!K)throw new $("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return K}},ut=async(e,n,s,f,h)=>{h&&W(s);const u=await e.insert(n,s,f);return a({key:u,op:"insert",row:{...s,_id:u},table:n}),u},je=(e,n)=>lt(e,"relation load").findMany(e,n),ft=(e,n)=>(ie(e)&&R(e,H),je(e,n)),cn=e=>!ie(e.table),ht=o.relationExistsPushDown??"auto",wt=ht!=="never",{maxRelationKeys:pt}=o,Re=(e,n,s)=>xt(e,{fetcher:ft,maxRelationKeys:pt,relationBaseWhere:s,schema:t,tableName:n}),gt=async(e,n,s,f)=>{const h=V(e,"relation grouped count");if(h)return R(e,H),Gn((B,v)=>h.count(B,v),e,n,s,f);const u=t.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);R(e,H);const c=de(u.softDeleteMode,void 0),l={[n]:{in:s}},w=z(z(l,f),c),T=await Re(w,e,void 0),g=ne(T,ye),b=X(n);let x=i`SELECT ${b} AS __fk__, COUNT(*) AS count FROM ${i.identifier(e)}`;g&&(x=i`${x} WHERE ${g}`),x=i`${x} GROUP BY ${b}`;const P=N(r,x).toArray();return new Map(P.map(B=>[B.__fk__,B.count]))};let Te=0;const $t=new Set;for(const[e,n]of Object.entries(t.tables))for(const s of Object.values(n.triggerMap??{}))$t.add(`${e} ${s.timing} ${s.op}`);const ee=(e,n,s)=>$t.has(`${e} ${n} ${s}`),te=async(e,n,s)=>{if(Te+=1,Te>Bt)throw Te-=1,new Ee(`trigger recursion exceeded ${String(Bt)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await jn({ctx:dn,event:s,op:n,schema:t,tableName:s.table,timing:e})}finally{Te-=1}},{ensureBackfilledForTable:he,ensureBackfilledIndex:Ke,ensureRankBackfilled:Qe,ensureRankBackfilledForTable:we,syncAggregates:Ae,syncCompanionsForInsert:yt,syncGeo:ve,syncRanks:pe,syncSearch:Ie}=un({broadcast:a,indexKeysFor:(e,n)=>S(e,n),invalidateCache:(e,n,s)=>m?.invalidate(e,n,S(e,s)),recordCdc:fe,schema:t,sql:r}),Et=(e,n,s)=>{const{shardMode:f}=n;if(f?.kind==="shardBy"&&!(f.field!==void 0&&(s.partitionBy??[]).includes(f.field)))throw Object.assign(new Error(`rank index "${s.name}" on "${e}" partitions across shards (shard key "${f.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},mt=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),ge=e=>e===void 0||ie(e)?K:void 0,se=(e,n)=>{const s=mt(n);for(let f=0;f<s.length;f+=$e){const h=s.slice(f,f+$e),[u]=Se(r,lo(h),...uo(e,h)).toArray();if(!u)continue;const c=u.__t__,l=le(u);if(typeof c!="string"||!l)return;const w=u[oe];return{docJson:typeof w=="string"?w:ce(w??{}),row:l,tableName:c}}},an=(e,n)=>{const s=[...new Set(e)],f=new Map;if(s.length===0)return f;const h=mt(n);for(let u=0;u<h.length;u+=$e){const c=h.slice(u,u+$e),l=Math.floor($e/c.length),w=In(i`${i.identifier("id")}`,s,!1,l),T=c.map(g=>i`SELECT ${i.raw(`'${g.replaceAll("'","''")}'`)} AS __t__, id FROM ${i.identifier(g)} WHERE ${w}`);for(const g of N(r,ct(T))){const{id:b,__t__:x}=g;typeof x=="string"&&typeof b=="string"&&f.set(b,x)}}return f},St={assertRankPartitionLocal:Et,ensureRankBackfilled:Qe,onRead:R,rowToDocument:le,schema:t,sql:r},U={system:sn,async aggregate(e,n){const s=V(e,"aggregate");if(s)return R(e,H),s.aggregate(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);if(Le(n.op),n.op==="count")return U.count(e,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new $("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);R(e,H);const h=de(f.softDeleteMode,void 0),u=z(z(n.baseWhere,n.where),h),c=await Re(u,e,n.relationBaseWhere),l=c!==u;if(f.aggregateIndexes&&!n.baseWhere&&!l&&(!h||Wt(f,[n.field]))){const B=En(f.aggregateIndexes,n.op,n.field,n.where);if(B){Ke(e,B.index);const v=ze(B.index.by??[],B.key),Q=Ve(e,B.index.name),J=N(r,i`SELECT ${ke} AS value, ${Xe} AS count FROM ${i.identifier(Q)} WHERE ${Fe} = ${v}`).toArray()[0];return Je(n.op,J)}}Ut(f,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const w=ne(c,ye),T=Le(n.op),g=X(n.field);let b=i`SELECT ${i.raw(T)}(${g}) AS value FROM ${i.identifier(e)}`;w&&(b=i`${b} WHERE ${w}`);const P=N(r,b).toArray()[0]?.value;return P??null},asId(e,n){const s=Pt(t,e,n);if(s===null)throw new $("BAD_REQUEST",`asId("${e}", …): "${n}" is not a valid id for table "${e}"`,{status:400});return s},async count(e,n){const s=V(e,"count");if(s)return R(e,H),s.count(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=gn(n);if(h.restrictsCounts)throw new Ye(e);R(e,H);const u=de(f.softDeleteMode,void 0),c=z(z(h.baseWhere,h.where),u),l=await Re(c,e,h.relationBaseWhere),w=l!==c;if(f.aggregateIndexes&&!h.baseWhere&&!w&&!u){const x=yn(f.aggregateIndexes,h.where);if(x){Ke(e,x.index);const P=ze(x.index.by??[],x.key),B=Ve(e,x.index.name),v=N(r,i`SELECT ${ke} AS value FROM ${i.identifier(B)} WHERE ${Fe} = ${P}`).toArray();return v[0]===void 0?0:v[0].value??0}}const T=ne(l,ye);let g=i`SELECT COUNT(*) AS count FROM ${i.identifier(e)}`;return T&&(g=i`${g} WHERE ${T}`),N(r,g).one().count},async delete(e,n,s){const f=se(e,n);if(!f){const g=ge(n);g&&(W(void 0),await g.delete(e,n,s));return}const{docJson:h,row:u,tableName:c}=f,l=t.tables[c],w=s?.hard===!0,T=!w&&l?.softDeleteMode?l.softDeleteMode.field:void 0;if(!(T&&u[T]!==null&&u[T]!==void 0)){if(ee(c,"before","delete")&&await te("before","delete",{id:e,op:"delete",previous:u,table:c}),await Pn({deletedId:e,deletedReference:g=>u[g],findHolders:async(g,b,x)=>(await Ne(g).findMany(g,{includeDeleted:w,where:{[b]:x}})).page,onCascade:(g,b)=>Ne(g).delete(b,void 0,s),onRestrict:g=>{throw new Ee(g,"restrict")},onSetNull:(g,b,x)=>Ne(g).patch(b,{[x]:null}),schema:t,tableName:c}),he(c),we(c),T){const g={...u,...E(c),[T]:C(),_id:e};Be(r,c,Ft(c),[ce(g),e,h]),Ie(c,e,g,u),ve(c,e,void 0),Ae(c,u,g),pe(c,e,u,void 0),m?.invalidate(c,e,S(c,u,g)),fe(c,e,"update",g),a({indexKeys:S(c,u,g),key:e,op:"update",row:g,table:c}),ee(c,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:u,table:c}),await O({id:e,op:"delete",table:c});return}Be(r,c,so(c),[e,h]),Ie(c,e,void 0),ve(c,e,void 0),Ae(c,u,void 0),pe(c,e,u,void 0),m?.invalidate(c,e,S(c,u)),fe(c,e,"delete"),a({indexKeys:S(c,u),key:e,op:"delete",table:c}),ee(c,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:u,table:c}),await O({id:e,op:"delete",table:c})}},async deleteAll(e,n){if(!t.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);const s=Math.max(1,n?.chunkSize??Yt),f=n?.hard===void 0?void 0:{hard:n.hard},h=ie(e)?void 0:e;let u=0;return await y(async()=>{for(;;){const l=(await U.findMany(e,{limit:s})).page.map(w=>String(w._id));if(l.length===0)break;for(const w of l)await U.delete(w,h,f),u+=1;if(l.length<s)break}}),{deleted:u}},async deleteMany(e,n,s){ae(e.length,n?.limit,"deleteMany");for(const f of e)await U.delete(f,s);return{deleted:e.length}},async deleteWhere(e,n,s){const u=(await(V(e,"deleteWhere")??U).findMany(e,{where:n})).page.map(c=>String(c._id));if(ae(u.length,s?.limit,"deleteWhere"),U.deleteMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return U.deleteMany(u,s)},async findFirst(e,n={}){return(await U.findMany(e,{...n,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,n={}){const s=await U.findFirst(e,n);if(s===null)throw new Dn(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,n={}){const s=V(e,"findMany");if(s)return R(e,H),s.findMany(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=!n.where&&!n.baseWhere;h?R(e,H):R(e);const u=nt(n.orderBy,f.shape),c=n.cursor?zt(u,ot(n.cursor)):void 0;let l=z(n.baseWhere,n.where);l=z(l,de(f.softDeleteMode,n.includeDeleted)),l=await xt(l,{canPushExists:wt?cn:void 0,existsPushMode:ht==="always"?"always":"auto",fetcher:ft,maxRelationKeys:pt,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),c&&(l=l?{AND:[l,c]}:c);const w=wt?vo(R):dt,T=ne(l,w,Pe),g=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0,b=tn(e,T,on(u),g===void 0?void 0:g+1),x=Se(r,b.text,...b.params).toArray();h&&!D&&_?.recordRead(x.length);const P=[];for(const J of x){const G=le(J);G&&(P.push(G),!h&&typeof G._id=="string"&&R(e,G._id))}if(g===void 0)return n.with&&await bt({groupedCounter:gt,fetcher:je,parents:P,...Mt(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:At(P,n.select,n.with)};const B=P.length>g,v=B?P.slice(0,g):P,Q=v.at(-1);return n.with&&await bt({fetcher:je,groupedCounter:gt,parents:v,...Mt(n),schema:t,tableName:e,with:n.with}),{continueCursor:B&&Q&&n.omitContinueCursor!==!0?rt(Q,u):null,isDone:!B,page:At(v,n.select,n.with)}},async get(e,n){const s=se(e,n);if(!s){const f=ge(n);return f?f.get(e,n):null}return R(s.tableName,e),s.row},async lookupById(e,n){const s=se(e,n);return s?(R(s.tableName,e),{row:s.row,tableName:s.tableName}):null},async groupBy(e,n){const s=V(e,"groupBy");if(s)return R(e,H),s.groupBy(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);R(e,H);const h=n.agg??{op:"count"};if(Le(h.op),h.op!=="count"&&!h.field)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const u=de(f.softDeleteMode,void 0),c=z(z(n.baseWhere,n.where),u),l=await Re(c,e,n.relationBaseWhere),w=l!==c,T=[...n.by,h.field];if(f.aggregateIndexes&&!n.baseWhere&&!w&&(!u||Wt(f,T))){const v=$n(f.aggregateIndexes,h.op,h.field,n.by,n.where),Q=v===void 0?0:Object.keys(v.partial).length,J=v?.index.by?.length??0;if(v&&(Q===0||Q===J)){Ke(e,v.index);const G=Ve(e,v.index.name),Ce=Object.keys(v.partial),xe=[];if(Ce.length===(v.index.by??[]).length&&Ce.length>0){const be=ze(v.index.by??[],v.partial),Me=N(r,i`SELECT ${ke} AS value, ${Xe} AS count FROM ${i.identifier(G)} WHERE ${Fe} = ${be}`).toArray();return Me.length>0&&xe.push({key:{...v.partial},value:Je(h.op,Me[0])}),xe}const ln=N(r,i`SELECT ${Fe} AS key, ${ke} AS value, ${Xe} AS count FROM ${i.identifier(G)}`).toArray();for(const be of ln){const Me=wn(JSON.parse(be.key));xe.push({key:Me,value:Je(h.op,be)})}return xe}}for(const v of T){if(v===void 0)continue;const Q=v===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${v}" } })`:`groupBy(${e}, { by: [..."${v}"] })`;Ut(f,v,Q)}const g=ne(l,ye),b=n.by.map(v=>i`${X(v)} AS ${i.identifier(v)}`);if(h.op==="count")b.push(i`COUNT(*) AS value`);else{const{field:v}=h;if(v===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);b.push(i`${i.raw(Le(h.op))}(${X(v)}) AS value`)}let x=i`SELECT ${i.join(b,i`, `)} FROM ${i.identifier(e)}`;g&&(x=i`${x} WHERE ${g}`),x=i`${x} GROUP BY ${i.join(n.by.map(v=>X(v)),i`, `)}`;const P=N(r,x).toArray(),B=[];for(const v of P){const Q={};for(const G of n.by)Q[G]=v[G]??null;const{value:J}=v;B.push({key:Q,value:J==null?null:Number(J)})}return B},async insert(e,n,s){const f=V(e,"insert");if(f)return ut(f,e,n,s,!0);const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const u=Gt(h,n,Z);et(h,u);let c;s?.clientId!==void 0?(ho(s.clientId),c=s.clientId):s?.allowExplicitId&&typeof u._id=="string"?c=u._id:c=M();const l=s?.allowExplicitId&&typeof u._creationTime=="number"?u._creationTime:C(),w={...u,...E(e),_creationTime:l,_id:c};return ee(e,"before","insert")&&await te("before","insert",{doc:{...w},id:c,op:"insert",table:e}),he(e),we(e),it(r,e,ro(e),[c,l,ce(w)]),yt(e,c,w),ee(e,"after","insert")&&await te("after","insert",{doc:w,id:c,op:"insert",table:e}),await O({doc:w,id:c,op:"insert",table:e}),c},async insertManyUnsafe(e,n,s){if(ae(n.length,s?.limit,"insertManyUnsafe"),n.length===0)return[];const f=V(e,"insert");if(f){const l=[];for(const w of n)W(w);for(const w of n){const T=await f.insert(e,w,{allowExplicitId:s?.allowExplicitId});a({key:T,op:"insert",row:{...w,_id:T},table:e}),l.push(T)}return l}const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);he(e),we(e);const u=[];for(let l=0;l<n.length;l+=qe)u.push(E(e));const c=n.map((l,w)=>{const T=Gt(h,l,Z),g=s?.allowExplicitId===!0&&typeof T._id=="string"?T._id:M(),b=s?.allowExplicitId===!0&&typeof T._creationTime=="number"?T._creationTime:C(),x={...T,...u[Math.floor(w/qe)],_creationTime:b,_id:g};return{creationTime:b,document:x,id:g}});for(const l of c)W(l.document);for(let l=0;l<c.length;l+=qe){const w=i.join(c.slice(l,l+qe).map(g=>i`(${g.id}, ${g.creationTime}, ${ce(g.document)})`),i`, `),T=Qt("sqlite",i`INSERT INTO ${i.identifier(e)} (id, _creationTime, ${i.identifier(oe)}) VALUES ${w}`);it(r,e,T.sql,T.params)}for(const{document:l,id:w}of c)yt(e,w,l),await q({doc:l,id:w,op:"insert",table:e});return c.map(l=>l.id)},async insertMany(e,n,s){ae(n.length,s?.limit,"insertMany");const f=s?.skipDuplicates===!0,h=[],u=V(e,"insert");if(u)for(const l of n)W(l);const c=async l=>u?ut(u,e,l,void 0,!1):U.insert(e,l);for(const l of n)try{h.push(await c(l))}catch(w){if(f&&w instanceof Ee&&w.kind==="unique")h.push(null);else throw w}return h},normalizeId(e,n){return Pt(t,e,n)},async patch(e,n,s){const f=se(e,s);if(!f){const T=ge(s);if(T){W(n),await T.patch(e,n,s);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:u,tableName:c}=f,l=t.tables[c];if(!l)throw new $("INTERNAL",`unknown table: ${c}`);R(c,e),Ot("patch",n);const w={...u,...n,...E(c),_id:e};Ht(l,n,w,Z),et(l,w,!0),ee(c,"before","update")&&await te("before","update",{doc:{...w},id:e,op:"update",previous:u,table:c}),he(c),we(c),Be(r,c,Ft(c),[ce(w),e,h]),Ie(c,e,w,u),ve(c,e,w),Ae(c,u,w),pe(c,e,u,w),m?.invalidate(c,e,S(c,u,w)),fe(c,e,"update",w),a({indexKeys:S(c,u,w),key:e,op:"update",row:w,table:c}),ee(c,"after","update")&&await te("after","update",{doc:w,id:e,op:"update",previous:u,table:c}),await O({doc:w,id:e,op:"update",table:c})},async patchMany(e,n,s){ae(e.length,n?.limit,"patchMany");for(const f of e)await U.patch(f.id,f.patch,s);return{patched:e.length}},async patchWhere(e,n,s){const u=(await(V(e,"patchWhere")??U).findMany(e,{where:n.where})).page.map(c=>({id:String(c._id),patch:n.patch}));if(ae(u.length,s?.limit,"patchWhere"),U.patchMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await U.patchMany(u,s),{patched:u.length}},query(e){const n=V(e,"query");return n?(R(e,H),n.query(e)):qo(r,t,e,k,s=>{s?j(s):R(e,H)},s=>{D||_?.recordRead(s)})},async rank(e,n,s){const f=V(e,"rank");if(f)return R(e,H),f.rank(e,n,s);k(e,n,"rank");const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const u=h.rankIndexes?.find(G=>G.name===n);if(!u)throw new $("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(Et(e,h,u),s.restrictsCounts)throw new Ye(e);R(e,H),Qe(e,u);const c=typeof s.row=="string"?s.row:s.row._id;if(!c)return null;const l=vt(e,u.name),w=u.sortBy.map((G,Ce)=>It(Ce)),T=w.map(G=>_e(G)).join(", "),g=N(r,i`SELECT ${i.identifier("__partition__")}, ${i.raw(T)} FROM ${i.identifier(l)} WHERE ${i.identifier("__id__")} = ${c}`).toArray(),[b]=g;if(b===void 0)return null;let x=b.__partition__;const P=z(s.baseWhere,s.where);Ze(P,t,e,"rank");const B=kn(u,P);if(B){const G=Fn(u.partitionBy??[],B);if(G!==x)return null;x=G}const v=w.map(G=>b[G]),{before:Q,total:J}=Nt(r,l,w,u.sortBy,x,v,c);return{position:Q+1,total:J}},async rankBefore(e,n,s){if(ie(e))throw new $("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(w=>w.name===n);if(!h)throw new $("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(s.restrictsCounts)throw new Ye(e);R(e,H),Qe(e,h);const u=vt(e,h.name),c=h.sortBy.map((w,T)=>It(T)),l=h.sortBy.map((w,T)=>re(s.sortValues[T]??null));return Nt(r,u,c,h.sortBy,s.partitionKey,l,s.rowId)},async rankPage(e,n,s={}){Ze(z(s.baseWhere,s.where),t,e,"rankPage");const f=V(e,"rankPage");if(f)return R(e,H),f.rankPage(e,n,s);k(e,n,"rank");const{continueCursor:h,hasMore:u,rows:c}=Rt(St,e,n,s);return{continueCursor:h,isDone:!u,page:c.map(l=>l.doc)}},async rankPageRows(e,n,s={}){Ze(z(s.baseWhere,s.where),t,e,"rankPage"),k(e,n,"rank");const{directions:f,hasMore:h,rows:u}=Rt(St,e,n,s);return{directions:f,hasMore:h,rows:u}},async restore(e,n){const s=se(e,n);if(!s){const u=ge(n);if(u?.restore){await u.restore(e,n);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const f=t.tables[s.tableName]?.softDeleteMode?.field;if(!f)throw new $("INTERNAL",`ctx.db.restore: table "${s.tableName}" is not a .softDelete() table`);const h=s.row[f]!==null&&s.row[f]!==void 0;await U.patch(e,{[f]:null},n),h&&pe(s.tableName,e,void 0,s.row)},async replace(e,n,s,f){const h=se(e,s);if(!h){const b=ge(s);if(b){W(n),await b.replace(e,n,s,f);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:u,row:c,tableName:l}=h,w=t.tables[l];if(!w)throw new $("INTERNAL",`unknown table: ${l}`);Ot("replace",n);const T=f?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:C(),g={...n,...E(l),_creationTime:T,_id:e};Ht(w,n,g,Z),et(w,g),ee(l,"before","update")&&await te("before","update",{doc:{...g},id:e,op:"update",previous:c,table:l}),he(l),we(l),Be(r,l,io(l),[T,ce(g),e,u]),Ie(l,e,g,c),ve(l,e,g),Ae(l,c,g),pe(l,e,c,g),m?.invalidate(l,e,S(l,c,g)),fe(l,e,"update",g),a({indexKeys:S(l,c,g),key:e,op:"update",row:g,table:l}),ee(l,"after","update")&&await te("after","update",{doc:g,id:e,op:"update",previous:c,table:l}),await O({doc:g,id:e,op:"update",table:l})},async wipeShard(e){const n=new Set(e?.exclude),s=e?.tables,f=Object.entries(t.tables).filter(([l,w])=>n.has(l)||s!==void 0&&!s.includes(l)?!1:w.shardMode?.kind!=="global").map(([l])=>l);if(s!==void 0){for(const l of s)if(!t.tables[l])throw new $("INTERNAL",`wipeShard: unknown table: ${l}`)}const h={};let u=0;const{deleteAll:c}=U;if(c===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of f){const w=await c(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[l]=w.deleted,u+=w.deleted}return{deleted:u,tables:h}}},dn={db:U,scheduler:L};return o.enforceRls===!0?Hn(U,t,(e,n)=>se(e,n)?.tableName,(e,n)=>an(e,n)):U};export{Ir as CDC_LOG_TABLE,Nr as CLIENT_WATERMARK_TABLE,zr as GLOBAL_SHAPE_SNAPSHOT_TABLE,ni as IDEMPOTENCY_TABLE,Lo as NotUniqueError,di as SEARCH_STATE_TABLE,jr as advanceClientWatermark,Cr as applyCdcChanges,Ot as assertNoExplicitUndefined,ho as assertValidClientId,Rr as backfillAggregateIndexes,Tr as backfillRankIndexes,Ar as backfillSearchIndexes,xr as bumpCdcEpoch,br as cdcCanVouchFor,Mr as cdcSeqLeavingRows,Dr as cdcTouchesTables,Lr as cdcTrimmedError,kr as compactCdcDocs,mr as createShardCtxDb,Fr as cursorBelowRetainedFloor,Jr as deleteGlobalShapeSnapshot,Yr as deleteGlobalShapeSnapshotsForConnection,Kr as migrateClientWatermark,Xr as migrateGlobalShapeSnapshot,qr as minCdcReplayableSeq,Br as minCdcSeq,Pt as normalizeIdStructurally,Wr as readCdcChangeKeys,Ur as readCdcChanges,Pr as readCdcCursor,Gr as readCdcEpoch,Qr as readClientWatermark,Zr as readGlobalShapeSnapshot,oi as readIdempotent,ci as runShardMigrations,ui as selectShapeMembers,fi as selectShapeRows,Hr as trimCdcChanges,ri as trimIdempotent,ei as writeGlobalShapeSnapshot,ii as writeIdempotent};
@@ -1 +1 @@
1
- import{sql as s}from"drizzle-orm";import{matchesStaticWhere as f}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{compareStrings as l}from"./aggregateTableName-BvenuaDR.mjs";import{serializeSqlValue as d}from"./serializeSqlValue-B_-zaEWZ.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};
1
+ import{sql as s}from"drizzle-orm";import{matchesStaticWhere as f}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{compareStrings as l}from"./aggregateTableName-C7o-gpms.mjs";import{serializeSqlValue as d}from"./serializeSqlValue-B_-zaEWZ.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};
@@ -1 +1 @@
1
- import{stableWireKey as y}from"./stableWireKey-DQZmSvS2.mjs";import{depKey as b,SCAN_DEP as p}from"./SCAN_DEP-D7qE3iUe.mjs";import{e as m}from"./estimate-bytes-DKqVDdZQ.mjs";import{keysTouchRanges as x}from"./buildIndexRange-CBKQmHSS.mjs";import{stableStringify as K}from"./stableStringify-DibjylKD.mjs";const l=(o,t,s)=>{let e=o.get(t);return e===void 0&&(e=s(),o.set(t,e)),e},v=1e3,E=4*1024*1024;class A{entries=new Map;tableIndex=new Map;rangeIndex=new Map;totalBytes=0;hits=0;misses=0;evictions=0;maxEntries;maxBytes;now;monotonic=0;generation=0;constructor(t={}){this.maxEntries=t.maxEntries??v,this.maxBytes=t.maxBytes??E,this.now=t.now??(()=>(this.monotonic+=1,this.monotonic))}async run(t,s,e,i=()=>[]){const n=this.entries.get(t);if(n)return this.hits+=1,n.lastUsed=this.now(),this.entries.delete(t),this.entries.set(t,n),n.result;this.misses+=1;const c=this.generation,a=await e();if(this.generation!==c)return a;const h=m(a);if(h===void 0)return a;const f=i(),u={bytes:h,deps:s,ranges:f,lastUsed:this.now(),result:a,subscribers:new Set},d=this.entries.get(t);if(d){this.dropEntry(t,d);for(const r of d.subscribers)u.subscribers.add(r)}this.entries.set(t,u),this.totalBytes+=h;for(const r of s)l(this.tableIndex,r,()=>new Set).add(t);for(const r of f){const g=l(this.rangeIndex,r.table,()=>new Map);l(g,r,()=>new Set).add(t)}return this.evict(),a}invalidate(t,s,e){this.generation+=1;const i=[];return this.collectAndDrop(b(t,s),i),this.collectAndDrop(b(t,p),i),this.dropRangeDeps(t,e,i),i}invalidateTable(t){this.generation+=1;const s=[],e=`${t}:`;for(const i of this.tableIndex.keys())i.startsWith(e)&&this.collectAndDrop(i,s);return this.dropRangeDeps(t,void 0,s),s}subscribe(t,s){const e=this.entries.get(t);e&&e.subscribers.add(s)}unsubscribe(t,s){const e=this.entries.get(t);e&&e.subscribers.delete(s)}size(){return{bytes:this.totalBytes,entries:this.entries.size}}clear(){this.generation+=1,this.entries.clear(),this.tableIndex.clear(),this.rangeIndex.clear(),this.totalBytes=0}subscribers(t){const s=this.entries.get(t);return s?[...s.subscribers]:[]}stats(){return{bytes:this.totalBytes,entries:this.entries.size,evictions:this.evictions,hits:this.hits,misses:this.misses}}dropRangeDeps(t,s,e){const i=this.rangeIndex.get(t);if(!(!i||i.size===0))for(const[n,c]of i)x([n],s)&&this.dropKeys(c,e)}collectAndDrop(t,s){const e=this.tableIndex.get(t);e&&this.dropKeys(e,s)}dropKeys(t,s){for(const e of t){const i=this.entries.get(e);i&&(this.dropEntry(e,i),s.push(e))}}dropEntry(t,s){this.entries.delete(t),this.totalBytes-=s.bytes;for(const e of s.deps){const i=this.tableIndex.get(e);i&&(i.delete(t),i.size===0&&this.tableIndex.delete(e))}for(const e of s.ranges){const i=this.rangeIndex.get(e.table),n=i?.get(e);n?.delete(t),i&&n?.size===0&&(i.delete(e),i.size===0&&this.rangeIndex.delete(e.table))}}evict(){if(!(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes))for(const[t,s]of this.entries){if(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes)return;s.subscribers.size>0||(this.dropEntry(t,s),this.evictions+=1)}}}const D=(o,t,s)=>`${s??"\0anon"}\0${o}:${y(t)}`;export{A as ReactiveCache,D as reactiveCacheKey,K as stableStringify,y as stableWireKey};
1
+ import{stableWireKey as y}from"./stableWireKey-D2US4k_J.mjs";import{depKey as b,SCAN_DEP as p}from"./SCAN_DEP-D7qE3iUe.mjs";import{e as m}from"./estimate-bytes-DKqVDdZQ.mjs";import{keysTouchRanges as x}from"./buildIndexRange-CBKQmHSS.mjs";import{stableStringify as K}from"./stableStringify-DibjylKD.mjs";const l=(o,t,s)=>{let e=o.get(t);return e===void 0&&(e=s(),o.set(t,e)),e},v=1e3,E=4*1024*1024;class A{entries=new Map;tableIndex=new Map;rangeIndex=new Map;totalBytes=0;hits=0;misses=0;evictions=0;maxEntries;maxBytes;now;monotonic=0;generation=0;constructor(t={}){this.maxEntries=t.maxEntries??v,this.maxBytes=t.maxBytes??E,this.now=t.now??(()=>(this.monotonic+=1,this.monotonic))}async run(t,s,e,i=()=>[]){const n=this.entries.get(t);if(n)return this.hits+=1,n.lastUsed=this.now(),this.entries.delete(t),this.entries.set(t,n),n.result;this.misses+=1;const c=this.generation,a=await e();if(this.generation!==c)return a;const h=m(a);if(h===void 0)return a;const f=i(),u={bytes:h,deps:s,ranges:f,lastUsed:this.now(),result:a,subscribers:new Set},d=this.entries.get(t);if(d){this.dropEntry(t,d);for(const r of d.subscribers)u.subscribers.add(r)}this.entries.set(t,u),this.totalBytes+=h;for(const r of s)l(this.tableIndex,r,()=>new Set).add(t);for(const r of f){const g=l(this.rangeIndex,r.table,()=>new Map);l(g,r,()=>new Set).add(t)}return this.evict(),a}invalidate(t,s,e){this.generation+=1;const i=[];return this.collectAndDrop(b(t,s),i),this.collectAndDrop(b(t,p),i),this.dropRangeDeps(t,e,i),i}invalidateTable(t){this.generation+=1;const s=[],e=`${t}:`;for(const i of this.tableIndex.keys())i.startsWith(e)&&this.collectAndDrop(i,s);return this.dropRangeDeps(t,void 0,s),s}subscribe(t,s){const e=this.entries.get(t);e&&e.subscribers.add(s)}unsubscribe(t,s){const e=this.entries.get(t);e&&e.subscribers.delete(s)}size(){return{bytes:this.totalBytes,entries:this.entries.size}}clear(){this.generation+=1,this.entries.clear(),this.tableIndex.clear(),this.rangeIndex.clear(),this.totalBytes=0}subscribers(t){const s=this.entries.get(t);return s?[...s.subscribers]:[]}stats(){return{bytes:this.totalBytes,entries:this.entries.size,evictions:this.evictions,hits:this.hits,misses:this.misses}}dropRangeDeps(t,s,e){const i=this.rangeIndex.get(t);if(!(!i||i.size===0))for(const[n,c]of i)x([n],s)&&this.dropKeys(c,e)}collectAndDrop(t,s){const e=this.tableIndex.get(t);e&&this.dropKeys(e,s)}dropKeys(t,s){for(const e of t){const i=this.entries.get(e);i&&(this.dropEntry(e,i),s.push(e))}}dropEntry(t,s){this.entries.delete(t),this.totalBytes-=s.bytes;for(const e of s.deps){const i=this.tableIndex.get(e);i&&(i.delete(t),i.size===0&&this.tableIndex.delete(e))}for(const e of s.ranges){const i=this.rangeIndex.get(e.table),n=i?.get(e);n?.delete(t),i&&n?.size===0&&(i.delete(e),i.size===0&&this.rangeIndex.delete(e.table))}}evict(){if(!(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes))for(const[t,s]of this.entries){if(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes)return;s.subscribers.size>0||(this.dropEntry(t,s),this.evictions+=1)}}}const D=(o,t,s)=>`${s??"\0anon"}\0${o}:${y(t)}`;export{A as ReactiveCache,D as reactiveCacheKey,K as stableStringify,y as stableWireKey};
@@ -1 +1 @@
1
- import{stableWireKey as o}from"./stableWireKey-DQZmSvS2.mjs";const s=r=>r.map(e=>`${String(e.length)}:${e}`).join(""),c=r=>o(r.effectiveWhere??null),g=(r,e,t)=>s([r,String(e),String(t)]),h=(r,e)=>{try{return s([c(r),e])}catch{return}};class d{keyScans=new Map;memberProbes=new Map;run=0;served=0;get probesRun(){return this.run}get probesServed(){return this.served}changedKeys(e,t){return this.getOrLoad(this.keyScans,e,t)}members(e,t,n){return this.getOrLoad(this.memberProbes,h(e,t),n)}getOrLoad(e,t,n){if(t!==void 0){const a=e.get(t);if(a!==void 0)return this.served+=1,a}this.run+=1;const i=n();return t!==void 0&&e.set(t,i),i}}const p=()=>new d,b=(r,e)=>{try{return s([r.table,c(r),o({identity:e.identity,userId:e.userId})])}catch{return}};export{d as ShapeDiffCache,p as createShapeDiffCache,b as globalShapeReadKey,g as shapeRangeKey};
1
+ import{stableWireKey as o}from"./stableWireKey-D2US4k_J.mjs";const s=r=>r.map(e=>`${String(e.length)}:${e}`).join(""),c=r=>o(r.effectiveWhere??null),g=(r,e,t)=>s([r,String(e),String(t)]),h=(r,e)=>{try{return s([c(r),e])}catch{return}};class d{keyScans=new Map;memberProbes=new Map;run=0;served=0;get probesRun(){return this.run}get probesServed(){return this.served}changedKeys(e,t){return this.getOrLoad(this.keyScans,e,t)}members(e,t,n){return this.getOrLoad(this.memberProbes,h(e,t),n)}getOrLoad(e,t,n){if(t!==void 0){const a=e.get(t);if(a!==void 0)return this.served+=1,a}this.run+=1;const i=n();return t!==void 0&&e.set(t,i),i}}const p=()=>new d,b=(r,e)=>{try{return s([r.table,c(r),o({identity:e.identity,userId:e.userId})])}catch{return}};export{d as ShapeDiffCache,p as createShapeDiffCache,b as globalShapeReadKey,g as shapeRangeKey};
@@ -1 +1 @@
1
- import{LunoraError as g}from"@lunora/errors";import{e as i}from"./wire-codec-CKV-4MEN.mjs";const a=BigInt(Number.MAX_SAFE_INTEGER),c=(e,t)=>e<t?-1:e>t?1:0,m=(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{m as aggregateTableName,l as coerceAggregateNumber,c as compareStrings,A as encodeAggregateKey,v as foldAggregateTally,d as readAggregateValue};
1
+ import{LunoraError as g}from"@lunora/errors";import{e as i}from"./wire-codec-C-FpWm52.mjs";const a=BigInt(Number.MAX_SAFE_INTEGER),c=(e,t)=>e<t?-1:e>t?1:0,m=(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{m as aggregateTableName,l as coerceAggregateNumber,c as compareStrings,A as encodeAggregateKey,v as foldAggregateTally,d as readAggregateValue};
@@ -1 +1 @@
1
- import{LunoraError as D}from"@lunora/errors";import{applySelect as I}from"./CURSOR_PREFIX-D8c7Ccj3.mjs";const W=Symbol.for("lunora.relations.fanOutBudget"),U=o=>({fanOutBudget:o[W],relationBaseWhere:o.relationBaseWhere,relationMask:o.relationMask}),A=(o,n)=>n.select?I(o,n.select,n.with):o,x=async(o,n,r,a,t)=>{const l=await Promise.all(a.map(async i=>{const h=t?{AND:[{[r]:i},t]}:{[r]:i};return[i,await o(n,h)]}));return new Map(l)},S=32,C=(o,n,r)=>{const a=new Map;for(const t of o)for(const l of r(t)){const i=l[n],h=a.get(i);h?h.push(l):a.set(i,[l])}return a},_=(o,n)=>({...o,[W]:n}),B=(o,n)=>{const r=new Set;for(const a of o){const t=a[n];t!=null&&r.add(t)}return[...r]},H=async o=>{const{groupedCounter:n,fanOutBudget:r,fetcher:a,parents:t,relationBaseWhere:l,relationMask:i,schema:h,tableName:m,with:v}=o,w=r??{remaining:S},k=(c,e)=>i?.(c,e)??e;if(t.length===0)return;const N=h.tables[m];if(!N)throw new D("INTERNAL",`unknown table: ${m}`);const O=N.relationMap??{},R=c=>{const e=O[c];if(!e)throw new D("INTERNAL",`unknown relation "${c}" on table "${m}"`);return e},V=async(c,e,s)=>{const u=B(t,e.field);if(u.length===0){for(const d of t)d[c]=null;return}const{page:p}=await a(e.table,_({baseWhere:l?.(e.table),relationBaseWhere:l,relationMask:i,where:{[e.references]:{in:u}},with:s.with},w)),b=new Map;for(const d of k(e.table,p))b.set(d[e.references],d);for(const d of t){const y=b.get(d[e.field]);d[c]=y?A([y],s)[0]??null:null}},$=async(c,e,s)=>{const u=B(t,e.references);if(u.length===0){for(const f of t)f[c]=[];return}const p=typeof s.limit=="number"?Math.max(0,Math.floor(s.limit)):void 0,b=async(f,g)=>{const{page:E}=await a(e.table,_({baseWhere:l?.(e.table),limit:g,orderBy:s.orderBy,relationBaseWhere:l,relationMask:i,where:s.where?{AND:[s.where,f]}:f,with:s.with},w));return E};if(p===0){for(const f of t)f[c]=[];return}const d=p!==void 0&&u.length<=w.remaining;d&&(w.remaining-=u.length);const y=d?await Promise.all(u.map(async f=>b({[e.field]:f},p))):[await b({[e.field]:{in:u}},void 0)],M=C(y,e.field,f=>k(e.table,f));for(const f of t){const g=M.get(f[e.references])??[];f[c]=A(p===void 0?g:g.slice(0,p),s)}},j=async c=>{for(const e of Object.keys(c)){const s=R(e),[u,p]=s.kind==="many"?[s.field,s.references]:[s.references,s.field],b=l?.(s.table),d=B(t,p),y=d.length===0?new Map:await n(s.table,u,d,b);for(const M of t){const f=M._count??{},g=M[p];f[e]=g==null?0:y.get(g)??0,M._count=f}}};for(const[c,e]of Object.entries(v)){if(e===void 0||e===!1)continue;if(c==="_count"){await j(e);continue}const s=R(c),u=e===!0?{}:e;await(s.kind==="one"?V(c,s,u):$(c,s,u))}},F=async(o,n,r)=>{const{deletedId:a,deletedReference:t,findHolders:l,onCascade:i,onRestrict:h,onSetNull:m,tableName:v}=o,w=r.references==="_id"?a:t(r.references);if(w==null)return;const k=await l(n,r.field,w);if(k.length!==0){r.onDelete==="restrict"&&h(`cannot delete "${v}" row: "${n}.${r.field}" still references it`);for(const N of k){const O=N._id;typeof O=="string"&&await(r.onDelete==="cascade"?i(n,O):m(n,O,r.field))}}},P=async o=>{const{schema:n,tableName:r}=o;if(!n.tables[r])throw new D("INTERNAL",`unknown table: ${r}`);for(const[a,t]of Object.entries(n.tables)){const l=t.relationMap;if(l)for(const i of Object.values(l))i.kind!=="one"||i.table!==r||!i.onDelete||await F(o,a,i)}},q=(o,n,r=!1)=>{for(const[a,t]of Object.entries(o.shape))a in n&&typeof t.parse=="function"&&(r&&n[a]===null&&t.kind==="optional"||t.parse(n[a]))};export{P as applyOnDelete,B as distinctValues,x as fanOutScalarCounts,U as relationHooks,H as resolveWith,q as runRowValidators};
1
+ import{LunoraError as D}from"@lunora/errors";import{applySelect as I}from"./CURSOR_PREFIX-qn6nNVS7.mjs";const W=Symbol.for("lunora.relations.fanOutBudget"),U=o=>({fanOutBudget:o[W],relationBaseWhere:o.relationBaseWhere,relationMask:o.relationMask}),A=(o,n)=>n.select?I(o,n.select,n.with):o,x=async(o,n,r,a,t)=>{const l=await Promise.all(a.map(async i=>{const h=t?{AND:[{[r]:i},t]}:{[r]:i};return[i,await o(n,h)]}));return new Map(l)},S=32,C=(o,n,r)=>{const a=new Map;for(const t of o)for(const l of r(t)){const i=l[n],h=a.get(i);h?h.push(l):a.set(i,[l])}return a},_=(o,n)=>({...o,[W]:n}),B=(o,n)=>{const r=new Set;for(const a of o){const t=a[n];t!=null&&r.add(t)}return[...r]},H=async o=>{const{groupedCounter:n,fanOutBudget:r,fetcher:a,parents:t,relationBaseWhere:l,relationMask:i,schema:h,tableName:m,with:v}=o,w=r??{remaining:S},k=(c,e)=>i?.(c,e)??e;if(t.length===0)return;const N=h.tables[m];if(!N)throw new D("INTERNAL",`unknown table: ${m}`);const O=N.relationMap??{},R=c=>{const e=O[c];if(!e)throw new D("INTERNAL",`unknown relation "${c}" on table "${m}"`);return e},V=async(c,e,s)=>{const u=B(t,e.field);if(u.length===0){for(const d of t)d[c]=null;return}const{page:p}=await a(e.table,_({baseWhere:l?.(e.table),relationBaseWhere:l,relationMask:i,where:{[e.references]:{in:u}},with:s.with},w)),b=new Map;for(const d of k(e.table,p))b.set(d[e.references],d);for(const d of t){const y=b.get(d[e.field]);d[c]=y?A([y],s)[0]??null:null}},$=async(c,e,s)=>{const u=B(t,e.references);if(u.length===0){for(const f of t)f[c]=[];return}const p=typeof s.limit=="number"?Math.max(0,Math.floor(s.limit)):void 0,b=async(f,g)=>{const{page:E}=await a(e.table,_({baseWhere:l?.(e.table),limit:g,orderBy:s.orderBy,relationBaseWhere:l,relationMask:i,where:s.where?{AND:[s.where,f]}:f,with:s.with},w));return E};if(p===0){for(const f of t)f[c]=[];return}const d=p!==void 0&&u.length<=w.remaining;d&&(w.remaining-=u.length);const y=d?await Promise.all(u.map(async f=>b({[e.field]:f},p))):[await b({[e.field]:{in:u}},void 0)],M=C(y,e.field,f=>k(e.table,f));for(const f of t){const g=M.get(f[e.references])??[];f[c]=A(p===void 0?g:g.slice(0,p),s)}},j=async c=>{for(const e of Object.keys(c)){const s=R(e),[u,p]=s.kind==="many"?[s.field,s.references]:[s.references,s.field],b=l?.(s.table),d=B(t,p),y=d.length===0?new Map:await n(s.table,u,d,b);for(const M of t){const f=M._count??{},g=M[p];f[e]=g==null?0:y.get(g)??0,M._count=f}}};for(const[c,e]of Object.entries(v)){if(e===void 0||e===!1)continue;if(c==="_count"){await j(e);continue}const s=R(c),u=e===!0?{}:e;await(s.kind==="one"?V(c,s,u):$(c,s,u))}},F=async(o,n,r)=>{const{deletedId:a,deletedReference:t,findHolders:l,onCascade:i,onRestrict:h,onSetNull:m,tableName:v}=o,w=r.references==="_id"?a:t(r.references);if(w==null)return;const k=await l(n,r.field,w);if(k.length!==0){r.onDelete==="restrict"&&h(`cannot delete "${v}" row: "${n}.${r.field}" still references it`);for(const N of k){const O=N._id;typeof O=="string"&&await(r.onDelete==="cascade"?i(n,O):m(n,O,r.field))}}},P=async o=>{const{schema:n,tableName:r}=o;if(!n.tables[r])throw new D("INTERNAL",`unknown table: ${r}`);for(const[a,t]of Object.entries(n.tables)){const l=t.relationMap;if(l)for(const i of Object.values(l))i.kind!=="one"||i.table!==r||!i.onDelete||await F(o,a,i)}},q=(o,n,r=!1)=>{for(const[a,t]of Object.entries(o.shape))a in n&&typeof t.parse=="function"&&(r&&n[a]===null&&t.kind==="optional"||t.parse(n[a]))};export{P as applyOnDelete,B as distinctValues,x as fanOutScalarCounts,U as relationHooks,H as resolveWith,q as runRowValidators};
@@ -1 +1 @@
1
- import{stableStringify as m}from"./stableStringify-DibjylKD.mjs";import{i as A,e as w,n as J}from"./wire-codec-CKV-4MEN.mjs";const D="_id",p="_creationTime",y="page",_=e=>{let t;for(const s of e){const o=s[p];if(typeof o=="number"){if(t!==void 0){if(o<t)return!0;if(o>t)return!1}t=o}}return!1},F=(e,t)=>{const s=t[p];if(typeof s!="number")return e.length;const o=_(e);for(const[n,r]of e.entries()){const i=r[p];if(typeof i=="number"&&(o?i<s:i>s))return n}return e.length},L="__lunora__",E=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return;const t=e[D];return typeof t=="string"?t:void 0},I=e=>{const t=new Map,s=[];for(const o of e){const n=E(o);if(n===void 0||t.has(n))return;t.set(n,o),s.push(n)}return{byId:t,order:s}},N=(e,t)=>{const s=e.order.filter(n=>t.byId.has(n)),o=t.order.filter(n=>e.byId.has(n));return s.length!==o.length?!1:s.every((n,r)=>o[r]===n)},R=(e,t,s,o)=>{const n=[];for(const r of e.order)t.byId.has(r)||n.push({delta:{key:r,op:"delete",table:s},frame:`{"key":${JSON.stringify(r)},"op":"delete","table":${o}}`});return n},P=(e,t,s,o)=>{const n=[];for(const r of t.order){const i=t.byId.get(r),a=e.byId.get(r),d=JSON.stringify(J(i)?w(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},T=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return{next:t,previous:e};if(!A(e)||!A(t))return;const s=e[y],o=t[y];if(!Array.isArray(s)||!Array.isArray(o))return;const n=r=>Object.fromEntries(Object.entries(r).filter(([i])=>i!==y));if(m(n(e))===m(w(n(t))))return{next:o,previous:s}},k=(e,t,s)=>{const o=s.filter(({delta:r})=>r.op==="insert");if(o.length===0)return!0;const n=e.order.filter(r=>t.byId.has(r)).map(r=>e.byId.get(r));for(const{delta:r}of o){const i=r.row;n.splice(F(n,i),0,i)}return n.length===t.order.length&&n.every((r,i)=>r[D]===t.order[i])},O=(e,t,s)=>{let o;try{o=JSON.parse(e)}catch{return}const n=T(o,t);if(n===void 0)return;const r=I(n.previous),i=I(n.next);if(r===void 0||i===void 0||!N(r,i))return;const a=s===""?L:s,d=JSON.stringify(a),c=[...R(r,i,a,d),...P(r,i,a,d)];return k(r,i,c)?c:void 0},W=(e,t,s,o)=>{const n=O(e,t,s);if(n!==void 0){if(o!==void 0)for(const{frame:r}of n)o.push(r);return n.map(({delta:r})=>r)}},C=(e,t)=>{try{return e.send(t),!0}catch{return!1}},K=e=>{const{cursorSuffix:t,lastMutationId:s,nextResult:o,pageDeltas:n,previousJson:r,snapshotJson:i,subId:a,table:d}=e,c=JSON.stringify(a),f=s===void 0?"":`,"lastMutationId":${String(s)}`,g=f+t,l=`{"type":"data","id":${c},"data":${i}${g}}`,u=r!==void 0&&(n===!0||Array.isArray(o))?O(r,o,d):void 0;if(u===void 0||u.length===0)return[l];const v=[];let b=0;for(const[$,{frame:x}]of u.entries()){const S=$===u.length-1,h=`{"type":"delta","id":${c},"delta":${x}${S?g:f}}`;if(b+=h.length,b>=l.length)return[l];v.push(h)}return v},G=async e=>{let t=0;for(;t<100;){t+=1;const{bufferedAmount:s}=e;if(typeof s!="number"||s<1048576)return;await new Promise(o=>{setTimeout(o,20)})}};export{G as awaitWsDrain,K as subscriptionFrames,W as subscriptionListDeltas,C as trySendFrame};
1
+ import{stableStringify as m}from"./stableStringify-DibjylKD.mjs";import{i as A,e as w,n as J}from"./wire-codec-C-FpWm52.mjs";const D="_id",p="_creationTime",y="page",_=e=>{let t;for(const s of e){const o=s[p];if(typeof o=="number"){if(t!==void 0){if(o<t)return!0;if(o>t)return!1}t=o}}return!1},F=(e,t)=>{const s=t[p];if(typeof s!="number")return e.length;const o=_(e);for(const[n,r]of e.entries()){const i=r[p];if(typeof i=="number"&&(o?i<s:i>s))return n}return e.length},L="__lunora__",E=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return;const t=e[D];return typeof t=="string"?t:void 0},I=e=>{const t=new Map,s=[];for(const o of e){const n=E(o);if(n===void 0||t.has(n))return;t.set(n,o),s.push(n)}return{byId:t,order:s}},N=(e,t)=>{const s=e.order.filter(n=>t.byId.has(n)),o=t.order.filter(n=>e.byId.has(n));return s.length!==o.length?!1:s.every((n,r)=>o[r]===n)},R=(e,t,s,o)=>{const n=[];for(const r of e.order)t.byId.has(r)||n.push({delta:{key:r,op:"delete",table:s},frame:`{"key":${JSON.stringify(r)},"op":"delete","table":${o}}`});return n},P=(e,t,s,o)=>{const n=[];for(const r of t.order){const i=t.byId.get(r),a=e.byId.get(r),d=JSON.stringify(J(i)?w(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},T=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return{next:t,previous:e};if(!A(e)||!A(t))return;const s=e[y],o=t[y];if(!Array.isArray(s)||!Array.isArray(o))return;const n=r=>Object.fromEntries(Object.entries(r).filter(([i])=>i!==y));if(m(n(e))===m(w(n(t))))return{next:o,previous:s}},k=(e,t,s)=>{const o=s.filter(({delta:r})=>r.op==="insert");if(o.length===0)return!0;const n=e.order.filter(r=>t.byId.has(r)).map(r=>e.byId.get(r));for(const{delta:r}of o){const i=r.row;n.splice(F(n,i),0,i)}return n.length===t.order.length&&n.every((r,i)=>r[D]===t.order[i])},O=(e,t,s)=>{let o;try{o=JSON.parse(e)}catch{return}const n=T(o,t);if(n===void 0)return;const r=I(n.previous),i=I(n.next);if(r===void 0||i===void 0||!N(r,i))return;const a=s===""?L:s,d=JSON.stringify(a),c=[...R(r,i,a,d),...P(r,i,a,d)];return k(r,i,c)?c:void 0},W=(e,t,s,o)=>{const n=O(e,t,s);if(n!==void 0){if(o!==void 0)for(const{frame:r}of n)o.push(r);return n.map(({delta:r})=>r)}},C=(e,t)=>{try{return e.send(t),!0}catch{return!1}},K=e=>{const{cursorSuffix:t,lastMutationId:s,nextResult:o,pageDeltas:n,previousJson:r,snapshotJson:i,subId:a,table:d}=e,c=JSON.stringify(a),f=s===void 0?"":`,"lastMutationId":${String(s)}`,g=f+t,l=`{"type":"data","id":${c},"data":${i}${g}}`,u=r!==void 0&&(n===!0||Array.isArray(o))?O(r,o,d):void 0;if(u===void 0||u.length===0)return[l];const v=[];let b=0;for(const[$,{frame:x}]of u.entries()){const S=$===u.length-1,h=`{"type":"delta","id":${c},"delta":${x}${S?g:f}}`;if(b+=h.length,b>=l.length)return[l];v.push(h)}return v},G=async e=>{let t=0;for(;t<100;){t+=1;const{bufferedAmount:s}=e;if(typeof s!="number"||s<1048576)return;await new Promise(o=>{setTimeout(o,20)})}};export{G as awaitWsDrain,K as subscriptionFrames,W as subscriptionListDeltas,C as trySendFrame};
@@ -1 +1 @@
1
- import{m as O,c as T,l as b,r as E,a as C,w as L}from"./ctx-db-search-state-ruTuCsxa.mjs";import{S as R,r as M,i as x,l as h,y as _,d as y}from"./ctx-db-companions-Z9JQ9xo1.mjs";import{sql as t}from"drizzle-orm";import{matchesStaticWhere as F}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as N,encodeAggregateKey as D,foldAggregateTally as v}from"./aggregateTableName-BvenuaDR.mjs";import{runDrizzle as l}from"./runDrizzle-2ULFQR_k.mjs";import{i as w,r as p,a as B,b as G,A as U,D as I,h as H}from"./do-sql-Cv3yRshL.mjs";import{isLiveForCompanion as P}from"./CURSOR_PREFIX-D8c7Ccj3.mjs";import{rankTableName as W,matchesRankStaticWhere as V}from"./RANK_TIEBREAK-B6iDKDW3.mjs";const k=(e,o)=>l(e,t`SELECT COUNT(*) AS count FROM ${t.identifier(o)}`).one().count>0,Y=(e,o)=>l(e,t`SELECT 1 FROM ${t.identifier(o)} LIMIT 1`).toArray().length>0,A=(e,o)=>l(e,t`SELECT id, _creationTime, ${t.identifier(I)} FROM ${t.identifier(o)}`).toArray(),j=(e,o,n,r)=>{const i=N(o,n.name);if(k(e,i))return;const c=n.by??[],a=new Map,s=A(e,o);for(const d of s){const f=p(d);if(!f||!P(f,r)||n.where&&!F(f,n.where))continue;const g=D(c,f);v(a,g,n,f)}for(const[d,f]of a)l(e,t`INSERT INTO ${t.identifier(i)} (${B}, ${G}, ${U}) VALUES (${d}, ${f.value}, ${f.count})`)},te=(e,o)=>{for(const[n,r]of Object.entries(o.tables))if(!(r.shardMode?.kind==="global"||!r.aggregateIndexes))for(const i of r.aggregateIndexes)j(e,n,i,r.softDeleteMode?.field)},K=(e,o,n)=>{const r=W(o,n.name);if(k(e,r))return;const i=M(n),c=A(e,o);for(const a of c){const s=p(a);!s||n.where&&!V(s,n.where)||x(e,r,n,i,s._id,s)}},ie=(e,o)=>{for(const[n,r]of Object.entries(o.tables))if(!(r.shardMode?.kind==="global"||!r.rankIndexes))for(const i of r.rankIndexes)K(e,n,i)},u=500,$=(e,o,n)=>{const r=R(o,n.name),i=T(n),c=b(E(e,r),i);if(c.finished)return{done:!0,rows:0};const{cursor:a}=c,s=l(e,a===void 0?t`SELECT id, _creationTime, ${t.identifier(I)} FROM ${t.identifier(o)} ORDER BY id ASC LIMIT ${t.raw(String(u))}`:t`SELECT id, _creationTime, ${t.identifier(I)} FROM ${t.identifier(o)} WHERE id > ${a} ORDER BY id ASC LIMIT ${t.raw(String(u))}`).toArray();let d=a;for(const g of s){const{id:m}=g;if(typeof m!="string")continue;d=m,l(e,t`DELETE FROM ${t.identifier(r)} WHERE ${t.identifier(h)} = ${m}`);const S=H(g);S&&l(e,t`INSERT INTO ${t.identifier(r)} (${t.identifier(_)}, ${t.identifier(h)}) VALUES (${y(S,n)}, ${m})`)}const f=s.length<u;return L(e,r,d,f,i),{done:f,rows:s.length}},ae=(e,o,n)=>{const r=R(o,n.name),i=T(n);return b(E(e,r),i).finished?!0:C(e,r)},se=(e,o,n)=>{if(w(e))for(const r of n.searchIndexes??[])r.staged&&Y(e,o)||$(e,o,r)},z=(e,o,n,r)=>{let i=0;for(;;){if(i>=r)return{done:!1,pages:i};const c=$(e,o,n);if(c.rows>0&&(i+=1),c.done)return{done:!0,pages:i}}},ce=(e,o,n={})=>{if(!w(e))return{done:!0,pages:0};O(e);const r=n.maxPages??Number.POSITIVE_INFINITY;let i=0;for(const[c,a]of Object.entries(o.tables))if(!(a.shardMode?.kind==="global"||!a.searchIndexes))for(const s of a.searchIndexes){const d=z(e,c,s,r-i);if(i+=d.pages,!d.done)return{done:!1,pages:i}}return{done:!0,pages:i}};export{te as backfillAggregateIndexes,ie as backfillRankIndexes,ce as backfillSearchIndexes,se as backfillSearchIndexesForTable,ae as searchIndexCoversTable};
1
+ import{m as O,c as T,l as b,r as E,a as C,w as L}from"./ctx-db-search-state-ruTuCsxa.mjs";import{S as R,r as M,i as x,l as h,y as _,d as y}from"./ctx-db-companions-B4O4d95S.mjs";import{sql as t}from"drizzle-orm";import{matchesStaticWhere as F}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as N,encodeAggregateKey as D,foldAggregateTally as v}from"./aggregateTableName-C7o-gpms.mjs";import{runDrizzle as l}from"./runDrizzle-2ULFQR_k.mjs";import{i as w,r as p,a as B,b as G,A as U,D as I,h as H}from"./do-sql-FNOnpyHm.mjs";import{isLiveForCompanion as P}from"./CURSOR_PREFIX-qn6nNVS7.mjs";import{rankTableName as W,matchesRankStaticWhere as V}from"./RANK_TIEBREAK-CkNuGm6a.mjs";const k=(e,o)=>l(e,t`SELECT COUNT(*) AS count FROM ${t.identifier(o)}`).one().count>0,Y=(e,o)=>l(e,t`SELECT 1 FROM ${t.identifier(o)} LIMIT 1`).toArray().length>0,A=(e,o)=>l(e,t`SELECT id, _creationTime, ${t.identifier(I)} FROM ${t.identifier(o)}`).toArray(),j=(e,o,n,r)=>{const i=N(o,n.name);if(k(e,i))return;const c=n.by??[],a=new Map,s=A(e,o);for(const d of s){const f=p(d);if(!f||!P(f,r)||n.where&&!F(f,n.where))continue;const g=D(c,f);v(a,g,n,f)}for(const[d,f]of a)l(e,t`INSERT INTO ${t.identifier(i)} (${B}, ${G}, ${U}) VALUES (${d}, ${f.value}, ${f.count})`)},te=(e,o)=>{for(const[n,r]of Object.entries(o.tables))if(!(r.shardMode?.kind==="global"||!r.aggregateIndexes))for(const i of r.aggregateIndexes)j(e,n,i,r.softDeleteMode?.field)},K=(e,o,n)=>{const r=W(o,n.name);if(k(e,r))return;const i=M(n),c=A(e,o);for(const a of c){const s=p(a);!s||n.where&&!V(s,n.where)||x(e,r,n,i,s._id,s)}},ie=(e,o)=>{for(const[n,r]of Object.entries(o.tables))if(!(r.shardMode?.kind==="global"||!r.rankIndexes))for(const i of r.rankIndexes)K(e,n,i)},u=500,$=(e,o,n)=>{const r=R(o,n.name),i=T(n),c=b(E(e,r),i);if(c.finished)return{done:!0,rows:0};const{cursor:a}=c,s=l(e,a===void 0?t`SELECT id, _creationTime, ${t.identifier(I)} FROM ${t.identifier(o)} ORDER BY id ASC LIMIT ${t.raw(String(u))}`:t`SELECT id, _creationTime, ${t.identifier(I)} FROM ${t.identifier(o)} WHERE id > ${a} ORDER BY id ASC LIMIT ${t.raw(String(u))}`).toArray();let d=a;for(const g of s){const{id:m}=g;if(typeof m!="string")continue;d=m,l(e,t`DELETE FROM ${t.identifier(r)} WHERE ${t.identifier(h)} = ${m}`);const S=H(g);S&&l(e,t`INSERT INTO ${t.identifier(r)} (${t.identifier(_)}, ${t.identifier(h)}) VALUES (${y(S,n)}, ${m})`)}const f=s.length<u;return L(e,r,d,f,i),{done:f,rows:s.length}},ae=(e,o,n)=>{const r=R(o,n.name),i=T(n);return b(E(e,r),i).finished?!0:C(e,r)},se=(e,o,n)=>{if(w(e))for(const r of n.searchIndexes??[])r.staged&&Y(e,o)||$(e,o,r)},z=(e,o,n,r)=>{let i=0;for(;;){if(i>=r)return{done:!1,pages:i};const c=$(e,o,n);if(c.rows>0&&(i+=1),c.done)return{done:!0,pages:i}}},ce=(e,o,n={})=>{if(!w(e))return{done:!0,pages:0};O(e);const r=n.maxPages??Number.POSITIVE_INFINITY;let i=0;for(const[c,a]of Object.entries(o.tables))if(!(a.shardMode?.kind==="global"||!a.searchIndexes))for(const s of a.searchIndexes){const d=z(e,c,s,r-i);if(i+=d.pages,!d.done)return{done:!1,pages:i}}return{done:!0,pages:i}};export{te as backfillAggregateIndexes,ie as backfillRankIndexes,ce as backfillSearchIndexes,se as backfillSearchIndexesForTable,ae as searchIndexCoversTable};
@@ -1 +1 @@
1
- import{e as h}from"./wire-codec-CKV-4MEN.mjs";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};
1
+ import{e as h}from"./wire-codec-C-FpWm52.mjs";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};
@@ -1 +1 @@
1
- import{quoteIdentifier as l}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as u}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{REPROJECTION_MIGRATION_PREFIX as v,reprojectionMigrationId as w}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{e as d}from"./wire-codec-CKV-4MEN.mjs";import{runSql as p}from"./runDrizzle-2ULFQR_k.mjs";import{k as m,D as E}from"./do-sql-Cv3yRshL.mjs";import{mayHoldProjectedValue as g}from"./BIGINT_KEY_DIGITS-GvEBhyR5.mjs";const b=d(0n)[0],_=e=>e.shardMode?.kind==="global"?[]:Object.entries(e.shape).filter(([,r])=>g(r)).map(([r])=>r),M=e=>Object.entries(e.tables).filter(([,r])=>_(r).length>0).map(([r])=>r),f=e=>{const r=`json_each(${l(E)}) AS __f__`;return{params:[JSON.stringify(e),b,"bigint","bytes"],sql:`EXISTS (SELECT 1 FROM ${r} WHERE __f__.type = 'array' AND __f__.key IN (SELECT value FROM json_each(?)) AND json_extract(__f__.value, '$[0]') = ? AND json_extract(__f__.value, '$[1]') IN (?, ?))`}},N=(e,r,o)=>{if(o.length===0)return 0;const{params:t,sql:n}=f(o);return p(e,`SELECT COUNT(*) AS count FROM ${l(r)} WHERE ${n}`,...t).toArray()[0]?.count??0},R=(e,r,o,t)=>{const{params:n,sql:i}=f(o);return p(e,`SELECT 1 FROM ${l(r)} WHERE id = ? AND (${i}) LIMIT 1`,t,...n).toArray().length>0},S=(e,r,o)=>{const t=u(e);if(t===void 0)return;const n=r.tables[t];if(!n)return;const i=_(n);if(i.length!==0)return{id:e,table:t,up:s=>{const a=s._id;if(!(typeof a!="string"||!R(o,t,i,a))){try{m(s)}catch(c){console.warn(`${e}: skipping row ${a} — it cannot be re-projected: ${c instanceof Error?c.message:String(c)}`);return}return s}}}};export{v as REPROJECTION_MIGRATION_PREFIX,S as buildReprojectionMigration,N as countLegacyRows,_ as reprojectableFields,w as reprojectionMigrationId,M as reprojectionTables};
1
+ import{quoteIdentifier as l}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as u}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{REPROJECTION_MIGRATION_PREFIX as v,reprojectionMigrationId as w}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{e as d}from"./wire-codec-C-FpWm52.mjs";import{runSql as p}from"./runDrizzle-2ULFQR_k.mjs";import{k as m,D as E}from"./do-sql-FNOnpyHm.mjs";import{mayHoldProjectedValue as g}from"./BIGINT_KEY_DIGITS-GvEBhyR5.mjs";const b=d(0n)[0],_=e=>e.shardMode?.kind==="global"?[]:Object.entries(e.shape).filter(([,r])=>g(r)).map(([r])=>r),M=e=>Object.entries(e.tables).filter(([,r])=>_(r).length>0).map(([r])=>r),f=e=>{const r=`json_each(${l(E)}) AS __f__`;return{params:[JSON.stringify(e),b,"bigint","bytes"],sql:`EXISTS (SELECT 1 FROM ${r} WHERE __f__.type = 'array' AND __f__.key IN (SELECT value FROM json_each(?)) AND json_extract(__f__.value, '$[0]') = ? AND json_extract(__f__.value, '$[1]') IN (?, ?))`}},N=(e,r,o)=>{if(o.length===0)return 0;const{params:t,sql:n}=f(o);return p(e,`SELECT COUNT(*) AS count FROM ${l(r)} WHERE ${n}`,...t).toArray()[0]?.count??0},R=(e,r,o,t)=>{const{params:n,sql:i}=f(o);return p(e,`SELECT 1 FROM ${l(r)} WHERE id = ? AND (${i}) LIMIT 1`,t,...n).toArray().length>0},S=(e,r,o)=>{const t=u(e);if(t===void 0)return;const n=r.tables[t];if(!n)return;const i=_(n);if(i.length!==0)return{id:e,table:t,up:s=>{const a=s._id;if(!(typeof a!="string"||!R(o,t,i,a))){try{m(s)}catch(c){console.warn(`${e}: skipping row ${a} — it cannot be re-projected: ${c instanceof Error?c.message:String(c)}`);return}return s}}}};export{v as REPROJECTION_MIGRATION_PREFIX,S as buildReprojectionMigration,N as countLegacyRows,_ as reprojectableFields,w as reprojectionMigrationId,M as reprojectionTables};
@@ -1 +1 @@
1
- import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-CMCaSndb.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-jydcnpzn.mjs";import{shapeRangeKey as u}from"./ShapeDiffCache-SgPO8heC.mjs";import{projectColumns as g}from"./buildPokeFrames-CkVxoDaR.mjs";const C=(m,e,a,i,p,f=s)=>{const r=u(e.table,a,i),n=p.changedKeys(r,()=>f(m,e.table,a,i));if(n.length===0)return[];const b=p.members(e,r,()=>h(m,e.table,e.effectiveWhere,n.map(t=>t.id))),o=[];for(const t of n){const c=b.get(t.id);if(c===void 0){t.op!=="insert"&&o.push({key:t.id,op:"delete",table:e.table});continue}o.push({key:t.id,op:t.op,table:e.table,value:g(c,e.columns)})}return o};export{C as buildShapeDiff};
1
+ import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-CAyqu8cg.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-DqikYFjS.mjs";import{shapeRangeKey as u}from"./ShapeDiffCache-gdaILV5E.mjs";import{projectColumns as g}from"./buildPokeFrames-BBE6J91z.mjs";const C=(m,e,a,i,p,f=s)=>{const r=u(e.table,a,i),n=p.changedKeys(r,()=>f(m,e.table,a,i));if(n.length===0)return[];const b=p.members(e,r,()=>h(m,e.table,e.effectiveWhere,n.map(t=>t.id))),o=[];for(const t of n){const c=b.get(t.id);if(c===void 0){t.op!=="insert"&&o.push({key:t.id,op:"delete",table:e.table});continue}o.push({key:t.id,op:t.op,table:e.table,value:g(c,e.columns)})}return o};export{C as buildShapeDiff};
@@ -1 +1 @@
1
- import{LunoraError as g}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{mergeWhere as b}from"./CountRlsUnsupportedError-Bdfupt3g.mjs";import{SCAN_DEP as j}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as A}from"./runDrizzle-2ULFQR_k.mjs";import{sqliteInList as O}from"./param-DlozcSQu.mjs";import{decodeCursor as F,CURSOR_PREFIX as P,toBase64 as U}from"./CURSOR_PREFIX-D8c7Ccj3.mjs";import{rankTableName as V,sortColumnName as z,resolveRankPartition as H,RANK_TIEBREAK as _,encodePartitionKey as J,rankPivotConditionSql as X}from"./RANK_TIEBREAK-B6iDKDW3.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};
1
+ import{LunoraError as g}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{mergeWhere as b}from"./CountRlsUnsupportedError-Bdfupt3g.mjs";import{SCAN_DEP as j}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as A}from"./runDrizzle-2ULFQR_k.mjs";import{sqliteInList as O}from"./param-DlozcSQu.mjs";import{decodeCursor as F,CURSOR_PREFIX as P,toBase64 as U}from"./CURSOR_PREFIX-qn6nNVS7.mjs";import{rankTableName as V,sortColumnName as z,resolveRankPartition as H,RANK_TIEBREAK as _,encodePartitionKey as J,rankPivotConditionSql as X}from"./RANK_TIEBREAK-CkNuGm6a.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{c as l,i as C,r as R}from"./ctx-db-companions-B4O4d95S.mjs";import"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import"./aggregateTableName-C7o-gpms.mjs";import"./runDrizzle-2ULFQR_k.mjs";import"./do-sql-FNOnpyHm.mjs";import"./param-DlozcSQu.mjs";import"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import"./CURSOR_PREFIX-qn6nNVS7.mjs";import"./RANK_TIEBREAK-CkNuGm6a.mjs";import"./BIGINT_KEY_DIGITS-GvEBhyR5.mjs";import"./serializeSqlValue-B_-zaEWZ.mjs";export{l as createCompanionSync,C as insertRankRow,R as rankColumnsSql};
@@ -0,0 +1,7 @@
1
+ import{d as u,e as S}from"./wire-codec-C-FpWm52.mjs";import{cursorBelowRetainedFloor as y}from"./CDC_LOG_TABLE-CAyqu8cg.mjs";import{envPositiveInt as v}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{v as A,R as g,s as N,a as E,b as T}from"./sibling-channel-Cxvk0Zca.mjs";const L=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],O=new Set(L),b=s=>typeof s=="string"&&O.has(s),l="::replica::",R=s=>{const e=s.lastIndexOf(l);if(e===-1)return;const t=s.slice(0,e),r=s.slice(e+l.length);if(!(t.length===0||!b(r)))return{ownerKey:t,region:r}},I=s=>{if(s==null||!/^\d+$/.test(s))return;const e=Number.parseInt(s,10);return Number.isSafeInteger(e)&&e>0?e:void 0},m=1e3,w=1e3,C=10,F=5e4,U=s=>v(s,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",F),d="__replica_state",h=new WeakSet,_=s=>{h.has(s)||(s.exec(`CREATE TABLE IF NOT EXISTS ${d} (
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
+ )`),h.add(s))},c=s=>(_(s),s.exec(`SELECT epoch, applied_seq AS appliedSeq, synced_at AS syncedAtMs FROM ${d} WHERE id = 1`).toArray()[0]),f=(s,e)=>{_(s),s.exec(`INSERT INTO ${d} (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)},q=s=>{const e=s.doName();if(e!==void 0&&R(e)!==void 0)return new Response("replica cannot serve replicas",{status:409});if(s.ownerEpoch()===void 0)return new Response("shard has no changelog to replicate",{status:409});if(E(s.env())===void 0)return new Response("replica control requires LUNORA_RELAY_SECRET",{status:403})},a=s=>Response.json(S(s)),P=async(s,e)=>{if(s.rowCount()>U(s.env()))return a({cursor:0,epoch:e,rows:[],truncated:!0});const t=s.ownerCursor()??0,r=await s.exportRows();return a({cursor:t,epoch:e,rows:r})},x=(s,e,t)=>{const r=s.ownerFloor();if(y(r,t))return a({changes:[],cursor:s.ownerCursor()??t,epoch:e,floor:r});const{changes:o,cursor:n}=s.readChanges(t,w);return a({changes:o,cursor:n,epoch:e,...r===void 0?{}:{floor:r}})},K=async(s,e)=>{const t=q(s);if(t!==void 0)return t;const r=s.ownerEpoch();let o;try{o=await e.text()}catch{return new Response("bad request",{status:400})}if(!await A(s.env(),e.headers.get(g),o))return new Response("forbidden",{status:403});let n;try{n=JSON.parse(o)}catch{return new Response("bad request",{status:400})}if(n.type==="replica_bootstrap")return P(s,r);if(n.type==="replica_pull"){const i=typeof n.sinceSeq=="number"&&Number.isInteger(n.sinceSeq)&&n.sinceSeq>=0?n.sinceSeq:0;return x(s,r,i)}return new Response("unknown replica frame",{status:400})};class M{constructor(e,t,r){this.host=e,this.ownerKey=t,this.region=r}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 c(this.host.sql())?.appliedSeq??0}isDivergent(){return this.divergent}async advance(e){let t=c(this.host.sql());if(t===void 0){const r=await this.bootstrap();if(r===void 0)return"unavailable";t=r}return this.catchUp(t,e)}isCaughtUp(e){const t=c(this.host.sql());return t!==void 0&&this.isFreshEnough(t,e)}async catchUp(e,t){let r=e;for(let o=0;o<C;o+=1){const n=await this.pull(r.appliedSeq);if(n===void 0)return t===void 0&&this.isFreshEnough(r,void 0)?"fresh":"unavailable";if(this.hasDiverged(r,n))return"unavailable";const i=n.changes.length<w;if(r=await this.applyPage(n),i||this.isFreshEnough(r,t))return this.isFreshEnough(r,t)?"fresh":"stale"}return this.isFreshEnough(r,t)?"fresh":"stale"}async applyPage(e){e.changes.length>0&&await this.host.applyChanges(e.changes);const t={appliedSeq:e.cursor,epoch:e.epoch,syncedAtMs:Date.now()};return f(this.host.sql(),t),t}hasDiverged(e,t){const r=t.changes.length===0&&t.cursor>e.appliedSeq,o=t.floor??(r?t.cursor:0),n=o>0&&o>e.appliedSeq+1;return t.epoch===e.epoch&&!n?!1:(this.divergent=!0,!0)}async bootstrap(){const e=await this.request({type:"replica_bootstrap"});if(e===void 0)return;const t=u(await e.json());if(t.truncated===!0){this.divergent=!0;return}const{errors:r}=await this.host.importRows(t.rows);if(r.length>0){this.divergent=!0;return}const o={appliedSeq:t.cursor,epoch:t.epoch,syncedAtMs:Date.now()};return f(this.host.sql(),o),o}isFreshEnough(e,t){return t!==void 0?e.appliedSeq>=t:Date.now()-e.syncedAtMs<=v(this.host.env(),"LUNORA_REPLICA_MAX_STALENESS_MS",m)}async pull(e){const t=await this.request({sinceSeq:e,type:"replica_pull"});return t===void 0?void 0:u(await t.json())}async request(e){const t=this.host.shardBinding(),r=N(this.host.env(),t,this.ownerKey);if(r===void 0)return;const o=JSON.stringify(e),n={"content-type":"application/json","x-lunora-shard-binding":t??""},i=E(this.host.env());i!==void 0&&(n[g]=await T(i,o));try{const p=await r.fetch("https://replica.internal/_lunora/replica",{body:o,headers:n,method:"POST"});return p.ok?p:void 0}catch{return}}}const j=s=>{const e=s.doName();if(e===void 0)return;const t=R(e);return t===void 0?void 0:new M(s,t.ownerKey,t.region)},G=async(s,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 r=await s.ensureFresh(I(e.headers.get("x-lunora-min-seq")));if(r!=="fresh")return Response.json({error:{code:"REPLICA_NOT_READY",message:`replica is ${r} for this read`}},{headers:{"x-lunora-replica-fallback":r},status:421})};export{j as createReplicaLink,G as gateReplicaDispatch,K as handleReplicaControl};
@@ -1 +1 @@
1
- import{D as ie}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as P,aggregateSqlFunction as ce}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as z,encodeAggregateKey as v,foldAggregateTally as J,coerceAggregateNumber as b}from"./aggregateTableName-BvenuaDR.mjs";import{runDrizzle as u}from"./runDrizzle-2ULFQR_k.mjs";import{i as fe,g as ae,D as M,r as q,a as L,b as h,A as p,c as D,e as U}from"./do-sql-Cv3yRshL.mjs";import{param as le,WORKERD_SQLITE_LIMITS as $e}from"./param-DlozcSQu.mjs";import{encodeGeohash as de,GEO_DEFAULT_PRECISION as ue}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as N}from"./CURSOR_PREFIX-D8c7Ccj3.mjs";import{encodePartitionKey as Ee,sortColumnName as _e,rankTableName as X,matchesRankStaticWhere as Y}from"./RANK_TIEBREAK-B6iDKDW3.mjs";import{mayHoldProjectedValue as ye}from"./BIGINT_KEY_DIGITS-GvEBhyR5.mjs";import{serializeSqlValue as Z}from"./serializeSqlValue-B_-zaEWZ.mjs";const ge=(t,i)=>{if(!i.includes("."))return t[i];let f=t;for(const A of i.split(".")){if(f===null||typeof f!="object"||Array.isArray(f))return;f=f[A]}return f},pe=(t,i)=>`${t}__fts_${i}`,me="__text__",Q="__id__",he=1e3,Se=(t,i)=>i.document(t),W=(t,i)=>ge(t,i),Te=t=>typeof t=="string"?t:t==null?"":typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"?String(t):JSON.stringify(t)??"",Re=(t,i,f)=>t!==void 0&&i!==void 0&&W(t,f.field)===W(i,f.field),Ae=(t,i)=>Se(Te(W(t,i.field)),ie(i.language)).slice(0,he),we=(t,i)=>Ae(t,i).join(" "),Fe=(t,i,f)=>[...t.partitionBy??[],...t.sortBy.map(S=>S.field),...t.where?Object.keys(t.where):[]].every(S=>i[S]===f[S]),x=t=>e.join(["__id__","__partition__",...t.sortBy.map((i,f)=>_e(f))].map(i=>e.identifier(i)),e`, `),ee=(t,i,f,A,S,y)=>{const c=Ee(f.partitionBy??[],y),C=f.sortBy.map(I=>Z(y[I.field]??null)),k=e.join([S,c,...C].map(I=>le(I)),e`, `);u(t,e`INSERT INTO ${e.identifier(i)} (${A}) VALUES (${k})`)},Oe=(t,i,f,A,S,y)=>{if(S&&y&&Fe(f,S,y))return;const c=X(i,f.name);S&&u(t,e`DELETE FROM ${e.identifier(c)} WHERE ${e.identifier("__id__")} = ${A}`),!(!y||f.where&&!Y(y,f.where))&&ee(t,c,f,x(f),A,y)},Be=t=>{const{broadcast:i,indexKeysFor:f,invalidateCache:A,recordCdc:S,schema:y,sql:c}=t,C=new Set,k=n=>y.tables[n]?.softDeleteMode?.field,I=new Set,j=(n,o)=>{const s=`${n}::${o.name}`;if(C.has(s))return;const l=z(n,o.name),$=o.by??[],d=k(n),_=new Map,m=u(c,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(n)}`).toArray();for(const T of m){const E=q(T);if(!E||!N(E,d)||o.where&&!P(E,o.where))continue;const R=v($,E);J(_,R,o,E)}u(c,e`DELETE FROM ${e.identifier(l)}`);const w=Math.floor($e.boundParams/3),F=[..._];for(let T=0;T<F.length;T+=w){const E=F.slice(T,T+w),R=e.join(E.map(([r,a])=>e`(${r}, ${a.value}, ${a.count})`),e`, `);u(c,e`INSERT INTO ${e.identifier(l)} (${L}, ${h}, ${p}) VALUES ${R}`)}C.add(s)},oe=(n,o,s)=>{const l=o.by??[],$=o.field??"",d=[],_=(r,a)=>{const g=Z(a);g===null?d.push(e`${U(r)} IS NULL`):d.push(e`${U(r)} = ${g}`)};for(const r of l)_(r,s[r]??null);const m=k(n);m!==void 0&&_(m,null);for(const[r,a]of Object.entries(o.where??{}))_(r,a!==null&&typeof a=="object"&&!Array.isArray(a)?a.eq:a);const w=d.length>0?e` WHERE ${e.join(d,e` AND `)}`:e``,F=y.tables[n]?.shape[$];if(F&&ye(F)){const r=u(c,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(n)}${w}`).toArray(),a=new Map;for(const g of r){const O=q(g);O&&J(a,"",o,O)}return{value:a.get("")?.value??null}}const T=ce(o.op),E=U($);return{value:u(c,e`SELECT ${e.raw(T)}(${E}) AS value FROM ${e.identifier(n)}${w}`).one().value??null}},ne=(n,o,s,l)=>{const $=z(n,o.name),{op:d}=o,_=o.field??"",m=r=>{u(c,e`DELETE FROM ${e.identifier($)} WHERE ${L} = ${r} AND ${p} <= 0`)},w=k(n),F=r=>!o.where||P(r,o.where),T=r=>N(r,w)&&F(r);l!==void 0&&d!=="count"&&F(l)&&b(l[_]);const E=s&&T(s)?s:void 0,R=l&&T(l)?l:void 0;if(!(!E&&!R)){if(d==="count"){for(const[r,a]of[[E,-1],[R,1]]){if(!r)continue;const g=v(o.by??[],r);u(c,D($,g,a,a,e`${h} = ${h} + excluded.${h}, ${p} = ${p} + excluded.${p}`))}E&&m(v(o.by??[],E));return}if(d==="sum"||d==="avg"){for(const[r,a]of[[E,-1],[R,1]]){if(!r)continue;const g=b(r[_]);if(g===void 0)continue;const O=v(o.by??[],r);u(c,D($,O,a*g,a,e`${h} = COALESCE(${h}, 0) + excluded.${h}, ${p} = ${p} + excluded.${p}`))}E&&m(v(o.by??[],E));return}if(E){const r=v(o.by??[],E),a=b(E[_]),g=u(c,e`SELECT ${h} AS value, ${p} AS count FROM ${e.identifier($)} WHERE ${L} = ${r}`).toArray()[0],O=(g?.count??0)-1;if(O<=0)u(c,e`DELETE FROM ${e.identifier($)} WHERE ${L} = ${r}`);else if(g&&a!==void 0&&g.value!==null&&a===g.value){const se=oe(n,o,E);u(c,e`UPDATE ${e.identifier($)} SET ${h} = ${se.value}, ${p} = ${O} WHERE ${L} = ${r}`)}else u(c,e`UPDATE ${e.identifier($)} SET ${p} = ${p} - 1 WHERE ${L} = ${r}`)}if(R){const r=v(o.by??[],R),a=b(R[_]);if(a===void 0)u(c,D($,r,null,1,e`${p} = ${p} + 1`));else{const g=d==="min"?"MIN":"MAX";u(c,D($,r,a,1,e`${h} = ${e.raw(g)}(COALESCE(${h}, excluded.${h}), excluded.${h}), ${p} = ${p} + 1`))}}}},te=n=>{for(const o of y.tables[n]?.aggregateIndexes??[])j(n,o)},H=(n,o,s)=>{for(const l of y.tables[n]?.aggregateIndexes??[])ne(n,l,o,s)},B=(n,o)=>{const s=`${n}::rank::${o.name}`;if(I.has(s))return;const l=X(n,o.name),$=u(c,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(n)}`).toArray();u(c,e`DELETE FROM ${e.identifier(l)}`);const d=x(o);for(const _ of $){const m=q(_);!m||o.where&&!Y(m,o.where)||ee(c,l,o,d,m._id,m)}I.add(s)},re=n=>{for(const o of y.tables[n]?.rankIndexes??[])B(n,o)},K=(n,o,s,l)=>{for(const $ of y.tables[n]?.rankIndexes??[])Oe(c,n,$,o,s,l)},V=(n,o,s,l)=>{const $=y.tables[n]?.searchIndexes??[];if(!($.length===0||!fe(c)))for(const d of $){if(Re(l,s,d))continue;const _=pe(n,d.name);u(c,e`DELETE FROM ${e.identifier(_)} WHERE ${e.identifier(Q)} = ${o}`),s&&u(c,e`INSERT INTO ${e.identifier(_)} (${e.identifier(me)}, ${e.identifier(Q)}) VALUES (${we(s,d)}, ${o})`)}},G=(n,o,s)=>{for(const l of y.tables[n]?.geoIndexes??[]){const $=ae(n,l.name);u(c,e`DELETE FROM ${e.identifier($)} WHERE ${e.identifier("__id__")} = ${o}`);const d=s?.[l.field];if(d!==null&&typeof d=="object"&&typeof d.lat=="number"&&typeof d.lng=="number"){const{lat:_,lng:m}=d,w=de({lat:_,lng:m},l.precision??ue);u(c,e`INSERT INTO ${e.identifier($)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${o}, ${w}, ${_}, ${m})`)}}};return{ensureBackfilledForTable:te,ensureBackfilledIndex:j,ensureRankBackfilled:B,ensureRankBackfilledForTable:re,syncAggregates:H,syncCompanionsForInsert:(n,o,s)=>{V(n,o,s),G(n,o,s),H(n,void 0,s),K(n,o,void 0,s),A(n,o,s),S(n,o,"insert",s),i({indexKeys:f(n,s),key:o,op:"insert",row:s,table:n})},syncGeo:G,syncRanks:K,syncSearch:V}};export{pe as S,Ae as a,Be as c,we as d,ee as i,Q as l,x as r,me as y};
1
+ import{D as ie}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as P,aggregateSqlFunction as ce}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as z,encodeAggregateKey as v,foldAggregateTally as J,coerceAggregateNumber as b}from"./aggregateTableName-C7o-gpms.mjs";import{runDrizzle as u}from"./runDrizzle-2ULFQR_k.mjs";import{i as fe,g as ae,D as M,r as q,a as L,b as h,A as p,c as D,e as U}from"./do-sql-FNOnpyHm.mjs";import{param as le,WORKERD_SQLITE_LIMITS as $e}from"./param-DlozcSQu.mjs";import{encodeGeohash as de,GEO_DEFAULT_PRECISION as ue}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as N}from"./CURSOR_PREFIX-qn6nNVS7.mjs";import{encodePartitionKey as Ee,sortColumnName as _e,rankTableName as X,matchesRankStaticWhere as Y}from"./RANK_TIEBREAK-CkNuGm6a.mjs";import{mayHoldProjectedValue as ye}from"./BIGINT_KEY_DIGITS-GvEBhyR5.mjs";import{serializeSqlValue as Z}from"./serializeSqlValue-B_-zaEWZ.mjs";const ge=(t,i)=>{if(!i.includes("."))return t[i];let f=t;for(const A of i.split(".")){if(f===null||typeof f!="object"||Array.isArray(f))return;f=f[A]}return f},pe=(t,i)=>`${t}__fts_${i}`,me="__text__",Q="__id__",he=1e3,Se=(t,i)=>i.document(t),W=(t,i)=>ge(t,i),Te=t=>typeof t=="string"?t:t==null?"":typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"?String(t):JSON.stringify(t)??"",Re=(t,i,f)=>t!==void 0&&i!==void 0&&W(t,f.field)===W(i,f.field),Ae=(t,i)=>Se(Te(W(t,i.field)),ie(i.language)).slice(0,he),we=(t,i)=>Ae(t,i).join(" "),Fe=(t,i,f)=>[...t.partitionBy??[],...t.sortBy.map(S=>S.field),...t.where?Object.keys(t.where):[]].every(S=>i[S]===f[S]),x=t=>e.join(["__id__","__partition__",...t.sortBy.map((i,f)=>_e(f))].map(i=>e.identifier(i)),e`, `),ee=(t,i,f,A,S,y)=>{const c=Ee(f.partitionBy??[],y),C=f.sortBy.map(I=>Z(y[I.field]??null)),k=e.join([S,c,...C].map(I=>le(I)),e`, `);u(t,e`INSERT INTO ${e.identifier(i)} (${A}) VALUES (${k})`)},Oe=(t,i,f,A,S,y)=>{if(S&&y&&Fe(f,S,y))return;const c=X(i,f.name);S&&u(t,e`DELETE FROM ${e.identifier(c)} WHERE ${e.identifier("__id__")} = ${A}`),!(!y||f.where&&!Y(y,f.where))&&ee(t,c,f,x(f),A,y)},Be=t=>{const{broadcast:i,indexKeysFor:f,invalidateCache:A,recordCdc:S,schema:y,sql:c}=t,C=new Set,k=n=>y.tables[n]?.softDeleteMode?.field,I=new Set,j=(n,o)=>{const s=`${n}::${o.name}`;if(C.has(s))return;const l=z(n,o.name),$=o.by??[],d=k(n),_=new Map,m=u(c,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(n)}`).toArray();for(const T of m){const E=q(T);if(!E||!N(E,d)||o.where&&!P(E,o.where))continue;const R=v($,E);J(_,R,o,E)}u(c,e`DELETE FROM ${e.identifier(l)}`);const w=Math.floor($e.boundParams/3),F=[..._];for(let T=0;T<F.length;T+=w){const E=F.slice(T,T+w),R=e.join(E.map(([r,a])=>e`(${r}, ${a.value}, ${a.count})`),e`, `);u(c,e`INSERT INTO ${e.identifier(l)} (${L}, ${h}, ${p}) VALUES ${R}`)}C.add(s)},oe=(n,o,s)=>{const l=o.by??[],$=o.field??"",d=[],_=(r,a)=>{const g=Z(a);g===null?d.push(e`${U(r)} IS NULL`):d.push(e`${U(r)} = ${g}`)};for(const r of l)_(r,s[r]??null);const m=k(n);m!==void 0&&_(m,null);for(const[r,a]of Object.entries(o.where??{}))_(r,a!==null&&typeof a=="object"&&!Array.isArray(a)?a.eq:a);const w=d.length>0?e` WHERE ${e.join(d,e` AND `)}`:e``,F=y.tables[n]?.shape[$];if(F&&ye(F)){const r=u(c,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(n)}${w}`).toArray(),a=new Map;for(const g of r){const O=q(g);O&&J(a,"",o,O)}return{value:a.get("")?.value??null}}const T=ce(o.op),E=U($);return{value:u(c,e`SELECT ${e.raw(T)}(${E}) AS value FROM ${e.identifier(n)}${w}`).one().value??null}},ne=(n,o,s,l)=>{const $=z(n,o.name),{op:d}=o,_=o.field??"",m=r=>{u(c,e`DELETE FROM ${e.identifier($)} WHERE ${L} = ${r} AND ${p} <= 0`)},w=k(n),F=r=>!o.where||P(r,o.where),T=r=>N(r,w)&&F(r);l!==void 0&&d!=="count"&&F(l)&&b(l[_]);const E=s&&T(s)?s:void 0,R=l&&T(l)?l:void 0;if(!(!E&&!R)){if(d==="count"){for(const[r,a]of[[E,-1],[R,1]]){if(!r)continue;const g=v(o.by??[],r);u(c,D($,g,a,a,e`${h} = ${h} + excluded.${h}, ${p} = ${p} + excluded.${p}`))}E&&m(v(o.by??[],E));return}if(d==="sum"||d==="avg"){for(const[r,a]of[[E,-1],[R,1]]){if(!r)continue;const g=b(r[_]);if(g===void 0)continue;const O=v(o.by??[],r);u(c,D($,O,a*g,a,e`${h} = COALESCE(${h}, 0) + excluded.${h}, ${p} = ${p} + excluded.${p}`))}E&&m(v(o.by??[],E));return}if(E){const r=v(o.by??[],E),a=b(E[_]),g=u(c,e`SELECT ${h} AS value, ${p} AS count FROM ${e.identifier($)} WHERE ${L} = ${r}`).toArray()[0],O=(g?.count??0)-1;if(O<=0)u(c,e`DELETE FROM ${e.identifier($)} WHERE ${L} = ${r}`);else if(g&&a!==void 0&&g.value!==null&&a===g.value){const se=oe(n,o,E);u(c,e`UPDATE ${e.identifier($)} SET ${h} = ${se.value}, ${p} = ${O} WHERE ${L} = ${r}`)}else u(c,e`UPDATE ${e.identifier($)} SET ${p} = ${p} - 1 WHERE ${L} = ${r}`)}if(R){const r=v(o.by??[],R),a=b(R[_]);if(a===void 0)u(c,D($,r,null,1,e`${p} = ${p} + 1`));else{const g=d==="min"?"MIN":"MAX";u(c,D($,r,a,1,e`${h} = ${e.raw(g)}(COALESCE(${h}, excluded.${h}), excluded.${h}), ${p} = ${p} + 1`))}}}},te=n=>{for(const o of y.tables[n]?.aggregateIndexes??[])j(n,o)},H=(n,o,s)=>{for(const l of y.tables[n]?.aggregateIndexes??[])ne(n,l,o,s)},B=(n,o)=>{const s=`${n}::rank::${o.name}`;if(I.has(s))return;const l=X(n,o.name),$=u(c,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(n)}`).toArray();u(c,e`DELETE FROM ${e.identifier(l)}`);const d=x(o);for(const _ of $){const m=q(_);!m||o.where&&!Y(m,o.where)||ee(c,l,o,d,m._id,m)}I.add(s)},re=n=>{for(const o of y.tables[n]?.rankIndexes??[])B(n,o)},K=(n,o,s,l)=>{for(const $ of y.tables[n]?.rankIndexes??[])Oe(c,n,$,o,s,l)},V=(n,o,s,l)=>{const $=y.tables[n]?.searchIndexes??[];if(!($.length===0||!fe(c)))for(const d of $){if(Re(l,s,d))continue;const _=pe(n,d.name);u(c,e`DELETE FROM ${e.identifier(_)} WHERE ${e.identifier(Q)} = ${o}`),s&&u(c,e`INSERT INTO ${e.identifier(_)} (${e.identifier(me)}, ${e.identifier(Q)}) VALUES (${we(s,d)}, ${o})`)}},G=(n,o,s)=>{for(const l of y.tables[n]?.geoIndexes??[]){const $=ae(n,l.name);u(c,e`DELETE FROM ${e.identifier($)} WHERE ${e.identifier("__id__")} = ${o}`);const d=s?.[l.field];if(d!==null&&typeof d=="object"&&typeof d.lat=="number"&&typeof d.lng=="number"){const{lat:_,lng:m}=d,w=de({lat:_,lng:m},l.precision??ue);u(c,e`INSERT INTO ${e.identifier($)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${o}, ${w}, ${_}, ${m})`)}}};return{ensureBackfilledForTable:te,ensureBackfilledIndex:j,ensureRankBackfilled:B,ensureRankBackfilledForTable:re,syncAggregates:H,syncCompanionsForInsert:(n,o,s)=>{V(n,o,s),G(n,o,s),H(n,void 0,s),K(n,o,void 0,s),A(n,o,s),S(n,o,"insert",s),i({indexKeys:f(n,s),key:o,op:"insert",row:s,table:n})},syncGeo:G,syncRanks:K,syncSearch:V}};export{pe as S,Ae as a,Be as c,we as d,ee as i,Q as l,x as r,me as y};
@@ -1,4 +1,4 @@
1
- import{sql as i}from"drizzle-orm";import{e as l,d as E}from"./wire-codec-CKV-4MEN.mjs";import{runDrizzle as a}from"./runDrizzle-2ULFQR_k.mjs";import{relayProxyKey as T}from"./DEFAULT_PROMOTION_THRESHOLDS-CIJjsrCU.mjs";const t="__lunora_relay_shapes",o=null,R=e=>{a(e,i`CREATE TABLE IF NOT EXISTS ${i.identifier(t)} (
1
+ import{sql as i}from"drizzle-orm";import{e as l,d as E}from"./wire-codec-C-FpWm52.mjs";import{runDrizzle as a}from"./runDrizzle-2ULFQR_k.mjs";import{relayProxyKey as T}from"./DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";const t="__lunora_relay_shapes",o=null,R=e=>{a(e,i`CREATE TABLE IF NOT EXISTS ${i.identifier(t)} (
2
2
  key TEXT PRIMARY KEY,
3
3
  relay_idx INTEGER,
4
4
  connection_id TEXT,
@@ -1 +1 @@
1
- import{createShardCtxDb as v}from"./NotUniqueError-DGa-X5AB.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-05EHd-ef.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as _}from"./runShardMigrations-B1ilHmKB.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-CIJjsrCU.mjs";const E=(C,m={})=>({_meta:{column:{notNull:!0,...m}},kind:C}),W=(C,m,O)=>{const{describe:S,expect:n,it:y}=O;S(`engine contract: ${C}`,()=>{S("optimistic concurrency",()=>{const b=u=>({tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});y("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await n(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(N)}finally{u?.()}}),y("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e.code).toBe("CONFLICT"),n(e.kind).toBe("occ")}finally{u?.()}}),y("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const o=await s.get("i1");n(o?.title).toBe("first"),n(o?.version).toBe(99)}finally{u?.()}}),y("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l={tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,a)=>{await t.db.patch(a.doc._id,{version:99})},op:"update",timing:"before"}}}}};_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e).toBeInstanceOf(N),n(e.code).toBe("CONFLICT"),n(e.kind).toBe("trigger")}finally{u?.()}})}),S("shape-poke ordering",()=>{const b="shard-a",u={args:{},name:"messages"},h=(e,t,a,r)=>e.accept(t?.()??{},{connectionId:a,shapes:{[r]:u}}),i=(e,t,a)=>{let r=0,d=0;const c=g=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${g}`)},p={fetch:(g,q)=>{if(JSON.parse(q?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const B=a[d];if(d+=1,B===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(B))}},k={get:()=>p,getByName:()=>p,idFromName:g=>g},w={buildShapeDiff:c("buildShapeDiff"),computeOpLogShapeSeed:c("computeOpLogShapeSeed"),currentCdcEpoch:c("currentCdcEpoch"),deliverWhisperLocal:c("deliverWhisperLocal"),doName:()=>F(b,0),env:()=>({SHARD:k}),getWebSockets:()=>e.getSockets(),maskMetadata:c("maskMetadata"),nextPokeId:()=>(r+=1,`poke-${String(r)}`),readAttachment:g=>g.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:c("resolveShape"),rlsMetadata:c("rlsMetadata"),shardBinding:()=>"SHARD",sql:()=>t},f=I(w);if(f===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return f},l=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,a)=>{const r=await e.seedRelayShape(t,a,u,{identity:void 0,userId:void 0});if(r!=="ok")throw new Error(`seed failed: ${JSON.stringify(r)}`)},o=(e={})=>l({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});y("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o());const w=(await r(p)).map(f=>JSON.parse(f));n(w.map(f=>f.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),n(new Set(w.map(f=>f.pokeId)).size).toBe(1),n(w[1]?.shapeId).toBe("s1"),n(w[2]?.checkpoint).toBe(20)}finally{e?.()}}),y("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1"),k=h(d,t,"c-bob","s2");await s(c,p,"s1"),await s(c,k,"s2"),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3);const f=await r(k);n(f.length).toBe(0),await c.handleControl(o());const g=await r(p);n(g.length).toBe(3)}finally{e?.()}}),y("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o({epoch:"e2"}));const k=await r(p);n(k.length).toBe(0),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3)}finally{e?.()}})}),S("RLS identity under live subscription",()=>{const b="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},i=s=>{const o=[],e=[],t={fetch:(d,c)=>(o.push(JSON.parse(c?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},r=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>b,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:d=>d}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(d,c,p)=>(e.push(p),d===h.name?{columns:["id"],effectiveWhere:{org:p?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",sql:()=>s});if(r===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:r,posts:o,resolvedUnder:e}},l=async(s,o)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...o,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};y("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:o}=m();try{const{owner:e,resolvedUnder:t}=i(o.sql);await l(e,h),n(t.some(a=>a?.userId==="u1"&&a.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),y("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),y("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{W as defineEngineContractSuite};
1
+ import{createShardCtxDb as v}from"./NotUniqueError-CTSwCMsP.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-C3L_1GLp.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as _}from"./runShardMigrations-CkG92fSl.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";const E=(C,m={})=>({_meta:{column:{notNull:!0,...m}},kind:C}),W=(C,m,O)=>{const{describe:S,expect:n,it:y}=O;S(`engine contract: ${C}`,()=>{S("optimistic concurrency",()=>{const b=u=>({tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});y("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await n(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(N)}finally{u?.()}}),y("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e.code).toBe("CONFLICT"),n(e.kind).toBe("occ")}finally{u?.()}}),y("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const o=await s.get("i1");n(o?.title).toBe("first"),n(o?.version).toBe(99)}finally{u?.()}}),y("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l={tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,a)=>{await t.db.patch(a.doc._id,{version:99})},op:"update",timing:"before"}}}}};_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e).toBeInstanceOf(N),n(e.code).toBe("CONFLICT"),n(e.kind).toBe("trigger")}finally{u?.()}})}),S("shape-poke ordering",()=>{const b="shard-a",u={args:{},name:"messages"},h=(e,t,a,r)=>e.accept(t?.()??{},{connectionId:a,shapes:{[r]:u}}),i=(e,t,a)=>{let r=0,d=0;const c=g=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${g}`)},p={fetch:(g,q)=>{if(JSON.parse(q?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const B=a[d];if(d+=1,B===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(B))}},k={get:()=>p,getByName:()=>p,idFromName:g=>g},w={buildShapeDiff:c("buildShapeDiff"),computeOpLogShapeSeed:c("computeOpLogShapeSeed"),currentCdcEpoch:c("currentCdcEpoch"),deliverWhisperLocal:c("deliverWhisperLocal"),doName:()=>F(b,0),env:()=>({SHARD:k}),getWebSockets:()=>e.getSockets(),maskMetadata:c("maskMetadata"),nextPokeId:()=>(r+=1,`poke-${String(r)}`),readAttachment:g=>g.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:c("resolveShape"),rlsMetadata:c("rlsMetadata"),shardBinding:()=>"SHARD",sql:()=>t},f=I(w);if(f===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return f},l=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,a)=>{const r=await e.seedRelayShape(t,a,u,{identity:void 0,userId:void 0});if(r!=="ok")throw new Error(`seed failed: ${JSON.stringify(r)}`)},o=(e={})=>l({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});y("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o());const w=(await r(p)).map(f=>JSON.parse(f));n(w.map(f=>f.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),n(new Set(w.map(f=>f.pokeId)).size).toBe(1),n(w[1]?.shapeId).toBe("s1"),n(w[2]?.checkpoint).toBe(20)}finally{e?.()}}),y("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1"),k=h(d,t,"c-bob","s2");await s(c,p,"s1"),await s(c,k,"s2"),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3);const f=await r(k);n(f.length).toBe(0),await c.handleControl(o());const g=await r(p);n(g.length).toBe(3)}finally{e?.()}}),y("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o({epoch:"e2"}));const k=await r(p);n(k.length).toBe(0),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3)}finally{e?.()}})}),S("RLS identity under live subscription",()=>{const b="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},i=s=>{const o=[],e=[],t={fetch:(d,c)=>(o.push(JSON.parse(c?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},r=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>b,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:d=>d}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(d,c,p)=>(e.push(p),d===h.name?{columns:["id"],effectiveWhere:{org:p?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",sql:()=>s});if(r===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:r,posts:o,resolvedUnder:e}},l=async(s,o)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...o,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};y("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:o}=m();try{const{owner:e,resolvedUnder:t}=i(o.sql);await l(e,h),n(t.some(a=>a?.userId==="u1"&&a.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),y("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),y("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{W as defineEngineContractSuite};
@@ -1 +1 @@
1
- import{LunoraError as _}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{quoteIdentifier as A}from"./quoteIdentifier-CObIFRhb.mjs";import{d as T,n as $,e as p}from"./wire-codec-CKV-4MEN.mjs";import{runDrizzle as l}from"./runDrizzle-2ULFQR_k.mjs";import{sqlComparableProjection as S}from"./BIGINT_KEY_DIGITS-GvEBhyR5.mjs";import"./serializeSqlValue-B_-zaEWZ.mjs";const O=/^[A-Za-z_$][\w$]*$/u,b=e=>O.test(e)?e:`"${e.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,m="__doc__",i="__originals__",R=e=>{if(Object.hasOwn(e,i))throw new _("BAD_REQUEST",`"${i}" is reserved by the row store's document encoding and cannot be used as a field name — rename the field`);let t,r;for(const[s,a]of Object.entries(e)){const c=S(a);c!==void 0&&(t??={...e},r??=Object.create(null),t[s]=c,r[s]=a)}t&&r&&(t[i]=r);const n=t??e;try{return $(n)?JSON.stringify(p(n)):JSON.stringify(n)}catch(s){throw new _("BAD_REQUEST",`this document cannot be stored: ${s instanceof Error?s.message:String(s)}`)}},h=e=>{const t=T(JSON.parse(e)),r=t[i];if(r===null||typeof r!="object"||Array.isArray(r))return t;const n={...t};return delete n[i],{...n,...r}},G=(e,t)=>`${e}__geo_${t}`,E=(e,t)=>t==="_id"||t==="id"?`${e}id`:t==="_creationTime"?`${e}_creationTime`:`json_extract(${e}${m}, '$.${b(t).replaceAll("'","''")}')`,g=e=>E("",e),J=e=>o.raw(g(e)),N=(e,t)=>E(`${A(e)}.`,t),q=(e,t)=>o.raw(N(e,t)),B=(e,t,r,n)=>o`CREATE ${n?o`UNIQUE `:o``}INDEX IF NOT EXISTS ${o.identifier(e)} ON ${o.identifier(t)} (${r})`,f=o.identifier("__key__"),y=o.identifier("__value__"),I=o.identifier("__count__"),z=(e,t,r,n,s)=>o`INSERT INTO ${o.identifier(e)} (${f}, ${y}, ${I}) VALUES (${t}, ${r}, ${n}) ON CONFLICT(${f}) DO UPDATE SET ${s}`,d=new WeakMap,F=e=>{const t=d.get(e);if(t!==void 0)return t;const r=[];for(const[n,s]of Object.entries(e.shape)){const a=s._meta?.column;a&&r.push(Object.freeze([n,a]))}return Object.freeze(r),d.set(e,r),r},j=e=>{if(!e)return;const t=e[m];let r;typeof t=="string"?r=h(t):t&&typeof t=="object"?r=t:r={};const{id:n}=e;typeof n=="string"&&(r._id=n);const s=e._creationTime;return typeof s=="number"&&(r._creationTime=s),r},W=e=>{try{return j(e)}catch{return}},u=new WeakMap,k=e=>{const t=u.get(e);if(t!==void 0)return t;let r;try{l(e,o`CREATE VIRTUAL TABLE IF NOT EXISTS ${o.identifier("__lunora_fts_probe")} USING fts5(x)`),r=!0}catch{r=!1}finally{try{l(e,o`DROP TABLE IF EXISTS ${o.identifier("__lunora_fts_probe")}`)}catch{}}return u.set(e,r),r};export{I as A,m as D,f as a,y as b,z as c,B as d,J as e,q as f,G as g,W as h,k as i,g as j,R as k,h as l,b as m,i as n,N as q,j as r,F as t};
1
+ import{LunoraError as _}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{quoteIdentifier as A}from"./quoteIdentifier-CObIFRhb.mjs";import{d as T,n as $,e as p}from"./wire-codec-C-FpWm52.mjs";import{runDrizzle as l}from"./runDrizzle-2ULFQR_k.mjs";import{sqlComparableProjection as S}from"./BIGINT_KEY_DIGITS-GvEBhyR5.mjs";import"./serializeSqlValue-B_-zaEWZ.mjs";const O=/^[A-Za-z_$][\w$]*$/u,b=e=>O.test(e)?e:`"${e.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,m="__doc__",i="__originals__",R=e=>{if(Object.hasOwn(e,i))throw new _("BAD_REQUEST",`"${i}" is reserved by the row store's document encoding and cannot be used as a field name — rename the field`);let t,r;for(const[s,a]of Object.entries(e)){const c=S(a);c!==void 0&&(t??={...e},r??=Object.create(null),t[s]=c,r[s]=a)}t&&r&&(t[i]=r);const n=t??e;try{return $(n)?JSON.stringify(p(n)):JSON.stringify(n)}catch(s){throw new _("BAD_REQUEST",`this document cannot be stored: ${s instanceof Error?s.message:String(s)}`)}},h=e=>{const t=T(JSON.parse(e)),r=t[i];if(r===null||typeof r!="object"||Array.isArray(r))return t;const n={...t};return delete n[i],{...n,...r}},G=(e,t)=>`${e}__geo_${t}`,E=(e,t)=>t==="_id"||t==="id"?`${e}id`:t==="_creationTime"?`${e}_creationTime`:`json_extract(${e}${m}, '$.${b(t).replaceAll("'","''")}')`,g=e=>E("",e),J=e=>o.raw(g(e)),N=(e,t)=>E(`${A(e)}.`,t),q=(e,t)=>o.raw(N(e,t)),B=(e,t,r,n)=>o`CREATE ${n?o`UNIQUE `:o``}INDEX IF NOT EXISTS ${o.identifier(e)} ON ${o.identifier(t)} (${r})`,f=o.identifier("__key__"),y=o.identifier("__value__"),I=o.identifier("__count__"),z=(e,t,r,n,s)=>o`INSERT INTO ${o.identifier(e)} (${f}, ${y}, ${I}) VALUES (${t}, ${r}, ${n}) ON CONFLICT(${f}) DO UPDATE SET ${s}`,d=new WeakMap,F=e=>{const t=d.get(e);if(t!==void 0)return t;const r=[];for(const[n,s]of Object.entries(e.shape)){const a=s._meta?.column;a&&r.push(Object.freeze([n,a]))}return Object.freeze(r),d.set(e,r),r},j=e=>{if(!e)return;const t=e[m];let r;typeof t=="string"?r=h(t):t&&typeof t=="object"?r=t:r={};const{id:n}=e;typeof n=="string"&&(r._id=n);const s=e._creationTime;return typeof s=="number"&&(r._creationTime=s),r},W=e=>{try{return j(e)}catch{return}},u=new WeakMap,k=e=>{const t=u.get(e);if(t!==void 0)return t;let r;try{l(e,o`CREATE VIRTUAL TABLE IF NOT EXISTS ${o.identifier("__lunora_fts_probe")} USING fts5(x)`),r=!0}catch{r=!1}finally{try{l(e,o`DROP TABLE IF EXISTS ${o.identifier("__lunora_fts_probe")}`)}catch{}}return u.set(e,r),r};export{I as A,m as D,f as a,y as b,z as c,B as d,J as e,q as f,G as g,W as h,k as i,g as j,R as k,h as l,b as m,i as n,N as q,j as r,F as t};
@@ -1,4 +1,4 @@
1
- import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-2ULFQR_k.mjs";import{liftSourceId as A}from"./liftSourceId-CA3ENhXj.mjs";import{normalizeSourceValue as W}from"./liftSourceId-CA3ENhXj.mjs";import{runExternalSourceTick as C,materializeExternalRowsIncremental as D}from"./materializeExternalRows-CXfp_DGO.mjs";const p="__lunora_source_cursor",M=e=>e instanceof Date?`d:${e.toISOString()}`:typeof e=="bigint"?`b:${e.toString()}`:typeof e=="number"?`n:${e.toString()}`:`s:${e}`,v=e=>{const t=e.slice(2);switch(e[0]){case"b":return BigInt(t);case"d":return new Date(t);case"n":return Number(t);default:return t}},h=/^-?\d+$/,N=/^-?\d+(?:\.\d+)?$/,x=(e,t)=>e instanceof Date&&t instanceof Date?e.getTime()>t.getTime():typeof e=="bigint"&&typeof t=="bigint"||typeof e=="number"&&typeof t=="number"?e>t:typeof e=="string"&&typeof t=="string"&&N.test(e)&&N.test(t)?h.test(e)&&h.test(t)?BigInt(e)>BigInt(t):Number(e)>Number(t):String(e)>String(t),O=(e,t,o)=>{let n=o===null?void 0:v(o);for(const r of e){const c=r[t];if(c==null)continue;const a=c;(n===void 0||x(a,n))&&(n=a)}return n===void 0?null:M(n)},B=e=>{S(e,m`CREATE TABLE IF NOT EXISTS ${m.identifier(p)} (
1
+ import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-2ULFQR_k.mjs";import{liftSourceId as A}from"./liftSourceId-CA3ENhXj.mjs";import{normalizeSourceValue as W}from"./liftSourceId-CA3ENhXj.mjs";import{runExternalSourceTick as C,materializeExternalRowsIncremental as D}from"./materializeExternalRows-CAPAra-0.mjs";const p="__lunora_source_cursor",M=e=>e instanceof Date?`d:${e.toISOString()}`:typeof e=="bigint"?`b:${e.toString()}`:typeof e=="number"?`n:${e.toString()}`:`s:${e}`,v=e=>{const t=e.slice(2);switch(e[0]){case"b":return BigInt(t);case"d":return new Date(t);case"n":return Number(t);default:return t}},h=/^-?\d+$/,N=/^-?\d+(?:\.\d+)?$/,x=(e,t)=>e instanceof Date&&t instanceof Date?e.getTime()>t.getTime():typeof e=="bigint"&&typeof t=="bigint"||typeof e=="number"&&typeof t=="number"?e>t:typeof e=="string"&&typeof t=="string"&&N.test(e)&&N.test(t)?h.test(e)&&h.test(t)?BigInt(e)>BigInt(t):Number(e)>Number(t):String(e)>String(t),O=(e,t,o)=>{let n=o===null?void 0:v(o);for(const r of e){const c=r[t];if(c==null)continue;const a=c;(n===void 0||x(a,n))&&(n=a)}return n===void 0?null:M(n)},B=e=>{S(e,m`CREATE TABLE IF NOT EXISTS ${m.identifier(p)} (
2
2
  table_name TEXT NOT NULL,
3
3
  shard_key TEXT NOT NULL,
4
4
  watermark TEXT,
@@ -1 +1 @@
1
- import{applyCdcChanges as p}from"./CDC_LOG_TABLE-CMCaSndb.mjs";import{selectShapeRows as m}from"./selectShapeMembers-jydcnpzn.mjs";import{diffExternalSource as g,projectExternalSourceRow as l}from"./diffExternalSource-DgDJhslq.mjs";import{stableStringify as d}from"./stableStringify-DibjylKD.mjs";const x=async(t,s,a,e)=>{const{changes:o,nextBaseline:n}=g(s,a,e);return await p(t,o),{applied:o.length,nextBaseline:n}},R=async(t,s,a)=>{const{columns:e,deletedIds:o,table:n}=a,r=[];for(const f of s){const i=l(f,e),c=String(i._id);if(o?.has(c)){await t.get(c,n)&&r.push({id:c,op:"delete",seq:0,table:n,ts:0});continue}const u=await t.get(c,n);u&&d(l({...u,_id:c},e))===d(i)||r.push({doc:i,id:c,op:"insert",seq:0,table:n,ts:0})}return await p(t,r),{applied:r.length}},h=(t,s,a)=>{const e=new Map;for(const{doc:o,id:n}of m(t,s,void 0))e.set(n,d(l({...o,_id:n},a)));return e},_=async(t,s,a,e)=>{const o=h(t,e.table,e.columns);return x(s,a,o,e)};export{x as materializeExternalRows,R as materializeExternalRowsIncremental,h as readExternalSourceBaseline,_ as runExternalSourceTick};
1
+ import{applyCdcChanges as p}from"./CDC_LOG_TABLE-CAyqu8cg.mjs";import{selectShapeRows as m}from"./selectShapeMembers-DqikYFjS.mjs";import{diffExternalSource as g,projectExternalSourceRow as l}from"./diffExternalSource-DgDJhslq.mjs";import{stableStringify as d}from"./stableStringify-DibjylKD.mjs";const x=async(t,s,a,e)=>{const{changes:o,nextBaseline:n}=g(s,a,e);return await p(t,o),{applied:o.length,nextBaseline:n}},R=async(t,s,a)=>{const{columns:e,deletedIds:o,table:n}=a,r=[];for(const f of s){const i=l(f,e),c=String(i._id);if(o?.has(c)){await t.get(c,n)&&r.push({id:c,op:"delete",seq:0,table:n,ts:0});continue}const u=await t.get(c,n);u&&d(l({...u,_id:c},e))===d(i)||r.push({doc:i,id:c,op:"insert",seq:0,table:n,ts:0})}return await p(t,r),{applied:r.length}},h=(t,s,a)=>{const e=new Map;for(const{doc:o,id:n}of m(t,s,void 0))e.set(n,d(l({...o,_id:n},a)));return e},_=async(t,s,a,e)=>{const o=h(t,e.table,e.columns);return x(s,a,o,e)};export{x as materializeExternalRows,R as materializeExternalRowsIncremental,h as readExternalSourceBaseline,_ as runExternalSourceTick};
@@ -1,4 +1,4 @@
1
- import{LunoraError as p}from"@lunora/errors";import{S as L,y as N,l as h}from"./ctx-db-companions-Z9JQ9xo1.mjs";import{sql as e}from"drizzle-orm";import{aggregateTableName as l}from"./aggregateTableName-BvenuaDR.mjs";import{backfillSearchIndexesForTable as R}from"./backfillAggregateIndexes-CMtnLFZa.mjs";import{migrateCdcLog as O,migrateCdcMeta as x}from"./CDC_LOG_TABLE-CMCaSndb.mjs";import{migrateClientWatermark as C}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{migrateCommitSeq as $}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{migrateGlobalShapeSnapshot as U}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{migrateIdempotency as b}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{m as D}from"./ctx-db-relay-shapes-Y0jy6_Qb.mjs";import{m as X}from"./ctx-db-search-state-ruTuCsxa.mjs";import{migrateShapePokeCursor as G}from"./SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs";import{runDrizzle as a}from"./runDrizzle-2ULFQR_k.mjs";import{D as M,d as E,e as g,t as F,i as B,g as y,a as Y,b as k,A as u}from"./do-sql-Cv3yRshL.mjs";import{renderSql as v}from"./param-DlozcSQu.mjs";import{migrateDurableStreams as P}from"./appendStreamChunk-C1Ok4b6J.mjs";import{rankTableName as w,sortColumnName as j}from"./RANK_TIEBREAK-B6iDKDW3.mjs";import{migrateReactorState as K}from"./REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{recordSchemaVersion as V}from"./SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";const A=e`_creationTime, id`,H=(i,o,n,r,t,s)=>{const f=a(i,e`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${o} AND tbl_name = ${n}`).toArray()[0]?.sql;if(f==null)return;const m=c=>{const I=c.indexOf("(");return I===-1?void 0:c.slice(I,c.lastIndexOf(")")+1)},T=m(v("sqlite",E(o,n,r,t)).sql),_=m(f);if(!(T===void 0||_===void 0||T===_)){if(t){const c=e.join(s.map(S=>e`${S} IS NOT NULL`),e` AND `);if(a(i,e`SELECT 1 FROM ${e.identifier(n)} WHERE ${c} GROUP BY ${r} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new p("INTERNAL",`unique index "${o}" on "${n}" cannot be re-created with its new column list: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)}a(i,e`DROP INDEX IF EXISTS ${e.identifier(o)}`)}},W=(i,o,n)=>{for(const r of n.indexes){const t=`${o}_${r.name}`,s=r.unique??!1,d=r.fields.map(T=>g(T)),f=e.join(d,e`, `),m=s?f:e`${f}, ${A}`;H(i,t,o,m,s,d),a(i,E(t,o,m,s))}for(const[r,t]of F(n)){if(!t.unique)continue;const s=`${o}_unique_${r}`;a(i,E(s,o,g(r),!0))}},z=(i,o,n)=>{if(!(!n.searchIndexes||n.searchIndexes.length===0||!B(i))){for(const r of n.searchIndexes){const t=L(o,r.name);a(i,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(t)} USING fts5(${e.identifier(N)}, ${e.identifier(h)} UNINDEXED)`),a(i,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${t}__vocab`)} USING fts5vocab(${e.identifier(t)}, ${e.raw("instance")})`)}R(i,o,n)}},J=(i,o,n)=>{if(n.geoIndexes)for(const r of n.geoIndexes){const t=y(o,r.name);a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__geohash__")} TEXT NOT NULL, ${e.identifier("__lat__")} REAL NOT NULL, ${e.identifier("__lng__")} REAL NOT NULL)`);const s=`${o}__geo_${r.name}__btree`;a(i,E(s,t,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},Q=(i,o,n)=>{if(n.aggregateIndexes)for(const r of n.aggregateIndexes){const t=l(o,r.name);a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${Y} TEXT PRIMARY KEY, ${k} REAL, ${u} INTEGER NOT NULL DEFAULT 0)`),a(i,e`PRAGMA table_info(${e.identifier(t)})`).toArray().some(d=>d.name==="__count__")||a(i,e`ALTER TABLE ${e.identifier(t)} ADD COLUMN ${u} INTEGER NOT NULL DEFAULT 0`)}},Z=(i,o,n)=>{if(n.rankIndexes)for(const r of n.rankIndexes){const t=w(o,r.name),s=r.sortBy.map((_,c)=>j(c)),d=s.map(_=>e`${e.identifier(_)} BLOB`),f=d.length>0?e`, ${e.join(d,e`, `)}`:e``;a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${f})`);const m=[e`${e.identifier("__partition__")} ASC`];for(const[_,c]of s.entries()){const I=r.sortBy[_]?.direction;m.push(e`${e.identifier(c)} ${e.raw(I==="desc"?"DESC":"ASC")}`)}m.push(e`${e.identifier("__id__")} ASC`);const T=`${o}__rank_${r.name}__btree`;a(i,E(T,t,e.join(m,e`, `),!1))}},Se=(i,o,n={})=>{n.schemaSnapshot!==void 0&&V(i,n.schemaSnapshot.hash,n.schemaSnapshot.json),X(i);for(const[r,t]of Object.entries(o.tables))t.shardMode?.kind!=="global"&&(a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(r)} (
1
+ import{LunoraError as p}from"@lunora/errors";import{S as L,y as N,l as h}from"./ctx-db-companions-B4O4d95S.mjs";import{sql as e}from"drizzle-orm";import{aggregateTableName as l}from"./aggregateTableName-C7o-gpms.mjs";import{backfillSearchIndexesForTable as R}from"./backfillAggregateIndexes-pQWaX2Yu.mjs";import{migrateCdcLog as O,migrateCdcMeta as x}from"./CDC_LOG_TABLE-CAyqu8cg.mjs";import{migrateClientWatermark as C}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{migrateCommitSeq as $}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{migrateGlobalShapeSnapshot as U}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{migrateIdempotency as b}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{m as D}from"./ctx-db-relay-shapes-Bg5YYnmN.mjs";import{m as X}from"./ctx-db-search-state-ruTuCsxa.mjs";import{migrateShapePokeCursor as G}from"./SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs";import{runDrizzle as a}from"./runDrizzle-2ULFQR_k.mjs";import{D as M,d as E,e as g,t as F,i as B,g as y,a as Y,b as k,A as u}from"./do-sql-FNOnpyHm.mjs";import{renderSql as v}from"./param-DlozcSQu.mjs";import{migrateDurableStreams as P}from"./appendStreamChunk-C1Ok4b6J.mjs";import{rankTableName as w,sortColumnName as j}from"./RANK_TIEBREAK-CkNuGm6a.mjs";import{migrateReactorState as K}from"./REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{recordSchemaVersion as V}from"./SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";const A=e`_creationTime, id`,H=(i,o,n,r,t,s)=>{const f=a(i,e`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${o} AND tbl_name = ${n}`).toArray()[0]?.sql;if(f==null)return;const m=c=>{const I=c.indexOf("(");return I===-1?void 0:c.slice(I,c.lastIndexOf(")")+1)},T=m(v("sqlite",E(o,n,r,t)).sql),_=m(f);if(!(T===void 0||_===void 0||T===_)){if(t){const c=e.join(s.map(S=>e`${S} IS NOT NULL`),e` AND `);if(a(i,e`SELECT 1 FROM ${e.identifier(n)} WHERE ${c} GROUP BY ${r} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new p("INTERNAL",`unique index "${o}" on "${n}" cannot be re-created with its new column list: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)}a(i,e`DROP INDEX IF EXISTS ${e.identifier(o)}`)}},W=(i,o,n)=>{for(const r of n.indexes){const t=`${o}_${r.name}`,s=r.unique??!1,d=r.fields.map(T=>g(T)),f=e.join(d,e`, `),m=s?f:e`${f}, ${A}`;H(i,t,o,m,s,d),a(i,E(t,o,m,s))}for(const[r,t]of F(n)){if(!t.unique)continue;const s=`${o}_unique_${r}`;a(i,E(s,o,g(r),!0))}},z=(i,o,n)=>{if(!(!n.searchIndexes||n.searchIndexes.length===0||!B(i))){for(const r of n.searchIndexes){const t=L(o,r.name);a(i,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(t)} USING fts5(${e.identifier(N)}, ${e.identifier(h)} UNINDEXED)`),a(i,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${t}__vocab`)} USING fts5vocab(${e.identifier(t)}, ${e.raw("instance")})`)}R(i,o,n)}},J=(i,o,n)=>{if(n.geoIndexes)for(const r of n.geoIndexes){const t=y(o,r.name);a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__geohash__")} TEXT NOT NULL, ${e.identifier("__lat__")} REAL NOT NULL, ${e.identifier("__lng__")} REAL NOT NULL)`);const s=`${o}__geo_${r.name}__btree`;a(i,E(s,t,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},Q=(i,o,n)=>{if(n.aggregateIndexes)for(const r of n.aggregateIndexes){const t=l(o,r.name);a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${Y} TEXT PRIMARY KEY, ${k} REAL, ${u} INTEGER NOT NULL DEFAULT 0)`),a(i,e`PRAGMA table_info(${e.identifier(t)})`).toArray().some(d=>d.name==="__count__")||a(i,e`ALTER TABLE ${e.identifier(t)} ADD COLUMN ${u} INTEGER NOT NULL DEFAULT 0`)}},Z=(i,o,n)=>{if(n.rankIndexes)for(const r of n.rankIndexes){const t=w(o,r.name),s=r.sortBy.map((_,c)=>j(c)),d=s.map(_=>e`${e.identifier(_)} BLOB`),f=d.length>0?e`, ${e.join(d,e`, `)}`:e``;a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${f})`);const m=[e`${e.identifier("__partition__")} ASC`];for(const[_,c]of s.entries()){const I=r.sortBy[_]?.direction;m.push(e`${e.identifier(c)} ${e.raw(I==="desc"?"DESC":"ASC")}`)}m.push(e`${e.identifier("__id__")} ASC`);const T=`${o}__rank_${r.name}__btree`;a(i,E(T,t,e.join(m,e`, `),!1))}},Se=(i,o,n={})=>{n.schemaSnapshot!==void 0&&V(i,n.schemaSnapshot.hash,n.schemaSnapshot.json),X(i);for(const[r,t]of Object.entries(o.tables))t.shardMode?.kind!=="global"&&(a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(r)} (
2
2
  id TEXT PRIMARY KEY,
3
3
  _creationTime REAL NOT NULL,
4
4
  ${e.identifier(M)} TEXT NOT NULL
@@ -1 +1 @@
1
- import{sql as o}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-2ULFQR_k.mjs";import{e}from"./do-sql-Cv3yRshL.mjs";const E=(s,t,f,r)=>{const d=f-(t.after??0),i=[o`${e(t.field)} IS NOT NULL`,o`${e(t.field)} < ${d}`];t.softDeleteField!==void 0&&i.push(o`${e(t.softDeleteField)} IS NULL`);const l=o`SELECT id FROM ${o.identifier(t.table)} WHERE ${o.join(i,o` AND `)} LIMIT ${o.raw(String(Math.max(0,Math.floor(r))+1))}`,n=h(s,l).toArray(),a=n.length>r,$=n.slice(0,r).map(c=>c.id);return{hasMore:a,ids:$}};export{E as selectExpiredIds};
1
+ import{sql as o}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-2ULFQR_k.mjs";import{e}from"./do-sql-FNOnpyHm.mjs";const E=(s,t,f,r)=>{const d=f-(t.after??0),i=[o`${e(t.field)} IS NOT NULL`,o`${e(t.field)} < ${d}`];t.softDeleteField!==void 0&&i.push(o`${e(t.softDeleteField)} IS NULL`);const l=o`SELECT id FROM ${o.identifier(t.table)} WHERE ${o.join(i,o` AND `)} LIMIT ${o.raw(String(Math.max(0,Math.floor(r))+1))}`,n=h(s,l).toArray(),a=n.length>r,$=n.slice(0,r).map(c=>c.id);return{hasMore:a,ids:$}};export{E as selectExpiredIds};
@@ -1 +1 @@
1
- import{sql as e}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-2ULFQR_k.mjs";import{D as p,r as d,e as h}from"./do-sql-Cv3yRshL.mjs";import{sqliteInList as w}from"./param-DlozcSQu.mjs";import{c as S}from"./where-sql-B1l5NcUZ.mjs";import{serializeSqlValue as $}from"./serializeSqlValue-B_-zaEWZ.mjs";const C={fieldRef:h,serialize:$},g=o=>{if(o.length!==0)return w(e`${e.identifier("id")}`,o,!1)},u=(o,i)=>{const r=[];i&&r.push(i);const t=S(o,C);return t&&r.push(t),r.length===0?e``:e` WHERE ${e.join(r,e` AND `)}`},v=(o,i,r)=>{const t=u(r,void 0),s=m(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${t}`).toArray(),f=[];for(const l of s){const n=d(l),{id:c}=l;n!==void 0&&typeof c=="string"&&f.push({doc:n,id:c})}return f},z=(o,i,r,t)=>{const s=new Map;if(t.length===0)return s;const f=u(r,g(t)),l=m(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${f}`).toArray();for(const n of l){const c=d(n),{id:a}=n;c!==void 0&&typeof a=="string"&&s.set(a,c)}return s};export{z as selectShapeMembers,v as selectShapeRows};
1
+ import{sql as e}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-2ULFQR_k.mjs";import{D as p,r as d,e as h}from"./do-sql-FNOnpyHm.mjs";import{sqliteInList as w}from"./param-DlozcSQu.mjs";import{c as S}from"./where-sql-B1l5NcUZ.mjs";import{serializeSqlValue as $}from"./serializeSqlValue-B_-zaEWZ.mjs";const C={fieldRef:h,serialize:$},g=o=>{if(o.length!==0)return w(e`${e.identifier("id")}`,o,!1)},u=(o,i)=>{const r=[];i&&r.push(i);const t=S(o,C);return t&&r.push(t),r.length===0?e``:e` WHERE ${e.join(r,e` AND `)}`},v=(o,i,r)=>{const t=u(r,void 0),s=m(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${t}`).toArray(),f=[];for(const l of s){const n=d(l),{id:c}=l;n!==void 0&&typeof c=="string"&&f.push({doc:n,id:c})}return f},z=(o,i,r,t)=>{const s=new Map;if(t.length===0)return s;const f=u(r,g(t)),l=m(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${f}`).toArray();for(const n of l){const c=d(n),{id:a}=n;c!==void 0&&typeof a=="string"&&s.set(a,c)}return s};export{z as selectShapeMembers,v as selectShapeRows};
@@ -1 +1 @@
1
- import{stableStringify as r}from"./stableStringify-DibjylKD.mjs";import{e as o}from"./wire-codec-CKV-4MEN.mjs";const m=e=>r(o(e));export{m as stableWireKey};
1
+ import{stableStringify as r}from"./stableStringify-DibjylKD.mjs";import{e as o}from"./wire-codec-C-FpWm52.mjs";const m=e=>r(o(e));export{m as stableWireKey};
@@ -0,0 +1 @@
1
+ import{t as g,f as j}from"./base64-DfpzS4o_.mjs";const o="$lunora.wire$",d=64,p=1024,w="__proto__",A={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},l={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},O=e=>{if(e===null||typeof e!="object")return!1;const n=Object.getPrototypeOf(e);return n===null||n===Object.prototype},E=(e,n=0)=>{if(n>d)return!0;if(e===null)return!1;const f=typeof e;if(f==="string"||f==="boolean")return!1;if(f==="number")return!Number.isFinite(e);if(f!=="object")return!0;if(Array.isArray(e))return e.length>0&&e[0]===o?!0:e.some(a=>a===void 0||E(a,n+1));if(!O(e)||Object.hasOwn(e,w))return!0;for(const a of Object.keys(e)){const s=e[a];if(s!==void 0&&E(s,n+1))return!0}return!1},b=(e,n=0)=>{if(n>d)throw new RangeError(`wire-codec: value nesting exceeds the ${d}-level limit`);if(e===void 0)return[o,"undefined"];if(e===null)return null;const f=typeof e;if(f==="bigint")return[o,"bigint",e.toString()];if(f==="number"){const r=e;return Number.isNaN(r)?[o,"nan"]:r===1/0?[o,"inf"]:r===-1/0?[o,"-inf"]:r}if(f!=="object")return e;if(e instanceof Date)return[o,"date",b(e.getTime(),n+1)];if(e instanceof Error){const r=e,t={};for(const i of Object.keys(r)){if(r[i]===void 0)continue;const u=b(r[i],n+1);i===w?Object.defineProperty(t,i,{configurable:!0,enumerable:!0,value:u,writable:!0}):t[i]=u}const c=[o,"error",String(r.name),String(r.message),t];return r.cause!==void 0&&c.push(b(r.cause,n+1)),c}if(e instanceof URL)return[o,"url",e.href];if(e instanceof Map)return[o,"map",[...e.entries()].map(([r,t])=>[b(r,n+1),b(t,n+1)])];if(e instanceof Set)return[o,"set",[...e].map(r=>b(r,n+1))];if(e instanceof ArrayBuffer)return[o,"bytes",g(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const r=e,t=r.constructor.name,c=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);return t==="Uint8Array"?[o,"bytes",g(c)]:[o,"bytes",g(c),t]}if(Array.isArray(e)){const r=e.map(t=>b(t,n+1));return r.length>0&&r[0]===o?[o,"arr",r]:r}if(!O(e)){const r=e.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${r} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const a=e,s={};for(const r of Object.keys(a)){const t=a[r];if(t===void 0)continue;const c=b(t,n+1);r===w?Object.defineProperty(s,r,{configurable:!0,enumerable:!0,value:c,writable:!0}):s[r]=c}return s},y=(e,n=0)=>{if(n>d)throw new RangeError(`wire-codec: value nesting exceeds the ${d}-level limit`);if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===o)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(r=>y(r,n+1));case"bigint":{const r=e[2];if(typeof r!="string"||r.length>p||!/^-?\d+$/.test(r))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${p} digits)`);return BigInt(r)}case"date":{const r=y(e[2],n+1);if(typeof r!="number")throw new TypeError("wire-codec: malformed date — epoch must be a number");return new Date(r)}case"map":{const r=e[2];return new Map(r.map(t=>{if(!Array.isArray(t)||t.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[y(t[0],n+1),y(t[1],n+1)]}))}case"set":return new Set(e[2].map(r=>y(r,n+1)));case"url":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed url — href must be a string");return new URL(r)}case"error":{const r=e[2],t=e[3];if(typeof r!="string"||typeof t!="string")throw new TypeError("wire-codec: malformed error — name and message must be strings");const c=(Object.hasOwn(l,r)?l[r]:void 0)??Error,i=new c(t);i.name!==r&&Object.defineProperty(i,"name",{configurable:!0,value:r,writable:!0});const u=y(e[4],n+1);if(u===null||typeof u!="object"||Array.isArray(u))throw new TypeError("wire-codec: malformed error — props must be an object");for(const m of Object.keys(u))m===w?Object.defineProperty(i,m,{configurable:!0,enumerable:!0,value:u[m],writable:!0}):i[m]=u[m];return e.length>5&&Object.defineProperty(i,"cause",{configurable:!0,value:y(e[5],n+1),writable:!0}),i}case"bytes":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const t=j(r);if(g(t)!==r)throw new TypeError("wire-codec: malformed bytes — payload must be canonical padded base64");const c=e[3]??"Uint8Array";if(c==="ArrayBuffer")return t.buffer.byteLength===t.byteLength?t.buffer:t.slice().buffer;const i=Object.hasOwn(A,c)?A[c]:void 0;return i?new i(t.slice().buffer):t}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(r=>y(r,n+1))}return e.map(s=>y(s,n+1))}const f=e,a={};for(const s of Object.keys(f)){const r=y(f[s],n+1);s===w?Object.defineProperty(a,s,{configurable:!0,enumerable:!0,value:r,writable:!0}):a[s]=r}return a};export{y as d,b as e,O as i,E as n};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/shard-engine",
3
- "version": "1.0.0-alpha.56",
3
+ "version": "1.0.0-alpha.58",
4
4
  "description": "Host-neutral reactive engine for Lunora: per-shard state, OCC, CDC, reactive subscriptions, and the poke protocol. Consumes @lunora/platform host contracts and can be mounted on any platform host.",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -48,8 +48,8 @@
48
48
  "access": "public"
49
49
  },
50
50
  "dependencies": {
51
- "@lunora/errors": "1.0.0-alpha.32",
52
- "@lunora/platform": "1.0.0-alpha.26",
51
+ "@lunora/errors": "1.0.0-alpha.33",
52
+ "@lunora/platform": "1.0.0-alpha.27",
53
53
  "drizzle-orm": "^0.45.2"
54
54
  },
55
55
  "engines": {
@@ -1,15 +0,0 @@
1
- import{LunoraError as p}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{quoteIdentifier as f}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as m,runDrizzle as n}from"./runDrizzle-2ULFQR_k.mjs";import{k as A,l as q}from"./do-sql-Cv3yRshL.mjs";import{ConflictError as I}from"./ConflictError-C8GtJmjS.mjs";const c="__cdc_log",N=`INSERT INTO ${f(c)} (ts, ${f("table")}, id, op, doc) VALUES (?, ?, ?, ?, ?)`,O="__cdc_log_table_seq",y=e=>{n(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(c)} (
2
- seq INTEGER PRIMARY KEY AUTOINCREMENT,
3
- ts REAL NOT NULL,
4
- ${t.identifier("table")} TEXT NOT NULL,
5
- id TEXT NOT NULL,
6
- op TEXT NOT NULL,
7
- doc TEXT
8
- )`);try{n(e,t`CREATE INDEX IF NOT EXISTS ${t.identifier(O)} ON ${t.identifier(c)} (${t.identifier("table")}, seq)`)}catch{}},U=(e,o,r,i,s,d)=>{const a=d===void 0?null:A(d);m(e,N,o,r,i,s,a)},S=90,u=e=>!e||e.size===0?t``:t` AND ${t.identifier("table")} IN (${t.join([...e].map(o=>t`${o}`),t`, `)})`,g=(e,o={})=>{const r=o.sinceSeq??0,i=Math.max(1,Math.min(o.limit??1e3,1e4)),s=u(o.tables),a=n(e,t`SELECT seq, ts, ${t.identifier("table")}, id, op, doc FROM ${t.identifier(c)} WHERE seq > ${r}${s} ORDER BY seq ASC LIMIT ${i}`).toArray().map(E=>{const C={id:E.id,op:E.op,seq:E.seq,table:E.table,ts:E.ts};return E.doc===null?C:{...C,doc:q(E.doc)}});return{changes:a,cursor:a.at(-1)?.seq??r}},X=(e,o,r)=>{if(r.size===0)return!1;const i=[...r];for(let s=0;s<i.length;s+=S){const d=new Set(i.slice(s,s+S));if(n(e,t`SELECT 1 AS hit FROM ${t.identifier(c)} WHERE seq > ${o}${u(d)} LIMIT 1`).toArray().length>0)return!0}return!1},l=new WeakMap,R=e=>new Set(n(e,t`SELECT name FROM sqlite_master WHERE type = 'table'`).toArray().map(o=>o.name)),B=(e,o)=>{if(o.size===0)return!1;let r=l.get(e),i=!1;r===void 0&&(r=R(e),i=!0,l.set(e,r));for(const s of o)if(!r.has(s)&&(i||(r=R(e),i=!0,l.set(e,r),!r.has(s))))return!1;return!0},H=(e,o,r,i)=>n(e,t`SELECT id, op, MAX(seq) AS maxSeq, COUNT(*) AS ops FROM ${t.identifier(c)}
9
- WHERE ${t.identifier("table")} = ${o} AND seq > ${r} AND seq <= ${i}
10
- GROUP BY id
11
- ORDER BY maxSeq ASC`).toArray().map(d=>{const a=d.op;return{id:d.id,op:a==="insert"&&d.ops>1?"update":a,seq:d.maxSeq}}),x=(e,o,r)=>{n(e,t`DELETE FROM ${t.identifier(c)} WHERE seq IN (
12
- SELECT seq FROM ${t.identifier(c)} WHERE seq <= ${o} ORDER BY seq ASC LIMIT ${r}
13
- )`)},W=(e,o,r)=>{n(e,t`UPDATE ${t.identifier(c)} SET doc = NULL WHERE seq IN (
14
- SELECT seq FROM ${t.identifier(c)} WHERE seq <= ${o} AND doc IS NOT NULL ORDER BY seq ASC LIMIT ${r}
15
- )`)},v=(e,o)=>{if(o<=0)return n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(c)}`).toArray()[0]?.seq??void 0;const i=n(e,t`SELECT seq FROM ${t.identifier(c)} ORDER BY seq DESC LIMIT 1 OFFSET ${o-1}`).toArray()[0]?.seq;return i===void 0?void 0:i-1},Y=e=>{const r=n(e,t`SELECT seq FROM sqlite_sequence WHERE name = ${c}`).toArray()[0]?.seq;return typeof r=="number"?r:n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(c)}`).toArray()[0]?.seq??0},P=(e,o)=>e!==void 0&&e>o+1,G=(e,o,r)=>new p("CDC_LOG_TRIMMED",`${r==="global"?"global cdc":"cdc"} entries at or below seq ${String(e-1)} have been trimmed; resume from a snapshot (sinceSeq ${String(o)} is below the retained window)`,{status:409}),$=e=>n(e,t`SELECT MIN(seq) AS seq FROM ${t.identifier(c)}`).toArray()[0]?.seq??void 0,K=e=>{const r=n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(c)} WHERE op <> 'delete' AND doc IS NULL`).toArray()[0]?.seq??void 0,i=$(e);return r===void 0?i:Math.max(r+1,i??0)},T="__cdc_meta",L=e=>{n(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(T)} (id INTEGER PRIMARY KEY CHECK (id = 1), epoch TEXT NOT NULL)`)},z=e=>{L(e);const r=n(e,t`SELECT epoch FROM ${t.identifier(T)} WHERE id = 1`).toArray()[0]?.epoch;if(typeof r=="string"&&r.length>0)return r;const i=crypto.randomUUID();return n(e,t`INSERT INTO ${t.identifier(T)} (id, epoch) VALUES (1, ${i})`),i},V=e=>{L(e);const o=crypto.randomUUID();return n(e,t`INSERT INTO ${t.identifier(T)} (id, epoch) VALUES (1, ${o}) ON CONFLICT(id) DO UPDATE SET epoch = excluded.epoch`),o},M=async(e,o)=>{if(o.op==="delete"){await e.delete(o.id,o.table);return}const r=o.doc??{};try{await e.insert(o.table,r,{allowExplicitId:!0})}catch(i){if(!(i instanceof I))throw i;const s={...r};delete s._id,await e.replace(o.id,s,o.table,{allowExplicitId:!0})}},k=async(e,o)=>{for(const r of o)await M(e,r)};export{N as CDC_APPEND_SQL,c as CDC_LOG_TABLE,O as CDC_LOG_TABLE_SEQ_INDEX,T as CDC_META_TABLE,U as appendCdcChange,k as applyCdcChanges,V as bumpCdcEpoch,B as cdcCanVouchFor,v as cdcSeqLeavingRows,X as cdcTouchesTables,G as cdcTrimmedError,W as compactCdcDocs,P as cursorBelowRetainedFloor,y as migrateCdcLog,L as migrateCdcMeta,K as minCdcReplayableSeq,$ as minCdcSeq,H as readCdcChangeKeys,g as readCdcChanges,Y as readCdcCursor,z as readCdcEpoch,x as trimCdcChanges};
@@ -1,4 +0,0 @@
1
- import{LunoraError as h}from"@lunora/errors";const m="x",d=" ",E={'"':'"',"'":"'","[":"]","`":"`"},f=(n,t)=>{let e=t+2;for(;e<n.length&&n[e]!==`
2
- `;)e+=1;return e},g=(n,t)=>{const e=n.indexOf("*/",t+2);return e===-1?-1:e+2},S=n=>{const t=n.split("");let e=0;for(;e<n.length;){const o=n[e]??"",c=E[o];if(o==="-"&&n[e+1]==="-"){const s=f(n,e);t.fill(d,e,s),e=s}else if(o==="/"&&n[e+1]==="*"){const s=g(n,e);if(s===-1)return;t.fill(d,e,s),e=s}else if(c!==void 0){let s=e+1;for(;s<n.length;)if(n[s]!==c)s+=1;else if(c!=="]"&&n[s+1]===c)s+=2;else break;if(s>=n.length)return;t.fill(m,e,s+1),e=s+1}else e+=1}for(let o=0;o<n.length;o+=1)n[o]===`
3
- `&&(t[o]=`
4
- `);return t.join("")},L=/^(?:explain\s+(?:query\s+plan\s+)?)?(?:select|with)\b/iu,A=/\b(?:alter|attach|create|delete|detach|drop|insert|pragma|reindex|replace|truncate|update|vacuum)\b/iu,p=/^\w+/u,N=/;\s*$/u,x=/\s/u,y=n=>{let t=0;for(;t<n.length;){const e=n[t];if(e!==void 0&&x.test(e))t+=1;else if(e==="-"&&n[t+1]==="-")t=f(n,t);else if(e==="/"&&n[t+1]==="*"){const o=g(n,t);if(o===-1)break;t=o}else break}return t},u=n=>{const t=y(n),e=n.slice(t).trimEnd();if(e==="")return{code:"SQL_EMPTY",message:"the query is empty"};const c=(S(e)??e).replace(N,""),s=e.slice(0,c.length),r=c.indexOf(";");if(r!==-1)return{code:"SQL_MULTIPLE_STATEMENTS",length:1,message:"only a single statement may be run",offset:t+r};const i="the SQL editor is read-only — only SELECT / WITH / EXPLAIN queries are allowed";if(!L.test(s))return{code:"SQL_NOT_READONLY",length:p.exec(s)?.[0].length??1,message:i,offset:t};const a=A.exec(s);if(a!==null)return{code:"SQL_NOT_READONLY",length:a[0].length,message:`${i} (\`${a[0].toUpperCase()}\` is not allowed)`,offset:t+a.index}},l=1e3,_=n=>{const t=u(n);if(t!==void 0)throw new h(t.code,t.message,{status:400})},b=(n,t)=>{_(t);const e=n.exec(t).toArray(),o=e.length>l?e.slice(0,l):e;return{columns:o.length>0?Object.keys(o[0]):[],rowCount:e.length,rows:o,truncated:e.length>l}},O=/near "([^"]*)": syntax error/iu,T=/^SCAN (?:TABLE )?(?!CONSTANT\b|SUBQUERY\b)([^\s(]+)/u,R=(n,t)=>{if(t==="")return{};const e=n.indexOf(t);return e===-1?{}:{length:t.length,offset:e}},v=(n,t)=>{const e=u(t);if(e!==void 0)return{diagnostics:e.code==="SQL_EMPTY"?[]:[{length:e.length,message:e.message,offset:e.offset,severity:"error",source:"gate"}],plan:[]};let o;try{o=n.exec(`EXPLAIN QUERY PLAN ${t}`).toArray().map(r=>{const{detail:i}=r;return typeof i=="string"?i:""}).filter(r=>r!=="")}catch(r){const i=r instanceof Error?r.message:String(r),a=O.exec(i);return{diagnostics:[{...a?R(t,a[1]??""):{},message:i,severity:"error",source:"syntax"}],plan:[]}}const c=[],s=new Set;for(const r of o){const i=T.exec(r);if(i){const a=i[1]??"";s.has(a)||(s.add(a),c.push({message:`full table scan on \`${a}\` — this query reads every row`,severity:"warning",source:"plan"}))}}return{diagnostics:c,plan:o}};export{l as MAX_SQL_ROWS,_ as assertReadonly,v as lintReadonlySql,b as runReadonlySql};
@@ -1 +0,0 @@
1
- import{LunoraError as $}from"@lunora/errors";import{D as it}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{c as ln,S as un,l as Me,a as fn}from"./ctx-db-companions-Z9JQ9xo1.mjs";import{sql as i}from"drizzle-orm";import{d as hn}from"./wire-codec-CKV-4MEN.mjs";import{throwingScheduler as wn,aggregateSqlFunction as De,normalizeCountArgument as pn}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as Qe,encodeAggregateKey as ze,readAggregateValue as Je}from"./aggregateTableName-BvenuaDR.mjs";import{mergeWhere as J,CountRlsUnsupportedError as Ve,selectIndexForGroupBy as gn,selectIndexForCount as $n,selectIndexForAggregate as yn}from"./CountRlsUnsupportedError-Bdfupt3g.mjs";import{backfillSearchIndexesForTable as En,searchIndexCoversTable as mn}from"./backfillAggregateIndexes-CMtnLFZa.mjs";import{backfillAggregateIndexes as _r,backfillRankIndexes as Rr,backfillSearchIndexes as Tr}from"./backfillAggregateIndexes-CMtnLFZa.mjs";import{appendCdcChange as Sn}from"./CDC_LOG_TABLE-CMCaSndb.mjs";import{CDC_LOG_TABLE as Ar,applyCdcChanges as Ir,bumpCdcEpoch as Cr,cdcCanVouchFor as xr,cdcSeqLeavingRows as br,cdcTouchesTables as Mr,cdcTrimmedError as Dr,compactCdcDocs as Lr,cursorBelowRetainedFloor as kr,minCdcReplayableSeq as Fr,minCdcSeq as qr,readCdcChangeKeys as Br,readCdcChanges as Wr,readCdcCursor as Ur,readCdcEpoch as Pr,trimCdcChanges as Gr}from"./CDC_LOG_TABLE-CMCaSndb.mjs";import{allocateCommitSeq as _n,COMMIT_SEQ_FIELD as Rn}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{isMemoryTable as St}from"./clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as _t}from"./computeRankPage-CrFzfXK5.mjs";import{SCAN_DEP as H}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as j,runSql as me}from"./runDrizzle-2ULFQR_k.mjs";import{D as oe,k as ce,r as le,b as Le,A as Ye,a as ke,e as X,t as Nt,j as Be,q as Rt,i as Tn,h as jt,g as vn}from"./do-sql-Cv3yRshL.mjs";import{renderSql as Kt,unionAll as st,WORKERD_SQLITE_LIMITS as Qt,sqliteInList as An}from"./param-DlozcSQu.mjs";import{coveringGeohashes as In,boundingBoxGeohashes as Cn,haversineMeters as xn,pointInBoundingBox as bn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Mn}from"./NotFoundError-BhF7FeFr.mjs";import{softDeleteScope as de,normalizeOrderKeys as tt,buildSeekWhere as zt,decodeCursor as nt,applySelect as Tt,encodeCursor as ot,tiebreakDirectionFor as Jt,buildSeekBeforeWhere as Dn}from"./CURSOR_PREFIX-D8c7Ccj3.mjs";import{rankTableName as vt,sortColumnName as At,resolveRankPartition as Ln,encodePartitionKey as kn,RANK_TIEBREAK as Fn,rankPivotConditionSql as qn}from"./RANK_TIEBREAK-B6iDKDW3.mjs";import{UNVOUCHABLE_DEP as It}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as Bn,buildIndexRange as Wn}from"./buildIndexRange-CBKQmHSS.mjs";import{assertFlatPredicate as Xe,resolveRelationPredicates as Ct}from"./DEFAULT_MAX_RELATION_KEYS--MhxjwFp.mjs";import{runRowValidators as Ze,resolveWith as xt,relationHooks as bt,applyOnDelete as Un,fanOutScalarCounts as Pn}from"./applyOnDelete-CmYAshr-.mjs";import{guardWriter as Gn}from"./RLS_UNWRAP_SYMBOL-B3RgW-Kb.mjs";import{quoteIdentifier as Se}from"./quoteIdentifier-CObIFRhb.mjs";import{isProjectedKind as Hn}from"./BIGINT_KEY_DIGITS-GvEBhyR5.mjs";import{createSystemReader as On}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as ye}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as Nn}from"./hasTrigger-CjlwI4le.mjs";import{c as ne,t as Ue,r as We,j as Ee,i as Mt}from"./where-sql-B1l5NcUZ.mjs";import{CLIENT_WATERMARK_TABLE as Or,advanceClientWatermark as Nr,migrateClientWatermark as jr,readClientWatermark as Kr}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as zr,deleteGlobalShapeSnapshot as Jr,deleteGlobalShapeSnapshotsForConnection as Vr,migrateGlobalShapeSnapshot as Yr,readGlobalShapeSnapshot as Xr,writeGlobalShapeSnapshot as Zr}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{IDEMPOTENCY_TABLE as ti,readIdempotent as ni,trimIdempotent as oi,writeIdempotent as ri}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{runShardMigrations as si}from"./runShardMigrations-B1ilHmKB.mjs";import{S as ai}from"./ctx-db-search-state-ruTuCsxa.mjs";import{selectShapeMembers as li,selectShapeRows as ui}from"./selectShapeMembers-jydcnpzn.mjs";import{serializeSqlValue as re}from"./serializeSqlValue-B_-zaEWZ.mjs";const jn=o=>{const r=atob(o),t=Uint8Array.from(r,a=>a.codePointAt(0)??0);return new TextDecoder().decode(t)},Kn=()=>new $("BAD_REQUEST","invalid cursor"),Dt=16,Lt=8,Y=1024,ct=(o,r)=>r.query(o),Qn=(o,r)=>{if(o.length===0)return 0;let t=0;for(const[a,d]of r.entries()){const p=a===r.length-1;let E=0;for(const S of o)(p?S.startsWith(d):S===d)&&(E+=1);if(E===0)return 0;t+=E}return t},zn=(o,r)=>{if(!r)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",a=(t.codePointAt(0)??0)+1;if(a>=55296&&a<=57343||a>1114111)return{exact:!0,lower:o,upper:o};const d=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:d+String.fromCodePoint(a)}},Jn=(o,r,t)=>{const a={eq:(d,p)=>{if(!o.definition.filterFields?.includes(d))throw new $("INTERNAL",`field "${d}" is not a filter field of search index "${o.indexName}" on table "${r}"`);if(o.filters.length>=Lt)throw new $("BAD_REQUEST",`search index "${o.indexName}" on table "${r}": at most ${String(Lt)} .eq() filters are supported per search query`);return o.filters.push({field:d,value:p}),a},search:(d,p)=>{const E=o;if(d!==E.definition.field)throw new $("INTERNAL",`search index "${E.indexName}" on table "${r}" indexes "${E.definition.field}", not "${d}"`);const S=ct(p,t).length;if(S>Dt)throw new $("BAD_REQUEST",`search index "${E.indexName}" on table "${r}": at most ${String(Dt)} search terms are supported (got ${String(S)})`);return E.field=d,E.query=p,E.hasQuery=!0,a}};return a},Vn=o=>{if(o.length>Y)throw new $("BAD_REQUEST",`more than ${String(Y)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Yn=o=>Math.min(o.offset+o.numItems+1,Y),Xn=o=>btoa(`search:${String(o)}`),Zn=o=>{let r;try{r=jn(o)}catch{return}if(!r.startsWith("search:"))return;const t=Number(r.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},eo=o=>{if(typeof o.endCursor=="string")throw new $("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(o.numItems))throw new $("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(o.numItems)}`);const r=Math.max(0,Math.floor(o.numItems)),t=o.cursor?Zn(o.cursor):0;if(t===void 0)throw Kn();if(t+r>=Y)throw new $("BAD_REQUEST",`search pagination reaches the ${String(Y)}-document limit (offset ${String(t)} + ${String(r)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,Y-t-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:t}},to=(o,r)=>{const t=r.offset+r.numItems,a=r.numItems>0&&o.length>t;return{continueCursor:a?Xn(t):null,isDone:!a,page:o.slice(r.offset,t)}},no=o=>{if(o===void 0)return Y+1;if(!Number.isFinite(o))return Y;const r=Math.max(0,Math.floor(o));if(r>Y)throw new $("BAD_REQUEST",`search returns at most ${String(Y)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},Pe=o=>{const r=new Map;return t=>{const a=r.get(t);if(a!==void 0)return a;const d=o(Se(t));return r.set(t,d),d}},ue=Se(oe),oo=Pe(o=>`INSERT INTO ${o} (id, _creationTime, ${ue}) VALUES (?, ?, ?)`),kt=Pe(o=>`UPDATE ${o} SET ${ue} = ? WHERE id = ? AND ${ue} = ?`),ro=Pe(o=>`UPDATE ${o} SET _creationTime = ?, ${ue} = ? WHERE id = ? AND ${ue} = ?`),io=Pe(o=>`DELETE FROM ${o} WHERE id = ? AND ${ue} = ?`),so="SELECT changes() AS changed",Ft=new Map,co="",ao=o=>{const r=JSON.stringify(o),t=Ft.get(r);if(t!==void 0)return t;const a=o.map(p=>i`SELECT ${i.raw(`'${p.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(p)} WHERE id = ${co}`),{sql:d}=Kt("sqlite",i`${st(a)} LIMIT 1`);return Ft.set(r,d),d},lo=(o,r)=>r.map(()=>o),uo=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,fo=o=>{if(!uo.test(o))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},qt=50,Vt=500,Fe=Math.floor(Qt.boundParams/3),ge=Qt.boundParams,ho=128,ae=(o,r,t)=>{const a=r??Vt;if(o>a)throw new $("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},wo=o=>{const r={eq:(t,a)=>(o.sqlConditions.push({comparator:"=",field:t,value:a}),r),gt:(t,a)=>(o.sqlConditions.push({comparator:">",field:t,value:a}),r),gte:(t,a)=>(o.sqlConditions.push({comparator:">=",field:t,value:a}),r),lt:(t,a)=>(o.sqlConditions.push({comparator:"<",field:t,value:a}),r),lte:(t,a)=>(o.sqlConditions.push({comparator:"<=",field:t,value:a}),r)};return r},po=o=>Math.max(o,Y),Yt=(o,r)=>{const t=o.filters.map(a=>i`${X(a.field)} = ${re(a.value)}`);return r&&t.push(r),t},go=(o,r,t,a,d)=>{const p=ct(t.query,it(t.definition.language));if(p.length===0)return[];const E=un(r,t.indexName),S=`${E}__vocab`,_=p.length-1,D=p.map((R,k)=>{const q=zn(R,k===_),W=q.exact?i`${i.identifier("term")} = ${q.lower}`:i`${i.identifier("term")} >= ${q.lower} AND ${i.identifier("term")} < ${q.upper}`;return i`SELECT ${i.identifier("doc")}, ${i.raw(String(k))} AS ${i.identifier("__term__")}, COUNT(*) AS ${i.identifier("__n__")} FROM ${i.identifier(S)} WHERE ${W} GROUP BY ${i.identifier("doc")}`}),y=p.map((R,k)=>i`SUM(CASE WHEN u.${i.identifier("__term__")} = ${i.raw(String(k))} THEN u.${i.identifier("__n__")} ELSE 0 END)`),v=i`SELECT f.${i.identifier(Me)} AS ${i.identifier(Me)}, ${i.join(y,i` + `)} AS ${i.identifier("__score__")} FROM (${st(D)}) u JOIN ${i.identifier(E)} f ON f.rowid = u.${i.identifier("doc")} GROUP BY f.${i.identifier(Me)} HAVING ${i.join(y.map(R=>i`${R} > 0`),i` AND `)}`,I=Yt(t,d);let F=i`SELECT m.id, m._creationTime, m.${i.identifier(oe)}, s.${i.identifier("__score__")} AS ${i.identifier("__score__")} FROM (${v}) s JOIN ${i.identifier(r)} m ON m.id = s.${i.identifier(Me)}`;I.length>0&&(F=i`${F} WHERE ${i.join(I,i` AND `)}`),F=i`${F} ORDER BY s.${i.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${i.raw(String(a))}`;const K=[];for(const R of j(o,F)){const k=jt(R);if(k){const q=R.__score__;K.push({document:k,score:typeof q=="number"?q:Number(q??0)})}}return K},$o=(o,r,t,a,d)=>{const p=it(t.definition.language),E=ct(t.query,p);if(E.length===0)return[];const S=Yt(t,d);let _=i`SELECT id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(r)}`;S.length>0&&(_=i`${_} WHERE ${i.join(S,i` AND `)}`),_=i`${_} ORDER BY _creationTime DESC, id ASC LIMIT ${i.raw(String(po(a)))}`;const D=j(o,_).toArray(),y=[];for(const v of D){const I=jt(v);if(!I)continue;const F=Qn(fn(I,t.definition),E);F>0&&y.push({creationTime:typeof I._creationTime=="number"?I._creationTime:0,doc:I,id:typeof I._id=="string"?I._id:"",score:F})}return y.sort((v,I)=>I.score-v.score||I.creationTime-v.creationTime||v.id.localeCompare(I.id)),y.slice(0,a).map(v=>({document:v.doc,score:v.score}))},et=(o,r,t,a)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new $("BAD_REQUEST",`geo index "${a}" on table "${t}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},yo=(o,r)=>{const t=o,a={near:(d,p)=>{if(t.within)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(et(d,".near() point",r,t.indexName),!Number.isFinite(p)||p<=0)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(p)}`);return t.near={point:{lat:d.lat,lng:d.lng},radiusMeters:p},a},within:d=>{if(t.near)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(et(d.sw,".within() sw corner",r,t.indexName),et(d.ne,".within() ne corner",r,t.indexName),d.sw.lat>d.ne.lat)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(d.sw.lng>d.ne.lng)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return t.within={ne:{lat:d.ne.lat,lng:d.ne.lng},sw:{lat:d.sw.lat,lng:d.sw.lng}},a}};return a},Eo=(o,r)=>{const t=o[r];if(t===null||typeof t!="object")return;const{lat:a,lng:d}=t;return typeof a=="number"&&typeof d=="number"?{lat:a,lng:d}:void 0},mo=(o,r)=>{const t=Eo(o,r.definition.field);if(!t)return;const a=typeof o._creationTime=="number"?o._creationTime:0;if(r.near){const d=xn(r.near.point,t);return d<=r.near.radiusMeters?{creationTime:a,distance:d}:void 0}return bn(t,r.within)?{creationTime:a,distance:0}:void 0},So=(o,r,t,a)=>{if(!t.near&&!t.within)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const d=t.near?In(t.near.point,t.near.radiusMeters):Cn(t.within),p=vn(r,t.indexName),E=d.map(v=>i`(g.${i.identifier("__geohash__")} >= ${v} AND g.${i.identifier("__geohash__")} < ${`${v}{`})`),S=[i`(${i.join(E,i` OR `)})`];a&&S.push(a);const _=i`SELECT m.id, m._creationTime, m.${i.identifier(oe)} FROM ${i.identifier(p)} g JOIN ${i.identifier(r)} m ON m.id = g.${i.identifier("__id__")} WHERE ${i.join(S,i` AND `)}`,D=j(o,_).toArray(),y=[];for(const v of D){const I=le(v),F=I?mo(I,t):void 0;I&&F&&y.push({creationTime:F.creationTime,distance:F.distance,doc:I})}return y.sort((v,I)=>v.distance-I.distance||I.creationTime-v.creationTime),y},Xt=(o,r,t,a)=>{const d=[];for(const p of o)if(r.every(E=>E(a(p)))&&(d.push(p),typeof t=="number"&&d.length>=t))break;return d},_o=(o,r,t,a,d,p=()=>{})=>{const E=t.within!==void 0,S=So(o,r,t,d).map(_=>({distanceMeters:E?null:_.distance,document:_.doc}));return p(S.length),typeof a=="number"?S.slice(0,Math.max(0,Math.floor(a))):S},Zt=(o,r,t,a,d,p=()=>{})=>{const{geo:E}=t;if(!E)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const S=t.inMemoryFilters.length>0,_=_o(o,r,E,S?void 0:d,a,p);return S?Xt(_,t.inMemoryFilters,d,D=>D.document):_},en=(o,r,t,a)=>{const d=`SELECT id, _creationTime, ${Se(oe)} FROM ${Se(o)}`,p=`ORDER BY ${t}${a===void 0?"":` LIMIT ${String(a)}`}`;return r===void 0?We(`${d} ${p}`):Ee(`${d} WHERE `,r,` ${p}`)},Ro=(o,r,t,a,d,p=()=>{})=>Zt(o,r,t,a,d,p).map(E=>E.document),To=(o,r,t,a,d,p,E=()=>{})=>{const S=[];for(const v of t.sqlConditions)S.push(i`${X(v.field)} ${i.raw(v.comparator)} ${re(v.value)}`);a&&S.push(a);let _=i`SELECT id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(r)}`;S.length>0&&(_=i`${_} WHERE ${i.join(S,i` AND `)}`),_=i`${_} ORDER BY ${d}`,typeof p=="number"&&t.inMemoryFilters.length===0&&(_=i`${_} LIMIT ${i.raw(String(Math.max(0,Math.floor(p))))}`);const D=j(o,_).toArray();E(D.length);const y=[];for(const v of D){const I=le(v);if(I&&t.inMemoryFilters.every(F=>F(I))&&(y.push(I),typeof p=="number"&&y.length>=p))break}return y},$e={fieldRef:X,serialize:re},tn=(o,r)=>{const t=r===void 0?void 0:o.shape[r];return t!==void 0&&Hn(t)},Bt=(o,r)=>r.some(t=>tn(o,t)),Wt=(o,r,t)=>{if(tn(o,r))throw new $("BAD_REQUEST",`${t}: "${r}" is stored as an order-preserving key, which SQL cannot reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},at={fieldRef:o=>We(Be(o)),serialize:re},vo=o=>{let r=0;const t=[],a={fieldRef:d=>We(Be(d)),relationExists:d=>{const{childWhere:p,negated:E,parentTable:S,relation:_}=d,D=`__rel_${String(r)}`,y=t.at(-1)??S;r+=1,o(_.table,H);const v=_.kind==="one"?_.field:_.references,I=_.kind==="one"?_.references:_.field,F=We(`${Rt(D,I)} = ${Rt(y,v)}`);t.push(D);const K=ne(p,a,Ue);t.pop();const R=K===void 0?F:Ee(F," AND ",K),k=Ee("EXISTS (SELECT 1 FROM ",Mt(_.table)," AS ",Mt(D)," WHERE ",R,")");return E?Ee("NOT ",k):k},serialize:re};return a},nn=o=>{const r=o.map(t=>`${Be(t.field)} ${t.direction==="desc"?"DESC":"ASC"}`);return o.some(t=>t.field==="_id"||t.field==="id")||r.push(`${Be("id")} ${Jt(o)==="desc"?"DESC":"ASC"}`),r.join(", ")},Ao=o=>{const r=o.map(t=>i`${X(t.field)} ${i.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||r.push(i`${X("id")} ${i.raw(Jt(o)==="desc"?"DESC":"ASC")}`),i.join(r,i`, `)},Io={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},Co=o=>{const r=new Set(o.sqlConditions.filter(a=>a.comparator==="=").map(a=>a.field));let t=0;for(;t<o.indexFields.length&&r.has(o.indexFields[t]??"");)t+=1;return o.indexFields.slice(t)},on=(o,r)=>{const t=o.order,a=Co(o);return a.length>0?tt(a.map(d=>({[d]:t})),r):tt([{_creationTime:t}],r)},xo=(o,r,t,a)=>{const d=o.sqlConditions.map(p=>({[p.field]:{[Io[p.comparator]??"eq"]:p.value}}));if(t&&d.push(zt(r,nt(t))),a&&d.push(Dn(r,nt(a))),d.length!==0)return d.length===1?d[0]:{AND:d}},bo=(o,r,t)=>{const a=[];for(const d of o){const p=le(d);if(p&&r.every(E=>E(p))&&(a.push(p),t!==void 0&&a.length>t))break}return a},Mo=(o,r,t,a,d,p,E=()=>{})=>{const S=Math.max(0,Math.floor(d.numItems)),_=on(a,t),D=typeof d.endCursor=="string",y=ne(xo(a,_,d.cursor,d.endCursor),at,Ue),v=p&&y?Ee(y," AND ",p):p??y,I=a.inMemoryFilters.length>0,F=en(r,v,nn(_),I||D?void 0:S+1),K=me(o,F.text,...F.params).toArray();E(K.length);const R=bo(K,a.inMemoryFilters,I||D?void 0:S);if(D){const N=R.length>=2?R[Math.floor(R.length/2)-1]:void 0;return{continueCursor:d.endCursor??null,isDone:!0,page:R,splitCursor:N?ot(N,_):null}}const k=R.length>S,q=k?R.slice(0,S):R,W=q.at(-1);return{continueCursor:k&&W?ot(W,_):null,isDone:!k,page:q}};class Do extends ${constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Lo=/\s/u,ko=String.fromCodePoint(0),Ut=(o,r,t)=>{if(!o.tables[r])throw new $("INTERNAL",`unknown table: ${r}`);return typeof t!="string"||t.length===0||Lo.test(t)||t.includes(ko)?null:t},Fo=(o,r,t,a=()=>{},d=()=>{},p=()=>{})=>{const E=r.tables[t];if(!E)throw new $("INTERNAL",`unknown table: ${t}`);const S=de(E.softDeleteMode,void 0),_=S?ne(S,$e):void 0,D=S?ne(S,at,Ue):void 0,y={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let v=0;const I=m=>{const{search:C}=y;if(!C)throw new $("INTERNAL","runSearchFetch called without a staged search");En(o,t,E);const M=y.inMemoryFilters.length>0,L=no(M?void 0:m),O=Tn(o);if(O&&!mn(o,t,C.definition))throw new $("SEARCH_INDEX_BUILDING",`search index "${C.indexName}" on table "${t}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const Z=O?go(o,t,C,L,_):$o(o,t,C,L,_);return M?(v=Z.length,Xt(Z,y.inMemoryFilters,m,Ge=>Ge.document)):(m===void 0&&Vn(Z),Z)},F=m=>I(m).map(C=>C.document),K=m=>{const C=eo(m);return to(F(Yn(C)),C)},R=()=>Ao(on(y,E.shape)),k=()=>{if(y.search||y.geo||y.indexName===void 0){d(void 0);return}d(Wn(t,y.indexName,y.indexFields,y.sqlConditions,re))},q=m=>{k();let C=0;const M=(()=>{if(y.search){const L=F(m);return C=v,L}return y.geo?Ro(o,t,y,_,m,L=>{C=L}):To(o,t,y,_,R(),m,L=>{C=L})})();return p(Math.max(C,M.length)),M},W=()=>{if(!y.search&&!y.geo)throw new $("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);k();let m=0;const C=(()=>{if(y.search){const M=I(void 0);return m=v,M}return Zt(o,t,y,_,void 0,M=>{m=M})})();return p(Math.max(m,C.length)),C},N={async*[Symbol.asyncIterator](){if(y.search){yield*q(void 0);return}const m=[...y.inMemoryFilters];let C;y.inMemoryFilters=[];try{for(;;){const M=await N.paginate({cursor:C??null,numItems:ho});for(const L of M.page)m.every(O=>O(L))&&(yield L);if(M.isDone||M.continueCursor===null)return;C=M.continueCursor}}finally{y.inMemoryFilters=m}},async collect(){return q(void 0)},async collectWithScores(){return W()},filter(m){return y.inMemoryFilters.push(m),N},async first(){return q(y.inMemoryFilters.length>0?void 0:1)[0]??null},order(m){return y.order=m==="desc"?"desc":"asc",N},async paginate(m){let C=0;if(k(),y.search){const L=K(m);return p(L.page.length),L}if(y.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const M=Mo(o,t,E.shape,y,m,D,L=>{C=L});return p(Math.max(C,M.page.length)),M},async take(m){return q(m)},async unique(){const m=q(y.inMemoryFilters.length>0?void 0:2);if(m.length>1)throw new Do(`unique() on table "${t}" matched ${String(m.length)} documents; expected at most one`);return m[0]??null},withGeoIndex(m,C){const M=(E.geoIndexes??[]).find(O=>O.name===m);if(!M)throw new $("INTERNAL",`unknown geo index "${m}" on table "${t}"`);a(t,m,"geo");const L={definition:M,indexName:m};if(y.geo=L,C(yo(L,t)),!L.near&&!L.within)throw new $("INTERNAL",`geo index "${m}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return N},withIndex(m,C){const M=E.indexes.find(L=>L.name===m);if(!M)throw new $("INTERNAL",`unknown index "${m}" on table "${t}"`);return a(t,m,"index"),y.indexName=m,y.indexFields=M.fields,C&&C(wo(y)),N},withSearchIndex(m,C){const M=(E.searchIndexes??[]).find(O=>O.name===m);if(!M)throw new $("INTERNAL",`unknown search index "${m}" on table "${t}"`);a(t,m,"search");const L={definition:M,field:M.field,filters:[],hasQuery:!1,indexName:m,query:""};if(y.search=L,C(Jn(L,t,it(M.language))),!L.hasQuery)throw new $("INTERNAL",`search index "${m}" on table "${t}" requires a .search(field, query) call`);return N}};return N},Pt=(o,r,t)=>{const a={...r};for(const[d,p]of Nt(o)){if(p.serverDefault){a[d]=p.serverDefault({auth:t});continue}a[d]===void 0&&(p.defaultFn?a[d]=p.defaultFn():"defaultValue"in p&&(a[d]=p.defaultValue))}return a},Gt=(o,r,t,a)=>{const d=t;for(const[p,E]of Nt(o)){if(E.serverDefault){p in r&&(d[p]=E.serverDefault({auth:a}));continue}E.onUpdateFn&&!(p in r)&&(d[p]=E.onUpdateFn())}},Ht=(o,r)=>{for(const t of Object.keys(r))if(r[t]===void 0)throw new $("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},qo=/unique constraint failed/i,Bo=o=>o instanceof Error&&qo.test(o.message),Wo=/string or blob too big/iu,Uo=(o,r)=>{if(!(!(o instanceof Error)||!Wo.test(o.message)))throw new $("PAYLOAD_TOO_LARGE",`document is too large to store in "${r}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},rt=(o,r,t,a)=>{try{me(o,t,...a)}catch(d){throw Bo(d)?new ye(`unique constraint violation on "${r}"`,"unique"):(Uo(d,r),d)}},qe=(o,r,t,a)=>{if(rt(o,r,t,a),me(o,so).one().changed===0)throw new ye(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},Ot=(o,r,t,a,d,p,E)=>{const S=[];for(let v=0;v<t.length+1;v+=1){const I=t[v],F=a[v],K=F?.direction==="desc"?"desc":"asc",R=I===void 0||F===void 0?i`${i.identifier(Fn)} < ${E}`:qn(I,p[v],K,!1);if(R===void 0)continue;const k=[];for(let W=0;W<v;W+=1)k.push(i`${i.identifier(t[W])} IS ${p[W]}`);k.push(R);const[q]=k;S.push(k.length===1&&q!==void 0?q:i`(${i.join(k,i` AND `)})`)}const _=S.length>0?i.join(S,i` OR `):i`1 = 0`,D=j(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${d} AND (${_})`).one(),y=j(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${d}`).one();return{before:D.c,total:y.c}},Er=o=>{const{sql:r}=o,{schema:t}=o,a=o.broadcast??(()=>{});let d;const p=()=>o.inTransaction?.()===!0,E=e=>t.tables[e]?.commitOrderedMode!==!0?{}:((d===void 0||!p())&&(d=_n(r)),{[Rn]:d}),S=(e,...n)=>{const s=t.tables[e]?.indexes;if(!s||s.length===0)return;const f=[];for(const h of n)h&&f.push(...Bn(s,h,re));return f.length>0?f:void 0},{headroom:_}=o;let D=!1;const y=async e=>{const n=D;D=!0;try{return await e()}finally{D=n}},v=o.onRead??(()=>{}),I=e=>{St(t.tables[e])&&v(It,It)},F=o.onReadRange??(e=>{v(e.table,H)}),K=e=>{I(e.table),F(e)},R=(e,n)=>{n!==void 0&&n!==H&&!D&&_?.recordRead(1),I(e),v(e,n)},k=o.onIndexUse??(()=>{}),q=o.onWrite??(()=>{}),W=e=>{D||_?.recordWrite(e)},N=async e=>{W(e.doc),await q(e)},{cache:m}=o,C=o.clock??(()=>Date.now()),M=o.idGenerator??(()=>crypto.randomUUID()),L=o.scheduler??wn,{globalDb:O}=o,Z=o.auth??{identity:null,userId:null},Ge=o.cdc??!1,He=L,rn=On({scheduler:typeof He.list=="function"&&typeof He.get=="function"?He:void 0,storage:o.storage}),fe=(e,n,s,f)=>{Ge&&!St(t.tables[e])&&Sn(r,C(),e,n,s,f)},se=e=>t.tables[e]?.shardMode?.kind==="global",dt=(e,n)=>{if(se(e)){if(!O)throw new $("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return O}return U},Oe=e=>dt(e,"cascade"),z=(e,n)=>{if(se(e)){if(!O)throw new $("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return O}},lt=async(e,n,s,f,h)=>{h&&W(s);const u=await e.insert(n,s,f);return a({key:u,op:"insert",row:{...s,_id:u},table:n}),u},Ne=(e,n)=>dt(e,"relation load").findMany(e,n),ut=(e,n)=>(se(e)&&R(e,H),Ne(e,n)),sn=e=>!se(e.table),ft=o.relationExistsPushDown??"auto",ht=ft!=="never",{maxRelationKeys:wt}=o,_e=(e,n,s)=>Ct(e,{fetcher:ut,maxRelationKeys:wt,relationBaseWhere:s,schema:t,tableName:n}),pt=async(e,n,s,f)=>{const h=z(e,"relation grouped count");if(h)return R(e,H),Pn((B,A)=>h.count(B,A),e,n,s,f);const u=t.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);R(e,H);const c=de(u.softDeleteMode,void 0),l={[n]:{in:s}},w=J(J(l,f),c),T=await _e(w,e,void 0),g=ne(T,$e),b=X(n);let x=i`SELECT ${b} AS __fk__, COUNT(*) AS count FROM ${i.identifier(e)}`;g&&(x=i`${x} WHERE ${g}`),x=i`${x} GROUP BY ${b}`;const P=j(r,x).toArray();return new Map(P.map(B=>[B.__fk__,B.count]))};let Re=0;const gt=new Set;for(const[e,n]of Object.entries(t.tables))for(const s of Object.values(n.triggerMap??{}))gt.add(`${e} ${s.timing} ${s.op}`);const ee=(e,n,s)=>gt.has(`${e} ${n} ${s}`),te=async(e,n,s)=>{if(Re+=1,Re>qt)throw Re-=1,new ye(`trigger recursion exceeded ${String(qt)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await Nn({ctx:an,event:s,op:n,schema:t,tableName:s.table,timing:e})}finally{Re-=1}},{ensureBackfilledForTable:he,ensureBackfilledIndex:je,ensureRankBackfilled:Ke,ensureRankBackfilledForTable:we,syncAggregates:Te,syncCompanionsForInsert:$t,syncGeo:ve,syncRanks:pe,syncSearch:Ae}=ln({broadcast:a,indexKeysFor:(e,n)=>S(e,n),invalidateCache:(e,n,s)=>m?.invalidate(e,n,S(e,s)),recordCdc:fe,schema:t,sql:r}),yt=(e,n,s)=>{const{shardMode:f}=n;if(f?.kind==="shardBy"&&!(f.field!==void 0&&(s.partitionBy??[]).includes(f.field)))throw Object.assign(new Error(`rank index "${s.name}" on "${e}" partitions across shards (shard key "${f.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},Et=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),ie=(e,n)=>{const s=Et(n);for(let f=0;f<s.length;f+=ge){const h=s.slice(f,f+ge),[u]=me(r,ao(h),...lo(e,h)).toArray();if(!u)continue;const c=u.__t__,l=le(u);if(typeof c!="string"||!l)return;const w=u[oe];return{docJson:typeof w=="string"?w:ce(w??{}),row:l,tableName:c}}},cn=(e,n)=>{const s=[...new Set(e)],f=new Map;if(s.length===0)return f;const h=Et(n);for(let u=0;u<h.length;u+=ge){const c=h.slice(u,u+ge),l=Math.floor(ge/c.length),w=An(i`${i.identifier("id")}`,s,!1,l),T=c.map(g=>i`SELECT ${i.raw(`'${g.replaceAll("'","''")}'`)} AS __t__, id FROM ${i.identifier(g)} WHERE ${w}`);for(const g of j(r,st(T))){const{id:b,__t__:x}=g;typeof x=="string"&&typeof b=="string"&&f.set(b,x)}}return f},mt={assertRankPartitionLocal:yt,ensureRankBackfilled:Ke,onRead:R,rowToDocument:le,schema:t,sql:r},U={system:rn,async aggregate(e,n){const s=z(e,"aggregate");if(s)return R(e,H),s.aggregate(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);if(De(n.op),n.op==="count")return U.count(e,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new $("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);R(e,H);const h=de(f.softDeleteMode,void 0),u=J(J(n.baseWhere,n.where),h),c=await _e(u,e,n.relationBaseWhere),l=c!==u;if(f.aggregateIndexes&&!n.baseWhere&&!l&&(!h||Bt(f,[n.field]))){const B=yn(f.aggregateIndexes,n.op,n.field,n.where);if(B){je(e,B.index);const A=ze(B.index.by??[],B.key),Q=Qe(e,B.index.name),V=j(r,i`SELECT ${Le} AS value, ${Ye} AS count FROM ${i.identifier(Q)} WHERE ${ke} = ${A}`).toArray()[0];return Je(n.op,V)}}Wt(f,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const w=ne(c,$e),T=De(n.op),g=X(n.field);let b=i`SELECT ${i.raw(T)}(${g}) AS value FROM ${i.identifier(e)}`;w&&(b=i`${b} WHERE ${w}`);const P=j(r,b).toArray()[0]?.value;return P??null},asId(e,n){const s=Ut(t,e,n);if(s===null)throw new $("BAD_REQUEST",`asId("${e}", …): "${n}" is not a valid id for table "${e}"`,{status:400});return s},async count(e,n){const s=z(e,"count");if(s)return R(e,H),s.count(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=pn(n);if(h.restrictsCounts)throw new Ve(e);R(e,H);const u=de(f.softDeleteMode,void 0),c=J(J(h.baseWhere,h.where),u),l=await _e(c,e,h.relationBaseWhere),w=l!==c;if(f.aggregateIndexes&&!h.baseWhere&&!w&&!u){const x=$n(f.aggregateIndexes,h.where);if(x){je(e,x.index);const P=ze(x.index.by??[],x.key),B=Qe(e,x.index.name),A=j(r,i`SELECT ${Le} AS value FROM ${i.identifier(B)} WHERE ${ke} = ${P}`).toArray();return A[0]===void 0?0:A[0].value??0}}const T=ne(l,$e);let g=i`SELECT COUNT(*) AS count FROM ${i.identifier(e)}`;return T&&(g=i`${g} WHERE ${T}`),j(r,g).one().count},async delete(e,n,s){const f=ie(e,n);if(!f){const g=n===void 0?O:void 0;g&&(W(void 0),await g.delete(e,void 0,s));return}const{docJson:h,row:u,tableName:c}=f,l=t.tables[c],w=s?.hard===!0,T=!w&&l?.softDeleteMode?l.softDeleteMode.field:void 0;if(!(T&&u[T]!==null&&u[T]!==void 0)){if(ee(c,"before","delete")&&await te("before","delete",{id:e,op:"delete",previous:u,table:c}),await Un({deletedId:e,deletedReference:g=>u[g],findHolders:async(g,b,x)=>(await Oe(g).findMany(g,{includeDeleted:w,where:{[b]:x}})).page,onCascade:(g,b)=>Oe(g).delete(b,void 0,s),onRestrict:g=>{throw new ye(g,"restrict")},onSetNull:(g,b,x)=>Oe(g).patch(b,{[x]:null}),schema:t,tableName:c}),he(c),we(c),T){const g={...u,...E(c),[T]:C(),_id:e};qe(r,c,kt(c),[ce(g),e,h]),Ae(c,e,g,u),ve(c,e,void 0),Te(c,u,g),pe(c,e,u,void 0),m?.invalidate(c,e,S(c,u,g)),fe(c,e,"update",g),a({indexKeys:S(c,u,g),key:e,op:"update",row:g,table:c}),ee(c,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:u,table:c}),await N({id:e,op:"delete",table:c});return}qe(r,c,io(c),[e,h]),Ae(c,e,void 0),ve(c,e,void 0),Te(c,u,void 0),pe(c,e,u,void 0),m?.invalidate(c,e,S(c,u)),fe(c,e,"delete"),a({indexKeys:S(c,u),key:e,op:"delete",table:c}),ee(c,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:u,table:c}),await N({id:e,op:"delete",table:c})}},async deleteAll(e,n){if(!t.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);const s=Math.max(1,n?.chunkSize??Vt),f=n?.hard===void 0?void 0:{hard:n.hard},h=se(e)?void 0:e;let u=0;return await y(async()=>{for(;;){const l=(await U.findMany(e,{limit:s})).page.map(w=>String(w._id));if(l.length===0)break;for(const w of l)await U.delete(w,h,f),u+=1;if(l.length<s)break}}),{deleted:u}},async deleteMany(e,n,s){ae(e.length,n?.limit,"deleteMany");for(const f of e)await U.delete(f,s);return{deleted:e.length}},async deleteWhere(e,n,s){const u=(await(z(e,"deleteWhere")??U).findMany(e,{where:n})).page.map(c=>String(c._id));if(ae(u.length,s?.limit,"deleteWhere"),U.deleteMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return U.deleteMany(u,s)},async findFirst(e,n={}){return(await U.findMany(e,{...n,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,n={}){const s=await U.findFirst(e,n);if(s===null)throw new Mn(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,n={}){const s=z(e,"findMany");if(s)return R(e,H),s.findMany(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=!n.where&&!n.baseWhere;h?R(e,H):R(e);const u=tt(n.orderBy,f.shape),c=n.cursor?zt(u,nt(n.cursor)):void 0;let l=J(n.baseWhere,n.where);l=J(l,de(f.softDeleteMode,n.includeDeleted)),l=await Ct(l,{canPushExists:ht?sn:void 0,existsPushMode:ft==="always"?"always":"auto",fetcher:ut,maxRelationKeys:wt,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),c&&(l=l?{AND:[l,c]}:c);const w=ht?vo(R):at,T=ne(l,w,Ue),g=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0,b=en(e,T,nn(u),g===void 0?void 0:g+1),x=me(r,b.text,...b.params).toArray();h&&!D&&_?.recordRead(x.length);const P=[];for(const V of x){const G=le(V);G&&(P.push(G),!h&&typeof G._id=="string"&&R(e,G._id))}if(g===void 0)return n.with&&await xt({groupedCounter:pt,fetcher:Ne,parents:P,...bt(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:Tt(P,n.select,n.with)};const B=P.length>g,A=B?P.slice(0,g):P,Q=A.at(-1);return n.with&&await xt({fetcher:Ne,groupedCounter:pt,parents:A,...bt(n),schema:t,tableName:e,with:n.with}),{continueCursor:B&&Q&&n.omitContinueCursor!==!0?ot(Q,u):null,isDone:!B,page:Tt(A,n.select,n.with)}},async get(e,n){const s=ie(e,n);if(!s){const f=n===void 0?O:void 0;return f?f.get(e):null}return R(s.tableName,e),s.row},async lookupById(e,n){const s=ie(e,n);return s?(R(s.tableName,e),{row:s.row,tableName:s.tableName}):null},async groupBy(e,n){const s=z(e,"groupBy");if(s)return R(e,H),s.groupBy(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);R(e,H);const h=n.agg??{op:"count"};if(De(h.op),h.op!=="count"&&!h.field)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const u=de(f.softDeleteMode,void 0),c=J(J(n.baseWhere,n.where),u),l=await _e(c,e,n.relationBaseWhere),w=l!==c,T=[...n.by,h.field];if(f.aggregateIndexes&&!n.baseWhere&&!w&&(!u||Bt(f,T))){const A=gn(f.aggregateIndexes,h.op,h.field,n.by,n.where),Q=A===void 0?0:Object.keys(A.partial).length,V=A?.index.by?.length??0;if(A&&(Q===0||Q===V)){je(e,A.index);const G=Qe(e,A.index.name),Ie=Object.keys(A.partial),Ce=[];if(Ie.length===(A.index.by??[]).length&&Ie.length>0){const xe=ze(A.index.by??[],A.partial),be=j(r,i`SELECT ${Le} AS value, ${Ye} AS count FROM ${i.identifier(G)} WHERE ${ke} = ${xe}`).toArray();return be.length>0&&Ce.push({key:{...A.partial},value:Je(h.op,be[0])}),Ce}const dn=j(r,i`SELECT ${ke} AS key, ${Le} AS value, ${Ye} AS count FROM ${i.identifier(G)}`).toArray();for(const xe of dn){const be=hn(JSON.parse(xe.key));Ce.push({key:be,value:Je(h.op,xe)})}return Ce}}for(const A of T){if(A===void 0)continue;const Q=A===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${A}" } })`:`groupBy(${e}, { by: [..."${A}"] })`;Wt(f,A,Q)}const g=ne(l,$e),b=n.by.map(A=>i`${X(A)} AS ${i.identifier(A)}`);if(h.op==="count")b.push(i`COUNT(*) AS value`);else{const{field:A}=h;if(A===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);b.push(i`${i.raw(De(h.op))}(${X(A)}) AS value`)}let x=i`SELECT ${i.join(b,i`, `)} FROM ${i.identifier(e)}`;g&&(x=i`${x} WHERE ${g}`),x=i`${x} GROUP BY ${i.join(n.by.map(A=>X(A)),i`, `)}`;const P=j(r,x).toArray(),B=[];for(const A of P){const Q={};for(const G of n.by)Q[G]=A[G]??null;const{value:V}=A;B.push({key:Q,value:V==null?null:Number(V)})}return B},async insert(e,n,s){const f=z(e,"insert");if(f)return lt(f,e,n,s,!0);const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const u=Pt(h,n,Z);Ze(h,u);let c;s?.clientId!==void 0?(fo(s.clientId),c=s.clientId):s?.allowExplicitId&&typeof u._id=="string"?c=u._id:c=M();const l=s?.allowExplicitId&&typeof u._creationTime=="number"?u._creationTime:C(),w={...u,...E(e),_creationTime:l,_id:c};return ee(e,"before","insert")&&await te("before","insert",{doc:{...w},id:c,op:"insert",table:e}),he(e),we(e),rt(r,e,oo(e),[c,l,ce(w)]),$t(e,c,w),ee(e,"after","insert")&&await te("after","insert",{doc:w,id:c,op:"insert",table:e}),await N({doc:w,id:c,op:"insert",table:e}),c},async insertManyUnsafe(e,n,s){if(ae(n.length,s?.limit,"insertManyUnsafe"),n.length===0)return[];const f=z(e,"insert");if(f){const l=[];for(const w of n)W(w);for(const w of n){const T=await f.insert(e,w,{allowExplicitId:s?.allowExplicitId});a({key:T,op:"insert",row:{...w,_id:T},table:e}),l.push(T)}return l}const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);he(e),we(e);const u=[];for(let l=0;l<n.length;l+=Fe)u.push(E(e));const c=n.map((l,w)=>{const T=Pt(h,l,Z),g=s?.allowExplicitId===!0&&typeof T._id=="string"?T._id:M(),b=s?.allowExplicitId===!0&&typeof T._creationTime=="number"?T._creationTime:C(),x={...T,...u[Math.floor(w/Fe)],_creationTime:b,_id:g};return{creationTime:b,document:x,id:g}});for(const l of c)W(l.document);for(let l=0;l<c.length;l+=Fe){const w=i.join(c.slice(l,l+Fe).map(g=>i`(${g.id}, ${g.creationTime}, ${ce(g.document)})`),i`, `),T=Kt("sqlite",i`INSERT INTO ${i.identifier(e)} (id, _creationTime, ${i.identifier(oe)}) VALUES ${w}`);rt(r,e,T.sql,T.params)}for(const{document:l,id:w}of c)$t(e,w,l),await q({doc:l,id:w,op:"insert",table:e});return c.map(l=>l.id)},async insertMany(e,n,s){ae(n.length,s?.limit,"insertMany");const f=s?.skipDuplicates===!0,h=[],u=z(e,"insert");if(u)for(const l of n)W(l);const c=async l=>u?lt(u,e,l,void 0,!1):U.insert(e,l);for(const l of n)try{h.push(await c(l))}catch(w){if(f&&w instanceof ye&&w.kind==="unique")h.push(null);else throw w}return h},normalizeId(e,n){return Ut(t,e,n)},async patch(e,n,s){const f=ie(e,s);if(!f){const T=s===void 0?O:void 0;if(T){W(n),await T.patch(e,n);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:u,tableName:c}=f,l=t.tables[c];if(!l)throw new $("INTERNAL",`unknown table: ${c}`);R(c,e),Ht("patch",n);const w={...u,...n,...E(c),_id:e};Gt(l,n,w,Z),Ze(l,w,!0),ee(c,"before","update")&&await te("before","update",{doc:{...w},id:e,op:"update",previous:u,table:c}),he(c),we(c),qe(r,c,kt(c),[ce(w),e,h]),Ae(c,e,w,u),ve(c,e,w),Te(c,u,w),pe(c,e,u,w),m?.invalidate(c,e,S(c,u,w)),fe(c,e,"update",w),a({indexKeys:S(c,u,w),key:e,op:"update",row:w,table:c}),ee(c,"after","update")&&await te("after","update",{doc:w,id:e,op:"update",previous:u,table:c}),await N({doc:w,id:e,op:"update",table:c})},async patchMany(e,n,s){ae(e.length,n?.limit,"patchMany");for(const f of e)await U.patch(f.id,f.patch,s);return{patched:e.length}},async patchWhere(e,n,s){const u=(await(z(e,"patchWhere")??U).findMany(e,{where:n.where})).page.map(c=>({id:String(c._id),patch:n.patch}));if(ae(u.length,s?.limit,"patchWhere"),U.patchMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await U.patchMany(u,s),{patched:u.length}},query(e){const n=z(e,"query");return n?(R(e,H),n.query(e)):Fo(r,t,e,k,s=>{s?K(s):R(e,H)},s=>{D||_?.recordRead(s)})},async rank(e,n,s){const f=z(e,"rank");if(f)return R(e,H),f.rank(e,n,s);k(e,n,"rank");const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const u=h.rankIndexes?.find(G=>G.name===n);if(!u)throw new $("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(yt(e,h,u),s.restrictsCounts)throw new Ve(e);R(e,H),Ke(e,u);const c=typeof s.row=="string"?s.row:s.row._id;if(!c)return null;const l=vt(e,u.name),w=u.sortBy.map((G,Ie)=>At(Ie)),T=w.map(G=>Se(G)).join(", "),g=j(r,i`SELECT ${i.identifier("__partition__")}, ${i.raw(T)} FROM ${i.identifier(l)} WHERE ${i.identifier("__id__")} = ${c}`).toArray(),[b]=g;if(b===void 0)return null;let x=b.__partition__;const P=J(s.baseWhere,s.where);Xe(P,t,e,"rank");const B=Ln(u,P);if(B){const G=kn(u.partitionBy??[],B);if(G!==x)return null;x=G}const A=w.map(G=>b[G]),{before:Q,total:V}=Ot(r,l,w,u.sortBy,x,A,c);return{position:Q+1,total:V}},async rankBefore(e,n,s){if(se(e))throw new $("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(w=>w.name===n);if(!h)throw new $("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(s.restrictsCounts)throw new Ve(e);R(e,H),Ke(e,h);const u=vt(e,h.name),c=h.sortBy.map((w,T)=>At(T)),l=h.sortBy.map((w,T)=>re(s.sortValues[T]??null));return Ot(r,u,c,h.sortBy,s.partitionKey,l,s.rowId)},async rankPage(e,n,s={}){Xe(J(s.baseWhere,s.where),t,e,"rankPage");const f=z(e,"rankPage");if(f)return R(e,H),f.rankPage(e,n,s);k(e,n,"rank");const{continueCursor:h,hasMore:u,rows:c}=_t(mt,e,n,s);return{continueCursor:h,isDone:!u,page:c.map(l=>l.doc)}},async rankPageRows(e,n,s={}){Xe(J(s.baseWhere,s.where),t,e,"rankPage"),k(e,n,"rank");const{directions:f,hasMore:h,rows:u}=_t(mt,e,n,s);return{directions:f,hasMore:h,rows:u}},async restore(e,n){const s=ie(e,n);if(!s){const u=n===void 0?O:void 0;if(u?.restore){await u.restore(e);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const f=t.tables[s.tableName]?.softDeleteMode?.field;if(!f)throw new $("INTERNAL",`ctx.db.restore: table "${s.tableName}" is not a .softDelete() table`);const h=s.row[f]!==null&&s.row[f]!==void 0;await U.patch(e,{[f]:null},n),h&&pe(s.tableName,e,void 0,s.row)},async replace(e,n,s,f){const h=ie(e,s);if(!h){const b=s===void 0?O:void 0;if(b){W(n),await b.replace(e,n,void 0,f);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:u,row:c,tableName:l}=h,w=t.tables[l];if(!w)throw new $("INTERNAL",`unknown table: ${l}`);Ht("replace",n);const T=f?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:C(),g={...n,...E(l),_creationTime:T,_id:e};Gt(w,n,g,Z),Ze(w,g),ee(l,"before","update")&&await te("before","update",{doc:{...g},id:e,op:"update",previous:c,table:l}),he(l),we(l),qe(r,l,ro(l),[T,ce(g),e,u]),Ae(l,e,g,c),ve(l,e,g),Te(l,c,g),pe(l,e,c,g),m?.invalidate(l,e,S(l,c,g)),fe(l,e,"update",g),a({indexKeys:S(l,c,g),key:e,op:"update",row:g,table:l}),ee(l,"after","update")&&await te("after","update",{doc:g,id:e,op:"update",previous:c,table:l}),await N({doc:g,id:e,op:"update",table:l})},async wipeShard(e){const n=new Set(e?.exclude),s=e?.tables,f=Object.entries(t.tables).filter(([l,w])=>n.has(l)||s!==void 0&&!s.includes(l)?!1:w.shardMode?.kind!=="global").map(([l])=>l);if(s!==void 0){for(const l of s)if(!t.tables[l])throw new $("INTERNAL",`wipeShard: unknown table: ${l}`)}const h={};let u=0;const{deleteAll:c}=U;if(c===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of f){const w=await c(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[l]=w.deleted,u+=w.deleted}return{deleted:u,tables:h}}},an={db:U,scheduler:L};return o.enforceRls===!0?Gn(U,t,(e,n)=>ie(e,n)?.tableName,(e,n)=>cn(e,n)):U};export{Ar as CDC_LOG_TABLE,Or as CLIENT_WATERMARK_TABLE,zr as GLOBAL_SHAPE_SNAPSHOT_TABLE,ti as IDEMPOTENCY_TABLE,Do as NotUniqueError,ai as SEARCH_STATE_TABLE,Nr as advanceClientWatermark,Ir as applyCdcChanges,Ht as assertNoExplicitUndefined,fo as assertValidClientId,_r as backfillAggregateIndexes,Rr as backfillRankIndexes,Tr as backfillSearchIndexes,Cr as bumpCdcEpoch,xr as cdcCanVouchFor,br as cdcSeqLeavingRows,Mr as cdcTouchesTables,Dr as cdcTrimmedError,Lr as compactCdcDocs,Er as createShardCtxDb,kr as cursorBelowRetainedFloor,Jr as deleteGlobalShapeSnapshot,Vr as deleteGlobalShapeSnapshotsForConnection,jr as migrateClientWatermark,Yr as migrateGlobalShapeSnapshot,Fr as minCdcReplayableSeq,qr as minCdcSeq,Ut as normalizeIdStructurally,Br as readCdcChangeKeys,Wr as readCdcChanges,Ur as readCdcCursor,Pr as readCdcEpoch,Kr as readClientWatermark,Xr as readGlobalShapeSnapshot,ni as readIdempotent,si as runShardMigrations,li as selectShapeMembers,ui as selectShapeRows,Gr as trimCdcChanges,oi as trimIdempotent,Zr as writeGlobalShapeSnapshot,ri as writeIdempotent};
@@ -1 +0,0 @@
1
- import{c as l,i as C,r as R}from"./ctx-db-companions-Z9JQ9xo1.mjs";import"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import"./aggregateTableName-BvenuaDR.mjs";import"./runDrizzle-2ULFQR_k.mjs";import"./do-sql-Cv3yRshL.mjs";import"./param-DlozcSQu.mjs";import"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import"./CURSOR_PREFIX-D8c7Ccj3.mjs";import"./RANK_TIEBREAK-B6iDKDW3.mjs";import"./BIGINT_KEY_DIGITS-GvEBhyR5.mjs";import"./serializeSqlValue-B_-zaEWZ.mjs";export{l as createCompanionSync,C as insertRankRow,R as rankColumnsSql};
@@ -1,7 +0,0 @@
1
- import{cursorBelowRetainedFloor as w}from"./CDC_LOG_TABLE-CMCaSndb.mjs";import{envPositiveInt as h}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{v as _,R as f,s as S,a as v,b as y}from"./sibling-channel-Cxvk0Zca.mjs";const A=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],N=new Set(A),T=s=>typeof s=="string"&&N.has(s),p="::replica::",R=s=>{const e=s.lastIndexOf(p);if(e===-1)return;const t=s.slice(0,e),r=s.slice(e+p.length);if(!(t.length===0||!T(r)))return{ownerKey:t,region:r}},L=s=>{if(s==null||!/^\d+$/.test(s))return;const e=Number.parseInt(s,10);return Number.isSafeInteger(e)&&e>0?e:void 0},O=1e3,g=1e3,b=10,I=5e4,m=s=>h(s,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",I),c="__replica_state",u=new WeakSet,E=s=>{u.has(s)||(s.exec(`CREATE TABLE IF NOT EXISTS ${c} (
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
- )`),u.add(s))},a=s=>(E(s),s.exec(`SELECT epoch, applied_seq AS appliedSeq, synced_at AS syncedAtMs FROM ${c} WHERE id = 1`).toArray()[0]),l=(s,e)=>{E(s),s.exec(`INSERT INTO ${c} (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)},C=s=>{const e=s.doName();if(e!==void 0&&R(e)!==void 0)return new Response("replica cannot serve replicas",{status:409});if(s.ownerEpoch()===void 0)return new Response("shard has no changelog to replicate",{status:409});if(v(s.env())===void 0)return new Response("replica control requires LUNORA_RELAY_SECRET",{status:403})},F=async(s,e)=>{if(s.rowCount()>m(s.env()))return Response.json({cursor:0,epoch:e,rows:[],truncated:!0});const t=s.ownerCursor()??0,r=await s.exportRows();return Response.json({cursor:t,epoch:e,rows:r})},U=(s,e,t)=>{const r=s.ownerFloor();if(w(r,t))return Response.json({changes:[],cursor:s.ownerCursor()??t,epoch:e,floor:r});const{changes:o,cursor:n}=s.readChanges(t,g);return Response.json({changes:o,cursor:n,epoch:e,...r===void 0?{}:{floor:r}})},D=async(s,e)=>{const t=C(s);if(t!==void 0)return t;const r=s.ownerEpoch();let o;try{o=await e.text()}catch{return new Response("bad request",{status:400})}if(!await _(s.env(),e.headers.get(f),o))return new Response("forbidden",{status:403});let n;try{n=JSON.parse(o)}catch{return new Response("bad request",{status:400})}if(n.type==="replica_bootstrap")return F(s,r);if(n.type==="replica_pull"){const i=typeof n.sinceSeq=="number"&&Number.isInteger(n.sinceSeq)&&n.sinceSeq>=0?n.sinceSeq:0;return U(s,r,i)}return new Response("unknown replica frame",{status:400})};class q{constructor(e,t,r){this.host=e,this.ownerKey=t,this.region=r}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 a(this.host.sql())?.appliedSeq??0}isDivergent(){return this.divergent}async advance(e){let t=a(this.host.sql());if(t===void 0){const r=await this.bootstrap();if(r===void 0)return"unavailable";t=r}return this.catchUp(t,e)}isCaughtUp(e){const t=a(this.host.sql());return t!==void 0&&this.isFreshEnough(t,e)}async catchUp(e,t){let r=e;for(let o=0;o<b;o+=1){const n=await this.pull(r.appliedSeq);if(n===void 0)return t===void 0&&this.isFreshEnough(r,void 0)?"fresh":"unavailable";if(this.hasDiverged(r,n))return"unavailable";const i=n.changes.length<g;if(r=await this.applyPage(n),i||this.isFreshEnough(r,t))return this.isFreshEnough(r,t)?"fresh":"stale"}return this.isFreshEnough(r,t)?"fresh":"stale"}async applyPage(e){e.changes.length>0&&await this.host.applyChanges(e.changes);const t={appliedSeq:e.cursor,epoch:e.epoch,syncedAtMs:Date.now()};return l(this.host.sql(),t),t}hasDiverged(e,t){const r=t.changes.length===0&&t.cursor>e.appliedSeq,o=t.floor??(r?t.cursor:0),n=o>0&&o>e.appliedSeq+1;return t.epoch===e.epoch&&!n?!1:(this.divergent=!0,!0)}async bootstrap(){const e=await this.request({type:"replica_bootstrap"});if(e===void 0)return;const t=await e.json();if(t.truncated===!0){this.divergent=!0;return}const{errors:r}=await this.host.importRows(t.rows);if(r.length>0){this.divergent=!0;return}const o={appliedSeq:t.cursor,epoch:t.epoch,syncedAtMs:Date.now()};return l(this.host.sql(),o),o}isFreshEnough(e,t){return t!==void 0?e.appliedSeq>=t:Date.now()-e.syncedAtMs<=h(this.host.env(),"LUNORA_REPLICA_MAX_STALENESS_MS",O)}async pull(e){const t=await this.request({sinceSeq:e,type:"replica_pull"});return t===void 0?void 0:await t.json()}async request(e){const t=this.host.shardBinding(),r=S(this.host.env(),t,this.ownerKey);if(r===void 0)return;const o=JSON.stringify(e),n={"content-type":"application/json","x-lunora-shard-binding":t??""},i=v(this.host.env());i!==void 0&&(n[f]=await y(i,o));try{const d=await r.fetch("https://replica.internal/_lunora/replica",{body:o,headers:n,method:"POST"});return d.ok?d:void 0}catch{return}}}const B=s=>{const e=s.doName();if(e===void 0)return;const t=R(e);return t===void 0?void 0:new q(s,t.ownerKey,t.region)},j=async(s,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 r=await s.ensureFresh(L(e.headers.get("x-lunora-min-seq")));if(r!=="fresh")return Response.json({error:{code:"REPLICA_NOT_READY",message:`replica is ${r} for this read`}},{headers:{"x-lunora-replica-fallback":r},status:421})};export{B as createReplicaLink,j as gateReplicaDispatch,D as handleReplicaControl};
@@ -1 +0,0 @@
1
- import{t as g,f as j}from"./base64-DfpzS4o_.mjs";const o="$lunora.wire$",d=64,p=1024,w="__proto__",A={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},l={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},O=r=>{if(r===null||typeof r!="object")return!1;const t=Object.getPrototypeOf(r);return t===null||t===Object.prototype},E=(r,t=0)=>{if(t>d)return!0;if(r===null)return!1;const f=typeof r;if(f==="string"||f==="boolean")return!1;if(f==="number")return!Number.isFinite(r);if(f!=="object")return!0;if(Array.isArray(r))return r.length>0&&r[0]===o?!0:r.some(a=>a===void 0||E(a,t+1));if(!O(r)||Object.hasOwn(r,w))return!0;for(const a of Object.keys(r)){const s=r[a];if(s!==void 0&&E(s,t+1))return!0}return!1},b=(r,t=0)=>{if(t>d)throw new RangeError(`wire-codec: value nesting exceeds the ${d}-level limit`);if(r===void 0)return[o,"undefined"];if(r===null)return null;const f=typeof r;if(f==="bigint")return[o,"bigint",r.toString()];if(f==="number"){const e=r;return Number.isNaN(e)?[o,"nan"]:e===1/0?[o,"inf"]:e===-1/0?[o,"-inf"]:e}if(f!=="object")return r;if(r instanceof Date)return[o,"date",b(r.getTime(),t+1)];if(r instanceof Error){const e=r,n={};for(const i of Object.keys(e)){if(e[i]===void 0)continue;const y=b(e[i],t+1);i===w?Object.defineProperty(n,i,{configurable:!0,enumerable:!0,value:y,writable:!0}):n[i]=y}const c=[o,"error",e.name,e.message,n];return e.cause!==void 0&&c.push(b(e.cause,t+1)),c}if(r instanceof URL)return[o,"url",r.href];if(r instanceof Map)return[o,"map",[...r.entries()].map(([e,n])=>[b(e,t+1),b(n,t+1)])];if(r instanceof Set)return[o,"set",[...r].map(e=>b(e,t+1))];if(r instanceof ArrayBuffer)return[o,"bytes",g(new Uint8Array(r)),"ArrayBuffer"];if(ArrayBuffer.isView(r)){const e=r,n=e.constructor.name,c=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return n==="Uint8Array"?[o,"bytes",g(c)]:[o,"bytes",g(c),n]}if(Array.isArray(r)){const e=r.map(n=>b(n,t+1));return e.length>0&&e[0]===o?[o,"arr",e]:e}if(!O(r)){const e=r.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${e} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const a=r,s={};for(const e of Object.keys(a)){const n=a[e];if(n===void 0)continue;const c=b(n,t+1);e===w?Object.defineProperty(s,e,{configurable:!0,enumerable:!0,value:c,writable:!0}):s[e]=c}return s},u=(r,t=0)=>{if(t>d)throw new RangeError(`wire-codec: value nesting exceeds the ${d}-level limit`);if(r===null||typeof r!="object")return r;if(Array.isArray(r)){if(r[0]===o)switch(r[1]){case"-inf":return-1/0;case"arr":return r[2].map(e=>u(e,t+1));case"bigint":{const e=r[2];if(typeof e!="string"||e.length>p||!/^-?\d+$/.test(e))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${p} digits)`);return BigInt(e)}case"date":{const e=u(r[2],t+1);if(typeof e!="number")throw new TypeError("wire-codec: malformed date — epoch must be a number");return new Date(e)}case"map":{const e=r[2];return new Map(e.map(n=>{if(!Array.isArray(n)||n.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[u(n[0],t+1),u(n[1],t+1)]}))}case"set":return new Set(r[2].map(e=>u(e,t+1)));case"url":{const e=r[2];if(typeof e!="string")throw new TypeError("wire-codec: malformed url — href must be a string");return new URL(e)}case"error":{const e=r[2],n=r[3],c=(Object.hasOwn(l,e)?l[e]:void 0)??Error,i=new c(n);i.name!==e&&Object.defineProperty(i,"name",{configurable:!0,value:e,writable:!0});const y=u(r[4],t+1);if(y===null||typeof y!="object"||Array.isArray(y))throw new TypeError("wire-codec: malformed error — props must be an object");for(const m of Object.keys(y))m===w?Object.defineProperty(i,m,{configurable:!0,enumerable:!0,value:y[m],writable:!0}):i[m]=y[m];return r.length>5&&Object.defineProperty(i,"cause",{configurable:!0,value:u(r[5],t+1),writable:!0}),i}case"bytes":{const e=r[2];if(typeof e!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const n=j(e),c=r[3]??"Uint8Array";if(c==="ArrayBuffer")return n.buffer.byteLength===n.byteLength?n.buffer:n.slice().buffer;const i=Object.hasOwn(A,c)?A[c]:void 0;return i?new i(n.slice().buffer):n}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return r.map(e=>u(e,t+1))}return r.map(s=>u(s,t+1))}const f=r,a={};for(const s of Object.keys(f)){const e=u(f[s],t+1);s===w?Object.defineProperty(a,s,{configurable:!0,enumerable:!0,value:e,writable:!0}):a[s]=e}return a};export{u as d,b as e,O as i,E as n};