@lunora/shard-engine 1.0.0-alpha.39 → 1.0.0-alpha.40
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/conformance/index.mjs +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{ADMIN_FUNCTIONS-DZ5yKTXx.mjs → ADMIN_FUNCTIONS-DcSYybsq.mjs} +1 -1
- package/dist/packem_shared/{AGG_COUNT-DOlqqroz.mjs → AGG_COUNT-B6_CmAZD.mjs} +1 -1
- package/dist/packem_shared/{CDC_LOG_TABLE-VfPoURHu.mjs → CDC_LOG_TABLE-CW0wHEgW.mjs} +1 -1
- package/dist/packem_shared/NotUniqueError-Dnik6z41.mjs +1 -0
- package/dist/packem_shared/{backfillAggregateIndexes-DDgDYJcc.mjs → backfillAggregateIndexes-C9wGiPH4.mjs} +1 -1
- package/dist/packem_shared/{buildReprojectionMigration-8nVn8Qwb.mjs → buildReprojectionMigration-D0f-sshM.mjs} +1 -1
- package/dist/packem_shared/{buildShapeDiff-umdBNFzJ.mjs → buildShapeDiff-C3sZW3bZ.mjs} +1 -1
- package/dist/packem_shared/{createCompanionSync-zCwaB6wj.mjs → createCompanionSync-Cfju9Ng2.mjs} +1 -1
- package/dist/packem_shared/{createReplicaLink-DZZxDW5c.mjs → createReplicaLink-Bv7250Ef.mjs} +1 -1
- package/dist/packem_shared/ctx-db-companions-BQRTS_WY.mjs +1 -0
- package/dist/packem_shared/{defineEngineContractSuite-C6NKOjJn.mjs → defineEngineContractSuite-CjxJNwwG.mjs} +1 -1
- package/dist/packem_shared/do-sql-DbEszTyj.mjs +1 -0
- package/dist/packem_shared/{isSoftDeleted-CZirzdQL.mjs → isSoftDeleted-D0iaSrDV.mjs} +1 -1
- package/dist/packem_shared/{materializeExternalRows-DYE0rlxi.mjs → materializeExternalRows-CX55UoV7.mjs} +1 -1
- package/dist/packem_shared/runShardMigrations-DFc_LoP-.mjs +5 -0
- package/dist/packem_shared/{selectExpiredIds-_5514W_v.mjs → selectExpiredIds-w4fPtlwT.mjs} +1 -1
- package/dist/packem_shared/{selectShapeMembers-GfRzwoVo.mjs → selectShapeMembers-C0vtU60D.mjs} +1 -1
- package/package.json +1 -1
- package/dist/packem_shared/NotUniqueError-C4DEsHec.mjs +0 -1
- package/dist/packem_shared/ctx-db-companions-lTt-rvKG.mjs +0 -1
- package/dist/packem_shared/do-sql-Dk_DJxn4.mjs +0 -1
- package/dist/packem_shared/runShardMigrations-C6JwX3Ie.mjs +0 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-
|
|
1
|
+
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-CjxJNwwG.mjs";export{t as defineEngineContractSuite};
|
package/dist/index.d.mts
CHANGED
|
@@ -1054,7 +1054,7 @@ declare const AGG_KEY: Name;
|
|
|
1054
1054
|
declare const AGG_VALUE: Name;
|
|
1055
1055
|
declare const AGG_COUNT: Name;
|
|
1056
1056
|
declare const aggUpsertSql: (aggTable: string, key: unknown, value: unknown, count: unknown, set: SQL) => SQL;
|
|
1057
|
-
declare const tableColumns: (definition: TableDefinitionLike) => [string, ColumnMetaLike]
|
|
1057
|
+
declare const tableColumns: (definition: TableDefinitionLike) => ReadonlyArray<readonly [string, ColumnMetaLike]>;
|
|
1058
1058
|
declare const rowToDocument: (row: Record<string, unknown> | undefined) => Record<string, unknown> | undefined;
|
|
1059
1059
|
declare const tryRowToDocument: (row: Record<string, unknown> | undefined) => Record<string, unknown> | undefined;
|
|
1060
1060
|
declare const isFtsAvailable: (sql: SqlExec) => boolean;
|
package/dist/index.d.ts
CHANGED
|
@@ -1054,7 +1054,7 @@ declare const AGG_KEY: Name;
|
|
|
1054
1054
|
declare const AGG_VALUE: Name;
|
|
1055
1055
|
declare const AGG_COUNT: Name;
|
|
1056
1056
|
declare const aggUpsertSql: (aggTable: string, key: unknown, value: unknown, count: unknown, set: SQL) => SQL;
|
|
1057
|
-
declare const tableColumns: (definition: TableDefinitionLike) => [string, ColumnMetaLike]
|
|
1057
|
+
declare const tableColumns: (definition: TableDefinitionLike) => ReadonlyArray<readonly [string, ColumnMetaLike]>;
|
|
1058
1058
|
declare const rowToDocument: (row: Record<string, unknown> | undefined) => Record<string, unknown> | undefined;
|
|
1059
1059
|
declare const tryRowToDocument: (row: Record<string, unknown> | undefined) => Record<string, unknown> | undefined;
|
|
1060
1060
|
declare const isFtsAvailable: (sql: SqlExec) => boolean;
|
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 s,validateImportRow as i}from"./packem_shared/exportShardRows-Cgt3ITwH.mjs";import{AGGREGATE_SQL_FUNCTION as c,aggregateSqlFunction as p,matchesStaticWhere as d,normalizeCountArgument as S,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as x,coerceAggregateNumber as T,encodeAggregateKey as h,foldAggregateTally as E,readAggregateValue as C}from"./packem_shared/aggregateTableName-Cy5e03oz.mjs";import{CountRlsUnsupportedError as A,mergeWhere as g,planAggregateLookup as _,selectIndexForAggregate as I,selectIndexForCount as b,selectIndexForGroupBy as L}from"./packem_shared/CountRlsUnsupportedError-Bdfupt3g.mjs";import{AUDIT_LOG_TABLE as P,appendAuditEntry as D,ensureAuditTable as y,readAuditLog as N}from"./packem_shared/AUDIT_LOG_TABLE-uNVU9O1W.mjs";import{NotUniqueError as F,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-C4DEsHec.mjs";import{backfillAggregateIndexes as q,backfillRankIndexes as w,backfillSearchIndexes as K,backfillSearchIndexesForTable as v}from"./packem_shared/backfillAggregateIndexes-DDgDYJcc.mjs";import{CDC_LOG_TABLE as H,CDC_LOG_TABLE_SEQ_INDEX as X,CDC_META_TABLE as z,appendCdcChange as V,applyCdcChanges as Q,bumpCdcEpoch as j,cdcCanVouchFor as Y,cdcSeqLeavingRows as J,cdcTouchesTables as Z,cdcTrimmedError as $,compactCdcDocs as ee,cursorBelowRetainedFloor as re,migrateCdcLog as oe,migrateCdcMeta as ae,minCdcReplayableSeq as te,minCdcSeq as ne,readCdcChangeKeys as le,readCdcChanges as se,readCdcCursor as ie,readCdcEpoch as me,trimCdcChanges as ce}from"./packem_shared/CDC_LOG_TABLE-VfPoURHu.mjs";import{CLIENT_WATERMARK_TABLE as de,advanceClientWatermark as Se,migrateClientWatermark as ue,readClientWatermark as fe}from"./packem_shared/CLIENT_WATERMARK_TABLE-BoS1HEqz.mjs";import{COMMIT_SEQ_FIELD as Te,COMMIT_SEQ_TABLE as he,allocateCommitSeq as Ee,migrateCommitSeq as Ce,readCommitSeq as Re}from"./packem_shared/COMMIT_SEQ_FIELD-CSe_oNZu.mjs";import{c as ge}from"./packem_shared/ctx-db-companions-lTt-rvKG.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Ie,deleteGlobalShapeSnapshot as be,deleteGlobalShapeSnapshotsForConnection as Le,migrateGlobalShapeSnapshot as Me,readGlobalShapeSnapshot as Pe,writeGlobalShapeSnapshot as De}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-NWaL77m5.mjs";import{IDEMPOTENCY_TABLE as Ne,migrateIdempotency as Oe,readIdempotent as Fe,trimIdempotent as ke,writeIdempotent as Be}from"./packem_shared/IDEMPOTENCY_TABLE-DKVe2Ohf.mjs";import{clearMemoryTables as Ue,isMemoryTable as qe,memoryTableNames as we}from"./packem_shared/clearMemoryTables-CXULwypv.mjs";import{computeRankPage as ve,hydrateDocsById as We}from"./packem_shared/computeRankPage-Bby1Npkd.mjs";import{SEARCH_STATE_TABLE as Xe,migrateSearchState as ze,readSearchBackfillState as Ve,writeSearchBackfillState as Qe}from"./packem_shared/SEARCH_STATE_TABLE-Dju8ebbU.mjs";import{SHAPE_POKE_CURSOR_TABLE as Ye,deleteShapePokeCursor as Je,deleteShapePokeCursorsForConnection as Ze,migrateShapePokeCursor as $e,minShapePokeCursor as er,readShapePokeCursor as rr,writeShapePokeCursor as or}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-BBuXXk5v.mjs";import{selectShapeMembers as tr,selectShapeRows as nr}from"./packem_shared/selectShapeMembers-GfRzwoVo.mjs";import{DATA_MIGRATION_STATE_TABLE as sr,readMigrationStatus as ir,runDataMigration as mr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-4l6aU1Vc.mjs";import{SCAN_DEP as pr,createDependencyTracker as dr,depKey as Sr,tableFromDepKey as ur}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as xr,runSql as Tr}from"./packem_shared/runDrizzle-it6rL9bR.mjs";import{A as Er,a as Cr,b as Rr,D as Ar,c as gr,d as _r,g as Ir,i as br,j as Lr,e as Mr,q as Pr,f as Dr,r as yr,t as Nr,h as Or}from"./packem_shared/do-sql-Dk_DJxn4.mjs";import{param as kr,renderSql as Br,sqliteInList as Gr,unionAll as Ur}from"./packem_shared/param-Ib8WHnrF.mjs";import{appendStreamChunk as wr,claimStreamRun as Kr,deleteStreamRun as vr,finishStreamRun as Wr,migrateDurableStreams as Hr,readStreamChunks as Xr,readStreamRun as zr,trimStreamRuns as Vr}from"./packem_shared/appendStreamChunk-CH4e4nJn.mjs";import{DurableStreamRunner as jr,MAX_DURABLE_STREAM_BYTES as Yr,MAX_DURABLE_STREAM_CHUNKS as Jr,decideDurableAttach as Zr}from"./packem_shared/DurableStreamRunner-DDBi1UXj.mjs";import{envOptionalPositiveInt as eo,envPositiveInt as ro}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as ao}from"./packem_shared/diffExternalSource-DbHrcoZK.mjs";import{liftSourceId as no,normalizeSourceDocument as lo,normalizeSourceValue as so}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as mo,materializeExternalRowsIncremental as co,readExternalSourceBaseline as po,runExternalSourceTick as So}from"./packem_shared/materializeExternalRows-DYE0rlxi.mjs";import{isSoftDeleted as fo,isSourceDue as xo,pullExternalSourceIncrementalTick as To,pullExternalSourceTick as ho}from"./packem_shared/isSoftDeleted-CZirzdQL.mjs";import{GEO_DEFAULT_PRECISION as Co,boundingBoxCenter as Ro,boundingBoxGeohashes as Ao,coveringGeohashes as go,encodeGeohash as _o,haversineMeters as Io,pointInBoundingBox as bo}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as Mo}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as Do,ADMIN_FUNCTION_PREFIX as yo,DEFAULT_FANOUT_TOPIC_LIMIT as No,FLAGS_FUNCTION_PREFIX as Oo,MAX_PAGE_SIZE as Fo,RELATION_FUNCTION_PREFIX as ko,createFanoutCounters as Bo,createGlobalPollCounters as Go,createShapeProbeCounters as Uo,facetColumn as qo,findStorageReferences as wo,listTables as Ko,readTablePage as vo,recordFanoutPass as Wo,recordGlobalPollPass as Ho,recordShapeProbePass as Xo,selectMatchingIds as zo,summarizeFanoutTopics as Vo,summarizeSubscriptions as Qo}from"./packem_shared/ADMIN_FUNCTIONS-DZ5yKTXx.mjs";import{MAIL_RETENTION as Yo,MAIL_TABLE as Jo,clearCapturedMail as Zo,ensureMailTable as $o,readCapturedMail as ea,recordCapturedMail as ra}from"./packem_shared/MAIL_RETENTION-Cig9Dmc8.mjs";import{NotFoundError as aa}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as na,readBookmark as la}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{applySelect as ia,buildSeekBeforeWhere as ma,buildSeekWhere as ca,decodeCursor as pa,encodeCursor as da,normalizeOrderKeys as Sa,softDeleteScope as ua}from"./packem_shared/applySelect-BQbHyo-W.mjs";import{QUEUE_TABLE as xa,clearQueueMessages as Ta,isLossyBody as ha,readQueueMessageById as Ea,readQueueMessages as Ca,recordQueueMessages as Ra}from"./packem_shared/QUEUE_TABLE-zj9Tt6tk.mjs";import{RANK_TIEBREAK as ga,encodePartitionKey as _a,matchesRankStaticWhere as Ia,rankKeyFromDoc as ba,rankTableName as La,resolveRankPartition as Ma,sortColumnName as Pa}from"./packem_shared/RANK_TIEBREAK-ci3MaM65.mjs";import{ReactiveCache as ya,reactiveCacheKey as Na}from"./packem_shared/ReactiveCache-DlJ38txF.mjs";import{REACTOR_STATE_TABLE as Fa,listReactorStates as ka,migrateReactorState as Ba,reactorNeedsRun as Ga,readReactorState as Ua,writeReactorState as qa}from"./packem_shared/REACTOR_STATE_TABLE-Cr9Orfp8.mjs";import{UNVOUCHABLE_DEP as Ka,createReadFootprint as va,markUnvouchableReads as Wa}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as Xa,indexKeysForRow as za,keysTouchRanges as Va}from"./packem_shared/buildIndexRange-CBKQmHSS.mjs";import{DEFAULT_MAX_RELATION_KEYS as ja,assertFlatPredicate as Ya,assertShapeShardable as Ja,containsRelationPredicate as Za,isRelationPredicate as $a,resolveRelationPredicates as et}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-BAWGIEvC.mjs";import{applyOnDelete as ot,distinctValues as at,fanOutScalarCounts as tt,relationHooks as nt,resolveWith as lt,runRowValidators as st}from"./packem_shared/applyOnDelete-BlcwKjuO.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as mt,clampPromotionThresholds as ct,nextPromotionState as pt,relayCountFor as dt,shapeRoutingKey as St}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-H2sHFvlw.mjs";import{DEFAULT_MAX_RELAYS as ft,OwnerRelay as xt,RelayMember as Tt,createRelayLink as ht}from"./packem_shared/DEFAULT_MAX_RELAYS-BPv7jVgK.mjs";import{createReplicaLink as Ct,gateReplicaDispatch as Rt,handleReplicaControl as At}from"./packem_shared/createReplicaLink-DZZxDW5c.mjs";import{buildReprojectionMigration as _t,countLegacyRows as It,reprojectableFields as bt,reprojectionTables as Lt}from"./packem_shared/buildReprojectionMigration-8nVn8Qwb.mjs";import{RLS_UNWRAP_SYMBOL as Pt,RlsRequiredError as Dt,guardWriter as yt}from"./packem_shared/RLS_UNWRAP_SYMBOL-BWloGsd3.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ot,readSchemaHistory as Ft,readSchemaVersion as kt,recordSchemaVersion as Bt}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-DsycDXWm.mjs";import{serializeSqlValue as Ut}from"./packem_shared/serializeSqlValue-DbI1VQYM.mjs";import{buildSettings as wt,isDevEnvironment as Kt}from"./packem_shared/buildSettings-B4igo4rJ.mjs";import{buildShapeDiff as Wt}from"./packem_shared/buildShapeDiff-umdBNFzJ.mjs";import{ShapeDiffCache as Xt,createShapeDiffCache as zt,globalShapeReadKey as Vt}from"./packem_shared/ShapeDiffCache-mE7ZzdPr.mjs";import{buildPokeFrames as jt,diffGlobalMembership as Yt,encodeRowsPatch as Jt,projectColumns as Zt}from"./packem_shared/buildPokeFrames-BhYUbqzO.mjs";import{ShardRunner as en}from"./packem_shared/ShardRunner-C9p5DVOx.mjs";import{runSocketPool as on}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as tn,assertReadonly as nn,lintReadonlySql as ln,runReadonlySql as sn}from"./packem_shared/MAX_SQL_ROWS-gsiUV0Eo.mjs";import{awaitWsDrain as cn,subscriptionFrames as pn,subscriptionListDeltas as dn,trySendFrame as Sn}from"./packem_shared/awaitWsDrain-CeaR5jj8.mjs";import{mergeChangedKeys as fn,recordChangedKeys as xn,writeTouchesMemo as Tn}from"./packem_shared/mergeChangedKeys-D1T-TPUb.mjs";import{createSystemReader as En}from"./packem_shared/createSystemReader-BtYeSMDb.mjs";import{ConflictError as Rn}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as gn,TransactionHeadroomTracker as _n}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-Bcoi7Bvf.mjs";import{hasTrigger as bn,runTriggers as Ln}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as Pn}from"./packem_shared/selectExpiredIds-_5514W_v.mjs";import{compileWhereSql as yn,literalInList as Nn}from"./packem_shared/compileWhereSql-JBpSfQm9.mjs";import{RELATION_EXISTS_KEY as Fn}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as Bn,reprojectionMigrationId as Gn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{quoteIdentifier as qn}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Kn}from"./packem_shared/runShardMigrations-C6JwX3Ie.mjs";import{stableStringify as Wn}from"./packem_shared/stableStringify-G9OF5wcs.mjs";import{stableWireKey as Xn}from"./packem_shared/stableWireKey-DSCJB6E7.mjs";export{Do as ADMIN_FUNCTIONS,yo as ADMIN_FUNCTION_PREFIX,c as AGGREGATE_SQL_FUNCTION,Er as AGG_COUNT,Cr as AGG_KEY,Rr as AGG_VALUE,P as AUDIT_LOG_TABLE,H as CDC_LOG_TABLE,X as CDC_LOG_TABLE_SEQ_INDEX,z as CDC_META_TABLE,de as CLIENT_WATERMARK_TABLE,Te as COMMIT_SEQ_FIELD,he as COMMIT_SEQ_TABLE,Rn as ConflictError,A as CountRlsUnsupportedError,sr as DATA_MIGRATION_STATE_TABLE,No as DEFAULT_FANOUT_TOPIC_LIMIT,ja as DEFAULT_MAX_RELATION_KEYS,ft as DEFAULT_MAX_RELAYS,mt as DEFAULT_PROMOTION_THRESHOLDS,gn as DEFAULT_TRANSACTION_LIMITS,Ar as DOC_COLUMN,jr as DurableStreamRunner,Oo as FLAGS_FUNCTION_PREFIX,Co as GEO_DEFAULT_PRECISION,Ie as GLOBAL_SHAPE_SNAPSHOT_TABLE,Mo as GlobalPollTick,Ne as IDEMPOTENCY_TABLE,Yo as MAIL_RETENTION,Jo as MAIL_TABLE,Yr as MAX_DURABLE_STREAM_BYTES,Jr as MAX_DURABLE_STREAM_CHUNKS,Fo as MAX_PAGE_SIZE,tn as MAX_SQL_ROWS,aa as NotFoundError,F as NotUniqueError,xt as OwnerRelay,xa as QUEUE_TABLE,ga as RANK_TIEBREAK,Fa as REACTOR_STATE_TABLE,Fn as RELATION_EXISTS_KEY,ko as RELATION_FUNCTION_PREFIX,Bn as REPROJECTION_MIGRATION_PREFIX,Pt as RLS_UNWRAP_SYMBOL,ya as ReactiveCache,Tt as RelayMember,Dt as RlsRequiredError,pr as SCAN_DEP,Ot as SCHEMA_HISTORY_MAX_VERSIONS,Xe as SEARCH_STATE_TABLE,Ye as SHAPE_POKE_CURSOR_TABLE,Xt as ShapeDiffCache,en as ShardRunner,_n as TransactionHeadroomTracker,Ka as UNVOUCHABLE_DEP,Se as advanceClientWatermark,gr as aggUpsertSql,p as aggregateSqlFunction,x as aggregateTableName,Ee as allocateCommitSeq,D as appendAuditEntry,V as appendCdcChange,wr as appendStreamChunk,Q as applyCdcChanges,ot as applyOnDelete,ia as applySelect,na as armRestore,Ya as assertFlatPredicate,nn as assertReadonly,Ja as assertShapeShardable,k as assertValidClientId,cn as awaitWsDrain,q as backfillAggregateIndexes,w as backfillRankIndexes,K as backfillSearchIndexes,v as backfillSearchIndexesForTable,Ro as boundingBoxCenter,Ao as boundingBoxGeohashes,Xa as buildIndexRange,jt as buildPokeFrames,_t as buildReprojectionMigration,ma as buildSeekBeforeWhere,ca as buildSeekWhere,wt as buildSettings,Wt as buildShapeDiff,j as bumpCdcEpoch,Y as cdcCanVouchFor,J as cdcSeqLeavingRows,Z as cdcTouchesTables,$ as cdcTrimmedError,Kr as claimStreamRun,ct as clampPromotionThresholds,Zo as clearCapturedMail,Ue as clearMemoryTables,Ta as clearQueueMessages,T as coerceAggregateNumber,ee as compactCdcDocs,yn as compileWhereSql,ve as computeRankPage,Za as containsRelationPredicate,It as countLegacyRows,go as coveringGeohashes,ge as createCompanionSync,dr as createDependencyTracker,Bo as createFanoutCounters,Go as createGlobalPollCounters,_r as createIndexSql,va as createReadFootprint,ht as createRelayLink,Ct as createReplicaLink,zt as createShapeDiffCache,Uo as createShapeProbeCounters,B as createShardCtxDb,En as createSystemReader,re as cursorBelowRetainedFloor,Zr as decideDurableAttach,pa as decodeCursor,be as deleteGlobalShapeSnapshot,Le as deleteGlobalShapeSnapshotsForConnection,Je as deleteShapePokeCursor,Ze as deleteShapePokeCursorsForConnection,vr as deleteStreamRun,Sr as depKey,ao as diffExternalSource,Yt as diffGlobalMembership,at as distinctValues,h as encodeAggregateKey,da as encodeCursor,_o as encodeGeohash,_a as encodePartitionKey,Jt as encodeRowsPatch,y as ensureAuditTable,$o as ensureMailTable,eo as envOptionalPositiveInt,ro as envPositiveInt,o as exportShardRows,a as exportShardTable,qo as facetColumn,tt as fanOutScalarCounts,wo as findStorageReferences,Wr as finishStreamRun,E as foldAggregateTally,Rt as gateReplicaDispatch,Ir as geoTableName,Vt as globalShapeReadKey,yt as guardWriter,At as handleReplicaControl,bn as hasTrigger,Io as haversineMeters,We as hydrateDocsById,t as importShardRows,za as indexKeysForRow,Kt as isDevEnvironment,br as isFtsAvailable,ha as isLossyBody,qe as isMemoryTable,$a as isRelationPredicate,fo as isSoftDeleted,xo as isSourceDue,Lr as jsonPath,Mr as jsonPathSql,Va as keysTouchRanges,no as liftSourceId,ln as lintReadonlySql,ka as listReactorStates,Ko as listTables,Nn as literalInList,Wa as markUnvouchableReads,Ia as matchesRankStaticWhere,d as matchesStaticWhere,mo as materializeExternalRows,co as materializeExternalRowsIncremental,we as memoryTableNames,fn as mergeChangedKeys,g as mergeWhere,oe as migrateCdcLog,ae as migrateCdcMeta,ue as migrateClientWatermark,Ce as migrateCommitSeq,Hr as migrateDurableStreams,Me as migrateGlobalShapeSnapshot,Oe as migrateIdempotency,Ba as migrateReactorState,ze as migrateSearchState,$e as migrateShapePokeCursor,te as minCdcReplayableSeq,ne as minCdcSeq,er as minShapePokeCursor,pt as nextPromotionState,S as normalizeCountArgument,G as normalizeIdStructurally,Sa as normalizeOrderKeys,lo as normalizeSourceDocument,so as normalizeSourceValue,kr as param,n as parseExportShardArgs,l as parseImportShardArgs,_ as planAggregateLookup,bo as pointInBoundingBox,Zt as projectColumns,To as pullExternalSourceIncrementalTick,ho as pullExternalSourceTick,Pr as qualifiedJsonPath,Dr as qualifiedJsonPathSql,qn as quoteIdentifier,ba as rankKeyFromDoc,La as rankTableName,Na as reactiveCacheKey,Ga as reactorNeedsRun,C as readAggregateValue,N as readAuditLog,la as readBookmark,ea as readCapturedMail,le as readCdcChangeKeys,se as readCdcChanges,ie as readCdcCursor,me as readCdcEpoch,fe as readClientWatermark,Re as readCommitSeq,po as readExternalSourceBaseline,Pe as readGlobalShapeSnapshot,Fe as readIdempotent,ir as readMigrationStatus,Ea as readQueueMessageById,Ca as readQueueMessages,Ua as readReactorState,Ft as readSchemaHistory,kt as readSchemaVersion,Ve as readSearchBackfillState,rr as readShapePokeCursor,Xr as readStreamChunks,zr as readStreamRun,vo as readTablePage,ra as recordCapturedMail,xn as recordChangedKeys,Wo as recordFanoutPass,Ho as recordGlobalPollPass,Ra as recordQueueMessages,Bt as recordSchemaVersion,Xo as recordShapeProbePass,nt as relationHooks,dt as relayCountFor,Br as renderSql,bt as reprojectableFields,Gn as reprojectionMigrationId,Lt as reprojectionTables,Ma as resolveRankPartition,et as resolveRelationPredicates,lt as resolveWith,yr as rowToDocument,mr as runDataMigration,xr as runDrizzle,So as runExternalSourceTick,sn as runReadonlySql,st as runRowValidators,Kn as runShardMigrations,on as runSocketPool,Tr as runSql,Ln as runTriggers,Pn as selectExpiredIds,s as selectExportTables,I as selectIndexForAggregate,b as selectIndexForCount,L as selectIndexForGroupBy,zo as selectMatchingIds,tr as selectShapeMembers,nr as selectShapeRows,Ut as serializeSqlValue,St as shapeRoutingKey,ua as softDeleteScope,Pa as sortColumnName,Gr as sqliteInList,Wn as stableStringify,Xn as stableWireKey,pn as subscriptionFrames,dn as subscriptionListDeltas,Vo as summarizeFanoutTopics,Qo as summarizeSubscriptions,Nr as tableColumns,ur as tableFromDepKey,u as throwingScheduler,ce as trimCdcChanges,ke as trimIdempotent,Vr as trimStreamRuns,Or as tryRowToDocument,Sn as trySendFrame,Ur as unionAll,i as validateImportRow,De as writeGlobalShapeSnapshot,Be as writeIdempotent,qa as writeReactorState,Qe as writeSearchBackfillState,or as writeShapePokeCursor,Tn as writeTouchesMemo};
|
|
1
|
+
import{exportShardRows as o,exportShardTable as a,importShardRows as t,parseExportShardArgs as n,parseImportShardArgs as l,selectExportTables as s,validateImportRow as i}from"./packem_shared/exportShardRows-Cgt3ITwH.mjs";import{AGGREGATE_SQL_FUNCTION as c,aggregateSqlFunction as p,matchesStaticWhere as d,normalizeCountArgument as S,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as x,coerceAggregateNumber as T,encodeAggregateKey as h,foldAggregateTally as E,readAggregateValue as C}from"./packem_shared/aggregateTableName-Cy5e03oz.mjs";import{CountRlsUnsupportedError as A,mergeWhere as g,planAggregateLookup as _,selectIndexForAggregate as I,selectIndexForCount as b,selectIndexForGroupBy as L}from"./packem_shared/CountRlsUnsupportedError-Bdfupt3g.mjs";import{AUDIT_LOG_TABLE as P,appendAuditEntry as D,ensureAuditTable as y,readAuditLog as N}from"./packem_shared/AUDIT_LOG_TABLE-uNVU9O1W.mjs";import{NotUniqueError as F,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-Dnik6z41.mjs";import{backfillAggregateIndexes as q,backfillRankIndexes as w,backfillSearchIndexes as K,backfillSearchIndexesForTable as v}from"./packem_shared/backfillAggregateIndexes-C9wGiPH4.mjs";import{CDC_LOG_TABLE as H,CDC_LOG_TABLE_SEQ_INDEX as X,CDC_META_TABLE as z,appendCdcChange as V,applyCdcChanges as Q,bumpCdcEpoch as j,cdcCanVouchFor as Y,cdcSeqLeavingRows as J,cdcTouchesTables as Z,cdcTrimmedError as $,compactCdcDocs as ee,cursorBelowRetainedFloor as re,migrateCdcLog as oe,migrateCdcMeta as ae,minCdcReplayableSeq as te,minCdcSeq as ne,readCdcChangeKeys as le,readCdcChanges as se,readCdcCursor as ie,readCdcEpoch as me,trimCdcChanges as ce}from"./packem_shared/CDC_LOG_TABLE-CW0wHEgW.mjs";import{CLIENT_WATERMARK_TABLE as de,advanceClientWatermark as Se,migrateClientWatermark as ue,readClientWatermark as fe}from"./packem_shared/CLIENT_WATERMARK_TABLE-BoS1HEqz.mjs";import{COMMIT_SEQ_FIELD as Te,COMMIT_SEQ_TABLE as he,allocateCommitSeq as Ee,migrateCommitSeq as Ce,readCommitSeq as Re}from"./packem_shared/COMMIT_SEQ_FIELD-CSe_oNZu.mjs";import{c as ge}from"./packem_shared/ctx-db-companions-BQRTS_WY.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Ie,deleteGlobalShapeSnapshot as be,deleteGlobalShapeSnapshotsForConnection as Le,migrateGlobalShapeSnapshot as Me,readGlobalShapeSnapshot as Pe,writeGlobalShapeSnapshot as De}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-NWaL77m5.mjs";import{IDEMPOTENCY_TABLE as Ne,migrateIdempotency as Oe,readIdempotent as Fe,trimIdempotent as ke,writeIdempotent as Be}from"./packem_shared/IDEMPOTENCY_TABLE-DKVe2Ohf.mjs";import{clearMemoryTables as Ue,isMemoryTable as qe,memoryTableNames as we}from"./packem_shared/clearMemoryTables-CXULwypv.mjs";import{computeRankPage as ve,hydrateDocsById as We}from"./packem_shared/computeRankPage-Bby1Npkd.mjs";import{SEARCH_STATE_TABLE as Xe,migrateSearchState as ze,readSearchBackfillState as Ve,writeSearchBackfillState as Qe}from"./packem_shared/SEARCH_STATE_TABLE-Dju8ebbU.mjs";import{SHAPE_POKE_CURSOR_TABLE as Ye,deleteShapePokeCursor as Je,deleteShapePokeCursorsForConnection as Ze,migrateShapePokeCursor as $e,minShapePokeCursor as er,readShapePokeCursor as rr,writeShapePokeCursor as or}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-BBuXXk5v.mjs";import{selectShapeMembers as tr,selectShapeRows as nr}from"./packem_shared/selectShapeMembers-C0vtU60D.mjs";import{DATA_MIGRATION_STATE_TABLE as sr,readMigrationStatus as ir,runDataMigration as mr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-4l6aU1Vc.mjs";import{SCAN_DEP as pr,createDependencyTracker as dr,depKey as Sr,tableFromDepKey as ur}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as xr,runSql as Tr}from"./packem_shared/runDrizzle-it6rL9bR.mjs";import{A as Er,a as Cr,b as Rr,D as Ar,c as gr,d as _r,g as Ir,i as br,j as Lr,e as Mr,q as Pr,f as Dr,r as yr,t as Nr,h as Or}from"./packem_shared/do-sql-DbEszTyj.mjs";import{param as kr,renderSql as Br,sqliteInList as Gr,unionAll as Ur}from"./packem_shared/param-Ib8WHnrF.mjs";import{appendStreamChunk as wr,claimStreamRun as Kr,deleteStreamRun as vr,finishStreamRun as Wr,migrateDurableStreams as Hr,readStreamChunks as Xr,readStreamRun as zr,trimStreamRuns as Vr}from"./packem_shared/appendStreamChunk-CH4e4nJn.mjs";import{DurableStreamRunner as jr,MAX_DURABLE_STREAM_BYTES as Yr,MAX_DURABLE_STREAM_CHUNKS as Jr,decideDurableAttach as Zr}from"./packem_shared/DurableStreamRunner-DDBi1UXj.mjs";import{envOptionalPositiveInt as eo,envPositiveInt as ro}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as ao}from"./packem_shared/diffExternalSource-DbHrcoZK.mjs";import{liftSourceId as no,normalizeSourceDocument as lo,normalizeSourceValue as so}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as mo,materializeExternalRowsIncremental as co,readExternalSourceBaseline as po,runExternalSourceTick as So}from"./packem_shared/materializeExternalRows-CX55UoV7.mjs";import{isSoftDeleted as fo,isSourceDue as xo,pullExternalSourceIncrementalTick as To,pullExternalSourceTick as ho}from"./packem_shared/isSoftDeleted-D0iaSrDV.mjs";import{GEO_DEFAULT_PRECISION as Co,boundingBoxCenter as Ro,boundingBoxGeohashes as Ao,coveringGeohashes as go,encodeGeohash as _o,haversineMeters as Io,pointInBoundingBox as bo}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as Mo}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as Do,ADMIN_FUNCTION_PREFIX as yo,DEFAULT_FANOUT_TOPIC_LIMIT as No,FLAGS_FUNCTION_PREFIX as Oo,MAX_PAGE_SIZE as Fo,RELATION_FUNCTION_PREFIX as ko,createFanoutCounters as Bo,createGlobalPollCounters as Go,createShapeProbeCounters as Uo,facetColumn as qo,findStorageReferences as wo,listTables as Ko,readTablePage as vo,recordFanoutPass as Wo,recordGlobalPollPass as Ho,recordShapeProbePass as Xo,selectMatchingIds as zo,summarizeFanoutTopics as Vo,summarizeSubscriptions as Qo}from"./packem_shared/ADMIN_FUNCTIONS-DcSYybsq.mjs";import{MAIL_RETENTION as Yo,MAIL_TABLE as Jo,clearCapturedMail as Zo,ensureMailTable as $o,readCapturedMail as ea,recordCapturedMail as ra}from"./packem_shared/MAIL_RETENTION-Cig9Dmc8.mjs";import{NotFoundError as aa}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as na,readBookmark as la}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{applySelect as ia,buildSeekBeforeWhere as ma,buildSeekWhere as ca,decodeCursor as pa,encodeCursor as da,normalizeOrderKeys as Sa,softDeleteScope as ua}from"./packem_shared/applySelect-BQbHyo-W.mjs";import{QUEUE_TABLE as xa,clearQueueMessages as Ta,isLossyBody as ha,readQueueMessageById as Ea,readQueueMessages as Ca,recordQueueMessages as Ra}from"./packem_shared/QUEUE_TABLE-zj9Tt6tk.mjs";import{RANK_TIEBREAK as ga,encodePartitionKey as _a,matchesRankStaticWhere as Ia,rankKeyFromDoc as ba,rankTableName as La,resolveRankPartition as Ma,sortColumnName as Pa}from"./packem_shared/RANK_TIEBREAK-ci3MaM65.mjs";import{ReactiveCache as ya,reactiveCacheKey as Na}from"./packem_shared/ReactiveCache-DlJ38txF.mjs";import{REACTOR_STATE_TABLE as Fa,listReactorStates as ka,migrateReactorState as Ba,reactorNeedsRun as Ga,readReactorState as Ua,writeReactorState as qa}from"./packem_shared/REACTOR_STATE_TABLE-Cr9Orfp8.mjs";import{UNVOUCHABLE_DEP as Ka,createReadFootprint as va,markUnvouchableReads as Wa}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as Xa,indexKeysForRow as za,keysTouchRanges as Va}from"./packem_shared/buildIndexRange-CBKQmHSS.mjs";import{DEFAULT_MAX_RELATION_KEYS as ja,assertFlatPredicate as Ya,assertShapeShardable as Ja,containsRelationPredicate as Za,isRelationPredicate as $a,resolveRelationPredicates as et}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-BAWGIEvC.mjs";import{applyOnDelete as ot,distinctValues as at,fanOutScalarCounts as tt,relationHooks as nt,resolveWith as lt,runRowValidators as st}from"./packem_shared/applyOnDelete-BlcwKjuO.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as mt,clampPromotionThresholds as ct,nextPromotionState as pt,relayCountFor as dt,shapeRoutingKey as St}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-H2sHFvlw.mjs";import{DEFAULT_MAX_RELAYS as ft,OwnerRelay as xt,RelayMember as Tt,createRelayLink as ht}from"./packem_shared/DEFAULT_MAX_RELAYS-BPv7jVgK.mjs";import{createReplicaLink as Ct,gateReplicaDispatch as Rt,handleReplicaControl as At}from"./packem_shared/createReplicaLink-Bv7250Ef.mjs";import{buildReprojectionMigration as _t,countLegacyRows as It,reprojectableFields as bt,reprojectionTables as Lt}from"./packem_shared/buildReprojectionMigration-D0f-sshM.mjs";import{RLS_UNWRAP_SYMBOL as Pt,RlsRequiredError as Dt,guardWriter as yt}from"./packem_shared/RLS_UNWRAP_SYMBOL-BWloGsd3.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ot,readSchemaHistory as Ft,readSchemaVersion as kt,recordSchemaVersion as Bt}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-DsycDXWm.mjs";import{serializeSqlValue as Ut}from"./packem_shared/serializeSqlValue-DbI1VQYM.mjs";import{buildSettings as wt,isDevEnvironment as Kt}from"./packem_shared/buildSettings-B4igo4rJ.mjs";import{buildShapeDiff as Wt}from"./packem_shared/buildShapeDiff-C3sZW3bZ.mjs";import{ShapeDiffCache as Xt,createShapeDiffCache as zt,globalShapeReadKey as Vt}from"./packem_shared/ShapeDiffCache-mE7ZzdPr.mjs";import{buildPokeFrames as jt,diffGlobalMembership as Yt,encodeRowsPatch as Jt,projectColumns as Zt}from"./packem_shared/buildPokeFrames-BhYUbqzO.mjs";import{ShardRunner as en}from"./packem_shared/ShardRunner-C9p5DVOx.mjs";import{runSocketPool as on}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as tn,assertReadonly as nn,lintReadonlySql as ln,runReadonlySql as sn}from"./packem_shared/MAX_SQL_ROWS-gsiUV0Eo.mjs";import{awaitWsDrain as cn,subscriptionFrames as pn,subscriptionListDeltas as dn,trySendFrame as Sn}from"./packem_shared/awaitWsDrain-CeaR5jj8.mjs";import{mergeChangedKeys as fn,recordChangedKeys as xn,writeTouchesMemo as Tn}from"./packem_shared/mergeChangedKeys-D1T-TPUb.mjs";import{createSystemReader as En}from"./packem_shared/createSystemReader-BtYeSMDb.mjs";import{ConflictError as Rn}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as gn,TransactionHeadroomTracker as _n}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-Bcoi7Bvf.mjs";import{hasTrigger as bn,runTriggers as Ln}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as Pn}from"./packem_shared/selectExpiredIds-w4fPtlwT.mjs";import{compileWhereSql as yn,literalInList as Nn}from"./packem_shared/compileWhereSql-JBpSfQm9.mjs";import{RELATION_EXISTS_KEY as Fn}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as Bn,reprojectionMigrationId as Gn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{quoteIdentifier as qn}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Kn}from"./packem_shared/runShardMigrations-DFc_LoP-.mjs";import{stableStringify as Wn}from"./packem_shared/stableStringify-G9OF5wcs.mjs";import{stableWireKey as Xn}from"./packem_shared/stableWireKey-DSCJB6E7.mjs";export{Do as ADMIN_FUNCTIONS,yo as ADMIN_FUNCTION_PREFIX,c as AGGREGATE_SQL_FUNCTION,Er as AGG_COUNT,Cr as AGG_KEY,Rr as AGG_VALUE,P as AUDIT_LOG_TABLE,H as CDC_LOG_TABLE,X as CDC_LOG_TABLE_SEQ_INDEX,z as CDC_META_TABLE,de as CLIENT_WATERMARK_TABLE,Te as COMMIT_SEQ_FIELD,he as COMMIT_SEQ_TABLE,Rn as ConflictError,A as CountRlsUnsupportedError,sr as DATA_MIGRATION_STATE_TABLE,No as DEFAULT_FANOUT_TOPIC_LIMIT,ja as DEFAULT_MAX_RELATION_KEYS,ft as DEFAULT_MAX_RELAYS,mt as DEFAULT_PROMOTION_THRESHOLDS,gn as DEFAULT_TRANSACTION_LIMITS,Ar as DOC_COLUMN,jr as DurableStreamRunner,Oo as FLAGS_FUNCTION_PREFIX,Co as GEO_DEFAULT_PRECISION,Ie as GLOBAL_SHAPE_SNAPSHOT_TABLE,Mo as GlobalPollTick,Ne as IDEMPOTENCY_TABLE,Yo as MAIL_RETENTION,Jo as MAIL_TABLE,Yr as MAX_DURABLE_STREAM_BYTES,Jr as MAX_DURABLE_STREAM_CHUNKS,Fo as MAX_PAGE_SIZE,tn as MAX_SQL_ROWS,aa as NotFoundError,F as NotUniqueError,xt as OwnerRelay,xa as QUEUE_TABLE,ga as RANK_TIEBREAK,Fa as REACTOR_STATE_TABLE,Fn as RELATION_EXISTS_KEY,ko as RELATION_FUNCTION_PREFIX,Bn as REPROJECTION_MIGRATION_PREFIX,Pt as RLS_UNWRAP_SYMBOL,ya as ReactiveCache,Tt as RelayMember,Dt as RlsRequiredError,pr as SCAN_DEP,Ot as SCHEMA_HISTORY_MAX_VERSIONS,Xe as SEARCH_STATE_TABLE,Ye as SHAPE_POKE_CURSOR_TABLE,Xt as ShapeDiffCache,en as ShardRunner,_n as TransactionHeadroomTracker,Ka as UNVOUCHABLE_DEP,Se as advanceClientWatermark,gr as aggUpsertSql,p as aggregateSqlFunction,x as aggregateTableName,Ee as allocateCommitSeq,D as appendAuditEntry,V as appendCdcChange,wr as appendStreamChunk,Q as applyCdcChanges,ot as applyOnDelete,ia as applySelect,na as armRestore,Ya as assertFlatPredicate,nn as assertReadonly,Ja as assertShapeShardable,k as assertValidClientId,cn as awaitWsDrain,q as backfillAggregateIndexes,w as backfillRankIndexes,K as backfillSearchIndexes,v as backfillSearchIndexesForTable,Ro as boundingBoxCenter,Ao as boundingBoxGeohashes,Xa as buildIndexRange,jt as buildPokeFrames,_t as buildReprojectionMigration,ma as buildSeekBeforeWhere,ca as buildSeekWhere,wt as buildSettings,Wt as buildShapeDiff,j as bumpCdcEpoch,Y as cdcCanVouchFor,J as cdcSeqLeavingRows,Z as cdcTouchesTables,$ as cdcTrimmedError,Kr as claimStreamRun,ct as clampPromotionThresholds,Zo as clearCapturedMail,Ue as clearMemoryTables,Ta as clearQueueMessages,T as coerceAggregateNumber,ee as compactCdcDocs,yn as compileWhereSql,ve as computeRankPage,Za as containsRelationPredicate,It as countLegacyRows,go as coveringGeohashes,ge as createCompanionSync,dr as createDependencyTracker,Bo as createFanoutCounters,Go as createGlobalPollCounters,_r as createIndexSql,va as createReadFootprint,ht as createRelayLink,Ct as createReplicaLink,zt as createShapeDiffCache,Uo as createShapeProbeCounters,B as createShardCtxDb,En as createSystemReader,re as cursorBelowRetainedFloor,Zr as decideDurableAttach,pa as decodeCursor,be as deleteGlobalShapeSnapshot,Le as deleteGlobalShapeSnapshotsForConnection,Je as deleteShapePokeCursor,Ze as deleteShapePokeCursorsForConnection,vr as deleteStreamRun,Sr as depKey,ao as diffExternalSource,Yt as diffGlobalMembership,at as distinctValues,h as encodeAggregateKey,da as encodeCursor,_o as encodeGeohash,_a as encodePartitionKey,Jt as encodeRowsPatch,y as ensureAuditTable,$o as ensureMailTable,eo as envOptionalPositiveInt,ro as envPositiveInt,o as exportShardRows,a as exportShardTable,qo as facetColumn,tt as fanOutScalarCounts,wo as findStorageReferences,Wr as finishStreamRun,E as foldAggregateTally,Rt as gateReplicaDispatch,Ir as geoTableName,Vt as globalShapeReadKey,yt as guardWriter,At as handleReplicaControl,bn as hasTrigger,Io as haversineMeters,We as hydrateDocsById,t as importShardRows,za as indexKeysForRow,Kt as isDevEnvironment,br as isFtsAvailable,ha as isLossyBody,qe as isMemoryTable,$a as isRelationPredicate,fo as isSoftDeleted,xo as isSourceDue,Lr as jsonPath,Mr as jsonPathSql,Va as keysTouchRanges,no as liftSourceId,ln as lintReadonlySql,ka as listReactorStates,Ko as listTables,Nn as literalInList,Wa as markUnvouchableReads,Ia as matchesRankStaticWhere,d as matchesStaticWhere,mo as materializeExternalRows,co as materializeExternalRowsIncremental,we as memoryTableNames,fn as mergeChangedKeys,g as mergeWhere,oe as migrateCdcLog,ae as migrateCdcMeta,ue as migrateClientWatermark,Ce as migrateCommitSeq,Hr as migrateDurableStreams,Me as migrateGlobalShapeSnapshot,Oe as migrateIdempotency,Ba as migrateReactorState,ze as migrateSearchState,$e as migrateShapePokeCursor,te as minCdcReplayableSeq,ne as minCdcSeq,er as minShapePokeCursor,pt as nextPromotionState,S as normalizeCountArgument,G as normalizeIdStructurally,Sa as normalizeOrderKeys,lo as normalizeSourceDocument,so as normalizeSourceValue,kr as param,n as parseExportShardArgs,l as parseImportShardArgs,_ as planAggregateLookup,bo as pointInBoundingBox,Zt as projectColumns,To as pullExternalSourceIncrementalTick,ho as pullExternalSourceTick,Pr as qualifiedJsonPath,Dr as qualifiedJsonPathSql,qn as quoteIdentifier,ba as rankKeyFromDoc,La as rankTableName,Na as reactiveCacheKey,Ga as reactorNeedsRun,C as readAggregateValue,N as readAuditLog,la as readBookmark,ea as readCapturedMail,le as readCdcChangeKeys,se as readCdcChanges,ie as readCdcCursor,me as readCdcEpoch,fe as readClientWatermark,Re as readCommitSeq,po as readExternalSourceBaseline,Pe as readGlobalShapeSnapshot,Fe as readIdempotent,ir as readMigrationStatus,Ea as readQueueMessageById,Ca as readQueueMessages,Ua as readReactorState,Ft as readSchemaHistory,kt as readSchemaVersion,Ve as readSearchBackfillState,rr as readShapePokeCursor,Xr as readStreamChunks,zr as readStreamRun,vo as readTablePage,ra as recordCapturedMail,xn as recordChangedKeys,Wo as recordFanoutPass,Ho as recordGlobalPollPass,Ra as recordQueueMessages,Bt as recordSchemaVersion,Xo as recordShapeProbePass,nt as relationHooks,dt as relayCountFor,Br as renderSql,bt as reprojectableFields,Gn as reprojectionMigrationId,Lt as reprojectionTables,Ma as resolveRankPartition,et as resolveRelationPredicates,lt as resolveWith,yr as rowToDocument,mr as runDataMigration,xr as runDrizzle,So as runExternalSourceTick,sn as runReadonlySql,st as runRowValidators,Kn as runShardMigrations,on as runSocketPool,Tr as runSql,Ln as runTriggers,Pn as selectExpiredIds,s as selectExportTables,I as selectIndexForAggregate,b as selectIndexForCount,L as selectIndexForGroupBy,zo as selectMatchingIds,tr as selectShapeMembers,nr as selectShapeRows,Ut as serializeSqlValue,St as shapeRoutingKey,ua as softDeleteScope,Pa as sortColumnName,Gr as sqliteInList,Wn as stableStringify,Xn as stableWireKey,pn as subscriptionFrames,dn as subscriptionListDeltas,Vo as summarizeFanoutTopics,Qo as summarizeSubscriptions,Nr as tableColumns,ur as tableFromDepKey,u as throwingScheduler,ce as trimCdcChanges,ke as trimIdempotent,Vr as trimStreamRuns,Or as tryRowToDocument,Sn as trySendFrame,Ur as unionAll,i as validateImportRow,De as writeGlobalShapeSnapshot,Be as writeIdempotent,qa as writeReactorState,Qe as writeSearchBackfillState,or as writeShapePokeCursor,Tn as writeTouchesMemo};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as v}from"@lunora/errors";import{m as $,n as y}from"./do-sql-Dk_DJxn4.mjs";import{quoteIdentifier as d}from"./quoteIdentifier-CObIFRhb.mjs";import{d as L}from"./wire-codec-BU9T2xJ7.mjs";const te="__lunora_admin__:",re="__lunora_relation__:",ne="__lunora_flags__:",se={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backfillSearch:"__lunora_admin__:backfillSearch",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",getAdvisories:"__lunora_admin__:getAdvisories",getAdvisorProcedures:"__lunora_admin__:getAdvisorProcedures",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",listTablesIndexes:"__lunora_admin__:listTablesIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listReactors:"__lunora_admin__:listReactors",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",replayQueueMessage:"__lunora_admin__:replayQueueMessage",resolveIssue:"__lunora_admin__:resolveIssue",rlsPolicies:"__lunora_admin__:rlsPolicies",schemaHistory:"__lunora_admin__:schemaHistory",schemaVersion:"__lunora_admin__:schemaVersion",runAs:"__lunora_admin__:runAs",runMigration:"__lunora_admin__:runMigration",runSql:"__lunora_admin__:runSql",sendQueueMessage:"__lunora_admin__:sendQueueMessage",sendTestMail:"__lunora_admin__:sendTestMail",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},D=50,g=500,U=30,W=200,m="__doc__",O=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},j=e=>{const{[y]:t,...r}=e;return t===void 0?r:t===null||typeof t!="object"||Array.isArray(t)?{[y]:t,...r}:{...r,...L(t)}},Q=(e,t)=>{if(!e.includes(m))return{columns:e,rows:t};const r=[];for(const s of t){const a=s[m],i=typeof a=="string"?O(a):void 0;if(i===void 0)return{columns:e,rows:t};const c=Object.fromEntries(Object.entries(s).filter(([u])=>u!==m));r.push({...c,...j(i)})}const n=e.filter(s=>s!==m),o=[],_=new Set(n);for(const s of r)for(const a of Object.keys(s))_.has(a)||(_.add(a),o.push(a));return{columns:[...n,...o],rows:r}},F=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,I=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),E=(e,t,r)=>Math.min(Math.max(e,t),r),x=(e,t)=>{const r=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(r.c)},oe=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),r=[];for(const{name:n}of t)I(n)||r.push({name:n,rowCount:x(e,d(n))});return r},P=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,C=(e,t)=>{if(I(t)||!P(e,t))throw new v("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},S=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(r=>r.name),q={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},G=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",M=(e,t)=>{const r=t.includes(e),n=t.includes(m);if(!(!r&&!n))return r?{expression:d(e),params:[]}:{expression:`json_extract(${d(m)}, ?)`,params:[`$.${$(e)}`]}},H=(e,t)=>{const r=M(e.column,t);if(r===void 0)return;const{expression:n,params:o}=r;return e.operator==="contains"?{params:[...o,G(e.value)],sql:F(n)}:{params:[...o,e.value],sql:`${n} ${q[e.operator]} ?`}},B=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,X=e=>{const t=B.exec(e.trim());if(t===null)return;const r=Number(t[1]),n=t[2]===void 0?void 0:Number(t[2]),o=t[3]===void 0?void 0:Number(t[3]);if(n!==void 0&&(n<1||n>12)||o!==void 0&&(o<1||o>31)||r<100)return;const _=Date.UTC(r,(n??1)-1,o??1);if(o!==void 0&&new Date(_).getUTCDate()!==o)return;let s;return o!==void 0?s=Date.UTC(r,(n??1)-1,o+1):n===void 0?s=Date.UTC(r+1,0,1):s=Date.UTC(r,n,1),{from:_,to:s}},A=(e,t,r)=>{const n=[],o=[];if(t!==""&&e.length>0){const _=e.map(a=>F(d(a)));o.push(...e.map(()=>t));const s=X(t);if(s!==void 0)for(const a of e)_.push(`(${d(a)} >= ? AND ${d(a)} < ?)`),o.push(s.from,s.to);n.push(`(${_.join(" OR ")})`)}for(const _ of r??[]){const s=H(_,e);s!==void 0&&(n.push(`(${s.sql})`),o.push(...s.params))}return n.length===0?void 0:{parameters:o,where:n.join(" AND ")}},K=(e,t)=>{if(e===void 0)return;const r=M(e.column,t);if(r===void 0)return;const n=e.direction==="desc"?"DESC":"ASC";return{params:r.params,sql:`${r.expression} ${n}`}},ae=(e,t)=>{const{table:r}=t;C(e,r);const n=E(Math.trunc(t.limit??D),1,g),o=Math.max(0,Math.trunc(t.offset??0)),_=d(r),s=S(e,_),a=t.search?.trim()??"",i=b=>{if(t.refs===void 0)return b;const T={};for(const k of b.columns){const w=t.refs[k];w!==void 0&&(T[k]=w)}return Object.keys(T).length>0?{...b,refs:T}:b},c=A(s,a,t.filters),u=K(t.orderBy,s),l=c===void 0?"":` WHERE ${c.where}`,f=u===void 0?"":` ORDER BY ${u.sql}`,p=c?.parameters??[],h=u?.params??[];let R;t.skipCount||(R=c===void 0?x(e,_):Number(e.exec(`SELECT COUNT(*) AS c FROM ${_}${l}`,...p).one().c));const N=e.exec(`SELECT * FROM ${_}${l}${f} LIMIT ? OFFSET ?`,...p,...h,n,o).toArray();return i({...Q(s,N),total:R})},_e=(e,t)=>{const{table:r}=t;C(e,r);const n=E(Math.trunc(t.limit??g),1,g),o=d(r),_=S(e,o),s=t.search?.trim()??"",a=A(_,s,t.filters),i=a===void 0?e.exec(`SELECT id FROM ${o} LIMIT ?`,n+1).toArray():e.exec(`SELECT id FROM ${o} WHERE ${a.where} LIMIT ?`,...a.parameters,n+1).toArray(),c=i.length>n,u=i.slice(0,n).map(l=>l.id);return{hasMore:c,ids:u}},Y=(e,t,r)=>{const n=new Set(r.filter(_=>_!==m));if(!r.includes(m))return n;const o=e.exec(`SELECT ${d(m)} AS doc FROM ${t} LIMIT ?`,g).toArray();for(const{doc:_}of o){const s=typeof _=="string"?O(_):void 0;if(s!==void 0)for(const a of Object.keys(s))n.add(a)}return n},ie=(e,t)=>{const{column:r,table:n}=t;C(e,n);const o=d(n),_=S(e,o);if(!Y(e,o,_).has(r))throw new v("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const s=M(r,_);if(s===void 0)throw new v("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const a=E(Math.trunc(t.limit??U),1,W),i=t.search?.trim()??"",c=A(_,i,t.filters),u=c===void 0?"":` WHERE ${c.where}`,l=c?.parameters??[],f=e.exec(`SELECT ${s.expression} AS value, COUNT(*) AS count FROM ${o}${u} GROUP BY ${s.expression} ORDER BY count DESC LIMIT ?`,...s.params,...l,...s.params,a+1).toArray();return{truncated:f.length>a,values:f.slice(0,a).map(h=>({count:Number(h.count),value:h.value}))}},ce=(e,t,r)=>{const n={},o=r.slice(0,g);for(const s of o)n[s]=[];if(o.length===0)return{references:n,storageColumns:t};const _=o.map(()=>"?").join(", ");for(const[s,a]of Object.entries(t)){if(I(s)||!P(e,s))continue;const i=d(s),c=S(e,i);for(const u of a){const l=M(u,c);if(l===void 0)continue;const f=e.exec(`SELECT id, ${l.expression} AS ref FROM ${i} WHERE ${l.expression} IN (${_})`,...l.params,...l.params,...o).toArray();for(const p of f)n[p.ref]?.push({column:u,id:p.id,table:s})}}return{references:n,storageColumns:t}},ue=e=>{const t=e.map((n,o)=>{const _=Object.values(n.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:n.admin===!0,id:o,subscriptions:_}}),r=t.reduce((n,o)=>n+o.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:r}},V=20,le=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),de=()=>({run:0,served:0}),me=()=>({drains:0,pairsSkipped:0}),fe=(e,t,r)=>({drains:e.drains+t,pairsSkipped:e.pairsSkipped+r}),pe=(e,t,r)=>({run:e.run+t,served:e.served+r}),ge=(e,t,r,n)=>({maxMs:Math.max(e.maxMs,n),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+r,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+n}),he=(e,t=V)=>{const r=new Map,n=new Map;for(const s of e){for(const a of Object.values(s.shapes??{})){const i=a.name??"(unknown shape)";r.set(i,(r.get(i)??0)+1)}for(const a of s.whispers??[])n.set(a,(n.get(a)??0)+1)}const o=[...[...r].map(([s,a])=>({kind:"shape",subscribers:a,topic:s})),...[...n].map(([s,a])=>({kind:"whisper",subscribers:a,topic:s}))];return o.sort((s,a)=>a.subscribers-s.subscribers||s.topic.localeCompare(a.topic)),{peakSubscribers:o[0]?.subscribers??0,topics:o.slice(0,t),totalConnections:e.length}};export{se as ADMIN_FUNCTIONS,te as ADMIN_FUNCTION_PREFIX,V as DEFAULT_FANOUT_TOPIC_LIMIT,ne as FLAGS_FUNCTION_PREFIX,g as MAX_PAGE_SIZE,re as RELATION_FUNCTION_PREFIX,le as createFanoutCounters,me as createGlobalPollCounters,de as createShapeProbeCounters,X as datePrefixRange,ie as facetColumn,ce as findStorageReferences,oe as listTables,ae as readTablePage,ge as recordFanoutPass,fe as recordGlobalPollPass,pe as recordShapeProbePass,_e as selectMatchingIds,he as summarizeFanoutTopics,ue as summarizeSubscriptions};
|
|
1
|
+
import{LunoraError as v}from"@lunora/errors";import{m as $,n as y}from"./do-sql-DbEszTyj.mjs";import{quoteIdentifier as d}from"./quoteIdentifier-CObIFRhb.mjs";import{d as L}from"./wire-codec-BU9T2xJ7.mjs";const te="__lunora_admin__:",re="__lunora_relation__:",ne="__lunora_flags__:",se={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backfillSearch:"__lunora_admin__:backfillSearch",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",getAdvisories:"__lunora_admin__:getAdvisories",getAdvisorProcedures:"__lunora_admin__:getAdvisorProcedures",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",listTablesIndexes:"__lunora_admin__:listTablesIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listReactors:"__lunora_admin__:listReactors",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",replayQueueMessage:"__lunora_admin__:replayQueueMessage",resolveIssue:"__lunora_admin__:resolveIssue",rlsPolicies:"__lunora_admin__:rlsPolicies",schemaHistory:"__lunora_admin__:schemaHistory",schemaVersion:"__lunora_admin__:schemaVersion",runAs:"__lunora_admin__:runAs",runMigration:"__lunora_admin__:runMigration",runSql:"__lunora_admin__:runSql",sendQueueMessage:"__lunora_admin__:sendQueueMessage",sendTestMail:"__lunora_admin__:sendTestMail",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},D=50,g=500,U=30,W=200,m="__doc__",O=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},j=e=>{const{[y]:t,...r}=e;return t===void 0?r:t===null||typeof t!="object"||Array.isArray(t)?{[y]:t,...r}:{...r,...L(t)}},Q=(e,t)=>{if(!e.includes(m))return{columns:e,rows:t};const r=[];for(const s of t){const a=s[m],i=typeof a=="string"?O(a):void 0;if(i===void 0)return{columns:e,rows:t};const c=Object.fromEntries(Object.entries(s).filter(([u])=>u!==m));r.push({...c,...j(i)})}const n=e.filter(s=>s!==m),o=[],_=new Set(n);for(const s of r)for(const a of Object.keys(s))_.has(a)||(_.add(a),o.push(a));return{columns:[...n,...o],rows:r}},F=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,I=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),E=(e,t,r)=>Math.min(Math.max(e,t),r),x=(e,t)=>{const r=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(r.c)},oe=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),r=[];for(const{name:n}of t)I(n)||r.push({name:n,rowCount:x(e,d(n))});return r},P=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,C=(e,t)=>{if(I(t)||!P(e,t))throw new v("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},S=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(r=>r.name),q={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},G=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",M=(e,t)=>{const r=t.includes(e),n=t.includes(m);if(!(!r&&!n))return r?{expression:d(e),params:[]}:{expression:`json_extract(${d(m)}, ?)`,params:[`$.${$(e)}`]}},H=(e,t)=>{const r=M(e.column,t);if(r===void 0)return;const{expression:n,params:o}=r;return e.operator==="contains"?{params:[...o,G(e.value)],sql:F(n)}:{params:[...o,e.value],sql:`${n} ${q[e.operator]} ?`}},B=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,X=e=>{const t=B.exec(e.trim());if(t===null)return;const r=Number(t[1]),n=t[2]===void 0?void 0:Number(t[2]),o=t[3]===void 0?void 0:Number(t[3]);if(n!==void 0&&(n<1||n>12)||o!==void 0&&(o<1||o>31)||r<100)return;const _=Date.UTC(r,(n??1)-1,o??1);if(o!==void 0&&new Date(_).getUTCDate()!==o)return;let s;return o!==void 0?s=Date.UTC(r,(n??1)-1,o+1):n===void 0?s=Date.UTC(r+1,0,1):s=Date.UTC(r,n,1),{from:_,to:s}},A=(e,t,r)=>{const n=[],o=[];if(t!==""&&e.length>0){const _=e.map(a=>F(d(a)));o.push(...e.map(()=>t));const s=X(t);if(s!==void 0)for(const a of e)_.push(`(${d(a)} >= ? AND ${d(a)} < ?)`),o.push(s.from,s.to);n.push(`(${_.join(" OR ")})`)}for(const _ of r??[]){const s=H(_,e);s!==void 0&&(n.push(`(${s.sql})`),o.push(...s.params))}return n.length===0?void 0:{parameters:o,where:n.join(" AND ")}},K=(e,t)=>{if(e===void 0)return;const r=M(e.column,t);if(r===void 0)return;const n=e.direction==="desc"?"DESC":"ASC";return{params:r.params,sql:`${r.expression} ${n}`}},ae=(e,t)=>{const{table:r}=t;C(e,r);const n=E(Math.trunc(t.limit??D),1,g),o=Math.max(0,Math.trunc(t.offset??0)),_=d(r),s=S(e,_),a=t.search?.trim()??"",i=b=>{if(t.refs===void 0)return b;const T={};for(const k of b.columns){const w=t.refs[k];w!==void 0&&(T[k]=w)}return Object.keys(T).length>0?{...b,refs:T}:b},c=A(s,a,t.filters),u=K(t.orderBy,s),l=c===void 0?"":` WHERE ${c.where}`,f=u===void 0?"":` ORDER BY ${u.sql}`,p=c?.parameters??[],h=u?.params??[];let R;t.skipCount||(R=c===void 0?x(e,_):Number(e.exec(`SELECT COUNT(*) AS c FROM ${_}${l}`,...p).one().c));const N=e.exec(`SELECT * FROM ${_}${l}${f} LIMIT ? OFFSET ?`,...p,...h,n,o).toArray();return i({...Q(s,N),total:R})},_e=(e,t)=>{const{table:r}=t;C(e,r);const n=E(Math.trunc(t.limit??g),1,g),o=d(r),_=S(e,o),s=t.search?.trim()??"",a=A(_,s,t.filters),i=a===void 0?e.exec(`SELECT id FROM ${o} LIMIT ?`,n+1).toArray():e.exec(`SELECT id FROM ${o} WHERE ${a.where} LIMIT ?`,...a.parameters,n+1).toArray(),c=i.length>n,u=i.slice(0,n).map(l=>l.id);return{hasMore:c,ids:u}},Y=(e,t,r)=>{const n=new Set(r.filter(_=>_!==m));if(!r.includes(m))return n;const o=e.exec(`SELECT ${d(m)} AS doc FROM ${t} LIMIT ?`,g).toArray();for(const{doc:_}of o){const s=typeof _=="string"?O(_):void 0;if(s!==void 0)for(const a of Object.keys(s))n.add(a)}return n},ie=(e,t)=>{const{column:r,table:n}=t;C(e,n);const o=d(n),_=S(e,o);if(!Y(e,o,_).has(r))throw new v("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const s=M(r,_);if(s===void 0)throw new v("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const a=E(Math.trunc(t.limit??U),1,W),i=t.search?.trim()??"",c=A(_,i,t.filters),u=c===void 0?"":` WHERE ${c.where}`,l=c?.parameters??[],f=e.exec(`SELECT ${s.expression} AS value, COUNT(*) AS count FROM ${o}${u} GROUP BY ${s.expression} ORDER BY count DESC LIMIT ?`,...s.params,...l,...s.params,a+1).toArray();return{truncated:f.length>a,values:f.slice(0,a).map(h=>({count:Number(h.count),value:h.value}))}},ce=(e,t,r)=>{const n={},o=r.slice(0,g);for(const s of o)n[s]=[];if(o.length===0)return{references:n,storageColumns:t};const _=o.map(()=>"?").join(", ");for(const[s,a]of Object.entries(t)){if(I(s)||!P(e,s))continue;const i=d(s),c=S(e,i);for(const u of a){const l=M(u,c);if(l===void 0)continue;const f=e.exec(`SELECT id, ${l.expression} AS ref FROM ${i} WHERE ${l.expression} IN (${_})`,...l.params,...l.params,...o).toArray();for(const p of f)n[p.ref]?.push({column:u,id:p.id,table:s})}}return{references:n,storageColumns:t}},ue=e=>{const t=e.map((n,o)=>{const _=Object.values(n.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:n.admin===!0,id:o,subscriptions:_}}),r=t.reduce((n,o)=>n+o.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:r}},V=20,le=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),de=()=>({run:0,served:0}),me=()=>({drains:0,pairsSkipped:0}),fe=(e,t,r)=>({drains:e.drains+t,pairsSkipped:e.pairsSkipped+r}),pe=(e,t,r)=>({run:e.run+t,served:e.served+r}),ge=(e,t,r,n)=>({maxMs:Math.max(e.maxMs,n),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+r,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+n}),he=(e,t=V)=>{const r=new Map,n=new Map;for(const s of e){for(const a of Object.values(s.shapes??{})){const i=a.name??"(unknown shape)";r.set(i,(r.get(i)??0)+1)}for(const a of s.whispers??[])n.set(a,(n.get(a)??0)+1)}const o=[...[...r].map(([s,a])=>({kind:"shape",subscribers:a,topic:s})),...[...n].map(([s,a])=>({kind:"whisper",subscribers:a,topic:s}))];return o.sort((s,a)=>a.subscribers-s.subscribers||s.topic.localeCompare(a.topic)),{peakSubscribers:o[0]?.subscribers??0,topics:o.slice(0,t),totalConnections:e.length}};export{se as ADMIN_FUNCTIONS,te as ADMIN_FUNCTION_PREFIX,V as DEFAULT_FANOUT_TOPIC_LIMIT,ne as FLAGS_FUNCTION_PREFIX,g as MAX_PAGE_SIZE,re as RELATION_FUNCTION_PREFIX,le as createFanoutCounters,me as createGlobalPollCounters,de as createShapeProbeCounters,X as datePrefixRange,ie as facetColumn,ce as findStorageReferences,oe as listTables,ae as readTablePage,ge as recordFanoutPass,fe as recordGlobalPollPass,pe as recordShapeProbePass,_e as selectMatchingIds,he as summarizeFanoutTopics,ue as summarizeSubscriptions};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{A as r,a as l,b as i,D as n,n as m,c as q,d as c,l as d,k as f,g as p,i as u,j as A,e as D,q as G,f as S,r as _,t as h,h as C}from"./do-sql-
|
|
1
|
+
import{A as r,a as l,b as i,D as n,n as m,c as q,d as c,l as d,k as f,g as p,i as u,j as A,e as D,q as G,f as S,r as _,t as h,h as C}from"./do-sql-DbEszTyj.mjs";import{quoteIdentifier as b}from"./quoteIdentifier-CObIFRhb.mjs";import"./wire-codec-BU9T2xJ7.mjs";import"./runDrizzle-it6rL9bR.mjs";import"./sql-projection-BqmxFxQU.mjs";import{serializeSqlValue as x}from"./serializeSqlValue-DbI1VQYM.mjs";export{r as AGG_COUNT,l as AGG_KEY,i as AGG_VALUE,n as DOC_COLUMN,m as DOC_ORIGINALS_KEY,q as aggUpsertSql,c as createIndexSql,d as decodeDocJson,f as encodeDocJson,p as geoTableName,u as isFtsAvailable,A as jsonPath,D as jsonPathSql,G as qualifiedJsonPath,S as qualifiedJsonPathSql,b as quoteIdentifier,_ as rowToDocument,x as serializeSqlValue,h as tableColumns,C as tryRowToDocument};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as u}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{runDrizzle as n}from"./runDrizzle-it6rL9bR.mjs";import{k as m,l as A}from"./do-sql-
|
|
1
|
+
import{LunoraError as u}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{runDrizzle as n}from"./runDrizzle-it6rL9bR.mjs";import{k as m,l as A}from"./do-sql-DbEszTyj.mjs";import{ConflictError as p}from"./ConflictError-C8GtJmjS.mjs";const c="__cdc_log",q="__cdc_log_table_seq",_=e=>{n(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(c)} (
|
|
2
2
|
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
3
3
|
ts REAL NOT NULL,
|
|
4
4
|
${t.identifier("table")} TEXT NOT NULL,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as y}from"@lunora/errors";import{c as Ht,q as Je,S as Nt,l as Ae,a as jt}from"./ctx-db-companions-BQRTS_WY.mjs";import{sql as r}from"drizzle-orm";import{d as Kt}from"./wire-codec-BU9T2xJ7.mjs";import{throwingScheduler as Ot,aggregateSqlFunction as ve,normalizeCountArgument as Qt}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as qe,encodeAggregateKey as Be,readAggregateValue as Ue}from"./aggregateTableName-Cy5e03oz.mjs";import{mergeWhere as J,CountRlsUnsupportedError as Pe,selectIndexForGroupBy as zt,selectIndexForCount as Jt,selectIndexForAggregate as Vt}from"./CountRlsUnsupportedError-Bdfupt3g.mjs";import{backfillSearchIndexesForTable as Yt}from"./backfillAggregateIndexes-C9wGiPH4.mjs";import{backfillAggregateIndexes as jr,backfillRankIndexes as Kr,backfillSearchIndexes as Or}from"./backfillAggregateIndexes-C9wGiPH4.mjs";import{appendCdcChange as Xt}from"./CDC_LOG_TABLE-CW0wHEgW.mjs";import{CDC_LOG_TABLE as zr,applyCdcChanges as Jr,bumpCdcEpoch as Vr,cdcCanVouchFor as Yr,cdcSeqLeavingRows as Xr,cdcTouchesTables as Zr,cdcTrimmedError as eo,compactCdcDocs as to,cursorBelowRetainedFloor as no,minCdcReplayableSeq as ro,minCdcSeq as oo,readCdcChangeKeys as io,readCdcChanges as so,readCdcCursor as co,readCdcEpoch as ao,trimCdcChanges as lo}from"./CDC_LOG_TABLE-CW0wHEgW.mjs";import{allocateCommitSeq as Zt,COMMIT_SEQ_FIELD as en}from"./COMMIT_SEQ_FIELD-CSe_oNZu.mjs";import{isMemoryTable as tn}from"./clearMemoryTables-CXULwypv.mjs";import{computeRankPage as dt}from"./computeRankPage-Bby1Npkd.mjs";import{SCAN_DEP as H}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as B}from"./runDrizzle-it6rL9bR.mjs";import{D as K,k as se,r as de,b as Ie,A as Ge,a as Ce,e as V,t as It,f as lt,i as nn,h as Ct,g as rn}from"./do-sql-DbEszTyj.mjs";import{WORKERD_SQLITE_LIMITS as xt,unionAll as Ke,sqliteInList as on}from"./param-Ib8WHnrF.mjs";import{coveringGeohashes as sn,boundingBoxGeohashes as cn,haversineMeters as an,pointInBoundingBox as dn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as ln}from"./NotFoundError-BhF7FeFr.mjs";import{softDeleteScope as ae,normalizeOrderKeys as un,buildSeekWhere as Mt,decodeCursor as Oe,applySelect as ut,encodeCursor as Qe,buildSeekBeforeWhere as fn}from"./applySelect-BQbHyo-W.mjs";import{rankTableName as ft,sortColumnName as ht,resolveRankPartition as hn,encodePartitionKey as wn,RANK_TIEBREAK as pn}from"./RANK_TIEBREAK-ci3MaM65.mjs";import{indexKeysForRow as gn,buildIndexRange as $n}from"./buildIndexRange-CBKQmHSS.mjs";import{assertFlatPredicate as He,resolveRelationPredicates as wt}from"./DEFAULT_MAX_RELATION_KEYS-BAWGIEvC.mjs";import{runRowValidators as Ne,resolveWith as pt,relationHooks as gt,applyOnDelete as yn,fanOutScalarCounts as En}from"./applyOnDelete-BlcwKjuO.mjs";import{guardWriter as mn}from"./RLS_UNWRAP_SYMBOL-BWloGsd3.mjs";import{i as Sn}from"./sql-projection-BqmxFxQU.mjs";import{createSystemReader as Rn}from"./createSystemReader-BtYeSMDb.mjs";import{ConflictError as pe}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as Tn}from"./hasTrigger-CjlwI4le.mjs";import{compileWhereSql as te}from"./compileWhereSql-JBpSfQm9.mjs";import{CLIENT_WATERMARK_TABLE as fo,advanceClientWatermark as ho,migrateClientWatermark as wo,readClientWatermark as po}from"./CLIENT_WATERMARK_TABLE-BoS1HEqz.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as $o,deleteGlobalShapeSnapshot as yo,deleteGlobalShapeSnapshotsForConnection as Eo,migrateGlobalShapeSnapshot as mo,readGlobalShapeSnapshot as So,writeGlobalShapeSnapshot as Ro}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-NWaL77m5.mjs";import{IDEMPOTENCY_TABLE as _o,readIdempotent as Ao,trimIdempotent as vo,writeIdempotent as Io}from"./IDEMPOTENCY_TABLE-DKVe2Ohf.mjs";import{runShardMigrations as xo}from"./runShardMigrations-DFc_LoP-.mjs";import{SEARCH_STATE_TABLE as bo}from"./SEARCH_STATE_TABLE-Dju8ebbU.mjs";import{selectShapeMembers as ko,selectShapeRows as Lo}from"./selectShapeMembers-C0vtU60D.mjs";import{serializeSqlValue as oe}from"./serializeSqlValue-DbI1VQYM.mjs";import{quoteIdentifier as _n}from"./quoteIdentifier-CObIFRhb.mjs";const An=o=>{const i=new TextEncoder().encode(o);let t="";for(const a of i)t+=String.fromCodePoint(a);return btoa(t)},vn=o=>{const i=atob(o),t=Uint8Array.from(i,a=>a.codePointAt(0)??0);return new TextDecoder().decode(t)},In=()=>new y("BAD_REQUEST","invalid cursor"),$t=16,yt=8,X=1024,Ve=(o,i)=>i.query(o),Cn=(o,i)=>{if(o.length===0)return 0;let t=0;for(const[a,f]of i.entries()){const g=a===i.length-1;let E=0;for(const T of o)(g?T.startsWith(f):T===f)&&(E+=1);if(E===0)return 0;t+=E}return t},xn=(o,i)=>{if(!i)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",a=(t.codePointAt(0)??0)+1;if(a>=55296&&a<=57343||a>1114111)return{exact:!0,lower:o,upper:o};const f=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:f+String.fromCodePoint(a)}},Mn=(o,i,t)=>{const a={eq:(f,g)=>{if(!o.definition.filterFields?.includes(f))throw new y("INTERNAL",`field "${f}" is not a filter field of search index "${o.indexName}" on table "${i}"`);if(o.filters.length>=yt)throw new y("BAD_REQUEST",`search index "${o.indexName}" on table "${i}": at most ${String(yt)} .eq() filters are supported per search query`);return o.filters.push({field:f,value:g}),a},search:(f,g)=>{const E=o;if(f!==E.definition.field)throw new y("INTERNAL",`search index "${E.indexName}" on table "${i}" indexes "${E.definition.field}", not "${f}"`);const T=Ve(g,t).length;if(T>$t)throw new y("BAD_REQUEST",`search index "${E.indexName}" on table "${i}": at most ${String($t)} search terms are supported (got ${String(T)})`);return E.field=f,E.query=g,E.hasQuery=!0,a}};return a},bn=o=>{if(o.length>X)throw new y("BAD_REQUEST",`more than ${String(X)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Dn=o=>Math.min(o.offset+o.numItems+1,X),kn=o=>An(`search:${String(o)}`),Ln=o=>{let i;try{i=vn(o)}catch{return}if(!i.startsWith("search:"))return;const t=Number(i.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},Fn=o=>{if(typeof o.endCursor=="string")throw new y("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(o.numItems))throw new y("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(o.numItems)}`);const i=Math.max(0,Math.floor(o.numItems)),t=o.cursor?Ln(o.cursor):0;if(t===void 0)throw In();if(t+i>=X)throw new y("BAD_REQUEST",`search pagination reaches the ${String(X)}-document limit (offset ${String(t)} + ${String(i)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,X-t-1))} or fewer, or narrow the query or the filters instead`);return{numItems:i,offset:t}},Wn=(o,i)=>{const t=i.offset+i.numItems,a=i.numItems>0&&o.length>t;return{continueCursor:a?kn(t):null,isDone:!a,page:o.slice(i.offset,t)}},qn=o=>{if(o===void 0)return X+1;if(!Number.isFinite(o))return X;const i=Math.max(0,Math.floor(o));if(i>X)throw new y("BAD_REQUEST",`search returns at most ${String(X)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},Bn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Un=o=>{if(!Bn.test(o))throw new y("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},Et=50,bt=500,xe=Math.floor(xt.boundParams/3),we=xt.boundParams,Pn=128,ce=(o,i,t)=>{const a=i??bt;if(o>a)throw new y("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},Gn=o=>{const i={eq:(t,a)=>(o.sqlConditions.push({comparator:"=",field:t,value:a}),i),gt:(t,a)=>(o.sqlConditions.push({comparator:">",field:t,value:a}),i),gte:(t,a)=>(o.sqlConditions.push({comparator:">=",field:t,value:a}),i),lt:(t,a)=>(o.sqlConditions.push({comparator:"<",field:t,value:a}),i),lte:(t,a)=>(o.sqlConditions.push({comparator:"<=",field:t,value:a}),i)};return i},Hn=o=>Math.max(o,X),Dt=(o,i)=>{const t=o.filters.map(a=>r`${V(a.field)} = ${oe(a.value)}`);return i&&t.push(i),t},Nn=(o,i,t,a,f)=>{const g=Ve(t.query,Je(t.definition.language));if(g.length===0)return[];const E=Nt(i,t.indexName),T=`${E}__vocab`,S=g.length-1,$=g.map((W,M)=>{const N=xn(W,M===S),j=N.exact?r`${r.identifier("term")} = ${N.lower}`:r`${r.identifier("term")} >= ${N.lower} AND ${r.identifier("term")} < ${N.upper}`;return r`SELECT ${r.identifier("doc")}, ${r.raw(String(M))} AS ${r.identifier("__term__")}, COUNT(*) AS ${r.identifier("__n__")} FROM ${r.identifier(T)} WHERE ${j} GROUP BY ${r.identifier("doc")}`}),L=g.map((W,M)=>r`SUM(CASE WHEN u.${r.identifier("__term__")} = ${r.raw(String(M))} THEN u.${r.identifier("__n__")} ELSE 0 END)`),_=r`SELECT f.${r.identifier(Ae)} AS ${r.identifier(Ae)}, ${r.join(L,r` + `)} AS ${r.identifier("__score__")} FROM (${Ke($)}) u JOIN ${r.identifier(E)} f ON f.rowid = u.${r.identifier("doc")} GROUP BY f.${r.identifier(Ae)} HAVING ${r.join(L.map(W=>r`${W} > 0`),r` AND `)}`,v=Dt(t,f);let R=r`SELECT m.id, m._creationTime, m.${r.identifier(K)}, s.${r.identifier("__score__")} AS ${r.identifier("__score__")} FROM (${_}) s JOIN ${r.identifier(i)} m ON m.id = s.${r.identifier(Ae)}`;v.length>0&&(R=r`${R} WHERE ${r.join(v,r` AND `)}`),R=r`${R} ORDER BY s.${r.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${r.raw(String(a))}`;const F=[];for(const W of B(o,R)){const M=Ct(W);if(M){const N=W.__score__;F.push({document:M,score:typeof N=="number"?N:Number(N??0)})}}return F},jn=(o,i,t,a,f)=>{const g=Je(t.definition.language),E=Ve(t.query,g);if(E.length===0)return[];const T=Dt(t,f);let S=r`SELECT id, _creationTime, ${r.identifier(K)} FROM ${r.identifier(i)}`;T.length>0&&(S=r`${S} WHERE ${r.join(T,r` AND `)}`),S=r`${S} ORDER BY _creationTime DESC, id ASC LIMIT ${r.raw(String(Hn(a)))}`;const $=B(o,S).toArray(),L=[];for(const _ of $){const v=Ct(_);if(!v)continue;const R=Cn(jt(v,t.definition),E);R>0&&L.push({creationTime:typeof v._creationTime=="number"?v._creationTime:0,doc:v,id:typeof v._id=="string"?v._id:"",score:R})}return L.sort((_,v)=>v.score-_.score||v.creationTime-_.creationTime||_.id.localeCompare(v.id)),L.slice(0,a).map(_=>({document:_.doc,score:_.score}))},je=(o,i,t,a)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new y("BAD_REQUEST",`geo index "${a}" on table "${t}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},Kn=(o,i)=>{const t=o,a={near:(f,g)=>{if(t.within)throw new y("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(je(f,".near() point",i,t.indexName),!Number.isFinite(g)||g<=0)throw new y("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(g)}`);return t.near={point:{lat:f.lat,lng:f.lng},radiusMeters:g},a},within:f=>{if(t.near)throw new y("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(je(f.sw,".within() sw corner",i,t.indexName),je(f.ne,".within() ne corner",i,t.indexName),f.sw.lat>f.ne.lat)throw new y("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(f.sw.lng>f.ne.lng)throw new y("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return t.within={ne:{lat:f.ne.lat,lng:f.ne.lng},sw:{lat:f.sw.lat,lng:f.sw.lng}},a}};return a},On=(o,i)=>{const t=o[i];if(t===null||typeof t!="object")return;const{lat:a,lng:f}=t;return typeof a=="number"&&typeof f=="number"?{lat:a,lng:f}:void 0},Qn=(o,i)=>{const t=On(o,i.definition.field);if(!t)return;const a=typeof o._creationTime=="number"?o._creationTime:0;if(i.near){const f=an(i.near.point,t);return f<=i.near.radiusMeters?{creationTime:a,distance:f}:void 0}return dn(t,i.within)?{creationTime:a,distance:0}:void 0},zn=(o,i,t,a)=>{if(!t.near&&!t.within)throw new y("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const f=t.near?sn(t.near.point,t.near.radiusMeters):cn(t.within),g=rn(i,t.indexName),E=f.map(_=>r`(g.${r.identifier("__geohash__")} >= ${_} AND g.${r.identifier("__geohash__")} < ${`${_}{`})`),T=[r`(${r.join(E,r` OR `)})`];a&&T.push(a);const S=r`SELECT m.id, m._creationTime, m.${r.identifier(K)} FROM ${r.identifier(g)} g JOIN ${r.identifier(i)} m ON m.id = g.${r.identifier("__id__")} WHERE ${r.join(T,r` AND `)}`,$=B(o,S).toArray(),L=[];for(const _ of $){const v=de(_),R=v?Qn(v,t):void 0;v&&R&&L.push({creationTime:R.creationTime,distance:R.distance,doc:v})}return L.sort((_,v)=>_.distance-v.distance||v.creationTime-_.creationTime),L},kt=(o,i,t,a)=>{const f=[];for(const g of o)if(i.every(E=>E(a(g)))&&(f.push(g),typeof t=="number"&&f.length>=t))break;return f},Jn=(o,i,t,a,f,g=()=>{})=>{const E=t.within!==void 0,T=zn(o,i,t,f).map(S=>({distanceMeters:E?null:S.distance,document:S.doc}));return g(T.length),typeof a=="number"?T.slice(0,Math.max(0,Math.floor(a))):T},Lt=(o,i,t,a,f,g=()=>{})=>{const{geo:E}=t;if(!E)throw new y("INTERNAL","runGeoTerminalScored called without a staged geo query");const T=t.inMemoryFilters.length>0,S=Jn(o,i,E,T?void 0:f,a,g);return T?kt(S,t.inMemoryFilters,f,$=>$.document):S},Vn=(o,i,t,a,f,g=()=>{})=>Lt(o,i,t,a,f,g).map(E=>E.document),Yn=(o,i,t,a,f,g,E=()=>{})=>{const T=[];for(const _ of t.sqlConditions)T.push(r`${V(_.field)} ${r.raw(_.comparator)} ${oe(_.value)}`);a&&T.push(a);let S=r`SELECT id, _creationTime, ${r.identifier(K)} FROM ${r.identifier(i)}`;T.length>0&&(S=r`${S} WHERE ${r.join(T,r` AND `)}`),S=r`${S} ORDER BY ${f}`,typeof g=="number"&&t.inMemoryFilters.length===0&&(S=r`${S} LIMIT ${r.raw(String(Math.max(0,Math.floor(g))))}`);const $=B(o,S).toArray();E($.length);const L=[];for(const _ of $){const v=de(_);if(v&&t.inMemoryFilters.every(R=>R(v))&&(L.push(v),typeof g=="number"&&L.length>=g))break}return L},re={fieldRef:V,serialize:oe},Ft=(o,i)=>{const t=i===void 0?void 0:o.shape[i];return t!==void 0&&Sn(t)},mt=(o,i)=>i.some(t=>Ft(o,t)),St=(o,i,t)=>{if(Ft(o,i))throw new y("BAD_REQUEST",`${t}: "${i}" is stored as an order-preserving key, which SQL cannot reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it`)},Xn=o=>{let i=0;const t=[],a={fieldRef:V,relationExists:f=>{const{childWhere:g,negated:E,parentTable:T,relation:S}=f,$=`__rel_${String(i)}`,L=t.at(-1)??T;i+=1,o(S.table,H);const _=S.kind==="one"?S.field:S.references,v=S.kind==="one"?S.references:S.field,R=r`${lt($,v)} = ${lt(L,_)}`;t.push($);const F=te(g,a);t.pop();const W=F?r`${R} AND ${F}`:R,M=r`EXISTS (SELECT 1 FROM ${r.identifier(S.table)} AS ${r.identifier($)} WHERE ${W})`;return E?r`NOT ${M}`:M},serialize:oe};return a},Wt=o=>{const i=o.map(t=>r`${V(t.field)} ${r.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||i.push(r`${V("id")} ASC`),r.join(i,r`, `)},Zn={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},er=o=>{const i=o.order;return o.indexFields.length>0?o.indexFields.map(t=>({direction:i,field:t})):[{direction:i,field:"_creationTime"}]},tr=(o,i,t,a)=>{const f=o.sqlConditions.map(g=>({[g.field]:{[Zn[g.comparator]??"eq"]:g.value}}));if(t&&f.push(Mt(i,Oe(t))),a&&f.push(fn(i,Oe(a))),f.length!==0)return f.length===1?f[0]:{AND:f}},nr=(o,i,t)=>{const a=[];for(const f of o){const g=de(f);if(g&&i.every(E=>E(g))&&(a.push(g),t!==void 0&&a.length>t))break}return a},rr=(o,i,t,a,f,g=()=>{})=>{const E=Math.max(0,Math.floor(a.numItems)),T=er(t),S=typeof a.endCursor=="string",$=te(tr(t,T,a.cursor,a.endCursor),re),L=f&&$?r`${$} AND ${f}`:f??$;let _=r`SELECT id, _creationTime, ${r.identifier(K)} FROM ${r.identifier(i)}`;L&&(_=r`${_} WHERE ${L}`),_=r`${_} ORDER BY ${Wt(T)}`;const v=t.inMemoryFilters.length>0;!v&&!S&&(_=r`${_} LIMIT ${r.raw(String(E+1))}`);const R=B(o,_).toArray();g(R.length);const F=nr(R,t.inMemoryFilters,v||S?void 0:E);if(S){const j=F.length>=2?F[Math.floor(F.length/2)-1]:void 0;return{continueCursor:a.endCursor??null,isDone:!0,page:F,splitCursor:j?Qe(j,T):null}}const W=F.length>E,M=W?F.slice(0,E):F,N=M.at(-1);return{continueCursor:W&&N?Qe(N,T):null,isDone:!W,page:M}};class or extends y{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const ir=/\s/u,sr=String.fromCodePoint(0),Rt=(o,i,t)=>{if(!o.tables[i])throw new y("INTERNAL",`unknown table: ${i}`);return typeof t!="string"||t.length===0||ir.test(t)||t.includes(sr)?null:t},cr=(o,i,t,a=()=>{},f=()=>{},g=()=>{})=>{const E=i.tables[t];if(!E)throw new y("INTERNAL",`unknown table: ${t}`);const T=ae(E.softDeleteMode,void 0),S=T?te(T,re):void 0,$={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let L=0;const _=m=>{const{search:b}=$;if(!b)throw new y("INTERNAL","runSearchFetch called without a staged search");Yt(o,t,E);const k=$.inMemoryFilters.length>0,C=qn(k?void 0:m),O=nn(o)?Nn(o,t,b,C,S):jn(o,t,b,C,S);return k?(L=O.length,kt(O,$.inMemoryFilters,m,be=>be.document)):(m===void 0&&bn(O),O)},v=m=>_(m).map(b=>b.document),R=m=>{const b=Fn(m);return Wn(v(Dn(b)),b)},F=()=>{const m=$.indexFields.length>0?$.indexFields:["_creationTime"],b=$.order==="desc"?"DESC":"ASC";return r.join(m.map(k=>r`${V(k)} ${r.raw(b)}`),r`, `)},W=()=>{if($.search||$.geo||$.indexName===void 0){f(void 0);return}f($n(t,$.indexName,$.indexFields,$.sqlConditions,oe))},M=m=>{W();let b=0;const k=(()=>{if($.search){const C=v(m);return b=L,C}return $.geo?Vn(o,t,$,S,m,C=>{b=C}):Yn(o,t,$,S,F(),m,C=>{b=C})})();return g(Math.max(b,k.length)),k},N=()=>{if(!$.search&&!$.geo)throw new y("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);W();let m=0;const b=(()=>{if($.search){const k=_(void 0);return m=L,k}return Lt(o,t,$,S,void 0,k=>{m=k})})();return g(Math.max(m,b.length)),b},j={async*[Symbol.asyncIterator](){const m=[...$.inMemoryFilters];let b;$.inMemoryFilters=[];try{for(;;){const k=await j.paginate({cursor:b??null,numItems:Pn});for(const C of k.page)m.every(O=>O(C))&&(yield C);if(k.isDone||k.continueCursor===null)return;b=k.continueCursor}}finally{$.inMemoryFilters=m}},async collect(){return M(void 0)},async collectWithScores(){return N()},filter(m){return $.inMemoryFilters.push(m),j},async first(){return M($.inMemoryFilters.length>0?void 0:1)[0]??null},order(m){return $.order=m==="desc"?"desc":"asc",j},async paginate(m){let b=0;if(W(),$.search){const C=R(m);return g(C.page.length),C}if($.geo)throw new y("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const k=rr(o,t,$,m,S,C=>{b=C});return g(Math.max(b,k.page.length)),k},async take(m){return M(m)},async unique(){const m=M($.inMemoryFilters.length>0?void 0:2);if(m.length>1)throw new or(`unique() on table "${t}" matched ${String(m.length)} documents; expected at most one`);return m[0]??null},withGeoIndex(m,b){const k=(E.geoIndexes??[]).find(O=>O.name===m);if(!k)throw new y("INTERNAL",`unknown geo index "${m}" on table "${t}"`);a(t,m,"geo");const C={definition:k,indexName:m};if($.geo=C,b(Kn(C,t)),!C.near&&!C.within)throw new y("INTERNAL",`geo index "${m}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return j},withIndex(m,b){const k=E.indexes.find(C=>C.name===m);if(!k)throw new y("INTERNAL",`unknown index "${m}" on table "${t}"`);return a(t,m,"index"),$.indexName=m,$.indexFields=k.fields,b&&b(Gn($)),j},withSearchIndex(m,b){const k=(E.searchIndexes??[]).find(O=>O.name===m);if(!k)throw new y("INTERNAL",`unknown search index "${m}" on table "${t}"`);a(t,m,"search");const C={definition:k,field:k.field,filters:[],hasQuery:!1,indexName:m,query:""};if($.search=C,b(Mn(C,t,Je(k.language))),!C.hasQuery)throw new y("INTERNAL",`search index "${m}" on table "${t}" requires a .search(field, query) call`);return j}};return j},Tt=(o,i,t)=>{const a={...i};for(const[f,g]of It(o)){if(g.serverDefault){a[f]=g.serverDefault({auth:t});continue}a[f]===void 0&&(g.defaultFn?a[f]=g.defaultFn():"defaultValue"in g&&(a[f]=g.defaultValue))}return a},_t=(o,i,t,a)=>{const f=t;for(const[g,E]of It(o)){if(E.serverDefault){g in i&&(f[g]=E.serverDefault({auth:a}));continue}E.onUpdateFn&&!(g in i)&&(f[g]=E.onUpdateFn())}},At=(o,i)=>{for(const t of Object.keys(i))if(i[t]===void 0)throw new y("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},ar=/unique constraint failed/i,dr=o=>o instanceof Error&&ar.test(o.message),ze=(o,i,t)=>{try{B(o,t)}catch(a){throw dr(a)?new pe(`unique constraint violation on "${i}"`,"unique"):a}},Me=(o,i,t)=>{if(ze(o,i,t),B(o,r`SELECT changes() AS changed`).one().changed===0)throw new pe(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},vt=(o,i,t,a,f,g,E)=>{const T=[];for(let _=0;_<t.length+1;_+=1){const v=[];for(let M=0;M<_;M+=1)v.push(r`${r.identifier(t[M])} IS ${g[M]}`);const R=t[_],F=a[_];if(R!==void 0&&F!==void 0){const M=F.direction==="desc"?">":"<";v.push(r`${r.identifier(R)} ${r.raw(M)} ${g[_]}`)}else v.push(r`${r.identifier(pn)} < ${E}`);const[W]=v;T.push(v.length===1&&W!==void 0?W:r`(${r.join(v,r` AND `)})`)}const S=r.join(T,r` OR `),$=B(o,r`SELECT COUNT(*) AS c FROM ${r.identifier(i)} WHERE ${r.identifier("__partition__")} = ${f} AND (${S})`).one(),L=B(o,r`SELECT COUNT(*) AS c FROM ${r.identifier(i)} WHERE ${r.identifier("__partition__")} = ${f}`).one();return{before:$.c,total:L.c}},Gr=o=>{const{sql:i}=o,{schema:t}=o,a=o.broadcast??(()=>{});let f;const g=()=>o.inTransaction?.()===!0,E=e=>t.tables[e]?.commitOrderedMode!==!0?{}:((f===void 0||!g())&&(f=Zt(i)),{[en]:f}),T=(e,...n)=>{const s=t.tables[e]?.indexes;if(!s||s.length===0)return;const u=[];for(const h of n)h&&u.push(...gn(s,h,oe));return u.length>0?u:void 0},{headroom:S}=o;let $=!1;const L=async e=>{const n=$;$=!0;try{return await e()}finally{$=n}},_=o.onRead??(()=>{}),v=o.onReadRange??(e=>{_(e.table,H)}),R=(e,n)=>{n!==void 0&&n!==H&&!$&&S?.recordRead(1),_(e,n)},F=o.onIndexUse??(()=>{}),W=o.onWrite??(()=>{}),M=e=>{$||S?.recordWrite(e)},N=async e=>{M(e.doc),await W(e)},{cache:j}=o,m=o.clock??(()=>Date.now()),b=o.idGenerator??(()=>crypto.randomUUID()),k=o.scheduler??Ot,{globalDb:C}=o,O=o.auth??{identity:null,userId:null},be=o.cdc??!1,De=k,qt=Rn({scheduler:typeof De.list=="function"&&typeof De.get=="function"?De:void 0,storage:o.storage}),le=(e,n,s,u)=>{be&&!tn(t.tables[e])&&Xt(i,m(),e,n,s,u)},ie=e=>t.tables[e]?.shardMode?.kind==="global",Ye=(e,n)=>{if(ie(e)){if(!C)throw new y("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return C}return U},ke=e=>Ye(e,"cascade"),z=(e,n)=>{if(ie(e)){if(!C)throw new y("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return C}},Xe=async(e,n,s,u,h)=>{h&&M(s);const l=await e.insert(n,s,u);return a({key:l,op:"insert",row:{...s,_id:l},table:n}),l},Le=(e,n)=>Ye(e,"relation load").findMany(e,n),Ze=(e,n)=>(ie(e)&&R(e,H),Le(e,n)),Bt=e=>!ie(e.table),et=o.relationExistsPushDown??"auto",tt=et!=="never",{maxRelationKeys:nt}=o,ge=(e,n,s)=>wt(e,{fetcher:Ze,maxRelationKeys:nt,relationBaseWhere:s,schema:t,tableName:n}),rt=async(e,n,s,u)=>{const h=z(e,"relation grouped count");if(h)return R(e,H),En((q,I)=>h.count(q,I),e,n,s,u);const l=t.tables[e];if(!l)throw new y("INTERNAL",`unknown table: ${e}`);R(e,H);const c=ae(l.softDeleteMode,void 0),d={[n]:{in:s}},w=J(J(d,u),c),A=await ge(w,e,void 0),p=te(A,re),x=V(n);let D=r`SELECT ${x} AS __fk__, COUNT(*) AS count FROM ${r.identifier(e)}`;p&&(D=r`${D} WHERE ${p}`),D=r`${D} GROUP BY ${x}`;const P=B(i,D).toArray();return new Map(P.map(q=>[q.__fk__,q.count]))};let $e=0;const ot=new Set;for(const[e,n]of Object.entries(t.tables))for(const s of Object.values(n.triggerMap??{}))ot.add(`${e} ${s.timing} ${s.op}`);const Z=(e,n,s)=>ot.has(`${e} ${n} ${s}`),ee=async(e,n,s)=>{if($e+=1,$e>Et)throw $e-=1,new pe(`trigger recursion exceeded ${String(Et)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await Tn({ctx:Pt,event:s,op:n,schema:t,tableName:s.table,timing:e})}finally{$e-=1}},{ensureBackfilledForTable:ue,ensureBackfilledIndex:Fe,ensureRankBackfilled:We,ensureRankBackfilledForTable:fe,syncAggregates:ye,syncCompanionsForInsert:it,syncGeo:Ee,syncRanks:he,syncSearch:me}=Ht({broadcast:a,indexKeysFor:(e,n)=>T(e,n),invalidateCache:(e,n,s)=>j?.invalidate(e,n,T(e,s)),recordCdc:le,schema:t,sql:i}),st=(e,n,s)=>{const{shardMode:u}=n;if(u?.kind==="shardBy"&&!(u.field!==void 0&&(s.partitionBy??[]).includes(u.field)))throw Object.assign(new Error(`rank index "${s.name}" on "${e}" partitions across shards (shard key "${u.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},ct=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),ne=(e,n)=>{const s=ct(n);for(let u=0;u<s.length;u+=we){const h=s.slice(u,u+we).map(p=>r`SELECT ${r.raw(`'${p.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${r.identifier(K)} FROM ${r.identifier(p)} WHERE id = ${e}`),[l]=B(i,r`${Ke(h)} LIMIT 1`).toArray();if(!l)continue;const c=l.__t__,d=de(l);if(typeof c!="string"||!d)return;const w=l[K];return{docJson:typeof w=="string"?w:se(w??{}),row:d,tableName:c}}},Ut=(e,n)=>{const s=[...new Set(e)],u=new Map;if(s.length===0)return u;const h=ct(n);for(let l=0;l<h.length;l+=we){const c=h.slice(l,l+we),d=Math.floor(we/c.length),w=on(r`${r.identifier("id")}`,s,!1,d),A=c.map(p=>r`SELECT ${r.raw(`'${p.replaceAll("'","''")}'`)} AS __t__, id FROM ${r.identifier(p)} WHERE ${w}`);for(const p of B(i,Ke(A))){const{id:x,__t__:D}=p;typeof D=="string"&&typeof x=="string"&&u.set(x,D)}}return u},at={assertRankPartitionLocal:st,ensureRankBackfilled:We,onRead:R,rowToDocument:de,schema:t,sql:i},U={system:qt,async aggregate(e,n){const s=z(e,"aggregate");if(s)return R(e,H),s.aggregate(e,n);const u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);if(ve(n.op),n.op==="count")return U.count(e,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new y("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);R(e,H);const h=ae(u.softDeleteMode,void 0),l=J(J(n.baseWhere,n.where),h),c=await ge(l,e,n.relationBaseWhere),d=c!==l;if(u.aggregateIndexes&&!n.baseWhere&&!d&&(!h||mt(u,[n.field]))){const q=Vt(u.aggregateIndexes,n.op,n.field,n.where);if(q){Fe(e,q.index);const I=Be(q.index.by??[],q.key),Q=qe(e,q.index.name),Y=B(i,r`SELECT ${Ie} AS value, ${Ge} AS count FROM ${r.identifier(Q)} WHERE ${Ce} = ${I}`).toArray()[0];return Ue(n.op,Y)}}St(u,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const w=te(c,re),A=ve(n.op),p=V(n.field);let x=r`SELECT ${r.raw(A)}(${p}) AS value FROM ${r.identifier(e)}`;w&&(x=r`${x} WHERE ${w}`);const P=B(i,x).toArray()[0]?.value;return P??null},asId(e,n){const s=Rt(t,e,n);if(s===null)throw new y("BAD_REQUEST",`asId("${e}", …): "${n}" is not a valid id for table "${e}"`,{status:400});return s},async count(e,n){const s=z(e,"count");if(s)return R(e,H),s.count(e,n);const u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const h=Qt(n);if(h.restrictsCounts)throw new Pe(e);R(e,H);const l=ae(u.softDeleteMode,void 0),c=J(J(h.baseWhere,h.where),l),d=await ge(c,e,h.relationBaseWhere),w=d!==c;if(u.aggregateIndexes&&!h.baseWhere&&!w&&!l){const D=Jt(u.aggregateIndexes,h.where);if(D){Fe(e,D.index);const P=Be(D.index.by??[],D.key),q=qe(e,D.index.name),I=B(i,r`SELECT ${Ie} AS value FROM ${r.identifier(q)} WHERE ${Ce} = ${P}`).toArray();return I[0]===void 0?0:I[0].value??0}}const A=te(d,re);let p=r`SELECT COUNT(*) AS count FROM ${r.identifier(e)}`;return A&&(p=r`${p} WHERE ${A}`),B(i,p).one().count},async delete(e,n,s){const u=ne(e,n);if(!u){const p=n===void 0?C:void 0;p&&(M(void 0),await p.delete(e,void 0,s));return}const{docJson:h,row:l,tableName:c}=u,d=t.tables[c],w=s?.hard===!0,A=!w&&d?.softDeleteMode?d.softDeleteMode.field:void 0;if(!(A&&l[A]!==null&&l[A]!==void 0)){if(Z(c,"before","delete")&&await ee("before","delete",{id:e,op:"delete",previous:l,table:c}),await yn({deletedId:e,deletedReference:p=>l[p],findHolders:async(p,x,D)=>(await ke(p).findMany(p,{includeDeleted:w,where:{[x]:D}})).page,onCascade:(p,x)=>ke(p).delete(x,void 0,s),onRestrict:p=>{throw new pe(p,"restrict")},onSetNull:(p,x,D)=>ke(p).patch(x,{[D]:null}),schema:t,tableName:c}),ue(c),fe(c),A){const p={...l,...E(c),[A]:m(),_id:e};Me(i,c,r`UPDATE ${r.identifier(c)} SET ${r.identifier(K)} = ${se(p)} WHERE id = ${e} AND ${r.identifier(K)} = ${h}`),me(c,e,p,l),Ee(c,e,void 0),ye(c,l,p),he(c,e,l,void 0),j?.invalidate(c,e,T(c,l,p)),le(c,e,"update",p),a({indexKeys:T(c,l,p),key:e,op:"update",row:p,table:c}),Z(c,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:c}),await N({id:e,op:"delete",table:c});return}Me(i,c,r`DELETE FROM ${r.identifier(c)} WHERE id = ${e} AND ${r.identifier(K)} = ${h}`),me(c,e,void 0),Ee(c,e,void 0),ye(c,l,void 0),he(c,e,l,void 0),j?.invalidate(c,e,T(c,l)),le(c,e,"delete"),a({indexKeys:T(c,l),key:e,op:"delete",table:c}),Z(c,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:c}),await N({id:e,op:"delete",table:c})}},async deleteAll(e,n){if(!t.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);const s=Math.max(1,n?.chunkSize??bt),u=n?.hard===void 0?void 0:{hard:n.hard},h=ie(e)?void 0:e;let l=0;return await L(async()=>{for(;;){const d=(await U.findMany(e,{limit:s})).page.map(w=>String(w._id));if(d.length===0)break;for(const w of d)await U.delete(w,h,u),l+=1;if(d.length<s)break}}),{deleted:l}},async deleteMany(e,n,s){ce(e.length,n?.limit,"deleteMany");for(const u of e)await U.delete(u,s);return{deleted:e.length}},async deleteWhere(e,n,s){const l=(await(z(e,"deleteWhere")??U).findMany(e,{where:n})).page.map(c=>String(c._id));if(ce(l.length,s?.limit,"deleteWhere"),U.deleteMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return U.deleteMany(l,s)},async findFirst(e,n={}){return(await U.findMany(e,{...n,limit:1})).page[0]??null},async findFirstOrThrow(e,n={}){const s=await U.findFirst(e,n);if(s===null)throw new ln(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,n={}){const s=z(e,"findMany");if(s)return R(e,H),s.findMany(e,n);const u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const h=!n.where&&!n.baseWhere;h?R(e,H):R(e);const l=un(n.orderBy),c=n.cursor?Mt(l,Oe(n.cursor)):void 0;let d=J(n.baseWhere,n.where);d=J(d,ae(u.softDeleteMode,n.includeDeleted)),d=await wt(d,{canPushExists:tt?Bt:void 0,existsPushMode:et==="always"?"always":"auto",fetcher:Ze,maxRelationKeys:nt,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),c&&(d=d?{AND:[d,c]}:c);const w=tt?Xn(R):re,A=te(d,w);let p=r`SELECT id, _creationTime, ${r.identifier(K)} FROM ${r.identifier(e)}`;A&&(p=r`${p} WHERE ${A}`),p=r`${p} ORDER BY ${Wt(l)}`;const x=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0;x!==void 0&&(p=r`${p} LIMIT ${r.raw(String(x+1))}`);const D=B(i,p).toArray();h&&!$&&S?.recordRead(D.length);const P=[];for(const Y of D){const G=de(Y);G&&(P.push(G),!h&&typeof G._id=="string"&&R(e,G._id))}if(x===void 0)return n.with&&await pt({groupedCounter:rt,fetcher:Le,parents:P,...gt(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:ut(P,n.select,n.with)};const q=P.length>x,I=q?P.slice(0,x):P,Q=I.at(-1);return n.with&&await pt({fetcher:Le,groupedCounter:rt,parents:I,...gt(n),schema:t,tableName:e,with:n.with}),{continueCursor:q&&Q?Qe(Q,l):null,isDone:!q,page:ut(I,n.select,n.with)}},async get(e,n){const s=ne(e,n);if(!s){const u=n===void 0?C:void 0;return u?u.get(e):null}return R(s.tableName,e),s.row},async lookupById(e,n){const s=ne(e,n);return s?(R(s.tableName,e),{row:s.row,tableName:s.tableName}):null},async groupBy(e,n){const s=z(e,"groupBy");if(s)return R(e,H),s.groupBy(e,n);const u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);R(e,H);const h=n.agg??{op:"count"};if(ve(h.op),h.op!=="count"&&!h.field)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const l=ae(u.softDeleteMode,void 0),c=J(J(n.baseWhere,n.where),l),d=await ge(c,e,n.relationBaseWhere),w=d!==c,A=[...n.by,h.field];if(u.aggregateIndexes&&!n.baseWhere&&!w&&(!l||mt(u,A))){const I=zt(u.aggregateIndexes,h.op,h.field,n.by,n.where),Q=I===void 0?0:Object.keys(I.partial).length,Y=I?.index.by?.length??0;if(I&&(Q===0||Q===Y)){Fe(e,I.index);const G=qe(e,I.index.name),Se=Object.keys(I.partial),Re=[];if(Se.length===(I.index.by??[]).length&&Se.length>0){const Te=Be(I.index.by??[],I.partial),_e=B(i,r`SELECT ${Ie} AS value, ${Ge} AS count FROM ${r.identifier(G)} WHERE ${Ce} = ${Te}`).toArray();return _e.length>0&&Re.push({key:{...I.partial},value:Ue(h.op,_e[0])}),Re}const Gt=B(i,r`SELECT ${Ce} AS key, ${Ie} AS value, ${Ge} AS count FROM ${r.identifier(G)}`).toArray();for(const Te of Gt){const _e=Kt(JSON.parse(Te.key));Re.push({key:_e,value:Ue(h.op,Te)})}return Re}}for(const I of A){if(I===void 0)continue;const Q=I===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${I}" } })`:`groupBy(${e}, { by: [..."${I}"] })`;St(u,I,Q)}const p=te(d,re),x=n.by.map(I=>r`${V(I)} AS ${r.identifier(I)}`);if(h.op==="count")x.push(r`COUNT(*) AS value`);else{const{field:I}=h;if(I===void 0)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);x.push(r`${r.raw(ve(h.op))}(${V(I)}) AS value`)}let D=r`SELECT ${r.join(x,r`, `)} FROM ${r.identifier(e)}`;p&&(D=r`${D} WHERE ${p}`),D=r`${D} GROUP BY ${r.join(n.by.map(I=>V(I)),r`, `)}`;const P=B(i,D).toArray(),q=[];for(const I of P){const Q={};for(const G of n.by)Q[G]=I[G]??null;const{value:Y}=I;q.push({key:Q,value:Y==null?null:Number(Y)})}return q},async insert(e,n,s){const u=z(e,"insert");if(u)return Xe(u,e,n,s,!0);const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);const l=Tt(h,n,O);Ne(h,l);let c;s?.clientId!==void 0?(Un(s.clientId),c=s.clientId):s?.allowExplicitId&&typeof l._id=="string"?c=l._id:c=b();const d=s?.allowExplicitId&&typeof l._creationTime=="number"?l._creationTime:m(),w={...l,...E(e),_creationTime:d,_id:c};return Z(e,"before","insert")&&await ee("before","insert",{doc:{...w},id:c,op:"insert",table:e}),ue(e),fe(e),ze(i,e,r`INSERT INTO ${r.identifier(e)} (id, _creationTime, ${r.identifier(K)}) VALUES (${c}, ${d}, ${se(w)})`),it(e,c,w),Z(e,"after","insert")&&await ee("after","insert",{doc:w,id:c,op:"insert",table:e}),await N({doc:w,id:c,op:"insert",table:e}),c},async insertManyUnsafe(e,n,s){if(ce(n.length,s?.limit,"insertManyUnsafe"),n.length===0)return[];const u=z(e,"insert");if(u){const d=[];for(const w of n)M(w);for(const w of n){const A=await u.insert(e,w,{allowExplicitId:s?.allowExplicitId});a({key:A,op:"insert",row:{...w,_id:A},table:e}),d.push(A)}return d}const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);ue(e),fe(e);const l=[];for(let d=0;d<n.length;d+=xe)l.push(E(e));const c=n.map((d,w)=>{const A=Tt(h,d,O),p=s?.allowExplicitId===!0&&typeof A._id=="string"?A._id:b(),x=s?.allowExplicitId===!0&&typeof A._creationTime=="number"?A._creationTime:m(),D={...A,...l[Math.floor(w/xe)],_creationTime:x,_id:p};return{creationTime:x,document:D,id:p}});for(const d of c)M(d.document);for(let d=0;d<c.length;d+=xe){const w=r.join(c.slice(d,d+xe).map(A=>r`(${A.id}, ${A.creationTime}, ${se(A.document)})`),r`, `);ze(i,e,r`INSERT INTO ${r.identifier(e)} (id, _creationTime, ${r.identifier(K)}) VALUES ${w}`)}for(const{document:d,id:w}of c)it(e,w,d),await W({doc:d,id:w,op:"insert",table:e});return c.map(d=>d.id)},async insertMany(e,n,s){ce(n.length,s?.limit,"insertMany");const u=s?.skipDuplicates===!0,h=[],l=z(e,"insert");if(l)for(const d of n)M(d);const c=async d=>l?Xe(l,e,d,void 0,!1):U.insert(e,d);for(const d of n)try{h.push(await c(d))}catch(w){if(u&&w instanceof pe&&w.kind==="unique")h.push(null);else throw w}return h},normalizeId(e,n){return Rt(t,e,n)},async patch(e,n,s){const u=ne(e,s);if(!u){const A=s===void 0?C:void 0;if(A){M(n),await A.patch(e,n);return}throw new y("INTERNAL",`document not found: ${e}`)}const{docJson:h,row:l,tableName:c}=u,d=t.tables[c];if(!d)throw new y("INTERNAL",`unknown table: ${c}`);R(c,e),At("patch",n);const w={...l,...n,...E(c),_id:e};_t(d,n,w,O),Ne(d,w,!0),Z(c,"before","update")&&await ee("before","update",{doc:{...w},id:e,op:"update",previous:l,table:c}),ue(c),fe(c),Me(i,c,r`UPDATE ${r.identifier(c)} SET ${r.identifier(K)} = ${se(w)} WHERE id = ${e} AND ${r.identifier(K)} = ${h}`),me(c,e,w,l),Ee(c,e,w),ye(c,l,w),he(c,e,l,w),j?.invalidate(c,e,T(c,l,w)),le(c,e,"update",w),a({indexKeys:T(c,l,w),key:e,op:"update",row:w,table:c}),Z(c,"after","update")&&await ee("after","update",{doc:w,id:e,op:"update",previous:l,table:c}),await N({doc:w,id:e,op:"update",table:c})},async patchMany(e,n,s){ce(e.length,n?.limit,"patchMany");for(const u of e)await U.patch(u.id,u.patch,s);return{patched:e.length}},async patchWhere(e,n,s){const l=(await(z(e,"patchWhere")??U).findMany(e,{where:n.where})).page.map(c=>({id:String(c._id),patch:n.patch}));if(ce(l.length,s?.limit,"patchWhere"),U.patchMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await U.patchMany(l,s),{patched:l.length}},query(e){const n=z(e,"query");return n?(R(e,H),n.query(e)):cr(i,t,e,F,s=>{s?v(s):R(e,H)},s=>{$||S?.recordRead(s)})},async rank(e,n,s){const u=z(e,"rank");if(u)return R(e,H),u.rank(e,n,s);F(e,n,"rank");const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);const l=h.rankIndexes?.find(G=>G.name===n);if(!l)throw new y("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(st(e,h,l),s.restrictsCounts)throw new Pe(e);R(e,H),We(e,l);const c=typeof s.row=="string"?s.row:s.row._id;if(!c)return null;const d=ft(e,l.name),w=l.sortBy.map((G,Se)=>ht(Se)),A=w.map(G=>_n(G)).join(", "),p=B(i,r`SELECT ${r.identifier("__partition__")}, ${r.raw(A)} FROM ${r.identifier(d)} WHERE ${r.identifier("__id__")} = ${c}`).toArray(),[x]=p;if(x===void 0)return null;let D=x.__partition__;const P=J(s.baseWhere,s.where);He(P,t,e,"rank");const q=hn(l,P);if(q){const G=wn(l.partitionBy??[],q);if(G!==D)return null;D=G}const I=w.map(G=>x[G]),{before:Q,total:Y}=vt(i,d,w,l.sortBy,D,I,c);return{position:Q+1,total:Y}},async rankBefore(e,n,s){if(ie(e))throw new y("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const h=u.rankIndexes?.find(w=>w.name===n);if(!h)throw new y("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(s.restrictsCounts)throw new Pe(e);R(e,H),We(e,h);const l=ft(e,h.name),c=h.sortBy.map((w,A)=>ht(A)),d=h.sortBy.map((w,A)=>oe(s.sortValues[A]??null));return vt(i,l,c,h.sortBy,s.partitionKey,d,s.rowId)},async rankPage(e,n,s={}){He(J(s.baseWhere,s.where),t,e,"rankPage");const u=z(e,"rankPage");if(u)return R(e,H),u.rankPage(e,n,s);F(e,n,"rank");const{continueCursor:h,hasMore:l,rows:c}=dt(at,e,n,s);return{continueCursor:h,isDone:!l,page:c.map(d=>d.doc)}},async rankPageRows(e,n,s={}){He(J(s.baseWhere,s.where),t,e,"rankPage"),F(e,n,"rank");const{directions:u,hasMore:h,rows:l}=dt(at,e,n,s);return{directions:u,hasMore:h,rows:l}},async restore(e,n){const s=ne(e,n);if(!s){const l=n===void 0?C:void 0;if(l?.restore){await l.restore(e);return}throw new y("INTERNAL",`document not found: ${e}`)}const u=t.tables[s.tableName]?.softDeleteMode?.field;if(!u)throw new y("INTERNAL",`ctx.db.restore: table "${s.tableName}" is not a .softDelete() table`);const h=s.row[u]!==null&&s.row[u]!==void 0;await U.patch(e,{[u]:null},n),h&&he(s.tableName,e,void 0,s.row)},async replace(e,n,s,u){const h=ne(e,s);if(!h){const x=s===void 0?C:void 0;if(x){M(n),await x.replace(e,n,void 0,u);return}throw new y("INTERNAL",`document not found: ${e}`)}const{docJson:l,row:c,tableName:d}=h,w=t.tables[d];if(!w)throw new y("INTERNAL",`unknown table: ${d}`);At("replace",n);const A=u?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:m(),p={...n,...E(d),_creationTime:A,_id:e};_t(w,n,p,O),Ne(w,p),Z(d,"before","update")&&await ee("before","update",{doc:{...p},id:e,op:"update",previous:c,table:d}),ue(d),fe(d),Me(i,d,r`UPDATE ${r.identifier(d)} SET _creationTime = ${A}, ${r.identifier(K)} = ${se(p)} WHERE id = ${e} AND ${r.identifier(K)} = ${l}`),me(d,e,p,c),Ee(d,e,p),ye(d,c,p),he(d,e,c,p),j?.invalidate(d,e,T(d,c,p)),le(d,e,"update",p),a({indexKeys:T(d,c,p),key:e,op:"update",row:p,table:d}),Z(d,"after","update")&&await ee("after","update",{doc:p,id:e,op:"update",previous:c,table:d}),await N({doc:p,id:e,op:"update",table:d})},async wipeShard(e){const n=new Set(e?.exclude),s=e?.tables,u=Object.entries(t.tables).filter(([d,w])=>n.has(d)||s!==void 0&&!s.includes(d)?!1:w.shardMode?.kind!=="global").map(([d])=>d);if(s!==void 0){for(const d of s)if(!t.tables[d])throw new y("INTERNAL",`wipeShard: unknown table: ${d}`)}const h={};let l=0;const{deleteAll:c}=U;if(c===void 0)throw new y("INTERNAL","wipeShard: this writer has no deleteAll");for(const d of u){const w=await c(d,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[d]=w.deleted,l+=w.deleted}return{deleted:l,tables:h}}},Pt={db:U,scheduler:k};return o.enforceRls===!0?mn(U,t,(e,n)=>ne(e,n)?.tableName,(e,n)=>Ut(e,n)):U};export{zr as CDC_LOG_TABLE,fo as CLIENT_WATERMARK_TABLE,$o as GLOBAL_SHAPE_SNAPSHOT_TABLE,_o as IDEMPOTENCY_TABLE,or as NotUniqueError,bo as SEARCH_STATE_TABLE,ho as advanceClientWatermark,Jr as applyCdcChanges,Un as assertValidClientId,jr as backfillAggregateIndexes,Kr as backfillRankIndexes,Or as backfillSearchIndexes,Vr as bumpCdcEpoch,Yr as cdcCanVouchFor,Xr as cdcSeqLeavingRows,Zr as cdcTouchesTables,eo as cdcTrimmedError,to as compactCdcDocs,Gr as createShardCtxDb,no as cursorBelowRetainedFloor,yo as deleteGlobalShapeSnapshot,Eo as deleteGlobalShapeSnapshotsForConnection,wo as migrateClientWatermark,mo as migrateGlobalShapeSnapshot,ro as minCdcReplayableSeq,oo as minCdcSeq,Rt as normalizeIdStructurally,io as readCdcChangeKeys,so as readCdcChanges,co as readCdcCursor,ao as readCdcEpoch,po as readClientWatermark,So as readGlobalShapeSnapshot,Ao as readIdempotent,xo as runShardMigrations,ko as selectShapeMembers,Lo as selectShapeRows,lo as trimCdcChanges,vo as trimIdempotent,Ro as writeGlobalShapeSnapshot,Io as writeIdempotent};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as R,i as k,
|
|
1
|
+
import{r as R,i as k,S as A,q as O,l as h,y as $,d as C}from"./ctx-db-companions-BQRTS_WY.mjs";import{sql as t}from"drizzle-orm";import{matchesStaticWhere as L}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as M,encodeAggregateKey as x,foldAggregateTally as N}from"./aggregateTableName-Cy5e03oz.mjs";import{migrateSearchState as _,readSearchBackfillState as F,writeSearchBackfillState as y}from"./SEARCH_STATE_TABLE-Dju8ebbU.mjs";import{runDrizzle as l}from"./runDrizzle-it6rL9bR.mjs";import{i as E,r as T,a as D,b as v,A as B,D as S,h as G}from"./do-sql-DbEszTyj.mjs";import{isLiveForCompanion as U}from"./applySelect-BQbHyo-W.mjs";import{rankTableName as P,matchesRankStaticWhere as W}from"./RANK_TIEBREAK-ci3MaM65.mjs";const H=(e,n)=>e.profile!==n?{cursor:void 0,finished:!1,wipe:e.cursor!==void 0||e.done}:{cursor:e.cursor,finished:e.done,wipe:!1},b=(e,n)=>l(e,t`SELECT COUNT(*) AS count FROM ${t.identifier(n)}`).one().count>0,p=(e,n)=>l(e,t`SELECT id, _creationTime, ${t.identifier(S)} FROM ${t.identifier(n)}`).toArray(),V=(e,n,r,o)=>{const i=M(n,r.name);if(b(e,i))return;const a=r.by??[],s=new Map,c=p(e,n);for(const d of c){const f=T(d);if(!f||!U(f,o)||r.where&&!L(f,r.where))continue;const g=x(a,f);N(s,g,r,f)}for(const[d,f]of s)l(e,t`INSERT INTO ${t.identifier(i)} (${D}, ${v}, ${B}) VALUES (${d}, ${f.value}, ${f.count})`)},ne=(e,n)=>{for(const[r,o]of Object.entries(n.tables))if(!(o.shardMode?.kind==="global"||!o.aggregateIndexes))for(const i of o.aggregateIndexes)V(e,r,i,o.softDeleteMode?.field)},Y=(e,n,r)=>{const o=P(n,r.name);if(b(e,o))return;const i=R(r),a=p(e,n);for(const s of a){const c=T(s);!c||r.where&&!W(c,r.where)||k(e,o,r,i,c._id,c)}},re=(e,n)=>{for(const[r,o]of Object.entries(n.tables))if(!(o.shardMode?.kind==="global"||!o.rankIndexes))for(const i of o.rankIndexes)Y(e,r,i)},m=500,w=(e,n,r)=>{const o=A(n,r.name),{profile:i}=O(r.language),a=H(F(e,o),i);if(a.finished)return{done:!0,rows:0};a.wipe&&l(e,t`DELETE FROM ${t.identifier(o)}`);const{cursor:s}=a,c=l(e,s===void 0?t`SELECT id, _creationTime, ${t.identifier(S)} FROM ${t.identifier(n)} ORDER BY id ASC LIMIT ${t.raw(String(m))}`:t`SELECT id, _creationTime, ${t.identifier(S)} FROM ${t.identifier(n)} WHERE id > ${s} ORDER BY id ASC LIMIT ${t.raw(String(m))}`).toArray();let d=s;for(const g of c){const{id:u}=g;if(typeof u!="string")continue;d=u,l(e,t`DELETE FROM ${t.identifier(o)} WHERE ${t.identifier(h)} = ${u}`);const I=G(g);I&&l(e,t`INSERT INTO ${t.identifier(o)} (${t.identifier($)}, ${t.identifier(h)}) VALUES (${C(I,r)}, ${u})`)}const f=c.length<m;return y(e,o,d,f,i),{done:f,rows:c.length}},te=(e,n,r)=>{if(E(e))for(const o of r.searchIndexes??[])o.staged||w(e,n,o)},j=(e,n,r,o)=>{let i=0;for(;;){if(i>=o)return{done:!1,pages:i};const a=w(e,n,r);if(a.rows>0&&(i+=1),a.done)return{done:!0,pages:i}}},ie=(e,n,r={})=>{if(!E(e))return{done:!0,pages:0};_(e);const o=r.maxPages??Number.POSITIVE_INFINITY;let i=0;for(const[a,s]of Object.entries(n.tables))if(!(s.shardMode?.kind==="global"||!s.searchIndexes))for(const c of s.searchIndexes){const d=j(e,a,c,o-i);if(i+=d.pages,!d.done)return{done:!1,pages:i}}return{done:!0,pages:i}};export{ne as backfillAggregateIndexes,re as backfillRankIndexes,ie as backfillSearchIndexes,te as backfillSearchIndexesForTable};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{quoteIdentifier as l}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as u}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{REPROJECTION_MIGRATION_PREFIX as v,reprojectionMigrationId as w}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{e as m}from"./wire-codec-BU9T2xJ7.mjs";import{runSql as p}from"./runDrizzle-it6rL9bR.mjs";import{k as d,D as E}from"./do-sql-
|
|
1
|
+
import{quoteIdentifier as l}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as u}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{REPROJECTION_MIGRATION_PREFIX as v,reprojectionMigrationId as w}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{e as m}from"./wire-codec-BU9T2xJ7.mjs";import{runSql as p}from"./runDrizzle-it6rL9bR.mjs";import{k as d,D as E}from"./do-sql-DbEszTyj.mjs";import{m as g}from"./sql-projection-BqmxFxQU.mjs";const b=m(0n)[0],_=e=>e.shardMode?.kind==="global"?[]:Object.entries(e.shape).filter(([,r])=>g(r)).map(([r])=>r),M=e=>Object.entries(e.tables).filter(([,r])=>_(r).length>0).map(([r])=>r),f=e=>{const r=`json_each(${l(E)}) AS __f__`;return{params:[JSON.stringify(e),b,"bigint","bytes"],sql:`EXISTS (SELECT 1 FROM ${r} WHERE __f__.type = 'array' AND __f__.key IN (SELECT value FROM json_each(?)) AND json_extract(__f__.value, '$[0]') = ? AND json_extract(__f__.value, '$[1]') IN (?, ?))`}},N=(e,r,o)=>{if(o.length===0)return 0;const{params:t,sql:n}=f(o);return p(e,`SELECT COUNT(*) AS count FROM ${l(r)} WHERE ${n}`,...t).toArray()[0]?.count??0},R=(e,r,o,t)=>{const{params:n,sql:i}=f(o);return p(e,`SELECT 1 FROM ${l(r)} WHERE id = ? AND (${i}) LIMIT 1`,t,...n).toArray().length>0},S=(e,r,o)=>{const t=u(e);if(t===void 0)return;const n=r.tables[t];if(!n)return;const i=_(n);if(i.length!==0)return{id:e,table:t,up:s=>{const a=s._id;if(!(typeof a!="string"||!R(o,t,i,a))){try{d(s)}catch(c){console.warn(`${e}: skipping row ${a} — it cannot be re-projected: ${c instanceof Error?c.message:String(c)}`);return}return s}}}};export{v as REPROJECTION_MIGRATION_PREFIX,S as buildReprojectionMigration,N as countLegacyRows,_ as reprojectableFields,w as reprojectionMigrationId,M as reprojectionTables};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-
|
|
1
|
+
import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-CW0wHEgW.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-C0vtU60D.mjs";import{shapeRangeKey as u}from"./ShapeDiffCache-mE7ZzdPr.mjs";import{projectColumns as g}from"./buildPokeFrames-BhYUbqzO.mjs";const C=(m,e,a,i,p,f=s)=>{const r=u(e.table,a,i),n=p.changedKeys(r,()=>f(m,e.table,a,i));if(n.length===0)return[];const b=p.members(e,r,()=>h(m,e.table,e.effectiveWhere,n.map(t=>t.id))),o=[];for(const t of n){const c=b.get(t.id);if(c===void 0){t.op!=="insert"&&o.push({key:t.id,op:"delete",table:e.table});continue}o.push({key:t.id,op:t.op,table:e.table,value:g(c,e.columns)})}return o};export{C as buildShapeDiff};
|
package/dist/packem_shared/{createCompanionSync-zCwaB6wj.mjs → createCompanionSync-Cfju9Ng2.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as l,i as C,r as R}from"./ctx-db-companions-
|
|
1
|
+
import{c as l,i as C,r as R}from"./ctx-db-companions-BQRTS_WY.mjs";import"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import"./aggregateTableName-Cy5e03oz.mjs";import"./runDrizzle-it6rL9bR.mjs";import"./do-sql-DbEszTyj.mjs";import"./param-Ib8WHnrF.mjs";import"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import"./applySelect-BQbHyo-W.mjs";import"./RANK_TIEBREAK-ci3MaM65.mjs";import"./sql-projection-BqmxFxQU.mjs";import"./serializeSqlValue-DbI1VQYM.mjs";export{l as createCompanionSync,C as insertRankRow,R as rankColumnsSql};
|
package/dist/packem_shared/{createReplicaLink-DZZxDW5c.mjs → createReplicaLink-Bv7250Ef.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{cursorBelowRetainedFloor as w}from"./CDC_LOG_TABLE-
|
|
1
|
+
import{cursorBelowRetainedFloor as w}from"./CDC_LOG_TABLE-CW0wHEgW.mjs";import{envPositiveInt as h}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{v as _,R as f,s as S,a as v,b as y}from"./sibling-channel-Cxvk0Zca.mjs";const A=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],N=new Set(A),T=s=>typeof s=="string"&&N.has(s),p="::replica::",R=s=>{const e=s.lastIndexOf(p);if(e===-1)return;const t=s.slice(0,e),r=s.slice(e+p.length);if(!(t.length===0||!T(r)))return{ownerKey:t,region:r}},L=s=>{if(s==null||!/^\d+$/.test(s))return;const e=Number.parseInt(s,10);return Number.isSafeInteger(e)&&e>0?e:void 0},O=1e3,g=1e3,b=10,I=5e4,m=s=>h(s,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",I),c="__replica_state",u=new WeakSet,E=s=>{u.has(s)||(s.exec(`CREATE TABLE IF NOT EXISTS ${c} (
|
|
2
2
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
3
3
|
epoch TEXT NOT NULL,
|
|
4
4
|
applied_seq INTEGER NOT NULL,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{matchesStaticWhere as P,aggregateSqlFunction as le}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as N,encodeAggregateKey as I,foldAggregateTally as J,coerceAggregateNumber as C}from"./aggregateTableName-Cy5e03oz.mjs";import{runDrizzle as $}from"./runDrizzle-it6rL9bR.mjs";import{i as fe,g as ue,D,r as M,a as q,b as S,A as g,c as j,e as z}from"./do-sql-DbEszTyj.mjs";import{param as de,WORKERD_SQLITE_LIMITS as $e}from"./param-Ib8WHnrF.mjs";import{encodeGeohash as me,GEO_DEFAULT_PRECISION as Ee}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as Q}from"./applySelect-BQbHyo-W.mjs";import{encodePartitionKey as pe,sortColumnName as he,rankTableName as Z,matchesRankStaticWhere as x}from"./RANK_TIEBREAK-ci3MaM65.mjs";import{m as ge}from"./sql-projection-BqmxFxQU.mjs";import{serializeSqlValue as ee}from"./serializeSqlValue-DbI1VQYM.mjs";const ye=["de","en","es","fr","it","nl","none","pt"],_e=n=>ye.includes(n),Se="a an and are as at be but by for if in into is it no not of on or such that the their then there these they this to was will with",we="aber als am an auch auf aus bei bin bis bist da dass der den des dem die das denn dir du ein eine für hat ich im in ist mit nicht noch nur oder sich sie sind über und von vor war wie wir zu zum zur",Te="a al como con de del el en es la las lo los mas no o para pero por que se su sus un una uno y ya",ve="au aux avec ce ces dans de des du elle en et eux il je la le les leur lui ma mais me même mes moi mon ne nos notre nous on ou par pas pour qu que qui sa se ses son sur ta te tes toi ton tu un une vos votre vous y",Re="a ai al alla anche che chi ci coi col come con da dal degli dei del della di do e ed gli ha hai hanno i il in la le lo ma mi ne nei nel non o per più quale quanto se si sono su sul tra un una uno vi",Ae="aan al als bij dan dat de der deze die dit door een en er het hij ij in is je kan me men met mij na naar niet nog nu of om ons ook op over te tot uit van voor was wat we wij zij zijn zo",Fe="a ao aos as até com como da das de do dos e em entre era essa esse esta este eu foi há isso já mais mas me mesmo meu na nas no nos num numa o os ou para pela pelo por qual que quem se sem seu só sua também te tem um uma você",be=/[\u0300-\u036F]/gu,Oe=/[\u0080-\u{10FFFF}]/u,Le=/[\p{L}\p{N}]+/gu,oe=n=>Oe.test(n)?n.normalize("NFD").replaceAll(be,"").normalize("NFC").toLowerCase():n.toLowerCase(),k=n=>new Set(oe(n).split(" ")),Ie={de:k(we),en:k(Se),es:k(Te),fr:k(ve),it:k(Re),nl:k(Ae),none:new Set,pt:k(Fe)},ke=2,qe=256,X=new Map,Ce=n=>{const s=n!==void 0&&_e(n)?n:"none",c=X.get(s);if(c)return c;const w=Ie[s],y=r=>{const A=(oe(r).match(Le)??[]).filter(T=>T.length<=qe);return w.size===0?A:A.filter(T=>!w.has(T))},E={document:y,profile:`${s}-v${String(ke)}`,query:r=>{const A=y(r);return A.filter((T,b)=>A.lastIndexOf(T)===b)}};return X.set(s,E),E},je=(n,s)=>{if(!s.includes("."))return n[s];let c=n;for(const w of s.split(".")){if(c===null||typeof c!="object"||Array.isArray(c))return;c=c[w]}return c},De=(n,s)=>`${n}__fts_${s}`,Me="__text__",Y="__id__",ze=1e3,Ue=(n,s)=>s.document(n),U=(n,s)=>je(n,s),We=n=>typeof n=="string"?n:n==null?"":typeof n=="number"||typeof n=="bigint"||typeof n=="boolean"?String(n):JSON.stringify(n)??"",He=(n,s,c)=>n!==void 0&&s!==void 0&&U(n,c.field)===U(s,c.field),Be=(n,s)=>Ue(We(U(n,s.field)),Ce(s.language)).slice(0,ze),Ke=(n,s)=>Be(n,s).join(" "),Ve=(n,s,c)=>[...n.partitionBy??[],...n.sortBy.map(y=>y.field),...n.where?Object.keys(n.where):[]].every(y=>s[y]===c[y]),ne=n=>e.join(["__id__","__partition__",...n.sortBy.map((s,c)=>he(c))].map(s=>e.identifier(s)),e`, `),te=(n,s,c,w,y,E)=>{const r=pe(c.partitionBy??[],E),A=c.sortBy.map(b=>ee(E[b.field]??null)),T=e.join([y,r,...A].map(b=>de(b)),e`, `);$(n,e`INSERT INTO ${e.identifier(s)} (${w}) VALUES (${T})`)},Ge=(n,s,c,w,y,E)=>{if(y&&E&&Ve(c,y,E))return;const r=Z(s,c.name);y&&$(n,e`DELETE FROM ${e.identifier(r)} WHERE ${e.identifier("__id__")} = ${w}`),!(!E||c.where&&!x(E,c.where))&&te(n,r,c,ne(c),w,E)},so=n=>{const{broadcast:s,indexKeysFor:c,invalidateCache:w,recordCdc:y,schema:E,sql:r}=n,A=new Set,T=t=>E.tables[t]?.softDeleteMode?.field,b=new Set,W=(t,o)=>{const a=`${t}::${o.name}`;if(A.has(a))return;const f=N(t,o.name),u=o.by??[],d=T(t),p=new Map,_=$(r,e`SELECT id, _creationTime, ${e.identifier(D)} FROM ${e.identifier(t)}`).toArray();for(const v of _){const m=M(v);if(!m||!Q(m,d)||o.where&&!P(m,o.where))continue;const R=I(u,m);J(p,R,o,m)}$(r,e`DELETE FROM ${e.identifier(f)}`);const F=Math.floor($e.boundParams/3),O=[...p];for(let v=0;v<O.length;v+=F){const m=O.slice(v,v+F),R=e.join(m.map(([i,l])=>e`(${i}, ${l.value}, ${l.count})`),e`, `);$(r,e`INSERT INTO ${e.identifier(f)} (${q}, ${S}, ${g}) VALUES ${R}`)}A.add(a)},se=(t,o,a)=>{const f=o.by??[],u=o.field??"",d=[],p=(i,l)=>{const h=ee(l);h===null?d.push(e`${z(i)} IS NULL`):d.push(e`${z(i)} = ${h}`)};for(const i of f)p(i,a[i]??null);const _=T(t);_!==void 0&&p(_,null);for(const[i,l]of Object.entries(o.where??{}))p(i,l!==null&&typeof l=="object"&&!Array.isArray(l)?l.eq:l);const F=d.length>0?e` WHERE ${e.join(d,e` AND `)}`:e``,O=E.tables[t]?.shape[u];if(O&&ge(O)){const i=$(r,e`SELECT id, _creationTime, ${e.identifier(D)} FROM ${e.identifier(t)}${F}`).toArray(),l=new Map;for(const h of i){const L=M(h);L&&J(l,"",o,L)}return{value:l.get("")?.value??null}}const v=le(o.op),m=z(u);return{value:$(r,e`SELECT ${e.raw(v)}(${m}) AS value FROM ${e.identifier(t)}${F}`).one().value??null}},ie=(t,o,a,f)=>{const u=N(t,o.name),{op:d}=o,p=o.field??"",_=i=>{$(r,e`DELETE FROM ${e.identifier(u)} WHERE ${q} = ${i} AND ${g} <= 0`)},F=T(t),O=i=>!o.where||P(i,o.where),v=i=>Q(i,F)&&O(i);f!==void 0&&d!=="count"&&O(f)&&C(f[p]);const m=a&&v(a)?a:void 0,R=f&&v(f)?f:void 0;if(!(!m&&!R)){if(d==="count"){for(const[i,l]of[[m,-1],[R,1]]){if(!i)continue;const h=I(o.by??[],i);$(r,j(u,h,l,l,e`${S} = ${S} + excluded.${S}, ${g} = ${g} + excluded.${g}`))}m&&_(I(o.by??[],m));return}if(d==="sum"||d==="avg"){for(const[i,l]of[[m,-1],[R,1]]){if(!i)continue;const h=C(i[p]);if(h===void 0)continue;const L=I(o.by??[],i);$(r,j(u,L,l*h,l,e`${S} = COALESCE(${S}, 0) + excluded.${S}, ${g} = ${g} + excluded.${g}`))}m&&_(I(o.by??[],m));return}if(m){const i=I(o.by??[],m),l=C(m[p]),h=$(r,e`SELECT ${S} AS value, ${g} AS count FROM ${e.identifier(u)} WHERE ${q} = ${i}`).toArray()[0],L=(h?.count??0)-1;if(L<=0)$(r,e`DELETE FROM ${e.identifier(u)} WHERE ${q} = ${i}`);else if(h&&l!==void 0&&h.value!==null&&l===h.value){const ce=se(t,o,m);$(r,e`UPDATE ${e.identifier(u)} SET ${S} = ${ce.value}, ${g} = ${L} WHERE ${q} = ${i}`)}else $(r,e`UPDATE ${e.identifier(u)} SET ${g} = ${g} - 1 WHERE ${q} = ${i}`)}if(R){const i=I(o.by??[],R),l=C(R[p]);if(l===void 0)$(r,j(u,i,null,1,e`${g} = ${g} + 1`));else{const h=d==="min"?"MIN":"MAX";$(r,j(u,i,l,1,e`${S} = ${e.raw(h)}(COALESCE(${S}, excluded.${S}), excluded.${S}), ${g} = ${g} + 1`))}}}},re=t=>{for(const o of E.tables[t]?.aggregateIndexes??[])W(t,o)},H=(t,o,a)=>{for(const f of E.tables[t]?.aggregateIndexes??[])ie(t,f,o,a)},B=(t,o)=>{const a=`${t}::rank::${o.name}`;if(b.has(a))return;const f=Z(t,o.name),u=$(r,e`SELECT id, _creationTime, ${e.identifier(D)} FROM ${e.identifier(t)}`).toArray();$(r,e`DELETE FROM ${e.identifier(f)}`);const d=ne(o);for(const p of u){const _=M(p);!_||o.where&&!x(_,o.where)||te(r,f,o,d,_._id,_)}b.add(a)},ae=t=>{for(const o of E.tables[t]?.rankIndexes??[])B(t,o)},K=(t,o,a,f)=>{for(const u of E.tables[t]?.rankIndexes??[])Ge(r,t,u,o,a,f)},V=(t,o,a,f)=>{const u=E.tables[t]?.searchIndexes??[];if(!(u.length===0||!fe(r)))for(const d of u){if(He(f,a,d))continue;const p=De(t,d.name);$(r,e`DELETE FROM ${e.identifier(p)} WHERE ${e.identifier(Y)} = ${o}`),a&&$(r,e`INSERT INTO ${e.identifier(p)} (${e.identifier(Me)}, ${e.identifier(Y)}) VALUES (${Ke(a,d)}, ${o})`)}},G=(t,o,a)=>{for(const f of E.tables[t]?.geoIndexes??[]){const u=ue(t,f.name);$(r,e`DELETE FROM ${e.identifier(u)} WHERE ${e.identifier("__id__")} = ${o}`);const d=a?.[f.field];if(d!==null&&typeof d=="object"&&typeof d.lat=="number"&&typeof d.lng=="number"){const{lat:p,lng:_}=d,F=me({lat:p,lng:_},f.precision??Ee);$(r,e`INSERT INTO ${e.identifier(u)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${o}, ${F}, ${p}, ${_})`)}}};return{ensureBackfilledForTable:re,ensureBackfilledIndex:W,ensureRankBackfilled:B,ensureRankBackfilledForTable:ae,syncAggregates:H,syncCompanionsForInsert:(t,o,a)=>{V(t,o,a),G(t,o,a),H(t,void 0,a),K(t,o,void 0,a),w(t,o,a),y(t,o,"insert",a),s({indexKeys:c(t,a),key:o,op:"insert",row:a,table:t})},syncGeo:G,syncRanks:K,syncSearch:V}};export{De as S,Be as a,so as c,Ke as d,te as i,Y as l,Ce as q,ne as r,Me as y};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createShardCtxDb as S}from"./NotUniqueError-
|
|
1
|
+
import{createShardCtxDb as S}from"./NotUniqueError-Dnik6z41.mjs";import{createRelayLink as B}from"./DEFAULT_MAX_RELAYS-BPv7jVgK.mjs";import{ConflictError as I}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as v}from"./runShardMigrations-DFc_LoP-.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-H2sHFvlw.mjs";const _=(E,u={})=>({_meta:{column:{notNull:!0,...u}},kind:E}),D=(E,u,N)=>{const{describe:k,expect:i,it:m}=N;k(`engine contract: ${E}`,()=>{k("optimistic concurrency",()=>{const b=h=>({tables:{items:{indexes:[],shape:{title:_("string"),version:_("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{h.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});m("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({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(I)}finally{h?.()}}),m("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;i(e.code).toBe("CONFLICT"),i(e.kind).toBe("occ")}finally{h?.()}}),m("leaves the row readable and unchanged after a conflict",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({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 a=await s.get("i1");i(a?.title).toBe("first"),i(a?.version).toBe(99)}finally{h?.()}}),m("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l={tables:{items:{indexes:[],shape:{title:_("string"),version:_("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=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;i(e).toBeInstanceOf(I),i(e.code).toBe("CONFLICT"),i(e.kind).toBe("trigger")}finally{h?.()}})}),k("shape-poke ordering",()=>{const b="shard-a",h={args:{},name:"messages"},d=(e,t,o,n)=>e.accept(t?.()??{},{connectionId:o,shapes:{[n]:h}}),c=(e,t)=>{let o=0,n=0;const r=g=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${g}`)},p={fetch:(g,O)=>{if(JSON.parse(O?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const C=t[n];if(n+=1,C===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(C))}},y={get:()=>p,getByName:()=>p,idFromName:g=>g},w={buildShapeDiff:r("buildShapeDiff"),computeOpLogShapeSeed:r("computeOpLogShapeSeed"),currentCdcEpoch:r("currentCdcEpoch"),deliverWhisperLocal:r("deliverWhisperLocal"),doName:()=>F(b,0),env:()=>({SHARD:y}),getWebSockets:()=>e.getSockets(),maskMetadata:r("maskMetadata"),nextPokeId:()=>(o+=1,`poke-${String(o)}`),readAttachment:g=>g.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:r("resolveShape"),rlsMetadata:r("rlsMetadata"),shardBinding:()=>"SHARD",sql:r("sql")},f=B(w);if(f===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return f},l=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,o)=>{const n=await e.seedRelayShape(t,o,h,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},a=(e={})=>l({...h,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});m("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1");await s(r,p,"s1"),await r.handleControl(a());const w=(await o(p)).map(f=>JSON.parse(f));i(w.map(f=>f.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),i(new Set(w.map(f=>f.pokeId)).size).toBe(1),i(w[1]?.shapeId).toBe("s1"),i(w[2]?.checkpoint).toBe(20)}finally{e?.()}}),m("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1"),y=d(n,t,"c-bob","s2");await s(r,p,"s1"),await s(r,y,"s2"),await r.handleControl(a());const w=await o(p);i(w.length).toBe(3);const f=await o(y);i(f.length).toBe(0),await r.handleControl(a());const g=await o(p);i(g.length).toBe(3)}finally{e?.()}}),m("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1");await s(r,p,"s1"),await r.handleControl(a({epoch:"e2"}));const y=await o(p);i(y.length).toBe(0),await r.handleControl(a());const w=await o(p);i(w.length).toBe(3)}finally{e?.()}})}),k("RLS identity under live subscription",()=>{const b="shard-a",h={args:{},name:"lobby-messages"},d={args:{},name:"my-orders"},c=s=>{const a=[],e=[],t={fetch:(r,p)=>(a.push(JSON.parse(p?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=B({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>b,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:r=>r}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(r,p,y)=>(e.push(y),r===d.name?{columns:["id"],effectiveWhere:{org:y?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:a,resolvedUnder:e}},l=async(s,a)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...a,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};m("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:a}=u();try{const{owner:e,resolvedUnder:t}=c(a.sql);await l(e,d),i(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),m("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:a}=u();try{const{owner:e,posts:t}=c(a.sql);await l(e,d),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),m("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:a}=u();try{const{owner:e,posts:t}=c(a.sql);await l(e,h),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{D as defineEngineContractSuite};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as c}from"@lunora/errors";import{sql as n}from"drizzle-orm";import{quoteIdentifier as A}from"./quoteIdentifier-CObIFRhb.mjs";import{d as E,e as T}from"./wire-codec-BU9T2xJ7.mjs";import{runDrizzle as _}from"./runDrizzle-it6rL9bR.mjs";import{s as $}from"./sql-projection-BqmxFxQU.mjs";import"./serializeSqlValue-DbI1VQYM.mjs";const p=/^[A-Za-z_$][\w$]*$/u,S=e=>p.test(e)?e:`"${e.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,u="__doc__",i="__originals__",v=e=>{if(Object.hasOwn(e,i))throw new c("BAD_REQUEST",`"${i}" is reserved by the row store's document encoding and cannot be used as a field name — rename the field`);let t,r;for(const[o,s]of Object.entries(e)){const a=$(s);a!==void 0&&(t??={...e},r??=Object.create(null),t[o]=a,r[o]=s)}t&&r&&(t[i]=r);try{return JSON.stringify(T(t??e))}catch(o){throw new c("BAD_REQUEST",`this document cannot be stored: ${o instanceof Error?o.message:String(o)}`)}},O=e=>{const t=E(JSON.parse(e)),{[i]:r,...o}=t;return r===null||typeof r!="object"||Array.isArray(r)?t:{...o,...r}},P=(e,t)=>`${e}__geo_${t}`,m=(e,t)=>t==="_id"||t==="id"?`${e}id`:t==="_creationTime"?`${e}_creationTime`:`json_extract(${e}${u}, '$.${S(t).replaceAll("'","''")}')`,b=e=>m("",e),R=e=>n.raw(b(e)),h=(e,t)=>m(`${A(e)}.`,t),G=(e,t)=>n.raw(h(e,t)),q=(e,t,r,o)=>n`CREATE ${o?n`UNIQUE `:n``}INDEX IF NOT EXISTS ${n.identifier(e)} ON ${n.identifier(t)} (${r})`,l=n.identifier("__key__"),g=n.identifier("__value__"),N=n.identifier("__count__"),B=(e,t,r,o,s)=>n`INSERT INTO ${n.identifier(e)} (${l}, ${g}, ${N}) VALUES (${t}, ${r}, ${o}) ON CONFLICT(${l}) DO UPDATE SET ${s}`,f=new WeakMap,J=e=>{const t=f.get(e);if(t!==void 0)return t;const r=[];for(const[o,s]of Object.entries(e.shape)){const a=s._meta?.column;a&&r.push(Object.freeze([o,a]))}return Object.freeze(r),f.set(e,r),r},y=e=>{if(!e)return;const t=e[u];let r;typeof t=="string"?r=O(t):t&&typeof t=="object"?r=t:r={};const{id:o}=e;typeof o=="string"&&(r._id=o);const s=e._creationTime;return typeof s=="number"&&(r._creationTime=s),r},z=e=>{try{return y(e)}catch{return}},d=new WeakMap,F=e=>{const t=d.get(e);if(t!==void 0)return t;let r;try{_(e,n`CREATE VIRTUAL TABLE IF NOT EXISTS ${n.identifier("__lunora_fts_probe")} USING fts5(x)`),r=!0}catch{r=!1}finally{try{_(e,n`DROP TABLE IF EXISTS ${n.identifier("__lunora_fts_probe")}`)}catch{}}return d.set(e,r),r};export{N as A,u as D,l as a,g as b,B as c,q as d,R as e,G as f,P as g,z as h,F as i,b as j,v as k,O as l,S as m,i as n,h as q,y as r,J as t};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-it6rL9bR.mjs";import{liftSourceId as A}from"./liftSourceId-CA3ENhXj.mjs";import{normalizeSourceValue as W}from"./liftSourceId-CA3ENhXj.mjs";import{runExternalSourceTick as C,materializeExternalRowsIncremental as D}from"./materializeExternalRows-
|
|
1
|
+
import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-it6rL9bR.mjs";import{liftSourceId as A}from"./liftSourceId-CA3ENhXj.mjs";import{normalizeSourceValue as W}from"./liftSourceId-CA3ENhXj.mjs";import{runExternalSourceTick as C,materializeExternalRowsIncremental as D}from"./materializeExternalRows-CX55UoV7.mjs";const p="__lunora_source_cursor",M=e=>e instanceof Date?`d:${e.toISOString()}`:typeof e=="bigint"?`b:${e.toString()}`:typeof e=="number"?`n:${e.toString()}`:`s:${e}`,v=e=>{const t=e.slice(2);switch(e[0]){case"b":return BigInt(t);case"d":return new Date(t);case"n":return Number(t);default:return t}},h=/^-?\d+$/,N=/^-?\d+(?:\.\d+)?$/,x=(e,t)=>e instanceof Date&&t instanceof Date?e.getTime()>t.getTime():typeof e=="bigint"&&typeof t=="bigint"||typeof e=="number"&&typeof t=="number"?e>t:typeof e=="string"&&typeof t=="string"&&N.test(e)&&N.test(t)?h.test(e)&&h.test(t)?BigInt(e)>BigInt(t):Number(e)>Number(t):String(e)>String(t),O=(e,t,o)=>{let n=o===null?void 0:v(o);for(const r of e){const c=r[t];if(c==null)continue;const a=c;(n===void 0||x(a,n))&&(n=a)}return n===void 0?null:M(n)},B=e=>{S(e,m`CREATE TABLE IF NOT EXISTS ${m.identifier(p)} (
|
|
2
2
|
table_name TEXT NOT NULL,
|
|
3
3
|
shard_key TEXT NOT NULL,
|
|
4
4
|
watermark TEXT,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{applyCdcChanges as p}from"./CDC_LOG_TABLE-
|
|
1
|
+
import{applyCdcChanges as p}from"./CDC_LOG_TABLE-CW0wHEgW.mjs";import{selectShapeRows as m}from"./selectShapeMembers-C0vtU60D.mjs";import{diffExternalSource as g,projectExternalSourceRow as l}from"./diffExternalSource-DbHrcoZK.mjs";import{stableStringify as d}from"./stableStringify-G9OF5wcs.mjs";const x=async(t,s,a,e)=>{const{changes:o,nextBaseline:n}=g(s,a,e);return await p(t,o),{applied:o.length,nextBaseline:n}},R=async(t,s,a)=>{const{columns:e,deletedIds:o,table:n}=a,r=[];for(const f of s){const i=l(f,e),c=String(i._id);if(o?.has(c)){await t.get(c,n)&&r.push({id:c,op:"delete",seq:0,table:n,ts:0});continue}const u=await t.get(c,n);u&&d(l({...u,_id:c},e))===d(i)||r.push({doc:i,id:c,op:"insert",seq:0,table:n,ts:0})}return await p(t,r),{applied:r.length}},h=(t,s,a)=>{const e=new Map;for(const{doc:o,id:n}of m(t,s,void 0))e.set(n,d(l({...o,_id:n},a)));return e},_=async(t,s,a,e)=>{const o=h(t,e.table,e.columns);return x(s,a,o,e)};export{x as materializeExternalRows,R as materializeExternalRowsIncremental,h as readExternalSourceBaseline,_ as runExternalSourceTick};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{S,y as L,l as N}from"./ctx-db-companions-BQRTS_WY.mjs";import{sql as e}from"drizzle-orm";import{aggregateTableName as p}from"./aggregateTableName-Cy5e03oz.mjs";import{backfillSearchIndexesForTable as u}from"./backfillAggregateIndexes-C9wGiPH4.mjs";import{migrateCdcLog as h,migrateCdcMeta as R}from"./CDC_LOG_TABLE-CW0wHEgW.mjs";import{migrateClientWatermark as x}from"./CLIENT_WATERMARK_TABLE-BoS1HEqz.mjs";import{migrateCommitSeq as C}from"./COMMIT_SEQ_FIELD-CSe_oNZu.mjs";import{migrateGlobalShapeSnapshot as O}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-NWaL77m5.mjs";import{migrateIdempotency as b}from"./IDEMPOTENCY_TABLE-DKVe2Ohf.mjs";import{m as U}from"./ctx-db-relay-shapes-Jf5xpD1r.mjs";import{migrateSearchState as l}from"./SEARCH_STATE_TABLE-Dju8ebbU.mjs";import{migrateShapePokeCursor as $}from"./SHAPE_POKE_CURSOR_TABLE-BBuXXk5v.mjs";import{runDrizzle as a}from"./runDrizzle-it6rL9bR.mjs";import{D as X,e as T,d,t as G,i as D,g as B,a as M,b as k,A as E}from"./do-sql-DbEszTyj.mjs";import{migrateDurableStreams as F}from"./appendStreamChunk-CH4e4nJn.mjs";import{rankTableName as Y,sortColumnName as P}from"./RANK_TIEBREAK-ci3MaM65.mjs";import{migrateReactorState as j}from"./REACTOR_STATE_TABLE-Cr9Orfp8.mjs";import{recordSchemaVersion as y}from"./SCHEMA_HISTORY_MAX_VERSIONS-DsycDXWm.mjs";const v=(r,n,o)=>{for(const i of o.indexes){const t=`${n}_${i.name}`,m=e.join(i.fields.map(s=>T(s)),e`, `);a(r,d(t,n,m,i.unique??!1))}for(const[i,t]of G(o)){if(!t.unique)continue;const m=`${n}_unique_${i}`;a(r,d(m,n,T(i),!0))}},K=(r,n,o)=>{if(!(!o.searchIndexes||o.searchIndexes.length===0||!D(r))){for(const i of o.searchIndexes){const t=S(n,i.name);a(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(t)} USING fts5(${e.identifier(L)}, ${e.identifier(N)} UNINDEXED)`),a(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${t}__vocab`)} USING fts5vocab(${e.identifier(t)}, ${e.raw("instance")})`)}u(r,n,o)}},V=(r,n,o)=>{if(o.geoIndexes)for(const i of o.geoIndexes){const t=B(n,i.name);a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__geohash__")} TEXT NOT NULL, ${e.identifier("__lat__")} REAL NOT NULL, ${e.identifier("__lng__")} REAL NOT NULL)`);const m=`${n}__geo_${i.name}__btree`;a(r,d(m,t,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},w=(r,n,o)=>{if(o.aggregateIndexes)for(const i of o.aggregateIndexes){const t=p(n,i.name);a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${M} TEXT PRIMARY KEY, ${k} REAL, ${E} INTEGER NOT NULL DEFAULT 0)`),a(r,e`PRAGMA table_info(${e.identifier(t)})`).toArray().some(s=>s.name==="__count__")||a(r,e`ALTER TABLE ${e.identifier(t)} ADD COLUMN ${E} INTEGER NOT NULL DEFAULT 0`)}},z=(r,n,o)=>{if(o.rankIndexes)for(const i of o.rankIndexes){const t=Y(n,i.name),m=i.sortBy.map((f,_)=>P(_)),s=m.map(f=>e`${e.identifier(f)} BLOB`),g=s.length>0?e`, ${e.join(s,e`, `)}`:e``;a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${g})`);const c=[e`${e.identifier("__partition__")} ASC`];for(const[f,_]of m.entries()){const I=i.sortBy[f]?.direction;c.push(e`${e.identifier(_)} ${e.raw(I==="desc"?"DESC":"ASC")}`)}c.push(e`${e.identifier("__id__")} ASC`);const A=`${n}__rank_${i.name}__btree`;a(r,d(A,t,e.join(c,e`, `),!1))}},_e=(r,n,o={})=>{o.schemaSnapshot!==void 0&&y(r,o.schemaSnapshot.hash,o.schemaSnapshot.json),l(r);for(const[i,t]of Object.entries(n.tables))t.shardMode?.kind!=="global"&&(a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(i)} (
|
|
2
|
+
id TEXT PRIMARY KEY,
|
|
3
|
+
_creationTime REAL NOT NULL,
|
|
4
|
+
${e.identifier(X)} TEXT NOT NULL
|
|
5
|
+
)`),v(r,i,t),K(r,i,t),V(r,i,t),w(r,i,t),z(r,i,t));o.cdc&&(h(r),R(r),x(r),$(r),U(r)),Object.values(n.tables).some(i=>i.commitOrderedMode===!0)&&C(r),j(r),b(r),O(r),F(r)};export{_e as runShardMigrations};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as o}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-it6rL9bR.mjs";import{e}from"./do-sql-
|
|
1
|
+
import{sql as o}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-it6rL9bR.mjs";import{e}from"./do-sql-DbEszTyj.mjs";const E=(s,t,f,r)=>{const d=f-(t.after??0),i=[o`${e(t.field)} IS NOT NULL`,o`${e(t.field)} < ${d}`];t.softDeleteField!==void 0&&i.push(o`${e(t.softDeleteField)} IS NULL`);const l=o`SELECT id FROM ${o.identifier(t.table)} WHERE ${o.join(i,o` AND `)} LIMIT ${o.raw(String(Math.max(0,Math.floor(r))+1))}`,n=h(s,l).toArray(),a=n.length>r,$=n.slice(0,r).map(c=>c.id);return{hasMore:a,ids:$}};export{E as selectExpiredIds};
|
package/dist/packem_shared/{selectShapeMembers-GfRzwoVo.mjs → selectShapeMembers-C0vtU60D.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-it6rL9bR.mjs";import{D as p,r as d,e as h}from"./do-sql-
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-it6rL9bR.mjs";import{D as p,r as d,e as h}from"./do-sql-DbEszTyj.mjs";import{sqliteInList as w}from"./param-Ib8WHnrF.mjs";import{compileWhereSql as S}from"./compileWhereSql-JBpSfQm9.mjs";import{serializeSqlValue as $}from"./serializeSqlValue-DbI1VQYM.mjs";const C={fieldRef:h,serialize:$},g=o=>{if(o.length!==0)return w(e`${e.identifier("id")}`,o,!1)},u=(o,i)=>{const r=[];i&&r.push(i);const t=S(o,C);return t&&r.push(t),r.length===0?e``:e` WHERE ${e.join(r,e` AND `)}`},v=(o,i,r)=>{const t=u(r,void 0),n=a(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${t}`).toArray(),f=[];for(const l of n){const s=d(l),{id:c}=l;s!==void 0&&typeof c=="string"&&f.push({doc:s,id:c})}return f},z=(o,i,r,t)=>{const n=new Map;if(t.length===0)return n;const f=u(r,g(t)),l=a(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${f}`).toArray();for(const s of l){const c=d(s),{id:m}=s;c!==void 0&&typeof m=="string"&&n.set(m,c)}return n};export{z as selectShapeMembers,v as selectShapeRows};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/shard-engine",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.40",
|
|
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 y}from"@lunora/errors";import{s as Ht,c as Nt,j as Je,a as jt,y as Ae,h as Kt}from"./ctx-db-companions-lTt-rvKG.mjs";import{sql as r}from"drizzle-orm";import{d as Ot}from"./wire-codec-BU9T2xJ7.mjs";import{throwingScheduler as Qt,aggregateSqlFunction as ve,normalizeCountArgument as zt}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as qe,encodeAggregateKey as Be,readAggregateValue as Ue}from"./aggregateTableName-Cy5e03oz.mjs";import{mergeWhere as J,CountRlsUnsupportedError as Pe,selectIndexForGroupBy as Jt,selectIndexForCount as Vt,selectIndexForAggregate as Yt}from"./CountRlsUnsupportedError-Bdfupt3g.mjs";import{backfillSearchIndexesForTable as Xt}from"./backfillAggregateIndexes-DDgDYJcc.mjs";import{backfillAggregateIndexes as Kr,backfillRankIndexes as Or,backfillSearchIndexes as Qr}from"./backfillAggregateIndexes-DDgDYJcc.mjs";import{appendCdcChange as Zt}from"./CDC_LOG_TABLE-VfPoURHu.mjs";import{CDC_LOG_TABLE as Jr,applyCdcChanges as Vr,bumpCdcEpoch as Yr,cdcCanVouchFor as Xr,cdcSeqLeavingRows as Zr,cdcTouchesTables as eo,cdcTrimmedError as to,compactCdcDocs as no,cursorBelowRetainedFloor as ro,minCdcReplayableSeq as oo,minCdcSeq as io,readCdcChangeKeys as so,readCdcChanges as co,readCdcCursor as ao,readCdcEpoch as lo,trimCdcChanges as uo}from"./CDC_LOG_TABLE-VfPoURHu.mjs";import{allocateCommitSeq as en,COMMIT_SEQ_FIELD as tn}from"./COMMIT_SEQ_FIELD-CSe_oNZu.mjs";import{isMemoryTable as nn}from"./clearMemoryTables-CXULwypv.mjs";import{computeRankPage as dt}from"./computeRankPage-Bby1Npkd.mjs";import{SCAN_DEP as H}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as B}from"./runDrizzle-it6rL9bR.mjs";import{D as K,k as se,r as de,b as Ie,A as Ge,a as Ce,e as V,t as It,f as lt,i as rn,h as Ct,g as on}from"./do-sql-Dk_DJxn4.mjs";import{WORKERD_SQLITE_LIMITS as xt,unionAll as Ke,sqliteInList as sn}from"./param-Ib8WHnrF.mjs";import{coveringGeohashes as cn,boundingBoxGeohashes as an,haversineMeters as dn,pointInBoundingBox as ln}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as un}from"./NotFoundError-BhF7FeFr.mjs";import{softDeleteScope as ae,normalizeOrderKeys as fn,buildSeekWhere as Mt,decodeCursor as Oe,applySelect as ut,encodeCursor as Qe,buildSeekBeforeWhere as hn}from"./applySelect-BQbHyo-W.mjs";import{rankTableName as ft,sortColumnName as ht,resolveRankPartition as wn,encodePartitionKey as pn,RANK_TIEBREAK as gn}from"./RANK_TIEBREAK-ci3MaM65.mjs";import{indexKeysForRow as $n,buildIndexRange as yn}from"./buildIndexRange-CBKQmHSS.mjs";import{assertFlatPredicate as He,resolveRelationPredicates as wt}from"./DEFAULT_MAX_RELATION_KEYS-BAWGIEvC.mjs";import{runRowValidators as Ne,resolveWith as pt,relationHooks as gt,applyOnDelete as En,fanOutScalarCounts as mn}from"./applyOnDelete-BlcwKjuO.mjs";import{guardWriter as Sn}from"./RLS_UNWRAP_SYMBOL-BWloGsd3.mjs";import{i as _n}from"./sql-projection-BqmxFxQU.mjs";import{createSystemReader as Rn}from"./createSystemReader-BtYeSMDb.mjs";import{ConflictError as pe}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as Tn}from"./hasTrigger-CjlwI4le.mjs";import{compileWhereSql as te}from"./compileWhereSql-JBpSfQm9.mjs";import{CLIENT_WATERMARK_TABLE as ho,advanceClientWatermark as wo,migrateClientWatermark as po,readClientWatermark as go}from"./CLIENT_WATERMARK_TABLE-BoS1HEqz.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as yo,deleteGlobalShapeSnapshot as Eo,deleteGlobalShapeSnapshotsForConnection as mo,migrateGlobalShapeSnapshot as So,readGlobalShapeSnapshot as _o,writeGlobalShapeSnapshot as Ro}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-NWaL77m5.mjs";import{IDEMPOTENCY_TABLE as Ao,readIdempotent as vo,trimIdempotent as Io,writeIdempotent as Co}from"./IDEMPOTENCY_TABLE-DKVe2Ohf.mjs";import{runShardMigrations as Mo}from"./runShardMigrations-C6JwX3Ie.mjs";import{SEARCH_STATE_TABLE as Do}from"./SEARCH_STATE_TABLE-Dju8ebbU.mjs";import{selectShapeMembers as Lo,selectShapeRows as Fo}from"./selectShapeMembers-GfRzwoVo.mjs";import{serializeSqlValue as oe}from"./serializeSqlValue-DbI1VQYM.mjs";import{quoteIdentifier as An}from"./quoteIdentifier-CObIFRhb.mjs";const vn=o=>{const i=new TextEncoder().encode(o);let t="";for(const a of i)t+=String.fromCodePoint(a);return btoa(t)},In=o=>{const i=atob(o),t=Uint8Array.from(i,a=>a.codePointAt(0)??0);return new TextDecoder().decode(t)},Cn=()=>new y("BAD_REQUEST","invalid cursor"),$t=16,yt=8,X=1024,Ve=(o,i)=>i.query(o),xn=(o,i,t)=>{const a=Ht(o,t);if(a.length===0)return 0;let f=0;for(const[p,E]of i.entries()){const R=p===i.length-1;let S=0;for(const $ of a)(R?$.startsWith(E):$===E)&&(S+=1);if(S===0)return 0;f+=S}return f},Mn=(o,i)=>{if(!i)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",a=(t.codePointAt(0)??0)+1;if(a>=55296&&a<=57343||a>1114111)return{exact:!0,lower:o,upper:o};const f=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:f+String.fromCodePoint(a)}},bn=(o,i,t)=>{const a={eq:(f,p)=>{if(!o.definition.filterFields?.includes(f))throw new y("INTERNAL",`field "${f}" is not a filter field of search index "${o.indexName}" on table "${i}"`);if(o.filters.length>=yt)throw new y("BAD_REQUEST",`search index "${o.indexName}" on table "${i}": at most ${String(yt)} .eq() filters are supported per search query`);return o.filters.push({field:f,value:p}),a},search:(f,p)=>{const E=o;if(f!==E.definition.field)throw new y("INTERNAL",`search index "${E.indexName}" on table "${i}" indexes "${E.definition.field}", not "${f}"`);const R=Ve(p,t).length;if(R>$t)throw new y("BAD_REQUEST",`search index "${E.indexName}" on table "${i}": at most ${String($t)} search terms are supported (got ${String(R)})`);return E.field=f,E.query=p,E.hasQuery=!0,a}};return a},Dn=o=>{if(o.length>X)throw new y("BAD_REQUEST",`more than ${String(X)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},kn=o=>Math.min(o.offset+o.numItems+1,X),Ln=o=>vn(`search:${String(o)}`),Fn=o=>{let i;try{i=In(o)}catch{return}if(!i.startsWith("search:"))return;const t=Number(i.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},Wn=o=>{if(typeof o.endCursor=="string")throw new y("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(o.numItems))throw new y("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(o.numItems)}`);const i=Math.max(0,Math.floor(o.numItems)),t=o.cursor?Fn(o.cursor):0;if(t===void 0)throw Cn();if(t+i>=X)throw new y("BAD_REQUEST",`search pagination reaches the ${String(X)}-document limit (offset ${String(t)} + ${String(i)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,X-t-1))} or fewer, or narrow the query or the filters instead`);return{numItems:i,offset:t}},qn=(o,i)=>{const t=i.offset+i.numItems,a=i.numItems>0&&o.length>t;return{continueCursor:a?Ln(t):null,isDone:!a,page:o.slice(i.offset,t)}},Bn=o=>{if(o===void 0)return X+1;if(!Number.isFinite(o))return X;const i=Math.max(0,Math.floor(o));if(i>X)throw new y("BAD_REQUEST",`search returns at most ${String(X)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},Un=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Pn=o=>{if(!Un.test(o))throw new y("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},Et=50,bt=500,xe=Math.floor(xt.boundParams/3),we=xt.boundParams,Gn=128,ce=(o,i,t)=>{const a=i??bt;if(o>a)throw new y("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},Hn=o=>{const i={eq:(t,a)=>(o.sqlConditions.push({comparator:"=",field:t,value:a}),i),gt:(t,a)=>(o.sqlConditions.push({comparator:">",field:t,value:a}),i),gte:(t,a)=>(o.sqlConditions.push({comparator:">=",field:t,value:a}),i),lt:(t,a)=>(o.sqlConditions.push({comparator:"<",field:t,value:a}),i),lte:(t,a)=>(o.sqlConditions.push({comparator:"<=",field:t,value:a}),i)};return i},Nn=o=>Math.max(o,X),Dt=(o,i)=>{const t=o.filters.map(a=>r`${V(a.field)} = ${oe(a.value)}`);return i&&t.push(i),t},jn=(o,i,t,a,f)=>{const p=Ve(t.query,Je(t.definition.language));if(p.length===0)return[];const E=jt(i,t.indexName),R=`${E}__vocab`,S=p.length-1,$=p.map((W,M)=>{const N=Mn(W,M===S),j=N.exact?r`${r.identifier("term")} = ${N.lower}`:r`${r.identifier("term")} >= ${N.lower} AND ${r.identifier("term")} < ${N.upper}`;return r`SELECT ${r.identifier("doc")}, ${r.raw(String(M))} AS ${r.identifier("__term__")}, COUNT(*) AS ${r.identifier("__n__")} FROM ${r.identifier(R)} WHERE ${j} GROUP BY ${r.identifier("doc")}`}),L=p.map((W,M)=>r`SUM(CASE WHEN u.${r.identifier("__term__")} = ${r.raw(String(M))} THEN u.${r.identifier("__n__")} ELSE 0 END)`),T=r`SELECT f.${r.identifier(Ae)} AS ${r.identifier(Ae)}, ${r.join(L,r` + `)} AS ${r.identifier("__score__")} FROM (${Ke($)}) u JOIN ${r.identifier(E)} f ON f.rowid = u.${r.identifier("doc")} GROUP BY f.${r.identifier(Ae)} HAVING ${r.join(L.map(W=>r`${W} > 0`),r` AND `)}`,v=Dt(t,f);let _=r`SELECT m.id, m._creationTime, m.${r.identifier(K)}, s.${r.identifier("__score__")} AS ${r.identifier("__score__")} FROM (${T}) s JOIN ${r.identifier(i)} m ON m.id = s.${r.identifier(Ae)}`;v.length>0&&(_=r`${_} WHERE ${r.join(v,r` AND `)}`),_=r`${_} ORDER BY s.${r.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${r.raw(String(a))}`;const F=[];for(const W of B(o,_)){const M=Ct(W);if(M){const N=W.__score__;F.push({document:M,score:typeof N=="number"?N:Number(N??0)})}}return F},Kn=(o,i,t,a,f)=>{const p=Je(t.definition.language),E=Ve(t.query,p);if(E.length===0)return[];const R=Dt(t,f);let S=r`SELECT id, _creationTime, ${r.identifier(K)} FROM ${r.identifier(i)}`;R.length>0&&(S=r`${S} WHERE ${r.join(R,r` AND `)}`),S=r`${S} ORDER BY _creationTime DESC, id ASC LIMIT ${r.raw(String(Nn(a)))}`;const $=B(o,S).toArray(),L=[];for(const T of $){const v=Ct(T);if(!v)continue;const _=xn(Kt(v,t.definition),E,p);_>0&&L.push({creationTime:typeof v._creationTime=="number"?v._creationTime:0,doc:v,id:typeof v._id=="string"?v._id:"",score:_})}return L.sort((T,v)=>v.score-T.score||v.creationTime-T.creationTime||T.id.localeCompare(v.id)),L.slice(0,a).map(T=>({document:T.doc,score:T.score}))},je=(o,i,t,a)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new y("BAD_REQUEST",`geo index "${a}" on table "${t}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},On=(o,i)=>{const t=o,a={near:(f,p)=>{if(t.within)throw new y("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(je(f,".near() point",i,t.indexName),!Number.isFinite(p)||p<=0)throw new y("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(p)}`);return t.near={point:{lat:f.lat,lng:f.lng},radiusMeters:p},a},within:f=>{if(t.near)throw new y("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(je(f.sw,".within() sw corner",i,t.indexName),je(f.ne,".within() ne corner",i,t.indexName),f.sw.lat>f.ne.lat)throw new y("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(f.sw.lng>f.ne.lng)throw new y("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return t.within={ne:{lat:f.ne.lat,lng:f.ne.lng},sw:{lat:f.sw.lat,lng:f.sw.lng}},a}};return a},Qn=(o,i)=>{const t=o[i];if(t===null||typeof t!="object")return;const{lat:a,lng:f}=t;return typeof a=="number"&&typeof f=="number"?{lat:a,lng:f}:void 0},zn=(o,i)=>{const t=Qn(o,i.definition.field);if(!t)return;const a=typeof o._creationTime=="number"?o._creationTime:0;if(i.near){const f=dn(i.near.point,t);return f<=i.near.radiusMeters?{creationTime:a,distance:f}:void 0}return ln(t,i.within)?{creationTime:a,distance:0}:void 0},Jn=(o,i,t,a)=>{if(!t.near&&!t.within)throw new y("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const f=t.near?cn(t.near.point,t.near.radiusMeters):an(t.within),p=on(i,t.indexName),E=f.map(T=>r`(g.${r.identifier("__geohash__")} >= ${T} AND g.${r.identifier("__geohash__")} < ${`${T}{`})`),R=[r`(${r.join(E,r` OR `)})`];a&&R.push(a);const S=r`SELECT m.id, m._creationTime, m.${r.identifier(K)} FROM ${r.identifier(p)} g JOIN ${r.identifier(i)} m ON m.id = g.${r.identifier("__id__")} WHERE ${r.join(R,r` AND `)}`,$=B(o,S).toArray(),L=[];for(const T of $){const v=de(T),_=v?zn(v,t):void 0;v&&_&&L.push({creationTime:_.creationTime,distance:_.distance,doc:v})}return L.sort((T,v)=>T.distance-v.distance||v.creationTime-T.creationTime),L},kt=(o,i,t,a)=>{const f=[];for(const p of o)if(i.every(E=>E(a(p)))&&(f.push(p),typeof t=="number"&&f.length>=t))break;return f},Vn=(o,i,t,a,f,p=()=>{})=>{const E=t.within!==void 0,R=Jn(o,i,t,f).map(S=>({distanceMeters:E?null:S.distance,document:S.doc}));return p(R.length),typeof a=="number"?R.slice(0,Math.max(0,Math.floor(a))):R},Lt=(o,i,t,a,f,p=()=>{})=>{const{geo:E}=t;if(!E)throw new y("INTERNAL","runGeoTerminalScored called without a staged geo query");const R=t.inMemoryFilters.length>0,S=Vn(o,i,E,R?void 0:f,a,p);return R?kt(S,t.inMemoryFilters,f,$=>$.document):S},Yn=(o,i,t,a,f,p=()=>{})=>Lt(o,i,t,a,f,p).map(E=>E.document),Xn=(o,i,t,a,f,p,E=()=>{})=>{const R=[];for(const T of t.sqlConditions)R.push(r`${V(T.field)} ${r.raw(T.comparator)} ${oe(T.value)}`);a&&R.push(a);let S=r`SELECT id, _creationTime, ${r.identifier(K)} FROM ${r.identifier(i)}`;R.length>0&&(S=r`${S} WHERE ${r.join(R,r` AND `)}`),S=r`${S} ORDER BY ${f}`,typeof p=="number"&&t.inMemoryFilters.length===0&&(S=r`${S} LIMIT ${r.raw(String(Math.max(0,Math.floor(p))))}`);const $=B(o,S).toArray();E($.length);const L=[];for(const T of $){const v=de(T);if(v&&t.inMemoryFilters.every(_=>_(v))&&(L.push(v),typeof p=="number"&&L.length>=p))break}return L},re={fieldRef:V,serialize:oe},Ft=(o,i)=>{const t=i===void 0?void 0:o.shape[i];return t!==void 0&&_n(t)},mt=(o,i)=>i.some(t=>Ft(o,t)),St=(o,i,t)=>{if(Ft(o,i))throw new y("BAD_REQUEST",`${t}: "${i}" is stored as an order-preserving key, which SQL cannot reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it`)},Zn=o=>{let i=0;const t=[],a={fieldRef:V,relationExists:f=>{const{childWhere:p,negated:E,parentTable:R,relation:S}=f,$=`__rel_${String(i)}`,L=t.at(-1)??R;i+=1,o(S.table,H);const T=S.kind==="one"?S.field:S.references,v=S.kind==="one"?S.references:S.field,_=r`${lt($,v)} = ${lt(L,T)}`;t.push($);const F=te(p,a);t.pop();const W=F?r`${_} AND ${F}`:_,M=r`EXISTS (SELECT 1 FROM ${r.identifier(S.table)} AS ${r.identifier($)} WHERE ${W})`;return E?r`NOT ${M}`:M},serialize:oe};return a},Wt=o=>{const i=o.map(t=>r`${V(t.field)} ${r.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||i.push(r`${V("id")} ASC`),r.join(i,r`, `)},er={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},tr=o=>{const i=o.order;return o.indexFields.length>0?o.indexFields.map(t=>({direction:i,field:t})):[{direction:i,field:"_creationTime"}]},nr=(o,i,t,a)=>{const f=o.sqlConditions.map(p=>({[p.field]:{[er[p.comparator]??"eq"]:p.value}}));if(t&&f.push(Mt(i,Oe(t))),a&&f.push(hn(i,Oe(a))),f.length!==0)return f.length===1?f[0]:{AND:f}},rr=(o,i,t)=>{const a=[];for(const f of o){const p=de(f);if(p&&i.every(E=>E(p))&&(a.push(p),t!==void 0&&a.length>t))break}return a},or=(o,i,t,a,f,p=()=>{})=>{const E=Math.max(0,Math.floor(a.numItems)),R=tr(t),S=typeof a.endCursor=="string",$=te(nr(t,R,a.cursor,a.endCursor),re),L=f&&$?r`${$} AND ${f}`:f??$;let T=r`SELECT id, _creationTime, ${r.identifier(K)} FROM ${r.identifier(i)}`;L&&(T=r`${T} WHERE ${L}`),T=r`${T} ORDER BY ${Wt(R)}`;const v=t.inMemoryFilters.length>0;!v&&!S&&(T=r`${T} LIMIT ${r.raw(String(E+1))}`);const _=B(o,T).toArray();p(_.length);const F=rr(_,t.inMemoryFilters,v||S?void 0:E);if(S){const j=F.length>=2?F[Math.floor(F.length/2)-1]:void 0;return{continueCursor:a.endCursor??null,isDone:!0,page:F,splitCursor:j?Qe(j,R):null}}const W=F.length>E,M=W?F.slice(0,E):F,N=M.at(-1);return{continueCursor:W&&N?Qe(N,R):null,isDone:!W,page:M}};class ir extends y{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const sr=/\s/u,cr=String.fromCodePoint(0),_t=(o,i,t)=>{if(!o.tables[i])throw new y("INTERNAL",`unknown table: ${i}`);return typeof t!="string"||t.length===0||sr.test(t)||t.includes(cr)?null:t},ar=(o,i,t,a=()=>{},f=()=>{},p=()=>{})=>{const E=i.tables[t];if(!E)throw new y("INTERNAL",`unknown table: ${t}`);const R=ae(E.softDeleteMode,void 0),S=R?te(R,re):void 0,$={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let L=0;const T=m=>{const{search:b}=$;if(!b)throw new y("INTERNAL","runSearchFetch called without a staged search");Xt(o,t,E);const k=$.inMemoryFilters.length>0,C=Bn(k?void 0:m),O=rn(o)?jn(o,t,b,C,S):Kn(o,t,b,C,S);return k?(L=O.length,kt(O,$.inMemoryFilters,m,be=>be.document)):(m===void 0&&Dn(O),O)},v=m=>T(m).map(b=>b.document),_=m=>{const b=Wn(m);return qn(v(kn(b)),b)},F=()=>{const m=$.indexFields.length>0?$.indexFields:["_creationTime"],b=$.order==="desc"?"DESC":"ASC";return r.join(m.map(k=>r`${V(k)} ${r.raw(b)}`),r`, `)},W=()=>{if($.search||$.geo||$.indexName===void 0){f(void 0);return}f(yn(t,$.indexName,$.indexFields,$.sqlConditions,oe))},M=m=>{W();let b=0;const k=(()=>{if($.search){const C=v(m);return b=L,C}return $.geo?Yn(o,t,$,S,m,C=>{b=C}):Xn(o,t,$,S,F(),m,C=>{b=C})})();return p(Math.max(b,k.length)),k},N=()=>{if(!$.search&&!$.geo)throw new y("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);W();let m=0;const b=(()=>{if($.search){const k=T(void 0);return m=L,k}return Lt(o,t,$,S,void 0,k=>{m=k})})();return p(Math.max(m,b.length)),b},j={async*[Symbol.asyncIterator](){const m=[...$.inMemoryFilters];let b;$.inMemoryFilters=[];try{for(;;){const k=await j.paginate({cursor:b??null,numItems:Gn});for(const C of k.page)m.every(O=>O(C))&&(yield C);if(k.isDone||k.continueCursor===null)return;b=k.continueCursor}}finally{$.inMemoryFilters=m}},async collect(){return M(void 0)},async collectWithScores(){return N()},filter(m){return $.inMemoryFilters.push(m),j},async first(){return M($.inMemoryFilters.length>0?void 0:1)[0]??null},order(m){return $.order=m==="desc"?"desc":"asc",j},async paginate(m){let b=0;if(W(),$.search){const C=_(m);return p(C.page.length),C}if($.geo)throw new y("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const k=or(o,t,$,m,S,C=>{b=C});return p(Math.max(b,k.page.length)),k},async take(m){return M(m)},async unique(){const m=M($.inMemoryFilters.length>0?void 0:2);if(m.length>1)throw new ir(`unique() on table "${t}" matched ${String(m.length)} documents; expected at most one`);return m[0]??null},withGeoIndex(m,b){const k=(E.geoIndexes??[]).find(O=>O.name===m);if(!k)throw new y("INTERNAL",`unknown geo index "${m}" on table "${t}"`);a(t,m,"geo");const C={definition:k,indexName:m};if($.geo=C,b(On(C,t)),!C.near&&!C.within)throw new y("INTERNAL",`geo index "${m}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return j},withIndex(m,b){const k=E.indexes.find(C=>C.name===m);if(!k)throw new y("INTERNAL",`unknown index "${m}" on table "${t}"`);return a(t,m,"index"),$.indexName=m,$.indexFields=k.fields,b&&b(Hn($)),j},withSearchIndex(m,b){const k=(E.searchIndexes??[]).find(O=>O.name===m);if(!k)throw new y("INTERNAL",`unknown search index "${m}" on table "${t}"`);a(t,m,"search");const C={definition:k,field:k.field,filters:[],hasQuery:!1,indexName:m,query:""};if($.search=C,b(bn(C,t,Je(k.language))),!C.hasQuery)throw new y("INTERNAL",`search index "${m}" on table "${t}" requires a .search(field, query) call`);return j}};return j},Rt=(o,i,t)=>{const a={...i};for(const[f,p]of It(o)){if(p.serverDefault){a[f]=p.serverDefault({auth:t});continue}a[f]===void 0&&(p.defaultFn?a[f]=p.defaultFn():"defaultValue"in p&&(a[f]=p.defaultValue))}return a},Tt=(o,i,t,a)=>{const f=t;for(const[p,E]of It(o)){if(E.serverDefault){p in i&&(f[p]=E.serverDefault({auth:a}));continue}E.onUpdateFn&&!(p in i)&&(f[p]=E.onUpdateFn())}},At=(o,i)=>{for(const t of Object.keys(i))if(i[t]===void 0)throw new y("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},dr=/unique constraint failed/i,lr=o=>o instanceof Error&&dr.test(o.message),ze=(o,i,t)=>{try{B(o,t)}catch(a){throw lr(a)?new pe(`unique constraint violation on "${i}"`,"unique"):a}},Me=(o,i,t)=>{if(ze(o,i,t),B(o,r`SELECT changes() AS changed`).one().changed===0)throw new pe(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},vt=(o,i,t,a,f,p,E)=>{const R=[];for(let T=0;T<t.length+1;T+=1){const v=[];for(let M=0;M<T;M+=1)v.push(r`${r.identifier(t[M])} IS ${p[M]}`);const _=t[T],F=a[T];if(_!==void 0&&F!==void 0){const M=F.direction==="desc"?">":"<";v.push(r`${r.identifier(_)} ${r.raw(M)} ${p[T]}`)}else v.push(r`${r.identifier(gn)} < ${E}`);const[W]=v;R.push(v.length===1&&W!==void 0?W:r`(${r.join(v,r` AND `)})`)}const S=r.join(R,r` OR `),$=B(o,r`SELECT COUNT(*) AS c FROM ${r.identifier(i)} WHERE ${r.identifier("__partition__")} = ${f} AND (${S})`).one(),L=B(o,r`SELECT COUNT(*) AS c FROM ${r.identifier(i)} WHERE ${r.identifier("__partition__")} = ${f}`).one();return{before:$.c,total:L.c}},Hr=o=>{const{sql:i}=o,{schema:t}=o,a=o.broadcast??(()=>{});let f;const p=()=>o.inTransaction?.()===!0,E=e=>t.tables[e]?.commitOrderedMode!==!0?{}:((f===void 0||!p())&&(f=en(i)),{[tn]:f}),R=(e,...n)=>{const s=t.tables[e]?.indexes;if(!s||s.length===0)return;const u=[];for(const h of n)h&&u.push(...$n(s,h,oe));return u.length>0?u:void 0},{headroom:S}=o;let $=!1;const L=async e=>{const n=$;$=!0;try{return await e()}finally{$=n}},T=o.onRead??(()=>{}),v=o.onReadRange??(e=>{T(e.table,H)}),_=(e,n)=>{n!==void 0&&n!==H&&!$&&S?.recordRead(1),T(e,n)},F=o.onIndexUse??(()=>{}),W=o.onWrite??(()=>{}),M=e=>{$||S?.recordWrite(e)},N=async e=>{M(e.doc),await W(e)},{cache:j}=o,m=o.clock??(()=>Date.now()),b=o.idGenerator??(()=>crypto.randomUUID()),k=o.scheduler??Qt,{globalDb:C}=o,O=o.auth??{identity:null,userId:null},be=o.cdc??!1,De=k,qt=Rn({scheduler:typeof De.list=="function"&&typeof De.get=="function"?De:void 0,storage:o.storage}),le=(e,n,s,u)=>{be&&!nn(t.tables[e])&&Zt(i,m(),e,n,s,u)},ie=e=>t.tables[e]?.shardMode?.kind==="global",Ye=(e,n)=>{if(ie(e)){if(!C)throw new y("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return C}return U},ke=e=>Ye(e,"cascade"),z=(e,n)=>{if(ie(e)){if(!C)throw new y("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return C}},Xe=async(e,n,s,u,h)=>{h&&M(s);const l=await e.insert(n,s,u);return a({key:l,op:"insert",row:{...s,_id:l},table:n}),l},Le=(e,n)=>Ye(e,"relation load").findMany(e,n),Ze=(e,n)=>(ie(e)&&_(e,H),Le(e,n)),Bt=e=>!ie(e.table),et=o.relationExistsPushDown??"auto",tt=et!=="never",{maxRelationKeys:nt}=o,ge=(e,n,s)=>wt(e,{fetcher:Ze,maxRelationKeys:nt,relationBaseWhere:s,schema:t,tableName:n}),rt=async(e,n,s,u)=>{const h=z(e,"relation grouped count");if(h)return _(e,H),mn((q,I)=>h.count(q,I),e,n,s,u);const l=t.tables[e];if(!l)throw new y("INTERNAL",`unknown table: ${e}`);_(e,H);const c=ae(l.softDeleteMode,void 0),d={[n]:{in:s}},w=J(J(d,u),c),A=await ge(w,e,void 0),g=te(A,re),x=V(n);let D=r`SELECT ${x} AS __fk__, COUNT(*) AS count FROM ${r.identifier(e)}`;g&&(D=r`${D} WHERE ${g}`),D=r`${D} GROUP BY ${x}`;const P=B(i,D).toArray();return new Map(P.map(q=>[q.__fk__,q.count]))};let $e=0;const ot=new Set;for(const[e,n]of Object.entries(t.tables))for(const s of Object.values(n.triggerMap??{}))ot.add(`${e} ${s.timing} ${s.op}`);const Z=(e,n,s)=>ot.has(`${e} ${n} ${s}`),ee=async(e,n,s)=>{if($e+=1,$e>Et)throw $e-=1,new pe(`trigger recursion exceeded ${String(Et)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await Tn({ctx:Pt,event:s,op:n,schema:t,tableName:s.table,timing:e})}finally{$e-=1}},{ensureBackfilledForTable:ue,ensureBackfilledIndex:Fe,ensureRankBackfilled:We,ensureRankBackfilledForTable:fe,syncAggregates:ye,syncCompanionsForInsert:it,syncGeo:Ee,syncRanks:he,syncSearch:me}=Nt({broadcast:a,indexKeysFor:(e,n)=>R(e,n),invalidateCache:(e,n,s)=>j?.invalidate(e,n,R(e,s)),recordCdc:le,schema:t,sql:i}),st=(e,n,s)=>{const{shardMode:u}=n;if(u?.kind==="shardBy"&&!(u.field!==void 0&&(s.partitionBy??[]).includes(u.field)))throw Object.assign(new Error(`rank index "${s.name}" on "${e}" partitions across shards (shard key "${u.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},ct=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),ne=(e,n)=>{const s=ct(n);for(let u=0;u<s.length;u+=we){const h=s.slice(u,u+we).map(g=>r`SELECT ${r.raw(`'${g.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${r.identifier(K)} FROM ${r.identifier(g)} WHERE id = ${e}`),[l]=B(i,r`${Ke(h)} LIMIT 1`).toArray();if(!l)continue;const c=l.__t__,d=de(l);if(typeof c!="string"||!d)return;const w=l[K];return{docJson:typeof w=="string"?w:se(w??{}),row:d,tableName:c}}},Ut=(e,n)=>{const s=[...new Set(e)],u=new Map;if(s.length===0)return u;const h=ct(n);for(let l=0;l<h.length;l+=we){const c=h.slice(l,l+we),d=Math.floor(we/c.length),w=sn(r`${r.identifier("id")}`,s,!1,d),A=c.map(g=>r`SELECT ${r.raw(`'${g.replaceAll("'","''")}'`)} AS __t__, id FROM ${r.identifier(g)} WHERE ${w}`);for(const g of B(i,Ke(A))){const{id:x,__t__:D}=g;typeof D=="string"&&typeof x=="string"&&u.set(x,D)}}return u},at={assertRankPartitionLocal:st,ensureRankBackfilled:We,onRead:_,rowToDocument:de,schema:t,sql:i},U={system:qt,async aggregate(e,n){const s=z(e,"aggregate");if(s)return _(e,H),s.aggregate(e,n);const u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);if(ve(n.op),n.op==="count")return U.count(e,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new y("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);_(e,H);const h=ae(u.softDeleteMode,void 0),l=J(J(n.baseWhere,n.where),h),c=await ge(l,e,n.relationBaseWhere),d=c!==l;if(u.aggregateIndexes&&!n.baseWhere&&!d&&(!h||mt(u,[n.field]))){const q=Yt(u.aggregateIndexes,n.op,n.field,n.where);if(q){Fe(e,q.index);const I=Be(q.index.by??[],q.key),Q=qe(e,q.index.name),Y=B(i,r`SELECT ${Ie} AS value, ${Ge} AS count FROM ${r.identifier(Q)} WHERE ${Ce} = ${I}`).toArray()[0];return Ue(n.op,Y)}}St(u,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const w=te(c,re),A=ve(n.op),g=V(n.field);let x=r`SELECT ${r.raw(A)}(${g}) AS value FROM ${r.identifier(e)}`;w&&(x=r`${x} WHERE ${w}`);const P=B(i,x).toArray()[0]?.value;return P??null},asId(e,n){const s=_t(t,e,n);if(s===null)throw new y("BAD_REQUEST",`asId("${e}", …): "${n}" is not a valid id for table "${e}"`,{status:400});return s},async count(e,n){const s=z(e,"count");if(s)return _(e,H),s.count(e,n);const u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const h=zt(n);if(h.restrictsCounts)throw new Pe(e);_(e,H);const l=ae(u.softDeleteMode,void 0),c=J(J(h.baseWhere,h.where),l),d=await ge(c,e,h.relationBaseWhere),w=d!==c;if(u.aggregateIndexes&&!h.baseWhere&&!w&&!l){const D=Vt(u.aggregateIndexes,h.where);if(D){Fe(e,D.index);const P=Be(D.index.by??[],D.key),q=qe(e,D.index.name),I=B(i,r`SELECT ${Ie} AS value FROM ${r.identifier(q)} WHERE ${Ce} = ${P}`).toArray();return I[0]===void 0?0:I[0].value??0}}const A=te(d,re);let g=r`SELECT COUNT(*) AS count FROM ${r.identifier(e)}`;return A&&(g=r`${g} WHERE ${A}`),B(i,g).one().count},async delete(e,n,s){const u=ne(e,n);if(!u){const g=n===void 0?C:void 0;g&&(M(void 0),await g.delete(e,void 0,s));return}const{docJson:h,row:l,tableName:c}=u,d=t.tables[c],w=s?.hard===!0,A=!w&&d?.softDeleteMode?d.softDeleteMode.field:void 0;if(!(A&&l[A]!==null&&l[A]!==void 0)){if(Z(c,"before","delete")&&await ee("before","delete",{id:e,op:"delete",previous:l,table:c}),await En({deletedId:e,deletedReference:g=>l[g],findHolders:async(g,x,D)=>(await ke(g).findMany(g,{includeDeleted:w,where:{[x]:D}})).page,onCascade:(g,x)=>ke(g).delete(x,void 0,s),onRestrict:g=>{throw new pe(g,"restrict")},onSetNull:(g,x,D)=>ke(g).patch(x,{[D]:null}),schema:t,tableName:c}),ue(c),fe(c),A){const g={...l,...E(c),[A]:m(),_id:e};Me(i,c,r`UPDATE ${r.identifier(c)} SET ${r.identifier(K)} = ${se(g)} WHERE id = ${e} AND ${r.identifier(K)} = ${h}`),me(c,e,g,l),Ee(c,e,void 0),ye(c,l,g),he(c,e,l,void 0),j?.invalidate(c,e,R(c,l,g)),le(c,e,"update",g),a({indexKeys:R(c,l,g),key:e,op:"update",row:g,table:c}),Z(c,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:c}),await N({id:e,op:"delete",table:c});return}Me(i,c,r`DELETE FROM ${r.identifier(c)} WHERE id = ${e} AND ${r.identifier(K)} = ${h}`),me(c,e,void 0),Ee(c,e,void 0),ye(c,l,void 0),he(c,e,l,void 0),j?.invalidate(c,e,R(c,l)),le(c,e,"delete"),a({indexKeys:R(c,l),key:e,op:"delete",table:c}),Z(c,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:c}),await N({id:e,op:"delete",table:c})}},async deleteAll(e,n){if(!t.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);const s=Math.max(1,n?.chunkSize??bt),u=n?.hard===void 0?void 0:{hard:n.hard},h=ie(e)?void 0:e;let l=0;return await L(async()=>{for(;;){const d=(await U.findMany(e,{limit:s})).page.map(w=>String(w._id));if(d.length===0)break;for(const w of d)await U.delete(w,h,u),l+=1;if(d.length<s)break}}),{deleted:l}},async deleteMany(e,n,s){ce(e.length,n?.limit,"deleteMany");for(const u of e)await U.delete(u,s);return{deleted:e.length}},async deleteWhere(e,n,s){const l=(await(z(e,"deleteWhere")??U).findMany(e,{where:n})).page.map(c=>String(c._id));if(ce(l.length,s?.limit,"deleteWhere"),U.deleteMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return U.deleteMany(l,s)},async findFirst(e,n={}){return(await U.findMany(e,{...n,limit:1})).page[0]??null},async findFirstOrThrow(e,n={}){const s=await U.findFirst(e,n);if(s===null)throw new un(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,n={}){const s=z(e,"findMany");if(s)return _(e,H),s.findMany(e,n);const u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const h=!n.where&&!n.baseWhere;h?_(e,H):_(e);const l=fn(n.orderBy),c=n.cursor?Mt(l,Oe(n.cursor)):void 0;let d=J(n.baseWhere,n.where);d=J(d,ae(u.softDeleteMode,n.includeDeleted)),d=await wt(d,{canPushExists:tt?Bt:void 0,existsPushMode:et==="always"?"always":"auto",fetcher:Ze,maxRelationKeys:nt,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),c&&(d=d?{AND:[d,c]}:c);const w=tt?Zn(_):re,A=te(d,w);let g=r`SELECT id, _creationTime, ${r.identifier(K)} FROM ${r.identifier(e)}`;A&&(g=r`${g} WHERE ${A}`),g=r`${g} ORDER BY ${Wt(l)}`;const x=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0;x!==void 0&&(g=r`${g} LIMIT ${r.raw(String(x+1))}`);const D=B(i,g).toArray();h&&!$&&S?.recordRead(D.length);const P=[];for(const Y of D){const G=de(Y);G&&(P.push(G),!h&&typeof G._id=="string"&&_(e,G._id))}if(x===void 0)return n.with&&await pt({groupedCounter:rt,fetcher:Le,parents:P,...gt(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:ut(P,n.select,n.with)};const q=P.length>x,I=q?P.slice(0,x):P,Q=I.at(-1);return n.with&&await pt({fetcher:Le,groupedCounter:rt,parents:I,...gt(n),schema:t,tableName:e,with:n.with}),{continueCursor:q&&Q?Qe(Q,l):null,isDone:!q,page:ut(I,n.select,n.with)}},async get(e,n){const s=ne(e,n);if(!s){const u=n===void 0?C:void 0;return u?u.get(e):null}return _(s.tableName,e),s.row},async lookupById(e,n){const s=ne(e,n);return s?(_(s.tableName,e),{row:s.row,tableName:s.tableName}):null},async groupBy(e,n){const s=z(e,"groupBy");if(s)return _(e,H),s.groupBy(e,n);const u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);_(e,H);const h=n.agg??{op:"count"};if(ve(h.op),h.op!=="count"&&!h.field)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const l=ae(u.softDeleteMode,void 0),c=J(J(n.baseWhere,n.where),l),d=await ge(c,e,n.relationBaseWhere),w=d!==c,A=[...n.by,h.field];if(u.aggregateIndexes&&!n.baseWhere&&!w&&(!l||mt(u,A))){const I=Jt(u.aggregateIndexes,h.op,h.field,n.by,n.where),Q=I===void 0?0:Object.keys(I.partial).length,Y=I?.index.by?.length??0;if(I&&(Q===0||Q===Y)){Fe(e,I.index);const G=qe(e,I.index.name),Se=Object.keys(I.partial),_e=[];if(Se.length===(I.index.by??[]).length&&Se.length>0){const Re=Be(I.index.by??[],I.partial),Te=B(i,r`SELECT ${Ie} AS value, ${Ge} AS count FROM ${r.identifier(G)} WHERE ${Ce} = ${Re}`).toArray();return Te.length>0&&_e.push({key:{...I.partial},value:Ue(h.op,Te[0])}),_e}const Gt=B(i,r`SELECT ${Ce} AS key, ${Ie} AS value, ${Ge} AS count FROM ${r.identifier(G)}`).toArray();for(const Re of Gt){const Te=Ot(JSON.parse(Re.key));_e.push({key:Te,value:Ue(h.op,Re)})}return _e}}for(const I of A){if(I===void 0)continue;const Q=I===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${I}" } })`:`groupBy(${e}, { by: [..."${I}"] })`;St(u,I,Q)}const g=te(d,re),x=n.by.map(I=>r`${V(I)} AS ${r.identifier(I)}`);if(h.op==="count")x.push(r`COUNT(*) AS value`);else{const{field:I}=h;if(I===void 0)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);x.push(r`${r.raw(ve(h.op))}(${V(I)}) AS value`)}let D=r`SELECT ${r.join(x,r`, `)} FROM ${r.identifier(e)}`;g&&(D=r`${D} WHERE ${g}`),D=r`${D} GROUP BY ${r.join(n.by.map(I=>V(I)),r`, `)}`;const P=B(i,D).toArray(),q=[];for(const I of P){const Q={};for(const G of n.by)Q[G]=I[G]??null;const{value:Y}=I;q.push({key:Q,value:Y==null?null:Number(Y)})}return q},async insert(e,n,s){const u=z(e,"insert");if(u)return Xe(u,e,n,s,!0);const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);const l=Rt(h,n,O);Ne(h,l);let c;s?.clientId!==void 0?(Pn(s.clientId),c=s.clientId):s?.allowExplicitId&&typeof l._id=="string"?c=l._id:c=b();const d=s?.allowExplicitId&&typeof l._creationTime=="number"?l._creationTime:m(),w={...l,...E(e),_creationTime:d,_id:c};return Z(e,"before","insert")&&await ee("before","insert",{doc:{...w},id:c,op:"insert",table:e}),ue(e),fe(e),ze(i,e,r`INSERT INTO ${r.identifier(e)} (id, _creationTime, ${r.identifier(K)}) VALUES (${c}, ${d}, ${se(w)})`),it(e,c,w),Z(e,"after","insert")&&await ee("after","insert",{doc:w,id:c,op:"insert",table:e}),await N({doc:w,id:c,op:"insert",table:e}),c},async insertManyUnsafe(e,n,s){if(ce(n.length,s?.limit,"insertManyUnsafe"),n.length===0)return[];const u=z(e,"insert");if(u){const d=[];for(const w of n)M(w);for(const w of n){const A=await u.insert(e,w,{allowExplicitId:s?.allowExplicitId});a({key:A,op:"insert",row:{...w,_id:A},table:e}),d.push(A)}return d}const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);ue(e),fe(e);const l=[];for(let d=0;d<n.length;d+=xe)l.push(E(e));const c=n.map((d,w)=>{const A=Rt(h,d,O),g=s?.allowExplicitId===!0&&typeof A._id=="string"?A._id:b(),x=s?.allowExplicitId===!0&&typeof A._creationTime=="number"?A._creationTime:m(),D={...A,...l[Math.floor(w/xe)],_creationTime:x,_id:g};return{creationTime:x,document:D,id:g}});for(const d of c)M(d.document);for(let d=0;d<c.length;d+=xe){const w=r.join(c.slice(d,d+xe).map(A=>r`(${A.id}, ${A.creationTime}, ${se(A.document)})`),r`, `);ze(i,e,r`INSERT INTO ${r.identifier(e)} (id, _creationTime, ${r.identifier(K)}) VALUES ${w}`)}for(const{document:d,id:w}of c)it(e,w,d),await W({doc:d,id:w,op:"insert",table:e});return c.map(d=>d.id)},async insertMany(e,n,s){ce(n.length,s?.limit,"insertMany");const u=s?.skipDuplicates===!0,h=[],l=z(e,"insert");if(l)for(const d of n)M(d);const c=async d=>l?Xe(l,e,d,void 0,!1):U.insert(e,d);for(const d of n)try{h.push(await c(d))}catch(w){if(u&&w instanceof pe&&w.kind==="unique")h.push(null);else throw w}return h},normalizeId(e,n){return _t(t,e,n)},async patch(e,n,s){const u=ne(e,s);if(!u){const A=s===void 0?C:void 0;if(A){M(n),await A.patch(e,n);return}throw new y("INTERNAL",`document not found: ${e}`)}const{docJson:h,row:l,tableName:c}=u,d=t.tables[c];if(!d)throw new y("INTERNAL",`unknown table: ${c}`);_(c,e),At("patch",n);const w={...l,...n,...E(c),_id:e};Tt(d,n,w,O),Ne(d,w,!0),Z(c,"before","update")&&await ee("before","update",{doc:{...w},id:e,op:"update",previous:l,table:c}),ue(c),fe(c),Me(i,c,r`UPDATE ${r.identifier(c)} SET ${r.identifier(K)} = ${se(w)} WHERE id = ${e} AND ${r.identifier(K)} = ${h}`),me(c,e,w,l),Ee(c,e,w),ye(c,l,w),he(c,e,l,w),j?.invalidate(c,e,R(c,l,w)),le(c,e,"update",w),a({indexKeys:R(c,l,w),key:e,op:"update",row:w,table:c}),Z(c,"after","update")&&await ee("after","update",{doc:w,id:e,op:"update",previous:l,table:c}),await N({doc:w,id:e,op:"update",table:c})},async patchMany(e,n,s){ce(e.length,n?.limit,"patchMany");for(const u of e)await U.patch(u.id,u.patch,s);return{patched:e.length}},async patchWhere(e,n,s){const l=(await(z(e,"patchWhere")??U).findMany(e,{where:n.where})).page.map(c=>({id:String(c._id),patch:n.patch}));if(ce(l.length,s?.limit,"patchWhere"),U.patchMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await U.patchMany(l,s),{patched:l.length}},query(e){const n=z(e,"query");return n?(_(e,H),n.query(e)):ar(i,t,e,F,s=>{s?v(s):_(e,H)},s=>{$||S?.recordRead(s)})},async rank(e,n,s){const u=z(e,"rank");if(u)return _(e,H),u.rank(e,n,s);F(e,n,"rank");const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);const l=h.rankIndexes?.find(G=>G.name===n);if(!l)throw new y("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(st(e,h,l),s.restrictsCounts)throw new Pe(e);_(e,H),We(e,l);const c=typeof s.row=="string"?s.row:s.row._id;if(!c)return null;const d=ft(e,l.name),w=l.sortBy.map((G,Se)=>ht(Se)),A=w.map(G=>An(G)).join(", "),g=B(i,r`SELECT ${r.identifier("__partition__")}, ${r.raw(A)} FROM ${r.identifier(d)} WHERE ${r.identifier("__id__")} = ${c}`).toArray(),[x]=g;if(x===void 0)return null;let D=x.__partition__;const P=J(s.baseWhere,s.where);He(P,t,e,"rank");const q=wn(l,P);if(q){const G=pn(l.partitionBy??[],q);if(G!==D)return null;D=G}const I=w.map(G=>x[G]),{before:Q,total:Y}=vt(i,d,w,l.sortBy,D,I,c);return{position:Q+1,total:Y}},async rankBefore(e,n,s){if(ie(e))throw new y("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const h=u.rankIndexes?.find(w=>w.name===n);if(!h)throw new y("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(s.restrictsCounts)throw new Pe(e);_(e,H),We(e,h);const l=ft(e,h.name),c=h.sortBy.map((w,A)=>ht(A)),d=h.sortBy.map((w,A)=>oe(s.sortValues[A]??null));return vt(i,l,c,h.sortBy,s.partitionKey,d,s.rowId)},async rankPage(e,n,s={}){He(J(s.baseWhere,s.where),t,e,"rankPage");const u=z(e,"rankPage");if(u)return _(e,H),u.rankPage(e,n,s);F(e,n,"rank");const{continueCursor:h,hasMore:l,rows:c}=dt(at,e,n,s);return{continueCursor:h,isDone:!l,page:c.map(d=>d.doc)}},async rankPageRows(e,n,s={}){He(J(s.baseWhere,s.where),t,e,"rankPage"),F(e,n,"rank");const{directions:u,hasMore:h,rows:l}=dt(at,e,n,s);return{directions:u,hasMore:h,rows:l}},async restore(e,n){const s=ne(e,n);if(!s){const l=n===void 0?C:void 0;if(l?.restore){await l.restore(e);return}throw new y("INTERNAL",`document not found: ${e}`)}const u=t.tables[s.tableName]?.softDeleteMode?.field;if(!u)throw new y("INTERNAL",`ctx.db.restore: table "${s.tableName}" is not a .softDelete() table`);const h=s.row[u]!==null&&s.row[u]!==void 0;await U.patch(e,{[u]:null},n),h&&he(s.tableName,e,void 0,s.row)},async replace(e,n,s,u){const h=ne(e,s);if(!h){const x=s===void 0?C:void 0;if(x){M(n),await x.replace(e,n,void 0,u);return}throw new y("INTERNAL",`document not found: ${e}`)}const{docJson:l,row:c,tableName:d}=h,w=t.tables[d];if(!w)throw new y("INTERNAL",`unknown table: ${d}`);At("replace",n);const A=u?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:m(),g={...n,...E(d),_creationTime:A,_id:e};Tt(w,n,g,O),Ne(w,g),Z(d,"before","update")&&await ee("before","update",{doc:{...g},id:e,op:"update",previous:c,table:d}),ue(d),fe(d),Me(i,d,r`UPDATE ${r.identifier(d)} SET _creationTime = ${A}, ${r.identifier(K)} = ${se(g)} WHERE id = ${e} AND ${r.identifier(K)} = ${l}`),me(d,e,g,c),Ee(d,e,g),ye(d,c,g),he(d,e,c,g),j?.invalidate(d,e,R(d,c,g)),le(d,e,"update",g),a({indexKeys:R(d,c,g),key:e,op:"update",row:g,table:d}),Z(d,"after","update")&&await ee("after","update",{doc:g,id:e,op:"update",previous:c,table:d}),await N({doc:g,id:e,op:"update",table:d})},async wipeShard(e){const n=new Set(e?.exclude),s=e?.tables,u=Object.entries(t.tables).filter(([d,w])=>n.has(d)||s!==void 0&&!s.includes(d)?!1:w.shardMode?.kind!=="global").map(([d])=>d);if(s!==void 0){for(const d of s)if(!t.tables[d])throw new y("INTERNAL",`wipeShard: unknown table: ${d}`)}const h={};let l=0;const{deleteAll:c}=U;if(c===void 0)throw new y("INTERNAL","wipeShard: this writer has no deleteAll");for(const d of u){const w=await c(d,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[d]=w.deleted,l+=w.deleted}return{deleted:l,tables:h}}},Pt={db:U,scheduler:k};return o.enforceRls===!0?Sn(U,t,(e,n)=>ne(e,n)?.tableName,(e,n)=>Ut(e,n)):U};export{Jr as CDC_LOG_TABLE,ho as CLIENT_WATERMARK_TABLE,yo as GLOBAL_SHAPE_SNAPSHOT_TABLE,Ao as IDEMPOTENCY_TABLE,ir as NotUniqueError,Do as SEARCH_STATE_TABLE,wo as advanceClientWatermark,Vr as applyCdcChanges,Pn as assertValidClientId,Kr as backfillAggregateIndexes,Or as backfillRankIndexes,Qr as backfillSearchIndexes,Yr as bumpCdcEpoch,Xr as cdcCanVouchFor,Zr as cdcSeqLeavingRows,eo as cdcTouchesTables,to as cdcTrimmedError,no as compactCdcDocs,Hr as createShardCtxDb,ro as cursorBelowRetainedFloor,Eo as deleteGlobalShapeSnapshot,mo as deleteGlobalShapeSnapshotsForConnection,po as migrateClientWatermark,So as migrateGlobalShapeSnapshot,oo as minCdcReplayableSeq,io as minCdcSeq,_t as normalizeIdStructurally,so as readCdcChangeKeys,co as readCdcChanges,ao as readCdcCursor,lo as readCdcEpoch,go as readClientWatermark,_o as readGlobalShapeSnapshot,vo as readIdempotent,Mo as runShardMigrations,Lo as selectShapeMembers,Fo as selectShapeRows,uo as trimCdcChanges,Io as trimIdempotent,Ro as writeGlobalShapeSnapshot,Co as writeIdempotent};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{matchesStaticWhere as P,aggregateSqlFunction as le}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as N,encodeAggregateKey as L,foldAggregateTally as J,coerceAggregateNumber as C}from"./aggregateTableName-Cy5e03oz.mjs";import{runDrizzle as $}from"./runDrizzle-it6rL9bR.mjs";import{i as fe,g as ue,D,r as M,a as q,b as S,A as g,c as j,e as z}from"./do-sql-Dk_DJxn4.mjs";import{param as de,WORKERD_SQLITE_LIMITS as $e}from"./param-Ib8WHnrF.mjs";import{encodeGeohash as me,GEO_DEFAULT_PRECISION as Ee}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as Q}from"./applySelect-BQbHyo-W.mjs";import{encodePartitionKey as pe,sortColumnName as he,rankTableName as Z,matchesRankStaticWhere as x}from"./RANK_TIEBREAK-ci3MaM65.mjs";import{m as ge}from"./sql-projection-BqmxFxQU.mjs";import{serializeSqlValue as ee}from"./serializeSqlValue-DbI1VQYM.mjs";const ye=["de","en","es","fr","it","nl","none","pt"],_e=n=>ye.includes(n),Se="a an and are as at be but by for if in into is it no not of on or such that the their then there these they this to was will with",we="aber als am an auch auf aus bei bin bis bist da dass der den des dem die das denn dir du ein eine für hat ich im in ist mit nicht noch nur oder sich sie sind über und von vor war wie wir zu zum zur",Te="a al como con de del el en es la las lo los mas no o para pero por que se su sus un una uno y ya",ve="au aux avec ce ces dans de des du elle en et eux il je la le les leur lui ma mais me même mes moi mon ne nos notre nous on ou par pas pour qu que qui sa se ses son sur ta te tes toi ton tu un une vos votre vous y",Re="a ai al alla anche che chi ci coi col come con da dal degli dei del della di do e ed gli ha hai hanno i il in la le lo ma mi ne nei nel non o per più quale quanto se si sono su sul tra un una uno vi",Ae="aan al als bij dan dat de der deze die dit door een en er het hij ij in is je kan me men met mij na naar niet nog nu of om ons ook op over te tot uit van voor was wat we wij zij zijn zo",be="a ao aos as até com como da das de do dos e em entre era essa esse esta este eu foi há isso já mais mas me mesmo meu na nas no nos num numa o os ou para pela pelo por qual que quem se sem seu só sua também te tem um uma você",Fe=/[\u0300-\u036F]/gu,oe=n=>n.normalize("NFD").replaceAll(Fe,"").normalize("NFC").toLowerCase(),k=n=>new Set(oe(n).split(" ")),Oe={de:k(we),en:k(Se),es:k(Te),fr:k(ve),it:k(Re),nl:k(Ae),none:new Set,pt:k(be)},Ie=2,Le=256,X=new Map,ke=n=>{const r=n!==void 0&&_e(n)?n:"none",c=X.get(r);if(c)return c;const w=Oe[r],y=i=>{const A=(oe(i).match(/[\p{L}\p{N}]+/gu)??[]).filter(T=>T.length<=Le);return w.size===0?A:A.filter(T=>!w.has(T))},E={document:y,profile:`${r}-v${String(Ie)}`,query:i=>{const A=y(i);return A.filter((T,F)=>A.lastIndexOf(T)===F)}};return X.set(r,E),E},qe=(n,r)=>{if(!r.includes("."))return n[r];let c=n;for(const w of r.split(".")){if(c===null||typeof c!="object"||Array.isArray(c))return;c=c[w]}return c},Ce=(n,r)=>`${n}__fts_${r}`,je="__text__",Y="__id__",De=1e3,Me=(n,r)=>r.document(n),U=(n,r)=>qe(n,r),ze=n=>typeof n=="string"?n:n==null?"":typeof n=="number"||typeof n=="bigint"||typeof n=="boolean"?String(n):JSON.stringify(n)??"",Ue=(n,r,c)=>n!==void 0&&r!==void 0&&U(n,c.field)===U(r,c.field),We=(n,r)=>Me(ze(U(n,r.field)),ke(r.language)).slice(0,De).join(" "),He=(n,r,c)=>[...n.partitionBy??[],...n.sortBy.map(y=>y.field),...n.where?Object.keys(n.where):[]].every(y=>r[y]===c[y]),ne=n=>e.join(["__id__","__partition__",...n.sortBy.map((r,c)=>he(c))].map(r=>e.identifier(r)),e`, `),te=(n,r,c,w,y,E)=>{const i=pe(c.partitionBy??[],E),A=c.sortBy.map(F=>ee(E[F.field]??null)),T=e.join([y,i,...A].map(F=>de(F)),e`, `);$(n,e`INSERT INTO ${e.identifier(r)} (${w}) VALUES (${T})`)},Be=(n,r,c,w,y,E)=>{if(y&&E&&He(c,y,E))return;const i=Z(r,c.name);y&&$(n,e`DELETE FROM ${e.identifier(i)} WHERE ${e.identifier("__id__")} = ${w}`),!(!E||c.where&&!x(E,c.where))&&te(n,i,c,ne(c),w,E)},oo=n=>{const{broadcast:r,indexKeysFor:c,invalidateCache:w,recordCdc:y,schema:E,sql:i}=n,A=new Set,T=t=>E.tables[t]?.softDeleteMode?.field,F=new Set,W=(t,o)=>{const a=`${t}::${o.name}`;if(A.has(a))return;const f=N(t,o.name),u=o.by??[],d=T(t),p=new Map,_=$(i,e`SELECT id, _creationTime, ${e.identifier(D)} FROM ${e.identifier(t)}`).toArray();for(const v of _){const m=M(v);if(!m||!Q(m,d)||o.where&&!P(m,o.where))continue;const R=L(u,m);J(p,R,o,m)}$(i,e`DELETE FROM ${e.identifier(f)}`);const b=Math.floor($e.boundParams/3),O=[...p];for(let v=0;v<O.length;v+=b){const m=O.slice(v,v+b),R=e.join(m.map(([s,l])=>e`(${s}, ${l.value}, ${l.count})`),e`, `);$(i,e`INSERT INTO ${e.identifier(f)} (${q}, ${S}, ${g}) VALUES ${R}`)}A.add(a)},se=(t,o,a)=>{const f=o.by??[],u=o.field??"",d=[],p=(s,l)=>{const h=ee(l);h===null?d.push(e`${z(s)} IS NULL`):d.push(e`${z(s)} = ${h}`)};for(const s of f)p(s,a[s]??null);const _=T(t);_!==void 0&&p(_,null);for(const[s,l]of Object.entries(o.where??{}))p(s,l!==null&&typeof l=="object"&&!Array.isArray(l)?l.eq:l);const b=d.length>0?e` WHERE ${e.join(d,e` AND `)}`:e``,O=E.tables[t]?.shape[u];if(O&&ge(O)){const s=$(i,e`SELECT id, _creationTime, ${e.identifier(D)} FROM ${e.identifier(t)}${b}`).toArray(),l=new Map;for(const h of s){const I=M(h);I&&J(l,"",o,I)}return{value:l.get("")?.value??null}}const v=le(o.op),m=z(u);return{value:$(i,e`SELECT ${e.raw(v)}(${m}) AS value FROM ${e.identifier(t)}${b}`).one().value??null}},ie=(t,o,a,f)=>{const u=N(t,o.name),{op:d}=o,p=o.field??"",_=s=>{$(i,e`DELETE FROM ${e.identifier(u)} WHERE ${q} = ${s} AND ${g} <= 0`)},b=T(t),O=s=>!o.where||P(s,o.where),v=s=>Q(s,b)&&O(s);f!==void 0&&d!=="count"&&O(f)&&C(f[p]);const m=a&&v(a)?a:void 0,R=f&&v(f)?f:void 0;if(!(!m&&!R)){if(d==="count"){for(const[s,l]of[[m,-1],[R,1]]){if(!s)continue;const h=L(o.by??[],s);$(i,j(u,h,l,l,e`${S} = ${S} + excluded.${S}, ${g} = ${g} + excluded.${g}`))}m&&_(L(o.by??[],m));return}if(d==="sum"||d==="avg"){for(const[s,l]of[[m,-1],[R,1]]){if(!s)continue;const h=C(s[p]);if(h===void 0)continue;const I=L(o.by??[],s);$(i,j(u,I,l*h,l,e`${S} = COALESCE(${S}, 0) + excluded.${S}, ${g} = ${g} + excluded.${g}`))}m&&_(L(o.by??[],m));return}if(m){const s=L(o.by??[],m),l=C(m[p]),h=$(i,e`SELECT ${S} AS value, ${g} AS count FROM ${e.identifier(u)} WHERE ${q} = ${s}`).toArray()[0],I=(h?.count??0)-1;if(I<=0)$(i,e`DELETE FROM ${e.identifier(u)} WHERE ${q} = ${s}`);else if(h&&l!==void 0&&h.value!==null&&l===h.value){const ce=se(t,o,m);$(i,e`UPDATE ${e.identifier(u)} SET ${S} = ${ce.value}, ${g} = ${I} WHERE ${q} = ${s}`)}else $(i,e`UPDATE ${e.identifier(u)} SET ${g} = ${g} - 1 WHERE ${q} = ${s}`)}if(R){const s=L(o.by??[],R),l=C(R[p]);if(l===void 0)$(i,j(u,s,null,1,e`${g} = ${g} + 1`));else{const h=d==="min"?"MIN":"MAX";$(i,j(u,s,l,1,e`${S} = ${e.raw(h)}(COALESCE(${S}, excluded.${S}), excluded.${S}), ${g} = ${g} + 1`))}}}},re=t=>{for(const o of E.tables[t]?.aggregateIndexes??[])W(t,o)},H=(t,o,a)=>{for(const f of E.tables[t]?.aggregateIndexes??[])ie(t,f,o,a)},B=(t,o)=>{const a=`${t}::rank::${o.name}`;if(F.has(a))return;const f=Z(t,o.name),u=$(i,e`SELECT id, _creationTime, ${e.identifier(D)} FROM ${e.identifier(t)}`).toArray();$(i,e`DELETE FROM ${e.identifier(f)}`);const d=ne(o);for(const p of u){const _=M(p);!_||o.where&&!x(_,o.where)||te(i,f,o,d,_._id,_)}F.add(a)},ae=t=>{for(const o of E.tables[t]?.rankIndexes??[])B(t,o)},K=(t,o,a,f)=>{for(const u of E.tables[t]?.rankIndexes??[])Be(i,t,u,o,a,f)},V=(t,o,a,f)=>{const u=E.tables[t]?.searchIndexes??[];if(!(u.length===0||!fe(i)))for(const d of u){if(Ue(f,a,d))continue;const p=Ce(t,d.name);$(i,e`DELETE FROM ${e.identifier(p)} WHERE ${e.identifier(Y)} = ${o}`),a&&$(i,e`INSERT INTO ${e.identifier(p)} (${e.identifier(je)}, ${e.identifier(Y)}) VALUES (${We(a,d)}, ${o})`)}},G=(t,o,a)=>{for(const f of E.tables[t]?.geoIndexes??[]){const u=ue(t,f.name);$(i,e`DELETE FROM ${e.identifier(u)} WHERE ${e.identifier("__id__")} = ${o}`);const d=a?.[f.field];if(d!==null&&typeof d=="object"&&typeof d.lat=="number"&&typeof d.lng=="number"){const{lat:p,lng:_}=d,b=me({lat:p,lng:_},f.precision??Ee);$(i,e`INSERT INTO ${e.identifier(u)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${o}, ${b}, ${p}, ${_})`)}}};return{ensureBackfilledForTable:re,ensureBackfilledIndex:W,ensureRankBackfilled:B,ensureRankBackfilledForTable:ae,syncAggregates:H,syncCompanionsForInsert:(t,o,a)=>{V(t,o,a),G(t,o,a),H(t,void 0,a),K(t,o,void 0,a),w(t,o,a),y(t,o,"insert",a),r({indexKeys:c(t,a),key:o,op:"insert",row:a,table:t})},syncGeo:G,syncRanks:K,syncSearch:V}};export{je as S,Ce as a,oo as c,We as h,te as i,ke as j,ne as r,Me as s,Y as y};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as c}from"@lunora/errors";import{sql as n}from"drizzle-orm";import{quoteIdentifier as m}from"./quoteIdentifier-CObIFRhb.mjs";import{d as T,e as $}from"./wire-codec-BU9T2xJ7.mjs";import{runDrizzle as l}from"./runDrizzle-it6rL9bR.mjs";import{s as A}from"./sql-projection-BqmxFxQU.mjs";import"./serializeSqlValue-DbI1VQYM.mjs";const E=/^[A-Za-z_$][\w$]*$/u,p=e=>E.test(e)?e:`"${e.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,d="__doc__",i="__originals__",C=e=>{if(Object.hasOwn(e,i))throw new c("BAD_REQUEST",`"${i}" is reserved by the row store's document encoding and cannot be used as a field name — rename the field`);let t,o;for(const[r,s]of Object.entries(e)){const a=A(s);a!==void 0&&(t??={...e},o??=Object.create(null),t[r]=a,o[r]=s)}t&&o&&(t[i]=o);try{return JSON.stringify($(t??e))}catch(r){throw new c("BAD_REQUEST",`this document cannot be stored: ${r instanceof Error?r.message:String(r)}`)}},S=e=>{const t=T(JSON.parse(e)),{[i]:o,...r}=t;return o===null||typeof o!="object"||Array.isArray(o)?t:{...r,...o}},L=(e,t)=>`${e}__geo_${t}`,u=(e,t)=>t==="_id"||t==="id"?`${e}id`:t==="_creationTime"?`${e}_creationTime`:`json_extract(${e}${d}, '$.${p(t).replaceAll("'","''")}')`,h=e=>u("",e),P=e=>n.raw(h(e)),O=(e,t)=>u(`${m(e)}.`,t),R=(e,t)=>n.raw(O(e,t)),G=(e,t,o,r)=>n`CREATE ${r?n`UNIQUE `:n``}INDEX IF NOT EXISTS ${n.identifier(e)} ON ${n.identifier(t)} (${o})`,_=n.identifier("__key__"),b=n.identifier("__value__"),g=n.identifier("__count__"),q=(e,t,o,r,s)=>n`INSERT INTO ${n.identifier(e)} (${_}, ${b}, ${g}) VALUES (${t}, ${o}, ${r}) ON CONFLICT(${_}) DO UPDATE SET ${s}`,J=e=>{const t=[];for(const[o,r]of Object.entries(e.shape)){const s=r._meta?.column;s&&t.push([o,s])}return t},y=e=>{if(!e)return;const t=e[d];let o;typeof t=="string"?o=S(t):t&&typeof t=="object"?o=t:o={};const{id:r}=e;typeof r=="string"&&(o._id=r);const s=e._creationTime;return typeof s=="number"&&(o._creationTime=s),o},B=e=>{try{return y(e)}catch{return}},f=new WeakMap,F=e=>{const t=f.get(e);if(t!==void 0)return t;let o;try{l(e,n`CREATE VIRTUAL TABLE IF NOT EXISTS ${n.identifier("__lunora_fts_probe")} USING fts5(x)`),o=!0}catch{o=!1}finally{try{l(e,n`DROP TABLE IF EXISTS ${n.identifier("__lunora_fts_probe")}`)}catch{}}return f.set(e,o),o};export{g as A,d as D,_ as a,b,q as c,G as d,P as e,R as f,L as g,B as h,F as i,h as j,C as k,S as l,p as m,i as n,O as q,y as r,J as t};
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import{a as S,S as L,y as N}from"./ctx-db-companions-lTt-rvKG.mjs";import{sql as e}from"drizzle-orm";import{aggregateTableName as p}from"./aggregateTableName-Cy5e03oz.mjs";import{backfillSearchIndexesForTable as u}from"./backfillAggregateIndexes-DDgDYJcc.mjs";import{migrateCdcLog as h,migrateCdcMeta as R}from"./CDC_LOG_TABLE-VfPoURHu.mjs";import{migrateClientWatermark as x}from"./CLIENT_WATERMARK_TABLE-BoS1HEqz.mjs";import{migrateCommitSeq as C}from"./COMMIT_SEQ_FIELD-CSe_oNZu.mjs";import{migrateGlobalShapeSnapshot as O}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-NWaL77m5.mjs";import{migrateIdempotency as b}from"./IDEMPOTENCY_TABLE-DKVe2Ohf.mjs";import{m as U}from"./ctx-db-relay-shapes-Jf5xpD1r.mjs";import{migrateSearchState as l}from"./SEARCH_STATE_TABLE-Dju8ebbU.mjs";import{migrateShapePokeCursor as $}from"./SHAPE_POKE_CURSOR_TABLE-BBuXXk5v.mjs";import{runDrizzle as a}from"./runDrizzle-it6rL9bR.mjs";import{D as X,e as T,d,t as G,i as D,g as B,a as M,b as k,A as E}from"./do-sql-Dk_DJxn4.mjs";import{migrateDurableStreams as F}from"./appendStreamChunk-CH4e4nJn.mjs";import{rankTableName as Y,sortColumnName as P}from"./RANK_TIEBREAK-ci3MaM65.mjs";import{migrateReactorState as j}from"./REACTOR_STATE_TABLE-Cr9Orfp8.mjs";import{recordSchemaVersion as y}from"./SCHEMA_HISTORY_MAX_VERSIONS-DsycDXWm.mjs";const v=(r,n,o)=>{for(const i of o.indexes){const t=`${n}_${i.name}`,m=e.join(i.fields.map(s=>T(s)),e`, `);a(r,d(t,n,m,i.unique??!1))}for(const[i,t]of G(o)){if(!t.unique)continue;const m=`${n}_unique_${i}`;a(r,d(m,n,T(i),!0))}},K=(r,n,o)=>{if(!(!o.searchIndexes||o.searchIndexes.length===0||!D(r))){for(const i of o.searchIndexes){const t=S(n,i.name);a(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(t)} USING fts5(${e.identifier(L)}, ${e.identifier(N)} UNINDEXED)`),a(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${t}__vocab`)} USING fts5vocab(${e.identifier(t)}, ${e.raw("instance")})`)}u(r,n,o)}},V=(r,n,o)=>{if(o.geoIndexes)for(const i of o.geoIndexes){const t=B(n,i.name);a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__geohash__")} TEXT NOT NULL, ${e.identifier("__lat__")} REAL NOT NULL, ${e.identifier("__lng__")} REAL NOT NULL)`);const m=`${n}__geo_${i.name}__btree`;a(r,d(m,t,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},w=(r,n,o)=>{if(o.aggregateIndexes)for(const i of o.aggregateIndexes){const t=p(n,i.name);a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${M} TEXT PRIMARY KEY, ${k} REAL, ${E} INTEGER NOT NULL DEFAULT 0)`),a(r,e`PRAGMA table_info(${e.identifier(t)})`).toArray().some(s=>s.name==="__count__")||a(r,e`ALTER TABLE ${e.identifier(t)} ADD COLUMN ${E} INTEGER NOT NULL DEFAULT 0`)}},z=(r,n,o)=>{if(o.rankIndexes)for(const i of o.rankIndexes){const t=Y(n,i.name),m=i.sortBy.map((f,_)=>P(_)),s=m.map(f=>e`${e.identifier(f)} BLOB`),g=s.length>0?e`, ${e.join(s,e`, `)}`:e``;a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${g})`);const c=[e`${e.identifier("__partition__")} ASC`];for(const[f,_]of m.entries()){const I=i.sortBy[f]?.direction;c.push(e`${e.identifier(_)} ${e.raw(I==="desc"?"DESC":"ASC")}`)}c.push(e`${e.identifier("__id__")} ASC`);const A=`${n}__rank_${i.name}__btree`;a(r,d(A,t,e.join(c,e`, `),!1))}},_e=(r,n,o={})=>{o.schemaSnapshot!==void 0&&y(r,o.schemaSnapshot.hash,o.schemaSnapshot.json),l(r);for(const[i,t]of Object.entries(n.tables))t.shardMode?.kind!=="global"&&(a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(i)} (
|
|
2
|
-
id TEXT PRIMARY KEY,
|
|
3
|
-
_creationTime REAL NOT NULL,
|
|
4
|
-
${e.identifier(X)} TEXT NOT NULL
|
|
5
|
-
)`),v(r,i,t),K(r,i,t),V(r,i,t),w(r,i,t),z(r,i,t));o.cdc&&(h(r),R(r),x(r),$(r),U(r)),Object.values(n.tables).some(i=>i.commitOrderedMode===!0)&&C(r),j(r),b(r),O(r),F(r)};export{_e as runShardMigrations};
|