@lunora/shard-engine 1.0.0-alpha.1 → 1.0.0-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/conformance/index.mjs +1 -1
- package/dist/index.d.mts +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/NotUniqueError-Bw1Oh2FL.mjs +1 -0
- package/dist/packem_shared/{defineEngineContractSuite-CVwNQvzx.mjs → defineEngineContractSuite-ii3_DS_I.mjs} +1 -1
- package/package.json +1 -1
- package/dist/packem_shared/NotUniqueError-B4piAtjk.mjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-
|
|
1
|
+
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-ii3_DS_I.mjs";export{t as defineEngineContractSuite};
|
package/dist/index.d.mts
CHANGED
|
@@ -339,6 +339,7 @@ interface GeoFilterBuilderLike {
|
|
|
339
339
|
}) => GeoFilterBuilderLike;
|
|
340
340
|
}
|
|
341
341
|
interface TableReaderLike {
|
|
342
|
+
[Symbol.asyncIterator]: () => AsyncIterator<Record<string, unknown>>;
|
|
342
343
|
collect: () => Promise<Record<string, unknown>[]>;
|
|
343
344
|
filter: (predicate: (document: Record<string, unknown>) => boolean) => TableReaderLike;
|
|
344
345
|
first: () => Promise<Record<string, unknown> | null>;
|
package/dist/index.d.ts
CHANGED
|
@@ -339,6 +339,7 @@ interface GeoFilterBuilderLike {
|
|
|
339
339
|
}) => GeoFilterBuilderLike;
|
|
340
340
|
}
|
|
341
341
|
interface TableReaderLike {
|
|
342
|
+
[Symbol.asyncIterator]: () => AsyncIterator<Record<string, unknown>>;
|
|
342
343
|
collect: () => Promise<Record<string, unknown>[]>;
|
|
343
344
|
filter: (predicate: (document: Record<string, unknown>) => boolean) => TableReaderLike;
|
|
344
345
|
first: () => Promise<Record<string, unknown> | null>;
|
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 p,aggregateSqlFunction as d,matchesStaticWhere as c,normalizeCountArgument as S,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{aggregateTableName as f,coerceAggregateNumber as E,encodeAggregateKey as g,foldAggregateTally as A,readAggregateValue as h}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 y,appendAuditEntry as M,ensureAuditTable as O,readAuditLog as D}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-B4piAtjk.mjs";import{backfillAggregateIndexes as q,backfillRankIndexes as w,backfillSearchIndexes as W,backfillSearchIndexesForTable as K}from"./packem_shared/backfillAggregateIndexes-BHiewuB-.mjs";import{CDC_LOG_TABLE as z,CDC_META_TABLE as V,appendCdcChange as X,applyCdcChanges as H,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-BCBUOnMk.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as pe,deleteGlobalShapeSnapshot as de,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 Ee,migrateIdempotency as ge,readIdempotent as Ae,trimIdempotent as he,writeIdempotent as Te}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 Ne,writeSearchBackfillState as ye}from"./packem_shared/SEARCH_STATE_TABLE-eLN8U5tz.mjs";import{selectShapeMemberIds as Oe,selectShapeRows as De}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-CaO6L0Ee.mjs";import{SCAN_DEP as Ue,createDependencyTracker as qe,depKey as we,tableFromDepKey as We}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 Xe,AGG_KEY as He,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 pr}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 Ar,readExternalSourceBaseline as hr,runExternalSourceTick as Tr}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 Nr,boundingBoxCenter as yr,boundingBoxGeohashes as Mr,coveringGeohashes as Or,encodeGeohash as Dr,haversineMeters as Fr,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 qr,MAX_PAGE_SIZE as wr,RELATION_FUNCTION_PREFIX as Wr,createFanoutCounters as Kr,facetColumn as vr,findStorageReferences as zr,listTables as Vr,readTablePage as Xr,recordFanoutPass as Hr,selectMatchingIds as Qr,summarizeFanoutTopics as Yr,summarizeSubscriptions as jr}from"./packem_shared/ADMIN_FUNCTIONS-B0xlQJ4w.mjs";import{MAIL_RETENTION as Zr,MAIL_TABLE as $r,clearCapturedMail as eo,ensureMailTable as ro,readCapturedMail as oo,recordCapturedMail as ao}from"./packem_shared/MAIL_RETENTION-KmozO2NQ.mjs";import{NotFoundError as no}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as io,readBookmark as so}from"./packem_shared/armRestore-BNzdvQ_o.mjs";import{applySelect as po,buildSeekBeforeWhere as co,buildSeekWhere as So,decodeCursor as uo,encodeCursor as xo,normalizeOrderKeys as fo,softDeleteScope as Eo}from"./packem_shared/applySelect-B0CF8T7y.mjs";import{QUEUE_TABLE as Ao,clearQueueMessages as ho,isLossyBody as To,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 No,rankKeyFromDoc as yo,rankTableName as Mo,resolveRankPartition as Oo,sortColumnName as Do}from"./packem_shared/RANK_TIEBREAK-9NU5s_mi.mjs";import{ReactiveCache as Po,reactiveCacheKey as ko}from"./packem_shared/ReactiveCache-1_9Rs7J_.mjs";import{DEFAULT_MAX_RELATION_KEYS as Go,assertFlatPredicate as Uo,assertShapeShardable as qo,containsRelationPredicate as wo,isRelationPredicate as Wo,resolveRelationPredicates as Ko}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-bq00btqV.mjs";import{applyOnDelete as zo,distinctValues as Vo,fanOutScalarCounts as Xo,resolveWith as Ho,runRowValidators as Qo}from"./packem_shared/applyOnDelete-uFRC5p1d.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as jo,clampPromotionThresholds as Jo,nextPromotionState as Zo,relayCountFor as $o,shapeRoutingKey as ea}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-Dteg0sZF.mjs";import{DEFAULT_MAX_RELAYS as oa,OwnerRelay as aa,RelayMember as ta,createRelayLink as na}from"./packem_shared/DEFAULT_MAX_RELAYS-CnCyh6oX.mjs";import{RLS_UNWRAP_SYMBOL as ia,RlsRequiredError as sa,guardWriter as ma}from"./packem_shared/RLS_UNWRAP_SYMBOL-C6_WX3dG.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as da,readSchemaHistory as ca,readSchemaVersion as Sa,recordSchemaVersion as ua}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CHXz6p_z.mjs";import{serializeSqlValue as fa}from"./packem_shared/serializeSqlValue-DnpyaLcw.mjs";import{buildSettings as ga,isDevEnvironment as Aa}from"./packem_shared/buildSettings-DT18_DkX.mjs";import{buildPokeFrames as Ta,diffGlobalMembership as Ca,encodeRowsPatch as Ia,projectColumns as _a}from"./packem_shared/buildPokeFrames-DaPpm5Ss.mjs";import{ShardRunner as La}from"./packem_shared/ShardRunner-DIqVdWtk.mjs";import{runSocketPool as Na}from"./packem_shared/runSocketPool-DPQLVyWF.mjs";import{MAX_SQL_ROWS as Ma,assertReadonly as Oa,lintReadonlySql as Da,runReadonlySql as Fa}from"./packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs";import{awaitWsDrain as ka,sendDeltaFrames as Ba,subscriptionListDeltas as Ga,trySendFrame as Ua}from"./packem_shared/awaitWsDrain-Dk50ISgE.mjs";import{createSystemReader as wa}from"./packem_shared/createSystemReader-DcDcrtM3.mjs";import{ConflictError as Ka}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{hasTrigger as za,runTriggers as Va}from"./packem_shared/hasTrigger-CbkOHExZ.mjs";import{selectExpiredIds as Ha}from"./packem_shared/selectExpiredIds-FzhIEeG1.mjs";import{compileWhereSql as Ya}from"./packem_shared/compileWhereSql-BLcfs4QW.mjs";import{RELATION_EXISTS_KEY as Ja}from"./packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs";import{runShardMigrations as $a}from"./packem_shared/runShardMigrations-CPxqCh3O.mjs";import{stableStringify as rt}from"./packem_shared/stableStringify-BjLh4gvA.mjs";import{stableWireKey as at}from"./packem_shared/stableWireKey-YEHLaX6X.mjs";export{Br as ADMIN_FUNCTIONS,Gr as ADMIN_FUNCTION_PREFIX,p as AGGREGATE_SQL_FUNCTION,Xe as AGG_COUNT,He as AGG_KEY,Qe as AGG_VALUE,y as AUDIT_LOG_TABLE,z as CDC_LOG_TABLE,V as CDC_META_TABLE,ae as CLIENT_WATERMARK_TABLE,Ka as ConflictError,C as CountRlsUnsupportedError,Pe as DATA_MIGRATION_STATE_TABLE,Ur as DEFAULT_FANOUT_TOPIC_LIMIT,Go as DEFAULT_MAX_RELATION_KEYS,oa as DEFAULT_MAX_RELAYS,jo as DEFAULT_PROMOTION_THRESHOLDS,Ye as DOC_COLUMN,qr as FLAGS_FUNCTION_PREFIX,Nr as GEO_DEFAULT_PRECISION,pe as GLOBAL_SHAPE_SNAPSHOT_TABLE,Ee as IDEMPOTENCY_TABLE,Zr as MAIL_RETENTION,$r as MAIL_TABLE,wr as MAX_PAGE_SIZE,Ma as MAX_SQL_ROWS,no as NotFoundError,P as NotUniqueError,aa as OwnerRelay,Ao as QUEUE_TABLE,Lo as RANK_TIEBREAK,Ja as RELATION_EXISTS_KEY,Wr as RELATION_FUNCTION_PREFIX,ia as RLS_UNWRAP_SYMBOL,Po as ReactiveCache,ta as RelayMember,sa as RlsRequiredError,Ue as SCAN_DEP,da as SCHEMA_HISTORY_MAX_VERSIONS,Le as SEARCH_STATE_TABLE,La as ShardRunner,te as advanceClientWatermark,je as aggUpsertSql,d as aggregateSqlFunction,f as aggregateTableName,M as appendAuditEntry,X as appendCdcChange,H as applyCdcChanges,zo as applyOnDelete,po as applySelect,io as armRestore,Uo as assertFlatPredicate,Oa as assertReadonly,qo as assertShapeShardable,k as assertValidClientId,ka as awaitWsDrain,q as backfillAggregateIndexes,w as backfillRankIndexes,W as backfillSearchIndexes,K as backfillSearchIndexesForTable,yr as boundingBoxCenter,Mr as boundingBoxGeohashes,Ta as buildPokeFrames,co as buildSeekBeforeWhere,So as buildSeekWhere,ga as buildSettings,Q as bumpCdcEpoch,Jo as clampPromotionThresholds,eo as clearCapturedMail,ho as clearQueueMessages,E as coerceAggregateNumber,Ya as compileWhereSql,Ie as computeRankPage,wo as containsRelationPredicate,Or as coveringGeohashes,se as createCompanionSync,qe as createDependencyTracker,Kr as createFanoutCounters,Je as createIndexSql,na as createRelayLink,B as createShardCtxDb,wa as createSystemReader,uo as decodeCursor,de as deleteGlobalShapeSnapshot,ce as deleteGlobalShapeSnapshotsForConnection,we as depKey,cr as diffExternalSource,Ca as diffGlobalMembership,Vo as distinctValues,g as encodeAggregateKey,xo as encodeCursor,Dr as encodeGeohash,bo as encodePartitionKey,Ia as encodeRowsPatch,O as ensureAuditTable,ro as ensureMailTable,o as exportShardRows,a as exportShardTable,vr as facetColumn,Xo as fanOutScalarCounts,zr as findStorageReferences,A as foldAggregateTally,Ze as geoTableName,ma as guardWriter,za as hasTrigger,Fr as haversineMeters,_e as hydrateDocsById,t as importShardRows,Aa as isDevEnvironment,$e as isFtsAvailable,To as isLossyBody,Wo as isRelationPredicate,Ir as isSoftDeleted,_r as isSourceDue,er as jsonPath,rr as jsonPathSql,ur as liftSourceId,Da as lintReadonlySql,Vr as listTables,No as matchesRankStaticWhere,c as matchesStaticWhere,gr as materializeExternalRows,Ar as materializeExternalRowsIncremental,I as mergeWhere,Y as migrateCdcLog,j as migrateCdcMeta,ne as migrateClientWatermark,Se as migrateGlobalShapeSnapshot,ge as migrateIdempotency,be as migrateSearchState,J as minCdcSeq,Zo 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,_a as projectColumns,Rr as pullExternalSourceIncrementalTick,Lr as pullExternalSourceTick,or as qualifiedJsonPath,ar as qualifiedJsonPathSql,tr as quoteIdentifier,yo as rankKeyFromDoc,Mo as rankTableName,ko as reactiveCacheKey,h as readAggregateValue,D as readAuditLog,so as readBookmark,oo as readCapturedMail,Z as readCdcChanges,$ as readCdcCursor,ee as readCdcEpoch,le as readClientWatermark,hr as readExternalSourceBaseline,ue as readGlobalShapeSnapshot,Ae as readIdempotent,ke as readMigrationStatus,Co as readQueueMessageById,Io as readQueueMessages,ca as readSchemaHistory,Sa as readSchemaVersion,Ne as readSearchBackfillState,Xr as readTablePage,ao as recordCapturedMail,Hr as recordFanoutPass,_o as recordQueueMessages,ua as recordSchemaVersion,$o as relayCountFor,pr as renderSql,Oo as resolveRankPartition,Ko as resolveRelationPredicates,Ho as resolveWith,nr as rowToDocument,Be as runDataMigration,ve as runDrizzle,Tr as runExternalSourceTick,Fa as runReadonlySql,Qo as runRowValidators,$a as runShardMigrations,Na as runSocketPool,ze as runSql,Va as runTriggers,Ha as selectExpiredIds,i as selectExportTables,R as selectIndexForAggregate,L as selectIndexForCount,b as selectIndexForGroupBy,Qr as selectMatchingIds,Oe as selectShapeMemberIds,De as selectShapeRows,Ba as sendDeltaFrames,fa as serializeSqlValue,ea as shapeRoutingKey,Eo as softDeleteScope,Do as sortColumnName,rt as stableStringify,at as stableWireKey,Ga as subscriptionListDeltas,Yr as summarizeFanoutTopics,jr as summarizeSubscriptions,lr as tableColumns,We as tableFromDepKey,u as throwingScheduler,re as trimCdcChanges,he as trimIdempotent,ir as tryRowToDocument,Ua as trySendFrame,s as validateImportRow,xe as writeGlobalShapeSnapshot,Te as writeIdempotent,ye as writeSearchBackfillState};
|
|
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 p,aggregateSqlFunction as d,matchesStaticWhere as c,normalizeCountArgument as S,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{aggregateTableName as f,coerceAggregateNumber as E,encodeAggregateKey as g,foldAggregateTally as A,readAggregateValue as h}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 y,appendAuditEntry as M,ensureAuditTable as O,readAuditLog as D}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-Bw1Oh2FL.mjs";import{backfillAggregateIndexes as q,backfillRankIndexes as w,backfillSearchIndexes as W,backfillSearchIndexesForTable as K}from"./packem_shared/backfillAggregateIndexes-BHiewuB-.mjs";import{CDC_LOG_TABLE as z,CDC_META_TABLE as V,appendCdcChange as X,applyCdcChanges as H,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-BCBUOnMk.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as pe,deleteGlobalShapeSnapshot as de,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 Ee,migrateIdempotency as ge,readIdempotent as Ae,trimIdempotent as he,writeIdempotent as Te}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 Ne,writeSearchBackfillState as ye}from"./packem_shared/SEARCH_STATE_TABLE-eLN8U5tz.mjs";import{selectShapeMemberIds as Oe,selectShapeRows as De}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-CaO6L0Ee.mjs";import{SCAN_DEP as Ue,createDependencyTracker as qe,depKey as we,tableFromDepKey as We}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 Xe,AGG_KEY as He,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 pr}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 Ar,readExternalSourceBaseline as hr,runExternalSourceTick as Tr}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 Nr,boundingBoxCenter as yr,boundingBoxGeohashes as Mr,coveringGeohashes as Or,encodeGeohash as Dr,haversineMeters as Fr,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 qr,MAX_PAGE_SIZE as wr,RELATION_FUNCTION_PREFIX as Wr,createFanoutCounters as Kr,facetColumn as vr,findStorageReferences as zr,listTables as Vr,readTablePage as Xr,recordFanoutPass as Hr,selectMatchingIds as Qr,summarizeFanoutTopics as Yr,summarizeSubscriptions as jr}from"./packem_shared/ADMIN_FUNCTIONS-B0xlQJ4w.mjs";import{MAIL_RETENTION as Zr,MAIL_TABLE as $r,clearCapturedMail as eo,ensureMailTable as ro,readCapturedMail as oo,recordCapturedMail as ao}from"./packem_shared/MAIL_RETENTION-KmozO2NQ.mjs";import{NotFoundError as no}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as io,readBookmark as so}from"./packem_shared/armRestore-BNzdvQ_o.mjs";import{applySelect as po,buildSeekBeforeWhere as co,buildSeekWhere as So,decodeCursor as uo,encodeCursor as xo,normalizeOrderKeys as fo,softDeleteScope as Eo}from"./packem_shared/applySelect-B0CF8T7y.mjs";import{QUEUE_TABLE as Ao,clearQueueMessages as ho,isLossyBody as To,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 No,rankKeyFromDoc as yo,rankTableName as Mo,resolveRankPartition as Oo,sortColumnName as Do}from"./packem_shared/RANK_TIEBREAK-9NU5s_mi.mjs";import{ReactiveCache as Po,reactiveCacheKey as ko}from"./packem_shared/ReactiveCache-1_9Rs7J_.mjs";import{DEFAULT_MAX_RELATION_KEYS as Go,assertFlatPredicate as Uo,assertShapeShardable as qo,containsRelationPredicate as wo,isRelationPredicate as Wo,resolveRelationPredicates as Ko}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-bq00btqV.mjs";import{applyOnDelete as zo,distinctValues as Vo,fanOutScalarCounts as Xo,resolveWith as Ho,runRowValidators as Qo}from"./packem_shared/applyOnDelete-uFRC5p1d.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as jo,clampPromotionThresholds as Jo,nextPromotionState as Zo,relayCountFor as $o,shapeRoutingKey as ea}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-Dteg0sZF.mjs";import{DEFAULT_MAX_RELAYS as oa,OwnerRelay as aa,RelayMember as ta,createRelayLink as na}from"./packem_shared/DEFAULT_MAX_RELAYS-CnCyh6oX.mjs";import{RLS_UNWRAP_SYMBOL as ia,RlsRequiredError as sa,guardWriter as ma}from"./packem_shared/RLS_UNWRAP_SYMBOL-C6_WX3dG.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as da,readSchemaHistory as ca,readSchemaVersion as Sa,recordSchemaVersion as ua}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CHXz6p_z.mjs";import{serializeSqlValue as fa}from"./packem_shared/serializeSqlValue-DnpyaLcw.mjs";import{buildSettings as ga,isDevEnvironment as Aa}from"./packem_shared/buildSettings-DT18_DkX.mjs";import{buildPokeFrames as Ta,diffGlobalMembership as Ca,encodeRowsPatch as Ia,projectColumns as _a}from"./packem_shared/buildPokeFrames-DaPpm5Ss.mjs";import{ShardRunner as La}from"./packem_shared/ShardRunner-DIqVdWtk.mjs";import{runSocketPool as Na}from"./packem_shared/runSocketPool-DPQLVyWF.mjs";import{MAX_SQL_ROWS as Ma,assertReadonly as Oa,lintReadonlySql as Da,runReadonlySql as Fa}from"./packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs";import{awaitWsDrain as ka,sendDeltaFrames as Ba,subscriptionListDeltas as Ga,trySendFrame as Ua}from"./packem_shared/awaitWsDrain-Dk50ISgE.mjs";import{createSystemReader as wa}from"./packem_shared/createSystemReader-DcDcrtM3.mjs";import{ConflictError as Ka}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{hasTrigger as za,runTriggers as Va}from"./packem_shared/hasTrigger-CbkOHExZ.mjs";import{selectExpiredIds as Ha}from"./packem_shared/selectExpiredIds-FzhIEeG1.mjs";import{compileWhereSql as Ya}from"./packem_shared/compileWhereSql-BLcfs4QW.mjs";import{RELATION_EXISTS_KEY as Ja}from"./packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs";import{runShardMigrations as $a}from"./packem_shared/runShardMigrations-CPxqCh3O.mjs";import{stableStringify as rt}from"./packem_shared/stableStringify-BjLh4gvA.mjs";import{stableWireKey as at}from"./packem_shared/stableWireKey-YEHLaX6X.mjs";export{Br as ADMIN_FUNCTIONS,Gr as ADMIN_FUNCTION_PREFIX,p as AGGREGATE_SQL_FUNCTION,Xe as AGG_COUNT,He as AGG_KEY,Qe as AGG_VALUE,y as AUDIT_LOG_TABLE,z as CDC_LOG_TABLE,V as CDC_META_TABLE,ae as CLIENT_WATERMARK_TABLE,Ka as ConflictError,C as CountRlsUnsupportedError,Pe as DATA_MIGRATION_STATE_TABLE,Ur as DEFAULT_FANOUT_TOPIC_LIMIT,Go as DEFAULT_MAX_RELATION_KEYS,oa as DEFAULT_MAX_RELAYS,jo as DEFAULT_PROMOTION_THRESHOLDS,Ye as DOC_COLUMN,qr as FLAGS_FUNCTION_PREFIX,Nr as GEO_DEFAULT_PRECISION,pe as GLOBAL_SHAPE_SNAPSHOT_TABLE,Ee as IDEMPOTENCY_TABLE,Zr as MAIL_RETENTION,$r as MAIL_TABLE,wr as MAX_PAGE_SIZE,Ma as MAX_SQL_ROWS,no as NotFoundError,P as NotUniqueError,aa as OwnerRelay,Ao as QUEUE_TABLE,Lo as RANK_TIEBREAK,Ja as RELATION_EXISTS_KEY,Wr as RELATION_FUNCTION_PREFIX,ia as RLS_UNWRAP_SYMBOL,Po as ReactiveCache,ta as RelayMember,sa as RlsRequiredError,Ue as SCAN_DEP,da as SCHEMA_HISTORY_MAX_VERSIONS,Le as SEARCH_STATE_TABLE,La as ShardRunner,te as advanceClientWatermark,je as aggUpsertSql,d as aggregateSqlFunction,f as aggregateTableName,M as appendAuditEntry,X as appendCdcChange,H as applyCdcChanges,zo as applyOnDelete,po as applySelect,io as armRestore,Uo as assertFlatPredicate,Oa as assertReadonly,qo as assertShapeShardable,k as assertValidClientId,ka as awaitWsDrain,q as backfillAggregateIndexes,w as backfillRankIndexes,W as backfillSearchIndexes,K as backfillSearchIndexesForTable,yr as boundingBoxCenter,Mr as boundingBoxGeohashes,Ta as buildPokeFrames,co as buildSeekBeforeWhere,So as buildSeekWhere,ga as buildSettings,Q as bumpCdcEpoch,Jo as clampPromotionThresholds,eo as clearCapturedMail,ho as clearQueueMessages,E as coerceAggregateNumber,Ya as compileWhereSql,Ie as computeRankPage,wo as containsRelationPredicate,Or as coveringGeohashes,se as createCompanionSync,qe as createDependencyTracker,Kr as createFanoutCounters,Je as createIndexSql,na as createRelayLink,B as createShardCtxDb,wa as createSystemReader,uo as decodeCursor,de as deleteGlobalShapeSnapshot,ce as deleteGlobalShapeSnapshotsForConnection,we as depKey,cr as diffExternalSource,Ca as diffGlobalMembership,Vo as distinctValues,g as encodeAggregateKey,xo as encodeCursor,Dr as encodeGeohash,bo as encodePartitionKey,Ia as encodeRowsPatch,O as ensureAuditTable,ro as ensureMailTable,o as exportShardRows,a as exportShardTable,vr as facetColumn,Xo as fanOutScalarCounts,zr as findStorageReferences,A as foldAggregateTally,Ze as geoTableName,ma as guardWriter,za as hasTrigger,Fr as haversineMeters,_e as hydrateDocsById,t as importShardRows,Aa as isDevEnvironment,$e as isFtsAvailable,To as isLossyBody,Wo as isRelationPredicate,Ir as isSoftDeleted,_r as isSourceDue,er as jsonPath,rr as jsonPathSql,ur as liftSourceId,Da as lintReadonlySql,Vr as listTables,No as matchesRankStaticWhere,c as matchesStaticWhere,gr as materializeExternalRows,Ar as materializeExternalRowsIncremental,I as mergeWhere,Y as migrateCdcLog,j as migrateCdcMeta,ne as migrateClientWatermark,Se as migrateGlobalShapeSnapshot,ge as migrateIdempotency,be as migrateSearchState,J as minCdcSeq,Zo 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,_a as projectColumns,Rr as pullExternalSourceIncrementalTick,Lr as pullExternalSourceTick,or as qualifiedJsonPath,ar as qualifiedJsonPathSql,tr as quoteIdentifier,yo as rankKeyFromDoc,Mo as rankTableName,ko as reactiveCacheKey,h as readAggregateValue,D as readAuditLog,so as readBookmark,oo as readCapturedMail,Z as readCdcChanges,$ as readCdcCursor,ee as readCdcEpoch,le as readClientWatermark,hr as readExternalSourceBaseline,ue as readGlobalShapeSnapshot,Ae as readIdempotent,ke as readMigrationStatus,Co as readQueueMessageById,Io as readQueueMessages,ca as readSchemaHistory,Sa as readSchemaVersion,Ne as readSearchBackfillState,Xr as readTablePage,ao as recordCapturedMail,Hr as recordFanoutPass,_o as recordQueueMessages,ua as recordSchemaVersion,$o as relayCountFor,pr as renderSql,Oo as resolveRankPartition,Ko as resolveRelationPredicates,Ho as resolveWith,nr as rowToDocument,Be as runDataMigration,ve as runDrizzle,Tr as runExternalSourceTick,Fa as runReadonlySql,Qo as runRowValidators,$a as runShardMigrations,Na as runSocketPool,ze as runSql,Va as runTriggers,Ha as selectExpiredIds,i as selectExportTables,R as selectIndexForAggregate,L as selectIndexForCount,b as selectIndexForGroupBy,Qr as selectMatchingIds,Oe as selectShapeMemberIds,De as selectShapeRows,Ba as sendDeltaFrames,fa as serializeSqlValue,ea as shapeRoutingKey,Eo as softDeleteScope,Do as sortColumnName,rt as stableStringify,at as stableWireKey,Ga as subscriptionListDeltas,Yr as summarizeFanoutTopics,jr as summarizeSubscriptions,lr as tableColumns,We as tableFromDepKey,u as throwingScheduler,re as trimCdcChanges,he as trimIdempotent,ir as tryRowToDocument,Ua as trySendFrame,s as validateImportRow,xe as writeGlobalShapeSnapshot,Te as writeIdempotent,ye as writeSearchBackfillState};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as b}from"@lunora/errors";import{n as ht,A as Le,T as we,y as pt,c as mt}from"./FTS_COUNT_COLUMN-D1gY3wwZ-CZHdaRrd.mjs";import{sql as t}from"drizzle-orm";import{aggregateSqlFunction as $e,normalizeCountArgument as wt,throwingScheduler as $t}from"./AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{encodeAggregateKey as Se,readAggregateValue as Ae,aggregateTableName as Re}from"./aggregateTableName-G-eXyjcz.mjs";import{mergeWhere as H,CountRlsUnsupportedError as _e,selectIndexForGroupBy as gt,selectIndexForCount as bt,selectIndexForAggregate as Et}from"./CountRlsUnsupportedError-B2WKJD9v.mjs";import{backfillSearchIndexesForTable as yt}from"./backfillAggregateIndexes-BHiewuB-.mjs";import{backfillAggregateIndexes as tr,backfillRankIndexes as nr,backfillSearchIndexes as rr}from"./backfillAggregateIndexes-BHiewuB-.mjs";import{appendCdcChange as Nt}from"./CDC_LOG_TABLE-BnqlH2eZ.mjs";import{CDC_LOG_TABLE as or,applyCdcChanges as ar,bumpCdcEpoch as sr,minCdcSeq as lr,readCdcChanges as dr,readCdcCursor as cr,readCdcEpoch as ur,trimCdcChanges as fr}from"./CDC_LOG_TABLE-BnqlH2eZ.mjs";import{createCompanionSync as Tt}from"./createCompanionSync-BCBUOnMk.mjs";import{computeRankPage as je}from"./computeRankPage-IUSS-zIB.mjs";import{SCAN_DEP as W}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as O}from"./runDrizzle-GKR3y97k.mjs";import{DOC_COLUMN as F,quoteIdentifier as St,AGG_VALUE as ge,AGG_COUNT as Ie,AGG_KEY as be,jsonPathSql as P,rowToDocument as re,tableColumns as at,isFtsAvailable as At,tryRowToDocument as st,geoTableName as Rt,qualifiedJsonPathSql as Je}from"./AGG_COUNT-BWXe3gtQ.mjs";import{coveringGeohashes as _t,boundingBoxGeohashes as It,pointInBoundingBox as vt,haversineMeters as xt}from"./GEO_DEFAULT_PRECISION-okRCkZ6r.mjs";import{NotFoundError as Ct}from"./NotFoundError-BhF7FeFr.mjs";import{normalizeOrderKeys as kt,buildSeekWhere as lt,decodeCursor as Ce,applySelect as ze,encodeCursor as ke,softDeleteScope as ne,buildSeekBeforeWhere as Mt}from"./applySelect-B0CF8T7y.mjs";import{sortColumnName as Ye,resolveRankPartition as Lt,encodePartitionKey as Dt,RANK_TIEBREAK as Ot,rankTableName as Ve}from"./RANK_TIEBREAK-9NU5s_mi.mjs";import{assertFlatPredicate as ve,resolveRelationPredicates as Ke}from"./DEFAULT_MAX_RELATION_KEYS-bq00btqV.mjs";import{runRowValidators as xe,resolveWith as Qe,applyOnDelete as Wt,fanOutScalarCounts as Ft}from"./applyOnDelete-uFRC5p1d.mjs";import{guardWriter as Bt}from"./RLS_UNWRAP_SYMBOL-C6_WX3dG.mjs";import{createSystemReader as qt}from"./createSystemReader-DcDcrtM3.mjs";import{ConflictError as de}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as Ut}from"./hasTrigger-CbkOHExZ.mjs";import{compileWhereSql as K}from"./compileWhereSql-BLcfs4QW.mjs";import{CLIENT_WATERMARK_TABLE as pr,advanceClientWatermark as mr,migrateClientWatermark as wr,readClientWatermark as $r}from"./CLIENT_WATERMARK_TABLE-CXsSLU8D.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as br,deleteGlobalShapeSnapshot as Er,deleteGlobalShapeSnapshotsForConnection as yr,migrateGlobalShapeSnapshot as Nr,readGlobalShapeSnapshot as Tr,writeGlobalShapeSnapshot as Sr}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DX-6-gBP.mjs";import{IDEMPOTENCY_TABLE as Rr,readIdempotent as _r,trimIdempotent as Ir,writeIdempotent as vr}from"./IDEMPOTENCY_TABLE-DjkEMp6w.mjs";import{runShardMigrations as Cr}from"./runShardMigrations-CPxqCh3O.mjs";import{SEARCH_STATE_TABLE as Mr}from"./SEARCH_STATE_TABLE-eLN8U5tz.mjs";import{selectShapeMemberIds as Dr,selectShapeRows as Or}from"./selectShapeMemberIds-DvE7K6zG.mjs";import{serializeSqlValue as ie}from"./serializeSqlValue-DnpyaLcw.mjs";const Ht=i=>{const o=new TextEncoder().encode(i);let n="";for(const d of o)n+=String.fromCodePoint(d);return btoa(n)},Pt=i=>{const o=atob(i),n=Uint8Array.from(o,d=>d.codePointAt(0)??0);return new TextDecoder().decode(n)},Gt=()=>new b("BAD_REQUEST","invalid cursor"),Xe=16,Ze=8,J=1024,De=(i,o)=>o.query(i),jt=(i,o,n)=>{const d=ht(i,n);if(d.length===0)return 0;let l=0;for(const[$,E]of o.entries()){const m=$===o.length-1;let T=0;for(const C of d)(m?C.startsWith(E):C===E)&&(T+=1);if(T===0)return 0;l+=T}return l},Jt=(i,o)=>{if(!o)return{exact:!0,lower:i,upper:i};const n=i.codePointAt(i.length-1)??0,d=i.slice(0,Math.max(0,i.length-String.fromCodePoint(n).length));return{exact:!1,lower:i,upper:d+String.fromCodePoint(n+1)}},zt=(i,o,n)=>{const d={eq:(l,$)=>{if(!i.definition.filterFields?.includes(l))throw new b("INTERNAL",`field "${l}" is not a filter field of search index "${i.indexName}" on table "${o}"`);if(i.filters.length>=Ze)throw new b("BAD_REQUEST",`search index "${i.indexName}" on table "${o}": at most ${String(Ze)} .eq() filters are supported per search query`);return i.filters.push({field:l,value:$}),d},search:(l,$)=>{const E=i;if(l!==E.definition.field)throw new b("INTERNAL",`search index "${E.indexName}" on table "${o}" indexes "${E.definition.field}", not "${l}"`);const m=De($,n).length;if(m>Xe)throw new b("BAD_REQUEST",`search index "${E.indexName}" on table "${o}": at most ${String(Xe)} search terms are supported (got ${String(m)})`);return E.field=l,E.query=$,E.hasQuery=!0,d}};return d},Yt=i=>{if(i.length>J)throw new b("BAD_REQUEST",`more than ${String(J)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Vt=i=>Math.min(i.offset+i.numItems+1,J),Kt=i=>Ht(`search:${String(i)}`),Qt=i=>{let o;try{o=Pt(i)}catch{return}if(!o.startsWith("search:"))return;const n=Number(o.slice(7));return Number.isInteger(n)&&n>=0?n:void 0},Xt=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)),n=i.cursor?Qt(i.cursor):0;if(n===void 0)throw Gt();if(n+o>J)throw new b("BAD_REQUEST",`search pagination reaches past the ${String(J)}-document limit (offset ${String(n)} + ${String(o)} requested) — narrow the query or the filters instead`);return{numItems:o,offset:n}},Zt=(i,o)=>{const n=o.offset+o.numItems,d=o.numItems>0&&i.length>n;return{continueCursor:d?Kt(n):null,isDone:!d,page:i.slice(o.offset,n)}},en=i=>{if(i===void 0)return J+1;if(!Number.isFinite(i))return J;const o=Math.max(0,Math.floor(i));if(o>J)throw new b("BAD_REQUEST",`search returns at most ${String(J)} documents (asked for ${String(o)}) — narrow the query or paginate instead`);return o},tn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,nn=i=>{if(!tn.test(i))throw new b("INTERNAL",`invalid clientId ${JSON.stringify(i)}: a client-supplied row id must be a UUID`)},et=50,dt=500,rn=128,te=(i,o,n)=>{const d=o??dt;if(i>d)throw new b("BATCH_LIMIT_EXCEEDED",`${n}: batch of ${String(i)} exceeds the limit of ${String(d)} (raise options.limit or chunk the call)`,{status:400})},on=i=>{const o={eq:(n,d)=>(i.sqlConditions.push({comparator:"=",field:n,value:d}),o),gt:(n,d)=>(i.sqlConditions.push({comparator:">",field:n,value:d}),o),gte:(n,d)=>(i.sqlConditions.push({comparator:">=",field:n,value:d}),o),lt:(n,d)=>(i.sqlConditions.push({comparator:"<",field:n,value:d}),o),lte:(n,d)=>(i.sqlConditions.push({comparator:"<=",field:n,value:d}),o)};return o},an=i=>Math.max(i,J),sn=(i,o,n,d,l)=>{const $=De(n.query,Le(n.definition.language));if($.length===0)return[];const E=mt(o,n.indexName),m=`${E}__vocab`,T=$.length-1,C=$.map((S,_)=>{const k=Jt(S,_===T),V=k.exact?t`${t.identifier("term")} = ${k.lower}`:t`${t.identifier("term")} >= ${k.lower} AND ${t.identifier("term")} < ${k.upper}`;return t`SELECT ${t.identifier("doc")}, ${t.raw(String(_))} AS ${t.identifier("__term__")}, COUNT(*) AS ${t.identifier("__n__")} FROM ${t.identifier(m)} WHERE ${V} GROUP BY ${t.identifier("doc")}`}),x=$.map((S,_)=>t`SUM(CASE WHEN u.${t.identifier("__term__")} = ${t.raw(String(_))} THEN u.${t.identifier("__n__")} ELSE 0 END)`),A=t`SELECT f.${t.identifier(we)} AS ${t.identifier(we)}, ${t.join(x,t` + `)} AS ${t.identifier("__score__")} FROM (${t.join(C,t` UNION ALL `)}) u JOIN ${t.identifier(E)} f ON f.rowid = u.${t.identifier("doc")} GROUP BY f.${t.identifier(we)} HAVING ${t.join(x.map(S=>t`${S} > 0`),t` AND `)}`,N=[];for(const S of n.filters)N.push(t`${P(S.field)} = ${ie(S.value)}`);l&&N.push(l);let h=t`SELECT m.id, m._creationTime, m.${t.identifier(F)} FROM (${A}) s JOIN ${t.identifier(o)} m ON m.id = s.${t.identifier(we)}`;N.length>0&&(h=t`${h} WHERE ${t.join(N,t` AND `)}`),h=t`${h} ORDER BY s.${t.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${t.raw(String(d))}`;const R=[];for(const S of O(i,h)){const _=st(S);_&&R.push(_)}return R},ln=(i,o,n,d,l)=>{const $=Le(n.definition.language),E=De(n.query,$);if(E.length===0)return[];const m=[];for(const A of n.filters)m.push(t`${P(A.field)} = ${ie(A.value)}`);l&&m.push(l);let T=t`SELECT id, _creationTime, ${t.identifier(F)} FROM ${t.identifier(o)}`;m.length>0&&(T=t`${T} WHERE ${t.join(m,t` AND `)}`),T=t`${T} ORDER BY _creationTime DESC, id ASC LIMIT ${t.raw(String(an(d)))}`;const C=O(i,T).toArray(),x=[];for(const A of C){const N=st(A);if(!N)continue;const h=jt(pt(N,n.definition),E,$);h>0&&x.push({creationTime:typeof N._creationTime=="number"?N._creationTime:0,doc:N,id:typeof N._id=="string"?N._id:"",score:h})}return x.sort((A,N)=>N.score-A.score||N.creationTime-A.creationTime||A.id.localeCompare(N.id)),x.slice(0,d).map(A=>A.doc)},dn=(i,o)=>{const n=i,d={near:(l,$)=>{if(n.within)throw new b("INTERNAL",`geo index "${n.indexName}" on table "${o}": call .near() or .within(), not both`);return n.near={point:{lat:l.lat,lng:l.lng},radiusMeters:$},d},within:l=>{if(n.near)throw new b("INTERNAL",`geo index "${n.indexName}" on table "${o}": call .near() or .within(), not both`);return n.within={ne:{lat:l.ne.lat,lng:l.ne.lng},sw:{lat:l.sw.lat,lng:l.sw.lng}},d}};return d},cn=(i,o)=>{const n=i[o];if(n===null||typeof n!="object")return;const{lat:d,lng:l}=n;return typeof d=="number"&&typeof l=="number"?{lat:d,lng:l}:void 0},un=(i,o)=>{const n=cn(i,o.definition.field);if(!n)return;const d=typeof i._creationTime=="number"?i._creationTime:0;if(o.near){const l=xt(o.near.point,n);return l<=o.near.radiusMeters?{creationTime:d,distance:l}:void 0}return vt(n,o.within)?{creationTime:d,distance:0}:void 0},fn=(i,o,n,d,l)=>{if(!n.near&&!n.within)throw new b("INTERNAL",`geo index "${n.indexName}" on table "${o}": call .near(point, radius) or .within(box)`);const $=n.near?_t(n.near.point,n.near.radiusMeters):It(n.within),E=Rt(o,n.indexName),m=$.map(h=>t`(g.${t.identifier("__geohash__")} >= ${h} AND g.${t.identifier("__geohash__")} < ${`${h}{`})`),T=[t`(${t.join(m,t` OR `)})`];l&&T.push(l);const C=t`SELECT m.id, m._creationTime, m.${t.identifier(F)} FROM ${t.identifier(E)} g JOIN ${t.identifier(o)} m ON m.id = g.${t.identifier("__id__")} WHERE ${t.join(T,t` AND `)}`,x=O(i,C).toArray(),A=[];for(const h of x){const R=re(h),S=R?un(R,n):void 0;R&&S&&A.push({creationTime:S.creationTime,distance:S.distance,doc:R})}A.sort((h,R)=>h.distance-R.distance||R.creationTime-h.creationTime);const N=A.map(h=>h.doc);return typeof d=="number"?N.slice(0,Math.max(0,Math.floor(d))):N},hn=(i,o,n,d,l)=>{const{geo:$}=n;if(!$)throw new b("INTERNAL","runGeoTerminal called without a staged geo query");const E=n.inMemoryFilters.length>0,m=fn(i,o,$,E?void 0:l,d);if(!E)return m;const T=[];for(const C of m)if(n.inMemoryFilters.every(x=>x(C))&&(T.push(C),typeof l=="number"&&T.length>=l))break;return T},pn=(i,o,n,d,l,$)=>{const E=[];for(const x of n.sqlConditions)E.push(t`${P(x.field)} ${t.raw(x.comparator)} ${ie(x.value)}`);d&&E.push(d);let m=t`SELECT id, _creationTime, ${t.identifier(F)} FROM ${t.identifier(o)}`;E.length>0&&(m=t`${m} WHERE ${t.join(E,t` AND `)}`),m=t`${m} ORDER BY ${l}`,typeof $=="number"&&n.inMemoryFilters.length===0&&(m=t`${m} LIMIT ${t.raw(String(Math.max(0,Math.floor($))))}`);const T=O(i,m).toArray(),C=[];for(const x of T){const A=re(x);if(A&&n.inMemoryFilters.every(N=>N(A))&&(C.push(A),typeof $=="number"&&C.length>=$))break}return C},X={fieldRef:P,serialize:ie},mn=i=>{let o=0;const n=[],d={fieldRef:P,relationExists:l=>{const{childWhere:$,negated:E,parentTable:m,relation:T}=l,C=`__rel_${String(o)}`,x=n.at(-1)??m;o+=1,i(T.table,W);const A=T.kind==="one"?T.field:T.references,N=T.kind==="one"?T.references:T.field,h=t`${Je(C,N)} = ${Je(x,A)}`;n.push(C);const R=K($,d);n.pop();const S=R?t`${h} AND ${R}`:h,_=t`EXISTS (SELECT 1 FROM ${t.identifier(T.table)} AS ${t.identifier(C)} WHERE ${S})`;return E?t`NOT ${_}`:_},serialize:ie};return d},ct=i=>{const o=i.map(n=>t`${P(n.field)} ${t.raw(n.direction==="desc"?"DESC":"ASC")}`);return i.some(n=>n.field==="_id"||n.field==="id")||o.push(t`${P("id")} ASC`),t.join(o,t`, `)},wn={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},$n=i=>{const o=i.order;return i.indexFields.length>0?i.indexFields.map(n=>({direction:o,field:n})):[{direction:o,field:"_creationTime"}]},gn=(i,o,n,d)=>{const l=i.sqlConditions.map($=>({[$.field]:{[wn[$.comparator]??"eq"]:$.value}}));if(n&&l.push(lt(o,Ce(n))),d&&l.push(Mt(o,Ce(d))),l.length!==0)return l.length===1?l[0]:{AND:l}},bn=(i,o,n)=>{const d=[];for(const l of i){const $=re(l);if($&&o.every(E=>E($))&&(d.push($),n!==void 0&&d.length>n))break}return d},En=(i,o,n,d,l)=>{const $=Math.max(0,Math.floor(d.numItems)),E=$n(n),m=typeof d.endCursor=="string",T=K(gn(n,E,d.cursor,d.endCursor),X),C=l&&T?t`${T} AND ${l}`:l??T;let x=t`SELECT id, _creationTime, ${t.identifier(F)} FROM ${t.identifier(o)}`;C&&(x=t`${x} WHERE ${C}`),x=t`${x} ORDER BY ${ct(E)}`;const A=n.inMemoryFilters.length>0;!A&&!m&&(x=t`${x} LIMIT ${t.raw(String($+1))}`);const N=O(i,x).toArray(),h=bn(N,n.inMemoryFilters,A||m?void 0:$);if(m){const k=h.length>=2?h[Math.floor(h.length/2)-1]:void 0;return{continueCursor:d.endCursor??null,isDone:!0,page:h,splitCursor:k?ke(k,E):null}}const R=h.length>$,S=R?h.slice(0,$):h,_=S.at(-1);return{continueCursor:R&&_?ke(_,E):null,isDone:!R,page:S}};class yn extends b{constructor(o="unique() found more than one matching document"){super("NOT_UNIQUE",o,{name:"NotUniqueError"})}}const Nn=/\s/u,Tn=String.fromCodePoint(0),tt=(i,o,n)=>{if(!i.tables[o])throw new b("INTERNAL",`unknown table: ${o}`);return typeof n!="string"||n.length===0||Nn.test(n)||n.includes(Tn)?null:n},Sn=(i,o,n,d=()=>{})=>{const l=o.tables[n];if(!l)throw new b("INTERNAL",`unknown table: ${n}`);const $=ne(l.softDeleteMode,void 0),E=$?K($,X):void 0,m={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]},T=h=>{const{search:R}=m;if(!R)throw new b("INTERNAL","runSearchFetch called without a staged search");yt(i,n,l);const S=m.inMemoryFilters.length>0,_=en(S?void 0:h),k=At(i)?sn(i,n,R,_,E):ln(i,n,R,_,E);if(!S)return h===void 0&&Yt(k),k;const V=[];for(const Z of k)if(m.inMemoryFilters.every(U=>U(Z))&&(V.push(Z),typeof h=="number"&&V.length>=h))break;return V},C=h=>{const R=Xt(h);return Zt(T(Vt(R)),R)},x=()=>{const h=m.indexFields.length>0?m.indexFields:["_creationTime"],R=m.order==="desc"?"DESC":"ASC";return t.join(h.map(S=>t`${P(S)} ${t.raw(R)}`),t`, `)},A=h=>m.search?T(h):m.geo?hn(i,n,m,E,h):pn(i,n,m,E,x(),h),N={async*[Symbol.asyncIterator](){const h=[...m.inMemoryFilters];let R;m.inMemoryFilters=[];try{for(;;){const S=await N.paginate({cursor:R??null,numItems:rn});for(const _ of S.page)h.every(k=>k(_))&&(yield _);if(S.isDone||S.continueCursor===null)return;R=S.continueCursor}}finally{m.inMemoryFilters=h}},async collect(){return A(void 0)},filter(h){return m.inMemoryFilters.push(h),N},async first(){return A(m.inMemoryFilters.length>0?void 0:1)[0]??null},order(h){return m.order=h==="desc"?"desc":"asc",N},async paginate(h){if(m.search)return C(h);if(m.geo)throw new b("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");return En(i,n,m,h,E)},async take(h){return A(h)},async unique(){const h=A(m.inMemoryFilters.length>0?void 0:2);if(h.length>1)throw new yn(`unique() on table "${n}" matched ${String(h.length)} documents; expected at most one`);return h[0]??null},withGeoIndex(h,R){const S=(l.geoIndexes??[]).find(k=>k.name===h);if(!S)throw new b("INTERNAL",`unknown geo index "${h}" on table "${n}"`);d(n,h,"geo");const _={definition:S,indexName:h};if(m.geo=_,R(dn(_,n)),!_.near&&!_.within)throw new b("INTERNAL",`geo index "${h}" on table "${n}" requires a .near(point, radius) or .within(box) call`);return N},withIndex(h,R){const S=l.indexes.find(_=>_.name===h);if(!S)throw new b("INTERNAL",`unknown index "${h}" on table "${n}"`);return d(n,h,"index"),m.indexName=h,m.indexFields=S.fields,R&&R(on(m)),N},withSearchIndex(h,R){const S=(l.searchIndexes??[]).find(k=>k.name===h);if(!S)throw new b("INTERNAL",`unknown search index "${h}" on table "${n}"`);d(n,h,"search");const _={definition:S,field:S.field,filters:[],hasQuery:!1,indexName:h,query:""};if(m.search=_,R(zt(_,n,Le(S.language))),!_.hasQuery)throw new b("INTERNAL",`search index "${h}" on table "${n}" requires a .search(field, query) call`);return N}};return N},nt=(i,o,n)=>{const d={...o};for(const[l,$]of at(i)){if($.serverDefault){d[l]=$.serverDefault({auth:n});continue}d[l]===void 0&&($.defaultFn?d[l]=$.defaultFn():"defaultValue"in $&&(d[l]=$.defaultValue))}return d},rt=(i,o,n,d)=>{const l=n;for(const[$,E]of at(i)){if(E.serverDefault){$ in o&&(l[$]=E.serverDefault({auth:d}));continue}E.onUpdateFn&&!($ in o)&&(l[$]=E.onUpdateFn())}},it=(i,o)=>{for(const n of Object.keys(o))if(o[n]===void 0)throw new b("INTERNAL",`Cannot ${i} field '${n}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},An=/unique constraint failed/i,Rn=i=>i instanceof Error&&An.test(i.message),Me=(i,o,n)=>{try{O(i,n)}catch(d){throw Rn(d)?new de(`unique constraint violation on "${o}"`,"unique"):d}},Ee=(i,o,n)=>{if(Me(i,o,n),O(i,t`SELECT changes() AS changed`).one().changed===0)throw new de(`optimistic concurrency conflict on "${o}" — the row changed during this mutation; refetch and retry`,"occ")},ot=(i,o,n,d,l,$,E)=>{const m=[];for(let A=0;A<n.length+1;A+=1){const N=[];for(let _=0;_<A;_+=1)N.push(t`${t.identifier(n[_])} IS ${$[_]}`);const h=n[A],R=d[A];if(h!==void 0&&R!==void 0){const _=R.direction==="desc"?">":"<";N.push(t`${t.identifier(h)} ${t.raw(_)} ${$[A]}`)}else N.push(t`${t.identifier(Ot)} < ${E}`);const[S]=N;m.push(N.length===1&&S!==void 0?S:t`(${t.join(N,t` AND `)})`)}const T=t.join(m,t` OR `),C=O(i,t`SELECT COUNT(*) AS c FROM ${t.identifier(o)} WHERE ${t.identifier("__partition__")} = ${l} AND (${T})`).one(),x=O(i,t`SELECT COUNT(*) AS c FROM ${t.identifier(o)} WHERE ${t.identifier("__partition__")} = ${l}`).one();return{before:C.c,total:x.c}},Xn=i=>{const{sql:o}=i,{schema:n}=i,d=i.broadcast??(()=>{}),l=i.onRead??(()=>{}),$=i.onIndexUse??(()=>{}),E=i.onWrite??(()=>{}),{cache:m}=i,T=i.clock??(()=>Date.now()),C=i.idGenerator??(()=>crypto.randomUUID()),x=i.scheduler??$t,{globalDb:A}=i,N=i.auth??{identity:null,userId:null},h=i.cdc??!1,R=x,S=qt({scheduler:typeof R.list=="function"&&typeof R.get=="function"?R:void 0,storage:i.storage}),_=(e,r,a,p)=>{h&&Nt(o,T(),e,r,a,p)},k=e=>n.tables[e]?.shardMode?.kind==="global",V=(e,r)=>{if(k(e)){if(!A)throw new b("INTERNAL",`cross-backend ${r} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return A}return L},Z=e=>V(e,"cascade"),U=(e,r)=>{if(k(e)){if(!A)throw new b("INTERNAL",`${r} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return A}},oe=()=>A,ye=(e,r)=>V(e,"relation load").findMany(e,r),Oe=(e,r)=>(k(e)&&l(e,W),ye(e,r)),ut=e=>!k(e.table),We=i.relationExistsPushDown??"auto",Fe=We!=="never",{maxRelationKeys:Be}=i,ce=(e,r,a)=>Ke(e,{fetcher:Oe,maxRelationKeys:Be,relationBaseWhere:a,schema:n,tableName:r}),qe=async(e,r,a,p)=>{const f=U(e,"relation grouped count");if(f)return l(e,W),Ft((v,q)=>f.count(v,q),e,r,a,p);const c=n.tables[e];if(!c)throw new b("INTERNAL",`unknown table: ${e}`);l(e,W);const s=ne(c.softDeleteMode,void 0),u={[r]:{in:a}},w=H(H(u,p),s),y=await ce(w,e,void 0),g=K(y,X),I=P(r);let D=t`SELECT ${I} AS __fk__, COUNT(*) AS count FROM ${t.identifier(e)}`;g&&(D=t`${D} WHERE ${g}`),D=t`${D} GROUP BY ${I}`;const M=O(o,D).toArray();return new Map(M.map(v=>[v.__fk__,v.count]))};let ue=0;const Ue=new Set;for(const[e,r]of Object.entries(n.tables))for(const a of Object.values(r.triggerMap??{}))Ue.add(`${e} ${a.timing} ${a.op}`);const z=(e,r,a)=>Ue.has(`${e} ${r} ${a}`),Y=async(e,r,a)=>{if(ue+=1,ue>et)throw ue-=1,new de(`trigger recursion exceeded ${String(et)} levels on "${a.table}" — check for a self-triggering write`,"trigger");try{await Ut({ctx:ft,event:a,op:r,schema:n,tableName:a.table,timing:e})}finally{ue-=1}},{ensureBackfilledForTable:ae,ensureBackfilledIndex:Ne,ensureRankBackfilled:Te,ensureRankBackfilledForTable:se,syncAggregates:fe,syncCompanionsForInsert:He,syncGeo:he,syncRanks:le,syncSearch:pe}=Tt({broadcast:d,invalidateCache:(e,r)=>m?.invalidate(e,r),recordCdc:_,schema:n,sql:o}),Pe=(e,r,a)=>{const{shardMode:p}=r;if(p?.kind==="shardBy"&&!(p.field!==void 0&&(a.partitionBy??[]).includes(p.field)))throw Object.assign(new Error(`rank index "${a.name}" on "${e}" partitions across shards (shard key "${p.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})},Q=(e,r)=>{const a=Object.entries(n.tables).filter(([,y])=>y.shardMode?.kind!=="global").map(([y])=>y).filter(y=>r===void 0||y===r);if(a.length===0)return;const p=a.map(y=>t`SELECT ${t.raw(`'${y.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${t.identifier(F)} FROM ${t.identifier(y)} WHERE id = ${e}`),f=t`${t.join(p,t` UNION ALL `)} LIMIT 1`,[c]=O(o,f).toArray();if(!c)return;const s=c.__t__,u=re(c);if(typeof s!="string"||!u)return;const w=c[F];return{docJson:typeof w=="string"?w:JSON.stringify(w??{}),row:u,tableName:s}},Ge={assertRankPartitionLocal:Pe,ensureRankBackfilled:Te,onRead:l,rowToDocument:re,schema:n,sql:o},L={system:S,async aggregate(e,r){const a=U(e,"aggregate");if(a)return l(e,W),a.aggregate(e,r);const p=n.tables[e];if(!p)throw new b("INTERNAL",`unknown table: ${e}`);if($e(r.op),r.op==="count")return L.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`);l(e,W);const f=ne(p.softDeleteMode,void 0),c=H(H(r.baseWhere,r.where),f),s=await ce(c,e,r.relationBaseWhere),u=s!==c;if(p.aggregateIndexes&&!r.baseWhere&&!u&&!f){const M=Et(p.aggregateIndexes,r.op,r.field,r.where);if(M){Ne(e,M.index);const v=Se(M.index.by??[],M.key),q=Re(e,M.index.name),G=O(o,t`SELECT ${ge} AS value, ${Ie} AS count FROM ${t.identifier(q)} WHERE ${be} = ${v}`).toArray()[0];return Ae(r.op,G)}}const w=K(s,X),y=$e(r.op),g=P(r.field);let I=t`SELECT ${t.raw(y)}(${g}) AS value FROM ${t.identifier(e)}`;return w&&(I=t`${I} WHERE ${w}`),O(o,I).toArray()[0]?.value??null},asId(e,r){const a=tt(n,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=U(e,"count");if(a)return l(e,W),a.count(e,r);const p=n.tables[e];if(!p)throw new b("INTERNAL",`unknown table: ${e}`);const f=wt(r);if(f.restrictsCounts)throw new _e(e);l(e,W);const c=ne(p.softDeleteMode,void 0),s=H(H(f.baseWhere,f.where),c),u=await ce(s,e,f.relationBaseWhere),w=u!==s;if(p.aggregateIndexes&&!f.baseWhere&&!w&&!c){const I=bt(p.aggregateIndexes,f.where);if(I){Ne(e,I.index);const D=Se(I.index.by??[],I.key),M=Re(e,I.index.name),v=O(o,t`SELECT ${ge} AS value FROM ${t.identifier(M)} WHERE ${be} = ${D}`).toArray();return v[0]===void 0?0:v[0].value??0}}const y=K(u,X);let g=t`SELECT COUNT(*) AS count FROM ${t.identifier(e)}`;return y&&(g=t`${g} WHERE ${y}`),O(o,g).one().count},async delete(e,r,a){const p=Q(e,r);if(!p){const g=r===void 0?oe():void 0;g&&await g.delete(e,void 0,a);return}const{docJson:f,row:c,tableName:s}=p,u=n.tables[s],w=a?.hard===!0,y=!w&&u?.softDeleteMode?u.softDeleteMode.field:void 0;if(!(y&&c[y]!==null&&c[y]!==void 0)){if(z(s,"before","delete")&&await Y("before","delete",{id:e,op:"delete",previous:c,table:s}),await Wt({deletedId:e,deletedReference:g=>c[g],findHolders:async(g,I,D)=>(await Z(g).findMany(g,{includeDeleted:w,where:{[I]:D}})).page,onCascade:(g,I)=>Z(g).delete(I,void 0,a),onRestrict:g=>{throw new de(g,"restrict")},onSetNull:(g,I,D)=>Z(g).patch(I,{[D]:null}),schema:n,tableName:s}),ae(s),se(s),y){const g={...c,[y]:T(),_id:e};Ee(o,s,t`UPDATE ${t.identifier(s)} SET ${t.identifier(F)} = ${JSON.stringify(g)} WHERE id = ${e} AND ${t.identifier(F)} = ${f}`),pe(s,e,g,c),he(s,e,void 0),fe(s,c,g),le(s,e,c,void 0),m?.invalidate(s,e),_(s,e,"update",g),d({key:e,op:"update",row:g,table:s}),z(s,"after","delete")&&await Y("after","delete",{id:e,op:"delete",previous:c,table:s}),await E({id:e,op:"delete",table:s});return}Ee(o,s,t`DELETE FROM ${t.identifier(s)} WHERE id = ${e} AND ${t.identifier(F)} = ${f}`),pe(s,e,void 0),he(s,e,void 0),fe(s,c,void 0),le(s,e,c,void 0),m?.invalidate(s,e),_(s,e,"delete"),d({key:e,op:"delete",table:s}),z(s,"after","delete")&&await Y("after","delete",{id:e,op:"delete",previous:c,table:s}),await E({id:e,op:"delete",table:s})}},async deleteAll(e,r){if(!n.tables[e])throw new b("INTERNAL",`unknown table: ${e}`);const a=Math.max(1,r?.chunkSize??dt),p=r?.hard===void 0?void 0:{hard:r.hard},f=k(e)?void 0:e;let c=0;for(;;){const s=(await L.findMany(e,{limit:a})).page.map(u=>String(u._id));if(s.length===0)break;for(const u of s)await L.delete(u,f,p),c+=1;if(s.length<a)break}return{deleted:c}},async deleteMany(e,r,a){te(e.length,r?.limit,"deleteMany");for(const p of e)await L.delete(p,a);return{deleted:e.length}},async deleteWhere(e,r,a){const p=U(e,"deleteWhere");let f;if(p)f=(await p.findMany(e,{where:r})).page.map(c=>String(c._id));else{if(!n.tables[e])throw new b("INTERNAL",`unknown table: ${e}`);f=(await L.findMany(e,{where:r})).page.map(c=>String(c._id))}if(te(f.length,a?.limit,"deleteWhere"),L.deleteMany===void 0)throw new b("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return L.deleteMany(f,a)},async findFirst(e,r={}){return(await L.findMany(e,{...r,limit:1})).page[0]??null},async findFirstOrThrow(e,r={}){const a=await L.findFirst(e,r);if(a===null)throw new Ct(`findFirstOrThrow: no "${e}" document matched`);return a},async findMany(e,r={}){const a=U(e,"findMany");if(a)return l(e,W),a.findMany(e,r);const p=n.tables[e];if(!p)throw new b("INTERNAL",`unknown table: ${e}`);const f=!r.where&&!r.baseWhere;f?l(e,W):l(e);const c=kt(r.orderBy),s=r.cursor?lt(c,Ce(r.cursor)):void 0;let u=H(r.baseWhere,r.where);u=H(u,ne(p.softDeleteMode,r.includeDeleted)),u=await Ke(u,{canPushExists:Fe?ut:void 0,existsPushMode:We==="always"?"always":"auto",fetcher:Oe,maxRelationKeys:Be,relationBaseWhere:r.relationBaseWhere,schema:n,tableName:e}),s&&(u=u?{AND:[u,s]}:s);const w=Fe?mn(l):X,y=K(u,w);let g=t`SELECT id, _creationTime, ${t.identifier(F)} FROM ${t.identifier(e)}`;y&&(g=t`${g} WHERE ${y}`),g=t`${g} ORDER BY ${ct(c)}`;const I=typeof r.limit=="number"?Math.max(0,Math.floor(r.limit)):void 0;I!==void 0&&(g=t`${g} LIMIT ${t.raw(String(I+1))}`);const D=O(o,g).toArray(),M=[];for(const j of D){const B=re(j);B&&(M.push(B),!f&&typeof B._id=="string"&&l(e,B._id))}if(I===void 0)return r.with&&await Qe({groupedCounter:qe,fetcher:ye,parents:M,relationBaseWhere:r.relationBaseWhere,schema:n,tableName:e,with:r.with}),{continueCursor:null,isDone:!0,page:ze(M,r.select,r.with)};const v=M.length>I,q=v?M.slice(0,I):M,G=q.at(-1);return r.with&&await Qe({fetcher:ye,groupedCounter:qe,parents:q,relationBaseWhere:r.relationBaseWhere,schema:n,tableName:e,with:r.with}),{continueCursor:v&&G?ke(G,c):null,isDone:!v,page:ze(q,r.select,r.with)}},async get(e,r){const a=Q(e,r);if(!a){const p=r===void 0?oe():void 0;return p?p.get(e):null}return l(a.tableName,e),a.row},async lookupById(e,r){const a=Q(e,r);return a?(l(a.tableName,e),{row:a.row,tableName:a.tableName}):null},async groupBy(e,r){const a=U(e,"groupBy");if(a)return l(e,W),a.groupBy(e,r);const p=n.tables[e];if(!p)throw new b("INTERNAL",`unknown table: ${e}`);l(e,W);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 c=ne(p.softDeleteMode,void 0),s=H(H(r.baseWhere,r.where),c),u=await ce(s,e,r.relationBaseWhere),w=u!==s;if(p.aggregateIndexes&&!r.baseWhere&&!w&&!c){const v=gt(p.aggregateIndexes,f.op,f.field,r.by,r.where);if(v){Ne(e,v.index);const q=Re(e,v.index.name),G=Object.keys(v.partial),j=[];if(G.length===(v.index.by??[]).length&&G.length>0){const ee=Se(v.index.by??[],v.partial),me=O(o,t`SELECT ${ge} AS value, ${Ie} AS count FROM ${t.identifier(q)} WHERE ${be} = ${ee}`).toArray();return me.length>0&&j.push({key:{...v.partial},value:Ae(f.op,me[0])}),j}const B=O(o,t`SELECT ${be} AS key, ${ge} AS value, ${Ie} AS count FROM ${t.identifier(q)}`).toArray();for(const ee of B){const me=JSON.parse(ee.key);j.push({key:me,value:Ae(f.op,ee)})}return j}}const y=K(u,X),g=r.by.map(v=>t`${P(v)} AS ${t.identifier(v)}`);if(f.op==="count")g.push(t`COUNT(*) AS value`);else{const{field:v}=f;if(v===void 0)throw new b("INTERNAL",`groupBy(${e}, { agg: { op: "${f.op}" } }): "field" is required for non-count reducers`);g.push(t`${t.raw($e(f.op))}(${P(v)}) AS value`)}let I=t`SELECT ${t.join(g,t`, `)} FROM ${t.identifier(e)}`;y&&(I=t`${I} WHERE ${y}`),I=t`${I} GROUP BY ${t.join(r.by.map(v=>P(v)),t`, `)}`;const D=O(o,I).toArray(),M=[];for(const v of D){const q={};for(const j of r.by)q[j]=v[j]??null;const{value:G}=v;M.push({key:q,value:G==null?null:Number(G)})}return M},async insert(e,r,a){const p=U(e,"insert");if(p){const y=await p.insert(e,r,a);return d({key:y,op:"insert",row:{...r,_id:y},table:e}),y}const f=n.tables[e];if(!f)throw new b("INTERNAL",`unknown table: ${e}`);const c=nt(f,r,N);xe(f,c);let s;a?.clientId!==void 0?(nn(a.clientId),s=a.clientId):a?.allowExplicitId&&typeof c._id=="string"?s=c._id:s=C();const u=a?.allowExplicitId&&typeof c._creationTime=="number"?c._creationTime:T(),w={...c,_creationTime:u,_id:s};return z(e,"before","insert")&&await Y("before","insert",{doc:{...w},id:s,op:"insert",table:e}),ae(e),se(e),Me(o,e,t`INSERT INTO ${t.identifier(e)} (id, _creationTime, ${t.identifier(F)}) VALUES (${s}, ${u}, ${JSON.stringify(w)})`),He(e,s,w),z(e,"after","insert")&&await Y("after","insert",{doc:w,id:s,op:"insert",table:e}),await E({doc:w,id:s,op:"insert",table:e}),s},async insertManyUnsafe(e,r,a){if(te(r.length,a?.limit,"insertManyUnsafe"),r.length===0)return[];const p=U(e,"insert");if(p){const u=[];for(const w of r){const y=await p.insert(e,w,{allowExplicitId:a?.allowExplicitId});d({key:y,op:"insert",row:{...w,_id:y},table:e}),u.push(y)}return u}const f=n.tables[e];if(!f)throw new b("INTERNAL",`unknown table: ${e}`);ae(e),se(e);const c=r.map(u=>{const w=nt(f,u,N),y=a?.allowExplicitId===!0&&typeof w._id=="string"?w._id:C(),g=a?.allowExplicitId===!0&&typeof w._creationTime=="number"?w._creationTime:T();return{creationTime:g,document:{...w,_creationTime:g,_id:y},id:y}}),s=t.join(c.map(u=>t`(${u.id}, ${u.creationTime}, ${JSON.stringify(u.document)})`),t`, `);Me(o,e,t`INSERT INTO ${t.identifier(e)} (id, _creationTime, ${t.identifier(F)}) VALUES ${s}`);for(const{document:u,id:w}of c)He(e,w,u),await E({doc:u,id:w,op:"insert",table:e});return c.map(u=>u.id)},async insertMany(e,r,a){te(r.length,a?.limit,"insertMany");const p=a?.skipDuplicates===!0,f=[];for(const c of r)try{f.push(await L.insert(e,c))}catch(s){if(p&&s instanceof de&&s.kind==="unique")f.push(null);else throw s}return f},normalizeId(e,r){return tt(n,e,r)},async patch(e,r,a){const p=Q(e,a);if(!p){const y=a===void 0?oe():void 0;if(y){await y.patch(e,r);return}throw new b("INTERNAL",`document not found: ${e}`)}const{docJson:f,row:c,tableName:s}=p,u=n.tables[s];if(!u)throw new b("INTERNAL",`unknown table: ${s}`);l(s,e),it("patch",r);const w={...c,...r,_id:e};rt(u,r,w,N),xe(u,w,!0),z(s,"before","update")&&await Y("before","update",{doc:{...w},id:e,op:"update",previous:c,table:s}),ae(s),se(s),Ee(o,s,t`UPDATE ${t.identifier(s)} SET ${t.identifier(F)} = ${JSON.stringify(w)} WHERE id = ${e} AND ${t.identifier(F)} = ${f}`),pe(s,e,w,c),he(s,e,w),fe(s,c,w),le(s,e,c,w),m?.invalidate(s,e),_(s,e,"update",w),d({key:e,op:"update",row:w,table:s}),z(s,"after","update")&&await Y("after","update",{doc:w,id:e,op:"update",previous:c,table:s}),await E({doc:w,id:e,op:"update",table:s})},async patchMany(e,r,a){te(e.length,r?.limit,"patchMany");for(const p of e)await L.patch(p.id,p.patch,a);return{patched:e.length}},async patchWhere(e,r,a){const p=U(e,"patchWhere");let f;if(p)f=(await p.findMany(e,{where:r.where})).page.map(c=>({id:String(c._id),patch:r.patch}));else{if(!n.tables[e])throw new b("INTERNAL",`unknown table: ${e}`);f=(await L.findMany(e,{where:r.where})).page.map(c=>({id:String(c._id),patch:r.patch}))}if(te(f.length,a?.limit,"patchWhere"),L.patchMany===void 0)throw new b("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await L.patchMany(f,a),{patched:f.length}},query(e){const r=U(e,"query");return r?(l(e,W),r.query(e)):(l(e,W),Sn(o,n,e,$))},async rank(e,r,a){const p=U(e,"rank");if(p)return l(e,W),p.rank(e,r,a);$(e,r,"rank");const f=n.tables[e];if(!f)throw new b("INTERNAL",`unknown table: ${e}`);const c=f.rankIndexes?.find(B=>B.name===r);if(!c)throw new b("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(Pe(e,f,c),a.restrictsCounts)throw new _e(e);l(e,W),Te(e,c);const s=typeof a.row=="string"?a.row:a.row._id;if(!s)return null;const u=Ve(e,c.name),w=c.sortBy.map((B,ee)=>Ye(ee)),y=w.map(B=>St(B)).join(", "),g=O(o,t`SELECT ${t.identifier("__partition__")}, ${t.raw(y)} FROM ${t.identifier(u)} WHERE ${t.identifier("__id__")} = ${s}`).toArray(),[I]=g;if(I===void 0)return null;let D=I.__partition__;const M=H(a.baseWhere,a.where);ve(M,n,e,"rank");const v=Lt(c,M);if(v){const B=Dt(c.partitionBy??[],v);if(B!==D)return null;D=B}const q=w.map(B=>I[B]),{before:G,total:j}=ot(o,u,w,c.sortBy,D,q,s);return{position:G+1,total:j}},async rankBefore(e,r,a){if(k(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 p=n.tables[e];if(!p)throw new b("INTERNAL",`unknown table: ${e}`);const f=p.rankIndexes?.find(w=>w.name===r);if(!f)throw new b("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(a.restrictsCounts)throw new _e(e);l(e,W),Te(e,f);const c=Ve(e,f.name),s=f.sortBy.map((w,y)=>Ye(y)),u=f.sortBy.map((w,y)=>ie(a.sortValues[y]??null));return ot(o,c,s,f.sortBy,a.partitionKey,u,a.rowId)},async rankPage(e,r,a={}){ve(H(a.baseWhere,a.where),n,e,"rankPage");const p=U(e,"rankPage");if(p)return l(e,W),p.rankPage(e,r,a);$(e,r,"rank");const{continueCursor:f,hasMore:c,rows:s}=je(Ge,e,r,a);return{continueCursor:f,isDone:!c,page:s.map(u=>u.doc)}},async rankPageRows(e,r,a={}){ve(H(a.baseWhere,a.where),n,e,"rankPage"),$(e,r,"rank");const{directions:p,hasMore:f,rows:c}=je(Ge,e,r,a);return{directions:p,hasMore:f,rows:c}},async restore(e,r){const a=Q(e,r);if(!a){const c=r===void 0?oe():void 0;if(c?.restore){await c.restore(e);return}throw new b("INTERNAL",`document not found: ${e}`)}const p=n.tables[a.tableName]?.softDeleteMode?.field;if(!p)throw new b("INTERNAL",`ctx.db.restore: table "${a.tableName}" is not a .softDelete() table`);const f=a.row[p]!==null&&a.row[p]!==void 0;await L.patch(e,{[p]:null},r),f&&le(a.tableName,e,void 0,a.row)},async replace(e,r,a,p){const f=Q(e,a);if(!f){const I=a===void 0?oe():void 0;if(I){await I.replace(e,r,void 0,p);return}throw new b("INTERNAL",`document not found: ${e}`)}const{docJson:c,row:s,tableName:u}=f,w=n.tables[u];if(!w)throw new b("INTERNAL",`unknown table: ${u}`);it("replace",r);const y=p?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:T(),g={...r,_creationTime:y,_id:e};rt(w,r,g,N),xe(w,g),z(u,"before","update")&&await Y("before","update",{doc:{...g},id:e,op:"update",previous:s,table:u}),ae(u),se(u),Ee(o,u,t`UPDATE ${t.identifier(u)} SET _creationTime = ${y}, ${t.identifier(F)} = ${JSON.stringify(g)} WHERE id = ${e} AND ${t.identifier(F)} = ${c}`),pe(u,e,g,s),he(u,e,g),fe(u,s,g),le(u,e,s,g),m?.invalidate(u,e),_(u,e,"update",g),d({key:e,op:"update",row:g,table:u}),z(u,"after","update")&&await Y("after","update",{doc:g,id:e,op:"update",previous:s,table:u}),await E({doc:g,id:e,op:"update",table:u})},async wipeShard(e){const r=new Set(e?.exclude),a=e?.tables,p=Object.entries(n.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(!n.tables[u])throw new b("INTERNAL",`wipeShard: unknown table: ${u}`)}const f={};let c=0;const{deleteAll:s}=L;if(s===void 0)throw new b("INTERNAL","wipeShard: this writer has no deleteAll");for(const u of p){const w=await s(u,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});f[u]=w.deleted,c+=w.deleted}return{deleted:c,tables:f}}},ft={db:L,scheduler:x};return i.enforceRls===!0?Bt(L,n,(e,r)=>Q(e,r)?.tableName):L};export{or as CDC_LOG_TABLE,pr as CLIENT_WATERMARK_TABLE,br as GLOBAL_SHAPE_SNAPSHOT_TABLE,Rr as IDEMPOTENCY_TABLE,yn as NotUniqueError,Mr as SEARCH_STATE_TABLE,mr as advanceClientWatermark,ar as applyCdcChanges,nn as assertValidClientId,tr as backfillAggregateIndexes,nr as backfillRankIndexes,rr as backfillSearchIndexes,sr as bumpCdcEpoch,Xn as createShardCtxDb,Er as deleteGlobalShapeSnapshot,yr as deleteGlobalShapeSnapshotsForConnection,wr as migrateClientWatermark,Nr as migrateGlobalShapeSnapshot,lr as minCdcSeq,tt as normalizeIdStructurally,dr as readCdcChanges,cr as readCdcCursor,ur as readCdcEpoch,$r as readClientWatermark,Tr as readGlobalShapeSnapshot,_r as readIdempotent,Cr as runShardMigrations,Dr as selectShapeMemberIds,Or as selectShapeRows,fr as trimCdcChanges,Ir as trimIdempotent,Sr as writeGlobalShapeSnapshot,vr as writeIdempotent};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createShardCtxDb as b}from"./NotUniqueError-
|
|
1
|
+
import{createShardCtxDb as b}from"./NotUniqueError-Bw1Oh2FL.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-CnCyh6oX.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as v}from"./runShardMigrations-CPxqCh3O.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};
|
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.2",
|
|
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",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as b}from"@lunora/errors";import{n as ht,A as Le,T as we,y as pt,c as mt}from"./FTS_COUNT_COLUMN-D1gY3wwZ-CZHdaRrd.mjs";import{sql as t}from"drizzle-orm";import{aggregateSqlFunction as $e,normalizeCountArgument as wt,throwingScheduler as $t}from"./AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{encodeAggregateKey as Se,readAggregateValue as Ae,aggregateTableName as _e}from"./aggregateTableName-G-eXyjcz.mjs";import{mergeWhere as H,CountRlsUnsupportedError as Re,selectIndexForGroupBy as gt,selectIndexForCount as bt,selectIndexForAggregate as Et}from"./CountRlsUnsupportedError-B2WKJD9v.mjs";import{backfillSearchIndexesForTable as yt}from"./backfillAggregateIndexes-BHiewuB-.mjs";import{backfillAggregateIndexes as er,backfillRankIndexes as tr,backfillSearchIndexes as nr}from"./backfillAggregateIndexes-BHiewuB-.mjs";import{appendCdcChange as Nt}from"./CDC_LOG_TABLE-BnqlH2eZ.mjs";import{CDC_LOG_TABLE as ir,applyCdcChanges as or,bumpCdcEpoch as ar,minCdcSeq as sr,readCdcChanges as lr,readCdcCursor as dr,readCdcEpoch as cr,trimCdcChanges as ur}from"./CDC_LOG_TABLE-BnqlH2eZ.mjs";import{createCompanionSync as Tt}from"./createCompanionSync-BCBUOnMk.mjs";import{computeRankPage as je}from"./computeRankPage-IUSS-zIB.mjs";import{SCAN_DEP as W}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as O}from"./runDrizzle-GKR3y97k.mjs";import{DOC_COLUMN as B,quoteIdentifier as St,AGG_VALUE as ge,AGG_COUNT as Ie,AGG_KEY as be,jsonPathSql as P,rowToDocument as re,tableColumns as at,isFtsAvailable as At,tryRowToDocument as st,geoTableName as _t,qualifiedJsonPathSql as Je}from"./AGG_COUNT-BWXe3gtQ.mjs";import{coveringGeohashes as Rt,boundingBoxGeohashes as It,pointInBoundingBox as vt,haversineMeters as xt}from"./GEO_DEFAULT_PRECISION-okRCkZ6r.mjs";import{NotFoundError as Ct}from"./NotFoundError-BhF7FeFr.mjs";import{normalizeOrderKeys as kt,buildSeekWhere as lt,decodeCursor as Ce,applySelect as ze,encodeCursor as ke,softDeleteScope as ne,buildSeekBeforeWhere as Mt}from"./applySelect-B0CF8T7y.mjs";import{sortColumnName as Ye,resolveRankPartition as Lt,encodePartitionKey as Dt,RANK_TIEBREAK as Ot,rankTableName as Ve}from"./RANK_TIEBREAK-9NU5s_mi.mjs";import{assertFlatPredicate as ve,resolveRelationPredicates as Ke}from"./DEFAULT_MAX_RELATION_KEYS-bq00btqV.mjs";import{runRowValidators as xe,resolveWith as Qe,applyOnDelete as Wt,fanOutScalarCounts as Bt}from"./applyOnDelete-uFRC5p1d.mjs";import{guardWriter as qt}from"./RLS_UNWRAP_SYMBOL-C6_WX3dG.mjs";import{createSystemReader as Ft}from"./createSystemReader-DcDcrtM3.mjs";import{ConflictError as de}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as Ut}from"./hasTrigger-CbkOHExZ.mjs";import{compileWhereSql as K}from"./compileWhereSql-BLcfs4QW.mjs";import{CLIENT_WATERMARK_TABLE as hr,advanceClientWatermark as pr,migrateClientWatermark as mr,readClientWatermark as wr}from"./CLIENT_WATERMARK_TABLE-CXsSLU8D.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as gr,deleteGlobalShapeSnapshot as br,deleteGlobalShapeSnapshotsForConnection as Er,migrateGlobalShapeSnapshot as yr,readGlobalShapeSnapshot as Nr,writeGlobalShapeSnapshot as Tr}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DX-6-gBP.mjs";import{IDEMPOTENCY_TABLE as Ar,readIdempotent as _r,trimIdempotent as Rr,writeIdempotent as Ir}from"./IDEMPOTENCY_TABLE-DjkEMp6w.mjs";import{runShardMigrations as xr}from"./runShardMigrations-CPxqCh3O.mjs";import{SEARCH_STATE_TABLE as kr}from"./SEARCH_STATE_TABLE-eLN8U5tz.mjs";import{selectShapeMemberIds as Lr,selectShapeRows as Dr}from"./selectShapeMemberIds-DvE7K6zG.mjs";import{serializeSqlValue as ie}from"./serializeSqlValue-DnpyaLcw.mjs";const Ht=i=>{const o=new TextEncoder().encode(i);let n="";for(const d of o)n+=String.fromCodePoint(d);return btoa(n)},Pt=i=>{const o=atob(i),n=Uint8Array.from(o,d=>d.codePointAt(0)??0);return new TextDecoder().decode(n)},Gt=()=>new b("BAD_REQUEST","invalid cursor"),Xe=16,Ze=8,J=1024,De=(i,o)=>o.query(i),jt=(i,o,n)=>{const d=ht(i,n);if(d.length===0)return 0;let l=0;for(const[w,E]of o.entries()){const $=w===o.length-1;let N=0;for(const C of d)($?C.startsWith(E):C===E)&&(N+=1);if(N===0)return 0;l+=N}return l},Jt=(i,o)=>{if(!o)return{exact:!0,lower:i,upper:i};const n=i.codePointAt(i.length-1)??0,d=i.slice(0,Math.max(0,i.length-String.fromCodePoint(n).length));return{exact:!1,lower:i,upper:d+String.fromCodePoint(n+1)}},zt=(i,o,n)=>{const d={eq:(l,w)=>{if(!i.definition.filterFields?.includes(l))throw new b("INTERNAL",`field "${l}" is not a filter field of search index "${i.indexName}" on table "${o}"`);if(i.filters.length>=Ze)throw new b("BAD_REQUEST",`search index "${i.indexName}" on table "${o}": at most ${String(Ze)} .eq() filters are supported per search query`);return i.filters.push({field:l,value:w}),d},search:(l,w)=>{const E=i;if(l!==E.definition.field)throw new b("INTERNAL",`search index "${E.indexName}" on table "${o}" indexes "${E.definition.field}", not "${l}"`);const $=De(w,n).length;if($>Xe)throw new b("BAD_REQUEST",`search index "${E.indexName}" on table "${o}": at most ${String(Xe)} search terms are supported (got ${String($)})`);return E.field=l,E.query=w,E.hasQuery=!0,d}};return d},Yt=i=>{if(i.length>J)throw new b("BAD_REQUEST",`more than ${String(J)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Vt=i=>Math.min(i.offset+i.numItems+1,J),Kt=i=>Ht(`search:${String(i)}`),Qt=i=>{let o;try{o=Pt(i)}catch{return}if(!o.startsWith("search:"))return;const n=Number(o.slice(7));return Number.isInteger(n)&&n>=0?n:void 0},Xt=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)),n=i.cursor?Qt(i.cursor):0;if(n===void 0)throw Gt();if(n+o>J)throw new b("BAD_REQUEST",`search pagination reaches past the ${String(J)}-document limit (offset ${String(n)} + ${String(o)} requested) — narrow the query or the filters instead`);return{numItems:o,offset:n}},Zt=(i,o)=>{const n=o.offset+o.numItems,d=o.numItems>0&&i.length>n;return{continueCursor:d?Kt(n):null,isDone:!d,page:i.slice(o.offset,n)}},en=i=>{if(i===void 0)return J+1;if(!Number.isFinite(i))return J;const o=Math.max(0,Math.floor(i));if(o>J)throw new b("BAD_REQUEST",`search returns at most ${String(J)} documents (asked for ${String(o)}) — narrow the query or paginate instead`);return o},tn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,nn=i=>{if(!tn.test(i))throw new b("INTERNAL",`invalid clientId ${JSON.stringify(i)}: a client-supplied row id must be a UUID`)},et=50,dt=500,te=(i,o,n)=>{const d=o??dt;if(i>d)throw new b("BATCH_LIMIT_EXCEEDED",`${n}: batch of ${String(i)} exceeds the limit of ${String(d)} (raise options.limit or chunk the call)`,{status:400})},rn=i=>{const o={eq:(n,d)=>(i.sqlConditions.push({comparator:"=",field:n,value:d}),o),gt:(n,d)=>(i.sqlConditions.push({comparator:">",field:n,value:d}),o),gte:(n,d)=>(i.sqlConditions.push({comparator:">=",field:n,value:d}),o),lt:(n,d)=>(i.sqlConditions.push({comparator:"<",field:n,value:d}),o),lte:(n,d)=>(i.sqlConditions.push({comparator:"<=",field:n,value:d}),o)};return o},on=i=>Math.max(i,J),an=(i,o,n,d,l)=>{const w=De(n.query,Le(n.definition.language));if(w.length===0)return[];const E=mt(o,n.indexName),$=`${E}__vocab`,N=w.length-1,C=w.map((R,_)=>{const k=Jt(R,_===N),V=k.exact?t`${t.identifier("term")} = ${k.lower}`:t`${t.identifier("term")} >= ${k.lower} AND ${t.identifier("term")} < ${k.upper}`;return t`SELECT ${t.identifier("doc")}, ${t.raw(String(_))} AS ${t.identifier("__term__")}, COUNT(*) AS ${t.identifier("__n__")} FROM ${t.identifier($)} WHERE ${V} GROUP BY ${t.identifier("doc")}`}),x=w.map((R,_)=>t`SUM(CASE WHEN u.${t.identifier("__term__")} = ${t.raw(String(_))} THEN u.${t.identifier("__n__")} ELSE 0 END)`),S=t`SELECT f.${t.identifier(we)} AS ${t.identifier(we)}, ${t.join(x,t` + `)} AS ${t.identifier("__score__")} FROM (${t.join(C,t` UNION ALL `)}) u JOIN ${t.identifier(E)} f ON f.rowid = u.${t.identifier("doc")} GROUP BY f.${t.identifier(we)} HAVING ${t.join(x.map(R=>t`${R} > 0`),t` AND `)}`,T=[];for(const R of n.filters)T.push(t`${P(R.field)} = ${ie(R.value)}`);l&&T.push(l);let p=t`SELECT m.id, m._creationTime, m.${t.identifier(B)} FROM (${S}) s JOIN ${t.identifier(o)} m ON m.id = s.${t.identifier(we)}`;T.length>0&&(p=t`${p} WHERE ${t.join(T,t` AND `)}`),p=t`${p} ORDER BY s.${t.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${t.raw(String(d))}`;const A=[];for(const R of O(i,p)){const _=st(R);_&&A.push(_)}return A},sn=(i,o,n,d,l)=>{const w=Le(n.definition.language),E=De(n.query,w);if(E.length===0)return[];const $=[];for(const S of n.filters)$.push(t`${P(S.field)} = ${ie(S.value)}`);l&&$.push(l);let N=t`SELECT id, _creationTime, ${t.identifier(B)} FROM ${t.identifier(o)}`;$.length>0&&(N=t`${N} WHERE ${t.join($,t` AND `)}`),N=t`${N} ORDER BY _creationTime DESC, id ASC LIMIT ${t.raw(String(on(d)))}`;const C=O(i,N).toArray(),x=[];for(const S of C){const T=st(S);if(!T)continue;const p=jt(pt(T,n.definition),E,w);p>0&&x.push({creationTime:typeof T._creationTime=="number"?T._creationTime:0,doc:T,id:typeof T._id=="string"?T._id:"",score:p})}return x.sort((S,T)=>T.score-S.score||T.creationTime-S.creationTime||S.id.localeCompare(T.id)),x.slice(0,d).map(S=>S.doc)},ln=(i,o)=>{const n=i,d={near:(l,w)=>{if(n.within)throw new b("INTERNAL",`geo index "${n.indexName}" on table "${o}": call .near() or .within(), not both`);return n.near={point:{lat:l.lat,lng:l.lng},radiusMeters:w},d},within:l=>{if(n.near)throw new b("INTERNAL",`geo index "${n.indexName}" on table "${o}": call .near() or .within(), not both`);return n.within={ne:{lat:l.ne.lat,lng:l.ne.lng},sw:{lat:l.sw.lat,lng:l.sw.lng}},d}};return d},dn=(i,o)=>{const n=i[o];if(n===null||typeof n!="object")return;const{lat:d,lng:l}=n;return typeof d=="number"&&typeof l=="number"?{lat:d,lng:l}:void 0},cn=(i,o)=>{const n=dn(i,o.definition.field);if(!n)return;const d=typeof i._creationTime=="number"?i._creationTime:0;if(o.near){const l=xt(o.near.point,n);return l<=o.near.radiusMeters?{creationTime:d,distance:l}:void 0}return vt(n,o.within)?{creationTime:d,distance:0}:void 0},un=(i,o,n,d,l)=>{if(!n.near&&!n.within)throw new b("INTERNAL",`geo index "${n.indexName}" on table "${o}": call .near(point, radius) or .within(box)`);const w=n.near?Rt(n.near.point,n.near.radiusMeters):It(n.within),E=_t(o,n.indexName),$=w.map(p=>t`(g.${t.identifier("__geohash__")} >= ${p} AND g.${t.identifier("__geohash__")} < ${`${p}{`})`),N=[t`(${t.join($,t` OR `)})`];l&&N.push(l);const C=t`SELECT m.id, m._creationTime, m.${t.identifier(B)} FROM ${t.identifier(E)} g JOIN ${t.identifier(o)} m ON m.id = g.${t.identifier("__id__")} WHERE ${t.join(N,t` AND `)}`,x=O(i,C).toArray(),S=[];for(const p of x){const A=re(p),R=A?cn(A,n):void 0;A&&R&&S.push({creationTime:R.creationTime,distance:R.distance,doc:A})}S.sort((p,A)=>p.distance-A.distance||A.creationTime-p.creationTime);const T=S.map(p=>p.doc);return typeof d=="number"?T.slice(0,Math.max(0,Math.floor(d))):T},fn=(i,o,n,d,l)=>{const{geo:w}=n;if(!w)throw new b("INTERNAL","runGeoTerminal called without a staged geo query");const E=n.inMemoryFilters.length>0,$=un(i,o,w,E?void 0:l,d);if(!E)return $;const N=[];for(const C of $)if(n.inMemoryFilters.every(x=>x(C))&&(N.push(C),typeof l=="number"&&N.length>=l))break;return N},hn=(i,o,n,d,l,w)=>{const E=[];for(const x of n.sqlConditions)E.push(t`${P(x.field)} ${t.raw(x.comparator)} ${ie(x.value)}`);d&&E.push(d);let $=t`SELECT id, _creationTime, ${t.identifier(B)} FROM ${t.identifier(o)}`;E.length>0&&($=t`${$} WHERE ${t.join(E,t` AND `)}`),$=t`${$} ORDER BY ${l}`,typeof w=="number"&&n.inMemoryFilters.length===0&&($=t`${$} LIMIT ${t.raw(String(Math.max(0,Math.floor(w))))}`);const N=O(i,$).toArray(),C=[];for(const x of N){const S=re(x);if(S&&n.inMemoryFilters.every(T=>T(S))&&(C.push(S),typeof w=="number"&&C.length>=w))break}return C},X={fieldRef:P,serialize:ie},pn=i=>{let o=0;const n=[],d={fieldRef:P,relationExists:l=>{const{childWhere:w,negated:E,parentTable:$,relation:N}=l,C=`__rel_${String(o)}`,x=n.at(-1)??$;o+=1,i(N.table,W);const S=N.kind==="one"?N.field:N.references,T=N.kind==="one"?N.references:N.field,p=t`${Je(C,T)} = ${Je(x,S)}`;n.push(C);const A=K(w,d);n.pop();const R=A?t`${p} AND ${A}`:p,_=t`EXISTS (SELECT 1 FROM ${t.identifier(N.table)} AS ${t.identifier(C)} WHERE ${R})`;return E?t`NOT ${_}`:_},serialize:ie};return d},ct=i=>{const o=i.map(n=>t`${P(n.field)} ${t.raw(n.direction==="desc"?"DESC":"ASC")}`);return i.some(n=>n.field==="_id"||n.field==="id")||o.push(t`${P("id")} ASC`),t.join(o,t`, `)},mn={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},wn=i=>{const o=i.order;return i.indexFields.length>0?i.indexFields.map(n=>({direction:o,field:n})):[{direction:o,field:"_creationTime"}]},$n=(i,o,n,d)=>{const l=i.sqlConditions.map(w=>({[w.field]:{[mn[w.comparator]??"eq"]:w.value}}));if(n&&l.push(lt(o,Ce(n))),d&&l.push(Mt(o,Ce(d))),l.length!==0)return l.length===1?l[0]:{AND:l}},gn=(i,o,n)=>{const d=[];for(const l of i){const w=re(l);if(w&&o.every(E=>E(w))&&(d.push(w),n!==void 0&&d.length>n))break}return d},bn=(i,o,n,d,l)=>{const w=Math.max(0,Math.floor(d.numItems)),E=wn(n),$=typeof d.endCursor=="string",N=K($n(n,E,d.cursor,d.endCursor),X),C=l&&N?t`${N} AND ${l}`:l??N;let x=t`SELECT id, _creationTime, ${t.identifier(B)} FROM ${t.identifier(o)}`;C&&(x=t`${x} WHERE ${C}`),x=t`${x} ORDER BY ${ct(E)}`;const S=n.inMemoryFilters.length>0;!S&&!$&&(x=t`${x} LIMIT ${t.raw(String(w+1))}`);const T=O(i,x).toArray(),p=gn(T,n.inMemoryFilters,S||$?void 0:w);if($){const k=p.length>=2?p[Math.floor(p.length/2)-1]:void 0;return{continueCursor:d.endCursor??null,isDone:!0,page:p,splitCursor:k?ke(k,E):null}}const A=p.length>w,R=A?p.slice(0,w):p,_=R.at(-1);return{continueCursor:A&&_?ke(_,E):null,isDone:!A,page:R}};class En extends b{constructor(o="unique() found more than one matching document"){super("NOT_UNIQUE",o,{name:"NotUniqueError"})}}const yn=/\s/u,Nn=String.fromCodePoint(0),tt=(i,o,n)=>{if(!i.tables[o])throw new b("INTERNAL",`unknown table: ${o}`);return typeof n!="string"||n.length===0||yn.test(n)||n.includes(Nn)?null:n},Tn=(i,o,n,d=()=>{})=>{const l=o.tables[n];if(!l)throw new b("INTERNAL",`unknown table: ${n}`);const w=ne(l.softDeleteMode,void 0),E=w?K(w,X):void 0,$={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]},N=p=>{const{search:A}=$;if(!A)throw new b("INTERNAL","runSearchFetch called without a staged search");yt(i,n,l);const R=$.inMemoryFilters.length>0,_=en(R?void 0:p),k=At(i)?an(i,n,A,_,E):sn(i,n,A,_,E);if(!R)return p===void 0&&Yt(k),k;const V=[];for(const Z of k)if($.inMemoryFilters.every(U=>U(Z))&&(V.push(Z),typeof p=="number"&&V.length>=p))break;return V},C=p=>{const A=Xt(p);return Zt(N(Vt(A)),A)},x=()=>{const p=$.indexFields.length>0?$.indexFields:["_creationTime"],A=$.order==="desc"?"DESC":"ASC";return t.join(p.map(R=>t`${P(R)} ${t.raw(A)}`),t`, `)},S=p=>$.search?N(p):$.geo?fn(i,n,$,E,p):hn(i,n,$,E,x(),p),T={async collect(){return S(void 0)},filter(p){return $.inMemoryFilters.push(p),T},async first(){return S($.inMemoryFilters.length>0?void 0:1)[0]??null},order(p){return $.order=p==="desc"?"desc":"asc",T},async paginate(p){if($.search)return C(p);if($.geo)throw new b("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");return bn(i,n,$,p,E)},async take(p){return S(p)},async unique(){const p=S($.inMemoryFilters.length>0?void 0:2);if(p.length>1)throw new En(`unique() on table "${n}" matched ${String(p.length)} documents; expected at most one`);return p[0]??null},withGeoIndex(p,A){const R=(l.geoIndexes??[]).find(k=>k.name===p);if(!R)throw new b("INTERNAL",`unknown geo index "${p}" on table "${n}"`);d(n,p,"geo");const _={definition:R,indexName:p};if($.geo=_,A(ln(_,n)),!_.near&&!_.within)throw new b("INTERNAL",`geo index "${p}" on table "${n}" requires a .near(point, radius) or .within(box) call`);return T},withIndex(p,A){const R=l.indexes.find(_=>_.name===p);if(!R)throw new b("INTERNAL",`unknown index "${p}" on table "${n}"`);return d(n,p,"index"),$.indexName=p,$.indexFields=R.fields,A&&A(rn($)),T},withSearchIndex(p,A){const R=(l.searchIndexes??[]).find(k=>k.name===p);if(!R)throw new b("INTERNAL",`unknown search index "${p}" on table "${n}"`);d(n,p,"search");const _={definition:R,field:R.field,filters:[],hasQuery:!1,indexName:p,query:""};if($.search=_,A(zt(_,n,Le(R.language))),!_.hasQuery)throw new b("INTERNAL",`search index "${p}" on table "${n}" requires a .search(field, query) call`);return T}};return T},nt=(i,o,n)=>{const d={...o};for(const[l,w]of at(i)){if(w.serverDefault){d[l]=w.serverDefault({auth:n});continue}d[l]===void 0&&(w.defaultFn?d[l]=w.defaultFn():"defaultValue"in w&&(d[l]=w.defaultValue))}return d},rt=(i,o,n,d)=>{const l=n;for(const[w,E]of at(i)){if(E.serverDefault){w in o&&(l[w]=E.serverDefault({auth:d}));continue}E.onUpdateFn&&!(w in o)&&(l[w]=E.onUpdateFn())}},it=(i,o)=>{for(const n of Object.keys(o))if(o[n]===void 0)throw new b("INTERNAL",`Cannot ${i} field '${n}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Sn=/unique constraint failed/i,An=i=>i instanceof Error&&Sn.test(i.message),Me=(i,o,n)=>{try{O(i,n)}catch(d){throw An(d)?new de(`unique constraint violation on "${o}"`,"unique"):d}},Ee=(i,o,n)=>{if(Me(i,o,n),O(i,t`SELECT changes() AS changed`).one().changed===0)throw new de(`optimistic concurrency conflict on "${o}" — the row changed during this mutation; refetch and retry`,"occ")},ot=(i,o,n,d,l,w,E)=>{const $=[];for(let S=0;S<n.length+1;S+=1){const T=[];for(let _=0;_<S;_+=1)T.push(t`${t.identifier(n[_])} IS ${w[_]}`);const p=n[S],A=d[S];if(p!==void 0&&A!==void 0){const _=A.direction==="desc"?">":"<";T.push(t`${t.identifier(p)} ${t.raw(_)} ${w[S]}`)}else T.push(t`${t.identifier(Ot)} < ${E}`);const[R]=T;$.push(T.length===1&&R!==void 0?R:t`(${t.join(T,t` AND `)})`)}const N=t.join($,t` OR `),C=O(i,t`SELECT COUNT(*) AS c FROM ${t.identifier(o)} WHERE ${t.identifier("__partition__")} = ${l} AND (${N})`).one(),x=O(i,t`SELECT COUNT(*) AS c FROM ${t.identifier(o)} WHERE ${t.identifier("__partition__")} = ${l}`).one();return{before:C.c,total:x.c}},Qn=i=>{const{sql:o}=i,{schema:n}=i,d=i.broadcast??(()=>{}),l=i.onRead??(()=>{}),w=i.onIndexUse??(()=>{}),E=i.onWrite??(()=>{}),{cache:$}=i,N=i.clock??(()=>Date.now()),C=i.idGenerator??(()=>crypto.randomUUID()),x=i.scheduler??$t,{globalDb:S}=i,T=i.auth??{identity:null,userId:null},p=i.cdc??!1,A=x,R=Ft({scheduler:typeof A.list=="function"&&typeof A.get=="function"?A:void 0,storage:i.storage}),_=(e,r,a,h)=>{p&&Nt(o,N(),e,r,a,h)},k=e=>n.tables[e]?.shardMode?.kind==="global",V=(e,r)=>{if(k(e)){if(!S)throw new b("INTERNAL",`cross-backend ${r} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return S}return L},Z=e=>V(e,"cascade"),U=(e,r)=>{if(k(e)){if(!S)throw new b("INTERNAL",`${r} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return S}},oe=()=>S,ye=(e,r)=>V(e,"relation load").findMany(e,r),Oe=(e,r)=>(k(e)&&l(e,W),ye(e,r)),ut=e=>!k(e.table),We=i.relationExistsPushDown??"auto",Be=We!=="never",{maxRelationKeys:qe}=i,ce=(e,r,a)=>Ke(e,{fetcher:Oe,maxRelationKeys:qe,relationBaseWhere:a,schema:n,tableName:r}),Fe=async(e,r,a,h)=>{const f=U(e,"relation grouped count");if(f)return l(e,W),Bt((v,F)=>f.count(v,F),e,r,a,h);const c=n.tables[e];if(!c)throw new b("INTERNAL",`unknown table: ${e}`);l(e,W);const s=ne(c.softDeleteMode,void 0),u={[r]:{in:a}},m=H(H(u,h),s),y=await ce(m,e,void 0),g=K(y,X),I=P(r);let D=t`SELECT ${I} AS __fk__, COUNT(*) AS count FROM ${t.identifier(e)}`;g&&(D=t`${D} WHERE ${g}`),D=t`${D} GROUP BY ${I}`;const M=O(o,D).toArray();return new Map(M.map(v=>[v.__fk__,v.count]))};let ue=0;const Ue=new Set;for(const[e,r]of Object.entries(n.tables))for(const a of Object.values(r.triggerMap??{}))Ue.add(`${e} ${a.timing} ${a.op}`);const z=(e,r,a)=>Ue.has(`${e} ${r} ${a}`),Y=async(e,r,a)=>{if(ue+=1,ue>et)throw ue-=1,new de(`trigger recursion exceeded ${String(et)} levels on "${a.table}" — check for a self-triggering write`,"trigger");try{await Ut({ctx:ft,event:a,op:r,schema:n,tableName:a.table,timing:e})}finally{ue-=1}},{ensureBackfilledForTable:ae,ensureBackfilledIndex:Ne,ensureRankBackfilled:Te,ensureRankBackfilledForTable:se,syncAggregates:fe,syncCompanionsForInsert:He,syncGeo:he,syncRanks:le,syncSearch:pe}=Tt({broadcast:d,invalidateCache:(e,r)=>$?.invalidate(e,r),recordCdc:_,schema:n,sql:o}),Pe=(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})},Q=(e,r)=>{const a=Object.entries(n.tables).filter(([,y])=>y.shardMode?.kind!=="global").map(([y])=>y).filter(y=>r===void 0||y===r);if(a.length===0)return;const h=a.map(y=>t`SELECT ${t.raw(`'${y.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${t.identifier(B)} FROM ${t.identifier(y)} WHERE id = ${e}`),f=t`${t.join(h,t` UNION ALL `)} LIMIT 1`,[c]=O(o,f).toArray();if(!c)return;const s=c.__t__,u=re(c);if(typeof s!="string"||!u)return;const m=c[B];return{docJson:typeof m=="string"?m:JSON.stringify(m??{}),row:u,tableName:s}},Ge={assertRankPartitionLocal:Pe,ensureRankBackfilled:Te,onRead:l,rowToDocument:re,schema:n,sql:o},L={system:R,async aggregate(e,r){const a=U(e,"aggregate");if(a)return l(e,W),a.aggregate(e,r);const h=n.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);if($e(r.op),r.op==="count")return L.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`);l(e,W);const f=ne(h.softDeleteMode,void 0),c=H(H(r.baseWhere,r.where),f),s=await ce(c,e,r.relationBaseWhere),u=s!==c;if(h.aggregateIndexes&&!r.baseWhere&&!u&&!f){const M=Et(h.aggregateIndexes,r.op,r.field,r.where);if(M){Ne(e,M.index);const v=Se(M.index.by??[],M.key),F=_e(e,M.index.name),G=O(o,t`SELECT ${ge} AS value, ${Ie} AS count FROM ${t.identifier(F)} WHERE ${be} = ${v}`).toArray()[0];return Ae(r.op,G)}}const m=K(s,X),y=$e(r.op),g=P(r.field);let I=t`SELECT ${t.raw(y)}(${g}) AS value FROM ${t.identifier(e)}`;return m&&(I=t`${I} WHERE ${m}`),O(o,I).toArray()[0]?.value??null},asId(e,r){const a=tt(n,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=U(e,"count");if(a)return l(e,W),a.count(e,r);const h=n.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);const f=wt(r);if(f.restrictsCounts)throw new Re(e);l(e,W);const c=ne(h.softDeleteMode,void 0),s=H(H(f.baseWhere,f.where),c),u=await ce(s,e,f.relationBaseWhere),m=u!==s;if(h.aggregateIndexes&&!f.baseWhere&&!m&&!c){const I=bt(h.aggregateIndexes,f.where);if(I){Ne(e,I.index);const D=Se(I.index.by??[],I.key),M=_e(e,I.index.name),v=O(o,t`SELECT ${ge} AS value FROM ${t.identifier(M)} WHERE ${be} = ${D}`).toArray();return v[0]===void 0?0:v[0].value??0}}const y=K(u,X);let g=t`SELECT COUNT(*) AS count FROM ${t.identifier(e)}`;return y&&(g=t`${g} WHERE ${y}`),O(o,g).one().count},async delete(e,r,a){const h=Q(e,r);if(!h){const g=r===void 0?oe():void 0;g&&await g.delete(e,void 0,a);return}const{docJson:f,row:c,tableName:s}=h,u=n.tables[s],m=a?.hard===!0,y=!m&&u?.softDeleteMode?u.softDeleteMode.field:void 0;if(!(y&&c[y]!==null&&c[y]!==void 0)){if(z(s,"before","delete")&&await Y("before","delete",{id:e,op:"delete",previous:c,table:s}),await Wt({deletedId:e,deletedReference:g=>c[g],findHolders:async(g,I,D)=>(await Z(g).findMany(g,{includeDeleted:m,where:{[I]:D}})).page,onCascade:(g,I)=>Z(g).delete(I,void 0,a),onRestrict:g=>{throw new de(g,"restrict")},onSetNull:(g,I,D)=>Z(g).patch(I,{[D]:null}),schema:n,tableName:s}),ae(s),se(s),y){const g={...c,[y]:N(),_id:e};Ee(o,s,t`UPDATE ${t.identifier(s)} SET ${t.identifier(B)} = ${JSON.stringify(g)} WHERE id = ${e} AND ${t.identifier(B)} = ${f}`),pe(s,e,g,c),he(s,e,void 0),fe(s,c,g),le(s,e,c,void 0),$?.invalidate(s,e),_(s,e,"update",g),d({key:e,op:"update",row:g,table:s}),z(s,"after","delete")&&await Y("after","delete",{id:e,op:"delete",previous:c,table:s}),await E({id:e,op:"delete",table:s});return}Ee(o,s,t`DELETE FROM ${t.identifier(s)} WHERE id = ${e} AND ${t.identifier(B)} = ${f}`),pe(s,e,void 0),he(s,e,void 0),fe(s,c,void 0),le(s,e,c,void 0),$?.invalidate(s,e),_(s,e,"delete"),d({key:e,op:"delete",table:s}),z(s,"after","delete")&&await Y("after","delete",{id:e,op:"delete",previous:c,table:s}),await E({id:e,op:"delete",table:s})}},async deleteAll(e,r){if(!n.tables[e])throw new b("INTERNAL",`unknown table: ${e}`);const a=Math.max(1,r?.chunkSize??dt),h=r?.hard===void 0?void 0:{hard:r.hard},f=k(e)?void 0:e;let c=0;for(;;){const s=(await L.findMany(e,{limit:a})).page.map(u=>String(u._id));if(s.length===0)break;for(const u of s)await L.delete(u,f,h),c+=1;if(s.length<a)break}return{deleted:c}},async deleteMany(e,r,a){te(e.length,r?.limit,"deleteMany");for(const h of e)await L.delete(h,a);return{deleted:e.length}},async deleteWhere(e,r,a){const h=U(e,"deleteWhere");let f;if(h)f=(await h.findMany(e,{where:r})).page.map(c=>String(c._id));else{if(!n.tables[e])throw new b("INTERNAL",`unknown table: ${e}`);f=(await L.findMany(e,{where:r})).page.map(c=>String(c._id))}if(te(f.length,a?.limit,"deleteWhere"),L.deleteMany===void 0)throw new b("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return L.deleteMany(f,a)},async findFirst(e,r={}){return(await L.findMany(e,{...r,limit:1})).page[0]??null},async findFirstOrThrow(e,r={}){const a=await L.findFirst(e,r);if(a===null)throw new Ct(`findFirstOrThrow: no "${e}" document matched`);return a},async findMany(e,r={}){const a=U(e,"findMany");if(a)return l(e,W),a.findMany(e,r);const h=n.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);const f=!r.where&&!r.baseWhere;f?l(e,W):l(e);const c=kt(r.orderBy),s=r.cursor?lt(c,Ce(r.cursor)):void 0;let u=H(r.baseWhere,r.where);u=H(u,ne(h.softDeleteMode,r.includeDeleted)),u=await Ke(u,{canPushExists:Be?ut:void 0,existsPushMode:We==="always"?"always":"auto",fetcher:Oe,maxRelationKeys:qe,relationBaseWhere:r.relationBaseWhere,schema:n,tableName:e}),s&&(u=u?{AND:[u,s]}:s);const m=Be?pn(l):X,y=K(u,m);let g=t`SELECT id, _creationTime, ${t.identifier(B)} FROM ${t.identifier(e)}`;y&&(g=t`${g} WHERE ${y}`),g=t`${g} ORDER BY ${ct(c)}`;const I=typeof r.limit=="number"?Math.max(0,Math.floor(r.limit)):void 0;I!==void 0&&(g=t`${g} LIMIT ${t.raw(String(I+1))}`);const D=O(o,g).toArray(),M=[];for(const j of D){const q=re(j);q&&(M.push(q),!f&&typeof q._id=="string"&&l(e,q._id))}if(I===void 0)return r.with&&await Qe({groupedCounter:Fe,fetcher:ye,parents:M,relationBaseWhere:r.relationBaseWhere,schema:n,tableName:e,with:r.with}),{continueCursor:null,isDone:!0,page:ze(M,r.select,r.with)};const v=M.length>I,F=v?M.slice(0,I):M,G=F.at(-1);return r.with&&await Qe({fetcher:ye,groupedCounter:Fe,parents:F,relationBaseWhere:r.relationBaseWhere,schema:n,tableName:e,with:r.with}),{continueCursor:v&&G?ke(G,c):null,isDone:!v,page:ze(F,r.select,r.with)}},async get(e,r){const a=Q(e,r);if(!a){const h=r===void 0?oe():void 0;return h?h.get(e):null}return l(a.tableName,e),a.row},async lookupById(e,r){const a=Q(e,r);return a?(l(a.tableName,e),{row:a.row,tableName:a.tableName}):null},async groupBy(e,r){const a=U(e,"groupBy");if(a)return l(e,W),a.groupBy(e,r);const h=n.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);l(e,W);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 c=ne(h.softDeleteMode,void 0),s=H(H(r.baseWhere,r.where),c),u=await ce(s,e,r.relationBaseWhere),m=u!==s;if(h.aggregateIndexes&&!r.baseWhere&&!m&&!c){const v=gt(h.aggregateIndexes,f.op,f.field,r.by,r.where);if(v){Ne(e,v.index);const F=_e(e,v.index.name),G=Object.keys(v.partial),j=[];if(G.length===(v.index.by??[]).length&&G.length>0){const ee=Se(v.index.by??[],v.partial),me=O(o,t`SELECT ${ge} AS value, ${Ie} AS count FROM ${t.identifier(F)} WHERE ${be} = ${ee}`).toArray();return me.length>0&&j.push({key:{...v.partial},value:Ae(f.op,me[0])}),j}const q=O(o,t`SELECT ${be} AS key, ${ge} AS value, ${Ie} AS count FROM ${t.identifier(F)}`).toArray();for(const ee of q){const me=JSON.parse(ee.key);j.push({key:me,value:Ae(f.op,ee)})}return j}}const y=K(u,X),g=r.by.map(v=>t`${P(v)} AS ${t.identifier(v)}`);if(f.op==="count")g.push(t`COUNT(*) AS value`);else{const{field:v}=f;if(v===void 0)throw new b("INTERNAL",`groupBy(${e}, { agg: { op: "${f.op}" } }): "field" is required for non-count reducers`);g.push(t`${t.raw($e(f.op))}(${P(v)}) AS value`)}let I=t`SELECT ${t.join(g,t`, `)} FROM ${t.identifier(e)}`;y&&(I=t`${I} WHERE ${y}`),I=t`${I} GROUP BY ${t.join(r.by.map(v=>P(v)),t`, `)}`;const D=O(o,I).toArray(),M=[];for(const v of D){const F={};for(const j of r.by)F[j]=v[j]??null;const{value:G}=v;M.push({key:F,value:G==null?null:Number(G)})}return M},async insert(e,r,a){const h=U(e,"insert");if(h){const y=await h.insert(e,r,a);return d({key:y,op:"insert",row:{...r,_id:y},table:e}),y}const f=n.tables[e];if(!f)throw new b("INTERNAL",`unknown table: ${e}`);const c=nt(f,r,T);xe(f,c);let s;a?.clientId!==void 0?(nn(a.clientId),s=a.clientId):a?.allowExplicitId&&typeof c._id=="string"?s=c._id:s=C();const u=a?.allowExplicitId&&typeof c._creationTime=="number"?c._creationTime:N(),m={...c,_creationTime:u,_id:s};return z(e,"before","insert")&&await Y("before","insert",{doc:{...m},id:s,op:"insert",table:e}),ae(e),se(e),Me(o,e,t`INSERT INTO ${t.identifier(e)} (id, _creationTime, ${t.identifier(B)}) VALUES (${s}, ${u}, ${JSON.stringify(m)})`),He(e,s,m),z(e,"after","insert")&&await Y("after","insert",{doc:m,id:s,op:"insert",table:e}),await E({doc:m,id:s,op:"insert",table:e}),s},async insertManyUnsafe(e,r,a){if(te(r.length,a?.limit,"insertManyUnsafe"),r.length===0)return[];const h=U(e,"insert");if(h){const u=[];for(const m of r){const y=await h.insert(e,m,{allowExplicitId:a?.allowExplicitId});d({key:y,op:"insert",row:{...m,_id:y},table:e}),u.push(y)}return u}const f=n.tables[e];if(!f)throw new b("INTERNAL",`unknown table: ${e}`);ae(e),se(e);const c=r.map(u=>{const m=nt(f,u,T),y=a?.allowExplicitId===!0&&typeof m._id=="string"?m._id:C(),g=a?.allowExplicitId===!0&&typeof m._creationTime=="number"?m._creationTime:N();return{creationTime:g,document:{...m,_creationTime:g,_id:y},id:y}}),s=t.join(c.map(u=>t`(${u.id}, ${u.creationTime}, ${JSON.stringify(u.document)})`),t`, `);Me(o,e,t`INSERT INTO ${t.identifier(e)} (id, _creationTime, ${t.identifier(B)}) VALUES ${s}`);for(const{document:u,id:m}of c)He(e,m,u),await E({doc:u,id:m,op:"insert",table:e});return c.map(u=>u.id)},async insertMany(e,r,a){te(r.length,a?.limit,"insertMany");const h=a?.skipDuplicates===!0,f=[];for(const c of r)try{f.push(await L.insert(e,c))}catch(s){if(h&&s instanceof de&&s.kind==="unique")f.push(null);else throw s}return f},normalizeId(e,r){return tt(n,e,r)},async patch(e,r,a){const h=Q(e,a);if(!h){const y=a===void 0?oe():void 0;if(y){await y.patch(e,r);return}throw new b("INTERNAL",`document not found: ${e}`)}const{docJson:f,row:c,tableName:s}=h,u=n.tables[s];if(!u)throw new b("INTERNAL",`unknown table: ${s}`);l(s,e),it("patch",r);const m={...c,...r,_id:e};rt(u,r,m,T),xe(u,m,!0),z(s,"before","update")&&await Y("before","update",{doc:{...m},id:e,op:"update",previous:c,table:s}),ae(s),se(s),Ee(o,s,t`UPDATE ${t.identifier(s)} SET ${t.identifier(B)} = ${JSON.stringify(m)} WHERE id = ${e} AND ${t.identifier(B)} = ${f}`),pe(s,e,m,c),he(s,e,m),fe(s,c,m),le(s,e,c,m),$?.invalidate(s,e),_(s,e,"update",m),d({key:e,op:"update",row:m,table:s}),z(s,"after","update")&&await Y("after","update",{doc:m,id:e,op:"update",previous:c,table:s}),await E({doc:m,id:e,op:"update",table:s})},async patchMany(e,r,a){te(e.length,r?.limit,"patchMany");for(const h of e)await L.patch(h.id,h.patch,a);return{patched:e.length}},async patchWhere(e,r,a){const h=U(e,"patchWhere");let f;if(h)f=(await h.findMany(e,{where:r.where})).page.map(c=>({id:String(c._id),patch:r.patch}));else{if(!n.tables[e])throw new b("INTERNAL",`unknown table: ${e}`);f=(await L.findMany(e,{where:r.where})).page.map(c=>({id:String(c._id),patch:r.patch}))}if(te(f.length,a?.limit,"patchWhere"),L.patchMany===void 0)throw new b("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await L.patchMany(f,a),{patched:f.length}},query(e){const r=U(e,"query");return r?(l(e,W),r.query(e)):(l(e,W),Tn(o,n,e,w))},async rank(e,r,a){const h=U(e,"rank");if(h)return l(e,W),h.rank(e,r,a);w(e,r,"rank");const f=n.tables[e];if(!f)throw new b("INTERNAL",`unknown table: ${e}`);const c=f.rankIndexes?.find(q=>q.name===r);if(!c)throw new b("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(Pe(e,f,c),a.restrictsCounts)throw new Re(e);l(e,W),Te(e,c);const s=typeof a.row=="string"?a.row:a.row._id;if(!s)return null;const u=Ve(e,c.name),m=c.sortBy.map((q,ee)=>Ye(ee)),y=m.map(q=>St(q)).join(", "),g=O(o,t`SELECT ${t.identifier("__partition__")}, ${t.raw(y)} FROM ${t.identifier(u)} WHERE ${t.identifier("__id__")} = ${s}`).toArray(),[I]=g;if(I===void 0)return null;let D=I.__partition__;const M=H(a.baseWhere,a.where);ve(M,n,e,"rank");const v=Lt(c,M);if(v){const q=Dt(c.partitionBy??[],v);if(q!==D)return null;D=q}const F=m.map(q=>I[q]),{before:G,total:j}=ot(o,u,m,c.sortBy,D,F,s);return{position:G+1,total:j}},async rankBefore(e,r,a){if(k(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=n.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);const f=h.rankIndexes?.find(m=>m.name===r);if(!f)throw new b("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(a.restrictsCounts)throw new Re(e);l(e,W),Te(e,f);const c=Ve(e,f.name),s=f.sortBy.map((m,y)=>Ye(y)),u=f.sortBy.map((m,y)=>ie(a.sortValues[y]??null));return ot(o,c,s,f.sortBy,a.partitionKey,u,a.rowId)},async rankPage(e,r,a={}){ve(H(a.baseWhere,a.where),n,e,"rankPage");const h=U(e,"rankPage");if(h)return l(e,W),h.rankPage(e,r,a);w(e,r,"rank");const{continueCursor:f,hasMore:c,rows:s}=je(Ge,e,r,a);return{continueCursor:f,isDone:!c,page:s.map(u=>u.doc)}},async rankPageRows(e,r,a={}){ve(H(a.baseWhere,a.where),n,e,"rankPage"),w(e,r,"rank");const{directions:h,hasMore:f,rows:c}=je(Ge,e,r,a);return{directions:h,hasMore:f,rows:c}},async restore(e,r){const a=Q(e,r);if(!a){const c=r===void 0?oe():void 0;if(c?.restore){await c.restore(e);return}throw new b("INTERNAL",`document not found: ${e}`)}const h=n.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 L.patch(e,{[h]:null},r),f&&le(a.tableName,e,void 0,a.row)},async replace(e,r,a,h){const f=Q(e,a);if(!f){const I=a===void 0?oe():void 0;if(I){await I.replace(e,r,void 0,h);return}throw new b("INTERNAL",`document not found: ${e}`)}const{docJson:c,row:s,tableName:u}=f,m=n.tables[u];if(!m)throw new b("INTERNAL",`unknown table: ${u}`);it("replace",r);const y=h?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:N(),g={...r,_creationTime:y,_id:e};rt(m,r,g,T),xe(m,g),z(u,"before","update")&&await Y("before","update",{doc:{...g},id:e,op:"update",previous:s,table:u}),ae(u),se(u),Ee(o,u,t`UPDATE ${t.identifier(u)} SET _creationTime = ${y}, ${t.identifier(B)} = ${JSON.stringify(g)} WHERE id = ${e} AND ${t.identifier(B)} = ${c}`),pe(u,e,g,s),he(u,e,g),fe(u,s,g),le(u,e,s,g),$?.invalidate(u,e),_(u,e,"update",g),d({key:e,op:"update",row:g,table:u}),z(u,"after","update")&&await Y("after","update",{doc:g,id:e,op:"update",previous:s,table:u}),await E({doc:g,id:e,op:"update",table:u})},async wipeShard(e){const r=new Set(e?.exclude),a=e?.tables,h=Object.entries(n.tables).filter(([u,m])=>r.has(u)||a!==void 0&&!a.includes(u)?!1:m.shardMode?.kind!=="global").map(([u])=>u);if(a!==void 0){for(const u of a)if(!n.tables[u])throw new b("INTERNAL",`wipeShard: unknown table: ${u}`)}const f={};let c=0;const{deleteAll:s}=L;if(s===void 0)throw new b("INTERNAL","wipeShard: this writer has no deleteAll");for(const u of h){const m=await s(u,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});f[u]=m.deleted,c+=m.deleted}return{deleted:c,tables:f}}},ft={db:L,scheduler:x};return i.enforceRls===!0?qt(L,n,(e,r)=>Q(e,r)?.tableName):L};export{ir as CDC_LOG_TABLE,hr as CLIENT_WATERMARK_TABLE,gr as GLOBAL_SHAPE_SNAPSHOT_TABLE,Ar as IDEMPOTENCY_TABLE,En as NotUniqueError,kr as SEARCH_STATE_TABLE,pr as advanceClientWatermark,or as applyCdcChanges,nn as assertValidClientId,er as backfillAggregateIndexes,tr as backfillRankIndexes,nr as backfillSearchIndexes,ar as bumpCdcEpoch,Qn as createShardCtxDb,br as deleteGlobalShapeSnapshot,Er as deleteGlobalShapeSnapshotsForConnection,mr as migrateClientWatermark,yr as migrateGlobalShapeSnapshot,sr as minCdcSeq,tt as normalizeIdStructurally,lr as readCdcChanges,dr as readCdcCursor,cr as readCdcEpoch,wr as readClientWatermark,Nr as readGlobalShapeSnapshot,_r as readIdempotent,xr as runShardMigrations,Lr as selectShapeMemberIds,Dr as selectShapeRows,ur as trimCdcChanges,Rr as trimIdempotent,Tr as writeGlobalShapeSnapshot,Ir as writeIdempotent};
|