@lunora/shard-engine 1.0.0-alpha.4 → 1.0.0-alpha.40
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/conformance/index.mjs +1 -1
- package/dist/index.d.mts +345 -26
- package/dist/index.d.ts +345 -26
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/ADMIN_FUNCTIONS-DcSYybsq.mjs +1 -0
- package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs +1 -0
- package/dist/packem_shared/AGG_COUNT-B6_CmAZD.mjs +1 -0
- package/dist/packem_shared/AUDIT_LOG_TABLE-uNVU9O1W.mjs +8 -0
- package/dist/packem_shared/CDC_LOG_TABLE-CW0wHEgW.mjs +15 -0
- package/dist/packem_shared/CLIENT_WATERMARK_TABLE-BoS1HEqz.mjs +7 -0
- package/dist/packem_shared/COMMIT_SEQ_FIELD-CSe_oNZu.mjs +4 -0
- package/dist/packem_shared/CountRlsUnsupportedError-Bdfupt3g.mjs +1 -0
- package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-4l6aU1Vc.mjs +31 -0
- package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-BAWGIEvC.mjs +1 -0
- package/dist/packem_shared/DEFAULT_MAX_RELAYS-BPv7jVgK.mjs +1 -0
- package/dist/packem_shared/DEFAULT_PROMOTION_THRESHOLDS-H2sHFvlw.mjs +1 -0
- package/dist/packem_shared/DEFAULT_TRANSACTION_LIMITS-Bcoi7Bvf.mjs +1 -0
- package/dist/packem_shared/DurableStreamRunner-DDBi1UXj.mjs +1 -0
- package/dist/packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs +1 -0
- package/dist/packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-NWaL77m5.mjs +7 -0
- package/dist/packem_shared/GlobalPollTick-BNK4o-XT.mjs +1 -0
- package/dist/packem_shared/IDEMPOTENCY_TABLE-DKVe2Ohf.mjs +7 -0
- package/dist/packem_shared/MAIL_RETENTION-Cig9Dmc8.mjs +18 -0
- package/dist/packem_shared/MAX_SQL_ROWS-gsiUV0Eo.mjs +5 -0
- package/dist/packem_shared/NotUniqueError-Dnik6z41.mjs +1 -0
- package/dist/packem_shared/QUEUE_TABLE-zj9Tt6tk.mjs +17 -0
- package/dist/packem_shared/RANK_TIEBREAK-ci3MaM65.mjs +1 -0
- package/dist/packem_shared/REACTOR_STATE_TABLE-Cr9Orfp8.mjs +28 -0
- package/dist/packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs +1 -0
- package/dist/packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs +1 -0
- package/dist/packem_shared/RLS_UNWRAP_SYMBOL-BWloGsd3.mjs +1 -0
- package/dist/packem_shared/ReactiveCache-DlJ38txF.mjs +1 -0
- package/dist/packem_shared/SCAN_DEP-D7qE3iUe.mjs +1 -0
- package/dist/packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-DsycDXWm.mjs +6 -0
- package/dist/packem_shared/SEARCH_STATE_TABLE-Dju8ebbU.mjs +1 -0
- package/dist/packem_shared/SHAPE_POKE_CURSOR_TABLE-BBuXXk5v.mjs +7 -0
- package/dist/packem_shared/ShapeDiffCache-mE7ZzdPr.mjs +1 -0
- package/dist/packem_shared/ShardRunner-C9p5DVOx.mjs +1 -0
- package/dist/packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs +1 -0
- package/dist/packem_shared/aggregateTableName-Cy5e03oz.mjs +1 -0
- package/dist/packem_shared/appendStreamChunk-CH4e4nJn.mjs +19 -0
- package/dist/packem_shared/applyOnDelete-BlcwKjuO.mjs +1 -0
- package/dist/packem_shared/applySelect-BQbHyo-W.mjs +1 -0
- package/dist/packem_shared/{armRestore-BNzdvQ_o.mjs → armRestore-Bu1_8SUa.mjs} +1 -1
- package/dist/packem_shared/awaitWsDrain-CeaR5jj8.mjs +1 -0
- package/dist/packem_shared/backfillAggregateIndexes-C9wGiPH4.mjs +1 -0
- package/dist/packem_shared/base64-DfpzS4o_.mjs +1 -0
- package/dist/packem_shared/buildIndexRange-CBKQmHSS.mjs +1 -0
- package/dist/packem_shared/buildPokeFrames-BhYUbqzO.mjs +1 -0
- package/dist/packem_shared/buildReprojectionMigration-D0f-sshM.mjs +1 -0
- package/dist/packem_shared/buildSettings-B4igo4rJ.mjs +1 -0
- package/dist/packem_shared/buildShapeDiff-C3sZW3bZ.mjs +1 -0
- package/dist/packem_shared/clearMemoryTables-CXULwypv.mjs +1 -0
- package/dist/packem_shared/compileWhereSql-JBpSfQm9.mjs +1 -0
- package/dist/packem_shared/computeRankPage-Bby1Npkd.mjs +1 -0
- package/dist/packem_shared/createCompanionSync-Cfju9Ng2.mjs +1 -0
- package/dist/packem_shared/createReplicaLink-Bv7250Ef.mjs +7 -0
- package/dist/packem_shared/createSystemReader-BtYeSMDb.mjs +1 -0
- package/dist/packem_shared/ctx-db-companions-BQRTS_WY.mjs +1 -0
- package/dist/packem_shared/ctx-db-relay-shapes-Jf5xpD1r.mjs +17 -0
- package/dist/packem_shared/defineEngineContractSuite-CjxJNwwG.mjs +1 -0
- package/dist/packem_shared/diffExternalSource-DbHrcoZK.mjs +1 -0
- package/dist/packem_shared/do-sql-DbEszTyj.mjs +1 -0
- package/dist/packem_shared/envOptionalPositiveInt-D2pY-c64.mjs +1 -0
- package/dist/packem_shared/estimate-bytes-CzG5x1f8.mjs +1 -0
- package/dist/packem_shared/exportShardRows-Cgt3ITwH.mjs +1 -0
- package/dist/packem_shared/hasTrigger-CjlwI4le.mjs +1 -0
- package/dist/packem_shared/isSoftDeleted-D0iaSrDV.mjs +9 -0
- package/dist/packem_shared/liftSourceId-CA3ENhXj.mjs +1 -0
- package/dist/packem_shared/materializeExternalRows-CX55UoV7.mjs +1 -0
- package/dist/packem_shared/mergeChangedKeys-D1T-TPUb.mjs +1 -0
- package/dist/packem_shared/param-Ib8WHnrF.mjs +1 -0
- package/dist/packem_shared/quoteIdentifier-CObIFRhb.mjs +1 -0
- package/dist/packem_shared/runDrizzle-it6rL9bR.mjs +1 -0
- package/dist/packem_shared/runShardMigrations-DFc_LoP-.mjs +5 -0
- package/dist/packem_shared/runSocketPool-CZJ2X9cF.mjs +1 -0
- package/dist/packem_shared/selectExpiredIds-w4fPtlwT.mjs +1 -0
- package/dist/packem_shared/selectShapeMembers-C0vtU60D.mjs +1 -0
- package/dist/packem_shared/serializeSqlValue-DbI1VQYM.mjs +1 -0
- package/dist/packem_shared/sibling-channel-Cxvk0Zca.mjs +1 -0
- package/dist/packem_shared/sql-projection-BqmxFxQU.mjs +1 -0
- package/dist/packem_shared/stableStringify-G9OF5wcs.mjs +1 -0
- package/dist/packem_shared/stableWireKey-DSCJB6E7.mjs +1 -0
- package/dist/packem_shared/wire-codec-BU9T2xJ7.mjs +1 -0
- package/package.json +3 -3
- package/dist/packem_shared/ADMIN_FUNCTIONS-B0xlQJ4w.mjs +0 -1
- package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs +0 -1
- package/dist/packem_shared/AGG_COUNT-BWXe3gtQ.mjs +0 -1
- package/dist/packem_shared/AUDIT_LOG_TABLE-CaA0jL0L.mjs +0 -8
- package/dist/packem_shared/CDC_LOG_TABLE-BnqlH2eZ.mjs +0 -8
- package/dist/packem_shared/CLIENT_WATERMARK_TABLE-CXsSLU8D.mjs +0 -7
- package/dist/packem_shared/CountRlsUnsupportedError-B2WKJD9v.mjs +0 -1
- package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-BZMVrLcy.mjs +0 -31
- package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-bq00btqV.mjs +0 -1
- package/dist/packem_shared/DEFAULT_MAX_RELAYS-CnCyh6oX.mjs +0 -1
- package/dist/packem_shared/DEFAULT_PROMOTION_THRESHOLDS-Dteg0sZF.mjs +0 -1
- package/dist/packem_shared/DEFAULT_TRANSACTION_LIMITS--TtB8Gpo.mjs +0 -1
- package/dist/packem_shared/FTS_COUNT_COLUMN-D1gY3wwZ-CZHdaRrd.mjs +0 -1
- package/dist/packem_shared/GEO_DEFAULT_PRECISION-okRCkZ6r.mjs +0 -1
- package/dist/packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-DX-6-gBP.mjs +0 -7
- package/dist/packem_shared/IDEMPOTENCY_TABLE-DjkEMp6w.mjs +0 -7
- package/dist/packem_shared/MAIL_RETENTION-KmozO2NQ.mjs +0 -18
- package/dist/packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs +0 -2
- package/dist/packem_shared/NotUniqueError-iGKd9wRR.mjs +0 -1
- package/dist/packem_shared/QUEUE_TABLE-DYCDvzTG.mjs +0 -17
- package/dist/packem_shared/RANK_TIEBREAK-9NU5s_mi.mjs +0 -1
- package/dist/packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs +0 -1
- package/dist/packem_shared/RLS_UNWRAP_SYMBOL-C6_WX3dG.mjs +0 -1
- package/dist/packem_shared/ReactiveCache-CF21t8IB.mjs +0 -1
- package/dist/packem_shared/SCAN_DEP-D_yR9EeV.mjs +0 -1
- package/dist/packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CHXz6p_z.mjs +0 -6
- package/dist/packem_shared/SEARCH_STATE_TABLE-eLN8U5tz.mjs +0 -1
- package/dist/packem_shared/ShardRunner-DIqVdWtk.mjs +0 -1
- package/dist/packem_shared/aggregateTableName-G-eXyjcz.mjs +0 -1
- package/dist/packem_shared/applyOnDelete-uFRC5p1d.mjs +0 -1
- package/dist/packem_shared/applySelect-B0CF8T7y.mjs +0 -1
- package/dist/packem_shared/awaitWsDrain-Dk50ISgE.mjs +0 -1
- package/dist/packem_shared/backfillAggregateIndexes-BHiewuB-.mjs +0 -1
- package/dist/packem_shared/buildIndexRange-DIjFVgeO.mjs +0 -1
- package/dist/packem_shared/buildPokeFrames-DaPpm5Ss.mjs +0 -1
- package/dist/packem_shared/buildSettings-DT18_DkX.mjs +0 -1
- package/dist/packem_shared/compileWhereSql-BLcfs4QW.mjs +0 -1
- package/dist/packem_shared/computeRankPage-IUSS-zIB.mjs +0 -1
- package/dist/packem_shared/createCompanionSync-DWK0Vlg1.mjs +0 -1
- package/dist/packem_shared/createReadFootprint-DIrrxRTE.mjs +0 -1
- package/dist/packem_shared/createSystemReader-DcDcrtM3.mjs +0 -1
- package/dist/packem_shared/defineEngineContractSuite-BefTibvY.mjs +0 -1
- package/dist/packem_shared/diffExternalSource-DMpkJta1.mjs +0 -1
- package/dist/packem_shared/estimate-bytes-DzD3PdCc.mjs +0 -1
- package/dist/packem_shared/exportShardRows-kt42wijd.mjs +0 -1
- package/dist/packem_shared/hasTrigger-CbkOHExZ.mjs +0 -1
- package/dist/packem_shared/isSoftDeleted-B-SXkGUo.mjs +0 -9
- package/dist/packem_shared/liftSourceId-DApAbu7Q.mjs +0 -1
- package/dist/packem_shared/materializeExternalRows-DOQJV9p2.mjs +0 -1
- package/dist/packem_shared/mergeChangedKeys-CvSHlkv-.mjs +0 -1
- package/dist/packem_shared/param-B5lF5Jd9.mjs +0 -1
- package/dist/packem_shared/quote-identifier-CGiYFBvY.mjs +0 -1
- package/dist/packem_shared/runDrizzle-GKR3y97k.mjs +0 -1
- package/dist/packem_shared/runShardMigrations-CPxqCh3O.mjs +0 -5
- package/dist/packem_shared/runSocketPool-DPQLVyWF.mjs +0 -1
- package/dist/packem_shared/selectExpiredIds-FzhIEeG1.mjs +0 -1
- package/dist/packem_shared/selectShapeMemberIds-DvE7K6zG.mjs +0 -1
- package/dist/packem_shared/serializeSqlValue-DnpyaLcw.mjs +0 -1
- package/dist/packem_shared/stableStringify-BjLh4gvA.mjs +0 -1
- package/dist/packem_shared/stableWireKey-YEHLaX6X.mjs +0 -1
- package/dist/packem_shared/wire-codec-Ctnni0h6.mjs +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{exportShardRows as o,exportShardTable as a,importShardRows as t,parseExportShardArgs as n,parseImportShardArgs as l,selectExportTables as i,validateImportRow as s}from"./packem_shared/exportShardRows-kt42wijd.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as p,matchesStaticWhere as c,normalizeCountArgument as S,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{aggregateTableName as f,coerceAggregateNumber as T,encodeAggregateKey as g,foldAggregateTally as h,readAggregateValue as A}from"./packem_shared/aggregateTableName-G-eXyjcz.mjs";import{CountRlsUnsupportedError as C,mergeWhere as I,planAggregateLookup as _,selectIndexForAggregate as R,selectIndexForCount as L,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-B2WKJD9v.mjs";import{AUDIT_LOG_TABLE as N,appendAuditEntry as M,ensureAuditTable as F,readAuditLog as O}from"./packem_shared/AUDIT_LOG_TABLE-CaA0jL0L.mjs";import{NotUniqueError as P,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-iGKd9wRR.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as K,backfillSearchIndexes as q,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-BHiewuB-.mjs";import{CDC_LOG_TABLE as z,CDC_META_TABLE as V,appendCdcChange as H,applyCdcChanges as X,bumpCdcEpoch as Q,migrateCdcLog as Y,migrateCdcMeta as j,minCdcSeq as J,readCdcChanges as Z,readCdcCursor as $,readCdcEpoch as ee,trimCdcChanges as re}from"./packem_shared/CDC_LOG_TABLE-BnqlH2eZ.mjs";import{CLIENT_WATERMARK_TABLE as ae,advanceClientWatermark as te,migrateClientWatermark as ne,readClientWatermark as le}from"./packem_shared/CLIENT_WATERMARK_TABLE-CXsSLU8D.mjs";import{createCompanionSync as se}from"./packem_shared/createCompanionSync-DWK0Vlg1.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as de,deleteGlobalShapeSnapshot as pe,deleteGlobalShapeSnapshotsForConnection as ce,migrateGlobalShapeSnapshot as Se,readGlobalShapeSnapshot as ue,writeGlobalShapeSnapshot as xe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-DX-6-gBP.mjs";import{IDEMPOTENCY_TABLE as Te,migrateIdempotency as ge,readIdempotent as he,trimIdempotent as Ae,writeIdempotent as Ee}from"./packem_shared/IDEMPOTENCY_TABLE-DjkEMp6w.mjs";import{computeRankPage as Ie,hydrateDocsById as _e}from"./packem_shared/computeRankPage-IUSS-zIB.mjs";import{SEARCH_STATE_TABLE as Le,migrateSearchState as be,readSearchBackfillState as ye,writeSearchBackfillState as Ne}from"./packem_shared/SEARCH_STATE_TABLE-eLN8U5tz.mjs";import{selectShapeMemberIds as Fe,selectShapeRows as Oe}from"./packem_shared/selectShapeMemberIds-DvE7K6zG.mjs";import{DATA_MIGRATION_STATE_TABLE as Pe,readMigrationStatus as ke,runDataMigration as Be}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-BZMVrLcy.mjs";import{SCAN_DEP as Ue,createDependencyTracker as we,depKey as Ke,tableFromDepKey as qe}from"./packem_shared/SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as ve,runSql as ze}from"./packem_shared/runDrizzle-GKR3y97k.mjs";import{AGG_COUNT as He,AGG_KEY as Xe,AGG_VALUE as Qe,DOC_COLUMN as Ye,aggUpsertSql as je,createIndexSql as Je,geoTableName as Ze,isFtsAvailable as $e,jsonPath as er,jsonPathSql as rr,qualifiedJsonPath as or,qualifiedJsonPathSql as ar,quoteIdentifier as tr,rowToDocument as nr,tableColumns as lr,tryRowToDocument as ir}from"./packem_shared/AGG_COUNT-BWXe3gtQ.mjs";import{param as mr,renderSql as dr}from"./packem_shared/param-B5lF5Jd9.mjs";import{diffExternalSource as cr}from"./packem_shared/diffExternalSource-DMpkJta1.mjs";import{liftSourceId as ur,normalizeSourceDocument as xr,normalizeSourceValue as fr}from"./packem_shared/liftSourceId-DApAbu7Q.mjs";import{materializeExternalRows as gr,materializeExternalRowsIncremental as hr,readExternalSourceBaseline as Ar,runExternalSourceTick as Er}from"./packem_shared/materializeExternalRows-DOQJV9p2.mjs";import{isSoftDeleted as Ir,isSourceDue as _r,pullExternalSourceIncrementalTick as Rr,pullExternalSourceTick as Lr}from"./packem_shared/isSoftDeleted-B-SXkGUo.mjs";import{GEO_DEFAULT_PRECISION as yr,boundingBoxCenter as Nr,boundingBoxGeohashes as Mr,coveringGeohashes as Fr,encodeGeohash as Or,haversineMeters as Dr,pointInBoundingBox as Pr}from"./packem_shared/GEO_DEFAULT_PRECISION-okRCkZ6r.mjs";import{ADMIN_FUNCTIONS as Br,ADMIN_FUNCTION_PREFIX as Gr,DEFAULT_FANOUT_TOPIC_LIMIT as Ur,FLAGS_FUNCTION_PREFIX as wr,MAX_PAGE_SIZE as Kr,RELATION_FUNCTION_PREFIX as qr,createFanoutCounters as Wr,facetColumn as vr,findStorageReferences as zr,listTables as Vr,readTablePage as Hr,recordFanoutPass as Xr,selectMatchingIds as Qr,summarizeFanoutTopics as Yr,summarizeSubscriptions as jr}from"./packem_shared/ADMIN_FUNCTIONS-B0xlQJ4w.mjs";import{MAIL_RETENTION as Zr,MAIL_TABLE as $r,clearCapturedMail as eo,ensureMailTable as ro,readCapturedMail as oo,recordCapturedMail as ao}from"./packem_shared/MAIL_RETENTION-KmozO2NQ.mjs";import{NotFoundError as no}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as io,readBookmark as so}from"./packem_shared/armRestore-BNzdvQ_o.mjs";import{applySelect as po,buildSeekBeforeWhere as co,buildSeekWhere as So,decodeCursor as uo,encodeCursor as xo,normalizeOrderKeys as fo,softDeleteScope as To}from"./packem_shared/applySelect-B0CF8T7y.mjs";import{QUEUE_TABLE as ho,clearQueueMessages as Ao,isLossyBody as Eo,readQueueMessageById as Co,readQueueMessages as Io,recordQueueMessages as _o}from"./packem_shared/QUEUE_TABLE-DYCDvzTG.mjs";import{RANK_TIEBREAK as Lo,encodePartitionKey as bo,matchesRankStaticWhere as yo,rankKeyFromDoc as No,rankTableName as Mo,resolveRankPartition as Fo,sortColumnName as Oo}from"./packem_shared/RANK_TIEBREAK-9NU5s_mi.mjs";import{ReactiveCache as Po,reactiveCacheKey as ko}from"./packem_shared/ReactiveCache-CF21t8IB.mjs";import{createReadFootprint as Go}from"./packem_shared/createReadFootprint-DIrrxRTE.mjs";import{buildIndexRange as wo,indexKeysForRow as Ko,keysTouchRanges as qo}from"./packem_shared/buildIndexRange-DIjFVgeO.mjs";import{DEFAULT_MAX_RELATION_KEYS as vo,assertFlatPredicate as zo,assertShapeShardable as Vo,containsRelationPredicate as Ho,isRelationPredicate as Xo,resolveRelationPredicates as Qo}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-bq00btqV.mjs";import{applyOnDelete as jo,distinctValues as Jo,fanOutScalarCounts as Zo,resolveWith as $o,runRowValidators as ea}from"./packem_shared/applyOnDelete-uFRC5p1d.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as oa,clampPromotionThresholds as aa,nextPromotionState as ta,relayCountFor as na,shapeRoutingKey as la}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-Dteg0sZF.mjs";import{DEFAULT_MAX_RELAYS as sa,OwnerRelay as ma,RelayMember as da,createRelayLink as pa}from"./packem_shared/DEFAULT_MAX_RELAYS-CnCyh6oX.mjs";import{RLS_UNWRAP_SYMBOL as Sa,RlsRequiredError as ua,guardWriter as xa}from"./packem_shared/RLS_UNWRAP_SYMBOL-C6_WX3dG.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ta,readSchemaHistory as ga,readSchemaVersion as ha,recordSchemaVersion as Aa}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CHXz6p_z.mjs";import{serializeSqlValue as Ca}from"./packem_shared/serializeSqlValue-DnpyaLcw.mjs";import{buildSettings as _a,isDevEnvironment as Ra}from"./packem_shared/buildSettings-DT18_DkX.mjs";import{buildPokeFrames as ba,diffGlobalMembership as ya,encodeRowsPatch as Na,projectColumns as Ma}from"./packem_shared/buildPokeFrames-DaPpm5Ss.mjs";import{ShardRunner as Oa}from"./packem_shared/ShardRunner-DIqVdWtk.mjs";import{runSocketPool as Pa}from"./packem_shared/runSocketPool-DPQLVyWF.mjs";import{MAX_SQL_ROWS as Ba,assertReadonly as Ga,lintReadonlySql as Ua,runReadonlySql as wa}from"./packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs";import{awaitWsDrain as qa,sendDeltaFrames as Wa,subscriptionListDeltas as va,trySendFrame as za}from"./packem_shared/awaitWsDrain-Dk50ISgE.mjs";import{mergeChangedKeys as Ha,recordChangedKeys as Xa,writeTouchesMemo as Qa}from"./packem_shared/mergeChangedKeys-CvSHlkv-.mjs";import{createSystemReader as ja}from"./packem_shared/createSystemReader-DcDcrtM3.mjs";import{ConflictError as Za}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as et,TransactionHeadroomTracker as rt}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS--TtB8Gpo.mjs";import{hasTrigger as at,runTriggers as tt}from"./packem_shared/hasTrigger-CbkOHExZ.mjs";import{selectExpiredIds as lt}from"./packem_shared/selectExpiredIds-FzhIEeG1.mjs";import{compileWhereSql as st}from"./packem_shared/compileWhereSql-BLcfs4QW.mjs";import{RELATION_EXISTS_KEY as dt}from"./packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs";import{runShardMigrations as ct}from"./packem_shared/runShardMigrations-CPxqCh3O.mjs";import{stableStringify as ut}from"./packem_shared/stableStringify-BjLh4gvA.mjs";import{stableWireKey as ft}from"./packem_shared/stableWireKey-YEHLaX6X.mjs";export{Br as ADMIN_FUNCTIONS,Gr as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,He as AGG_COUNT,Xe as AGG_KEY,Qe as AGG_VALUE,N as AUDIT_LOG_TABLE,z as CDC_LOG_TABLE,V as CDC_META_TABLE,ae as CLIENT_WATERMARK_TABLE,Za as ConflictError,C as CountRlsUnsupportedError,Pe as DATA_MIGRATION_STATE_TABLE,Ur as DEFAULT_FANOUT_TOPIC_LIMIT,vo as DEFAULT_MAX_RELATION_KEYS,sa as DEFAULT_MAX_RELAYS,oa as DEFAULT_PROMOTION_THRESHOLDS,et as DEFAULT_TRANSACTION_LIMITS,Ye as DOC_COLUMN,wr as FLAGS_FUNCTION_PREFIX,yr as GEO_DEFAULT_PRECISION,de as GLOBAL_SHAPE_SNAPSHOT_TABLE,Te as IDEMPOTENCY_TABLE,Zr as MAIL_RETENTION,$r as MAIL_TABLE,Kr as MAX_PAGE_SIZE,Ba as MAX_SQL_ROWS,no as NotFoundError,P as NotUniqueError,ma as OwnerRelay,ho as QUEUE_TABLE,Lo as RANK_TIEBREAK,dt as RELATION_EXISTS_KEY,qr as RELATION_FUNCTION_PREFIX,Sa as RLS_UNWRAP_SYMBOL,Po as ReactiveCache,da as RelayMember,ua as RlsRequiredError,Ue as SCAN_DEP,Ta as SCHEMA_HISTORY_MAX_VERSIONS,Le as SEARCH_STATE_TABLE,Oa as ShardRunner,rt as TransactionHeadroomTracker,te as advanceClientWatermark,je as aggUpsertSql,p as aggregateSqlFunction,f as aggregateTableName,M as appendAuditEntry,H as appendCdcChange,X as applyCdcChanges,jo as applyOnDelete,po as applySelect,io as armRestore,zo as assertFlatPredicate,Ga as assertReadonly,Vo as assertShapeShardable,k as assertValidClientId,qa as awaitWsDrain,w as backfillAggregateIndexes,K as backfillRankIndexes,q as backfillSearchIndexes,W as backfillSearchIndexesForTable,Nr as boundingBoxCenter,Mr as boundingBoxGeohashes,wo as buildIndexRange,ba as buildPokeFrames,co as buildSeekBeforeWhere,So as buildSeekWhere,_a as buildSettings,Q as bumpCdcEpoch,aa as clampPromotionThresholds,eo as clearCapturedMail,Ao as clearQueueMessages,T as coerceAggregateNumber,st as compileWhereSql,Ie as computeRankPage,Ho as containsRelationPredicate,Fr as coveringGeohashes,se as createCompanionSync,we as createDependencyTracker,Wr as createFanoutCounters,Je as createIndexSql,Go as createReadFootprint,pa as createRelayLink,B as createShardCtxDb,ja as createSystemReader,uo as decodeCursor,pe as deleteGlobalShapeSnapshot,ce as deleteGlobalShapeSnapshotsForConnection,Ke as depKey,cr as diffExternalSource,ya as diffGlobalMembership,Jo as distinctValues,g as encodeAggregateKey,xo as encodeCursor,Or as encodeGeohash,bo as encodePartitionKey,Na as encodeRowsPatch,F as ensureAuditTable,ro as ensureMailTable,o as exportShardRows,a as exportShardTable,vr as facetColumn,Zo as fanOutScalarCounts,zr as findStorageReferences,h as foldAggregateTally,Ze as geoTableName,xa as guardWriter,at as hasTrigger,Dr as haversineMeters,_e as hydrateDocsById,t as importShardRows,Ko as indexKeysForRow,Ra as isDevEnvironment,$e as isFtsAvailable,Eo as isLossyBody,Xo as isRelationPredicate,Ir as isSoftDeleted,_r as isSourceDue,er as jsonPath,rr as jsonPathSql,qo as keysTouchRanges,ur as liftSourceId,Ua as lintReadonlySql,Vr as listTables,yo as matchesRankStaticWhere,c as matchesStaticWhere,gr as materializeExternalRows,hr as materializeExternalRowsIncremental,Ha as mergeChangedKeys,I as mergeWhere,Y as migrateCdcLog,j as migrateCdcMeta,ne as migrateClientWatermark,Se as migrateGlobalShapeSnapshot,ge as migrateIdempotency,be as migrateSearchState,J as minCdcSeq,ta as nextPromotionState,S as normalizeCountArgument,G as normalizeIdStructurally,fo as normalizeOrderKeys,xr as normalizeSourceDocument,fr as normalizeSourceValue,mr as param,n as parseExportShardArgs,l as parseImportShardArgs,_ as planAggregateLookup,Pr as pointInBoundingBox,Ma as projectColumns,Rr as pullExternalSourceIncrementalTick,Lr as pullExternalSourceTick,or as qualifiedJsonPath,ar as qualifiedJsonPathSql,tr as quoteIdentifier,No as rankKeyFromDoc,Mo as rankTableName,ko as reactiveCacheKey,A as readAggregateValue,O as readAuditLog,so as readBookmark,oo as readCapturedMail,Z as readCdcChanges,$ as readCdcCursor,ee as readCdcEpoch,le as readClientWatermark,Ar as readExternalSourceBaseline,ue as readGlobalShapeSnapshot,he as readIdempotent,ke as readMigrationStatus,Co as readQueueMessageById,Io as readQueueMessages,ga as readSchemaHistory,ha as readSchemaVersion,ye as readSearchBackfillState,Hr as readTablePage,ao as recordCapturedMail,Xa as recordChangedKeys,Xr as recordFanoutPass,_o as recordQueueMessages,Aa as recordSchemaVersion,na as relayCountFor,dr as renderSql,Fo as resolveRankPartition,Qo as resolveRelationPredicates,$o as resolveWith,nr as rowToDocument,Be as runDataMigration,ve as runDrizzle,Er as runExternalSourceTick,wa as runReadonlySql,ea as runRowValidators,ct as runShardMigrations,Pa as runSocketPool,ze as runSql,tt as runTriggers,lt as selectExpiredIds,i as selectExportTables,R as selectIndexForAggregate,L as selectIndexForCount,b as selectIndexForGroupBy,Qr as selectMatchingIds,Fe as selectShapeMemberIds,Oe as selectShapeRows,Wa as sendDeltaFrames,Ca as serializeSqlValue,la as shapeRoutingKey,To as softDeleteScope,Oo as sortColumnName,ut as stableStringify,ft as stableWireKey,va as subscriptionListDeltas,Yr as summarizeFanoutTopics,jr as summarizeSubscriptions,lr as tableColumns,qe as tableFromDepKey,u as throwingScheduler,re as trimCdcChanges,Ae as trimIdempotent,ir as tryRowToDocument,za as trySendFrame,s as validateImportRow,xe as writeGlobalShapeSnapshot,Ee as writeIdempotent,Ne as writeSearchBackfillState,Qa as writeTouchesMemo};
|
|
1
|
+
import{exportShardRows as o,exportShardTable as a,importShardRows as t,parseExportShardArgs as n,parseImportShardArgs as l,selectExportTables as s,validateImportRow as i}from"./packem_shared/exportShardRows-Cgt3ITwH.mjs";import{AGGREGATE_SQL_FUNCTION as c,aggregateSqlFunction as p,matchesStaticWhere as d,normalizeCountArgument as S,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as x,coerceAggregateNumber as T,encodeAggregateKey as h,foldAggregateTally as E,readAggregateValue as C}from"./packem_shared/aggregateTableName-Cy5e03oz.mjs";import{CountRlsUnsupportedError as A,mergeWhere as g,planAggregateLookup as _,selectIndexForAggregate as I,selectIndexForCount as b,selectIndexForGroupBy as L}from"./packem_shared/CountRlsUnsupportedError-Bdfupt3g.mjs";import{AUDIT_LOG_TABLE as P,appendAuditEntry as D,ensureAuditTable as y,readAuditLog as N}from"./packem_shared/AUDIT_LOG_TABLE-uNVU9O1W.mjs";import{NotUniqueError as F,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-Dnik6z41.mjs";import{backfillAggregateIndexes as q,backfillRankIndexes as w,backfillSearchIndexes as K,backfillSearchIndexesForTable as v}from"./packem_shared/backfillAggregateIndexes-C9wGiPH4.mjs";import{CDC_LOG_TABLE as H,CDC_LOG_TABLE_SEQ_INDEX as X,CDC_META_TABLE as z,appendCdcChange as V,applyCdcChanges as Q,bumpCdcEpoch as j,cdcCanVouchFor as Y,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 le,readCdcChanges as se,readCdcCursor as ie,readCdcEpoch as me,trimCdcChanges as ce}from"./packem_shared/CDC_LOG_TABLE-CW0wHEgW.mjs";import{CLIENT_WATERMARK_TABLE as de,advanceClientWatermark as Se,migrateClientWatermark as ue,readClientWatermark as fe}from"./packem_shared/CLIENT_WATERMARK_TABLE-BoS1HEqz.mjs";import{COMMIT_SEQ_FIELD as Te,COMMIT_SEQ_TABLE as he,allocateCommitSeq as Ee,migrateCommitSeq as Ce,readCommitSeq as Re}from"./packem_shared/COMMIT_SEQ_FIELD-CSe_oNZu.mjs";import{c as ge}from"./packem_shared/ctx-db-companions-BQRTS_WY.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Ie,deleteGlobalShapeSnapshot as be,deleteGlobalShapeSnapshotsForConnection as Le,migrateGlobalShapeSnapshot as Me,readGlobalShapeSnapshot as Pe,writeGlobalShapeSnapshot as De}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-NWaL77m5.mjs";import{IDEMPOTENCY_TABLE as Ne,migrateIdempotency as Oe,readIdempotent as Fe,trimIdempotent as ke,writeIdempotent as Be}from"./packem_shared/IDEMPOTENCY_TABLE-DKVe2Ohf.mjs";import{clearMemoryTables as Ue,isMemoryTable as qe,memoryTableNames as we}from"./packem_shared/clearMemoryTables-CXULwypv.mjs";import{computeRankPage as ve,hydrateDocsById as We}from"./packem_shared/computeRankPage-Bby1Npkd.mjs";import{SEARCH_STATE_TABLE as Xe,migrateSearchState as ze,readSearchBackfillState as Ve,writeSearchBackfillState as Qe}from"./packem_shared/SEARCH_STATE_TABLE-Dju8ebbU.mjs";import{SHAPE_POKE_CURSOR_TABLE as Ye,deleteShapePokeCursor as Je,deleteShapePokeCursorsForConnection as Ze,migrateShapePokeCursor as $e,minShapePokeCursor as er,readShapePokeCursor as rr,writeShapePokeCursor as or}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-BBuXXk5v.mjs";import{selectShapeMembers as tr,selectShapeRows as nr}from"./packem_shared/selectShapeMembers-C0vtU60D.mjs";import{DATA_MIGRATION_STATE_TABLE as sr,readMigrationStatus as ir,runDataMigration as mr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-4l6aU1Vc.mjs";import{SCAN_DEP as pr,createDependencyTracker as dr,depKey as Sr,tableFromDepKey as ur}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as xr,runSql as Tr}from"./packem_shared/runDrizzle-it6rL9bR.mjs";import{A as Er,a as Cr,b as Rr,D as Ar,c as gr,d as _r,g as Ir,i as br,j as Lr,e as Mr,q as Pr,f as Dr,r as yr,t as Nr,h as Or}from"./packem_shared/do-sql-DbEszTyj.mjs";import{param as kr,renderSql as Br,sqliteInList as Gr,unionAll as Ur}from"./packem_shared/param-Ib8WHnrF.mjs";import{appendStreamChunk as wr,claimStreamRun as Kr,deleteStreamRun as vr,finishStreamRun as Wr,migrateDurableStreams as Hr,readStreamChunks as Xr,readStreamRun as zr,trimStreamRuns as Vr}from"./packem_shared/appendStreamChunk-CH4e4nJn.mjs";import{DurableStreamRunner as jr,MAX_DURABLE_STREAM_BYTES as Yr,MAX_DURABLE_STREAM_CHUNKS as Jr,decideDurableAttach as Zr}from"./packem_shared/DurableStreamRunner-DDBi1UXj.mjs";import{envOptionalPositiveInt as eo,envPositiveInt as ro}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as ao}from"./packem_shared/diffExternalSource-DbHrcoZK.mjs";import{liftSourceId as no,normalizeSourceDocument as lo,normalizeSourceValue as so}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as mo,materializeExternalRowsIncremental as co,readExternalSourceBaseline as po,runExternalSourceTick as So}from"./packem_shared/materializeExternalRows-CX55UoV7.mjs";import{isSoftDeleted as fo,isSourceDue as xo,pullExternalSourceIncrementalTick as To,pullExternalSourceTick as ho}from"./packem_shared/isSoftDeleted-D0iaSrDV.mjs";import{GEO_DEFAULT_PRECISION as Co,boundingBoxCenter as Ro,boundingBoxGeohashes as Ao,coveringGeohashes as go,encodeGeohash as _o,haversineMeters as Io,pointInBoundingBox as bo}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as Mo}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as Do,ADMIN_FUNCTION_PREFIX as yo,DEFAULT_FANOUT_TOPIC_LIMIT as No,FLAGS_FUNCTION_PREFIX as Oo,MAX_PAGE_SIZE as Fo,RELATION_FUNCTION_PREFIX as ko,createFanoutCounters as Bo,createGlobalPollCounters as Go,createShapeProbeCounters as Uo,facetColumn as qo,findStorageReferences as wo,listTables as Ko,readTablePage as vo,recordFanoutPass as Wo,recordGlobalPollPass as Ho,recordShapeProbePass as Xo,selectMatchingIds as zo,summarizeFanoutTopics as Vo,summarizeSubscriptions as Qo}from"./packem_shared/ADMIN_FUNCTIONS-DcSYybsq.mjs";import{MAIL_RETENTION as Yo,MAIL_TABLE as Jo,clearCapturedMail as Zo,ensureMailTable as $o,readCapturedMail as ea,recordCapturedMail as ra}from"./packem_shared/MAIL_RETENTION-Cig9Dmc8.mjs";import{NotFoundError as aa}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as na,readBookmark as la}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{applySelect as ia,buildSeekBeforeWhere as ma,buildSeekWhere as ca,decodeCursor as pa,encodeCursor as da,normalizeOrderKeys as Sa,softDeleteScope as ua}from"./packem_shared/applySelect-BQbHyo-W.mjs";import{QUEUE_TABLE as xa,clearQueueMessages as Ta,isLossyBody as ha,readQueueMessageById as Ea,readQueueMessages as Ca,recordQueueMessages as Ra}from"./packem_shared/QUEUE_TABLE-zj9Tt6tk.mjs";import{RANK_TIEBREAK as ga,encodePartitionKey as _a,matchesRankStaticWhere as Ia,rankKeyFromDoc as ba,rankTableName as La,resolveRankPartition as Ma,sortColumnName as Pa}from"./packem_shared/RANK_TIEBREAK-ci3MaM65.mjs";import{ReactiveCache as ya,reactiveCacheKey as Na}from"./packem_shared/ReactiveCache-DlJ38txF.mjs";import{REACTOR_STATE_TABLE as Fa,listReactorStates as ka,migrateReactorState as Ba,reactorNeedsRun as Ga,readReactorState as Ua,writeReactorState as qa}from"./packem_shared/REACTOR_STATE_TABLE-Cr9Orfp8.mjs";import{UNVOUCHABLE_DEP as Ka,createReadFootprint as va,markUnvouchableReads as Wa}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as Xa,indexKeysForRow as za,keysTouchRanges as Va}from"./packem_shared/buildIndexRange-CBKQmHSS.mjs";import{DEFAULT_MAX_RELATION_KEYS as ja,assertFlatPredicate as Ya,assertShapeShardable as Ja,containsRelationPredicate as Za,isRelationPredicate as $a,resolveRelationPredicates as et}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-BAWGIEvC.mjs";import{applyOnDelete as ot,distinctValues as at,fanOutScalarCounts as tt,relationHooks as nt,resolveWith as lt,runRowValidators as st}from"./packem_shared/applyOnDelete-BlcwKjuO.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as mt,clampPromotionThresholds as ct,nextPromotionState as pt,relayCountFor as dt,shapeRoutingKey as St}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-H2sHFvlw.mjs";import{DEFAULT_MAX_RELAYS as ft,OwnerRelay as xt,RelayMember as Tt,createRelayLink as ht}from"./packem_shared/DEFAULT_MAX_RELAYS-BPv7jVgK.mjs";import{createReplicaLink as Ct,gateReplicaDispatch as Rt,handleReplicaControl as At}from"./packem_shared/createReplicaLink-Bv7250Ef.mjs";import{buildReprojectionMigration as _t,countLegacyRows as It,reprojectableFields as bt,reprojectionTables as Lt}from"./packem_shared/buildReprojectionMigration-D0f-sshM.mjs";import{RLS_UNWRAP_SYMBOL as Pt,RlsRequiredError as Dt,guardWriter as yt}from"./packem_shared/RLS_UNWRAP_SYMBOL-BWloGsd3.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ot,readSchemaHistory as Ft,readSchemaVersion as kt,recordSchemaVersion as Bt}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-DsycDXWm.mjs";import{serializeSqlValue as Ut}from"./packem_shared/serializeSqlValue-DbI1VQYM.mjs";import{buildSettings as wt,isDevEnvironment as Kt}from"./packem_shared/buildSettings-B4igo4rJ.mjs";import{buildShapeDiff as Wt}from"./packem_shared/buildShapeDiff-C3sZW3bZ.mjs";import{ShapeDiffCache as Xt,createShapeDiffCache as zt,globalShapeReadKey as Vt}from"./packem_shared/ShapeDiffCache-mE7ZzdPr.mjs";import{buildPokeFrames as jt,diffGlobalMembership as Yt,encodeRowsPatch as Jt,projectColumns as Zt}from"./packem_shared/buildPokeFrames-BhYUbqzO.mjs";import{ShardRunner as en}from"./packem_shared/ShardRunner-C9p5DVOx.mjs";import{runSocketPool as on}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as tn,assertReadonly as nn,lintReadonlySql as ln,runReadonlySql as sn}from"./packem_shared/MAX_SQL_ROWS-gsiUV0Eo.mjs";import{awaitWsDrain as cn,subscriptionFrames as pn,subscriptionListDeltas as dn,trySendFrame as Sn}from"./packem_shared/awaitWsDrain-CeaR5jj8.mjs";import{mergeChangedKeys as fn,recordChangedKeys as xn,writeTouchesMemo as Tn}from"./packem_shared/mergeChangedKeys-D1T-TPUb.mjs";import{createSystemReader as En}from"./packem_shared/createSystemReader-BtYeSMDb.mjs";import{ConflictError as Rn}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as gn,TransactionHeadroomTracker as _n}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-Bcoi7Bvf.mjs";import{hasTrigger as bn,runTriggers as Ln}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as Pn}from"./packem_shared/selectExpiredIds-w4fPtlwT.mjs";import{compileWhereSql as yn,literalInList as Nn}from"./packem_shared/compileWhereSql-JBpSfQm9.mjs";import{RELATION_EXISTS_KEY as Fn}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as Bn,reprojectionMigrationId as Gn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{quoteIdentifier as qn}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Kn}from"./packem_shared/runShardMigrations-DFc_LoP-.mjs";import{stableStringify as Wn}from"./packem_shared/stableStringify-G9OF5wcs.mjs";import{stableWireKey as Xn}from"./packem_shared/stableWireKey-DSCJB6E7.mjs";export{Do as ADMIN_FUNCTIONS,yo as ADMIN_FUNCTION_PREFIX,c as AGGREGATE_SQL_FUNCTION,Er as AGG_COUNT,Cr as AGG_KEY,Rr as AGG_VALUE,P as AUDIT_LOG_TABLE,H as CDC_LOG_TABLE,X as CDC_LOG_TABLE_SEQ_INDEX,z as CDC_META_TABLE,de as CLIENT_WATERMARK_TABLE,Te as COMMIT_SEQ_FIELD,he as COMMIT_SEQ_TABLE,Rn as ConflictError,A as CountRlsUnsupportedError,sr as DATA_MIGRATION_STATE_TABLE,No as DEFAULT_FANOUT_TOPIC_LIMIT,ja as DEFAULT_MAX_RELATION_KEYS,ft as DEFAULT_MAX_RELAYS,mt as DEFAULT_PROMOTION_THRESHOLDS,gn as DEFAULT_TRANSACTION_LIMITS,Ar as DOC_COLUMN,jr as DurableStreamRunner,Oo as FLAGS_FUNCTION_PREFIX,Co as GEO_DEFAULT_PRECISION,Ie as GLOBAL_SHAPE_SNAPSHOT_TABLE,Mo as GlobalPollTick,Ne as IDEMPOTENCY_TABLE,Yo as MAIL_RETENTION,Jo as MAIL_TABLE,Yr as MAX_DURABLE_STREAM_BYTES,Jr as MAX_DURABLE_STREAM_CHUNKS,Fo as MAX_PAGE_SIZE,tn as MAX_SQL_ROWS,aa as NotFoundError,F as NotUniqueError,xt as OwnerRelay,xa as QUEUE_TABLE,ga as RANK_TIEBREAK,Fa as REACTOR_STATE_TABLE,Fn as RELATION_EXISTS_KEY,ko as RELATION_FUNCTION_PREFIX,Bn as REPROJECTION_MIGRATION_PREFIX,Pt as RLS_UNWRAP_SYMBOL,ya as ReactiveCache,Tt as RelayMember,Dt as RlsRequiredError,pr as SCAN_DEP,Ot as SCHEMA_HISTORY_MAX_VERSIONS,Xe as SEARCH_STATE_TABLE,Ye as SHAPE_POKE_CURSOR_TABLE,Xt as ShapeDiffCache,en as ShardRunner,_n as TransactionHeadroomTracker,Ka as UNVOUCHABLE_DEP,Se as advanceClientWatermark,gr as aggUpsertSql,p as aggregateSqlFunction,x as aggregateTableName,Ee as allocateCommitSeq,D as appendAuditEntry,V as appendCdcChange,wr as appendStreamChunk,Q as applyCdcChanges,ot as applyOnDelete,ia as applySelect,na as armRestore,Ya as assertFlatPredicate,nn as assertReadonly,Ja as assertShapeShardable,k as assertValidClientId,cn as awaitWsDrain,q as backfillAggregateIndexes,w as backfillRankIndexes,K as backfillSearchIndexes,v as backfillSearchIndexesForTable,Ro as boundingBoxCenter,Ao as boundingBoxGeohashes,Xa as buildIndexRange,jt as buildPokeFrames,_t as buildReprojectionMigration,ma as buildSeekBeforeWhere,ca as buildSeekWhere,wt as buildSettings,Wt as buildShapeDiff,j as bumpCdcEpoch,Y as cdcCanVouchFor,J as cdcSeqLeavingRows,Z as cdcTouchesTables,$ as cdcTrimmedError,Kr as claimStreamRun,ct as clampPromotionThresholds,Zo as clearCapturedMail,Ue as clearMemoryTables,Ta as clearQueueMessages,T as coerceAggregateNumber,ee as compactCdcDocs,yn as compileWhereSql,ve as computeRankPage,Za as containsRelationPredicate,It as countLegacyRows,go as coveringGeohashes,ge as createCompanionSync,dr as createDependencyTracker,Bo as createFanoutCounters,Go as createGlobalPollCounters,_r as createIndexSql,va as createReadFootprint,ht as createRelayLink,Ct as createReplicaLink,zt as createShapeDiffCache,Uo as createShapeProbeCounters,B as createShardCtxDb,En as createSystemReader,re as cursorBelowRetainedFloor,Zr as decideDurableAttach,pa as decodeCursor,be as deleteGlobalShapeSnapshot,Le as deleteGlobalShapeSnapshotsForConnection,Je as deleteShapePokeCursor,Ze as deleteShapePokeCursorsForConnection,vr as deleteStreamRun,Sr as depKey,ao as diffExternalSource,Yt as diffGlobalMembership,at as distinctValues,h as encodeAggregateKey,da as encodeCursor,_o as encodeGeohash,_a as encodePartitionKey,Jt as encodeRowsPatch,y as ensureAuditTable,$o as ensureMailTable,eo as envOptionalPositiveInt,ro as envPositiveInt,o as exportShardRows,a as exportShardTable,qo as facetColumn,tt as fanOutScalarCounts,wo as findStorageReferences,Wr as finishStreamRun,E as foldAggregateTally,Rt as gateReplicaDispatch,Ir as geoTableName,Vt as globalShapeReadKey,yt as guardWriter,At as handleReplicaControl,bn as hasTrigger,Io as haversineMeters,We as hydrateDocsById,t as importShardRows,za as indexKeysForRow,Kt as isDevEnvironment,br as isFtsAvailable,ha as isLossyBody,qe as isMemoryTable,$a as isRelationPredicate,fo as isSoftDeleted,xo as isSourceDue,Lr as jsonPath,Mr as jsonPathSql,Va as keysTouchRanges,no as liftSourceId,ln as lintReadonlySql,ka as listReactorStates,Ko as listTables,Nn as literalInList,Wa as markUnvouchableReads,Ia as matchesRankStaticWhere,d as matchesStaticWhere,mo as materializeExternalRows,co as materializeExternalRowsIncremental,we as memoryTableNames,fn as mergeChangedKeys,g as mergeWhere,oe as migrateCdcLog,ae as migrateCdcMeta,ue as migrateClientWatermark,Ce as migrateCommitSeq,Hr as migrateDurableStreams,Me as migrateGlobalShapeSnapshot,Oe as migrateIdempotency,Ba as migrateReactorState,ze as migrateSearchState,$e as migrateShapePokeCursor,te as minCdcReplayableSeq,ne as minCdcSeq,er as minShapePokeCursor,pt as nextPromotionState,S as normalizeCountArgument,G as normalizeIdStructurally,Sa as normalizeOrderKeys,lo as normalizeSourceDocument,so as normalizeSourceValue,kr as param,n as parseExportShardArgs,l as parseImportShardArgs,_ as planAggregateLookup,bo as pointInBoundingBox,Zt as projectColumns,To as pullExternalSourceIncrementalTick,ho as pullExternalSourceTick,Pr as qualifiedJsonPath,Dr as qualifiedJsonPathSql,qn as quoteIdentifier,ba as rankKeyFromDoc,La as rankTableName,Na as reactiveCacheKey,Ga as reactorNeedsRun,C as readAggregateValue,N as readAuditLog,la as readBookmark,ea as readCapturedMail,le as readCdcChangeKeys,se as readCdcChanges,ie as readCdcCursor,me as readCdcEpoch,fe as readClientWatermark,Re as readCommitSeq,po as readExternalSourceBaseline,Pe as readGlobalShapeSnapshot,Fe as readIdempotent,ir as readMigrationStatus,Ea as readQueueMessageById,Ca as readQueueMessages,Ua as readReactorState,Ft as readSchemaHistory,kt as readSchemaVersion,Ve as readSearchBackfillState,rr as readShapePokeCursor,Xr as readStreamChunks,zr as readStreamRun,vo as readTablePage,ra as recordCapturedMail,xn as recordChangedKeys,Wo as recordFanoutPass,Ho as recordGlobalPollPass,Ra as recordQueueMessages,Bt as recordSchemaVersion,Xo as recordShapeProbePass,nt as relationHooks,dt as relayCountFor,Br as renderSql,bt as reprojectableFields,Gn as reprojectionMigrationId,Lt as reprojectionTables,Ma as resolveRankPartition,et as resolveRelationPredicates,lt as resolveWith,yr as rowToDocument,mr as runDataMigration,xr as runDrizzle,So as runExternalSourceTick,sn as runReadonlySql,st as runRowValidators,Kn as runShardMigrations,on as runSocketPool,Tr as runSql,Ln as runTriggers,Pn as selectExpiredIds,s as selectExportTables,I as selectIndexForAggregate,b as selectIndexForCount,L as selectIndexForGroupBy,zo as selectMatchingIds,tr as selectShapeMembers,nr as selectShapeRows,Ut as serializeSqlValue,St as shapeRoutingKey,ua as softDeleteScope,Pa as sortColumnName,Gr as sqliteInList,Wn as stableStringify,Xn as stableWireKey,pn as subscriptionFrames,dn as subscriptionListDeltas,Vo as summarizeFanoutTopics,Qo as summarizeSubscriptions,Nr as tableColumns,ur as tableFromDepKey,u as throwingScheduler,ce as trimCdcChanges,ke as trimIdempotent,Vr as trimStreamRuns,Or as tryRowToDocument,Sn as trySendFrame,Ur as unionAll,i as validateImportRow,De as writeGlobalShapeSnapshot,Be as writeIdempotent,qa as writeReactorState,Qe as writeSearchBackfillState,or as writeShapePokeCursor,Tn as writeTouchesMemo};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as v}from"@lunora/errors";import{m as $,n as y}from"./do-sql-DbEszTyj.mjs";import{quoteIdentifier as d}from"./quoteIdentifier-CObIFRhb.mjs";import{d as L}from"./wire-codec-BU9T2xJ7.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",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,g=500,U=30,W=200,m="__doc__",O=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},j=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(m))return{columns:e,rows:t};const r=[];for(const s of t){const a=s[m],i=typeof a=="string"?O(a):void 0;if(i===void 0)return{columns:e,rows:t};const c=Object.fromEntries(Object.entries(s).filter(([u])=>u!==m));r.push({...c,...j(i)})}const n=e.filter(s=>s!==m),o=[],_=new Set(n);for(const s of r)for(const a of Object.keys(s))_.has(a)||(_.add(a),o.push(a));return{columns:[...n,...o],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_"),E=(e,t,r)=>Math.min(Math.max(e,t),r),x=(e,t)=>{const r=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(r.c)},oe=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:x(e,d(n))});return r},P=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,C=(e,t)=>{if(I(t)||!P(e,t))throw new v("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},S=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(r=>r.name),q={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},G=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",M=(e,t)=>{const r=t.includes(e),n=t.includes(m);if(!(!r&&!n))return r?{expression:d(e),params:[]}:{expression:`json_extract(${d(m)}, ?)`,params:[`$.${$(e)}`]}},H=(e,t)=>{const r=M(e.column,t);if(r===void 0)return;const{expression:n,params:o}=r;return e.operator==="contains"?{params:[...o,G(e.value)],sql:F(n)}:{params:[...o,e.value],sql:`${n} ${q[e.operator]} ?`}},B=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,X=e=>{const t=B.exec(e.trim());if(t===null)return;const r=Number(t[1]),n=t[2]===void 0?void 0:Number(t[2]),o=t[3]===void 0?void 0:Number(t[3]);if(n!==void 0&&(n<1||n>12)||o!==void 0&&(o<1||o>31)||r<100)return;const _=Date.UTC(r,(n??1)-1,o??1);if(o!==void 0&&new Date(_).getUTCDate()!==o)return;let s;return o!==void 0?s=Date.UTC(r,(n??1)-1,o+1):n===void 0?s=Date.UTC(r+1,0,1):s=Date.UTC(r,n,1),{from:_,to:s}},A=(e,t,r)=>{const n=[],o=[];if(t!==""&&e.length>0){const _=e.map(a=>F(d(a)));o.push(...e.map(()=>t));const s=X(t);if(s!==void 0)for(const a of e)_.push(`(${d(a)} >= ? AND ${d(a)} < ?)`),o.push(s.from,s.to);n.push(`(${_.join(" OR ")})`)}for(const _ of r??[]){const s=H(_,e);s!==void 0&&(n.push(`(${s.sql})`),o.push(...s.params))}return n.length===0?void 0:{parameters:o,where:n.join(" AND ")}},K=(e,t)=>{if(e===void 0)return;const r=M(e.column,t);if(r===void 0)return;const n=e.direction==="desc"?"DESC":"ASC";return{params:r.params,sql:`${r.expression} ${n}`}},ae=(e,t)=>{const{table:r}=t;C(e,r);const n=E(Math.trunc(t.limit??D),1,g),o=Math.max(0,Math.trunc(t.offset??0)),_=d(r),s=S(e,_),a=t.search?.trim()??"",i=b=>{if(t.refs===void 0)return b;const T={};for(const k of b.columns){const w=t.refs[k];w!==void 0&&(T[k]=w)}return Object.keys(T).length>0?{...b,refs:T}:b},c=A(s,a,t.filters),u=K(t.orderBy,s),l=c===void 0?"":` WHERE ${c.where}`,f=u===void 0?"":` ORDER BY ${u.sql}`,p=c?.parameters??[],h=u?.params??[];let R;t.skipCount||(R=c===void 0?x(e,_):Number(e.exec(`SELECT COUNT(*) AS c FROM ${_}${l}`,...p).one().c));const N=e.exec(`SELECT * FROM ${_}${l}${f} LIMIT ? OFFSET ?`,...p,...h,n,o).toArray();return i({...Q(s,N),total:R})},_e=(e,t)=>{const{table:r}=t;C(e,r);const n=E(Math.trunc(t.limit??g),1,g),o=d(r),_=S(e,o),s=t.search?.trim()??"",a=A(_,s,t.filters),i=a===void 0?e.exec(`SELECT id FROM ${o} LIMIT ?`,n+1).toArray():e.exec(`SELECT id FROM ${o} WHERE ${a.where} LIMIT ?`,...a.parameters,n+1).toArray(),c=i.length>n,u=i.slice(0,n).map(l=>l.id);return{hasMore:c,ids:u}},Y=(e,t,r)=>{const n=new Set(r.filter(_=>_!==m));if(!r.includes(m))return n;const o=e.exec(`SELECT ${d(m)} AS doc FROM ${t} LIMIT ?`,g).toArray();for(const{doc:_}of o){const s=typeof _=="string"?O(_):void 0;if(s!==void 0)for(const a of Object.keys(s))n.add(a)}return n},ie=(e,t)=>{const{column:r,table:n}=t;C(e,n);const o=d(n),_=S(e,o);if(!Y(e,o,_).has(r))throw new v("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const s=M(r,_);if(s===void 0)throw new v("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const a=E(Math.trunc(t.limit??U),1,W),i=t.search?.trim()??"",c=A(_,i,t.filters),u=c===void 0?"":` WHERE ${c.where}`,l=c?.parameters??[],f=e.exec(`SELECT ${s.expression} AS value, COUNT(*) AS count FROM ${o}${u} GROUP BY ${s.expression} ORDER BY count DESC LIMIT ?`,...s.params,...l,...s.params,a+1).toArray();return{truncated:f.length>a,values:f.slice(0,a).map(h=>({count:Number(h.count),value:h.value}))}},ce=(e,t,r)=>{const n={},o=r.slice(0,g);for(const s of o)n[s]=[];if(o.length===0)return{references:n,storageColumns:t};const _=o.map(()=>"?").join(", ");for(const[s,a]of Object.entries(t)){if(I(s)||!P(e,s))continue;const i=d(s),c=S(e,i);for(const u of a){const l=M(u,c);if(l===void 0)continue;const f=e.exec(`SELECT id, ${l.expression} AS ref FROM ${i} WHERE ${l.expression} IN (${_})`,...l.params,...l.params,...o).toArray();for(const p of f)n[p.ref]?.push({column:u,id:p.id,table:s})}}return{references:n,storageColumns:t}},ue=e=>{const t=e.map((n,o)=>{const _=Object.values(n.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:n.admin===!0,id:o,subscriptions:_}}),r=t.reduce((n,o)=>n+o.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 a of Object.values(s.shapes??{})){const i=a.name??"(unknown shape)";r.set(i,(r.get(i)??0)+1)}for(const a of s.whispers??[])n.set(a,(n.get(a)??0)+1)}const o=[...[...r].map(([s,a])=>({kind:"shape",subscribers:a,topic:s})),...[...n].map(([s,a])=>({kind:"whisper",subscribers:a,topic:s}))];return o.sort((s,a)=>a.subscribers-s.subscribers||s.topic.localeCompare(a.topic)),{peakSubscribers:o[0]?.subscribers??0,topics:o.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,g 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,oe as listTables,ae as readTablePage,ge as recordFanoutPass,fe as recordGlobalPollPass,pe as recordShapeProbePass,_e as selectMatchingIds,he as summarizeFanoutTopics,ue as summarizeSubscriptions};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as u}from"@lunora/errors";const f=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),c=()=>{throw new u("INTERNAL","ctx.scheduler: no scheduler configured for triggers. Pass `scheduler` to the ctx-db factory.")},h=(e,r)=>{for(const[n,t]of Object.entries(r)){const o=e[n];if(t!==null&&typeof t=="object"&&!Array.isArray(t)){const s=Object.keys(t);if(s.length===1&&s[0]==="eq"){if(o!==t.eq)return!1;continue}return!1}if(o!==t)return!1}return!0},l=e=>{if(e===void 0)return{};if(typeof e!="object"||Array.isArray(e))return{where:e};const r=Object.keys(e);return r.length===0?{}:r.every(n=>f.has(n))?e:{where:e}},i={avg:"AVG",count:"COUNT",max:"MAX",min:"MIN",sum:"SUM"},y=e=>{const r=i[e];if(r===void 0)throw new u("INTERNAL",`unknown aggregate op "${e}": expected one of ${Object.keys(i).join(", ")}`);return r},A={runAfter:c,runAt:c};export{i as AGGREGATE_SQL_FUNCTION,y as aggregateSqlFunction,h as matchesStaticWhere,l as normalizeCountArgument,A as throwingScheduler};
|
|
@@ -0,0 +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-DbEszTyj.mjs";import{quoteIdentifier as b}from"./quoteIdentifier-CObIFRhb.mjs";import"./wire-codec-BU9T2xJ7.mjs";import"./runDrizzle-it6rL9bR.mjs";import"./sql-projection-BqmxFxQU.mjs";import{serializeSqlValue as x}from"./serializeSqlValue-DbI1VQYM.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,8 @@
|
|
|
1
|
+
import{runSql as T}from"./runDrizzle-it6rL9bR.mjs";const i="__lunora_audit__",a=1e3,s=E=>{T(E,`CREATE TABLE IF NOT EXISTS "${i}" (
|
|
2
|
+
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
3
|
+
ts REAL NOT NULL,
|
|
4
|
+
op TEXT NOT NULL,
|
|
5
|
+
"table" TEXT,
|
|
6
|
+
id TEXT,
|
|
7
|
+
detail TEXT
|
|
8
|
+
)`)},R=(E,t)=>{s(E),T(E,`INSERT INTO "${i}" (ts, op, "table", id, detail) VALUES (?, ?, ?, ?, ?)`,t.ts,t.op,t.table??null,t.id??null,t.detail===void 0?null:JSON.stringify(t.detail)),T(E,`DELETE FROM "${i}" WHERE seq <= (SELECT MAX(seq) - ? FROM "${i}")`,a)},o=(E,t={})=>{s(E);const d=t.sinceSeq??0,n=Math.max(1,Math.min(t.limit??a,1e4));return T(E,`SELECT seq, ts, op, "table", id, detail FROM "${i}" WHERE seq > ? ORDER BY seq DESC LIMIT ?`,d,n).toArray().map(e=>{const l={op:e.op,seq:e.seq,ts:e.ts};return e.table!==null&&(l.table=e.table),e.id!==null&&(l.id=e.id),e.detail!==null&&(l.detail=JSON.parse(e.detail)),l})};export{i as AUDIT_LOG_TABLE,R as appendAuditEntry,s as ensureAuditTable,o as readAuditLog};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import{LunoraError as u}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{runDrizzle as n}from"./runDrizzle-it6rL9bR.mjs";import{k as m,l as A}from"./do-sql-DbEszTyj.mjs";import{ConflictError as p}from"./ConflictError-C8GtJmjS.mjs";const c="__cdc_log",q="__cdc_log_table_seq",_=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(q)} ON ${t.identifier(c)} (${t.identifier("table")}, seq)`)}catch{}},w=(e,o,r,i,s,d)=>{const E=d===void 0?null:m(d);n(e,t`INSERT INTO ${t.identifier(c)} (ts, ${t.identifier("table")}, id, op, doc) VALUES (${o}, ${r}, ${i}, ${s}, ${E})`)},C=90,S=e=>!e||e.size===0?t``:t` AND ${t.identifier("table")} IN (${t.join([...e].map(o=>t`${o}`),t`, `)})`,F=(e,o={})=>{const r=o.sinceSeq??0,i=Math.max(1,Math.min(o.limit??1e3,1e4)),s=S(o.tables),E=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(a=>{const f={id:a.id,op:a.op,seq:a.seq,table:a.table,ts:a.ts};return a.doc===null?f:{...f,doc:A(a.doc)}});return{changes:E,cursor:E.at(-1)?.seq??r}},b=(e,o,r)=>{if(r.size===0)return!1;const i=[...r];for(let s=0;s<i.length;s+=C){const d=new Set(i.slice(s,s+C));if(n(e,t`SELECT 1 AS hit FROM ${t.identifier(c)} WHERE seq > ${o}${S(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)),y=(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},g=(e,o,r,i)=>n(e,t`SELECT id, op, MAX(seq) AS maxSeq 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=>({id:d.id,op:d.op,seq:d.maxSeq})),U=(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
|
+
)`)},X=(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
|
+
)`)},B=(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},H=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},v=(e,o)=>e!==void 0&&e>o+1,x=(e,o,r)=>new u("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,W=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)`)},Y=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},G=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},I=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 p))throw i;const s={...r};delete s._id,await e.replace(o.id,s,void 0,{allowExplicitId:!0})}},K=async(e,o)=>{for(const r of o)await I(e,r)};export{c as CDC_LOG_TABLE,q as CDC_LOG_TABLE_SEQ_INDEX,T as CDC_META_TABLE,w as appendCdcChange,K as applyCdcChanges,G as bumpCdcEpoch,y as cdcCanVouchFor,B as cdcSeqLeavingRows,b as cdcTouchesTables,x as cdcTrimmedError,X as compactCdcDocs,v as cursorBelowRetainedFloor,_ as migrateCdcLog,L as migrateCdcMeta,W as minCdcReplayableSeq,$ as minCdcSeq,g as readCdcChangeKeys,F as readCdcChanges,H as readCdcCursor,Y as readCdcEpoch,U as trimCdcChanges};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{sql as t}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-it6rL9bR.mjs";const r="__client_watermark",o=i=>{a(i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(r)} (
|
|
2
|
+
identity TEXT NOT NULL,
|
|
3
|
+
client_id TEXT NOT NULL,
|
|
4
|
+
last_mutation_id INTEGER NOT NULL,
|
|
5
|
+
PRIMARY KEY (identity, client_id)
|
|
6
|
+
)`)},E=(i,e,n)=>a(i,t`SELECT last_mutation_id FROM ${t.identifier(r)} WHERE identity = ${e} AND client_id = ${n} LIMIT 1`).toArray()[0]?.last_mutation_id??0,l=(i,e,n,d)=>{a(i,t`INSERT INTO ${t.identifier(r)} (identity, client_id, last_mutation_id) VALUES (${e}, ${n}, ${d})
|
|
7
|
+
ON CONFLICT(identity, client_id) DO UPDATE SET last_mutation_id = MAX(last_mutation_id, excluded.last_mutation_id)`)};export{r as CLIENT_WATERMARK_TABLE,l as advanceClientWatermark,o as migrateClientWatermark,E as readClientWatermark};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as E}from"./runDrizzle-it6rL9bR.mjs";const t="__commit_seq",n="_commitSeq",S=i=>{E(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (
|
|
2
|
+
id INTEGER PRIMARY KEY CHECK (id = 0),
|
|
3
|
+
value INTEGER NOT NULL
|
|
4
|
+
)`),E(i,e`INSERT OR IGNORE INTO ${e.identifier(t)} (id, value) VALUES (0, 0)`)},r=i=>{const[o]=E(i,e`SELECT value FROM ${e.identifier(t)} WHERE id = 0`);return typeof o?.value=="number"?o.value:0},a=i=>(E(i,e`UPDATE ${e.identifier(t)} SET value = value + 1 WHERE id = 0`),r(i));export{n as COMMIT_SEQ_FIELD,t as COMMIT_SEQ_TABLE,a as allocateCommitSeq,S as migrateCommitSeq,r as readCommitSeq};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as p}from"@lunora/errors";class R extends p{constructor(n){super("COUNT_RLS_UNSUPPORTED",n===void 0?"count() is not supported in an RLS-restricted context":`count() is not supported on table "${n}" inside an RLS-restricted context`)}}const S=(e,n)=>e?n?{AND:[e,n]}:e:n,v=new Set(["AND","NOT","OR"]),d=Symbol("not-eq"),O=e=>{if(e!==null&&typeof e=="object"&&!Array.isArray(e)){const n=Object.keys(e);return n.length===1&&n[0]==="eq"?e.eq:d}return e},f=(e,n)=>{const i={};for(const[t,o]of Object.entries(e)){if(v.has(t)||!n(t))return;const r=O(o);if(r===d)return;i[t]=r}return i},l=(e,n,i)=>{const t={...n};if(!e)return t;for(const[o,r]of Object.entries(e))if(o in t){if(t[o]!==r)return}else if(o in i){if(i[o]!==r)return}else t[o]=r;return t},b=(e,n)=>{const i=e.by??[],t=n??{},o=f(t,r=>i.includes(r));if(o!==void 0){for(const r of i)if(!(r in o))return;return l(e.where,o,t)}},x=(e,n,i)=>{const t=f(n??{},o=>i.has(o));if(t!==void 0)return l(e.where,t,{})},y=(e,n,i,t)=>{let o;for(const r of e){if(r.op!==n||n!=="count"&&r.field!==i)continue;const s=b(r,t);s&&(!o||(r.by?.length??0)>(o.index.by?.length??0))&&(o={index:r,key:s})}return o},h=(e,n)=>y(e,"count",void 0,n),A=(e,n,i,t)=>y(e,n,i,t),N=(e,n,i,t,o)=>{const r=new Set(t);for(const s of e){if(s.op!==n||n!=="count"&&s.field!==i)continue;const c=s.by??[];if(c.length!==r.size||!c.every(a=>r.has(a)))continue;const u=x(s,o,r);if(u!==void 0)return{index:s,partial:u}}};export{R as CountRlsUnsupportedError,S as mergeWhere,b as planAggregateLookup,A as selectIndexForAggregate,h as selectIndexForCount,N as selectIndexForGroupBy};
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import{LunoraError as b}from"@lunora/errors";import{runSql as c}from"./runDrizzle-it6rL9bR.mjs";const n="__lunora_migrations",x=100,D=3e4,y=1e4,M=e=>{c(e,`CREATE TABLE IF NOT EXISTS "${n}" (
|
|
2
|
+
id TEXT PRIMARY KEY,
|
|
3
|
+
direction TEXT NOT NULL,
|
|
4
|
+
status TEXT NOT NULL,
|
|
5
|
+
cursor TEXT,
|
|
6
|
+
processed INTEGER NOT NULL DEFAULT 0,
|
|
7
|
+
changed INTEGER NOT NULL DEFAULT 0,
|
|
8
|
+
started_at REAL,
|
|
9
|
+
updated_at REAL,
|
|
10
|
+
error TEXT
|
|
11
|
+
)`)},N=e=>({changed:e.changed,cursor:typeof e.cursor=="string"?e.cursor:null,direction:e.direction==="down"?"down":"up",processed:e.processed,status:e.status==="completed"||e.status==="failed"?e.status:"in_progress"}),h=(e,t)=>{const r=c(e,`SELECT * FROM "${n}" WHERE id = ?`,t).toArray()[0];if(r)return{...N(r),startedAt:typeof r.started_at=="number"?r.started_at:void 0}},C=(e,t)=>{c(e,`DELETE FROM "${n}" WHERE id = ?`,t)},S=(e,t)=>{c(e,`INSERT INTO "${n}"
|
|
12
|
+
(id, direction, status, cursor, processed, changed, started_at, updated_at, error)
|
|
13
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
14
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
15
|
+
direction = excluded.direction,
|
|
16
|
+
status = excluded.status,
|
|
17
|
+
cursor = excluded.cursor,
|
|
18
|
+
processed = excluded.processed,
|
|
19
|
+
changed = excluded.changed,
|
|
20
|
+
updated_at = excluded.updated_at,
|
|
21
|
+
error = excluded.error`,t.id,t.direction,t.status,t.cursor,t.processed,t.changed,t.startedAt,t.updatedAt,t.error)},U=(e,t,s,r)=>(c(e,`INSERT INTO "${n}"
|
|
22
|
+
(id, direction, status, cursor, processed, changed, started_at, updated_at, error)
|
|
23
|
+
VALUES (?, ?, 'in_progress', NULL, 0, 0, ?, ?, NULL)
|
|
24
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
25
|
+
status = 'in_progress',
|
|
26
|
+
updated_at = excluded.updated_at
|
|
27
|
+
WHERE
|
|
28
|
+
"${n}".direction <> excluded.direction
|
|
29
|
+
OR "${n}".status <> 'in_progress'
|
|
30
|
+
OR "${n}".updated_at IS NULL
|
|
31
|
+
OR "${n}".updated_at <= excluded.updated_at - ${String(D)}`,t,s,r,r),c(e,"SELECT changes() AS changed").one().changed>0),$=(e,t,s)=>{c(e,`UPDATE "${n}" SET updated_at = ? WHERE id = ? AND status = 'in_progress'`,s,t)},F=(e,t)=>{c(e,`UPDATE "${n}" SET updated_at = 0 WHERE id = ? AND status = 'in_progress'`,t)},B=(e,t)=>{if(c(e,"SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",n).toArray().length===0)return[];const r=t===void 0?" ORDER BY id":" WHERE id = ?",i=t===void 0?[]:[t];return c(e,`SELECT * FROM "${n}"${r}`,...i).toArray().map(a=>({...N(a),error:typeof a.error=="string"?a.error:null,id:a.id,startedAt:typeof a.started_at=="number"?a.started_at:null,updatedAt:typeof a.updated_at=="number"?a.updated_at:null}))},w=async e=>{const{migration:t,sql:s,writer:r}=e,i=e.direction??"up",o=e.dryRun??!1,a=e.clock??(()=>Date.now()),R=e.maxBatches??Number.POSITIVE_INFINITY,I=e.batchSize??t.batchSize??x,L=i==="up"?t.up:t.down;if(!L)throw new b("INTERNAL",`data migration "${t.id}" has no \`${i}\` transform`);const O={db:{count:r.count.bind(r),findFirst:r.findFirst.bind(r),findMany:r.findMany.bind(r),get:r.get.bind(r)}};let T=null,_=0,g=0,A=a();if(!o){M(s);const d=h(s,t.id);if(d?.direction===i&&d.status==="completed")return{changed:d.changed,cursor:null,direction:i,dryRun:o,id:t.id,processed:d.processed,status:"completed"};if(d&&d.direction!==i&&C(s,t.id),!U(s,t.id,i,a())){const E=h(s,t.id);return{changed:E?.changed??0,cursor:E?.cursor??T,direction:i,dryRun:o,id:t.id,processed:E?.processed??0,status:E?.status??"in_progress"}}const l=d?.direction===i?d:void 0;l&&(T=l.cursor,_=l.processed,g=l.changed,A=l.startedAt??A)}let p=!1,m=0,f=A;try{for(;!p&&m<R;){const d=await r.findMany(t.table,{cursor:T,limit:I});for(const u of d.page){_+=1;const l=await L(u,O);if(l!==void 0&&(g+=1,o||await r.replace(String(u._id),{...l,_creationTime:u._creationTime,_id:u._id},void 0,{allowExplicitId:!0})),!o){const E=a();E-f>=y&&($(s,t.id,E),f=E)}}if(T=d.continueCursor,p=d.isDone,m+=1,!o){const u=a();S(s,{changed:g,cursor:p?null:T,direction:i,error:null,id:t.id,processed:_,startedAt:A,status:p?"completed":"in_progress",updatedAt:u}),f=u;try{await e.onBatch?.({batches:m,changed:g,processed:_})}catch{}}}}catch(d){throw o||S(s,{changed:g,cursor:T,direction:i,error:d instanceof Error?d.message:String(d),id:t.id,processed:_,startedAt:A,status:"failed",updatedAt:a()}),d}if(!o&&!p)try{F(s,t.id)}catch(d){console.warn(`data migration "${t.id}": releaseClaim failed`,d)}return{changed:g,cursor:p?null:T,direction:i,dryRun:o,id:t.id,processed:_,status:p?"completed":"in_progress"}};export{n as DATA_MIGRATION_STATE_TABLE,B as readMigrationStatus,w as runDataMigration};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as h}from"@lunora/errors";import{distinctValues as w}from"./applyOnDelete-BlcwKjuO.mjs";import{RELATION_EXISTS_KEY as N}from"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";const g={every:{kind:"many",negateChild:!0,negated:!0},is:{kind:"one",negated:!1},isNot:{kind:"one",negated:!0,nullDisjunct:!0},none:{kind:"many",negated:!0},some:{kind:"many",negated:!1}},T=new Set(Object.keys(g)),p=e=>{const t=g[e];if(!t)throw new h("INTERNAL",`unknown relation operator "${e}"`);return t},j=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},S=5e3,l=Symbol("relation-key-overflow"),b=e=>Array.isArray(e)?e.map(t=>t??{}):[],R=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},y=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(n=>T.has(n))},u=(e,t,n)=>{const r=t.tables[n]?.relationMap??{};return Object.keys(e).some(s=>{const a=e[s];return s==="AND"||s==="OR"?b(a).some(o=>u(o,t,n)):s==="NOT"?u(a??{},t,n):!!r[s]&&y(a)})},K=(e,t,n,r)=>{if(e&&u(e,t,n))throw new h("INTERNAL",`relation-crossing predicates are not supported in ${r}() — use them in findMany/findFirst or an RLS read policy`)},P=async(e,t,n,r,s)=>{const a=await d(t,e.table,r),{page:o}=await r.fetcher(e.table,{baseWhere:r.relationBaseWhere?.(e.table),relationBaseWhere:r.relationBaseWhere,where:a}),i=w(o,n);if(i.length>r.maxRelationKeys){if(s)return l;throw new h("INTERNAL",`relation predicate on "${e.table}" matched ${String(i.length)} rows, exceeding the ${String(r.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)}return i},$=async(e,t,n,r,s)=>{const a=p(e),{clause:o,project:i}=j(t),c=await P(t,a.negateChild?{NOT:n}:n,i,r,s);return c===l?l:a.negated?a.nullDisjunct?{OR:[{[o]:{notIn:c}},{[o]:{isNull:!0}}]}:{[o]:{notIn:c}}:{[o]:{in:c}}},m=async(e,t,n,r,s)=>{const a=p(e),o=s.relationBaseWhere?.(t.table),i=a.negateChild?{NOT:n}:n,A={childWhere:await d(o?{AND:[o,i]}:i,t.table,s),negated:a.negated,parentTable:r,relation:t};return{[N]:A}},k=(e,t,n)=>{const r=g[e];if(r&&r.kind!==n.kind)throw new h("INTERNAL",`relation operator "${e}" requires a to-${r.kind} relation, but "${t}" is to-${n.kind}`)},I=async(e,t,n,r,s)=>{const a=[];for(const o of Object.keys(n)){k(o,e,t);const i=n[o]??{},c=s.canPushExists?.(t)??!1;if(c&&s.existsPushMode==="always"){a.push(await m(o,t,i,r,s));continue}const f=await $(o,t,i,s,c);f===l?a.push(await m(o,t,i,r,s)):a.push(f)}return R(a)},L=async(e,t,n,r)=>{if(e==="AND"||e==="OR"){const a=[];for(const o of b(t))a.push(await d(o,n,r));return{[e]:a}}if(e==="NOT")return{NOT:await d(t??{},n,r)};const s=r.schema.tables[n]?.relationMap?.[e];return s&&y(t)?I(e,s,t,n,r):{[e]:t}},d=async(e,t,n)=>{const r=[];for(const s of Object.keys(e))r.push(await L(s,e[s],t,n));return R(r)},v=async(e,t)=>!e||!u(e,t.schema,t.tableName)?e:d(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??S,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),O=(e,t,n)=>{for(const r of e){const s=E(r,t,n);if(s)return s}},M=(e,t,n,r)=>{if(e==="AND"||e==="OR")return O(b(t),n,r);if(e==="NOT")return O([t??{}],n,r);const s=n.tables[r]?.relationMap?.[e];if(!(!s||!y(t)))return n.tables[s.table]?.shardMode?.kind==="shardBy"?{relation:e,target:s.table}:O(Object.values(t),n,s.table)},E=(e,t,n)=>{for(const r of Object.keys(e)){const s=M(r,e[r],t,n);if(s)return s}},B=(e,t,n)=>{if(!e)return;const r=E(e,t,n);if(r)throw Object.assign(new Error(`shape on "${n}" joins the sharded table "${r.target}" via relation "${r.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${n}", or (b) moving "${r.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{S as DEFAULT_MAX_RELATION_KEYS,K as assertFlatPredicate,B as assertShapeShardable,u as containsRelationPredicate,y as isRelationPredicate,v as resolveRelationPredicates};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{toErrorBody as P,LunoraError as M}from"@lunora/errors";import{e as x,d as I}from"./wire-codec-BU9T2xJ7.mjs";import{w as _,a as w,m as k,r as N,d as C,b as O}from"./ctx-db-relay-shapes-Jf5xpD1r.mjs";import{envPositiveInt as g}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{relayName as m,DEFAULT_PROMOTION_THRESHOLDS as E,nextPromotionState as D,shapeRoutingKey as R,parseRelayName as F,clampPromotionThresholds as U}from"./DEFAULT_PROMOTION_THRESHOLDS-H2sHFvlw.mjs";import{encodeRowsPatch as W,buildPokeFrames as T}from"./buildPokeFrames-BhYUbqzO.mjs";import{v as K,R as v,s as Y,a as B,b as H}from"./sibling-channel-Cxvk0Zca.mjs";import{awaitWsDrain as $,trySendFrame as A}from"./awaitWsDrain-CeaR5jj8.mjs";import{stableWireKey as f}from"./stableWireKey-DSCJB6E7.mjs";const j=2,z=8,b={},G=c=>{throw new M("INTERNAL",`unhandled relay frame: ${JSON.stringify(c)}`)},X=(c,e)=>c===void 0||c.epoch!==e.epoch?!1:c.cursor>=e.fromCursor&&c.cursor<e.checkpoint,J=c=>Response.json(c,{headers:{"content-type":"application/json"}}),S=()=>new Response(null,{status:204});class L{constructor(e,t){this.host=e,this.roleId=t}host;roleId;async handleControl(e){let t;try{t=await e.text()}catch{return new Response("bad request",{status:400})}if(!await K(this.host.env(),e.headers.get(v),t))return new Response("forbidden",{status:403});let s;try{s=JSON.parse(t)}catch{return new Response("bad request",{status:400})}switch(s.type){case"relay_attach":return this.onAttach(s.relayIndex),S();case"relay_detach":return this.onDetach(s.relayIndex),S();case"relay_frame":return this.host.deliverWhisperLocal(s.topic,s.frame,void 0),await this.onWhisperFrame(s),S();case"relay_shape_poke":{const r=this.host.getWebSockets().length,o=Date.now(),a=this.onShapePoke({...s,args:I(s.args)});return this.host.recordShapePokeFanout(r,a,Date.now()-o),S()}case"relay_shape_subscribe":return J(this.onShapeSubscribe({...s,args:I(s.args)}));default:return G(s)}}maxRelays(){return g(this.host.env(),"LUNORA_MAX_RELAYS",z)}canAddressSiblings(){return this.siblingStub(this.roleId.ownerKey)!==void 0}siblingStub(e){return Y(this.host.env(),this.bindingName(),e)}bindingName(){return this.host.shardBinding()}async postRelayMessage(e,t){await this.requestRelayMessage(e,t)}async requestRelayMessage(e,t){const s=this.siblingStub(e);if(s===void 0)return;const r=JSON.stringify(t),o={"content-type":"application/json","x-lunora-shard-binding":this.host.shardBinding()??""},a=B(this.host.env());a!==void 0&&(o[v]=await H(a,r));try{return await s.fetch("https://relay.internal/_lunora/relay",{body:r,headers:o,method:"POST"})}catch{return}}}class V extends L{shapeUniformCache=new Map;relaySetCache;registryCache;recordedBinding;promotionState="owned";constructor(e,t){super(e,{ownerKey:t})}async forwardWhisper(e,t){if(!this.canAddressSiblings())return;const s=this.ownerRelaySet();s.size!==0&&await Promise.all([...s].map(r=>this.postRelayMessage(m(this.roleId.ownerKey,r),{frame:t,topic:e,type:"relay_frame"})))}async onFlush(e,t){this.canAddressSiblings()&&await Promise.all([this.multicastShapePokes(e,t),this.proxyShapePokes(e,t)])}seedRelayShape(){return Promise.resolve(void 0)}announce(){return Promise.resolve()}announceDrain(){return Promise.resolve()}relayCount(){const e=this.host.getWebSockets().length,t=g(this.host.env(),"LUNORA_RELAY_THRESHOLD",E.tUp),s=g(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",E.tDown);if(this.promotionState=D(this.promotionState,e,U(t,s)),this.promotionState==="owned")return 0;const r=g(this.host.env(),"LUNORA_RELAY_FAN",j);return Math.min(this.maxRelays(),Math.max(1,r))}minShapeCursor(){const{cohort:e,proxies:t}=this.relayShapes();let s;for(const r of[...e.values(),...t.values()])s=s===void 0?r.cursor:Math.min(s,r.cursor);return s}isShapeRelayUniform(e,t){const s=R(e,t),r=this.shapeUniformCache.get(s);if(r!==void 0)return r;const o=this.probeShapeRelayUniform(e,t);return this.shapeUniformCache.set(s,o),o}onAttach(e){this.addRelayToSet(e)}onDetach(e){this.removeRelayFromSet(e)}async onWhisperFrame(e){await Promise.all([...this.ownerRelaySet()].filter(t=>t!==e.originRelay).map(t=>this.postRelayMessage(m(this.roleId.ownerKey,t),{frame:e.frame,topic:e.topic,type:"relay_frame"})))}onShapeSubscribe(e){return this.buildShapeSeedFrames(e)}onShapePoke(){return 0}buildShapePoke(e,t,s,r,o){let a;try{a=this.host.resolveShape(e.name,e.args,t)}catch{return}if(a===void 0||a.global===!0||!s.has(a.table))return;const n=e,l=n.cursor,i=this.host.buildShapeDiff(a,l,r);if(i.length!==0)return n.cursor=r,_(this.host.sql(),n.key,r),{args:x(e.args),checkpoint:r,epoch:o,fromCursor:l,name:e.name,rowsPatch:W(i),type:"relay_shape_poke"}}async multicastShapePokes(e,t){const s=this.ownerRelaySet();if(s.size===0)return;const{cohort:r}=this.relayShapes();if(r.size===0)return;const o=this.host.currentCdcEpoch(),a=[];for(const n of r.values()){const l=this.buildShapePoke(n,b,e,t,o);l&&a.push(this.multicastToRelays(s,l,n))}await Promise.all(a)}async multicastToRelays(e,t,s){(await Promise.all([...e].map(async o=>(await this.requestRelayMessage(m(this.roleId.ownerKey,o),t))?.ok===!0))).includes(!1)&&this.rewindShapeCursor(s,t.fromCursor)}async proxyShapePokes(e,t){if(this.ownerRelaySet().size===0)return;const{proxies:s}=this.relayShapes();if(s.size===0)return;const r=this.host.currentCdcEpoch(),o=[];for(const a of s.values()){const n=this.buildShapePoke(a,a.identity,e,t,r);n&&o.push(this.proxyToRelay(n,a))}await Promise.all(o)}async proxyToRelay(e,t){(await this.requestRelayMessage(m(this.roleId.ownerKey,t.relayIndex),{...e,targetConnectionId:t.connectionId}))?.ok!==!0&&this.rewindShapeCursor(t,e.fromCursor)}buildShapeSeedFrames(e){const t={identity:e.identity,userId:e.userId};let s;try{s=this.host.resolveShape(e.name,e.args,t)}catch(h){const{body:u}=P(h,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{error:{code:u.code,message:u.message}}}if(s===void 0||s.global===!0)return{error:{code:"SHAPE_NOT_FOUND",message:`shape not relayable: ${e.name}`}};e.relayIndex!==void 0&&this.addRelayToSet(e.relayIndex);const{baseCheckpoint:r,cursor:o,epoch:a,reset:n,rowsPatch:l}=this.host.computeOpLogShapeSeed({args:e.args,name:e.name,sinceEpoch:e.sinceEpoch,sinceSeq:e.sinceSeq},s);let i=o;const{cohort:d,proxies:p}=this.relayShapes();if(this.isShapeRelayUniform(e.name,e.args)){const h=R(e.name,e.args);let u=d.get(h);u===void 0&&(u={args:e.args,cursor:o,key:h,name:e.name},d.set(h,u),w(this.host.sql(),u)),i=u.cursor}else if(e.relayIndex!==void 0&&e.connectionId!==void 0){const h=`${String(e.relayIndex)}:${e.connectionId}:${e.subId}`,u={args:e.args,connectionId:e.connectionId,cursor:o,identity:t,key:h,name:e.name,relayIndex:e.relayIndex};p.set(h,u),w(this.host.sql(),u)}else return{error:{code:"RELAY_SHAPE_UNROUTABLE",message:`shape ${e.name} is per-socket on a relay, but the subscribe carries no ${e.relayIndex===void 0?"relay index":"connection id"}`}};const y=T([{reset:n,rowsPatch:l,shapeId:e.subId}],{baseCheckpoint:r,checkpoint:i,epoch:a,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:i,epoch:a,frames:y}}ensureRelayTables(){this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relays (idx INTEGER PRIMARY KEY)"),this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relay_binding (id INTEGER PRIMARY KEY, binding TEXT NOT NULL)"),k(this.host.sql())}bindingName(){const e=this.host.shardBinding();if(e!==void 0&&e!=="")return e!==this.recordedBinding&&(this.recordedBinding=e,this.ensureRelayTables(),this.host.sql().exec("INSERT INTO __lunora_relay_binding (id, binding) VALUES (1, ?) ON CONFLICT(id) DO UPDATE SET binding = excluded.binding",e)),e;if(this.recordedBinding!==void 0)return this.recordedBinding;try{const t=this.host.sql().exec("SELECT binding FROM __lunora_relay_binding WHERE id = 1").toArray();this.recordedBinding=t[0]?.binding}catch{this.recordedBinding=void 0}return this.recordedBinding}relayShapes(){const e=this.registryCache;if(e!==void 0)return e;this.ensureRelayTables();const t={cohort:new Map,proxies:new Map};for(const s of N(this.host.sql()))s.relayIndex===void 0||s.connectionId===void 0?t.cohort.set(s.key,{args:s.args,cursor:s.cursor,key:s.key,name:s.name}):t.proxies.set(s.key,{args:s.args,connectionId:s.connectionId,cursor:s.cursor,identity:s.identity??{},key:s.key,name:s.name,relayIndex:s.relayIndex});return this.registryCache=t,t}rewindShapeCursor(e,t){const s=e;s.cursor<=t||(s.cursor=t,_(this.host.sql(),s.key,t))}ownerRelaySet(){if(this.relaySetCache===void 0){this.ensureRelayTables();const e=this.host.sql().exec("SELECT idx FROM __lunora_relays").toArray();this.relaySetCache=new Set(e.map(t=>Number(t.idx)))}return this.relaySetCache}addRelayToSet(e){this.ensureRelayTables(),this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relays (idx) VALUES (?)",e),this.ownerRelaySet().add(e)}removeRelayFromSet(e){this.ensureRelayTables(),this.host.sql().exec("DELETE FROM __lunora_relays WHERE idx = ?",e);const t=this.ownerRelaySet();t.delete(e);const{cohort:s,proxies:r}=this.relayShapes();for(const[o,a]of r)a.relayIndex===e&&r.delete(o);C(this.host.sql(),e),t.size===0&&(s.clear(),this.shapeUniformCache.clear(),O(this.host.sql()))}probeShapeRelayUniform(e,t){let s;try{s=this.host.resolveShape(e,t,b)}catch{return!1}if(s===void 0||s.global===!0||this.host.rlsMetadata().policies.some(i=>i.on==="read"&&i.table===s.table)||this.tableHasAnyMask(s.table))return!1;const r=f(s.effectiveWhere),o=f(s.columns);let a=!1;const n=i=>{const d={groups:[`grp_${i}`],roles:[i],sub:`__lunora_probe_${i}__`};return{identity:new Proxy(d,{get:(y,h)=>typeof h=="symbol"||h in y?Reflect.get(y,h):`${i}:${h}`,getOwnPropertyDescriptor:(y,h)=>(a=!0,Reflect.getOwnPropertyDescriptor(y,h)),has:(y,h)=>typeof h=="symbol"?Reflect.has(y,h):!0,ownKeys:y=>(a=!0,Reflect.ownKeys(y))}),userId:`__lunora_probe_${i}__`}};return[b,n("a"),n("b")].every(i=>{let d;try{d=this.host.resolveShape(e,t,i)}catch{return!1}return d!==void 0&&d.global!==!0&&d.table===s.table&&f(d.effectiveWhere)===r&&f(d.columns)===o})&&!a}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(t=>t.table===e)}}class Q extends L{relayAnnounced=!1;shapeRelayMemos=new WeakMap;constructor(e,t,s){super(e,{ownerKey:t,relayIndex:s})}async forwardWhisper(e,t){this.canAddressSiblings()&&await this.postRelayMessage(this.roleId.ownerKey,{frame:t,originRelay:this.roleId.relayIndex,topic:e,type:"relay_frame"})}onFlush(){return Promise.resolve()}async seedRelayShape(e,t,s,r){if(!this.canAddressSiblings())return{code:"RELAY_MISCONFIGURED",message:"relay cannot address its owner"};await this.announce();const o={args:x(s.args??{}),connectionId:this.host.readAttachment(e).connectionId,identity:r.identity,name:s.name,relayIndex:this.roleId.relayIndex,sinceEpoch:s.sinceEpoch,sinceSeq:s.sinceSeq,subId:t,type:"relay_shape_subscribe",userId:r.userId},a=await this.requestRelayMessage(this.roleId.ownerKey,o);if(a===void 0)return{code:"RELAY_SEED_FAILED",message:"owner did not answer the shape seed"};let n;try{n=await a.json()}catch{return{code:"RELAY_SEED_FAILED",message:"malformed shape seed from owner"}}if(n.error!==void 0)return n.error;if(n.frames===void 0)return{code:"RELAY_SEED_FAILED",message:"owner returned no shape frames"};await $(e);for(const l of n.frames)A(e,l);return this.recordRelayShapeMemo(e,t,n.cursor??0,n.epoch),"ok"}async announce(){if(this.relayAnnounced||!this.canAddressSiblings())return;this.relayAnnounced=!0,(await this.requestRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_attach"}))?.ok||(this.relayAnnounced=!1)}async announceDrain(e){this.canAddressSiblings()&&(this.host.getWebSockets().some(t=>t!==e)||(this.relayAnnounced=!1,await this.postRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_detach"})))}relayCount(){return 0}isShapeRelayUniform(){return!1}minShapeCursor(){}onAttach(){}onDetach(){}onWhisperFrame(){return Promise.resolve()}onShapeSubscribe(){return{error:{code:"RELAY_CANNOT_SEED",message:"a relay has no op-log to seed from"}}}onShapePoke(e){return this.deliverShapePoke(e)}recordRelayShapeMemo(e,t,s,r){let o=this.shapeRelayMemos.get(e);o===void 0&&(o=new Map,this.shapeRelayMemos.set(e,o)),o.set(t,{cursor:s,epoch:r})}deliverShapePoke(e){const t=R(e.name,e.args);let s=0;for(const r of this.host.getWebSockets()){const o=this.host.readAttachment(r),{shapes:a}=o,n=this.shapeRelayMemos.get(r);if(!(a===void 0||n===void 0)&&!(e.targetConnectionId!==void 0&&o.connectionId!==e.targetConnectionId))for(const[l,i]of Object.entries(a)){const d=n.get(l);if(R(i.name,i.args)!==t||!X(d,e))continue;const p=T([{baseCheckpoint:d?.cursor,rowsPatch:e.rowsPatch,shapeId:l}],{baseCheckpoint:void 0,checkpoint:e.checkpoint,epoch:e.epoch,lastMutationId:void 0,pokeId:this.host.nextPokeId()},{preEncoded:!0});for(const y of p)A(r,y);n.set(l,{cursor:e.checkpoint,epoch:e.epoch}),s+=1}}return s}}const ie=c=>{const e=c.doName();if(e===void 0)return;const t=F(e);return t===void 0?new V(c,e):new Q(c,t.ownerKey,t.relayIndex)};export{z as DEFAULT_MAX_RELAYS,V as OwnerRelay,Q as RelayMember,ie as createRelayLink};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as m}from"@lunora/errors";import{stableWireKey as a}from"./stableWireKey-DSCJB6E7.mjs";const i="::relay::",f=(t,n)=>`${t}${i}${String(n)}`,s=t=>{const n=t.lastIndexOf(i);if(n===-1)return;const o=t.slice(0,n),e=t.slice(n+i.length),r=Number(e);if(!(o.length===0||!Number.isInteger(r)||r<0||String(r)!==e))return{ownerKey:o,relayIndex:r}},d=(t,n)=>a({args:n??{},name:t}),c={tDown:4e3,tUp:8e3},l=(t,n,o=c)=>{if(o.tDown>=o.tUp)throw new m("INTERNAL",`invalid promotion thresholds: tDown (${String(o.tDown)}) must be < tUp (${String(o.tUp)})`);return t==="owned"?n>=o.tUp?"promoted":"owned":n<o.tDown?"owned":"promoted"},g=(t,n)=>n<t?{tDown:n,tUp:t}:{tDown:Math.min(Math.max(1,Math.floor(t/2)),t-1),tUp:t},N=(t,n,o)=>{if(t<=n||n<=0)return 0;const e=t-n,r=Math.ceil(e/n);return Math.min(r,Math.max(0,o))};export{c as DEFAULT_PROMOTION_THRESHOLDS,i as RELAY_NAME_INFIX,g as clampPromotionThresholds,l as nextPromotionState,s as parseRelayName,N as relayCountFor,f as relayName,d as shapeRoutingKey};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as i}from"@lunora/errors";import{e}from"./estimate-bytes-CzG5x1f8.mjs";const r={maxReadRows:1e5,maxWrittenBytes:32*1024*1024,maxWrittenRows:5e4};class w{readRows=0;writtenRows=0;writtenBytes=0;limits;constructor(t={}){this.limits={...r,...t}}recordRead(t){if(this.readRows+=t,this.readRows>this.limits.maxReadRows)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction read ${String(this.readRows)} documents, over the ${String(this.limits.maxReadRows)}-document limit`)}recordWrite(t){const s=e(t);if(s===void 0)throw new i("BAD_REQUEST","this document is not JSON-serializable (cyclic or non-JSON value); it cannot be written");if(this.writtenRows+=1,this.writtenBytes+=s,this.writtenRows>this.limits.maxWrittenRows)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction wrote ${String(this.writtenRows)} documents, over the ${String(this.limits.maxWrittenRows)}-document limit`);if(this.writtenBytes>this.limits.maxWrittenBytes)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction wrote ${String(this.writtenBytes)} bytes, over the ${String(this.limits.maxWrittenBytes)}-byte limit`)}headroom(){return{readRows:this.readRows,remainingReadRows:Math.max(0,this.limits.maxReadRows-this.readRows),remainingWrittenBytes:Math.max(0,this.limits.maxWrittenBytes-this.writtenBytes),remainingWrittenRows:Math.max(0,this.limits.maxWrittenRows-this.writtenRows),writtenBytes:this.writtenBytes,writtenRows:this.writtenRows}}}export{r as DEFAULT_TRANSACTION_LIMITS,w as TransactionHeadroomTracker};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{toErrorBody as R,LunoraError as k}from"@lunora/errors";import{e as A}from"./wire-codec-BU9T2xJ7.mjs";import{readStreamRun as T,deleteStreamRun as w,claimStreamRun as _,appendStreamChunk as b,finishStreamRun as E,trimStreamRuns as y,readStreamChunks as v}from"./appendStreamChunk-CH4e4nJn.mjs";const p=5e4,S=64*1024*1024,M=864e5,N=36e5,L=(i,e)=>{const r=i?.startedAt??e.live?.generation;return e.resuming&&e.generation!==void 0&&r!==void 0&&e.generation!==r?"interrupted":e.live!==void 0?"attach":i===void 0?e.resuming?"interrupted":"attach":i.status==="complete"||i.status==="error"?e.resuming?"replay-terminal":"reclaim":e.resuming?"interrupted":"reclaim"},O=(i,e,r)=>{(i||r())&&e.fail({code:"STREAM_INTERRUPTED",message:i?"the run this durable stream resumed from no longer exists; start a new run":"the producer for this durable stream did not survive; start a new run"})};class I{lastTrimAt=0;runs=new Map;sql;waitUntil;constructor(e){this.sql=e.sql,this.waitUntil=e.waitUntil}async attach(e){try{await this.attachOrThrow(e)}catch(r){const{body:t,redacted:o}=R(r,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});o&&console.error("[@lunora/shard-engine] durable stream attach failed:",r),e.sink.fail({code:t.code,message:t.message})}}detach(e,r){this.runs.get(e)?.sinks.delete(r)}isLive(e){return this.runs.has(e)}async attachOrThrow(e){const r=this.sql(),{runKey:t,sinceChunk:o,sink:c}=e,n=T(r,t),u=o>0,s=this.runs.get(t),a=n?.startedAt??s?.generation,l=L(n,{generation:e.generation,live:s,resuming:u}),d=()=>{for(const g of v(r,t,o))if(!c.chunk({data:JSON.parse(g.dataJson),generation:a,seq:g.seq}))return!1;return!0};if(l==="replay-terminal"){d()&&(n?.status==="error"?c.fail({code:n.errorCode??"INTERNAL_SERVER_ERROR",message:n.error??"stream failed"}):c.complete());return}if(l==="interrupted"){O(e.generation!==void 0&&a!==void 0&&e.generation!==a,c,d);return}if(s){d()&&s.sinks.add(c);return}l==="reclaim"&&w(r,t),this.trim(r);const m=Math.max(Date.now(),n===void 0?0:n.startedAt+1);_(r,t,m,e.ttlMs??M);const h={generation:m,sinks:new Set([c])};this.runs.set(t,h);const f=this.produce(t,e.iterator,h);this.waitUntil?.(f),await f}async produce(e,r,t){const o=this.sql(),c=new AbortController;let n=0,u=0;try{for await(const s of r(c.signal)){const a=A(s),l=JSON.stringify(a);if(n+=1,u+=l.length,n>p||u>S)throw new k("STREAM_TOO_LONG",`durable stream exceeded its ceiling (${String(p)} chunks / ${String(S)} bytes); yield less, or drop \`durable\``,{status:507});b(o,e,n,l);for(const d of t.sinks)d.chunk({data:a,generation:t.generation,seq:n})||t.sinks.delete(d)}E(o,e,"complete",n);for(const s of t.sinks)s.complete()}catch(s){const{body:a,redacted:l}=R(s,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});l&&console.error("[@lunora/shard-engine] unhandled durable stream error:",s),E(o,e,"error",n,{code:a.code,message:a.message});for(const d of t.sinks)d.fail({code:a.code,message:a.message})}finally{this.runs.delete(e)}}trim(e){const r=Date.now();if(!(r-this.lastTrimAt<=N)){this.lastTrimAt=r;try{y(e,r)}catch{}}}}export{I as DurableStreamRunner,S as MAX_DURABLE_STREAM_BYTES,p as MAX_DURABLE_STREAM_CHUNKS,L as decideDurableAttach};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const m="0123456789bcdefghjkmnpqrstuvwxyz",k=9,p=63710088e-1,d=Math.PI/180,f=[Number.POSITIVE_INFINITY,5009400,1252300,156500,39100,4900,1200,152.9,38.2,4.77,1.19,.149,.037],S=f.map((t,n)=>n%2===0?t/2:t),I=.01,C=Math.acos(I)/d,z=2,_=t=>t/p/d,R=t=>{const n=5*t;return{latBands:2**Math.floor(n/2),lngSectors:2**Math.ceil(n/2)}},T=t=>Math.min(Math.max(Math.trunc(t),1),12),b=(t,n)=>{const a=T(n);let s=-90,o=90,e=-180,c=180,r="",g=0,l=0,u=!0;for(;r.length<a;){if(u){const h=(e+c)/2;t.lng>=h?(l=l*2+1,e=h):(l*=2,c=h)}else{const h=(s+o)/2;t.lat>=h?(l=l*2+1,s=h):(l*=2,o=h)}u=!u,g<4?g+=1:(r+=m[l]??"0",g=0,l=0)}return r},v=(t,n)=>Math.min(90,Math.abs(t)+_(n)),j=(t,n)=>{const a=(n.lat-t.lat)*d,s=(n.lng-t.lng)*d,o=t.lat*d,e=n.lat*d,c=Math.sin(a/2)**2+Math.cos(o)*Math.cos(e)*Math.sin(s/2)**2;return 2*p*Math.asin(Math.min(1,Math.sqrt(c)))},y=(t,n)=>{const a=Math.max(Math.cos(v(n,t)*d),I);for(let s=f.length-1;s>=1;s-=1){const o=f[s],e=S[s];if(o!==void 0&&e!==void 0&&o*a>=t&&e>=t)return s}return 1},B={east:["bc01fg45238967deuvhjyznpkmstqrwx","p0r21436x8zb9dcf5h7kjnmqesgutwvy"],north:["p0r21436x8zb9dcf5h7kjnmqesgutwvy","bc01fg45238967deuvhjyznpkmstqrwx"],south:["14365h7k9dcfesgujnmqp0r2twvyx8zb","238967debc01fg45kmstqrwxuvhjyznp"],west:["238967debc01fg45kmstqrwxuvhjyznp","14365h7k9dcfesgujnmqp0r2twvyx8zb"]},P={east:["bcfguvyz","prxz"],north:["prxz","bcfguvyz"],south:["028b","0145hjnp"],west:["0145hjnp","028b"]},i=(t,n)=>{const a=t.toLowerCase(),s=a.at(-1)??"";let o=a.slice(0,-1);const e=a.length%2===0?0:1;return P[n][e].includes(s)&&o!==""&&(o=i(o,n)),o+(m[B[n][e].indexOf(s)]??"")},q=(t,n,a)=>{const s=Math.min(a,z),{latBands:o,lngSectors:e}=R(s),c=180/o,r=360/e,g=_(n),l=Math.max(-90,t.lat-g),u=Math.min(90,t.lat+g),h=new Set;for(let M=0;M<o;M+=1){const w=-90+M*c;if(w+c<l||w>u)continue;const x=w+c/2;for(let E=0;E<e;E+=1){const L=-180+(E+.5)*r;h.add(b({lat:x,lng:L},s))}}return[...h]},A=(t,n)=>{const a=Math.max(n,1),s=y(a,t.lat);if(v(t.lat,a)>=C)return q(t,a,s);const e=b(t,s),c=i(e,"north"),r=i(e,"south"),g=[e,c,r,i(e,"east"),i(e,"west"),i(c,"east"),i(c,"west"),i(r,"east"),i(r,"west")];return[...new Set(g)]},G=(t,n)=>t.lat>=n.sw.lat&&t.lat<=n.ne.lat&&t.lng>=n.sw.lng&&t.lng<=n.ne.lng,D=t=>({lat:(t.sw.lat+t.ne.lat)/2,lng:(t.sw.lng+t.ne.lng)/2}),H=t=>{const n=D(t);return A(n,Math.max(j(n,t.ne),1))};export{k as GEO_DEFAULT_PRECISION,D as boundingBoxCenter,H as boundingBoxGeohashes,A as coveringGeohashes,b as encodeGeohash,j as haversineMeters,G as pointInBoundingBox};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as i}from"./runDrizzle-it6rL9bR.mjs";const r="__global_shape_snapshot",T=n=>{i(n,e`CREATE TABLE IF NOT EXISTS ${e.identifier(r)} (
|
|
2
|
+
connection_id TEXT NOT NULL,
|
|
3
|
+
sub_id TEXT NOT NULL,
|
|
4
|
+
members TEXT NOT NULL,
|
|
5
|
+
PRIMARY KEY (connection_id, sub_id)
|
|
6
|
+
)`)},b=(n,o,t)=>{const s=i(n,e`SELECT members FROM ${e.identifier(r)} WHERE connection_id = ${o} AND sub_id = ${t} LIMIT 1`).toArray()[0]?.members;if(s===void 0)return new Map;try{const c=JSON.parse(s);return c===null||typeof c!="object"?new Map:new Map(Object.entries(c))}catch{return new Map}},p=(n,o,t,a)=>{const s=JSON.stringify(Object.fromEntries(a));i(n,e`INSERT INTO ${e.identifier(r)} (connection_id, sub_id, members) VALUES (${o}, ${t}, ${s})
|
|
7
|
+
ON CONFLICT(connection_id, sub_id) DO UPDATE SET members = excluded.members`)},S=(n,o,t)=>{i(n,e`DELETE FROM ${e.identifier(r)} WHERE connection_id = ${o} AND sub_id = ${t}`)},m=(n,o)=>{i(n,e`DELETE FROM ${e.identifier(r)} WHERE connection_id = ${o}`)};export{r as GLOBAL_SHAPE_SNAPSHOT_TABLE,S as deleteGlobalShapeSnapshot,m as deleteGlobalShapeSnapshotsForConnection,T as migrateGlobalShapeSnapshot,b as readGlobalShapeSnapshot,p as writeGlobalShapeSnapshot};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
class n{changedTables;reads=new Map;resync=!1;skippedCount=0;constructor(e){this.changedTables=e}get readCount(){return this.reads.size}get resyncRequested(){return this.resync}get skipped(){return this.skippedCount}requestResync(){this.resync=!0}async rows(e,s){if(e===void 0)return s();const t=this.reads.get(e)??s();return this.reads.set(e,t),t}shouldRead(e){return this.changedTables===void 0||this.changedTables.has(e)?!0:(this.skippedCount+=1,!1)}}export{n as default};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{sql as t}from"drizzle-orm";import{runDrizzle as n}from"./runDrizzle-it6rL9bR.mjs";const r="__idempotency",m=i=>{n(i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(r)} (
|
|
2
|
+
identity TEXT NOT NULL,
|
|
3
|
+
mutation_id TEXT NOT NULL,
|
|
4
|
+
result_json TEXT NOT NULL,
|
|
5
|
+
ts REAL NOT NULL,
|
|
6
|
+
PRIMARY KEY (identity, mutation_id)
|
|
7
|
+
)`)},L=(i,e,s)=>{const o=n(i,t`SELECT result_json, ts FROM ${t.identifier(r)} WHERE identity = ${e} AND mutation_id = ${s} LIMIT 1`).toArray()[0];return o===void 0?void 0:{resultJson:o.result_json,ts:o.ts}},N=(i,e,s,E,o)=>{n(i,t`INSERT OR IGNORE INTO ${t.identifier(r)} (identity, mutation_id, result_json, ts) VALUES (${e}, ${s}, ${E}, ${o})`)},I=(i,e)=>{n(i,t`DELETE FROM ${t.identifier(r)} WHERE ts < ${e}`)};export{r as IDEMPOTENCY_TABLE,m as migrateIdempotency,L as readIdempotent,I as trimIdempotent,N as writeIdempotent};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import{runSql as c,decodeJsonColumn as a,orNull as o}from"./runDrizzle-it6rL9bR.mjs";const e="__lunora_mail",l=500,i=256*1024,n=t=>t!==void 0&&t.length>i?`${t.slice(0,i)}
|
|
2
|
+
… [truncated by the dev mail catcher]`:t,s=t=>t===void 0?null:JSON.stringify(t),_=t=>{c(t,`CREATE TABLE IF NOT EXISTS "${e}" (
|
|
3
|
+
id TEXT PRIMARY KEY,
|
|
4
|
+
captured_at INTEGER NOT NULL,
|
|
5
|
+
from_addr TEXT,
|
|
6
|
+
to_addrs TEXT NOT NULL,
|
|
7
|
+
cc_addrs TEXT,
|
|
8
|
+
bcc_addrs TEXT,
|
|
9
|
+
reply_to TEXT,
|
|
10
|
+
subject TEXT NOT NULL,
|
|
11
|
+
html TEXT,
|
|
12
|
+
body_text TEXT,
|
|
13
|
+
headers TEXT
|
|
14
|
+
)`)},N=(t,r,T)=>{_(t);const E=crypto.randomUUID();return c(t,`INSERT INTO "${e}" (id, captured_at, from_addr, to_addrs, cc_addrs, bcc_addrs, reply_to, subject, html, body_text, headers)
|
|
15
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,E,T,o(r.from),JSON.stringify(r.to),s(r.cc),s(r.bcc),o(r.replyTo),r.subject,o(n(r.html)),o(n(r.text)),s(r.headers)),c(t,`DELETE FROM "${e}"
|
|
16
|
+
WHERE id NOT IN (
|
|
17
|
+
SELECT id FROM "${e}" ORDER BY captured_at DESC, id DESC LIMIT ?
|
|
18
|
+
)`,l),{id:E}},u=(t,r={})=>{_(t);const T=Math.min(Math.max(r.limit??50,1),l);return{entries:c(t,`SELECT * FROM "${e}" ORDER BY captured_at DESC, id DESC LIMIT ?`,T).toArray().map(d=>({bcc:a(d.bcc_addrs),capturedAt:d.captured_at,cc:a(d.cc_addrs),from:d.from_addr??void 0,headers:a(d.headers),html:d.html??void 0,id:d.id,replyTo:d.reply_to??void 0,subject:d.subject,text:d.body_text??void 0,to:a(d.to_addrs)??d.to_addrs}))}},M=t=>(_(t),c(t,`DELETE FROM "${e}"`),{cleared:!0});export{l as MAIL_RETENTION,e as MAIL_TABLE,i as MAX_BODY_CHARS,M as clearCapturedMail,_ as ensureMailTable,u as readCapturedMail,N as recordCapturedMail};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{LunoraError as u}from"@lunora/errors";const l="x",g={'"':'"',"'":"'","[":"]","`":"`"},h=(n,t)=>{let e=t+2;for(;e<n.length&&n[e]!==`
|
|
2
|
+
`;)e+=1;return e},m=(n,t)=>{const e=n.indexOf("*/",t+2);return e===-1?-1:e+2},E=n=>{const t=n.split("");let e=0;for(;e<n.length;){const s=n[e]??"",c=g[s];if(s==="-"&&n[e+1]==="-"){const o=h(n,e);t.fill(l,e,o),e=o}else if(s==="/"&&n[e+1]==="*"){const o=m(n,e);if(o===-1)return;t.fill(l,e,o),e=o}else if(c!==void 0){let o=e+1;for(;o<n.length;)if(n[o]!==c)o+=1;else if(c!=="]"&&n[o+1]===c)o+=2;else break;if(o>=n.length)return;t.fill(l,e,o+1),e=o+1}else e+=1}for(let s=0;s<n.length;s+=1)n[s]===`
|
|
3
|
+
`&&(t[s]=`
|
|
4
|
+
`);return t.join("")},L=/^(?:explain\s+(?:query\s+plan\s+)?)?(?:select|with)\b/iu,S=/\b(?:alter|attach|create|delete|detach|drop|insert|pragma|reindex|replace|truncate|update|vacuum)\b/iu,p=/^\w+/u,A=/;\s*$/u,x=/\s/u,N=(n,t)=>{let e=t+2;for(;e<n.length&&n[e]!==`
|
|
5
|
+
`;)e+=1;return e},y=(n,t)=>{const e=n.indexOf("*/",t+2);return e===-1?-1:e+2},O=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=N(n,t);else if(e==="/"&&n[t+1]==="*"){const s=y(n,t);if(s===-1)break;t=s}else break}return t},f=n=>{const t=O(n),e=n.slice(t).trimEnd();if(e==="")return{code:"SQL_EMPTY",message:"the query is empty"};const s=e.replace(A,""),c=(E(s)??s).indexOf(";");if(c!==-1)return{code:"SQL_MULTIPLE_STATEMENTS",length:1,message:"only a single statement may be run",offset:t+c};const o="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:o,offset:t};const r=S.exec(s);if(r!==null)return{code:"SQL_NOT_READONLY",length:r[0].length,message:`${o} (\`${r[0].toUpperCase()}\` is not allowed)`,offset:t+r.index}},d=1e3,T=n=>{const t=f(n);if(t!==void 0)throw new u(t.code,t.message,{status:400})},b=(n,t)=>{T(t);const e=n.exec(t).toArray(),s=e.length>d?e.slice(0,d):e;return{columns:s.length>0?Object.keys(s[0]):[],rowCount:e.length,rows:s,truncated:e.length>d}},_=/near "([^"]*)": syntax error/iu,R=/^SCAN (?:TABLE )?(?!CONSTANT\b|SUBQUERY\b)([^\s(]+)/u,w=(n,t)=>{if(t==="")return{};const e=n.indexOf(t);return e===-1?{}:{length:t.length,offset:e}},v=(n,t)=>{const e=f(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 s;try{s=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=_.exec(i);return{diagnostics:[{...a?w(t,a[1]??""):{},message:i,severity:"error",source:"syntax"}],plan:[]}}const c=[],o=new Set;for(const r of s){const i=R.exec(r);if(i){const a=i[1]??"";o.has(a)||(o.add(a),c.push({message:`full table scan on \`${a}\` — this query reads every row`,severity:"warning",source:"plan"}))}}return{diagnostics:c,plan:s}};export{d as MAX_SQL_ROWS,T as assertReadonly,v as lintReadonlySql,b as runReadonlySql};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as y}from"@lunora/errors";import{c as Ht,q as Je,S as Nt,l as Ae,a as jt}from"./ctx-db-companions-BQRTS_WY.mjs";import{sql as r}from"drizzle-orm";import{d as Kt}from"./wire-codec-BU9T2xJ7.mjs";import{throwingScheduler as Ot,aggregateSqlFunction as ve,normalizeCountArgument as Qt}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as qe,encodeAggregateKey as Be,readAggregateValue as Ue}from"./aggregateTableName-Cy5e03oz.mjs";import{mergeWhere as J,CountRlsUnsupportedError as Pe,selectIndexForGroupBy as zt,selectIndexForCount as Jt,selectIndexForAggregate as Vt}from"./CountRlsUnsupportedError-Bdfupt3g.mjs";import{backfillSearchIndexesForTable as Yt}from"./backfillAggregateIndexes-C9wGiPH4.mjs";import{backfillAggregateIndexes as jr,backfillRankIndexes as Kr,backfillSearchIndexes as Or}from"./backfillAggregateIndexes-C9wGiPH4.mjs";import{appendCdcChange as Xt}from"./CDC_LOG_TABLE-CW0wHEgW.mjs";import{CDC_LOG_TABLE as zr,applyCdcChanges as Jr,bumpCdcEpoch as Vr,cdcCanVouchFor as Yr,cdcSeqLeavingRows as Xr,cdcTouchesTables as Zr,cdcTrimmedError as eo,compactCdcDocs as to,cursorBelowRetainedFloor as no,minCdcReplayableSeq as ro,minCdcSeq as oo,readCdcChangeKeys as io,readCdcChanges as so,readCdcCursor as co,readCdcEpoch as ao,trimCdcChanges as lo}from"./CDC_LOG_TABLE-CW0wHEgW.mjs";import{allocateCommitSeq as Zt,COMMIT_SEQ_FIELD as en}from"./COMMIT_SEQ_FIELD-CSe_oNZu.mjs";import{isMemoryTable as tn}from"./clearMemoryTables-CXULwypv.mjs";import{computeRankPage as dt}from"./computeRankPage-Bby1Npkd.mjs";import{SCAN_DEP as H}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as B}from"./runDrizzle-it6rL9bR.mjs";import{D as K,k as se,r as de,b as Ie,A as Ge,a as Ce,e as V,t as It,f as lt,i as nn,h as Ct,g as rn}from"./do-sql-DbEszTyj.mjs";import{WORKERD_SQLITE_LIMITS as xt,unionAll as Ke,sqliteInList as on}from"./param-Ib8WHnrF.mjs";import{coveringGeohashes as sn,boundingBoxGeohashes as cn,haversineMeters as an,pointInBoundingBox as dn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as ln}from"./NotFoundError-BhF7FeFr.mjs";import{softDeleteScope as ae,normalizeOrderKeys as un,buildSeekWhere as Mt,decodeCursor as Oe,applySelect as ut,encodeCursor as Qe,buildSeekBeforeWhere as fn}from"./applySelect-BQbHyo-W.mjs";import{rankTableName as ft,sortColumnName as ht,resolveRankPartition as hn,encodePartitionKey as wn,RANK_TIEBREAK as pn}from"./RANK_TIEBREAK-ci3MaM65.mjs";import{indexKeysForRow as gn,buildIndexRange as $n}from"./buildIndexRange-CBKQmHSS.mjs";import{assertFlatPredicate as He,resolveRelationPredicates as wt}from"./DEFAULT_MAX_RELATION_KEYS-BAWGIEvC.mjs";import{runRowValidators as Ne,resolveWith as pt,relationHooks as gt,applyOnDelete as yn,fanOutScalarCounts as En}from"./applyOnDelete-BlcwKjuO.mjs";import{guardWriter as mn}from"./RLS_UNWRAP_SYMBOL-BWloGsd3.mjs";import{i as Sn}from"./sql-projection-BqmxFxQU.mjs";import{createSystemReader as Rn}from"./createSystemReader-BtYeSMDb.mjs";import{ConflictError as pe}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as Tn}from"./hasTrigger-CjlwI4le.mjs";import{compileWhereSql as te}from"./compileWhereSql-JBpSfQm9.mjs";import{CLIENT_WATERMARK_TABLE as fo,advanceClientWatermark as ho,migrateClientWatermark as wo,readClientWatermark as po}from"./CLIENT_WATERMARK_TABLE-BoS1HEqz.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as $o,deleteGlobalShapeSnapshot as yo,deleteGlobalShapeSnapshotsForConnection as Eo,migrateGlobalShapeSnapshot as mo,readGlobalShapeSnapshot as So,writeGlobalShapeSnapshot as Ro}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-NWaL77m5.mjs";import{IDEMPOTENCY_TABLE as _o,readIdempotent as Ao,trimIdempotent as vo,writeIdempotent as Io}from"./IDEMPOTENCY_TABLE-DKVe2Ohf.mjs";import{runShardMigrations as xo}from"./runShardMigrations-DFc_LoP-.mjs";import{SEARCH_STATE_TABLE as bo}from"./SEARCH_STATE_TABLE-Dju8ebbU.mjs";import{selectShapeMembers as ko,selectShapeRows as Lo}from"./selectShapeMembers-C0vtU60D.mjs";import{serializeSqlValue as oe}from"./serializeSqlValue-DbI1VQYM.mjs";import{quoteIdentifier as _n}from"./quoteIdentifier-CObIFRhb.mjs";const An=o=>{const i=new TextEncoder().encode(o);let t="";for(const a of i)t+=String.fromCodePoint(a);return btoa(t)},vn=o=>{const i=atob(o),t=Uint8Array.from(i,a=>a.codePointAt(0)??0);return new TextDecoder().decode(t)},In=()=>new y("BAD_REQUEST","invalid cursor"),$t=16,yt=8,X=1024,Ve=(o,i)=>i.query(o),Cn=(o,i)=>{if(o.length===0)return 0;let t=0;for(const[a,f]of i.entries()){const g=a===i.length-1;let E=0;for(const T of o)(g?T.startsWith(f):T===f)&&(E+=1);if(E===0)return 0;t+=E}return t},xn=(o,i)=>{if(!i)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 f=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:f+String.fromCodePoint(a)}},Mn=(o,i,t)=>{const a={eq:(f,g)=>{if(!o.definition.filterFields?.includes(f))throw new y("INTERNAL",`field "${f}" is not a filter field of search index "${o.indexName}" on table "${i}"`);if(o.filters.length>=yt)throw new y("BAD_REQUEST",`search index "${o.indexName}" on table "${i}": at most ${String(yt)} .eq() filters are supported per search query`);return o.filters.push({field:f,value:g}),a},search:(f,g)=>{const E=o;if(f!==E.definition.field)throw new y("INTERNAL",`search index "${E.indexName}" on table "${i}" indexes "${E.definition.field}", not "${f}"`);const T=Ve(g,t).length;if(T>$t)throw new y("BAD_REQUEST",`search index "${E.indexName}" on table "${i}": at most ${String($t)} search terms are supported (got ${String(T)})`);return E.field=f,E.query=g,E.hasQuery=!0,a}};return a},bn=o=>{if(o.length>X)throw new y("BAD_REQUEST",`more than ${String(X)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Dn=o=>Math.min(o.offset+o.numItems+1,X),kn=o=>An(`search:${String(o)}`),Ln=o=>{let i;try{i=vn(o)}catch{return}if(!i.startsWith("search:"))return;const t=Number(i.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},Fn=o=>{if(typeof o.endCursor=="string")throw new y("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(o.numItems))throw new y("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(o.numItems)}`);const i=Math.max(0,Math.floor(o.numItems)),t=o.cursor?Ln(o.cursor):0;if(t===void 0)throw In();if(t+i>=X)throw new y("BAD_REQUEST",`search pagination reaches the ${String(X)}-document limit (offset ${String(t)} + ${String(i)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,X-t-1))} or fewer, or narrow the query or the filters instead`);return{numItems:i,offset:t}},Wn=(o,i)=>{const t=i.offset+i.numItems,a=i.numItems>0&&o.length>t;return{continueCursor:a?kn(t):null,isDone:!a,page:o.slice(i.offset,t)}},qn=o=>{if(o===void 0)return X+1;if(!Number.isFinite(o))return X;const i=Math.max(0,Math.floor(o));if(i>X)throw new y("BAD_REQUEST",`search returns at most ${String(X)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},Bn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Un=o=>{if(!Bn.test(o))throw new y("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},Et=50,bt=500,xe=Math.floor(xt.boundParams/3),we=xt.boundParams,Pn=128,ce=(o,i,t)=>{const a=i??bt;if(o>a)throw new y("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},Gn=o=>{const i={eq:(t,a)=>(o.sqlConditions.push({comparator:"=",field:t,value:a}),i),gt:(t,a)=>(o.sqlConditions.push({comparator:">",field:t,value:a}),i),gte:(t,a)=>(o.sqlConditions.push({comparator:">=",field:t,value:a}),i),lt:(t,a)=>(o.sqlConditions.push({comparator:"<",field:t,value:a}),i),lte:(t,a)=>(o.sqlConditions.push({comparator:"<=",field:t,value:a}),i)};return i},Hn=o=>Math.max(o,X),Dt=(o,i)=>{const t=o.filters.map(a=>r`${V(a.field)} = ${oe(a.value)}`);return i&&t.push(i),t},Nn=(o,i,t,a,f)=>{const g=Ve(t.query,Je(t.definition.language));if(g.length===0)return[];const E=Nt(i,t.indexName),T=`${E}__vocab`,S=g.length-1,$=g.map((W,M)=>{const N=xn(W,M===S),j=N.exact?r`${r.identifier("term")} = ${N.lower}`:r`${r.identifier("term")} >= ${N.lower} AND ${r.identifier("term")} < ${N.upper}`;return r`SELECT ${r.identifier("doc")}, ${r.raw(String(M))} AS ${r.identifier("__term__")}, COUNT(*) AS ${r.identifier("__n__")} FROM ${r.identifier(T)} WHERE ${j} GROUP BY ${r.identifier("doc")}`}),L=g.map((W,M)=>r`SUM(CASE WHEN u.${r.identifier("__term__")} = ${r.raw(String(M))} THEN u.${r.identifier("__n__")} ELSE 0 END)`),_=r`SELECT f.${r.identifier(Ae)} AS ${r.identifier(Ae)}, ${r.join(L,r` + `)} AS ${r.identifier("__score__")} FROM (${Ke($)}) u JOIN ${r.identifier(E)} f ON f.rowid = u.${r.identifier("doc")} GROUP BY f.${r.identifier(Ae)} HAVING ${r.join(L.map(W=>r`${W} > 0`),r` AND `)}`,v=Dt(t,f);let R=r`SELECT m.id, m._creationTime, m.${r.identifier(K)}, s.${r.identifier("__score__")} AS ${r.identifier("__score__")} FROM (${_}) s JOIN ${r.identifier(i)} m ON m.id = s.${r.identifier(Ae)}`;v.length>0&&(R=r`${R} WHERE ${r.join(v,r` AND `)}`),R=r`${R} ORDER BY s.${r.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${r.raw(String(a))}`;const F=[];for(const W of B(o,R)){const M=Ct(W);if(M){const N=W.__score__;F.push({document:M,score:typeof N=="number"?N:Number(N??0)})}}return F},jn=(o,i,t,a,f)=>{const g=Je(t.definition.language),E=Ve(t.query,g);if(E.length===0)return[];const T=Dt(t,f);let S=r`SELECT id, _creationTime, ${r.identifier(K)} FROM ${r.identifier(i)}`;T.length>0&&(S=r`${S} WHERE ${r.join(T,r` AND `)}`),S=r`${S} ORDER BY _creationTime DESC, id ASC LIMIT ${r.raw(String(Hn(a)))}`;const $=B(o,S).toArray(),L=[];for(const _ of $){const v=Ct(_);if(!v)continue;const R=Cn(jt(v,t.definition),E);R>0&&L.push({creationTime:typeof v._creationTime=="number"?v._creationTime:0,doc:v,id:typeof v._id=="string"?v._id:"",score:R})}return L.sort((_,v)=>v.score-_.score||v.creationTime-_.creationTime||_.id.localeCompare(v.id)),L.slice(0,a).map(_=>({document:_.doc,score:_.score}))},je=(o,i,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 y("BAD_REQUEST",`geo index "${a}" on table "${t}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},Kn=(o,i)=>{const t=o,a={near:(f,g)=>{if(t.within)throw new y("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(je(f,".near() point",i,t.indexName),!Number.isFinite(g)||g<=0)throw new y("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(g)}`);return t.near={point:{lat:f.lat,lng:f.lng},radiusMeters:g},a},within:f=>{if(t.near)throw new y("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(je(f.sw,".within() sw corner",i,t.indexName),je(f.ne,".within() ne corner",i,t.indexName),f.sw.lat>f.ne.lat)throw new y("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(f.sw.lng>f.ne.lng)throw new y("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return t.within={ne:{lat:f.ne.lat,lng:f.ne.lng},sw:{lat:f.sw.lat,lng:f.sw.lng}},a}};return a},On=(o,i)=>{const t=o[i];if(t===null||typeof t!="object")return;const{lat:a,lng:f}=t;return typeof a=="number"&&typeof f=="number"?{lat:a,lng:f}:void 0},Qn=(o,i)=>{const t=On(o,i.definition.field);if(!t)return;const a=typeof o._creationTime=="number"?o._creationTime:0;if(i.near){const f=an(i.near.point,t);return f<=i.near.radiusMeters?{creationTime:a,distance:f}:void 0}return dn(t,i.within)?{creationTime:a,distance:0}:void 0},zn=(o,i,t,a)=>{if(!t.near&&!t.within)throw new y("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const f=t.near?sn(t.near.point,t.near.radiusMeters):cn(t.within),g=rn(i,t.indexName),E=f.map(_=>r`(g.${r.identifier("__geohash__")} >= ${_} AND g.${r.identifier("__geohash__")} < ${`${_}{`})`),T=[r`(${r.join(E,r` OR `)})`];a&&T.push(a);const S=r`SELECT m.id, m._creationTime, m.${r.identifier(K)} FROM ${r.identifier(g)} g JOIN ${r.identifier(i)} m ON m.id = g.${r.identifier("__id__")} WHERE ${r.join(T,r` AND `)}`,$=B(o,S).toArray(),L=[];for(const _ of $){const v=de(_),R=v?Qn(v,t):void 0;v&&R&&L.push({creationTime:R.creationTime,distance:R.distance,doc:v})}return L.sort((_,v)=>_.distance-v.distance||v.creationTime-_.creationTime),L},kt=(o,i,t,a)=>{const f=[];for(const g of o)if(i.every(E=>E(a(g)))&&(f.push(g),typeof t=="number"&&f.length>=t))break;return f},Jn=(o,i,t,a,f,g=()=>{})=>{const E=t.within!==void 0,T=zn(o,i,t,f).map(S=>({distanceMeters:E?null:S.distance,document:S.doc}));return g(T.length),typeof a=="number"?T.slice(0,Math.max(0,Math.floor(a))):T},Lt=(o,i,t,a,f,g=()=>{})=>{const{geo:E}=t;if(!E)throw new y("INTERNAL","runGeoTerminalScored called without a staged geo query");const T=t.inMemoryFilters.length>0,S=Jn(o,i,E,T?void 0:f,a,g);return T?kt(S,t.inMemoryFilters,f,$=>$.document):S},Vn=(o,i,t,a,f,g=()=>{})=>Lt(o,i,t,a,f,g).map(E=>E.document),Yn=(o,i,t,a,f,g,E=()=>{})=>{const T=[];for(const _ of t.sqlConditions)T.push(r`${V(_.field)} ${r.raw(_.comparator)} ${oe(_.value)}`);a&&T.push(a);let S=r`SELECT id, _creationTime, ${r.identifier(K)} FROM ${r.identifier(i)}`;T.length>0&&(S=r`${S} WHERE ${r.join(T,r` AND `)}`),S=r`${S} ORDER BY ${f}`,typeof g=="number"&&t.inMemoryFilters.length===0&&(S=r`${S} LIMIT ${r.raw(String(Math.max(0,Math.floor(g))))}`);const $=B(o,S).toArray();E($.length);const L=[];for(const _ of $){const v=de(_);if(v&&t.inMemoryFilters.every(R=>R(v))&&(L.push(v),typeof g=="number"&&L.length>=g))break}return L},re={fieldRef:V,serialize:oe},Ft=(o,i)=>{const t=i===void 0?void 0:o.shape[i];return t!==void 0&&Sn(t)},mt=(o,i)=>i.some(t=>Ft(o,t)),St=(o,i,t)=>{if(Ft(o,i))throw new y("BAD_REQUEST",`${t}: "${i}" 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`)},Xn=o=>{let i=0;const t=[],a={fieldRef:V,relationExists:f=>{const{childWhere:g,negated:E,parentTable:T,relation:S}=f,$=`__rel_${String(i)}`,L=t.at(-1)??T;i+=1,o(S.table,H);const _=S.kind==="one"?S.field:S.references,v=S.kind==="one"?S.references:S.field,R=r`${lt($,v)} = ${lt(L,_)}`;t.push($);const F=te(g,a);t.pop();const W=F?r`${R} AND ${F}`:R,M=r`EXISTS (SELECT 1 FROM ${r.identifier(S.table)} AS ${r.identifier($)} WHERE ${W})`;return E?r`NOT ${M}`:M},serialize:oe};return a},Wt=o=>{const i=o.map(t=>r`${V(t.field)} ${r.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||i.push(r`${V("id")} ASC`),r.join(i,r`, `)},Zn={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},er=o=>{const i=o.order;return o.indexFields.length>0?o.indexFields.map(t=>({direction:i,field:t})):[{direction:i,field:"_creationTime"}]},tr=(o,i,t,a)=>{const f=o.sqlConditions.map(g=>({[g.field]:{[Zn[g.comparator]??"eq"]:g.value}}));if(t&&f.push(Mt(i,Oe(t))),a&&f.push(fn(i,Oe(a))),f.length!==0)return f.length===1?f[0]:{AND:f}},nr=(o,i,t)=>{const a=[];for(const f of o){const g=de(f);if(g&&i.every(E=>E(g))&&(a.push(g),t!==void 0&&a.length>t))break}return a},rr=(o,i,t,a,f,g=()=>{})=>{const E=Math.max(0,Math.floor(a.numItems)),T=er(t),S=typeof a.endCursor=="string",$=te(tr(t,T,a.cursor,a.endCursor),re),L=f&&$?r`${$} AND ${f}`:f??$;let _=r`SELECT id, _creationTime, ${r.identifier(K)} FROM ${r.identifier(i)}`;L&&(_=r`${_} WHERE ${L}`),_=r`${_} ORDER BY ${Wt(T)}`;const v=t.inMemoryFilters.length>0;!v&&!S&&(_=r`${_} LIMIT ${r.raw(String(E+1))}`);const R=B(o,_).toArray();g(R.length);const F=nr(R,t.inMemoryFilters,v||S?void 0:E);if(S){const j=F.length>=2?F[Math.floor(F.length/2)-1]:void 0;return{continueCursor:a.endCursor??null,isDone:!0,page:F,splitCursor:j?Qe(j,T):null}}const W=F.length>E,M=W?F.slice(0,E):F,N=M.at(-1);return{continueCursor:W&&N?Qe(N,T):null,isDone:!W,page:M}};class or extends y{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const ir=/\s/u,sr=String.fromCodePoint(0),Rt=(o,i,t)=>{if(!o.tables[i])throw new y("INTERNAL",`unknown table: ${i}`);return typeof t!="string"||t.length===0||ir.test(t)||t.includes(sr)?null:t},cr=(o,i,t,a=()=>{},f=()=>{},g=()=>{})=>{const E=i.tables[t];if(!E)throw new y("INTERNAL",`unknown table: ${t}`);const T=ae(E.softDeleteMode,void 0),S=T?te(T,re):void 0,$={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let L=0;const _=m=>{const{search:b}=$;if(!b)throw new y("INTERNAL","runSearchFetch called without a staged search");Yt(o,t,E);const k=$.inMemoryFilters.length>0,C=qn(k?void 0:m),O=nn(o)?Nn(o,t,b,C,S):jn(o,t,b,C,S);return k?(L=O.length,kt(O,$.inMemoryFilters,m,be=>be.document)):(m===void 0&&bn(O),O)},v=m=>_(m).map(b=>b.document),R=m=>{const b=Fn(m);return Wn(v(Dn(b)),b)},F=()=>{const m=$.indexFields.length>0?$.indexFields:["_creationTime"],b=$.order==="desc"?"DESC":"ASC";return r.join(m.map(k=>r`${V(k)} ${r.raw(b)}`),r`, `)},W=()=>{if($.search||$.geo||$.indexName===void 0){f(void 0);return}f($n(t,$.indexName,$.indexFields,$.sqlConditions,oe))},M=m=>{W();let b=0;const k=(()=>{if($.search){const C=v(m);return b=L,C}return $.geo?Vn(o,t,$,S,m,C=>{b=C}):Yn(o,t,$,S,F(),m,C=>{b=C})})();return g(Math.max(b,k.length)),k},N=()=>{if(!$.search&&!$.geo)throw new y("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);W();let m=0;const b=(()=>{if($.search){const k=_(void 0);return m=L,k}return Lt(o,t,$,S,void 0,k=>{m=k})})();return g(Math.max(m,b.length)),b},j={async*[Symbol.asyncIterator](){const m=[...$.inMemoryFilters];let b;$.inMemoryFilters=[];try{for(;;){const k=await j.paginate({cursor:b??null,numItems:Pn});for(const C of k.page)m.every(O=>O(C))&&(yield C);if(k.isDone||k.continueCursor===null)return;b=k.continueCursor}}finally{$.inMemoryFilters=m}},async collect(){return M(void 0)},async collectWithScores(){return N()},filter(m){return $.inMemoryFilters.push(m),j},async first(){return M($.inMemoryFilters.length>0?void 0:1)[0]??null},order(m){return $.order=m==="desc"?"desc":"asc",j},async paginate(m){let b=0;if(W(),$.search){const C=R(m);return g(C.page.length),C}if($.geo)throw new y("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const k=rr(o,t,$,m,S,C=>{b=C});return g(Math.max(b,k.page.length)),k},async take(m){return M(m)},async unique(){const m=M($.inMemoryFilters.length>0?void 0:2);if(m.length>1)throw new or(`unique() on table "${t}" matched ${String(m.length)} documents; expected at most one`);return m[0]??null},withGeoIndex(m,b){const k=(E.geoIndexes??[]).find(O=>O.name===m);if(!k)throw new y("INTERNAL",`unknown geo index "${m}" on table "${t}"`);a(t,m,"geo");const C={definition:k,indexName:m};if($.geo=C,b(Kn(C,t)),!C.near&&!C.within)throw new y("INTERNAL",`geo index "${m}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return j},withIndex(m,b){const k=E.indexes.find(C=>C.name===m);if(!k)throw new y("INTERNAL",`unknown index "${m}" on table "${t}"`);return a(t,m,"index"),$.indexName=m,$.indexFields=k.fields,b&&b(Gn($)),j},withSearchIndex(m,b){const k=(E.searchIndexes??[]).find(O=>O.name===m);if(!k)throw new y("INTERNAL",`unknown search index "${m}" on table "${t}"`);a(t,m,"search");const C={definition:k,field:k.field,filters:[],hasQuery:!1,indexName:m,query:""};if($.search=C,b(Mn(C,t,Je(k.language))),!C.hasQuery)throw new y("INTERNAL",`search index "${m}" on table "${t}" requires a .search(field, query) call`);return j}};return j},Tt=(o,i,t)=>{const a={...i};for(const[f,g]of It(o)){if(g.serverDefault){a[f]=g.serverDefault({auth:t});continue}a[f]===void 0&&(g.defaultFn?a[f]=g.defaultFn():"defaultValue"in g&&(a[f]=g.defaultValue))}return a},_t=(o,i,t,a)=>{const f=t;for(const[g,E]of It(o)){if(E.serverDefault){g in i&&(f[g]=E.serverDefault({auth:a}));continue}E.onUpdateFn&&!(g in i)&&(f[g]=E.onUpdateFn())}},At=(o,i)=>{for(const t of Object.keys(i))if(i[t]===void 0)throw new y("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},ar=/unique constraint failed/i,dr=o=>o instanceof Error&&ar.test(o.message),ze=(o,i,t)=>{try{B(o,t)}catch(a){throw dr(a)?new pe(`unique constraint violation on "${i}"`,"unique"):a}},Me=(o,i,t)=>{if(ze(o,i,t),B(o,r`SELECT changes() AS changed`).one().changed===0)throw new pe(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},vt=(o,i,t,a,f,g,E)=>{const T=[];for(let _=0;_<t.length+1;_+=1){const v=[];for(let M=0;M<_;M+=1)v.push(r`${r.identifier(t[M])} IS ${g[M]}`);const R=t[_],F=a[_];if(R!==void 0&&F!==void 0){const M=F.direction==="desc"?">":"<";v.push(r`${r.identifier(R)} ${r.raw(M)} ${g[_]}`)}else v.push(r`${r.identifier(pn)} < ${E}`);const[W]=v;T.push(v.length===1&&W!==void 0?W:r`(${r.join(v,r` AND `)})`)}const S=r.join(T,r` OR `),$=B(o,r`SELECT COUNT(*) AS c FROM ${r.identifier(i)} WHERE ${r.identifier("__partition__")} = ${f} AND (${S})`).one(),L=B(o,r`SELECT COUNT(*) AS c FROM ${r.identifier(i)} WHERE ${r.identifier("__partition__")} = ${f}`).one();return{before:$.c,total:L.c}},Gr=o=>{const{sql:i}=o,{schema:t}=o,a=o.broadcast??(()=>{});let f;const g=()=>o.inTransaction?.()===!0,E=e=>t.tables[e]?.commitOrderedMode!==!0?{}:((f===void 0||!g())&&(f=Zt(i)),{[en]:f}),T=(e,...n)=>{const s=t.tables[e]?.indexes;if(!s||s.length===0)return;const u=[];for(const h of n)h&&u.push(...gn(s,h,oe));return u.length>0?u:void 0},{headroom:S}=o;let $=!1;const L=async e=>{const n=$;$=!0;try{return await e()}finally{$=n}},_=o.onRead??(()=>{}),v=o.onReadRange??(e=>{_(e.table,H)}),R=(e,n)=>{n!==void 0&&n!==H&&!$&&S?.recordRead(1),_(e,n)},F=o.onIndexUse??(()=>{}),W=o.onWrite??(()=>{}),M=e=>{$||S?.recordWrite(e)},N=async e=>{M(e.doc),await W(e)},{cache:j}=o,m=o.clock??(()=>Date.now()),b=o.idGenerator??(()=>crypto.randomUUID()),k=o.scheduler??Ot,{globalDb:C}=o,O=o.auth??{identity:null,userId:null},be=o.cdc??!1,De=k,qt=Rn({scheduler:typeof De.list=="function"&&typeof De.get=="function"?De:void 0,storage:o.storage}),le=(e,n,s,u)=>{be&&!tn(t.tables[e])&&Xt(i,m(),e,n,s,u)},ie=e=>t.tables[e]?.shardMode?.kind==="global",Ye=(e,n)=>{if(ie(e)){if(!C)throw new y("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return C}return U},ke=e=>Ye(e,"cascade"),z=(e,n)=>{if(ie(e)){if(!C)throw new y("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return C}},Xe=async(e,n,s,u,h)=>{h&&M(s);const l=await e.insert(n,s,u);return a({key:l,op:"insert",row:{...s,_id:l},table:n}),l},Le=(e,n)=>Ye(e,"relation load").findMany(e,n),Ze=(e,n)=>(ie(e)&&R(e,H),Le(e,n)),Bt=e=>!ie(e.table),et=o.relationExistsPushDown??"auto",tt=et!=="never",{maxRelationKeys:nt}=o,ge=(e,n,s)=>wt(e,{fetcher:Ze,maxRelationKeys:nt,relationBaseWhere:s,schema:t,tableName:n}),rt=async(e,n,s,u)=>{const h=z(e,"relation grouped count");if(h)return R(e,H),En((q,I)=>h.count(q,I),e,n,s,u);const l=t.tables[e];if(!l)throw new y("INTERNAL",`unknown table: ${e}`);R(e,H);const c=ae(l.softDeleteMode,void 0),d={[n]:{in:s}},w=J(J(d,u),c),A=await ge(w,e,void 0),p=te(A,re),x=V(n);let D=r`SELECT ${x} AS __fk__, COUNT(*) AS count FROM ${r.identifier(e)}`;p&&(D=r`${D} WHERE ${p}`),D=r`${D} GROUP BY ${x}`;const P=B(i,D).toArray();return new Map(P.map(q=>[q.__fk__,q.count]))};let $e=0;const ot=new Set;for(const[e,n]of Object.entries(t.tables))for(const s of Object.values(n.triggerMap??{}))ot.add(`${e} ${s.timing} ${s.op}`);const Z=(e,n,s)=>ot.has(`${e} ${n} ${s}`),ee=async(e,n,s)=>{if($e+=1,$e>Et)throw $e-=1,new pe(`trigger recursion exceeded ${String(Et)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await Tn({ctx:Pt,event:s,op:n,schema:t,tableName:s.table,timing:e})}finally{$e-=1}},{ensureBackfilledForTable:ue,ensureBackfilledIndex:Fe,ensureRankBackfilled:We,ensureRankBackfilledForTable:fe,syncAggregates:ye,syncCompanionsForInsert:it,syncGeo:Ee,syncRanks:he,syncSearch:me}=Ht({broadcast:a,indexKeysFor:(e,n)=>T(e,n),invalidateCache:(e,n,s)=>j?.invalidate(e,n,T(e,s)),recordCdc:le,schema:t,sql:i}),st=(e,n,s)=>{const{shardMode:u}=n;if(u?.kind==="shardBy"&&!(u.field!==void 0&&(s.partitionBy??[]).includes(u.field)))throw Object.assign(new Error(`rank index "${s.name}" on "${e}" partitions across shards (shard key "${u.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},ct=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),ne=(e,n)=>{const s=ct(n);for(let u=0;u<s.length;u+=we){const h=s.slice(u,u+we).map(p=>r`SELECT ${r.raw(`'${p.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${r.identifier(K)} FROM ${r.identifier(p)} WHERE id = ${e}`),[l]=B(i,r`${Ke(h)} LIMIT 1`).toArray();if(!l)continue;const c=l.__t__,d=de(l);if(typeof c!="string"||!d)return;const w=l[K];return{docJson:typeof w=="string"?w:se(w??{}),row:d,tableName:c}}},Ut=(e,n)=>{const s=[...new Set(e)],u=new Map;if(s.length===0)return u;const h=ct(n);for(let l=0;l<h.length;l+=we){const c=h.slice(l,l+we),d=Math.floor(we/c.length),w=on(r`${r.identifier("id")}`,s,!1,d),A=c.map(p=>r`SELECT ${r.raw(`'${p.replaceAll("'","''")}'`)} AS __t__, id FROM ${r.identifier(p)} WHERE ${w}`);for(const p of B(i,Ke(A))){const{id:x,__t__:D}=p;typeof D=="string"&&typeof x=="string"&&u.set(x,D)}}return u},at={assertRankPartitionLocal:st,ensureRankBackfilled:We,onRead:R,rowToDocument:de,schema:t,sql:i},U={system:qt,async aggregate(e,n){const s=z(e,"aggregate");if(s)return R(e,H),s.aggregate(e,n);const u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);if(ve(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 y("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);R(e,H);const h=ae(u.softDeleteMode,void 0),l=J(J(n.baseWhere,n.where),h),c=await ge(l,e,n.relationBaseWhere),d=c!==l;if(u.aggregateIndexes&&!n.baseWhere&&!d&&(!h||mt(u,[n.field]))){const q=Vt(u.aggregateIndexes,n.op,n.field,n.where);if(q){Fe(e,q.index);const I=Be(q.index.by??[],q.key),Q=qe(e,q.index.name),Y=B(i,r`SELECT ${Ie} AS value, ${Ge} AS count FROM ${r.identifier(Q)} WHERE ${Ce} = ${I}`).toArray()[0];return Ue(n.op,Y)}}St(u,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const w=te(c,re),A=ve(n.op),p=V(n.field);let x=r`SELECT ${r.raw(A)}(${p}) AS value FROM ${r.identifier(e)}`;w&&(x=r`${x} WHERE ${w}`);const P=B(i,x).toArray()[0]?.value;return P??null},asId(e,n){const s=Rt(t,e,n);if(s===null)throw new y("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 u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const h=Qt(n);if(h.restrictsCounts)throw new Pe(e);R(e,H);const l=ae(u.softDeleteMode,void 0),c=J(J(h.baseWhere,h.where),l),d=await ge(c,e,h.relationBaseWhere),w=d!==c;if(u.aggregateIndexes&&!h.baseWhere&&!w&&!l){const D=Jt(u.aggregateIndexes,h.where);if(D){Fe(e,D.index);const P=Be(D.index.by??[],D.key),q=qe(e,D.index.name),I=B(i,r`SELECT ${Ie} AS value FROM ${r.identifier(q)} WHERE ${Ce} = ${P}`).toArray();return I[0]===void 0?0:I[0].value??0}}const A=te(d,re);let p=r`SELECT COUNT(*) AS count FROM ${r.identifier(e)}`;return A&&(p=r`${p} WHERE ${A}`),B(i,p).one().count},async delete(e,n,s){const u=ne(e,n);if(!u){const p=n===void 0?C:void 0;p&&(M(void 0),await p.delete(e,void 0,s));return}const{docJson:h,row:l,tableName:c}=u,d=t.tables[c],w=s?.hard===!0,A=!w&&d?.softDeleteMode?d.softDeleteMode.field:void 0;if(!(A&&l[A]!==null&&l[A]!==void 0)){if(Z(c,"before","delete")&&await ee("before","delete",{id:e,op:"delete",previous:l,table:c}),await yn({deletedId:e,deletedReference:p=>l[p],findHolders:async(p,x,D)=>(await ke(p).findMany(p,{includeDeleted:w,where:{[x]:D}})).page,onCascade:(p,x)=>ke(p).delete(x,void 0,s),onRestrict:p=>{throw new pe(p,"restrict")},onSetNull:(p,x,D)=>ke(p).patch(x,{[D]:null}),schema:t,tableName:c}),ue(c),fe(c),A){const p={...l,...E(c),[A]:m(),_id:e};Me(i,c,r`UPDATE ${r.identifier(c)} SET ${r.identifier(K)} = ${se(p)} WHERE id = ${e} AND ${r.identifier(K)} = ${h}`),me(c,e,p,l),Ee(c,e,void 0),ye(c,l,p),he(c,e,l,void 0),j?.invalidate(c,e,T(c,l,p)),le(c,e,"update",p),a({indexKeys:T(c,l,p),key:e,op:"update",row:p,table:c}),Z(c,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:c}),await N({id:e,op:"delete",table:c});return}Me(i,c,r`DELETE FROM ${r.identifier(c)} WHERE id = ${e} AND ${r.identifier(K)} = ${h}`),me(c,e,void 0),Ee(c,e,void 0),ye(c,l,void 0),he(c,e,l,void 0),j?.invalidate(c,e,T(c,l)),le(c,e,"delete"),a({indexKeys:T(c,l),key:e,op:"delete",table:c}),Z(c,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:c}),await N({id:e,op:"delete",table:c})}},async deleteAll(e,n){if(!t.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);const s=Math.max(1,n?.chunkSize??bt),u=n?.hard===void 0?void 0:{hard:n.hard},h=ie(e)?void 0:e;let l=0;return await L(async()=>{for(;;){const d=(await U.findMany(e,{limit:s})).page.map(w=>String(w._id));if(d.length===0)break;for(const w of d)await U.delete(w,h,u),l+=1;if(d.length<s)break}}),{deleted:l}},async deleteMany(e,n,s){ce(e.length,n?.limit,"deleteMany");for(const u of e)await U.delete(u,s);return{deleted:e.length}},async deleteWhere(e,n,s){const l=(await(z(e,"deleteWhere")??U).findMany(e,{where:n})).page.map(c=>String(c._id));if(ce(l.length,s?.limit,"deleteWhere"),U.deleteMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return U.deleteMany(l,s)},async findFirst(e,n={}){return(await U.findMany(e,{...n,limit:1})).page[0]??null},async findFirstOrThrow(e,n={}){const s=await U.findFirst(e,n);if(s===null)throw new ln(`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 u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const h=!n.where&&!n.baseWhere;h?R(e,H):R(e);const l=un(n.orderBy),c=n.cursor?Mt(l,Oe(n.cursor)):void 0;let d=J(n.baseWhere,n.where);d=J(d,ae(u.softDeleteMode,n.includeDeleted)),d=await wt(d,{canPushExists:tt?Bt:void 0,existsPushMode:et==="always"?"always":"auto",fetcher:Ze,maxRelationKeys:nt,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),c&&(d=d?{AND:[d,c]}:c);const w=tt?Xn(R):re,A=te(d,w);let p=r`SELECT id, _creationTime, ${r.identifier(K)} FROM ${r.identifier(e)}`;A&&(p=r`${p} WHERE ${A}`),p=r`${p} ORDER BY ${Wt(l)}`;const x=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0;x!==void 0&&(p=r`${p} LIMIT ${r.raw(String(x+1))}`);const D=B(i,p).toArray();h&&!$&&S?.recordRead(D.length);const P=[];for(const Y of D){const G=de(Y);G&&(P.push(G),!h&&typeof G._id=="string"&&R(e,G._id))}if(x===void 0)return n.with&&await pt({groupedCounter:rt,fetcher:Le,parents:P,...gt(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:ut(P,n.select,n.with)};const q=P.length>x,I=q?P.slice(0,x):P,Q=I.at(-1);return n.with&&await pt({fetcher:Le,groupedCounter:rt,parents:I,...gt(n),schema:t,tableName:e,with:n.with}),{continueCursor:q&&Q?Qe(Q,l):null,isDone:!q,page:ut(I,n.select,n.with)}},async get(e,n){const s=ne(e,n);if(!s){const u=n===void 0?C:void 0;return u?u.get(e):null}return R(s.tableName,e),s.row},async lookupById(e,n){const s=ne(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 u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);R(e,H);const h=n.agg??{op:"count"};if(ve(h.op),h.op!=="count"&&!h.field)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const l=ae(u.softDeleteMode,void 0),c=J(J(n.baseWhere,n.where),l),d=await ge(c,e,n.relationBaseWhere),w=d!==c,A=[...n.by,h.field];if(u.aggregateIndexes&&!n.baseWhere&&!w&&(!l||mt(u,A))){const I=zt(u.aggregateIndexes,h.op,h.field,n.by,n.where),Q=I===void 0?0:Object.keys(I.partial).length,Y=I?.index.by?.length??0;if(I&&(Q===0||Q===Y)){Fe(e,I.index);const G=qe(e,I.index.name),Se=Object.keys(I.partial),Re=[];if(Se.length===(I.index.by??[]).length&&Se.length>0){const Te=Be(I.index.by??[],I.partial),_e=B(i,r`SELECT ${Ie} AS value, ${Ge} AS count FROM ${r.identifier(G)} WHERE ${Ce} = ${Te}`).toArray();return _e.length>0&&Re.push({key:{...I.partial},value:Ue(h.op,_e[0])}),Re}const Gt=B(i,r`SELECT ${Ce} AS key, ${Ie} AS value, ${Ge} AS count FROM ${r.identifier(G)}`).toArray();for(const Te of Gt){const _e=Kt(JSON.parse(Te.key));Re.push({key:_e,value:Ue(h.op,Te)})}return Re}}for(const I of A){if(I===void 0)continue;const Q=I===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${I}" } })`:`groupBy(${e}, { by: [..."${I}"] })`;St(u,I,Q)}const p=te(d,re),x=n.by.map(I=>r`${V(I)} AS ${r.identifier(I)}`);if(h.op==="count")x.push(r`COUNT(*) AS value`);else{const{field:I}=h;if(I===void 0)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);x.push(r`${r.raw(ve(h.op))}(${V(I)}) AS value`)}let D=r`SELECT ${r.join(x,r`, `)} FROM ${r.identifier(e)}`;p&&(D=r`${D} WHERE ${p}`),D=r`${D} GROUP BY ${r.join(n.by.map(I=>V(I)),r`, `)}`;const P=B(i,D).toArray(),q=[];for(const I of P){const Q={};for(const G of n.by)Q[G]=I[G]??null;const{value:Y}=I;q.push({key:Q,value:Y==null?null:Number(Y)})}return q},async insert(e,n,s){const u=z(e,"insert");if(u)return Xe(u,e,n,s,!0);const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);const l=Tt(h,n,O);Ne(h,l);let c;s?.clientId!==void 0?(Un(s.clientId),c=s.clientId):s?.allowExplicitId&&typeof l._id=="string"?c=l._id:c=b();const d=s?.allowExplicitId&&typeof l._creationTime=="number"?l._creationTime:m(),w={...l,...E(e),_creationTime:d,_id:c};return Z(e,"before","insert")&&await ee("before","insert",{doc:{...w},id:c,op:"insert",table:e}),ue(e),fe(e),ze(i,e,r`INSERT INTO ${r.identifier(e)} (id, _creationTime, ${r.identifier(K)}) VALUES (${c}, ${d}, ${se(w)})`),it(e,c,w),Z(e,"after","insert")&&await ee("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(ce(n.length,s?.limit,"insertManyUnsafe"),n.length===0)return[];const u=z(e,"insert");if(u){const d=[];for(const w of n)M(w);for(const w of n){const A=await u.insert(e,w,{allowExplicitId:s?.allowExplicitId});a({key:A,op:"insert",row:{...w,_id:A},table:e}),d.push(A)}return d}const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);ue(e),fe(e);const l=[];for(let d=0;d<n.length;d+=xe)l.push(E(e));const c=n.map((d,w)=>{const A=Tt(h,d,O),p=s?.allowExplicitId===!0&&typeof A._id=="string"?A._id:b(),x=s?.allowExplicitId===!0&&typeof A._creationTime=="number"?A._creationTime:m(),D={...A,...l[Math.floor(w/xe)],_creationTime:x,_id:p};return{creationTime:x,document:D,id:p}});for(const d of c)M(d.document);for(let d=0;d<c.length;d+=xe){const w=r.join(c.slice(d,d+xe).map(A=>r`(${A.id}, ${A.creationTime}, ${se(A.document)})`),r`, `);ze(i,e,r`INSERT INTO ${r.identifier(e)} (id, _creationTime, ${r.identifier(K)}) VALUES ${w}`)}for(const{document:d,id:w}of c)it(e,w,d),await W({doc:d,id:w,op:"insert",table:e});return c.map(d=>d.id)},async insertMany(e,n,s){ce(n.length,s?.limit,"insertMany");const u=s?.skipDuplicates===!0,h=[],l=z(e,"insert");if(l)for(const d of n)M(d);const c=async d=>l?Xe(l,e,d,void 0,!1):U.insert(e,d);for(const d of n)try{h.push(await c(d))}catch(w){if(u&&w instanceof pe&&w.kind==="unique")h.push(null);else throw w}return h},normalizeId(e,n){return Rt(t,e,n)},async patch(e,n,s){const u=ne(e,s);if(!u){const A=s===void 0?C:void 0;if(A){M(n),await A.patch(e,n);return}throw new y("INTERNAL",`document not found: ${e}`)}const{docJson:h,row:l,tableName:c}=u,d=t.tables[c];if(!d)throw new y("INTERNAL",`unknown table: ${c}`);R(c,e),At("patch",n);const w={...l,...n,...E(c),_id:e};_t(d,n,w,O),Ne(d,w,!0),Z(c,"before","update")&&await ee("before","update",{doc:{...w},id:e,op:"update",previous:l,table:c}),ue(c),fe(c),Me(i,c,r`UPDATE ${r.identifier(c)} SET ${r.identifier(K)} = ${se(w)} WHERE id = ${e} AND ${r.identifier(K)} = ${h}`),me(c,e,w,l),Ee(c,e,w),ye(c,l,w),he(c,e,l,w),j?.invalidate(c,e,T(c,l,w)),le(c,e,"update",w),a({indexKeys:T(c,l,w),key:e,op:"update",row:w,table:c}),Z(c,"after","update")&&await ee("after","update",{doc:w,id:e,op:"update",previous:l,table:c}),await N({doc:w,id:e,op:"update",table:c})},async patchMany(e,n,s){ce(e.length,n?.limit,"patchMany");for(const u of e)await U.patch(u.id,u.patch,s);return{patched:e.length}},async patchWhere(e,n,s){const l=(await(z(e,"patchWhere")??U).findMany(e,{where:n.where})).page.map(c=>({id:String(c._id),patch:n.patch}));if(ce(l.length,s?.limit,"patchWhere"),U.patchMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await U.patchMany(l,s),{patched:l.length}},query(e){const n=z(e,"query");return n?(R(e,H),n.query(e)):cr(i,t,e,F,s=>{s?v(s):R(e,H)},s=>{$||S?.recordRead(s)})},async rank(e,n,s){const u=z(e,"rank");if(u)return R(e,H),u.rank(e,n,s);F(e,n,"rank");const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);const l=h.rankIndexes?.find(G=>G.name===n);if(!l)throw new y("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(st(e,h,l),s.restrictsCounts)throw new Pe(e);R(e,H),We(e,l);const c=typeof s.row=="string"?s.row:s.row._id;if(!c)return null;const d=ft(e,l.name),w=l.sortBy.map((G,Se)=>ht(Se)),A=w.map(G=>_n(G)).join(", "),p=B(i,r`SELECT ${r.identifier("__partition__")}, ${r.raw(A)} FROM ${r.identifier(d)} WHERE ${r.identifier("__id__")} = ${c}`).toArray(),[x]=p;if(x===void 0)return null;let D=x.__partition__;const P=J(s.baseWhere,s.where);He(P,t,e,"rank");const q=hn(l,P);if(q){const G=wn(l.partitionBy??[],q);if(G!==D)return null;D=G}const I=w.map(G=>x[G]),{before:Q,total:Y}=vt(i,d,w,l.sortBy,D,I,c);return{position:Q+1,total:Y}},async rankBefore(e,n,s){if(ie(e))throw new y("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const h=u.rankIndexes?.find(w=>w.name===n);if(!h)throw new y("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(s.restrictsCounts)throw new Pe(e);R(e,H),We(e,h);const l=ft(e,h.name),c=h.sortBy.map((w,A)=>ht(A)),d=h.sortBy.map((w,A)=>oe(s.sortValues[A]??null));return vt(i,l,c,h.sortBy,s.partitionKey,d,s.rowId)},async rankPage(e,n,s={}){He(J(s.baseWhere,s.where),t,e,"rankPage");const u=z(e,"rankPage");if(u)return R(e,H),u.rankPage(e,n,s);F(e,n,"rank");const{continueCursor:h,hasMore:l,rows:c}=dt(at,e,n,s);return{continueCursor:h,isDone:!l,page:c.map(d=>d.doc)}},async rankPageRows(e,n,s={}){He(J(s.baseWhere,s.where),t,e,"rankPage"),F(e,n,"rank");const{directions:u,hasMore:h,rows:l}=dt(at,e,n,s);return{directions:u,hasMore:h,rows:l}},async restore(e,n){const s=ne(e,n);if(!s){const l=n===void 0?C:void 0;if(l?.restore){await l.restore(e);return}throw new y("INTERNAL",`document not found: ${e}`)}const u=t.tables[s.tableName]?.softDeleteMode?.field;if(!u)throw new y("INTERNAL",`ctx.db.restore: table "${s.tableName}" is not a .softDelete() table`);const h=s.row[u]!==null&&s.row[u]!==void 0;await U.patch(e,{[u]:null},n),h&&he(s.tableName,e,void 0,s.row)},async replace(e,n,s,u){const h=ne(e,s);if(!h){const x=s===void 0?C:void 0;if(x){M(n),await x.replace(e,n,void 0,u);return}throw new y("INTERNAL",`document not found: ${e}`)}const{docJson:l,row:c,tableName:d}=h,w=t.tables[d];if(!w)throw new y("INTERNAL",`unknown table: ${d}`);At("replace",n);const A=u?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:m(),p={...n,...E(d),_creationTime:A,_id:e};_t(w,n,p,O),Ne(w,p),Z(d,"before","update")&&await ee("before","update",{doc:{...p},id:e,op:"update",previous:c,table:d}),ue(d),fe(d),Me(i,d,r`UPDATE ${r.identifier(d)} SET _creationTime = ${A}, ${r.identifier(K)} = ${se(p)} WHERE id = ${e} AND ${r.identifier(K)} = ${l}`),me(d,e,p,c),Ee(d,e,p),ye(d,c,p),he(d,e,c,p),j?.invalidate(d,e,T(d,c,p)),le(d,e,"update",p),a({indexKeys:T(d,c,p),key:e,op:"update",row:p,table:d}),Z(d,"after","update")&&await ee("after","update",{doc:p,id:e,op:"update",previous:c,table:d}),await N({doc:p,id:e,op:"update",table:d})},async wipeShard(e){const n=new Set(e?.exclude),s=e?.tables,u=Object.entries(t.tables).filter(([d,w])=>n.has(d)||s!==void 0&&!s.includes(d)?!1:w.shardMode?.kind!=="global").map(([d])=>d);if(s!==void 0){for(const d of s)if(!t.tables[d])throw new y("INTERNAL",`wipeShard: unknown table: ${d}`)}const h={};let l=0;const{deleteAll:c}=U;if(c===void 0)throw new y("INTERNAL","wipeShard: this writer has no deleteAll");for(const d of u){const w=await c(d,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[d]=w.deleted,l+=w.deleted}return{deleted:l,tables:h}}},Pt={db:U,scheduler:k};return o.enforceRls===!0?mn(U,t,(e,n)=>ne(e,n)?.tableName,(e,n)=>Ut(e,n)):U};export{zr as CDC_LOG_TABLE,fo as CLIENT_WATERMARK_TABLE,$o as GLOBAL_SHAPE_SNAPSHOT_TABLE,_o as IDEMPOTENCY_TABLE,or as NotUniqueError,bo as SEARCH_STATE_TABLE,ho as advanceClientWatermark,Jr as applyCdcChanges,Un as assertValidClientId,jr as backfillAggregateIndexes,Kr as backfillRankIndexes,Or as backfillSearchIndexes,Vr as bumpCdcEpoch,Yr as cdcCanVouchFor,Xr as cdcSeqLeavingRows,Zr as cdcTouchesTables,eo as cdcTrimmedError,to as compactCdcDocs,Gr as createShardCtxDb,no as cursorBelowRetainedFloor,yo as deleteGlobalShapeSnapshot,Eo as deleteGlobalShapeSnapshotsForConnection,wo as migrateClientWatermark,mo as migrateGlobalShapeSnapshot,ro as minCdcReplayableSeq,oo as minCdcSeq,Rt as normalizeIdStructurally,io as readCdcChangeKeys,so as readCdcChanges,co as readCdcCursor,ao as readCdcEpoch,po as readClientWatermark,So as readGlobalShapeSnapshot,Ao as readIdempotent,xo as runShardMigrations,ko as selectShapeMembers,Lo as selectShapeRows,lo as trimCdcChanges,vo as trimIdempotent,Ro as writeGlobalShapeSnapshot,Io as writeIdempotent};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import{runSql as o,orNull as a,decodeJsonColumn as _}from"./runDrizzle-it6rL9bR.mjs";const s="__lunora_queue_messages",n=500,E=128*1024,T="… [truncated by the dev queue catcher]",c="[unserializable message body]",R=e=>{if(e===void 0)return"null";try{const r=JSON.stringify(e);return r.length>E?JSON.stringify(`${r.slice(0,E)}${T}`):r}catch{return JSON.stringify(c)}},g=e=>typeof e=="string"&&(e===c||e.endsWith(T)),u=e=>{o(e,`CREATE TABLE IF NOT EXISTS "${s}" (
|
|
2
|
+
id TEXT PRIMARY KEY,
|
|
3
|
+
captured_at INTEGER NOT NULL,
|
|
4
|
+
message_id TEXT NOT NULL,
|
|
5
|
+
queue TEXT NOT NULL,
|
|
6
|
+
export_name TEXT,
|
|
7
|
+
body TEXT NOT NULL,
|
|
8
|
+
attempts INTEGER NOT NULL,
|
|
9
|
+
outcome TEXT NOT NULL,
|
|
10
|
+
error TEXT,
|
|
11
|
+
dead_lettered INTEGER NOT NULL,
|
|
12
|
+
message_ts INTEGER NOT NULL
|
|
13
|
+
)`)},p=(e,r,d)=>{u(e);for(const t of r)o(e,`INSERT INTO "${s}" (id, captured_at, message_id, queue, export_name, body, attempts, outcome, error, dead_lettered, message_ts)
|
|
14
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,crypto.randomUUID(),d,t.messageId,t.queue,a(t.exportName),R(t.body),t.attempts,t.outcome,a(t.error),t.deadLettered===!0?1:0,t.timestamp);return o(e,`DELETE FROM "${s}"
|
|
15
|
+
WHERE id NOT IN (
|
|
16
|
+
SELECT id FROM "${s}" ORDER BY captured_at DESC, id DESC LIMIT ?
|
|
17
|
+
)`,n),{recorded:r.length}},i=e=>({attempts:e.attempts,body:_(e.body),capturedAt:e.captured_at,deadLettered:e.dead_lettered===1,error:e.error??void 0,exportName:e.export_name??void 0,id:e.id,messageId:e.message_id,outcome:e.outcome,queue:e.queue,timestamp:e.message_ts}),y=(e,r={})=>{u(e);const d=Math.min(Math.max(r.limit??100,1),n),t=typeof r.queue=="string"&&r.queue.length>0?r.queue:void 0,m=t===void 0?"":"WHERE queue = ?",N=t===void 0?[d]:[t,d];return{entries:o(e,`SELECT * FROM "${s}" ${m} ORDER BY captured_at DESC, id DESC LIMIT ?`,...N).toArray().map(L=>i(L))}},S=(e,r)=>{u(e);const t=o(e,`SELECT * FROM "${s}" WHERE id = ? LIMIT 1`,r).toArray()[0];return t===void 0?void 0:i(t)},U=e=>(u(e),o(e,`DELETE FROM "${s}"`),{cleared:!0});export{E as MAX_BODY_CHARS,n as QUEUE_RETENTION,s as QUEUE_TABLE,U as clearQueueMessages,u as ensureQueueTable,g as isLossyBody,S as readQueueMessageById,y as readQueueMessages,p as recordQueueMessages};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{matchesStaticWhere as a}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{compareStrings as l}from"./aggregateTableName-Cy5e03oz.mjs";import{serializeSqlValue as f}from"./serializeSqlValue-DbI1VQYM.mjs";const c=Symbol("not-resolvable"),y=r=>{if(r!==null&&typeof r=="object"&&!Array.isArray(r)){const t=Object.keys(r);return t.length===1&&t[0]==="eq"?r.eq:c}return r},m=(r,t)=>{if(r.length===0)return"";const o={};for(const n of r.toSorted(l))o[n]=t[n]??null;return JSON.stringify(o)},k="__id__",d=r=>`__sort_k${String(r)}__`,h=(r,t)=>{const o=r.partitionBy??[],n=t??{};for(const e of Object.keys(n))if(e==="AND"||e==="OR"||e==="NOT")return;const s={};for(const e of o)if(e in n){const i=y(n[e]);if(i===c)return;s[e]=i}else if(r.where&&e in r.where)s[e]=r.where[e];else return;return s},S=(r,t)=>`${r}__rank_${t}`,K=(r,t)=>({partitionKey:m(r.partitionBy??[],t),rowId:t._id,sortValues:r.sortBy.map(o=>f(t[o.field]??null))}),N=a;export{k as RANK_TIEBREAK,m as encodePartitionKey,N as matchesRankStaticWhere,K as rankKeyFromDoc,S as rankTableName,h as resolveRankPartition,d as sortColumnName};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import{sql as t}from"drizzle-orm";import{runDrizzle as o}from"./runDrizzle-it6rL9bR.mjs";const a="__reactor_state",c=[["runs","runs INTEGER NOT NULL DEFAULT 0"],["suppressed","suppressed INTEGER NOT NULL DEFAULT 0"],["errors","errors INTEGER NOT NULL DEFAULT 0"],["last_ran_at","last_ran_at INTEGER NOT NULL DEFAULT 0"],["last_error","last_error TEXT"]],O=r=>{o(r,t`CREATE TABLE IF NOT EXISTS ${t.identifier(a)} (
|
|
2
|
+
path TEXT PRIMARY KEY,
|
|
3
|
+
digest TEXT NOT NULL,
|
|
4
|
+
tables TEXT NOT NULL,
|
|
5
|
+
runs INTEGER NOT NULL DEFAULT 0,
|
|
6
|
+
suppressed INTEGER NOT NULL DEFAULT 0,
|
|
7
|
+
errors INTEGER NOT NULL DEFAULT 0,
|
|
8
|
+
last_ran_at INTEGER NOT NULL DEFAULT 0,
|
|
9
|
+
last_error TEXT
|
|
10
|
+
)`);const e=new Set(o(r,t`PRAGMA table_info(${t.identifier(a)})`).toArray().map(s=>s.name));for(const[s,i]of c)e.has(s)||o(r,t`ALTER TABLE ${t.identifier(a)} ADD COLUMN ${t.raw(i)}`)},R=r=>{if(typeof r=="string")try{const e=JSON.parse(r);return Array.isArray(e)&&e.every(s=>typeof s=="string")?e:void 0}catch{return}},T=r=>typeof r=="number"&&Number.isFinite(r)?r:0,d=r=>({digest:r.digest,...typeof r.last_error=="string"&&r.last_error.length>0?{lastError:r.last_error}:{},lastRanAt:T(r.last_ran_at),stats:{errors:T(r.errors),runs:T(r.runs),suppressed:T(r.suppressed)},tables:R(r.tables)}),l="path, digest, tables, runs, suppressed, errors, last_ran_at, last_error",f=(r,e)=>{const[s]=o(r,t`SELECT ${t.raw(l)} FROM ${t.identifier(a)} WHERE path = ${e}`);if(!(s===void 0||typeof s.digest!="string"))return d(s)},U=r=>o(r,t`SELECT ${t.raw(l)} FROM ${t.identifier(a)} ORDER BY path`).toArray().filter(e=>typeof e.digest=="string").map(e=>({path:e.path,state:d(e)})),g=(r,e,s)=>{const{digest:i,error:p,now:u,result:n,tables:E}=s,L=i??"",N=E===void 0?"":JSON.stringify([...E]),_=p??null;o(r,t`INSERT INTO ${t.identifier(a)} (path, digest, tables, runs, suppressed, errors, last_ran_at, last_error)
|
|
11
|
+
VALUES (
|
|
12
|
+
${e},
|
|
13
|
+
${L},
|
|
14
|
+
${N},
|
|
15
|
+
${n==="ran"?1:0},
|
|
16
|
+
${n==="suppressed"?1:0},
|
|
17
|
+
${n==="error"?1:0},
|
|
18
|
+
${u},
|
|
19
|
+
${_}
|
|
20
|
+
)
|
|
21
|
+
ON CONFLICT(path) DO UPDATE SET
|
|
22
|
+
digest = ${i===void 0?t.raw(`${a}.digest`):t`excluded.digest`},
|
|
23
|
+
tables = ${E===void 0?t.raw(`${a}.tables`):t`excluded.tables`},
|
|
24
|
+
runs = ${t.raw(`${a}.runs`)} + ${n==="ran"?1:0},
|
|
25
|
+
suppressed = ${t.raw(`${a}.suppressed`)} + ${n==="suppressed"?1:0},
|
|
26
|
+
errors = ${t.raw(`${a}.errors`)} + ${n==="error"?1:0},
|
|
27
|
+
last_ran_at = excluded.last_ran_at,
|
|
28
|
+
last_error = ${n==="error"?t`excluded.last_error`:t.raw("NULL")}`)},S=(r,e)=>r?.tables===void 0?!0:r.tables.some(s=>e.has(s));export{a as REACTOR_STATE_TABLE,U as listReactorStates,O as migrateReactorState,S as reactorNeedsRun,f as readReactorState,g as writeReactorState};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const t="__relationExists";export{t as RELATION_EXISTS_KEY};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const o="__lunora_reproject__",e=t=>`${o}${t}`,n=t=>{if(!t.startsWith(o))return;const r=t.slice(o.length);return r===""?void 0:r};export{o as REPROJECTION_MIGRATION_PREFIX,e as reprojectionMigrationId,n as reprojectionMigrationTable};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";const p=Symbol.for("lunora.ctxdb.rls-unwrap");class R extends g{table;constructor(a){super("RLS_REQUIRED",`ctx.db access to "${a}" is denied: the schema is marked .rls("required"), so this table is protected. Apply RLS with .use(rls(policies)) in the procedure, or mark the table .public() to opt it out.`,{name:"RlsRequiredError"}),this.table=a}}const S=o=>Object.entries(o.tables).filter(([,a])=>a.shardMode?.kind!=="global").map(([a])=>a),M=(o,a,l)=>{const u=a?.tables,n=new Set(a?.exclude);for(const d of o)(u===void 0||u.includes(d))&&!n.has(d)&&l(d)},m=["aggregate","count","deleteAll","findFirst","findFirstOrThrow","findMany","groupBy","insert","insertMany","insertManyUnsafe","query","rank","rankBefore","rankPage","rankPageRows"],v=(o,a,l,u)=>{if(a.rlsMode!=="required")return o;const n=o,d=r=>{const t=a.tables[r];return t!==void 0&&t.isPublic!==!0},s=r=>{if(d(r))throw new R(r)},c=async(r,t)=>{if(t!==void 0){s(t);return}const e=await l(r);e!==void 0&&s(e)},h=async(r,t)=>{if(t!==void 0){s(t);return}if(!u){for(const i of r)await c(i,t);return}const e=await u([...new Set(r)],t);for(const i of r){const y=e.get(i);y!==void 0&&s(y)}},f={...o,[p]:o,delete:async(r,t,e)=>(await c(r,t),n.delete(r,t,e)),deleteMany:async(r,t,e)=>(await h(r,e),n.deleteMany(r,t,e)),deleteWhere:n.deleteWhere?async(r,t,e)=>(s(r),await n.deleteWhere?.(r,t,e)):void 0,get:async(r,t)=>(await c(r,t),n.get(r,t)),lookupById:async(r,t)=>(await c(r,t),n.lookupById?.(r,t)??null),patch:async(r,t,e)=>(await c(r,e),n.patch(r,t,e)),patchMany:async(r,t,e)=>(await h(r.map(i=>i.id),e),n.patchMany(r,t,e)),patchWhere:n.patchWhere?async(r,t,e)=>(s(r),await n.patchWhere?.(r,t,e)):void 0,replace:async(r,t,e,i)=>(await c(r,e),n.replace(r,t,e,i)),restore:async(r,t)=>(await c(r,t),n.restore?.(r,t))},w=n;for(const r of m){const t=w[r];typeof t=="function"&&(f[r]=(e,...i)=>(s(e),t.call(n,e,...i)))}if(n.wipeShard){const{wipeShard:r}=n;f.wipeShard=t=>(M(S(a),t,s),r.call(n,t))}return f};export{p as RLS_UNWRAP_SYMBOL,R as RlsRequiredError,v as guardWriter};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{stableWireKey as b}from"./stableWireKey-DSCJB6E7.mjs";import{depKey as l,SCAN_DEP as y}from"./SCAN_DEP-D7qE3iUe.mjs";import{e as g}from"./estimate-bytes-CzG5x1f8.mjs";import{keysTouchRanges as p}from"./buildIndexRange-CBKQmHSS.mjs";import{stableStringify as A}from"./stableStringify-G9OF5wcs.mjs";const h=(o,t,s)=>{let e=o.get(t);return e===void 0&&(e=s(),o.set(t,e)),e},m=1e3,x=4*1024*1024;class w{entries=new Map;tableIndex=new Map;rangeIndex=new Map;totalBytes=0;hits=0;misses=0;evictions=0;maxEntries;maxBytes;now;monotonic=0;constructor(t={}){this.maxEntries=t.maxEntries??m,this.maxBytes=t.maxBytes??x,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 r=await e(),c=g(r);if(c===void 0)return r;const d=i(),f={bytes:c,deps:s,ranges:d,lastUsed:this.now(),result:r,subscribers:new Set};this.entries.set(t,f),this.totalBytes+=c;for(const a of s)h(this.tableIndex,a,()=>new Set).add(t);for(const a of d){const u=h(this.rangeIndex,a.table,()=>new Map);h(u,a,()=>new Set).add(t)}return this.evict(),r}invalidate(t,s,e){const i=[];return this.collectAndDrop(l(t,s),i),this.collectAndDrop(l(t,y),i),this.dropRangeDeps(t,e,i),i}invalidateTable(t){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.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,r]of i)p([n],s)&&this.dropKeys(r,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 z=(o,t,s)=>`${s??"\0anon"}\0${o}:${b(t)}`;export{w as ReactiveCache,z as reactiveCacheKey,A as stableStringify,b as stableWireKey};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const r="*scan",t=(e,c)=>`${e}:${c}`,o=e=>{const c=e.indexOf(":");return c===-1?e:e.slice(0,c)},s=()=>{const e=new Set;return{collect(){return e},recordRead(c,n){e.add(t(c,n))}}};export{r as SCAN_DEP,s as createDependencyTracker,t as depKey,o as tableFromDepKey};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{quoteIdentifier as i}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as n}from"./runDrizzle-it6rL9bR.mjs";const p="__lunora_schema_history",c=50,e=i(p),E=t=>({appliedAt:typeof t.applied_at=="number"?t.applied_at:0,hash:typeof t.hash=="string"?t.hash:"",seq:typeof t.seq=="number"?t.seq:0}),a=t=>{n(t,`CREATE TABLE IF NOT EXISTS ${e} (
|
|
2
|
+
hash TEXT PRIMARY KEY,
|
|
3
|
+
seq INTEGER NOT NULL,
|
|
4
|
+
snapshot_json TEXT NOT NULL,
|
|
5
|
+
applied_at INTEGER NOT NULL
|
|
6
|
+
)`)},S=t=>{n(t,`DELETE FROM ${e} WHERE hash NOT IN (SELECT hash FROM ${e} ORDER BY seq DESC LIMIT ?)`,c)},I=(t,s,r,h=Date.now())=>{if(s===""||r==="")return!1;try{if(a(t),n(t,`SELECT hash FROM ${e} WHERE hash = ? LIMIT 1`,s).toArray().length>0)return!1;const[o]=n(t,`SELECT COALESCE(MAX(seq), 0) + 1 AS next FROM ${e}`).toArray(),T=typeof o?.next=="number"?o.next:1;return n(t,`INSERT INTO ${e} (hash, seq, snapshot_json, applied_at) VALUES (?, ?, ?, ?) ON CONFLICT(hash) DO NOTHING`,s,T,r,h),S(t),!0}catch{return!1}},_=t=>{try{return a(t),n(t,`SELECT hash, seq, applied_at FROM ${e} ORDER BY seq DESC`).toArray().map(s=>E(s))}catch{return[]}},u=(t,s)=>{try{a(t);const[r]=n(t,`SELECT hash, seq, applied_at, snapshot_json FROM ${e} WHERE hash = ? LIMIT 1`,s).toArray();return r===void 0?void 0:{...E(r),snapshotJson:typeof r.snapshot_json=="string"?r.snapshot_json:""}}catch{return}};export{c as SCHEMA_HISTORY_MAX_VERSIONS,_ as readSchemaHistory,u as readSchemaVersion,I as recordSchemaVersion};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{sql as i}from"drizzle-orm";import{runDrizzle as o}from"./runDrizzle-it6rL9bR.mjs";const n="__lunora_search_state",s=e=>{o(e,i`CREATE TABLE IF NOT EXISTS ${i.identifier(n)} (${i.identifier("companion")} TEXT PRIMARY KEY, ${i.identifier("cursor")} TEXT, ${i.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${i.identifier("profile")} TEXT)`);try{o(e,i`ALTER TABLE ${i.identifier(n)} ADD COLUMN ${i.identifier("profile")} TEXT`)}catch{}},$=e=>e===1||e===!0||e==="1",l=(e,t)=>{const r=o(e,i`SELECT ${i.identifier("cursor")}, ${i.identifier("done")}, ${i.identifier("profile")} FROM ${i.identifier(n)} WHERE ${i.identifier("companion")} = ${t}`).toArray()[0];return r?{cursor:r.cursor??void 0,done:$(r.done),profile:r.profile??void 0}:{cursor:void 0,done:!1,profile:void 0}},a=(e,t,d,r,f)=>{const c=d??null;o(e,i`INSERT INTO ${i.identifier(n)} (${i.identifier("companion")}, ${i.identifier("cursor")}, ${i.identifier("done")}, ${i.identifier("profile")}) VALUES (${t}, ${c}, ${r?1:0}, ${f}) ON CONFLICT (${i.identifier("companion")}) DO UPDATE SET ${i.identifier("cursor")} = excluded.${i.identifier("cursor")}, ${i.identifier("done")} = excluded.${i.identifier("done")}, ${i.identifier("profile")} = excluded.${i.identifier("profile")}`)};export{n as SEARCH_STATE_TABLE,s as migrateSearchState,l as readSearchBackfillState,a as writeSearchBackfillState};
|