@lunora/shard-engine 1.0.0-alpha.6 → 1.0.0-alpha.8
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.mjs +1 -1
- package/dist/packem_shared/AGG_COUNT-D-wORk0b.mjs +1 -0
- package/dist/packem_shared/CDC_LOG_TABLE-q7MSIAzR.mjs +8 -0
- package/dist/packem_shared/NotUniqueError-CjdcqrlK.mjs +1 -0
- package/dist/packem_shared/backfillAggregateIndexes-u6_SblD0.mjs +1 -0
- package/dist/packem_shared/{createCompanionSync-DWK0Vlg1.mjs → createCompanionSync-DCfEbb9_.mjs} +1 -1
- package/dist/packem_shared/{defineEngineContractSuite-1f7OcQND.mjs → defineEngineContractSuite-C1e_JZp1.mjs} +1 -1
- package/dist/packem_shared/{isSoftDeleted-B-SXkGUo.mjs → isSoftDeleted-CvcsqA59.mjs} +1 -1
- package/dist/packem_shared/{materializeExternalRows-DOQJV9p2.mjs → materializeExternalRows-DmYwTW_A.mjs} +1 -1
- package/dist/packem_shared/{runShardMigrations-CPxqCh3O.mjs → runShardMigrations-MWWmpqzb.mjs} +3 -3
- package/dist/packem_shared/{selectExpiredIds-FzhIEeG1.mjs → selectExpiredIds-BnHyOKtN.mjs} +1 -1
- package/dist/packem_shared/{selectShapeMemberIds-DvE7K6zG.mjs → selectShapeMemberIds-TPdvxh2A.mjs} +1 -1
- package/package.json +2 -2
- package/dist/packem_shared/AGG_COUNT-BWXe3gtQ.mjs +0 -1
- package/dist/packem_shared/CDC_LOG_TABLE-BnqlH2eZ.mjs +0 -8
- package/dist/packem_shared/NotUniqueError-Qrtwm7S6.mjs +0 -1
- package/dist/packem_shared/backfillAggregateIndexes-BHiewuB-.mjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-
|
|
1
|
+
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-C1e_JZp1.mjs";export{t as defineEngineContractSuite};
|
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-Qrtwm7S6.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-vj2G8OR6.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-C6QAa7MG.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-DFsdtPjD.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-D0oc40p6.mjs";import{RLS_UNWRAP_SYMBOL as Sa,RlsRequiredError as ua,guardWriter as xa}from"./packem_shared/RLS_UNWRAP_SYMBOL-CBYPlYBb.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-CCZ-8wjm.mjs";import{mergeChangedKeys as Ha,recordChangedKeys as Xa,writeTouchesMemo as Qa}from"./packem_shared/mergeChangedKeys-BXtUgIPW.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-BH5q0Ror.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 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-CjdcqrlK.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as K,backfillSearchIndexes as q,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-u6_SblD0.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-q7MSIAzR.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-DCfEbb9_.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-TPdvxh2A.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-D-wORk0b.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-DmYwTW_A.mjs";import{isSoftDeleted as Ir,isSourceDue as _r,pullExternalSourceIncrementalTick as Rr,pullExternalSourceTick as Lr}from"./packem_shared/isSoftDeleted-CvcsqA59.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-vj2G8OR6.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-C6QAa7MG.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-DFsdtPjD.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-D0oc40p6.mjs";import{RLS_UNWRAP_SYMBOL as Sa,RlsRequiredError as ua,guardWriter as xa}from"./packem_shared/RLS_UNWRAP_SYMBOL-CBYPlYBb.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-CCZ-8wjm.mjs";import{mergeChangedKeys as Ha,recordChangedKeys as Xa,writeTouchesMemo as Qa}from"./packem_shared/mergeChangedKeys-BXtUgIPW.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-BH5q0Ror.mjs";import{hasTrigger as at,runTriggers as tt}from"./packem_shared/hasTrigger-CbkOHExZ.mjs";import{selectExpiredIds as lt}from"./packem_shared/selectExpiredIds-BnHyOKtN.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-MWWmpqzb.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{sql as i}from"drizzle-orm";import{c as l,f}from"./wire-codec-Ctnni0h6.mjs";import{runDrizzle as n}from"./runDrizzle-GKR3y97k.mjs";import{serializeSqlValue as G}from"./serializeSqlValue-DnpyaLcw.mjs";const s="__doc__",N=e=>JSON.stringify(f(e)),$=e=>l(JSON.parse(e)),O=(e,t)=>`${e}__geo_${t}`,d=e=>`"${e.replaceAll('"','""')}"`,T=e=>e==="_id"||e==="id"?"id":e==="_creationTime"?"_creationTime":`json_extract(${s}, '$.${e.replaceAll("'","''")}')`,y=e=>i.raw(T(e)),u=(e,t)=>{const r=d(e);return t==="_id"||t==="id"?`${r}.id`:t==="_creationTime"?`${r}._creationTime`:`json_extract(${r}.${s}, '$.${t.replaceAll("'","''")}')`},D=(e,t)=>i.raw(u(e,t)),U=(e,t,r,o)=>i`CREATE ${o?i`UNIQUE `:i``}INDEX IF NOT EXISTS ${i.identifier(e)} ON ${i.identifier(t)} (${r})`,_=i.identifier("__key__"),m=i.identifier("__value__"),p=i.identifier("__count__"),b=(e,t,r,o,a)=>i`INSERT INTO ${i.identifier(e)} (${_}, ${m}, ${p}) VALUES (${t}, ${r}, ${o}) ON CONFLICT(${_}) DO UPDATE SET ${a}`,g=e=>{const t=[];for(const[r,o]of Object.entries(e.shape)){const a=o._meta?.column;a&&t.push([r,a])}return t},E=e=>{if(!e)return;const t=e[s];let r;typeof t=="string"?r=$(t):t&&typeof t=="object"?r=t:r={};const{id:o}=e;typeof o=="string"&&(r._id=o);const a=e._creationTime;return typeof a=="number"&&(r._creationTime=a),r},h=e=>{try{return E(e)}catch{return}},c=new WeakMap,q=e=>{const t=c.get(e);if(t!==void 0)return t;let r;try{n(e,i`CREATE VIRTUAL TABLE IF NOT EXISTS ${i.identifier("__lunora_fts_probe")} USING fts5(x)`),r=!0}catch{r=!1}finally{try{n(e,i`DROP TABLE IF EXISTS ${i.identifier("__lunora_fts_probe")}`)}catch{}}return c.set(e,r),r};export{p as AGG_COUNT,_ as AGG_KEY,m as AGG_VALUE,s as DOC_COLUMN,b as aggUpsertSql,U as createIndexSql,$ as decodeDocJson,N as encodeDocJson,O as geoTableName,q as isFtsAvailable,T as jsonPath,y as jsonPathSql,u as qualifiedJsonPath,D as qualifiedJsonPathSql,d as quoteIdentifier,E as rowToDocument,G as serializeSqlValue,g as tableColumns,h as tryRowToDocument};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-GKR3y97k.mjs";import{encodeDocJson as l,decodeDocJson as C}from"./AGG_COUNT-D-wORk0b.mjs";import{ConflictError as f}from"./ConflictError-C8GtJmjS.mjs";const c="__cdc_log",I=t=>{a(t,e`CREATE TABLE IF NOT EXISTS ${e.identifier(c)} (
|
|
2
|
+
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
3
|
+
ts REAL NOT NULL,
|
|
4
|
+
${e.identifier("table")} TEXT NOT NULL,
|
|
5
|
+
id TEXT NOT NULL,
|
|
6
|
+
op TEXT NOT NULL,
|
|
7
|
+
doc TEXT
|
|
8
|
+
)`)},m=(t,i,r,E,s,d)=>{const o=d===void 0?null:l(d);a(t,e`INSERT INTO ${e.identifier(c)} (ts, ${e.identifier("table")}, id, op, doc) VALUES (${i}, ${r}, ${E}, ${s}, ${o})`)},O=(t,i={})=>{const r=i.sinceSeq??0,E=Math.max(1,Math.min(i.limit??1e3,1e4)),s=i.tables&&i.tables.size>0?e` AND ${e.identifier("table")} IN (${e.join([...i.tables].map(o=>e`${o}`),e`, `)})`:e``,d=a(t,e`SELECT seq, ts, ${e.identifier("table")}, id, op, doc FROM ${e.identifier(c)} WHERE seq > ${r}${s} ORDER BY seq ASC LIMIT ${E}`).toArray().map(o=>{const T={id:o.id,op:o.op,seq:o.seq,table:o.table,ts:o.ts};return o.doc===null?T:{...T,doc:C(o.doc)}});return{changes:d,cursor:d.at(-1)?.seq??r}},q=(t,i)=>{a(t,e`DELETE FROM ${e.identifier(c)} WHERE seq <= ${i}`)},S=t=>{const i=a(t,e`SELECT seq FROM sqlite_sequence WHERE name = ${c}`).toArray()[0]?.seq;return typeof i=="number"?i:a(t,e`SELECT MAX(seq) AS seq FROM ${e.identifier(c)}`).toArray()[0]?.seq??0},h=t=>a(t,e`SELECT MIN(seq) AS seq FROM ${e.identifier(c)}`).toArray()[0]?.seq??void 0,n="__cdc_meta",p=t=>{a(t,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (id INTEGER PRIMARY KEY CHECK (id = 1), epoch TEXT NOT NULL)`)},u=t=>{p(t);const i=a(t,e`SELECT epoch FROM ${e.identifier(n)} WHERE id = 1`).toArray()[0]?.epoch;if(typeof i=="string"&&i.length>0)return i;const r=crypto.randomUUID();return a(t,e`INSERT INTO ${e.identifier(n)} (id, epoch) VALUES (1, ${r})`),r},M=t=>{p(t);const i=crypto.randomUUID();return a(t,e`INSERT INTO ${e.identifier(n)} (id, epoch) VALUES (1, ${i}) ON CONFLICT(id) DO UPDATE SET epoch = excluded.epoch`),i},$=async(t,i)=>{if(i.op==="delete"){await t.delete(i.id,i.table);return}const r=i.doc??{};try{await t.insert(i.table,r,{allowExplicitId:!0})}catch(E){if(!(E instanceof f))throw E;const s={};for(const[d,o]of Object.entries(r))d!=="_id"&&(s[d]=o);await t.replace(i.id,s,void 0,{allowExplicitId:!0})}},b=async(t,i)=>{for(const r of i)await $(t,r)};export{c as CDC_LOG_TABLE,n as CDC_META_TABLE,m as appendCdcChange,b as applyCdcChanges,M as bumpCdcEpoch,I as migrateCdcLog,p as migrateCdcMeta,h as minCdcSeq,O as readCdcChanges,S as readCdcCursor,u as readCdcEpoch,q as trimCdcChanges};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as b}from"@lunora/errors";import{n as St,A as je,T as Se,y as _t,c as Rt}from"./FTS_COUNT_COLUMN-D1gY3wwZ-CZHdaRrd.mjs";import{sql as n}from"drizzle-orm";import{aggregateSqlFunction as _e,normalizeCountArgument as At,throwingScheduler as xt}from"./AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{encodeAggregateKey as Ce,readAggregateValue as ke,aggregateTableName as Le}from"./aggregateTableName-G-eXyjcz.mjs";import{mergeWhere as Q,CountRlsUnsupportedError as De,selectIndexForGroupBy as vt,selectIndexForCount as It,selectIndexForAggregate as Mt}from"./CountRlsUnsupportedError-B2WKJD9v.mjs";import{backfillSearchIndexesForTable as Ct}from"./backfillAggregateIndexes-u6_SblD0.mjs";import{backfillAggregateIndexes as $r,backfillRankIndexes as gr,backfillSearchIndexes as br}from"./backfillAggregateIndexes-u6_SblD0.mjs";import{appendCdcChange as kt}from"./CDC_LOG_TABLE-q7MSIAzR.mjs";import{CDC_LOG_TABLE as Er,applyCdcChanges as Nr,bumpCdcEpoch as Tr,minCdcSeq as Sr,readCdcChanges as _r,readCdcCursor as Rr,readCdcEpoch as Ar,trimCdcChanges as xr}from"./CDC_LOG_TABLE-q7MSIAzR.mjs";import{createCompanionSync as Lt}from"./createCompanionSync-DCfEbb9_.mjs";import{computeRankPage as et}from"./computeRankPage-IUSS-zIB.mjs";import{SCAN_DEP as B}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as F}from"./runDrizzle-GKR3y97k.mjs";import{DOC_COLUMN as P,encodeDocJson as se,quoteIdentifier as Dt,AGG_VALUE as Re,AGG_COUNT as We,AGG_KEY as Ae,jsonPathSql as z,rowToDocument as ce,tableColumns as wt,isFtsAvailable as Wt,tryRowToDocument as mt,geoTableName as Ot,qualifiedJsonPathSql as tt}from"./AGG_COUNT-D-wORk0b.mjs";import{coveringGeohashes as Ft,boundingBoxGeohashes as qt,pointInBoundingBox as Bt,haversineMeters as Ut}from"./GEO_DEFAULT_PRECISION-okRCkZ6r.mjs";import{NotFoundError as Pt}from"./NotFoundError-BhF7FeFr.mjs";import{normalizeOrderKeys as jt,buildSeekWhere as $t,decodeCursor as Be,applySelect as nt,encodeCursor as Ue,softDeleteScope as de,buildSeekBeforeWhere as Ht}from"./applySelect-B0CF8T7y.mjs";import{sortColumnName as rt,resolveRankPartition as Gt,encodePartitionKey as Kt,RANK_TIEBREAK as Qt,rankTableName as ot}from"./RANK_TIEBREAK-9NU5s_mi.mjs";import{indexKeysForRow as zt,buildIndexRange as Yt}from"./buildIndexRange-DFsdtPjD.mjs";import{assertFlatPredicate as Oe,resolveRelationPredicates as it}from"./DEFAULT_MAX_RELATION_KEYS-bq00btqV.mjs";import{runRowValidators as Fe,resolveWith as at,applyOnDelete as Vt,fanOutScalarCounts as Jt}from"./applyOnDelete-uFRC5p1d.mjs";import{guardWriter as Xt}from"./RLS_UNWRAP_SYMBOL-CBYPlYBb.mjs";import{createSystemReader as Zt}from"./createSystemReader-DcDcrtM3.mjs";import{ConflictError as $e}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as en}from"./hasTrigger-CbkOHExZ.mjs";import{compileWhereSql as ne}from"./compileWhereSql-BLcfs4QW.mjs";import{CLIENT_WATERMARK_TABLE as Ir,advanceClientWatermark as Mr,migrateClientWatermark as Cr,readClientWatermark as kr}from"./CLIENT_WATERMARK_TABLE-CXsSLU8D.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Dr,deleteGlobalShapeSnapshot as Wr,deleteGlobalShapeSnapshotsForConnection as Or,migrateGlobalShapeSnapshot as Fr,readGlobalShapeSnapshot as qr,writeGlobalShapeSnapshot as Br}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DX-6-gBP.mjs";import{IDEMPOTENCY_TABLE as Pr,readIdempotent as jr,trimIdempotent as Hr,writeIdempotent as Gr}from"./IDEMPOTENCY_TABLE-DjkEMp6w.mjs";import{runShardMigrations as Qr}from"./runShardMigrations-MWWmpqzb.mjs";import{SEARCH_STATE_TABLE as Yr}from"./SEARCH_STATE_TABLE-eLN8U5tz.mjs";import{selectShapeMemberIds as Jr,selectShapeRows as Xr}from"./selectShapeMemberIds-TPdvxh2A.mjs";import{serializeSqlValue as re}from"./serializeSqlValue-DnpyaLcw.mjs";const tn=o=>{const i=new TextEncoder().encode(o);let t="";for(const l of i)t+=String.fromCodePoint(l);return btoa(t)},nn=o=>{const i=atob(o),t=Uint8Array.from(i,l=>l.codePointAt(0)??0);return new TextDecoder().decode(t)},rn=()=>new b("BAD_REQUEST","invalid cursor"),st=16,lt=8,Z=1024,He=(o,i)=>i.query(o),on=(o,i,t)=>{const l=St(o,t);if(l.length===0)return 0;let c=0;for(const[p,m]of i.entries()){const R=p===i.length-1;let T=0;for(const $ of l)(R?$.startsWith(m):$===m)&&(T+=1);if(T===0)return 0;c+=T}return c},an=(o,i)=>{if(!i)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",l=(t.codePointAt(0)??0)+1;if(l>=55296&&l<=57343||l>1114111)return{exact:!0,lower:o,upper:o};const c=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:c+String.fromCodePoint(l)}},sn=(o,i,t)=>{const l={eq:(c,p)=>{if(!o.definition.filterFields?.includes(c))throw new b("INTERNAL",`field "${c}" is not a filter field of search index "${o.indexName}" on table "${i}"`);if(o.filters.length>=lt)throw new b("BAD_REQUEST",`search index "${o.indexName}" on table "${i}": at most ${String(lt)} .eq() filters are supported per search query`);return o.filters.push({field:c,value:p}),l},search:(c,p)=>{const m=o;if(c!==m.definition.field)throw new b("INTERNAL",`search index "${m.indexName}" on table "${i}" indexes "${m.definition.field}", not "${c}"`);const R=He(p,t).length;if(R>st)throw new b("BAD_REQUEST",`search index "${m.indexName}" on table "${i}": at most ${String(st)} search terms are supported (got ${String(R)})`);return m.field=c,m.query=p,m.hasQuery=!0,l}};return l},ln=o=>{if(o.length>Z)throw new b("BAD_REQUEST",`more than ${String(Z)} 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,Z),cn=o=>tn(`search:${String(o)}`),un=o=>{let i;try{i=nn(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 b("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");const i=Math.max(0,Math.floor(o.numItems)),t=o.cursor?un(o.cursor):0;if(t===void 0)throw rn();if(t+i>Z)throw new b("BAD_REQUEST",`search pagination reaches past the ${String(Z)}-document limit (offset ${String(t)} + ${String(i)} requested) — narrow the query or the filters instead`);return{numItems:i,offset:t}},hn=(o,i)=>{const t=i.offset+i.numItems,l=i.numItems>0&&o.length>t;return{continueCursor:l?cn(t):null,isDone:!l,page:o.slice(i.offset,t)}},pn=o=>{if(o===void 0)return Z+1;if(!Number.isFinite(o))return Z;const i=Math.max(0,Math.floor(o));if(i>Z)throw new b("BAD_REQUEST",`search returns at most ${String(Z)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},wn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,mn=o=>{if(!wn.test(o))throw new b("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},dt=50,gt=500,$n=128,le=(o,i,t)=>{const l=i??gt;if(o>l)throw new b("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(l)} (raise options.limit or chunk the call)`,{status:400})},gn=o=>{const i={eq:(t,l)=>(o.sqlConditions.push({comparator:"=",field:t,value:l}),i),gt:(t,l)=>(o.sqlConditions.push({comparator:">",field:t,value:l}),i),gte:(t,l)=>(o.sqlConditions.push({comparator:">=",field:t,value:l}),i),lt:(t,l)=>(o.sqlConditions.push({comparator:"<",field:t,value:l}),i),lte:(t,l)=>(o.sqlConditions.push({comparator:"<=",field:t,value:l}),i)};return i},bn=o=>Math.max(o,Z),yn=(o,i,t,l,c)=>{const p=He(t.query,je(t.definition.language));if(p.length===0)return[];const m=Rt(i,t.indexName),R=`${m}__vocab`,T=p.length-1,$=p.map((C,L)=>{const j=an(C,L===T),U=j.exact?n`${n.identifier("term")} = ${j.lower}`:n`${n.identifier("term")} >= ${j.lower} AND ${n.identifier("term")} < ${j.upper}`;return n`SELECT ${n.identifier("doc")}, ${n.raw(String(L))} AS ${n.identifier("__term__")}, COUNT(*) AS ${n.identifier("__n__")} FROM ${n.identifier(R)} WHERE ${U} GROUP BY ${n.identifier("doc")}`}),y=p.map((C,L)=>n`SUM(CASE WHEN u.${n.identifier("__term__")} = ${n.raw(String(L))} THEN u.${n.identifier("__n__")} ELSE 0 END)`),E=n`SELECT f.${n.identifier(Se)} AS ${n.identifier(Se)}, ${n.join(y,n` + `)} AS ${n.identifier("__score__")} FROM (${n.join($,n` UNION ALL `)}) u JOIN ${n.identifier(m)} f ON f.rowid = u.${n.identifier("doc")} GROUP BY f.${n.identifier(Se)} HAVING ${n.join(y.map(C=>n`${C} > 0`),n` AND `)}`,_=[];for(const C of t.filters)_.push(n`${z(C.field)} = ${re(C.value)}`);c&&_.push(c);let M=n`SELECT m.id, m._creationTime, m.${n.identifier(P)}, s.${n.identifier("__score__")} AS ${n.identifier("__score__")} FROM (${E}) s JOIN ${n.identifier(i)} m ON m.id = s.${n.identifier(Se)}`;_.length>0&&(M=n`${M} WHERE ${n.join(_,n` AND `)}`),M=n`${M} ORDER BY s.${n.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${n.raw(String(l))}`;const W=[];for(const C of F(o,M)){const L=mt(C);if(L){const j=C.__score__;W.push({document:L,score:typeof j=="number"?j:Number(j??0)})}}return W},En=(o,i,t,l,c)=>{const p=je(t.definition.language),m=He(t.query,p);if(m.length===0)return[];const R=[];for(const E of t.filters)R.push(n`${z(E.field)} = ${re(E.value)}`);c&&R.push(c);let T=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(i)}`;R.length>0&&(T=n`${T} WHERE ${n.join(R,n` AND `)}`),T=n`${T} ORDER BY _creationTime DESC, id ASC LIMIT ${n.raw(String(bn(l)))}`;const $=F(o,T).toArray(),y=[];for(const E of $){const _=mt(E);if(!_)continue;const M=on(_t(_,t.definition),m,p);M>0&&y.push({creationTime:typeof _._creationTime=="number"?_._creationTime:0,doc:_,id:typeof _._id=="string"?_._id:"",score:M})}return y.sort((E,_)=>_.score-E.score||_.creationTime-E.creationTime||E.id.localeCompare(_.id)),y.slice(0,l).map(E=>({document:E.doc,score:E.score}))},qe=(o,i,t,l)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new b("BAD_REQUEST",`geo index "${l}" on table "${t}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},Nn=(o,i)=>{const t=o,l={near:(c,p)=>{if(t.within)throw new b("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(qe(c,".near() point",i,t.indexName),!Number.isFinite(p)||p<=0)throw new b("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(p)}`);return t.near={point:{lat:c.lat,lng:c.lng},radiusMeters:p},l},within:c=>{if(t.near)throw new b("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(qe(c.sw,".within() sw corner",i,t.indexName),qe(c.ne,".within() ne corner",i,t.indexName),c.sw.lat>c.ne.lat)throw new b("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(c.sw.lng>c.ne.lng)throw new b("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:c.ne.lat,lng:c.ne.lng},sw:{lat:c.sw.lat,lng:c.sw.lng}},l}};return l},Tn=(o,i)=>{const t=o[i];if(t===null||typeof t!="object")return;const{lat:l,lng:c}=t;return typeof l=="number"&&typeof c=="number"?{lat:l,lng:c}:void 0},Sn=(o,i)=>{const t=Tn(o,i.definition.field);if(!t)return;const l=typeof o._creationTime=="number"?o._creationTime:0;if(i.near){const c=Ut(i.near.point,t);return c<=i.near.radiusMeters?{creationTime:l,distance:c}:void 0}return Bt(t,i.within)?{creationTime:l,distance:0}:void 0},bt=(o,i,t,l)=>{if(!t.near&&!t.within)throw new b("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const c=t.near?Ft(t.near.point,t.near.radiusMeters):qt(t.within),p=Ot(i,t.indexName),m=c.map(E=>n`(g.${n.identifier("__geohash__")} >= ${E} AND g.${n.identifier("__geohash__")} < ${`${E}{`})`),R=[n`(${n.join(m,n` OR `)})`];l&&R.push(l);const T=n`SELECT m.id, m._creationTime, m.${n.identifier(P)} FROM ${n.identifier(p)} g JOIN ${n.identifier(i)} m ON m.id = g.${n.identifier("__id__")} WHERE ${n.join(R,n` AND `)}`,$=F(o,T).toArray(),y=[];for(const E of $){const _=ce(E),M=_?Sn(_,t):void 0;_&&M&&y.push({creationTime:M.creationTime,distance:M.distance,doc:_})}return y.sort((E,_)=>E.distance-_.distance||_.creationTime-E.creationTime),y},_n=(o,i,t,l,c,p=()=>{})=>{const m=bt(o,i,t,c).map(R=>R.doc);return p(m.length),typeof l=="number"?m.slice(0,Math.max(0,Math.floor(l))):m},Rn=(o,i,t,l,c,p=()=>{})=>{const m=t.within!==void 0,R=bt(o,i,t,c).map(T=>({distanceMeters:m?null:T.distance,document:T.doc}));return p(R.length),R},An=(o,i,t,l,c,p=()=>{})=>{const{geo:m}=t;if(!m)throw new b("INTERNAL","runGeoTerminal called without a staged geo query");const R=t.inMemoryFilters.length>0,T=_n(o,i,m,R?void 0:c,l,p);if(!R)return T;const $=[];for(const y of T)if(t.inMemoryFilters.every(E=>E(y))&&($.push(y),typeof c=="number"&&$.length>=c))break;return $},xn=(o,i,t,l,c,p=()=>{})=>{const{geo:m}=t;if(!m)throw new b("INTERNAL","runGeoTerminalScored called without a staged geo query");const R=t.inMemoryFilters.length>0,T=Rn(o,i,m,R?void 0:c,l,p);if(!R)return T;const $=[];for(const y of T)t.inMemoryFilters.every(E=>E(y.document))&&$.push(y);return $},vn=(o,i,t,l,c,p,m=()=>{})=>{const R=[];for(const E of t.sqlConditions)R.push(n`${z(E.field)} ${n.raw(E.comparator)} ${re(E.value)}`);l&&R.push(l);let T=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(i)}`;R.length>0&&(T=n`${T} WHERE ${n.join(R,n` AND `)}`),T=n`${T} ORDER BY ${c}`,typeof p=="number"&&t.inMemoryFilters.length===0&&(T=n`${T} LIMIT ${n.raw(String(Math.max(0,Math.floor(p))))}`);const $=F(o,T).toArray();m($.length);const y=[];for(const E of $){const _=ce(E);if(_&&t.inMemoryFilters.every(M=>M(_))&&(y.push(_),typeof p=="number"&&y.length>=p))break}return y},ie={fieldRef:z,serialize:re},In=o=>{let i=0;const t=[],l={fieldRef:z,relationExists:c=>{const{childWhere:p,negated:m,parentTable:R,relation:T}=c,$=`__rel_${String(i)}`,y=t.at(-1)??R;i+=1,o(T.table,B);const E=T.kind==="one"?T.field:T.references,_=T.kind==="one"?T.references:T.field,M=n`${tt($,_)} = ${tt(y,E)}`;t.push($);const W=ne(p,l);t.pop();const C=W?n`${M} AND ${W}`:M,L=n`EXISTS (SELECT 1 FROM ${n.identifier(T.table)} AS ${n.identifier($)} WHERE ${C})`;return m?n`NOT ${L}`:L},serialize:re};return l},yt=o=>{const i=o.map(t=>n`${z(t.field)} ${n.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||i.push(n`${z("id")} ASC`),n.join(i,n`, `)},Mn={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},Cn=o=>{const i=o.order;return o.indexFields.length>0?o.indexFields.map(t=>({direction:i,field:t})):[{direction:i,field:"_creationTime"}]},kn=(o,i,t,l)=>{const c=o.sqlConditions.map(p=>({[p.field]:{[Mn[p.comparator]??"eq"]:p.value}}));if(t&&c.push($t(i,Be(t))),l&&c.push(Ht(i,Be(l))),c.length!==0)return c.length===1?c[0]:{AND:c}},Ln=(o,i,t)=>{const l=[];for(const c of o){const p=ce(c);if(p&&i.every(m=>m(p))&&(l.push(p),t!==void 0&&l.length>t))break}return l},Dn=(o,i,t,l,c,p=()=>{})=>{const m=Math.max(0,Math.floor(l.numItems)),R=Cn(t),T=typeof l.endCursor=="string",$=ne(kn(t,R,l.cursor,l.endCursor),ie),y=c&&$?n`${$} AND ${c}`:c??$;let E=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(i)}`;y&&(E=n`${E} WHERE ${y}`),E=n`${E} ORDER BY ${yt(R)}`;const _=t.inMemoryFilters.length>0;!_&&!T&&(E=n`${E} LIMIT ${n.raw(String(m+1))}`);const M=F(o,E).toArray();p(M.length);const W=Ln(M,t.inMemoryFilters,_||T?void 0:m);if(T){const U=W.length>=2?W[Math.floor(W.length/2)-1]:void 0;return{continueCursor:l.endCursor??null,isDone:!0,page:W,splitCursor:U?Ue(U,R):null}}const C=W.length>m,L=C?W.slice(0,m):W,j=L.at(-1);return{continueCursor:C&&j?Ue(j,R):null,isDone:!C,page:L}};class Wn extends b{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const On=/\s/u,Fn=String.fromCodePoint(0),ct=(o,i,t)=>{if(!o.tables[i])throw new b("INTERNAL",`unknown table: ${i}`);return typeof t!="string"||t.length===0||On.test(t)||t.includes(Fn)?null:t},qn=(o,i,t,l=()=>{},c=()=>{},p=()=>{})=>{const m=i.tables[t];if(!m)throw new b("INTERNAL",`unknown table: ${t}`);const R=de(m.softDeleteMode,void 0),T=R?ne(R,ie):void 0,$={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let y=0;const E=N=>{const{search:I}=$;if(!I)throw new b("INTERNAL","runSearchFetch called without a staged search");Ct(o,t,m);const v=$.inMemoryFilters.length>0,k=pn(v?void 0:N),H=Wt(o)?yn(o,t,I,k,T):En(o,t,I,k,T);if(!v)return N===void 0&&ln(H),H;const X=[];y=H.length;for(const ue of H)if($.inMemoryFilters.every(fe=>fe(ue.document))&&(X.push(ue),typeof N=="number"&&X.length>=N))break;return X},_=N=>E(N).map(I=>I.document),M=N=>{const I=fn(N);return hn(_(dn(I)),I)},W=()=>{const N=$.indexFields.length>0?$.indexFields:["_creationTime"],I=$.order==="desc"?"DESC":"ASC";return n.join(N.map(v=>n`${z(v)} ${n.raw(I)}`),n`, `)},C=()=>{if($.search||$.geo||$.indexName===void 0){c(void 0);return}c(Yt(t,$.indexName,$.indexFields,$.sqlConditions,re))},L=N=>{C();let I=0;const v=(()=>{if($.search){const k=_(N);return I=y,k}return $.geo?An(o,t,$,T,N,k=>{I=k}):vn(o,t,$,T,W(),N,k=>{I=k})})();return p(Math.max(I,v.length)),v},j=()=>{if(!$.search&&!$.geo)throw new b("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);C();let N=0;const I=(()=>{if($.search){const v=E(void 0);return N=y,v}return xn(o,t,$,T,void 0,v=>{N=v})})();return p(Math.max(N,I.length)),I},U={async*[Symbol.asyncIterator](){const N=[...$.inMemoryFilters];let I;$.inMemoryFilters=[];try{for(;;){const v=await U.paginate({cursor:I??null,numItems:$n});for(const k of v.page)N.every(H=>H(k))&&(yield k);if(v.isDone||v.continueCursor===null)return;I=v.continueCursor}}finally{$.inMemoryFilters=N}},async collect(){return L(void 0)},async collectWithScores(){return j()},filter(N){return $.inMemoryFilters.push(N),U},async first(){return L($.inMemoryFilters.length>0?void 0:1)[0]??null},order(N){return $.order=N==="desc"?"desc":"asc",U},async paginate(N){let I=0;if(C(),$.search){const k=M(N);return p(k.page.length),k}if($.geo)throw new b("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const v=Dn(o,t,$,N,T,k=>{I=k});return p(Math.max(I,v.page.length)),v},async take(N){return L(N)},async unique(){const N=L($.inMemoryFilters.length>0?void 0:2);if(N.length>1)throw new Wn(`unique() on table "${t}" matched ${String(N.length)} documents; expected at most one`);return N[0]??null},withGeoIndex(N,I){const v=(m.geoIndexes??[]).find(H=>H.name===N);if(!v)throw new b("INTERNAL",`unknown geo index "${N}" on table "${t}"`);l(t,N,"geo");const k={definition:v,indexName:N};if($.geo=k,I(Nn(k,t)),!k.near&&!k.within)throw new b("INTERNAL",`geo index "${N}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return U},withIndex(N,I){const v=m.indexes.find(k=>k.name===N);if(!v)throw new b("INTERNAL",`unknown index "${N}" on table "${t}"`);return l(t,N,"index"),$.indexName=N,$.indexFields=v.fields,I&&I(gn($)),U},withSearchIndex(N,I){const v=(m.searchIndexes??[]).find(H=>H.name===N);if(!v)throw new b("INTERNAL",`unknown search index "${N}" on table "${t}"`);l(t,N,"search");const k={definition:v,field:v.field,filters:[],hasQuery:!1,indexName:N,query:""};if($.search=k,I(sn(k,t,je(v.language))),!k.hasQuery)throw new b("INTERNAL",`search index "${N}" on table "${t}" requires a .search(field, query) call`);return U}};return U},ut=(o,i,t)=>{const l={...i};for(const[c,p]of wt(o)){if(p.serverDefault){l[c]=p.serverDefault({auth:t});continue}l[c]===void 0&&(p.defaultFn?l[c]=p.defaultFn():"defaultValue"in p&&(l[c]=p.defaultValue))}return l},ft=(o,i,t,l)=>{const c=t;for(const[p,m]of wt(o)){if(m.serverDefault){p in i&&(c[p]=m.serverDefault({auth:l}));continue}m.onUpdateFn&&!(p in i)&&(c[p]=m.onUpdateFn())}},ht=(o,i)=>{for(const t of Object.keys(i))if(i[t]===void 0)throw new b("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Bn=/unique constraint failed/i,Un=o=>o instanceof Error&&Bn.test(o.message),Pe=(o,i,t)=>{try{F(o,t)}catch(l){throw Un(l)?new $e(`unique constraint violation on "${i}"`,"unique"):l}},xe=(o,i,t)=>{if(Pe(o,i,t),F(o,n`SELECT changes() AS changed`).one().changed===0)throw new $e(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},pt=(o,i,t,l,c,p,m)=>{const R=[];for(let E=0;E<t.length+1;E+=1){const _=[];for(let L=0;L<E;L+=1)_.push(n`${n.identifier(t[L])} IS ${p[L]}`);const M=t[E],W=l[E];if(M!==void 0&&W!==void 0){const L=W.direction==="desc"?">":"<";_.push(n`${n.identifier(M)} ${n.raw(L)} ${p[E]}`)}else _.push(n`${n.identifier(Qt)} < ${m}`);const[C]=_;R.push(_.length===1&&C!==void 0?C:n`(${n.join(_,n` AND `)})`)}const T=n.join(R,n` OR `),$=F(o,n`SELECT COUNT(*) AS c FROM ${n.identifier(i)} WHERE ${n.identifier("__partition__")} = ${c} AND (${T})`).one(),y=F(o,n`SELECT COUNT(*) AS c FROM ${n.identifier(i)} WHERE ${n.identifier("__partition__")} = ${c}`).one();return{before:$.c,total:y.c}},pr=o=>{const{sql:i}=o,{schema:t}=o,l=o.broadcast??(()=>{}),c=(e,...r)=>{const a=t.tables[e]?.indexes;if(!a||a.length===0)return;const h=[];for(const f of r)f&&h.push(...zt(a,f,re));return h.length>0?h:void 0},{headroom:p}=o;let m=!1;const R=async e=>{const r=m;m=!0;try{return await e()}finally{m=r}},T=o.onRead??(()=>{}),$=o.onReadRange??(e=>{T(e.table,B)}),y=(e,r)=>{r!==void 0&&r!==B&&!m&&p?.recordRead(1),T(e,r)},E=o.onIndexUse??(()=>{}),_=o.onWrite??(()=>{}),M=async e=>{m||p?.recordWrite(e.doc),await _(e)},{cache:W}=o,C=o.clock??(()=>Date.now()),L=o.idGenerator??(()=>crypto.randomUUID()),j=o.scheduler??xt,{globalDb:U}=o,N=o.auth??{identity:null,userId:null},I=o.cdc??!1,v=j,k=Zt({scheduler:typeof v.list=="function"&&typeof v.get=="function"?v:void 0,storage:o.storage}),H=(e,r,a,h)=>{I&&kt(i,C(),e,r,a,h)},X=e=>t.tables[e]?.shardMode?.kind==="global",ue=(e,r)=>{if(X(e)){if(!U)throw new b("INTERNAL",`cross-backend ${r} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return U}return q},fe=e=>ue(e,"cascade"),Y=(e,r)=>{if(X(e)){if(!U)throw new b("INTERNAL",`${r} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return U}},he=()=>U,ve=(e,r)=>ue(e,"relation load").findMany(e,r),Ge=(e,r)=>(X(e)&&y(e,B),ve(e,r)),Et=e=>!X(e.table),Ke=o.relationExistsPushDown??"auto",Qe=Ke!=="never",{maxRelationKeys:ze}=o,ge=(e,r,a)=>it(e,{fetcher:Ge,maxRelationKeys:ze,relationBaseWhere:a,schema:t,tableName:r}),Ye=async(e,r,a,h)=>{const f=Y(e,"relation grouped count");if(f)return y(e,B),Jt((x,K)=>f.count(x,K),e,r,a,h);const d=t.tables[e];if(!d)throw new b("INTERNAL",`unknown table: ${e}`);y(e,B);const s=de(d.softDeleteMode,void 0),u={[r]:{in:a}},w=Q(Q(u,h),s),S=await ge(w,e,void 0),g=ne(S,ie),A=z(r);let O=n`SELECT ${A} AS __fk__, COUNT(*) AS count FROM ${n.identifier(e)}`;g&&(O=n`${O} WHERE ${g}`),O=n`${O} GROUP BY ${A}`;const D=F(i,O).toArray();return new Map(D.map(x=>[x.__fk__,x.count]))};let be=0;const Ve=new Set;for(const[e,r]of Object.entries(t.tables))for(const a of Object.values(r.triggerMap??{}))Ve.add(`${e} ${a.timing} ${a.op}`);const ee=(e,r,a)=>Ve.has(`${e} ${r} ${a}`),te=async(e,r,a)=>{if(be+=1,be>dt)throw be-=1,new $e(`trigger recursion exceeded ${String(dt)} levels on "${a.table}" — check for a self-triggering write`,"trigger");try{await en({ctx:Tt,event:a,op:r,schema:t,tableName:a.table,timing:e})}finally{be-=1}},{ensureBackfilledForTable:pe,ensureBackfilledIndex:Ie,ensureRankBackfilled:Me,ensureRankBackfilledForTable:we,syncAggregates:ye,syncCompanionsForInsert:Je,syncGeo:Ee,syncRanks:me,syncSearch:Ne}=Lt({broadcast:l,indexKeysFor:(e,r)=>c(e,r),invalidateCache:(e,r,a)=>W?.invalidate(e,r,c(e,a)),recordCdc:H,schema:t,sql:i}),Xe=(e,r,a)=>{const{shardMode:h}=r;if(h?.kind==="shardBy"&&!(h.field!==void 0&&(a.partitionBy??[]).includes(h.field)))throw Object.assign(new Error(`rank index "${a.name}" on "${e}" partitions across shards (shard key "${h.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})},oe=(e,r)=>{const a=Object.entries(t.tables).filter(([,S])=>S.shardMode?.kind!=="global").map(([S])=>S).filter(S=>r===void 0||S===r);if(a.length===0)return;const h=a.map(S=>n`SELECT ${n.raw(`'${S.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(S)} WHERE id = ${e}`),f=n`${n.join(h,n` UNION ALL `)} LIMIT 1`,[d]=F(i,f).toArray();if(!d)return;const s=d.__t__,u=ce(d);if(typeof s!="string"||!u)return;const w=d[P];return{docJson:typeof w=="string"?w:se(w??{}),row:u,tableName:s}},Nt=(e,r)=>{const a=[...new Set(e)],h=new Map;if(a.length===0)return h;const f=Object.entries(t.tables).filter(([,s])=>s.shardMode?.kind!=="global").map(([s])=>s).filter(s=>r===void 0||s===r);if(f.length===0)return h;const d=Math.max(1,Math.floor(900/f.length));for(let s=0;s<a.length;s+=d){const u=a.slice(s,s+d),w=n.join(u.map(A=>n`${A}`),n`, `),S=f.map(A=>n`SELECT ${n.raw(`'${A.replaceAll("'","''")}'`)} AS __t__, id FROM ${n.identifier(A)} WHERE id IN (${w})`),g=n.join(S,n` UNION ALL `);for(const A of F(i,g)){const{id:O,__t__:D}=A;typeof D=="string"&&typeof O=="string"&&h.set(O,D)}}return h},Ze={assertRankPartitionLocal:Xe,ensureRankBackfilled:Me,onRead:y,rowToDocument:ce,schema:t,sql:i},q={system:k,async aggregate(e,r){const a=Y(e,"aggregate");if(a)return y(e,B),a.aggregate(e,r);const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);if(_e(r.op),r.op==="count")return q.count(e,{baseWhere:r.baseWhere,relationBaseWhere:r.relationBaseWhere,restrictsCounts:r.restrictsCounts,where:r.where});if(!r.field)throw new b("INTERNAL",`aggregate(${e}, { op: "${r.op}" }): "field" is required for non-count reducers`);y(e,B);const f=de(h.softDeleteMode,void 0),d=Q(Q(r.baseWhere,r.where),f),s=await ge(d,e,r.relationBaseWhere),u=s!==d;if(h.aggregateIndexes&&!r.baseWhere&&!u&&!f){const D=Mt(h.aggregateIndexes,r.op,r.field,r.where);if(D){Ie(e,D.index);const x=Ce(D.index.by??[],D.key),K=Le(e,D.index.name),V=F(i,n`SELECT ${Re} AS value, ${We} AS count FROM ${n.identifier(K)} WHERE ${Ae} = ${x}`).toArray()[0];return ke(r.op,V)}}const w=ne(s,ie),S=_e(r.op),g=z(r.field);let A=n`SELECT ${n.raw(S)}(${g}) AS value FROM ${n.identifier(e)}`;return w&&(A=n`${A} WHERE ${w}`),F(i,A).toArray()[0]?.value??null},asId(e,r){const a=ct(t,e,r);if(a===null)throw new b("BAD_REQUEST",`asId("${e}", …): "${r}" is not a valid id for table "${e}"`,{status:400});return a},async count(e,r){const a=Y(e,"count");if(a)return y(e,B),a.count(e,r);const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);const f=At(r);if(f.restrictsCounts)throw new De(e);y(e,B);const d=de(h.softDeleteMode,void 0),s=Q(Q(f.baseWhere,f.where),d),u=await ge(s,e,f.relationBaseWhere),w=u!==s;if(h.aggregateIndexes&&!f.baseWhere&&!w&&!d){const A=It(h.aggregateIndexes,f.where);if(A){Ie(e,A.index);const O=Ce(A.index.by??[],A.key),D=Le(e,A.index.name),x=F(i,n`SELECT ${Re} AS value FROM ${n.identifier(D)} WHERE ${Ae} = ${O}`).toArray();return x[0]===void 0?0:x[0].value??0}}const S=ne(u,ie);let g=n`SELECT COUNT(*) AS count FROM ${n.identifier(e)}`;return S&&(g=n`${g} WHERE ${S}`),F(i,g).one().count},async delete(e,r,a){const h=oe(e,r);if(!h){const g=r===void 0?he():void 0;g&&await g.delete(e,void 0,a);return}const{docJson:f,row:d,tableName:s}=h,u=t.tables[s],w=a?.hard===!0,S=!w&&u?.softDeleteMode?u.softDeleteMode.field:void 0;if(!(S&&d[S]!==null&&d[S]!==void 0)){if(ee(s,"before","delete")&&await te("before","delete",{id:e,op:"delete",previous:d,table:s}),await Vt({deletedId:e,deletedReference:g=>d[g],findHolders:async(g,A,O)=>(await fe(g).findMany(g,{includeDeleted:w,where:{[A]:O}})).page,onCascade:(g,A)=>fe(g).delete(A,void 0,a),onRestrict:g=>{throw new $e(g,"restrict")},onSetNull:(g,A,O)=>fe(g).patch(A,{[O]:null}),schema:t,tableName:s}),pe(s),we(s),S){const g={...d,[S]:C(),_id:e};xe(i,s,n`UPDATE ${n.identifier(s)} SET ${n.identifier(P)} = ${se(g)} WHERE id = ${e} AND ${n.identifier(P)} = ${f}`),Ne(s,e,g,d),Ee(s,e,void 0),ye(s,d,g),me(s,e,d,void 0),W?.invalidate(s,e,c(s,d,g)),H(s,e,"update",g),l({indexKeys:c(s,d,g),key:e,op:"update",row:g,table:s}),ee(s,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:d,table:s}),await M({id:e,op:"delete",table:s});return}xe(i,s,n`DELETE FROM ${n.identifier(s)} WHERE id = ${e} AND ${n.identifier(P)} = ${f}`),Ne(s,e,void 0),Ee(s,e,void 0),ye(s,d,void 0),me(s,e,d,void 0),W?.invalidate(s,e,c(s,d)),H(s,e,"delete"),l({indexKeys:c(s,d),key:e,op:"delete",table:s}),ee(s,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:d,table:s}),await M({id:e,op:"delete",table:s})}},async deleteAll(e,r){if(!t.tables[e])throw new b("INTERNAL",`unknown table: ${e}`);const a=Math.max(1,r?.chunkSize??gt),h=r?.hard===void 0?void 0:{hard:r.hard},f=X(e)?void 0:e;let d=0;return await R(async()=>{for(;;){const s=(await q.findMany(e,{limit:a})).page.map(u=>String(u._id));if(s.length===0)break;for(const u of s)await q.delete(u,f,h),d+=1;if(s.length<a)break}}),{deleted:d}},async deleteMany(e,r,a){le(e.length,r?.limit,"deleteMany");for(const h of e)await q.delete(h,a);return{deleted:e.length}},async deleteWhere(e,r,a){const h=Y(e,"deleteWhere");let f;if(h)f=(await h.findMany(e,{where:r})).page.map(d=>String(d._id));else{if(!t.tables[e])throw new b("INTERNAL",`unknown table: ${e}`);f=(await q.findMany(e,{where:r})).page.map(d=>String(d._id))}if(le(f.length,a?.limit,"deleteWhere"),q.deleteMany===void 0)throw new b("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return q.deleteMany(f,a)},async findFirst(e,r={}){return(await q.findMany(e,{...r,limit:1})).page[0]??null},async findFirstOrThrow(e,r={}){const a=await q.findFirst(e,r);if(a===null)throw new Pt(`findFirstOrThrow: no "${e}" document matched`);return a},async findMany(e,r={}){const a=Y(e,"findMany");if(a)return y(e,B),a.findMany(e,r);const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);const f=!r.where&&!r.baseWhere;f?y(e,B):y(e);const d=jt(r.orderBy),s=r.cursor?$t(d,Be(r.cursor)):void 0;let u=Q(r.baseWhere,r.where);u=Q(u,de(h.softDeleteMode,r.includeDeleted)),u=await it(u,{canPushExists:Qe?Et:void 0,existsPushMode:Ke==="always"?"always":"auto",fetcher:Ge,maxRelationKeys:ze,relationBaseWhere:r.relationBaseWhere,schema:t,tableName:e}),s&&(u=u?{AND:[u,s]}:s);const w=Qe?In(y):ie,S=ne(u,w);let g=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(e)}`;S&&(g=n`${g} WHERE ${S}`),g=n`${g} ORDER BY ${yt(d)}`;const A=typeof r.limit=="number"?Math.max(0,Math.floor(r.limit)):void 0;A!==void 0&&(g=n`${g} LIMIT ${n.raw(String(A+1))}`);const O=F(i,g).toArray();f&&!m&&p?.recordRead(O.length);const D=[];for(const J of O){const G=ce(J);G&&(D.push(G),!f&&typeof G._id=="string"&&y(e,G._id))}if(A===void 0)return r.with&&await at({groupedCounter:Ye,fetcher:ve,parents:D,relationBaseWhere:r.relationBaseWhere,schema:t,tableName:e,with:r.with}),{continueCursor:null,isDone:!0,page:nt(D,r.select,r.with)};const x=D.length>A,K=x?D.slice(0,A):D,V=K.at(-1);return r.with&&await at({fetcher:ve,groupedCounter:Ye,parents:K,relationBaseWhere:r.relationBaseWhere,schema:t,tableName:e,with:r.with}),{continueCursor:x&&V?Ue(V,d):null,isDone:!x,page:nt(K,r.select,r.with)}},async get(e,r){const a=oe(e,r);if(!a){const h=r===void 0?he():void 0;return h?h.get(e):null}return y(a.tableName,e),a.row},async lookupById(e,r){const a=oe(e,r);return a?(y(a.tableName,e),{row:a.row,tableName:a.tableName}):null},async groupBy(e,r){const a=Y(e,"groupBy");if(a)return y(e,B),a.groupBy(e,r);const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);y(e,B);const f=r.agg??{op:"count"};if(_e(f.op),f.op!=="count"&&!f.field)throw new b("INTERNAL",`groupBy(${e}, { agg: { op: "${f.op}" } }): "field" is required for non-count reducers`);const d=de(h.softDeleteMode,void 0),s=Q(Q(r.baseWhere,r.where),d),u=await ge(s,e,r.relationBaseWhere),w=u!==s;if(h.aggregateIndexes&&!r.baseWhere&&!w&&!d){const x=vt(h.aggregateIndexes,f.op,f.field,r.by,r.where);if(x){Ie(e,x.index);const K=Le(e,x.index.name),V=Object.keys(x.partial),J=[];if(V.length===(x.index.by??[]).length&&V.length>0){const ae=Ce(x.index.by??[],x.partial),Te=F(i,n`SELECT ${Re} AS value, ${We} AS count FROM ${n.identifier(K)} WHERE ${Ae} = ${ae}`).toArray();return Te.length>0&&J.push({key:{...x.partial},value:ke(f.op,Te[0])}),J}const G=F(i,n`SELECT ${Ae} AS key, ${Re} AS value, ${We} AS count FROM ${n.identifier(K)}`).toArray();for(const ae of G){const Te=JSON.parse(ae.key);J.push({key:Te,value:ke(f.op,ae)})}return J}}const S=ne(u,ie),g=r.by.map(x=>n`${z(x)} AS ${n.identifier(x)}`);if(f.op==="count")g.push(n`COUNT(*) AS value`);else{const{field:x}=f;if(x===void 0)throw new b("INTERNAL",`groupBy(${e}, { agg: { op: "${f.op}" } }): "field" is required for non-count reducers`);g.push(n`${n.raw(_e(f.op))}(${z(x)}) AS value`)}let A=n`SELECT ${n.join(g,n`, `)} FROM ${n.identifier(e)}`;S&&(A=n`${A} WHERE ${S}`),A=n`${A} GROUP BY ${n.join(r.by.map(x=>z(x)),n`, `)}`;const O=F(i,A).toArray(),D=[];for(const x of O){const K={};for(const J of r.by)K[J]=x[J]??null;const{value:V}=x;D.push({key:K,value:V==null?null:Number(V)})}return D},async insert(e,r,a){const h=Y(e,"insert");if(h){const S=await h.insert(e,r,a);return m||p?.recordWrite(r),l({key:S,op:"insert",row:{...r,_id:S},table:e}),S}const f=t.tables[e];if(!f)throw new b("INTERNAL",`unknown table: ${e}`);const d=ut(f,r,N);Fe(f,d);let s;a?.clientId!==void 0?(mn(a.clientId),s=a.clientId):a?.allowExplicitId&&typeof d._id=="string"?s=d._id:s=L();const u=a?.allowExplicitId&&typeof d._creationTime=="number"?d._creationTime:C(),w={...d,_creationTime:u,_id:s};return ee(e,"before","insert")&&await te("before","insert",{doc:{...w},id:s,op:"insert",table:e}),pe(e),we(e),Pe(i,e,n`INSERT INTO ${n.identifier(e)} (id, _creationTime, ${n.identifier(P)}) VALUES (${s}, ${u}, ${se(w)})`),Je(e,s,w),ee(e,"after","insert")&&await te("after","insert",{doc:w,id:s,op:"insert",table:e}),await M({doc:w,id:s,op:"insert",table:e}),s},async insertManyUnsafe(e,r,a){if(le(r.length,a?.limit,"insertManyUnsafe"),r.length===0)return[];const h=Y(e,"insert");if(h){const u=[];for(const w of r){const S=await h.insert(e,w,{allowExplicitId:a?.allowExplicitId});m||p?.recordWrite(w),l({key:S,op:"insert",row:{...w,_id:S},table:e}),u.push(S)}return u}const f=t.tables[e];if(!f)throw new b("INTERNAL",`unknown table: ${e}`);pe(e),we(e);const d=r.map(u=>{const w=ut(f,u,N),S=a?.allowExplicitId===!0&&typeof w._id=="string"?w._id:L(),g=a?.allowExplicitId===!0&&typeof w._creationTime=="number"?w._creationTime:C();return{creationTime:g,document:{...w,_creationTime:g,_id:S},id:S}});if(!m)for(const u of d)p?.recordWrite(u.document);const s=n.join(d.map(u=>n`(${u.id}, ${u.creationTime}, ${se(u.document)})`),n`, `);Pe(i,e,n`INSERT INTO ${n.identifier(e)} (id, _creationTime, ${n.identifier(P)}) VALUES ${s}`);for(const{document:u,id:w}of d)Je(e,w,u),await _({doc:u,id:w,op:"insert",table:e});return d.map(u=>u.id)},async insertMany(e,r,a){le(r.length,a?.limit,"insertMany");const h=a?.skipDuplicates===!0,f=[];for(const d of r)try{f.push(await q.insert(e,d))}catch(s){if(h&&s instanceof $e&&s.kind==="unique")f.push(null);else throw s}return f},normalizeId(e,r){return ct(t,e,r)},async patch(e,r,a){const h=oe(e,a);if(!h){const S=a===void 0?he():void 0;if(S){await S.patch(e,r);return}throw new b("INTERNAL",`document not found: ${e}`)}const{docJson:f,row:d,tableName:s}=h,u=t.tables[s];if(!u)throw new b("INTERNAL",`unknown table: ${s}`);y(s,e),ht("patch",r);const w={...d,...r,_id:e};ft(u,r,w,N),Fe(u,w,!0),ee(s,"before","update")&&await te("before","update",{doc:{...w},id:e,op:"update",previous:d,table:s}),pe(s),we(s),xe(i,s,n`UPDATE ${n.identifier(s)} SET ${n.identifier(P)} = ${se(w)} WHERE id = ${e} AND ${n.identifier(P)} = ${f}`),Ne(s,e,w,d),Ee(s,e,w),ye(s,d,w),me(s,e,d,w),W?.invalidate(s,e,c(s,d,w)),H(s,e,"update",w),l({indexKeys:c(s,d,w),key:e,op:"update",row:w,table:s}),ee(s,"after","update")&&await te("after","update",{doc:w,id:e,op:"update",previous:d,table:s}),await M({doc:w,id:e,op:"update",table:s})},async patchMany(e,r,a){le(e.length,r?.limit,"patchMany");for(const h of e)await q.patch(h.id,h.patch,a);return{patched:e.length}},async patchWhere(e,r,a){const h=Y(e,"patchWhere");let f;if(h)f=(await h.findMany(e,{where:r.where})).page.map(d=>({id:String(d._id),patch:r.patch}));else{if(!t.tables[e])throw new b("INTERNAL",`unknown table: ${e}`);f=(await q.findMany(e,{where:r.where})).page.map(d=>({id:String(d._id),patch:r.patch}))}if(le(f.length,a?.limit,"patchWhere"),q.patchMany===void 0)throw new b("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await q.patchMany(f,a),{patched:f.length}},query(e){const r=Y(e,"query");return r?(y(e,B),r.query(e)):qn(i,t,e,E,a=>{a?$(a):y(e,B)},a=>{m||p?.recordRead(a)})},async rank(e,r,a){const h=Y(e,"rank");if(h)return y(e,B),h.rank(e,r,a);E(e,r,"rank");const f=t.tables[e];if(!f)throw new b("INTERNAL",`unknown table: ${e}`);const d=f.rankIndexes?.find(G=>G.name===r);if(!d)throw new b("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(Xe(e,f,d),a.restrictsCounts)throw new De(e);y(e,B),Me(e,d);const s=typeof a.row=="string"?a.row:a.row._id;if(!s)return null;const u=ot(e,d.name),w=d.sortBy.map((G,ae)=>rt(ae)),S=w.map(G=>Dt(G)).join(", "),g=F(i,n`SELECT ${n.identifier("__partition__")}, ${n.raw(S)} FROM ${n.identifier(u)} WHERE ${n.identifier("__id__")} = ${s}`).toArray(),[A]=g;if(A===void 0)return null;let O=A.__partition__;const D=Q(a.baseWhere,a.where);Oe(D,t,e,"rank");const x=Gt(d,D);if(x){const G=Kt(d.partitionBy??[],x);if(G!==O)return null;O=G}const K=w.map(G=>A[G]),{before:V,total:J}=pt(i,u,w,d.sortBy,O,K,s);return{position:V+1,total:J}},async rankBefore(e,r,a){if(X(e))throw new b("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);const f=h.rankIndexes?.find(w=>w.name===r);if(!f)throw new b("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(a.restrictsCounts)throw new De(e);y(e,B),Me(e,f);const d=ot(e,f.name),s=f.sortBy.map((w,S)=>rt(S)),u=f.sortBy.map((w,S)=>re(a.sortValues[S]??null));return pt(i,d,s,f.sortBy,a.partitionKey,u,a.rowId)},async rankPage(e,r,a={}){Oe(Q(a.baseWhere,a.where),t,e,"rankPage");const h=Y(e,"rankPage");if(h)return y(e,B),h.rankPage(e,r,a);E(e,r,"rank");const{continueCursor:f,hasMore:d,rows:s}=et(Ze,e,r,a);return{continueCursor:f,isDone:!d,page:s.map(u=>u.doc)}},async rankPageRows(e,r,a={}){Oe(Q(a.baseWhere,a.where),t,e,"rankPage"),E(e,r,"rank");const{directions:h,hasMore:f,rows:d}=et(Ze,e,r,a);return{directions:h,hasMore:f,rows:d}},async restore(e,r){const a=oe(e,r);if(!a){const d=r===void 0?he():void 0;if(d?.restore){await d.restore(e);return}throw new b("INTERNAL",`document not found: ${e}`)}const h=t.tables[a.tableName]?.softDeleteMode?.field;if(!h)throw new b("INTERNAL",`ctx.db.restore: table "${a.tableName}" is not a .softDelete() table`);const f=a.row[h]!==null&&a.row[h]!==void 0;await q.patch(e,{[h]:null},r),f&&me(a.tableName,e,void 0,a.row)},async replace(e,r,a,h){const f=oe(e,a);if(!f){const A=a===void 0?he():void 0;if(A){await A.replace(e,r,void 0,h);return}throw new b("INTERNAL",`document not found: ${e}`)}const{docJson:d,row:s,tableName:u}=f,w=t.tables[u];if(!w)throw new b("INTERNAL",`unknown table: ${u}`);ht("replace",r);const S=h?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:C(),g={...r,_creationTime:S,_id:e};ft(w,r,g,N),Fe(w,g),ee(u,"before","update")&&await te("before","update",{doc:{...g},id:e,op:"update",previous:s,table:u}),pe(u),we(u),xe(i,u,n`UPDATE ${n.identifier(u)} SET _creationTime = ${S}, ${n.identifier(P)} = ${se(g)} WHERE id = ${e} AND ${n.identifier(P)} = ${d}`),Ne(u,e,g,s),Ee(u,e,g),ye(u,s,g),me(u,e,s,g),W?.invalidate(u,e,c(u,s,g)),H(u,e,"update",g),l({indexKeys:c(u,s,g),key:e,op:"update",row:g,table:u}),ee(u,"after","update")&&await te("after","update",{doc:g,id:e,op:"update",previous:s,table:u}),await M({doc:g,id:e,op:"update",table:u})},async wipeShard(e){const r=new Set(e?.exclude),a=e?.tables,h=Object.entries(t.tables).filter(([u,w])=>r.has(u)||a!==void 0&&!a.includes(u)?!1:w.shardMode?.kind!=="global").map(([u])=>u);if(a!==void 0){for(const u of a)if(!t.tables[u])throw new b("INTERNAL",`wipeShard: unknown table: ${u}`)}const f={};let d=0;const{deleteAll:s}=q;if(s===void 0)throw new b("INTERNAL","wipeShard: this writer has no deleteAll");for(const u of h){const w=await s(u,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});f[u]=w.deleted,d+=w.deleted}return{deleted:d,tables:f}}},Tt={db:q,scheduler:j};return o.enforceRls===!0?Xt(q,t,(e,r)=>oe(e,r)?.tableName,(e,r)=>Nt(e,r)):q};export{Er as CDC_LOG_TABLE,Ir as CLIENT_WATERMARK_TABLE,Dr as GLOBAL_SHAPE_SNAPSHOT_TABLE,Pr as IDEMPOTENCY_TABLE,Wn as NotUniqueError,Yr as SEARCH_STATE_TABLE,Mr as advanceClientWatermark,Nr as applyCdcChanges,mn as assertValidClientId,$r as backfillAggregateIndexes,gr as backfillRankIndexes,br as backfillSearchIndexes,Tr as bumpCdcEpoch,pr as createShardCtxDb,Wr as deleteGlobalShapeSnapshot,Or as deleteGlobalShapeSnapshotsForConnection,Cr as migrateClientWatermark,Fr as migrateGlobalShapeSnapshot,Sr as minCdcSeq,ct as normalizeIdStructurally,_r as readCdcChanges,Rr as readCdcCursor,Ar as readCdcEpoch,kr as readClientWatermark,qr as readGlobalShapeSnapshot,jr as readIdempotent,Qr as runShardMigrations,Jr as selectShapeMemberIds,Xr as selectShapeRows,xr as trimCdcChanges,Hr as trimIdempotent,Br as writeGlobalShapeSnapshot,Gr as writeIdempotent};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{A as R,T,l as I,y as O,c as A}from"./FTS_COUNT_COLUMN-D1gY3wwZ-CZHdaRrd.mjs";import"@lunora/errors";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as b}from"./AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{encodeAggregateKey as _,foldAggregateTally as L,aggregateTableName as M}from"./aggregateTableName-G-eXyjcz.mjs";import{migrateSearchState as k,readSearchBackfillState as w,writeSearchBackfillState as C}from"./SEARCH_STATE_TABLE-eLN8U5tz.mjs";import{runDrizzle as c}from"./runDrizzle-GKR3y97k.mjs";import{isFtsAvailable as u,DOC_COLUMN as g,rowToDocument as p,AGG_KEY as y,AGG_VALUE as N,AGG_COUNT as x,tryRowToDocument as F}from"./AGG_COUNT-D-wORk0b.mjs";import{param as D}from"./param-B5lF5Jd9.mjs";import{sortColumnName as U,matchesRankStaticWhere as B,encodePartitionKey as G,rankTableName as j}from"./RANK_TIEBREAK-9NU5s_mi.mjs";import{serializeSqlValue as v}from"./serializeSqlValue-DnpyaLcw.mjs";const V=(i,t)=>i.profile!==t?{cursor:void 0,finished:!1,wipe:i.cursor!==void 0||i.done}:{cursor:i.cursor,finished:i.done,wipe:!1},W=(i,t,r)=>{const o=M(t,r.name);if(c(i,e`SELECT COUNT(*) AS count FROM ${e.identifier(o)}`).one().count>0)return;const n=r.by??[],s=new Map,d=c(i,e`SELECT id, _creationTime, ${e.identifier(g)} FROM ${e.identifier(t)}`).toArray();for(const f of d){const a=p(f);if(!a||r.where&&!b(a,r.where))continue;const m=_(n,a);L(s,m,r,a)}for(const[f,a]of s)c(i,e`INSERT INTO ${e.identifier(o)} (${y}, ${N}, ${x}) VALUES (${f}, ${a.value}, ${a.count})`)},oe=(i,t)=>{for(const[r,o]of Object.entries(t.tables))if(!(o.shardMode?.kind==="global"||!o.aggregateIndexes))for(const n of o.aggregateIndexes)W(i,r,n)},z=(i,t,r)=>{const o=j(t,r.name);if(c(i,e`SELECT COUNT(*) AS count FROM ${e.identifier(o)}`).one().count>0)return;const n=r.sortBy.map((f,a)=>U(a)),s=e.join(["__id__","__partition__",...n].map(f=>e.identifier(f)),e`, `),d=c(i,e`SELECT id, _creationTime, ${e.identifier(g)} FROM ${e.identifier(t)}`).toArray();for(const f of d){const a=p(f);if(!a||r.where&&!B(a,r.where))continue;const m=G(r.partitionBy??[],a),E=r.sortBy.map($=>v(a[$.field]??null)),l=e.join([a._id,m,...E].map($=>D($)),e`, `);c(i,e`INSERT INTO ${e.identifier(o)} (${s}) VALUES (${l})`)}},re=(i,t)=>{for(const[r,o]of Object.entries(t.tables))if(!(o.shardMode?.kind==="global"||!o.rankIndexes))for(const n of o.rankIndexes)z(i,r,n)},S=500,h=(i,t,r)=>{const o=A(t,r.name),{profile:n}=R(r.language),s=V(w(i,o),n);if(s.finished)return!0;s.wipe&&c(i,e`DELETE FROM ${e.identifier(o)}`);const{cursor:d}=s,f=c(i,d===void 0?e`SELECT id, _creationTime, ${e.identifier(g)} FROM ${e.identifier(t)} ORDER BY id ASC LIMIT ${e.raw(String(S))}`:e`SELECT id, _creationTime, ${e.identifier(g)} FROM ${e.identifier(t)} WHERE id > ${d} ORDER BY id ASC LIMIT ${e.raw(String(S))}`).toArray();let a=d;for(const E of f){const{id:l}=E;if(typeof l!="string")continue;a=l;const $=F(E);if(!$){c(i,e`DELETE FROM ${e.identifier(o)} WHERE ${e.identifier(T)} = ${l}`);continue}c(i,e`DELETE FROM ${e.identifier(o)} WHERE ${e.identifier(T)} = ${l}`),c(i,e`INSERT INTO ${e.identifier(o)} (${e.identifier(I)}, ${e.identifier(T)}) VALUES (${O($,r)}, ${l})`)}const m=f.length<S;return C(i,o,a,m,n),m},te=(i,t,r)=>{if(u(i))for(const o of r.searchIndexes??[])o.staged||h(i,t,o)},ae=(i,t)=>{if(u(i)){k(i);for(const[r,o]of Object.entries(t.tables))if(!(o.shardMode?.kind==="global"||!o.searchIndexes))for(const n of o.searchIndexes){let s=!1;for(;!s;)s=h(i,r,n)}}};export{oe as backfillAggregateIndexes,re as backfillRankIndexes,ae as backfillSearchIndexes,te as backfillSearchIndexesForTable};
|
package/dist/packem_shared/{createCompanionSync-DWK0Vlg1.mjs → createCompanionSync-DCfEbb9_.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{u as ee,T as G,l as ne,y as ie,c as oe}from"./FTS_COUNT_COLUMN-D1gY3wwZ-CZHdaRrd.mjs";import"@lunora/errors";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as U,aggregateSqlFunction as te}from"./AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{encodeAggregateKey as b,foldAggregateTally as re,aggregateTableName as H,coerceAggregateNumber as B}from"./aggregateTableName-G-eXyjcz.mjs";import{runDrizzle as l}from"./runDrizzle-GKR3y97k.mjs";import{isFtsAvailable as ae,DOC_COLUMN as V,rowToDocument as K,AGG_KEY as R,AGG_VALUE as
|
|
1
|
+
import{u as ee,T as G,l as ne,y as ie,c as oe}from"./FTS_COUNT_COLUMN-D1gY3wwZ-CZHdaRrd.mjs";import"@lunora/errors";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as U,aggregateSqlFunction as te}from"./AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{encodeAggregateKey as b,foldAggregateTally as re,aggregateTableName as H,coerceAggregateNumber as B}from"./aggregateTableName-G-eXyjcz.mjs";import{runDrizzle as l}from"./runDrizzle-GKR3y97k.mjs";import{isFtsAvailable as ae,DOC_COLUMN as V,rowToDocument as K,AGG_KEY as R,AGG_VALUE as _,AGG_COUNT as m,geoTableName as se,aggUpsertSql as x,jsonPathSql as O}from"./AGG_COUNT-D-wORk0b.mjs";import{param as P}from"./param-B5lF5Jd9.mjs";import{encodeGeohash as $e,GEO_DEFAULT_PRECISION as ce}from"./GEO_DEFAULT_PRECISION-okRCkZ6r.mjs";import{sortColumnName as z,matchesRankStaticWhere as J,encodePartitionKey as X,rankTableName as Y}from"./RANK_TIEBREAK-9NU5s_mi.mjs";import{serializeSqlValue as M}from"./serializeSqlValue-DnpyaLcw.mjs";const fe=(y,I,h)=>[...y.partitionBy??[],...y.sortBy.map(T=>T.field),...y.where?Object.keys(y.where):[]].every(T=>I[T]===h[T]),le=(y,I,h,T,L,g)=>{if(L&&g&&fe(h,L,g))return;const s=Y(I,h.name);if(L&&l(y,e`DELETE FROM ${e.identifier(s)} WHERE ${e.identifier("__id__")} = ${T}`),!g||h.where&&!J(g,h.where))return;const N=h.sortBy.map((S,F)=>z(F)),v=e.join(["__id__","__partition__",...N].map(S=>e.identifier(S)),e`, `),C=X(h.partitionBy??[],g),w=h.sortBy.map(S=>M(g[S.field]??null)),D=e.join([T,C,...w].map(S=>P(S)),e`, `);l(y,e`INSERT INTO ${e.identifier(s)} (${v}) VALUES (${D})`)},Ae=y=>{const{broadcast:I,indexKeysFor:h,invalidateCache:T,recordCdc:L,schema:g,sql:s}=y,N=new Set,v=new Set,C=(i,n)=>{const o=`${i}::${n.name}`;if(N.has(o))return;const c=H(i,n.name),r=n.by??[],d=new Map,f=l(s,e`SELECT id, _creationTime, ${e.identifier(V)} FROM ${e.identifier(i)}`).toArray();for(const $ of f){const t=K($);if(!t||n.where&&!U(t,n.where))continue;const E=b(r,t);re(d,E,n,t)}l(s,e`DELETE FROM ${e.identifier(c)}`);const p=32,a=[...d];for(let $=0;$<a.length;$+=p){const t=a.slice($,$+p),E=e.join(t.map(([u,A])=>e`(${u}, ${A.value}, ${A.count})`),e`, `);l(s,e`INSERT INTO ${e.identifier(c)} (${R}, ${_}, ${m}) VALUES ${E}`)}N.add(o)},w=(i,n,o)=>{const c=n.by??[],r=te(n.op),d=n.field??"",f=[];for(const $ of c){const t=M(o[$]??null);t===null?f.push(e`${O($)} IS NULL`):f.push(e`${O($)} = ${t}`)}for(const[$,t]of Object.entries(n.where??{})){const E=t!==null&&typeof t=="object"&&!Array.isArray(t)?t.eq:t,u=M(E);u===null?f.push(e`${O($)} IS NULL`):f.push(e`${O($)} = ${u}`)}const p=f.length>0?e` WHERE ${e.join(f,e` AND `)}`:e``,a=O(d);return{value:l(s,e`SELECT ${e.raw(r)}(${a}) AS value FROM ${e.identifier(i)}${p}`).one().value??null}},D=(i,n,o,c)=>{const r=H(i,n.name),{op:d}=n,f=n.field??"",p=t=>{l(s,e`DELETE FROM ${e.identifier(r)} WHERE ${R} = ${t} AND ${m} <= 0`)},a=o&&(!n.where||U(o,n.where))?o:void 0,$=c&&(!n.where||U(c,n.where))?c:void 0;if(!(!a&&!$)){if(d==="count"){for(const[t,E]of[[a,-1],[$,1]]){if(!t)continue;const u=b(n.by??[],t);l(s,x(r,u,E,E,e`${_} = ${_} + excluded.${_}, ${m} = ${m} + excluded.${m}`))}a&&p(b(n.by??[],a));return}if(d==="sum"||d==="avg"){for(const[t,E]of[[a,-1],[$,1]]){if(!t)continue;const u=B(t[f]);if(u===void 0)continue;const A=b(n.by??[],t);l(s,x(r,A,E*u,E,e`${_} = COALESCE(${_}, 0) + excluded.${_}, ${m} = ${m} + excluded.${m}`))}a&&p(b(n.by??[],a));return}if(a){const t=b(n.by??[],a),E=B(a[f]),u=l(s,e`SELECT ${_} AS value, ${m} AS count FROM ${e.identifier(r)} WHERE ${R} = ${t}`).toArray()[0],A=(u?.count??0)-1;if(A<=0)l(s,e`DELETE FROM ${e.identifier(r)} WHERE ${R} = ${t}`);else if(u&&E!==void 0&&u.value!==null&&E===u.value){const Q=w(i,n,a);l(s,e`UPDATE ${e.identifier(r)} SET ${_} = ${Q.value}, ${m} = ${A} WHERE ${R} = ${t}`)}else l(s,e`UPDATE ${e.identifier(r)} SET ${m} = ${m} - 1 WHERE ${R} = ${t}`)}if($){const t=b(n.by??[],$),E=B($[f]);if(E===void 0)l(s,x(r,t,null,1,e`${m} = ${m} + 1`));else{const u=d==="min"?"MIN":"MAX";l(s,x(r,t,E,1,e`${_} = ${e.raw(u)}(COALESCE(${_}, excluded.${_}), excluded.${_}), ${m} = ${m} + 1`))}}}},S=i=>{const n=g.tables[i]?.aggregateIndexes;if(!(!n||n.length===0))for(const o of n)C(i,o)},F=(i,n,o)=>{const c=g.tables[i]?.aggregateIndexes;if(!(!c||c.length===0))for(const r of c)D(i,r,n,o)},j=(i,n)=>{const o=`${i}::rank::${n.name}`;if(v.has(o))return;const c=Y(i,n.name),r=l(s,e`SELECT id, _creationTime, ${e.identifier(V)} FROM ${e.identifier(i)}`).toArray();l(s,e`DELETE FROM ${e.identifier(c)}`);const d=n.sortBy.map((p,a)=>z(a)),f=e.join(["__id__","__partition__",...d].map(p=>e.identifier(p)),e`, `);for(const p of r){const a=K(p);if(!a||n.where&&!J(a,n.where))continue;const $=X(n.partitionBy??[],a),t=n.sortBy.map(u=>M(a[u.field]??null)),E=e.join([a._id,$,...t].map(u=>P(u)),e`, `);l(s,e`INSERT INTO ${e.identifier(c)} (${f}) VALUES (${E})`)}v.add(o)},Z=i=>{const n=g.tables[i]?.rankIndexes;if(!(!n||n.length===0))for(const o of n)j(i,o)},W=(i,n,o,c)=>{const r=g.tables[i]?.rankIndexes;if(!(!r||r.length===0))for(const d of r)le(s,i,d,n,o,c)},k=(i,n,o,c)=>{const r=g.tables[i]?.searchIndexes;if(!(!r||r.length===0||!ae(s)))for(const d of r){if(ee(c,o,d))continue;const f=oe(i,d.name);l(s,e`DELETE FROM ${e.identifier(f)} WHERE ${e.identifier(G)} = ${n}`),o&&l(s,e`INSERT INTO ${e.identifier(f)} (${e.identifier(ne)}, ${e.identifier(G)}) VALUES (${ie(o,d)}, ${n})`)}},q=(i,n,o)=>{const c=g.tables[i]?.geoIndexes;if(!(!c||c.length===0))for(const r of c){const d=se(i,r.name);l(s,e`DELETE FROM ${e.identifier(d)} WHERE ${e.identifier("__id__")} = ${n}`);const f=o?.[r.field];if(f!==null&&typeof f=="object"&&typeof f.lat=="number"&&typeof f.lng=="number"){const{lat:p,lng:a}=f,$=$e({lat:p,lng:a},r.precision??ce);l(s,e`INSERT INTO ${e.identifier(d)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${n}, ${$}, ${p}, ${a})`)}}};return{ensureBackfilledForTable:S,ensureBackfilledIndex:C,ensureRankBackfilled:j,ensureRankBackfilledForTable:Z,syncAggregates:F,syncCompanionsForInsert:(i,n,o)=>{k(i,n,o),q(i,n,o),F(i,void 0,o),W(i,n,void 0,o),T(i,n,o),L(i,n,"insert",o),I({indexKeys:h(i,o),key:n,op:"insert",row:o,table:i})},syncGeo:q,syncRanks:W,syncSearch:k}};export{Ae as createCompanionSync};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createShardCtxDb as b}from"./NotUniqueError-
|
|
1
|
+
import{createShardCtxDb as b}from"./NotUniqueError-CjdcqrlK.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-D0oc40p6.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as v}from"./runShardMigrations-MWWmpqzb.mjs";import{relayName as q}from"./DEFAULT_PROMOTION_THRESHOLDS-Dteg0sZF.mjs";const C=(_,m={})=>({_meta:{column:{notNull:!0,...m}},kind:_}),D=(_,m,E)=>{const{describe:k,expect:i,it:f}=E;k(`engine contract: ${_}`,()=>{k("optimistic concurrency",()=>{const g=p=>({tables:{items:{indexes:[],shape:{title:C("string"),version:C("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{p.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});f("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await i(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(N)}finally{p?.()}}),f("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("i1",{title:"second"})}catch(t){r=t}const e=r;i(e.code).toBe("CONFLICT"),i(e.kind).toBe("occ")}finally{p?.()}}),f("leaves the row readable and unchanged after a conflict",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const r=await s.get("i1");i(r?.title).toBe("first"),i(r?.version).toBe(99)}finally{p?.()}}),f("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l={tables:{items:{indexes:[],shape:{title:C("string"),version:C("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch(o.doc._id,{version:99})},op:"update",timing:"before"}}}}};v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("i1",{title:"second"})}catch(t){r=t}const e=r;i(e).toBeInstanceOf(N),i(e.code).toBe("CONFLICT"),i(e.kind).toBe("trigger")}finally{p?.()}})}),k("shape-poke ordering",()=>{const g="shard-a",p={args:{},name:"messages"},d=(e,t,o,a)=>e.accept(t?.()??{},{connectionId:o,shapes:{[a]:p}}),c=(e,t)=>{let o=0,a=0;const n=u=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${u}`)},h={fetch:(u,O)=>{if(JSON.parse(O?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const B=t[a];if(a+=1,B===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(B))}},y={get:()=>h,getByName:()=>h,idFromName:u=>u},w={buildShapeDiff:n("buildShapeDiff"),computeOpLogShapeSeed:n("computeOpLogShapeSeed"),currentCdcEpoch:n("currentCdcEpoch"),deliverWhisperLocal:n("deliverWhisperLocal"),doName:()=>q(g,0),env:()=>({SHARD:y}),getWebSockets:()=>e.getSockets(),maskMetadata:n("maskMetadata"),nextPokeId:()=>(o+=1,`poke-${String(o)}`),readAttachment:u=>u.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:n("resolveShape"),rlsMetadata:n("rlsMetadata"),shardBinding:()=>"SHARD",sql:n("sql")},S=I(w);if(S===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return S},l=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,o)=>{const a=await e.seedRelayShape(t,o,p,{identity:void 0,userId:void 0});if(a!=="ok")throw new Error(`seed failed: ${JSON.stringify(a)}`)},r=(e={})=>l({...p,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});f("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1");await s(n,h,"s1"),await n.handleControl(r());const y=(await o(h)).map(w=>JSON.parse(w));i(y.map(w=>w.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),i(new Set(y.map(w=>w.pokeId)).size).toBe(1),i(y[1]?.shapeId).toBe("s1"),i(y[2]?.checkpoint).toBe(20)}finally{e?.()}}),f("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1"),y=d(a,t,"c-bob","s2");await s(n,h,"s1"),await s(n,y,"s2"),await n.handleControl(r());const w=await o(h);i(w.length).toBe(3);const S=await o(y);i(S.length).toBe(0),await n.handleControl(r());const u=await o(h);i(u.length).toBe(3)}finally{e?.()}}),f("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1");await s(n,h,"s1"),await n.handleControl(r({epoch:"e2"}));const y=await o(h);i(y.length).toBe(0),await n.handleControl(r());const w=await o(h);i(w.length).toBe(3)}finally{e?.()}})}),k("RLS identity under live subscription",()=>{const g="shard-a",p={args:{},name:"lobby-messages"},d={args:{},name:"my-orders"},c=s=>{const r=[],e=[],t={fetch:(a,n)=>(r.push(JSON.parse(n?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},o=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>g,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:a=>a}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(a,n,h)=>(e.push(h),a===d.name?{columns:["id"],effectiveWhere:{org:h?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",sql:()=>s});if(o===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:o,posts:r,resolvedUnder:e}},l=async(s,r)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...r,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};f("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:r}=m();try{const{owner:e,resolvedUnder:t}=c(r.sql);await l(e,d),i(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),f("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:r}=m();try{const{owner:e,posts:t}=c(r.sql);await l(e,d),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(a=>a.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),f("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:r}=m();try{const{owner:e,posts:t}=c(r.sql);await l(e,p),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(a=>a.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{D as defineEngineContractSuite};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as E}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-GKR3y97k.mjs";import{liftSourceId as x}from"./liftSourceId-DApAbu7Q.mjs";import{normalizeSourceValue as K}from"./liftSourceId-DApAbu7Q.mjs";import{runExternalSourceTick as v,materializeExternalRowsIncremental as M}from"./materializeExternalRows-
|
|
1
|
+
import{LunoraError as E}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-GKR3y97k.mjs";import{liftSourceId as x}from"./liftSourceId-DApAbu7Q.mjs";import{normalizeSourceValue as K}from"./liftSourceId-DApAbu7Q.mjs";import{runExternalSourceTick as v,materializeExternalRowsIncremental as M}from"./materializeExternalRows-DmYwTW_A.mjs";const _="__lunora_source_cursor",D=e=>e instanceof Date?`d:${e.toISOString()}`:typeof e=="bigint"?`b:${e.toString()}`:typeof e=="number"?`n:${e.toString()}`:`s:${e}`,R=e=>{const t=e.slice(2);switch(e[0]){case"b":return BigInt(t);case"d":return new Date(t);case"n":return Number(t);default:return t}},k=/^-?\d+$/,I=/^-?\d+(?:\.\d+)?$/,A=(e,t)=>e instanceof Date&&t instanceof Date?e.getTime()>t.getTime():typeof e=="bigint"&&typeof t=="bigint"||typeof e=="number"&&typeof t=="number"?e>t:typeof e=="string"&&typeof t=="string"&&I.test(e)&&I.test(t)?k.test(e)&&k.test(t)?BigInt(e)>BigInt(t):Number(e)>Number(t):String(e)>String(t),q=(e,t,a)=>{let n=a===null?void 0:R(a);for(const r of e){const s=r[t];if(s==null)continue;const i=s;(n===void 0||A(i,n))&&(n=i)}return n===void 0?null:D(n)},O=e=>{h(e,m`CREATE TABLE IF NOT EXISTS ${m.identifier(_)} (
|
|
2
2
|
table_name TEXT NOT NULL,
|
|
3
3
|
shard_key TEXT NOT NULL,
|
|
4
4
|
watermark TEXT,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{applyCdcChanges as m}from"./CDC_LOG_TABLE-
|
|
1
|
+
import{applyCdcChanges as m}from"./CDC_LOG_TABLE-q7MSIAzR.mjs";import{selectShapeRows as f}from"./selectShapeMemberIds-TPdvxh2A.mjs";import{diffExternalSource as g,projectExternalSourceRow as c}from"./diffExternalSource-DMpkJta1.mjs";import{stableStringify as p}from"./stableStringify-BjLh4gvA.mjs";const x=async(t,s,r,e)=>{const{changes:n,nextBaseline:a}=g(s,r,e);return await m(t,n),{applied:n.length,nextBaseline:a}},E=async(t,s,r)=>{const{columns:e,deletedIds:n,table:a}=r,i=[];for(const u of s){const l=c(u,e),o=String(l._id);if(n?.has(o)){await t.get(o,a)&&i.push({id:o,op:"delete",seq:0,table:a,ts:0});continue}const d=await t.get(o,a);d&&p(c({...d,_id:o},e))===p(l)||i.push({doc:l,id:o,op:"insert",seq:0,table:a,ts:0})}return await m(t,i),{applied:i.length}},h=(t,s,r)=>{const e=new Map;for(const{doc:n,id:a}of f(t,s,void 0))e.set(a,p(c({...n,_id:a},r)));return e},R=async(t,s,r,e)=>{const n=h(t,e.table,e.columns);return x(s,r,n,e)};export{x as materializeExternalRows,E as materializeExternalRowsIncremental,h as readExternalSourceBaseline,R as runExternalSourceTick};
|
package/dist/packem_shared/{runShardMigrations-CPxqCh3O.mjs → runShardMigrations-MWWmpqzb.mjs}
RENAMED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{l as I,T as N,c as l}from"./FTS_COUNT_COLUMN-D1gY3wwZ-CZHdaRrd.mjs";import"@lunora/errors";import{sql as e}from"drizzle-orm";import{aggregateTableName as S}from"./aggregateTableName-G-eXyjcz.mjs";import{backfillSearchIndexesForTable as
|
|
1
|
+
import{l as I,T as N,c as l}from"./FTS_COUNT_COLUMN-D1gY3wwZ-CZHdaRrd.mjs";import"@lunora/errors";import{sql as e}from"drizzle-orm";import{aggregateTableName as S}from"./aggregateTableName-G-eXyjcz.mjs";import{backfillSearchIndexesForTable as g}from"./backfillAggregateIndexes-u6_SblD0.mjs";import{migrateCdcLog as p,migrateCdcMeta as h}from"./CDC_LOG_TABLE-q7MSIAzR.mjs";import{migrateClientWatermark as R}from"./CLIENT_WATERMARK_TABLE-CXsSLU8D.mjs";import{migrateGlobalShapeSnapshot as C}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DX-6-gBP.mjs";import{migrateIdempotency as O}from"./IDEMPOTENCY_TABLE-DjkEMp6w.mjs";import{migrateSearchState as U}from"./SEARCH_STATE_TABLE-eLN8U5tz.mjs";import{runDrizzle as t}from"./runDrizzle-GKR3y97k.mjs";import{DOC_COLUMN as u,jsonPathSql as E,createIndexSql as T,tableColumns as b,isFtsAvailable as X,AGG_KEY as x,AGG_VALUE as B,AGG_COUNT as c,geoTableName as G}from"./AGG_COUNT-D-wORk0b.mjs";import{sortColumnName as Y,rankTableName as F}from"./RANK_TIEBREAK-9NU5s_mi.mjs";import{recordSchemaVersion as M}from"./SCHEMA_HISTORY_MAX_VERSIONS-CHXz6p_z.mjs";const D=(r,o,a)=>{for(const i of a.indexes){const n=`${o}_${i.name}`,s=e.join(i.fields.map(f=>E(f)),e`, `);t(r,T(n,o,s,i.unique??!1))}for(const[i,n]of b(a)){if(!n.unique)continue;const s=`${o}_unique_${i}`;t(r,T(s,o,E(i),!0))}},k=(r,o,a)=>{if(!(!a.searchIndexes||a.searchIndexes.length===0||!X(r))){for(const i of a.searchIndexes){const n=l(o,i.name);t(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(n)} USING fts5(${e.identifier(I)}, ${e.identifier(N)} UNINDEXED)`),t(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${n}__vocab`)} USING fts5vocab(${e.identifier(n)}, ${e.raw("instance")})`)}g(r,o,a)}},j=(r,o,a)=>{if(a.geoIndexes)for(const i of a.geoIndexes){const n=G(o,i.name);t(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__geohash__")} TEXT NOT NULL, ${e.identifier("__lat__")} REAL NOT NULL, ${e.identifier("__lng__")} REAL NOT NULL)`);const s=`${o}__geo_${i.name}__btree`;t(r,T(s,n,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},q=(r,o,a)=>{if(a.aggregateIndexes)for(const i of a.aggregateIndexes){const n=S(o,i.name);t(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${x} TEXT PRIMARY KEY, ${B} REAL, ${c} INTEGER NOT NULL DEFAULT 0)`),t(r,e`PRAGMA table_info(${e.identifier(n)})`).toArray().some(s=>s.name==="__count__")||t(r,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${c} INTEGER NOT NULL DEFAULT 0`)}},P=(r,o,a)=>{if(a.rankIndexes)for(const i of a.rankIndexes){const n=F(o,i.name),s=i.sortBy.map((_,d)=>Y(d)),f=s.map(_=>e`${e.identifier(_)} BLOB`),$=f.length>0?e`, ${e.join(f,e`, `)}`:e``;t(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${$})`);const m=[e`${e.identifier("__partition__")} ASC`];for(const[_,d]of s.entries()){const L=i.sortBy[_]?.direction;m.push(e`${e.identifier(d)} ${e.raw(L==="desc"?"DESC":"ASC")}`)}m.push(e`${e.identifier("__id__")} ASC`);const A=`${o}__rank_${i.name}__btree`;t(r,T(A,n,e.join(m,e`, `),!1))}},ne=(r,o,a={})=>{a.schemaSnapshot!==void 0&&M(r,a.schemaSnapshot.hash,a.schemaSnapshot.json),U(r);for(const[i,n]of Object.entries(o.tables))n.shardMode?.kind!=="global"&&(t(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(i)} (
|
|
2
2
|
id TEXT PRIMARY KEY,
|
|
3
3
|
_creationTime REAL NOT NULL,
|
|
4
|
-
${e.identifier(
|
|
5
|
-
)`),D(r,i,n),
|
|
4
|
+
${e.identifier(u)} TEXT NOT NULL
|
|
5
|
+
)`),D(r,i,n),k(r,i,n),j(r,i,n),q(r,i,n),P(r,i,n));a.cdc&&(p(r),h(r),R(r)),O(r),C(r)};export{ne as runShardMigrations};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{runDrizzle as
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as $}from"./runDrizzle-GKR3y97k.mjs";import{jsonPathSql as r}from"./AGG_COUNT-D-wORk0b.mjs";const E=(s,i,a,o)=>{const d=a-(i.after??0),t=[e`${r(i.field)} IS NOT NULL`,e`${r(i.field)} < ${d}`];i.softDeleteField!==void 0&&t.push(e`${r(i.softDeleteField)} IS NULL`);const f=e`SELECT id FROM ${e.identifier(i.table)} WHERE ${e.join(t,e` AND `)} LIMIT ${e.raw(String(Math.max(0,Math.floor(o))+1))}`,l=$(s,f).toArray(),n=l.length>o,m=l.slice(0,o).map(p=>p.id);return{hasMore:n,ids:m}};export{E as selectExpiredIds};
|
package/dist/packem_shared/{selectShapeMemberIds-DvE7K6zG.mjs → selectShapeMemberIds-TPdvxh2A.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-GKR3y97k.mjs";import{DOC_COLUMN as a,rowToDocument as c,jsonPathSql as u}from"./AGG_COUNT-
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-GKR3y97k.mjs";import{DOC_COLUMN as a,rowToDocument as c,jsonPathSql as u}from"./AGG_COUNT-D-wORk0b.mjs";import{compileWhereSql as h}from"./compileWhereSql-BLcfs4QW.mjs";import{serializeSqlValue as S}from"./serializeSqlValue-DnpyaLcw.mjs";const $={fieldRef:u,serialize:S},E=i=>{if(i.length!==0)return e`id IN (${e.join(i.map(o=>e`${o}`),e`, `)})`},p=(i,o)=>{const r=[];o&&r.push(o);const t=h(i,$);return t&&r.push(t),r.length===0?e``:e` WHERE ${e.join(r,e` AND `)}`},z=(i,o,r)=>{const t=p(r,void 0),d=m(i,e`SELECT id, _creationTime, ${e.identifier(a)} FROM ${e.identifier(o)}${t}`).toArray(),n=[];for(const s of d){const f=c(s),{id:l}=s;f!==void 0&&typeof l=="string"&&n.push({doc:f,id:l})}return n},C=(i,o,r,t)=>{if(t.length===0)return new Set;const d=p(r,E(t)),n=m(i,e`SELECT id FROM ${e.identifier(o)}${d}`).toArray();return new Set(n.map(s=>s.id))};export{C as selectShapeMemberIds,z as selectShapeRows};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/shard-engine",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.8",
|
|
4
4
|
"description": "Host-neutral reactive engine for Lunora: per-shard state, OCC, CDC, reactive subscriptions, and the poke protocol. Consumes @lunora/platform host contracts and can be mounted on any platform host.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
},
|
|
50
50
|
"dependencies": {
|
|
51
51
|
"@lunora/errors": "1.0.0-alpha.12",
|
|
52
|
-
"@lunora/platform": "1.0.0-alpha.
|
|
52
|
+
"@lunora/platform": "1.0.0-alpha.4",
|
|
53
53
|
"drizzle-orm": "^0.45.2"
|
|
54
54
|
},
|
|
55
55
|
"engines": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{sql as i}from"drizzle-orm";import{runDrizzle as n}from"./runDrizzle-GKR3y97k.mjs";import{serializeSqlValue as q}from"./serializeSqlValue-DnpyaLcw.mjs";const s="__doc__",E=(e,t)=>`${e}__geo_${t}`,c=e=>`"${e.replaceAll('"','""')}"`,f=e=>e==="_id"||e==="id"?"id":e==="_creationTime"?"_creationTime":`json_extract(${s}, '$.${e.replaceAll("'","''")}')`,S=e=>i.raw(f(e)),$=(e,t)=>{const r=c(e);return t==="_id"||t==="id"?`${r}.id`:t==="_creationTime"?`${r}._creationTime`:`json_extract(${r}.${s}, '$.${t.replaceAll("'","''")}')`},A=(e,t)=>i.raw($(e,t)),I=(e,t,r,a)=>i`CREATE ${a?i`UNIQUE `:i``}INDEX IF NOT EXISTS ${i.identifier(e)} ON ${i.identifier(t)} (${r})`,_=i.identifier("__key__"),T=i.identifier("__value__"),u=i.identifier("__count__"),N=(e,t,r,a,o)=>i`INSERT INTO ${i.identifier(e)} (${_}, ${T}, ${u}) VALUES (${t}, ${r}, ${a}) ON CONFLICT(${_}) DO UPDATE SET ${o}`,O=e=>{const t=[];for(const[r,a]of Object.entries(e.shape)){const o=a._meta?.column;o&&t.push([r,o])}return t},d=e=>{if(!e)return;const t=e[s];let r;typeof t=="string"?r=JSON.parse(t):t&&typeof t=="object"?r=t:r={};const{id:a}=e;typeof a=="string"&&(r._id=a);const o=e._creationTime;return typeof o=="number"&&(r._creationTime=o),r},y=e=>{try{return d(e)}catch{return}},l=new WeakMap,U=e=>{const t=l.get(e);if(t!==void 0)return t;let r;try{n(e,i`CREATE VIRTUAL TABLE IF NOT EXISTS ${i.identifier("__lunora_fts_probe")} USING fts5(x)`),r=!0}catch{r=!1}finally{try{n(e,i`DROP TABLE IF EXISTS ${i.identifier("__lunora_fts_probe")}`)}catch{}}return l.set(e,r),r};export{u as AGG_COUNT,_ as AGG_KEY,T as AGG_VALUE,s as DOC_COLUMN,N as aggUpsertSql,I as createIndexSql,E as geoTableName,U as isFtsAvailable,f as jsonPath,S as jsonPathSql,$ as qualifiedJsonPath,A as qualifiedJsonPathSql,c as quoteIdentifier,d as rowToDocument,q as serializeSqlValue,O as tableColumns,y as tryRowToDocument};
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-GKR3y97k.mjs";import{ConflictError as l}from"./ConflictError-C8GtJmjS.mjs";const o="__cdc_log",$=t=>{a(t,e`CREATE TABLE IF NOT EXISTS ${e.identifier(o)} (
|
|
2
|
-
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
3
|
-
ts REAL NOT NULL,
|
|
4
|
-
${e.identifier("table")} TEXT NOT NULL,
|
|
5
|
-
id TEXT NOT NULL,
|
|
6
|
-
op TEXT NOT NULL,
|
|
7
|
-
doc TEXT
|
|
8
|
-
)`)},R=(t,i,s,E,c,d)=>{const r=d===void 0?null:JSON.stringify(d);a(t,e`INSERT INTO ${e.identifier(o)} (ts, ${e.identifier("table")}, id, op, doc) VALUES (${i}, ${s}, ${E}, ${c}, ${r})`)},A=(t,i={})=>{const s=i.sinceSeq??0,E=Math.max(1,Math.min(i.limit??1e3,1e4)),c=i.tables&&i.tables.size>0?e` AND ${e.identifier("table")} IN (${e.join([...i.tables].map(r=>e`${r}`),e`, `)})`:e``,d=a(t,e`SELECT seq, ts, ${e.identifier("table")}, id, op, doc FROM ${e.identifier(o)} WHERE seq > ${s}${c} ORDER BY seq ASC LIMIT ${E}`).toArray().map(r=>{const T={id:r.id,op:r.op,seq:r.seq,table:r.table,ts:r.ts};return r.doc===null?T:{...T,doc:JSON.parse(r.doc)}});return{changes:d,cursor:d.at(-1)?.seq??s}},O=(t,i)=>{a(t,e`DELETE FROM ${e.identifier(o)} WHERE seq <= ${i}`)},I=t=>{const i=a(t,e`SELECT seq FROM sqlite_sequence WHERE name = ${o}`).toArray()[0]?.seq;return typeof i=="number"?i:a(t,e`SELECT MAX(seq) AS seq FROM ${e.identifier(o)}`).toArray()[0]?.seq??0},S=t=>a(t,e`SELECT MIN(seq) AS seq FROM ${e.identifier(o)}`).toArray()[0]?.seq??void 0,n="__cdc_meta",p=t=>{a(t,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (id INTEGER PRIMARY KEY CHECK (id = 1), epoch TEXT NOT NULL)`)},m=t=>{p(t);const i=a(t,e`SELECT epoch FROM ${e.identifier(n)} WHERE id = 1`).toArray()[0]?.epoch;if(typeof i=="string"&&i.length>0)return i;const s=crypto.randomUUID();return a(t,e`INSERT INTO ${e.identifier(n)} (id, epoch) VALUES (1, ${s})`),s},q=t=>{p(t);const i=crypto.randomUUID();return a(t,e`INSERT INTO ${e.identifier(n)} (id, epoch) VALUES (1, ${i}) ON CONFLICT(id) DO UPDATE SET epoch = excluded.epoch`),i},C=async(t,i)=>{if(i.op==="delete"){await t.delete(i.id,i.table);return}const s=i.doc??{};try{await t.insert(i.table,s,{allowExplicitId:!0})}catch(E){if(!(E instanceof l))throw E;const c={};for(const[d,r]of Object.entries(s))d!=="_id"&&(c[d]=r);await t.replace(i.id,c,void 0,{allowExplicitId:!0})}},h=async(t,i)=>{for(const s of i)await C(t,s)};export{o as CDC_LOG_TABLE,n as CDC_META_TABLE,R as appendCdcChange,h as applyCdcChanges,q as bumpCdcEpoch,$ as migrateCdcLog,p as migrateCdcMeta,S as minCdcSeq,A as readCdcChanges,I as readCdcCursor,m as readCdcEpoch,O as trimCdcChanges};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as b}from"@lunora/errors";import{n as St,A as Pe,T as Se,y as Tt,c as _t}from"./FTS_COUNT_COLUMN-D1gY3wwZ-CZHdaRrd.mjs";import{sql as n}from"drizzle-orm";import{aggregateSqlFunction as Te,normalizeCountArgument as Rt,throwingScheduler as At}from"./AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{encodeAggregateKey as Me,readAggregateValue as Ce,aggregateTableName as ke}from"./aggregateTableName-G-eXyjcz.mjs";import{mergeWhere as Q,CountRlsUnsupportedError as Le,selectIndexForGroupBy as xt,selectIndexForCount as vt,selectIndexForAggregate as It}from"./CountRlsUnsupportedError-B2WKJD9v.mjs";import{backfillSearchIndexesForTable as Mt}from"./backfillAggregateIndexes-BHiewuB-.mjs";import{backfillAggregateIndexes as mr,backfillRankIndexes as $r,backfillSearchIndexes as gr}from"./backfillAggregateIndexes-BHiewuB-.mjs";import{appendCdcChange as Ct}from"./CDC_LOG_TABLE-BnqlH2eZ.mjs";import{CDC_LOG_TABLE as yr,applyCdcChanges as Er,bumpCdcEpoch as Nr,minCdcSeq as Sr,readCdcChanges as Tr,readCdcCursor as _r,readCdcEpoch as Rr,trimCdcChanges as Ar}from"./CDC_LOG_TABLE-BnqlH2eZ.mjs";import{createCompanionSync as kt}from"./createCompanionSync-DWK0Vlg1.mjs";import{computeRankPage as Ze}from"./computeRankPage-IUSS-zIB.mjs";import{SCAN_DEP as B}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as F}from"./runDrizzle-GKR3y97k.mjs";import{DOC_COLUMN as P,quoteIdentifier as Lt,AGG_VALUE as _e,AGG_COUNT as De,AGG_KEY as Re,jsonPathSql as z,rowToDocument as de,tableColumns as pt,isFtsAvailable as Dt,tryRowToDocument as wt,geoTableName as Ot,qualifiedJsonPathSql as et}from"./AGG_COUNT-BWXe3gtQ.mjs";import{coveringGeohashes as Wt,boundingBoxGeohashes as Ft,pointInBoundingBox as qt,haversineMeters as Bt}from"./GEO_DEFAULT_PRECISION-okRCkZ6r.mjs";import{NotFoundError as Ut}from"./NotFoundError-BhF7FeFr.mjs";import{normalizeOrderKeys as Pt,buildSeekWhere as mt,decodeCursor as qe,applySelect as tt,encodeCursor as Be,softDeleteScope as le,buildSeekBeforeWhere as jt}from"./applySelect-B0CF8T7y.mjs";import{sortColumnName as nt,resolveRankPartition as Ht,encodePartitionKey as Gt,RANK_TIEBREAK as Kt,rankTableName as rt}from"./RANK_TIEBREAK-9NU5s_mi.mjs";import{indexKeysForRow as Qt,buildIndexRange as zt}from"./buildIndexRange-DFsdtPjD.mjs";import{assertFlatPredicate as Oe,resolveRelationPredicates as it}from"./DEFAULT_MAX_RELATION_KEYS-bq00btqV.mjs";import{runRowValidators as We,resolveWith as ot,applyOnDelete as Jt,fanOutScalarCounts as Yt}from"./applyOnDelete-uFRC5p1d.mjs";import{guardWriter as Vt}from"./RLS_UNWRAP_SYMBOL-CBYPlYBb.mjs";import{createSystemReader as Xt}from"./createSystemReader-DcDcrtM3.mjs";import{ConflictError as me}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as Zt}from"./hasTrigger-CbkOHExZ.mjs";import{compileWhereSql as ne}from"./compileWhereSql-BLcfs4QW.mjs";import{CLIENT_WATERMARK_TABLE as vr,advanceClientWatermark as Ir,migrateClientWatermark as Mr,readClientWatermark as Cr}from"./CLIENT_WATERMARK_TABLE-CXsSLU8D.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Lr,deleteGlobalShapeSnapshot as Dr,deleteGlobalShapeSnapshotsForConnection as Or,migrateGlobalShapeSnapshot as Wr,readGlobalShapeSnapshot as Fr,writeGlobalShapeSnapshot as qr}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DX-6-gBP.mjs";import{IDEMPOTENCY_TABLE as Ur,readIdempotent as Pr,trimIdempotent as jr,writeIdempotent as Hr}from"./IDEMPOTENCY_TABLE-DjkEMp6w.mjs";import{runShardMigrations as Kr}from"./runShardMigrations-CPxqCh3O.mjs";import{SEARCH_STATE_TABLE as zr}from"./SEARCH_STATE_TABLE-eLN8U5tz.mjs";import{selectShapeMemberIds as Yr,selectShapeRows as Vr}from"./selectShapeMemberIds-DvE7K6zG.mjs";import{serializeSqlValue as re}from"./serializeSqlValue-DnpyaLcw.mjs";const en=i=>{const o=new TextEncoder().encode(i);let t="";for(const l of o)t+=String.fromCodePoint(l);return btoa(t)},tn=i=>{const o=atob(i),t=Uint8Array.from(o,l=>l.codePointAt(0)??0);return new TextDecoder().decode(t)},nn=()=>new b("BAD_REQUEST","invalid cursor"),at=16,st=8,Z=1024,je=(i,o)=>o.query(i),rn=(i,o,t)=>{const l=St(i,t);if(l.length===0)return 0;let c=0;for(const[p,m]of o.entries()){const R=p===o.length-1;let S=0;for(const $ of l)(R?$.startsWith(m):$===m)&&(S+=1);if(S===0)return 0;c+=S}return c},on=(i,o)=>{if(!o)return{exact:!0,lower:i,upper:i};const t=[...i].at(-1)??"",l=(t.codePointAt(0)??0)+1;if(l>=55296&&l<=57343||l>1114111)return{exact:!0,lower:i,upper:i};const c=i.slice(0,i.length-t.length);return{exact:!1,lower:i,upper:c+String.fromCodePoint(l)}},an=(i,o,t)=>{const l={eq:(c,p)=>{if(!i.definition.filterFields?.includes(c))throw new b("INTERNAL",`field "${c}" is not a filter field of search index "${i.indexName}" on table "${o}"`);if(i.filters.length>=st)throw new b("BAD_REQUEST",`search index "${i.indexName}" on table "${o}": at most ${String(st)} .eq() filters are supported per search query`);return i.filters.push({field:c,value:p}),l},search:(c,p)=>{const m=i;if(c!==m.definition.field)throw new b("INTERNAL",`search index "${m.indexName}" on table "${o}" indexes "${m.definition.field}", not "${c}"`);const R=je(p,t).length;if(R>at)throw new b("BAD_REQUEST",`search index "${m.indexName}" on table "${o}": at most ${String(at)} search terms are supported (got ${String(R)})`);return m.field=c,m.query=p,m.hasQuery=!0,l}};return l},sn=i=>{if(i.length>Z)throw new b("BAD_REQUEST",`more than ${String(Z)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},ln=i=>Math.min(i.offset+i.numItems+1,Z),dn=i=>en(`search:${String(i)}`),cn=i=>{let o;try{o=tn(i)}catch{return}if(!o.startsWith("search:"))return;const t=Number(o.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},un=i=>{if(typeof i.endCursor=="string")throw new b("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");const o=Math.max(0,Math.floor(i.numItems)),t=i.cursor?cn(i.cursor):0;if(t===void 0)throw nn();if(t+o>Z)throw new b("BAD_REQUEST",`search pagination reaches past the ${String(Z)}-document limit (offset ${String(t)} + ${String(o)} requested) — narrow the query or the filters instead`);return{numItems:o,offset:t}},fn=(i,o)=>{const t=o.offset+o.numItems,l=o.numItems>0&&i.length>t;return{continueCursor:l?dn(t):null,isDone:!l,page:i.slice(o.offset,t)}},hn=i=>{if(i===void 0)return Z+1;if(!Number.isFinite(i))return Z;const o=Math.max(0,Math.floor(i));if(o>Z)throw new b("BAD_REQUEST",`search returns at most ${String(Z)} documents (asked for ${String(o)}) — narrow the query or paginate instead`);return o},pn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,wn=i=>{if(!pn.test(i))throw new b("INTERNAL",`invalid clientId ${JSON.stringify(i)}: a client-supplied row id must be a UUID`)},lt=50,$t=500,mn=128,se=(i,o,t)=>{const l=o??$t;if(i>l)throw new b("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(i)} exceeds the limit of ${String(l)} (raise options.limit or chunk the call)`,{status:400})},$n=i=>{const o={eq:(t,l)=>(i.sqlConditions.push({comparator:"=",field:t,value:l}),o),gt:(t,l)=>(i.sqlConditions.push({comparator:">",field:t,value:l}),o),gte:(t,l)=>(i.sqlConditions.push({comparator:">=",field:t,value:l}),o),lt:(t,l)=>(i.sqlConditions.push({comparator:"<",field:t,value:l}),o),lte:(t,l)=>(i.sqlConditions.push({comparator:"<=",field:t,value:l}),o)};return o},gn=i=>Math.max(i,Z),bn=(i,o,t,l,c)=>{const p=je(t.query,Pe(t.definition.language));if(p.length===0)return[];const m=_t(o,t.indexName),R=`${m}__vocab`,S=p.length-1,$=p.map((C,L)=>{const j=on(C,L===S),U=j.exact?n`${n.identifier("term")} = ${j.lower}`:n`${n.identifier("term")} >= ${j.lower} AND ${n.identifier("term")} < ${j.upper}`;return n`SELECT ${n.identifier("doc")}, ${n.raw(String(L))} AS ${n.identifier("__term__")}, COUNT(*) AS ${n.identifier("__n__")} FROM ${n.identifier(R)} WHERE ${U} GROUP BY ${n.identifier("doc")}`}),y=p.map((C,L)=>n`SUM(CASE WHEN u.${n.identifier("__term__")} = ${n.raw(String(L))} THEN u.${n.identifier("__n__")} ELSE 0 END)`),E=n`SELECT f.${n.identifier(Se)} AS ${n.identifier(Se)}, ${n.join(y,n` + `)} AS ${n.identifier("__score__")} FROM (${n.join($,n` UNION ALL `)}) u JOIN ${n.identifier(m)} f ON f.rowid = u.${n.identifier("doc")} GROUP BY f.${n.identifier(Se)} HAVING ${n.join(y.map(C=>n`${C} > 0`),n` AND `)}`,_=[];for(const C of t.filters)_.push(n`${z(C.field)} = ${re(C.value)}`);c&&_.push(c);let M=n`SELECT m.id, m._creationTime, m.${n.identifier(P)}, s.${n.identifier("__score__")} AS ${n.identifier("__score__")} FROM (${E}) s JOIN ${n.identifier(o)} m ON m.id = s.${n.identifier(Se)}`;_.length>0&&(M=n`${M} WHERE ${n.join(_,n` AND `)}`),M=n`${M} ORDER BY s.${n.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${n.raw(String(l))}`;const O=[];for(const C of F(i,M)){const L=wt(C);if(L){const j=C.__score__;O.push({document:L,score:typeof j=="number"?j:Number(j??0)})}}return O},yn=(i,o,t,l,c)=>{const p=Pe(t.definition.language),m=je(t.query,p);if(m.length===0)return[];const R=[];for(const E of t.filters)R.push(n`${z(E.field)} = ${re(E.value)}`);c&&R.push(c);let S=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(o)}`;R.length>0&&(S=n`${S} WHERE ${n.join(R,n` AND `)}`),S=n`${S} ORDER BY _creationTime DESC, id ASC LIMIT ${n.raw(String(gn(l)))}`;const $=F(i,S).toArray(),y=[];for(const E of $){const _=wt(E);if(!_)continue;const M=rn(Tt(_,t.definition),m,p);M>0&&y.push({creationTime:typeof _._creationTime=="number"?_._creationTime:0,doc:_,id:typeof _._id=="string"?_._id:"",score:M})}return y.sort((E,_)=>_.score-E.score||_.creationTime-E.creationTime||E.id.localeCompare(_.id)),y.slice(0,l).map(E=>({document:E.doc,score:E.score}))},Fe=(i,o,t,l)=>{if(!Number.isFinite(i.lat)||i.lat<-90||i.lat>90||!Number.isFinite(i.lng)||i.lng<-180||i.lng>180)throw new b("BAD_REQUEST",`geo index "${l}" on table "${t}": ${o} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},En=(i,o)=>{const t=i,l={near:(c,p)=>{if(t.within)throw new b("INTERNAL",`geo index "${t.indexName}" on table "${o}": call .near() or .within(), not both`);if(Fe(c,".near() point",o,t.indexName),!Number.isFinite(p)||p<=0)throw new b("BAD_REQUEST",`geo index "${t.indexName}" on table "${o}": .near() radiusMeters must be a finite number > 0, got ${String(p)}`);return t.near={point:{lat:c.lat,lng:c.lng},radiusMeters:p},l},within:c=>{if(t.near)throw new b("INTERNAL",`geo index "${t.indexName}" on table "${o}": call .near() or .within(), not both`);if(Fe(c.sw,".within() sw corner",o,t.indexName),Fe(c.ne,".within() ne corner",o,t.indexName),c.sw.lat>c.ne.lat)throw new b("BAD_REQUEST",`geo index "${t.indexName}" on table "${o}": .within() corners are transposed (sw.lat > ne.lat)`);if(c.sw.lng>c.ne.lng)throw new b("BAD_REQUEST",`geo index "${t.indexName}" on table "${o}": .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:c.ne.lat,lng:c.ne.lng},sw:{lat:c.sw.lat,lng:c.sw.lng}},l}};return l},Nn=(i,o)=>{const t=i[o];if(t===null||typeof t!="object")return;const{lat:l,lng:c}=t;return typeof l=="number"&&typeof c=="number"?{lat:l,lng:c}:void 0},Sn=(i,o)=>{const t=Nn(i,o.definition.field);if(!t)return;const l=typeof i._creationTime=="number"?i._creationTime:0;if(o.near){const c=Bt(o.near.point,t);return c<=o.near.radiusMeters?{creationTime:l,distance:c}:void 0}return qt(t,o.within)?{creationTime:l,distance:0}:void 0},gt=(i,o,t,l)=>{if(!t.near&&!t.within)throw new b("INTERNAL",`geo index "${t.indexName}" on table "${o}": call .near(point, radius) or .within(box)`);const c=t.near?Wt(t.near.point,t.near.radiusMeters):Ft(t.within),p=Ot(o,t.indexName),m=c.map(E=>n`(g.${n.identifier("__geohash__")} >= ${E} AND g.${n.identifier("__geohash__")} < ${`${E}{`})`),R=[n`(${n.join(m,n` OR `)})`];l&&R.push(l);const S=n`SELECT m.id, m._creationTime, m.${n.identifier(P)} FROM ${n.identifier(p)} g JOIN ${n.identifier(o)} m ON m.id = g.${n.identifier("__id__")} WHERE ${n.join(R,n` AND `)}`,$=F(i,S).toArray(),y=[];for(const E of $){const _=de(E),M=_?Sn(_,t):void 0;_&&M&&y.push({creationTime:M.creationTime,distance:M.distance,doc:_})}return y.sort((E,_)=>E.distance-_.distance||_.creationTime-E.creationTime),y},Tn=(i,o,t,l,c,p=()=>{})=>{const m=gt(i,o,t,c).map(R=>R.doc);return p(m.length),typeof l=="number"?m.slice(0,Math.max(0,Math.floor(l))):m},_n=(i,o,t,l,c,p=()=>{})=>{const m=t.within!==void 0,R=gt(i,o,t,c).map(S=>({distanceMeters:m?null:S.distance,document:S.doc}));return p(R.length),R},Rn=(i,o,t,l,c,p=()=>{})=>{const{geo:m}=t;if(!m)throw new b("INTERNAL","runGeoTerminal called without a staged geo query");const R=t.inMemoryFilters.length>0,S=Tn(i,o,m,R?void 0:c,l,p);if(!R)return S;const $=[];for(const y of S)if(t.inMemoryFilters.every(E=>E(y))&&($.push(y),typeof c=="number"&&$.length>=c))break;return $},An=(i,o,t,l,c,p=()=>{})=>{const{geo:m}=t;if(!m)throw new b("INTERNAL","runGeoTerminalScored called without a staged geo query");const R=t.inMemoryFilters.length>0,S=_n(i,o,m,R?void 0:c,l,p);if(!R)return S;const $=[];for(const y of S)t.inMemoryFilters.every(E=>E(y.document))&&$.push(y);return $},xn=(i,o,t,l,c,p,m=()=>{})=>{const R=[];for(const E of t.sqlConditions)R.push(n`${z(E.field)} ${n.raw(E.comparator)} ${re(E.value)}`);l&&R.push(l);let S=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(o)}`;R.length>0&&(S=n`${S} WHERE ${n.join(R,n` AND `)}`),S=n`${S} ORDER BY ${c}`,typeof p=="number"&&t.inMemoryFilters.length===0&&(S=n`${S} LIMIT ${n.raw(String(Math.max(0,Math.floor(p))))}`);const $=F(i,S).toArray();m($.length);const y=[];for(const E of $){const _=de(E);if(_&&t.inMemoryFilters.every(M=>M(_))&&(y.push(_),typeof p=="number"&&y.length>=p))break}return y},oe={fieldRef:z,serialize:re},vn=i=>{let o=0;const t=[],l={fieldRef:z,relationExists:c=>{const{childWhere:p,negated:m,parentTable:R,relation:S}=c,$=`__rel_${String(o)}`,y=t.at(-1)??R;o+=1,i(S.table,B);const E=S.kind==="one"?S.field:S.references,_=S.kind==="one"?S.references:S.field,M=n`${et($,_)} = ${et(y,E)}`;t.push($);const O=ne(p,l);t.pop();const C=O?n`${M} AND ${O}`:M,L=n`EXISTS (SELECT 1 FROM ${n.identifier(S.table)} AS ${n.identifier($)} WHERE ${C})`;return m?n`NOT ${L}`:L},serialize:re};return l},bt=i=>{const o=i.map(t=>n`${z(t.field)} ${n.raw(t.direction==="desc"?"DESC":"ASC")}`);return i.some(t=>t.field==="_id"||t.field==="id")||o.push(n`${z("id")} ASC`),n.join(o,n`, `)},In={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},Mn=i=>{const o=i.order;return i.indexFields.length>0?i.indexFields.map(t=>({direction:o,field:t})):[{direction:o,field:"_creationTime"}]},Cn=(i,o,t,l)=>{const c=i.sqlConditions.map(p=>({[p.field]:{[In[p.comparator]??"eq"]:p.value}}));if(t&&c.push(mt(o,qe(t))),l&&c.push(jt(o,qe(l))),c.length!==0)return c.length===1?c[0]:{AND:c}},kn=(i,o,t)=>{const l=[];for(const c of i){const p=de(c);if(p&&o.every(m=>m(p))&&(l.push(p),t!==void 0&&l.length>t))break}return l},Ln=(i,o,t,l,c,p=()=>{})=>{const m=Math.max(0,Math.floor(l.numItems)),R=Mn(t),S=typeof l.endCursor=="string",$=ne(Cn(t,R,l.cursor,l.endCursor),oe),y=c&&$?n`${$} AND ${c}`:c??$;let E=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(o)}`;y&&(E=n`${E} WHERE ${y}`),E=n`${E} ORDER BY ${bt(R)}`;const _=t.inMemoryFilters.length>0;!_&&!S&&(E=n`${E} LIMIT ${n.raw(String(m+1))}`);const M=F(i,E).toArray();p(M.length);const O=kn(M,t.inMemoryFilters,_||S?void 0:m);if(S){const U=O.length>=2?O[Math.floor(O.length/2)-1]:void 0;return{continueCursor:l.endCursor??null,isDone:!0,page:O,splitCursor:U?Be(U,R):null}}const C=O.length>m,L=C?O.slice(0,m):O,j=L.at(-1);return{continueCursor:C&&j?Be(j,R):null,isDone:!C,page:L}};class Dn extends b{constructor(o="unique() found more than one matching document"){super("NOT_UNIQUE",o,{name:"NotUniqueError"})}}const On=/\s/u,Wn=String.fromCodePoint(0),dt=(i,o,t)=>{if(!i.tables[o])throw new b("INTERNAL",`unknown table: ${o}`);return typeof t!="string"||t.length===0||On.test(t)||t.includes(Wn)?null:t},Fn=(i,o,t,l=()=>{},c=()=>{},p=()=>{})=>{const m=o.tables[t];if(!m)throw new b("INTERNAL",`unknown table: ${t}`);const R=le(m.softDeleteMode,void 0),S=R?ne(R,oe):void 0,$={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let y=0;const E=N=>{const{search:I}=$;if(!I)throw new b("INTERNAL","runSearchFetch called without a staged search");Mt(i,t,m);const v=$.inMemoryFilters.length>0,k=hn(v?void 0:N),H=Dt(i)?bn(i,t,I,k,S):yn(i,t,I,k,S);if(!v)return N===void 0&&sn(H),H;const X=[];y=H.length;for(const ce of H)if($.inMemoryFilters.every(ue=>ue(ce.document))&&(X.push(ce),typeof N=="number"&&X.length>=N))break;return X},_=N=>E(N).map(I=>I.document),M=N=>{const I=un(N);return fn(_(ln(I)),I)},O=()=>{const N=$.indexFields.length>0?$.indexFields:["_creationTime"],I=$.order==="desc"?"DESC":"ASC";return n.join(N.map(v=>n`${z(v)} ${n.raw(I)}`),n`, `)},C=()=>{if($.search||$.geo||$.indexName===void 0){c(void 0);return}c(zt(t,$.indexName,$.indexFields,$.sqlConditions,re))},L=N=>{C();let I=0;const v=(()=>{if($.search){const k=_(N);return I=y,k}return $.geo?Rn(i,t,$,S,N,k=>{I=k}):xn(i,t,$,S,O(),N,k=>{I=k})})();return p(Math.max(I,v.length)),v},j=()=>{if(!$.search&&!$.geo)throw new b("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);C();let N=0;const I=(()=>{if($.search){const v=E(void 0);return N=y,v}return An(i,t,$,S,void 0,v=>{N=v})})();return p(Math.max(N,I.length)),I},U={async*[Symbol.asyncIterator](){const N=[...$.inMemoryFilters];let I;$.inMemoryFilters=[];try{for(;;){const v=await U.paginate({cursor:I??null,numItems:mn});for(const k of v.page)N.every(H=>H(k))&&(yield k);if(v.isDone||v.continueCursor===null)return;I=v.continueCursor}}finally{$.inMemoryFilters=N}},async collect(){return L(void 0)},async collectWithScores(){return j()},filter(N){return $.inMemoryFilters.push(N),U},async first(){return L($.inMemoryFilters.length>0?void 0:1)[0]??null},order(N){return $.order=N==="desc"?"desc":"asc",U},async paginate(N){let I=0;if(C(),$.search){const k=M(N);return p(k.page.length),k}if($.geo)throw new b("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const v=Ln(i,t,$,N,S,k=>{I=k});return p(Math.max(I,v.page.length)),v},async take(N){return L(N)},async unique(){const N=L($.inMemoryFilters.length>0?void 0:2);if(N.length>1)throw new Dn(`unique() on table "${t}" matched ${String(N.length)} documents; expected at most one`);return N[0]??null},withGeoIndex(N,I){const v=(m.geoIndexes??[]).find(H=>H.name===N);if(!v)throw new b("INTERNAL",`unknown geo index "${N}" on table "${t}"`);l(t,N,"geo");const k={definition:v,indexName:N};if($.geo=k,I(En(k,t)),!k.near&&!k.within)throw new b("INTERNAL",`geo index "${N}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return U},withIndex(N,I){const v=m.indexes.find(k=>k.name===N);if(!v)throw new b("INTERNAL",`unknown index "${N}" on table "${t}"`);return l(t,N,"index"),$.indexName=N,$.indexFields=v.fields,I&&I($n($)),U},withSearchIndex(N,I){const v=(m.searchIndexes??[]).find(H=>H.name===N);if(!v)throw new b("INTERNAL",`unknown search index "${N}" on table "${t}"`);l(t,N,"search");const k={definition:v,field:v.field,filters:[],hasQuery:!1,indexName:N,query:""};if($.search=k,I(an(k,t,Pe(v.language))),!k.hasQuery)throw new b("INTERNAL",`search index "${N}" on table "${t}" requires a .search(field, query) call`);return U}};return U},ct=(i,o,t)=>{const l={...o};for(const[c,p]of pt(i)){if(p.serverDefault){l[c]=p.serverDefault({auth:t});continue}l[c]===void 0&&(p.defaultFn?l[c]=p.defaultFn():"defaultValue"in p&&(l[c]=p.defaultValue))}return l},ut=(i,o,t,l)=>{const c=t;for(const[p,m]of pt(i)){if(m.serverDefault){p in o&&(c[p]=m.serverDefault({auth:l}));continue}m.onUpdateFn&&!(p in o)&&(c[p]=m.onUpdateFn())}},ft=(i,o)=>{for(const t of Object.keys(o))if(o[t]===void 0)throw new b("INTERNAL",`Cannot ${i} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},qn=/unique constraint failed/i,Bn=i=>i instanceof Error&&qn.test(i.message),Ue=(i,o,t)=>{try{F(i,t)}catch(l){throw Bn(l)?new me(`unique constraint violation on "${o}"`,"unique"):l}},Ae=(i,o,t)=>{if(Ue(i,o,t),F(i,n`SELECT changes() AS changed`).one().changed===0)throw new me(`optimistic concurrency conflict on "${o}" — the row changed during this mutation; refetch and retry`,"occ")},ht=(i,o,t,l,c,p,m)=>{const R=[];for(let E=0;E<t.length+1;E+=1){const _=[];for(let L=0;L<E;L+=1)_.push(n`${n.identifier(t[L])} IS ${p[L]}`);const M=t[E],O=l[E];if(M!==void 0&&O!==void 0){const L=O.direction==="desc"?">":"<";_.push(n`${n.identifier(M)} ${n.raw(L)} ${p[E]}`)}else _.push(n`${n.identifier(Kt)} < ${m}`);const[C]=_;R.push(_.length===1&&C!==void 0?C:n`(${n.join(_,n` AND `)})`)}const S=n.join(R,n` OR `),$=F(i,n`SELECT COUNT(*) AS c FROM ${n.identifier(o)} WHERE ${n.identifier("__partition__")} = ${c} AND (${S})`).one(),y=F(i,n`SELECT COUNT(*) AS c FROM ${n.identifier(o)} WHERE ${n.identifier("__partition__")} = ${c}`).one();return{before:$.c,total:y.c}},hr=i=>{const{sql:o}=i,{schema:t}=i,l=i.broadcast??(()=>{}),c=(e,...r)=>{const a=t.tables[e]?.indexes;if(!a||a.length===0)return;const h=[];for(const f of r)f&&h.push(...Qt(a,f,re));return h.length>0?h:void 0},{headroom:p}=i;let m=!1;const R=async e=>{const r=m;m=!0;try{return await e()}finally{m=r}},S=i.onRead??(()=>{}),$=i.onReadRange??(e=>{S(e.table,B)}),y=(e,r)=>{r!==void 0&&r!==B&&!m&&p?.recordRead(1),S(e,r)},E=i.onIndexUse??(()=>{}),_=i.onWrite??(()=>{}),M=async e=>{m||p?.recordWrite(e.doc),await _(e)},{cache:O}=i,C=i.clock??(()=>Date.now()),L=i.idGenerator??(()=>crypto.randomUUID()),j=i.scheduler??At,{globalDb:U}=i,N=i.auth??{identity:null,userId:null},I=i.cdc??!1,v=j,k=Xt({scheduler:typeof v.list=="function"&&typeof v.get=="function"?v:void 0,storage:i.storage}),H=(e,r,a,h)=>{I&&Ct(o,C(),e,r,a,h)},X=e=>t.tables[e]?.shardMode?.kind==="global",ce=(e,r)=>{if(X(e)){if(!U)throw new b("INTERNAL",`cross-backend ${r} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return U}return q},ue=e=>ce(e,"cascade"),J=(e,r)=>{if(X(e)){if(!U)throw new b("INTERNAL",`${r} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return U}},fe=()=>U,xe=(e,r)=>ce(e,"relation load").findMany(e,r),He=(e,r)=>(X(e)&&y(e,B),xe(e,r)),yt=e=>!X(e.table),Ge=i.relationExistsPushDown??"auto",Ke=Ge!=="never",{maxRelationKeys:Qe}=i,$e=(e,r,a)=>it(e,{fetcher:He,maxRelationKeys:Qe,relationBaseWhere:a,schema:t,tableName:r}),ze=async(e,r,a,h)=>{const f=J(e,"relation grouped count");if(f)return y(e,B),Yt((x,K)=>f.count(x,K),e,r,a,h);const d=t.tables[e];if(!d)throw new b("INTERNAL",`unknown table: ${e}`);y(e,B);const s=le(d.softDeleteMode,void 0),u={[r]:{in:a}},w=Q(Q(u,h),s),T=await $e(w,e,void 0),g=ne(T,oe),A=z(r);let W=n`SELECT ${A} AS __fk__, COUNT(*) AS count FROM ${n.identifier(e)}`;g&&(W=n`${W} WHERE ${g}`),W=n`${W} GROUP BY ${A}`;const D=F(o,W).toArray();return new Map(D.map(x=>[x.__fk__,x.count]))};let ge=0;const Je=new Set;for(const[e,r]of Object.entries(t.tables))for(const a of Object.values(r.triggerMap??{}))Je.add(`${e} ${a.timing} ${a.op}`);const ee=(e,r,a)=>Je.has(`${e} ${r} ${a}`),te=async(e,r,a)=>{if(ge+=1,ge>lt)throw ge-=1,new me(`trigger recursion exceeded ${String(lt)} levels on "${a.table}" — check for a self-triggering write`,"trigger");try{await Zt({ctx:Nt,event:a,op:r,schema:t,tableName:a.table,timing:e})}finally{ge-=1}},{ensureBackfilledForTable:he,ensureBackfilledIndex:ve,ensureRankBackfilled:Ie,ensureRankBackfilledForTable:pe,syncAggregates:be,syncCompanionsForInsert:Ye,syncGeo:ye,syncRanks:we,syncSearch:Ee}=kt({broadcast:l,indexKeysFor:(e,r)=>c(e,r),invalidateCache:(e,r,a)=>O?.invalidate(e,r,c(e,a)),recordCdc:H,schema:t,sql:o}),Ve=(e,r,a)=>{const{shardMode:h}=r;if(h?.kind==="shardBy"&&!(h.field!==void 0&&(a.partitionBy??[]).includes(h.field)))throw Object.assign(new Error(`rank index "${a.name}" on "${e}" partitions across shards (shard key "${h.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})},ie=(e,r)=>{const a=Object.entries(t.tables).filter(([,T])=>T.shardMode?.kind!=="global").map(([T])=>T).filter(T=>r===void 0||T===r);if(a.length===0)return;const h=a.map(T=>n`SELECT ${n.raw(`'${T.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(T)} WHERE id = ${e}`),f=n`${n.join(h,n` UNION ALL `)} LIMIT 1`,[d]=F(o,f).toArray();if(!d)return;const s=d.__t__,u=de(d);if(typeof s!="string"||!u)return;const w=d[P];return{docJson:typeof w=="string"?w:JSON.stringify(w??{}),row:u,tableName:s}},Et=(e,r)=>{const a=[...new Set(e)],h=new Map;if(a.length===0)return h;const f=Object.entries(t.tables).filter(([,s])=>s.shardMode?.kind!=="global").map(([s])=>s).filter(s=>r===void 0||s===r);if(f.length===0)return h;const d=Math.max(1,Math.floor(900/f.length));for(let s=0;s<a.length;s+=d){const u=a.slice(s,s+d),w=n.join(u.map(A=>n`${A}`),n`, `),T=f.map(A=>n`SELECT ${n.raw(`'${A.replaceAll("'","''")}'`)} AS __t__, id FROM ${n.identifier(A)} WHERE id IN (${w})`),g=n.join(T,n` UNION ALL `);for(const A of F(o,g)){const{id:W,__t__:D}=A;typeof D=="string"&&typeof W=="string"&&h.set(W,D)}}return h},Xe={assertRankPartitionLocal:Ve,ensureRankBackfilled:Ie,onRead:y,rowToDocument:de,schema:t,sql:o},q={system:k,async aggregate(e,r){const a=J(e,"aggregate");if(a)return y(e,B),a.aggregate(e,r);const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);if(Te(r.op),r.op==="count")return q.count(e,{baseWhere:r.baseWhere,relationBaseWhere:r.relationBaseWhere,restrictsCounts:r.restrictsCounts,where:r.where});if(!r.field)throw new b("INTERNAL",`aggregate(${e}, { op: "${r.op}" }): "field" is required for non-count reducers`);y(e,B);const f=le(h.softDeleteMode,void 0),d=Q(Q(r.baseWhere,r.where),f),s=await $e(d,e,r.relationBaseWhere),u=s!==d;if(h.aggregateIndexes&&!r.baseWhere&&!u&&!f){const D=It(h.aggregateIndexes,r.op,r.field,r.where);if(D){ve(e,D.index);const x=Me(D.index.by??[],D.key),K=ke(e,D.index.name),Y=F(o,n`SELECT ${_e} AS value, ${De} AS count FROM ${n.identifier(K)} WHERE ${Re} = ${x}`).toArray()[0];return Ce(r.op,Y)}}const w=ne(s,oe),T=Te(r.op),g=z(r.field);let A=n`SELECT ${n.raw(T)}(${g}) AS value FROM ${n.identifier(e)}`;return w&&(A=n`${A} WHERE ${w}`),F(o,A).toArray()[0]?.value??null},asId(e,r){const a=dt(t,e,r);if(a===null)throw new b("BAD_REQUEST",`asId("${e}", …): "${r}" is not a valid id for table "${e}"`,{status:400});return a},async count(e,r){const a=J(e,"count");if(a)return y(e,B),a.count(e,r);const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);const f=Rt(r);if(f.restrictsCounts)throw new Le(e);y(e,B);const d=le(h.softDeleteMode,void 0),s=Q(Q(f.baseWhere,f.where),d),u=await $e(s,e,f.relationBaseWhere),w=u!==s;if(h.aggregateIndexes&&!f.baseWhere&&!w&&!d){const A=vt(h.aggregateIndexes,f.where);if(A){ve(e,A.index);const W=Me(A.index.by??[],A.key),D=ke(e,A.index.name),x=F(o,n`SELECT ${_e} AS value FROM ${n.identifier(D)} WHERE ${Re} = ${W}`).toArray();return x[0]===void 0?0:x[0].value??0}}const T=ne(u,oe);let g=n`SELECT COUNT(*) AS count FROM ${n.identifier(e)}`;return T&&(g=n`${g} WHERE ${T}`),F(o,g).one().count},async delete(e,r,a){const h=ie(e,r);if(!h){const g=r===void 0?fe():void 0;g&&await g.delete(e,void 0,a);return}const{docJson:f,row:d,tableName:s}=h,u=t.tables[s],w=a?.hard===!0,T=!w&&u?.softDeleteMode?u.softDeleteMode.field:void 0;if(!(T&&d[T]!==null&&d[T]!==void 0)){if(ee(s,"before","delete")&&await te("before","delete",{id:e,op:"delete",previous:d,table:s}),await Jt({deletedId:e,deletedReference:g=>d[g],findHolders:async(g,A,W)=>(await ue(g).findMany(g,{includeDeleted:w,where:{[A]:W}})).page,onCascade:(g,A)=>ue(g).delete(A,void 0,a),onRestrict:g=>{throw new me(g,"restrict")},onSetNull:(g,A,W)=>ue(g).patch(A,{[W]:null}),schema:t,tableName:s}),he(s),pe(s),T){const g={...d,[T]:C(),_id:e};Ae(o,s,n`UPDATE ${n.identifier(s)} SET ${n.identifier(P)} = ${JSON.stringify(g)} WHERE id = ${e} AND ${n.identifier(P)} = ${f}`),Ee(s,e,g,d),ye(s,e,void 0),be(s,d,g),we(s,e,d,void 0),O?.invalidate(s,e,c(s,d,g)),H(s,e,"update",g),l({indexKeys:c(s,d,g),key:e,op:"update",row:g,table:s}),ee(s,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:d,table:s}),await M({id:e,op:"delete",table:s});return}Ae(o,s,n`DELETE FROM ${n.identifier(s)} WHERE id = ${e} AND ${n.identifier(P)} = ${f}`),Ee(s,e,void 0),ye(s,e,void 0),be(s,d,void 0),we(s,e,d,void 0),O?.invalidate(s,e,c(s,d)),H(s,e,"delete"),l({indexKeys:c(s,d),key:e,op:"delete",table:s}),ee(s,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:d,table:s}),await M({id:e,op:"delete",table:s})}},async deleteAll(e,r){if(!t.tables[e])throw new b("INTERNAL",`unknown table: ${e}`);const a=Math.max(1,r?.chunkSize??$t),h=r?.hard===void 0?void 0:{hard:r.hard},f=X(e)?void 0:e;let d=0;return await R(async()=>{for(;;){const s=(await q.findMany(e,{limit:a})).page.map(u=>String(u._id));if(s.length===0)break;for(const u of s)await q.delete(u,f,h),d+=1;if(s.length<a)break}}),{deleted:d}},async deleteMany(e,r,a){se(e.length,r?.limit,"deleteMany");for(const h of e)await q.delete(h,a);return{deleted:e.length}},async deleteWhere(e,r,a){const h=J(e,"deleteWhere");let f;if(h)f=(await h.findMany(e,{where:r})).page.map(d=>String(d._id));else{if(!t.tables[e])throw new b("INTERNAL",`unknown table: ${e}`);f=(await q.findMany(e,{where:r})).page.map(d=>String(d._id))}if(se(f.length,a?.limit,"deleteWhere"),q.deleteMany===void 0)throw new b("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return q.deleteMany(f,a)},async findFirst(e,r={}){return(await q.findMany(e,{...r,limit:1})).page[0]??null},async findFirstOrThrow(e,r={}){const a=await q.findFirst(e,r);if(a===null)throw new Ut(`findFirstOrThrow: no "${e}" document matched`);return a},async findMany(e,r={}){const a=J(e,"findMany");if(a)return y(e,B),a.findMany(e,r);const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);const f=!r.where&&!r.baseWhere;f?y(e,B):y(e);const d=Pt(r.orderBy),s=r.cursor?mt(d,qe(r.cursor)):void 0;let u=Q(r.baseWhere,r.where);u=Q(u,le(h.softDeleteMode,r.includeDeleted)),u=await it(u,{canPushExists:Ke?yt:void 0,existsPushMode:Ge==="always"?"always":"auto",fetcher:He,maxRelationKeys:Qe,relationBaseWhere:r.relationBaseWhere,schema:t,tableName:e}),s&&(u=u?{AND:[u,s]}:s);const w=Ke?vn(y):oe,T=ne(u,w);let g=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(e)}`;T&&(g=n`${g} WHERE ${T}`),g=n`${g} ORDER BY ${bt(d)}`;const A=typeof r.limit=="number"?Math.max(0,Math.floor(r.limit)):void 0;A!==void 0&&(g=n`${g} LIMIT ${n.raw(String(A+1))}`);const W=F(o,g).toArray();f&&!m&&p?.recordRead(W.length);const D=[];for(const V of W){const G=de(V);G&&(D.push(G),!f&&typeof G._id=="string"&&y(e,G._id))}if(A===void 0)return r.with&&await ot({groupedCounter:ze,fetcher:xe,parents:D,relationBaseWhere:r.relationBaseWhere,schema:t,tableName:e,with:r.with}),{continueCursor:null,isDone:!0,page:tt(D,r.select,r.with)};const x=D.length>A,K=x?D.slice(0,A):D,Y=K.at(-1);return r.with&&await ot({fetcher:xe,groupedCounter:ze,parents:K,relationBaseWhere:r.relationBaseWhere,schema:t,tableName:e,with:r.with}),{continueCursor:x&&Y?Be(Y,d):null,isDone:!x,page:tt(K,r.select,r.with)}},async get(e,r){const a=ie(e,r);if(!a){const h=r===void 0?fe():void 0;return h?h.get(e):null}return y(a.tableName,e),a.row},async lookupById(e,r){const a=ie(e,r);return a?(y(a.tableName,e),{row:a.row,tableName:a.tableName}):null},async groupBy(e,r){const a=J(e,"groupBy");if(a)return y(e,B),a.groupBy(e,r);const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);y(e,B);const f=r.agg??{op:"count"};if(Te(f.op),f.op!=="count"&&!f.field)throw new b("INTERNAL",`groupBy(${e}, { agg: { op: "${f.op}" } }): "field" is required for non-count reducers`);const d=le(h.softDeleteMode,void 0),s=Q(Q(r.baseWhere,r.where),d),u=await $e(s,e,r.relationBaseWhere),w=u!==s;if(h.aggregateIndexes&&!r.baseWhere&&!w&&!d){const x=xt(h.aggregateIndexes,f.op,f.field,r.by,r.where);if(x){ve(e,x.index);const K=ke(e,x.index.name),Y=Object.keys(x.partial),V=[];if(Y.length===(x.index.by??[]).length&&Y.length>0){const ae=Me(x.index.by??[],x.partial),Ne=F(o,n`SELECT ${_e} AS value, ${De} AS count FROM ${n.identifier(K)} WHERE ${Re} = ${ae}`).toArray();return Ne.length>0&&V.push({key:{...x.partial},value:Ce(f.op,Ne[0])}),V}const G=F(o,n`SELECT ${Re} AS key, ${_e} AS value, ${De} AS count FROM ${n.identifier(K)}`).toArray();for(const ae of G){const Ne=JSON.parse(ae.key);V.push({key:Ne,value:Ce(f.op,ae)})}return V}}const T=ne(u,oe),g=r.by.map(x=>n`${z(x)} AS ${n.identifier(x)}`);if(f.op==="count")g.push(n`COUNT(*) AS value`);else{const{field:x}=f;if(x===void 0)throw new b("INTERNAL",`groupBy(${e}, { agg: { op: "${f.op}" } }): "field" is required for non-count reducers`);g.push(n`${n.raw(Te(f.op))}(${z(x)}) AS value`)}let A=n`SELECT ${n.join(g,n`, `)} FROM ${n.identifier(e)}`;T&&(A=n`${A} WHERE ${T}`),A=n`${A} GROUP BY ${n.join(r.by.map(x=>z(x)),n`, `)}`;const W=F(o,A).toArray(),D=[];for(const x of W){const K={};for(const V of r.by)K[V]=x[V]??null;const{value:Y}=x;D.push({key:K,value:Y==null?null:Number(Y)})}return D},async insert(e,r,a){const h=J(e,"insert");if(h){const T=await h.insert(e,r,a);return m||p?.recordWrite(r),l({key:T,op:"insert",row:{...r,_id:T},table:e}),T}const f=t.tables[e];if(!f)throw new b("INTERNAL",`unknown table: ${e}`);const d=ct(f,r,N);We(f,d);let s;a?.clientId!==void 0?(wn(a.clientId),s=a.clientId):a?.allowExplicitId&&typeof d._id=="string"?s=d._id:s=L();const u=a?.allowExplicitId&&typeof d._creationTime=="number"?d._creationTime:C(),w={...d,_creationTime:u,_id:s};return ee(e,"before","insert")&&await te("before","insert",{doc:{...w},id:s,op:"insert",table:e}),he(e),pe(e),Ue(o,e,n`INSERT INTO ${n.identifier(e)} (id, _creationTime, ${n.identifier(P)}) VALUES (${s}, ${u}, ${JSON.stringify(w)})`),Ye(e,s,w),ee(e,"after","insert")&&await te("after","insert",{doc:w,id:s,op:"insert",table:e}),await M({doc:w,id:s,op:"insert",table:e}),s},async insertManyUnsafe(e,r,a){if(se(r.length,a?.limit,"insertManyUnsafe"),r.length===0)return[];const h=J(e,"insert");if(h){const u=[];for(const w of r){const T=await h.insert(e,w,{allowExplicitId:a?.allowExplicitId});m||p?.recordWrite(w),l({key:T,op:"insert",row:{...w,_id:T},table:e}),u.push(T)}return u}const f=t.tables[e];if(!f)throw new b("INTERNAL",`unknown table: ${e}`);he(e),pe(e);const d=r.map(u=>{const w=ct(f,u,N),T=a?.allowExplicitId===!0&&typeof w._id=="string"?w._id:L(),g=a?.allowExplicitId===!0&&typeof w._creationTime=="number"?w._creationTime:C();return{creationTime:g,document:{...w,_creationTime:g,_id:T},id:T}});if(!m)for(const u of d)p?.recordWrite(u.document);const s=n.join(d.map(u=>n`(${u.id}, ${u.creationTime}, ${JSON.stringify(u.document)})`),n`, `);Ue(o,e,n`INSERT INTO ${n.identifier(e)} (id, _creationTime, ${n.identifier(P)}) VALUES ${s}`);for(const{document:u,id:w}of d)Ye(e,w,u),await _({doc:u,id:w,op:"insert",table:e});return d.map(u=>u.id)},async insertMany(e,r,a){se(r.length,a?.limit,"insertMany");const h=a?.skipDuplicates===!0,f=[];for(const d of r)try{f.push(await q.insert(e,d))}catch(s){if(h&&s instanceof me&&s.kind==="unique")f.push(null);else throw s}return f},normalizeId(e,r){return dt(t,e,r)},async patch(e,r,a){const h=ie(e,a);if(!h){const T=a===void 0?fe():void 0;if(T){await T.patch(e,r);return}throw new b("INTERNAL",`document not found: ${e}`)}const{docJson:f,row:d,tableName:s}=h,u=t.tables[s];if(!u)throw new b("INTERNAL",`unknown table: ${s}`);y(s,e),ft("patch",r);const w={...d,...r,_id:e};ut(u,r,w,N),We(u,w,!0),ee(s,"before","update")&&await te("before","update",{doc:{...w},id:e,op:"update",previous:d,table:s}),he(s),pe(s),Ae(o,s,n`UPDATE ${n.identifier(s)} SET ${n.identifier(P)} = ${JSON.stringify(w)} WHERE id = ${e} AND ${n.identifier(P)} = ${f}`),Ee(s,e,w,d),ye(s,e,w),be(s,d,w),we(s,e,d,w),O?.invalidate(s,e,c(s,d,w)),H(s,e,"update",w),l({indexKeys:c(s,d,w),key:e,op:"update",row:w,table:s}),ee(s,"after","update")&&await te("after","update",{doc:w,id:e,op:"update",previous:d,table:s}),await M({doc:w,id:e,op:"update",table:s})},async patchMany(e,r,a){se(e.length,r?.limit,"patchMany");for(const h of e)await q.patch(h.id,h.patch,a);return{patched:e.length}},async patchWhere(e,r,a){const h=J(e,"patchWhere");let f;if(h)f=(await h.findMany(e,{where:r.where})).page.map(d=>({id:String(d._id),patch:r.patch}));else{if(!t.tables[e])throw new b("INTERNAL",`unknown table: ${e}`);f=(await q.findMany(e,{where:r.where})).page.map(d=>({id:String(d._id),patch:r.patch}))}if(se(f.length,a?.limit,"patchWhere"),q.patchMany===void 0)throw new b("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await q.patchMany(f,a),{patched:f.length}},query(e){const r=J(e,"query");return r?(y(e,B),r.query(e)):Fn(o,t,e,E,a=>{a?$(a):y(e,B)},a=>{m||p?.recordRead(a)})},async rank(e,r,a){const h=J(e,"rank");if(h)return y(e,B),h.rank(e,r,a);E(e,r,"rank");const f=t.tables[e];if(!f)throw new b("INTERNAL",`unknown table: ${e}`);const d=f.rankIndexes?.find(G=>G.name===r);if(!d)throw new b("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(Ve(e,f,d),a.restrictsCounts)throw new Le(e);y(e,B),Ie(e,d);const s=typeof a.row=="string"?a.row:a.row._id;if(!s)return null;const u=rt(e,d.name),w=d.sortBy.map((G,ae)=>nt(ae)),T=w.map(G=>Lt(G)).join(", "),g=F(o,n`SELECT ${n.identifier("__partition__")}, ${n.raw(T)} FROM ${n.identifier(u)} WHERE ${n.identifier("__id__")} = ${s}`).toArray(),[A]=g;if(A===void 0)return null;let W=A.__partition__;const D=Q(a.baseWhere,a.where);Oe(D,t,e,"rank");const x=Ht(d,D);if(x){const G=Gt(d.partitionBy??[],x);if(G!==W)return null;W=G}const K=w.map(G=>A[G]),{before:Y,total:V}=ht(o,u,w,d.sortBy,W,K,s);return{position:Y+1,total:V}},async rankBefore(e,r,a){if(X(e))throw new b("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);const f=h.rankIndexes?.find(w=>w.name===r);if(!f)throw new b("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(a.restrictsCounts)throw new Le(e);y(e,B),Ie(e,f);const d=rt(e,f.name),s=f.sortBy.map((w,T)=>nt(T)),u=f.sortBy.map((w,T)=>re(a.sortValues[T]??null));return ht(o,d,s,f.sortBy,a.partitionKey,u,a.rowId)},async rankPage(e,r,a={}){Oe(Q(a.baseWhere,a.where),t,e,"rankPage");const h=J(e,"rankPage");if(h)return y(e,B),h.rankPage(e,r,a);E(e,r,"rank");const{continueCursor:f,hasMore:d,rows:s}=Ze(Xe,e,r,a);return{continueCursor:f,isDone:!d,page:s.map(u=>u.doc)}},async rankPageRows(e,r,a={}){Oe(Q(a.baseWhere,a.where),t,e,"rankPage"),E(e,r,"rank");const{directions:h,hasMore:f,rows:d}=Ze(Xe,e,r,a);return{directions:h,hasMore:f,rows:d}},async restore(e,r){const a=ie(e,r);if(!a){const d=r===void 0?fe():void 0;if(d?.restore){await d.restore(e);return}throw new b("INTERNAL",`document not found: ${e}`)}const h=t.tables[a.tableName]?.softDeleteMode?.field;if(!h)throw new b("INTERNAL",`ctx.db.restore: table "${a.tableName}" is not a .softDelete() table`);const f=a.row[h]!==null&&a.row[h]!==void 0;await q.patch(e,{[h]:null},r),f&&we(a.tableName,e,void 0,a.row)},async replace(e,r,a,h){const f=ie(e,a);if(!f){const A=a===void 0?fe():void 0;if(A){await A.replace(e,r,void 0,h);return}throw new b("INTERNAL",`document not found: ${e}`)}const{docJson:d,row:s,tableName:u}=f,w=t.tables[u];if(!w)throw new b("INTERNAL",`unknown table: ${u}`);ft("replace",r);const T=h?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:C(),g={...r,_creationTime:T,_id:e};ut(w,r,g,N),We(w,g),ee(u,"before","update")&&await te("before","update",{doc:{...g},id:e,op:"update",previous:s,table:u}),he(u),pe(u),Ae(o,u,n`UPDATE ${n.identifier(u)} SET _creationTime = ${T}, ${n.identifier(P)} = ${JSON.stringify(g)} WHERE id = ${e} AND ${n.identifier(P)} = ${d}`),Ee(u,e,g,s),ye(u,e,g),be(u,s,g),we(u,e,s,g),O?.invalidate(u,e,c(u,s,g)),H(u,e,"update",g),l({indexKeys:c(u,s,g),key:e,op:"update",row:g,table:u}),ee(u,"after","update")&&await te("after","update",{doc:g,id:e,op:"update",previous:s,table:u}),await M({doc:g,id:e,op:"update",table:u})},async wipeShard(e){const r=new Set(e?.exclude),a=e?.tables,h=Object.entries(t.tables).filter(([u,w])=>r.has(u)||a!==void 0&&!a.includes(u)?!1:w.shardMode?.kind!=="global").map(([u])=>u);if(a!==void 0){for(const u of a)if(!t.tables[u])throw new b("INTERNAL",`wipeShard: unknown table: ${u}`)}const f={};let d=0;const{deleteAll:s}=q;if(s===void 0)throw new b("INTERNAL","wipeShard: this writer has no deleteAll");for(const u of h){const w=await s(u,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});f[u]=w.deleted,d+=w.deleted}return{deleted:d,tables:f}}},Nt={db:q,scheduler:j};return i.enforceRls===!0?Vt(q,t,(e,r)=>ie(e,r)?.tableName,(e,r)=>Et(e,r)):q};export{yr as CDC_LOG_TABLE,vr as CLIENT_WATERMARK_TABLE,Lr as GLOBAL_SHAPE_SNAPSHOT_TABLE,Ur as IDEMPOTENCY_TABLE,Dn as NotUniqueError,zr as SEARCH_STATE_TABLE,Ir as advanceClientWatermark,Er as applyCdcChanges,wn as assertValidClientId,mr as backfillAggregateIndexes,$r as backfillRankIndexes,gr as backfillSearchIndexes,Nr as bumpCdcEpoch,hr as createShardCtxDb,Dr as deleteGlobalShapeSnapshot,Or as deleteGlobalShapeSnapshotsForConnection,Mr as migrateClientWatermark,Wr as migrateGlobalShapeSnapshot,Sr as minCdcSeq,dt as normalizeIdStructurally,Tr as readCdcChanges,_r as readCdcCursor,Rr as readCdcEpoch,Cr as readClientWatermark,Fr as readGlobalShapeSnapshot,Pr as readIdempotent,Kr as runShardMigrations,Yr as selectShapeMemberIds,Vr as selectShapeRows,Ar as trimCdcChanges,jr as trimIdempotent,qr as writeGlobalShapeSnapshot,Hr as writeIdempotent};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{A as R,T as S,l as O,y as I,c as b}from"./FTS_COUNT_COLUMN-D1gY3wwZ-CZHdaRrd.mjs";import"@lunora/errors";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as A}from"./AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{encodeAggregateKey as _,foldAggregateTally as L,aggregateTableName as M}from"./aggregateTableName-G-eXyjcz.mjs";import{migrateSearchState as k,readSearchBackfillState as C,writeSearchBackfillState as N}from"./SEARCH_STATE_TABLE-eLN8U5tz.mjs";import{runDrizzle as c}from"./runDrizzle-GKR3y97k.mjs";import{isFtsAvailable as u,DOC_COLUMN as g,rowToDocument as p,AGG_KEY as w,AGG_VALUE as y,AGG_COUNT as x,tryRowToDocument as F}from"./AGG_COUNT-BWXe3gtQ.mjs";import{param as D}from"./param-B5lF5Jd9.mjs";import{sortColumnName as U,matchesRankStaticWhere as B,encodePartitionKey as G,rankTableName as j}from"./RANK_TIEBREAK-9NU5s_mi.mjs";import{serializeSqlValue as v}from"./serializeSqlValue-DnpyaLcw.mjs";const V=(i,t)=>i.profile!==t?{cursor:void 0,finished:!1,wipe:i.cursor!==void 0||i.done}:{cursor:i.cursor,finished:i.done,wipe:!1},W=(i,t,r)=>{const o=M(t,r.name);if(c(i,e`SELECT COUNT(*) AS count FROM ${e.identifier(o)}`).one().count>0)return;const n=r.by??[],s=new Map,d=c(i,e`SELECT id, _creationTime, ${e.identifier(g)} FROM ${e.identifier(t)}`).toArray();for(const f of d){const a=p(f);if(!a||r.where&&!A(a,r.where))continue;const m=_(n,a);L(s,m,r,a)}for(const[f,a]of s)c(i,e`INSERT INTO ${e.identifier(o)} (${w}, ${y}, ${x}) VALUES (${f}, ${a.value}, ${a.count})`)},oe=(i,t)=>{for(const[r,o]of Object.entries(t.tables))if(!(o.shardMode?.kind==="global"||!o.aggregateIndexes))for(const n of o.aggregateIndexes)W(i,r,n)},z=(i,t,r)=>{const o=j(t,r.name);if(c(i,e`SELECT COUNT(*) AS count FROM ${e.identifier(o)}`).one().count>0)return;const n=r.sortBy.map((f,a)=>U(a)),s=e.join(["__id__","__partition__",...n].map(f=>e.identifier(f)),e`, `),d=c(i,e`SELECT id, _creationTime, ${e.identifier(g)} FROM ${e.identifier(t)}`).toArray();for(const f of d){const a=p(f);if(!a||r.where&&!B(a,r.where))continue;const m=G(r.partitionBy??[],a),E=r.sortBy.map($=>v(a[$.field]??null)),l=e.join([a._id,m,...E].map($=>D($)),e`, `);c(i,e`INSERT INTO ${e.identifier(o)} (${s}) VALUES (${l})`)}},re=(i,t)=>{for(const[r,o]of Object.entries(t.tables))if(!(o.shardMode?.kind==="global"||!o.rankIndexes))for(const n of o.rankIndexes)z(i,r,n)},T=500,h=(i,t,r)=>{const o=b(t,r.name),{profile:n}=R(r.language),s=V(C(i,o),n);if(s.finished)return!0;s.wipe&&c(i,e`DELETE FROM ${e.identifier(o)}`);const{cursor:d}=s,f=c(i,d===void 0?e`SELECT id, _creationTime, ${e.identifier(g)} FROM ${e.identifier(t)} ORDER BY id ASC LIMIT ${e.raw(String(T))}`:e`SELECT id, _creationTime, ${e.identifier(g)} FROM ${e.identifier(t)} WHERE id > ${d} ORDER BY id ASC LIMIT ${e.raw(String(T))}`).toArray();let a=d;for(const E of f){const{id:l}=E;if(typeof l!="string")continue;a=l;const $=F(E);if(!$){c(i,e`DELETE FROM ${e.identifier(o)} WHERE ${e.identifier(S)} = ${l}`);continue}c(i,e`DELETE FROM ${e.identifier(o)} WHERE ${e.identifier(S)} = ${l}`),c(i,e`INSERT INTO ${e.identifier(o)} (${e.identifier(O)}, ${e.identifier(S)}) VALUES (${I($,r)}, ${l})`)}const m=f.length<T;return N(i,o,a,m,n),m},te=(i,t,r)=>{if(u(i))for(const o of r.searchIndexes??[])o.staged||h(i,t,o)},ae=(i,t)=>{if(u(i)){k(i);for(const[r,o]of Object.entries(t.tables))if(!(o.shardMode?.kind==="global"||!o.searchIndexes))for(const n of o.searchIndexes){let s=!1;for(;!s;)s=h(i,r,n)}}};export{oe as backfillAggregateIndexes,re as backfillRankIndexes,ae as backfillSearchIndexes,te as backfillSearchIndexesForTable};
|